Debian Codegraph @

docs_sphinx/developer/openmp.rst

raw
1 Multi-threading with OpenMP
2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
3
4 The following is an outline of how to make C++ standalone templates compatible
5 with OpenMP, and therefore make them work in a multi-threaded environment. This
6 should be considered as an extension to :doc:`codegen`, that has to
7 be read first. The C++ standalone mode of Brian is compatible with OpenMP, and
8 therefore simulations can be launched by users with one or with multiple
9 threads. Therefore, when adding new templates, the developers need to make sure
10 that those templates are properly handling the situation if launched with
11 OpenMP.
12
13 Key concepts
14 ============
15
16 All the simulations performed with the C++ standalone mode can be launched with
17 multi-threading, and make use of multiple cores on the same machine. Basically,
18 all the Brian operations that can easily be performed in parallel, such as
19 computing the equations for `NeuronGroup`, `Synapses`, and so on can and should
20 be split among several threads. The network construction, so far, is still
21 performed only by one single thread, and all created objects are shared by all
22 the threads.
23
24 Use of ``#pragma`` flags
25 ========================
26
27 In OpenMP, all the parallelism is handled thanks to extra comments, added in the
28 main C++ code, under the form::
29
30 #pragma omp ...
31
32 But to avoid any dependencies in the code that is generated by Brian when
33 OpenMP is not activated, we are using functions that will only add those
34 comments, during code generation, when such a multi-threading mode is turned on.
35 By default, nothing will be inserted.
36
37 Translations of the ``#pragma`` commands
38 ----------------------------------------
39
40 All the translations from ``openmp_pragma()`` calls in the C++ templates are
41 handled
42 in the file ``devices/cpp_standalone/codeobject.py`` In this function, you can
43 see that all calls with various string inputs will generate #pragma statements
44 inserted into the C++ templates during code generation. For example::
45
46 {{ openmp_pragma('static') }}
47
48 will be transformed, during code generation, into::
49
50 #pragma omp for schedule(static)
51
52 You can find the list of all the translations in the core of the
53 ``openmp_pragma()`` function, and if some extra translations are needed, they
54 should be added here.
55
56 Execution of the OpenMP code
57 ----------------------------
58
59 In this section, we are explaining the main ideas behind the OpenMP mode of
60 Brian, and how the simulation is executed in such a parallel context.
61 As can be seen in ``devices/cpp_standalone/templates/main.cpp``, the appropriate
62 number of threads, defined by the user, is fixed at the beginning
63 of the main function in the C++ code with::
64
65 {{ openmp_pragma('set_num_threads') }}
66
67 equivalent to (thanks to the ``openmp_pragam()`` function defined above):
68 nothing if OpenMP is turned off (default), and to::
69
70 omp_set_dynamic(0);
71 omp_set_num_threads(nb_threads);
72
73 otherwise. When OpenMP creates a parallel context, this is the number of
74 threads that will be used. As said, network creation is performed without
75 any calls to OpenMP, on one single thread. Each template that wants to use
76 parallelism has to add ``{{ openmp_pragma{('parallel')}}`` to create a general
77 block that will be executed in parallel or
78 ``{{ openmp_pragma{('parallel-static')}}`` to execute a single loop in parallel.
79
80 How to make your template use OpenMP parallelism
81 ================================================
82
83 To design a parallel template, such as for example
84 ``devices/cpp_standalone/templates/common_group.cpp``, you can see that as soon
85 as you have loops that can safely be split across nodes, you just need to add
86 an openmp command in front of those loops::
87
88 {{openmp_pragma('parallel-static')}}
89 for(int _idx=0; _idx<N; _idx++)
90 {
91 ...
92 }
93
94 By doing so, OpenMP will take care of splitting the indices and each thread
95 will loop only on a subset of indices, sharing the load. By default, the
96 scheduling use for splitting the indices is static, meaning that each node will
97 get the same number of indices: this is the faster scheduling in OpenMP, and it
98 makes sense for `NeuronGroup` or `Synapses` because operations are the same for
99 all indices. By having a look at examples of templates such as
100 ``devices/cpp_standalone/templates/statemonitor.cpp``, you can see that you can
101 merge portions of code executed by only one node and portions executed in
102 parallel. In this template, for example, only one node is recording the time and
103 extending the size of the arrays to store the recorded values::
104
105 {{_dynamic_t}}.push_back(_clock_t);
106
107 // Resize the dynamic arrays
108 {{_recorded}}.resize(_new_size, _num_indices);
109
110 But then, values are written in the arrays by all the nodes::
111
112 {{ openmp_pragma('parallel-static') }}
113 for (int _i = 0; _i < _num_indices; _i++)
114 {
115 ....
116 }
117
118 In general, operations that manipulate global data structures, e.g. that use
119 ``push_back`` for a ``std::vector``, should only be executed by a single thread.
120
121 Synaptic propagation in parallel
122 ================================
123
124 General ideas
125 -------------
126
127 With OpenMP, synaptic propagation is also multi-threaded. Therefore, we have to
128 modify the `SynapticPathway` objects, handling spike propagation. As can be seen
129 in ``devices/cpp_standalone/templates/synapses_classes.cpp``, such an object,
130 created during run time, will be able to get the number of threads decided by
131 the user::
132
133 _nb_threads = {{ openmp_pragma('get_num_threads') }};
134
135 By doing so, a `SynapticPathway`, instead of handling only one `SpikeQueue`,
136 will be divided into ``_nb_threads`` `SpikeQueue`\ s, each of them handling a
137 subset of the total number of connections. All the calls to
138 `SynapticPathway` object are performed from within ``parallel`` blocks in the
139 ``synapses`` and ``synapses_push_spikes`` template, we have to take this
140 parallel context into account. This is why all the function of the
141 `SynapticPathway` object are taking care of the node number::
142
143 void push(int *spikes, unsigned int nspikes)
144 {
145 queue[{{ openmp_pragma('get_thread_num') }}]->push(spikes, nspikes);
146 }
147
148 Such a method for the `SynapticPathway` will make sure that when spikes are
149 propagated, all the threads will propagate them to their connections. By
150 default, again, if OpenMP is turned off, the queue vector has size 1.
151
152 Preparation of the `SynapticPathway`
153 ------------------------------------
154
155 Here we are explaining the implementation of the ``prepare()`` method for
156 `SynapticPathway`::
157
158 {{ openmp_pragma('parallel') }}
159 {
160 unsigned int length;
161 if ({{ openmp_pragma('get_thread_num') }} == _nb_threads - 1)
162 length = n_synapses - (unsigned int) {{ openmp_pragma('get_thread_num') }}*n_synapses/_nb_threads;
163 else
164 length = (unsigned int) n_synapses/_nb_threads;
165
166 unsigned int padding = {{ openmp_pragma('get_thread_num') }}*(n_synapses/_nb_threads);
167
168 queue[{{ openmp_pragma('get_thread_num') }}]->openmp_padding = padding;
169 queue[{{ openmp_pragma('get_thread_num') }}]->prepare(&real_delays[padding], &sources[padding], length, _dt);
170 }
171
172 Basically, each threads is getting an equal number of synapses (except the
173 last one, that will get the remaining ones, if the number is not a multiple of
174 ``n_threads``), and the queues are receiving a padding integer telling them what
175 part of the synapses belongs to each queue. After that, the parallel context is
176 destroyed, and network creation can continue. Note that this could have been
177 done without a parallel context, in a sequential manner, but this is just
178 speeding up everything.
179
180 Selection of the spikes
181 -----------------------
182
183 Here we are explaining the implementation of the ``peek()`` method for
184 `SynapticPathway`. This is an example of concurrent access to data structures
185 that are not well handled in parallel, such as ``std::vector``. When ``peek()`` is
186 called, we need to return a vector of all the neuron spiking at that particular
187 time. Therefore, we need to ask every queue of the `SynapticPathway` what are the
188 id of the spiking neurons, and concatenate them. Because those ids are stored
189 in vectors with various shapes, we need to loop over nodes to perform this
190 concatenate, in a sequential manner::
191
192 {{ openmp_pragma('static-ordered') }}
193 for(int _thread=0; _thread < {{ openmp_pragma('get_num_threads') }}; _thread++)
194 {
195 {{ openmp_pragma('ordered') }}
196 {
197 if (_thread == 0)
198 all_peek.clear();
199 all_peek.insert(all_peek.end(), queue[_thread]->peek()->begin(), queue[_thread]->peek()->end());
200 }
201 }
202
203 The loop, with the keyword 'static-ordered', is therefore performed such that
204 node 0 enters it first, then node 1, and so on. Only one node at a time is
205 executing the block statement. This is needed because vector manipulations can
206 not be performed in a multi-threaded manner. At the end of the loop, ``all_peek``
207 is now a vector where all sub queues have written the id of spiking cells, and
208 therefore this is the list of all spiking cells within the `SynapticPathway`.
209
210 Compilation of the code
211 =======================
212
213 One extra file needs to be modified, in order for OpenMP implementation to work.
214 This is the makefile ``devices/cpp_standalone/templates/makefile``. As one can
215 simply see, the CFLAGS are dynamically modified during code generation thanks
216 to::
217
218 {{ openmp_pragma('compilation') }}
219
220 If OpenMP is activated, this will add the following dependencies::
221
222 -fopenmp
223
224 such that if OpenMP is turned off, nothing, in the generated code, does depend
225 on it.