-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathbenchmarks.py
800 lines (645 loc) · 25.6 KB
/
benchmarks.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
"""
Benchmark networks and utilities for evaluating NengoDL's performance.
"""
import inspect
import random
import timeit
import click
import nengo
import numpy as np
import tensorflow as tf
from nengo.utils.filter_design import cont2discrete
import nengo_dl
def cconv(dimensions, neurons_per_d, neuron_type):
"""
Circular convolution (EnsembleArray) benchmark.
Parameters
----------
dimensions : int
Number of dimensions for vector values
neurons_per_d : int
Number of neurons to use per vector dimension
neuron_type : `~nengo.neurons.NeuronType`
Simulation neuron type
Returns
-------
net : `nengo.Network`
benchmark network
"""
with nengo.Network(label="cconv", seed=0) as net:
net.config[nengo.Ensemble].neuron_type = neuron_type
net.config[nengo.Ensemble].gain = nengo.dists.Choice([1, -1])
net.config[nengo.Ensemble].bias = nengo.dists.Uniform(-1, 1)
net.cconv = nengo.networks.CircularConvolution(neurons_per_d, dimensions)
net.inp_a = nengo.Node([0] * dimensions)
net.inp_b = nengo.Node([1] * dimensions)
nengo.Connection(net.inp_a, net.cconv.input_a)
nengo.Connection(net.inp_b, net.cconv.input_b)
net.p = nengo.Probe(net.cconv.output)
return net
def integrator(dimensions, neurons_per_d, neuron_type):
"""
Single integrator ensemble benchmark.
Parameters
----------
dimensions : int
Number of dimensions for vector values
neurons_per_d : int
Number of neurons to use per vector dimension
neuron_type : `~nengo.neurons.NeuronType`
Simulation neuron type
Returns
-------
net : `nengo.Network`
benchmark network
"""
with nengo.Network(label="integrator", seed=0) as net:
net.config[nengo.Ensemble].neuron_type = neuron_type
net.config[nengo.Ensemble].gain = nengo.dists.Choice([1, -1])
net.config[nengo.Ensemble].bias = nengo.dists.Uniform(-1, 1)
net.integ = nengo.networks.EnsembleArray(neurons_per_d, dimensions)
nengo.Connection(net.integ.output, net.integ.input, synapse=0.01)
net.inp = nengo.Node([0] * dimensions)
nengo.Connection(net.inp, net.integ.input, transform=0.01)
net.p = nengo.Probe(net.integ.output)
return net
def pes(dimensions, neurons_per_d, neuron_type):
"""
PES learning rule benchmark.
Parameters
----------
dimensions : int
Number of dimensions for vector values
neurons_per_d : int
Number of neurons to use per vector dimension
neuron_type : `~nengo.neurons.NeuronType`
Simulation neuron type
Returns
-------
net : `nengo.Network`
benchmark network
"""
with nengo.Network(label="pes", seed=0) as net:
net.config[nengo.Ensemble].neuron_type = neuron_type
net.config[nengo.Ensemble].gain = nengo.dists.Choice([1, -1])
net.config[nengo.Ensemble].bias = nengo.dists.Uniform(-1, 1)
net.inp = nengo.Node([1] * dimensions)
net.pre = nengo.Ensemble(neurons_per_d * dimensions, dimensions)
net.post = nengo.Node(size_in=dimensions)
nengo.Connection(net.inp, net.pre)
conn = nengo.Connection(net.pre, net.post, learning_rule_type=nengo.PES())
nengo.Connection(net.post, conn.learning_rule, transform=-1)
nengo.Connection(net.inp, conn.learning_rule)
net.p = nengo.Probe(net.post)
return net
def basal_ganglia(dimensions, neurons_per_d, neuron_type):
"""
Basal ganglia network benchmark.
Parameters
----------
dimensions : int
Number of dimensions for vector values
neurons_per_d : int
Number of neurons to use per vector dimension
neuron_type : `~nengo.neurons.NeuronType`
Simulation neuron type
Returns
-------
net : `nengo.Network`
benchmark network
"""
with nengo.Network(label="basal_ganglia", seed=0) as net:
net.config[nengo.Ensemble].neuron_type = neuron_type
net.inp = nengo.Node([1] * dimensions)
net.bg = nengo.networks.BasalGanglia(dimensions, neurons_per_d)
nengo.Connection(net.inp, net.bg.input)
net.p = nengo.Probe(net.bg.output)
return net
def mnist(use_tensor_layer=True):
"""
A network designed to stress-test tensor layers (based on mnist net).
Parameters
----------
use_tensor_layer : bool
If True, use individual tensor_layers to build the network, as opposed
to a single TensorNode containing all layers.
Returns
-------
net : `nengo.Network`
benchmark network
"""
with nengo.Network() as net:
# create node to feed in images
net.inp = nengo.Node(np.ones(28 * 28))
if use_tensor_layer:
nengo_nl = nengo.RectifiedLinear()
ensemble_params = dict(
max_rates=nengo.dists.Choice([100]), intercepts=nengo.dists.Choice([0])
)
amplitude = 1
synapse = None
x = nengo_dl.Layer(tf.keras.layers.Conv2D(filters=32, kernel_size=3))(
net.inp, shape_in=(28, 28, 1)
)
x = nengo_dl.Layer(nengo_nl)(x, **ensemble_params)
x = nengo_dl.Layer(tf.keras.layers.Conv2D(filters=32, kernel_size=3))(
x, shape_in=(26, 26, 32), transform=amplitude
)
x = nengo_dl.Layer(nengo_nl)(x, **ensemble_params)
x = nengo_dl.Layer(
tf.keras.layers.AveragePooling2D(pool_size=2, strides=2)
)(x, shape_in=(24, 24, 32), synapse=synapse, transform=amplitude)
x = nengo_dl.Layer(tf.keras.layers.Dense(units=128))(x)
x = nengo_dl.Layer(nengo_nl)(x, **ensemble_params)
x = nengo_dl.Layer(tf.keras.layers.Dropout(rate=0.4))(
x, transform=amplitude
)
x = nengo_dl.Layer(tf.keras.layers.Dense(units=10))(x)
else:
nl = tf.nn.relu
# def softlif_layer(x, sigma=1, tau_ref=0.002, tau_rc=0.02,
# amplitude=1):
# # x -= 1
# z = tf.nn.softplus(x / sigma) * sigma
# z += 1e-10
# rates = amplitude / (tau_ref + tau_rc * tf.log1p(1 / z))
# return rates
def mnist_node(x): # pragma: no cover (runs in TF)
x = tf.keras.layers.Conv2D(filters=32, kernel_size=3, activation=nl)(x)
x = tf.keras.layers.Conv2D(filters=32, kernel_size=3, activation=nl)(x)
x = tf.keras.layers.AveragePooling2D(pool_size=2, strides=2)(x)
x = tf.keras.layers.Flatten()(x)
x = tf.keras.layers.Dense(128, activation=nl)(x)
x = tf.keras.layers.Dropout(rate=0.4)(x)
x = tf.keras.layers.Dense(10)(x)
return x
node = nengo_dl.TensorNode(
mnist_node, shape_in=(28, 28, 1), shape_out=(10,)
)
x = node
nengo.Connection(net.inp, node, synapse=None)
net.p = nengo.Probe(x)
return net
def spaun(dimensions):
"""
Builds the Spaun network.
See [1]_ for more details.
Parameters
----------
dimensions : int
Number of dimensions for vector values
Returns
-------
net : `nengo.Network`
benchmark network
References
----------
.. [1] Chris Eliasmith, Terrence C. Stewart, Xuan Choo, Trevor Bekolay,
Travis DeWolf, Yichuan Tang, and Daniel Rasmussen (2012). A large-scale
model of the functioning brain. Science, 338:1202-1205.
Notes
-----
This network needs to be installed via
.. code-block:: bash
pip install git+https://github.com/drasmuss/spaun2.0.git
"""
# pylint: disable=import-outside-toplevel
from _spaun.configurator import cfg
from _spaun.experimenter import experiment
from _spaun.modules.motor import mtr_data
from _spaun.modules.stim import stim_data
from _spaun.modules.vision import vis_data
from _spaun.spaun_main import Spaun
from _spaun.vocabulator import vocab
vocab.sp_dim = dimensions
cfg.mtr_arm_type = None
cfg.set_seed(1)
experiment.initialize(
"A",
stim_data.get_image_ind,
stim_data.get_image_label,
cfg.mtr_est_digit_response_time,
"",
cfg.rng,
)
vocab.initialize(stim_data.stim_SP_labels, experiment.num_learn_actions, cfg.rng)
vocab.initialize_mtr_vocab(mtr_data.dimensions, mtr_data.sps)
vocab.initialize_vis_vocab(vis_data.dimensions, vis_data.sps)
return Spaun()
def random_network(
dimensions,
neurons_per_d,
neuron_type,
n_ensembles,
connections_per_ensemble,
seed=0,
):
"""
A randomly interconnected network of ensembles.
Parameters
----------
dimensions : int
Number of dimensions for vector values
neurons_per_d : int
Number of neurons to use per vector dimension
neuron_type : `~nengo.neurons.NeuronType`
Simulation neuron type
n_ensembles : int
Number of ensembles in the network
connections_per_ensemble : int
Outgoing connections from each ensemble
Returns
-------
net : `nengo.Network`
benchmark network
"""
random.seed(seed)
with nengo.Network(label="random", seed=seed) as net:
net.inp = nengo.Node([0] * dimensions)
net.out = nengo.Node(size_in=dimensions)
net.p = nengo.Probe(net.out)
ensembles = [
nengo.Ensemble(
neurons_per_d * dimensions, dimensions, neuron_type=neuron_type
)
for _ in range(n_ensembles)
]
dec = np.ones((neurons_per_d * dimensions, dimensions))
for ens in net.ensembles:
# add a connection to input and output node, so we never have
# any "orphan" ensembles
nengo.Connection(net.inp, ens)
nengo.Connection(ens, net.out, solver=nengo.solvers.NoSolver(dec))
posts = random.sample(ensembles, connections_per_ensemble)
for post in posts:
nengo.Connection(ens, post, solver=nengo.solvers.NoSolver(dec))
return net
def lmu(theta, input_d, native_nengo=False, dtype="float32"):
"""
A network containing a single Legendre Memory Unit cell and dense readout.
See [1]_ for more details.
Parameters
----------
theta : int
Time window parameter for LMU.
input_d : int
Dimensionality of input signal.
native_nengo : bool
If True, build the LMU out of Nengo objects. Otherwise, build the LMU
directly in TensorFlow, and use a `.TensorNode` to wrap the whole cell.
dtype : str
Float dtype to use for internal parameters of LMU when ``native_nengo=False``
(``native_nengo=True`` will use the dtype of the Simulator).
Returns
-------
net : `nengo.Network`
Benchmark network
References
----------
.. [1] Aaron R. Voelker, Ivana Kajić, and Chris Eliasmith. Legendre memory units:
continuous-time representation in recurrent neural networks.
In Advances in Neural Information Processing Systems. 2019.
https://papers.nips.cc/paper/9689-legendre-memory-units-continuous-time-representation-in-recurrent-neural-networks.
"""
if native_nengo:
# building LMU cell directly out of Nengo objects
class LMUCell(nengo.Network):
"""Implements an LMU cell as a Nengo network."""
def __init__(self, units, order, theta, input_d, **kwargs):
super().__init__(**kwargs)
# compute the A and B matrices according to the LMU's mathematical
# derivation (see the paper for details)
Q = np.arange(order, dtype=np.float64)
R = (2 * Q + 1)[:, None] / theta
j, i = np.meshgrid(Q, Q)
A = np.where(i < j, -1, (-1.0) ** (i - j + 1)) * R
B = (-1.0) ** Q[:, None] * R
C = np.ones((1, order))
D = np.zeros((1,))
A, B, _, _, _ = cont2discrete((A, B, C, D), dt=1.0, method="zoh")
with self:
nengo_dl.configure_settings(trainable=None)
# create objects corresponding to the x/u/m/h variables in LMU
self.x = nengo.Node(size_in=input_d)
self.u = nengo.Node(size_in=1)
self.m = nengo.Node(size_in=order)
self.h = nengo_dl.TensorNode(
tf.nn.tanh, shape_in=(units,), pass_time=False
)
# compute u_t
# note that setting synapse=0 (versus synapse=None) adds a
# one-timestep delay, so we can think of any connections with
# synapse=0 as representing value_{t-1}
nengo.Connection(
self.x, self.u, transform=np.ones((1, input_d)), synapse=None
)
nengo.Connection(
self.h, self.u, transform=np.zeros((1, units)), synapse=0
)
nengo.Connection(
self.m, self.u, transform=np.zeros((1, order)), synapse=0
)
# compute m_t
# in this implementation we'll make A and B non-trainable, but they
# could also be optimized in the same way as the other parameters
conn = nengo.Connection(self.m, self.m, transform=A, synapse=0)
self.config[conn].trainable = False
conn = nengo.Connection(self.u, self.m, transform=B, synapse=None)
self.config[conn].trainable = False
# compute h_t
nengo.Connection(
self.x,
self.h,
transform=np.zeros((units, input_d)),
synapse=None,
)
nengo.Connection(
self.h, self.h, transform=np.zeros((units, units)), synapse=0
)
nengo.Connection(
self.m,
self.h,
transform=nengo_dl.dists.Glorot(distribution="normal"),
synapse=None,
)
with nengo.Network(seed=0) as net:
# remove some unnecessary features to speed up the training
nengo_dl.configure_settings(
trainable=None, stateful=False, keep_history=False
)
# input node
net.inp = nengo.Node(np.zeros(input_d))
# lmu cell
lmu_cell = LMUCell(units=212, order=256, theta=theta, input_d=input_d)
conn = nengo.Connection(net.inp, lmu_cell.x, synapse=None)
net.config[conn].trainable = False
# dense linear readout
out = nengo.Node(size_in=10)
nengo.Connection(
lmu_cell.h, out, transform=nengo_dl.dists.Glorot(), synapse=None
)
# record output. note that we set keep_history=False above, so this will
# only record the output on the last timestep (which is all we need
# on this task)
net.p = nengo.Probe(out)
else:
# putting everything in a tensornode
# define LMUCell
class LMUCell(tf.keras.layers.AbstractRNNCell):
"""Implement LMU as Keras RNN cell."""
def __init__(self, units, order, theta, **kwargs):
super().__init__(**kwargs)
self.units = units
self.order = order
self.theta = theta
Q = np.arange(order, dtype=np.float64)
R = (2 * Q + 1)[:, None] / theta
j, i = np.meshgrid(Q, Q)
A = np.where(i < j, -1, (-1.0) ** (i - j + 1)) * R
B = (-1.0) ** Q[:, None] * R
C = np.ones((1, order))
D = np.zeros((1,))
self._A, self._B, _, _, _ = cont2discrete(
(A, B, C, D), dt=1.0, method="zoh"
)
@property
def state_size(self):
"""Size of RNN state variables."""
return self.units, self.order
@property
def output_size(self):
"""Size of cell output."""
return self.units
def build(self, input_shape):
"""Set up all the weight matrices used inside the cell."""
super().build(input_shape)
input_dim = input_shape[-1]
self.input_encoders = self.add_weight(
shape=(input_dim, 1), initializer=tf.initializers.ones()
)
self.hidden_encoders = self.add_weight(
shape=(self.units, 1), initializer=tf.initializers.zeros()
)
self.memory_encoders = self.add_weight(
shape=(self.order, 1), initializer=tf.initializers.zeros()
)
self.input_kernel = self.add_weight(
shape=(input_dim, self.units), initializer=tf.initializers.zeros()
)
self.hidden_kernel = self.add_weight(
shape=(self.units, self.units), initializer=tf.initializers.zeros()
)
self.memory_kernel = self.add_weight(
shape=(self.order, self.units),
initializer=tf.initializers.glorot_normal(),
)
self.AT = self.add_weight(
shape=(self.order, self.order),
initializer=tf.initializers.constant(self._A.T),
trainable=False,
)
self.BT = self.add_weight(
shape=(1, self.order),
initializer=tf.initializers.constant(self._B.T),
trainable=False,
)
def call(self, inputs, states):
"""Compute cell output and state updates."""
h_prev, m_prev = states
# compute u_t from the above diagram
u = (
tf.matmul(inputs, self.input_encoders)
+ tf.matmul(h_prev, self.hidden_encoders)
+ tf.matmul(m_prev, self.memory_encoders)
)
# compute updated memory state vector (m_t in diagram)
m = tf.matmul(m_prev, self.AT) + tf.matmul(u, self.BT)
# compute updated hidden state vector (h_t in diagram)
h = tf.nn.tanh(
tf.matmul(inputs, self.input_kernel)
+ tf.matmul(h_prev, self.hidden_kernel)
+ tf.matmul(m, self.memory_kernel)
)
return h, [h, m]
with nengo.Network(seed=0) as net:
# remove some unnecessary features to speed up the training
# we could set use_loop=False as well here, but leaving it for parity
# with native_nengo
nengo_dl.configure_settings(stateful=False)
net.inp = nengo.Node(np.zeros(theta))
rnn = nengo_dl.Layer(
tf.keras.layers.RNN(
LMUCell(units=212, order=256, theta=theta, dtype=dtype),
return_sequences=False,
)
)(net.inp, shape_in=(theta, input_d))
out = nengo.Node(size_in=10)
nengo.Connection(rnn, out, transform=nengo_dl.dists.Glorot(), synapse=None)
net.p = nengo.Probe(out)
return net
def run_profile(
net, train=False, n_steps=150, do_profile=True, reps=1, dtype="float32", **kwargs
):
"""
Run profiler on a benchmark network.
Parameters
----------
net : `~nengo.Network`
The nengo Network to be profiled.
train : bool
If True, profile the `.Simulator.fit` function. Otherwise, profile the
`.Simulator.run` function.
n_steps : int
The number of timesteps to run the simulation.
do_profile : bool
Whether or not to run profiling
reps : int
Repeat the run this many times (only profile data from the last
run will be kept).
dtype : str
Simulation dtype (e.g. "float32")
Returns
-------
exec_time : float
Time (in seconds) taken to run the benchmark, taking the minimum over
``reps``.
Notes
-----
kwargs will be passed on to `.Simulator`
"""
exec_time = 1e10
n_batches = 1
with net:
nengo_dl.configure_settings(inference_only=not train, dtype=dtype)
with nengo_dl.Simulator(net, **kwargs) as sim:
if hasattr(net, "inp"):
x = {
net.inp: np.random.randn(
sim.minibatch_size * n_batches, n_steps, net.inp.size_out
)
}
elif hasattr(net, "inp_a"):
x = {
net.inp_a: np.random.randn(
sim.minibatch_size * n_batches, n_steps, net.inp_a.size_out
),
net.inp_b: np.random.randn(
sim.minibatch_size * n_batches, n_steps, net.inp_b.size_out
),
}
else:
x = None
if train:
y = {
net.p: np.random.randn(
sim.minibatch_size * n_batches, n_steps, net.p.size_in
)
}
sim.compile(tf.optimizers.SGD(0.001), loss=tf.losses.mse)
# run once to eliminate startup overhead
start = timeit.default_timer()
sim.fit(x, y, epochs=1, n_steps=n_steps)
print("Warmup time:", timeit.default_timer() - start)
for _ in range(reps):
if do_profile:
tf.profiler.experimental.start("profile")
start = timeit.default_timer()
sim.fit(x, y, epochs=1, n_steps=n_steps)
exec_time = min(timeit.default_timer() - start, exec_time)
if do_profile:
tf.profiler.experimental.stop()
else:
# run once to eliminate startup overhead
start = timeit.default_timer()
sim.predict(x, n_steps=n_steps)
print("Warmup time:", timeit.default_timer() - start)
for _ in range(reps):
if do_profile:
tf.profiler.experimental.start("profile")
start = timeit.default_timer()
sim.predict(x, n_steps=n_steps)
exec_time = min(timeit.default_timer() - start, exec_time)
if do_profile:
tf.profiler.experimental.stop()
exec_time /= n_batches
print("Execution time:", exec_time)
return exec_time
@click.group(chain=True)
def main():
"""Command-line interface for benchmarks."""
@main.command()
@click.pass_obj
@click.option("--benchmark", default="cconv", help="Name of benchmark network")
@click.option("--dimensions", default=128, help="Number of dimensions")
@click.option("--neurons_per_d", default=64, help="Neurons per dimension")
@click.option("--neuron_type", default="RectifiedLinear", help="Nengo neuron model")
@click.option(
"--kwarg",
type=str,
multiple=True,
help="Arbitrary kwarg to pass to benchmark network (key=value)",
)
def build(obj, benchmark, dimensions, neurons_per_d, neuron_type, kwarg):
"""Builds one of the benchmark networks"""
# get benchmark network by name
benchmark = globals()[benchmark]
# get the neuron type object from string class name
try:
neuron_type = getattr(nengo, neuron_type)()
except AttributeError:
neuron_type = getattr(nengo_dl, neuron_type)()
# set up kwargs
kwargs = dict((k, int(v)) for k, v in [a.split("=") for a in kwarg])
# add the special cli kwargs if applicable; note we could just do
# everything through --kwarg, but it is convenient to have a
# direct option for the common arguments
params = inspect.signature(benchmark).parameters
for kw in ("benchmark", "dimensions", "neurons_per_d", "neuron_type"):
if kw in params:
kwargs[kw] = locals()[kw]
# build benchmark and add to context for chaining
print(
f"Building {nengo_dl.utils.function_name(benchmark, sanitize=False)} "
f"with {kwargs}"
)
obj["net"] = benchmark(**kwargs)
@main.command()
@click.pass_obj
@click.option(
"--train/--no-train",
default=False,
help="Whether to profile training (as opposed to running) the network",
)
@click.option(
"--n_steps", default=150, help="Number of steps for which to run the simulation"
)
@click.option("--batch_size", default=1, help="Number of inputs to the model")
@click.option(
"--device",
default="/gpu:0",
help="TensorFlow device on which to run the simulation",
)
@click.option(
"--unroll", default=25, help="Number of steps for which to unroll the simulation"
)
@click.option(
"--time-only",
is_flag=True,
default=False,
help="Only count total time, rather than profiling internals",
)
def profile(obj, train, n_steps, batch_size, device, unroll, time_only):
"""Runs profiling on a network (call after 'build')"""
if "net" not in obj:
raise ValueError("Must call `build` before `profile`")
obj["time"] = run_profile(
obj["net"],
do_profile=not time_only,
train=train,
n_steps=n_steps,
minibatch_size=batch_size,
device=device,
unroll_simulation=unroll,
)
if __name__ == "__main__":
main(obj={}) # pragma: no cover