Documentation
¶
Overview ¶
Package hostemu runs CUDA kernel source on the host CPU, for testing kernels where no GPU is available.
The emulation is a C++20 header, cudahostemu.h, that defines the CUDA qualifiers, built-in variables, mask-aware warp collectives (including disjoint sub-warp masks), named CTA barriers (bar.sync id, count), cp.async, ldmatrix, mma.sync and wgmma (bf16, f16 and e4m3 forms, with K-major or MN-major layouts and no/32B/64B/128B swizzle descriptors), thread-block clusters, and a host-memory subset of the CUDA runtime. Each CUDA thread is a host thread started for its launch. On the fiber engine, which Schedule.Fibers selects (EG_EMU_FIBERS), each thread is instead a fiber that shares its warp's host thread on arm64 and switches only where it synchronizes or waits; elsewhere it is a thread from a pool kept between launches. Shared memory, cp.async destinations and cudaMalloc memory start as 0xff bytes (NaN in every float format the header handles), so a kernel that reads memory it never wrote fails visibly; define EG_EMU_ZERO_SMEM to start shared memory zeroed. cp.async and, in kernels that issue wgmma.fence, wgmma are modeled at their latest legal timing, so a result read or an operand overwritten before the matching wait_group shows up on the host; EG_EMU_SYNC_WGMMA, as a macro or as an environment variable of the running program, turns the wgmma model off. Hopper mbarriers, cp.async.bulk and 2D TMA tile loads (with the 128-byte swizzle) are modeled adversarially: a copy's destination reads NaN until a thread waits on the phase that completes it, so a missing wait or a wait for the wrong phase parity shows up, and a satisfied wait returns only once no other thread of the block can run, so a producer that refills a stage before its consumers release it shows up too; EG_EMU_SYNC_MBAR, as a macro or environment variable, turns that model off. EG_EMU_LAG_LANE=L, as a macro, holds lane L of every warp at each parity wait until the rest of the block is blocked, so a lane that releases a stage before its warp's other lanes have waited on it shows up as a deadlock. The rest of the mbarrier instructions are there too (eg_emu_mbar_*: arrive with a count, arrive_drop, .noComplete, expect_tx, complete_tx, waits on an arrival's state, a bounded try_wait, pending_count and inval), as are the shared::cluster forms that reach another CTA's mbarrier and the multicast arrive and copies; a misuse the PTX ISA leaves undefined, such as a count out of range, a stale state or a use after inval, fails the run. sgl_mock.h adds the parts of SGLang's JIT headers and tvm-ffi that generated launcher structs use.
Run compiles kernel source with a launch statement and named buffers, runs it, and returns each buffer's final bytes. WriteHeaders writes the headers for callers that drive the compiler themselves.
MMAM16N8K16A, MMAM16N8K16B, MMAM16N8C, MMAM16N8K32A, MMAM16N8K32B, MMAM16N8K64NVFP4A, MMAM16N8K64NVFP4B, LDMatrixM8N8X4, WGMMADesc, and SwizzleOffset report the PTX ISA register-fragment and shared-memory descriptor layouts that the header emulates.
A wait that no thread of the launch can satisfy, such as an epoch ready counter whose producers have all exited or are themselves waiting, fails as soon as every thread is blocked. A wait that a running thread may still satisfy fails only after EG_EMU_WAIT_TIMEOUT_MS milliseconds (default 120000), a backstop, so a slow host does not fail a correct kernel.
The emulation checks a kernel's arithmetic, indexing and synchronization on small inputs. It does not model timing, memory ordering beyond barriers, or the GPU's floating-point contraction choices.
Dynamic shared memory ¶
A kernel declares dynamic shared memory as it does for a device,
extern __shared__ float s[];
and the launch gives its size in bytes: the third argument of eg_emu_launch(grid, block, bytes, kernel, args...), the position it has in kernel<<<grid, block, bytes>>> and the value that github.com/tmc/lib/nvidia/x/cudalaunch.Launcher.SharedMem takes. No host-only macro or fixed size is needed. Run rewrites the declaration with RewriteExternShared, because C++ cannot spell it.
Each block has its own region, filled with 0xff bytes (zeros under EG_EMU_ZERO_SMEM) when the block starts and 1024-byte aligned whatever alignment the declaration asks for. Every extern __shared__ array names the region's first byte, so two of them alias and a kernel divides the region by hand. Static __shared__ arrays are separate storage: the emulator does not place the dynamic region directly after them as a device does (16 bytes after the start of a 12-byte static array on the one device tried, an NVIDIA GB10, where the region was therefore not 1024-byte aligned), so a kernel that runs off the end of a static array into dynamic memory, or that depends on the region's address, behaves differently here. TestDynamicSharedOnDevice prints both layouts and runs one kernel with two sizes on a device and on the emulator; on a device not listed here the kernel's results are expected to match and the layout is unknown.
The emulator cannot check an index, because the kernel reaches the region through ordinary pointers. Instead 1024 bytes of 0xff follow the region: a read past the end reads 0xff, and a write past the end fails the run when the block finishes, naming the byte and the launch's size. That holds for a launch of zero bytes too, where every access is past the end. A write more than 1024 bytes past the end is not detected. Launches made by CheckHazards and RunWithTMEM allocate at least 65536 bytes, so they detect only writes past that.
Modeled constructs ¶
The table lists what the emulator does with each CUDA construct. Modeled means the result is the one a device gives, for the cases the named tests cover. Approximated means the emulator runs something close and the note below says how it differs. Not modeled means the kernel compiles and runs with the host's behavior, which may differ from a device's without any report. Rejected means the compile or the run fails. A row with no test is marked untested: it describes the code, and nothing checks it.
construct status tested by thread = host thread, blocks in sequence modeled TestWarpCollectives, TestBlockOrder blocks of a grid at once (Schedule.Concurrent) modeled TestConcurrentGridBarrier, TestDynamicSharedPerBlock warp lanes as fibers (Schedule.Fibers) modeled TestFiberMatchesThreads, TestFiberEngine atomic spin on a lane of one warp, fibers rejected TestFiberAtomicSpin thread-block clusters modeled TestCluster __syncthreads modeled TestDynamicSharedTwoSizes, TestPartialWarpsAndEarlyExit named barriers (bar.sync id, count) modeled TestNamedBarriers barrier that cannot complete rejected TestNamedBarriers, TestMBarrierErrors data race between barriers not modeled untested shared-memory race report (CheckHazards) approximated TestHazardSharedRace, TestHazardHappensBefore async copy race report (CheckHazards) approximated TestHazardAsyncCopies schedule perturbation (Schedule.Points) approximated TestSchedulePointsReplay timing not modeled untested __shfl_sync, _up_, _down_, _xor_ modeled TestWarpCollectives, TestSubWarpMaskShuffles __ballot_sync, __any_sync, __all_sync modeled TestSubWarpMaskShuffles __syncwarp modeled TestSubWarpMaskShuffles lane outside its mask, conflicting masks rejected untested __popc modeled TestHostLanguage __clz, __ffs, __brev, __activemask, __match_* rejected TestUndeclaredIntrinsics __shfl, __ballot, __any, __all (no _sync) rejected TestUndeclaredIntrinsics atomicAdd, Min, Max, Exch, CAS, Or, And modeled TestAtomicReadModifyWrite, TestAtomicOrAnd atomic ordering weaker than sequential not modeled TestAtomicsSequentiallyConsistent atomicSub, atomicXor, atomicInc, atomicDec rejected TestUndeclaredIntrinsics __threadfence, __threadfence_block approximated untested __threadfence_system rejected TestUndeclaredIntrinsics unsynchronized access, volatile not modeled untested static __shared__ approximated TestSharedMemoryStartsPoisoned, TestDynamicSharedWithStatic static __shared__ with blocks at once rejected TestConcurrentRefusesStaticShared CUDAHOSTEMU_SHARED (per-block, keyed) modeled TestCluster extern __shared__ (dynamic), aliasing modeled TestDynamicSharedTwoSizes, TestDynamicSharedAliases write past dynamic shared memory rejected TestDynamicSharedLaunchSize other out-of-bounds access not modeled untested unwritten shared and cudaMalloc memory approximated TestSharedMemoryStartsPoisoned, TestRuntime uninitialized locals not modeled untested device shared-memory size limits not modeled untested device functions, templates, recursion modeled TestHostLanguage unsigned wraparound modeled TestHostLanguage signed overflow, wide shifts, division by 0 not modeled untested float to integer conversion out of range not modeled untested __fmul_rn, __fadd_rn, __fsqrt_rn, fmaf modeled TestHostLanguage __fsub_rn, __fdiv_rn, __frcp_rn modeled untested __float2int_rn modeled TestHostLanguage FMA contraction of a*b+c, fast math not modeled untested expf, sinf and other math functions approximated untested __nv_bfloat16 and its conversions modeled TestHostLanguage, TestMMABF16 __half, half2 and their conversions rejected TestUndeclaredIntrinsics E4M3 and F16 values in matrix instructions modeled TestE4M3MatchesMoe8ops cp.async modeled TestCpAsyncLandsAtWait ldmatrix, mma.sync modeled TestMMABF16 wgmma modeled TestWGMMAAsync, TestWGMMAMissingWait mbarrier, cp.async.bulk, 2D TMA modeled TestMBarrierRing, TestTensorMap2D mbarrier arrive with a count, arrive_drop modeled TestMBarrierSingleThread, TestMBarrierArriveDrop mbarrier expect_tx, complete_tx modeled TestMBarrierSingleThread, TestMBarrierMutations mbarrier state wait, noComplete, pending_count modeled TestMBarrierStateWait, TestMBarrierSingleThread mbarrier try_wait time limit approximated TestMBarrierTryWait mbarrier inval, reinit, count ranges rejected TestMBarrierMisuse mbarrier of another CTA (shared::cluster) modeled TestMBarrierRemoteArrive multicast arrive, bulk copy and 2D TMA modeled TestMBarrierMulticast mbarrier .relaxed, .release, .acquire, scope approximated TestHazardMBarrierOrdering, TestMBarrierSemForms layout::v1 mbarrier, cp.async.mbarrier.arrive not modeled untested cudaMalloc, cudaMemcpy, streams approximated TestRuntime launch configuration approximated TestRuntime, TestRunErrors
Scheduling. Each CUDA thread is a host thread, so the threads of a block interleave as the host schedules them, and __syncthreads is a real barrier that every live thread of the block must reach. Blocks run one after another unless a Schedule or a cluster runs them together. A kernel with a data race between barriers therefore has one here too, but nothing explores interleavings: a racy kernel usually produces the same answer on every run, and the answer may be the one the author expected. Schedule.Points perturbs threads only at __syncthreads, spin waits and atomics (not atomicOr or atomicAnd).
Races. CheckHazards orders shared-memory accesses by happens-before, with the same vector-clock rules as the deterministic scheduler's detector: each thread has a clock, and __syncthreads, cluster barriers, named barriers (their participants only), __syncwarp (the lanes of its mask) and mbarrier arrive/wait pairs join clocks. A satisfied mbarrier wait orders only the waiting thread after the phase's arrivals. Writes by cp.async and bulk copies belong to a copy agent: cp.async.wait_group orders it before its issuer only, and a bulk copy's agent is ordered before threads that observe the completion of the phase the copy completes. Two accesses to a byte, at least one a write, race unless the later thread's clock covers the earlier access, including two lanes of one warp. Under clang every shared memory access the kernel source makes is tracked, through raw pointers too; with another compiler, or Launch.NoRawPointers, only the shared arrays the checker can rewrite. The copies it wraps are tracked either way, and so are the atomic functions' accesses to shared memory. An atomic is relaxed, ordering nothing. It races a plain access it is not ordered with, and an atomic that overlaps it at another address or size, but never an atomic of the same size at the same address. An atomicCAS that fails only reads. The checker wraps the atomic functions in macros, so a qualified call such as ::atomicAdd(...) does not compile, and a call that names its template argument, as in atomicAdd<float>(...), or goes through a pointer such as &atomicAdd<float>, is not checked. Global memory is not tracked. Tensor-core operand reads are only tracked through eg_emu_hazard_umma_read and eg_emu_hazard_umma_commit, which no header calls yet. A tcgen05.mma reads its shared-memory operands until the covering tcgen05.commit arrives. Even the issuer races with that read if it writes before observing the commit's phase complete. HazardReport.Coverage counts what was and says which mode ran.
Fences. __threadfence_block and __threadfence are fence.sc.cta and fence.sc.gpu, checked as fence.acq_rel at those scopes. A fence before an atomic write synchronizes with a fence after an atomic read of the same location, of the same size, that observes that write or a read-modify-write after it, when both fences' scopes include both threads; the edges fence.sc adds by its total order alone are left out. The atomic location can be in global memory. A plain or copy write over part of it ends what a later read can observe; under Launch.NoRawPointers or another compiler than clang, a plain write to global memory is not seen, so a race-free plain reset of a global flag does not end it, and a later read can be ordered by a write it did not observe. Clocks are per cluster and clusters run one at a time, so a handoff between clusters cannot be checked: a kernel that waits on another cluster does not finish. A thread that spins on a volatile load is reported as racing even when PTX orders it, as the checker sees a plain read, which is not strong. A fence also promotes .relaxed mbarrier operations, as eg_emu_fence_acq_rel does. HazardReport.Races gives the races as Race values, for tools that gate on them.
Ordering qualifiers. The plain mbarrier functions stand for the forms MBarrierForms lists: .release.cta arrives and .acquire.cta waits, the PTX defaults, except that the shared::cluster arrives to one peer CTA are .release.cluster; the multicast arrive is .release.cta and orders no other CTA's wait. The _sem forms (eg_emu_mbar_arrive_sem, eg_emu_mbar_wait_sem and others in mbarsem.h) take EG_EMU_RELAXED and EG_EMU_SCOPE_CLUSTER. Run ignores them, as a host thread sees every write after any wait; CheckHazards gives a .relaxed arrive or wait no edge unless eg_emu_fence_acq_rel promotes it, at the narrower of the fence's scope and its own, and an arrive from another CTA an edge only when both it and the wait are .cluster scope. ptxas emits the same SASS on sm_121a for .relaxed and .release CTA arrives, so a GPU run cannot show the difference. Launch.PermissiveScopes lets a .release.cluster arrive from another CTA synchronize with a .cta wait, as some cluster pipelines assume; the PTX memory model gives that pair no edge.
Under Schedule.Fibers on arm64 the lanes of a warp are fibers on one host thread and switch only at warp and block synchronization, spin waits (eg_emu_spin_until), mbarrier waits and __nanosleep; __syncthreads is still a barrier for the whole block. Two lanes of one warp then never interleave between those points, so a data race within a warp always resolves the same way and is hidden; races between warps and between blocks remain host-thread races. Atomics do not switch fibers: a lane that spins on atomics alone, waiting for a lane of its own warp, fails after EG_EMU_WAIT_TIMEOUT_MS (put __nanosleep in the loop, or use a barrier or eg_emu_spin_until).
Warps. The collectives exchange values through a per-warp buffer between two barrier phases and honor the mask, including disjoint sub-warp masks. Shuffle operands are at most 8 bytes. A shuffle from a lane outside the mask returns that lane's stale value; a device leaves it undefined.
Atomics. Every atomic function takes one process-wide lock, so all atomic operations of a launch, on any address and in any block, happen in one total order: they are sequentially consistent, and more, since no two overlap at all. A device promises only that each operation is an indivisible read-modify-write. The emulator therefore cannot show a bug that needs a weaker ordering, such as two threads that each store a flag and then read the other's and both read the old value, and it cannot show a bug in code that mixes atomics with plain reads and writes of the same word, which run unlocked with the host's memory model and whatever the host compiler does to them at -O1. __threadfence and __threadfence_block are a host sequentially consistent fence, and the emulated threads are host threads on the host's memory model, so a write is never held back the way a device may hold it: a kernel that omits the fence between writing data and publishing a flag for it passes here.
Mbarriers. The emulation follows the PTX ISA's .layout::v0 mbarrier: a phase completes when its pending arrivals and its tx-count both reach zero, the tx-count may go negative, and counts outside the ranges the ISA gives fail the run. An arrival returns a state that names the barrier's init and phase, so a wait with the state of another barrier, of an earlier init, or of a phase before the preceding one fails. A try_wait (eg_emu_mbar_try_wait) returns false at once the first time a thread tries an incomplete phase, as a device may when its time limit expires, and blocks on later tries; the emulation keeps no clock, and the time hint changes nothing. That is an approximation: a correct kernel that needs two false results in one phase, to poll two barriers in turn, say, is reported deadlocked. Initializing a barrier again fails unless it was invalidated or is unused. In a cluster, the shared::cluster forms (eg_emu_mbar_arrive_cluster, eg_emu_mbar_expect_tx and the like) reach another CTA's barrier through an address from eg_emu_map_shared_rank, and the other forms fail on one. Multicast takes the barrier, and the copy's destination, at the same CTA-relative offset in each CTA of the mask, which must be in per-block shared memory (dynamic or CUDAHOSTEMU_SHARED). A block of a cluster whose threads all wait on its mbarriers fails once no thread of the cluster can run, but while a peer waits in a cluster barrier it fails only after EG_EMU_WAIT_TIMEOUT_MS. There are no multicast forms of expect_tx, complete_tx, arrive.expect_tx or arrive_drop, and no .cta_group::2 copies; clc.h reroutes only the parity waits. The emulation does not model the .layout::v1 conditional phase and report, cp.async.mbarrier.arrive or check_layout, and it does not check that multicast is used only on the architectures that have it (ptxas 13.4 rejects the multicast arrive for sm_121a). MBarrierForms lists the SASS that ptxas emits for each form. Every arrival behaves as .release and every wait as .acquire, at cluster scope, so a kernel that arrives .relaxed where it needs .release, or at .cta scope where a peer CTA reads, passes here.
What an emulator run can expose: a lost update, a protocol that deadlocks or releases a barrier or wait early, a read of memory never written, a read of a copy or accumulator before its wait. What it cannot: any bug that needs release/acquire or weaker ordering to appear, a missing or misplaced fence, and a race on plain memory except by chance. A kernel that passes here is not thereby free of ordering or race bugs on a device; a green run is not an ordering proof.
Shared memory. Static __shared__ arrays are function-local statics in one linker section that is refilled with 0xff before each block (each cluster) runs. They are one object per program, not per block, so a launch that runs blocks at once refuses a program that has any; use CUDAHOSTEMU_SHARED or dynamic shared memory there. Nothing limits shared memory to what a device offers. Shared memory, cudaMalloc memory and a cp.async destination hold 0xff bytes until written, where a device holds arbitrary bytes; an uninitialized local holds whatever the host's stack does.
Arithmetic. Kernel code is C++20 compiled by the host compiler at -O1 with no fast-math flag, so device functions, templates and recursion are the host's, and so is everything C++ leaves undefined: signed overflow, shifts by the width or more, integer division by zero and float conversions that overflow the integer give the host's result, not the device's. The host compiler decides whether a*b+c becomes a fused multiply-add, and nvcc decides separately, so results can differ in the last bit; the __f*_rn functions are never fused. Math functions are the host C library's and are not bit-identical to the device's. There is no __half type: the header converts F16 and E4M3 bit patterns only inside the matrix instructions.
The runtime calls complete synchronously on host memory. A launch is checked for 1 to 1024 threads per block and a nonzero grid, and for nothing else a device checks.
Timing is estimated separately, without running kernel source: SimulateTimeline schedules a TimelineProgram, each warp's TMA, mbarrier, MMA and tensor-memory instructions, against a fixed latency table and reports tensor-core utilization, TMA overlap, consumer stalls and tensor-memory occupancy. TimelineSummary.WritePerfettoJSON writes the result as Chrome trace-event JSON for ui.perfetto.dev. The latencies are round figures, not measurements; the estimates rank schedules of one kernel and do not predict a device's run time.
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
Example ¶
package main
import (
"context"
"encoding/binary"
"fmt"
"log"
"math"
"os"
"github.com/tmc/lib/nvidia/x/nn/hostemu"
)
func main() {
dir, err := os.MkdirTemp("", "cudahostemu")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
const src = `
__global__ void warp_sum(float* x) {
float v = x[threadIdx.x];
for (int m = 16; m; m >>= 1) v += __shfl_xor_sync(~0u, v, m);
if (threadIdx.x == 0) x[0] = v;
}`
x := make([]byte, 32*4)
for i := range 32 {
binary.LittleEndian.PutUint32(x[4*i:], math.Float32bits(float32(i)))
}
out, err := hostemu.Run(context.Background(), dir, hostemu.Program{
Source: src,
Launch: "eg_emu_launch(dim3(1), dim3(32), 0, warp_sum, x)",
Buffers: []hostemu.Buffer{{Name: "x", CType: "float", Data: x}},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(math.Float32frombits(binary.LittleEndian.Uint32(out["x"])))
}
Output: 496
Index ¶
- Constants
- Variables
- func CLCHeader() string
- func Compiler() (string, error)
- func CompilerFamily(cxx string) (string, error)
- func CondGraphHeader() string
- func LDMatrixM8N8X4(lane int) (matrix, row, colBytes int)
- func MMAM16N8C(lane, reg int) (row, col int)
- func MMAM16N8K16A(lane, reg int) (row, colPair int)
- func MMAM16N8K16B(lane, reg int) (rowPair, col int)
- func MMAM16N8K32A(lane, reg int) (row, colQuad int)
- func MMAM16N8K32B(lane, reg int) (rowQuad, col int)
- func MMAM16N8K64NVFP4A(lane, reg int) (row, colOct int)
- func MMAM16N8K64NVFP4B(lane, reg int) (rowOct, col int)
- func MultimemSource() []byte
- func PDLHeader() string
- func Poison(n int) []byte
- func RewriteExternShared(src string) string
- func Run(ctx context.Context, dir string, p Program) (map[string][]byte, error)
- func RunMultiRank(ctx context.Context, src string, numRanks int, launch Launch, args ...Arg) error
- func RunPDLChain(ctx context.Context, src string, stages []PDLStage, args ...Arg) error
- func RunWithCLC(ctx context.Context, src string, activeCTAs, totalTiles int, block Dim3, ...) error
- func RunWithCLCGrid(ctx context.Context, src string, launch CLCLaunch, block Dim3, sharedBytes int, ...) error
- func RunWithTMEM(ctx context.Context, src string, launch Launch, args ...Arg) error
- func Source(name string) ([]byte, error)
- func SwizzleOffset(offsetBytes int, swizzle SwizzleMode) int
- func TMEMHeader() string
- func WGMMADesc(smemOffsetBytes, leadingBytes, strideBytes int, swizzle SwizzleMode) uint64
- func WriteHeaders(dir string) error
- type Arg
- type BlockOrder
- type Buffer
- type CLCLaunch
- type CondGraphStep
- type CondWhileConfig
- type CondWhileResult
- type DetBufferSpec
- type DetConflictKind
- type DetHazard
- type DetKernel
- type DetLaunch
- type DetLayout
- type DetResult
- type DetScalarSpec
- type DetStatus
- type DetWorker
- type Dim3
- type GEMMTimeline
- type Hazard
- type HazardCoverage
- type HazardKind
- type HazardReport
- type Launch
- type MBarrierForm
- type PDLStage
- type PDLViolation
- type PDLViolationError
- type PipeKind
- type Program
- type Race
- type Schedule
- type SwizzleMode
- type TMEMColumnSlice
- type TimelineArch
- type TimelineFinding
- type TimelineFlow
- type TimelineOp
- type TimelineOpKind
- type TimelineProgram
- type TimelineSpan
- type TimelineSummary
- type TimelineWarp
Examples ¶
Constants ¶
const ( Header = "cudahostemu.h" // the emulator SGLangMock = "sgl_mock.h" // SGLang and tvm-ffi host mock; includes Header UMMA = "umma.h" // tcgen05 descriptor-level MMA and TMEM; include after Header UMMAArith = "umma_arith.h" // pure-integer tcgen05 UMMA scalar reference arithmetic; included by UMMA MBarSem = "mbarsem.h" // mbarrier ordering qualifiers; Run includes it after Header )
Header names, as written by WriteHeaders.
const ( TrackTMAEngine = 1000 TrackTensorCore = 1001 )
Timeline track IDs for the asynchronous engines, above any warp ID.
const CLCHeaderFile = "clc.h"
CLCHeaderFile is the filename of the Blackwell clusterlaunchcontrol host emulation C++ header.
const CondGraphHeaderFile = "condgraph.h"
CondGraphHeaderFile is the filename of the CUDA Conditional Graph emulation header.
const ConsumerStallLimit = 0.20
ConsumerStallLimit is the fraction of total cycles of consumer stall above which SimulateTimeline reports a "consumer-stall" finding.
const HazardHeader = "hazard.h"
HazardHeader is the filename of the host hazard-sanitizer C++ header.
const MultimemHeader = "multimem.h"
MultimemHeader is the filename of the multi-rank NVLink symmetric memory header.
const PDLHeaderFile = "pdl.h"
PDLHeaderFile is the filename of the Programmatic Dependent Launch emulation header.
const StatusCheck = " if (cudaError_t cudahostemu_e = cudaPeekAtLastError(); cudahostemu_e != cudaSuccess) {\n" +
" std::fprintf(stderr, \"cudahostemu: launch left status %d\\n\", (int)cudahostemu_e);\n" +
" return 1;\n }\n"
StatusCheck is the C++ that main runs after the launch of a Program with CheckStatus set. A program of another runner that builds its own main may include it too.
const TMEMHeaderFile = "tmem.h"
TMEMHeaderFile is the filename of the Blackwell TMEM and tcgen05 host emulation C++ header.
Variables ¶
var ( // ErrCondGraphRunawayLoop is returned by [RunConditionalWhile] when the // conditional WHILE body never sets the conditional handle to 0 within // MaxIterations, or when RequireExplicitUpdate is set and a body iteration // fails to call cudaGraphSetConditional. ErrCondGraphRunawayLoop = errors.New("cudahostemu: conditional graph WHILE loop exceeded MaxIterations or failed to update handle") // ErrCondGraphDataRace is returned by [RunConditionalWhile] when // DetectDataRace is enabled and multiple threads update the same // conditional handle within a single body iteration. ErrCondGraphDataRace = errors.New("cudahostemu: data race on cudaGraphConditionalHandle across threads") )
var ErrNVLinkOrderingViolation = errors.New("cudahostemu: NVLink ordering violation")
ErrNVLinkOrderingViolation is returned by RunMultiRank when a kernel performs a cross-rank multimem.ld_reduce or remote peer read before all ranks have synchronized at eg_emu_nvlink_barrier for an epoch with prior writes.
var ErrNoCompiler = errors.New("cudahostemu: no C++ compiler (set CXX or install clang++)")
ErrNoCompiler is returned when no C++20 compiler is found.
var ErrWorkerTimeout = errors.New("hostemu: detsched worker timed out")
ErrWorkerTimeout is returned when a launch exceeds its Go-side context deadline and the persistent worker had to be terminated and restarted.
var MBarrierForms = []MBarrierForm{
{"mbarrier.init.shared::cta.b64 [bar], 32", "eg_emu_mbar_init", "SYNCS.EXCH.64", "after FENCE.VIEW.ASYNC.S"},
{"mbarrier.inval.shared::cta.b64 [bar]", "eg_emu_mbar_inval", "SYNCS.CCTL.IV", ""},
{"mbarrier.arrive.shared::cta.b64 st, [bar]", "eg_emu_mbar_arrive", "SYNCS.ARRIVE.TRANS64.A1T0", ""},
{"mbarrier.arrive.relaxed.cta.shared::cta.b64 st, [bar]", "eg_emu_mbar_arrive", "SYNCS.ARRIVE.TRANS64.A1T0", "same as .release"},
{"mbarrier.arrive.shared::cta.b64 st, [bar], count", "eg_emu_mbar_arrive", "SYNCS.ARRIVE.TRANS64.ART0", ""},
{"mbarrier.arrive.expect_tx.shared::cta.b64 st, [bar], 128", "eg_emu_mbar_arrive_expect_tx", "SYNCS.ARRIVE.TRANS64", ""},
{"mbarrier.arrive.noComplete.shared::cta.b64 st, [bar], count", "eg_emu_mbar_arrive_no_complete", "SYNCS.ARRIVE.TRANS64.TMASK.ART0", ""},
{"mbarrier.arrive_drop.shared::cta.b64 st, [bar]", "eg_emu_mbar_arrive_drop", "SYNCS.ARRIVE.TRANS64.OPTOUT.A1T0", ""},
{"mbarrier.arrive_drop.shared::cta.b64 st, [bar], count", "eg_emu_mbar_arrive_drop", "SYNCS.ARRIVE.TRANS64.OPTOUT.ART0", ""},
{"mbarrier.arrive.release.cluster.shared::cluster.b64 _, [remote]", "eg_emu_mbar_arrive_cluster", "SYNCS.ARRIVE.TRANS64.RED.A1T0", "after MEMBAR.ALL.CTA and MEMBAR.ALL.GPU"},
{"mbarrier.arrive.expect_tx.release.cluster.shared::cluster.b64 _, [remote], 128", "eg_emu_mbar_arrive_expect_tx_cluster", "SYNCS.ARRIVE.TRANS64.RED", "after MEMBAR.ALL.CTA and MEMBAR.ALL.GPU"},
{"mbarrier.arrive_drop.release.cluster.shared::cluster.b64 _, [remote]", "eg_emu_mbar_arrive_drop_cluster", "SYNCS.ARRIVE.TRANS64.RED.OPTOUT.A1T0", "after MEMBAR.ALL.CTA and MEMBAR.ALL.GPU"},
{"mbarrier.arrive.release.cta.shared::cluster.multicast::cluster::32b.b64 _, [bar], 1, 3", "eg_emu_mbar_arrive_multicast", "", "ptxas rejects the form for sm_121a"},
{"mbarrier.expect_tx.relaxed.cta.shared::cta.b64 [bar], 128", "eg_emu_mbar_expect_tx", "SYNCS.ARRIVE.TRANS64.RED.A0TR", ""},
{"mbarrier.expect_tx.relaxed.cluster.shared::cluster.b64 [remote], 128", "eg_emu_mbar_expect_tx", "SYNCS.ARRIVE.TRANS64.RED.A0TR", ""},
{"mbarrier.complete_tx.relaxed.cta.shared::cta.b64 [bar], 128", "eg_emu_mbar_complete_tx", "SYNCS.ARRIVE.TRANS64.RED.A0TX", ""},
{"mbarrier.test_wait.parity.shared::cta.b64 p, [bar], 0", "eg_emu_mbar_test_wait", "SYNCS.PHASECHK.TRANS64", ""},
{"mbarrier.test_wait.shared::cta.b64 p, [bar], st", "eg_emu_mbar_test_wait_state", "SYNCS.PHASECHK.TRANS64", ""},
{"mbarrier.try_wait.parity.shared::cta.b64 p, [bar], 0", "eg_emu_mbar_try_wait", "SYNCS.PHASECHK.TRANS64.TRYWAIT", ""},
{"mbarrier.try_wait.parity.relaxed.cluster.shared::cta.b64 p, [bar], 0", "eg_emu_mbar_try_wait", "SYNCS.PHASECHK.TRANS64.TRYWAIT", "same as .acquire.cta"},
{"mbarrier.try_wait.parity.shared::cta.b64 p, [bar], 0, 1000", "eg_emu_mbar_try_wait", "SYNCS.PHASECHK.TRANS64.TRYWAIT", "then, if not complete, NANOSLEEP.SYNCS 0x3e8 and SYNCS.PHASECHK.TRANS64"},
{"mbarrier.try_wait.shared::cta.b64 p, [bar], st", "eg_emu_mbar_try_wait_state", "SYNCS.PHASECHK.TRANS64.TRYWAIT", ""},
{"mbarrier.pending_count.b64 count, st", "eg_emu_mbar_pending_count", "", "integer arithmetic on the state register"},
}
MBarrierForms lists mbarrier forms as ptxas 13.4 (V13.4.59) compiles them for sm_121a (GB10). Each row was observed by compiling a one-kernel probe with that form and disassembling the cubin with cuobjdump -sass. Forms not listed were not tried.
Functions ¶
func CLCHeader ¶
func CLCHeader() string
CLCHeader returns the C++ header implementing Blackwell sm_100a clusterlaunchcontrol (try_cancel / query_cancel) host emulation and async mbarrier hazard detection.
func Compiler ¶
Compiler returns the C++ compiler to use: $CXX if set, else the first of clang++, g++ and c++ on PATH.
func CompilerFamily ¶
CompilerFamily reports which compiler cxx is, from its --version banner: "clang" or "gcc", or "" for neither. Flags outside the common set, such as clang's -mllvm or -include-pch, depend on it.
func CondGraphHeader ¶
func CondGraphHeader() string
CondGraphHeader returns the C++ header text implementing CUDA 12.4+/13.x cudaGraphConditionalHandle and cudaGraphSetConditional device-side emulation.
func LDMatrixM8N8X4 ¶
LDMatrixM8N8X4 returns the 8x8 matrix index (0..3) and row (0..7) whose shared-memory row address lane (0..31) supplies to ldmatrix.sync.aligned.m8n8.x4.shared.b16, together with the byte offset colBytes (0, 4, 8, or 12) within row (lane&31)/4 of matrix j that lane receives in destination register j (0..3).
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/nn/hostemu"
)
func main() {
mat, row, colBytes := hostemu.LDMatrixM8N8X4(19)
fmt.Printf("matrix=%d row=%d colBytes=%d\n", mat, row, colBytes)
}
Output: matrix=2 row=3 colBytes=12
func MMAM16N8C ¶
MMAM16N8C returns the accumulator row (0..15) and column (0..7) held by FP32 register reg (0..3) of warp lane (0..31) in mma.sync.aligned.m16n8k16, mma.sync.aligned.m16n8k32, and mma.sync.aligned.m16n8k64.
func MMAM16N8K16A ¶
MMAM16N8K16A returns the matrix A row (0..15) and starting K-column pair (0, 2, ..., 14) held by 32-bit register reg (0..3) of warp lane (0..31) in mma.sync.aligned.m16n8k16.row.col.f32.{bf16,f16}.f32.
The low 16 bits of reg hold A[row, colPair] and the high 16 bits hold A[row, colPair+1].
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/nn/hostemu"
)
func main() {
row, colPair := hostemu.MMAM16N8K16A(5, 2)
bRowPair, bCol := hostemu.MMAM16N8K16B(5, 1)
cRow, cCol := hostemu.MMAM16N8C(5, 3)
fmt.Printf("A=(%d,%d) B=(%d,%d) C=(%d,%d)\n", row, colPair, bRowPair, bCol, cRow, cCol)
}
Output: A=(1,10) B=(10,1) C=(9,3)
func MMAM16N8K16B ¶
MMAM16N8K16B returns the starting K-row pair (0, 2, ..., 14) and N-column (0..7) held by 32-bit register reg (0..1) of warp lane (0..31) in mma.sync.aligned.m16n8k16.row.col.f32.{bf16,f16}.f32.
The low 16 bits of reg hold B[rowPair, col] and the high 16 bits hold B[rowPair+1, col].
func MMAM16N8K32A ¶
MMAM16N8K32A returns the matrix A row (0..15) and starting K-column quad (0, 4, ..., 28) held by 32-bit register reg (0..3) of warp lane (0..31) in mma.sync.aligned.m16n8k32.row.col.f32.e4m3.e4m3.f32.
Byte b (0..3, from low byte to high byte) of reg holds A[row, colQuad+b].
func MMAM16N8K32B ¶
MMAM16N8K32B returns the starting K-row quad (0, 4, ..., 28) and N-column (0..7) held by 32-bit register reg (0..1) of warp lane (0..31) in mma.sync.aligned.m16n8k32.row.col.f32.e4m3.e4m3.f32.
Byte b (0..3, from low byte to high byte) of reg holds B[rowQuad+b, col].
func MMAM16N8K64NVFP4A ¶
MMAM16N8K64NVFP4A returns the matrix A row (0..15) and starting K-column octad (0, 8, ..., 56) held by 32-bit register reg (0..3) of warp lane (0..31) in Blackwell block-scaled mma.sync.aligned.m16n8k64.row.col.kind::mxf4nvf4.
Nibble n (0..7, from bits 0..3 to bits 28..31) of reg holds A[row, colOct+n]. The four E4M3 block-16 scales for A[row, 0..63] sit in bytes 0..3 of sfa on lane (row%8)*4 + (row/8).
func MMAM16N8K64NVFP4B ¶
MMAM16N8K64NVFP4B returns the starting K-row octad (0, 8, ..., 56) and N-column (0..7) held by 32-bit register reg (0..1) of warp lane (0..31) in Blackwell block-scaled mma.sync.aligned.m16n8k64.row.col.kind::mxf4nvf4.
Nibble n (0..7, from bits 0..3 to bits 28..31) of reg holds B[rowOct+n, col]. The four E4M3 block-16 scales for B[0..63, col] sit in bytes 0..3 of sfb on lane col*4.
func MultimemSource ¶
func MultimemSource() []byte
MultimemSource returns the embedded multimem.h header bytes.
func PDLHeader ¶
func PDLHeader() string
PDLHeader returns the C++ header text implementing adversarial Hopper/Blackwell Programmatic Dependent Launch (griddepcontrol.launch_dependents / griddepcontrol.wait) emulation.
func Poison ¶
Poison returns n bytes of 0xff, NaN in every float format the header handles. Passing outputs in poisoned shows an element a kernel never writes.
func RewriteExternShared ¶
RewriteExternShared returns CUDA source with each dynamic shared memory declaration,
extern __shared__ T name[];
replaced by the emulator's form of it, since "extern static" is not C++. Run applies it to Program.Source; a caller that compiles kernel source against the headers itself (see WriteHeaders) calls it first.
Every rewritten name is the start of the running block's dynamic shared memory, whose size in bytes is the third argument of eg_emu_launch or CUDAHOSTEMU_LAUNCH, so several declarations alias one region and a kernel carves it up by hand, as on a GPU. An alignment specifier is dropped: the region is always 1024-byte aligned. Inside a function the name stays an array in every expression, and a declaration in a macro body is taken to be used inside one. At namespace scope it is an object that converts to T*, which reinterpret_cast and template argument deduction do not accept.
The rewrite is textual. It keeps line numbers, skips comments and string literals, and does not see a declaration assembled by macro expansion, which then fails to compile.
func Run ¶
Run compiles and runs p in dir, a scratch directory, and returns every buffer's final contents by name. Flags in $CUDAHOSTEMU_FLAGS, split on spaces, follow p.Flags, so that a caller can rebuild every program differently (-DEG_EMU_ZERO_SMEM, say) without editing it.
func RunMultiRank ¶
RunMultiRank compiles and executes src across numRanks simulated GPUs simultaneously on the host CPU. Each rank r in 0..numRanks-1 executes its CTA grid on its own C++ thread(s) with eg_emu_rank() == r and eg_emu_num_ranks() == numRanks. Any Arg with a non-empty Data slice is updated in place with the buffer's final contents after the launch completes.
func RunPDLChain ¶
RunPDLChain compiles and executes a sequence of Programmatic Dependent Launch stages on the host CPU with adversarial buffer poisoning enabled.
Intermediate buffers produced by stage i and consumed by stage i+1 are registered with eg_emu_pdl_register_buffer and poisoned with 0xff (NaN) until the producer triggers eg_pdl_trigger / eg_emu_pdl_launch_dependents and the consumer calls eg_pdl_wait / eg_emu_pdl_wait. Final buffer contents are copied back into any non-empty Data slices in args. If any PDL ordering violation is observed, RunPDLChain returns a *PDLViolationError.
func RunWithCLC ¶
func RunWithCLC(ctx context.Context, src string, activeCTAs, totalTiles int, block Dim3, sharedBytes int, args ...Arg) error
RunWithCLC emulates a full-grid, single-CTA CLC launch and checks coverage.
func RunWithCLCGrid ¶
func RunWithCLCGrid(ctx context.Context, src string, launch CLCLaunch, block Dim3, sharedBytes int, args ...Arg) error
RunWithCLCGrid runs the supplied kernel with explicit physical launch geometry.
func RunWithTMEM ¶
RunWithTMEM compiles and runs src on the host CPU with Blackwell sm_100a TMEM and tcgen05 emulation enabled. Any BufferArg with non-empty Data is updated in place with the buffer's post-launch contents. After the kernel finishes, RunWithTMEM verifies eg_emu_tmem_error_count() == 0 and returns a descriptive error if any TMEM synchronization hazard (such as tcgen05.ld before tcgen05.wait) or TMEM lifecycle error (such as leaked columns on CTA exit) occurred.
A tcgen05.ld (eg_emu_tcgen05_ld_f32) completes only at the thread's next tcgen05.wait::ld (eg_emu_tcgen05_wait_ld): its registers hold NaN until then, and an eg_emu_tmem_dealloc or tcgen05.mma that reaches its columns first is an error. Under clang, unless launch.NoRawPointers is set, the kernel source is compiled with the instrumentation CheckHazards uses for raw pointers, and a read of the registers before the wait is an error too; with another compiler such a read only sees NaN.
func SwizzleOffset ¶
func SwizzleOffset(offsetBytes int, swizzle SwizzleMode) int
SwizzleOffset returns the shared-memory byte offset after applying swizzle.
func TMEMHeader ¶
func TMEMHeader() string
TMEMHeader returns the C++ header implementing Blackwell sm_100a Tensor Memory (TMEM) and tcgen05 host emulation.
func WGMMADesc ¶
func WGMMADesc(smemOffsetBytes, leadingBytes, strideBytes int, swizzle SwizzleMode) uint64
WGMMADesc encodes a 64-bit Hopper WGMMA shared-memory matrix descriptor from byte offsets (each shifted right by 4 into a 14-bit field) and a swizzle mode.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/nn/hostemu"
)
func main() {
desc := hostemu.WGMMADesc(1024, 16, 1024, hostemu.Swizzle128B)
swz := hostemu.SwizzleOffset(128+16, hostemu.Swizzle128B)
fmt.Printf("desc=%#x swz=%d\n", desc, swz)
}
Output: desc=0x4000004000010040 swz=128
func WriteHeaders ¶
WriteHeaders writes every header into dir, which must exist.
Types ¶
type Arg ¶
type Arg struct {
Name string // optional variable name in main
CType string // element C type for pointer buffers (e.g. "float", "uint32_t")
Data []byte // initial buffer contents; if nil, Size zero bytes are allocated
Size int // buffer size in bytes when Data is nil (default 4096)
Expr string // C++ expression for scalar arguments (e.g. "64", "1.0f")
}
Arg describes a kernel argument passed to CheckHazards. A buffer argument sets CType (and optionally Name, Data, or Size); a scalar argument sets Expr to a C++ literal expression.
func CondHandleArg ¶
CondHandleArg returns a scalar Arg binding a named or positional cudaGraphConditionalHandle parameter.
func ZeroBufferArg ¶
ZeroBufferArg returns a zero-initialized pointer buffer Arg of size bytes.
type BlockOrder ¶
type BlockOrder int
A BlockOrder is the order in which a launch runs its blocks, or, in a concurrent launch, starts them.
const ( GridOrder BlockOrder = iota // x fastest, then y, then z ReverseOrder // grid order reversed ShuffleOrder // a permutation drawn from Schedule.Seed )
func (BlockOrder) String ¶
func (o BlockOrder) String() string
type Buffer ¶
type Buffer struct {
Name string
CType string // element type, such as "float" or "uint16_t"
Data []byte
}
A Buffer is one kernel buffer. Run binds it in main as a pointer named Name of type CType*, initialized with Data, and returns its final contents, len(Data) bytes.
type CLCLaunch ¶
CLCLaunch describes the physical 1D grid and the logical tiles it must cover. ActiveCTAs reserves the first resident CTAs; remaining physical CTAs may be canceled. ClusterSize defaults to one. CheckCoverage requires the kernel to call eg_emu_clc_record_tile once at each logical tile's output.
type CondGraphStep ¶
type CondGraphStep struct {
Kernel string // __global__ function name, or raw C++ launch statement
Grid Dim3 // grid dimensions in blocks (zero components default to 1)
Block Dim3 // block dimensions in threads (zero components default to 1)
Cluster int // cluster size in blocks along X (0 or 1 means no cluster)
Args []string // optional explicit C++ argument expressions for this step
}
CondGraphStep configures one kernel step inside a conditional WHILE or IF graph body executed by RunConditionalWhile.
type CondWhileConfig ¶
type CondWhileConfig struct {
Handle uint64 // conditional handle identifier (0 defaults to 1)
InitialCondition uint32 // initial handle condition (1 to enter loop, 0 to skip)
MaxIterations int // runaway loop guard (<= 0 defaults to 1024)
RequireExplicitUpdate bool // fail with ErrCondGraphRunawayLoop if an iteration does not call cudaGraphSetConditional
DetectDataRace bool // fail with ErrCondGraphDataRace if multiple threads write the handle in one iteration
}
CondWhileConfig configures a CUDA Conditional WHILE graph node execution in RunConditionalWhile.
type CondWhileResult ¶
type CondWhileResult struct {
IterationsExecuted int // number of body iterations executed
FinalCondition uint32 // final condition value stored in the handle
HandleUpdateCount int // total number of cudaGraphSetConditional calls across all iterations
IterationTrace []uint32 // condition value at the end of each executed iteration
}
CondWhileResult summarizes the execution of a CUDA Conditional WHILE loop under RunConditionalWhile.
func RunConditionalWhile ¶
func RunConditionalWhile(ctx context.Context, src string, cfg CondWhileConfig, body []CondGraphStep, args ...Arg) (*CondWhileResult, error)
RunConditionalWhile compiles and executes a conditional WHILE graph body on the host CPU across iterations without host round-trips between iterations until a kernel inside body calls cudaGraphSetConditional(handle, 0) or cfg.MaxIterations trips ErrCondGraphRunawayLoop.
Final buffer contents are copied back into any non-empty Data slices in args.
type DetBufferSpec ¶
type DetBufferSpec struct {
Name string
CType string // element C type, e.g. "float" or "unsigned"
}
DetBufferSpec describes one pointer parameter passed to a kernel.
type DetConflictKind ¶
type DetConflictKind uint32
DetConflictKind classifies a cross-fiber memory access conflict.
const ( DetConflictRAW DetConflictKind = 1 DetConflictWAR DetConflictKind = 2 DetConflictWAW DetConflictKind = 3 )
func (DetConflictKind) String ¶
func (c DetConflictKind) String() string
type DetHazard ¶
type DetHazard struct {
Kind HazardKind
BlockA uint32
FiberA uint32
BlockB uint32
FiberB uint32
SiteA uint32
SiteB uint32
ConflictKind DetConflictKind
Detail string
}
DetHazard describes one race or deadlock observed during a detsched launch.
type DetKernel ¶
type DetKernel struct {
// Source is the C++ kernel source defining KernelName. It is compiled as its
// own translation unit so clang -fsanitize-coverage instruments only kernel
// basic blocks (L1), not the scheduler or pipe runtime.
Source string
// KernelName is the __global__ function name to dispatch.
KernelName string
// Buffers and Scalars list the kernel's parameters in declaration order:
// all buffer pointers precede scalars unless ArgOrder is provided.
Buffers []DetBufferSpec
Scalars []DetScalarSpec
// ArgExprs optionally supplies the exact C++ argument list passed to
// KernelName(...), referencing bufs[i] and scalars[j]. If empty, buffers
// are passed first in order, followed by scalars.
ArgExprs []string
// Flags are extra C++ compiler flags passed to both TUs.
Flags []string
// L2Counters is the fixed size of the L2 conflict-pair counter array.
// Zero defaults to 4096.
L2Counters int
// SanCov enables clang -fsanitize-coverage=inline-8bit-counters,pc-table on
// the kernel TU for L1 branch coverage.
SanCov bool
// Compiler overrides Compiler() when non-empty.
Compiler string
}
DetKernel configures the one-time compilation of a persistent detsched worker.
type DetLaunch ¶
type DetLaunch struct {
Grid Dim3
Block Dim3
SMCount int // defaults to 48 if <= 0
BlocksPerSM int // defaults to 1 if <= 0
MaxSteps int // deterministic fiber-step watchdog; defaults to 200000 if <= 0
// Tape feeds one byte per schedule point when UseSeed is false.
Tape []byte
// UseSeed selects SplitMix64 seed replay instead of tape bytes.
UseSeed bool
Seed uint64
// DisableL2 skips L2 conflict-pair counter updates when true.
DisableL2 bool
// FrozenClock keeps eg_det_globaltimer() / clock64() frozen at 0ns when
// true (control arm), instead of advancing deterministically from the tape.
FrozenClock bool
Scalars []uint64
Buffers [][]byte
}
DetLaunch configures one execution sent over the pipe to a DetWorker.
type DetResult ¶
type DetResult struct {
Status DetStatus
TapeUsed int
TapeOverrun bool
ScheduleHash uint64
Steps uint64
Buffers [][]byte
Hazards []DetHazard
L1 []byte
L2 []byte
// Diagnostic carries an optional non-hazard runtime note (for example,
// "spin suspected (M-poll heuristic)" when a fiber polled an unchanged
// address for M = 2048 probes without confirming a closed state cycle).
// Diagnostic notes never indicate a proved hazard.
Diagnostic string
}
DetResult is the output, hazard report, and coverage counters from one launch.
type DetScalarSpec ¶
type DetScalarSpec struct {
Name string
CType string // scalar C type, e.g. "int", "unsigned", "float"
}
DetScalarSpec describes one scalar parameter passed to a kernel.
type DetStatus ¶
type DetStatus uint32
DetStatus classifies the outcome of one deterministic fiber launch.
Proved statuses (never trigger on step budget alone):
- DetDeadlock: tier-1 structural deadlock where runnable is empty while live fibers remain blocked in __syncthreads, grid.sync, or eg_det_spin_until (always outranks DetSpinStuck when both apply).
- DetSpinStuck: tier-2 proved unannotated spin-stuck, strictly when runnable is empty, zero fibers are blocked in sync/grid/spin, every watched address is unchanged across the probe, no other fiber can still write it, and every watch-parked fiber confirms a closed architectural state cycle (callee-saved registers and active fiber stack repeating identically across consecutive watched polls with zero writes and zero clock advance, within the M = 2048 poll probe window and 64-entry state ring). Assumes no untracked mutable C++ globals outside the fiber stack and tracked memory.
Heuristic / budget-exhaustion status:
- DetHang: deterministic MaxSteps budget expired before completion (not a proof of deadlock or spin-stuck). A live counter-bounded retry loop mutates its counter in registers/stack on every poll and therefore never returns DetSpinStuck or emits HazardSpinStuck; if it completes M = 2048 unchanged watched polls without a confirmed cycle, it continues until DetOK or DetHang and sets DetResult.Diagnostic to "spin suspected (M-poll heuristic)".
type DetWorker ¶
type DetWorker struct {
// contains filtered or unexported fields
}
DetWorker is a compiled, persistent single-OS-thread fiber worker communicating over stdin/stdout pipes. It is safe for sequential calls from a single caller or concurrent calls (serialized internally).
func CompileDetWorker ¶
CompileDetWorker builds a persistent detsched worker binary in dir and starts it.
func (*DetWorker) Layout ¶
Layout returns the worker's deterministic L1/L2 counter layout and digest.
func (*DetWorker) Run ¶
Run executes one deterministic launch on the persistent worker. If ctx expires or is canceled while waiting on the worker, the worker is killed (and restarted lazily on the next call), returning ErrWorkerTimeout on deadline expiry or context.Canceled on cancellation.
type Dim3 ¶
type Dim3 struct {
X, Y, Z int
}
Dim3 is a three-dimensional grid or block extent. Zero components default to 1.
type GEMMTimeline ¶
type GEMMTimeline struct {
M, N, K int // MMA shape per K step
KSteps int
Stages int // shared-memory ring depth
// Specialized puts TMA issue in a producer warp and MMA issue in a
// consumer warp. Otherwise one warp loads, waits and multiplies in turn.
Specialized bool
// WaitLoadInLoop reads the accumulator with tcgen05.ld and waits for
// it in every K step, right after the MMA, instead of once after the
// loop.
WaitLoadInLoop bool
ElemBytes int // operand element size; 0 means 2 (BF16)
}
A GEMMTimeline describes the main loop of one CTA's GEMM tile for GEMMTimelineProgram.
type Hazard ¶
type Hazard struct {
Kind HazardKind
CTA int
Thread int
PeerTID int
Offset int
Detail string
// contains filtered or unexported fields
}
Hazard describes a single detected concurrency or uniformity violation.
type HazardCoverage ¶
type HazardCoverage struct {
CopyWriteBytes int64 // bytes of shared memory written by cp.async and bulk copies
Syncs map[string]int64 // synchronization events by kind, such as "__syncthreads" or "mbarrier.wait"
// RawPointers reports whether the run checked the kernel source's
// accesses through raw pointers (see Launch.NoRawPointers). Without
// it, only the arrays the checker rewrites were checked.
RawPointers bool
}
HazardCoverage counts what a CheckHazards run tracked. A report with no hazards is evidence only about these accesses and synchronizations: a kernel whose shared memory the checker could not instrument shows zero tracked bytes, not an absence of races.
type HazardKind ¶
type HazardKind string
HazardKind classifies a GPU synchronization or uniformity hazard caught on the host CPU.
const ( HazardGlobalRace HazardKind = "global_memory_race" HazardDeadlock HazardKind = "deadlock" HazardSpinStuck HazardKind = "spin_stuck" )
HazardGlobalRace, HazardDeadlock, and HazardSpinStuck extend HazardKind for detsched reports.
const ( HazardDSMEMBeforeWait HazardKind = "dsmem_before_cluster_wait" HazardWGMMADivergence HazardKind = "wgmma_warpgroup_divergence" HazardNamedBarrierCount HazardKind = "named_barrier_count_mismatch" )
type HazardReport ¶
type HazardReport struct {
Hazards []Hazard
Coverage HazardCoverage
}
HazardReport summarizes hazards observed during an emulated kernel launch.
func CheckHazards ¶
func CheckHazards(ctx context.Context, src string, launch Launch, args ...Arg) (*HazardReport, error)
CheckHazards compiles and runs src on the host CPU with EG_EMU_HAZARD_CHECK enabled and returns all concurrency, barrier, DSMEM, and WGMMA uniformity hazards observed during the launch. If the emulator fails the run after recording hazards, as it does for a deadlock or a protocol error, CheckHazards returns those hazards together with the error.
func (*HazardReport) Count ¶
func (r *HazardReport) Count(kind HazardKind) int
Count returns the number of hazards in r matching kind.
func (*HazardReport) Has ¶
func (r *HazardReport) Has(kind HazardKind) bool
Has reports whether r contains at least one hazard of the given kind.
func (*HazardReport) Races ¶
func (r *HazardReport) Races() []Race
Races returns the shared memory races in r, in the order found. A report with no races is evidence only about the accesses and synchronizations that r.Coverage counts.
Example ¶
A cp.async copy is ordered before its issuer only by cp.async.wait_group. Reading the copied word without the wait is a race between the copy and the read.
package main
import (
"context"
"fmt"
"log"
"github.com/tmc/lib/nvidia/x/nn/hostemu"
)
func main() {
const src = `
__global__ void k(const uint32_t* in, uint32_t* out) {
uint32_t* s = (uint32_t*)eg_emu_dynamic_smem();
eg_emu_cp_async(s + 4 * threadIdx.x, in + 4 * threadIdx.x, 16);
eg_emu_cp_async_commit();
out[threadIdx.x] = s[4 * threadIdx.x]; // missing eg_emu_cp_async_wait(0)
}`
rep, err := hostemu.CheckHazards(context.Background(), src, hostemu.Launch{
Grid: hostemu.Dim3{X: 1}, Block: hostemu.Dim3{X: 1}, SharedBytes: 64,
}, hostemu.ZeroBufferArg("in", "uint32_t", 16), hostemu.ZeroBufferArg("out", "uint32_t", 4))
if err != nil {
log.Fatal(err)
}
for _, r := range rep.Races() {
fmt.Printf("%s at byte %d, copy %v\n", r.Conflict, r.Offset, r.Copy)
}
fmt.Println("copy bytes tracked:", rep.Coverage.CopyWriteBytes)
}
Output: read-after-write at byte 0, copy true copy bytes tracked: 16
type Launch ¶
type Launch struct {
Kernel string // __global__ function name, or raw C++ launch statement
Grid Dim3 // grid dimensions in blocks
Block Dim3 // block dimensions in threads
Cluster int // cluster size in blocks along X
Flags []string // extra C++ compiler flags
Mock bool // also include sgl_mock.h
// PermissiveScopes makes a .release.cluster mbarrier arrive from
// another CTA, observed by a .cta-scoped wait, synchronize. The PTX
// memory model gives that pair no edge, and by default the checker
// reports the accesses it would order; some cluster pipelines rely on
// it all the same.
PermissiveScopes bool
// NoRawPointers checks only the shared memory accesses to the arrays
// the checker can rewrite (declared __shared__ arrays and pointers
// cast from eg_emu_dynamic_smem), as a compiler other than clang
// always does.
//
// Otherwise, under clang, CheckHazards checks every shared memory
// access the kernel source makes, through raw pointers too. It
// compiles src with clang's address sanitizer instrumentation, which
// calls the checker on each load and store, and leaves out every
// function defined in the emulator's headers or in an include
// directory (the C++ library's), so the emulator's own bookkeeping is
// not checked. Device functions src includes from its own headers are
// checked, unless they live under a directory named include. The
// emulator's headers must be included as files, not pasted into src.
// HazardCoverage.RawPointers reports which a run did.
NoRawPointers bool
}
Launch configures a kernel launch for CheckHazards. Zero Grid, Block, or Cluster dimensions default to 1 (or Cluster for Grid.X when Cluster > 1). If Kernel is empty, CheckHazards launches the first __global__ kernel defined in src.
type MBarrierForm ¶
type MBarrierForm struct {
PTX string // the instruction; count is a register, remote an address from mapa
Func string // the emulating function in cudahostemu.h
SASS string // the SYNCS instruction emitted, or "" if none is
Note string // other instructions emitted, or why there is no SASS
}
An MBarrierForm links a PTX mbarrier instruction to the cudahostemu.h function that emulates it and to the SASS instruction ptxas emits for it.
type PDLStage ¶
type PDLStage struct {
Kernel string // __global__ function name (e.g. "producer" or "gemm<16>"), or raw C++ launch statement
Grid Dim3 // grid dimensions in blocks (zero components default to 1)
Block Dim3 // block dimensions in threads (zero components default to 1)
Cluster int // cluster size in blocks along X (0 or 1 means no cluster)
StageID uint32 // PDL stage ID (0 defaults to uint32(stageIndex + 1))
Buffer string // optional intermediate buffer name produced by this stage
Buffers []string // optional intermediate buffer names produced by this stage
Args []string // optional explicit C++ argument expressions for this stage
}
PDLStage configures one stage in a multi-kernel Programmatic Dependent Launch chain executed by RunPDLChain.
type PDLViolation ¶
PDLViolation describes a single Programmatic Dependent Launch ordering or synchronization violation detected during host emulation.
type PDLViolationError ¶
type PDLViolationError struct {
Violations []PDLViolation
}
PDLViolationError is returned by RunPDLChain when one or more PDL ordering violations occur during emulation.
func (*PDLViolationError) Error ¶
func (e *PDLViolationError) Error() string
type Program ¶
type Program struct {
Source string // kernels and launchers, compiled after the headers
Launch string // C++ statements run in main once buffers are bound
Buffers []Buffer // in the order they are bound
Flags []string // extra compiler flags, such as -DEG_EMU_ZERO_SMEM
Mock bool // also include sgl_mock.h
// Schedule chooses block order, concurrency and the clock; its flags
// precede Flags.
Schedule Schedule
// CheckStatus makes main exit with status 1, before it writes any
// buffer, if the emulated runtime recorded an error that Launch
// did not take: the status cudaPeekAtLastError returns after
// Launch is not cudaSuccess. Peeking leaves the error for a caller
// that reads it afterwards. A launcher that returns void drops such
// an error.
CheckStatus bool
}
A Program is kernel source and the statement that launches it.
Source may declare dynamic shared memory as CUDA does, with "extern __shared__ T name[];": Run passes it through RewriteExternShared. The region's size in bytes is the third argument of eg_emu_launch in Launch, as it is the third launch parameter of kernel<<<grid, block, bytes>>>.
type Race ¶
type Race struct {
Conflict string // "read-after-write", "write-after-read" or "write-after-write"
CTA int // linear index of the CTA whose shared memory both touch
Offset int // byte offset in that CTA's shared memory
Thread int // thread of the later access, or the issuer of its copy
Peer int // thread of the earlier access, or the issuer of its copy
Copy bool // either access is a cp.async or bulk copy's write
Detail string // the checker's account, naming any ordering edge an mbarrier qualifier or a fence scope dropped
}
A Race is a pair of shared memory accesses, one a write, that no happens-before edge orders: a HazardSharedRace in structured form.
type Schedule ¶
type Schedule struct {
// Order is the order of blocks, or of whole clusters.
Order BlockOrder
// Seed draws ShuffleOrder's permutation and the schedule points'
// perturbations.
Seed uint64
// Points perturbs each thread at schedule points (spin-wait polls,
// __syncthreads and atomics) with yields and short sleeps drawn from
// Seed. The same seed gives the same draws, not the same interleaving.
Points bool
// Concurrent runs every block of a non-cluster launch at once, as a
// cooperative grid runs, so that grid barriers complete. The program
// must keep per-block shared memory in CUDAHOSTEMU_SHARED or dynamic
// shared memory; a concurrent launch fails if there is static
// __shared__ storage.
Concurrent bool
// Stall, in a concurrent launch, holds back block StallBlock (linear,
// x fastest) until every other block has exited.
Stall bool
StallBlock int
// Fibers runs the launch on the fiber engine (EG_EMU_FIBERS): on
// arm64 the lanes of each warp run as fibers on one host thread and
// switch only where they synchronize or wait; elsewhere threads come
// from a pool kept between launches, not started per launch. Results
// do not change for a program free of data races.
Fibers bool
// ClockStep, if positive, makes eg_emu_now_ns a virtual clock that
// every read advances by ClockStep, the rule of
// [github.com/tmc/lib/nvidia/x/virtualclock].
ClockStep time.Duration
}
A Schedule chooses how the emulator runs a launch, so that a test can put a kernel's grid barriers and bounded waits under adversarial block orders and replay a failing one. The zero Schedule is the emulator's default: blocks one after another in grid order, on the host's clock.
A Schedule applies to launches through eg_emu_launch, CUDAHOSTEMU_LAUNCH, run_grid and run_cluster_grid. It becomes -D flags (see Schedule.Flags and the schedule-control comment in cudahostemu.h), so a failing schedule replays from its flags, which Run's errors name.
type SwizzleMode ¶
type SwizzleMode uint8
SwizzleMode is the shared-memory swizzle mode of a Hopper WGMMA matrix descriptor (bits 62..63 of the 64-bit descriptor).
const ( SwizzleNone SwizzleMode = 0 // no swizzle (16-byte core matrix) Swizzle128B SwizzleMode = 1 // 128-byte swizzle Swizzle64B SwizzleMode = 2 // 64-byte swizzle Swizzle32B SwizzleMode = 3 // 32-byte swizzle )
type TMEMColumnSlice ¶
type TMEMColumnSlice struct {
StartCol int
NumCols int
AllocCycle uint64
FreeCycle uint64
Label string
}
A TMEMColumnSlice is a tensor-memory allocation of NumCols columns from StartCol, live from AllocCycle to FreeCycle.
type TimelineArch ¶
type TimelineArch struct {
Name string
TMEMColumns int // 0 for an architecture without tensor memory
TMAIssue int // cycles to issue cp.async.bulk.tensor
TMALatency int // minimum cycles from issue to completion
TMABytesCycle float64 // bytes per cycle the TMA engine moves
MMAIssue int // cycles to issue an MMA
MMAOpsCycle float64 // multiply-add operations (2 per MAC) per cycle
TMEMIssue int // cycles to issue tcgen05.ld
TMEMLdLag int // cycles after the last MMA completes until tcgen05.ld data is ready
BarrierIssue int // cycles for an arrive, a commit, or a satisfied wait
AllocIssue int // cycles for tcgen05.alloc or dealloc
}
A TimelineArch is the latency model SimulateTimeline uses. The values from TimelineArchFor are round figures chosen to be in proportion to one another, not measurements of a device.
func TimelineArchFor ¶
func TimelineArchFor(arch string) (TimelineArch, error)
TimelineArchFor returns the model for arch: sm_90a (wgmma, no tensor memory), sm_100a, sm_107a, or sm_121a. GB10 (sm_121a) has no tcgen05 hardware; its entry models the emulated form only.
type TimelineFinding ¶
type TimelineFinding struct {
Kind string // "consumer-stall" or "wait-ld-after-mma"
Warp int
Op int // index in the warp's Ops, or -1
Detail string
}
A TimelineFinding is a schedule problem SimulateTimeline flagged.
type TimelineFlow ¶
type TimelineFlow struct {
ID uint64
FromTrack int
FromCycle uint64
ToTrack int
ToCycle uint64
Barrier int
Phase int
}
A TimelineFlow links the arrival that completed a barrier phase to the wait it released.
type TimelineOp ¶
type TimelineOp struct {
Kind TimelineOpKind
Bar int
Phase int
Bytes int
M, N, K int
Cols int
Cycles int
Label string
}
A TimelineOp is one modeled instruction. Phase counts completions of the barrier from zero; the PTX parity operand is Phase&1.
func (TimelineOp) Mnemonic ¶
func (op TimelineOp) Mnemonic(arch TimelineArch) string
Mnemonic returns the PTX instruction op stands for on arch.
type TimelineOpKind ¶
type TimelineOpKind uint8
A TimelineOpKind is an instruction a TimelineProgram models.
const ( OpTMALoad TimelineOpKind = iota // cp.async.bulk.tensor completing Bytes on mbarrier Bar OpArrive // mbarrier.arrive on Bar OpWait // mbarrier.try_wait.parity until phase Phase of Bar completes OpMMA // tcgen05.mma (wgmma.mma_async on sm_90a) of shape M×N×K OpCommit // tcgen05.commit: arrive on Bar when this warp's MMAs complete OpAlloc // tcgen05.alloc of Cols columns, named Label OpDealloc // tcgen05.dealloc of the allocation named Label OpLoad // tcgen05.ld OpWaitLoad // tcgen05.wait::ld OpCompute // Cycles of other work )
type TimelineProgram ¶
type TimelineProgram struct {
CTA int
// Barriers holds each mbarrier's arrival count per phase.
Barriers []int
Warps []TimelineWarp
}
A TimelineProgram is the modeled instruction streams of one CTA.
func GEMMTimelineProgram ¶
func GEMMTimelineProgram(g GEMMTimeline) (TimelineProgram, error)
GEMMTimelineProgram returns the modeled instruction streams of g's main loop: per K step, a TMA load of the A and B tiles into stage k%Stages, a wait on that stage's full barrier, an MMA, and a commit to its empty barrier, which the load of step k+Stages waits on. The accumulator lives in tensor memory, allocated before the loop and read after it.
type TimelineSpan ¶
type TimelineSpan struct {
Name string `json:"name"`
Category PipeKind `json:"cat"`
Track int `json:"tid"`
CTA int `json:"pid"`
StartCycle uint64 `json:"ts"`
DurCycles uint64 `json:"dur"`
Args map[string]any `json:"args,omitempty"`
}
A TimelineSpan is one interval of the timeline: an instruction, an asynchronous engine operation, or a stall.
type TimelineSummary ¶
type TimelineSummary struct {
Arch string
CTA int
TotalCycles uint64
TensorCoreActiveCyc uint64
TMAActiveCyc uint64
ConsumerStallCyc uint64 // cycles consumer warps wait with none of their MMAs in flight
TensorUtilPct float64 // 100 * TensorCoreActiveCyc / TotalCycles
TMAOverlapPct float64 // percent of TMAActiveCyc during which the tensor core is busy
PeakTMEMCols int
Spans []TimelineSpan
Flows []TimelineFlow
TMEMMap []TMEMColumnSlice
Findings []TimelineFinding
}
A TimelineSummary is the result of SimulateTimeline.
func SimulateTimeline ¶
func SimulateTimeline(p TimelineProgram, arch string) (TimelineSummary, error)
SimulateTimeline schedules p on the model for arch. Each warp issues its instructions in order; a ready warp with the earliest clock runs next. The TMA engine and the tensor core each serve one operation at a time, in issue order. A wait for a barrier phase blocks its warp until the phase's last arrival; a tcgen05.wait::ld blocks until the last MMA issued before the matching tcgen05.ld has completed plus TMEMLdLag. SimulateTimeline returns an error if every unfinished warp is blocked on a phase that can no longer complete, or if a tensor-memory allocation does not fit.
Example ¶
p, err := GEMMTimelineProgram(GEMMTimeline{M: 128, N: 256, K: 64, KSteps: 32, Stages: 3, Specialized: true})
if err != nil {
panic(err)
}
s, err := SimulateTimeline(p, "sm_100a")
if err != nil {
panic(err)
}
fmt.Printf("%d cycles, tensor core %.0f%% busy, %.0f%% of TMA time overlapped\n", s.TotalCycles, s.TensorUtilPct, s.TMAOverlapPct)
Output: 16823 cycles, tensor core 97% busy, 97% of TMA time overlapped
func (TimelineSummary) WritePerfettoJSON ¶
func (s TimelineSummary) WritePerfettoJSON(w io.Writer) error
WritePerfettoJSON writes s as a Chrome trace-event JSON document, which ui.perfetto.dev and chrome://tracing open. One cycle is written as one microsecond. The document holds process and thread names, an "X" event per span, an "s" and "f" event pair per flow, and a "C" counter track of allocated tensor-memory columns.
type TimelineWarp ¶
type TimelineWarp struct {
ID int
Role PipeKind // PipeProducerWarp or PipeConsumerWarp
Ops []TimelineOp
}
A TimelineWarp is one warp's instruction stream.