From 21c810e7567a56ef148718c273aa2cf2a9c04ace Mon Sep 17 00:00:00 2001 From: stloufra Date: Fri, 20 Nov 2026 15:52:30 +0100 Subject: [PATCH 1/6] 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 2/6] 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 3/6] 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 4/6] 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 5/6] 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 6/6] 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 # ------------------------------------------------------------------