pacrunner 0.5.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. pacrunner/__init__.py +55 -0
  2. pacrunner/_artifacts.py +259 -0
  3. pacrunner/_env.py +260 -0
  4. pacrunner/_libraries.py +314 -0
  5. pacrunner/_literal.py +52 -0
  6. pacrunner/_mad.py +276 -0
  7. pacrunner/_madgraph.py +357 -0
  8. pacrunner/_mgrun.py +110 -0
  9. pacrunner/_pyamplicol.py +134 -0
  10. pacrunner/_runtime.py +142 -0
  11. pacrunner/c/cuda/pool.cu +151 -0
  12. pacrunner/c/cuda/pool.h +55 -0
  13. pacrunner/c/cuda/uirgpu.c +103 -0
  14. pacrunner/c/cuda/uirgpu.h +70 -0
  15. pacrunner/c/cuda/uirgpu_pool.c +89 -0
  16. pacrunner/c/cuda/uirgpu_provider.c +103 -0
  17. pacrunner/c/cuda/uirgpu_umami.c +108 -0
  18. pacrunner/c/metal/PLAN.md +248 -0
  19. pacrunner/c/metal/df64.h +185 -0
  20. pacrunner/c/metal/metalpool.h +47 -0
  21. pacrunner/c/metal/metalpool.m +93 -0
  22. pacrunner/c/metal/msl_shim.h +86 -0
  23. pacrunner/c/metal/pacops.metal +472 -0
  24. pacrunner/c/metal/uirmetal.h +42 -0
  25. pacrunner/c/metal/uirmetal.m +222 -0
  26. pacrunner/c/metal/uirvm.metal +491 -0
  27. pacrunner/c/metal/umami_metal.c +230 -0
  28. pacrunner/c/pacops.c +498 -0
  29. pacrunner/c/pacops.h +210 -0
  30. pacrunner/c/uirvm.c +408 -0
  31. pacrunner/c/uirvm.h +165 -0
  32. pacrunner/c/umami.h +334 -0
  33. pacrunner/c/umami_finish.h +109 -0
  34. pacrunner/c/umami_pac.c +558 -0
  35. pacrunner/codegen/__init__.py +21 -0
  36. pacrunner/codegen/common.py +355 -0
  37. pacrunner/codegen/compile.py +245 -0
  38. pacrunner/codegen/compile_metal.py +246 -0
  39. pacrunner/codegen/compile_simd.py +1006 -0
  40. pacrunner/codegen/compile_split.py +443 -0
  41. pacrunner/codegen/compile_vm.py +236 -0
  42. pacrunner/kernels/__init__.py +18 -0
  43. pacrunner/kernels/kernel_c.py +744 -0
  44. pacrunner/kernels/kernel_msl.py +84 -0
  45. pacrunner/kernels/mir.py +368 -0
  46. pacrunner/simd/__init__.py +3 -0
  47. pacrunner/simd/elf.py +177 -0
  48. pacrunner/simd/handgen.py +235 -0
  49. pacrunner/simd/lib/closure_1.json +1 -0
  50. pacrunner/simd/lib/closure_2.json +1 -0
  51. pacrunner/simd/lib/closure_3.json +1 -0
  52. pacrunner/simd/lib/closure_4.json +1 -0
  53. pacrunner/simd/lib/closure_5.json +1 -0
  54. pacrunner/simd/lib/closure_6.json +1 -0
  55. pacrunner/simd/lib/config.json +37 -0
  56. pacrunner/simd/lib/propagator_vector.json +1 -0
  57. pacrunner/simd/lib/propagator_weyl_a.json +1 -0
  58. pacrunner/simd/lib/propagator_weyl_b.json +1 -0
  59. pacrunner/simd/lib/vertex_tensor_vector_add.json +1 -0
  60. pacrunner/simd/lib/vertex_tensor_vector_set.json +1 -0
  61. pacrunner/simd/lib/vertex_three_vector_add.json +1 -0
  62. pacrunner/simd/lib/vertex_three_vector_set.json +1 -0
  63. pacrunner/simd/lib/vertex_vector_wedge_add.json +1 -0
  64. pacrunner/simd/lib/vertex_vector_wedge_set.json +1 -0
  65. pacrunner/simd/lib/vertex_weyl_vector_a_add.json +1 -0
  66. pacrunner/simd/lib/vertex_weyl_vector_a_set.json +1 -0
  67. pacrunner/simd/lib/vertex_weyl_vector_b_add.json +1 -0
  68. pacrunner/simd/lib/vertex_weyl_vector_b_set.json +1 -0
  69. pacrunner/simd/lib/wave_dirac_anti_1_massive.json +1 -0
  70. pacrunner/simd/lib/wave_dirac_anti_1_massless.json +1 -0
  71. pacrunner/simd/lib/wave_dirac_anti_m1_massive.json +1 -0
  72. pacrunner/simd/lib/wave_dirac_anti_m1_massless.json +1 -0
  73. pacrunner/simd/lib/wave_dirac_part_1_massive.json +1 -0
  74. pacrunner/simd/lib/wave_dirac_part_1_massless.json +1 -0
  75. pacrunner/simd/lib/wave_dirac_part_m1_massive.json +1 -0
  76. pacrunner/simd/lib/wave_dirac_part_m1_massless.json +1 -0
  77. pacrunner/simd/lib/wave_gluon_1.json +1 -0
  78. pacrunner/simd/lib/wave_gluon_m1.json +1 -0
  79. pacrunner/simd/lib/wave_massive_vector_0.json +1 -0
  80. pacrunner/simd/lib/wave_massive_vector_1.json +1 -0
  81. pacrunner/simd/lib/wave_massive_vector_m1.json +1 -0
  82. pacrunner/simd/lib/wave_weyl_anti_1_1.json +1 -0
  83. pacrunner/simd/lib/wave_weyl_anti_1_m1.json +1 -0
  84. pacrunner/simd/lib/wave_weyl_anti_m1_1.json +1 -0
  85. pacrunner/simd/lib/wave_weyl_anti_m1_m1.json +1 -0
  86. pacrunner/simd/lib/wave_weyl_part_1_1.json +1 -0
  87. pacrunner/simd/lib/wave_weyl_part_1_m1.json +1 -0
  88. pacrunner/simd/lib/wave_weyl_part_m1_1.json +1 -0
  89. pacrunner/simd/lib/wave_weyl_part_m1_m1.json +1 -0
  90. pacrunner/simd/lib_hand_avx2/closure_1.json +1 -0
  91. pacrunner/simd/lib_hand_avx2/closure_2.json +1 -0
  92. pacrunner/simd/lib_hand_avx2/closure_3.json +1 -0
  93. pacrunner/simd/lib_hand_avx2/closure_4.json +1 -0
  94. pacrunner/simd/lib_hand_avx2/closure_5.json +1 -0
  95. pacrunner/simd/lib_hand_avx2/closure_6.json +1 -0
  96. pacrunner/simd/lib_hand_avx2/propagator_vector.json +1 -0
  97. pacrunner/simd/lib_hand_avx2/propagator_weyl_a.json +1 -0
  98. pacrunner/simd/lib_hand_avx2/propagator_weyl_b.json +1 -0
  99. pacrunner/simd/lib_hand_avx2/vertex_tensor_vector_add.json +1 -0
  100. pacrunner/simd/lib_hand_avx2/vertex_tensor_vector_set.json +1 -0
  101. pacrunner/simd/lib_hand_avx2/vertex_three_vector_add.json +1 -0
  102. pacrunner/simd/lib_hand_avx2/vertex_three_vector_set.json +1 -0
  103. pacrunner/simd/lib_hand_avx2/vertex_vector_wedge_add.json +1 -0
  104. pacrunner/simd/lib_hand_avx2/vertex_vector_wedge_set.json +1 -0
  105. pacrunner/simd/lib_hand_avx2/vertex_weyl_vector_a_add.json +1 -0
  106. pacrunner/simd/lib_hand_avx2/vertex_weyl_vector_a_set.json +1 -0
  107. pacrunner/simd/lib_hand_avx2/vertex_weyl_vector_b_add.json +1 -0
  108. pacrunner/simd/lib_hand_avx2/vertex_weyl_vector_b_set.json +1 -0
  109. pacrunner/simd/lib_hand_avx512/closure_1.json +1 -0
  110. pacrunner/simd/lib_hand_avx512/closure_2.json +1 -0
  111. pacrunner/simd/lib_hand_avx512/closure_3.json +1 -0
  112. pacrunner/simd/lib_hand_avx512/closure_4.json +1 -0
  113. pacrunner/simd/lib_hand_avx512/closure_5.json +1 -0
  114. pacrunner/simd/lib_hand_avx512/closure_6.json +1 -0
  115. pacrunner/simd/lib_hand_avx512/propagator_vector.json +1 -0
  116. pacrunner/simd/lib_hand_avx512/propagator_weyl_a.json +1 -0
  117. pacrunner/simd/lib_hand_avx512/propagator_weyl_b.json +1 -0
  118. pacrunner/simd/lib_hand_avx512/vertex_tensor_vector_add.json +1 -0
  119. pacrunner/simd/lib_hand_avx512/vertex_tensor_vector_set.json +1 -0
  120. pacrunner/simd/lib_hand_avx512/vertex_three_vector_add.json +1 -0
  121. pacrunner/simd/lib_hand_avx512/vertex_three_vector_set.json +1 -0
  122. pacrunner/simd/lib_hand_avx512/vertex_vector_wedge_add.json +1 -0
  123. pacrunner/simd/lib_hand_avx512/vertex_vector_wedge_set.json +1 -0
  124. pacrunner/simd/lib_hand_avx512/vertex_weyl_vector_a_add.json +1 -0
  125. pacrunner/simd/lib_hand_avx512/vertex_weyl_vector_a_set.json +1 -0
  126. pacrunner/simd/lib_hand_avx512/vertex_weyl_vector_b_add.json +1 -0
  127. pacrunner/simd/lib_hand_avx512/vertex_weyl_vector_b_set.json +1 -0
  128. pacrunner/simd/lib_hand_neon/closure_1.json +1 -0
  129. pacrunner/simd/lib_hand_neon/closure_2.json +1 -0
  130. pacrunner/simd/lib_hand_neon/closure_3.json +1 -0
  131. pacrunner/simd/lib_hand_neon/closure_4.json +1 -0
  132. pacrunner/simd/lib_hand_neon/closure_5.json +1 -0
  133. pacrunner/simd/lib_hand_neon/closure_6.json +1 -0
  134. pacrunner/simd/lib_hand_neon/propagator_vector.json +1 -0
  135. pacrunner/simd/lib_hand_neon/propagator_weyl_a.json +1 -0
  136. pacrunner/simd/lib_hand_neon/propagator_weyl_b.json +1 -0
  137. pacrunner/simd/lib_hand_neon/vertex_tensor_vector_add.json +1 -0
  138. pacrunner/simd/lib_hand_neon/vertex_tensor_vector_set.json +1 -0
  139. pacrunner/simd/lib_hand_neon/vertex_three_vector_add.json +1 -0
  140. pacrunner/simd/lib_hand_neon/vertex_three_vector_set.json +1 -0
  141. pacrunner/simd/lib_hand_neon/vertex_vector_wedge_add.json +1 -0
  142. pacrunner/simd/lib_hand_neon/vertex_vector_wedge_set.json +1 -0
  143. pacrunner/simd/lib_hand_neon/vertex_weyl_vector_a_add.json +1 -0
  144. pacrunner/simd/lib_hand_neon/vertex_weyl_vector_a_set.json +1 -0
  145. pacrunner/simd/lib_hand_neon/vertex_weyl_vector_b_add.json +1 -0
  146. pacrunner/simd/lib_hand_neon/vertex_weyl_vector_b_set.json +1 -0
  147. pacrunner/simd/library.py +495 -0
  148. pacrunner/simd/mir.py +233 -0
  149. pacrunner/simd/split_kernel.py +308 -0
  150. pacrunner/uir/__init__.py +25 -0
  151. pacrunner/uir/encode.py +212 -0
  152. pacrunner/uir/export.py +482 -0
  153. pacrunner/uir/passes.py +69 -0
  154. pacrunner/uir/types.py +318 -0
  155. pacrunner/uir/validate.py +333 -0
  156. pacrunner/umami.py +636 -0
  157. pacrunner-0.5.1.dist-info/METADATA +453 -0
  158. pacrunner-0.5.1.dist-info/RECORD +162 -0
  159. pacrunner-0.5.1.dist-info/WHEEL +5 -0
  160. pacrunner-0.5.1.dist-info/licenses/LICENSE +21 -0
  161. pacrunner-0.5.1.dist-info/licenses/pacrunner/c/UMAMI_LICENSE +41 -0
  162. pacrunner-0.5.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,314 @@
1
+ """Provider: PacRunner's build of a UMAMI provider, the folder PacRunner's umami_libraries writes.
2
+
3
+ provider = Provider("zgg_libs") # a folder (or its umami_pac.json)
4
+ provider.device, provider.precision, provider.channels, provider.flavours(0), provider.library_count
5
+ rt = provider.runtime(channel=0) # a pacrunner.Runtime over all the channel's flavours
6
+ provider.subprocess, provider.run() # a provider in a MadGraph7 output: its SubProcess, generate_events
7
+
8
+ A provider (pyAmpliCol's `p0`, ...) is one UMAMI matrix-element interface for its channels and flavours;
9
+ pyAmpliCol's own build is the stock library, PacRunner's this folder. umami_libraries writes one library
10
+ per (process, colour flow, permutation) a provider uses, each for one flavour (always called
11
+ with flavour 0), and umami_pac.json: the libraries and, per UMAMI channel, the library of each of the
12
+ provider's flavours. A runtime is one MadSpace function that looks up each event's library, splits the
13
+ batch (batch_split_by_index), runs each library with flavour 0 and merges the outputs back
14
+ (batch_merge_by_index), as MadSpace's Integrand does; a channel of one library needs no split. So the
15
+ split runs where the context runs: on the GPU for cuda_provider libraries.
16
+
17
+ The device: libraries built for cpu, cuda and metal are CPU providers (a CPU context); cuda_provider
18
+ libraries need MadSpace's CUDA build and a CUDA context (made here). The libraries carry the export's
19
+ model parameters; `parameters` holds the artifact's external ones at those values."""
20
+
21
+ import json
22
+ import os
23
+ from pathlib import Path
24
+
25
+ from . import _env, _runtime
26
+
27
+
28
+ def exported_parameters(export_path, artifact=None):
29
+ """the model parameters of a recurrence export, {name: real part} (MadSpace's parameters are real):
30
+ with `artifact`, only its model's external parameters (model/parameters.json: the ones a library can
31
+ be given; the export also lists the derived ones)"""
32
+ with open(export_path) as f:
33
+ values = {p["name"]: float(p["value"]["re"]) for p in json.load(f)["parameters"]}
34
+ external = os.path.join(artifact, "model", "parameters.json") if artifact else None
35
+ if external is None or not os.path.isfile(external):
36
+ return values
37
+ with open(external) as f:
38
+ names = json.load(f)["parameters"]
39
+ return {name: values[name] for name in names if name in values}
40
+
41
+
42
+ def read_table(folder):
43
+ """umami_pac.json of an umami_libraries folder (or the file): (table, the folder)"""
44
+ path = Path(folder)
45
+ path = path if path.suffix == ".json" else path / "umami_pac.json"
46
+ if not path.is_file():
47
+ raise _env.PacRunnerError(f"{path}: no umami_pac.json (not an output of PacRunner's umami_libraries)")
48
+ with open(path) as f:
49
+ table = json.load(f)
50
+ if table.get("kind") != "pacrunner-umami-libraries":
51
+ raise _env.PacRunnerError(f"{path}: not the output of PacRunner's umami_libraries")
52
+ return table, path.parent.resolve()
53
+
54
+
55
+ def _with_channel(ME, inputs):
56
+ """the inputs with channel_in (the channel is the MatrixElement's, not a call argument)"""
57
+ inputs = list(inputs)
58
+ if ME.momenta_in not in inputs or ME.flavor_in not in inputs:
59
+ raise ValueError("the inputs need momenta_in and flavor_in")
60
+ return inputs if ME.channel_in in inputs else inputs + [ME.channel_in]
61
+
62
+
63
+ class Provider:
64
+ """One UMAMI provider: PacRunner's build (an umami_libraries folder: Provider(folder)) or
65
+ pyAmpliCol's own, the stock library (stock: Artifact.stock(), SubProcess.stock()).
66
+
67
+ stock True for pyAmpliCol's stock library (one library for every channel and flavour,
68
+ called with the flavour itself), False for PacRunner's build
69
+ folder the folder (the stock library's folder)
70
+ output the MadGraph7 output it lies in (OUTPUT/lib/pacrunner[-device]/<name>), else None
71
+ name the folder's name (in an output: the stock library's, lib/libamplicol_<name>.so)
72
+ table umami_pac.json, as read (the stock library's: one library, every flavour on it)
73
+ device what they were built for: "cpu", "cuda", "cuda_provider", "metal"
74
+ precision "f64" or "mixed"
75
+ particle_count the provider's particles
76
+ channels the UMAMI channels' count
77
+ library_count the libraries' count
78
+ artifact the pyAmpliCol artifact the provider belongs to
79
+ parameters the artifact's external model parameters at the exported values ({name: real part})"""
80
+
81
+ def __init__(self, folder):
82
+ self.table, self.folder = read_table(folder)
83
+ self.device = self.table["device"]
84
+ self.precision = self.table.get("precision", "f64")
85
+ self.particle_count = int(self.table["particle_count"])
86
+ self.channels = len(self.table["channels"])
87
+ self.library_count = len(self.table["libraries"])
88
+ # the metadata is <artifact>/API/umami/metadata.json
89
+ metadata = Path(self.table["metadata"])
90
+ self.artifact = metadata.parent.parent.parent
91
+ export = Path(self.table["export"])
92
+ self.parameters = exported_parameters(export, self.artifact) if export.is_file() else {}
93
+ self.output = _env.mg7_output_of(self.artifact)
94
+ self.name = self.folder.name
95
+ self.stock = False
96
+ self._load_with = "" # load_matrix_element's second argument (PacRunner's libraries read no card)
97
+ self._remap = None # a channel's flavour remap (None: every flavour to 0)
98
+ self._apis = {} # id(context) -> [MatrixElementApi]
99
+ self._subprocess = None
100
+
101
+ @classmethod
102
+ def _stock(cls, library, artifact, particle_count, flavours, parameters=None, name=None, subprocess=None, remap=None):
103
+ """pyAmpliCol's stock library as a Provider: one library, every channel's flavours on it, each
104
+ called with its own flavour (remap: per channel, MadGraph7's flavour -> the provider's)"""
105
+ self = cls.__new__(cls)
106
+ library = Path(library)
107
+ self.table = {"device": "cpu", "precision": "f64", "particle_count": particle_count,
108
+ "libraries": [{"path": library.name}],
109
+ "channels": [{"libraries": [0], "flavor_libraries": [0] * n} for n in flavours]}
110
+ self.folder = library.parent
111
+ self.device, self.precision, self.particle_count = "cpu", "f64", int(particle_count)
112
+ self.channels, self.library_count = len(flavours), 1
113
+ self.artifact = Path(artifact)
114
+ self.parameters = dict(parameters or {})
115
+ self.output = _env.mg7_output_of(self.folder)
116
+ self.name = name or library.stem
117
+ self.stock = True
118
+ self._load_with = os.fspath(self.artifact) # the stock library reads the artifact's model
119
+ self._remap = remap
120
+ self._apis = {}
121
+ self._subprocess = subprocess
122
+ return self
123
+
124
+ def __repr__(self):
125
+ if self.stock:
126
+ return f"<{type(self).__name__} stock {self.folder / self.table['libraries'][0]['path']} ({self.channels} channels)>"
127
+ return (f"<{type(self).__name__} {self.folder} ({self.device}, {self.precision}: {self.library_count} libraries, "
128
+ f"{self.channels} channels)>")
129
+
130
+ # ---- the layout
131
+
132
+ def _channel(self, channel):
133
+ if not 0 <= channel < self.channels:
134
+ raise IndexError(f"UMAMI channel {channel}: there are {self.channels}")
135
+ return self.table["channels"][channel]
136
+
137
+ def flavours(self, channel):
138
+ """the provider's flavours of `channel`"""
139
+ return len(self._channel(channel)["flavor_libraries"])
140
+
141
+ def library(self, channel, flavour):
142
+ """the index of the library of `flavour` in `channel`"""
143
+ return self._channel(channel)["flavor_libraries"][flavour]
144
+
145
+ def library_path(self, k):
146
+ return self.folder / self.table["libraries"][k]["path"]
147
+
148
+ def flavor_arguments(self, channel):
149
+ """an Integrand's flavour arguments for `channel`'s matrix_elements: flavor_remap (every flavour
150
+ to 0: each of PacRunner's libraries is one flavour; the stock library: the flavour itself) and
151
+ flavor_diff_xs_indices (flavour f's library's position)"""
152
+ ch = self._channel(channel)
153
+ libs = ch["libraries"]
154
+ n = len(ch["flavor_libraries"])
155
+ remap = [0] * n if not self.stock else (self._remap[channel] if self._remap is not None else list(range(n)))
156
+ return {"flavor_remap": remap,
157
+ "flavor_diff_xs_indices": [libs.index(k) for k in ch["flavor_libraries"]]}
158
+
159
+ # ---- MadSpace
160
+
161
+ @property
162
+ def context_device(self):
163
+ """the MadSpace device of these libraries' context: "cuda" for CUDA providers, else "cpu" """
164
+ return "cuda" if self.device == "cuda_provider" else "cpu"
165
+
166
+ def context(self, threads=None):
167
+ """the madspace.Context for these libraries (made once per process and thread count)"""
168
+ return _runtime.context(self.context_device, threads, _env.madgraph7_for(self.folder, required=False))
169
+
170
+ def apis(self, context, parameters=None, param_card=""):
171
+ """every library loaded into `context` (once per context): [MatrixElementApi]. PacRunner's
172
+ libraries do not read param_card, and a parameter given must be the exported value (or the
173
+ library refuses it); the stock library is loaded with its artifact and the provider's parameters"""
174
+ key = id(context)
175
+ if key not in self._apis:
176
+ (with_, values) = (self._load_with, self.parameters) if self.stock else (param_card, parameters)
177
+ self._apis[key] = [context.load_matrix_element(os.fspath(self.library_path(k)), with_, dict(values or {}))
178
+ for k in range(self.library_count)]
179
+ return self._apis[key]
180
+
181
+ def matrix_elements(self, channel, inputs=None, outputs=None, context=None, sample_random_inputs=False,
182
+ me_frame=(), incoming_count=2):
183
+ """one madspace.MatrixElement per library of `channel` (in the order of the channel's
184
+ "libraries", the order flavor_arguments' indices refer to), the channel fixed; flavour inputs
185
+ must be 0 (default inputs: momenta, flavour; outputs: the matrix element)"""
186
+ ms = _runtime.madspace()
187
+ ME = ms.MatrixElement
188
+ inputs = _with_channel(ME, inputs if inputs is not None else [ME.momenta_in, ME.flavor_in])
189
+ outputs = list(outputs if outputs is not None else [ME.matrix_element_out])
190
+ apis = self.apis(context if context is not None else self.context())
191
+ return [ME(apis[k].index(), self.particle_count, inputs, outputs, diagram_count=1,
192
+ sample_random_inputs=sample_random_inputs, me_frame=list(me_frame), incoming_count=incoming_count,
193
+ channel=channel)
194
+ for k in self._channel(channel)["libraries"]]
195
+
196
+ def function(self, channel, inputs, outputs, context=None, me_frame=(), incoming_count=2):
197
+ """`channel`'s matrix element over all its flavours as one madspace.Function: the arguments are
198
+ `inputs` but channel_in, the results `outputs`, events in order"""
199
+ ms = _runtime.madspace()
200
+ ME = ms.MatrixElement
201
+ mes = self.matrix_elements(channel, inputs, outputs, context, me_frame=me_frame, incoming_count=incoming_count)
202
+ first = mes[0].function()
203
+ fb = ms.FunctionBuilder(ms.NamedTypes([(f"input{i}", v.type) for i, v in enumerate(first.inputs)]),
204
+ ms.NamedTypes([(f"output{i}", v.type) for i, v in enumerate(first.outputs)]))
205
+ args = [fb.input(i) for i in range(len(first.inputs))]
206
+ flavour = [i for i in inputs if i != ME.channel_in].index(ME.flavor_in)
207
+ tables = self.flavor_arguments(channel)
208
+ if len(mes) == 1:
209
+ # one library: no split (its gathers and merges cost as much as a fast matrix element)
210
+ if not self.stock:
211
+ args[flavour] = fb.gather_int(args[flavour], ms.Value(tables["flavor_remap"])) # every flavour: 0
212
+ for j, value in enumerate(mes[0].build_function(fb, args).values()):
213
+ fb.output(j, value)
214
+ return fb.function()
215
+ # each event's library (its position among the channel's), the batch split by it
216
+ position = fb.gather_int(args[flavour], ms.Value(tables["flavor_diff_xs_indices"]))
217
+ parts = fb.batch_split_by_index(position, ms.Value(len(mes)))
218
+ merged = [[] for _ in first.outputs]
219
+ for me, indices in zip(mes, parts):
220
+ part = [fb.batch_gather(indices, a) for a in args]
221
+ part[flavour] = fb.gather_int(part[flavour], ms.Value(tables["flavor_remap"])) # every flavour: 0
222
+ for j, value in enumerate(me.build_function(fb, part).values()):
223
+ merged[j] += [value, indices]
224
+ for j, values in enumerate(merged):
225
+ fb.output(j, fb.batch_merge_by_index(values))
226
+ return fb.function()
227
+
228
+ def runtime(self, channel=0, threads=None):
229
+ """`channel`'s matrix element over all its flavours: a pacrunner.Runtime (threads: the CPU
230
+ context's, default all CPUs; a CUDA context's for cuda_provider libraries, default 1)"""
231
+ self._channel(channel)
232
+ context = self.context(threads)
233
+ return _runtime.Runtime(lambda inputs, outputs: self.function(channel, inputs, outputs, context),
234
+ context, self.particle_count, self.context_device == "cuda",
235
+ f"{'stock ' if self.stock else ''}{self.name} channel {channel}")
236
+
237
+
238
+ # ---- in a MadGraph7 output
239
+
240
+ @property
241
+ def subprocess(self):
242
+ """the SubProcess it was compiled for (in a MadGraph7 output), else None"""
243
+ if self.output is None:
244
+ return None
245
+ if self._subprocess is None:
246
+ from ._mad import Output
247
+ self._subprocess = Output(self.output).subprocess(self.name)
248
+ return self._subprocess
249
+
250
+ def run(self, args=None, in_process=False, log=None):
251
+ """an end-to-end MadGraph7 run (generate_events: the survey, the events, the cross section) with
252
+ this subprocess on these libraries and the output's other subprocesses on their stock ones.
253
+ In a process of its own by default, the output's python (in_process=True: in this one, once per
254
+ process); `args` generate_events' arguments (default -f); `log` a file for its output (default:
255
+ this process's). The cards are the output's (Cards/run_card.toml: cuda_provider libraries need
256
+ run.device = ["cuda"]). Returns a RunResult (cross_section, error, events, run_dir, output,
257
+ wall_seconds). A provider in a MadGraph7 output only; the stock provider's run is the output's
258
+ own (bin/generate_events, every subprocess stock)."""
259
+ from . import _mgrun
260
+ if self.output is None:
261
+ raise _env.PacRunnerError(f"{self.folder}: its artifact {self.artifact} is not in a MadGraph7 output: "
262
+ "run() needs one (SubProcess.compile builds a provider there)")
263
+ return _mgrun.run_libraries(self.output, [self], args=args, in_process=in_process, log=log)
264
+
265
+ def integrand_inputs(self, channel, inputs=None, outputs=None, context=None, me_frame=(), incoming_count=2):
266
+ """the pieces of a madspace.Integrand of your own for `channel`: (matrix_elements, flavour
267
+ arguments), matrix_elements one madspace.MatrixElement per library (sampling its random inputs,
268
+ as the Integrand needs), the arguments {flavor_remap, flavor_diff_xs_indices} to pass with them"""
269
+ return (self.matrix_elements(channel, inputs, outputs, context, sample_random_inputs=True, me_frame=me_frame,
270
+ incoming_count=incoming_count),
271
+ self.flavor_arguments(channel))
272
+
273
+
274
+ class _ContextLibraries:
275
+ """load_libraries' result (the earlier utils/libraries.py API, for code written against it): a
276
+ Provider loaded into the caller's context; runtime() a madspace.FunctionRuntime"""
277
+
278
+ def __init__(self, context, folder, parameters=None, param_card=""):
279
+ self.library = Provider(folder)
280
+ for name in ("table", "device", "particle_count", "channels", "artifact", "parameters"):
281
+ setattr(self, name, getattr(self.library, name))
282
+ self.context = context
283
+ self.apis = self.library.apis(context, parameters, param_card)
284
+
285
+ def flavours(self, channel):
286
+ return self.library.flavours(channel)
287
+
288
+ def library_index(self, channel, flavour):
289
+ return self.library.library(channel, flavour)
290
+
291
+ def flavor_arguments(self, channel):
292
+ return self.library.flavor_arguments(channel)
293
+
294
+ def matrix_elements(self, channel, inputs=None, outputs=None, sample_random_inputs=False, me_frame=(),
295
+ incoming_count=2):
296
+ return self.library.matrix_elements(channel, inputs, outputs, self.context, sample_random_inputs, me_frame,
297
+ incoming_count)
298
+
299
+ def function(self, channel=0, inputs=None, outputs=None, me_frame=(), incoming_count=2):
300
+ ME = _runtime.madspace().MatrixElement
301
+ inputs = list(inputs if inputs is not None else [ME.momenta_in, ME.flavor_in])
302
+ outputs = list(outputs if outputs is not None else [ME.matrix_element_out])
303
+ return self.library.function(channel, inputs, outputs, self.context, me_frame, incoming_count)
304
+
305
+ def runtime(self, channel=0, inputs=None, outputs=None, me_frame=(), incoming_count=2):
306
+ ms = _runtime.madspace()
307
+ return ms.FunctionRuntime(self.function(channel, inputs, outputs, me_frame, incoming_count), self.context)
308
+
309
+
310
+ def load_libraries(context, out, parameters=None, param_card=""):
311
+ """the libraries of umami_libraries' output `out` loaded into `context` (a madspace.Context you
312
+ made): the earlier utils/libraries.py API (runtime() a madspace.FunctionRuntime). New code:
313
+ Provider(out).runtime(channel) (a pacrunner.Runtime, the context made for the libraries' device)."""
314
+ return _ContextLibraries(context, out, parameters, param_card)
pacrunner/_literal.py ADDED
@@ -0,0 +1,52 @@
1
+ """Doubles spelled as Julia's `repr` spells them, so that the C pacrunner writes is pac-julia's byte for
2
+ byte: the shortest digits that read back exactly (Python's repr has the same digits), in fixed
3
+ notation when the decimal point falls within −4 < point ≤ 6 of the first digit and in Julia's
4
+ scientific notation otherwise (1.0e-5, 1.0e6, 1.234567e6, 5.0e-324; Python: 1e-05, 1000000.0).
5
+ Checked against Julia 1.13 on 40,388 values (random bit patterns, rounded decimals, powers of ten).
6
+ Floats (julia_repr_f32) likewise: the shortest digits of the float32, the same layout, with "f" for
7
+ "e" and "f0" after a fixed notation (0.5f0, 1.0f-5, 1.0f6); checked on 24,355 values
8
+ (test/data/julia_repr_f32.txt)."""
9
+
10
+ import numpy as np
11
+
12
+
13
+ def julia_repr(x: float) -> str:
14
+ """a finite double as Julia's repr writes it"""
15
+ if x != x or x in (float("inf"), float("-inf")):
16
+ raise ValueError(f"julia_repr: {x} is not finite")
17
+ return _layout(repr(x), "e", "")
18
+
19
+
20
+ def julia_repr_f32(x) -> str:
21
+ """a finite float32 (a numpy float32, or a value rounded to one) as Julia's repr writes it"""
22
+ x = np.float32(x)
23
+ if not np.isfinite(x):
24
+ raise ValueError(f"julia_repr_f32: {x} is not finite")
25
+ # numpy's shortest digits of the float32 ("0.5", "1e-05", "-0.0")
26
+ return _layout(np.format_float_positional(x, unique=True, trim="0") if 1e-4 <= abs(x) < 1e16 or x == 0
27
+ else np.format_float_scientific(x, unique=True, trim="0"), "f", "f0")
28
+
29
+
30
+ def _layout(text: str, e: str, fixed_suffix: str) -> str:
31
+ """Julia's layout of the shortest digits in `text` (Python's or numpy's spelling of them): fixed
32
+ notation for −4 < point ≤ 6 (then `fixed_suffix`), else d.ddd + e + the exponent"""
33
+ sign = "-" if text.startswith("-") else ""
34
+ mantissa, _, exponent = text.lstrip("-").partition("e")
35
+ whole, _, fraction = mantissa.partition(".")
36
+ padded = whole + fraction
37
+ digits = padded.lstrip("0")
38
+ if not digits:
39
+ return sign + "0.0" + fixed_suffix
40
+ point = len(whole) + (int(exponent) if exponent else 0) - (len(padded) - len(digits))
41
+ digits = digits.rstrip("0")
42
+ if -4 < point <= 6:
43
+ if point <= 0:
44
+ s = "0." + "0" * -point + digits
45
+ elif point >= len(digits):
46
+ s = digits + "0" * (point - len(digits)) + ".0"
47
+ else:
48
+ s = digits[:point] + "." + digits[point:]
49
+ s += fixed_suffix
50
+ else:
51
+ s = digits[0] + "." + (digits[1:] or "0") + e + str(point - 1)
52
+ return sign + s
pacrunner/_mad.py ADDED
@@ -0,0 +1,276 @@
1
+ """Output and SubProcess: a MadGraph7 output (`generate ... [amplicol]`, `output mg7 OUTPUT`) and its
2
+ pyAmpliCol subprocesses.
3
+
4
+ out = Output("OUTPUT")
5
+ out.names # ["A1_pp_zj", "A2_pp_zjj"]: the subprocesses (SubProcesses/<name>)
6
+ s = out.subprocess("A1_pp_zj") # or SubProcess("OUTPUT") when it has one
7
+ s.processes, s.channels, s.flavours(0), s.parameters, s.artifact # an Artifact
8
+ stock = s.runtime(channel=0) # lib/libamplicol_<name>_<provider>.so at the param card's parameters
9
+ provider = s.compile(device="cpu") # -> Provider in OUTPUT/lib/pacrunner[-device[-precision]]/<name>_<provider>
10
+ provider.run() # generate_events on it (the other subprocesses stock)
11
+ out.run(device="cpu") # every subprocess compiled (when needed) and run on PacRunner
12
+
13
+ Nomenclature: an output holds one or more processes (`generate`, `add process`), MadGraph splits them
14
+ into subprocesses (SubProcesses/<name>, one pyAmpliCol artifact each); an artifact's provider (`p0`, ...)
15
+ is one UMAMI matrix-element library (the stock lib/libamplicol_<name>_<provider>.so), with one
16
+ subprocesses.json entry per UMAMI channel; a Provider is PacRunner's build of it."""
17
+
18
+ import json
19
+ import re
20
+ from pathlib import Path
21
+
22
+ from . import _env
23
+ from ._artifacts import Artifact
24
+
25
+
26
+ def read_param_card(path):
27
+ """{(block, (code, ...)): value} of an SLHA param card: BLOCK sections and DECAY lines, block
28
+ names lower case (as MadGraph7's ParamCard; a "width" block is "decay")"""
29
+ values, block = {}, None
30
+ with open(path) as f:
31
+ for line in f:
32
+ line = line.split("#", 1)[0].strip()
33
+ if not line:
34
+ continue
35
+ fields = line.split()
36
+ head = fields[0].lower()
37
+ if head == "block":
38
+ block = fields[1].lower() if len(fields) > 1 else None
39
+ block = "decay" if block == "width" else block
40
+ continue
41
+ if head == "decay":
42
+ block = None
43
+ if len(fields) >= 3:
44
+ values[("decay", (int(fields[1]),))] = float(fields[2])
45
+ continue
46
+ if block is None:
47
+ continue
48
+ try:
49
+ codes, value = tuple(int(x) for x in fields[:-1]), float(fields[-1].replace("d", "e").replace("D", "e"))
50
+ except ValueError:
51
+ continue
52
+ values[(block, codes)] = value
53
+ return values
54
+
55
+
56
+ def card_parameters(param_card, references):
57
+ """{name: value} of the param card for a subprocess's parameter references ({name: [block, code]}),
58
+ as MadGraph7's amplicol_parameters gives them to the libraries (missing ones left out)"""
59
+ card = read_param_card(param_card)
60
+ out = {}
61
+ for name, (block, code) in references.items():
62
+ value = card.get((block.lower(), tuple(code)))
63
+ if value is not None:
64
+ out[name] = value
65
+ return out
66
+
67
+
68
+ def library_folder_name(device="cpu", precision="f64"):
69
+ """lib/<this>/<name>: pacrunner (cpu, f64), pacrunner-<device>[-<precision>] (cuda_full: cuda_provider's;
70
+ gpu: this system's GPU; metal: always -mixed)"""
71
+ device, precision = _env.compile_target(device, precision)
72
+ if device == "cpu" and precision == "f64":
73
+ return "pacrunner"
74
+ return f"pacrunner-{device}" + ("" if precision == "f64" else f"-{precision}")
75
+
76
+
77
+ class Output:
78
+ """A MadGraph7 output with pyAmpliCol subprocesses.
79
+
80
+ path the output folder
81
+ madgraph7 the MadGraph7 checkout it was made with
82
+ run_card, param_card its cards (Cards/run_card.toml, Cards/param_card.dat)
83
+ names its pyAmpliCol subprocesses (SubProcesses/<name>), one SubProcess each"""
84
+
85
+ def __init__(self, path):
86
+ path = Path(path).expanduser().resolve()
87
+ output = _env.mg7_output_of(path)
88
+ if output is None or not (output / "SubProcesses" / "subprocesses.json").is_file():
89
+ raise _env.PacRunnerError(f"{path}: not a MadGraph7 output (no bin/generate_events and "
90
+ "SubProcesses/subprocesses.json): `output mg7 OUTPUT` in MadGraph7 makes one")
91
+ self.path = output
92
+ self.madgraph7 = _env.madgraph7_of_output(output)
93
+ self.run_card = output / "Cards" / "run_card.toml"
94
+ self.param_card = output / "Cards" / "param_card.dat"
95
+ with open(output / "SubProcesses" / "subprocesses.json") as f:
96
+ entries = json.load(f)
97
+ entries = entries.get("subprocesses", entries) if isinstance(entries, dict) else entries
98
+ # subprocess folder -> stock library name (<name>_<provider>) -> its entries (one per UMAMI channel)
99
+ self.entries = {}
100
+ for e in entries:
101
+ if e.get("backend") == "amplicol":
102
+ self.entries.setdefault(Path(e["path"]).name, {}).setdefault(self._library_name(e["me_path"]), []).append(e)
103
+ if not self.entries:
104
+ raise _env.PacRunnerError(f"{output}: no pyAmpliCol subprocess (generate with [amplicol])")
105
+ self.names = sorted(self.entries)
106
+ self._subprocesses = {}
107
+
108
+ @staticmethod
109
+ def _library_name(me_path):
110
+ m = re.fullmatch(r"libamplicol_(.*)\.(so|dylib)", Path(me_path).name)
111
+ if m is None:
112
+ raise _env.PacRunnerError(f"{me_path}: not a pyAmpliCol stock library name (libamplicol_<name>.so)")
113
+ return m.group(1)
114
+
115
+ def __repr__(self):
116
+ return f"<Output {self.path} ({', '.join(self.names)})>"
117
+
118
+ def _resolve(self, name):
119
+ """(subprocess, stock library name or None) for a subprocess name or a stock library name"""
120
+ if name is None:
121
+ if len(self.names) != 1:
122
+ raise _env.PacRunnerError(f"{self.path}: {len(self.names)} pyAmpliCol subprocesses {self.names}: pick "
123
+ "one by name")
124
+ return self.names[0], None
125
+ if name in self.entries:
126
+ return name, None
127
+ for sub, libs in self.entries.items():
128
+ if name in libs:
129
+ return sub, name
130
+ raise _env.PacRunnerError(f"{self.path}: no pyAmpliCol subprocess {name!r} (there are {self.names})")
131
+
132
+ def subprocess(self, name=None, provider=None):
133
+ """the SubProcess `name` (SubProcesses/<name>; default: the only one), its provider `provider`
134
+ (default: the only one); a stock library's name (<name>_<provider>) names both"""
135
+ key = (name, provider)
136
+ if key not in self._subprocesses:
137
+ self._subprocesses[key] = SubProcess(self, name, provider)
138
+ return self._subprocesses[key]
139
+
140
+ def subprocesses(self):
141
+ """every subprocess, with every provider: [SubProcess]"""
142
+ return [self.subprocess(lib) for n in self.names for lib in sorted(self.entries[n])]
143
+
144
+ def compile(self, device="cpu", precision="f64", interpreter=False, force=False):
145
+ """every subprocess's Provider (SubProcess.compile): [Provider]"""
146
+ return [s.compile(device, precision, interpreter=interpreter, force=force) for s in self.subprocesses()]
147
+
148
+ def run(self, providers=None, device="cpu", precision="f64", args=None, in_process=False, log=None):
149
+ """generate_events on PacRunner's providers: `providers` (of this output; default: every
150
+ subprocess's, compiled for `device` and `precision` when needed); see Provider.run"""
151
+ from . import _mgrun
152
+ if providers is None:
153
+ providers = self.compile(device, precision)
154
+ for p in providers:
155
+ if p.output != self.path:
156
+ raise _env.PacRunnerError(f"{p.folder}: a provider of {p.output}, not of {self.path}")
157
+ return _mgrun.run_libraries(self.path, providers, args=args, in_process=in_process, log=log)
158
+
159
+
160
+ class SubProcess:
161
+ """One pyAmpliCol subprocess of a MadGraph7 output (SubProcesses/<name>), with one of its artifact's
162
+ providers.
163
+
164
+ output its Output; name: the SubProcesses folder's name
165
+ provider the provider's id (p0, ...); providers: all of them
166
+ library_name the stock library's name: lib/libamplicol_<library_name>.so (<name>_<provider>)
167
+ entries its subprocesses.json entries (one per UMAMI channel)
168
+ artifact its Artifact (SubProcesses/<name>/lc, with the provider)
169
+ processes, particle_count, masses, channels, flavours(channel): the artifact's
170
+ parameters the param card's values of the model parameters (what MadGraph7 sets)"""
171
+
172
+ def __init__(self, output, name=None, provider=None):
173
+ if not isinstance(output, Output):
174
+ output = Output(output)
175
+ (name, library_name) = output._resolve(name)
176
+ libs = output.entries[name]
177
+ if library_name is None:
178
+ if provider is not None:
179
+ library_name = next((l for l in libs if l.endswith("_" + str(provider))), None)
180
+ if library_name is None:
181
+ raise _env.PacRunnerError(f"{name}: no provider {provider!r} (stock libraries {sorted(libs)})")
182
+ elif len(libs) == 1:
183
+ library_name = next(iter(libs))
184
+ else:
185
+ raise _env.PacRunnerError(f"{name}: {len(libs)} providers ({sorted(libs)}): pick one, provider=...")
186
+ self.output, self.name, self.library_name = output, name, library_name
187
+ self.entries = sorted(libs[library_name], key=lambda e: e["umami_channel"])
188
+ artifacts = {e["artifact"] for e in self.entries}
189
+ if len(artifacts) != 1:
190
+ raise _env.PacRunnerError(f"{library_name}: entries of several artifacts {sorted(artifacts)}")
191
+ lc = output.path / artifacts.pop()
192
+ # the stock library <name>_<provider>: the artifact's provider of that id
193
+ ids = list(Artifact.provider_metadata(lc))
194
+ self.providers = ids
195
+ match = ids if len(ids) == 1 else [p for p in ids if library_name.endswith("_" + p)]
196
+ if len(match) != 1:
197
+ raise _env.PacRunnerError(f"{lc}: no single UMAMI provider for {library_name} among {ids}")
198
+ self.provider = match[0]
199
+ self.artifact = Artifact(lc, provider=self.provider)
200
+ self.stock_library_path = output.path / self.entries[0]["me_path"]
201
+ if [e["umami_channel"] for e in self.entries] != list(range(self.artifact.channels)):
202
+ raise _env.PacRunnerError(f"{library_name}: subprocesses.json has UMAMI channels "
203
+ f"{[e['umami_channel'] for e in self.entries]}, the artifact {self.artifact.channels}")
204
+
205
+ def __repr__(self):
206
+ return (f"<SubProcess {self.name} of {self.output.path} (provider {self.provider}, "
207
+ f"{self.artifact.channels} channels)>")
208
+
209
+ @property
210
+ def processes(self):
211
+ return self.artifact.processes
212
+
213
+ @property
214
+ def particle_count(self):
215
+ return self.artifact.particle_count
216
+
217
+ @property
218
+ def masses(self):
219
+ return self.artifact.masses
220
+
221
+ @property
222
+ def channels(self):
223
+ return self.artifact.channels
224
+
225
+ def flavours(self, channel):
226
+ return self.artifact.flavours(channel)
227
+
228
+ @property
229
+ def parameters(self):
230
+ """the param card's values of the subprocess's model parameters (read each time: the card may change)"""
231
+ return card_parameters(self.output.param_card, self.entries[0]["parameters"])
232
+
233
+ def stock(self):
234
+ """the stock provider (lib/libamplicol_<library_name>.so, which MadGraph7 builds at the output's
235
+ first run) as a Provider (stock=True), at the param card's parameters, called with MadGraph7's
236
+ flavours (each channel's entry's flavour indices)"""
237
+ from ._libraries import Provider
238
+ if not self.stock_library_path.is_file():
239
+ raise _env.PacRunnerError(f"{self.stock_library_path}: not built yet; MadGraph7 builds it at the output's "
240
+ "first run (bin/generate_events -f in the output)")
241
+ params = self.parameters
242
+ key = json.dumps(params, sort_keys=True)
243
+ if getattr(self, "_stock_key", None) != key:
244
+ remap = [[f["index"] for f in e["flavors"]] for e in self.entries]
245
+ self._stock_provider = Provider._stock(self.stock_library_path, self.artifact.path, self.particle_count,
246
+ [len(r) for r in remap], params, name=self.library_name,
247
+ subprocess=self, remap=remap)
248
+ self._stock_key = key
249
+ return self._stock_provider
250
+
251
+ def runtime(self, channel=0, threads=None):
252
+ """the stock provider's `channel` as a pacrunner.Runtime (on the CPU): stock().runtime"""
253
+ if not 0 <= channel < self.channels:
254
+ raise IndexError(f"UMAMI channel {channel}: there are {self.channels}")
255
+ return self.stock().runtime(channel, threads)
256
+
257
+ def provider_folder(self, device="cpu", precision="f64"):
258
+ """where compile() puts the Provider: OUTPUT/lib/pacrunner[-device[-precision]]/<library_name>"""
259
+ return self.output.path / "lib" / library_folder_name(device, precision) / self.library_name
260
+
261
+ def compile(self, device="cpu", precision="f64", interpreter=False, force=False):
262
+ """PacRunner's build of the provider, exported at the param card's parameters (the values
263
+ MadGraph7 sets: a library refuses others), in provider_folder(); returns the Provider. Skipped
264
+ when built already for the same card (the stamp)."""
265
+ from ._libraries import Provider
266
+ self.artifact.compile(self.provider_folder(device, precision), device, precision, parameters=self.parameters,
267
+ interpreter=interpreter, force=force)
268
+ return Provider(self.provider_folder(device, precision))
269
+
270
+ def compiled(self, device="cpu", precision="f64"):
271
+ """the Provider compiled already (no build)"""
272
+ from ._libraries import Provider
273
+ folder = self.provider_folder(device, precision)
274
+ if not (folder / "umami_pac.json").is_file():
275
+ raise _env.PacRunnerError(f"{folder}: not compiled (SubProcess.compile)")
276
+ return Provider(folder)