Documentation
¶
Overview ¶
Package graph builds, captures, instantiates, and replays CUDA execution graphs, plans SM-partitioned green contexts, and validates cooperative thread and warpgroup execution groups.
Execution Graphs ¶
Construct a Graph explicitly with New or by stream capture with Capture and CaptureWithMode, instantiate an executable Exec with Graph.Instantiate or Graph.InstantiateWithOptions, and replay it with Exec.Launch. Release Graph, Exec, and Node handles with their idempotent Graph.Close, Exec.Close, and Node.Close methods.
Green Contexts ¶
ComputePlan carves a device's SMs across Role specs according to hardware split Granularity, and Open or OpenDomains materializes green contexts and non-blocking streams in Partitions.
Execution Groups ¶
NewGroup and NewCollective model thread, warp, warpgroup, CTA, and cluster participation contracts and launch geometry requirements.
This package is outside the compatibility promise of github.com/tmc/lib/nvidia.
Index ¶
- Constants
- Variables
- func BuildBatchBuckets(policy BucketPolicy) ([]int, error)
- func CaptureTo(s *cuda.Stream, g *Graph, mode driver.StreamCaptureMode, fn func()) error
- func CheckGreenIsolation(trace *cudaprofile.Trace, rules map[uint16]GreenIsolationRule) (*SMIsolationReport, []SMIsolationViolation, error)
- func CheckGroupSets(sets [][]int, n int) error
- func CheckLaunchGeometry(grid, block driver.Dim3) error
- func ClassGroups(groupSMs [][]int, classes [][]int) ([][]int, error)
- func DomainGroupParams(specs []DomainSpec) ([]driver.CuDevSmResourceGroupParams, error)
- func DomainSMs(dev driver.Device, specs []DomainSpec) ([]int, error)
- func GroupSMs(dev driver.Device, g Granularity) ([][]int, error)
- func ProgrammaticEdgeData() driver.GraphEdgeData
- func RecordExternalEvent(stream driver.Stream, ev driver.Event) error
- func ReduceSumReference(values []float32) (float32, error)
- func SetEventRecordNodeEvent(exec driver.GraphExec, node EventRecordNode, ev driver.Event) error
- func Supported() error
- func SupportedDomains() error
- func ValidateLaunch(req LaunchRequirements, group Group) error
- func VerifyPlan(p Plan) error
- type BucketManager
- type BucketPadding
- type BucketPolicy
- type BucketRunner
- func (r *BucketRunner[T]) Buckets() []int
- func (r *BucketRunner[T]) Lookup(actualBsz int) (handle T, pad BucketPadding, err error)
- func (r *BucketRunner[T]) Register(bucketBsz int, handle T) error
- func (r *BucketRunner[T]) Select(totalQ int) (handle T, pad BucketPadding, err error)
- func (r *BucketRunner[T]) WarmupOrder() []int
- type Collective
- type CollectiveKind
- type ConditionalHandle
- type ConditionalType
- type DeviceKernelNodeUpdate
- type DeviceNode
- type DomainSpec
- type Eligibility
- type EventRecordNode
- type Exec
- func (e *Exec) ApplyKernelNodeUpdate(node *Node, update KernelNodeUpdate) error
- func (e *Exec) Close() error
- func (e *Exec) HotSwapNode(node *Node, fn driver.Function, grid driver.Dim3, args ...any) error
- func (e *Exec) KernelOrder() (driver.GraphExec, []string, error)
- func (e *Exec) Launch(s *cuda.Stream) error
- func (e *Exec) SetKernelNodeGrid(node *Node, grid driver.Dim3) error
- func (e *Exec) SetKernelNodeLaunch(node *Node, grid, block driver.Dim3, args ...any) error
- func (e *Exec) SetKernelNodeParams(node *Node, params *driver.KernelNodeParams) error
- func (e *Exec) Update(g *Graph) error
- func (e *Exec) UpdateKernelNode(node *Node, grid driver.Dim3, args ...any) error
- type Fixture
- type Granularity
- type Graph
- func (g *Graph) AddConditional(typ ConditionalType, h ConditionalHandle, size int, dependencies ...*Node) (*Node, []*Graph, error)
- func (g *Graph) AddDependencies(from, to []*Node, edgeData ...driver.GraphEdgeData) error
- func (g *Graph) AddDependency(from, to *Node) error
- func (g *Graph) AddDeviceUpdatableKernelNode(params *driver.KernelNodeParams, dependencies ...*Node) (*Node, error)
- func (g *Graph) AddEmptyNode(dependencies ...*Node) (*Node, error)
- func (g *Graph) AddKernelNode(params *driver.KernelNodeParams, dependencies ...*Node) (*Node, error)
- func (g *Graph) AddLaunch(desc cuda.Description, args []any, dependencies ...*Node) (*Node, error)
- func (g *Graph) AddLauncher(l *cuda.Launcher, args []any, dependencies ...*Node) (*Node, error)
- func (g *Graph) AddProgrammaticDependency(from, to *Node) error
- func (g *Graph) AddWhile(h ConditionalHandle, dependencies ...*Node) (*Node, *Graph, error)
- func (g *Graph) Close() error
- func (g *Graph) ConditionalHandle(defaultValue uint32, assignDefault bool) (ConditionalHandle, error)
- func (g *Graph) Eligibility() (Eligibility, error)
- func (g *Graph) Instantiate() (*Exec, error)
- func (g *Graph) InstantiateWithOptions(options InstantiateOptions) (*Exec, error)
- func (g *Graph) Nodes() ([]*Node, error)
- func (g *Graph) ProgrammaticEdges() (int, error)
- func (g *Graph) Raw() driver.Graph
- type GreenIsolationRule
- type Group
- type GroupKind
- type InstantiateOptions
- type Issuer
- type KernelNodeField
- type KernelNodeUpdate
- func NewEnabledUpdate(node DeviceNode, enabled bool) KernelNodeUpdate
- func NewGridDimUpdate(node DeviceNode, grid driver.Dim3) KernelNodeUpdate
- func NewParamUpdate(node DeviceNode, offset uintptr, val unsafe.Pointer, size uintptr) KernelNodeUpdate
- func NewParamUpdateForFunc(node DeviceNode, fn driver.Function, paramIndex uint, val unsafe.Pointer) (KernelNodeUpdate, error)
- type LaunchGeometryError
- type LaunchRequirements
- type Mask
- type MemoryScope
- type Node
- func (n *Node) Close() error
- func (n *Node) DeviceNode() (DeviceNode, error)
- func (n *Node) Graph() *Graph
- func (n *Node) IsDeviceUpdatable() (bool, error)
- func (n *Node) Params() (driver.KernelNodeParams, error)
- func (n *Node) Raw() driver.GraphNode
- func (n *Node) SetDeviceUpdatable(enable bool) error
- func (n *Node) SetGrid(grid driver.Dim3) error
- func (n *Node) SetParams(params *driver.KernelNodeParams) error
- type Partition
- type Partitions
- type PingPongTimer
- func (t *PingPongTimer) ActiveBank() int
- func (t *PingPongTimer) BindBankEvents(bank int, events []driver.Event) error
- func (t *PingPongTimer) HistoryDurationsMS() [][]float64
- func (t *PingPongTimer) LastDurationsMS() []float64
- func (t *PingPongTimer) PrepareReplay(exec driver.GraphExec, nodes []EventRecordNode) (bank int, err error)
- func (t *PingPongTimer) RecordSimulatedReplay(durationsMS []float64) error
- func (t *PingPongTimer) ReplayCount() int
- type PingPongTimerConfig
- type Plan
- type Role
- type SMIsolationReport
- type SMIsolationViolation
- type SMProbe
- func (p *SMProbe) Block() int
- func (p *SMProbe) Close() error
- func (p *SMProbe) Function() driver.Function
- func (p *SMProbe) Grid() int
- func (p *SMProbe) Launch(s driver.Stream) error
- func (p *SMProbe) Out() driver.DevicePtr
- func (p *SMProbe) Read() ([]uint32, error)
- func (p *SMProbe) Reset() error
- func (p *SMProbe) SpinNs() uint64
- type SMSpread
- type Spec
- type TMEMCollective
- type TMEMPeers
Examples ¶
- BucketRunner
- CaptureWithMode
- CheckGreenIsolation
- CheckGroupSets
- CheckLaunchGeometry
- CheckSMSpread
- CheckSMSpreadIn
- ClassGroups
- Collective.ValidateRanks
- Collective.ValidateUniform
- ComputePlan
- Exec.KernelOrder
- Fixture.ValidateCapability
- Fixture.ValidateLaunch
- GenerateReductionFixture
- GenerateReductionFixtureWithCapability
- Graph.Eligibility
- Graph.InstantiateWithOptions
- Graph.ProgrammaticEdges
- Group
- Group.Dims
- Group.Kind
- Group.Rank
- Group.Size
- InstantiateOptions
- NewCollective
- NewGroup
- NewTMEMCollective
- PingPongTimer
- ReduceSumReference
- TMEMCollective.Peers
- TMEMCollective.ValidateLaunch
- TMEMCollective.ValidateParticipation
- VerifyGreenContextSMIsolation
- WarpGroupForCTA
Constants ¶
const ( // ConditionalIf runs its first body once if the condition is not // zero, and its second, if it has two, otherwise. ConditionalIf = driver.GraphCondTypeIf // ConditionalWhile runs its one body while the condition is not // zero, testing it when the node starts and after each run of the // body. ConditionalWhile = driver.GraphCondTypeWhile // ConditionalSwitch runs body n once, n being the condition, or none // if n is not less than the number of bodies. ConditionalSwitch = driver.GraphCondTypeSwitch )
The kinds of conditional nodes.
const MaxSMs = 256
MaxSMs is the largest SM count a Mask can describe.
const MinDriverVersion = 12040
MinDriverVersion is the first CUDA driver version, 12.4, with green contexts, in the encoding of cuDriverGetVersion.
const SMProbePTX = `` /* 650-byte string literal not displayed */
SMProbePTX is the probe kernel smid_probe(u32 *out, u64 spin_ns). Thread 0 of each block spins for spin_ns nanoseconds of %globaltimer, so that the blocks of one launch are resident together and the block scheduler has to spread them, then writes the block's %smid to out[blockIdx.x].
It is PTX, not CUDA C, so that the check needs no compiler: the driver JIT-compiles it for any device from sm_70 on.
Variables ¶
var ( // ErrCapabilityAbsent means a required record or attribute is missing. ErrCapabilityAbsent = errors.New("capability is absent") // ErrCapabilityUnverified means a required limit was not directly probed. ErrCapabilityUnverified = errors.New("capability is not directly probed") // ErrCapabilityUnsupported means probed limits cannot admit the fixture. ErrCapabilityUnsupported = errors.New("capability does not support the fixture") // ErrCapabilityInvalid means a record is malformed or names another // device architecture. ErrCapabilityInvalid = errors.New("capability record is invalid") )
var ErrInfeasible = errors.New("cudagreen: minimum partitions exceed device")
ErrInfeasible reports that a plan's minimums do not fit on the device.
var ErrPartitionEscaped = errors.New("cudagreen: work ran outside its partition")
ErrPartitionEscaped reports work that ran on more SMs than its partition holds: the green context was accepted, and the launch ignored it.
var ErrUnsupported = errors.New("cudagreen: driver has no green contexts")
ErrUnsupported reports a driver without green contexts.
Functions ¶
func BuildBatchBuckets ¶
func BuildBatchBuckets(policy BucketPolicy) ([]int, error)
BuildBatchBuckets generates a sorted, deduplicated slice of positive batch-size buckets according to policy.
func CaptureTo ¶
CaptureTo records the work fn queues on s into g, an existing graph such as a conditional node's body. The first captured nodes are roots: they do not depend on nodes g held before. Kernels launched with programmatic stream serialization record programmatic edges, as in Capture. It needs cuStreamBeginCaptureToGraph (CUDA 12.3).
Begin, fn and end run on one OS thread, in mode; the caller handles the errors of what fn queues, as with Capture.
func CheckGreenIsolation ¶
func CheckGreenIsolation(trace *cudaprofile.Trace, rules map[uint16]GreenIsolationRule) (*SMIsolationReport, []SMIsolationViolation, error)
CheckGreenIsolation verifies that every event in trace maps to a rule in rules and executed on an SM inside that rule's allowed SM set (the union of AllowedSMs and AllowedMask). It fails closed by returning an error on empty or unmapped inputs and reporting an SMIsolationViolation for every event whose hardware %smid is outside its partition's allowed SMs.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/graph"
cudaprofile "github.com/tmc/lib/nvidia/x/obs/iket/ring"
)
func main() {
trace := &cudaprofile.Trace{
Events: []cudaprofile.Event{
{Start: 1000, End: 1400, SM: 0, Block: 0, Warp: 0, ID: 1},
{Start: 1010, End: 1900, SM: 8, Block: 0, Warp: 0, ID: 2},
},
}
rules := map[uint16]graph.GreenIsolationRule{
1: {Partition: "decode", Region: "decode_step", AllowedMask: graph.Range(0, 8)},
2: {Partition: "prefill", Region: "prefill_mma", AllowedMask: graph.Range(8, 8)},
}
rep, viols, err := graph.CheckGreenIsolation(trace, rules)
if err != nil {
panic(err)
}
fmt.Printf("isolated=%v violations=%d\n", rep.StrictlyIsolated, len(viols))
}
Output: isolated=true violations=0
func CheckGroupSets ¶
CheckGroupSets reports whether sets can be opened from n split groups: each set non-empty, every index in [0, n), and no index in two sets or twice in one.
Example ¶
fmt.Println(CheckGroupSets([][]int{{0, 2}, {1, 3}}, 4))
fmt.Println(CheckGroupSets([][]int{{0, 2}, {2}}, 4))
Output: <nil> cudagreen: group 2 is in sets 0 and 1
func CheckLaunchGeometry ¶
CheckLaunchGeometry reports whether grid and block are within CUDA's architectural limits: every extent nonzero, grid at most (2³¹-1)×65535×65535, block at most 1024×1024×64 and 1024 threads in total. It returns a *LaunchGeometryError otherwise. Limits that depend on the device or the kernel are left to CUDA.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
fmt.Println(graph.CheckLaunchGeometry(driver.Dims(8, 1, 1), driver.Dims(256, 1, 1)))
fmt.Println(graph.CheckLaunchGeometry(driver.Dims(8, 1, 1), driver.Dims(32, 32, 2)))
}
Output: <nil> cudagraph: invalid launch geometry grid 8x1x1 block 32x32x2: block exceeds 1024 threads
func ClassGroups ¶
ClassGroups returns, for each class, the indices of the groups whose SMs all lie in it, in group order. groupSMs[i] holds the physical SMs of split group i, as GroupSMs reports them; a class is a set of physical SMs, such as the SMs that share an instruction cache, which the caller measured. ClassGroups fails if a group has no SMs, holds SMs of more than one class or of none, or if a class gets no group: then no union of groups is that class.
Example ¶
// The SMs of each split group, as GroupSMs reports them, and the
// measured classes of SMs that share an instruction cache.
groupSMs := [][]int{{0, 1}, {2, 3}, {4, 5}, {6, 7}}
classes := [][]int{{0, 1, 4, 5}, {2, 3, 6, 7}}
sets, err := ClassGroups(groupSMs, classes)
if err != nil {
panic(err)
}
fmt.Println(sets)
Output: [[0 2] [1 3]]
func DomainGroupParams ¶
func DomainGroupParams(specs []DomainSpec) ([]driver.CuDevSmResourceGroupParams, error)
DomainGroupParams returns the cuDevSmResourceSplit group parameters for specs, one entry per spec, each asking for SMs of its domain with DevSmResourceGroupLocalityDomainId. It reports an error for a spec the driver would refuse: a negative domain, an odd or single SM count, or a count that is not a multiple of Coscheduled without Backfill.
func DomainSMs ¶
func DomainSMs(dev driver.Device, specs []DomainSpec) ([]int, error)
DomainSMs asks the driver, without creating anything, how many SMs each of specs would get: cuDevSmResourceSplit's discovery mode, which fills in each count. A spec's SMs of 0 asks for every SM the driver will give it after the specs before it. The caller must have called driver.Init.
func GroupSMs ¶
func GroupSMs(dev driver.Device, g Granularity) ([][]int, error)
GroupSMs returns the physical SMs of each group the driver splits dev's SMs into, for groups of g's granule with g's flags: for each group, the SMs SMProbePTX ran on in a green context of that group alone, in ascending order. The driver does not report them.
func ProgrammaticEdgeData ¶
func ProgrammaticEdgeData() driver.GraphEdgeData
ProgrammaticEdgeData returns a driver.GraphEdgeData configured for a Programmatic Dependent Launch (PDL) dependency edge.
func RecordExternalEvent ¶
RecordExternalEvent records ev on stream with driver.EventRecordExternal (CU_EVENT_RECORD_EXTERNAL = 0x1) so stream capture records a driver.GraphNodeTypeEventRecord node inside the captured graph.
func ReduceSumReference ¶
ReduceSumReference sums in input order. The GPU uses a different addition tree; arbitrary floating-point inputs require an explicit tolerance policy.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
values := make([]float32, 32)
for i := range values {
values[i] = 1
}
sum, _ := graph.ReduceSumReference(values)
fmt.Println(sum)
}
Output: 32
func SetEventRecordNodeEvent ¶
SetEventRecordNodeEvent updates the event recorded by node in an instantiated executable graph without recapturing or reinstantiating the graph.
func Supported ¶
func Supported() error
Supported reports whether the loaded driver has green contexts. The caller must have called driver.Init.
func SupportedDomains ¶
func SupportedDomains() error
SupportedDomains reports whether the loaded driver can split SMs by locality domain: whether it has green contexts and cuDevSmResourceSplit. It does not report whether the device has more than one domain; see cudadevicetable.ReadLocalityDomains. The caller must have called driver.Init.
func ValidateLaunch ¶
func ValidateLaunch(req LaunchRequirements, group Group) error
ValidateLaunch checks membership against a launch description. It does not establish device capability, residency, synchronization, or forward progress.
func VerifyPlan ¶
VerifyPlan checks that no two partitions share an SM, that each mask holds exactly the partition's SM count and lies on the device, that each count meets its minimum, the granule and its cluster size, that the partitions fit in the groups the device makes, and that partitions and unassigned SMs account for the whole device.
Types ¶
type BucketManager ¶
type BucketManager struct {
// contains filtered or unexported fields
}
BucketManager manages a discrete lattice of instantiated graphs for dynamic tensor dimensions, avoiding expensive runtime recaptures and topology change errors.
func NewBucketManager ¶
func NewBucketManager(buckets []int, builder func(s *cuda.Stream, dim int) (*Graph, error)) *BucketManager
NewBucketManager creates a new manager caching instantiated graphs across discrete dimension buckets.
func (*BucketManager) Close ¶
func (bm *BucketManager) Close() error
Close destroys all cached instantiated graphs.
type BucketPadding ¶
BucketPadding describes the selected CUDA Graph bucket and required dummy token/sequence padding for an actual batch size.
func ResolveBucket ¶
func ResolveBucket(buckets []int, actualBsz int) (BucketPadding, error)
ResolveBucket finds the smallest bucket in buckets that is >= actualBsz and returns the corresponding BucketPadding. It returns an error wrapping cuda.ErrUnsupported if buckets is empty, actualBsz <= 0, or actualBsz exceeds the largest bucket.
type BucketPolicy ¶
type BucketPolicy struct {
MaxBsz int
SmallStep int
MedStep int
LargeStep int
ExplicitBuckets []int
}
BucketPolicy configures piecewise CUDA Graph batch-size bucket generation.
When ExplicitBuckets is empty, BuildBatchBuckets generates buckets up to MaxBsz using power-of-two warmup sizes (1, 2) followed by three piecewise step regimes:
- SmallStep (default 4) up to 16: [4, 8, 12, 16]
- MedStep (default 8) from 16 up to 64: [24, 32, 40, 48, 56, 64]
- LargeStep (default 16) above 64: [80, 96, ...]
MaxBsz is always included when MaxBsz > 0.
type BucketRunner ¶
type BucketRunner[T any] struct { // contains filtered or unexported fields }
BucketRunner maps piecewise batch-size buckets to captured graph handles of type T and provides descending warmup ordering and padded bucket lookup.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
runner, err := graph.NewBucketRunnerFromPolicy[string](graph.BucketPolicy{
MaxBsz: 24,
})
if err != nil {
fmt.Println("error:", err)
return
}
for _, b := range runner.WarmupOrder() {
if err := runner.Register(b, fmt.Sprintf("exec_%d", b)); err != nil {
fmt.Println("error:", err)
return
}
}
handle, pad, err := runner.Lookup(9)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("warmup=%v handle=%s bucket=%d pad=%d\n", runner.WarmupOrder(), handle, pad.BucketBsz, pad.PadCount)
}
Output: warmup=[24 16 12 8 4 2 1] handle=exec_12 bucket=12 pad=3
func NewBucketRunner ¶
func NewBucketRunner[T any](buckets []int) (*BucketRunner[T], error)
NewBucketRunner constructs a BucketRunner over a non-empty list of positive bucket sizes. The input slice is copied, sorted, and deduplicated.
func NewBucketRunnerFromPolicy ¶
func NewBucketRunnerFromPolicy[T any](policy BucketPolicy) (*BucketRunner[T], error)
NewBucketRunnerFromPolicy constructs a BucketRunner using BuildBatchBuckets.
func (*BucketRunner[T]) Buckets ¶
func (r *BucketRunner[T]) Buckets() []int
Buckets returns the configured bucket sizes in ascending order.
func (*BucketRunner[T]) Lookup ¶
func (r *BucketRunner[T]) Lookup(actualBsz int) (handle T, pad BucketPadding, err error)
Lookup resolves actualBsz to the smallest configured bucket >= actualBsz and returns its registered handle and BucketPadding.
func (*BucketRunner[T]) Register ¶
func (r *BucketRunner[T]) Register(bucketBsz int, handle T) error
Register binds handle to bucketBsz. It returns an error wrapping cuda.ErrUnsupported if bucketBsz is not a configured bucket in r.
func (*BucketRunner[T]) Select ¶
func (r *BucketRunner[T]) Select(totalQ int) (handle T, pad BucketPadding, err error)
Select is an alias for BucketRunner.Lookup that resolves totalQ to the smallest configured bucket >= totalQ.
func (*BucketRunner[T]) WarmupOrder ¶
func (r *BucketRunner[T]) WarmupOrder() []int
WarmupOrder returns the configured bucket sizes in descending order (from MaxBsz down to the smallest bucket), matching DeepInfer's warmup and graph capture order so the shared allocator high-water mark is established first.
type Collective ¶
type Collective struct {
Kind CollectiveKind
Group Group
Scope MemoryScope
Uniform bool
}
Collective describes participants, required uniformity and memory scope.
func NewCollective ¶
func NewCollective(kind CollectiveKind, group Group, scope MemoryScope) (Collective, error)
NewCollective describes warp or CTA rendezvous, warp reduction or broadcast, or warpgroup uniform issue. Transaction barriers are not modeled here.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
warp, _ := graph.NewGroup(graph.Warp, driver.Dim3{X: 32, Y: 1, Z: 1})
c, _ := graph.NewCollective(graph.ReduceSum, warp, graph.MemoryThread)
ranks := make([]uint64, 32)
for i := range ranks {
ranks[i] = uint64(i)
}
fmt.Println(c.ValidateRanks(ranks), c.ValidateParticipation(32))
}
Output: <nil> <nil>
func (Collective) ValidateParticipation ¶
func (c Collective) ValidateParticipation(participants uint64) error
ValidateParticipation checks the exact participant count, catching dropped participants before a generated collective is launched.
func (Collective) ValidateRanks ¶
func (c Collective) ValidateRanks(ranks []uint64) error
ValidateRanks checks that every participant rank appears exactly once. A count alone cannot detect a duplicate lane replacing a missing lane.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
warp, _ := graph.NewGroup(graph.Warp, driver.Dim3{X: 32, Y: 1, Z: 1})
c, _ := graph.NewCollective(graph.Broadcast, warp, graph.MemoryCTA)
ranks := make([]uint64, 32)
for i := range ranks {
ranks[i] = uint64(i)
}
fmt.Println(c.ValidateRanks(ranks))
}
Output: <nil>
func (Collective) ValidateUniform ¶
func (c Collective) ValidateUniform(ranks []uint64, values []uint32) error
ValidateUniform checks one operation argument per participant. All values must agree. Instruction-specific value ranges remain the owner's contract.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
warp, _ := graph.NewGroup(graph.Warp, driver.Dim3{X: 32, Y: 1, Z: 1})
c, _ := graph.NewCollective(graph.ReduceSum, warp, graph.MemoryThread)
ranks, values := make([]uint64, 32), make([]uint32, 32)
for i := range ranks {
ranks[i] = uint64(i)
values[i] = 7
}
fmt.Println(c.ValidateUniform(ranks, values))
}
Output: <nil>
type CollectiveKind ¶
type CollectiveKind uint8
CollectiveKind identifies an operation-specific synchronization contract.
const ( Rendezvous CollectiveKind = iota + 1 ReduceSum Broadcast // WarpgroupUniformity checks uniform issue; it admits no instruction. WarpgroupUniformity )
type ConditionalHandle ¶
type ConditionalHandle uint64
A ConditionalHandle names the condition value of a conditional node. A kernel in the graph sets it with the device runtime's cudaGraphSetConditional, passing the handle as a kernel argument of type unsigned long long (cudaGraphConditionalHandle):
extern "C" __global__ void step(unsigned long long h, int* n, int limit) {
if (threadIdx.x == 0 && blockIdx.x == 0)
cudaGraphSetConditional(h, ++*n < limit);
}
Only one thread of the graph may set a handle at a time: concurrent calls are undefined. The handle belongs to the graph it was created in and to the context current at creation, which must be the kernels'.
type ConditionalType ¶
type ConditionalType = driver.GraphConditionalNodeType
A ConditionalType is the kind of a conditional node.
type DeviceKernelNodeUpdate ¶
type DeviceKernelNodeUpdate struct {
Field uint32
Node uint64
UpdateData [24]byte
// contains filtered or unexported fields
}
DeviceKernelNodeUpdate matches the exact 40-byte C-ABI layout of cudaGraphKernelNodeUpdate in the CUDA Runtime. It can be copied directly to GPU device memory for consumption by kernels calling cudaGraphKernelNodeUpdatesApply.
func EncodeDeviceUpdates ¶
func EncodeDeviceUpdates(updates []KernelNodeUpdate) []DeviceKernelNodeUpdate
EncodeDeviceUpdates converts a slice of KernelNodeUpdate into a slice of DeviceKernelNodeUpdate.
func (DeviceKernelNodeUpdate) Bytes ¶
func (d DeviceKernelNodeUpdate) Bytes() []byte
Bytes returns the raw 40-byte slice of the device update.
type DeviceNode ¶
type DeviceNode uintptr
DeviceNode represents a CUDA device node handle (cudaGraphDeviceNode_t) used for device-side graph updates.
func (DeviceNode) String ¶
func (d DeviceNode) String() string
String returns the hexadecimal representation of the device node handle.
func (DeviceNode) Uint64 ¶
func (d DeviceNode) Uint64() uint64
Uint64 returns the handle as a uint64.
type DomainSpec ¶
type DomainSpec struct {
// Domain is the locality domain ID, from 0 to the device's
// DevAttrLocalityDomainCount less one.
Domain int
// SMs is the partition's SM count: 0, to take as many of the domain's
// SMs as the driver gives, or an even number of at least 2.
SMs int
// Coscheduled is the number of SMs the driver keeps together so that
// a cluster of that many CTAs fits; 0 is the device's default (8 on
// compute capability 9.0 and later). A nonzero SMs must be a multiple
// of it unless Backfill is set.
Coscheduled int
// Supplemental lets the partition take the domain's supplemental SMs,
// those beyond DevAttrLocalityDomainMultiprocessorCount.
Supplemental bool
// Backfill lets the driver make up a shortfall with SMs in no domain
// and then SMs of other domains, so the partition reaches SMs. A
// backfilled partition may not be local to Domain.
Backfill bool
}
A DomainSpec asks for one partition of the SMs of a CUDA locality domain. See OpenDomains.
type Eligibility ¶
type Eligibility struct {
Captured bool // True if the graph has been successfully captured and can be instantiated
Reasons []string // Diagnostic reasons explaining any ineligibility or replay caveats
Nodes int // Total number of nodes in the graph
Kernels int // Number of kernel execution nodes
Updates []string // Descriptions of nodes requiring or supporting dynamic parameter updates
}
Eligibility describes the structural validation, node composition, and replay suitability of a CUDA execution graph.
type EventRecordNode ¶
type EventRecordNode struct {
// contains filtered or unexported fields
}
EventRecordNode wraps a CUDA graph node of type driver.GraphNodeTypeEventRecord.
func AddEventRecordNode ¶
func AddEventRecordNode(g driver.Graph, deps []driver.GraphNode, ev driver.Event) (EventRecordNode, error)
AddEventRecordNode adds an event-record node to g that records ev after deps complete.
func EventRecordNodes ¶
func EventRecordNodes(g driver.Graph) ([]EventRecordNode, error)
EventRecordNodes enumerates all nodes in g and returns those of type driver.GraphNodeTypeEventRecord in the order reported by the graph.
func NewEventRecordNode ¶
func NewEventRecordNode(node driver.GraphNode) EventRecordNode
NewEventRecordNode wraps raw as an EventRecordNode.
func (EventRecordNode) Event ¶
func (n EventRecordNode) Event() (driver.Event, error)
Event queries the driver.Event currently bound to this event-record node.
func (EventRecordNode) Node ¶
func (n EventRecordNode) Node() driver.GraphNode
Node returns the underlying driver.GraphNode handle.
func (EventRecordNode) Raw ¶
func (n EventRecordNode) Raw() driver.EventRecordNode
Raw returns the underlying driver.EventRecordNode handle.
func (EventRecordNode) SetEvent ¶
func (n EventRecordNode) SetEvent(ev driver.Event) error
SetEvent updates the driver.Event bound to this uninstantiated event-record node.
type Exec ¶
type Exec struct {
// contains filtered or unexported fields
}
Exec represents an instantiated, executable CUDA graph.
func (*Exec) ApplyKernelNodeUpdate ¶
func (e *Exec) ApplyKernelNodeUpdate(node *Node, update KernelNodeUpdate) error
ApplyKernelNodeUpdate applies a host update. Parameter offsets are CUDA's packed-device parameter offsets, not offsets into the void** pointer array. Only owned, known argument sizes are writable. The current state remains unchanged on native rejection. Caller must provide readable Value bytes, serialize the update and ensure there are no launches/device updates in flight.
func (*Exec) HotSwapNode ¶
HotSwapNode replaces the function while preserving current arguments when none are supplied. The caller owns the new function's module lifetime; changing a raw handle cannot acquire a module reference. The retained arguments must match the new function's queried count and sizes. CUDA validates function context and graph capability restrictions. See UpdateKernelNode for the serialized, no-inflight update requirement.
func (*Exec) KernelOrder ¶
KernelOrder returns the executable handle and a copy of its retained kernel symbols in dependency order. RetainKernelOrder must have been selected when instantiating. Update and Destroy invalidate this evidence. Source graph destruction does not invalidate the snapshot.
The caller must not mutate the executable through raw driver bindings or concurrently with profiling. This evidence describes a native graph topology; associating it with profiler ordinals still requires a qualified collector.
Example ¶
var exec *Exec _, _, err := exec.KernelOrder() fmt.Println(err)
Output: cudagraph: executable graph is closed
func (*Exec) SetKernelNodeGrid ¶
SetKernelNodeGrid preserves the Exec's current function and arguments. A grid outside CUDA's architectural limits is refused with a *LaunchGeometryError before any native call. Nodes built from raw argument arrays or by stream capture require SetKernelNodeParams with a fresh complete set: the Exec does not own their argument storage.
func (*Exec) SetKernelNodeLaunch ¶
SetKernelNodeLaunch sets the grid and block dimensions of node in future launches and, when args are given, replaces its arguments, preserving the Exec's current function and shared memory size. A zero Dim3 leaves that dimension unchanged. Grid, block and arguments are committed by one native call: if CUDA rejects it, for example because the block is too large for the kernel's register or shared memory use, the Exec keeps its previous grid, block and arguments.
Without args the owned argument storage is kept, so the node keeps its identity and later grid, argument and launch updates continue to use it. Nodes built from raw argument arrays or by stream capture are refused without args, as for SetKernelNodeGrid. Dimensions outside CUDA's architectural limits are refused with a *LaunchGeometryError before any native call. See UpdateKernelNode for argument handling and the serialized, no-inflight update requirement.
func (*Exec) SetKernelNodeParams ¶
func (e *Exec) SetKernelNodeParams(node *Node, params *driver.KernelNodeParams) error
SetKernelNodeParams updates future launches, without modifying the original graph node. Raw argument arrays remain caller-owned: retain them until the next successful replacement or destruction. Calls on a graph or Exec must be serialized. Before replacing retained storage, ensure no launches are in flight and no device-side updates are concurrent. Modules and device memory must remain valid independently of the host argument storage.
func (*Exec) Update ¶
Update updates this executable graph from a topologically identical graph. CUDA checks the graph topology, but does not check that kernel nodes use the same kernel function, parameters, or shared-memory size. Callers must ensure those properties themselves.
A successful update transfers argument ownership: the Exec then holds g's argument storage and modules and releases the previous graph's, so g may be destroyed while this Exec remains valid. A driver-rejected update changes nothing, including ownership. A context restoration error after native success still commits ownership. Per-node convenience updates are invalidated because this wrapper cannot establish CUDA's topological matching; SetKernelNodeParams still accepts complete parameters for a node of the original graph. Callers must ensure no launch is in flight before updating: this wrapper releases previous argument and module owners after a successful update.
func (*Exec) UpdateKernelNode ¶
UpdateKernelNode replaces arguments when provided and otherwise preserves the current executable parameters. A zero grid leaves its dimensions alone. Superseded argument storage is released, so callers must serialize updates and ensure no launches or device-side updates are in flight.
type Fixture ¶
type Fixture struct {
Source string
Group Group
Collective Collective
Target string
Launch LaunchRequirements
}
Fixture is a generated warp reduction kernel and its launch contract.
func GenerateReductionFixture ¶
GenerateReductionFixture emits a CUDA C++ warp reduction with full-mask participation. It is a source fixture; compilation and execution require a separately authorized CUDA toolchain and device.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
warp, _ := graph.NewGroup(graph.Warp, driver.Dim3{X: 32, Y: 1, Z: 1})
f, _ := graph.GenerateReductionFixture(warp)
fmt.Println(f.Collective.Group.Size(), len(f.Source) > 0)
}
Output: 32 true
func GenerateReductionFixtureForTarget ¶
GenerateReductionFixtureForTarget emits the fixture for an explicitly admitted SIMT target. The fixture uses only ordinary warp operations; its admission does not assert target-specific geometry or instruction support.
func GenerateReductionFixtureWithCapability ¶
func GenerateReductionFixtureWithCapability(group Group, target string, record devicetable.Architecture) (Fixture, error)
GenerateReductionFixtureWithCapability generates the real reduction fixture and checks its declared launch against record before returning it. Refusal returns an empty Fixture. The caller must supply device facts; a target's assembler feature record cannot supply device limits.
This checks the recorded warp size and block-thread limit, not the current device, toolchain, compiled kernel resources, or native execution. The older GenerateReductionFixture functions generate source without this admission.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda/graph"
"github.com/tmc/lib/nvidia/x/isa/devicetable"
)
func main() {
// Recorded launch limits, not a native execution result.
warp, _ := graph.NewGroup(graph.Warp, driver.Dim3{X: 32, Y: 1, Z: 1})
record, _ := devicetable.Lookup("sm_121")
f, err := graph.GenerateReductionFixtureWithCapability(warp, "sm_121a", record)
fmt.Println(f.Target, f.Launch.Block, err)
}
Output: sm_121a 32x1x1 <nil>
func (Fixture) ValidateCapability ¶
func (f Fixture) ValidateCapability(record devicetable.Architecture) error
ValidateCapability checks this fixture's launch geometry and the supplied device record. Required limits must be positive, directly probed driver attributes with valid provenance. Missing and unverified limits do not imply unsupported hardware; use errors.Is with the ErrCapability errors to distinguish them.
Architecture suffixes select instruction sets, not different device limits: sm_121a uses a sm_121 Architecture, while the exact fixture target must still be admitted by ValidateLaunch. This does not validate arbitrary source or prove instruction support, current-device availability, or native execution. The record is read only and must not be concurrently mutated by its caller.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda/graph"
"github.com/tmc/lib/nvidia/x/isa/devicetable"
)
func main() {
warp, _ := graph.NewGroup(graph.Warp, driver.Dim3{X: 32, Y: 1, Z: 1})
f, _ := graph.GenerateReductionFixtureForTarget(warp, "sm_121a")
record, _ := devicetable.Lookup("sm_121a") // Same device limits as sm_121.
fmt.Println(f.ValidateCapability(record))
err := f.ValidateCapability(devicetable.Architecture{})
fmt.Println(errors.Is(err, graph.ErrCapabilityAbsent), errors.Is(err, graph.ErrCapabilityUnsupported))
}
Output: <nil> true false
func (Fixture) ValidateLaunch ¶
ValidateLaunch checks the exact single-warp launch required by this fixture.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
warp, _ := graph.NewGroup(graph.Warp, driver.Dim3{X: 32, Y: 1, Z: 1})
f, _ := graph.GenerateReductionFixture(warp)
fmt.Println(f.Target, f.ValidateLaunch())
}
Output: sm_90 <nil>
type Granularity ¶
A Granularity is how a device's SMs can be split. The driver reports Min and Alignment in the minSmPartitionSize and smCoscheduledAlignment fields of an SM resource. A partition is a whole number of groups of Granularity.Granule SMs.
The driver splits along the GPU's hardware hierarchy and makes only groups that are alike, so it may make fewer groups than the SM count divided by the granule: on GB10 (48 SMs, granule 8) it makes 4. Groups, when nonzero, is that limit, as DeviceSplit discovers it; the SMs left over are not assigned.
IgnoreCoscheduling asks the driver to split with CU_DEV_SM_RESOURCE_SPLIT_IGNORE_SM_COSCHEDULING, which treats each SM independently of the hierarchy. Partitions then cover more of the device, at the cost of the guarantees that large thread-block clusters need: on GB10 the driver makes 6 groups of 8 instead of 4. Kernels that launch clusters should not run in partitions split this way.
func DefaultGranularity ¶
func DefaultGranularity(arch string) (Granularity, error)
DefaultGranularity returns the split quantum the CUDA documentation gives for arch's compute capability (sm_70 through sm_8x: 2 SMs, sm_90 and later: 8 SMs) without SM coscheduling disabled. A live device's own report, used by Open, takes precedence.
func DeviceGranularity ¶
func DeviceGranularity(dev driver.Device) (int, Granularity, error)
DeviceGranularity returns dev's SM count and split granularity as the driver reports them. A driver that reports no minimum partition size (before CUDA 13) yields the zero Granularity; use DefaultGranularity.
func DeviceSplit ¶
func DeviceSplit(dev driver.Device, g Granularity) (Granularity, error)
DeviceSplit returns g with Groups set to the number of groups of g.Granule() SMs the driver makes from dev's SMs, as a simulated cuDevSmResourceSplitByCount with g's flags reports it.
func (Granularity) Granule ¶
func (g Granularity) Granule() int
Granule returns the group size: Min rounded up to a multiple of Alignment.
type Graph ¶
type Graph struct {
// contains filtered or unexported fields
}
Graph represents an uninstantiated CUDA execution graph DAG.
func Capture ¶
Capture executes fn on stream while recording all enqueued operations into a Graph. The caller must not destroy stream until Capture returns. A non-nil graph must be destroyed even when an error is returned.
func CaptureWithMode ¶
CaptureWithMode records fn using mode. ThreadLocal restricts the unsafe-API checks to the capturing thread; it does not make unsafe calls on that thread valid. Independent captures must also avoid implicit legacy-stream ordering. Begin, fn, and end run on one OS thread. A non-nil graph must be destroyed even when an error is returned.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
// On a CUDA device, pass an independent nonblocking stream in place of
// nil. The callback enqueues operations on that stream only.
_, err := graph.CaptureWithMode(nil, driver.StreamCaptureModeThreadLocal, func() {})
fmt.Println(err)
}
Output: cudagraph: nil stream passed to Capture
func New ¶
New creates an empty CUDA graph. A non-nil graph must be destroyed even when an error is returned, including an error restoring the previous context after successful creation.
func (*Graph) AddConditional ¶
func (g *Graph) AddConditional(typ ConditionalType, h ConditionalHandle, size int, dependencies ...*Node) (*Node, []*Graph, error)
AddConditional adds a conditional node of kind typ on handle h, after dependencies, and returns it with its bodies: size of them, which must be 1 for a WHILE node, 1 or 2 for an IF node and at least 1 for a SWITCH node. The bodies are empty graphs that the caller fills with nodes, by the graph API or by CaptureTo, before g is instantiated.
The bodies belong to the node: their Destroy does nothing, and they cannot be instantiated alone. Launch arguments added to a body with Graph.AddLaunch are kept by g's executables, as g's own are.
A graph that holds a conditional node cannot be cloned or used as a child graph, and may have only one executable at a time. A body may hold kernel, empty, memset, memcpy, child graph and conditional nodes, all in g's context; its kernels cannot use dynamic parallelism or device graph launch, and cooperative launches are refused. CUDA does not document a restriction on programmatic edges between a body's kernels, nor a promise that they overlap there: see the package documentation.
func (*Graph) AddDependencies ¶
func (g *Graph) AddDependencies(from, to []*Node, edgeData ...driver.GraphEdgeData) error
AddDependencies adds dependency edges from nodes in from to nodes in to. from and to must have equal non-zero lengths. Optional edgeData specifies annotations (such as Programmatic edges). If omitted, standard (default) dependency edges are created.
func (*Graph) AddDependency ¶
AddDependency adds a single standard dependency edge from from to to.
func (*Graph) AddDeviceUpdatableKernelNode ¶
func (g *Graph) AddDeviceUpdatableKernelNode(params *driver.KernelNodeParams, dependencies ...*Node) (*Node, error)
AddDeviceUpdatableKernelNode creates a kernel execution node in g marked as device-updatable.
func (*Graph) AddEmptyNode ¶
AddEmptyNode creates an empty node in g that performs no operation and can be used for barrier and dependency synchronization.
func (*Graph) AddKernelNode ¶
func (g *Graph) AddKernelNode(params *driver.KernelNodeParams, dependencies ...*Node) (*Node, error)
AddKernelNode creates a kernel execution node in g with the given parameters and dependencies.
func (*Graph) AddLaunch ¶
AddLaunch adds a kernel node executing desc with args, and returns it.
The graph owns the packed arguments and keeps desc's module reachable for as long as the graph or an Exec instantiated from it is reachable, so the caller need not retain either against the collector. It is not a lease on the module: cuda.Module.Close unloads it regardless, and the node's function handle then names nothing loaded. The caller must not close the module until every graph and Exec built from desc is done with it.
AddLaunch reports an error for any launch attribute a kernel node cannot express, rather than dropping it: attributes on a graph launch are carried by edges and by instantiation options, not by the node. See AddProgrammaticDependency for programmatic dependent launch and AddDeviceUpdatableKernelNode for device-updatable nodes.
func (*Graph) AddLauncher ¶
AddLauncher adds a kernel node running what l is configured to launch. It is the common case of AddLaunch: a caller holding a Launcher needs no intermediate value.
func (*Graph) AddProgrammaticDependency ¶
AddProgrammaticDependency adds a typed Programmatic dependent launch edge from from to to. Both from and to must be kernel execution nodes (created via Graph.AddKernelNode). Empty nodes (created via Graph.AddEmptyNode) do not possess programmatic completion ports and will be rejected by the CUDA driver with CUDA_ERROR_INVALID_VALUE.
func (*Graph) AddWhile ¶
AddWhile adds a WHILE node on handle h after dependencies, and returns it and its body. See Graph.AddConditional.
func (*Graph) Close ¶
Close closes the uninstantiated graph. The body of a conditional node belongs to the node: its Close does nothing.
func (*Graph) ConditionalHandle ¶
func (g *Graph) ConditionalHandle(defaultValue uint32, assignDefault bool) (ConditionalHandle, error)
ConditionalHandle creates a condition value in g. If assignDefault is set, each launch of the executable graph starts with the value set to defaultValue; otherwise the value persists from launch to launch and starts at zero. A WHILE node whose default is 1 is a do-while loop: its body runs at least once.
A handle not used by a conditional node of g or of one of its bodies makes instantiation fail. Conditional nodes need CUDA 12.4 (WHILE and IF with one body) or 12.8 (IF with two bodies, SWITCH).
func (*Graph) Eligibility ¶
func (g *Graph) Eligibility() (Eligibility, error)
Eligibility inspects the graph DAG, counts node types, discovers dynamic parameter update points, and verifies instantiation readiness.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
var g graph.Graph
el, err := g.Eligibility()
fmt.Println(err)
fmt.Println(el.Captured)
}
Output: cudagraph: graph is closed false
func (*Graph) Instantiate ¶
Instantiate validates and instantiates the graph for execution on the GPU. A non-nil executable must be destroyed even when an error is returned.
func (*Graph) InstantiateWithOptions ¶
func (g *Graph) InstantiateWithOptions(options InstantiateOptions) (*Exec, error)
InstantiateWithOptions validates options and instantiates the graph. It includes the driver's detailed failure result when available. Upload is separate because the native upload-on-instantiation flag requires the parameter-based API and an upload stream, not cuGraphInstantiateWithFlags. A non-nil executable must be destroyed even when an error is returned.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
var g graph.Graph
_, err := g.InstantiateWithOptions(graph.InstantiateOptions{})
fmt.Println(err)
}
Output: cudagraph: graph is closed
func (*Graph) ProgrammaticEdges ¶
ProgrammaticEdges returns the number of g's dependency edges of the programmatic type: those Graph.AddProgrammaticDependency adds, and those a stream capture records for a kernel launched with programmatic stream serialization after another kernel. A launch whose predecessor is not a kernel, such as a memory copy, records an ordinary edge.
A count above zero says the graph allows its consumer kernels to launch before their producers complete. It does not say they overlap at run time. The query needs cuGraphGetEdges_v2 (CUDA 12.3); on an older driver it returns an error wrapping driver.ErrNotSupported.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
var g graph.Graph
n, err := g.ProgrammaticEdges()
fmt.Println(n, err)
}
Output: 0 cudagraph: graph is closed
type GreenIsolationRule ¶
type GreenIsolationRule struct {
Partition string
Region string
AllowedSMs []uint32
AllowedMask Mask
}
GreenIsolationRule binds a cudaprofile.Event ID (and its IKET region name) to a named green-context partition and the hardware %smid set permitted for that partition. The allowed set is the union of AllowedSMs and AllowedMask.
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
Group is an immutable execution membership description.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
g, _ := graph.NewGroup(graph.Warp, driver.Dim3{X: 32, Y: 1, Z: 1})
rank, _ := g.Rank(driver.Dim3{X: 7})
fmt.Println(rank, g.Size())
}
Output: 7 32
func NewGroup ¶
NewGroup constructs a group. Warp and warpgroup dimensions are fixed by CUDA.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
g, err := graph.NewGroup(graph.Warp, driver.Dim3{X: 32, Y: 1, Z: 1})
fmt.Println(err, g.Kind(), g.Dims(), g.Size())
}
Output: <nil> warp 32x1x1 32
func WarpGroupForCTA ¶
WarpGroupForCTA returns the warpgroup containing warp in a CTA.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
cta, _ := graph.NewGroup(graph.CTA, driver.Dim3{X: 256, Y: 1, Z: 1})
g, _ := graph.WarpGroupForCTA(cta, 4)
rank, _ := g.Rank(driver.Dim3{})
fmt.Println(g.Kind(), g.Size(), rank)
}
Output: warpgroup 128 128
func (Group) Dims ¶
Dims returns thread dimensions, or CTA dimensions for a cluster.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
g, _ := graph.NewGroup(graph.Thread, driver.Dim3{X: 1, Y: 1, Z: 1})
fmt.Println(g.Dims())
}
Output: 1x1x1
func (Group) Kind ¶
Kind returns the execution membership kind.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
g, _ := graph.NewGroup(graph.WarpGroup, driver.Dim3{X: 128, Y: 1, Z: 1})
fmt.Println(g.Kind())
}
Output: warpgroup
func (Group) Rank ¶
Rank returns the linear participant rank for a group-local coordinate. A subgroup's ranks are relative to its parent CTA; other ranks start at zero.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
g, _ := graph.NewGroup(graph.Warp, driver.Dim3{X: 32, Y: 1, Z: 1})
rank, err := g.Rank(driver.Dim3{X: 7})
fmt.Println(rank, err, g.Contains(driver.Dim3{X: 31}))
}
Output: 7 <nil> true
func (Group) Size ¶
Size returns the number of participants, or zero for an invalid group.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
g, _ := graph.NewGroup(graph.CTA, driver.Dim3{X: 128, Y: 2, Z: 1})
fmt.Println(g.Size())
}
Output: 256
type GroupKind ¶
type GroupKind uint8
Kind identifies an execution group. A warpgroup is four warps (128 threads).
type InstantiateOptions ¶
type InstantiateOptions struct {
// AutoFreeOnLaunch frees allocations left by a previous graph launch.
// It cannot be combined with DeviceLaunch.
AutoFreeOnLaunch bool
DeviceLaunch bool
// UseNodePriority uses kernel-node priorities instead of stream priority.
UseNodePriority bool
// RetainKernelOrder records native symbols only when completion dependencies
// prove a unique kernel order. Unsupported nodes or parallel kernels fail
// before instantiation. A driver before CUDA 12.3, which cannot name a
// kernel, fails with an error wrapping [errors.ErrUnsupported].
RetainKernelOrder bool
}
InstantiateOptions controls graph instantiation. The zero value preserves ordinary host-launch behavior. DeviceLaunch enables device-side launch; it does not upload the graph or supply a device-side launcher. CUDA validates graph contents and device support during instantiation.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
options := graph.InstantiateOptions{UseNodePriority: true}
fmt.Println(options.DeviceLaunch, options.UseNodePriority)
}
Output: false true
type Issuer ¶
type Issuer struct{ CTA, Thread uint64 }
Issuer names a CTA rank within a cluster and a linear thread rank in that CTA.
type KernelNodeField ¶
type KernelNodeField uint32
KernelNodeField specifies the field to update when performing node updates via cudaGraphKernelNodeUpdatesApply.
const ( KernelNodeFieldInvalid KernelNodeField = 0 KernelNodeFieldGridDim KernelNodeField = 1 KernelNodeFieldParam KernelNodeField = 2 KernelNodeFieldEnabled KernelNodeField = 3 )
func (KernelNodeField) String ¶
func (f KernelNodeField) String() string
type KernelNodeUpdate ¶
type KernelNodeUpdate struct {
Field KernelNodeField
Node DeviceNode
GridDim driver.Dim3
Offset uintptr
Value unsafe.Pointer
Size uintptr
IsEnabled uint32
}
KernelNodeUpdate specifies a single kernel node update, matching the semantics of CUDA's cudaGraphKernelNodeUpdate structure for device-side updates.
func NewEnabledUpdate ¶
func NewEnabledUpdate(node DeviceNode, enabled bool) KernelNodeUpdate
NewEnabledUpdate creates a KernelNodeUpdate to enable or disable node.
func NewGridDimUpdate ¶
func NewGridDimUpdate(node DeviceNode, grid driver.Dim3) KernelNodeUpdate
NewGridDimUpdate creates a KernelNodeUpdate to update the grid dimensions of node.
func NewParamUpdate ¶
func NewParamUpdate(node DeviceNode, offset uintptr, val unsafe.Pointer, size uintptr) KernelNodeUpdate
NewParamUpdate creates a KernelNodeUpdate to update a parameter at offset with size bytes.
func NewParamUpdateForFunc ¶
func NewParamUpdateForFunc(node DeviceNode, fn driver.Function, paramIndex uint, val unsafe.Pointer) (KernelNodeUpdate, error)
NewParamUpdateForFunc queries the offset and size of the parameter at paramIndex of fn using cuFuncGetParamInfo and returns a typed KernelNodeUpdate.
func (KernelNodeUpdate) DeviceUpdate ¶
func (u KernelNodeUpdate) DeviceUpdate() DeviceKernelNodeUpdate
DeviceUpdate converts u into the C-ABI compliant DeviceKernelNodeUpdate struct.
type LaunchGeometryError ¶
LaunchGeometryError reports grid or block dimensions that no CUDA device can launch.
func (*LaunchGeometryError) Error ¶
func (e *LaunchGeometryError) Error() string
type LaunchRequirements ¶
LaunchRequirements describes grid and cluster dimensions in CTAs and block dimensions in threads. A zero Cluster means an ordinary, unclustered launch. Device-specific limits and cluster launch attributes need driver validation.
type Mask ¶
A Mask is a set of logical SM indices in [0, MaxSMs). Bit i of word i/64 is SM i.
type MemoryScope ¶
type MemoryScope uint8
MemoryScope is a visibility/ordering scope, not an execution membership.
const ( MemoryThread MemoryScope = iota + 1 MemoryCTA MemoryCluster )
func (MemoryScope) String ¶
func (s MemoryScope) String() string
type Node ¶
type Node struct {
// contains filtered or unexported fields
}
Node represents an individual execution node within a CUDA graph.
func (*Node) DeviceNode ¶
func (n *Node) DeviceNode() (DeviceNode, error)
DeviceNode returns the device-side node handle (cudaGraphDeviceNode_t) for this node. Returns an error if the node is not device-updatable.
func (*Node) IsDeviceUpdatable ¶
IsDeviceUpdatable reports whether this kernel node is configured as device-updatable.
func (*Node) Params ¶
func (n *Node) Params() (driver.KernelNodeParams, error)
Params returns the kernel node's parameters. CUDA owns the returned argument array and values; they must not be written and remain valid only until the original node changes or is destroyed.
func (*Node) SetDeviceUpdatable ¶
SetDeviceUpdatable marks the kernel node as device-updatable. Once enabled, CUDA does not allow opting out, and device-updatable nodes cannot be destroyed individually via DestroyNode.
type Partition ¶
type Partition struct {
Spec Spec
SMs int // assigned SM count
First int // first logical SM
Mask Mask // logical SMs [First, First+SMs)
Clusters int // SMs / cluster size: the persistent grid, in clusters
}
A Partition is one role's share of a Plan.
type Partitions ¶
type Partitions struct {
Plan Plan
// contains filtered or unexported fields
}
Partitions holds the green contexts and streams Open created for a plan.
func Open ¶
func Open(dev driver.Device, plan Plan) (_ *Partitions, err error)
Open creates one green context, with a non-blocking stream, for each of plan's partitions on dev. It asks the driver to split the device's SMs into as many groups of the plan's granule as the partitions need, and combines each partition's groups into one resource descriptor. A plan computed without the device's group limit (see DeviceSplit) may need more groups than the driver makes, and fails here. Open checks that each green context reports the planned SM count. The caller must have called driver.Init.
func OpenDomains ¶
func OpenDomains(dev driver.Device, specs []DomainSpec) (*Partitions, error)
OpenDomains creates one green context, with a non-blocking stream, for each of specs, from SMs of the spec's locality domain. It splits the device's SMs with cuDevSmResourceSplit and the DevSmResourceGroupLocalityDomainId flag, so the driver, not the caller, chooses which physical SMs lie in each domain. Specs are filled in order, so two specs of one domain take disjoint SMs, and a later spec with SMs of 0 takes what the earlier ones left.
The returned Partitions' Plan has one Partition per spec with the SM count the driver gave; its Mask is empty. OpenDomains checks that each green context reports that count, and Partitions.Verify checks a partition from the device. That a partition is local to its domain rests on the driver; a kernel can confirm it by reading %locality_domain_id (see cudamega.LocalityDomainSource).
On a device with one domain, domain 0 is the whole device. The caller must have called driver.Init.
func OpenGroups ¶
func OpenGroups(dev driver.Device, g Granularity, sets [][]int) (*Partitions, error)
OpenGroups creates one green context, with a non-blocking stream, for each of sets: the indices of the split groups it combines, in the order cuDevSmResourceSplitByCount returns them for groups of g's granule with g's flags. A set need not be a contiguous run, as Open's partitions are; this is how a partition takes the groups of one class that ClassGroups found. OpenGroups returns an error for an empty set, an index the split did not make, or an index in two sets, and checks that each green context reports its SM count.
The returned Partitions' Plan has one Partition per set with its SM count; its Mask is empty, since its SMs are not a logical range, and its Spec is the zero Spec. Partitions.Verify checks a partition from the device as it does for Open. The caller must have called driver.Init.
func (*Partitions) Close ¶
func (p *Partitions) Close() error
Close destroys the streams and green contexts and returns the first error.
func (*Partitions) GreenCtx ¶
func (p *Partitions) GreenCtx(i int) driver.GreenCtx
GreenCtx returns the green context of the i'th partition.
func (*Partitions) Stream ¶
func (p *Partitions) Stream(i int) driver.Stream
Stream returns the stream of the i'th partition.
func (*Partitions) Verify ¶
func (p *Partitions) Verify(i int) (SMSpread, error)
Verify launches the SM probe on the i'th partition's stream and checks, from the %smid each block recorded, that the launch ran on no more SMs than the partition holds. It returns an error wrapping ErrPartitionEscaped if it did not. Call it after Open and before trusting a partition: the driver accepts a green context in places where it does not confine the work.
type PingPongTimer ¶
type PingPongTimer struct {
// contains filtered or unexported fields
}
PingPongTimer manages double-buffered (bank 0 and bank 1) event handles for event-record nodes inside an instantiated CUDA graph.
Before each graph launch, PingPongTimer.PrepareReplay (or PingPongTimer.RecordSimulatedReplay in host-only simulation mode) swaps the active event bank (0 -> 1 -> 0), rebinds all event-record nodes to the newly selected bank, and harvests elapsed milliseconds from the previous bank once at least one prior replay has been launched. This avoids host synchronization on the first launch and prevents racing an in-flight graph replay.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
timer, err := graph.NewPingPongTimer(graph.PingPongTimerConfig{
NumEventNodes: 2,
HistoryCap: 4,
})
if err != nil {
fmt.Println("error:", err)
return
}
// Launch 1: arms bank 0; no prior replay exists yet, so LastDurationsMS is nil.
if err := timer.RecordSimulatedReplay([]float64{1.25}); err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("launch=%d bank=%d prev_ms=%v\n", timer.ReplayCount(), timer.ActiveBank(), timer.LastDurationsMS())
// Launch 2: flips to bank 1 and harvests bank 0's duration from launch 1.
if err := timer.RecordSimulatedReplay([]float64{1.50}); err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("launch=%d bank=%d prev_ms=%v\n", timer.ReplayCount(), timer.ActiveBank(), timer.LastDurationsMS())
// Launch 3: flips back to bank 0 and harvests bank 1's duration from launch 2.
if err := timer.RecordSimulatedReplay([]float64{1.10}); err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("launch=%d bank=%d prev_ms=%v\n", timer.ReplayCount(), timer.ActiveBank(), timer.LastDurationsMS())
}
Output: launch=1 bank=0 prev_ms=[] launch=2 bank=1 prev_ms=[1.25] launch=3 bank=0 prev_ms=[1.5]
func NewPingPongTimer ¶
func NewPingPongTimer(cfg PingPongTimerConfig) (*PingPongTimer, error)
NewPingPongTimer constructs a PingPongTimer for cfg.
func (*PingPongTimer) ActiveBank ¶
func (t *PingPongTimer) ActiveBank() int
ActiveBank returns the bank index (0 or 1) armed by the most recent replay, or -1 before the first replay.
func (*PingPongTimer) BindBankEvents ¶
func (t *PingPongTimer) BindBankEvents(bank int, events []driver.Event) error
BindBankEvents sets the driver.Event handles used for bank (0 or 1). The slice length must match PingPongTimerConfig.NumEventNodes.
func (*PingPongTimer) HistoryDurationsMS ¶
func (t *PingPongTimer) HistoryDurationsMS() [][]float64
HistoryDurationsMS returns a copy of the bounded history of harvested replay duration slices in chronological order.
func (*PingPongTimer) LastDurationsMS ¶
func (t *PingPongTimer) LastDurationsMS() []float64
LastDurationsMS returns a copy of the most recently harvested previous-bank replay durations in milliseconds, or nil if fewer than two replays have been prepared/recorded.
func (*PingPongTimer) PrepareReplay ¶
func (t *PingPongTimer) PrepareReplay(exec driver.GraphExec, nodes []EventRecordNode) (bank int, err error)
PrepareReplay swaps the active event bank (0 vs 1), rebinds every node in nodes to the new bank's events on exec, and reads elapsed times from the previous bank (prevBank = 1 - bank) if at least one prior replay occurred.
func (*PingPongTimer) RecordSimulatedReplay ¶
func (t *PingPongTimer) RecordSimulatedReplay(durationsMS []float64) error
RecordSimulatedReplay advances the ping-pong state machine in pure-Go simulation mode without a CUDA driver context.
On the first replay (ReplayCount == 1), bank 0 is armed with durationsMS and no prior bank is read, so PingPongTimer.LastDurationsMS remains nil (zero host-blocking on the first launch). On replay k >= 2, the active bank flips (0 -> 1 -> 0) and PingPongTimer.LastDurationsMS returns the durations recorded by replay k-1 in prevBank = 1 - bank.
func (*PingPongTimer) ReplayCount ¶
func (t *PingPongTimer) ReplayCount() int
ReplayCount returns the total number of replays prepared or simulated so far.
type PingPongTimerConfig ¶
type PingPongTimerConfig struct {
// NumEventNodes is the number of EventRecordNode handles rebound before each replay.
NumEventNodes int
// HistoryCap bounds how many completed replay duration slices are retained.
// When zero or negative, a default capacity of 16 is used.
HistoryCap int
}
PingPongTimerConfig configures a PingPongTimer over a fixed number of event-record nodes in a captured CUDA graph.
type Plan ¶
type Plan struct {
Arch string
TotalSMs int
Granularity Granularity
Partitions []Partition
Unassigned int // SMs no partition holds
}
A Plan is a disjoint carving of one device's SMs.
func ComputePlan ¶
ComputePlan carves totalSMs SMs among specs, in order. Each partition starts at its target fraction rounded to the nearest legal size, and is raised to its minimum. If the total exceeds the SMs available in whole granules, or in the groups the device makes, the partition furthest above its target shrinks by one unit at a time until the plan fits; ComputePlan returns an error wrapping ErrInfeasible if the minimums alone do not fit.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
g, err := graph.DefaultGranularity("sm_100a")
if err != nil {
panic(err)
}
plan, err := graph.ComputePlan("sm_100a", 160, g, graph.DecodeHeavy())
if err != nil {
panic(err)
}
if err := graph.VerifyPlan(plan); err != nil {
panic(err)
}
for _, p := range plan.Partitions {
fmt.Printf("%-11v SMs %3d-%3d\n", p.Spec.Role, p.First, p.First+p.SMs-1)
}
}
Output: compute SMs 0- 31 decode SMs 32-143 fabric SMs 144-151 maintenance SMs 152-159
type SMIsolationReport ¶
type SMIsolationReport struct {
PartitionSMs map[string][]uint32
Violations []SMIsolationViolation
StrictlyIsolated bool
}
SMIsolationReport records the hardware %smid sets observed per workload partition in a cudaprofile.Trace, any SMs shared across partitions, any per-partition allowed-SM violations, and whether the partitions are strictly SM-isolated.
func VerifyGreenContextSMIsolation ¶
func VerifyGreenContextSMIsolation(trace *cudaprofile.Trace, idPartitions map[uint16]string) (*SMIsolationReport, error)
VerifyGreenContextSMIsolation groups observed Event.SM (%smid) values in trace by partition name (idPartitions[ev.ID]), sorts and deduplicates each partition's SM set, identifies any SMs shared by two or more partitions in SharedSMs, and reports whether all observed partitions are strictly SM-disjoint.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/graph"
cudaprofile "github.com/tmc/lib/nvidia/x/obs/iket/ring"
)
func main() {
trace := &cudaprofile.Trace{
Events: []cudaprofile.Event{
{Start: 1000, End: 1400, SM: 0, Block: 0, Warp: 0, ID: 1},
{Start: 1000, End: 1420, SM: 1, Block: 1, Warp: 0, ID: 1},
{Start: 1010, End: 1900, SM: 8, Block: 0, Warp: 0, ID: 2},
{Start: 1010, End: 1920, SM: 9, Block: 1, Warp: 0, ID: 2},
},
}
idPartitions := map[uint16]string{
1: "decode",
2: "prefill",
}
rep, err := graph.VerifyGreenContextSMIsolation(trace, idPartitions)
if err != nil {
panic(err)
}
fmt.Printf("isolated=%v decode=%v prefill=%v shared=%v\n",
rep.StrictlyIsolated, rep.PartitionSMs["decode"], rep.PartitionSMs["prefill"], rep.SharedSMs)
}
Output: isolated=true decode=[0 1] prefill=[8 9] shared=[]
type SMIsolationViolation ¶
type SMIsolationViolation struct {
Partition string
Region string
ID uint16
SM uint32
AllowedSMs []uint32
Block uint32
Warp uint16
Start uint64
End uint64
}
SMIsolationViolation reports a trace event whose hardware %smid (SM) fell outside the allowed SM set of its green-context partition.
func (SMIsolationViolation) String ¶
func (v SMIsolationViolation) String() string
String formats v with the offending SM, partition, region, block, and warp.
type SMProbe ¶
type SMProbe struct {
// contains filtered or unexported fields
}
An SMProbe launches SMProbePTX in one context and reads back where its blocks ran. The zero SMProbe is not usable; call NewSMProbe.
func NewSMProbe ¶
NewSMProbe loads the probe in ctx with an output buffer for grid blocks. Choose grid to be several times the device's SM count, so that an unpartitioned launch reaches every SM. Like every SMProbe method, it makes ctx current only while it works and then restores the thread's current context.
func (*SMProbe) Out ¶
Out and SpinNs return the probe's two kernel arguments, for a caller that launches it some other way (a graph node, a library kernel).
func (*SMProbe) Read ¶
Read waits for the device and returns the %smid of every probe block. It fails if any block left its slot unwritten.
type SMSpread ¶
type SMSpread struct {
Blocks int // blocks the probe launched, all of which reported
SMs []uint32 // distinct %smid values, ascending
Limit int // SMs the partition holds
}
An SMSpread is the set of physical SMs a probe launch ran on.
func CheckSMSpread ¶
CheckSMSpread returns the distinct SMs in smids, one %smid per probe block, and an error wrapping ErrPartitionEscaped if there are more than limit of them. A probe that reported nothing proves nothing, so an empty smids is an error too.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
// Eight probe blocks on a 4-SM partition that held, then the same
// partition's work reported from six SMs.
_, err := graph.CheckSMSpread([]uint32{8, 9, 10, 11, 8, 9, 10, 11}, 4)
fmt.Println(err)
_, err = graph.CheckSMSpread([]uint32{8, 9, 10, 11, 0, 1, 10, 11}, 4)
fmt.Println(err)
}
Output: <nil> cudagreen: work ran outside its partition: 8 blocks ran on 6 SMs, partition holds 4
func CheckSMSpreadIn ¶
CheckSMSpreadIn is CheckSMSpread against the SMs a partition may use rather than their count: it returns the distinct SMs in smids, with Limit the number of allowed SMs, and an error wrapping ErrPartitionEscaped that names each SM not in allowed. A count misses work that escaped onto as many SMs as the partition holds; this does not. An empty smids or allowed is an error.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
// A partition of SMs 8 to 11 whose work ran on four SMs, one of them SM
// 24: the count is within the partition, the set is not.
allowed := []int{8, 9, 10, 11}
_, err := graph.CheckSMSpread([]uint32{8, 9, 10, 24}, len(allowed))
fmt.Println(err)
_, err = graph.CheckSMSpreadIn([]uint32{8, 9, 10, 24}, allowed)
fmt.Println(err)
}
Output: <nil> cudagreen: work ran outside its partition: 4 blocks ran on SMs [24], outside the 4 allowed
type Spec ¶
type Spec struct {
Role Role
MinSMs int // hard minimum
Fraction float64 // target share of the device's SMs; fractions sum to at most 1
// ClusterSize is the thread-block cluster size the role launches,
// at one CTA per SM. The partition's SM count is a multiple of it.
// Zero means 1.
ClusterSize int
}
A Spec requests SMs for one role.
func DecodeHeavy ¶
func DecodeHeavy() []Spec
DecodeHeavy returns specs that give most SMs to the decode role, in the proportions 20/70/5/5 percent.
func PrefillHeavy ¶
func PrefillHeavy() []Spec
PrefillHeavy returns specs that give most SMs to the compute role, in the proportions 80/10/5/5 percent.
type TMEMCollective ¶
type TMEMCollective struct {
// contains filtered or unexported fields
}
TMEMCollective describes one issuing warp per participating CTA for tcgen05 allocation, deallocation, or permit relinquishment. It does not allocate memory or prove ordering, allocation units, or permit lifetime. Construct it with NewTMEMCollective; the zero value is invalid.
func NewTMEMCollective ¶
func NewTMEMCollective(target string, peers TMEMPeers, cluster Group, block driver.Dim3, firstCTA uint64, warp uint32) (TMEMCollective, error)
NewTMEMCollective admits the sm_100a subset of PTX 8.6 allocation-management participation. Group2 requires an even/odd peer pair within the cluster. This bounded model uses the same issuing warp index in each peer CTA.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
cluster, _ := graph.NewGroup(graph.Cluster, driver.Dim3{X: 2, Y: 1, Z: 1})
t, _ := graph.NewTMEMCollective("sm_100a", graph.TMEMGroup2, cluster, driver.Dim3{X: 128, Y: 1, Z: 1}, 0, 0)
fmt.Println(t.Peers())
}
Output: 2
func (TMEMCollective) Peers ¶
func (c TMEMCollective) Peers() TMEMPeers
Peers returns the instruction's CTA group qualifier, not the cluster size.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
cluster, _ := graph.NewGroup(graph.Cluster, driver.Dim3{X: 1, Y: 1, Z: 1})
t, _ := graph.NewTMEMCollective("sm_100a", graph.TMEMGroup1, cluster, driver.Dim3{X: 128, Y: 1, Z: 1}, 0, 0)
fmt.Println(t.Peers() == graph.TMEMGroup1)
}
Output: true
func (TMEMCollective) ValidateLaunch ¶
func (c TMEMCollective) ValidateLaunch(req LaunchRequirements) error
ValidateLaunch checks the cluster and block containing the issuing warps.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
cluster, _ := graph.NewGroup(graph.Cluster, driver.Dim3{X: 1, Y: 1, Z: 1})
t, _ := graph.NewTMEMCollective("sm_100a", graph.TMEMGroup1, cluster, driver.Dim3{X: 128, Y: 1, Z: 1}, 0, 0)
err := t.ValidateLaunch(graph.LaunchRequirements{Grid: driver.Dim3{X: 1, Y: 1, Z: 1}, Block: driver.Dim3{X: 128, Y: 1, Z: 1}, Cluster: driver.Dim3{X: 1, Y: 1, Z: 1}})
fmt.Println(err)
}
Output: <nil>
func (TMEMCollective) ValidateParticipation ¶
func (c TMEMCollective) ValidateParticipation(issuers []Issuer, args []uint32) error
ValidateParticipation checks complete issuing warps and uniform arguments. Each argument could be nCols; legal values are checked by cudatmem.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/cuda/graph"
)
func main() {
cluster, _ := graph.NewGroup(graph.Cluster, driver.Dim3{X: 1, Y: 1, Z: 1})
t, _ := graph.NewTMEMCollective("sm_100a", graph.TMEMGroup1, cluster, driver.Dim3{X: 32, Y: 1, Z: 1}, 0, 0)
issuers, args := make([]graph.Issuer, 32), make([]uint32, 32)
for i := range issuers {
issuers[i] = graph.Issuer{CTA: 0, Thread: uint64(i)}
args[i] = 8
}
fmt.Println(t.ValidateParticipation(issuers, args))
}
Output: <nil>