From d2aa138a5ca3958abefc31eba43ca7d43a6a07e5 Mon Sep 17 00:00:00 2001 From: Olivier Mattelaer Date: Thu, 19 Nov 2026 23:18:04 +0100 Subject: [PATCH 1/7] Make denom64 (FPTYPE=v) the default precision, add an mg7 precision check - madmatrix.mk, the mg7 run card (precision = "denom64"), the madevent floating_type and the MadtRex fallbacks now default to v (momenta and propagator denominators in FP64, amplitudes and colour in FP32). MadSpin's density libraries stay pinned to m. - The object directory is build._: two FPTYPEs of one backend can coexist, and changing [run] precision between two runs of one output no longer fails with "Cannot build for tag". - [run] precision_check (default 0.01): an mg7 run in a precision other than all64 also builds an FPTYPE=d library of each MadMatrix subprocess and, once the events are written, evaluates a sample of them in both precisions (UMAMI through ctypes, one process per FPTYPE). Mean, |M|^2-weighted and max relative deviation are logged and written to Events//precision_check.json; it warns above precision_check_threshold (1e-3) or on non-finite values. - Tests: unit tests for the defaults, the statistics and the event to library/flavour mapping; acceptance tests for a real run, the side by side builds, a precision change without make clean, and that the check reproduces the |M|^2 madspace computed in the run. Registered in CI. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/acceptancetest_mg7.yml | 11 + .github/workflows/unittest.yml | 2 +- .../madspace/examples/matrix-element.rst | 2 +- docs/source/run_card.rst | 17 +- docs/source/standalone.rst | 8 +- .../template_files/madmatrix/madmatrix.mk | 15 +- .../template_files/madmatrix/madmatrix_src.mk | 4 +- .../madmatrix/madmatrix_standalone.mk | 7 +- .../template_files/mg7/madtrex_driver.py | 2 +- .../template_files/mg7/param_reweight_card.py | 2 +- .../iolibs/template_files/mg7/run_card.toml | 2 + madgraph/mg7/madgraph_process.py | 80 +++- madgraph/mg7/precision_check.py | 386 ++++++++++++++++++ madgraph/various/banner.py | 10 +- madmatrix/density.py | 5 +- madmatrix/launch_plugin.py | 4 +- madmatrix/output.py | 2 +- .../test_mg7_precision_check.py | 211 ++++++++++ .../interface/test_mg7_precision_check.py | 179 ++++++++ tests/unit_tests/madevent/test_hel_recycle.py | 16 +- 20 files changed, 925 insertions(+), 40 deletions(-) create mode 100644 madgraph/mg7/precision_check.py create mode 100644 tests/acceptance_tests/test_mg7_precision_check.py create mode 100644 tests/unit_tests/interface/test_mg7_precision_check.py diff --git a/.github/workflows/acceptancetest_mg7.yml b/.github/workflows/acceptancetest_mg7.yml index 8fe9b74b7a..311d7789d6 100644 --- a/.github/workflows/acceptancetest_mg7.yml +++ b/.github/workflows/acceptancetest_mg7.yml @@ -658,6 +658,17 @@ jobs: cd $GITHUB_WORKSPACE ./tests/test_manager.py test_madmatrix_mssm_gogo -pA -t0 -l INFO + # ---- acceptancetest_mg7_precision_check ---- + # The default precision denom64 (FPTYPE=v) and [run] precision_check: a + # fraction of the events evaluated again with an all64 (FPTYPE=d) build, + # the two built side by side; the check reproduces the |M|^2 of the run. + # Needs the madspace + LHAPDF(NNPDF23) stack. + - name: "acceptancetest_mg7_precision_check" + if: ${{ !cancelled() }} + run: | + cd $GITHUB_WORKSPACE + ./tests/test_manager.py test_precision_check_mg7 test_precision_check_reproduces_the_run_mg7 -pA -t0 -l INFO + acceptancetest_mg7_madtrex: needs: build_madspace # MadtRex (madtrex/, 'install madtrex'): built on top of the cached madspace diff --git a/.github/workflows/unittest.yml b/.github/workflows/unittest.yml index a7debac77f..30d851f8ef 100644 --- a/.github/workflows/unittest.yml +++ b/.github/workflows/unittest.yml @@ -605,7 +605,7 @@ jobs: if: ${{ !cancelled() }} run: | cd $GITHUB_WORKSPACE - ./tests/test_manager.py test_default_switch test_history_recording test_interference_syntax test_mg7_systematics_summary test_reweight_card_input test_tutorials TestNoFileOutsideOutputDir CheckDisplayWithoutProcessTest DisplayInertCouplingOrderTest NeglectedMassAdviceTest RequiredSChannelErrorTest TestHepToolsInstallTarget test_display_processes TestDelphesFusion TestLhapdfInfoPatch TestSharedPdfsetsDir test_generate_propagator_only_polarisation test_propagator_polarisation_round_trip test_dynamical_scale_choice_ht TestAutomaticGauge TestAutomaticGaugeOutput TestProcessGauge TestProcessGaugeOutput TestProcCardOneGauge TestGaugeHelpers test_save_and_load_processes_are_refused -e TestOneImplementation -e TestRealRunNumbers -t0 + ./tests/test_manager.py test_default_switch test_history_recording test_interference_syntax test_mg7_systematics_summary TestPrecisionDefault TestSummarize TestFlavorTable test_reweight_card_input test_tutorials TestNoFileOutsideOutputDir CheckDisplayWithoutProcessTest DisplayInertCouplingOrderTest NeglectedMassAdviceTest RequiredSChannelErrorTest TestHepToolsInstallTarget test_display_processes TestDelphesFusion TestLhapdfInfoPatch TestSharedPdfsetsDir test_generate_propagator_only_polarisation test_propagator_polarisation_round_trip test_dynamical_scale_choice_ht TestAutomaticGauge TestAutomaticGaugeOutput TestProcessGauge TestProcessGaugeOutput TestProcCardOneGauge TestGaugeHelpers test_save_and_load_processes_are_refused -e TestOneImplementation -e TestRealRunNumbers -t0 - name: "unittest_iolibs_uncovered" if: ${{ !cancelled() }} diff --git a/docs/source/madspace/examples/matrix-element.rst b/docs/source/madspace/examples/matrix-element.rst index c4a53d92ef..3a68857b3e 100644 --- a/docs/source/madspace/examples/matrix-element.rst +++ b/docs/source/madspace/examples/matrix-element.rst @@ -47,7 +47,7 @@ Loading the matrix element The library name also appears, alongside every other subprocess of the process, in ``PROC_ggttg/SubProcesses/subprocesses.json``, as ``me_path`` with a ``{device}`` placeholder for the backend and an ``{fptype}`` placeholder for the floating-point precision the library -was compiled with (``FPTYPE``, ``m`` by default). The model name (``sm``) is part of the +was compiled with (``FPTYPE``, ``v`` by default). The model name (``sm``) is part of the library name too. :py:meth:`Context.load_matrix_element ` returns a diff --git a/docs/source/run_card.rst b/docs/source/run_card.rst index bcbc132dfe..0c1184f403 100644 --- a/docs/source/run_card.rst +++ b/docs/source/run_card.rst @@ -55,11 +55,22 @@ fixed parameters. Their entries are described below. ``auto`` picks ``simd_512``, then ``simd_256`` on x86. On ARM it picks ``scalar``, because the vectorized mode is currently slower there. -``precision`` (``"color32"``) +``precision`` (``"denom64"``) Floating-point precision of the matrix elements. ``all64`` and ``all32`` use double and single precision throughout. ``color32`` evaluates the color algebra in single precision - and everything else in double precision. ``denom64`` keeps the momenta and propagator - denominators in double precision and uses single precision elsewhere. + and everything else in double precision. ``denom64``, the default, keeps the momenta and + propagator denominators in double precision and uses single precision elsewhere. + +``precision_check`` (``0.01``) + Fraction of the events evaluated again with the matrix elements in ``all64``, to check + the precision of a run in any other precision. The run then also builds an ``all64`` + CPU library of each subprocess and, once the events are written, compares the two at + the momenta of the first events of the output (at most 1000 of them, hidden entry + ``precision_check_max_events``). The mean, ``|M|^2``-weighted and maximal relative + deviations are logged and written to ``Events//precision_check.json``; the run + warns when an event deviates by more than ``1e-3`` (hidden entry + ``precision_check_threshold``) or is not finite, in which case ``all64`` or ``color32`` + is the safer choice for that process. ``0`` disables the check, and the extra build. ``cpu_thread_pool_size`` (``-1``), ``gpu_thread_pool_size`` (``1``), ``combine_thread_pool_size`` (``-1``) diff --git a/docs/source/standalone.rst b/docs/source/standalone.rst index 0bd83ff99b..ed52a3d8ba 100644 --- a/docs/source/standalone.rst +++ b/docs/source/standalone.rst @@ -21,7 +21,7 @@ In a ``P1_*`` directory, ``make`` builds the process library and ``check_sa.exe` Two variables select the build; they are part of the library name, so several builds coexist:: - make BACKEND=auto FPTYPE=m # the defaults + make BACKEND=auto FPTYPE=v # the defaults make BACKEND=simd_256 FPTYPE=d -j8 ``BACKEND`` @@ -30,9 +30,9 @@ builds coexist:: on Apple silicon). The resolved choice is written to ``.resolved-backend``. ``FPTYPE`` - ``d`` (double precision everywhere), ``f`` (single), ``m`` (the default: - amplitudes in double precision, colour algebra in single precision), ``v`` - (single-precision amplitudes with double-precision momenta and denominators), + ``d`` (double precision everywhere), ``f`` (single), ``m`` (amplitudes in + double precision, colour algebra in single precision), ``v`` (the default: + single-precision amplitudes with double-precision momenta and denominators), ``e`` (double-word expansion). Compare them with ``check precision``. The flags are ``-O3 -std=c++20 -ffast-math`` (``OPTFLAGS`` for the optimisation diff --git a/madgraph/iolibs/template_files/madmatrix/madmatrix.mk b/madgraph/iolibs/template_files/madmatrix/madmatrix.mk index b723350f14..cef031149a 100644 --- a/madgraph/iolibs/template_files/madmatrix/madmatrix.mk +++ b/madgraph/iolibs/template_files/madmatrix/madmatrix.mk @@ -17,8 +17,10 @@ endif ifeq ($(FPTYPE),) # OLD DEFAULT UP TO v1.00.00 INCLUDED (inconsistent with default floating_type='m' in run_card.dat) ###override FPTYPE = d - # NEW DEFAULT (#995) AS OF v1.00.01 (now consistent with default floating_type='m' in run_card.dat) - override FPTYPE = m + # DEFAULT (#995) FROM v1.00.01: FPTYPE = m (color32) + # DEFAULT AS OF MG7: FPTYPE = v (denom64), consistent with the default precision='denom64' of + # run_card.toml and floating_type='denom64' of run_card.dat + override FPTYPE = v endif # Set the default HELINL (inline helicities?) choice @@ -73,10 +75,13 @@ endif #=== Configure MADMATRIX_BUILDDIR -# Build directory: build. by default (USEBUILDDIR=1), or current directory if USEBUILDDIR=0 +# Build directory: build._ by default (USEBUILDDIR=1), or current directory if USEBUILDDIR=0 # NB: using '=' (not ':=') ensures BACKEND is evaluated lazily after the potential 'auto' resolution +# NB: FPTYPE is part of the name, as it is of the library names: several FPTYPEs of one +# backend coexist (an mg7 run with [run] precision_check builds its FPTYPE and FPTYPE=d), +# and a change of FPTYPE needs no 'make clean' ifeq ($(USEBUILDDIR),1) - override MADMATRIX_BUILDDIR = build.$(BACKEND) + override MADMATRIX_BUILDDIR = build.$(BACKEND)_$(FPTYPE) else override MADMATRIX_BUILDDIR = . endif @@ -768,7 +773,7 @@ override TAG = $(BACKEND)_$(FPTYPE)_inl$(HELINL) # Export TAG (so that there is no need to check/define it again in src/Makefile) export TAG -# Build directory for object files: build. by default, or current directory if USEBUILDDIR=0 +# Build directory for object files: build._ by default, or current directory if USEBUILDDIR=0 override BUILDDIR = $(MADMATRIX_BUILDDIR) ###override INCDIR = ../../include diff --git a/madgraph/iolibs/template_files/madmatrix/madmatrix_src.mk b/madgraph/iolibs/template_files/madmatrix/madmatrix_src.mk index 97fdcbc492..906d594a96 100644 --- a/madgraph/iolibs/template_files/madmatrix/madmatrix_src.mk +++ b/madgraph/iolibs/template_files/madmatrix/madmatrix_src.mk @@ -47,7 +47,7 @@ endif # Use the build lockfile "full" tag exported from the subprocess Makefile ###$(info TAG=$(TAG)) -# Build directory for object files: current directory by default, or build. if USEBUILDDIR==1 +# Build directory for object files: current directory by default, or build._ if USEBUILDDIR==1 ###$(info Current directory is $(shell pwd)) override BUILDDIR = $(MADMATRIX_BUILDDIR) @@ -106,7 +106,7 @@ $(BUILDDIR)/.build.$(TAG): #------------------------------------------------------------------------------- # Generic target and build rules: objects from C++ or CUDA/HIP compilation. -# Plain .o suffix — the BUILDDIR (e.g. build.simd_256/) provides backend separation. +# Plain .o suffix — the BUILDDIR (e.g. build.simd_256_v/) provides backend and FPTYPE separation. # Use USEBUILDDIR=1 to build for multiple backends simultaneously without cleaning. ifeq ($(GPUCC),) $(BUILDDIR)/%%.o : %%.cc *.h $(BUILDDIR)/.build.$(TAG) diff --git a/madgraph/iolibs/template_files/madmatrix/madmatrix_standalone.mk b/madgraph/iolibs/template_files/madmatrix/madmatrix_standalone.mk index c0536e0b89..f44fffdf96 100644 --- a/madgraph/iolibs/template_files/madmatrix/madmatrix_standalone.mk +++ b/madgraph/iolibs/template_files/madmatrix/madmatrix_standalone.mk @@ -25,12 +25,13 @@ override standalone_objects = $(BUILDDIR)/RamboSamplingKernels.o \ $(BUILDDIR)/CommonRandomNumberKernel.o \ $(BUILDDIR)/check_sa.o -# force relink when changing to before compiled backend +# force relink when changing to a before compiled backend or FPTYPE (each has its own +# build directory, whose objects can then be older than check_sa.exe) CHECK_SA_BACKEND_MARKER = .check_sa_backend check_sa.exe: $(CHECK_SA_BACKEND_MARKER) $(CHECK_SA_BACKEND_MARKER): FORCE - @if [ ! -f $(CHECK_SA_BACKEND_MARKER) ] || [ "$$(cat $(CHECK_SA_BACKEND_MARKER) 2>/dev/null)" != "$(BACKEND)" ]; then \ - echo $(BACKEND) > $(CHECK_SA_BACKEND_MARKER); \ + @if [ ! -f $(CHECK_SA_BACKEND_MARKER) ] || [ "$$(cat $(CHECK_SA_BACKEND_MARKER) 2>/dev/null)" != "$(BACKEND)_$(FPTYPE)" ]; then \ + echo $(BACKEND)_$(FPTYPE) > $(CHECK_SA_BACKEND_MARKER); \ fi .PHONY: FORCE FORCE: diff --git a/madgraph/iolibs/template_files/mg7/madtrex_driver.py b/madgraph/iolibs/template_files/mg7/madtrex_driver.py index fdb0d7a596..b141a389e0 100644 --- a/madgraph/iolibs/template_files/mg7/madtrex_driver.py +++ b/madgraph/iolibs/template_files/mg7/madtrex_driver.py @@ -342,7 +342,7 @@ def default_output_path(events_path: str) -> str: # reweighting doesn't need MadGraph's card machinery. MadGraph always writes # every entry out, so these only matter for hand-written cards. _RUN_CARD_DEFAULTS = { - "run": {"device": ["cpu"], "cpu_mode": "auto", "precision": "color32"}, + "run": {"device": ["cpu"], "cpu_mode": "auto", "precision": "denom64"}, "beam": { "leptonic": False, "pdf1": "NNPDF40_lo_as_01180", diff --git a/madgraph/iolibs/template_files/mg7/param_reweight_card.py b/madgraph/iolibs/template_files/mg7/param_reweight_card.py index d9a1316db3..f89e27ae5e 100644 --- a/madgraph/iolibs/template_files/mg7/param_reweight_card.py +++ b/madgraph/iolibs/template_files/mg7/param_reweight_card.py @@ -100,7 +100,7 @@ # Hard-set for now (see the module docstring); should become a modifiable # global default once MadtRex/madevent.py grow one of their own. -DEFAULT_FPTYPE = "m" +DEFAULT_FPTYPE = "v" # Recognized "change " preamble Driver options (see # DriverOptions) besides the shared "change helicity", lowercase, matched diff --git a/madgraph/iolibs/template_files/mg7/run_card.toml b/madgraph/iolibs/template_files/mg7/run_card.toml index c48935c541..e231fe9dd9 100644 --- a/madgraph/iolibs/template_files/mg7/run_card.toml +++ b/madgraph/iolibs/template_files/mg7/run_card.toml @@ -12,6 +12,8 @@ cpu_mode = %(run.cpu_mode)s madspace_cpu_mode = %(run.madspace_cpu_mode)s # matrix element precision; options: all64, all32, color32, denom64 precision = %(run.precision)s +# fraction of the events evaluated again in all64 to check the precision (0: no check) +precision_check = %(run.precision_check)s # -1 sets the thread count automatically cpu_thread_pool_size = %(run.cpu_thread_pool_size)s # cpu gzip of the lhe output: auto uses pigz when installed; false uses gzip diff --git a/madgraph/mg7/madgraph_process.py b/madgraph/mg7/madgraph_process.py index 667e12ac54..f583238e78 100644 --- a/madgraph/mg7/madgraph_process.py +++ b/madgraph/mg7/madgraph_process.py @@ -25,6 +25,7 @@ from madgraph.mg7 import npy_to_lhe from madgraph.mg7 import options from madgraph.mg7 import plots +from madgraph.mg7 import precision_check from madgraph.mg7 import systematics_summary from madgraph.mg7.bootstrap import INSTALL_DIR as _INSTALL_DIR from madgraph.mg7.bootstrap import MG_ROOT as _MG_ROOT @@ -1912,6 +1913,7 @@ def compile_matrix_elements(self) -> list[str]: meta for meta in self.subprocess_data if not is_amplicol(meta) ] self.helicity_choice_build = None + self.precision_check_builds = None if not madmatrix_data: return backends @@ -1978,13 +1980,14 @@ def compile_matrix_elements(self) -> list[str]: for backend, fptype in builds: # by library: the flavours of a split subprocess share one; a library # built with other recycling settings is rebuilt too: its SigmaKin.o - # records them in build./.hrflags (madmatrix.mk) + # records them in build._/.hrflags (madmatrix.mk) missing = list({ meta["me_path"]: meta for meta in madmatrix_data if not os.path.isfile( meta["me_path"].format(device=backend, fptype=fptype) ) - or self.hel_recycling_flags_changed(meta["path"], backend, hr_flags) + or self.hel_recycling_flags_changed( + meta["path"], backend, fptype, hr_flags) }.values()) if not missing: continue @@ -2003,8 +2006,69 @@ def compile_matrix_elements(self) -> list[str]: logger.info( f"Compilation of SubProcesses done in {time.time() - start_time:.1f} s" ) + self.compile_precision_check( + madmatrix_data, subproc_path, cpu_backends, fptype, builds, + hr_args, hr_flags, nb_core, log_path) return resolved + def precision_check_enabled(self, fptype: str) -> bool: + """Whether this run checks the precision of its matrix elements on a + fraction of its events (see precision_check.py). A card without the + entry checks nothing.""" + return ( + fptype != "d" + and float(self.run_card["run"].get("precision_check", 0)) > 0 + and not self.run_card["run"]["dummy_matrix_element"] + and self.gridpack_run_mode == "regular" + and not self.gridpack_data_only + ) + + def compile_precision_check( + self, madmatrix_data, subproc_path, cpu_backends, fptype, builds, + hr_args, hr_flags, nb_core, log_path + ) -> None: + """Build the two CPU libraries the precision check compares: one in + the precision of the run and one in all64 (FPTYPE=d), on the CPU + backend of the run, else on the scalar one. A failure only disables + the check.""" + if not self.precision_check_enabled(fptype): + return + backend = cpu_backends[0] if cpu_backends else "scalar" + checks = [(backend, fptype), (backend, "d")] + try: + for build_backend, build_fptype in checks: + if (build_backend, build_fptype) in builds: + continue + missing = [ + meta for meta in madmatrix_data + if not os.path.isfile(meta["me_path"].format( + device=build_backend, fptype=build_fptype)) + or self.hel_recycling_flags_changed( + meta["path"], build_backend, build_fptype, hr_flags) + ] + if not missing: + continue + logger.info( + "precision check (%s of the events): compilation of SubProcesses " + "for '%s' with FPTYPE=%s, see log detail in %s", + self.run_card["run"]["precision_check"], build_backend, + build_fptype, log_path) + start_time = time.time() + make_args = [f"BACKEND={build_backend}", f"FPTYPE={build_fptype}", + "USEBUILDDIR=1"] + self.extra_make_args + hr_args + if (len(missing) >= PCH_MIN_SUBPROCESSES + and not any(arg.startswith("PCH=") for arg in make_args)): + make_args.append("PCH=1") + self.make_subprocesses(subproc_path, make_args, nb_core, log_path) + logger.info( + f"Compilation for the precision check done in " + f"{time.time() - start_time:.1f} s" + ) + except RuntimeError as error: + logger.warning("no precision check for this run: %s", error) + return + self.precision_check_builds = tuple(checks) + def compile_amplicol(self) -> None: """Build the libraries of the [amplicol] processes that are missing.""" paths = sorted({ @@ -2071,14 +2135,17 @@ def hel_recycling_make_args(self) -> list[str]: return [f"HRMAXMB={max_mb}", f"HRNOBLAS={no_blas}"] @staticmethod - def hel_recycling_flags_changed(proc_path: str, backend: str, hr_flags: str) -> bool: - """Whether a --hel_recycling subprocess was built for this backend with - other recycling settings than hr_flags (see .hrflags in madmatrix.mk).""" + def hel_recycling_flags_changed( + proc_path: str, backend: str, fptype: str, hr_flags: str + ) -> bool: + """Whether a --hel_recycling subprocess was built for this backend and + FPTYPE with other recycling settings than hr_flags (see .hrflags in + madmatrix.mk).""" if backend.startswith(("cuda", "hip")): return False if not os.path.isfile(os.path.join(proc_path, "HelRecycling.inc")): return False - marker = os.path.join(proc_path, f"build.{backend}", ".hrflags") + marker = os.path.join(proc_path, f"build.{backend}_{fptype}", ".hrflags") try: with open(marker) as fsock: return fsock.read().strip() != hr_flags @@ -2402,6 +2469,7 @@ def generate_events(self, output_format=None) -> None: self.event_generator.generate() control.armed = False self.write_events(output_format) + precision_check.run(self) def write_events(self, output_format) -> None: """Combine the generated events into the output_format file, then write diff --git a/madgraph/mg7/precision_check.py b/madgraph/mg7/precision_check.py new file mode 100644 index 0000000000..20b36cf245 --- /dev/null +++ b/madgraph/mg7/precision_check.py @@ -0,0 +1,386 @@ +"""The precision check of an mg7 run: a fraction of its events evaluated again +with the matrix elements in double precision. + +A run whose [run] precision is not all64 (the default, denom64, keeps only the +momenta and the propagator denominators in double precision) evaluates the +matrix elements in single precision, which is accurate to ~1e-6 on most phase +space points but can lose digits where the amplitudes cancel. With +[run] precision_check > 0, the run builds the CPU library of each MadMatrix +subprocess in its own precision and in all64 (FPTYPE=d) and, once the events +are written, evaluates a sample of them with both, at the same momenta, flavour +and alpha_s, with the same good helicities. It reports the relative deviation +|M2 - M2_d| / |M2_d|: its mean over the unweighted events estimates the +relative bias of the cross section; its maximum and the number of events above +[run] precision_check_threshold flag unstable phase-space regions. + +The sample is the first events of the output (the events are written in a +random order), so an LHE output need not be read to its end. The events are +matched to a library and flavour by their PDG ids (incoming then outgoing, +resonances left out, as in the output), the incoming legs swapped for the +mirrored flavours; events that match none (an AmpliCol subprocess) are not +checked. + +Each library is evaluated in a separate Python process (this file run as a +script): the libraries of two precisions export the same C++ symbols, which +must not resolve across them, and the run process has already loaded one of +them through madspace. +""" + +import ctypes +import json +import logging +import math +import os +import subprocess +import sys + +logger = logging.getLogger("madevent") + +RESULT_FILE = "precision_check.json" + +UMAMI_SUCCESS = 0 +UMAMI_IN_MOMENTA = 0 +UMAMI_IN_ALPHA_S = 1 +UMAMI_IN_FLAVOR_INDEX = 2 +UMAMI_OUT_MATRIX_ELEMENT = 0 + + +# ---------------------------------------------------------------------------- +# evaluation (in a separate process, see evaluate()) +# ---------------------------------------------------------------------------- +def _evaluate_library(library, param_card, parameters, helicity_choice, + momenta, alpha_s, flavors): + """|M|^2 of the CPU MadMatrix library at momenta (shape (n, legs, 4), as + E, px, py, pz), alpha_s and flavour indices (shape (n,)).""" + import numpy as np + + lib = ctypes.CDLL(os.path.abspath(library), mode=os.RTLD_LOCAL) + lib.umami_initialize.argtypes = [ctypes.POINTER(ctypes.c_void_p), ctypes.c_char_p] + lib.umami_set_parameter.argtypes = [ + ctypes.c_void_p, ctypes.c_char_p, ctypes.c_double, ctypes.c_double] + lib.umami_free.argtypes = [ctypes.c_void_p] + lib.umami_matrix_element.argtypes = [ + ctypes.c_void_p, ctypes.c_size_t, ctypes.c_size_t, ctypes.c_size_t, + ctypes.c_size_t, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_void_p), + ctypes.c_size_t, ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_void_p)] + + handle = ctypes.c_void_p() + if lib.umami_initialize(ctypes.byref(handle), os.path.abspath(param_card).encode()) \ + != UMAMI_SUCCESS: + raise RuntimeError(f"{library}: umami_initialize failed with {param_card}") + try: + for name, value in parameters.items(): + if lib.umami_set_parameter(handle, name.encode(), float(value), 0.) \ + != UMAMI_SUCCESS: + raise RuntimeError(f"{library} refuses the parameter {name}") + if helicity_choice: + try: + set_choice = lib.madmatrix_set_helicity_choice + except AttributeError: + set_choice = None + if set_choice is not None: + set_choice.argtypes = [ + ctypes.c_void_p, ctypes.POINTER(ctypes.c_int), ctypes.c_int] + choice = (ctypes.c_int * len(helicity_choice))(*helicity_choice) + if set_choice(handle, choice, len(helicity_choice)) != UMAMI_SUCCESS: + raise RuntimeError(f"{library} refuses the helicity choice") + + count = len(alpha_s) + # column-major with the event index contiguous: [component][leg][event] + momenta_in = np.ascontiguousarray(np.transpose(momenta, (2, 1, 0)), dtype=np.float64) + alpha_s_in = np.ascontiguousarray(alpha_s, dtype=np.float64) + flavors_in = np.ascontiguousarray(flavors, dtype=np.uint32) + result = np.zeros(count, dtype=np.float64) + in_keys = (ctypes.c_int * 3)(UMAMI_IN_MOMENTA, UMAMI_IN_ALPHA_S, UMAMI_IN_FLAVOR_INDEX) + inputs = (ctypes.c_void_p * 3)( + momenta_in.ctypes.data, alpha_s_in.ctypes.data, flavors_in.ctypes.data) + out_keys = (ctypes.c_int * 1)(UMAMI_OUT_MATRIX_ELEMENT) + outputs = (ctypes.c_void_p * 1)(result.ctypes.data) + status = lib.umami_matrix_element( + handle, count, count, 0, 3, in_keys, inputs, 1, out_keys, outputs) + if status != UMAMI_SUCCESS: + raise RuntimeError(f"{library}: umami_matrix_element failed ({status})") + return result + finally: + lib.umami_free(handle) + + +def _evaluate_job(job_path): + """The worker: evaluate the events of job_path (an npz file and its json + description) with one library per group, write the results next to it.""" + import numpy as np + + with open(job_path) as f: + job = json.load(f) + data = np.load(job["inputs"]) + results = {} + for name, group in job["groups"].items(): + results[name] = _evaluate_library( + group["library"], job["param_card"], job["parameters"], + group["helicity_choice"], data[f"{name}_momenta"], + data[f"{name}_alpha_s"], data[f"{name}_flavors"]) + np.savez(job["outputs"], **results) + + +def evaluate(work_dir, tag, groups, inputs, param_card, parameters): + """|M|^2 of each group of events with its library, evaluated in a separate + process. groups maps a group name to {"library", "helicity_choice"}; + inputs maps "_momenta"/"_alpha_s"/"_flavors" to arrays.""" + import numpy as np + + inputs_path = os.path.join(work_dir, f"precision_check_{tag}_in.npz") + outputs_path = os.path.join(work_dir, f"precision_check_{tag}_out.npz") + job_path = os.path.join(work_dir, f"precision_check_{tag}.json") + np.savez(inputs_path, **inputs) + with open(job_path, "w") as f: + json.dump({"inputs": inputs_path, "outputs": outputs_path, "groups": groups, + "param_card": os.path.abspath(param_card), + "parameters": parameters}, f) + try: + result = subprocess.run([sys.executable, os.path.abspath(__file__), job_path], + capture_output=True, text=True) + if result.returncode != 0: + message = (result.stderr.strip() or result.stdout.strip()).splitlines() + raise RuntimeError(message[-1] if message else + f"exit status {result.returncode}") + with np.load(outputs_path) as data: + return {name: data[name] for name in data.files} + finally: + for path in (inputs_path, outputs_path, job_path): + if os.path.exists(path): + os.remove(path) + + +# ---------------------------------------------------------------------------- +# events +# ---------------------------------------------------------------------------- +def flavor_table(process): + """{(pdg ids of the legs): (me_path format, flavour index, mirrored)} of + every MadMatrix subprocess of process. A mirrored flavour is also reached + with its two incoming legs exchanged, the event's momenta then exchanged + too.""" + table = {} + mirrored = {} + for subproc in process.subprocesses: + unmerged_meta = getattr(subproc, "unmerged_meta", None) + if unmerged_meta is None: + members = [subproc.meta] + else: + members = [unmerged_meta[i] for i in subproc.meta["subprocesses"]] + for meta in members: + if meta.get("backend") == "amplicol": + continue + incoming = len(meta["incoming"]) + for flavor in meta["flavors"]: + for option in flavor["options"]: + key = tuple(option) + table.setdefault(key, (meta["me_path"], flavor["index"], False)) + if flavor.get("mirror") and incoming == 2: + swapped = (key[1], key[0]) + key[2:] + mirrored.setdefault( + swapped, (meta["me_path"], flavor["index"], True)) + for key, value in mirrored.items(): + table.setdefault(key, value) + return table + + +def _npy_events(path, count, rng): + """(pdg ids or None, subprocess and flavour indices or None, momenta, + alpha_s) of count events of an npy output, drawn at random.""" + import numpy as np + + events = np.load(path, mmap_mode="r", max_header_size=1 << 30) + total = len(events) + if total == 0: + return [] + picked = np.sort(rng.choice(total, size=min(count, total), replace=False)) + sample = events[picked] + names = sample.dtype.names + legs = 0 + while f"part{legs + 1}_energy" in names: + legs += 1 + rows = [] + for event in sample: + momenta = [[event[f"part{i}_{c}"] for c in ("energy", "px", "py", "pz")] + for i in range(1, legs + 1)] + if "part1_pdg_id" in names: # lhe_npy + kept = [i for i in range(legs) if event[f"part{i + 1}_status_code"] in (-1, 1)] + rows.append(dict( + pdgs=tuple(int(event[f"part{i + 1}_pdg_id"]) for i in kept), + momenta=[momenta[i] for i in kept], + alpha_s=float(event["alpha_qcd"]))) + else: # compact_npy + rows.append(dict( + indices=(int(event["subprocess_index"]), int(event["flavor_index"])), + momenta=momenta, alpha_s=float(event["alpha_qcd"]))) + return rows + + +def _lhe_events(path, count): + """The pdg ids, momenta and alpha_s of the first count events of an LHE + output.""" + from madgraph.various import lhe_parser + + rows = [] + for event in lhe_parser.EventFile(path): + kept = [p for p in event if p.status in (-1, 1)] + rows.append(dict(pdgs=tuple(int(p.pid) for p in kept), + momenta=[[p.E, p.px, p.py, p.pz] for p in kept], + alpha_s=float(event.aqcd))) + if len(rows) >= count: + break + return rows + + +def _compact_pdgs(process, subproc_index, flavor_index): + """The pdg ids of a compact_npy event, from its subprocess and flavour.""" + for subproc in process.subprocesses: + if subproc.subproc_id != subproc_index: + continue + flavor = subproc.meta["flavors"][flavor_index] + unmerged_meta = getattr(subproc, "unmerged_meta", None) + if unmerged_meta is not None and "subprocess" in flavor: + member = unmerged_meta[subproc.meta["subprocesses"][flavor["subprocess"]]] + flavor = member["flavors"][flavor["flavor"]] + return tuple(flavor["options"][0]) + return None + + +# ---------------------------------------------------------------------------- +# the check +# ---------------------------------------------------------------------------- +def summarize(values, references, threshold): + """The statistics of the relative deviation of values from references.""" + import numpy as np + + values = np.asarray(values, dtype=float) + references = np.asarray(references, dtype=float) + finite = np.isfinite(values) & np.isfinite(references) + scale = np.abs(references) + with np.errstate(divide="ignore", invalid="ignore"): + rel = np.where(scale > 0, np.abs(values - references) / scale, + np.where(values == references, 0., np.inf)) + rel = np.where(finite, rel, np.inf) + total = float(np.sum(scale[finite])) + return { + "events": int(len(values)), + "non_finite": int(np.sum(~finite)), + "mean_relative_deviation": float(np.mean(rel)) if len(rel) else 0., + "max_relative_deviation": float(np.max(rel)) if len(rel) else 0., + # the |M|^2-weighted mean: the relative change of a sum over the events + "weighted_relative_deviation": + float(np.sum(np.abs(values - references)[finite]) / total) if total > 0 else 0., + "above_threshold": int(np.sum(rel > threshold)), + "threshold": float(threshold), + } + + +def run(process): + """The precision check of the events process wrote (see the module + docstring). Returns its summary, also written to the run directory, or + None when there was nothing to check. Never fatal to the run.""" + try: + return _run(process) + except Exception as error: + logger.warning("precision check skipped: %s", error) + return None + + +def _run(process): + import numpy as np + from madgraph.mg7.common import me_parameters + + builds = getattr(process, "precision_check_builds", None) + events_path = getattr(process, "events_path", None) + if not builds or not events_path or not os.path.isfile(events_path): + return None + (backend, fptype), (ref_backend, ref_fptype) = builds + run_card = process.run_card["run"] + total = int(process.run_card["generation"]["events"]) + count = max(1, math.ceil(float(run_card["precision_check"]) * max(total, 1))) + count = min(count, int(run_card["precision_check_max_events"])) + threshold = float(run_card["precision_check_threshold"]) + + if events_path.endswith(".npy"): + rows = _npy_events(events_path, count, np.random.default_rng(process.run_seed)) + else: + rows = _lhe_events(events_path, count) + table = flavor_table(process) + + groups = {} + unmatched = 0 + for row in rows: + pdgs = row.get("pdgs") + if pdgs is None: + pdgs = _compact_pdgs(process, *row["indices"]) + match = table.get(pdgs) if pdgs is not None else None + if match is None or len(row["momenta"]) != len(pdgs): + unmatched += 1 + continue + path_format, flavor_index, swap = match + momenta = row["momenta"] + if swap: + momenta = [momenta[1], momenta[0]] + momenta[2:] + group = groups.setdefault(path_format, {"momenta": [], "alpha_s": [], "flavors": []}) + group["momenta"].append(momenta) + group["alpha_s"].append(row["alpha_s"]) + group["flavors"].append(flavor_index) + if not groups: + logger.info("precision check: none of the %d events read is from a " + "MadMatrix subprocess", len(rows)) + return None + + parameters = me_parameters(process.run_card) + names = {path_format: f"g{i}" for i, path_format in enumerate(groups)} + inputs = {} + for path_format, group in groups.items(): + name = names[path_format] + inputs[f"{name}_momenta"] = np.array(group["momenta"], dtype=np.float64) + inputs[f"{name}_alpha_s"] = np.array(group["alpha_s"], dtype=np.float64) + inputs[f"{name}_flavors"] = np.array(group["flavors"], dtype=np.uint32) + + def libraries(build_backend, build_fptype): + return { + names[path_format]: { + "library": path_format.format(device=build_backend, fptype=build_fptype), + "helicity_choice": process.helicity_choices.get(path_format), + } + for path_format in groups + } + + work_dir = process.run_path + values = evaluate(work_dir, fptype, libraries(backend, fptype), inputs, + process.param_card_path, parameters) + references = evaluate(work_dir, ref_fptype, libraries(ref_backend, ref_fptype), + inputs, process.param_card_path, parameters) + order = [names[path_format] for path_format in groups] + summary = summarize(np.concatenate([values[n] for n in order]), + np.concatenate([references[n] for n in order]), threshold) + summary.update({ + "precision": run_card["precision"], + "fptype": fptype, + "reference_fptype": ref_fptype, + "backend": backend, + "unmatched_events": unmatched, + "events_path": os.path.basename(events_path), + }) + with open(os.path.join(process.run_path, RESULT_FILE), "w") as f: + json.dump(summary, f, indent=1) + + message = ("precision check (%s vs all64, %d events): mean relative deviation " + "%.2g, |M|^2-weighted %.2g, max %.2g; %d above %.0e%s") + args = (run_card["precision"], summary["events"], + summary["mean_relative_deviation"], summary["weighted_relative_deviation"], + summary["max_relative_deviation"], summary["above_threshold"], threshold, + ", %d not finite" % summary["non_finite"] if summary["non_finite"] else "") + if summary["above_threshold"] or summary["non_finite"]: + logger.warning(message + ". This process may need [run] precision = " + "\"all64\" (or \"color32\"); details in %s", + *(args + (os.path.join(process.run_path, RESULT_FILE),))) + else: + logger.info(message, *args) + return summary + + +if __name__ == "__main__": + _evaluate_job(sys.argv[1]) diff --git a/madgraph/various/banner.py b/madgraph/various/banner.py index f2ba1e0baa..5d6379eed4 100755 --- a/madgraph/various/banner.py +++ b/madgraph/various/banner.py @@ -7333,9 +7333,17 @@ def default_setup(self): allowed=['auto', 'scalar', 'simd_128', 'simd_256', 'avx512y', 'simd_512'], execution=True, comment="SIMD width of the phase-space sampling on cpu devices; simd_128 is ARM only") - self.add_toml_param('run', 'precision', "color32", gridpack=True, + self.add_toml_param('run', 'precision', "denom64", gridpack=True, allowed=['all64', 'all32', 'color32', 'denom64'], comment="matrix element precision: all64, all32, color32 (FP32 color sum) or denom64 (FP64 momenta and propagator denominators)") + # The precision check (madgraph/mg7/precision_check.py): a fraction of + # the events evaluated again in all64, for a precision other than all64 + self.add_toml_param('run', 'precision_check', 0.01, + comment="fraction of the events evaluated again in all64 to check the precision (0: no check); needs an all64 build of the matrix elements") + self.add_toml_param('run', 'precision_check_max_events', 1000, hidden=True, + comment="the precision check evaluates at most this many events") + self.add_toml_param('run', 'precision_check_threshold', 1e-3, hidden=True, + comment="relative deviation from all64 above which the precision check warns") # --hel_recycling outputs (madmatrix, cpu only): the size of the recycled # tables per SIMD page above which the build takes the plain matrix # element (HRMAXMB of madmatrix.mk; -1: the build's default, 0: no diff --git a/madmatrix/density.py b/madmatrix/density.py index e695538b8a..df580722a2 100644 --- a/madmatrix/density.py +++ b/madmatrix/density.py @@ -43,8 +43,9 @@ PROCESSES_FILE = 'madmatrix_processes.json' -# The FPTYPE of the libraries this module builds and loads: the default of -# madmatrix.mk, made explicit since it is part of the library names +# The FPTYPE of the libraries this module builds and loads, explicit since it +# is part of the library names: color32, the precision the density matrices +# were validated in (madmatrix.mk itself defaults to v, denom64, since then) FPTYPE = 'm' diff --git a/madmatrix/launch_plugin.py b/madmatrix/launch_plugin.py index c02fd17302..2324c3ab97 100644 --- a/madmatrix/launch_plugin.py +++ b/madmatrix/launch_plugin.py @@ -134,10 +134,10 @@ def reset_makeopts(self, old_value, new_value, name): def default_setup(self): super().default_setup() - self.add_param('floating_type', 'color32', include=False, hidden=True, + self.add_param('floating_type', 'denom64', include=False, hidden=True, fct_mod=(self.reset_makeopts,(),{}), allowed=['color32','all64','all32','denom64','m','d','f','v'], - comment='precision: all32, all64, color32 (colour fp32, rest fp64), denom64 (momenta+denom fp64, rest fp32; SIMD falls back to color32)' + comment='precision: all32, all64, color32 (colour fp32, rest fp64), denom64 (momenta+denom fp64, rest fp32; the default)' ) self.add_param('cudacpp_backend', 'auto', include=False, hidden=False, allowed=CUDACPP_SUPPORTED_BACKENDS) diff --git a/madmatrix/output.py b/madmatrix/output.py index b50eab73ac..6088742489 100644 --- a/madmatrix/output.py +++ b/madmatrix/output.py @@ -172,7 +172,7 @@ class ProcessExporterMadMatrix(export_cpp.ProcessExporterMG7): # etc.) are NOT linked into P* at all: they are read straight from the # top-level backend// and backend/common/ dirs via the Makefile's # INCFLAGS/vpath (see BACKENDDIR in madmatrix.mk). They are still compiled - # once per P* directory, into its own build./, and have to be: + # once per P* directory, into its own build._/, and have to be: # they include that directory's generated ProcessData.h, ColorData.h and # ProcessTables.h. Only files with no backend/ counterpart - genuinely # backend-agnostic - stay here. diff --git a/tests/acceptance_tests/test_mg7_precision_check.py b/tests/acceptance_tests/test_mg7_precision_check.py new file mode 100644 index 0000000000..0c2518cc57 --- /dev/null +++ b/tests/acceptance_tests/test_mg7_precision_check.py @@ -0,0 +1,211 @@ +"""The precision check of an mg7 run (madgraph/mg7/precision_check.py). + +The default precision, denom64 (FPTYPE=v), evaluates the amplitudes in single +precision. [run] precision_check re-evaluates a fraction of the events with an +all64 (FPTYPE=d) build of the same matrix elements: + + * ``test_precision_check_mg7`` -- ``p p > e+ e- j`` with LHE output: the run + builds both FPTYPEs side by side (build._v and build._d), + writes precision_check.json for the requested fraction of the events, all + matched to a library, finite, and within single-precision rounding of all64 + without being identical to it; then a second run in color32 rebuilds in its + own directory without a 'make clean', and a third, in all64, checks nothing. + * ``test_precision_check_reproduces_the_run_mg7`` -- the same process with + lhe_npy output and the |M|^2 of every event stored by madspace: the check's + own evaluation in the run's precision reproduces it, mirrored flavours + included, so the check compares the very matrix elements the run used. + +Self-skips if the mg7 runtime stack / PDF is unavailable (as +test_mg7_reproducibility.py). Run locally with e.g.:: + + ./tests/test_manager.py test_precision_check.*_mg7 -pA -t0 -l INFO +""" + +from __future__ import absolute_import +from __future__ import division + +import glob +import json +import os +import shutil +import subprocess +import sys +import tempfile +import textwrap +import unittest + +import madgraph.interface.master_interface as MGCmd +from madgraph.various.banner import RunCardMG7 +from tests.acceptance_tests.test_mg7_reproducibility import ( + _mg7_datadir_or_skip, _run) + +pjoin = os.path.join + +_PROCESS = 'p p > e+ e- j' +_EVENTS = 2000 + + +class MG7PrecisionCheckTest(unittest.TestCase): + + def setUp(self): + self.path = tempfile.mkdtemp(prefix='mg7_precision_check_') + + def tearDown(self): + shutil.rmtree(self.path, ignore_errors=True) + + def _output_process(self, name, **settings): + run_dir = pjoin(self.path, name) + mg = MGCmd.MasterCmd() + mg.no_notification() + mg.exec_cmd('set automatic_html_opening False --no_save') + mg.exec_cmd('generate %s' % _PROCESS) + mg.exec_cmd('output mg7 %s' % run_dir) + defaults = { + 'generation.events': _EVENTS, + 'postprocessing.systematics': False, + 'run.seed': 4242, + } + defaults.update(settings) + self._set_run_card(run_dir, **defaults) + return run_dir + + @staticmethod + def _set_run_card(run_dir, **settings): + toml = pjoin(run_dir, 'Cards', 'run_card.toml') + card = RunCardMG7(toml) + for key, value in settings.items(): + card.set(key, value, user=True) + card.write(toml) + + def _generate(self, run_dir, datadir, tag): + env = dict(os.environ) + env['LHAPDF_DATA_PATH'] = datadir + _run([sys.executable, pjoin(run_dir, 'bin', 'generate_events'), '-f'], + run_dir, pjoin(run_dir, 'gen_%s.log' % tag), env, + 'mg7 generate_events') + runs = sorted(glob.glob(pjoin(run_dir, 'Events', 'run_*'))) + self.assertTrue(runs, 'no run directory under %s' % run_dir) + return runs[-1] + + def test_precision_check_mg7(self): + datadir = _mg7_datadir_or_skip(self) + run_dir = self._output_process( + 'lhe', **{'run.output_format': 'lhe', 'run.precision_check': 0.05}) + card = RunCardMG7(pjoin(run_dir, 'Cards', 'run_card.toml')) + self.assertEqual(card['run']['precision'], 'denom64') + + run_path = self._generate(run_dir, datadir, 'denom64') + with open(pjoin(run_path, 'precision_check.json')) as f: + summary = json.load(f) + self.assertEqual(summary['fptype'], 'v') + self.assertEqual(summary['reference_fptype'], 'd') + self.assertEqual(summary['events'], 100) # 5% of 2000 + self.assertEqual(summary['unmatched_events'], 0) + self.assertEqual(summary['non_finite'], 0) + self.assertEqual(summary['above_threshold'], 0) + # single precision amplitudes: not all64, but close to it + self.assertGreater(summary['max_relative_deviation'], 0.) + self.assertLess(summary['max_relative_deviation'], 1e-4) + self.assertLess(summary['mean_relative_deviation'], 1e-5) + + # the two FPTYPEs were built side by side + subprocess_dir = sorted(glob.glob(pjoin(run_dir, 'SubProcesses', 'P*')))[0] + builds = sorted(os.path.basename(path) for path in + glob.glob(pjoin(subprocess_dir, 'build.*'))) + self.assertEqual(len(builds), 2, builds) + self.assertTrue(builds[0].endswith('_d') and builds[1].endswith('_v'), builds) + + # another precision: built in its own directory, no 'make clean' needed + self._set_run_card(run_dir, **{'run.precision': 'color32', + 'run.precision_check': 0.0}) + run_path = self._generate(run_dir, datadir, 'color32') + self.assertFalse(os.path.exists(pjoin(run_path, 'precision_check.json'))) + self.assertTrue(glob.glob(pjoin(subprocess_dir, 'build.*_m'))) + + # all64 is its own reference: nothing to check + self._set_run_card(run_dir, **{'run.precision': 'all64', + 'run.precision_check': 0.05}) + run_path = self._generate(run_dir, datadir, 'all64') + self.assertFalse(os.path.exists(pjoin(run_path, 'precision_check.json'))) + + def test_precision_check_reproduces_the_run_mg7(self): + datadir = _mg7_datadir_or_skip(self) + run_dir = self._output_process( + 'stored', **{'run.output_format': 'lhe_npy', 'run.precision_check': 0.01}) + script = pjoin(run_dir, 'check_mapping.py') + with open(script, 'w') as f: + f.write(textwrap.dedent(''' + import json, os, sys + sys.path.insert(0, %r) + import numpy as np + from madgraph.mg7.madgraph_process import MadgraphProcess + from madgraph.mg7 import precision_check as pc + from madgraph.mg7.common import me_parameters + + process = MadgraphProcess() + process.store_matrix_elements = True + process.survey() + process.train_madnis() + process.generate_events() + events = np.load(process.events_path, mmap_mode="r", + max_header_size=1 << 30) + legs = 0 + while "part%%d_energy" %% (legs + 1) in events.dtype.names: + legs += 1 + table = pc.flavor_table(process) + groups = {} + for event in events[:1000]: + kept = [i for i in range(1, legs + 1) + if event["part%%d_status_code" %% i] in (-1, 1)] + pdgs = tuple(int(event["part%%d_pdg_id" %% i]) for i in kept) + path_format, flavor, swap = table[pdgs] + momenta = [[event["part%%d_%%s" %% (i, c)] + for c in ("energy", "px", "py", "pz")] for i in kept] + if swap: + momenta = [momenta[1], momenta[0]] + momenta[2:] + group = groups.setdefault(path_format, [[], [], [], [], 0]) + group[0].append(momenta) + group[1].append(float(event["alpha_qcd"])) + group[2].append(flavor) + group[3].append(float(event["matrix_element"])) + group[4] += int(swap) + names = {p: "g%%d" %% i for i, p in enumerate(groups)} + inputs = {} + for p, g in groups.items(): + inputs[names[p] + "_momenta"] = np.array(g[0]) + inputs[names[p] + "_alpha_s"] = np.array(g[1]) + inputs[names[p] + "_flavors"] = np.array(g[2], dtype=np.uint32) + backend, fptype = process.precision_check_builds[0] + libraries = {names[p]: { + "library": p.format(device=backend, fptype=fptype), + "helicity_choice": process.helicity_choices.get(p)} + for p in groups} + values = pc.evaluate(process.run_path, "test", libraries, inputs, + process.param_card_path, + me_parameters(process.run_card)) + worst = max(float(np.max(np.abs(values[names[p]] / np.array(g[3]) - 1))) + for p, g in groups.items()) + with open("mapping.json", "w") as f: + json.dump({"worst": worst, "fptype": fptype, + "events": sum(len(g[3]) for g in groups.values()), + "mirrored": sum(g[4] for g in groups.values()), + "summary": os.path.isfile(os.path.join( + process.run_path, pc.RESULT_FILE))}, f) + ''' % os.path.dirname(os.path.dirname(os.path.dirname( + os.path.abspath(__file__)))))) + env = dict(os.environ) + env['LHAPDF_DATA_PATH'] = datadir + _run([sys.executable, script], run_dir, pjoin(run_dir, 'mapping.log'), env, + 'stored matrix element comparison') + with open(pjoin(run_dir, 'mapping.json')) as f: + result = json.load(f) + self.assertEqual(result['fptype'], 'v') + self.assertEqual(result['events'], 1000) + self.assertGreater(result['mirrored'], 0) + self.assertTrue(result['summary']) + # the same library at the same inputs: the same |M|^2 as in the run + self.assertLess(result['worst'], 1e-12) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/unit_tests/interface/test_mg7_precision_check.py b/tests/unit_tests/interface/test_mg7_precision_check.py new file mode 100644 index 0000000000..6597aa5c2d --- /dev/null +++ b/tests/unit_tests/interface/test_mg7_precision_check.py @@ -0,0 +1,179 @@ +################################################################################ +# +# Copyright (c) 2026 The MadGraph5_aMC@NLO Development team and Contributors +# +# This file is a part of the MadGraph5_aMC@NLO project, an application which +# automatically generates Feynman diagrams and matrix elements for arbitrary +# high-energy processes in the Standard Model and beyond. +# +# It is subject to the MadGraph5_aMC@NLO license which should accompany this +# distribution. +# +# For more information, visit madgraph.phys.ucl.ac.be and amcatnlo.web.cern.ch +# +################################################################################ +"""The precision check of an mg7 run (madgraph/mg7/precision_check.py), and +denom64 as the default precision. + +What needs a compiler and madspace -- the two builds, the ctypes evaluation, +that it reproduces the |M|^2 of the run itself -- is in +tests/acceptance_tests/test_mg7_precision_check.py. +""" + +from __future__ import absolute_import + +import math +import os +import shutil +import tempfile +import unittest + +# no madgraph.mg7.common here: it imports madspace, which the unit-test +# runners do not have when they collect the test modules +import madgraph.mg7.precision_check as precision_check +from madgraph.various.banner import RunCardMG7 + +pjoin = os.path.join + + +class TestPrecisionDefault(unittest.TestCase): + """denom64 (FPTYPE=v) is the default precision everywhere.""" + + def test_run_card_default_is_denom64(self): + card = RunCardMG7() + self.assertEqual(card['run']['precision'], 'denom64') + self.assertEqual(card['run']['precision_check'], 0.01) + self.assertEqual(card['run']['precision_check_max_events'], 1000) + self.assertEqual(card['run']['precision_check_threshold'], 1e-3) + + def test_written_run_card_has_the_precision_check(self): + tmpdir = tempfile.mkdtemp() + try: + path = pjoin(tmpdir, 'run_card.toml') + RunCardMG7().write(path) + with open(path) as f: + text = f.read() + self.assertIn('precision = "denom64"', text) + self.assertIn('precision_check = 0.01', text) + card = RunCardMG7(path) + self.assertEqual(card['run']['precision_check'], 0.01) + finally: + shutil.rmtree(tmpdir) + + def test_makefile_default_is_v(self): + """madmatrix.mk builds FPTYPE=v without an FPTYPE, in a build + directory of its own per FPTYPE.""" + import madgraph + mk = pjoin(os.path.dirname(madgraph.__file__), 'iolibs', 'template_files', + 'madmatrix', 'madmatrix.mk') + with open(mk) as f: + text = f.read() + default = text[text.index('ifeq ($(FPTYPE),)'):] + default = default[:default.index('endif')] + self.assertIn('override FPTYPE = v', default) + self.assertIn('override MADMATRIX_BUILDDIR = build.$(BACKEND)_$(FPTYPE)', text) + + def test_reweighting_fallbacks_are_v(self): + from madgraph.iolibs.template_files.mg7 import param_reweight_card + self.assertEqual(param_reweight_card.DEFAULT_FPTYPE, 'v') + + +class TestSummarize(unittest.TestCase): + + def test_statistics(self): + summary = precision_check.summarize([1.0, 2.002, 3.0], [1.0, 2.0, 3.0], 1e-4) + self.assertEqual(summary['events'], 3) + self.assertEqual(summary['non_finite'], 0) + self.assertAlmostEqual(summary['max_relative_deviation'], 1e-3) + self.assertAlmostEqual(summary['mean_relative_deviation'], 1e-3 / 3) + # |M|^2-weighted: the relative change of the sum + self.assertAlmostEqual(summary['weighted_relative_deviation'], 0.002 / 6.0) + self.assertEqual(summary['above_threshold'], 1) + self.assertEqual(summary['threshold'], 1e-4) + + def test_zero_and_non_finite(self): + summary = precision_check.summarize( + [0.0, 1.0, float('nan'), float('inf')], [0.0, 0.0, 1.0, 1.0], 1e-3) + # 0 vs 0 agrees; 1 vs 0, nan and inf are all infinitely off + self.assertEqual(summary['non_finite'], 2) + self.assertEqual(summary['above_threshold'], 3) + self.assertTrue(math.isinf(summary['max_relative_deviation'])) + # the weighted mean only sums the finite events + self.assertEqual(summary['weighted_relative_deviation'], 0.0) + + def test_identical(self): + summary = precision_check.summarize([1.5, 2.5], [1.5, 2.5], 1e-3) + self.assertEqual(summary['max_relative_deviation'], 0.0) + self.assertEqual(summary['above_threshold'], 0) + + +class TestFlavorTable(unittest.TestCase): + """Events are matched to a library and flavour by their PDG ids.""" + + class _Subprocess(object): + """The attributes of a MadgraphSubprocess the check reads.""" + def __init__(self, meta, unmerged_meta=None, subproc_id=0): + self.meta = meta + self.unmerged_meta = unmerged_meta + self.subproc_id = subproc_id + + def _subprocess(self, meta, unmerged_meta=None, subproc_id=0): + return self._Subprocess(meta, unmerged_meta, subproc_id) + + class _Process(object): + def __init__(self, subprocesses): + self.subprocesses = subprocesses + + def test_options_and_mirror(self): + meta = { + 'incoming': [81, -81], 'outgoing': [-11, 11, 21], + 'me_path': 'lib/libA_{device}_{fptype}.so', + 'flavors': [ + {'index': 4, 'mirror': True, + 'options': [[1, -1, -11, 11, 21], [3, -3, -11, 11, 21]]}, + {'index': 5, 'mirror': False, 'options': [[2, -2, -11, 11, 21]]}, + ], + } + table = precision_check.flavor_table(self._Process([self._subprocess(meta)])) + self.assertEqual(table[(1, -1, -11, 11, 21)], ('lib/libA_{device}_{fptype}.so', 4, False)) + self.assertEqual(table[(3, -3, -11, 11, 21)], ('lib/libA_{device}_{fptype}.so', 4, False)) + # a mirrored flavour, reached with its incoming legs exchanged + self.assertEqual(table[(-1, 1, -11, 11, 21)], ('lib/libA_{device}_{fptype}.so', 4, True)) + self.assertEqual(table[(2, -2, -11, 11, 21)], ('lib/libA_{device}_{fptype}.so', 5, False)) + self.assertNotIn((-2, 2, -11, 11, 21), table) + + def test_amplicol_subprocess_is_left_out(self): + meta = {'incoming': [21, 21], 'outgoing': [21, 21], 'backend': 'amplicol', + 'me_path': 'lib/libAC.so', + 'flavors': [{'index': 0, 'mirror': False, 'options': [[21, 21, 21, 21]]}]} + self.assertEqual( + precision_check.flavor_table(self._Process([self._subprocess(meta)])), {}) + + def test_merged_subprocess_members(self): + unmerged = [ + {'incoming': [2, -2], 'outgoing': [23], 'me_path': 'lib/libU_{device}_{fptype}.so', + 'flavors': [{'index': 0, 'mirror': False, 'options': [[2, -2, 23]]}]}, + {'incoming': [1, -1], 'outgoing': [23], 'me_path': 'lib/libD_{device}_{fptype}.so', + 'flavors': [{'index': 0, 'mirror': False, 'options': [[1, -1, 23]]}]}, + ] + merged = {'subprocesses': [0, 1], + 'flavors': [{'subprocess': 0, 'flavor': 0}, {'subprocess': 1, 'flavor': 0}]} + process = self._Process([self._subprocess(merged, unmerged, subproc_id=3)]) + table = precision_check.flavor_table(process) + self.assertEqual(table[(2, -2, 23)], ('lib/libU_{device}_{fptype}.so', 0, False)) + self.assertEqual(table[(1, -1, 23)], ('lib/libD_{device}_{fptype}.so', 0, False)) + # compact_npy events name their subprocess and flavour instead + self.assertEqual(precision_check._compact_pdgs(process, 3, 1), (1, -1, 23)) + self.assertIsNone(precision_check._compact_pdgs(process, 0, 0)) + + def test_run_without_builds_checks_nothing(self): + """No precision_check_builds (all64, precision_check = 0, a gridpack + run, a failed build): nothing is checked, nothing is written.""" + class Process(object): + precision_check_builds = None + events_path = None + self.assertIsNone(precision_check.run(Process())) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/unit_tests/madevent/test_hel_recycle.py b/tests/unit_tests/madevent/test_hel_recycle.py index 7d29f85413..5bbbf12d8e 100644 --- a/tests/unit_tests/madevent/test_hel_recycle.py +++ b/tests/unit_tests/madevent/test_hel_recycle.py @@ -1547,15 +1547,17 @@ def test_rebuild_when_the_settings_change(self): changed = self.launch.MadgraphProcess.hel_recycling_flags_changed tmpdir = tempfile.mkdtemp() try: - self.assertFalse(changed(tmpdir, 'simd_128', ':')) # not recycled + self.assertFalse(changed(tmpdir, 'simd_128', 'v', ':')) # not recycled open(os.path.join(tmpdir, 'HelRecycling.inc'), 'w').close() - self.assertFalse(changed(tmpdir, 'simd_128', ':')) # never built - os.mkdir(os.path.join(tmpdir, 'build.simd_128')) - with open(os.path.join(tmpdir, 'build.simd_128', '.hrflags'), 'w') as fsock: + self.assertFalse(changed(tmpdir, 'simd_128', 'v', ':')) # never built + os.mkdir(os.path.join(tmpdir, 'build.simd_128_v')) + with open(os.path.join(tmpdir, 'build.simd_128_v', '.hrflags'), 'w') as fsock: fsock.write(':\n') - self.assertFalse(changed(tmpdir, 'simd_128', ':')) - self.assertTrue(changed(tmpdir, 'simd_128', '0:')) - self.assertFalse(changed(tmpdir, 'cuda', '0:')) # gpu: plain anyway + self.assertFalse(changed(tmpdir, 'simd_128', 'v', ':')) + self.assertTrue(changed(tmpdir, 'simd_128', 'v', '0:')) + # each FPTYPE has its own build directory, hence its own record + self.assertFalse(changed(tmpdir, 'simd_128', 'd', '0:')) # never built + self.assertFalse(changed(tmpdir, 'cuda', 'v', '0:')) # gpu: plain anyway finally: shutil.rmtree(tmpdir) From 6412ea6934832eaec7511058ba6e5d58890d06aa Mon Sep 17 00:00:00 2001 From: Olivier Mattelaer Date: Fri, 20 Nov 2026 04:01:36 +0100 Subject: [PATCH 2/7] madmatrix: FP32 tolerance for the C-parity helicity scan The C-parity scan in the cpu and simd SigmaKin.cc compared mirror helicity rows with an FP64 tolerance (1e-6 relative, 1e-12 of the largest |M|^2). With FP32 amplitudes (FPTYPE=f and the new default v) rounding noise exceeds it, the verdict latched "not C-symmetric" and the dedup was off: every helicity row evaluated, the mirrored half outside the hel-recycling table. On g g > t t~ g g (simd_128, 1 thread) v ran at 39.7 us/event against 23.4 for d. Under MGONGPU_FPTYPE_FLOAT the test now uses 1e-4 relative and 1e-6 of the largest |M|^2: v 13.0 us/event, f 12.2, |M|^2 identical to v with the helicity choice of the d build (v vs d max 8.7e-6). d and m keep the FP64 tolerance. u u~ > e+ e- is still refused the dedup under v; the gpu backend has no such scan. Co-Authored-By: Claude Opus 5.5 --- .../template_files/madmatrix/backend/cpu/SigmaKin.cc | 12 +++++++++++- .../madmatrix/backend/simd/SigmaKin.cc | 12 +++++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/madgraph/iolibs/template_files/madmatrix/backend/cpu/SigmaKin.cc b/madgraph/iolibs/template_files/madmatrix/backend/cpu/SigmaKin.cc index 583dfa5c60..e748cfe004 100644 --- a/madgraph/iolibs/template_files/madmatrix/backend/cpu/SigmaKin.cc +++ b/madgraph/iolibs/template_files/madmatrix/backend/cpu/SigmaKin.cc @@ -1374,7 +1374,17 @@ namespace madmatrix // dedup. A row that far below the largest cannot bias the helicity sum // whichever way it is paired, while a genuine parity violation shows up // at the relative level. One verdict for every crossing. + // FP32 amplitudes (FPTYPE=f and the default v) round at ~1e-7 per + // operation, so two mirror rows of a long helicity/colour sum differ + // by more than 1e-6: an FP64 tolerance there switches the dedup off + // (all ncomb rows evaluated, the mirrored half outside the + // hel-recycling table: v ran 1.7x slower than d on g g > t t~ g g). { +#if defined MGONGPU_FPTYPE_FLOAT + const fptype csymRel = (fptype)1e-4, csymAbs = (fptype)1e-6; +#else + const fptype csymRel = (fptype)1e-6, csymAbs = (fptype)1e-12; +#endif fptype mmax = (fptype)0.; for( int h = 0; h < ncomb; h++ ) for( int ie = 0; ie < neppV; ++ie ) @@ -1394,7 +1404,7 @@ namespace madmatrix if( d < (fptype)0. ) d = -d; const fptype aa = a < (fptype)0. ? -a : a; const fptype bb = b < (fptype)0. ? -b : b; - if( d > (fptype)1e-6 * ( aa + bb ) && d > (fptype)1e-12 * mmax ) + if( d > csymRel * ( aa + bb ) && d > csymAbs * mmax ) cCsymBad = true; } } diff --git a/madgraph/iolibs/template_files/madmatrix/backend/simd/SigmaKin.cc b/madgraph/iolibs/template_files/madmatrix/backend/simd/SigmaKin.cc index 1b20e59c0c..9ec9e013d3 100644 --- a/madgraph/iolibs/template_files/madmatrix/backend/simd/SigmaKin.cc +++ b/madgraph/iolibs/template_files/madmatrix/backend/simd/SigmaKin.cc @@ -1439,7 +1439,17 @@ namespace madmatrix // dedup. A row that far below the largest cannot bias the helicity sum // whichever way it is paired, while a genuine parity violation shows up // at the relative level. One verdict for every crossing. + // FP32 amplitudes (FPTYPE=f and the default v) round at ~1e-7 per + // operation, so two mirror rows of a long helicity/colour sum differ + // by more than 1e-6: an FP64 tolerance there switches the dedup off + // (all ncomb rows evaluated, the mirrored half outside the + // hel-recycling table: v ran 1.7x slower than d on g g > t t~ g g). { +#if defined MGONGPU_FPTYPE_FLOAT + const fptype csymRel = (fptype)1e-4, csymAbs = (fptype)1e-6; +#else + const fptype csymRel = (fptype)1e-6, csymAbs = (fptype)1e-12; +#endif fptype mmax = (fptype)0.; for( int h = 0; h < ncomb; h++ ) for( int ie = 0; ie < neppV; ++ie ) @@ -1459,7 +1469,7 @@ namespace madmatrix if( d < (fptype)0. ) d = -d; const fptype aa = a < (fptype)0. ? -a : a; const fptype bb = b < (fptype)0. ? -b : b; - if( d > (fptype)1e-6 * ( aa + bb ) && d > (fptype)1e-12 * mmax ) + if( d > csymRel * ( aa + bb ) && d > csymAbs * mmax ) cCsymBad = true; } } From 42a13e68989ffa0547dc3f4422f8cf5d4306c387 Mon Sep 17 00:00:00 2001 From: Olivier Mattelaer Date: Fri, 20 Nov 2026 08:30:45 +0100 Subject: [PATCH 3/7] MadtRex: stored-|M|^2 check tolerance follows the fptype _check_stored_matrix_elements warned when the stored matrix elements differ from re-evaluated ones by more than 1e-6, sized for the old color32 default (about 1e-7 apart). With FP32 amplitudes (denom64, the new default, and all32) an MLM run's stored |M|^2 (rescaled to the event's alpha_s) and the re-evaluation differ by a few 1e-6 (1.76e-6 on CI), so test_madtrex_reweights_mlm_events_with_their_stored_matrix_elements saw a false warning. The default tolerance is now 1e-5 for f/v, 1e-6 otherwise. Co-Authored-By: Claude Opus 5.5 --- madgraph/iolibs/template_files/mg7/madtrex_driver.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/madgraph/iolibs/template_files/mg7/madtrex_driver.py b/madgraph/iolibs/template_files/mg7/madtrex_driver.py index b141a389e0..ded1aaa8fa 100644 --- a/madgraph/iolibs/template_files/mg7/madtrex_driver.py +++ b/madgraph/iolibs/template_files/mg7/madtrex_driver.py @@ -531,7 +531,7 @@ def _generation_param_card(process_directory: str, events_path: str, param_card: def _check_stored_matrix_elements(events_path: str, init_meta, process_directory: str, param_card: str, devices: list[str], fptype: str, - sample: int = 32, rel_tol: float = 1e-6, + sample: int = 32, rel_tol: float | None = None, card_label: str = "") -> None: """Re-evaluates the original matrix element (helicity-summed, with param_card, at fptype) for a sample of the events of events_path whose @@ -541,9 +541,12 @@ def _check_stored_matrix_elements(events_path: str, init_meta, process_directory changing nothing normalised by the stored ones gives the ratio of the two as its weight over the event weight. rel_tol leaves room for an MLM run's stored matrix elements, which are the first evaluation rescaled to - the event's alpha_s rather than evaluated again (about 1e-7 apart at the - mixed fptype).""" + the event's alpha_s rather than evaluated again: about 1e-7 apart with + FP64 amplitudes (fptype d, m, e), a few 1e-6 with FP32 ones (f, v); the + default rel_tol is 1e-6, resp. 1e-5.""" import numpy as np + if rel_tol is None: + rel_tol = 1e-5 if fptype in ("f", "v") else 1e-6 if not events_path.endswith(".npy"): return events = np.load(events_path, mmap_mode="r", max_header_size=1 << 30) From 7c849b3f5565c51b18902a8af7232d2b567e0fb4 Mon Sep 17 00:00:00 2001 From: Olivier Mattelaer Date: Fri, 20 Nov 2026 13:34:29 +0100 Subject: [PATCH 4/7] docs: madmatrix library names follow the v default The madspace examples load libmadmatrix_sm_P0_gg_ttxg_scalar_m.so after a plain 'make BACKEND=scalar', which builds FPTYPE=v now: the docs examples CI could not load the library. Same in the gridpack build example, whose FPTYPE has to match the card's precision (denom64 by default). Co-Authored-By: Claude Opus 5.5 --- docs/source/gridpacks.rst | 2 +- docs/source/madspace/examples/flow-training.rst | 2 +- docs/source/madspace/examples/integrator-madnis.rst | 2 +- docs/source/madspace/examples/integrator.rst | 2 +- docs/source/madspace/examples/matrix-element.rst | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/source/gridpacks.rst b/docs/source/gridpacks.rst index 315d33ee4b..4e7e94e936 100644 --- a/docs/source/gridpacks.rst +++ b/docs/source/gridpacks.rst @@ -216,7 +216,7 @@ Matrix elements .. code-block:: bash cd SubProcesses - make -j8 BACKEND=simd_128 FPTYPE=m USEBUILDDIR=1 + make -j8 BACKEND=simd_128 FPTYPE=v USEBUILDDIR=1 ``BACKEND`` is the ``cpu_mode`` in ``Cards/grid_run_card.toml`` for a ``cpu`` device, and ``cuda`` or ``hip`` for a GPU. ``FPTYPE`` follows the ``precision`` of the card: diff --git a/docs/source/madspace/examples/flow-training.rst b/docs/source/madspace/examples/flow-training.rst index fef6814a72..3876aafa86 100644 --- a/docs/source/madspace/examples/flow-training.rst +++ b/docs/source/madspace/examples/flow-training.rst @@ -40,7 +40,7 @@ The mapping, cuts, matrix element, PDF and scale are exactly the same building b mapping = ms.PhaseSpaceMapping(masses, E_CM, mode="propagator", cuts=cuts) proc_dir = "PROC_ggttg" - me_path = os.path.join(proc_dir, "lib", "libmadmatrix_sm_P0_gg_ttxg_scalar_m.so") + me_path = os.path.join(proc_dir, "lib", "libmadmatrix_sm_P0_gg_ttxg_scalar_v.so") param_card = os.path.join(proc_dir, "Cards", "param_card.dat") ctx = ms.default_context() diff --git a/docs/source/madspace/examples/integrator-madnis.rst b/docs/source/madspace/examples/integrator-madnis.rst index 3f1a329697..f46a2c7848 100644 --- a/docs/source/madspace/examples/integrator-madnis.rst +++ b/docs/source/madspace/examples/integrator-madnis.rst @@ -38,7 +38,7 @@ random numbers are now PyTorch tensors, since MadNIS trains with PyTorch: mapping = ms.PhaseSpaceMapping(masses, E_CM, mode="propagator", cuts=cuts) proc_dir = "PROC_ggttg" - me_path = os.path.join(proc_dir, "lib", "libmadmatrix_sm_P0_gg_ttxg_scalar_m.so") + me_path = os.path.join(proc_dir, "lib", "libmadmatrix_sm_P0_gg_ttxg_scalar_v.so") param_card = os.path.join(proc_dir, "Cards", "param_card.dat") ctx = ms.default_context() diff --git a/docs/source/madspace/examples/integrator.rst b/docs/source/madspace/examples/integrator.rst index 0b91de83c0..2b069b82f6 100644 --- a/docs/source/madspace/examples/integrator.rst +++ b/docs/source/madspace/examples/integrator.rst @@ -42,7 +42,7 @@ examples, generated with ``output mg7 PROC_ggttg`` and ``make BACKEND=scalar`` b .. code-block:: python proc_dir = "PROC_ggttg" - me_path = os.path.join(proc_dir, "lib", "libmadmatrix_sm_P0_gg_ttxg_scalar_m.so") + me_path = os.path.join(proc_dir, "lib", "libmadmatrix_sm_P0_gg_ttxg_scalar_v.so") param_card = os.path.join(proc_dir, "Cards", "param_card.dat") ctx = ms.default_context() diff --git a/docs/source/madspace/examples/matrix-element.rst b/docs/source/madspace/examples/matrix-element.rst index 3a68857b3e..93b535c7d2 100644 --- a/docs/source/madspace/examples/matrix-element.rst +++ b/docs/source/madspace/examples/matrix-element.rst @@ -37,7 +37,7 @@ Loading the matrix element import madspace as ms proc_dir = "PROC_ggttg" - me_path = os.path.join(proc_dir, "lib", "libmadmatrix_sm_P0_gg_ttxg_scalar_m.so") + me_path = os.path.join(proc_dir, "lib", "libmadmatrix_sm_P0_gg_ttxg_scalar_v.so") param_card = os.path.join(proc_dir, "Cards", "param_card.dat") ctx = ms.default_context() From bb90202581232de506a0a069f7ebc48de2f7737e Mon Sep 17 00:00:00 2001 From: Olivier Mattelaer Date: Sat, 21 Nov 2026 07:53:56 +0100 Subject: [PATCH 5/7] precision_check: off by default; review fixes Addresses the review of #497: - [run] precision_check defaults to 0: the check compiles every subprocess a second time (all64); [run] validation (MadtRex) is the whole-sample alternative. - A GPU-only run never ran the check: the build loop reused 'fptype', and its last build is the scalar all64 one of the helicity choice, so the check saw 'd'. New test test_a_gpu_only_run_checks_its_own_precision. - Statistics: cross_section_bias is the signed mean of r = v/d - 1 (the unweighted events already follow |M|^2); the |M|^2-weighted number, which applied |M|^2 twice, is gone. Mean and max of |r| stay. - LHE output: the events are drawn at random from the whole file (reservoir sampling over the raw text, only the kept ones parsed), not the first N. - precision_check.json is strict JSON: non-finite values as strings. Co-Authored-By: Claude Opus 5.5 --- docs/source/run_card.rst | 19 +++-- .../iolibs/template_files/mg7/run_card.toml | 3 +- madgraph/mg7/madgraph_process.py | 14 ++-- madgraph/mg7/precision_check.py | 82 ++++++++++++------- madgraph/various/banner.py | 8 +- .../interface/test_auto_width_nlo.py | 27 ++++++ .../interface/test_mg7_precision_check.py | 25 ++++-- 7 files changed, 126 insertions(+), 52 deletions(-) diff --git a/docs/source/run_card.rst b/docs/source/run_card.rst index 0c1184f403..e7af6e195d 100644 --- a/docs/source/run_card.rst +++ b/docs/source/run_card.rst @@ -61,16 +61,19 @@ fixed parameters. Their entries are described below. and everything else in double precision. ``denom64``, the default, keeps the momenta and propagator denominators in double precision and uses single precision elsewhere. -``precision_check`` (``0.01``) +``precision_check`` (``0``) Fraction of the events evaluated again with the matrix elements in ``all64``, to check - the precision of a run in any other precision. The run then also builds an ``all64`` - CPU library of each subprocess and, once the events are written, compares the two at - the momenta of the first events of the output (at most 1000 of them, hidden entry - ``precision_check_max_events``). The mean, ``|M|^2``-weighted and maximal relative - deviations are logged and written to ``Events//precision_check.json``; the run - warns when an event deviates by more than ``1e-3`` (hidden entry + the precision of a run in any other precision. Off by default, because the run then + also builds an ``all64`` CPU library of each subprocess (``validation`` below + reweights the whole sample through MadtRex instead). Once the events are written, the + two are compared at the momenta of events drawn at random from the output (at most + 1000 of them, hidden entry ``precision_check_max_events``). With + ``r = |M|^2 / |M|^2_all64 - 1`` per event, the mean of ``r`` (the relative change of the + cross section, since unweighted events already follow ``|M|^2``), the mean and the + maximum of ``|r|`` are logged and written to ``Events//precision_check.json``; the + run warns when an event deviates by more than ``1e-3`` (hidden entry ``precision_check_threshold``) or is not finite, in which case ``all64`` or ``color32`` - is the safer choice for that process. ``0`` disables the check, and the extra build. + is the safer choice for that process. ``cpu_thread_pool_size`` (``-1``), ``gpu_thread_pool_size`` (``1``), ``combine_thread_pool_size`` (``-1``) diff --git a/madgraph/iolibs/template_files/mg7/run_card.toml b/madgraph/iolibs/template_files/mg7/run_card.toml index 9059b4841d..c28df91ed9 100644 --- a/madgraph/iolibs/template_files/mg7/run_card.toml +++ b/madgraph/iolibs/template_files/mg7/run_card.toml @@ -12,7 +12,8 @@ cpu_mode = %(run.cpu_mode)s madspace_cpu_mode = %(run.madspace_cpu_mode)s # matrix element precision; options: all64, all32, color32, denom64 precision = %(run.precision)s -# fraction of the events evaluated again in all64 to check the precision (0: no check) +# fraction of the events evaluated again in all64 to check the precision (0: no check); +# builds the matrix elements a second time, in all64 precision_check = %(run.precision_check)s # after the generation, reweight the events to the matrix elements compiled at # this FPTYPE and report how many significant digits they share with the diff --git a/madgraph/mg7/madgraph_process.py b/madgraph/mg7/madgraph_process.py index f583238e78..b9cd30ec1c 100644 --- a/madgraph/mg7/madgraph_process.py +++ b/madgraph/mg7/madgraph_process.py @@ -1977,27 +1977,31 @@ def compile_matrix_elements(self) -> list[str]: builds = [(backend, fptype) for backend in resolved] if not cpu_backends and not self.run_card["run"]["dummy_matrix_element"]: builds.append(self.helicity_choice_build) - for backend, fptype in builds: + # (not 'backend, fptype': a GPU-only run's last build is the scalar + # all64 one of the helicity choice, and the precision check below + # needs the run's fptype) + for build_backend, build_fptype in builds: # by library: the flavours of a split subprocess share one; a library # built with other recycling settings is rebuilt too: its SigmaKin.o # records them in build._/.hrflags (madmatrix.mk) missing = list({ meta["me_path"]: meta for meta in madmatrix_data if not os.path.isfile( - meta["me_path"].format(device=backend, fptype=fptype) + meta["me_path"].format(device=build_backend, fptype=build_fptype) ) or self.hel_recycling_flags_changed( - meta["path"], backend, fptype, hr_flags) + meta["path"], build_backend, build_fptype, hr_flags) }.values()) if not missing: continue logger.info( - f"Start compilation of SubProcesses for device '{backend}' " + f"Start compilation of SubProcesses for device '{build_backend}' " f"({len(missing)} subprocess(es), {nb_core} parallel job(s)), " f"see log detail in {log_path}" ) start_time = time.time() - make_args = [f"BACKEND={backend}", f"FPTYPE={fptype}", "USEBUILDDIR=1"] + make_args = [f"BACKEND={build_backend}", f"FPTYPE={build_fptype}", + "USEBUILDDIR=1"] make_args += self.extra_make_args + hr_args if (len(missing) >= PCH_MIN_SUBPROCESSES and not any(arg.startswith("PCH=") for arg in make_args)): diff --git a/madgraph/mg7/precision_check.py b/madgraph/mg7/precision_check.py index 20b36cf245..2aef2db8b8 100644 --- a/madgraph/mg7/precision_check.py +++ b/madgraph/mg7/precision_check.py @@ -5,16 +5,19 @@ momenta and the propagator denominators in double precision) evaluates the matrix elements in single precision, which is accurate to ~1e-6 on most phase space points but can lose digits where the amplitudes cancel. With -[run] precision_check > 0, the run builds the CPU library of each MadMatrix -subprocess in its own precision and in all64 (FPTYPE=d) and, once the events -are written, evaluates a sample of them with both, at the same momenta, flavour -and alpha_s, with the same good helicities. It reports the relative deviation -|M2 - M2_d| / |M2_d|: its mean over the unweighted events estimates the -relative bias of the cross section; its maximum and the number of events above -[run] precision_check_threshold flag unstable phase-space regions. - -The sample is the first events of the output (the events are written in a -random order), so an LHE output need not be read to its end. The events are +[run] precision_check > 0 (off by default: it compiles every subprocess a +second time; [run] validation reweights the whole sample through MadtRex +instead), the run builds the CPU library of each MadMatrix subprocess in its +own precision and in all64 (FPTYPE=d) and, once the events are written, +evaluates a sample of them with both, at the same momenta, flavour and alpha_s, +with the same good helicities. With r = M2 / M2_d - 1 per event, it reports: + * the mean of r: the unweighted events follow dsigma ~ PDF |M2|, so this is + the relative change of the cross section from the precision; + * the mean and the maximum of |r|, and the number of events with |r| above + [run] precision_check_threshold: unstable phase-space regions. + +The sample is drawn at random from the whole output (an LHE output is read to +its end, but only the sampled events are parsed). The events are matched to a library and flavour by their PDG ids (incoming then outgoing, resonances left out, as in the output), the incoming legs swapped for the mirrored flavours; events that match none (an AmpliCol subprocess) are not @@ -216,19 +219,32 @@ def _npy_events(path, count, rng): return rows -def _lhe_events(path, count): - """The pdg ids, momenta and alpha_s of the first count events of an LHE - output.""" +def _lhe_events(path, count, rng): + """The pdg ids, momenta and alpha_s of count events of an LHE output, + drawn at random: one pass over the raw text of the events (reservoir + sampling), parsing only the ones kept.""" from madgraph.various import lhe_parser + texts = [] + lhe = lhe_parser.EventFile(path) + lhe.parsing = False + try: + for seen, text in enumerate(lhe): + if seen < count: + texts.append(text) + else: + slot = int(rng.integers(0, seen + 1)) + if slot < count: + texts[slot] = text + finally: + lhe.close() rows = [] - for event in lhe_parser.EventFile(path): + for text in texts: + event = lhe_parser.Event(text) kept = [p for p in event if p.status in (-1, 1)] rows.append(dict(pdgs=tuple(int(p.pid) for p in kept), momenta=[[p.E, p.px, p.py, p.pz] for p in kept], alpha_s=float(event.aqcd))) - if len(rows) >= count: - break return rows @@ -250,7 +266,8 @@ def _compact_pdgs(process, subproc_index, flavor_index): # the check # ---------------------------------------------------------------------------- def summarize(values, references, threshold): - """The statistics of the relative deviation of values from references.""" + """The statistics of r = values / references - 1 over unweighted events + (see the module docstring).""" import numpy as np values = np.asarray(values, dtype=float) @@ -261,20 +278,30 @@ def summarize(values, references, threshold): rel = np.where(scale > 0, np.abs(values - references) / scale, np.where(values == references, 0., np.inf)) rel = np.where(finite, rel, np.inf) - total = float(np.sum(scale[finite])) + # signed, over the events with a finite, non-zero reference: the events + # already follow |M|^2, so its mean is the relative change of the cross + # section (no |M|^2 weight on top) + usable = finite & (scale > 0) + signed = (values[usable] - references[usable]) / references[usable] return { "events": int(len(values)), "non_finite": int(np.sum(~finite)), + "cross_section_bias": float(np.mean(signed)) if len(signed) else 0., "mean_relative_deviation": float(np.mean(rel)) if len(rel) else 0., "max_relative_deviation": float(np.max(rel)) if len(rel) else 0., - # the |M|^2-weighted mean: the relative change of a sum over the events - "weighted_relative_deviation": - float(np.sum(np.abs(values - references)[finite]) / total) if total > 0 else 0., "above_threshold": int(np.sum(rel > threshold)), "threshold": float(threshold), } +def _json_safe(summary): + """summary with its non-finite floats as strings ("inf", "nan"): strict + JSON has no Infinity/NaN.""" + return {key: (repr(value) if isinstance(value, float) and not math.isfinite(value) + else value) + for key, value in summary.items()} + + def run(process): """The precision check of the events process wrote (see the module docstring). Returns its summary, also written to the run directory, or @@ -304,7 +331,7 @@ def _run(process): if events_path.endswith(".npy"): rows = _npy_events(events_path, count, np.random.default_rng(process.run_seed)) else: - rows = _lhe_events(events_path, count) + rows = _lhe_events(events_path, count, np.random.default_rng(process.run_seed)) table = flavor_table(process) groups = {} @@ -365,13 +392,12 @@ def libraries(build_backend, build_fptype): "events_path": os.path.basename(events_path), }) with open(os.path.join(process.run_path, RESULT_FILE), "w") as f: - json.dump(summary, f, indent=1) + json.dump(_json_safe(summary), f, indent=1, allow_nan=False) - message = ("precision check (%s vs all64, %d events): mean relative deviation " - "%.2g, |M|^2-weighted %.2g, max %.2g; %d above %.0e%s") - args = (run_card["precision"], summary["events"], - summary["mean_relative_deviation"], summary["weighted_relative_deviation"], - summary["max_relative_deviation"], summary["above_threshold"], threshold, + message = ("precision check (%s vs all64, %d events): cross-section bias %.2g, " + "mean |relative deviation| %.2g, max %.2g; %d above %.0e%s") + args = (run_card["precision"], summary["events"], summary["cross_section_bias"], + summary["mean_relative_deviation"], summary["max_relative_deviation"], summary["above_threshold"], threshold, ", %d not finite" % summary["non_finite"] if summary["non_finite"] else "") if summary["above_threshold"] or summary["non_finite"]: logger.warning(message + ". This process may need [run] precision = " diff --git a/madgraph/various/banner.py b/madgraph/various/banner.py index e0bcbef57c..90fa048494 100644 --- a/madgraph/various/banner.py +++ b/madgraph/various/banner.py @@ -7347,9 +7347,11 @@ def default_setup(self): allowed=['all64', 'all32', 'color32', 'denom64'], comment="matrix element precision: all64, all32, color32 (FP32 color sum) or denom64 (FP64 momenta and propagator denominators)") # The precision check (madgraph/mg7/precision_check.py): a fraction of - # the events evaluated again in all64, for a precision other than all64 - self.add_toml_param('run', 'precision_check', 0.01, - comment="fraction of the events evaluated again in all64 to check the precision (0: no check); needs an all64 build of the matrix elements") + # the events evaluated again in all64, for a precision other than all64. + # Off by default: it builds every subprocess a second time (in all64); + # 'validation' below reweights the whole sample through MadtRex instead. + self.add_toml_param('run', 'precision_check', 0.0, + comment="fraction of the events evaluated again in all64 to check the precision (0: no check, the default); builds the matrix elements a second time, in all64") self.add_toml_param('run', 'precision_check_max_events', 1000, hidden=True, comment="the precision check evaluates at most this many events") self.add_toml_param('run', 'precision_check_threshold', 1e-3, hidden=True, diff --git a/tests/unit_tests/interface/test_auto_width_nlo.py b/tests/unit_tests/interface/test_auto_width_nlo.py index bc20c37be8..ef9369681d 100644 --- a/tests/unit_tests/interface/test_auto_width_nlo.py +++ b/tests/unit_tests/interface/test_auto_width_nlo.py @@ -935,6 +935,33 @@ def test_only_what_is_to_build_counts(self): process.compile_matrix_elements() self.assertNotIn('PCH=1', make.call_args[0][1]) + def test_a_gpu_only_run_checks_its_own_precision(self): + """A cuda-only run also builds the scalar all64 library of the + helicity choice, last: the precision check must still get the run's + FPTYPE (v), not that build's d, which disabled it.""" + from madgraph.mg7 import launch as mg7_launch + process = object.__new__(mg7_launch.MadgraphProcess) + process.run_card = {'run': {'device': ['cuda'], 'cpu_mode': 'auto', + 'precision': 'denom64', 'cpu_thread_pool_size': 2, + 'dummy_matrix_element': False, + 'precision_check': 0.05}} + process.run_path = self.tmp + process.extra_make_args = [] + process.subprocess_data = [ + {'path': pjoin('SubProcesses', 'P0_x'), + 'me_path': pjoin(self.tmp, 'libmadmatrix_P0_x_{device}_{fptype}.so')}] + with mock.patch.object(mg7_launch.MadgraphProcess, 'make_subprocesses') as make, \ + mock.patch.object(mg7_launch.MadgraphProcess, + 'compile_precision_check') as check: + process.compile_matrix_elements() + built = [(a for a in call[0][1]) for call in make.call_args_list] + built = [sorted(arg for arg in args if arg.startswith(('BACKEND=', 'FPTYPE='))) + for args in built] + self.assertEqual(built, [['BACKEND=cuda', 'FPTYPE=v'], + ['BACKEND=scalar', 'FPTYPE=d']]) + check.assert_called_once() + self.assertEqual(check.call_args[0][3], 'v') + def test_an_explicit_pch_is_respected(self): self.assertNotIn('PCH=1', self.compile_args(10, ['PCH=0'])) self.assertIn('PCH=0', self.compile_args(10, ['PCH=0'])) diff --git a/tests/unit_tests/interface/test_mg7_precision_check.py b/tests/unit_tests/interface/test_mg7_precision_check.py index 6597aa5c2d..e028f8998e 100644 --- a/tests/unit_tests/interface/test_mg7_precision_check.py +++ b/tests/unit_tests/interface/test_mg7_precision_check.py @@ -42,7 +42,7 @@ class TestPrecisionDefault(unittest.TestCase): def test_run_card_default_is_denom64(self): card = RunCardMG7() self.assertEqual(card['run']['precision'], 'denom64') - self.assertEqual(card['run']['precision_check'], 0.01) + self.assertEqual(card['run']['precision_check'], 0.0) self.assertEqual(card['run']['precision_check_max_events'], 1000) self.assertEqual(card['run']['precision_check_threshold'], 1e-3) @@ -54,9 +54,9 @@ def test_written_run_card_has_the_precision_check(self): with open(path) as f: text = f.read() self.assertIn('precision = "denom64"', text) - self.assertIn('precision_check = 0.01', text) + self.assertIn('precision_check = 0.0', text) card = RunCardMG7(path) - self.assertEqual(card['run']['precision_check'], 0.01) + self.assertEqual(card['run']['precision_check'], 0.0) finally: shutil.rmtree(tmpdir) @@ -86,8 +86,8 @@ def test_statistics(self): self.assertEqual(summary['non_finite'], 0) self.assertAlmostEqual(summary['max_relative_deviation'], 1e-3) self.assertAlmostEqual(summary['mean_relative_deviation'], 1e-3 / 3) - # |M|^2-weighted: the relative change of the sum - self.assertAlmostEqual(summary['weighted_relative_deviation'], 0.002 / 6.0) + # signed mean of r = v/d - 1: the relative change of the cross section + self.assertAlmostEqual(summary['cross_section_bias'], 1e-3 / 3) self.assertEqual(summary['above_threshold'], 1) self.assertEqual(summary['threshold'], 1e-4) @@ -98,8 +98,19 @@ def test_zero_and_non_finite(self): self.assertEqual(summary['non_finite'], 2) self.assertEqual(summary['above_threshold'], 3) self.assertTrue(math.isinf(summary['max_relative_deviation'])) - # the weighted mean only sums the finite events - self.assertEqual(summary['weighted_relative_deviation'], 0.0) + # the bias only averages finite events with a non-zero reference + self.assertEqual(summary['cross_section_bias'], 0.0) + + def test_bias_is_signed(self): + summary = precision_check.summarize([1.001, 0.999], [1.0, 1.0], 1e-2) + self.assertAlmostEqual(summary['cross_section_bias'], 0.0) + self.assertAlmostEqual(summary['mean_relative_deviation'], 1e-3) + + def test_json_safe(self): + import json + summary = precision_check.summarize([float('inf')], [1.0], 1e-3) + text = json.dumps(precision_check._json_safe(summary), allow_nan=False) + self.assertEqual(json.loads(text)['max_relative_deviation'], 'inf') def test_identical(self): summary = precision_check.summarize([1.5, 2.5], [1.5, 2.5], 1e-3) From 55b865618fcbe88d91e9af514458dbd8bd1b4f59 Mon Sep 17 00:00:00 2001 From: Olivier Mattelaer Date: Sun, 22 Nov 2026 05:40:53 +0100 Subject: [PATCH 6/7] precision_check: review fixes - summarize: the mean |r| averages the same events as the cross-section bias (finite, non-zero reference); one non-finite event no longer makes it inf, it still shows in non_finite, above_threshold and the max. - compile_precision_check: count the missing libraries by me_path, as the main build loop does, for the PCH decision. - run_card.rst: name [run] validation instead of pointing to an entry that is not documented. Co-Authored-By: Claude Opus 5.5 --- docs/source/run_card.rst | 2 +- madgraph/mg7/madgraph_process.py | 7 ++++--- madgraph/mg7/precision_check.py | 4 +++- .../unit_tests/interface/test_mg7_precision_check.py | 11 ++++++++++- 4 files changed, 18 insertions(+), 6 deletions(-) diff --git a/docs/source/run_card.rst b/docs/source/run_card.rst index e7af6e195d..c2630c4280 100644 --- a/docs/source/run_card.rst +++ b/docs/source/run_card.rst @@ -64,7 +64,7 @@ fixed parameters. Their entries are described below. ``precision_check`` (``0``) Fraction of the events evaluated again with the matrix elements in ``all64``, to check the precision of a run in any other precision. Off by default, because the run then - also builds an ``all64`` CPU library of each subprocess (``validation`` below + also builds an ``all64`` CPU library of each subprocess (``[run] validation`` reweights the whole sample through MadtRex instead). Once the events are written, the two are compared at the momenta of events drawn at random from the output (at most 1000 of them, hidden entry ``precision_check_max_events``). With diff --git a/madgraph/mg7/madgraph_process.py b/madgraph/mg7/madgraph_process.py index abf6a28614..e2987bdca5 100644 --- a/madgraph/mg7/madgraph_process.py +++ b/madgraph/mg7/madgraph_process.py @@ -2089,13 +2089,14 @@ def compile_precision_check( for build_backend, build_fptype in checks: if (build_backend, build_fptype) in builds: continue - missing = [ - meta for meta in madmatrix_data + # by library, as above + missing = list({ + meta["me_path"]: meta for meta in madmatrix_data if not os.path.isfile(meta["me_path"].format( device=build_backend, fptype=build_fptype)) or self.hel_recycling_flags_changed( meta["path"], build_backend, build_fptype, hr_flags) - ] + }.values()) if not missing: continue logger.info( diff --git a/madgraph/mg7/precision_check.py b/madgraph/mg7/precision_check.py index 2aef2db8b8..0addb95c38 100644 --- a/madgraph/mg7/precision_check.py +++ b/madgraph/mg7/precision_check.py @@ -283,11 +283,13 @@ def summarize(values, references, threshold): # section (no |M|^2 weight on top) usable = finite & (scale > 0) signed = (values[usable] - references[usable]) / references[usable] + # the mean |r| over the same events: one infinitely-off event (counted in + # non_finite / above_threshold, and in the max) does not hide the others return { "events": int(len(values)), "non_finite": int(np.sum(~finite)), "cross_section_bias": float(np.mean(signed)) if len(signed) else 0., - "mean_relative_deviation": float(np.mean(rel)) if len(rel) else 0., + "mean_relative_deviation": float(np.mean(np.abs(signed))) if len(signed) else 0., "max_relative_deviation": float(np.max(rel)) if len(rel) else 0., "above_threshold": int(np.sum(rel > threshold)), "threshold": float(threshold), diff --git a/tests/unit_tests/interface/test_mg7_precision_check.py b/tests/unit_tests/interface/test_mg7_precision_check.py index e028f8998e..ebfe001652 100644 --- a/tests/unit_tests/interface/test_mg7_precision_check.py +++ b/tests/unit_tests/interface/test_mg7_precision_check.py @@ -98,8 +98,17 @@ def test_zero_and_non_finite(self): self.assertEqual(summary['non_finite'], 2) self.assertEqual(summary['above_threshold'], 3) self.assertTrue(math.isinf(summary['max_relative_deviation'])) - # the bias only averages finite events with a non-zero reference + # the bias and the mean |r| only average finite events with a + # non-zero reference self.assertEqual(summary['cross_section_bias'], 0.0) + self.assertEqual(summary['mean_relative_deviation'], 0.0) + + def test_one_bad_event_keeps_the_mean(self): + summary = precision_check.summarize( + [1.001, 0.999, float('nan')], [1.0, 1.0, 1.0], 1e-2) + self.assertAlmostEqual(summary['mean_relative_deviation'], 1e-3) + self.assertTrue(math.isinf(summary['max_relative_deviation'])) + self.assertEqual(summary['above_threshold'], 1) def test_bias_is_signed(self): summary = precision_check.summarize([1.001, 0.999], [1.0, 1.0], 1e-2) From 24013e10285ee7fb7a2aa9a8b174c593495ebd06 Mon Sep 17 00:00:00 2001 From: Olivier Mattelaer Date: Sun, 22 Nov 2026 05:40:53 +0100 Subject: [PATCH 7/7] madmatrix: FP32 C-parity tolerances 1e-5 relative and absolute The FP32 C-parity scan used 1e-4 relative and 1e-6 of the largest |M|^2. Measured on the scan points (simd_128), the mirror rows of C-symmetric processes differ by up to 7e-7 of the largest |M|^2 (g g > t t~ g g in f), 1.5x below that cut, so the relative test never acted and one harder point of a run could latch the dedup off. A genuine parity violation is O(1) on both measures (0.7 for u u~ > e+ e-, u u~ > z g g). Both FP32 tolerances are now 1e-5: a pair is flagged only above both, the cut against the largest |M|^2 ~15x above the roundoff. g g > t t~ g g and u u~ > t t~ g g (v, f) keep the dedup, u u~ > e+ e- is refused it (simd and scalar). FP64 builds keep 1e-6 / 1e-12. Co-Authored-By: Claude Opus 5.5 --- .../madmatrix/backend/cpu/SigmaKin.cc | 16 +++++++++++----- .../madmatrix/backend/simd/SigmaKin.cc | 16 +++++++++++----- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/madgraph/iolibs/template_files/madmatrix/backend/cpu/SigmaKin.cc b/madgraph/iolibs/template_files/madmatrix/backend/cpu/SigmaKin.cc index e72695ec8a..04af130030 100644 --- a/madgraph/iolibs/template_files/madmatrix/backend/cpu/SigmaKin.cc +++ b/madgraph/iolibs/template_files/madmatrix/backend/cpu/SigmaKin.cc @@ -1312,13 +1312,19 @@ namespace madmatrix // whichever way it is paired, while a genuine parity violation shows up // at the relative level. One verdict for every crossing. // FP32 amplitudes (FPTYPE=f and the default v) round at ~1e-7 per - // operation, so two mirror rows of a long helicity/colour sum differ - // by more than 1e-6: an FP64 tolerance there switches the dedup off - // (all ncomb rows evaluated, the mirrored half outside the - // hel-recycling table: v ran 1.7x slower than d on g g > t t~ g g). + // operation: an FP64 tolerance there switches the dedup off (all ncomb + // rows evaluated, the mirrored half outside the hel-recycling table: v + // ran 1.7x slower than d on g g > t t~ g g). Measured on the scan + // points (simd_128, FP32), the mirror rows of C-symmetric processes + // differ by up to 7e-7 of the largest |M|^2 and 1.3e-5 of the pair + // (g g > t t~ g g (g), u u~ > t t~ g g), a genuine parity violation by + // O(1) on both (0.7 for u u~ > e+ e-, u u~ > z g g). A pair is flagged + // only above both FP32 tolerances (1e-5): the cut against the largest + // |M|^2 stays ~15x above the roundoff (as the verdict latches, one + // harder point of the run must not switch the dedup off). { #if defined MADMATRIX_FPTYPE_FLOAT - const fptype csymRel = (fptype)1e-4, csymAbs = (fptype)1e-6; + const fptype csymRel = (fptype)1e-5, csymAbs = (fptype)1e-5; #else const fptype csymRel = (fptype)1e-6, csymAbs = (fptype)1e-12; #endif diff --git a/madgraph/iolibs/template_files/madmatrix/backend/simd/SigmaKin.cc b/madgraph/iolibs/template_files/madmatrix/backend/simd/SigmaKin.cc index f4d0da5c7e..be951bb485 100644 --- a/madgraph/iolibs/template_files/madmatrix/backend/simd/SigmaKin.cc +++ b/madgraph/iolibs/template_files/madmatrix/backend/simd/SigmaKin.cc @@ -1413,13 +1413,19 @@ namespace madmatrix // whichever way it is paired, while a genuine parity violation shows up // at the relative level. One verdict for every crossing. // FP32 amplitudes (FPTYPE=f and the default v) round at ~1e-7 per - // operation, so two mirror rows of a long helicity/colour sum differ - // by more than 1e-6: an FP64 tolerance there switches the dedup off - // (all ncomb rows evaluated, the mirrored half outside the - // hel-recycling table: v ran 1.7x slower than d on g g > t t~ g g). + // operation: an FP64 tolerance there switches the dedup off (all ncomb + // rows evaluated, the mirrored half outside the hel-recycling table: v + // ran 1.7x slower than d on g g > t t~ g g). Measured on the scan + // points (simd_128, FP32), the mirror rows of C-symmetric processes + // differ by up to 7e-7 of the largest |M|^2 and 1.3e-5 of the pair + // (g g > t t~ g g (g), u u~ > t t~ g g), a genuine parity violation by + // O(1) on both (0.7 for u u~ > e+ e-, u u~ > z g g). A pair is flagged + // only above both FP32 tolerances (1e-5): the cut against the largest + // |M|^2 stays ~15x above the roundoff (as the verdict latches, one + // harder point of the run must not switch the dedup off). { #if defined MADMATRIX_FPTYPE_FLOAT - const fptype csymRel = (fptype)1e-4, csymAbs = (fptype)1e-6; + const fptype csymRel = (fptype)1e-5, csymAbs = (fptype)1e-5; #else const fptype csymRel = (fptype)1e-6, csymAbs = (fptype)1e-12; #endif