Skip to content
QFT.org

Search QFT.org

Enter a word or phrase.

    You can also browse the main navigation and chapter contents.

    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

    εˉ=ε−kp⋅εp⋅k,fˉ=f−k′p⋅fp⋅k′,Me2=2εˉ⋅fˉ.\bar\varepsilon=\varepsilon-k\frac{p\cdot\varepsilon}{p\cdot k}, \qquad \bar f=f-k'\frac{p\cdot f}{p\cdot k'},\qquad \frac{\mathcal M}{e^2}=2\bar\varepsilon\cdot\bar f.

    Here f=ε′∗f=\varepsilon'^*, p+k=p′+k′p+k=p'+k', both scalar momenta have mass m>0m>0, 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 (p,k,k′,ε,ε′)(p,k,k',\varepsilon,\varepsilon'), each in the order (v+,v−,vx,vy)(v^+,v^-,v_x,v_y), where v±=v0±v3v^\pm=v^0\pm v^3. The output is the dimensionless M/e2\mathcal M/e^2 in four-dimensional scalar QED. For these real polarizations, f=ε′f=\varepsilon'. 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 NN events, the input is a contiguous array of shape (N,20)(N,20) and the output has shape (N,)(N,). 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 p⋅k,p⋅k′p\cdot k,p\cdot k'. 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 p⋅ε/(p⋅k)p\cdot\varepsilon/(p\cdot k) and p⋅f/(p⋅k′)p\cdot f/(p\cdot k'). 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 pp; 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 M/e2\mathcal M/e^2 are:

    ImplementationLargest absolute error
    Readable NumPy reference1.2×10−151.2\times10^{-15}
    Generated NumPy, plain1.8×10−151.8\times10^{-15}
    Generated NumPy, CSE1.2×10−151.2\times10^{-15}
    Compiled C, plain1.8×10−151.8\times10^{-15}
    Compiled C, CSE1.2×10−151.2\times10^{-15}

    All five also pass the ten fixed boost/soft diagnostics when given the retained light-cone inputs, with maximum error below 5×10−165\times10^{-16} relative to the binary64 value of −1.2-1.2. The higher-precision physical-error convention in the previous article instead compares against the exact rational −6/5-6/5; 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:

    ImplementationMedian time (ms)Range (ms)
    Readable NumPy reference4.8864.8864.8564.856–6.0816.081
    Generated NumPy, plain11.22511.22511.15411.154–12.08712.087
    Generated NumPy, CSE3.5273.5273.4643.464–3.7863.786
    Compiled C, plain0.2830.2830.2820.282–0.2870.287
    Compiled C, CSE0.2690.2690.2650.265–0.3170.317

    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 F=(x+y)2+(x+y)3F=(x+y)^2+(x+y)^3, a generator returns t0=x+yt_0=x+y, t1=t02t_1=t_0^2, F=t1(1+t0)F=t_1(1+t_0). Give the dependency order and verify the result. A proposed optimization changes t1t_1 to x2+y2x^2+y^2. Derive the resulting error and give a decisive test point.

    Solution

    Assign t0t_0 before t1t_1, and both before FF. Substituting t1t_1 and then t0t_0 gives (x+y)2(1+x+y)(x+y)^2(1+x+y), the original polynomial. The replacement omits 2xy2xy from t1t_1, so the changed output minus the correct output is −2xy(1+x+y)-2xy(1+x+y). At x=y=1x=y=1, the correct answer is 1212 and the changed answer is 66. Tests restricted to x=0x=0 or y=0y=0 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 MijM_{ij} denote the amplitude for real incoming basis vector eie_i and real outgoing basis vector fjf_j, with i,j=1,2i,j=1,2. Derive the amplitude for incoming (e1+ie2)/2(e_1+ie_2)/\sqrt2 and outgoing (f1+if2)/2(f_1+if_2)/\sqrt2. Evaluate it for the rest-frame scalar basis and explain how to test a vanishing opposite-helicity amplitude at θ=0\theta=0.

    Solution

    The outgoing vector is conjugated in the amplitude. Bilinearity therefore gives

    M++=12(M11−iM12+iM21+M22).M_{++}=\frac12(M_{11}-iM_{12}+iM_{21}+M_{22}).

    For the planar scalar basis, M11=−2e2cos⁡θM_{11}=-2e^2\cos\theta, M22=−2e2M_{22}=-2e^2 and M12=M21=0M_{12}=M_{21}=0. Thus M++=−e2(1+cos⁡θ)M_{++}=-e^2(1+\cos\theta). Changing the outgoing helicity gives M+−=e2(1−cos⁡θ)M_{+-}=e^2(1-\cos\theta). At θ=0\theta=0 the latter is zero; dividing its numerical error by the exact answer is undefined. Test an absolute error in units of e2e^2, together with nonzero nearby cases. Near that forward zero, 1−cos⁡θ=2sin⁡2(θ/2)1-\cos\theta=2\sin^2(\theta/2) 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.