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
pacrunner/__init__.py ADDED
@@ -0,0 +1,55 @@
1
+ """pacrunner: PacRunner (formerly pac-julia) in Python.
2
+
3
+ pyAmpliCol's leading-colour recurrence programs, compiled by PacRunner into UMAMI libraries (CPU, CUDA)
4
+ for MadGraph7 and MadSpace. Two layers:
5
+
6
+ - the high-level API: Artifact (a pyAmpliCol artifact), Output and SubProcess (a MadGraph7 output and
7
+ its pyAmpliCol subprocesses), Provider (an artifact's UMAMI provider: pyAmpliCol's stock library,
8
+ Artifact/SubProcess.stock(), or PacRunner's build, .compile(); in an output, Provider.run:
9
+ generate_events on it) and Runtime, the one callable for any UMAMI matrix element (one channel of
10
+ a provider);
11
+ - the modules beneath it: pacrunner.uir (the recurrence export read into UIR v0.8 programs, the
12
+ passes, the encoding), pacrunner.kernels (the symjit kernels' MIR and C), pacrunner.codegen (a
13
+ program as C) and pacrunner.umami (the UMAMI libraries; also `python -m pacrunner.umami`).
14
+
15
+ Setup: this repository cloned and installed with `python -m pip install -e .` (or not editable),
16
+ symjit >= 2.29 (a pip requirement, or from conda-forge: the kernels' MIR), a C compiler (nvcc for the
17
+ GPU), a MadGraph7 checkout with MadSpace for running libraries:
18
+
19
+ import pacrunner
20
+ pacrunner.configure(madgraph7="~/MadGraph7") # or PACRUNNER_MADGRAPH7
21
+ provider = pacrunner.Output("OUTPUT").subprocess("A1_pp_jjj").compile(device="cpu")
22
+ out = provider.runtime(channel=0)(momenta, flavours, random_helicity=r)
23
+ out.matrix_element, out.color_index, out.helicity_index
24
+
25
+ Nomenclature: an Output holds processes (`generate`, `add process`), split by MadGraph into
26
+ subprocesses (SubProcesses/<name>), one pyAmpliCol artifact each; an artifact's provider (p0, ...) is
27
+ one UMAMI matrix-element library with its channels (each a group of flavours); a Provider is
28
+ pyAmpliCol's (stock) or PacRunner's build of it, the latter one library per (process, colour flow,
29
+ permutation) it uses.
30
+ """
31
+
32
+ from ._env import CONFIG, Config, PacRunnerError, configure, repository
33
+
34
+ __version__ = "0.5.1"
35
+
36
+ # imported on first use: `python -m pacrunner._madgraph` runs in MadGraph7's python, which may have
37
+ # no numpy (nor symjit: only building libraries needs it)
38
+ _LAZY = {"Output": "._mad", "SubProcess": "._mad", "Artifact": "._artifacts", "Provider": "._libraries",
39
+ "Runtime": "._runtime", "RuntimeResult": "._runtime", "RunResult": "._mgrun", "load_libraries": "._libraries",
40
+ "uir": None, "kernels": None, "codegen": None, "umami": None}
41
+
42
+
43
+ def __getattr__(name):
44
+ if name in _LAZY:
45
+ import importlib
46
+ module = importlib.import_module(_LAZY[name] or f".{name}", __name__)
47
+ value = module if _LAZY[name] is None else getattr(module, name)
48
+ globals()[name] = value
49
+ return value
50
+ raise AttributeError(f"module 'pacrunner' has no attribute {name!r}")
51
+
52
+
53
+ __all__ = ["CONFIG", "Config", "PacRunnerError", "configure", "repository", "uir", "kernels", "codegen", "umami",
54
+ "Output", "SubProcess", "Artifact", "Provider", "Runtime", "RuntimeResult", "RunResult", "load_libraries",
55
+ "__version__"]
@@ -0,0 +1,259 @@
1
+ """Artifact: a pyAmpliCol artifact folder (`pyamplicol generate`, or the one MadGraph7's [amplicol]
2
+ writes in an mg7 output).
3
+
4
+ a = Artifact("artifacts/zgg")
5
+ a.id, a.producer_version, a.processes, a.particle_count, a.masses, a.channels, a.flavours(0), a.parameters
6
+ process, momenta = a.validation_points()[0]
7
+ stock = a.runtime(channel=0) # the stock UMAMI library (built once)
8
+ provider = a.compile(device="cpu") # export + umami_libraries -> Provider
9
+ stock(momenta[None], 0).matrix_element, provider.runtime(0)(momenta[None], 0).matrix_element
10
+
11
+ The export and the stock library's build use the pyAmpliCol installation that produced the artifact
12
+ (pacrunner._pyamplicol: found by its revision, or configure(pyamplicol=...)). An artifact may hold
13
+ several UMAMI providers (API/umami/metadata.json an index): pick one with `provider=`."""
14
+
15
+ import hashlib
16
+ import json
17
+ import os
18
+ import subprocess
19
+ from pathlib import Path
20
+
21
+ import numpy as np
22
+
23
+ from . import _env, _pyamplicol
24
+
25
+ STAMP = "pacrunner-build.json"
26
+
27
+
28
+ def _read(path):
29
+ with open(path) as f:
30
+ return json.load(f)
31
+
32
+
33
+ def _git_revision(folder):
34
+ """this repository's revision, '+' when its Python or C sources (pacrunner/) differ from it (None
35
+ without git)"""
36
+ try:
37
+ head = subprocess.run(["git", "-C", os.fspath(folder), "rev-parse", "HEAD"], capture_output=True, text=True,
38
+ check=True).stdout.strip()
39
+ dirty = subprocess.run(["git", "-C", os.fspath(folder), "status", "--porcelain", "--", "pacrunner"],
40
+ capture_output=True, text=True, check=True).stdout.strip()
41
+ return head + ("+" if dirty else "")
42
+ except (OSError, subprocess.CalledProcessError):
43
+ return None
44
+
45
+
46
+ def _sources_digest():
47
+ """pacrunner's version and a hash of its Python and C sources (an installed copy, or a clone without git)"""
48
+ from . import __version__
49
+ h = hashlib.sha256()
50
+ for f in sorted(p for p in _env.PACKAGE.rglob("*") if p.is_file() and "__pycache__" not in p.parts):
51
+ h.update(f.relative_to(_env.PACKAGE).as_posix().encode() + b"\0" + f.read_bytes() + b"\0")
52
+ return f"{__version__}:{h.hexdigest()[:16]}"
53
+
54
+
55
+ def source_revision():
56
+ """what pacrunner's builds are stamped with: the clone's git revision ('+' when dirty: builds are not
57
+ reused), else the version and a hash of the sources"""
58
+ folder = _env.repository()
59
+ return (_git_revision(folder) if folder is not None else None) or _sources_digest()
60
+
61
+
62
+ class Artifact:
63
+ """A pyAmpliCol artifact, one of its UMAMI providers.
64
+
65
+ path the artifact folder
66
+ id its artifact id
67
+ producer artifact.json's producer (version, git_revision, ...)
68
+ processes [{"id", "expression", ...}]
69
+ providers the UMAMI providers' ids; provider: the one used here
70
+ metadata the provider's UMAMI metadata (API/umami/...)
71
+ particle_count, masses, pdg_ids, color_accuracy, helicity_count, incoming_count, supports_alpha_s
72
+ channels the provider's UMAMI channels' count; flavours(channel): a channel's flavours
73
+ parameters the model's external parameters at their defaults ({name: real part})"""
74
+
75
+ def __init__(self, path, provider=None):
76
+ self.path = Path(path).expanduser().resolve()
77
+ manifest = self.path / "artifact.json"
78
+ if not manifest.is_file():
79
+ raise _env.PacRunnerError(f"{self.path}: not a pyAmpliCol artifact (no artifact.json)")
80
+ self.manifest = _read(manifest)
81
+ self.id = self.manifest["artifact_id"]
82
+ self.producer = self.manifest.get("producer", {})
83
+ self.processes = self.manifest.get("processes", [])
84
+ entries = self.provider_metadata(self.path)
85
+ self.providers = list(entries)
86
+ if provider is None:
87
+ if len(entries) != 1:
88
+ raise _env.PacRunnerError(f"{self.path}: {len(entries)} UMAMI providers {self.providers}: pick one, "
89
+ "Artifact(path, provider=...)")
90
+ provider = self.providers[0]
91
+ if str(provider) not in entries:
92
+ raise _env.PacRunnerError(f"{self.path}: no UMAMI provider {provider!r} (there are {self.providers})")
93
+ self.provider = str(provider)
94
+ self.metadata_path = entries[self.provider]
95
+ self.metadata = _read(self.metadata_path)
96
+ p = self.metadata["provider"]
97
+ self.particle_count = int(p["particle_count"])
98
+ self.masses = [float(m) for m in p["masses"]]
99
+ self.color_accuracy = p.get("color_accuracy")
100
+ self.helicity_count = p.get("helicity_count")
101
+ self.incoming_count = p.get("incoming_count", 2)
102
+ self.supports_alpha_s = bool(p.get("supports_alpha_s", False))
103
+ self.pdg_ids = self.metadata.get("pdg_ids")
104
+ self.channels = len(self.metadata["channels"])
105
+ params = self.path / "model" / "parameters.json"
106
+ self.parameters = {k: float(v[0] if isinstance(v, list) else v) for k, v in _read(params)["parameters"].items()} \
107
+ if params.is_file() else {}
108
+ self._stock_apis = {}
109
+ self._stock_providers = {} # parameters (JSON) -> the stock Provider
110
+
111
+ @staticmethod
112
+ def provider_metadata(path):
113
+ """{provider id: its UMAMI metadata path} of the artifact at `path`"""
114
+ umami = Path(path) / "API" / "umami"
115
+ if not (umami / "metadata.json").is_file():
116
+ raise _env.PacRunnerError(f"{path}: no UMAMI bundle (API/umami/metadata.json): generate with the API "
117
+ "bundle (pyamplicol generate --emit-api-bundle)")
118
+ index = _read(umami / "metadata.json")
119
+ if index.get("kind") == "pyamplicol-umami-provider-index":
120
+ return {str(p.get("id", p.get("provider"))): umami / p["metadata"] for p in index["providers"]}
121
+ return {str(index["provider"].get("id")): umami / "metadata.json"}
122
+
123
+ def __repr__(self):
124
+ names = ", ".join(p.get("expression") or p["id"] for p in self.processes[:3])
125
+ return f"<Artifact {self.path} ({names}; provider {self.provider}, {self.color_accuracy}, {self.channels} channels)>"
126
+
127
+ @property
128
+ def producer_version(self):
129
+ return self.producer.get("version")
130
+
131
+ @property
132
+ def producer_revision(self):
133
+ return self.producer.get("git_revision")
134
+
135
+ def flavours(self, channel):
136
+ """the provider's flavours of `channel`"""
137
+ if not 0 <= channel < self.channels:
138
+ raise IndexError(f"UMAMI channel {channel}: there are {self.channels}")
139
+ return len(self.metadata["channels"][channel]["processes"])
140
+
141
+ def validation_points(self):
142
+ """the saved phase-space points (API/validation_points.dat): [(process id, momenta[particle, 4])]"""
143
+ path = self.path / "API" / "validation_points.dat"
144
+ points = []
145
+ with open(path) as f:
146
+ if f.readline().strip() != "RUSTICOL_VALIDATION_POINTS_V1":
147
+ raise _env.PacRunnerError(f"{path}: not a RUSTICOL_VALIDATION_POINTS_V1 file")
148
+ for line in f:
149
+ fields = line.split()
150
+ if fields:
151
+ n = int(fields[1])
152
+ points.append((fields[0], np.array([float(x) for x in fields[2:2 + 4 * n]]).reshape(n, 4)))
153
+ return points
154
+
155
+ # ---- pyAmpliCol
156
+
157
+ def pyamplicol(self, strict=True):
158
+ """the pyAmpliCol installation that produced the artifact (pacrunner._pyamplicol)"""
159
+ return _pyamplicol.producer_of(self.path / "artifact.json", near=self.path, strict=strict)
160
+
161
+ # ---- the stock library
162
+
163
+ @property
164
+ def stock_library_path(self):
165
+ """the stock UMAMI library of the provider (the bundle's Makefile puts it in the sibling
166
+ .pyamplicol-api-build/<artifact>/umami)"""
167
+ build = self.path.parent / ".pyamplicol-api-build" / self.path.name / "umami"
168
+ name = "libumami.so" if len(self.providers) == 1 else f"libumami_{self.provider}.so"
169
+ for suffix in (".so", ".dylib"):
170
+ candidate = build / (Path(name).stem + suffix)
171
+ if candidate.is_file():
172
+ return candidate
173
+ return build / name
174
+
175
+ def build_stock_library(self, force=False):
176
+ """the stock library built (`make` in API/umami, the producer's rusticol-config); returns its path"""
177
+ lib = self.stock_library_path
178
+ if lib.is_file() and not force:
179
+ return lib
180
+ producer = self.pyamplicol()
181
+ env = producer.env()
182
+ env["RUSTICOL_CONFIG"] = producer.rusticol_config
183
+ r = subprocess.run(["make", "-s", "-C", os.fspath(self.path / "API" / "umami")], env=env, capture_output=True,
184
+ text=True)
185
+ if r.returncode != 0:
186
+ raise _env.PacRunnerError(f"{self.path}: building the stock UMAMI library failed:\n{(r.stderr or r.stdout)[-3000:]}")
187
+ lib = self.stock_library_path
188
+ if not lib.is_file():
189
+ raise _env.PacRunnerError(f"{self.path}: make built no {lib}")
190
+ return lib
191
+
192
+ def stock(self, parameters=None):
193
+ """the stock provider (pyAmpliCol's library, built once) as a Provider (stock=True), the model at
194
+ `parameters` over the artifact's defaults"""
195
+ from ._libraries import Provider
196
+ key = json.dumps(parameters or {}, sort_keys=True)
197
+ if key not in self._stock_providers:
198
+ lib = self.build_stock_library()
199
+ self._stock_providers[key] = Provider._stock(lib, self.path, self.particle_count,
200
+ [self.flavours(c) for c in range(self.channels)],
201
+ parameters, name=f"{self.path.name}_{self.provider}")
202
+ return self._stock_providers[key]
203
+
204
+ def runtime(self, channel=0, threads=None, parameters=None):
205
+ """the stock provider's `channel` as a pacrunner.Runtime (on the CPU): stock(parameters).runtime"""
206
+ return self.stock(parameters).runtime(channel, threads)
207
+
208
+ # ---- the export and PacRunner's libraries
209
+
210
+ def export(self, path=None, parameters=None):
211
+ """the recurrence export (`pyamplicol export-recurrence`, with the producing pyAmpliCol) to `path`
212
+ (default: export.json in the default library folder), the model at `parameters` (default: the
213
+ artifact's); returns the path"""
214
+ path = Path(path) if path is not None else self.default_folder() / "export.json"
215
+ path.parent.mkdir(parents=True, exist_ok=True)
216
+ args = ["export-recurrence", self.path, "-o", path]
217
+ if parameters:
218
+ params = path.with_name(path.stem + ".parameters.json")
219
+ params.write_text(json.dumps(dict(parameters), indent=1))
220
+ args += ["--model-parameters", params]
221
+ self.pyamplicol().run(*args)
222
+ return path
223
+
224
+ def default_folder(self, device="cpu", precision="f64"):
225
+ """where compile puts the libraries by default: <parent>/.pacrunner-build/<artifact>/<provider>-<device>[-<precision>]"""
226
+ device, precision = _env.compile_target(device, precision)
227
+ name = f"{self.provider}-{device}" + ("" if precision == "f64" else f"-{precision}")
228
+ return self.path.parent / ".pacrunner-build" / self.path.name / name
229
+
230
+ def compile(self, folder=None, device="cpu", precision="f64", parameters=None, interpreter=False, force=False):
231
+ """PacRunner's UMAMI libraries of this provider: the export (export()), then umami_libraries
232
+ (pacrunner.umami) into `folder` (default: default_folder()); returns the Provider. Skipped when
233
+ `folder` holds libraries of the same artifact, provider, parameters, device, precision, pacrunner
234
+ revision and symjit (its pacrunner-build.json), unless `force`. device: "cpu", "cpu-jit" (the CPU runner
235
+ made by symjit: a SIMD device's kernel as scalar code, the cpu bits), a SIMD device ("simd-avx2", "simd-avx512",
236
+ "simd-neon", "simd"), "cuda" (an NVIDIA GPU, a
237
+ CPU provider), "metal" (an Apple GPU, a CPU provider, macOS; always mixed f32/df64), "gpu" (this
238
+ system's: metal on macOS, cuda elsewhere), "cuda_provider" or its alias "cuda_full" (MadSpace's GPU
239
+ runtime); precision "f64", "mixed" (a GPU device) or "split" (a SIMD device)."""
240
+ from .kernels import require_symjit, symjit_fingerprint
241
+ from .umami import umami_libraries
242
+ require_symjit() # symjit >= 2.29, before the export
243
+ _env.c_sources() # and the C sources
244
+ device, precision = _env.compile_target(device, precision)
245
+ from ._libraries import Provider
246
+ folder = Path(folder) if folder is not None else self.default_folder(device, precision)
247
+ stamp = {"artifact_id": self.id, "provider": self.provider, "device": device, "precision": precision,
248
+ "interpreter": bool(interpreter), "parameters": dict(sorted((parameters or {}).items())),
249
+ "pacrunner": source_revision(), "symjit": symjit_fingerprint()} # the kernels' C
250
+ if not force and (folder / "umami_pac.json").is_file() and (folder / STAMP).is_file():
251
+ if _read(folder / STAMP) == stamp and stamp["pacrunner"] is not None and not stamp["pacrunner"].endswith("+"):
252
+ return Provider(folder)
253
+ folder.mkdir(parents=True, exist_ok=True)
254
+ (folder / STAMP).unlink(missing_ok=True)
255
+ export = self.export(folder / "export.json", parameters)
256
+ umami_libraries(export, self.metadata_path, folder, device=device, precision=precision, interpreter=interpreter,
257
+ quiet=True)
258
+ (folder / STAMP).write_text(json.dumps(stamp, indent=1))
259
+ return Provider(folder)
pacrunner/_env.py ADDED
@@ -0,0 +1,260 @@
1
+ """Where pacrunner's tools are: its C sources (pacrunner/c/), a MadGraph7 checkout with its
2
+ MadSpace (CPU or CUDA build) and pyAmpliCol. Set with pacrunner.configure(...), else from the
3
+ environment (PACRUNNER_MADGRAPH7, PACRUNNER_PYAMPLICOL), else found."""
4
+
5
+ import os
6
+ import platform
7
+ import sys
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+
11
+
12
+ class PacRunnerError(RuntimeError):
13
+ """A pacrunner setup or use error, with what to do about it"""
14
+
15
+
16
+ # the package, and the C sources the libraries are built from (package data: pacrunner/c/)
17
+ PACKAGE = Path(__file__).resolve().parent
18
+ C_DIR = PACKAGE / "c"
19
+ # the clone pacrunner is installed from, editable (its parent folder); not one for an installed copy
20
+ REPOSITORY = PACKAGE.parent
21
+
22
+
23
+ # the SIMD devices: one symjit kernel per program, for one instruction set (its f64 lanes)
24
+ SIMD_DEVICES = {"simd-avx2": 4, "simd-avx512": 8, "simd-neon": 2}
25
+ # cpu-jit: the CPU runner made by symjit: the SIMD devices' kernel of a program (simd-avx2's on x86-64, simd-neon's on
26
+ # aarch64) as symjit's scalar kernel, one event a call; f64, the cpu runner's bits; builds where a SIMD device does
27
+ CPU_JIT = "cpu-jit"
28
+ DEVICES = ("cpu", CPU_JIT, *SIMD_DEVICES, "cuda", "cuda_provider", "metal")
29
+ # cuda_full: everything on the GPU (MadSpace's GPU runtime); simd: this machine's SIMD device (simd_device)
30
+ DEVICE_ALIASES = {"cuda_full": "cuda_provider", "simd": None}
31
+ # f64; mixed: a GPU's f32 currents (Metal: f32/df64); split: a SIMD device's split kernels (f64 + f32)
32
+ PRECISIONS = ("f64", "mixed", "split")
33
+
34
+
35
+ def device_name(device: str) -> str:
36
+ """a compile device's own name: an alias's target (cuda_full is cuda_provider), "gpu" this
37
+ system's GPU with MadSpace on the CPU (metal on macOS, cuda elsewhere), "simd" this machine's SIMD
38
+ device (simd_device)"""
39
+ if device == "gpu":
40
+ return "metal" if sys.platform == "darwin" else "cuda"
41
+ if device == "simd":
42
+ return simd_device() or "simd"
43
+ return DEVICE_ALIASES.get(device) or device
44
+
45
+
46
+ def compile_target(device: str, precision: str = "f64") -> tuple[str, str]:
47
+ """(device, precision) of a build: the device's own name (device_name), and for metal always
48
+ "mixed" (Metal has no f64: mixed f32/df64). A SIMD device's name may carry its precision
49
+ ("simd-avx2-split", "simd-split"); "mixed" on a SIMD device is "split" (its former name). An
50
+ unknown device or precision, metal off macOS, or a SIMD device (or cpu-jit, f64 only) this machine
51
+ cannot build (symjit's JIT compiles the kernels: simd_devices), is a PacRunnerError"""
52
+ if device.endswith("-split") and device != "-split":
53
+ device, precision = device[:-len("-split")], "split"
54
+ name = device_name(device)
55
+ if name not in DEVICES:
56
+ raise PacRunnerError(f"device {device!r}: one of {', '.join(DEVICES)}, or gpu, "
57
+ f"{', '.join(DEVICE_ALIASES)}, or a SIMD device with -split")
58
+ if precision not in PRECISIONS:
59
+ raise PacRunnerError(f"precision {precision!r}: one of {', '.join(PRECISIONS)}")
60
+ if name == "metal":
61
+ if sys.platform != "darwin":
62
+ raise PacRunnerError(f"device {device!r} is metal (an Apple GPU): macOS only")
63
+ return name, "mixed"
64
+ if name in SIMD_DEVICES:
65
+ if name not in simd_devices():
66
+ here = ", ".join(simd_devices()) or "none"
67
+ raise PacRunnerError(f"device {name!r} does not build on this machine ({platform.machine()}; its SIMD "
68
+ f"devices: {here})")
69
+ if precision == "mixed":
70
+ precision = "split"
71
+ return name, precision
72
+ if name == CPU_JIT:
73
+ if not simd_devices():
74
+ raise PacRunnerError(f"device {CPU_JIT!r} does not build on this machine ({platform.machine()}): symjit's JIT "
75
+ "compiles its kernels, as a SIMD device's (x86-64 with AVX2 and FMA, or aarch64)")
76
+ if precision != "f64":
77
+ raise PacRunnerError(f"device {CPU_JIT!r} is f64 only (precision {precision!r}: a SIMD or GPU device)")
78
+ return name, precision
79
+ if precision == "split":
80
+ raise PacRunnerError(f"precision 'split' needs a SIMD device ({', '.join(SIMD_DEVICES)}, simd)")
81
+ if precision != "f64" and name == "cpu":
82
+ raise PacRunnerError(f"precision {precision!r} needs a GPU device (cuda, cuda_provider, metal) or a SIMD device")
83
+ return name, precision
84
+
85
+
86
+ def cpu_jit_isa() -> str | None:
87
+ """the instruction set of the SIMD kernel whose scalar code device cpu-jit runs: avx2 on x86-64 (its fragments
88
+ use 14 registers, which scalar code has too), neon on aarch64; None where no SIMD device builds"""
89
+ here = simd_devices()
90
+ return None if not here else ("neon" if here[0] == "simd-neon" else "avx2")
91
+
92
+
93
+ def library_name(device: str, precision: str = "f64") -> str:
94
+ """the name of a build (compile_target's): its device, and its precision unless f64
95
+ ("simd-avx512-split", "cuda-mixed", "cpu")"""
96
+ device, precision = compile_target(device, precision)
97
+ return device if precision == "f64" else f"{device}-{precision}"
98
+
99
+
100
+ def _cpu_flags() -> set:
101
+ try:
102
+ return set(Path("/proc/cpuinfo").read_text().split())
103
+ except OSError:
104
+ return set()
105
+
106
+
107
+ def simd_devices() -> tuple[str, ...]:
108
+ """the SIMD devices that build on this machine (symjit's JIT compiles their kernels for this CPU):
109
+ simd-avx2 (an x86-64 CPU with AVX2 and FMA) and simd-avx512 (AVX-512 F and DQ as well), simd-neon
110
+ (aarch64: Linux or macOS)"""
111
+ machine = platform.machine().lower()
112
+ if machine in ("x86_64", "amd64"):
113
+ flags = _cpu_flags()
114
+ if not {"avx2", "fma"} <= flags:
115
+ return ()
116
+ return ("simd-avx2", "simd-avx512") if {"avx512f", "avx512dq"} <= flags else ("simd-avx2",)
117
+ if machine in ("aarch64", "arm64"):
118
+ return ("simd-neon",)
119
+ return ()
120
+
121
+
122
+ def simd_device() -> str | None:
123
+ """this machine's SIMD device (the alias "simd"): simd-avx512 where the CPU has AVX-512, else
124
+ simd-avx2, simd-neon on aarch64; None without one"""
125
+ here = simd_devices()
126
+ return here[-1] if here else None
127
+
128
+
129
+ def simd_machine() -> bool:
130
+ """whether a SIMD device builds here"""
131
+ return bool(simd_devices())
132
+
133
+
134
+ def c_sources() -> Path:
135
+ """the C sources' folder (pacrunner/c/), checked"""
136
+ if not (C_DIR / "umami_pac.c").is_file() or not (C_DIR / "pacops.c").is_file():
137
+ raise PacRunnerError(f"{C_DIR}: no umami_pac.c, pacops.c: pacrunner is installed without its C sources "
138
+ "(package data); reinstall it")
139
+ return C_DIR
140
+
141
+
142
+ def repository() -> Path | None:
143
+ """the git clone pacrunner runs from (installed editable), else None (an installed copy)"""
144
+ if (REPOSITORY / "pyproject.toml").is_file() and (REPOSITORY / ".git").exists():
145
+ return REPOSITORY
146
+ return None
147
+
148
+
149
+ @dataclass
150
+ class Config:
151
+ madgraph7: str | None = None # a MadGraph7 checkout (madspace/, pyamplicol/)
152
+ cuda: bool | None = None # MadSpace's CUDA build (None: when MadGraph7 has one)
153
+ pyamplicol: str | None = None # a pyAmpliCol installation: a python or an install folder
154
+
155
+
156
+ CONFIG = Config()
157
+
158
+
159
+ def configure(julia=None, madgraph7=None, cuda=None, pyamplicol=None):
160
+ """Where pacrunner's tools are, for this process: `madgraph7` (a MadGraph7 checkout with MadSpace and
161
+ pyAmpliCol installed; default PACRUNNER_MADGRAPH7, or an mg7 output's own), `cuda` (True: MadSpace's
162
+ CUDA build, False: the CPU build; default: the CUDA build when MadGraph7 has one), `pyamplicol` (a
163
+ pyAmpliCol installation for artifacts it produced: a python that imports pyamplicol, or an install
164
+ folder such as MADGRAPH7/pyamplicol/install; default PACRUNNER_PYAMPLICOL, else found). MadSpace is
165
+ loaded once per process: configure it before its first use. `julia` is ignored (with a warning):
166
+ pacrunner no longer uses Julia. Returns the configuration."""
167
+ if julia is not None:
168
+ import warnings
169
+ warnings.warn("pacrunner.configure(julia=...) is ignored: pacrunner no longer uses Julia", DeprecationWarning,
170
+ stacklevel=2)
171
+ if madgraph7 is not None or cuda is not None:
172
+ if "madspace" in sys.modules:
173
+ raise PacRunnerError("MadSpace is already loaded in this process: configure(madgraph7=..., cuda=...) "
174
+ "before the first runtime")
175
+ if madgraph7 is not None:
176
+ CONFIG.madgraph7 = os.fspath(Path(madgraph7).expanduser().resolve())
177
+ if cuda is not None:
178
+ CONFIG.cuda = bool(cuda)
179
+ if pyamplicol is not None:
180
+ CONFIG.pyamplicol = os.fspath(Path(pyamplicol).expanduser())
181
+ return CONFIG
182
+
183
+
184
+ def madgraph7(required=True) -> Path | None:
185
+ """the MadGraph7 checkout: configure(madgraph7=...) or PACRUNNER_MADGRAPH7"""
186
+ path = CONFIG.madgraph7 or os.environ.get("PACRUNNER_MADGRAPH7") or None # an empty variable: unset
187
+ if path is None:
188
+ if required:
189
+ raise PacRunnerError("no MadGraph7: pacrunner.configure(madgraph7=...) or PACRUNNER_MADGRAPH7 (a MadGraph7 "
190
+ "checkout with MadSpace installed: `install madspace` in its bin/madgraph)")
191
+ return None
192
+ path = Path(path).expanduser().resolve()
193
+ if not (path / "bin" / "madgraph").is_file():
194
+ raise PacRunnerError(f"{path}: not a MadGraph7 checkout (no bin/madgraph)")
195
+ return path
196
+
197
+
198
+ def mg7_output_of(path) -> Path | None:
199
+ """the mg7 output holding `path` (the first folder, `path` or above, with bin/generate_events)"""
200
+ d = Path(path).expanduser().resolve()
201
+ for p in (d, *d.parents):
202
+ if (p / "bin" / "generate_events").is_file():
203
+ return p
204
+ return None
205
+
206
+
207
+ def madgraph7_of_output(output) -> Path:
208
+ """the MadGraph7 checkout an mg7 output was made with (its bin/generate_events' sys.path line)"""
209
+ import re
210
+ text = (Path(output) / "bin" / "generate_events").read_text()
211
+ m = re.search(r"sys\.path\.append\('([^']*)'\)", text)
212
+ if m is None:
213
+ raise PacRunnerError(f"{output}: bin/generate_events names no MadGraph7 folder")
214
+ return Path(m.group(1)).resolve()
215
+
216
+
217
+ def madgraph7_for(path=None, required=True) -> Path | None:
218
+ """the MadGraph7 checkout for something at `path`: the configured one, else the one of the mg7 output
219
+ holding `path` (none: None, or the error when `required`)"""
220
+ mg7 = madgraph7(required=False)
221
+ if mg7 is not None:
222
+ return mg7
223
+ output = mg7_output_of(path) if path is not None else None
224
+ if output is not None:
225
+ return madgraph7_of_output(output)
226
+ return madgraph7(required=required) # none configured: None or the error
227
+
228
+
229
+ def madspace_dir(mg7: Path) -> Path:
230
+ """the MadSpace build to import: install-cuda (configure(cuda=True), or by default when it exists:
231
+ it has the CPU device too), else install"""
232
+ cuda, cpu = mg7 / "madspace" / "install-cuda", mg7 / "madspace" / "install"
233
+ want_cuda = CONFIG.cuda if CONFIG.cuda is not None else (cuda / "madspace").is_dir()
234
+ path = cuda if want_cuda else cpu
235
+ if not (path / "madspace").is_dir():
236
+ what = "a CUDA build of MadSpace (cmake -DENABLE_CUDA=ON)" if want_cuda else "MadSpace (`install madspace`)"
237
+ raise PacRunnerError(f"{mg7}: no {what} in {path}")
238
+ return path
239
+
240
+
241
+ def import_madspace(mg7: Path | None = None):
242
+ """MadSpace, imported once for this process: from the MadGraph7 checkout (`mg7`, or the configured
243
+ one), else the one installed in this python (`import madspace`); Symbolica's lock folder defaulted
244
+ (XDG_RUNTIME_DIR) for pyAmpliCol's libraries"""
245
+ if "madspace" in sys.modules:
246
+ return sys.modules["madspace"]
247
+ mg7 = mg7 or madgraph7(required=False)
248
+ os.environ.setdefault("XDG_RUNTIME_DIR", os.path.expanduser("~/.cache/xdg-runtime"))
249
+ os.makedirs(os.environ["XDG_RUNTIME_DIR"], exist_ok=True)
250
+ if mg7 is not None:
251
+ sys.path.insert(0, os.fspath(madspace_dir(mg7)))
252
+ try:
253
+ import madspace
254
+ except ImportError as e:
255
+ if mg7 is not None:
256
+ raise
257
+ raise PacRunnerError("no MadSpace: install it in this python, or point pacrunner at a MadGraph7 checkout with "
258
+ "MadSpace installed (pacrunner.configure(madgraph7=...) or PACRUNNER_MADGRAPH7; "
259
+ "`install madspace` in its bin/madgraph)") from e
260
+ return madspace