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 e37574c4e7..5311c2286d 100644 --- a/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc +++ b/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc @@ -444,10 +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. -#define SHWF_RELOAD() 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. @@ -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/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/madgraph/iolibs/template_files/madmatrix/madmatrix.mk b/madgraph/iolibs/template_files/madmatrix/madmatrix.mk index d800b0a4e1..6b78619ab1 100644 --- a/madgraph/iolibs/template_files/madmatrix/madmatrix.mk +++ b/madgraph/iolibs/template_files/madmatrix/madmatrix.mk @@ -983,13 +983,46 @@ 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. +# 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 \ @@ -997,18 +1030,35 @@ $(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))" ] && [ -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; \ + 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 [ "$(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)); \ 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); \ + 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; \ diff --git a/madmatrix/model_handling.py b/madmatrix/model_handling.py index 91b60560e1..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 @@ -2925,16 +2926,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])), @@ -4267,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) @@ -4460,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 @@ -4802,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""" @@ -4818,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 # ------------------------------------------------------------------