diff --git a/madgraph/iolibs/template_files/madmatrix/backend/cpu/SigmaKin.cc b/madgraph/iolibs/template_files/madmatrix/backend/cpu/SigmaKin.cc index 04af130030..7cf3cd6ec0 100644 --- a/madgraph/iolibs/template_files/madmatrix/backend/cpu/SigmaKin.cc +++ b/madgraph/iolibs/template_files/madmatrix/backend/cpu/SigmaKin.cc @@ -464,6 +464,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 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 @@ -723,6 +725,7 @@ namespace madmatrix #undef NUM_ATOMIC_ADD #undef MG_HR_PROBE_AMP +#undef 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 d309691934..0f6f7dd91a 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 5dd35e57ef..b376db4a9d 100644 --- a/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc +++ b/madgraph/iolibs/template_files/madmatrix/backend/gpu/SigmaKin.cc @@ -31,6 +31,10 @@ #include #include +#include +#include +#include +#include #include namespace madmatrix @@ -374,6 +378,91 @@ 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. 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 MADMATRIX_NO_SHARED_WF + return 0; +#else + 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 + } + + 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__ + // 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( mask ) +#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 @@ -440,11 +529,22 @@ 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 ) + { + 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] }; + } +#endif fptype_amp* amp_fp = reinterpret_cast( amp_sv ); // special temporary ALOHAOBJ to hold F/Vtmp values in the combined vertex functions @@ -560,6 +660,40 @@ namespace madmatrix #undef NUM_ATOMIC_ADD #undef MG_HR_PROBE_AMP +#undef 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 MADMATRIX_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 -DMADMATRIX_NO_SHARED_WF" ); + return stride * nthreads; +#else + return 0; +#endif + } //-------------------------------------------------------------------------- @@ -669,7 +803,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 ) @@ -1117,7 +1251,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 ) @@ -1128,7 +1262,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 numerator slots 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 be951bb485..fd5125b51e 100644 --- a/madgraph/iolibs/template_files/madmatrix/backend/simd/SigmaKin.cc +++ b/madgraph/iolibs/template_files/madmatrix/backend/simd/SigmaKin.cc @@ -536,6 +536,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 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 @@ -793,6 +795,7 @@ namespace madmatrix #undef NUM_ATOMIC_ADD #undef MG_HR_PROBE_AMP +#undef SHWF_RELOAD //-------------------------------------------------------------------------- diff --git a/madgraph/iolibs/template_files/madmatrix/madmatrix.mk b/madgraph/iolibs/template_files/madmatrix/madmatrix.mk index 4796caca0e..083183e818 100644 --- a/madgraph/iolibs/template_files/madmatrix/madmatrix.mk +++ b/madgraph/iolibs/template_files/madmatrix/madmatrix.mk @@ -23,6 +23,16 @@ ifeq ($(HELINL),) override HELINL = 0 endif +# 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 + +# 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 @@ -54,6 +64,21 @@ 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),auto) + ifneq ($(BACKEND),cuda) + $(error FASTMATH='auto' is implemented for BACKEND=cuda only) + endif +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),) @@ -163,7 +188,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 +321,17 @@ 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 + + ifeq ($(SHAREDWF),0) + GPUFLAGS += -DMADMATRIX_NO_SHARED_WF + endif # Extra build warnings GPUFLAGS += $(XCOMPILERFLAG) -Wunused-parameter @@ -351,8 +388,12 @@ 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?) - GPUFLAGS += -DHIP_FAST_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 + GPUFLAGS += -DHIP_FAST_MATH + endif # Extra build warnings ###GPUFLAGS += $(XCOMPILERFLAG) -Wall $(XCOMPILERFLAG) -Wextra $(XCOMPILERFLAG) -Wshadow @@ -757,7 +798,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)$(if $(filter cuda,$(BACKEND)),_sw$(SHAREDWF)) # Export TAG (so that there is no need to check/define it again in src/Makefile) export TAG @@ -922,6 +963,98 @@ $(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. +# 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). +# 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 \ + 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) & \ + eval "pid_$${variant%%.*}_$${variant#*.}=$$!"; \ + done; \ + 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; \ + 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 + #------------------------------------------------------------------------------- # Target (and build rules): common (src) library diff --git a/madmatrix/model_handling.py b/madmatrix/model_handling.py index dbda5ac5ea..5277adefd0 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,8 +2926,27 @@ 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(helas_calls) return '' + 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])), + ''] + 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""" @@ -4233,6 +4253,10 @@ 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 = [] + # 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) @@ -4368,6 +4392,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 @@ -4381,6 +4406,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'): @@ -4399,6 +4425,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) @@ -4422,6 +4449,8 @@ def _guard_open(group_mask): continue 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 @@ -4740,6 +4769,57 @@ 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]) + + 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""" @@ -4756,10 +4836,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 # ------------------------------------------------------------------