- Home
- Library
- Computational Quantum Field Theory
- From a Lagrangian to Executable Amplitudes
- Generating Fast Numerical Amplitude Code
Generating Fast Numerical Amplitude Code
A validated amplitude is not yet a useful numerical kernel. Its arguments must have a fixed order, its complex conjugations and units must survive translation, and the generated code must be tested on the same inputs as a readable reference. Only then does a timing comparison answer a meaningful question.
We compile the stabilized scalar-Compton amplitude. This small example makes the entire path inspectable: physical expression, dependency graph, C and NumPy code, numerical checks, and measured warm evaluation. It is a finite tree-level kernel, not a general event generator.
State the numerical interface before generating code
For physical scalar Compton kinematics, put
Here , , both scalar momenta have mass , and the photons are nonzero future null vectors with transverse polarizations. The tensor derivation supplies the Ward identities that justify this form. The fast function does not infer those physical conditions from an arbitrary list of numbers.
The compiled interface accepts real linear polarizations. Each row contains 20 binary64 numbers: the five vectors , each in the order , where . The output is the dimensionless in four-dimensional scalar QED. For these real polarizations, . General complex polarizations can be reconstructed from real basis amplitudes, as in Exercise 2; the readable Python reference also performs the outgoing conjugation directly.
For events, the input is a contiguous array of shape and the output has shape . The input and output buffers are distinct. Before a batch enters a fast loop, its caller must establish the layout, finite components, physical domain and nonzero . A denominator that vanishes because of an invalid event or corrupted representation should not be silently replaced by a small arbitrary number.
The portable reference computes the two projections and their light-cone dot product directly. It is kept alongside the generated routines. The diagram expression is a further independent algebraic representation for checking ordinary kinematics; it is deliberately not used as a double-precision oracle at the ill-conditioned points of the preceding article.
A dependency graph, not a shorter printed formula
The scalar expression repeatedly uses and . CSE introduces temporaries so those values are evaluated once. Conceptually, the generated computation is:
r_in = dot(p, epsilon) / dot(p, k)
r_out = dot(p, epsilon_out) / dot(p, kprime)
epsilon_bar = epsilon - r_in * k
out_bar = epsilon_out - r_out * kprime
amplitude = 2 * dot(epsilon_bar, out_bar)
Every temporary must be assigned after its dependencies. Renaming a temporary is harmless; changing its definition or evaluation domain is not. The retained generator re-expands the CSE assignments in reverse dependency order and checks exact equality to the original symbolic expression.
In this example, SymPy's operation count decreases from 177 to 57 with four temporaries. Two temporaries are half-components of ; the other two are the projection ratios. This is a count of operations in the symbolic expression, not a count of processor instructions and not a predicted speedup. Compilers can perform their own CSE even when source-level CSE is disabled. Conversely, a vectorized temporary may be an entire array whose allocation and memory traffic have a cost.
SymPy distinguishes a code printer, which emits an expression, from a code generator that produces a routine with arguments and outputs. Its CCodeGen interface exposes the CSE choice and argument ordering: Codegen documentation, Routine and CCodeGen. The example uses an explicit argument sequence; alphabetical sorting is not allowed to silently define the numerical interface.
Generate and actually compile
The generator constructs its expression from local symbols, then requests plain and CSE versions:
from sympy.utilities.codegen import CCodeGen
generator = CCodeGen(cse=True)
routine = generator.routine(
"scalar_projected_cse",
expression,
argument_sequence=ordered_components,
)
files = generator.write(
[routine], "scalar_projected_cse", header=False,
)
It writes complete C sources and headers and adds a batch loop that calls the scalar routine for each row. A single Python-to-C call then handles the full batch. The C routine reads its inputs and fills a separately allocated output; it does not retain a pointer for later use.
The recorded compilation uses Apple Clang 21, C99 and optimization level
-O3, with floating-point contraction disabled and without fast-math.
The driver selects the shared-library flags for macOS or a Unix-like host and
loads the resulting library through ctypes. The generated source and its
Python generator are retained; the binary library is a disposable build
output. If no C compiler is available, the driver reports that compiled checks
are unavailable while keeping the NumPy reference usable.
For NumPy, the same symbolic expression is translated with lambdify using CSE either off or on. Generation takes time too: precomputing subexpressions can reduce evaluation cost while increasing construction cost. The actual lambdify documentation also explains how to inspect the generated function. Only the locally constructed trusted expression is passed to this code-producing interface.
Reproduce generation, compilation, correctness checks and the optional local timing measurement with:
python3 examples/computational-qft/symbolic-computation/scalar_codegen.py --timing
The driver puts disposable compiled outputs under
build/scientific/symbolic-computation. Adding the explicit
--write option refreshes the retained C sources, headers and
scalar-codegen-results.json. The pure scalar_compton.py reference has no
import-time compilation or file writes.
Correctness before throughput
The test grid has 256 polarized events: four rest-frame photon energies, four scattering angles, two frames, two gauge choices and four real polarization pairs. Against the analytic rest-frame amplitudes, the maximum absolute errors in are:
| Implementation | Largest absolute error |
|---|---|
| Readable NumPy reference | |
| Generated NumPy, plain | |
| Generated NumPy, CSE | |
| Compiled C, plain | |
| Compiled C, CSE |
All five also pass the ten fixed boost/soft diagnostics when given the retained light-cone inputs, with maximum error below relative to the binary64 value of . The higher-precision physical-error convention in the previous article instead compares against the exact rational ; those two last-digit error definitions should not be conflated.
Exact CSE re-expansion tests the symbolic transformation. The compiled and NumPy comparisons test translation and calling conventions. Neither replaces the independently derived Ward and mass-shell checks. In particular, compiling an incorrectly signed seagull efficiently would still give incorrect physics.
Measure the actual workload
For a reproducible warm-throughput experiment, the same 256-event grid is tiled to 65,536 rows. There are three warmups followed by seven timed calls for each implementation. Every path receives identical binary64 input; outputs are checked and consumed. Timing includes output allocation and Python/ctypes dispatch, but excludes symbolic generation, compilation, input construction and correctness checks.
The retained measurement on an arm64 macOS host gives:
| Implementation | Median time (ms) | Range (ms) |
|---|---|---|
| Readable NumPy reference | – | |
| Generated NumPy, plain | – | |
| Generated NumPy, CSE | – | |
| Compiled C, plain | – | |
| Compiled C, CSE | – |
These are local measurements, not portable performance constants. The compiled plain and CSE ranges overlap; the result does not establish that manual CSE always improves optimized C. The much larger difference between the two generated NumPy paths reflects their actual array evaluation, and the readable reference remains competitive with generated NumPy.
The input occupies 10 MiB and the output 0.5 MiB. Four named NumPy CSE temporaries account for another 2 MiB; intermediate arithmetic can allocate additional arrays, so this is not a peak-memory measurement. In compiled scalar evaluation the temporaries are scalar values per event, not four full-batch arrays. The retained output records Python 3.9.6, NumPy 2.0.2, SymPy 1.14.0, compiler flags and machine details. No GPU, threading or automatic vectorization speedup is inferred from these timings.
Summary
Generate code from a validated expression with a fixed interface. Preserve the readable reference, verify CSE by exact re-expansion, check compiled outputs on ordinary and difficult inputs, and time equal workloads only after correctness. Operation counts explain a transformation; measured runtime and memory behavior decide whether it helps a particular application.
Exercises
1. Restore a CSE dependency
For , a generator returns , , . Give the dependency order and verify the result. A proposed optimization changes to . Derive the resulting error and give a decisive test point.
Solution
Assign before , and both before . Substituting and then gives , the original polynomial. The replacement omits from , so the changed output minus the correct output is . At , the correct answer is and the changed answer is . Tests restricted to or would miss the error. This illustrates why a set of unused, nondegenerate check points complements the exact symbolic comparison.
2. Recover complex polarizations from a real kernel
Let denote the amplitude for real incoming basis vector and real outgoing basis vector , with . Derive the amplitude for incoming and outgoing . Evaluate it for the rest-frame scalar basis and explain how to test a vanishing opposite-helicity amplitude at .
Solution
The outgoing vector is conjugated in the amplitude. Bilinearity therefore gives
For the planar scalar basis, , and . Thus . Changing the outgoing helicity gives . At the latter is zero; dividing its numerical error by the exact answer is undefined. Test an absolute error in units of , together with nonzero nearby cases. Near that forward zero, can preserve a small value more accurately. This extra algebraic choice is distinct from CSE and does not follow merely from compiling the real basis evaluator.
References
- D. Goldberg, “What Every Computer Scientist Should Know About Floating-Point Arithmetic,” ACM Computing Surveys 23 (1991), 5–48; authorized edited reprint, section “Cancellation.”
- SymPy 1.14 documentation, Codegen, Routine, CCodeGen, argument_sequence and write: complete routine generation.
- SymPy 1.14 documentation, Lambdify, CSE option, numerical namespaces and source inspection: numerical function generation.
Scrollable formula. Use Left and Right arrow keys to reveal hidden content.
Scrollable table. Use Left and Right arrow keys to reveal hidden columns.
Scrollable figure. Use Left and Right arrow keys to reveal hidden content.