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/_runtime.py ADDED
@@ -0,0 +1,142 @@
1
+ """Runtime: one callable for any UMAMI matrix element in MadSpace (the stock pyAmpliCol library or
2
+ PacRunner's), numpy in and numpy out, the MadSpace function built for each call's inputs on first use.
3
+
4
+ rt = library.runtime(channel=0)
5
+ out = rt(momenta, flavours) # the helicity-summed matrix element
6
+ out = rt(momenta, flavours, random_helicity=r) # the LC pass: + colour and helicity indices
7
+ out = rt(momenta, flavours, helicity=h) # one exported helicity
8
+ out.matrix_element, out.color_index, out.helicity_index # numpy arrays (None when not asked)
9
+
10
+ Contexts (madspace.Context) are made here, one per (device, threads) and process."""
11
+
12
+ from typing import NamedTuple
13
+
14
+ import numpy as np
15
+
16
+ from . import _env
17
+
18
+ _contexts = {}
19
+
20
+
21
+ def madspace(mg7=None):
22
+ """MadSpace, imported once for this process (pacrunner._env.import_madspace)"""
23
+ return _env.import_madspace(mg7)
24
+
25
+
26
+ def context(device="cpu", threads=None, mg7=None):
27
+ """the madspace.Context of `device` ("cpu" or "cuda") with `threads` threads (default: the CPUs for
28
+ the CPU, 1 for CUDA), one per process"""
29
+ ms = madspace(mg7)
30
+ if device not in ("cpu", "cuda"):
31
+ raise _env.PacRunnerError(f"device {device!r}: 'cpu' or 'cuda'")
32
+ threads = threads if threads is not None else (-1 if device == "cpu" else 1)
33
+ key = (device, threads)
34
+ if key not in _contexts:
35
+ dev = ms.cpu_device() if device == "cpu" else ms.cuda_device()
36
+ _contexts[key] = ms.Context(dev, threads)
37
+ return _contexts[key]
38
+
39
+
40
+ class RuntimeResult(NamedTuple):
41
+ """a Runtime call's outputs, one value per event (None: not asked for)"""
42
+ matrix_element: object
43
+ color_index: object = None
44
+ helicity_index: object = None
45
+
46
+
47
+ def _events(x, n, dtype, what):
48
+ """an input of one value per event: a scalar repeated, or an array of n"""
49
+ if np.isscalar(x):
50
+ return np.full(n, x, dtype=dtype)
51
+ if _is_device_array(x):
52
+ return x
53
+ a = np.asarray(x, dtype=dtype)
54
+ if a.shape != (n,):
55
+ raise ValueError(f"{what}: {a.shape}, expected one value per event ({n},)")
56
+ return a
57
+
58
+
59
+ def _is_device_array(x):
60
+ return hasattr(x, "__cuda_array_interface__")
61
+
62
+
63
+ class Runtime:
64
+ """A matrix element of one UMAMI channel in MadSpace: call(momenta, flavour, ...) -> RuntimeResult.
65
+
66
+ momenta[event, particle, (E, px, py, pz)] in the provider's particle order; flavour the provider's
67
+ flavour per event (an int: every event). On a CUDA context numpy inputs are moved to the device
68
+ (CuPy) and the outputs back; device arrays (CuPy) in give device arrays out. `function(inputs,
69
+ outputs)` is the madspace.Function of one input set, `function_runtime(...)` its FunctionRuntime."""
70
+
71
+ def __init__(self, build, context, particle_count, cuda, description=""):
72
+ self._build = build # (inputs, outputs) -> madspace.Function
73
+ self.context = context
74
+ self.particle_count = particle_count
75
+ self.cuda = cuda
76
+ self.description = description
77
+ self._runtimes = {}
78
+
79
+ def __repr__(self):
80
+ return f"<pacrunner.Runtime {self.description} ({'cuda' if self.cuda else 'cpu'})>"
81
+
82
+ def function(self, inputs, outputs):
83
+ return self._build(list(inputs), list(outputs))
84
+
85
+ def function_runtime(self, inputs, outputs):
86
+ """the madspace.FunctionRuntime of these inputs and outputs (built once)"""
87
+ ms = madspace()
88
+ key = (tuple(int(i) for i in inputs), tuple(int(o) for o in outputs))
89
+ if key not in self._runtimes:
90
+ self._runtimes[key] = ms.FunctionRuntime(self.function(inputs, outputs), self.context)
91
+ return self._runtimes[key]
92
+
93
+ def __call__(self, momenta, flavour=0, *, random_helicity=None, helicity=None, alpha_s=None):
94
+ ME = madspace().MatrixElement
95
+ if random_helicity is not None and helicity is not None:
96
+ raise ValueError("random_helicity (the LC pass: a helicity drawn) or helicity (one fixed), not both")
97
+ device_in = _is_device_array(momenta)
98
+ if not device_in:
99
+ momenta = np.asarray(momenta, dtype=np.float64)
100
+ n = momenta.shape[0]
101
+ if tuple(momenta.shape[1:]) != (self.particle_count, 4):
102
+ raise ValueError(f"momenta: {tuple(momenta.shape)}, expected (events, {self.particle_count}, 4)")
103
+ inputs, args = [ME.momenta_in, ME.flavor_in], [momenta, _events(flavour, n, np.int32, "flavour")]
104
+ outputs = [ME.matrix_element_out]
105
+ if random_helicity is not None:
106
+ inputs.append(ME.random_helicity_in)
107
+ args.append(_events(random_helicity, n, np.float64, "random_helicity"))
108
+ outputs += [ME.color_index_out, ME.helicity_index_out]
109
+ elif helicity is not None:
110
+ inputs.append(ME.helicity_in)
111
+ args.append(_events(helicity, n, np.int32, "helicity"))
112
+ if alpha_s is not None:
113
+ inputs.append(ME.alpha_s_in)
114
+ args.append(_events(alpha_s, n, np.float64, "alpha_s"))
115
+ values = self._call(self.function_runtime(inputs, outputs), args, device_in)
116
+ return RuntimeResult(*values)
117
+
118
+ def _call(self, rt, args, device_in):
119
+ if not self.cuda:
120
+ if any(_is_device_array(a) for a in args):
121
+ raise ValueError("device arrays for a CPU runtime: pass numpy arrays")
122
+ return [np.array(x.numpy()) for x in rt.call(args)]
123
+ try:
124
+ import cupy
125
+ except ImportError as e:
126
+ raise _env.PacRunnerError("a CUDA runtime needs CuPy (pacrunner's `cuda` extra, or `python -m pip install cupy-cuda13x`)") from e
127
+ outs = rt.call([cupy.asarray(a) for a in args])
128
+ cupy.cuda.runtime.deviceSynchronize()
129
+ return [cupy.from_dlpack(x) if device_in else cupy.from_dlpack(x).get() for x in outs]
130
+
131
+
132
+ def matrix_element_runtime(api, particle_count, channel, context, cuda, description=""):
133
+ """a Runtime of one loaded UMAMI library as it is (a provider of many flavours, called with each
134
+ event's flavour: the stock library), its channel fixed"""
135
+ ms = madspace()
136
+ ME = ms.MatrixElement
137
+
138
+ def build(inputs, outputs):
139
+ return ME(api.index(), particle_count, inputs + [ME.channel_in], outputs, diagram_count=1,
140
+ sample_random_inputs=False, me_frame=[], incoming_count=2, channel=channel).function()
141
+
142
+ return Runtime(build, context, particle_count, cuda, description)
@@ -0,0 +1,151 @@
1
+ /* pool.cu: the slot pool of pool.h. Built once per output folder by nvcc into
2
+ * libpacpool.so (shared CUDA runtime), which every program library links. */
3
+
4
+ #include <condition_variable>
5
+ #include <cstdio>
6
+ #include <cstdlib>
7
+ #include <mutex>
8
+ #include <vector>
9
+ #include <unistd.h>
10
+ #include <cuda_runtime.h>
11
+ #include "pool.h"
12
+
13
+ namespace {
14
+
15
+ struct Pool {
16
+ std::mutex lock;
17
+ std::condition_variable freed;
18
+ bool configured = false;
19
+ int slots = 0;
20
+ size_t slot_bytes = 0;
21
+ std::vector<pacpool_slot *> all; // created lazily, up to `slots`
22
+ std::vector<pacpool_slot *> idle; // free ones, the most recently used last
23
+ };
24
+
25
+ Pool &pool()
26
+ {
27
+ static Pool *p = new Pool(); // never destroyed: the libraries may unload in any order at exit
28
+ return *p;
29
+ }
30
+
31
+ bool check(cudaError_t e, const char *what)
32
+ {
33
+ if (e == cudaSuccess) return true;
34
+ std::fprintf(stderr, "pacpool: %s: %s\n", what, cudaGetErrorString(e));
35
+ return false;
36
+ }
37
+
38
+ pacpool_slot *new_slot()
39
+ {
40
+ auto *s = static_cast<pacpool_slot *>(std::calloc(1, sizeof(pacpool_slot)));
41
+ if (s == nullptr) return nullptr;
42
+ cudaStream_t stream;
43
+ if (!check(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking), "cudaStreamCreate") ||
44
+ !check(cudaMalloc((void **)&s->status, sizeof(int)), "cudaMalloc") ||
45
+ !check(cudaMallocHost((void **)&s->host_status, sizeof(int)), "cudaMallocHost")) {
46
+ std::free(s);
47
+ return nullptr;
48
+ }
49
+ s->stream = stream;
50
+ return s;
51
+ }
52
+
53
+ size_t grow(size_t have, size_t need, size_t most)
54
+ {
55
+ size_t n = have * 2 > need ? have * 2 : need;
56
+ return n < most ? n : most;
57
+ }
58
+
59
+ } // namespace
60
+
61
+ extern "C" int pacpool_configure(int slots, size_t slot_bytes, int abi)
62
+ {
63
+ Pool &p = pool();
64
+ std::lock_guard<std::mutex> g(p.lock);
65
+ if (abi != PACPOOL_ABI) {
66
+ std::fprintf(stderr, "pacpool: a library of ABI %d, the runtime's is %d\n", abi, PACPOOL_ABI);
67
+ return -1;
68
+ }
69
+ if (slots <= 0) {
70
+ long cpus = sysconf(_SC_NPROCESSORS_ONLN);
71
+ slots = cpus > 0 ? (int)cpus : 1;
72
+ }
73
+ if (!p.configured) {
74
+ p.configured = true;
75
+ p.slots = slots;
76
+ p.slot_bytes = slot_bytes;
77
+ return 0;
78
+ }
79
+ if (slots != p.slots || slot_bytes != p.slot_bytes) {
80
+ static bool warned = false;
81
+ if (!warned)
82
+ std::fprintf(stderr, "pacpool: a library asks for %d slots of %zu bytes; the pool has %d of %zu\n",
83
+ slots, slot_bytes, p.slots, p.slot_bytes);
84
+ warned = true;
85
+ return -1;
86
+ }
87
+ return 0;
88
+ }
89
+
90
+ extern "C" size_t pacpool_slot_bytes(void) { return pool().slot_bytes; }
91
+ extern "C" int pacpool_slots(void) { return pool().slots; }
92
+
93
+ extern "C" pacpool_slot *pacpool_acquire(void)
94
+ {
95
+ Pool &p = pool();
96
+ std::unique_lock<std::mutex> g(p.lock);
97
+ for (;;) {
98
+ if (!p.idle.empty()) {
99
+ pacpool_slot *s = p.idle.back();
100
+ p.idle.pop_back();
101
+ return s;
102
+ }
103
+ if ((int)p.all.size() < p.slots) {
104
+ pacpool_slot *s = new_slot();
105
+ if (s == nullptr) return nullptr;
106
+ p.all.push_back(s);
107
+ return s;
108
+ }
109
+ p.freed.wait(g);
110
+ }
111
+ }
112
+
113
+ extern "C" void pacpool_release(pacpool_slot *s)
114
+ {
115
+ if (s == nullptr) return;
116
+ Pool &p = pool();
117
+ {
118
+ std::lock_guard<std::mutex> g(p.lock);
119
+ p.idle.push_back(s);
120
+ }
121
+ p.freed.notify_one();
122
+ }
123
+
124
+ extern "C" int pacpool_reserve(pacpool_slot *s, size_t device_bytes, size_t host_bytes)
125
+ {
126
+ size_t budget = pool().slot_bytes;
127
+ if (device_bytes > budget) {
128
+ std::fprintf(stderr, "pacpool: %zu device bytes asked of a %zu-byte slot\n", device_bytes, budget);
129
+ return -1;
130
+ }
131
+ cudaStream_t stream = (cudaStream_t)s->stream;
132
+ if (device_bytes > s->device_bytes) {
133
+ size_t n = grow(s->device_bytes, device_bytes, budget);
134
+ if (!check(cudaStreamSynchronize(stream), "cudaStreamSynchronize")) return -1;
135
+ cudaFree(s->device);
136
+ s->device = nullptr;
137
+ s->device_bytes = 0;
138
+ if (!check(cudaMalloc(&s->device, n), "cudaMalloc")) return -1;
139
+ s->device_bytes = n;
140
+ }
141
+ if (host_bytes > s->host_bytes) {
142
+ size_t n = grow(s->host_bytes, host_bytes, (size_t)-1);
143
+ if (!check(cudaStreamSynchronize(stream), "cudaStreamSynchronize")) return -1;
144
+ cudaFreeHost(s->host);
145
+ s->host = nullptr;
146
+ s->host_bytes = 0;
147
+ if (!check(cudaMallocHost(&s->host, n), "cudaMallocHost")) return -1;
148
+ s->host_bytes = n;
149
+ }
150
+ return 0;
151
+ }
@@ -0,0 +1,55 @@
1
+ /* pool.h: the process-wide GPU slot pool of PacRunner's CUDA UMAMI libraries (libpacpool.so,
2
+ * loaded once per process, whatever the number of program libraries).
3
+ *
4
+ * A slot is a device memory block of at most `slot_bytes`, pinned host staging, a status word and
5
+ * its own non-blocking stream. A call borrows any free slot (pacpool_acquire), carves its arena out
6
+ * of it, runs on its stream, and gives it back (pacpool_release); when every slot is busy, the
7
+ * caller waits. Slots get their memory the first time they are used and keep it, so the device
8
+ * memory is at most (slots that ran at once) × slot_bytes.
9
+ *
10
+ * The first configure call wins (the first program library to run): `slots` = 0 means the number
11
+ * of online CPUs (MadSpace's default thread pool), so that every thread can have one. */
12
+
13
+ #ifndef POOL_H
14
+ #define POOL_H
15
+
16
+ #include <stddef.h>
17
+
18
+ #ifdef __cplusplus
19
+ extern "C" {
20
+ #endif
21
+
22
+ #define PACPOOL_ABI 1
23
+
24
+ typedef struct {
25
+ void *stream; /* cudaStream_t */
26
+ void *device; /* device block, device_bytes */
27
+ size_t device_bytes;
28
+ void *host; /* pinned host block, host_bytes */
29
+ size_t host_bytes;
30
+ int *status; /* device */
31
+ int *host_status; /* pinned */
32
+ } pacpool_slot;
33
+
34
+ /* the pool's size: slots (0: the online CPUs) and the device bytes per slot; only the first call
35
+ * counts. Returns 0, or -1 (a different configuration than the first, reported on stderr; the
36
+ * first stays) */
37
+ int pacpool_configure(int slots, size_t slot_bytes, int abi);
38
+
39
+ /* the slot budget (bytes) and the number of slots, after configure */
40
+ size_t pacpool_slot_bytes(void);
41
+ int pacpool_slots(void);
42
+
43
+ /* a free slot (waits while all are busy); NULL on a CUDA error (reported on stderr) */
44
+ pacpool_slot *pacpool_acquire(void);
45
+
46
+ /* the slot's blocks grown to at least these sizes (device_bytes ≤ the budget); 0, or -1 */
47
+ int pacpool_reserve(pacpool_slot *slot, size_t device_bytes, size_t host_bytes);
48
+
49
+ void pacpool_release(pacpool_slot *slot);
50
+
51
+ #ifdef __cplusplus
52
+ }
53
+ #endif
54
+
55
+ #endif
@@ -0,0 +1,103 @@
1
+ /* uirgpu.c: uirgpu.h, included by runner.c under nvcc after the program's tables and uir_stub,
2
+ * with its sizes defined:
3
+ * UIRGPU_LEGS, UIRGPU_OUTPUTS, UIRGPU_FORMS, UIRGPU_AMPLITUDES, UIRGPU_PLANES
4
+ * (legs; helicity outputs; momentum forms; amplitudes; planes = complex components).
5
+ *
6
+ * This file holds what every build shares: the arena's regions per point, their carving out of
7
+ * one device block, the CUDA error check. Then it includes the entries of one build:
8
+ *
9
+ * (default) uirgpu_pool.c pac_gpu_run, run_gpu on the slot pool (pool.h): the
10
+ * standalone runner (tests)
11
+ * UIRGPU_UMAMI + uirgpu_umami.c pac_gpu_umami: a UMAMI library's call on the pool,
12
+ * finished on the device (umami_finish.h)
13
+ * UIRGPU_PROVIDER uirgpu_provider.c pac_gpu_provider: a CUDA provider on MadSpace's device
14
+ * arrays and stream (no pool)
15
+ *
16
+ * The pool's size (the first program library of the process decides): UIRGPU_SLOTS (0: the online
17
+ * CPUs), UIRGPU_SLOT_BYTES (device bytes per slot; the CUDA provider's workspace budget of a
18
+ * launch). Without PACPOOL_EXTERNAL the pool itself (pool.cu) is compiled in: a standalone runner
19
+ * (tests); the UMAMI libraries link the process-wide libpacpool.so instead. */
20
+
21
+ #include <stdio.h>
22
+ #include <stdlib.h>
23
+ #include <string.h>
24
+ #include "uirgpu.h"
25
+
26
+ #ifndef UIRGPU_SLOTS
27
+ #define UIRGPU_SLOTS 0
28
+ #endif
29
+ #ifndef UIRGPU_SLOT_BYTES
30
+ #define UIRGPU_SLOT_BYTES ((size_t)256 << 20)
31
+ #endif
32
+
33
+ /* numbers per point of each region (at least 1: no empty regions); momenta, outputs and forms are
34
+ * double, amplitudes pac_amp, planes pac_real (pacops.h: float under PAC_MIXED) */
35
+ #define UIRGPU_MAX1(x) ((x) > 0 ? (x) : 1)
36
+ #define UIRGPU_N_MOMENTA UIRGPU_MAX1(4 * UIRGPU_LEGS)
37
+ #define UIRGPU_N_OUT UIRGPU_MAX1(UIRGPU_OUTPUTS)
38
+ #define UIRGPU_N_FORMS UIRGPU_MAX1(4 * UIRGPU_FORMS)
39
+ #define UIRGPU_N_AMPLITUDES UIRGPU_MAX1(2 * UIRGPU_AMPLITUDES)
40
+ #define UIRGPU_N_PLANES UIRGPU_MAX1(2 * UIRGPU_PLANES)
41
+ #define UIRGPU_REGIONS 5
42
+ #define UIRGPU_ALIGN ((size_t)256)
43
+
44
+ /* bytes per point of each region: momenta, outputs, forms, amplitudes, planes */
45
+ static const size_t uirgpu_per_point[UIRGPU_REGIONS] = {
46
+ UIRGPU_N_MOMENTA * sizeof(double), UIRGPU_N_OUT * sizeof(double), UIRGPU_N_FORMS * sizeof(double),
47
+ UIRGPU_N_AMPLITUDES * sizeof(pac_amp), UIRGPU_N_PLANES * sizeof(pac_real)};
48
+
49
+ static size_t uirgpu_aligned(size_t bytes) { return (bytes + UIRGPU_ALIGN - 1) / UIRGPU_ALIGN * UIRGPU_ALIGN; }
50
+
51
+ /* A launch's regions: `n` arrays of per_point[r] bytes a point, each 256-byte aligned.
52
+ * uirgpu_chunk: the most points of one launch within `budget` bytes, at most `points` (0, with a
53
+ * message: the budget holds no point); uirgpu_bytes: the bytes of `chunk` points; uirgpu_carve:
54
+ * the regions' addresses in a block of that size. */
55
+ static size_t uirgpu_chunk(const size_t *per_point, int n, size_t budget, size_t points)
56
+ {
57
+ size_t each = 0, slack = (size_t)n * UIRGPU_ALIGN;
58
+ for (int r = 0; r < n; r++) each += per_point[r];
59
+ size_t most = budget > slack ? (budget - slack) / each : 0;
60
+ if (most == 0)
61
+ fprintf(stderr, "uirgpu (%s %s): %zu bytes hold no point (%zu bytes each)\n", RUNNER_PROCESS, RUNNER_COLOUR,
62
+ budget, each);
63
+ return points < most ? points : most;
64
+ }
65
+
66
+ static size_t uirgpu_bytes(const size_t *per_point, int n, size_t chunk)
67
+ {
68
+ size_t total = 0;
69
+ for (int r = 0; r < n; r++) total += uirgpu_aligned(per_point[r] * chunk);
70
+ return total;
71
+ }
72
+
73
+ static void uirgpu_carve(void *block, const size_t *per_point, int n, size_t chunk, void **region)
74
+ {
75
+ char *p = (char *)block;
76
+ for (int r = 0; r < n; r++) {
77
+ region[r] = p;
78
+ p += uirgpu_aligned(per_point[r] * chunk);
79
+ }
80
+ }
81
+
82
+ /* UIRGPU_REPORT: a failed CUDA call `x` (its error `e_`) printed to stderr; UIRGPU_CHECK: a CUDA
83
+ * call that, failing, is reported and sets status = -1, then goto done (the entry's cleanup) */
84
+ #define UIRGPU_REPORT(x) fprintf(stderr, "uirgpu (%s %s): %s: %s\n", RUNNER_PROCESS, RUNNER_COLOUR, #x, cudaGetErrorString(e_))
85
+ #define UIRGPU_CHECK(x) \
86
+ do { \
87
+ cudaError_t e_ = (x); \
88
+ if (e_ != cudaSuccess) { \
89
+ UIRGPU_REPORT(x); \
90
+ status = -1; \
91
+ goto done; \
92
+ } \
93
+ } while (0)
94
+
95
+ /* the entries of this build */
96
+ #ifdef UIRGPU_PROVIDER
97
+ #include "uirgpu_provider.c"
98
+ #else
99
+ #include "uirgpu_pool.c"
100
+ #ifdef UIRGPU_UMAMI
101
+ #include "uirgpu_umami.c"
102
+ #endif
103
+ #endif
@@ -0,0 +1,70 @@
1
+ /* uirgpu: one program (runner.c under nvcc) on a CUDA GPU, one thread per point, on a slot of the
2
+ * process-wide pool (pool.h): a call borrows a free slot, carves the program's arena out of the
3
+ * slot's device block, runs on the slot's stream, and gives the slot back. The arena, momenta and
4
+ * outputs are plane-major (ld = the launch's points: coalesced); a call larger than the slot's
5
+ * budget runs as several launches (every point is computed alone: the same values).
6
+ *
7
+ * The bits are the CPU interpreter's (uirvm.c with ld = 1) when built with --fmad=false.
8
+ * Thread safe: any number of threads may call at once (up to the pool's slots run together). */
9
+
10
+ #ifndef UIRGPU_H
11
+ #define UIRGPU_H
12
+
13
+ #include <stddef.h>
14
+
15
+ #ifdef __cplusplus
16
+ extern "C" {
17
+ #endif
18
+
19
+ /* the program on `points` points: momenta[(4 leg + component) points + point] (E, px, py, pz per
20
+ * leg, the program's leg order), out[output points + point]; both host memory (any). Returns 0, a
21
+ * kernel's failing status, or -1 (a CUDA error, printed to stderr). */
22
+ int pac_gpu_run(const double *momenta, double *out, size_t points);
23
+
24
+ /* UIRGPU_UMAMI (a UMAMI library, umami_finish.h): `count` events of MadSpace's momentum layout,
25
+ * component k of particle p at momenta[(n k + p) stride + event] (n = the legs; `momenta` at the
26
+ * call's first event), run with the program's crossing (which carries the library's leg
27
+ * permutation) and finished on the device (pac_finish): me[event], label[event] (either NULL: not
28
+ * wanted). Per event, optional (NULL): scale (the alpha_s rescale, multiplied in), fixed (an
29
+ * exported helicity, else the sum and, with `draw`, a drawn one), random (the draw's number; else
30
+ * 0.5). All host memory. Returns 0, a kernel's failing status, -2 (a non-finite momentum or
31
+ * matrix element) or -1 (a CUDA error, printed to stderr). */
32
+ int pac_gpu_umami(const double *momenta, size_t stride, size_t count, const double *scale, const int *fixed,
33
+ const double *random, int draw, double *me, int *label);
34
+
35
+ /* UIRGPU_PROVIDER (a UMAMI library that identifies as CUDA): one call's device arrays, in
36
+ * MadSpace's layout (momenta: component k of particle p at [stride (n k + p) + event], from the
37
+ * call's first event; the others one value per event); NULL: absent. */
38
+ typedef struct {
39
+ const double *momenta;
40
+ size_t stride;
41
+ const double *alpha_s;
42
+ const int *flavor;
43
+ const double *random;
44
+ const int *fixed; /* exported helicity indices: the fixed-helicity pass */
45
+ double *me;
46
+ int *label;
47
+ int *colour;
48
+ int draw; /* the helicity index wanted without `fixed`: draw it */
49
+ } uirgpu_call;
50
+
51
+ /* an error flag in mapped pinned memory (0: no failure): a failing event of any call stores its
52
+ * code there (umami_finish.h's PAC_E_), which the host reads without a sync and clears when it
53
+ * reports it; NULL on a CUDA error */
54
+ int *pac_gpu_error_flag(void);
55
+ void pac_gpu_free_error_flag(int *flag);
56
+
57
+ /* `count` events queued on `stream` (a cudaStream_t; its device is used): the checks, the program
58
+ * and pac_finish per event, the outputs written in place; nothing synchronized. A failing event's
59
+ * matrix element is NaN (helicity 0) and its code goes to *error. The thread's current device is
60
+ * left as it was. Returns 0, or -1 (a CUDA error while queuing, printed to stderr). */
61
+ int pac_gpu_provider(const uirgpu_call *call, size_t count, void *stream, int *error);
62
+
63
+ /* the test entry: momenta[point][4 legs], out[point][outputs] (point-major) */
64
+ int run_gpu(double *out, const double *momenta, size_t points);
65
+
66
+ #ifdef __cplusplus
67
+ }
68
+ #endif
69
+
70
+ #endif
@@ -0,0 +1,89 @@
1
+ /* uirgpu_pool.c: the entries of uirgpu.h on the slot pool (pool.h): pac_gpu_run and the test entry
2
+ * run_gpu. A call borrows a free slot, carves the program's arena out of the slot's device block,
3
+ * runs on the slot's stream, and gives the slot back. Included by uirgpu.c (not UIRGPU_PROVIDER),
4
+ * after the regions and their carving. Without PACPOOL_EXTERNAL the pool itself (pool.cu) is
5
+ * compiled in (a standalone runner); the UMAMI libraries link libpacpool.so instead. */
6
+
7
+ #include "pool.h"
8
+ #ifndef PACPOOL_EXTERNAL
9
+ #include "pool.cu"
10
+ #endif
11
+
12
+ __global__ static void uirgpu_points(const double *momenta, double *out, double *forms, pac_amp *amplitudes,
13
+ pac_real *planes, size_t points, int *status)
14
+ {
15
+ size_t i = (size_t)blockIdx.x * blockDim.x + threadIdx.x;
16
+ if (i >= points) return;
17
+ uir_arena a = {forms, amplitudes, planes, points, i};
18
+ int s = uir_run(&program, &a, momenta + i, out + i);
19
+ if (s != 0) *status = s; /* any failing point's status */
20
+ }
21
+
22
+ int pac_gpu_run(const double *momenta, double *out, size_t points)
23
+ {
24
+ if (points == 0) return 0;
25
+ pacpool_configure(UIRGPU_SLOTS, UIRGPU_SLOT_BYTES, PACPOOL_ABI); /* the first library decides */
26
+ const size_t d = sizeof(double), rows_m = 4 * (size_t)UIRGPU_LEGS, rows_o = UIRGPU_OUTPUTS;
27
+ /* the most points of one launch within the slot's budget */
28
+ size_t chunk = uirgpu_chunk(uirgpu_per_point, UIRGPU_REGIONS, pacpool_slot_bytes(), points);
29
+ if (chunk == 0) return -1;
30
+ int status = 0;
31
+ pacpool_slot *s = pacpool_acquire();
32
+ if (s == NULL) return -1;
33
+ cudaStream_t stream = (cudaStream_t)s->stream;
34
+ if (pacpool_reserve(s, uirgpu_bytes(uirgpu_per_point, UIRGPU_REGIONS, chunk), (rows_m + rows_o) * points * d) != 0) {
35
+ status = -1;
36
+ goto done;
37
+ }
38
+ {
39
+ /* the arena's regions, for launches of up to `chunk` points */
40
+ void *region[UIRGPU_REGIONS];
41
+ uirgpu_carve(s->device, uirgpu_per_point, UIRGPU_REGIONS, chunk, region);
42
+ double *host_momenta = (double *)s->host, *host_out = host_momenta + rows_m * points;
43
+ memcpy(host_momenta, momenta, rows_m * points * d);
44
+ UIRGPU_CHECK(cudaMemsetAsync(s->status, 0, sizeof(int), stream));
45
+ for (size_t first = 0; first < points; first += chunk) {
46
+ size_t q = points - first < chunk ? points - first : chunk; /* this launch's points: ld = q */
47
+ if (rows_m > 0)
48
+ UIRGPU_CHECK(cudaMemcpy2DAsync(region[0], q * d, host_momenta + first, points * d, q * d, rows_m,
49
+ cudaMemcpyHostToDevice, stream));
50
+ /* the arena at zero (uir_run writes the forms and the outputs) */
51
+ UIRGPU_CHECK(cudaMemsetAsync(region[3], 0, uirgpu_per_point[3] * q, stream));
52
+ UIRGPU_CHECK(cudaMemsetAsync(region[4], 0, uirgpu_per_point[4] * q, stream));
53
+ uirgpu_points<<<(unsigned)((q + 127) / 128), 128, 0, stream>>>(
54
+ (const double *)region[0], (double *)region[1], (double *)region[2], (pac_amp *)region[3],
55
+ (pac_real *)region[4], q, s->status);
56
+ UIRGPU_CHECK(cudaGetLastError());
57
+ if (rows_o > 0)
58
+ UIRGPU_CHECK(cudaMemcpy2DAsync(host_out + first, points * d, region[1], q * d, q * d, rows_o,
59
+ cudaMemcpyDeviceToHost, stream));
60
+ }
61
+ UIRGPU_CHECK(cudaMemcpyAsync(s->host_status, s->status, sizeof(int), cudaMemcpyDeviceToHost, stream));
62
+ UIRGPU_CHECK(cudaStreamSynchronize(stream));
63
+ status = *s->host_status;
64
+ if (status == 0) memcpy(out, host_out, rows_o * points * d);
65
+ }
66
+ done:
67
+ pacpool_release(s);
68
+ return status;
69
+ }
70
+
71
+ int run_gpu(double *out, const double *momenta, size_t points)
72
+ {
73
+ if (points == 0) return 0;
74
+ size_t nm = 4 * (size_t)UIRGPU_LEGS, no = UIRGPU_OUTPUTS;
75
+ double *m = (double *)malloc(UIRGPU_MAX1(nm) * points * sizeof(double));
76
+ double *o = (double *)malloc(UIRGPU_MAX1(no) * points * sizeof(double));
77
+ int status = -1;
78
+ if (m != NULL && o != NULL) {
79
+ for (size_t p = 0; p < points; p++)
80
+ for (size_t k = 0; k < nm; k++) m[k * points + p] = momenta[p * nm + k];
81
+ status = pac_gpu_run(m, o, points);
82
+ if (status == 0)
83
+ for (size_t p = 0; p < points; p++)
84
+ for (size_t h = 0; h < no; h++) out[p * no + h] = o[h * points + p];
85
+ }
86
+ free(m);
87
+ free(o);
88
+ return status;
89
+ }