Debian Codegraph @

docs_sphinx/user/computation.rst

raw
1 Computational methods and efficiency
2 ====================================
3
4 .. contents::
5 :local:
6 :depth: 2
7
8 Brian has several different methods for running the computations in a
9 simulation. The default mode is :ref:`runtime`, which runs the simulation loop
10 in Python but compiles and executes the modules doing the actual simulation
11 work (numerical integration, synaptic propagation, etc.) in a defined target
12 language. Brian will select the best available target language automatically.
13 On Windows, to ensure that you get the advantages of compiled code, read
14 the instructions on installing a suitable compiler in
15 :ref:`installation_cpp`.
16 Runtime mode has the advantage that you can combine the computations
17 performed by Brian with arbitrary Python code specified as `NetworkOperation`.
18
19 The fact that the simulation is run in Python means that there is a (potentially
20 big) overhead for each simulated time step. An alternative is to run Brian in with
21 :ref:`cpp_standalone` -- this is in general faster (for certain types of simulations
22 *much* faster) but cannot be used for all kinds of simulations. To enable this
23 mode, add the following line after your Brian import, but before your simulation
24 code::
25
26 set_device('cpp_standalone')
27
28 For detailed control over the compilation process (both for runtime and standalone
29 code generation), you can change the :ref:`compiler_settings` that are used.
30
31 .. admonition:: The following topics are not essential for beginners.
32
33 |
34
35 .. _runtime:
36
37 Runtime code generation
38 -----------------------
39 Code generation means that Brian takes the Python code and strings
40 in your model and generates code in one of several possible different
41 languages which is then executed. The target language for this code
42 generation process is set in the `codegen.target` preference. By default, this
43 preference is set to ``'auto'``, meaning that it will choose the compiled language
44 target if possible and fall back to Python otherwise (also raising a warning).
45 The compiled language target is ``'cython'`` which needs the `Cython`_ package in
46 addition to a working C++ compiler. If you want to
47 chose a code generation target explicitly (e.g. because you want to get rid of the
48 warning that only the Python fallback is available), set the preference to ``'numpy'``
49 or ``'cython'`` at the beginning of your script::
50
51 from brian2 import *
52 prefs.codegen.target = 'numpy' # use the Python fallback
53
54 See :doc:`../advanced/preferences` for different ways of setting preferences.
55
56 .. _Cython: http://cython.org/
57
58 Caching
59 ~~~~~~~
60 When you run code with ``cython`` for the first time, it will take
61 some time to compile the code. For short simulations, this can make these
62 targets to appear slow compared to the ``numpy`` target where such compilation
63 is not necessary. However, the compiled code is stored on disk and will be
64 re-used for later runs, making these simulations start faster. If you run many
65 simulations with different code (e.g. Brian's
66 :doc:`test suite <../developer/guidelines/testing>`), this code can take quite
67 a bit of space on the disk. During the import of the ``brian2`` package, we
68 check whether the size of the disk cache exceeds the value set by the
69 `codegen.max_cache_dir_size` preference (by default, 1GB) and display a message
70 if this is the case. You can clear the disk cache manually, or use the
71 `~brian2.__init__.clear_cache` function, e.g. ``clear_cache('cython')``.
72
73 .. note::
74
75 If you run simulations on parallel on a machine using the Network File System, see
76 :ref:`this known issue <parallel_cython>`.
77
78 .. _cpp_standalone:
79
80 Standalone code generation
81 --------------------------
82 Brian supports generating standalone code for multiple devices. In this mode, running a Brian script generates
83 source code in a project tree for the target device/language. This code can then be compiled and run on the device,
84 and modified if needed. At the moment, the only "device" supported is standalone C++ code.
85 In some cases, the speed gains can be impressive, in particular for smaller networks with complicated spike
86 propagation rules (such as STDP).
87
88 To use the C++ standalone mode, you only have to make very small changes to your script. The exact change depends on
89 whether your script has only a single `run` (or `Network.run`) call, or several of them:
90
91 Single run call
92 ~~~~~~~~~~~~~~~
93 At the beginning of the script, i.e. after the import statements, add::
94
95 set_device('cpp_standalone')
96
97 The `Device.build` function will be automatically called with default arguments right after the `run`
98 call. If you need non-standard arguments then you can specify them as part of the `set_device` call::
99
100 set_device('cpp_standalone', directory='my_directory', debug=True)
101
102 Multiple run calls
103 ~~~~~~~~~~~~~~~~~~
104 At the beginning of the script, i.e. after the import statements, add::
105
106 set_device('cpp_standalone', build_on_run=False)
107
108 After the last `run` call, call `CPPStandaloneDevice.build` explicitly::
109
110 device.build()
111
112 The `~Device.build` function has several arguments to specify the output directory, whether or not to
113 compile and run the project after creating it and whether or not to compile it with debugging support or not.
114
115 .. _standalone_multiple_full_runs:
116
117 Multiple full simulation runs
118 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
119
120 To run multiple full, independent, simulations (i.e. not just multiple `run` calls as discussed above), you can
121 use the device's `~brian2.devices.cpp_standalone.device.CPPStandaloneDevice.run` function after an initial build. This will use the previously
122 generated and compiled code, and will therefore run immediately. Note that you cannot change the model or its
123 parameters in the usual way between the `~brian2.devices.cpp_standalone.device.CPPStandaloneDevice.build` and
124 `~brian2.devices.cpp_standalone.device.CPPStandaloneDevice.run` calls.
125 If you want to change some of its parameters, you will have to use the ``run_args`` argument as described below.
126
127 Running multiple simulations with same parameters
128 +++++++++++++++++++++++++++++++++++++++++++++++++
129
130 By default, a device's `~brian2.devices.cpp_standalone.device.CPPStandaloneDevice.run` will run the simulation again,
131 using the same model parameters and initializations. This can be useful, when the model is itself stochastic
132 (e.g. using the ``xi`` noise term in the equations, using a stochastic group such as `PoissonGroup` or
133 `PoissonInput`, etc.), when it uses random synaptic connections, or when it uses random variable initialization::
134
135 set_device('cpp_standalone')
136 group = NeuronGroup(1, 'dv/dt = -v / (10*ms) : 1') # a simple IF neuron without threshold
137 group.v = 'rand()' # v is randomly initialized between 0 and 1
138 mon = StateMonitor(group, 'v', record=0)
139 run(100*ms) # calls device.build and device.run
140 results = [mon.v[0]]
141 # Do 9 more runs without recompiling, each time initializing v to a new value
142 for _ in range(9):
143 device.run()
144 results.append(mon.v[0])
145
146 For more consistent code, you might consider to disable the automatic ``device.build``/``device.run`` call, so
147 that the initial run of the simulation is not different to subsequent runs::
148
149 set_device('cpp_standalone', build_on_run=False)
150 # ... Set up model as before
151 run(100*ms) # will not call device.build/device.run
152 device.build(run=False) # Compile the code
153 results = []
154 # Do 10 runs without recompiling, each time initializing v to a new value
155 for _ in range(10):
156 device.run()
157 results.append(mon.v[0])
158
159
160 Running multiple simulations with different parameters
161 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
162
163 When launching new simulation runs as described above, you can also change parameters of the model. Note that this
164 only concerns parameters that are included in equations, you cannot change externally defined constants. You can
165 easily work around this limitation, however, by declaring such constants in the equations, using the ``(shared, constant)``
166 flags. Here's a similar example to the one shown before, now exploring the effect of the time constant ``tau``, while
167 assuring via a `seed` call that the random initializations are identical across runs::
168
169 set_device('cpp_standalone', build_on_run=False)
170 seed(111) # same random numbers for each run
171 group = NeuronGroup(10, '''dv/dt = -v / tau : 1
172 tau : second (shared, constant)''') # 10 simple IF neuron without threshold
173 group.v = 'rand()'
174 mon = StateMonitor(group, 'v', record=0)
175 run(100*ms)
176 device.build(run=False) # Compile the code
177 results = []
178 # Do 10 runs without recompiling, each time setting group.tau to a new value
179 for tau_value in (np.arange(10)+1)*5*ms:
180 device.run(run_args={group.tau: tau_value})
181 results.append(mon.v[:])
182
183 You can use the same mechanism to provide an array of initial values for a group. E.g., to systematically try out
184 different initializations of ``v``, you could use::
185
186 set_device('cpp_standalone', build_on_run=False)
187 group = NeuronGroup(10, 'dv/dt = -v / (10*ms) : 1') # ten simple IF neurons without threshold
188 mon = StateMonitor(group, 'v', record=True)
189 run(100*ms) # will not call device.build/device.run
190 device.build(run=False) # Compile the code
191 results = []
192 # Do 10 runs without recompiling, each time initializing v differently
193 for idx in range(10):
194 device.run(run_args={group.v: np.arange(10)*0.01 + 0.1*idx})
195 results.append(mon.v[0])
196
197 You can also overwrite the values in a `TimedArray` using this mechanism, by using the `TimedArray` as a key in the
198 ``run_args`` dictionary::
199
200 set_device('cpp_standalone', build_on_run=False)
201 stim = TimedArray(np.zeros(10), dt=10*ms)
202 group = NeuronGroup(10, 'dv/dt = (stim(t) - v)/ (10*ms) : 1') # time-dependent stimulus
203 mon = StateMonitor(group, 'v', record=True)
204 run(100 * ms)
205 device.build(run=False)
206 results = []
207 # Do 10 runs with a 10ms at a random time
208 for idx in range(10):
209 values = np.zeros(10)
210 values[np.random.randint(0, 10)] = 1
211 device.run(run_args={stim: values})
212 results.append(mon.v[0])
213
214 By default, the initialization provided via ``run_args`` overwrites any initializations done in the usual way.
215 This might not exactly do what you want if you use string-based variable initializations that refer to each other.
216 For example, if your equations contain two synaptic time constants ``tau_exc`` and ``tau_inh``, and you always
217 want the latter to be twice the value of the former, you can write::
218
219 group.tau_exc = 5*ms
220 group.tau_inh = 'tau_exc * 2'
221
222 If you now use the ``run_args`` argument to set ``tau_exc`` to a different value, this will not be taken into account
223 for setting ``tau_inh``, since the value change for ``tau_exc`` happens *after* the initialization of ``tau_inh``.
224 Of course you can simply set the value for ``tau_inh`` manually using ``run_args`` as well, but a more general solution
225 is to move the point where the ``run_args`` are applied. You can do this by calling the device's
226 `~brian2.devices.cpp_standalone.device.CPPStandaloneDevice.apply_run_args` function::
227
228 group.tau_exc = 5*ms
229 device.apply_run_args()
230 group.tau_inh = 'tau_exc * 2'
231
232 With this change, setting ``tau_exc`` via ``run_args`` will affect the value of ``tau_inh``.
233
234 Running multiple simulations in parallel
235 ++++++++++++++++++++++++++++++++++++++++
236
237 The techniques mentioned above cannot be directly used to run simulations in parallel (e.g. with Python's
238 `multiprocessing` module), since all of them will try to write the results to the same place. You can
239 circumvent this problem by specifying the ``results_directory`` argument, and setting it to a different value
240 for each run. Note that using the standalone device with `multiprocessing` can be a bit tricky, since the
241 currently selected device is stored globally in the ``device`` module. Use the approach presented below to
242 make sure the device is selected correctly. Here's a variant of the previously shown example running a
243 simulation with random initialization repeatedly, this time running everything in parallel using Python's
244 `multiprocessing` module::
245
246 class SimWrapper:
247 def __init__(self):
248 # Runs once to set up the simulation
249 group = NeuronGroup(1, 'dv/dt = -v / (10*ms) : 1', name='group')
250 group.v = 'rand()' # v is randomly initialized between 0 and 1
251 mon = StateMonitor(group, 'v', record=0, name='monitor')
252 # Store everything in a network
253 self.network = Network([group, mon])
254 self.network.run(100*ms)
255 device.build(run=False)
256 self.device = get_device() # store device object
257
258 def do_run(self, result_dir):
259 # Runs in every process
260 # Workaround to set the device globally in this context
261 from brian2.devices import device_module
262 device_module.active_device = self.device
263 self.device.run(results_directory=result_dir)
264 # Return the results
265 return self.network['monitor'].v[0]
266
267 if __name__ == '__main__': # Important for running on Windows and OS X
268 set_device('cpp_standalone', build_on_run=False)
269 sim = SimWrapper()
270 import multiprocessing
271 with multiprocessing.Pool() as p:
272 # Run 10 simulations in parallel
273 results = p.map(sim.do_run, [f'result_{idx}' for idx in range(10)])
274
275 You can also use parallel runs with the ``run_args`` argument. For example, to do 10 simulations
276 with different (deterministic) initial values for ``v``::
277
278 class SimWrapper:
279 # ... model definition without random initialization
280
281 def do_run(self, v_init):
282 # Set result directory based on variable
283 result_dir = f'result_{v_init}'
284 self.device.run(run_args={self.network['group'].v: v_init},
285 results_directory=result_dir)
286 # Return the results
287 return self.network['monitor'].v[0]
288
289 if __name__ == '__main__': # Important for running on Windows and OS X
290 set_device('cpp_standalone', build_on_run=False)
291 sim = SimWrapper()
292 import multiprocessing
293 with multiprocessing.Pool() as p:
294 # Run 10 simulations in parallel
295 results = p.map(sim.do_run, np.linspace(0, 1, 10))
296
297 .. note::
298
299 Python's `multiprocessing` module cannot deal with user-defined functions (including `~.TimedArray`) and other
300 complex code structures. If you run into `~.pickle.PicklingError` or `AttributeError` exceptions, you might
301 have to use the `pathos` (https://pypi.org/project/pathos) package instead, which can handle more complex
302 code structures.
303
304 Limitations
305 ~~~~~~~~~~~
306 Not all features of Brian will work with C++ standalone, in particular Python based network operations and
307 some array based syntax such as ``S.w[0, :] = ...`` will not work. If possible, rewrite these using string
308 based syntax and they should work. Also note that since the Python code actually runs as normal, code that does
309 something like this may not behave as you would like::
310
311 results = []
312 for val in vals:
313 # set up a network
314 run()
315 results.append(result)
316
317 The current C++ standalone code generation only works for a fixed number of `~Network.run` statements, not with loops.
318 If you need to do loops or other features not supported automatically, you can do so by inspecting the generated
319 C++ source code and modifying it, or by inserting code directly into the main loop as described below.
320
321 .. _standalone_variables:
322
323 Variables
324 ~~~~~~~~~
325 In standalone mode, code will only be executed when the simulation is run (after the `run` call by default, or after a call
326 to `~brian2.devices.cpp_standalone.device..build`, if `set_device` has been called with ``build_on_run`` set to ``False``).
327 This means that it is not possible to access state variables and synaptic connection indices in the Python script doing the
328 set up of the model. For example, the following code would work fine in runtime mode, but raise a ``NotImplementedError``
329 in standalone mode::
330
331 neuron = NeuronGroup(10, 'v : volt')
332 neuron.v = '-70*mV + rand()*10*mV'
333 print(np.mean(neuron.v))
334
335 Sometimes, access is needed to make one variable depend on another variable for initialization. In such cases, it is often
336 possible to circumvent the issue by using initialization with string expressions for both variables. For example, to set
337 the initial membrane potential relative to a random leak reversal potential, the following code would work in runtime mode
338 but fail in standalone mode::
339
340 neuron = NeuronGroup(10, 'dv/dt = -g_L*(v - E_L)/tau : volt')
341 neuron.E_L = '-70*mV + rand()*10*mV' # E_L between -70mV and -60mV
342 neuron.v = neuron.E_L # initial membrane potential equal to E_L
343
344 Instead, you can initialize the variable `v` with a string expression, which means that standalone will execute it
345 during the run when the value of `E_L` is available::
346
347 neuron = NeuronGroup(10, 'dv/dt = -g_L*(v - E_L)/tau : volt')
348 neuron.E_L = '-70*mV + rand()*10*mV' # E_L between -70mV and -60mV
349 neuron.v = 'E_L' # works both in runtime and standalone mode
350
351 The same applies to synaptic indices. For example, if we want to set weights differently depending on the target index
352 of a synapse, the following would work in runtime mode but fail in standalone mode, since the synaptic indices have not
353 been determined yet::
354
355 neurons = NeuronGroup(10, '')
356 synapses = Synapses(neurons, neurons, 'w : 1')
357 synapses.connect(p=0.25)
358 # Set weights to low values when targetting first five neurons and to high values otherwise
359 synapses.w[:, :5] = 0.1
360 synapses.w[:, 5:] = 0.9
361
362 Again, this initialization can be replaced by string expressions, so that standalone mode can evaluate them in the
363 generated code after synapse creation::
364
365 neurons = NeuronGroup(10, '')
366 synapses = Synapses(neurons, neurons, 'w : 1')
367 synapses.connect(p=0.25)
368 # Set weights to low values when targetting first five neurons and to high values otherwise
369 synapses.w['j < 5'] = 0.1
370 synapses.w['j >= 5'] = 0.9
371
372 Note that this limitation only applies if the variables or synapses have been initialized in ways that require the
373 execution of code. If instead they are initialized with concrete values, they can be accessed in Python code even
374 in standalone mode::
375
376 neurons = NeuronGroup(10, 'v : volt')
377 neurons.v = -70*mV
378 print(np.mean(neurons.v)) # works in standalone
379 synapses = Synapses(neurons, neurons, 'w : 1')
380 synapses.connect(i=[0, 2, 4, 6, 8], j=[1, 3, 5, 7, 9])
381 # works as well, since synaptic indices are known
382 synapses.w[:, :5] = 0.1
383 synapses.w[:, 5:] = 0.9
384
385
386
387 In any case, state variables, synaptic indices, and monitored variables can be accessed using standard syntax *after* a
388 run (with a few exceptions, e.g. string expressions for indexing).
389
390 .. _openmp:
391
392 Multi-threading with OpenMP
393 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
394
395 .. warning::
396 OpenMP code has not yet been well tested and so may be inaccurate.
397
398 When using the C++ standalone mode, you have the opportunity to turn on multi-threading, if your C++ compiler is compatible with
399 OpenMP. By default, this option is turned off and only one thread is used. However, by changing the preferences of the codegen.cpp_standalone
400 object, you can turn it on. To do so, just add the following line in your python script::
401
402 prefs.devices.cpp_standalone.openmp_threads = XX
403
404 XX should be a positive value representing the number of threads that will be
405 used during the simulation. Note that the speedup will strongly depend on the
406 network, so there is no guarantee that the speedup will be linear as a function
407 of the number of threads. However, this is working fine for networks with not
408 too small timestep (dt > 0.1ms), and results do not depend on the number of
409 threads used in the simulation.
410
411 Custom code injection
412 ~~~~~~~~~~~~~~~~~~~~~
413 It is possible to insert custom code directly into the generated code of a
414 standalone simulation using a Device's `~.Device.insert_code` method::
415
416 device.insert_code(slot, code)
417
418 ``slot`` can be one of ``main``, ``before_start``, ``after_start``,
419 ``before_network_run``, ``after_network_run``, ``before_end`` and ``after_end``,
420 which determines where the code is inserted. ``code`` is the code in the
421 Device's language. Here is an example for the C++ Standalone Device::
422
423 device.insert_code('main', '''
424 cout << "Testing direct insertion of code." << endl;
425 ''')
426
427 For the C++ Standalone Device, all code is inserted into the ``main.cpp`` file,
428 here into the ``main`` slot, referring to the main simulation function.
429 This is a simplified version of this function in ``main.cpp``::
430
431 int main(int argc, char **argv)
432 {
433 // before_start
434 brian_start();
435 // after_start
436
437 {{main_lines}}
438
439 // before_end
440 brian_end();
441 // after_end
442
443 return 0;
444 }
445
446 ``{{main_lines}}`` is replaced in the generated code with the actual simulation.
447 Code inserted into the ``main`` slot will be placed within the
448 ``{{main_lines}}``. ``brian_start`` allocates and initializes all arrays needed
449 during the simulation and ``brian_end`` writes the results to disc and
450 deallocates memory. Within the ``{{main_lines}}``, all ``Network`` objects
451 defined in Python are created and run. Code inserted in the
452 ``before/after_network_run`` slot will be inserted around the ``Network.run``
453 call, which starts the time loop. Note that if your Python script has multiple
454 ``Network`` objects or multiple ``run`` calls, code in the
455 ``before/after_network_run`` slot will be inserted around each ``Network.run``
456 call in the generated code.
457
458 The code injection mechanism has been used for benchmarking experiments, see
459 e.g. `here for Brian2CUDA benchmarks <https://github.com/brian-team/brian2cuda/blob/835c978ad758bc0621e34344c1fb7b811ef8a118/brian2cuda/tests/features/cuda_configuration.py#L148-L156>`_ or `here for Brian2GeNN benchmarks <https://github.com/brian-team/brian2genn_benchmarks/blob/6d1a6d9d97c05653cec2e413c9fd312cfe13e15c/benchmark_utils.py#L78-L136>`_.
460
461
462 .. _standalone_custom_build:
463
464 Customizing the build process
465 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
466 In standalone mode, a standard "make file" is used to orchestrate the
467 compilation and linking. To provide additional arguments to the ``make`` command
468 (respectively ``nmake`` on Windows), you can use the
469 `devices.cpp_standalone.extra_make_args_unix` or
470 `devices.cpp_standalone.extra_make_args_windows` preference. On Linux,
471 this preference is by default set to ``['-j']`` to enable parallel compilation.
472 Note that you can also use these arguments to overwrite variables in the make
473 file, e.g. to use `clang <https://clang.llvm.org/>`_ instead of the default
474 `gcc <https://gcc.gnu.org/>`_ compiler::
475
476 prefs.devices.cpp_standalone.extra_make_args_unix += ['CC=clang++']
477
478
479 .. _compiler_settings:
480
481 Cleaning up after a run
482 ~~~~~~~~~~~~~~~~~~~~~~~
483 Standalone simulations store all results of a simulation (final state variable
484 values and values stored in monitors) to disk. These results can take up quite
485 significant amount of space, and you might therefore want to delete these
486 results when you do not need them anymore. You can do this by using the device's
487 `~.Device.delete` method::
488
489 device.delete()
490
491 Be aware that deleting the data will make all access to state variables fail,
492 including the access to values in monitors. You should therefore only delete the
493 data after doing all analysis/plotting that you are interested in.
494
495 By default, this function will delete both the generated code and the data, i.e.
496 the full project directory. If you want to keep the code (which typically takes
497 up little space compared to the results), exclude it from the deletion::
498
499 device.delete(code=False)
500
501 If you added any additional files to the project directory manually, these will
502 not be deleted by default. To delete the full directory regardless of its
503 content, use the ``force`` option::
504
505 device.delete(force=True)
506
507 .. note::
508 When you initialize state variables with concrete values (and not with
509 a string expression), they will be stored to disk from your Python script
510 and loaded from disk at the beginning of the standalone run. Since these
511 values are necessary for the compiled binary file to run, they are
512 considered "code" from the point of view of the `~.Device.delete` function.
513
514 Compiler settings
515 -----------------
516
517 If using C++ code generation (either via cython or standalone), the
518 compiler settings can make a big difference for the speed of the simulation.
519 By default, Brian uses a set of compiler settings that switches on various
520 optimizations and compiles for running on the same architecture where the
521 code is compiled. This allows the compiler to make use of as many advanced
522 instructions as possible, but reduces portability of the generated executable
523 (which is not usually an issue).
524
525 If there are any issues with these compiler settings, for example because
526 you are using an older version of the C++ compiler or because you want to
527 run the generated code on a different architecture, you can change the
528 settings by manually specifying the `codegen.cpp.extra_compile_args`
529 preference (or by using `codegen.cpp.extra_compile_args_gcc` or
530 `codegen.cpp.extra_compile_args_msvc` if you want to specify the settings
531 for either compiler only).