def test_no_nengo_dl(Simulator, monkeypatch): # check that things still work without nengo_dl / tf monkeypatch.setattr(neurons, "HAS_TF", False) with nengo.Network() as net: a = nengo.Ensemble(10, 1, neuron_type=LoihiLIF()) nengo.Probe(a) with Simulator(net) as sim: sim.step()
def test_install_on_instantiation(): tf_neuron_impl = nengo_dl.neuron_builders.SimNeuronsBuilder.TF_NEURON_IMPL # undo any installation that happened in other tests if LoihiLIF in tf_neuron_impl: del tf_neuron_impl[LoihiLIF] install_dl_builders.installed = False assert LoihiLIF not in tf_neuron_impl LoihiLIF() assert LoihiLIF in tf_neuron_impl
def test_install_on_instantiation(): nengo_dl = pytest.importorskip("nengo_dl") if builder_nengo_dl.install_dl_builders.installed: # undo any installation that happened in other tests del nengo_dl.neuron_builders.SimNeuronsBuilder.TF_NEURON_IMPL[LoihiLIF] builder_nengo_dl.install_dl_builders.installed = False assert LoihiLIF not in nengo_dl.neuron_builders.SimNeuronsBuilder.TF_NEURON_IMPL LoihiLIF() assert LoihiLIF in nengo_dl.neuron_builders.SimNeuronsBuilder.TF_NEURON_IMPL
assert allclose(est_rates, ref_rates, atol=1, rtol=0, xtol=1) def test_loihi_rates_other_type(allclose): """Test using a neuron type that has no Loihi-specific implementation""" neuron_type = nengo.neurons.Sigmoid() x = np.linspace(-7, 10) gain, bias = 0.2, 0.4 dt = 0.002 ref_rates = neuron_type.rates(x, gain, bias) rates = loihi_rates(neuron_type, x, gain, bias, dt) assert allclose(rates, ref_rates) @pytest.mark.parametrize('neuron_type', [ LoihiLIF(), LoihiSpikingRectifiedLinear(), ]) def test_loihi_neurons(neuron_type, Simulator, plt, allclose): dt = 0.0007 n = 256 encoders = np.ones((n, 1)) gain = np.zeros(n) if isinstance(neuron_type, nengo.SpikingRectifiedLinear): bias = np.linspace(0, 1001, n) else: bias = np.linspace(0, 30, n) with nengo.Network() as model: ens = nengo.Ensemble(n,
nengo.RegularSpiking(nengo.Sigmoid()), ], ) def test_loihi_rates_other_type(neuron_type, allclose): """Test using a neuron type that has no Loihi-specific implementation""" x = np.linspace(-7, 10) gain, bias = 0.2, 0.4 dt = 0.002 ref_rates = nengo_rates(neuron_type, x, gain, bias) rates = loihi_rates(neuron_type, x, gain, bias, dt) assert ref_rates.shape == rates.shape assert allclose(rates, ref_rates) @pytest.mark.parametrize( "neuron_type", [LoihiLIF(), LoihiSpikingRectifiedLinear()]) def test_loihi_neurons(neuron_type, Simulator, plt, allclose): dt = 0.0007 n = 256 encoders = np.ones((n, 1)) gain = np.zeros(n) if isinstance(neuron_type, nengo.SpikingRectifiedLinear): bias = np.linspace(0, 1001, n) else: bias = np.linspace(0, 30, n) with nengo.Network() as model: ens = nengo.Ensemble(n, 1, neuron_type=neuron_type,
def test_conv_connection(channels, channels_last, Simulator, seed, rng, plt, allclose): if channels_last: plt.saveas = None pytest.xfail("Blocked by CxBase cannot be > 256 bug") # load data with open(os.path.join(test_dir, 'mnist10.pkl'), 'rb') as f: test10 = pickle.load(f) test_x = test10[0][0].reshape(28, 28) test_x = 1.999 * test_x - 0.999 # range (-1, 1) input_shape = nengo_transforms.ChannelShape( (test_x.shape + (channels, )) if channels_last else ((channels, ) + test_x.shape), channels_last=channels_last) filters = Gabor(freq=Uniform(0.5, 1)).generate(8, (7, 7), rng=rng) filters = filters[None, :, :, :] # single channel filters = np.transpose(filters, (2, 3, 0, 1)) strides = (2, 2) tau_rc = 0.02 tau_ref = 0.002 tau_s = 0.005 dt = 0.001 neuron_type = LoihiLIF(tau_rc=tau_rc, tau_ref=tau_ref) pres_time = 0.1 with nengo.Network(seed=seed) as model: nengo_loihi.add_params(model) u = nengo.Node(test_x.ravel(), label="u") a = nengo.Ensemble(input_shape.size, 1, neuron_type=LoihiSpikingRectifiedLinear(), max_rates=nengo.dists.Choice([40 / channels]), intercepts=nengo.dists.Choice([0]), label='a') model.config[a].on_chip = False if channels == 1: nengo.Connection(u, a.neurons, transform=1, synapse=None) elif channels == 2: # encode image into spikes using two channels (on/off) if input_shape.channels_last: nengo.Connection(u, a.neurons[0::2], transform=1, synapse=None) nengo.Connection(u, a.neurons[1::2], transform=-1, synapse=None) else: k = input_shape.spatial_shape[0] * input_shape.spatial_shape[1] nengo.Connection(u, a.neurons[:k], transform=1, synapse=None) nengo.Connection(u, a.neurons[k:], transform=-1, synapse=None) filters = np.concatenate([filters, -filters], axis=2) else: raise ValueError("Test not configured for more than two channels") conv2d_transform = nengo_transforms.Convolution( 8, input_shape, strides=strides, kernel_size=(7, 7), channels_last=channels_last, init=filters) output_shape = conv2d_transform.output_shape gain, bias = neuron_type.gain_bias(max_rates=100, intercepts=0) gain = gain * 0.01 # account for `a` max_rates b = nengo.Ensemble(output_shape.size, 1, neuron_type=neuron_type, gain=nengo.dists.Choice([gain[0]]), bias=nengo.dists.Choice([bias[0]]), label='b') nengo.Connection(a.neurons, b.neurons, synapse=tau_s, transform=conv2d_transform) bp = nengo.Probe(b.neurons) with nengo.Simulator(model, dt=dt, optimize=False) as sim: sim.run(pres_time) ref_out = sim.data[bp].mean(axis=0).reshape(output_shape.shape) # Currently, non-gpu TensorFlow does not support channels first in conv use_nengo_dl = HAS_DL and channels_last ndl_out = np.zeros_like(ref_out) if use_nengo_dl: with nengo_dl.Simulator(model, dt=dt) as sim_dl: sim_dl.run(pres_time) ndl_out = sim_dl.data[bp].mean(axis=0).reshape(output_shape.shape) with nengo_loihi.Simulator(model, dt=dt, target='simreal') as sim_real: sim_real.run(pres_time) real_out = sim_real.data[bp].mean(axis=0).reshape(output_shape.shape) with Simulator(model, dt=dt) as sim_loihi: if "loihi" in sim_loihi.sims: sim_loihi.sims["loihi"].snip_max_spikes_per_step = 800 sim_loihi.run(pres_time) sim_out = sim_loihi.data[bp].mean(axis=0).reshape(output_shape.shape) if not output_shape.channels_last: ref_out = np.transpose(ref_out, (1, 2, 0)) ndl_out = np.transpose(ndl_out, (1, 2, 0)) real_out = np.transpose(real_out, (1, 2, 0)) sim_out = np.transpose(sim_out, (1, 2, 0)) out_max = max(ref_out.max(), sim_out.max()) # --- plot results rows = 2 cols = 3 ax = plt.subplot(rows, cols, 1) imshow(test_x, vmin=0, vmax=1, ax=ax) ax = plt.subplot(rows, cols, 2) tile(np.transpose(filters[0], (2, 0, 1)), cols=8, ax=ax) ax = plt.subplot(rows, cols, 3) plt.hist(ref_out.ravel(), bins=31) plt.hist(sim_out.ravel(), bins=31) ax = plt.subplot(rows, cols, 4) tile(np.transpose(ref_out, (2, 0, 1)), vmin=0, vmax=out_max, cols=8, ax=ax) ax = plt.subplot(rows, cols, 5) tile(np.transpose(ndl_out, (2, 0, 1)), vmin=0, vmax=out_max, cols=8, ax=ax) ax = plt.subplot(rows, cols, 6) tile(np.transpose(sim_out, (2, 0, 1)), vmin=0, vmax=out_max, cols=8, ax=ax) if use_nengo_dl: assert allclose(ndl_out, ref_out, atol=1e-5, rtol=1e-5) assert allclose(real_out, ref_out, atol=1, rtol=1e-3) assert allclose(sim_out, ref_out, atol=10, rtol=1e-3)
def test_conv_connection(channels, channels_last, Simulator, seed, rng, plt, allclose): # load data with open(os.path.join(test_dir, "mnist10.pkl"), "rb") as f: test10 = pickle.load(f) test_x = test10[0][0].reshape((28, 28)) test_x = 1.999 * test_x - 0.999 # range (-1, 1) input_shape = make_channel_shape(test_x.shape, channels, channels_last) filters = Gabor(freq=Uniform(0.5, 1)).generate(8, (7, 7), rng=rng) filters = filters[None, :, :, :] # single channel filters = np.transpose(filters, (2, 3, 0, 1)) strides = (2, 2) tau_rc = 0.02 tau_ref = 0.002 tau_s = 0.005 neuron_type = LoihiLIF(tau_rc=tau_rc, tau_ref=tau_ref) pres_time = 0.1 with nengo.Network(seed=seed) as model: nengo_loihi.add_params(model) u = nengo.Node(test_x.ravel(), label="u") a = nengo.Ensemble( input_shape.size, 1, neuron_type=LoihiSpikingRectifiedLinear(), max_rates=nengo.dists.Choice([40 / channels]), intercepts=nengo.dists.Choice([0]), label="a", ) model.config[a].on_chip = False if channels == 1: nengo.Connection(u, a.neurons, transform=1, synapse=None) elif channels == 2: # encode image into spikes using two channels (on/off) if input_shape.channels_last: nengo.Connection(u, a.neurons[0::2], transform=1, synapse=None) nengo.Connection(u, a.neurons[1::2], transform=-1, synapse=None) else: k = input_shape.spatial_shape[0] * input_shape.spatial_shape[1] nengo.Connection(u, a.neurons[:k], transform=1, synapse=None) nengo.Connection(u, a.neurons[k:], transform=-1, synapse=None) filters = np.concatenate([filters, -filters], axis=2) else: raise ValueError("Test not configured for more than two channels") conv2d_transform = nengo_transforms.Convolution( 8, input_shape, strides=strides, kernel_size=(7, 7), channels_last=channels_last, init=filters, ) output_shape = conv2d_transform.output_shape gain, bias = neuron_type.gain_bias(max_rates=100, intercepts=0) gain = gain * 0.01 # account for `a` max_rates b = nengo.Ensemble( output_shape.size, 1, neuron_type=neuron_type, gain=nengo.dists.Choice([gain[0]]), bias=nengo.dists.Choice([bias[0]]), label="b", ) nengo.Connection(a.neurons, b.neurons, synapse=tau_s, transform=conv2d_transform) bp = nengo.Probe(b.neurons) with nengo.Simulator(model, optimize=False) as sim_nengo: sim_nengo.run(pres_time) ref_out = sim_nengo.data[bp].mean(axis=0).reshape(output_shape.shape) with Simulator(model, target="simreal") as sim_emu: sim_emu.run(pres_time) emu_out = sim_emu.data[bp].mean(axis=0).reshape(output_shape.shape) with Simulator(model, hardware_options={"snip_max_spikes_per_step": 800}) as sim_loihi: sim_loihi.run(pres_time) sim_out = sim_loihi.data[bp].mean(axis=0).reshape(output_shape.shape) if not output_shape.channels_last: ref_out = np.transpose(ref_out, (1, 2, 0)) emu_out = np.transpose(emu_out, (1, 2, 0)) sim_out = np.transpose(sim_out, (1, 2, 0)) out_max = max(ref_out.max(), emu_out.max(), sim_out.max()) # --- plot results rows = 2 cols = 3 ax = plt.subplot(rows, cols, 1) imshow(test_x, vmin=0, vmax=1, ax=ax) ax = plt.subplot(rows, cols, 2) tile(np.transpose(filters[0], (2, 0, 1)), cols=8, ax=ax) ax = plt.subplot(rows, cols, 3) plt.hist(ref_out.ravel(), bins=31) plt.hist(sim_out.ravel(), bins=31) ax = plt.subplot(rows, cols, 4) tile(np.transpose(ref_out, (2, 0, 1)), vmin=0, vmax=out_max, cols=8, ax=ax) ax = plt.subplot(rows, cols, 5) tile(np.transpose(emu_out, (2, 0, 1)), vmin=0, vmax=out_max, cols=8, ax=ax) ax = plt.subplot(rows, cols, 6) tile(np.transpose(sim_out, (2, 0, 1)), vmin=0, vmax=out_max, cols=8, ax=ax) assert allclose(emu_out, ref_out, atol=10, rtol=1e-3) assert allclose(sim_out, ref_out, atol=10, rtol=1e-3)
def test_conv_connection(channels, Simulator, seed, rng, plt, allclose): # channels_last = True channels_last = False if channels > 1: pytest.xfail("Cannot send population spikes to chip") # load data with open(os.path.join(test_dir, 'mnist10.pkl'), 'rb') as f: test10 = pickle.load(f) test_x = test10[0][0].reshape(28, 28) test_x = 1.999 * test_x - 0.999 # range (-1, 1) test_x = test_x[:, :, None] # single channel input_shape = ImageShape(test_x.shape[0], test_x.shape[1], channels, channels_last=channels_last) filters = Gabor(freq=Uniform(0.5, 1)).generate(8, (7, 7), rng=rng) filters = filters[None, :, :, :] # single channel filters = np.transpose(filters, (0, 2, 3, 1)) # filters last strides = (2, 2) tau_rc = 0.02 tau_ref = 0.002 tau_s = 0.005 dt = 0.001 neuron_type = LoihiLIF(tau_rc=tau_rc, tau_ref=tau_ref) pres_time = 0.1 with nengo.Network(seed=seed) as model: nengo_loihi.add_params(model) u = nengo.Node(nengo.processes.PresentInput([test_x.ravel()], pres_time), label='u') a = nengo.Ensemble(input_shape.size, 1, neuron_type=LoihiSpikingRectifiedLinear(), max_rates=nengo.dists.Choice([40 / channels]), intercepts=nengo.dists.Choice([0]), label='a') model.config[a].on_chip = False if channels == 1: nengo.Connection(u, a.neurons, transform=1, synapse=None) elif channels == 2: # encode image into spikes using two channels (on/off) if input_shape.channels_last: nengo.Connection(u, a.neurons[0::2], transform=1, synapse=None) nengo.Connection(u, a.neurons[1::2], transform=-1, synapse=None) else: k = input_shape.rows * input_shape.cols nengo.Connection(u, a.neurons[:k], transform=1, synapse=None) nengo.Connection(u, a.neurons[k:], transform=-1, synapse=None) filters = np.vstack([filters, -filters]) else: raise ValueError("Test not configured for more than two channels") conv2d_transform = Conv2D.from_kernel(filters, input_shape, strides=strides) output_shape = conv2d_transform.output_shape gain, bias = neuron_type.gain_bias(max_rates=100, intercepts=0) gain = gain * 0.01 # account for `a` max_rates b = nengo.Ensemble(output_shape.size, 1, neuron_type=neuron_type, gain=nengo.dists.Choice([gain[0]]), bias=nengo.dists.Choice([bias[0]]), label='b') nengo.Connection(a.neurons, b.neurons, synapse=tau_s, transform=conv2d_transform) bp = nengo.Probe(b.neurons) with nengo.Simulator(model, dt=dt, optimize=False) as sim: sim.run(pres_time) ref_out = sim.data[bp].mean(axis=0).reshape(output_shape.shape()) # Currently, default TensorFlow does not support channels first in conv use_nengo_dl = nengo_dl is not None and channels_last ndl_out = np.zeros_like(ref_out) if use_nengo_dl: with nengo_dl.Simulator(model, dt=dt) as sim: sim.run(pres_time) ndl_out = sim.data[bp].mean(axis=0).reshape(output_shape.shape()) with nengo_loihi.Simulator(model, dt=dt, target='simreal') as sim: sim.run(pres_time) real_out = sim.data[bp].mean(axis=0).reshape(output_shape.shape()) with Simulator(model, dt=dt) as sim: sim.run(pres_time) sim_out = sim.data[bp].mean(axis=0).reshape(output_shape.shape()) if not output_shape.channels_last: ref_out = np.transpose(ref_out, (1, 2, 0)) ndl_out = np.transpose(ndl_out, (1, 2, 0)) real_out = np.transpose(real_out, (1, 2, 0)) sim_out = np.transpose(sim_out, (1, 2, 0)) out_max = max(ref_out.max(), sim_out.max()) # --- plot results rows = 2 cols = 3 ax = plt.subplot(rows, cols, 1) imshow(test_x, vmin=0, vmax=1, ax=ax) ax = plt.subplot(rows, cols, 2) tile(np.transpose(filters[0], (2, 0, 1)), cols=8, ax=ax) ax = plt.subplot(rows, cols, 3) plt.hist(ref_out.ravel(), bins=31) plt.hist(sim_out.ravel(), bins=31) ax = plt.subplot(rows, cols, 4) tile(np.transpose(ref_out, (2, 0, 1)), vmin=0, vmax=out_max, cols=8, ax=ax) ax = plt.subplot(rows, cols, 5) tile(np.transpose(ndl_out, (2, 0, 1)), vmin=0, vmax=out_max, cols=8, ax=ax) ax = plt.subplot(rows, cols, 6) tile(np.transpose(sim_out, (2, 0, 1)), vmin=0, vmax=out_max, cols=8, ax=ax) if use_nengo_dl: assert allclose(ndl_out, ref_out, atol=1e-5, rtol=1e-5) assert allclose(real_out, ref_out, atol=1, rtol=1e-3) assert allclose(sim_out, ref_out, atol=10, rtol=1e-3)
with Simulator(model, dt=dt) as sim: sim.run(1.0) est_rates = sim.data[ap].mean(axis=0) ref_rates = loihi_rates(neuron_type, x, gain, bias, dt=dt) plt.plot(x, ref_rates, "k", label="predicted") plt.plot(x, est_rates, "g", label="measured") plt.legend(loc='best') assert allclose(est_rates, ref_rates, atol=1, rtol=0, xtol=1) @pytest.mark.parametrize('neuron_type', [ LoihiLIF(), LoihiSpikingRectifiedLinear(), ]) def test_loihi_neurons(neuron_type, Simulator, plt, allclose): dt = 0.0007 n = 256 encoders = np.ones((n, 1)) gain = np.zeros(n) if isinstance(neuron_type, nengo.SpikingRectifiedLinear): bias = np.linspace(0, 1001, n) else: bias = np.linspace(0, 30, n) with nengo.Network() as model: a = nengo.Ensemble(n,
# First time does not warn with pytest.warns(None) as record: NoiseBuilder.register(int)(MockNoiseBuilder) assert len(record) == 0 # Second time warns with pytest.warns(UserWarning, match="already has a builder"): NoiseBuilder.register(int)(MockNoiseBuilder) @pytest.mark.skipif(not reqs.HAS_NENGO_DL, reason="requires nengo-dl") @pytest.mark.skipif(not reqs.HAS_NENGO_LOIHI, reason="requires nengo-loihi") @pytest.mark.filterwarnings("ignore:divide by zero") @pytest.mark.filterwarnings("ignore:invalid value") @pytest.mark.filterwarnings("ignore:Non-finite values detected") @pytest.mark.parametrize("neuron_type", [LoihiLIF(), LoihiSpikingRectifiedLinear()]) @pytest.mark.parametrize("inference_only", (True, False)) def test_nengo_dl_neurons(neuron_type, inference_only, Simulator, plt, allclose): install_dl_builders() dt = 0.0007 n = 256 encoders = np.ones((n, 1)) gain = np.zeros(n) if isinstance(neuron_type, nengo.SpikingRectifiedLinear): bias = np.linspace(0, 1001, n) else: bias = np.linspace(0, 30, n) with nengo.Network() as model: