From 0aa4709fb53deb2518b235e9a06195dbb81a9dc4 Mon Sep 17 00:00:00 2001 From: stloufra Date: Wed, 18 Nov 2026 16:46:51 +0100 Subject: [PATCH 01/14] Add FASTMATH=auto to madmatrix Fast math per subprocess, kept unless approx div/sqrt grow jamps spill stack. --- .../template_files/madmatrix/madmatrix.mk | 49 +++++++++++++++++-- 1 file changed, 45 insertions(+), 4 deletions(-) diff --git a/madgraph/iolibs/template_files/madmatrix/madmatrix.mk b/madgraph/iolibs/template_files/madmatrix/madmatrix.mk index b723350f14..08957298ce 100644 --- a/madgraph/iolibs/template_files/madmatrix/madmatrix.mk +++ b/madgraph/iolibs/template_files/madmatrix/madmatrix.mk @@ -26,6 +26,11 @@ ifeq ($(HELINL),) override HELINL = 0 endif +# Set the default FASTMATH choice (0: IEEE-strict, i.e. no fast-math and no FP contraction) +ifeq ($(FASTMATH),) + override FASTMATH = 1 +endif + # default USEBUILDDIR = 1 ifeq ($(USEBUILDDIR),) override USEBUILDDIR = 1 @@ -57,6 +62,14 @@ ifneq ($(filter-out 0,$(HRDCOD)),) $(error HRDCOD=$(HRDCOD) is no longer supported: model parameters are always read at runtime (#226)) endif +override SUPPORTED_FASTMATHS = 0 1 auto +ifneq ($(words $(filter $(FASTMATH), $(SUPPORTED_FASTMATHS))),1) + $(error Invalid fastmath FASTMATH='$(FASTMATH)': supported fastmaths are $(foreach fastmath,$(SUPPORTED_FASTMATHS),'$(fastmath)')) +endif +ifeq ($(FASTMATH)$(filter-out cuda,$(BACKEND)),auto$(BACKEND)) + $(error FASTMATH='auto' is implemented for BACKEND=cuda only) +endif + # Stop immediately if BACKEND=cuda but nvcc is missing ifeq ($(BACKEND),cuda) ifeq ($(shell which nvcc 2>/dev/null),) @@ -163,7 +176,9 @@ endif #=== Configure the C++ compiler CXXFLAGS = $(OPTFLAGS) -std=c++20 -Wall -Wshadow -Wextra -ifeq ($(shell $(CXX) --version | grep ^nvc++),) +ifeq ($(FASTMATH),0) + CXXFLAGS += -fno-fast-math -ffp-contract=off +else ifeq ($(shell $(CXX) --version | grep ^nvc++),) CXXFLAGS += -ffast-math # see issue #117 endif ###CXXFLAGS+= -Ofast # performance is not different from --fast-math @@ -294,7 +309,13 @@ ifeq ($(BACKEND),cuda) ###GPUCC_VERSION = $(shell $(GPUCC) --version | grep 'Cuda compilation tools' | cut -d' ' -f5 | cut -d, -f1) # Fast math - GPUFLAGS += -use_fast_math + ifeq ($(FASTMATH),0) + GPUFLAGS += -fmad=false + else ifeq ($(FASTMATH),auto) + GPUFLAGS += -fmad=true + else + GPUFLAGS += -use_fast_math + endif # Extra build warnings GPUFLAGS += $(XCOMPILERFLAG) -Wunused-parameter @@ -352,7 +373,11 @@ else ifeq ($(BACKEND),hip) GPUFLAGS += -target x86_64-linux-gnu -DHIP_PLATFORM=amd # Fast math (is -DHIP_FAST_MATH equivalent to -ffast-math?) - GPUFLAGS += -DHIP_FAST_MATH + ifeq ($(FASTMATH),0) + GPUFLAGS += -ffp-contract=off + else + GPUFLAGS += -DHIP_FAST_MATH + endif # Extra build warnings ###GPUFLAGS += $(XCOMPILERFLAG) -Wall $(XCOMPILERFLAG) -Wextra $(XCOMPILERFLAG) -Wshadow @@ -763,7 +788,7 @@ endif # Build lockfile "full" tag (defines full specification of object-file builds that cannot be intermixed) # NB: the backend name is used as-is ('simd_128', 'scalar', 'cuda', 'hip'...) -override TAG = $(BACKEND)_$(FPTYPE)_inl$(HELINL) +override TAG = $(BACKEND)_$(FPTYPE)_inl$(HELINL)_fm$(FASTMATH) # Export TAG (so that there is no need to check/define it again in src/Makefile) export TAG @@ -937,6 +962,22 @@ $(BUILDDIR)/%%.o : %%.cc *.h ../../backend/$(BACKENDDIR)/*.h ../../backend/commo $(GPUCC) $(CPPFLAGS) $(INCFLAGS) $(GPUFLAGS) -c -x $(GPULANGUAGE) $< -o $@ endif +# FASTMATH=auto: SigmaKin.o is built with -fmad and with -use_fast_math. The approximate div/sqrt of +# the latter make calculate_jamps spill more, which costs more than they save once its stack grows by +# more than FASTMATH_STACK_GROWTH bytes (fast-math benchmarks on L40S and H100): then -fmad is kept. +ifeq ($(FASTMATH),auto) +FASTMATH_STACK_GROWTH ?= 128 +override JAMPS_STACK = $(CUDA_HOME)/bin/cuobjdump -res-usage $(1) | awk '/Function .*calculate_jamps/ { getline; sub(/.*STACK:/, ""); if ($$1 + 0 > max) max = $$1 + 0 } END { print max + 0 }' +$(BUILDDIR)/SigmaKin.o : SigmaKin.cc *.h ../../backend/$(BACKENDDIR)/*.h ../../backend/common/*.h $(SRC)/*.h $(SRC)/rambo/*.h $(BUILDDIR)/.build.$(TAG) + @if [ ! -d $(BUILDDIR) ]; then echo "mkdir -p $(BUILDDIR)"; mkdir -p $(BUILDDIR); fi + $(GPUCC) $(CPPFLAGS) $(INCFLAGS) $(GPUFLAGS) -c -x $(GPULANGUAGE) $< -o $(@:.o=.mad.o) & mad=$$!; \ + $(GPUCC) $(CPPFLAGS) $(INCFLAGS) $(GPUFLAGS) -use_fast_math -c -x $(GPULANGUAGE) $< -o $(@:.o=.fm1.o) && wait $$mad + @growth=$$(( $$($(call JAMPS_STACK,$(@:.o=.fm1.o))) - $$($(call JAMPS_STACK,$(@:.o=.mad.o))) )); \ + if [ $$growth -le $(FASTMATH_STACK_GROWTH) ]; then pick=fm1; else pick=mad; fi; \ + cp $(@:.o=.$$pick.o) $@; \ + echo "FASTMATH=auto $(processid_short): calculate_jamps stack +$$growth B with -use_fast_math, keeping $$pick" | tee $(@:.o=.fastmath) +endif + #------------------------------------------------------------------------------- # Target (and build rules): common (src) library From 8548838f7e5eeef62f1019334692fc33ef017455 Mon Sep 17 00:00:00 2001 From: stloufra Date: Thu, 19 Nov 2026 11:01:40 +0100 Subject: [PATCH 02/14] Add shared-memory wavefunctions and SHAREDWF=auto to madmatrix Hot wf slots by generator score in GPU shared mem, kept only where calculate_jamps spills without. Co-Authored-By: Claude Opus 5.5 --- .../madmatrix/backend/cpu/SigmaKin.cc | 3 + .../madmatrix/backend/gpu/GpuAbstraction.h | 8 +- .../madmatrix/backend/gpu/SigmaKin.cc | 119 +++++++++++++++++- .../madmatrix/backend/simd/SigmaKin.cc | 3 + .../template_files/madmatrix/madmatrix.mk | 58 +++++++-- madmatrix/model_handling.py | 46 +++++++ 6 files changed, 223 insertions(+), 14 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..c0909ca328 100644 --- a/madgraph/iolibs/template_files/madmatrix/backend/cpu/SigmaKin.cc +++ b/madgraph/iolibs/template_files/madmatrix/backend/cpu/SigmaKin.cc @@ -496,6 +496,8 @@ namespace madmatrix // event page is processed serially within the helicity loop, so a plain // sum suffices (CUDA needs atomicAdd instead: see backend/gpu/SigmaKin.cc). #define NUM_ATOMIC_ADD( DST, VAL ) ( DST ) += ( VAL ) +// Shared-memory wavefunctions are GPU only (backend/gpu/SigmaKin.cc). +#define MG_SHWF_RELOAD() // --hel_recycling warm-up probe (madmatrix/output.py). The recycled build drops // the amplitudes that vanish at a given helicity, and it has to be told which @@ -755,6 +757,7 @@ namespace madmatrix #undef NUM_ATOMIC_ADD #undef MG_HR_PROBE_AMP +#undef MG_SHWF_RELOAD //-------------------------------------------------------------------------- diff --git a/madgraph/iolibs/template_files/madmatrix/backend/gpu/GpuAbstraction.h b/madgraph/iolibs/template_files/madmatrix/backend/gpu/GpuAbstraction.h index e0d489b47d..fb8223d743 100644 --- a/madgraph/iolibs/template_files/madmatrix/backend/gpu/GpuAbstraction.h +++ b/madgraph/iolibs/template_files/madmatrix/backend/gpu/GpuAbstraction.h @@ -48,9 +48,11 @@ #define gpuDeviceReset cudaDeviceReset #define gpuLaunchKernel( kernel, blocks, threads, ... ) kernel<<>>( __VA_ARGS__ ) -//#define gpuLaunchKernelSharedMem( kernel, blocks, threads, sharedMem, ... ) kernel<<>>( __VA_> +#define gpuLaunchKernelSharedMem( kernel, blocks, threads, sharedMem, ... ) kernel<<>>( __VA_ARGS__ ) #define gpuLaunchKernelStream( kernel, blocks, threads, stream, ... ) kernel<<>>( __VA_ARGS__ ) #define gpuLaunchKernel2D( kernel, blocks_x, blocks_y, threads, stream, ... ) kernel<<>>( __VA_ARGS__ ) +#define gpuLaunchKernelStreamSharedMem( kernel, blocks, threads, sharedMem, stream, ... ) kernel<<>>( __VA_ARGS__ ) +#define gpuLaunchKernel2DSharedMem( kernel, blocks_x, blocks_y, threads, sharedMem, stream, ... ) kernel<<>>( __VA_ARGS__ ) #define gpuStream_t cudaStream_t #define gpuStreamCreate( pStream ) checkGpu( cudaStreamCreate( pStream ) ) @@ -121,9 +123,11 @@ #define gpuDeviceReset hipDeviceReset #define gpuLaunchKernel( kernel, blocks, threads, ... ) kernel<<>>( __VA_ARGS__ ) -//#define gpuLaunchKernelSharedMem( kernel, blocks, threads, sharedMem, ... ) kernel<<>>( __VA_> +#define gpuLaunchKernelSharedMem( kernel, blocks, threads, sharedMem, ... ) kernel<<>>( __VA_ARGS__ ) #define gpuLaunchKernelStream( kernel, blocks, threads, stream, ... ) kernel<<>>( __VA_ARGS__ ) #define gpuLaunchKernel2D( kernel, blocks_x, blocks_y, threads, stream, ... ) kernel<<>>( __VA_ARGS__ ) +#define gpuLaunchKernelStreamSharedMem( kernel, blocks, threads, sharedMem, stream, ... ) kernel<<>>( __VA_ARGS__ ) +#define gpuLaunchKernel2DSharedMem( kernel, blocks_x, blocks_y, threads, sharedMem, stream, ... ) kernel<<>>( __VA_ARGS__ ) #define gpuStream_t hipStream_t #define gpuStreamCreate( pStream ) checkGpu( hipStreamCreate( pStream ) ) diff --git a/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc b/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc index ee95c780d9..aaadfa300d 100644 --- a/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc +++ b/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc @@ -32,6 +32,10 @@ #include #include +#include +#include +#include +#include #include namespace madmatrix @@ -363,6 +367,73 @@ namespace madmatrix // built for cuda/hip is the plain matrix element (madmatrix.mk says so). #define MG_HR_PROBE_AMP( NAMP ) + //-------------------------------------------------------------------------- + + // Shared-memory wavefunctions. calculate_jamps runs at the 255-register cap and spills + // wavefunctions to local memory; the slots that hold the most reads over the longest + // lifetimes (SharedWavefunctions.inc, by the generator) live instead in dynamic shared + // memory, one padded record per thread, as many as fit with sharedWfBlockThreads threads + // per block. MGONGPU_NO_SHARED_WF turns it off. +#include "SharedWavefunctions.inc" + + // Dynamic shared memory per block that a kernel can opt in to, by compute capability. + constexpr size_t + sharedWfOptinBytes( int sm ) + { +#ifdef MGONGPU_NO_SHARED_WF + return 0; +#else + if( sm == 80 || sm == 87 ) return 166912; + if( sm >= 90 && sm < 120 ) return 232448; + return 101376; +#endif + } + + constexpr int sharedWfBlockThreads = 256; // as umami launches; more threads per block are refused + constexpr size_t sharedWfSlotBytes = np4 * sizeof( fptype_momenta_sv ) + nw6 * sizeof( cxtype_amp_sv ); + + // Odd multiple of 16 bytes: the records of consecutive threads start in different banks. + constexpr size_t + sharedWfStride( int nslots ) + { + const size_t chunks = ( nslots * sharedWfSlotBytes + 15 ) / 16; + return ( chunks % 2 ? chunks : chunks + 1 ) * 16; + } + + constexpr int + sharedWfCount( int sm ) + { + // FP64 on a 99 KB part lost 8% (L40S, g g > t t~ g g): the shared memory shrinks L1. + if( sharedWfOptinBytes( sm ) < 128 * 1024 && sizeof( fptype_amp ) == 8 ) return 0; + int nslots = 0; + while( nslots < nSharedWfSlots && sharedWfStride( nslots + 1 ) * sharedWfBlockThreads <= sharedWfOptinBytes( sm ) ) nslots++; + return nslots; + } + +#ifdef __CUDA_ARCH__ + constexpr int nSharedWf = sharedWfCount( __CUDA_ARCH__ / 10 ); +#else + constexpr int nSharedWf = 0; // host and HIP passes: the size comes from dSharedWfStride +#endif + + struct SharedWfRecord + { + fptype_momenta_sv pvec[nSharedWf > 0 ? nSharedWf : 1][np4]; + cxtype_amp_sv w[nSharedWf > 0 ? nSharedWf : 1][nw6]; + }; + + constexpr size_t sharedWfStrideBytes = nSharedWf > 0 ? sharedWfStride( nSharedWf ) : 0; + + // Bytes per thread of the cubin the device runs (also PTX compiled for a newer GPU): the host reads it back. + __device__ const size_t dSharedWfStride = sharedWfStrideBytes; + +#ifdef __CUDA_ARCH__ + // Every amplitude: without it the compiler keeps the shared values in registers as well. +#define MG_SHWF_RELOAD() asm volatile( "" ::: "memory" ) +#else +#define MG_SHWF_RELOAD() +#endif + // Evaluate QCD partial amplitudes jamps for this given helicity from Feynman diagrams. // Also compute running sums over helicities adding jamp2, numerator, denominator // (NB: this function no longer handles matrix elements as the color sum has now been @@ -435,6 +506,14 @@ namespace madmatrix cxtype_amp_sv amp_sv[1]; // invariant amplitude for one given Feynman diagram ALOHAOBJ aloha_obj[nwf]; for( int iwf = 0; iwf < nwf; iwf++ ) aloha_obj[iwf] = ALOHAOBJ{ pvec_sv[iwf], w_sv[iwf] }; + if constexpr( nSharedWf > 0 ) + { + extern __shared__ __align__( 16 ) unsigned char sharedWfRaw[]; + SharedWfRecord* sharedWf = reinterpret_cast( sharedWfRaw + threadIdx.x * sharedWfStrideBytes ); + // Unrolled: a runtime index into aloha_obj would put all of it in local memory. +#pragma unroll + for( int k = 0; k < nSharedWf; k++ ) aloha_obj[sharedWfSlots[k]] = ALOHAOBJ{ sharedWf->pvec[k], sharedWf->w[k] }; + } fptype_amp* amp_fp = reinterpret_cast( amp_sv ); // special temporary ALOHAOBJ to hold F/Vtmp values in the combined vertex functions @@ -551,6 +630,40 @@ namespace madmatrix #undef NUM_ATOMIC_ADD #undef MG_HR_PROBE_AMP +#undef MG_SHWF_RELOAD + + //-------------------------------------------------------------------------- + + // Dynamic shared memory of calculate_jamps for nthreads per block on the current device. + static size_t + sharedWfBytes( int nthreads ) + { +#if defined __CUDACC__ && !defined MGONGPU_NO_SHARED_WF + static std::mutex mutex; + static std::map strides; // the opt-in is per device, the cubin per architecture + int device; + checkGpu( cudaGetDevice( &device ) ); + size_t stride; + { + std::lock_guard lock( mutex ); + auto it = strides.find( device ); + if( it == strides.end() ) + { + gpuMemcpyFromSymbol( &stride, dSharedWfStride, sizeof( stride ) ); + if( stride > 0 ) + checkGpu( cudaFuncSetAttribute( calculate_jamps, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)( stride * sharedWfBlockThreads ) ) ); + it = strides.emplace( device, stride ).first; + } + stride = it->second; + } + if( stride > 0 && nthreads > sharedWfBlockThreads ) + throw std::runtime_error( "calculate_jamps: shared-memory wavefunctions are sized for " + std::to_string( sharedWfBlockThreads ) + + " threads per block, got " + std::to_string( nthreads ) + ": use fewer or build with -DMGONGPU_NO_SHARED_WF" ); + return stride * nthreads; +#else + return 0; +#endif + } //-------------------------------------------------------------------------- @@ -660,7 +773,7 @@ namespace madmatrix gpuMemset( allMEs, 0, maxtry * sizeof( fptype ) ); // NB: color_sum ADDS |M|^2 for one helicity to the running sum of |M|^2 over helicities for the given event(s) constexpr fptype_amp_sv* allJamp2s = nullptr; // no need for color selection during helicity filtering - gpuLaunchKernel( calculate_jamps, gpublocks, gputhreads, params, ihel, nullptr, scanMomenta, scanCouplings, devFlavorVec, allJamps, false, allNumerators, allDenominators, allJamp2s, gpublocks * gputhreads, nOneHel, false ); + gpuLaunchKernelSharedMem( calculate_jamps, gpublocks, gputhreads, sharedWfBytes( gputhreads ), params, ihel, nullptr, scanMomenta, scanCouplings, devFlavorVec, allJamps, false, allNumerators, allDenominators, allJamp2s, gpublocks * gputhreads, nOneHel, false ); gpuLaunchKernel( color_sum_kernel, gpublocks, gputhreads, allMEs, allJamps, nOneHel, 0 ); gpuMemcpy( hstMEs, allMEs, maxtry * sizeof( fptype ), gpuMemcpyDeviceToHost ); for( int ievt = 0; ievt < maxtry; ++ievt ) @@ -1108,7 +1221,7 @@ namespace madmatrix bool storeChannelWeights = allChannelIds != nullptr || allrnddiagram != nullptr; if( nhel > 0 && async ) { - gpuLaunchKernel2D( calculate_jamps, gpublocks, nhel, gputhreads, ghelStreams[0], kparams, 0, allihel, allmomenta, allcouplings, iflavorVec, ghelAllJamps, storeChannelWeights, ghelAllNumerators, ghelAllDenominators, colAllJamp2s, nevt, nhel, true ); + gpuLaunchKernel2DSharedMem( calculate_jamps, gpublocks, nhel, gputhreads, sharedWfBytes( gputhreads ), ghelStreams[0], kparams, 0, allihel, allmomenta, allcouplings, iflavorVec, ghelAllJamps, storeChannelWeights, ghelAllNumerators, ghelAllDenominators, colAllJamp2s, nevt, nhel, true ); color_sum_gpu( ghelAllMEs, ghelAllJamps, ghelAllBlasTmp, pBlasHandle, ghelStreams, nhel, gpublocks, gputhreads, true ); } else if( nhel > 0 ) @@ -1119,7 +1232,7 @@ namespace madmatrix fptype_amp* hAllJamps = ghelAllJamps + ighel * nevt; // HACK: bypass DeviceAccessJamp (consistent with layout defined there) // NB: the numerators buffer has no helicity dimension: every helicity stream accumulates in place // into the same [nevt][ndiagrams] slot via atomicAdd. The denominators are derived later. - gpuLaunchKernelStream( calculate_jamps, gpublocks, gputhreads, ghelStreams[ighel], kparams, ihel, allihel, allmomenta, allcouplings, iflavorVec, hAllJamps, storeChannelWeights, ghelAllNumerators, ghelAllDenominators, colAllJamp2s, nevt, nhel, false ); + gpuLaunchKernelStreamSharedMem( calculate_jamps, gpublocks, gputhreads, sharedWfBytes( gputhreads ), ghelStreams[ighel], kparams, ihel, allihel, allmomenta, allcouplings, iflavorVec, hAllJamps, storeChannelWeights, ghelAllNumerators, ghelAllDenominators, colAllJamp2s, nevt, nhel, false ); } // (2) Then compute the ME for that helicity from the color sum of QCD partial amplitudes jamps color_sum_gpu( ghelAllMEs, ghelAllJamps, ghelAllBlasTmp, pBlasHandle, ghelStreams, nhel, gpublocks, gputhreads, false ); diff --git a/madgraph/iolibs/template_files/madmatrix/backend/simd/SigmaKin.cc b/madgraph/iolibs/template_files/madmatrix/backend/simd/SigmaKin.cc index 1b20e59c0c..3da94373d5 100644 --- a/madgraph/iolibs/template_files/madmatrix/backend/simd/SigmaKin.cc +++ b/madgraph/iolibs/template_files/madmatrix/backend/simd/SigmaKin.cc @@ -561,6 +561,8 @@ namespace madmatrix // event page is processed serially within the helicity loop, so a plain // sum suffices (CUDA needs atomicAdd instead: see backend/gpu/SigmaKin.cc). #define NUM_ATOMIC_ADD( DST, VAL ) ( DST ) += ( VAL ) +// Shared-memory wavefunctions are GPU only (backend/gpu/SigmaKin.cc). +#define MG_SHWF_RELOAD() // --hel_recycling warm-up probe (madmatrix/output.py). The recycled build drops // the amplitudes that vanish at a given helicity, and it has to be told which @@ -820,6 +822,7 @@ namespace madmatrix #undef NUM_ATOMIC_ADD #undef MG_HR_PROBE_AMP +#undef MG_SHWF_RELOAD //-------------------------------------------------------------------------- diff --git a/madgraph/iolibs/template_files/madmatrix/madmatrix.mk b/madgraph/iolibs/template_files/madmatrix/madmatrix.mk index 08957298ce..477f0999d6 100644 --- a/madgraph/iolibs/template_files/madmatrix/madmatrix.mk +++ b/madgraph/iolibs/template_files/madmatrix/madmatrix.mk @@ -31,6 +31,11 @@ ifeq ($(FASTMATH),) override FASTMATH = 1 endif +# Set the default SHAREDWF choice (wavefunctions in GPU shared memory, auto: only where calculate_jamps spills; BACKEND=cuda only) +ifeq ($(SHAREDWF),) + override SHAREDWF = auto +endif + # default USEBUILDDIR = 1 ifeq ($(USEBUILDDIR),) override USEBUILDDIR = 1 @@ -70,6 +75,11 @@ ifeq ($(FASTMATH)$(filter-out cuda,$(BACKEND)),auto$(BACKEND)) $(error FASTMATH='auto' is implemented for BACKEND=cuda only) endif +override SUPPORTED_SHAREDWFS = 0 1 auto +ifneq ($(words $(filter $(SHAREDWF), $(SUPPORTED_SHAREDWFS))),1) + $(error Invalid sharedwf SHAREDWF='$(SHAREDWF)': supported sharedwfs are $(foreach sharedwf,$(SUPPORTED_SHAREDWFS),'$(sharedwf)')) +endif + # Stop immediately if BACKEND=cuda but nvcc is missing ifeq ($(BACKEND),cuda) ifeq ($(shell which nvcc 2>/dev/null),) @@ -317,6 +327,10 @@ ifeq ($(BACKEND),cuda) GPUFLAGS += -use_fast_math endif + ifeq ($(SHAREDWF),0) + GPUFLAGS += -DMGONGPU_NO_SHARED_WF + endif + # Extra build warnings GPUFLAGS += $(XCOMPILERFLAG) -Wunused-parameter ###GPUFLAGS += $(XCOMPILERFLAG) -Wall $(XCOMPILERFLAG) -Wextra $(XCOMPILERFLAG) -Wshadow @@ -788,7 +802,7 @@ endif # Build lockfile "full" tag (defines full specification of object-file builds that cannot be intermixed) # NB: the backend name is used as-is ('simd_128', 'scalar', 'cuda', 'hip'...) -override TAG = $(BACKEND)_$(FPTYPE)_inl$(HELINL)_fm$(FASTMATH) +override TAG = $(BACKEND)_$(FPTYPE)_inl$(HELINL)_fm$(FASTMATH)$(if $(filter cuda,$(BACKEND)),_sw$(SHAREDWF)) # Export TAG (so that there is no need to check/define it again in src/Makefile) export TAG @@ -965,17 +979,43 @@ endif # FASTMATH=auto: SigmaKin.o is built with -fmad and with -use_fast_math. The approximate div/sqrt of # the latter make calculate_jamps spill more, which costs more than they save once its stack grows by # more than FASTMATH_STACK_GROWTH bytes (fast-math benchmarks on L40S and H100): then -fmad is kept. -ifeq ($(FASTMATH),auto) +# SHAREDWF=auto: SigmaKin.o is built without (sw0) and with (sw1) wavefunctions in shared memory, each +# side picking its fast-math mode as above. Shared memory pays only where calculate_jamps spills without +# it, so it is kept once that stack exceeds SHAREDWF_STACK bytes (pp > tt~/l+l- + 0-3 jets on L40S and +# H100: up to 1.7x faster above 168 B, up to 15% slower below 104 B). +ifeq ($(BACKEND),cuda) +ifneq ($(filter auto,$(FASTMATH) $(SHAREDWF)),) FASTMATH_STACK_GROWTH ?= 128 -override JAMPS_STACK = $(CUDA_HOME)/bin/cuobjdump -res-usage $(1) | awk '/Function .*calculate_jamps/ { getline; sub(/.*STACK:/, ""); if ($$1 + 0 > max) max = $$1 + 0 } END { print max + 0 }' +SHAREDWF_STACK ?= 128 +override JAMPS_STACK = $(CUDA_HOME)/bin/cuobjdump -res-usage $(1) | awk '/Function .*calculate_jamps/ { found = 1; getline; sub(/.*STACK:/, ""); if ($$1 + 0 > max) max = $$1 + 0 } END { if (!found) exit 1; print max + 0 }' +override AUTO_SHAREDWFS = $(if $(filter auto,$(SHAREDWF)),sw0 sw1,sw$(SHAREDWF)) +override AUTO_FASTMATHS = $(if $(filter auto,$(FASTMATH)),mad fm1,fm$(FASTMATH)) $(BUILDDIR)/SigmaKin.o : SigmaKin.cc *.h ../../backend/$(BACKENDDIR)/*.h ../../backend/common/*.h $(SRC)/*.h $(SRC)/rambo/*.h $(BUILDDIR)/.build.$(TAG) @if [ ! -d $(BUILDDIR) ]; then echo "mkdir -p $(BUILDDIR)"; mkdir -p $(BUILDDIR); fi - $(GPUCC) $(CPPFLAGS) $(INCFLAGS) $(GPUFLAGS) -c -x $(GPULANGUAGE) $< -o $(@:.o=.mad.o) & mad=$$!; \ - $(GPUCC) $(CPPFLAGS) $(INCFLAGS) $(GPUFLAGS) -use_fast_math -c -x $(GPULANGUAGE) $< -o $(@:.o=.fm1.o) && wait $$mad - @growth=$$(( $$($(call JAMPS_STACK,$(@:.o=.fm1.o))) - $$($(call JAMPS_STACK,$(@:.o=.mad.o))) )); \ - if [ $$growth -le $(FASTMATH_STACK_GROWTH) ]; then pick=fm1; else pick=mad; fi; \ - cp $(@:.o=.$$pick.o) $@; \ - echo "FASTMATH=auto $(processid_short): calculate_jamps stack +$$growth B with -use_fast_math, keeping $$pick" | tee $(@:.o=.fastmath) + @pids=; for variant in $(foreach sw,$(AUTO_SHAREDWFS),$(foreach fm,$(AUTO_FASTMATHS),$(sw).$(fm))); do \ + flags=; \ + case $(SHAREDWF).$$variant in auto.sw0.*) flags=-DMGONGPU_NO_SHARED_WF;; esac; \ + case $(FASTMATH).$$variant in auto.*.fm1) flags="$$flags -use_fast_math";; esac; \ + echo "$(GPUCC) $(CPPFLAGS) $(INCFLAGS) $(GPUFLAGS) $$flags -c -x $(GPULANGUAGE) $< -o $(@:.o=.$$variant.o)"; \ + $(GPUCC) $(CPPFLAGS) $(INCFLAGS) $(GPUFLAGS) $$flags -c -x $(GPULANGUAGE) $< -o $(@:.o=.$$variant.o) & pids="$$pids $$!"; \ + done; \ + status=0; for pid in $$pids; do wait $$pid || status=1; done; exit $$status + @stack() { stack=$$($(call JAMPS_STACK,$(@:.o=.$$1.o))) || { echo "ERROR! no calculate_jamps stack in $(@:.o=.$$1.o)"; exit 1; }; }; \ + fastmath() { \ + if [ $(FASTMATH) != auto ]; then pick=$$1.fm$(FASTMATH); stack $$pick; return; fi; \ + stack $$1.mad; mad=$$stack; stack $$1.fm1; growth=$$((stack - mad)); \ + if [ $$growth -le $(FASTMATH_STACK_GROWTH) ]; then pick=$$1.fm1; else pick=$$1.mad; stack=$$mad; fi; \ + echo "FASTMATH=auto $(processid_short) $$1: calculate_jamps stack +$$growth B with -use_fast_math, keeping $$pick" | tee -a $(@:.o=.fastmath); \ + }; \ + : > $(@:.o=.fastmath); \ + if [ $(SHAREDWF) != auto ]; then fastmath sw$(SHAREDWF); \ + else \ + fastmath sw0; without=$$stack; \ + if [ $$without -gt $(SHAREDWF_STACK) ]; then fastmath sw1; fi; \ + echo "SHAREDWF=auto $(processid_short): calculate_jamps stack $$without B without shared memory, keeping $$pick" | tee $(@:.o=.sharedwf); \ + fi; \ + cp $(@:.o=.$$pick.o) $@ +endif endif #------------------------------------------------------------------------------- diff --git a/madmatrix/model_handling.py b/madmatrix/model_handling.py index 47f5b2ee88..5ee0b52900 100644 --- a/madmatrix/model_handling.py +++ b/madmatrix/model_handling.py @@ -2925,8 +2925,24 @@ def get_all_sigmaKin_lines(self, color_amplitudes, class_name): ff = open(pjoin(self.path, 'EvaluateDiagrams.inc'), 'w') ff.write('\n'.join(helas_calls)) ff.close() + self.edit_sharedwavefunctions() return '' + def edit_sharedwavefunctions(self): + """Generate SharedWavefunctions.inc: the wavefunction slots of EvaluateDiagrams.inc in the + order the GPU calculate_jamps moves them to shared memory, as many as fit (see + backend/gpu/SigmaKin.cc).""" + order = self.helas_call_writer.shared_wf_order() + lines = ['// Wavefunction slots, most worth keeping out of registers first (generated).', + '// #included by backend/gpu/SigmaKin.cc: the first nSharedWf live in shared memory.', + ' constexpr int nSharedWfSlots = %d; // the slots EvaluateDiagrams.inc writes' % len(order), + ' __device__ constexpr int sharedWfSlots[nSharedWfSlots > 0 ? nSharedWfSlots : 1] = { %s };' + % ', '.join(map(str, order or [0])), + ''] + ff = open(pjoin(self.path, 'SharedWavefunctions.inc'), 'w') + ff.write('\n'.join(lines)) + ff.close() + # AV - modify export_cpp.OneProcessExporterCPP method (replace '# Process' by '// Process') def get_process_info_lines(self, matrix_element): """Return info lines describing the processes for this matrix element""" @@ -4249,6 +4265,8 @@ def super_get_matrix_element_calls(self, matrix_element, color_amplitudes, multi '%s not valid argument for get_matrix_element_calls' % \ type(matrix_element) self.nb_tmp_jamp = 0 + # (line, slots read, slot written or None) of every call, in order: see shared_wf_order + self.wf_events = [] # Do not reuse the wavefunctions for loop matrix elements if isinstance(matrix_element, loop_helas_objects.LoopHelasMatrixElement): return self.get_loop_matrix_element_calls(matrix_element) @@ -4384,6 +4402,7 @@ def _guard_open(group_mask): res.append('}') else: res.append(call) + self.wf_events.append((len(res), [m.get('me_id') - 1 for m in wf.get('mothers')], wf.get('me_id') - 1)) for isum in sum_after.get(wf.get('number'), []): # a wavefunction number can be listed by more than one # diagram here, and the sum must only be written once @@ -4397,6 +4416,7 @@ def _guard_open(group_mask): cubic.get('me_id') - 1, quartic.get('me_id') - 1, sum_slots[isum] - 1)) + self.wf_events.append((len(res), [cubic.get('me_id') - 1, quartic.get('me_id') - 1], sum_slots[isum] - 1)) if len(diagram.get('wavefunctions')) == 0 : res.append('// (none)') # AV res.append('\n // Amplitude(s) for diagram number %d' % diagram.get('number')) for amplitude in diagram.get('amplitudes'): @@ -4415,6 +4435,7 @@ def _guard_open(group_mask): sum_original.append((mother, mother.get('me_id'))) mother.set('me_id', sum_slots[isum]) amp_block = [ self.get_amplitude_call(amplitude) ] # AV new: avoid format_call + self.wf_events.append((len(res), [m.get('me_id') - 1 for m in amplitude.get('mothers')], None)) for mother, me_id in sum_original: mother.set('me_id', me_id) # the flavours this amplitude contributes to (None: all of them) @@ -4438,6 +4459,7 @@ def _guard_open(group_mask): continue if self.hr_probe: amp_block.append('MG_HR_PROBE_AMP( %d );' % namp) + amp_block.append('MG_SHWF_RELOAD();') if id_amp in diag_to_config: ###res.append("if( channelId == %i ) numerators_sv += cxabs2( amp_sv[0] );" % diag_to_config[id_amp]) # BUG #472 ###res.append("if( channelId == %i ) numerators_sv += cxabs2( amp_sv[0] );" % id_amp) # wrong fix for BUG #472 @@ -4756,6 +4778,30 @@ def to_group(perflavor_mask): wf_group_mask[id(wf)] = gm return diag_group_mask, wf_group_mask + def shared_wf_order(self): + """The wavefunction slots of the last get_matrix_element_calls, by the sum over the values + each one holds of reads x lines from the write to the last read, largest first: on GPUs + the first slots of this list are kept in shared memory (SharedWavefunctions.inc), out of + the registers that spill most.""" + score = defaultdict(int) + live = {} # slot: (line written, last line read, reads) + def close(slot): + if slot in live: + start, last, reads = live.pop(slot) + score[slot] += reads * (last - start) + for line, reads, write in self.wf_events: + for slot in reads: + if slot in live: # a priority only: a slot read before any write here just scores 0 + start, _, nreads = live[slot] + live[slot] = (start, line, nreads + 1) + if write is not None: + close(write) + live[write] = (line, line, 0) + for slot in list(live): + close(slot) + slots = sorted({write for _, _, write in self.wf_events if write is not None}) + return sorted(slots, key=lambda slot: -score[slot]) + # AV - overload helas_call_writers.GPUFOHelasCallWriter method (improve formatting) def get_matrix_element_calls(self, matrix_element, color_amplitudes, multi_channel_map): """Return a list of strings, corresponding to the Helas calls for the matrix element""" From 5a7e4fed0f4301d8f1dd51cd4dccf9a5f91a7b11 Mon Sep 17 00:00:00 2001 From: stloufra Date: Thu, 19 Nov 2026 11:11:18 +0100 Subject: [PATCH 03/14] Rename MGONGPU_NO_SHARED_WF to MADMATRIX_NO_SHARED_WF New macros use MADMATRIX prefix, no MGONGPU. Co-Authored-By: Claude Opus 5.5 --- .../template_files/madmatrix/backend/gpu/SigmaKin.cc | 8 ++++---- madgraph/iolibs/template_files/madmatrix/madmatrix.mk | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc b/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc index aaadfa300d..62236c82b5 100644 --- a/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc +++ b/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc @@ -373,14 +373,14 @@ namespace madmatrix // wavefunctions to local memory; the slots that hold the most reads over the longest // lifetimes (SharedWavefunctions.inc, by the generator) live instead in dynamic shared // memory, one padded record per thread, as many as fit with sharedWfBlockThreads threads - // per block. MGONGPU_NO_SHARED_WF turns it off. + // per block. MADMATRIX_NO_SHARED_WF turns it off. #include "SharedWavefunctions.inc" // Dynamic shared memory per block that a kernel can opt in to, by compute capability. constexpr size_t sharedWfOptinBytes( int sm ) { -#ifdef MGONGPU_NO_SHARED_WF +#ifdef MADMATRIX_NO_SHARED_WF return 0; #else if( sm == 80 || sm == 87 ) return 166912; @@ -638,7 +638,7 @@ namespace madmatrix static size_t sharedWfBytes( int nthreads ) { -#if defined __CUDACC__ && !defined MGONGPU_NO_SHARED_WF +#if defined __CUDACC__ && !defined MADMATRIX_NO_SHARED_WF static std::mutex mutex; static std::map strides; // the opt-in is per device, the cubin per architecture int device; @@ -658,7 +658,7 @@ namespace madmatrix } if( stride > 0 && nthreads > sharedWfBlockThreads ) throw std::runtime_error( "calculate_jamps: shared-memory wavefunctions are sized for " + std::to_string( sharedWfBlockThreads ) + - " threads per block, got " + std::to_string( nthreads ) + ": use fewer or build with -DMGONGPU_NO_SHARED_WF" ); + " threads per block, got " + std::to_string( nthreads ) + ": use fewer or build with -DMADMATRIX_NO_SHARED_WF" ); return stride * nthreads; #else return 0; diff --git a/madgraph/iolibs/template_files/madmatrix/madmatrix.mk b/madgraph/iolibs/template_files/madmatrix/madmatrix.mk index 477f0999d6..9f220721c1 100644 --- a/madgraph/iolibs/template_files/madmatrix/madmatrix.mk +++ b/madgraph/iolibs/template_files/madmatrix/madmatrix.mk @@ -328,7 +328,7 @@ ifeq ($(BACKEND),cuda) endif ifeq ($(SHAREDWF),0) - GPUFLAGS += -DMGONGPU_NO_SHARED_WF + GPUFLAGS += -DMADMATRIX_NO_SHARED_WF endif # Extra build warnings @@ -994,7 +994,7 @@ $(BUILDDIR)/SigmaKin.o : SigmaKin.cc *.h ../../backend/$(BACKENDDIR)/*.h ../../b @if [ ! -d $(BUILDDIR) ]; then echo "mkdir -p $(BUILDDIR)"; mkdir -p $(BUILDDIR); fi @pids=; for variant in $(foreach sw,$(AUTO_SHAREDWFS),$(foreach fm,$(AUTO_FASTMATHS),$(sw).$(fm))); do \ flags=; \ - case $(SHAREDWF).$$variant in auto.sw0.*) flags=-DMGONGPU_NO_SHARED_WF;; esac; \ + case $(SHAREDWF).$$variant in auto.sw0.*) flags=-DMADMATRIX_NO_SHARED_WF;; esac; \ case $(FASTMATH).$$variant in auto.*.fm1) flags="$$flags -use_fast_math";; esac; \ echo "$(GPUCC) $(CPPFLAGS) $(INCFLAGS) $(GPUFLAGS) $$flags -c -x $(GPULANGUAGE) $< -o $(@:.o=.$$variant.o)"; \ $(GPUCC) $(CPPFLAGS) $(INCFLAGS) $(GPUFLAGS) $$flags -c -x $(GPULANGUAGE) $< -o $(@:.o=.$$variant.o) & pids="$$pids $$!"; \ From 2369c2533047ca055f66448a4ccddf59631debd5 Mon Sep 17 00:00:00 2001 From: stloufra Date: Thu, 19 Nov 2026 11:14:53 +0100 Subject: [PATCH 04/14] Rename MG_SHWF_RELOAD to SHWF_RELOAD Shorter name, no MG prefix. Co-Authored-By: Claude Opus 5.5 --- .../iolibs/template_files/madmatrix/backend/cpu/SigmaKin.cc | 4 ++-- .../iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc | 6 +++--- .../template_files/madmatrix/backend/simd/SigmaKin.cc | 4 ++-- madmatrix/model_handling.py | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/madgraph/iolibs/template_files/madmatrix/backend/cpu/SigmaKin.cc b/madgraph/iolibs/template_files/madmatrix/backend/cpu/SigmaKin.cc index c0909ca328..c315bf1eaa 100644 --- a/madgraph/iolibs/template_files/madmatrix/backend/cpu/SigmaKin.cc +++ b/madgraph/iolibs/template_files/madmatrix/backend/cpu/SigmaKin.cc @@ -497,7 +497,7 @@ namespace madmatrix // sum suffices (CUDA needs atomicAdd instead: see backend/gpu/SigmaKin.cc). #define NUM_ATOMIC_ADD( DST, VAL ) ( DST ) += ( VAL ) // Shared-memory wavefunctions are GPU only (backend/gpu/SigmaKin.cc). -#define MG_SHWF_RELOAD() +#define SHWF_RELOAD() // --hel_recycling warm-up probe (madmatrix/output.py). The recycled build drops // the amplitudes that vanish at a given helicity, and it has to be told which @@ -757,7 +757,7 @@ namespace madmatrix #undef NUM_ATOMIC_ADD #undef MG_HR_PROBE_AMP -#undef MG_SHWF_RELOAD +#undef SHWF_RELOAD //-------------------------------------------------------------------------- diff --git a/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc b/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc index 62236c82b5..fe043ac447 100644 --- a/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc +++ b/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc @@ -429,9 +429,9 @@ namespace madmatrix #ifdef __CUDA_ARCH__ // Every amplitude: without it the compiler keeps the shared values in registers as well. -#define MG_SHWF_RELOAD() asm volatile( "" ::: "memory" ) +#define SHWF_RELOAD() asm volatile( "" ::: "memory" ) #else -#define MG_SHWF_RELOAD() +#define SHWF_RELOAD() #endif // Evaluate QCD partial amplitudes jamps for this given helicity from Feynman diagrams. @@ -630,7 +630,7 @@ namespace madmatrix #undef NUM_ATOMIC_ADD #undef MG_HR_PROBE_AMP -#undef MG_SHWF_RELOAD +#undef SHWF_RELOAD //-------------------------------------------------------------------------- diff --git a/madgraph/iolibs/template_files/madmatrix/backend/simd/SigmaKin.cc b/madgraph/iolibs/template_files/madmatrix/backend/simd/SigmaKin.cc index 3da94373d5..12d2ec6f89 100644 --- a/madgraph/iolibs/template_files/madmatrix/backend/simd/SigmaKin.cc +++ b/madgraph/iolibs/template_files/madmatrix/backend/simd/SigmaKin.cc @@ -562,7 +562,7 @@ namespace madmatrix // sum suffices (CUDA needs atomicAdd instead: see backend/gpu/SigmaKin.cc). #define NUM_ATOMIC_ADD( DST, VAL ) ( DST ) += ( VAL ) // Shared-memory wavefunctions are GPU only (backend/gpu/SigmaKin.cc). -#define MG_SHWF_RELOAD() +#define SHWF_RELOAD() // --hel_recycling warm-up probe (madmatrix/output.py). The recycled build drops // the amplitudes that vanish at a given helicity, and it has to be told which @@ -822,7 +822,7 @@ namespace madmatrix #undef NUM_ATOMIC_ADD #undef MG_HR_PROBE_AMP -#undef MG_SHWF_RELOAD +#undef SHWF_RELOAD //-------------------------------------------------------------------------- diff --git a/madmatrix/model_handling.py b/madmatrix/model_handling.py index 5ee0b52900..91b60560e1 100644 --- a/madmatrix/model_handling.py +++ b/madmatrix/model_handling.py @@ -4459,7 +4459,7 @@ def _guard_open(group_mask): continue if self.hr_probe: amp_block.append('MG_HR_PROBE_AMP( %d );' % namp) - amp_block.append('MG_SHWF_RELOAD();') + amp_block.append('SHWF_RELOAD();') if id_amp in diag_to_config: ###res.append("if( channelId == %i ) numerators_sv += cxabs2( amp_sv[0] );" % diag_to_config[id_amp]) # BUG #472 ###res.append("if( channelId == %i ) numerators_sv += cxabs2( amp_sv[0] );" % id_amp) # wrong fix for BUG #472 From 8935706db3cf33da1f00d9cc6d2280b7fb5b2e0a Mon Sep 17 00:00:00 2001 From: stloufra Date: Thu, 19 Nov 2026 13:41:52 +0100 Subject: [PATCH 05/14] Escape percent in madmatrix.mk SHAREDWF comment Template is %-formatted, bare 15% broke output. Co-Authored-By: Claude Opus 5.5 --- madgraph/iolibs/template_files/madmatrix/madmatrix.mk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/madgraph/iolibs/template_files/madmatrix/madmatrix.mk b/madgraph/iolibs/template_files/madmatrix/madmatrix.mk index 9f220721c1..d800b0a4e1 100644 --- a/madgraph/iolibs/template_files/madmatrix/madmatrix.mk +++ b/madgraph/iolibs/template_files/madmatrix/madmatrix.mk @@ -982,7 +982,7 @@ endif # SHAREDWF=auto: SigmaKin.o is built without (sw0) and with (sw1) wavefunctions in shared memory, each # side picking its fast-math mode as above. Shared memory pays only where calculate_jamps spills without # it, so it is kept once that stack exceeds SHAREDWF_STACK bytes (pp > tt~/l+l- + 0-3 jets on L40S and -# H100: up to 1.7x faster above 168 B, up to 15% slower below 104 B). +# H100: up to 1.7x faster above 168 B, up to 15%% slower below 104 B). ifeq ($(BACKEND),cuda) ifneq ($(filter auto,$(FASTMATH) $(SHAREDWF)),) FASTMATH_STACK_GROWTH ?= 128 From b2dc19053d53380104314e661c5c2fc6f7fdfee4 Mon Sep 17 00:00:00 2001 From: stloufra Date: Thu, 19 Nov 2026 16:05:28 +0100 Subject: [PATCH 06/14] Guard shared-wf block with __CUDA_ARCH__ Discarded if constexpr still parsed on host HIP, __align__ undefined there. Co-Authored-By: Claude Opus 5.5 --- .../iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc | 2 ++ 1 file changed, 2 insertions(+) diff --git a/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc b/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc index fe043ac447..4611c87a33 100644 --- a/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc +++ b/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc @@ -506,6 +506,7 @@ namespace madmatrix cxtype_amp_sv amp_sv[1]; // invariant amplitude for one given Feynman diagram ALOHAOBJ aloha_obj[nwf]; for( int iwf = 0; iwf < nwf; iwf++ ) aloha_obj[iwf] = ALOHAOBJ{ pvec_sv[iwf], w_sv[iwf] }; +#ifdef __CUDA_ARCH__ if constexpr( nSharedWf > 0 ) { extern __shared__ __align__( 16 ) unsigned char sharedWfRaw[]; @@ -514,6 +515,7 @@ namespace madmatrix #pragma unroll for( int k = 0; k < nSharedWf; k++ ) aloha_obj[sharedWfSlots[k]] = ALOHAOBJ{ sharedWf->pvec[k], sharedWf->w[k] }; } +#endif fptype_amp* amp_fp = reinterpret_cast( amp_sv ); // special temporary ALOHAOBJ to hold F/Vtmp values in the combined vertex functions From 0984bc7371bdadfd1223fb732a743f7db7a14816 Mon Sep 17 00:00:00 2001 From: stloufra Date: Thu, 19 Nov 2026 16:31:53 +0100 Subject: [PATCH 07/14] Make FASTMATH=auto gate explicit Rule under autocuda, HIP_FAST_MATH comment answered (no-op on AMD). --- .../iolibs/template_files/madmatrix/madmatrix.mk | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/madgraph/iolibs/template_files/madmatrix/madmatrix.mk b/madgraph/iolibs/template_files/madmatrix/madmatrix.mk index 08957298ce..0738aea318 100644 --- a/madgraph/iolibs/template_files/madmatrix/madmatrix.mk +++ b/madgraph/iolibs/template_files/madmatrix/madmatrix.mk @@ -26,7 +26,7 @@ ifeq ($(HELINL),) override HELINL = 0 endif -# Set the default FASTMATH choice (0: IEEE-strict, i.e. no fast-math and no FP contraction) +# Set the default FASTMATH choice (0: IEEE-strict, i.e. no fast-math and no FP contraction; auto: opt-in, CUDA only, see SigmaKin.o) ifeq ($(FASTMATH),) override FASTMATH = 1 endif @@ -66,8 +66,10 @@ override SUPPORTED_FASTMATHS = 0 1 auto ifneq ($(words $(filter $(FASTMATH), $(SUPPORTED_FASTMATHS))),1) $(error Invalid fastmath FASTMATH='$(FASTMATH)': supported fastmaths are $(foreach fastmath,$(SUPPORTED_FASTMATHS),'$(fastmath)')) endif -ifeq ($(FASTMATH)$(filter-out cuda,$(BACKEND)),auto$(BACKEND)) - $(error FASTMATH='auto' is implemented for BACKEND=cuda only) +ifeq ($(FASTMATH),auto) + ifneq ($(BACKEND),cuda) + $(error FASTMATH='auto' is implemented for BACKEND=cuda only) + endif endif # Stop immediately if BACKEND=cuda but nvcc is missing @@ -372,7 +374,7 @@ else ifeq ($(BACKEND),hip) # Other AMD-specific flags GPUFLAGS += -target x86_64-linux-gnu -DHIP_PLATFORM=amd - # Fast math (is -DHIP_FAST_MATH equivalent to -ffast-math?) + # -DHIP_FAST_MATH is read only on hipcc's NVIDIA path, no-op on AMD: FASTMATH=1 is the clang default (FMA contraction on). ifeq ($(FASTMATH),0) GPUFLAGS += -ffp-contract=off else @@ -965,7 +967,7 @@ endif # FASTMATH=auto: SigmaKin.o is built with -fmad and with -use_fast_math. The approximate div/sqrt of # the latter make calculate_jamps spill more, which costs more than they save once its stack grows by # more than FASTMATH_STACK_GROWTH bytes (fast-math benchmarks on L40S and H100): then -fmad is kept. -ifeq ($(FASTMATH),auto) +ifeq ($(FASTMATH)$(BACKEND),autocuda) FASTMATH_STACK_GROWTH ?= 128 override JAMPS_STACK = $(CUDA_HOME)/bin/cuobjdump -res-usage $(1) | awk '/Function .*calculate_jamps/ { getline; sub(/.*STACK:/, ""); if ($$1 + 0 > max) max = $$1 + 0 } END { print max + 0 }' $(BUILDDIR)/SigmaKin.o : SigmaKin.cc *.h ../../backend/$(BACKENDDIR)/*.h ../../backend/common/*.h $(SRC)/*.h $(SRC)/rambo/*.h $(BUILDDIR)/.build.$(TAG) From c6b083e4b1cbcf4796a57f86293734667ef588fc Mon Sep 17 00:00:00 2001 From: stloufra Date: Thu, 19 Nov 2026 17:07:47 +0100 Subject: [PATCH 08/14] List shared-memory opt-in limit per CUDA arch Turing 64 KB not 99 KB, unknown arch fall back to 48 KB. Co-Authored-By: Claude Opus 5.5 --- .../madmatrix/backend/gpu/SigmaKin.cc | 22 ++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc b/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc index 4611c87a33..e37574c4e7 100644 --- a/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc +++ b/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc @@ -383,9 +383,25 @@ namespace madmatrix #ifdef MADMATRIX_NO_SHARED_WF return 0; #else - if( sm == 80 || sm == 87 ) return 166912; - if( sm >= 90 && sm < 120 ) return 232448; - return 101376; + switch( sm ) + { + case 70: + case 72: return 98304; + case 75: return 65536; + case 80: + case 87: return 166912; + case 86: + case 89: + case 120: + case 121: return 101376; + case 90: + case 100: + case 101: + case 103: + case 107: + case 110: return 232448; + default: return 49152; // Unknown arch: no opt-in needed. + } #endif } From 21c810e7567a56ef148718c273aa2cf2a9c04ace Mon Sep 17 00:00:00 2001 From: stloufra Date: Fri, 20 Nov 2026 15:52:30 +0100 Subject: [PATCH 09/14] Size GPU wavefunction arrays by slots used nwf counts calls, slots reused: ttggg 121 not 391, barrier only with shared slots. Co-Authored-By: Claude Opus 5.5 --- .../madmatrix/backend/gpu/SigmaKin.cc | 15 +++++++++------ madmatrix/model_handling.py | 7 +++++-- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc b/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc index e37574c4e7..845256bc52 100644 --- a/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc +++ b/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc @@ -445,7 +445,9 @@ namespace madmatrix #ifdef __CUDA_ARCH__ // Every amplitude: without it the compiler keeps the shared values in registers as well. -#define SHWF_RELOAD() asm volatile( "" ::: "memory" ) + // Only with shared slots: 1890 of them make cicc 3x slower on g g > t t~ g g g for nothing. +#define SHWF_RELOAD() \ + if constexpr( nSharedWf > 0 ) asm volatile( "" ::: "memory" ) #else #define SHWF_RELOAD() #endif @@ -517,11 +519,12 @@ namespace madmatrix // (ievt) [NB these variables are reused several times (and re-initialised each time) // within the same event]. Create memory for both momenta and wavefunctions separately, // and later wrap them in ALOHAOBJ. - fptype_momenta_sv pvec_sv[nwf][np4]; - cxtype_amp_sv w_sv[nwf][nw6]; // particle wavefunctions within Feynman diagrams - cxtype_amp_sv amp_sv[1]; // invariant amplitude for one given Feynman diagram - ALOHAOBJ aloha_obj[nwf]; - for( int iwf = 0; iwf < nwf; iwf++ ) aloha_obj[iwf] = ALOHAOBJ{ pvec_sv[iwf], w_sv[iwf] }; + // nWfSlots, not nwf: slots are reused, and unused ones still cost local memory and stores. + fptype_momenta_sv pvec_sv[nWfSlots][np4]; + cxtype_amp_sv w_sv[nWfSlots][nw6]; // particle wavefunctions within Feynman diagrams + cxtype_amp_sv amp_sv[1]; // invariant amplitude for one given Feynman diagram + ALOHAOBJ aloha_obj[nWfSlots]; + for( int iwf = 0; iwf < nWfSlots; iwf++ ) aloha_obj[iwf] = ALOHAOBJ{ pvec_sv[iwf], w_sv[iwf] }; #ifdef __CUDA_ARCH__ if constexpr( nSharedWf > 0 ) { diff --git a/madmatrix/model_handling.py b/madmatrix/model_handling.py index 91b60560e1..ec239cdc71 100644 --- a/madmatrix/model_handling.py +++ b/madmatrix/model_handling.py @@ -2925,16 +2925,19 @@ def get_all_sigmaKin_lines(self, color_amplitudes, class_name): ff = open(pjoin(self.path, 'EvaluateDiagrams.inc'), 'w') ff.write('\n'.join(helas_calls)) ff.close() - self.edit_sharedwavefunctions() + self.edit_sharedwavefunctions(helas_calls) return '' - def edit_sharedwavefunctions(self): + def edit_sharedwavefunctions(self, helas_calls): """Generate SharedWavefunctions.inc: the wavefunction slots of EvaluateDiagrams.inc in the order the GPU calculate_jamps moves them to shared memory, as many as fit (see backend/gpu/SigmaKin.cc).""" order = self.helas_call_writer.shared_wf_order() + # nwf counts wavefunction calls, slots are reused: size the GPU arrays by the slots indexed + nslots = 1 + max((int(i) for line in helas_calls for i in re.findall(r'aloha_obj\[(\d+)\]', line)), default=0) lines = ['// Wavefunction slots, most worth keeping out of registers first (generated).', '// #included by backend/gpu/SigmaKin.cc: the first nSharedWf live in shared memory.', + ' constexpr int nWfSlots = %d; // highest aloha_obj index of EvaluateDiagrams.inc + 1' % nslots, ' constexpr int nSharedWfSlots = %d; // the slots EvaluateDiagrams.inc writes' % len(order), ' __device__ constexpr int sharedWfSlots[nSharedWfSlots > 0 ? nSharedWfSlots : 1] = { %s };' % ', '.join(map(str, order or [0])), From 0b95a6d5d4913a35d871d33136ae02989ec71bbb Mon Sep 17 00:00:00 2001 From: stloufra Date: Fri, 20 Nov 2026 15:52:45 +0100 Subject: [PATCH 10/14] Stop fast-math compile once fmad build spills over 4 KB Fast math never picked there, dense arrays make its ptxas take over an hour. Co-Authored-By: Claude Opus 5.5 --- .../template_files/madmatrix/madmatrix.mk | 23 +++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/madgraph/iolibs/template_files/madmatrix/madmatrix.mk b/madgraph/iolibs/template_files/madmatrix/madmatrix.mk index d800b0a4e1..920f7c3c0b 100644 --- a/madgraph/iolibs/template_files/madmatrix/madmatrix.mk +++ b/madgraph/iolibs/template_files/madmatrix/madmatrix.mk @@ -983,10 +983,16 @@ endif # side picking its fast-math mode as above. Shared memory pays only where calculate_jamps spills without # it, so it is kept once that stack exceeds SHAREDWF_STACK bytes (pp > tt~/l+l- + 0-3 jets on L40S and # H100: up to 1.7x faster above 168 B, up to 15%% slower below 104 B). +# FASTMATH=auto, FP32 amplitudes (FASTMATH_CUTOFF_FPTYPES): once a side's -fmad build spills more than +# FASTMATH_MAD_STACK bytes, its -use_fast_math build is stopped and -fmad kept. Fast math only ever won +# there below 1.2 KB (96 picks, L40S and H100), and with dense wavefunction arrays approximate division +# takes ptxas from minutes to over an hour on g g > t t~ g g g. ifeq ($(BACKEND),cuda) ifneq ($(filter auto,$(FASTMATH) $(SHAREDWF)),) FASTMATH_STACK_GROWTH ?= 128 SHAREDWF_STACK ?= 128 +FASTMATH_MAD_STACK ?= 4096 +FASTMATH_CUTOFF_FPTYPES ?= f v override JAMPS_STACK = $(CUDA_HOME)/bin/cuobjdump -res-usage $(1) | awk '/Function .*calculate_jamps/ { found = 1; getline; sub(/.*STACK:/, ""); if ($$1 + 0 > max) max = $$1 + 0 } END { if (!found) exit 1; print max + 0 }' override AUTO_SHAREDWFS = $(if $(filter auto,$(SHAREDWF)),sw0 sw1,sw$(SHAREDWF)) override AUTO_FASTMATHS = $(if $(filter auto,$(FASTMATH)),mad fm1,fm$(FASTMATH)) @@ -997,12 +1003,25 @@ $(BUILDDIR)/SigmaKin.o : SigmaKin.cc *.h ../../backend/$(BACKENDDIR)/*.h ../../b case $(SHAREDWF).$$variant in auto.sw0.*) flags=-DMADMATRIX_NO_SHARED_WF;; esac; \ case $(FASTMATH).$$variant in auto.*.fm1) flags="$$flags -use_fast_math";; esac; \ echo "$(GPUCC) $(CPPFLAGS) $(INCFLAGS) $(GPUFLAGS) $$flags -c -x $(GPULANGUAGE) $< -o $(@:.o=.$$variant.o)"; \ - $(GPUCC) $(CPPFLAGS) $(INCFLAGS) $(GPUFLAGS) $$flags -c -x $(GPULANGUAGE) $< -o $(@:.o=.$$variant.o) & pids="$$pids $$!"; \ + $(GPUCC) $(CPPFLAGS) $(INCFLAGS) $(GPUFLAGS) $$flags -c -x $(GPULANGUAGE) $< -o $(@:.o=.$$variant.o) & \ + eval "pid_$${variant%%.*}_$${variant#*.}=$$!"; \ done; \ - status=0; for pid in $$pids; do wait $$pid || status=1; done; exit $$status + rm -f $(@:.o=).*.skipped; status=0; \ + for variant in $(foreach sw,$(AUTO_SHAREDWFS),$(foreach fm,$(AUTO_FASTMATHS),$(sw).$(fm))); do \ + sw=$${variant%%.*} fm=$${variant#*.}; eval "pid=\$$pid_$${sw}_$$fm"; \ + if [ -f $(@:.o=.$$variant.skipped) ]; then wait $$pid; continue; fi; \ + wait $$pid || { status=1; continue; }; \ + [ $$fm = mad ] && [ -n "$(filter $(FPTYPE),$(FASTMATH_CUTOFF_FPTYPES))" ] || continue; \ + stack=$$($(call JAMPS_STACK,$(@:.o=.$$variant.o))) || continue; \ + [ $$stack -gt $(FASTMATH_MAD_STACK) ] || continue; \ + eval "fm1=\$$pid_$${sw}_fm1"; pkill -P $$fm1; kill $$fm1 2> /dev/null; \ + echo "$$stack" > $(@:.o=.$$sw.fm1.skipped); rm -f $(@:.o=.$$sw.fm1.o); \ + done; exit $$status @stack() { stack=$$($(call JAMPS_STACK,$(@:.o=.$$1.o))) || { echo "ERROR! no calculate_jamps stack in $(@:.o=.$$1.o)"; exit 1; }; }; \ fastmath() { \ if [ $(FASTMATH) != auto ]; then pick=$$1.fm$(FASTMATH); stack $$pick; return; fi; \ + if [ -f $(@:.o=.$$1.fm1.skipped) ]; then pick=$$1.mad; stack $$pick; \ + echo "FASTMATH=auto $(processid_short) $$1: calculate_jamps stack $$stack B with -fmad > $(FASTMATH_MAD_STACK), -use_fast_math stopped, keeping $$pick" | tee -a $(@:.o=.fastmath); return; fi; \ stack $$1.mad; mad=$$stack; stack $$1.fm1; growth=$$((stack - mad)); \ if [ $$growth -le $(FASTMATH_STACK_GROWTH) ]; then pick=$$1.fm1; else pick=$$1.mad; stack=$$mad; fi; \ echo "FASTMATH=auto $(processid_short) $$1: calculate_jamps stack +$$growth B with -use_fast_math, keeping $$pick" | tee -a $(@:.o=.fastmath); \ From 82c4276d0e28f342f0733ea71f46e4573f6ae2bf Mon Sep 17 00:00:00 2001 From: stloufra Date: Fri, 20 Nov 2026 19:10:10 +0100 Subject: [PATCH 11/14] Keep #491 arrays and barrier without shared slots Smaller arrays, no barrier there: L40S FP64 ttggg 0.89x, ttgQQ 0.985x. Co-Authored-By: Claude Opus 5.5 --- .../madmatrix/backend/gpu/SigmaKin.cc | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc b/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc index 845256bc52..1af44fb63f 100644 --- a/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc +++ b/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc @@ -440,14 +440,17 @@ namespace madmatrix constexpr size_t sharedWfStrideBytes = nSharedWf > 0 ? sharedWfStride( nSharedWf ) : 0; + // Slots are reused, so nWfSlots < nwf, but the smaller arrays only measured as a win with shared slots: + // without them L40S FP64 g g > t t~ g g g spills 5x more loads and runs 0.89x. + constexpr int nWfArray = nSharedWf > 0 ? nWfSlots : nwf; + // Bytes per thread of the cubin the device runs (also PTX compiled for a newer GPU): the host reads it back. __device__ const size_t dSharedWfStride = sharedWfStrideBytes; #ifdef __CUDA_ARCH__ // Every amplitude: without it the compiler keeps the shared values in registers as well. - // Only with shared slots: 1890 of them make cicc 3x slower on g g > t t~ g g g for nothing. -#define SHWF_RELOAD() \ - if constexpr( nSharedWf > 0 ) asm volatile( "" ::: "memory" ) + // Kept without shared slots too: dropping it there costs L40S FP64 g g > t t~ g Q Q~ 1.5%. +#define SHWF_RELOAD() asm volatile( "" ::: "memory" ) #else #define SHWF_RELOAD() #endif @@ -519,12 +522,11 @@ namespace madmatrix // (ievt) [NB these variables are reused several times (and re-initialised each time) // within the same event]. Create memory for both momenta and wavefunctions separately, // and later wrap them in ALOHAOBJ. - // nWfSlots, not nwf: slots are reused, and unused ones still cost local memory and stores. - fptype_momenta_sv pvec_sv[nWfSlots][np4]; - cxtype_amp_sv w_sv[nWfSlots][nw6]; // particle wavefunctions within Feynman diagrams + fptype_momenta_sv pvec_sv[nWfArray][np4]; + cxtype_amp_sv w_sv[nWfArray][nw6]; // particle wavefunctions within Feynman diagrams cxtype_amp_sv amp_sv[1]; // invariant amplitude for one given Feynman diagram - ALOHAOBJ aloha_obj[nWfSlots]; - for( int iwf = 0; iwf < nWfSlots; iwf++ ) aloha_obj[iwf] = ALOHAOBJ{ pvec_sv[iwf], w_sv[iwf] }; + ALOHAOBJ aloha_obj[nWfArray]; + for( int iwf = 0; iwf < nWfArray; iwf++ ) aloha_obj[iwf] = ALOHAOBJ{ pvec_sv[iwf], w_sv[iwf] }; #ifdef __CUDA_ARCH__ if constexpr( nSharedWf > 0 ) { From b2ea410b5cedb76e61eea3055f47d0a9931522ab Mon Sep 17 00:00:00 2001 From: stloufra Date: Fri, 20 Nov 2026 22:30:16 +0100 Subject: [PATCH 12/14] Use slot-sized arrays and no barrier without shared slots again Compile time over L40S FP64 run time, FP64 not target there. Co-Authored-By: Claude Opus 5.5 --- .../madmatrix/backend/gpu/SigmaKin.cc | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc b/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc index 1af44fb63f..845256bc52 100644 --- a/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc +++ b/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc @@ -440,17 +440,14 @@ namespace madmatrix constexpr size_t sharedWfStrideBytes = nSharedWf > 0 ? sharedWfStride( nSharedWf ) : 0; - // Slots are reused, so nWfSlots < nwf, but the smaller arrays only measured as a win with shared slots: - // without them L40S FP64 g g > t t~ g g g spills 5x more loads and runs 0.89x. - constexpr int nWfArray = nSharedWf > 0 ? nWfSlots : nwf; - // Bytes per thread of the cubin the device runs (also PTX compiled for a newer GPU): the host reads it back. __device__ const size_t dSharedWfStride = sharedWfStrideBytes; #ifdef __CUDA_ARCH__ // Every amplitude: without it the compiler keeps the shared values in registers as well. - // Kept without shared slots too: dropping it there costs L40S FP64 g g > t t~ g Q Q~ 1.5%. -#define SHWF_RELOAD() asm volatile( "" ::: "memory" ) + // Only with shared slots: 1890 of them make cicc 3x slower on g g > t t~ g g g for nothing. +#define SHWF_RELOAD() \ + if constexpr( nSharedWf > 0 ) asm volatile( "" ::: "memory" ) #else #define SHWF_RELOAD() #endif @@ -522,11 +519,12 @@ namespace madmatrix // (ievt) [NB these variables are reused several times (and re-initialised each time) // within the same event]. Create memory for both momenta and wavefunctions separately, // and later wrap them in ALOHAOBJ. - fptype_momenta_sv pvec_sv[nWfArray][np4]; - cxtype_amp_sv w_sv[nWfArray][nw6]; // particle wavefunctions within Feynman diagrams + // nWfSlots, not nwf: slots are reused, and unused ones still cost local memory and stores. + fptype_momenta_sv pvec_sv[nWfSlots][np4]; + cxtype_amp_sv w_sv[nWfSlots][nw6]; // particle wavefunctions within Feynman diagrams cxtype_amp_sv amp_sv[1]; // invariant amplitude for one given Feynman diagram - ALOHAOBJ aloha_obj[nWfArray]; - for( int iwf = 0; iwf < nWfArray; iwf++ ) aloha_obj[iwf] = ALOHAOBJ{ pvec_sv[iwf], w_sv[iwf] }; + ALOHAOBJ aloha_obj[nWfSlots]; + for( int iwf = 0; iwf < nWfSlots; iwf++ ) aloha_obj[iwf] = ALOHAOBJ{ pvec_sv[iwf], w_sv[iwf] }; #ifdef __CUDA_ARCH__ if constexpr( nSharedWf > 0 ) { From 695991addf58511ea4691c68acc1d521ff805bce Mon Sep 17 00:00:00 2001 From: stloufra Date: Sat, 21 Nov 2026 19:06:09 +0100 Subject: [PATCH 13/14] Compile only the predicted gate variants outside the amplitude band Picks follow amplitude count, GPU-independent outside band, 234 picks none missed. Co-Authored-By: Claude Opus 5.5 --- .../template_files/madmatrix/madmatrix.mk | 33 ++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/madgraph/iolibs/template_files/madmatrix/madmatrix.mk b/madgraph/iolibs/template_files/madmatrix/madmatrix.mk index 920f7c3c0b..6b78619ab1 100644 --- a/madgraph/iolibs/template_files/madmatrix/madmatrix.mk +++ b/madgraph/iolibs/template_files/madmatrix/madmatrix.mk @@ -987,15 +987,42 @@ endif # FASTMATH_MAD_STACK bytes, its -use_fast_math build is stopped and -fmad kept. Fast math only ever won # there below 1.2 KB (96 picks, L40S and H100), and with dense wavefunction arrays approximate division # takes ptxas from minutes to over an hour on g g > t t~ g g g. +# AUTO_PREDICT=1, FPTYPE d/f/v: the picks follow the number of amplitudes in EvaluateDiagrams.inc, the same +# on every GPU outside a band (234 picks on L40S, H100 and sm_70/80/100 builds, none missed), so outside it +# only the predicted variant is compiled. AUTO_PREDICT=0 compiles all of them. ifeq ($(BACKEND),cuda) ifneq ($(filter auto,$(FASTMATH) $(SHAREDWF)),) FASTMATH_STACK_GROWTH ?= 128 SHAREDWF_STACK ?= 128 FASTMATH_MAD_STACK ?= 4096 FASTMATH_CUTOFF_FPTYPES ?= f v +AUTO_PREDICT ?= 1 override JAMPS_STACK = $(CUDA_HOME)/bin/cuobjdump -res-usage $(1) | awk '/Function .*calculate_jamps/ { found = 1; getline; sub(/.*STACK:/, ""); if ($$1 + 0 > max) max = $$1 + 0 } END { if (!found) exit 1; print max + 0 }' override AUTO_SHAREDWFS = $(if $(filter auto,$(SHAREDWF)),sw0 sw1,sw$(SHAREDWF)) override AUTO_FASTMATHS = $(if $(filter auto,$(FASTMATH)),mad fm1,fm$(FASTMATH)) +ifeq ($(AUTO_PREDICT)$(filter $(FPTYPE),d f v),1$(FPTYPE)) +override GATE_AMPS := $(if $(wildcard EvaluateDiagrams.inc),$(strip $(shell grep -o '&_fp\[' EvaluateDiagrams.inc | wc -l))) +endif +ifneq ($(GATE_AMPS),) +override gate_amps = $(shell [ $(GATE_AMPS) $(1) $(2) ] && echo y) +ifeq ($(SHAREDWF),auto) + ifeq ($(call gate_amps,-lt,$(if $(filter d,$(FPTYPE)),10,21)),y) + override AUTO_SHAREDWFS = sw0 + else ifeq ($(call gate_amps,-gt,$(if $(filter d,$(FPTYPE)),30,130)),y) + override AUTO_SHAREDWFS = sw1 + endif +endif +ifeq ($(FASTMATH),auto) + # FP64: -use_fast_math never grew the stack. + ifeq ($(FPTYPE),d) + override AUTO_FASTMATHS = fm1 + else ifeq ($(call gate_amps,-lt,21),y) + override AUTO_FASTMATHS = fm1 + else ifeq ($(call gate_amps,-gt,300),y) + override AUTO_FASTMATHS = mad + endif +endif +endif $(BUILDDIR)/SigmaKin.o : SigmaKin.cc *.h ../../backend/$(BACKENDDIR)/*.h ../../backend/common/*.h $(SRC)/*.h $(SRC)/rambo/*.h $(BUILDDIR)/.build.$(TAG) @if [ ! -d $(BUILDDIR) ]; then echo "mkdir -p $(BUILDDIR)"; mkdir -p $(BUILDDIR); fi @pids=; for variant in $(foreach sw,$(AUTO_SHAREDWFS),$(foreach fm,$(AUTO_FASTMATHS),$(sw).$(fm))); do \ @@ -1011,7 +1038,7 @@ $(BUILDDIR)/SigmaKin.o : SigmaKin.cc *.h ../../backend/$(BACKENDDIR)/*.h ../../b sw=$${variant%%.*} fm=$${variant#*.}; eval "pid=\$$pid_$${sw}_$$fm"; \ if [ -f $(@:.o=.$$variant.skipped) ]; then wait $$pid; continue; fi; \ wait $$pid || { status=1; continue; }; \ - [ $$fm = mad ] && [ -n "$(filter $(FPTYPE),$(FASTMATH_CUTOFF_FPTYPES))" ] || continue; \ + [ $$fm = mad ] && [ -n "$(filter $(FPTYPE),$(FASTMATH_CUTOFF_FPTYPES))" ] && [ -n "$(filter fm1,$(AUTO_FASTMATHS))" ] || continue; \ stack=$$($(call JAMPS_STACK,$(@:.o=.$$variant.o))) || continue; \ [ $$stack -gt $(FASTMATH_MAD_STACK) ] || continue; \ eval "fm1=\$$pid_$${sw}_fm1"; pkill -P $$fm1; kill $$fm1 2> /dev/null; \ @@ -1020,6 +1047,8 @@ $(BUILDDIR)/SigmaKin.o : SigmaKin.cc *.h ../../backend/$(BACKENDDIR)/*.h ../../b @stack() { stack=$$($(call JAMPS_STACK,$(@:.o=.$$1.o))) || { echo "ERROR! no calculate_jamps stack in $(@:.o=.$$1.o)"; exit 1; }; }; \ fastmath() { \ if [ $(FASTMATH) != auto ]; then pick=$$1.fm$(FASTMATH); stack $$pick; return; fi; \ + if [ "$(AUTO_FASTMATHS)" != "mad fm1" ]; then pick=$$1.$(AUTO_FASTMATHS); stack $$pick; \ + echo "FASTMATH=auto $(processid_short) $$1: $(GATE_AMPS) amplitudes, compiled and keeping $$pick only" | tee -a $(@:.o=.fastmath); return; fi; \ if [ -f $(@:.o=.$$1.fm1.skipped) ]; then pick=$$1.mad; stack $$pick; \ echo "FASTMATH=auto $(processid_short) $$1: calculate_jamps stack $$stack B with -fmad > $(FASTMATH_MAD_STACK), -use_fast_math stopped, keeping $$pick" | tee -a $(@:.o=.fastmath); return; fi; \ stack $$1.mad; mad=$$stack; stack $$1.fm1; growth=$$((stack - mad)); \ @@ -1028,6 +1057,8 @@ $(BUILDDIR)/SigmaKin.o : SigmaKin.cc *.h ../../backend/$(BACKENDDIR)/*.h ../../b }; \ : > $(@:.o=.fastmath); \ if [ $(SHAREDWF) != auto ]; then fastmath sw$(SHAREDWF); \ + elif [ "$(AUTO_SHAREDWFS)" != "sw0 sw1" ]; then fastmath $(AUTO_SHAREDWFS); \ + echo "SHAREDWF=auto $(processid_short): $(GATE_AMPS) amplitudes, compiled and keeping $$pick only" | tee $(@:.o=.sharedwf); \ else \ fastmath sw0; without=$$stack; \ if [ $$without -gt $(SHAREDWF_STACK) ]; then fastmath sw1; fi; \ From f96ceb95fcc46b18705befb5b578c34b8a8606a7 Mon Sep 17 00:00:00 2001 From: stloufra Date: Sat, 21 Nov 2026 19:09:38 +0100 Subject: [PATCH 14/14] Keep only the shared-memory barriers a later read needs Generator mask per barrier, bit per nSharedWf, constexpr no-op otherwise. Co-Authored-By: Claude Opus 5.5 --- .../madmatrix/backend/cpu/SigmaKin.cc | 2 +- .../madmatrix/backend/gpu/SigmaKin.cc | 10 +++--- .../madmatrix/backend/simd/SigmaKin.cc | 2 +- madmatrix/model_handling.py | 34 +++++++++++++++++++ 4 files changed, 41 insertions(+), 7 deletions(-) diff --git a/madgraph/iolibs/template_files/madmatrix/backend/cpu/SigmaKin.cc b/madgraph/iolibs/template_files/madmatrix/backend/cpu/SigmaKin.cc index c315bf1eaa..4a782bb2c2 100644 --- a/madgraph/iolibs/template_files/madmatrix/backend/cpu/SigmaKin.cc +++ b/madgraph/iolibs/template_files/madmatrix/backend/cpu/SigmaKin.cc @@ -497,7 +497,7 @@ namespace madmatrix // sum suffices (CUDA needs atomicAdd instead: see backend/gpu/SigmaKin.cc). #define NUM_ATOMIC_ADD( DST, VAL ) ( DST ) += ( VAL ) // Shared-memory wavefunctions are GPU only (backend/gpu/SigmaKin.cc). -#define SHWF_RELOAD() +#define SHWF_RELOAD( mask ) // --hel_recycling warm-up probe (madmatrix/output.py). The recycled build drops // the amplitudes that vanish at a given helicity, and it has to be told which diff --git a/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc b/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc index 845256bc52..5311c2286d 100644 --- a/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc +++ b/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc @@ -444,12 +444,12 @@ namespace madmatrix __device__ const size_t dSharedWfStride = sharedWfStrideBytes; #ifdef __CUDA_ARCH__ - // Every amplitude: without it the compiler keeps the shared values in registers as well. - // Only with shared slots: 1890 of them make cicc 3x slower on g g > t t~ g g g for nothing. -#define SHWF_RELOAD() \ - if constexpr( nSharedWf > 0 ) asm volatile( "" ::: "memory" ) + // After amplitudes: without it the compiler keeps the shared values in registers as well. Bit n-1 of mask + // (generator): needed with nSharedWf = n. Every barrier costs cicc time, 1890 of them 3x on g g > t t~ g g g. +#define SHWF_RELOAD( mask ) \ + if constexpr( nSharedWf > 32 || ( nSharedWf > 0 && ( ( ( mask ) >> ( nSharedWf > 0 ? nSharedWf - 1 : 0 ) ) & 1 ) ) ) asm volatile( "" ::: "memory" ) #else -#define SHWF_RELOAD() +#define SHWF_RELOAD( mask ) #endif // Evaluate QCD partial amplitudes jamps for this given helicity from Feynman diagrams. diff --git a/madgraph/iolibs/template_files/madmatrix/backend/simd/SigmaKin.cc b/madgraph/iolibs/template_files/madmatrix/backend/simd/SigmaKin.cc index 12d2ec6f89..4bb1705fec 100644 --- a/madgraph/iolibs/template_files/madmatrix/backend/simd/SigmaKin.cc +++ b/madgraph/iolibs/template_files/madmatrix/backend/simd/SigmaKin.cc @@ -562,7 +562,7 @@ namespace madmatrix // sum suffices (CUDA needs atomicAdd instead: see backend/gpu/SigmaKin.cc). #define NUM_ATOMIC_ADD( DST, VAL ) ( DST ) += ( VAL ) // Shared-memory wavefunctions are GPU only (backend/gpu/SigmaKin.cc). -#define SHWF_RELOAD() +#define SHWF_RELOAD( mask ) // --hel_recycling warm-up probe (madmatrix/output.py). The recycled build drops // the amplitudes that vanish at a given helicity, and it has to be told which diff --git a/madmatrix/model_handling.py b/madmatrix/model_handling.py index ec239cdc71..85a05bcace 100644 --- a/madmatrix/model_handling.py +++ b/madmatrix/model_handling.py @@ -8,6 +8,7 @@ import sys import glob +import bisect import math import contextlib import re @@ -4270,6 +4271,8 @@ def super_get_matrix_element_calls(self, matrix_element, color_amplitudes, multi self.nb_tmp_jamp = 0 # (line, slots read, slot written or None) of every call, in order: see shared_wf_order self.wf_events = [] + # len(wf_events) at each SHWF_RELOAD: see barrier_masks + self.barrier_events = [] # Do not reuse the wavefunctions for loop matrix elements if isinstance(matrix_element, loop_helas_objects.LoopHelasMatrixElement): return self.get_loop_matrix_element_calls(matrix_element) @@ -4463,6 +4466,7 @@ def _guard_open(group_mask): if self.hr_probe: amp_block.append('MG_HR_PROBE_AMP( %d );' % namp) amp_block.append('SHWF_RELOAD();') + self.barrier_events.append(len(self.wf_events)) if id_amp in diag_to_config: ###res.append("if( channelId == %i ) numerators_sv += cxabs2( amp_sv[0] );" % diag_to_config[id_amp]) # BUG #472 ###res.append("if( channelId == %i ) numerators_sv += cxabs2( amp_sv[0] );" % id_amp) # wrong fix for BUG #472 @@ -4805,6 +4809,33 @@ def close(slot): slots = sorted({write for _, _, write in self.wf_events if write is not None}) return sorted(slots, key=lambda slot: -score[slot]) + def barrier_masks(self, nbits=32): + """Per SHWF_RELOAD of the last get_matrix_element_calls, bit n-1 set when it is needed with the first n + slots of shared_wf_order in shared memory: between two accesses of a shared slot, one barrier makes the + second one reload it instead of keeping it in a register, and the one closest to that access is kept.""" + masks = [0] * len(self.barrier_events) + order = self.shared_wf_order() + for n in range(1, nbits + 1): + shared, last, gaps = set(order[:n]), {}, [] + for i, (_, reads, write) in enumerate(self.wf_events): + for slot in reads: + if slot not in shared: + continue + if slot in last: + first = bisect.bisect_right(self.barrier_events, last[slot]) + closest = bisect.bisect_right(self.barrier_events, i) - 1 + if first <= closest: + gaps.append((first, closest)) + last[slot] = i + if write in shared: + last[write] = i + kept = -1 + for first, closest in sorted(gaps, key=lambda gap: gap[1]): + if kept < first: + kept = closest + masks[closest] |= 1 << (n - 1) + return masks + # AV - overload helas_call_writers.GPUFOHelasCallWriter method (improve formatting) def get_matrix_element_calls(self, matrix_element, color_amplitudes, multi_channel_map): """Return a list of strings, corresponding to the Helas calls for the matrix element""" @@ -4821,10 +4852,13 @@ def get_matrix_element_calls(self, matrix_element, color_amplitudes, multi_chann res = self.super_get_matrix_element_calls(matrix_element, color_amplitudes, multi_channel_map) finally: self.axial_gauge_refs = {} + masks = iter(self.barrier_masks()) for i, item in enumerate(res): + if item == 'SHWF_RELOAD();': item = res[i] = 'SHWF_RELOAD( 0x%08x );' % next(masks) ###print(item) # FOR DEBUGGING if item.startswith('# Amplitude'): item='//'+item[1:] # AV replace '# Amplitude' by '// Amplitude' if not item.startswith('\n') and not item.startswith('#'): res[i]=' '+item + assert next(masks, None) is None, 'SHWF_RELOAD count differs from barrier_events' return res # ------------------------------------------------------------------