Debian Codegraph @

brian2/devices/cpp_standalone/codeobject.py

raw
1 """
2 Module implementing the C++ "standalone" `CodeObject`
3 """
4
5 from brian2.codegen.codeobject import CodeObject, constant_or_scalar
6 from brian2.codegen.generators.cpp_generator import CPPCodeGenerator, c_data_type
7 from brian2.codegen.targets import codegen_targets
8 from brian2.codegen.templates import Templater
9 from brian2.core.functions import DEFAULT_FUNCTIONS
10 from brian2.core.preferences import prefs
11 from brian2.devices.device import get_device
12 from brian2.utils.stringtools import replace
13
14 __all__ = ["CPPStandaloneCodeObject"]
15
16
17 def openmp_pragma(pragma_type):
18 nb_threads = prefs.devices.cpp_standalone.openmp_threads
19 openmp_on = not (nb_threads == 0)
20
21 ## First we need to deal with some special cases that have to be handle in case
22 ## openmp is not activated
23 if pragma_type == "set_num_threads":
24 if not openmp_on:
25 return ""
26 elif nb_threads > 0:
27 # We have to fix the exact number of threads in all parallel sections
28 return f"omp_set_dynamic(0);\nomp_set_num_threads({int(nb_threads)});"
29 elif pragma_type == "get_thread_num":
30 if not openmp_on:
31 return "0"
32 else:
33 return "omp_get_thread_num()"
34 elif pragma_type == "get_num_threads":
35 if not openmp_on:
36 return "1"
37 else:
38 return f"{int(nb_threads)}"
39 elif pragma_type == "with_openmp":
40 # The returned value is a proper Python boolean, i.e. not something
41 # that should be included in the generated code but rather for use
42 # in {% if ... %} statements in the template
43 return openmp_on
44
45 ## Then by default, if openmp is off, we do not return any pragma statement in the templates
46 elif not openmp_on:
47 return ""
48 ## Otherwise, we return the correct pragma statement
49 elif pragma_type == "static":
50 return "#pragma omp for schedule(static)"
51 elif pragma_type == "single":
52 return "#pragma omp single"
53 elif pragma_type == "single-nowait":
54 return "#pragma omp single nowait"
55 elif pragma_type == "critical":
56 return "#pragma omp critical"
57 elif pragma_type == "atomic":
58 return "#pragma omp atomic"
59 elif pragma_type == "once":
60 return "#pragma once"
61 elif pragma_type == "parallel-static":
62 return "#pragma omp parallel for schedule(static)"
63 elif pragma_type == "static-ordered":
64 return "#pragma omp for schedule(static) ordered"
65 elif pragma_type == "ordered":
66 return "#pragma omp ordered"
67 elif pragma_type == "include":
68 return "#include <omp.h>"
69 elif pragma_type == "parallel":
70 return "#pragma omp parallel"
71 elif pragma_type == "master":
72 return "#pragma omp master"
73 elif pragma_type == "barrier":
74 return "#pragma omp barrier"
75 elif pragma_type == "compilation":
76 return "-fopenmp"
77 elif pragma_type == "sections":
78 return "#pragma omp sections"
79 elif pragma_type == "section":
80 return "#pragma omp section"
81 else:
82 raise ValueError(f'Unknown OpenMP pragma "{pragma_type}"')
83
84
85 class CPPStandaloneCodeObject(CodeObject):
86 """
87 C++ standalone code object
88
89 The ``code`` should be a `~brian2.codegen.templates.MultiTemplate`
90 object with two macros defined, ``main`` (for the main loop code) and
91 ``support_code`` for any support code (e.g. function definitions).
92 """
93
94 templater = Templater(
95 "brian2.devices.cpp_standalone",
96 ".cpp",
97 env_globals={
98 "c_data_type": c_data_type,
99 "openmp_pragma": openmp_pragma,
100 "constant_or_scalar": constant_or_scalar,
101 "prefs": prefs,
102 "zip": zip,
103 },
104 )
105 generator_class = CPPCodeGenerator
106
107 def __init__(self, *args, **kwds):
108 super().__init__(*args, **kwds)
109 #: Store whether this code object defines before/after blocks
110 self.before_after_blocks = []
111
112 def __call__(self, **kwds):
113 return self.run()
114
115 def compile_block(self, block):
116 pass # Compilation will be handled in device
117
118 def run_block(self, block):
119 if block == "run":
120 get_device().main_queue.append((f"{block}_code_object", (self,)))
121 else:
122 # Check the C++ code whether there is anything to run
123 cpp_code = getattr(self.code, f"{block}_cpp_file")
124 if len(cpp_code) and "EMPTY_CODE_BLOCK" not in cpp_code:
125 get_device().main_queue.append((f"{block}_code_object", (self,)))
126 self.before_after_blocks.append(block)
127
128
129 codegen_targets.add(CPPStandaloneCodeObject)
130
131
132 # At module initialization time, we do not yet know whether the code will be
133 # run with OpenMP or not. We therefore use a "dynamic implementation" which
134 # generates the rand/randn implementation during code generation.
135 def generate_rand_code(rand_func, owner):
136 nb_threads = prefs.devices.cpp_standalone.openmp_threads
137 if nb_threads == 0: # no OpenMP
138 thread_number = "0"
139 else:
140 thread_number = "omp_get_thread_num()"
141 if rand_func not in ["rand", "randn"]:
142 raise AssertionError(rand_func)
143 code = """
144 inline double _%RAND_FUNC%(const int _vectorisation_idx) {
145 return brian::_random_generators[%THREAD_NUMBER%].%RAND_FUNC%();
146 }
147 """
148 code = replace(
149 code,
150 {
151 "%THREAD_NUMBER%": thread_number,
152 "%RAND_FUNC%": rand_func,
153 },
154 )
155 return {"support_code": code}
156
157
158 rand_impls = DEFAULT_FUNCTIONS["rand"].implementations
159 rand_impls.add_dynamic_implementation(
160 CPPStandaloneCodeObject,
161 code=lambda owner: generate_rand_code("rand", owner),
162 namespace=lambda owner: {},
163 name="_rand",
164 )
165
166 randn_impls = DEFAULT_FUNCTIONS["randn"].implementations
167 randn_impls.add_dynamic_implementation(
168 CPPStandaloneCodeObject,
169 code=lambda owner: generate_rand_code("randn", owner),
170 namespace=lambda owner: {},
171 name="_randn",
172 )