Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 11 additions & 8 deletions madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 )
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
54 changes: 52 additions & 2 deletions madgraph/iolibs/template_files/madmatrix/madmatrix.mk
Original file line number Diff line number Diff line change
Expand Up @@ -983,32 +983,82 @@ 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 '&amp_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 \
flags=; \
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; \
Expand Down
41 changes: 39 additions & 2 deletions madmatrix/model_handling.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import sys

import glob
import bisect
import math
import contextlib
import re
Expand Down Expand Up @@ -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])),
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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"""
Expand All @@ -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

# ------------------------------------------------------------------
Expand Down
Loading