Metadata-Version: 2.4
Name: pacrunner
Version: 0.6.0
Summary: pyAmpliCol's LC recurrence programs as UMAMI libraries for MadGraph7/MadSpace (CPU, CUDA), from Python
Author: Shahriar Iravanian
License-Expression: MIT
Project-URL: Homepage, https://github.com/shahriariravanian/pacrunner
Project-URL: Source, https://github.com/shahriariravanian/pacrunner
Project-URL: Issues, https://github.com/shahriariravanian/pacrunner/issues
Keywords: MadGraph7,MadSpace,pyAmpliCol,UMAMI,matrix elements,CUDA,SIMD,particle physics
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: MacOS
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: C
Classifier: Topic :: Scientific/Engineering :: Physics
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: pacrunner/c/UMAMI_LICENSE
Requires-Dist: numpy
Requires-Dist: symjit>=2.29.3
Provides-Extra: cuda
Requires-Dist: cupy-cuda13x; extra == "cuda"
Dynamic: license-file

# PacRunner

PacRunner is a compiler to convert [pyAmpliCol](https://github.com/MadGraphTeam/pyamplicol)'s recurrence 
mode processes to UMAMI-compatible libraries for both CPU and GPU.

Unified  MAtrix  eleMent  Interface (UMAMI) is a standard interface to bridge various matrix elements 
generators and [MadGraph](https://github.com/MadGraphTeam/MadGraph7) ecosystem. 

## Installation

1. Clone [MadGraph7](https://github.com/MadGraphTeam/MadGraph7/):
   `git clone https://github.com/MadGraphTeam/MadGraph7.git`. 
2. Build MadSpace and pyAmpliCol inside the checkout, either from the MadGraph7 prompt
   (`./bin/madgraph`, then `install madspace` and `install pyamplicol`) or from the checkout's root:
   ```sh
   python madspace/install.py --source -y
   python pyamplicol/install.py --source -y
   ```
   Do not pass `--system`: the builds go to `madspace/install` and `pyamplicol/install`.
3. Optional, for `device="cuda_full"` (MadSpace itself on the GPU): a CUDA build of MadSpace in
   `madspace/install-cuda`, next to the CPU build of step 2 (whose build dependencies it uses):
   ```sh
   cd madspace
   PYTHONPATH=install python -m pip install --no-build-isolation --upgrade \
       -Cbuild-dir=build-cuda --target=install-cuda \
       -Ccmake.define.ENABLE_CUDA=ON -Ccmake.define.CMAKE_CUDA_ARCHITECTURES=120 \
       -Ccmake.define.ENABLE_OPENBLAS=ON -Ccmake.build-type=Release .
   ```
   `device="cuda"` does not need it (the matrix elements on the GPU, MadSpace on the CPU).
4. Install PacRunner from PyPI: `python -m pip install pacrunner`, or `python -m pip install "pacrunner[cuda]"`
   for the CUDA devices (it adds CuPy). numpy and symjit (2.29.3 or later) come with it; to use conda-forge's
   symjit, install it first (`conda install -c conda-forge 'symjit>=2.29.3'`) and pip keeps it.
5. Or, to work on PacRunner itself, install it from a clone, editable:
   `git clone https://github.com/shahriariravanian/pacrunner`, `cd pacrunner`, then `python -m pip install -e .`
   (the tests and the tutorial are in the clone, not in the PyPI package).
6. Point PacRunner at the MadGraph7 checkout: `export PACRUNNER_MADGRAPH7=/path/to/MadGraph7`, or
   `pacrunner.configure(madgraph7="/path/to/MadGraph7")` before the first runtime. PacRunner then
   imports MadSpace from `madspace/install-cuda` when it exists and from `madspace/install` otherwise
   (`configure(cuda=False)`: the CPU build), and finds pyAmpliCol in `pyamplicol/install`. Do not put
   these folders on `PYTHONPATH`: a MadSpace imported before PacRunner chooses its build cannot be
   switched (`configure` then fails with "MadSpace is already loaded in this process"). Without
   either setting, PacRunner uses the MadGraph7 an mg7 output was made with, or a `madspace`
   installed in the python.
7. Optional tests, in a clone: `python -m unittest discover -s test/python` (see [Tests](#tests)).
8. Set `export NVCC=path/to/nvcc` (optional, should be needed only if CUDA is installed in a non-standard location).

You also need a C compiler (`cc`, or `CC`), and `nvcc` for the GPU devices.
  
## Quick Start

Before explaining how PacRunner works, let's run a simple example showcasing the interaction 
between pyAmpliCol and MadGraph. 

Start in a scratch folder. First, we generate a process by running

```
pyamplicol generate "u u~ > z g g" artifacts/zgg --color-accuracy lc --emit-api-bundle
```

Now, `artifacts/zgg` is the artifact folder generated by pyAmpliCol for the "u u~ > z g g" process.
In addition, `artifacts/zgg/API/umami/` contains the source for the UMAMI wrapper. However, it is not 
compiled yet. You can compile it as `make -C artifacts/zgg/API/umami/`, but PacRunner will compile it 
on demand if not available. After this command is executed, the compiled UMAMI driver (`libumami.so` 
or `libumami.dylib`) is placed in `artifacts/.pyamplicol-api-build/zgg/umami/`. 

First, let's see how PacRunner's Python API works. The first example does not use PacRunner's
compiler and runs the stock matrix-element generator:

```python
import pacrunner

a = pacrunner.Artifact("artifacts/zgg/")    # a pyAmpliCol artifact
process, momenta = a.validation_points()[0]
batch = momenta[None, :, :]                 # a batch of one event
provider_stock = a.stock()                  # pyAmpliCol's own provider (libumami.so beside the artifact)
rt_stock = provider_stock.runtime()         # a pacrunner.Runtime of its channel 0
print(rt_stock(batch, 0).matrix_element)    # should print [2.43239313e-05]
```

Some terminology: An `Artifact` is the output folder of pyAmpliCol or a sub-process of MadMatrix. 
A `Provider` is a unit of computation and `Runtime` means `madspace.Runtime`. The general program
flow is `Artifact -> Provider -> Runtime`. In the previous example, we used the stock provider. Next
example shows how to generate a CPU provider using PacRunner:

```python
import pacrunner

a = pacrunner.Artifact("artifacts/zgg/")    # a pyAmpliCol artifact
process, momenta = a.validation_points()[0]
batch = momenta[None, :, :]                 # a batch of one event
provider_cpu = a.compile(device="cpu")      # PacRunner's provider on the CPU
rt_cpu = provider_cpu.runtime()             # a pacrunner.Runtime of its channel 0
print(rt_cpu(batch, 0).matrix_element)      # should print [2.43239313e-05]
```

The main change is using `a.compile(device="cpu")` instead of `a.stock()`. This function does the 
following operations:

1. Creating a folder `artifacts/.pacrunner-build/zgg/p0-cpu/`.
2. Exporting the recurrence program using `pyamplicol --export-recurrence` and saving it as `artifacts/.pacrunner-build/zgg/p0-cpu/export.json`.
3. Writing the source files for the CPU provider using `export.json` and the meta data in `artifacts/zgg`.
4. The source files are written to `artifacts/.pacrunner-build/zgg/p0-cpu/programs/0000`.
5. The source folder is compiled to generate `libumami_pac.so`.

We will discuss the files in the source folder below.

The SIMD devices build a faster CPU provider: each program becomes one symjit kernel (PacRunner's library of
the UIR operations in `pacrunner/simd/`, spliced by `codegen/compile_simd.py`), compiled by symjit's JIT for one
instruction set:

| Device | Machine | Events per kernel call (f64 / split) |
|---|---|---|
| `simd-avx2` | x86-64 with AVX2 and FMA | 4 / 8 |
| `simd-avx512` | x86-64 with AVX-512 (F, DQ) | 8 / 16 |
| `simd-neon` | aarch64 (Linux, macOS) | 2 / 4 |

`simd` is this machine's: `simd-avx512` where the CPU has AVX-512, else `simd-avx2`, and `simd-neon` on
aarch64. A SIMD device builds on a machine whose CPU runs it (symjit's JIT compiles the kernels for it), and its
library checks the CPU when it loads. PacRunner writes the machine code as object files (`pacrunner/simd/elf.py`:
an ELF object on x86-64, an assembler file on aarch64; the kernels call no functions, so they need no
relocations) and links them with the UMAMI layer. The values are the `cpu` provider's bit for bit; it needs
nothing beyond symjit and `cc`.

```python
provider_simd = a.compile(device="simd")    # PacRunner's SIMD provider on the CPU
rt_simd = provider_simd.runtime(0)
print(rt_simd(batch, 0).matrix_element)     # should print [2.43239313e-05], as the cpu provider
```

`compile(device="simd", precision="split")` (or the device names `simd-split`, `simd-avx2-split`,
`simd-avx512-split`, `simd-neon-split`) runs each program as two kernels: kernel A in f64 computes what needs
f64 from the momenta (the forms, `1/k²` of the propagators, the sources' wavefunctions, the wide parts of the
model kernels: their denominators `k² − M²`), rounded to f32; kernel B computes the rest (vertices, propagators,
model kernels, amplitudes, the reduction) in f32 at twice the lanes. Kernel B is symjit's f32 twin of its f64
kernel (`dump(.., "simd-f32")`: the machine code rewritten instruction by instruction, symjit >= 2.29.2);
`codegen/compile_split.py` splits the program. The matrix element is within about 1e-6 of f64, and 1.2–1.9×
faster than f64 on x86-64 (more with model kernels and many propagators). The precision's former name, `mixed`,
is accepted on a SIMD device.

`compile(device="cpu-jit")` is the CPU runner made by symjit instead of the C compiler: the SIMD device's kernel
of each program (the application of `simd-avx2` on x86-64, of `simd-neon` on aarch64: the same fragments,
subroutines and chained runs) as symjit's scalar code, one event per kernel call, in the same UMAMI layer. f64,
the `cpu` provider's bits; it builds where a SIMD device does. It runs fewer instructions than the C runner (no
generic `vertex()` and its dispatch) but its code is larger: on a Ryzen 9900X it is 0.8× of `cpu` for small
programs and 1.3× for large ones (`d d~ > z + 5 g`, one flow); on the M4 0.86–0.98× of `cpu`.

For now, let's continue with generating CUDA providers. 
PacRunner currently supports two types of GPU backend: `compile(device="cuda")` and `compile(device="cuda_provider")`
(also called `device="cuda_full"`: everything on the GPU). 

The first one is a hybrid provider, where the UMAMI library identifies itself as a "CPU" provider but actually runs CUDA 
kernels. The second one is a full CUDA provider that identifies itself as "CUDA".

On macOS, `compile(device="metal")` builds the same kind of hybrid provider for an Apple GPU through
Metal; it always computes in mixed precision (f32 and double-f32), since Metal has no f64. For code
that runs on both, `compile(device="gpu")` picks `metal` on macOS and `cuda` elsewhere
(`pacrunner/c/metal/PLAN.md`: the Metal runner, its tests and results).

First, the `cuda` option:

```python
import pacrunner

a = pacrunner.Artifact("artifacts/zgg/")    # a pyAmpliCol artifact
process, momenta = a.validation_points()[0]
batch = momenta[None, :, :]                 # a batch of one event, in host memory
provider_cuda = a.compile(device="cuda")    # PacRunner's provider on the GPU, called from the CPU
rt_cuda = provider_cuda.runtime()           # a pacrunner.Runtime of its channel 0
print(rt_cuda(batch, 0).matrix_element)     # should print [2.43239313e-05]
```

In this example, only the `device` option is changed. The source folder is now `artifacts/.pacrunner-build/zgg/p0-cuda/programs/0000`
and has additional files, which will be discussed below. Next, the `cuda_full` option (an alias of `cuda_provider`):

```python
import pacrunner
import cupy as cp

a = pacrunner.Artifact("artifacts/zgg/")    # a pyAmpliCol artifact
process, momenta = a.validation_points()[0]
batch = cp.array(momenta[None, :, :])       # a batch of one event, in GPU memory
provider_gpu = a.compile(device="cuda_full")   # PacRunner's CUDA provider (alias: "cuda_provider")
rt_gpu = provider_gpu.runtime()             # a pacrunner.Runtime of its channel 0, on a CUDA context
print(rt_gpu(batch, 0).matrix_element)      # should print [2.43239313e-05]
```

Note that for `device="cuda_full"`, we need to pass the momenta wrapped in a CuPy array.

## Devices

The `device` option of `Artifact.compile` (and `--device` of `python -m pacrunner.umami`) chooses where
the matrix elements run. Every device builds UMAMI libraries for MadSpace. All but `cuda_provider`
identify as CPU providers: MadSpace runs on the CPU and calls them with host memory.

| Device | Alias | Needs | Summary |
|---|---|---|---|
| `cpu` | | a C compiler | The program's C, compiled with `cc`; one event per call, f64. The reference build. |
| `cpu-jit` | | x86-64 with AVX2 and FMA, or aarch64 | The SIMD device's kernel as symjit's scalar code, one event per call; f64, the same bits as `cpu`. |
| `simd-avx2` | `simd` (x86-64 without AVX-512) | x86-64 with AVX2 and FMA | One symjit SIMD kernel per program, 4 events per call; the same bits as `cpu`. |
| `simd-avx512` | `simd` (x86-64 with AVX-512) | AVX-512 F and DQ | As `simd-avx2`, 8 events per call. |
| `simd-neon` | `simd` (aarch64) | aarch64, Linux or macOS | As `simd-avx2`, 2 events per call. |
| `simd-avx2-split` | `simd-split` (x86-64 without AVX-512) | as `simd-avx2` | The split kernels: kernel A in f64 (4 events), kernel B in f32 (8 events). Faster than `simd-avx2`, matrix elements to about 1e-6. |
| `simd-avx512-split` | `simd-split` (x86-64 with AVX-512) | as `simd-avx512` | As `simd-avx2-split`, with 8 and 16 events. |
| `simd-neon-split` | `simd-split` (aarch64) | as `simd-neon` | As `simd-avx2-split`, with 2 and 4 events. |
| `cuda` | `gpu` (Linux) | an NVIDIA GPU, `nvcc` | The program on the GPU (the UIR interpreter), called from MadSpace's CPU threads: a hybrid provider. |
| `cuda_provider` | `cuda_full` | an NVIDIA GPU, `nvcc`, MadSpace's CUDA build | A CUDA provider for MadSpace's GPU runtime: everything on the GPU, momenta in GPU memory. MadGraph7 runs need `run.device = ["cuda"]` and `color_accuracy = "lc"`. |
| `metal` | `gpu` (macOS) | an Apple GPU, macOS | The program on the GPU through Metal, called from the CPU: a hybrid provider, always in mixed precision. |

The `precision` option is `f64` (the default) on every device except `metal`, and also:

- `mixed` on the GPU devices: f32 currents (on `metal` always: f32 and double-f32, since Metal has no f64);
- `split` on the SIMD devices: each program as two kernels, one in f64 and one in f32 with twice the
  lanes. `device="simd-avx2", precision="split"` is the same build as `device="simd-avx2-split"`
  (the split devices above).

A SIMD device, or `cpu-jit`, builds only on a machine whose CPU has its instruction set: symjit
compiles the kernels for the CPU it runs on.

## MadMatrix

The previous examples all used the pyAmpliCol directly to generate matrix elements. However, to find the cross-section, we need
Madspace. We start with generating the process:

```
$ mkdir -p processes
mg7> generate u u~ > z g g [amplicol]
mg7> output mg7 processes/zgg
mg7> output mg7 processes/zgg_gpu
```

`processes/` must exist: MadGraph7 creates no parent folders (it fails with a `FileNotFoundError`).
The second output, `processes/zgg_gpu`, is for the end-to-end GPU run below, which needs its own run
card.

We can load the resulting folder using `pacrunner.Output`. Each `Output` has a set of sub-processes,
which can be names using `names` or accessed using `subprocess(name)` or `subprocesses()`. Each
subprocess is a pyAmpliCol artifact with additional metadata. Therefore, we can adopt the same code
as above to generate matrix elements:

```python
import numpy as np
import pacrunner

out = pacrunner.Output("processes/zgg")
a = out.subprocess("A1_uux_zgg")

momenta = np.array([
    [500., 0., 0., 500.],
    [500., 0., 0., -500.],
    [142.22002372, -53.10090083, 59.0409804, -74.87149502],
    [380.350097, -268.20692462, 256.15852034, -84.34485361],
    [477.42987928, 321.30782545, -315.19950074, 159.21634863]])

batch = momenta[None, :, :]                 # a batch of one event
provider_cpu = a.compile(device="cpu")      # PacRunner's provider, at the param card's parameters
rt_cpu = provider_cpu.runtime()             # a pacrunner.Runtime of its channel 0
print(rt_cpu(batch, 0).matrix_element)      # should print [2.43239313e-05]
```

We can use Madspace to calculate a process cross-section:

```python
import pacrunner

out = pacrunner.Output("processes/zgg")
a = out.subprocess("A1_uux_zgg")

# the matrix elements on the GPU, MadSpace on the CPU: the output's default run card works
provider_cuda = a.compile(device="cuda")
print(provider_cuda.run().cross_section)    # should print about 75.3 (pb, ± 0.2: the default card draws a new seed each run)
```

Note that passing `cuda` uses the hybrid mode with a CPU interface; therefore, it works with the
CPU-only build of Madspace and the output's default run card. The default card draws a new random
seed for each run (`seed = -1`), so the cross section differs from run to run within its error (about
0.2 pb here); set `seed` in `Cards/run_card.toml` for a reproducible one.

We can do an end-to-end GPU run by passing `device="cuda_full"` (or its alias `"cuda_provider"`),
assuming Madspace is built for CUDA ([Installation](#installation), step 3). MadSpace then runs on the GPU too, which needs the run card's
`device = ["cuda"]`, and leading colour (`color_accuracy = "lc"`): the full-colour correction is a CPU
library. Hence the second output:

```python
import re
from pathlib import Path
import pacrunner

# everything on the GPU (MadSpace's CUDA build): the run card needs run.device = ["cuda"] and leading
# colour (the full-colour correction is a CPU library), so a second output, processes/zgg_gpu
card = Path("processes/zgg_gpu/Cards/run_card.toml")
text = re.sub(r'(?m)^device = .*$', 'device = ["cuda"]', card.read_text())
text = re.sub(r'(?m)^color_accuracy = .*$', 'color_accuracy = "lc"', text)
card.write_text(text)

out = pacrunner.Output("processes/zgg_gpu")
a = out.subprocess("A1_uux_zgg")
provider_gpu = a.compile(device="cuda_full")    # alias of "cuda_provider"
print(provider_gpu.run().cross_section)    # should print about 94.4 (pb, ± 0.2: leading colour, so above the full-colour 75.3)
```

The leading-colour cross section is larger than the full-colour one (about 94.4 against 75.5 pb for
this process): the colour approximation, not a GPU difference.

## In place of pyAmpliCol's library

PacRunner can also stand in for pyAmpliCol's own UMAMI library, with no change to pyAmpliCol or
MadGraph7: `generate_events` then runs PacRunner's code as if it were pyAmpliCol's.

```sh
python -m pacrunner --replace-lib processes/zgg                  # every [amplicol] subprocess of the output
cd processes/zgg && ./bin/generate_events -f                     # builds and runs PacRunner's library
python -m pacrunner --restore-lib processes/zgg                  # pyAmpliCol's library back
```

or from Python:

```python
import pacrunner

pacrunner.replace_lib("processes/zgg")   # device=None, precision=None, param_card=None,
                                         # parameters=None ({name: value}), force=False
pacrunner.restore_lib("processes/zgg")
```

The path is an mg7 output (every `[amplicol]` subprocess of it) or a single artifact
(`processes/zgg/SubProcesses/A1_uux_zgg/lc`, or one from `pyamplicol generate`). Both return one summary
per artifact (what was built, and the stale library copies deleted); `python -m pacrunner --help` lists the
command line's options.

For each provider of the artifact, `replace_lib` builds a *single library*: every program of the provider in
one `libumami.so`, with the stock library's interface (every channel and flavour, chosen per event). It
identifies itself as the stock library does (a CPU provider, the provider's particles, helicities, colours
and masses), and MadGraph7 calls it with batches of mixed flavours, as it calls the stock one: when a
batch is all one program's, the call goes to that program as it is; otherwise the library groups the
events by program, calls each program on its own, and puts the outputs back in the events' order. In an
mg7 output the programs are exported with MadGraph7's own pyAmpliCol (`pyamplicol/install` of its
checkout), once the output's `check-pyamplicol` accepts it, as for the stock library. Then `replace_lib`
puts the library where the stock one is built:

- the artifact's stock UMAMI bundle (`API/umami`) is kept whole in `API/umami.stock`;
- `API/umami` keeps its `metadata.json`, and its new `Makefile` copies PacRunner's library (in
  `API/umami/pacrunner/<provider>`) to wherever MadGraph7's build expects the stock one;
- the copies of the stock library that MadGraph7 would reuse are deleted, so the next `generate_events`
  copies PacRunner's library in.

`restore_lib` moves `API/umami.stock` back and deletes PacRunner's copies, so the next run rebuilds the
stock library.

Notes:

- Devices: `cpu`, `cpu-jit` and the SIMD devices, f64 or split. The default is the fastest CPU build:
  `simd` (this machine's SIMD device) in split precision, or `cpu` on a machine with none. A precision
  not given is `split` on a SIMD device and `f64` on `cpu` and `cpu-jit`. The GPU devices run through
  `Provider.run` (above).
- `simd` is the building machine's best instruction set (`simd-avx512` where the CPU has AVX-512). The
  library runs only on CPUs with that instruction set: elsewhere it refuses to load and MadGraph7 stops.
  Replace the library on the machines that run the events, or name the device (`--device simd-avx2`).
- Running `replace_lib` again (another device, `--force`) keeps the stock bundle saved the first time.
  If the artifact is generated again, so that `API/umami` is a stock bundle once more, the next
  `replace_lib` saves the new one.
- The library is built at the model parameters of the output's `Cards/param_card.dat` (`--param-card`
  for another card; outside an output, the artifact's defaults) and refuses other values. After you
  change the param card, run `--replace-lib` again.
- The results are the per-program libraries' bit for bit, and so the stock library's. The one exception
  is the helicity sum (a call with neither a helicity index nor a drawn helicity), which agrees with the
  stock library's to about 2e-16. On gg > ggg and pp > jjj (full colour, seed 7), the runs give the
  same events (flavours, colours and helicities) as the stock runs, with cross sections equal to about
  1e-12.
- MadGraph7's ratio library (`lib/libamplicol_<name>_<provider>_ratio.so`, for the full-colour ratio pass)
  stays pyAmpliCol's.
- An event's helicity is drawn from its own random number, so the events are the stock library's
  however the batch is grouped. The per-program route (`Provider.run`) differs there: MadSpace splits each
  batch by flavour, which reassigns the random numbers, so a multi-flavour process (p p > j j j) draws
  other helicities, with the same momenta, flavours and weights.
- `umami_libraries(..., single=True)` (`python -m pacrunner.umami ... --single`) and
  `Artifact.compile(..., single=True)` build a single library on its own; `Provider` runs it like any
  other build.

**Speed and size**: against the per-program libraries (`Provider.run`) on the five benchmark processes
(100k events, the fastest of 3 runs), the single library's wall clock is the same or up to 7% shorter:
for multi-flavour processes MadSpace no longer splits and merges the batches, which saves more than the
library's own grouping costs (0.1–0.3 µs per point). It is also smaller than the per-program libraries
together, which repeat the UMAMI layer in every program:

| Process | Programs | Wall, `cpu` (s): stock / per-program / single | Wall, `simd-split-avx512` (s) | Size, `cpu` (MB): per-program / single |
| --- | ---: | ---: | ---: | ---: |
| `p p > z j j` | 156 | 39.5 / 6.83 / 6.79 | 5.74 / 5.48 | 11.2 / 6.5 |
| `p p > j j j` | 53 | 34.9 / 14.4 / 14.4 | 13.9 / 13.7 | 2.9 / 1.4 |
| `g g > t t~ g g` | 12 | 44.8 / 25.1 / 25.1 | 15.4 / 15.4 | 1.6 / 1.3 |
| `u u~ > z g g g g` | 1 | 95.7 / 44.5 / 45.3 | 16.7 / 16.5 | 0.17 / 0.17 |

Ryzen 9 9900X, 24 threads, pacrunner c28c567, MadGraph7 2079d93; the M4 (`simd-neon`) shows the same, up
to 7% shorter (`p p > z j j`). The scripts: `bench/` (the `single-<device>` variants). pyAmpliCol's stock
library is about 50 MB.

## Benchmarks

The scripts that measure these are in [`bench/`](https://github.com/shahriariravanian/pacrunner/blob/main/bench/README.md): `bench/bench_full.sh` (every CPU, SIMD
and GPU variant this machine runs) and `bench/bench_cpu.sh` (without the GPU), on five processes.

`u u~ > z g g g g`, one MadGraph7 `generate_events` run of 100k events per mode, on three machines.

**Wall clock (s)**

| Mode | Precision | RTX 5060 + Ryzen 9900X | H100 + EPYC 9334 | M4 Mac mini |
| --- | --- | ---: | ---: | ---: |
| stock (pyAmpliCol) | f64 | 95.4 | 126.4 | 129.9 |
| `cpu` | f64 | 44.4 | 48.5 | 58.4 |
| `simd` (AVX-512) | f64 | 21.4 | 25.0 | — |
| `simd` (AVX2) | f64 | 26.0 | 26.7 | — |
| `gpu` (cuda / metal) | f64 | 28.6 | 11.6 | — |
| `gpu` (cuda / metal) | mixed | 15.6 | 11.2 | 24.9 |
| `cuda_full` | f64 | 38.1 | 6.78 | — |
| `cuda_full` | mixed | 15.3 | 5.31 | — |

**Matrix element per point (µs)**: the time inside the matrix-element library per event, summed over
MadSpace's threads.

| Mode | Precision | RTX 5060 + Ryzen 9900X | H100 + EPYC 9334 | M4 Mac mini |
| --- | --- | ---: | ---: | ---: |
| stock (pyAmpliCol) | f64 | 61.6 | 80.9 | 42.0 |
| `cpu` | f64 | 23.6 | 23.3 | 15.7 |
| `simd` (AVX-512) | f64 | 6.50 | 10.2 | — |
| `simd` (AVX2) | f64 | 10.2 | 11.3 | — |
| `gpu` (cuda / metal) | f64 | 15.1 | 0.889 | — |
| `gpu` (cuda / metal) | mixed | 1.08 | 0.550 | 2.54 |
| `cuda_full` | f64 | 1.18\* | 0.158\* | — |
| `cuda_full` | mixed | 0.254\* | 0.091\* | — |

- Wall times: the fastest of 3 untimed runs (RTX 5060, H100); one untimed run after a warm-up (M4).
- `simd`: one symjit kernel per program, 8 events per call with AVX-512 (`simd-avx512`) and 4 with AVX2
  (`simd-avx2`); the `cpu` provider's bits (the events of the two runs are identical). RTX 5060 machine: the fastest
  of 2 runs, measured beside a fresh `cpu` run (44.7 s, 23.6 µs/pt); H100 machine: from the CPU benchmark below.
- `gpu` is CUDA on the RTX 5060 and H100, Metal on the M4 (mixed precision only; no `cuda_full`
  counterpart).
- Per-point times for `gpu` include threads waiting for the shared GPU. \* `cuda_full`: measured
  outside mg7 in synchronized 64k-event batches.
- MadSpace threads: 24 (RTX 5060, H100), 10 (M4). MadGraph7 2079d93; fixed scales, NNPDF23, seed 7,
  64k batches, leading colour.

**The CPU modes on four processes**: stock, `cpu` and `simd`, wall clock (s, the fastest of 3 runs) and the
matrix element per point (µs, as above), 100k events, 24 threads; pacrunner 8dd5aeb, MadGraph7 2079d93.
`simd`'s events are those of `cpu`, bit for bit, in every row.

Ryzen 9 9900X (Zen 5):

| Process | stock | `cpu` | `simd` AVX-512 | `simd` AVX2 | ME stock | ME `cpu` | ME AVX-512 | ME AVX2 |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| `p p > z j j` | 39.8 | 6.72 | 5.58 | 5.76 | 31.5 | 2.62 | 0.831 | 1.07 |
| `p p > j j j` | 34.7 | 14.5 | 13.8 | 14.0 | 17.7 | 1.61 | 0.875 | 1.10 |
| `g g > t t~ g g` (full colour) | 44.1 | 25.5 | 16.2 | 17.4 | 38.1 | 15.6 | 2.95 | 4.34 |
| `u u~ > z g g g g` | 96.3 | 44.0 | 21.2 | 26.0 | 61.4 | 23.5 | 6.47 | 10.2 |

EPYC 9334 (Zen 4, the H100 machine's 24 vCPUs at 2.0 GHz):

| Process | stock | `cpu` | `simd` AVX-512 | `simd` AVX2 | ME stock | ME `cpu` | ME AVX-512 | ME AVX2 |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| `p p > z j j` | 47.1 | 6.18 | 4.62 | 4.65 | 32.2 | 2.90 | 0.993 | 1.08 |
| `p p > j j j` | 35.1 | 8.83 | 7.52 | 7.65 | 18.1 | 1.67 | 0.902 | 0.921 |
| `g g > t t~ g g` (full colour) | 64.0 | 35.9 | 25.4 | 25.5 | 53.4 | 20.6 | 5.44 | 5.98 |
| `u u~ > z g g g g` | 124.3 | 48.8 | 25.0 | 26.7 | 79.6 | 24.7 | 10.2 | 11.3 |

- `simd` gains most where the matrix element dominates (`g g > t t~ g g`, `u u~ > z g g g g`: 1.4–2.1× the
  wall of `cpu`); for the light processes MadSpace's own work is most of the wall.
- Zen 4 runs 512-bit vectors as two 256-bit halves: AVX2 is within 1–10% of AVX-512 there, against
  up to 1.6× slower on Zen 5.

## pyAmpliCol 1.0.x: RustiCol's recurrence export

pyAmpliCol 1.0.x writes an LC artifact's programs itself: `pyamplicol export-recurrence LC_DIR -o
capture.json`; the format is its `docs/reference/recurrence-export.md`). 

## The compiled folder

| File | What it is |
| --- | --- |
| `runner.c` | the program: `int run(double *out, double *p, const double *momenta)` for one point |
| `runner.h` | its prototype and sizes: `RUNNER_LEGS`, `RUNNER_OUTPUTS`, `RUNNER_ARENA_SIZE` (the scratch `p`) |
| `pacops.c`, `pacops.h` | the sources and instructions |
| `Makefile` | `make` (`runner.o`, `pacops.o`, `testing`), `make clean`; `CC`, `CFLAGS` may be set |

With `interpreter=True`, `runner.c` holds the program as data (the encoded words, sources first, the
edge table and the tables they index, as one `uir_program`) and includes `uirvm.c`, the UIR
interpreter, copied next to it with `uirvm.h`. `run()`, `runner.h` and the values are the same, bit
for bit. The straight-line C is the CPU runner (about twice as fast); the interpreter is the GPU's,
and its CPU build is its test. The interpreter reads each row's fields straight from its word (the
`UIR_` macros of `uirvm.h`) and takes one-word rows only: a program with a wide row (an index beyond
the one-word fields) is refused.

The interpreter's `runner.c` also builds with nvcc: `make gpu` gives `runner_gpu.o` with
`int run_gpu(double *out, const double *momenta, size_t points)` (`uirvm.h`), every point on the GPU,
one thread each, momenta and outputs point by point on the host. Every function of `pacops`, `uirvm`
and the kernels is then a device function too (`PAC_FN`), and the tables are `__device__` data
(`UIR_DATA`). The outputs are the CPU build's bit for bit (`--fmad=false`, as `-ffp-contract=off`).

## Building libraries directly

`Artifact.compile` and `SubProcess.compile` export the programs and build the libraries for you. To
build from a recurrence export you already have, call `pacrunner.umami.umami_libraries`, or run it
from the command line (e.g. from another Python, such as MadGraph7's):

```sh
python -m pacrunner.umami EXPORT.json ARTIFACT/API/umami/metadata.json OUT --device cpu
python -m pacrunner.umami EXPORT.json METADATA OUT --device cuda_provider --precision mixed --cuda-arch sm_90
```

`OUT/umami_pac.json` then lists the libraries and each channel's flavours, for MadSpace;
`python -m pacrunner.umami --help` lists the options. Beneath it are the modules `pacrunner.uir` (the
export read into UIR programs, the passes, the 8-byte encoding), `pacrunner.kernels` (the symjit
kernels' MIR and their C) and `pacrunner.codegen` (a program as a compiled folder):

```python
from pacrunner import codegen, uir

programs = uir.load_recurrence_export("export.json")     # one uir.Lowered per program
codegen.compile("folder", uir.optimize(programs[0]))      # runner.c, runner.h, pacops.c, Makefile
```

Indices are 0-based throughout, and an absent one is `None`.

## Tests

```sh
python -m unittest discover -s test/python
```

Without external tools this checks the export reader, the passes, the encoding, the kernels' C and the
compiled folders against pac-julia's outputs (`test/data/goldens`, byte for byte), and, with a C
compiler, that the fixture's compiled folders pass `make test` (RustiCol's reference values, bit for
bit).
The kernels' tests need symjit ≥ 2.29. The larger golden corpus (`tools/goldens`) is used when it is
at `PACRUNNER_GOLDENS` (default `~/symjit-data/pacrunner-goldens`). More tests run when their tools are
set:

| Variable | What it enables |
| --- | --- |
| `PACRUNNER_MADGRAPH7` | a MadGraph7 checkout with MadSpace: the runtime tests |
| `PACRUNNER_TEST_ARTIFACT`, `PACRUNNER_PYAMPLICOL` | an LC artifact and the pyAmpliCol that made it: export and compile |
| `PACRUNNER_TEST_MG7_OUTPUT`, `PACRUNNER_TEST_CUDA_OUTPUT`, `PACRUNNER_TEST_MG7_MULTI` | mg7 outputs: end-to-end runs against stock |
| `PACRUNNER_TEST_TUTORIAL=1` | the tutorial's snippets (`tutorial/`), about 3 minutes |

Symbolica (pyAmpliCol) needs a writable `XDG_RUNTIME_DIR`. The scripts in `test/` (`umami_check.py`,
`umami_check_gpu.py`, `test_libraries.py`, `mg7_run.py`, ...) compare built libraries against
pyAmpliCol's stock ones through MadSpace; each says how to run it.

The C must be built with `-ffp-contract=off` (nvcc: `--fmad=false`): the values are bit for bit only
without contracted multiply-adds.
