Documentation
¶
Overview ¶
Package layout provides checked physical tile layouts, CuTe layout algebra, Tensor Memory Accelerator (TMA) transfer and multicast planning, Blackwell Tensor Memory (TMEM) allocation protocols, thread-block-cluster distributed shared-memory emitters, per-block shared-memory planning, cooperative block primitives, and static/dynamic mbarrier pipeline verification.
A Layout represents CuTe's shape:stride mapping from logical coordinates to offsets, with Coalesce, Composition, Complement, LogicalDivide, ZippedDivide, and F2 XORSwizzle algebra. Tile, Partition, and PlanCopy describe checked physical tile storage, disjoint launch-grid partitions, and host/device layout copies.
[EncodeTiled], NewMulticastPlan, and NewUnicastRingPlan plan TMA bulk tensor descriptors and transfers without packing opaque vendor descriptor bytes on the host. Allocator and VerifyTrace model sm_100a TMEM column allocation and collective WarpGroup lifecycles. Check and Open gate cluster distributed shared-memory windows against target toolchain and hardware evidence, NewPlan and HazardMatrix plan non-overlapping per-CTA shared-memory regions, Header embeds cooperative block collectives, and ValidatePTX and NewBarrierTracker verify mbarrier transaction and phase-parity protocols in straight-line code. CheckSync specializes a kernel with branches and loops for a fixed launch and checks that its mbarriers are well-synchronized.
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
Example ¶
tile, _ := NewTile(2, 3, 4, WithStride(4)) p, _ := tile.Index(1, 2) fmt.Println(p.ByteOffset)
Output: 24
Example (Cluster) ¶
Example shows the all-to-one shape: every CTA publishes its rank into its own window, the cluster synchronizes, and rank 0 reads each peer in turn. The synchronization is written by the caller because only the caller knows the dependency it is enforcing.
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
limits := layout.Limits{StaticMax: 49152, DynamicMax: 102400, TotalMax: 102400, Source: "example target"}
plan, err := layout.NewPlan(limits)
if err != nil {
panic(err)
}
window, err := plan.Add(layout.Request{Name: "window", Size: 4, Alignment: 4})
if err != nil {
panic(err)
}
c, err := layout.Open("sm_121a")
if err != nil {
panic(err)
}
fmt.Println(layout.EmitBlockRank("%r1"))
for _, s := range layout.EmitClusterSync() {
fmt.Println(s)
}
addr, err := layout.EmitSharedAddr("%r9", "smem", plan, window)
if err != nil {
panic(err)
}
fmt.Println(addr)
read, err := c.EmitReadU32("%r4", "%r3", "%r9", plan, window, "%r2")
if err != nil {
panic(err)
}
for _, s := range read {
fmt.Println(s)
}
}
Output: mov.u32 %r1, %cluster_ctarank; barrier.cluster.arrive; barrier.cluster.wait; mov.u32 %r9, smem; mapa.shared::cluster.u32 %r3, %r9, %r2; ld.shared::cluster.u32 %r4, [%r3];
Example (Pipeline) ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/isa/ptx"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
const src = `
.version 8.8
.target sm_121a
.address_size 64
.visible .entry example_kernel(.param .u64 tmap) {
.reg .b64 %rd_tmap, %state;
.reg .pred %p0;
.shared .align 8 .b64 bar;
ld.param.u64 %rd_tmap, [tmap];
mbarrier.init.shared::cta.b64 [bar], 1;
mbarrier.arrive.expect_tx.shared::cta.b64 %state, [bar], 1024;
cp.async.bulk.tensor.2d.shared::cta.global.mbarrier::complete_tx::bytes [0], [%rd_tmap, {0, 0}], [bar];
mbarrier.try_wait.parity.shared::cta.b64 %p0, [bar], 0;
ret;
}
`
mod, err := ptx.Parse(strings.NewReader(src))
if err != nil {
panic(err)
}
violations, err := layout.ValidatePTX(mod, layout.WithTensorSize("tmap", 1024))
if err != nil {
panic(err)
}
fmt.Println("Violations:", len(violations))
}
Output: Violations: 0
Example (Tma) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
m, _ := layout.NewMulticast(0, []uint32{1, 2}, 128)
fmt.Println(m.Mask, m.CompleteAll())
}
Output: 6 false
Example (Tmem) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
a, err := layout.New(layout.SM100A)
if err != nil {
fmt.Println(err)
return
}
p, err := a.AcquirePermit(32)
if err != nil {
fmt.Println(err)
return
}
x, err := a.Allocate(p, 32, 64, 1)
if err != nil {
fmt.Println(err)
return
}
y, err := a.Allocate(p, 32, 32, 1)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(x.Columns(), y.Columns())
// Relinquishing ends allocation, not ownership of live allocations.
fmt.Println(a.Relinquish(p))
_, err = a.Allocate(p, 32, 32, 1)
fmt.Println(err)
fmt.Println(a.Release(p, x, 32), a.Release(p, y, 32), a.Close())
}
Output: 64 32 <nil> cudatmem: allocation permission required: permit relinquished <nil> <nil> <nil>
Index ¶
- Constants
- Variables
- func AuditTensormapReplaceAllocClass(m *ptx.Module) error
- func BindPartitionArgs(p Partition) []any
- func BindPartitionArgs32(p Partition) ([]any, error)
- func BindPartitionMutArgs(p PartitionMut) []any
- func BindPartitionMutArgs32(p PartitionMut) ([]any, error)
- func BulkWaitGroup(pending int, read bool) (string, error)
- func ByteRangeOverlap(aOffset uint64, aSize uint32, bOffset uint64, bSize uint32) bool
- func CanonicalArch(arch string) string
- func Check(target string) error
- func CheckClusterHardware(arch string) error
- func CheckDSMEM(target string) error
- func CheckTopKStatus(status []int32) error
- func Copy[T any](plan CopyPlan, dst, src cuda.Slice[T]) error
- func EmitArriveExpectTx(mbarAddr string, txBytes int) string
- func EmitArriveExpectTxRemote(mbarAddr string, txBytes int) (string, error)
- func EmitBlockRank(dst string) string
- func EmitCPAsyncCommitGroup() string
- func EmitCPAsyncMBarrierArrive(mbarAddr string, noinc bool) (string, error)
- func EmitCPAsyncWaitGroup(pending int) (string, error)
- func EmitClusterBarrier(relaxed bool) string
- func EmitClusterCTAID(dst string, dim Dim) (string, error)
- func EmitClusterNCTAID(dst string, dim Dim) (string, error)
- func EmitClusterSize(dst string) string
- func EmitClusterSync() []string
- func EmitFenceProxyAsync(space AsyncProxySpace) (string, error)
- func EmitInlineAsmArriveExpectTx(mbarOffset, txBytes int) string
- func EmitInlineAsmInit(mbarOffset, arrivalCount int) string
- func EmitInlineAsmTMA2D(dstOffset int, descPtrReg, coord0Reg, coord1Reg string, mbarOffset int) string
- func EmitInlineAsmTMA2DTMEM(dstTmemReg, descPtrReg, coord0Reg, coord1Reg string, mbarOffset int) string
- func EmitInlineAsmTMEMAlloc(dstSharedOffset int, nCols int) string
- func EmitInlineAsmTMEMDealloc(taddrReg string, nCols int) string
- func EmitInlineAsmWait(mbarOffset int, phaseParity int) string
- func EmitMBarrierArrive(mbarAddr string, count int, remote bool) (string, error)
- func EmitMBarrierExpectTx(mbarAddr string, txBytes int, remote bool) (string, error)
- func EmitMBarrierInit(mbarAddr string, arrivalCount int) string
- func EmitMBarrierInvalidate(mbarAddr string) (string, error)
- func EmitPrefetchTile2DL2(desc, c0, c1, policy string) (string, error)
- func EmitQueryAllocClassLarge(predicate, desc string) (string, error)
- func EmitQueryAllocClassLargeSharedCTA(predicate, desc string) (string, error)
- func EmitReplaceGlobalAddress(desc, addr string, class AllocClass) (string, error)
- func EmitReplaceGlobalAddressGlobal(desc, addr string, class AllocClass) (string, error)
- func EmitSharedAddr(dst, symbol string, plan *Plan, region Region) (string, error)
- func EmitTMABulkAsync2D(dstSmem, descAddr, coord0, coord1, mbarAddr string) string
- func EmitTMABulkAsync2DCluster(dstSmem, descAddr, coord0, coord1, mbarAddr string) string
- func EmitTMABulkAsync2DTMEM(dstTmem, descAddr, coord0, coord1, mbarAddr string) string
- func EmitTMABulkAsyncTMEM(dstTmem, srcGlobal string, sizeBytes int, mbarAddr string) string
- func EmitTMEMAlloc(dstSharedAddr string, nCols int) string
- func EmitTMEMDealloc(taddrReg string, nCols int) string
- func EmitTMEMRelinquishPermit() string
- func EmitWaitGroupAsyncProxy(pending int) (string, error)
- func EmitWaitLoop(mbarAddr string, phaseParity int, labelPrefix string) string
- func EmitWaitParity(mbarAddr string, phaseParity int, predReg string) string
- func ExpectedReduction(clusterSize int) uint32
- func FixtureSource(target string, elements int) (string, error)
- func FixtureSourceForTarget(t Tile, target string) (string, error)
- func FootprintBytes(factors IndexFactorization, bypass DatatypeBypass, dtypes map[TensorRole]int, ...) (int, error)
- func GenerateMutantCUDA(kind string) (string, error)
- func InferLaunchGrid(explicit shape.Grid3D, partitions []Partition) (shape.Grid3D, error)
- func MulticastSource(target string) (string, error)
- func NormalizeUnsetNUMA(node int) int
- func PTX95AllocClassFixtureSource(target string) (string, error)
- func ReadProcNvidiaGPUNUMANode(fsRoot string, pciBusID string) (int, error)
- func ReadSysfsIBNUMANode(fsRoot string, ibDevName string) (int, error)
- func ReadSysfsPCINUMANode(fsRoot string, pciBusID string) (int, error)
- func ReductionFixture(target string, clusterSize int, mut Mutant) (string, error)
- func SameReductionTree(a, b Layout, levels ...int) bool
- func StagedCopyFixture(plan *Plan, target string, elements int) (string, int64, error)
- func StagedCopyFixtureSource(target string, elements int) (string, error)
- func TMAFixtureSource(target string) (string, error)
- func TileFixtureSource(t Tile) (string, error)
- func TopKSchema() (kernel.Schema, error)
- func ValidateCapacity(factors IndexFactorization, bypass DatatypeBypass, dtypes map[TensorRole]int, ...) error
- func ValidateCollective(c graph.TMEMCollective, issuers []graph.Issuer, args []uint32) error
- func ValidateFixture(f Fixture) error
- func ValidateSM121Resources(smemBytesPerBlock int, warpsPerBlock int, blocksPerSM int, ...) (ResourceSummary, []ValidationError)
- func WordOverlap(aOffset uint64, aSize uint32, bOffset uint64, bSize uint32) bool
- type Access
- type Address
- type AllocClass
- type Allocation
- type Allocator
- func (a *Allocator) AcquireCollectivePermit(issuers []graph.Issuer) (*Permit, error)
- func (a *Allocator) AcquirePermit(participants uint32) (*Permit, error)
- func (a *Allocator) Allocate(p *Permit, participants, columns, rows uint32) (*Allocation, error)
- func (a *Allocator) AllocateCollective(p *Permit, issuers []graph.Issuer, columns []uint32, rows uint32) (*Allocation, error)
- func (a *Allocator) CTAGroup() CTAGroup
- func (a *Allocator) Capability() TMEMCapability
- func (a *Allocator) Close() error
- func (a *Allocator) EnableExclusive(group CTAGroup) error
- func (a *Allocator) Exclusive() bool
- func (a *Allocator) Release(p *Permit, x *Allocation, participants uint32) error
- func (a *Allocator) ReleaseCollective(p *Permit, x *Allocation, issuers []graph.Issuer, columns []uint32) error
- func (a *Allocator) Relinquish(p *Permit) error
- func (a *Allocator) RelinquishCollective(p *Permit, issuers []graph.Issuer) error
- type ArchProfile
- type AsyncCopyPipeline
- func (p *AsyncCopyPipeline) ArriveExpectTx(stage int, txBytes uint64) error
- func (p *AsyncCopyPipeline) CheckHazards() []PipelineHazard
- func (p *AsyncCopyPipeline) CommitGroup() error
- func (p *AsyncCopyPipeline) CompleteTx(stage int, txBytes uint64) error
- func (p *AsyncCopyPipeline) IssueCopy(stage int, bytes uint64) error
- func (p *AsyncCopyPipeline) NumStages() int
- func (p *AsyncCopyPipeline) ReadStage(stage int) error
- func (p *AsyncCopyPipeline) WaitGroup(remaining int) error
- func (p *AsyncCopyPipeline) WaitParity(stage int, phase int) error
- func (p *AsyncCopyPipeline) WriteStage(stage int) error
- type AsyncProxySpace
- type AttentionLayout
- type Barrier
- type BarrierEvent
- type BarrierEventKind
- type BarrierExpectation
- type BarrierOption
- type BarrierState
- type BarrierTracker
- func (t *BarrierTracker) Barrier(name string) *BarrierState
- func (t *BarrierTracker) Barriers() map[string]*BarrierState
- func (t *BarrierTracker) Reset()
- func (t *BarrierTracker) SetTensorSize(tensorMap string, bytes int64)
- func (t *BarrierTracker) Validate(mod *ptx.Module) ([]ValidationError, error)
- func (t *BarrierTracker) ValidateKernel(k *ptx.Kernel) ([]ValidationError, error)
- type Buffer
- type CPAsyncSpec
- type CTAGroup
- type Capability
- type Category
- type Cluster
- func (c *Cluster) EmitLoadU32(dst string, p ClusterPtr) (string, error)
- func (c *Cluster) EmitReadU32(dst, addr, base string, plan *Plan, region Region, rank string) ([]string, error)
- func (c *Cluster) EmitStoreU32(p ClusterPtr, src string) (string, error)
- func (c *Cluster) MapSharedRank(dst, base string, plan *Plan, region Region, rank string) (string, ClusterPtr, error)
- func (c *Cluster) MapSharedRankMut(dst, base string, plan *Plan, region Region, rank string) (string, ClusterPtr, error)
- type ClusterPtr
- type Column
- type CopyPlan
- type CopyRun
- type DatatypeBypass
- type Descriptor
- type DescriptorSlot
- func (s *DescriptorSlot) Complete(h TransferHandle) error
- func (s *DescriptorSlot) Current() (Descriptor, uint64)
- func (s *DescriptorSlot) Descriptor() Descriptor
- func (s *DescriptorSlot) Generation() uint64
- func (s *DescriptorSlot) InFlight() int
- func (s *DescriptorSlot) Issue(generation uint64, t Transfer) (TransferHandle, error)
- func (s *DescriptorSlot) Update(d Descriptor) error
- type DeviceTopology
- type Dim
- type Direction
- type ElementType
- type EventKind
- type ExecutionScope
- type Fixture
- type Fragment
- func (f Fragment) Cols() int
- func (f Fragment) Element(o FragmentOwner) (row, col int, err error)
- func (f Fragment) ElementBytes() int
- func (f Fragment) ElementsPerSlot() int
- func (f Fragment) ElementsPerThread() int
- func (f Fragment) Layout() FragmentLayout
- func (f Fragment) Owner(row, col int) (FragmentOwner, error)
- func (f Fragment) PackedPerThread() int
- func (f Fragment) RegistersPerThread() int
- func (f Fragment) Rows() int
- type FragmentLayout
- type FragmentOwner
- type HardwareConstraints
- type HazardMatrix
- type HazardRecord
- type HazardType
- type IndexFactorization
- type Issue
- type L2CachePolicySpec
- type L2EvictionPolicy
- type Layout
- func Coalesce(l Layout) Layout
- func CoalesceByMode(l Layout) Layout
- func CompactLayout(shape Shape) (Layout, error)
- func Complement(l Layout, cotarget int) (Layout, error)
- func ComposeByMode(a Layout, tiler []Layout) (Layout, error)
- func Composition(a, b Layout) (Layout, error)
- func GreatestCommonDomain(a, b Layout) (Layout, error)
- func LogicalDivide(a, b Layout) (Layout, error)
- func LogicalDivideByMode(a Layout, tiler []Layout) (Layout, error)
- func NewLayout(shape Shape, stride Stride) (Layout, error)
- func Nullspace(l Layout) (Layout, error)
- func ParseLayout(s string) (Layout, error)
- func RightInverse(l Layout) (Layout, error)
- func ShapeTiler(extents ...int) ([]Layout, error)
- func TMASwizzleLayout(rows, cols, elementBytes int, mode TMASwizzle) (Layout, error)
- func ZippedDivide(a Layout, tiler []Layout) (Layout, error)
- func (l Layout) BasisOffset(i int, dst []int) ([]int, error)
- func (l Layout) Coordinate(i int, dst []int) ([]int, error)
- func (l Layout) Cosize() (int, error)
- func (l Layout) Equal(m Layout) bool
- func (l Layout) Index(i int) (int, error)
- func (l Layout) Mode(i int) (Layout, error)
- func (l Layout) Offset(crd ...int) (int, error)
- func (l Layout) Rank() int
- func (l Layout) Shape() Shape
- func (l Layout) Size() int
- func (l Layout) Stride() Stride
- func (l Layout) String() string
- type Limits
- type LoopPermutation
- type Map
- type MapSpace
- type MemoryAccess
- type MemorySpace
- type Multicast
- type MulticastConfig
- type MulticastPlan
- type MulticastRequirements
- type Mutant
- type Option
- type Partition
- func (p Partition) ElementBytes() int
- func (p Partition) Grid() (shape.Grid3D, error)
- func (p Partition) IsMutable() bool
- func (p Partition) PartitionShape() shape.Shape
- func (p Partition) PartitionStrides() []int
- func (p Partition) Ptr() driver.DevicePtr
- func (p Partition) Strides() []int
- func (p Partition) TensorShape() shape.Shape
- func (p Partition) TileStride() int
- func (p Partition) TileStride32() (int32, error)
- func (p Partition) ValidateDisjoint() error
- type PartitionMut
- type PartitionOption
- type Permit
- type PhysicalIndex
- type Pipeline
- func (p *Pipeline) EmitEpilogPTX() string
- func (p *Pipeline) EmitPrologPTX() string
- func (p *Pipeline) EmitStageLoadPTX(stageIdx int, descAddr, coord0, coord1 string) string
- func (p *Pipeline) EmitStageWaitPTX(stageIdx int, phaseParity int) string
- func (p *Pipeline) NumStages() int
- func (p *Pipeline) Simulate(iterations int) (*SimulationTrace, error)
- func (p *Pipeline) Stage(i int) *Stage
- func (p *Pipeline) TotalSharedBytes() int
- func (p *Pipeline) TotalTMEMBytes() int
- func (p *Pipeline) TotalTMEMColumns() int
- func (p *Pipeline) Validate() *Report
- type PipelineConfig
- type PipelineHazard
- type PipelineMemorySpace
- type PipelineScenario
- type PipelineSchedule
- type Plan
- type RedistributionPermutation
- type Region
- type RegisterOwner
- type Report
- type Request
- type ResourceSummary
- type Role
- type Row
- type ScheduleStep
- type Severity
- type Shape
- type SharedWindow
- type SimulationTrace
- type Slice
- type SpatialTiling
- type Stage
- type StageOwnership
- type StageState
- type StepEvent
- type StepKind
- type StorageLevel
- type Stride
- type Swizzle
- type SwizzledTile
- func (t SwizzledTile) AgreesWith(descriptor TMASwizzle) error
- func (t SwizzledTile) BaseAlignment() int
- func (t SwizzledTile) ByteOffset(row, col int) (int, error)
- func (t SwizzledTile) Bytes() int
- func (t SwizzledTile) Cols() int
- func (t SwizzledTile) ElementBytes() int
- func (t SwizzledTile) Rows() int
- func (t SwizzledTile) Swizzle() TMASwizzle
- type SyncCheck
- type SyncEvent
- type SyncEventKind
- type SyncLaunch
- type SyncResult
- type SyncRole
- type SyncVerdict
- type SyncWitness
- type TMABox
- type TMAGather4Mode
- type TMAGather4Spec
- type TMAMulticastSpec
- type TMAReduceOp
- type TMAReduceSpec
- type TMAReduceType
- type TMAStageState
- type TMASwizzle
- type TMATileSpec
- type TMEMCapability
- type Target
- type TensorRole
- type Tile
- func (t Tile) AlignmentBytes() int
- func (t Tile) Cols() int
- func (t Tile) Compatible(other Tile) bool
- func (t Tile) ElementBytes() int
- func (t Tile) FootprintBytes() (int, error)
- func (t Tile) Identity() string
- func (t Tile) Index(row, col int) (PhysicalIndex, error)
- func (t Tile) Owner(row, col int) (RegisterOwner, error)
- func (t Tile) OwnerFor(lane, register int) (row, col int, err error)
- func (t Tile) Rows() int
- func (t Tile) StrideElements() int
- func (t Tile) Swizzle() Swizzle
- func (t Tile) TransposeOwners(row, col int) (RegisterOwner, error)
- type TileConfig
- type TopK
- type TopKBF16
- type TopKBF16Buffers
- type TopKBuffers
- type TopKConfig
- type TopKExtents
- type TopKStatus
- type TraceEvent
- type TraceSummary
- type Transfer
- type TransferHandle
- type UnicastRingConfig
- type UnicastRingPlan
- type ValidationError
- type XORSwizzle
Examples ¶
- Package
- Package (Cluster)
- Package (Pipeline)
- Package (Shared)
- Package (Tma)
- Package (Tmem)
- Access.Complete
- Allocation.Slice
- Allocator.AcquireCollectivePermit
- Allocator.AllocateCollective
- Allocator.ReleaseCollective
- Allocator.RelinquishCollective
- AsyncCopyPipeline
- AuditTensormapReplaceAllocClass
- CheckDSMEM
- CheckSync
- CheckTopKStatus
- Coalesce
- CoalesceByMode
- CompactLayout
- CompileTopK
- CompileTopKBF16
- Complement
- ComposeByMode
- Composition
- CopyPlan
- DescriptorSlot
- DiscoverHostTopology
- EmitPrefetchTile2DL2
- EmitQueryAllocClassLarge
- EmitReplaceGlobalAddress
- EmitWaitGroupAsyncProxy
- F2Stride
- FixtureSourceForTarget
- GreatestCommonDomain
- HazardMatrix
- InferLaunchGrid
- Layout.BasisOffset
- Layout.Coordinate
- Layout.Cosize
- Layout.Equal
- Layout.Mode
- Layout.Offset
- LoadTopK
- LogicalDivide
- LogicalDivideByMode
- Multicast
- MulticastPlan.Descriptor
- MulticastPlan.Requirements
- MulticastPlan.Source
- NewBarrierTracker
- NewCollective
- NewLayout
- NewMulticastPlan
- NewPartition
- NewPipeline
- NewPipeline (Tmem)
- NewTile
- NewUnicastRingPlan
- NewXORSwizzle
- Nullspace
- ParseLayout
- ParseStride
- PipelineSchedule.AttentionSource
- PipelineSchedule.CopySources
- PlanCopy
- RedistributionPermutation.Map
- RightInverse
- SameReductionTree
- Shape.String
- ShapeTiler
- Slice.Address
- Slice.BeginAccess
- Slice.Sub
- SpatialTiling.Validate
- StagedCopyFixture
- StagedCopyFixtureSource
- TMAGather4Spec
- TMASwizzleLayout
- Tile (Accessors)
- Tile.Compatible
- Tile.Index
- Tile.Owner
- Tile.TransposeOwners
- TopK.Artifact
- TopK.Close
- TopK.Execute
- TopKBF16.Artifact
- TopKBF16.Close
- TopKBF16.Execute
- TopKConfig.Extents
- TopKSchema
- ValidateCapacity
- ValidatePTX
- XORSwizzle.Apply
- XORSwizzle.CheckDevice
- XORSwizzle.Compose
- ZippedDivide
Constants ¶
const ( ArchSM90 = "sm_90" ArchSM90a = "sm_90a" ArchSM100 = "sm_100" ArchSM100a = "sm_100a" ArchSM107 = "sm_107" ArchSM107a = "sm_107a" ArchSM121a = "sm_121a" )
Supported GPU architecture identifiers.
const ( FeatureTMA = "tma" FeatureMBarrier = "mbarrier" FeatureMultimem = "multimem" FeatureWGMMA = "wgmma" FeatureTCGen05 = "tcgen05" FeatureTMEM = "tmem" )
Feature identifiers for PTX / GPU instructions and hardware capabilities.
const ( BlackwellTMEMCapacityBytes = 256 * 1024 // 256 KiB capacity per SM (512 columns * 512 bytes) BlackwellTMEMColumns = 512 // Total addressable TMEM columns per SM BlackwellTMEMBytesPerCol = 512 // 512 bytes per column (128 rows * 4 bytes) BlackwellTMEMAllocUnitCols = 32 // Column allocation granularity (32 columns = 16 KiB) BlackwellTMEMMinAlignBytes = 16 // 16-byte minimum alignment required for bulk async copy )
Architectural limits and dimensions for Blackwell Tensor Memory (TMEM).
const ( TargetSM90a = "sm_90a" TargetSM120a = "sm_120a" )
const ( ScopeSubwarp = cudahazard.ScopeSubwarp ScopeWarp = cudahazard.ScopeWarp ScopeCTA = cudahazard.ScopeCTA ScopeCluster = cudahazard.ScopeCluster ScopeDevice = cudahazard.ScopeDevice ScopeHostDevice = cudahazard.ScopeHostDevice ScopeMultiGPU = cudahazard.ScopeMultiGPU )
const ( MemoryDSMEM = cudahazard.MemoryDSMEM MemoryGlobal = cudahazard.MemoryGlobal MemoryUnified = cudahazard.MemoryUnified )
const ( HazardNone = cudahazard.HazardNone HazardReadWrite = cudahazard.HazardReadWrite HazardWriteWrite = cudahazard.HazardWriteWrite HazardWriteRead = cudahazard.HazardWriteRead )
const ( SM121MaxWarpsPerSM = 48 SM121MaxBlocksPerSM = 24 SM121RegAllocQuantumPerWarp = 256 SM121TotalRegsPerSM = 65536 ThreadsPerWarp = 32 )
SM121 (GB10) Hardware Limits: - Max opt-in shared memory per block: 101,376 bytes (102,400 bytes total per SM) - Max warps per SM: 48 - Max blocks per SM: 24 - Register allocation quantum: 256 registers per warp (65,536 registers per SM)
They are constants for callers that need one; the values were probed on a GB10 and are recorded in [cudadevicetable], which a test checks them against.
const ( TargetSM100a = "sm_100a" TargetSM103a = "sm_103a" TargetSM107a = "sm_107a" TargetSM100f = "sm_100f" TargetSM103f = "sm_103f" TargetSM107f = "sm_107f" TargetSM121a = "sm_121a" )
const ( ErrUninitializedBarrier = "uninitialized barrier" ErrDuplicateInit = "duplicate barrier initialization" ErrInvalidatedBarrier = "barrier invalidated" ErrMissingArrive = "missing barrier arrive" ErrMismatchedTxBytes = "mismatched transaction byte count" ErrUnverifiedTxBytes = "unverified transaction byte count" ErrInvalidTxBytes = "invalid transaction byte count" ErrUnexpectedTx = "unexpected transaction without expect_tx" ErrPhaseParity = "phase parity mismatch" ErrInvalidParity = "invalid parity value" ErrTMEMCapacityExceeded = "TMEM capacity exceeded" ErrInvalidTMEMColumns = "invalid TMEM column count" ErrUnsupportedTMEM = "unsupported TMEM operation on architecture" ErrUnsupportedControlFlow = "unsupported control flow across barrier protocol" ErrInvalidBulkTMEMPTX = "invalid bulk async TMEM PTX instruction" ErrInvalidClusterMulticast = "invalid cluster multicast instruction" ErrStageIndexOutOfBounds = "stage index out of bounds" ErrStageOverwrite = "stage buffer overwritten before consumer release" ErrStageNotReady = "stage consumed or released before ready" ErrEpochReuseStale = "stale epoch reused" ErrBarrierPhaseParity = "barrier phase parity mismatch" ErrTransactionUnderflow = "transaction bytes underflow" ErrExceededSMEMLimit = "shared memory exceeds limit" ErrExceededWarpsPerSM = "warps per SM exceeds limit" ErrExceededBlocksPerSM = "blocks per SM exceeds limit" ErrInvalidRegisterQuantum = "registers per warp must align to 256 quantum" )
Violation kinds identified during static pipeline analysis.
const Header = `` /* 5989-byte string literal not displayed */
Header is the embedded CUDA C++ header defining warp and block collective primitives.
const MaxColumnsExclusive = 576
MaxColumnsExclusive is the largest tcgen05.alloc.exclusive column count, available only on sm_107a/sm_107f (PTX ISA 9.4 section 9.7.18.7.1, Table 58); sm_100 and sm_103 exclusive allocations are limited to 512 columns.
const MaxRank = 5
MaxRank is the greatest tensor rank a tiled tensor map admits.
const TopKBF16Source = `` /* 1716-byte string literal not displayed */
TopKBF16Source implements ordinary selection from BF16 storage. Conversion copies each uint16 into the high half of an FP32 word; it never rounds or reinterprets input as FP16. Optional values are FP32 decoded source values.
const TopKSource = `` /* 1653-byte string literal not displayed */
TopKSource is an independently written ordinary CUDA repeated-selection baseline. One thread processes each row; no TMA or cluster support is assumed. DeepSelect bfa4507d935f17ebfc3d0f00ff7d3c9a4d0e5c18 was consulted for its interface and short-row caveats; no implementation was copied.
Variables ¶
var ( // ErrUnsupported reports that an instrument examined the target and // refused. It is a measurement. ErrClusterUnsupported = cuda.ErrUnsupported // ErrHardwarePending reports that no instrument has examined the // target, so support is unknown. It is the absence of a measurement and // must never be reported as a negative one. ErrHardwarePending = cuda.ErrHardwarePending )
The capability sentinels live in cudaerrors, because four lanes in three unrelated areas answer the same question and none of them should import a cluster package for an error value. These aliases exist so that callers of this package can match without a second import; the definitions and the contract are there, not here.
var ( // ErrWriteAfterWrite reports differing source addresses for one destination. ErrWriteAfterWrite = errors.New("copy has a write-after-write alias") // ErrNullspaceInvariant reports a nullspace coordinate with nonzero destination offset. ErrNullspaceInvariant = errors.New("destination nullspace has a nonzero offset") // ErrCopySizeMismatch reports layouts or slices with incompatible sizes. ErrCopySizeMismatch = errors.New("copy size mismatch") )
var ( // ErrUnsupported indicates an unsupported or invalid layout description. // // It is the general case. Two refinements wrap it, so a caller that does // not care about the distinction can keep testing for ErrUnsupported // alone: [ErrUnmodeled] and [ErrUninitialized]. ErrUnsupported = errors.New("unsupported layout") // ErrUnmodeled indicates a layout the hardware has and this package does // not describe. It is not the same as a layout that does not exist: the // caller's description is fine and the work has not been done here. // // That is an actionable difference. A caller meeting ErrUnsupported has a // bug; a caller meeting ErrUnmodeled has a dependency. ErrUnmodeled = fmt.Errorf("%w: not modeled", ErrUnsupported) // ErrUninitialized indicates a zero value that never passed through its // constructor, so it describes no layout at all. Constructors are the only // way to build a valid Tile, Fragment or SwizzledTile, and a zero value // reaching a method is a programming error rather than an unsupported // description. ErrUninitialized = fmt.Errorf("%w: not constructed", ErrUnsupported) // ErrOverflow indicates a host integer or shape address-limit overflow. ErrOverflow = errors.New("layout arithmetic overflow") // ErrOutOfBounds indicates a logical element or register slot outside a tile. ErrOutOfBounds = errors.New("logical index out of bounds") )
var ( // ErrInFlight reports an update to a descriptor that transfers issued // from it are still reading. ErrInFlight = errors.New("descriptor has transfers in flight") // ErrStaleGeneration reports a handle or issue request naming a // generation the slot has since replaced. ErrStaleGeneration = errors.New("stale descriptor generation") // ErrFutureGeneration reports an issue request naming a generation the // slot has not reached. ErrFutureGeneration = errors.New("future descriptor generation") // ErrDescriptorMismatch reports a transfer whose descriptor differs from // the one the slot holds at the requested generation. ErrDescriptorMismatch = errors.New("descriptor differs from slot") // ErrNotInFlight reports a completion for a transfer that was already // completed. ErrNotInFlight = errors.New("transfer not in flight") // ErrForeignHandle reports a handle that the slot did not issue, // including the zero TransferHandle. ErrForeignHandle = errors.New("handle not issued by this slot") )
Errors reported by DescriptorSlot.
var ( // ErrCapacityExceeded indicates a tile factorization exceeds hardware storage limits. ErrCapacityExceeded = fmt.Errorf("%w: capacity constraint exceeded", ErrUnsupported) // ErrAlignmentFailed indicates a tile factorization violates hardware alignment requirements. ErrAlignmentFailed = fmt.Errorf("%w: alignment constraint failed", ErrUnsupported) )
var ( // ErrWrappingPartition indicates a partition shape whose bounds wrap into adjacent dimensions. ErrWrappingPartition = errors.New("cudalayout: wrapping partition shape") // ErrOverlappingPartition indicates partition strides that permit overlapping tile offsets across blocks. ErrOverlappingPartition = errors.New("cudalayout: overlapping partition tiles") // ErrInvalidPartition indicates an invalid partition configuration. ErrInvalidPartition = errors.New("cudalayout: invalid partition") )
var ( // ErrGridMismatch is returned when inferred partition grids or explicit grids do not match. ErrGridMismatch = cuda.ErrGridMismatch // ErrClusterGridMismatch is returned when the inferred grid is not divisible by the cluster dimension. ErrClusterGridMismatch = cuda.ErrClusterGridMismatch )
var ( ErrUnsupportedTarget = errors.New("cudatmem: target does not support tmem") ErrInvalidUnit = errors.New("cudatmem: invalid allocation unit") ErrPermission = errors.New("cudatmem: allocation permission required") ErrParticipation = errors.New("cudatmem: collective participation mismatch") ErrBusy = errors.New("cudatmem: allocation still has asynchronous users") ErrClosed = errors.New("cudatmem: allocator is closed") )
var ( ErrSingleThreadIssue = errors.New("cudatmem: mma/cp/commit/shift require ActiveThreads == 1 (elect.sync)") ErrWarpRowPartition = errors.New("cudatmem: ld/st violates 4-warp 32-row datapath partition") ErrScaleNotStaged = errors.New("cudatmem: block-scale mma requires prior tcgen05.cp into scale tmem") ErrOperandANotReady = errors.New("cudatmem: tmem operand A requires prior mma + commit + wait") ErrCTA2Protocol = errors.New("cudatmem: cta_group::2 cooperative lifecycle violation") )
var ErrDuplicateCompletion = errors.New("duplicate completion")
ErrDuplicateCompletion reports a second completion from a multicast destination rank that has already completed.
var ErrTopKUnsupported = errors.New("cudablock: unsupported topk configuration")
ErrTopKUnsupported reports a row count, width or K outside the initial domain.
Functions ¶
func AuditTensormapReplaceAllocClass ¶
AuditTensormapReplaceAllocClass checks all instructions in m for PTX 9.5 tensormap.replace.tile.global_address, cp.async.bulk.wait_group, and cp.async.bulk.prefetch rules:
- Any tensormap.replace instruction modifying global_address must include an explicit .alloc_small, .alloc_large, or .alloc_same qualifier (PTX ISA 9.5 Section 9.7.10.29) so it does not silently reset the descriptor allocation class to Small.
- Any cp.async.bulk.wait_group instruction with .sync_restrict::proxy::async (PTX ISA 9.5 Section 9.7.10.28.6.2) must not also specify .read, and must not execute while a preceding .bulk_group transfer is uncommitted (before its cp.async.bulk.commit_group).
- Any cp.async.bulk.prefetch instruction must use the concrete .L2::cache_hint modifier rather than the grammar placeholder .level::cache_hint.
Example ¶
package main
import (
"fmt"
isa_ptx "github.com/tmc/lib/nvidia/x/isa/ptx"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
inst, err := layout.EmitReplaceGlobalAddress("%rd1", "%rd2", layout.AllocLarge)
if err != nil {
panic(err)
}
src := ".version 9.5\n.target sm_121a\n.address_size 64\n.visible .entry k() {\n\t" + inst + "\n\tret;\n}\n"
m, err := isa_ptx.ParseString(src)
if err != nil {
panic(err)
}
fmt.Println(layout.AuditTensormapReplaceAllocClass(m) == nil)
}
Output: true
func BindPartitionArgs ¶
BindPartitionArgs returns the pointer, all non-innermost strides in axis order, then every partition extent in axis order.
func BindPartitionArgs32 ¶
BindPartitionArgs32 returns the same arguments as BindPartitionArgs using int32 strides and extents. It errors if any value does not fit.
func BindPartitionMutArgs ¶
func BindPartitionMutArgs(p PartitionMut) []any
BindPartitionMutArgs returns the pointer, non-innermost strides, and tile extents.
func BindPartitionMutArgs32 ¶
func BindPartitionMutArgs32(p PartitionMut) ([]any, error)
BindPartitionMutArgs32 returns the same arguments using int32 values and errors if any stride or extent does not fit.
func BulkWaitGroup ¶
BulkWaitGroup emits cp.async.bulk.wait_group, which waits until at most pending bulk async-groups committed by the executing thread are still in flight. With read set it waits only until those groups have finished reading their shared-memory sources (the .read modifier), which is enough to reuse a TMA store's staging buffer but does not make the writes visible in global memory. This is Gluon's tma.store_wait(pending, read_only).
Pending counts above 63 are refused by policy rather than by a PTX syntax limit: ptxas saturates constants above 63 to DEPBAR.LE SB0, 0x3f (which conservatively waits for more groups), so refusing pending > 63 avoids silently clamping the caller's bound.
func ByteRangeOverlap ¶
ByteRangeOverlap reports whether two byte intervals [aOffset, aOffset+aSize) and [bOffset, bOffset+bSize) intersect.
func CanonicalArch ¶
CanonicalArch normalizes an architecture string like "sm90", "SM_121A", or "sm_121a" into canonical form.
func Check ¶
Check reports whether target may be used for cluster work.
It requires two independent things to agree: the capability fence, which is documented and lexical, and the recorded assembler fact, which is measured. Either one alone has been wrong in this corpus, so neither is trusted alone.
It returns ErrUnsupported when an instrument refused the target, ErrHardwarePending when none has looked, and nil when the target is recorded as accepting clusters. A nil result is permission to attempt a run, not evidence that a run succeeded.
func CheckClusterHardware ¶
CheckClusterHardware checks whether the target architecture supports thread block clusters and DSMEM.
func CheckDSMEM ¶
CheckDSMEM reports whether target may be used for distributed shared memory specifically, and it currently returns ErrHardwarePending for every target.
This is not an oversight. The device table's "cluster" fixture asserts the cluster barrier and %cluster_ctarank; it contains no mapa.shared::cluster and no ld.shared::cluster. So the recorded fact establishes that a target has clusters, and says nothing about whether its assembler accepts a remote shared-memory window. Reporting the cluster fact as a DSMEM answer would be substituting a neighbouring measurement for a missing one.
testdata/dsmem.ptx is the fixture that would settle it, written to the same shape as the existing probes. Assembling it per target and recording the result belongs to the owner of cudadevicetable, not here.
Example ¶
ExampleCheckDSMEM shows that a target with clusters is not thereby a target with a verified remote window.
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
fmt.Println(layout.Check("sm_121a"))
fmt.Println(layout.CheckDSMEM("sm_121a") != nil)
}
Output: <nil> true
func CheckTopKStatus ¶
CheckTopKStatus refuses any nonzero or unknown device status. An empty table is missing evidence, not successful execution.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
fmt.Println(layout.CheckTopKStatus([]int32{0, 0}))
fmt.Println(layout.CheckTopKStatus([]int32{0, int32(layout.TopKNaN)}))
}
Output: <nil> cudablock: topk row 1 device status 1
func Copy ¶
Copy executes all vector transfers first, followed by scalar residuals. The complete plan and slice bounds are checked before the first transfer. Source and destination storage must not overlap.
func EmitArriveExpectTx ¶
EmitArriveExpectTx returns a PTX instruction string arriving on an mbarrier and registering an expected transaction byte count for TMA.
func EmitArriveExpectTxRemote ¶
EmitArriveExpectTxRemote returns an arrive.expect_tx on a barrier in another CTA of the cluster, addressed by a shared::cluster address:
mbarrier.arrive.expect_tx.release.cluster.shared::cluster.b64 _, [mbar], txBytes;
This is Gluon's mbarrier.expect(..., from_cta=...).
func EmitBlockRank ¶
EmitBlockRank returns PTX reading the calling CTA's rank within its cluster into dst, a .u32 register.
Verified: %cluster_ctarank is asserted by cudadevicetable/ptxprobe/cluster.ptx.
func EmitCPAsyncCommitGroup ¶
func EmitCPAsyncCommitGroup() string
EmitCPAsyncCommitGroup returns the cp.async.commit_group that closes the executing thread's current group of cp.async copies.
func EmitCPAsyncMBarrierArrive ¶
EmitCPAsyncMBarrierArrive returns a cp.async.mbarrier.arrive, which makes the barrier at mbarAddr track completion of all prior cp.async copies of the executing thread: an arrive-on is triggered once they land. It replaces commit_group and wait_group when the consumer waits on an mbarrier phase, and is Gluon's ampere.async_copy.mbarrier_arrive.
By default the barrier's pending count is incremented before the asynchronous arrive, so the arrive is net zero against the count given to mbarrier.init. With noinc set it is not, and the arrive consumes one of the expected arrivals (Gluon's increment_count=False).
func EmitCPAsyncWaitGroup ¶
EmitCPAsyncWaitGroup returns a cp.async.wait_group that blocks until at most pending of the executing thread's committed groups are incomplete.
pending must be in [0, 63]. ptxas accepts any immediate, but it lowers the wait to DEPBAR.LE SB0 with a 6-bit count and saturates larger values: for sm_80, N = 64 and N = 1000 both assemble to DEPBAR.LE SB0, 0x3f, the same instruction as N = 63.
func EmitClusterBarrier ¶
EmitClusterBarrier returns a full cluster barrier: every thread of every CTA in the cluster arrives, then waits for all others. With relaxed set the arrive carries no release semantics, so it orders execution but not memory; that is Gluon's cluster.barrier(relaxed=True).
func EmitClusterCTAID ¶
EmitClusterCTAID returns PTX reading the calling CTA's three-dimensional id within its cluster into dst, a .u32 register, for the named dimension.
Not covered by any fixture in this tree.
func EmitClusterNCTAID ¶
EmitClusterNCTAID returns PTX reading the cluster's three-dimensional extent in CTAs into dst, a .u32 register, for the named dimension.
Not covered by any fixture in this tree.
func EmitClusterSize ¶
EmitClusterSize returns PTX reading the number of CTAs in the cluster into dst, a .u32 register.
Not covered by any fixture in this tree. %cluster_nctarank is the ISA spelling for the cluster's CTA count.
func EmitClusterSync ¶
func EmitClusterSync() []string
EmitClusterSync returns the cluster-wide barrier, as the two instructions that this tree has actually assembled.
cudadevicetable/ptxprobe/cluster.ptx asserts barrier.cluster.arrive followed by barrier.cluster.wait, and ptxas accepted that pair for every target at or above sm_90. NVlabs/cuda-oxide's intrinsic table instead names a single barrier.cluster.sync.aligned for cluster_sync(). That form is not assembled anywhere in this tree and is not emitted here. The discrepancy is recorded, not resolved: emitting the unverified spelling to match a secondhand table would trade a measurement for a citation.
Both instructions are cluster-wide and must be executed by every thread of every CTA in the cluster. Placing one inside divergent control flow hangs the cluster.
func EmitFenceProxyAsync ¶
func EmitFenceProxyAsync(space AsyncProxySpace) (string, error)
EmitFenceProxyAsync returns the bidirectional proxy fence that makes generic-proxy writes to space visible to later async-proxy operations, and async-proxy writes visible to later generic accesses. Gluon's fence_async_shared() is AsyncProxySharedCTA and fence_async_shared(cluster=True) is AsyncProxySharedCluster.
func EmitInlineAsmArriveExpectTx ¶
EmitInlineAsmArriveExpectTx returns a CUDA C++ inline assembly snippet for arrive-expect-tx.
func EmitInlineAsmInit ¶
EmitInlineAsmInit returns a CUDA C++ inline assembly snippet initializing an mbarrier at mbarOffset.
func EmitInlineAsmTMA2D ¶
func EmitInlineAsmTMA2D(dstOffset int, descPtrReg, coord0Reg, coord1Reg string, mbarOffset int) string
EmitInlineAsmTMA2D returns a CUDA C++ inline assembly snippet issuing a 2D TMA bulk asynchronous copy.
func EmitInlineAsmTMA2DTMEM ¶
func EmitInlineAsmTMA2DTMEM(dstTmemReg, descPtrReg, coord0Reg, coord1Reg string, mbarOffset int) string
EmitInlineAsmTMA2DTMEM returns a CUDA C++ inline assembly snippet issuing a 2D TMA copy into TMEM.
func EmitInlineAsmTMEMAlloc ¶
EmitInlineAsmTMEMAlloc returns a CUDA C++ inline assembly snippet allocating nCols in TMEM.
func EmitInlineAsmTMEMDealloc ¶
EmitInlineAsmTMEMDealloc returns a CUDA C++ inline assembly snippet deallocating nCols from TMEM.
func EmitInlineAsmWait ¶
EmitInlineAsmWait returns a CUDA C++ inline assembly snippet implementing a spin-wait loop on phase parity.
func EmitMBarrierArrive ¶
EmitMBarrierArrive returns an mbarrier.arrive that performs count arrive-on operations with release semantics.
With remote unset it arrives on a barrier in the executing CTA:
mbarrier.arrive.release.cta.shared::cta.b64 _, [mbar], count;
With remote set, mbarAddr must be a shared::cluster address of a barrier in another CTA of the cluster (from mapa.shared::cluster), and the arrival has cluster scope:
mbarrier.arrive.release.cluster.shared::cluster.b64 _, [mbar], count;
The remote form is what Gluon's mbarrier.arrive(..., from_cta=...) lowers to; the count operand is Gluon's count argument. Both forms need sm_90 or later, as do the other cluster-scope and .relaxed forms below.
func EmitMBarrierExpectTx ¶
EmitMBarrierExpectTx returns an mbarrier.expect_tx that raises the pending transaction count of the barrier's current phase by txBytes without arriving. With remote set, mbarAddr is a shared::cluster address and the operation has cluster scope:
mbarrier.expect_tx.relaxed.cta.shared::cta.b64 [mbar], txBytes; mbarrier.expect_tx.relaxed.cluster.shared::cluster.b64 [mbar], txBytes;
Pair it with a separate arrive when one thread accounts for bytes that several TMA loads deliver; EmitArriveExpectTx does both in one step.
func EmitMBarrierInit ¶
EmitMBarrierInit returns a PTX instruction string initializing an mbarrier in shared memory with the given arrival count.
func EmitMBarrierInvalidate ¶
EmitMBarrierInvalidate returns the mbarrier.inval that ends a barrier's lifetime, after which its shared memory may be reused for other data:
mbarrier.inval.shared::cta.b64 [mbar];
func EmitPrefetchTile2DL2 ¶
EmitPrefetchTile2DL2 emits a PTX 9.5 2D tensor tile L2 prefetch instruction with an .L2::cache_hint eviction policy descriptor:
cp.async.bulk.prefetch.tensor.2d.L2.global.tile.L2::cache_hint [desc, {c0, c1}], policy;
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
ptx, err := layout.EmitPrefetchTile2DL2("%rd1", "%r1", "%r2", "%rd2")
if err != nil {
panic(err)
}
fmt.Println(ptx)
}
Output: cp.async.bulk.prefetch.tensor.2d.L2.global.tile.L2::cache_hint [%rd1, {%r1, %r2}], %rd2;
func EmitQueryAllocClassLarge ¶
EmitQueryAllocClassLarge emits a PTX 9.5 tensormap.query.alloc_class_large instruction reading a 1024-bit tensor map descriptor in .global state space and writing a predicate register:
tensormap.query.alloc_class_large.global.b1024 predicate, [desc];
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
ptx, err := layout.EmitQueryAllocClassLarge("%p1", "%rd1")
if err != nil {
panic(err)
}
fmt.Println(ptx)
}
Output: tensormap.query.alloc_class_large.global.b1024 %p1, [%rd1];
func EmitQueryAllocClassLargeSharedCTA ¶
EmitQueryAllocClassLargeSharedCTA emits a PTX 9.5 tensormap.query.alloc_class_large instruction reading a 1024-bit tensor map descriptor in .shared::cta state space and writing a predicate register:
tensormap.query.alloc_class_large.shared::cta.b1024 predicate, [desc];
func EmitReplaceGlobalAddress ¶
func EmitReplaceGlobalAddress(desc, addr string, class AllocClass) (string, error)
EmitReplaceGlobalAddress emits a PTX 9.5 tensormap.replace.tile.global_address instruction targeting a descriptor in .shared::cta state space with an explicit .alloc_class qualifier:
tensormap.replace.tile.global_address.<class>.shared::cta.b1024.b64 [desc], addr;
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
ptx, err := layout.EmitReplaceGlobalAddress("%rd1", "%rd2", layout.AllocSame)
if err != nil {
panic(err)
}
fmt.Println(ptx)
}
Output: tensormap.replace.tile.global_address.alloc_same.shared::cta.b1024.b64 [%rd1], %rd2;
func EmitReplaceGlobalAddressGlobal ¶
func EmitReplaceGlobalAddressGlobal(desc, addr string, class AllocClass) (string, error)
EmitReplaceGlobalAddressGlobal emits a PTX 9.5 tensormap.replace.tile.global_address instruction targeting a descriptor in .global state space with an explicit .alloc_class qualifier:
tensormap.replace.tile.global_address.<class>.global.b1024.b64 [desc], addr;
func EmitSharedAddr ¶
EmitSharedAddr returns PTX materializing the CTA-local address of a region into dst, a .u32 register, suitable as the base operand of [MapSharedRank].
symbol names the .shared array the plan was laid out over. The region's offset within it is folded in here, so that the mapping call takes an address rather than a number. A shared symbol is materialized with `mov.u32`; a register operand with a nonzero offset uses `add.u32`. Operand text is emitted verbatim, so callers must supply valid PTX operands.
func EmitTMABulkAsync2D ¶
EmitTMABulkAsync2D returns a PTX instruction string issuing a 2D TMA bulk asynchronous copy from global memory to CTA shared memory, signaling completion to an mbarrier.
func EmitTMABulkAsync2DCluster ¶
EmitTMABulkAsync2DCluster returns a PTX instruction string issuing a 2D TMA bulk asynchronous copy targeted across a CTA cluster.
func EmitTMABulkAsync2DTMEM ¶
EmitTMABulkAsync2DTMEM returns a PTX instruction string issuing a 2D TMA bulk asynchronous copy directly from global memory into TMEM, signaling completion to an mbarrier in shared memory.
func EmitTMABulkAsyncTMEM ¶
EmitTMABulkAsyncTMEM returns a PTX instruction string issuing a 1D bulk asynchronous copy directly from global memory into TMEM, signaling completion to an mbarrier in shared memory.
func EmitTMEMAlloc ¶
EmitTMEMAlloc returns a PTX instruction string allocating nCols of Tensor Memory (TMEM).
func EmitTMEMDealloc ¶
EmitTMEMDealloc returns a PTX instruction string deallocating nCols of Tensor Memory (TMEM).
func EmitTMEMRelinquishPermit ¶
func EmitTMEMRelinquishPermit() string
EmitTMEMRelinquishPermit returns a PTX instruction string relinquishing the TMEM allocation permit.
func EmitWaitGroupAsyncProxy ¶
EmitWaitGroupAsyncProxy emits a PTX 9.5 cp.async.bulk.wait_group instruction with the .sync_restrict::proxy::async qualifier:
cp.async.bulk.wait_group.sync_restrict::proxy::async N;
Per PTX ISA 9.5 Section 9.7.10.28.6.2, .sync_restrict::proxy::async waits only for bulk async-proxy operations without stalling the generic proxy, and cannot be combined with the .read modifier.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
ptx, err := layout.EmitWaitGroupAsyncProxy(0)
if err != nil {
panic(err)
}
fmt.Println(ptx)
}
Output: cp.async.bulk.wait_group.sync_restrict::proxy::async 0;
func EmitWaitLoop ¶
EmitWaitLoop returns a spin-wait loop in PTX using nanosleep to minimize power/replay overhead.
func EmitWaitParity ¶
EmitWaitParity returns a single PTX try_wait instruction testing completion of a phase parity.
func ExpectedReduction ¶
ExpectedReduction returns the total the unmutated fixture must produce: the sum of the distinct per-rank seeds.
func FixtureSource ¶
FixtureSource emits an ordinary synchronous global-to-shared fixture.
func FixtureSourceForTarget ¶
FixtureSourceForTarget emits a checked consumer fixture for an admitted target. The kernel uses row stride and the same bounded XOR swizzle as Index.
Example ¶
t, _ := NewTile(2, 2, 2) source, err := FixtureSourceForTarget(t, TargetSM100a) fmt.Println(err == nil, len(source) > 0)
Output: true true
func FootprintBytes ¶
func FootprintBytes(factors IndexFactorization, bypass DatatypeBypass, dtypes map[TensorRole]int, level StorageLevel) (int, error)
FootprintBytes computes the memory footprint in bytes at level for the given factorization and bypass. It requires exactly the B, M, N and K dimensions and a positive byte size for each tensor role, including bypassed tensors.
func GenerateMutantCUDA ¶
GenerateMutantCUDA returns deliberate source mutants for the native oracle. Both must fail the all-lane populated-output comparison when executed.
func InferLaunchGrid ¶
InferLaunchGrid reconciles an optional caller-specified explicit grid with grids inferred from one or more tensor partitions.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/host/shape"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
tensorShape, err := shape.New(1024, 2048)
if err != nil {
panic(err)
}
tileShape, err := shape.New(64, 128)
if err != nil {
panic(err)
}
partA, err := layout.NewPartition(driver.DevicePtr(0x1000), tensorShape, tileShape, 4)
if err != nil {
panic(err)
}
partB, err := layout.NewPartition(driver.DevicePtr(0x2000), tensorShape, tileShape, 4)
if err != nil {
panic(err)
}
grid, err := layout.InferLaunchGrid(shape.Grid3D{}, []layout.Partition{partA, partB})
if err != nil {
panic(err)
}
fmt.Printf("inferred grid: %s\n", grid)
}
Output: inferred grid: (16, 16, 1)
func MulticastSource ¶
MulticastSource emits a real two-CTA, two-dimensional FP32 fixture. Both CTAs receive a 128-byte tile. Launch one 2x1x1 cluster with 136 shared bytes, encode the returned fixture's equivalent tensor map, and pass coordinates (0, 0). Compiler and native qualification are separate from emission.
func NormalizeUnsetNUMA ¶
NormalizeUnsetNUMA normalizes negative kernel NUMA node sentinels (such as -1 on single-socket or UMA hosts) to 0, leaving non-negative NUMA node indices unchanged.
func PTX95AllocClassFixtureSource ¶
PTX95AllocClassFixtureSource returns a CUDA C++ kernel source string for sm_121a (and sm_100a / sm_103a / sm_120a) that exercises PTX 9.5 tensormap.replace.tile.global_address.<alloc_class> (Section 9.7.10.29), tensormap.query.alloc_class_large, and a chained async-proxy copy synchronized by cp.async.bulk.wait_group.sync_restrict::proxy::async 0 (Section 9.7.10.28.6.2).
Because .sync_restrict::proxy::async orders prior async-proxy accesses before subsequent async-proxy accesses (not generic-proxy loads), the kernel chains:
- First async-proxy write: cp.async.bulk.global.shared::cta.bulk_group from smem_src to bulk_dst in global memory, followed by cp.async.bulk.commit_group.
- Restricted wait: cp.async.bulk.wait_group.sync_restrict::proxy::async 0, ordering the async-proxy write to bulk_dst before the next async-proxy read.
- Second async-proxy read: cp.async.bulk.shared::cta.global.mbarrier::complete_tx::bytes from bulk_dst into a second shared buffer smem_dst, synchronized via mbarrier before reading smem_dst[0] and smem_dst[3].
The device data check on smem_dst[0] and smem_dst[3] is a positive control only: under the R2 ordering mutant (wait before commit_group) the second copy races the first on hardware (unmeasured and not expected to fail reliably on a single run); R2 is rejected statically by AuditTensormapReplaceAllocClass and the PTX text-order check.
The kernel writes six words to out_status:
- out_status[0]: predicate result after .alloc_large replacement (expected 1)
- out_status[1]: predicate result after .alloc_same replacement following .alloc_large (expected 1)
- out_status[2]: predicate result after .alloc_small replacement (expected 0)
- out_status[3]: predicate result after .alloc_same replacement following .alloc_small (expected 0)
- out_status[4]: smem_dst[0] read after the chained async-proxy copy (expected 0x13579bdf)
- out_status[5]: smem_dst[3] read after the chained async-proxy copy (expected 0x76543210)
func ReadProcNvidiaGPUNUMANode ¶
ReadProcNvidiaGPUNUMANode reads the NUMA node for pciBusID from <fsRoot>/proc/driver/nvidia/gpus/<pciBusID>/information, falling back to ReadSysfsPCINUMANode when the procfs information file omits a numeric NUMA Node entry.
func ReadSysfsIBNUMANode ¶
ReadSysfsIBNUMANode reads the raw NUMA node for an InfiniBand HCA from <fsRoot>/sys/class/infiniband/<ibDevName>/device/numa_node.
func ReadSysfsPCINUMANode ¶
ReadSysfsPCINUMANode reads the raw NUMA node for pciBusID from <fsRoot>/sys/bus/pci/devices/<pciBusID>/numa_node (or the nvidia driver sysfs fallback <fsRoot>/sys/bus/pci/drivers/nvidia/<pciBusID>/numa_node). A kernel sentinel of -1 is returned as -1; pass the result to NormalizeUnsetNUMA when a non-negative node index is required.
func ReductionFixture ¶
ReductionFixture returns CUDA C++ for the all-to-one reduction: every CTA in a cluster publishes a distinguishable seed into its own shared window, the cluster synchronizes, and rank 0 reads every peer's window and sums them.
The seeds are distinguishable on purpose. Equal seeds would make a local window and a remote window produce the same total, which is exactly the failure the per-rank values rule out.
clusterSize is compiled in via __cluster_dims__, so an ordinary launch configuration carries the cluster shape. target selects a recorded cluster capability and is checked before the source is generated. Sizes from 2 to 8 are accepted because the fixture does not opt into non-portable clusters.
func SameReductionTree ¶
SameReductionTree reports whether a and b give the same grouping of operands in a binary reduction. Both must be F2-linear bijections from hardware indices to logical indices in [0, Size()), with equal sizes. Hardware bits are ordered from the earliest reduction level to the latest, starting with the least significant bit of the flattened index.
Each entry in levels gives the number of bits in one level. A level with more than one bit must allow arbitrary permutations within that level, as in an unscaled MMA atom. With no levels, each bit is its own level. The comparison requires A⁻¹B to be block upper triangular with invertible diagonal blocks. It does not compare the arithmetic used at each level or the order of a sequential accumulation.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
a, _ := layout.NewLayout(layout.IntShape(4), layout.F2Stride(1, 2))
b, _ := layout.NewLayout(layout.IntShape(4), layout.F2Stride(1, 3))
fmt.Println(layout.SameReductionTree(a, b))
}
Output: true
func StagedCopyFixture ¶
StagedCopyFixture consumes a validated plan region and returns the source plus the dynamic byte count required by the launch contract. Only the dynamic pool is supported, with alignments at most 128 bytes. Target limits are checked independently of the plan's supplied limits. The caller owns input and output buffers through completion. Emitting an alignment declaration does not qualify its compiler or device behavior.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
limits, err := layout.LimitsFromDevice("sm_121a")
if err != nil {
panic(err)
}
p, err := layout.NewPlan(limits)
if err != nil {
panic(err)
}
if _, err := p.Add(layout.Request{Name: "stage0", Size: 260, Alignment: 32, Dynamic: true}); err != nil {
panic(err)
}
src, launchBytes, err := layout.StagedCopyFixture(p, "sm_121a", 65)
if err != nil {
panic(err)
}
fmt.Println(launchBytes, strings.Contains(src, "__align__(32)"))
}
Output: 260 true
func StagedCopyFixtureSource ¶
StagedCopyFixtureSource returns a synchronous global-to-shared-to-global kernel for a bounded host or native compile fixture. It uses no TMA or vendor-specific instructions; native execution remains separately gated. The target must have probed shared-memory limits. The source declares a four-byte-aligned dynamic pool; compiler and device qualification are separate.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
src, err := layout.StagedCopyFixtureSource("sm_121a", 65)
if err != nil {
panic(err)
}
fmt.Println(strings.Contains(src, "__align__(4)"))
}
Output: true
func TMAFixtureSource ¶
TMAFixtureSource emits the documented tensor-map/mbarrier protocol. It is compile-gated because instruction availability and syntax are target and toolkit specific; this source is never treated as native evidence by itself.
Two details of the emitted source are load-bearing and are easy to get wrong in ways that do not announce themselves.
The descriptor parameter is __grid_constant__. Without it the compiler copies all 128 bytes out of parameter space onto the stack and hands cp.async.bulk.tensor a generic address of that copy, which is not where the instruction reads a tensor map from. That version still compiles, so the compile gate cannot see it; [TestTMAFixturePassesTheMapInParamSpace] reads the PTX instead and requires cvta.param.
mbarrier.try_wait.parity writes a predicate, not a 32-bit register. The inline asm therefore declares a .pred and moves it with selp. Naming an "=r" operand as the destination is an arguments mismatch that ptxas rejects outright.
func TileFixtureSource ¶
FixtureSource emits a small CUDA source fixture consuming a physical tile. It is syntax-only until compiled by an explicitly authorized native gate.
func TopKSchema ¶
TopKSchema describes topk_fp32's fixed CUDA parameter ABI.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
s, err := layout.TopKSchema()
fmt.Println(len(s.Params), s.TotalParamBytes, err)
}
Output: 12 80 <nil>
func ValidateCapacity ¶
func ValidateCapacity(factors IndexFactorization, bypass DatatypeBypass, dtypes map[TensorRole]int, limits HardwareConstraints) error
ValidateCapacity checks tile factorizations against target shared memory, register bounds, and TMA alignment constraints.
Example ¶
levels := []StorageLevel{LevelRegister, LevelShared, LevelDRAM}
factors := NewIndexFactorization(levels, map[StorageLevel]map[string]int{
LevelRegister: {"B": 1, "M": 1, "N": 1, "K": 1},
LevelShared: {"B": 1, "M": 4, "N": 4, "K": 4},
LevelDRAM: {"B": 1, "M": 4, "N": 4, "K": 4},
})
err := ValidateCapacity(factors, NewDatatypeBypass(), map[TensorRole]int{
TensorA: 2, TensorB: 2, TensorC: 4,
}, HardwareConstraints{MaxSharedMemoryPerBlock: 1024})
fmt.Println(err)
Output: <nil>
func ValidateCollective ¶
ValidateCollective consumes cudagroup's exact TMEM participation contract.
func ValidateFixture ¶
ValidateFixture checks the required protocol instruction sequence and exact target fence. It is a source-level control, not proof of driver execution.
func ValidateSM121Resources ¶
func ValidateSM121Resources(smemBytesPerBlock int, warpsPerBlock int, blocksPerSM int, registersPerThread int) (ResourceSummary, []ValidationError)
ValidateSM121Resources validates nonnegative resource quantities against strict SM121 (GB10) architectural limits. Zero quantities are allowed; this checks resource demand, not whether an occupancy configuration can be launched. Unrepresentable products or quantum rounding are rejected, not saturated. Limits:
- Shared memory per block must not exceed 101,376 B opt-in limit (and total SM smem <= 102,400 B).
- Warps per SM must not exceed 48 across active blocks.
- Blocks per SM must not exceed 24.
- Register allocation quantum must allocate in multiples of 256 registers per warp.
Types ¶
type Access ¶
type Access struct {
// contains filtered or unexported fields
}
Access owns one declared asynchronous use of a slice. Copies share completion state; Complete consumes that use at most once. The zero value is invalid. Access neither issues an instruction nor observes its device completion.
func (*Access) Complete ¶
Complete declares the caller's asynchronous operation complete. It is idempotent even across copies and concurrent calls, and does not consume another access's use. It does not perform a device wait.
Example ¶
a, ids, p, x, err := exampleAllocation()
if err != nil {
fmt.Println(err)
return
}
s, err := x.Slice(0, 0, 32, 1)
if err != nil {
fmt.Println(err)
return
}
layout, err := tilelayout.NewTile(32, 1, 4)
if err != nil {
fmt.Println(err)
return
}
base, err := s.Address(0, 0)
if err != nil {
fmt.Println(err)
return
}
bases := make([]tilelayout.Address, 32)
for i := range bases {
bases[i] = base
}
use, err := s.BeginAccess(0, layout, ids, bases)
if err != nil {
fmt.Println(err)
return
}
alias := *use
fmt.Println(use.Complete(), alias.Complete())
fmt.Println(a.ReleaseCollective(p, x, ids, columnArgs(32)))
fmt.Println(a.RelinquishCollective(p, ids), a.Close())
Output: <nil> <nil> <nil> <nil> <nil>
type Address ¶
Address is a modeled cell coordinate in the allocator's column pool. It is not a device pointer or an encoded taddr, and does not grant access authority.
type AllocClass ¶
type AllocClass string
AllocClass specifies the PTX 9.5 .alloc_class qualifier for tensormap.replace.tile.global_address.
Per PTX ISA 9.5 Section 9.7.10.29, replacing global_address without an explicit .alloc_class qualifier resets the tensor map's allocation class to Small. Using a derived 4 GiB (32-bit byte-offset) threshold for a single contiguous allocation, Small addresses allocations of <= 4 GiB whereas allocations of > 4 GiB require Large.
const ( // AllocSmall sets the tensor map allocation class to Small (derived // single-allocation threshold <= 4 GiB). AllocSmall AllocClass = "alloc_small" // AllocLarge sets the tensor map allocation class to Large (derived // single-allocation threshold > 4 GiB). AllocLarge AllocClass = "alloc_large" // AllocSame preserves the tensor map's existing allocation class across // a global_address replacement. AllocSame AllocClass = "alloc_same" )
func (AllocClass) String ¶
func (c AllocClass) String() string
String returns the PTX qualifier token without a leading dot.
func (AllocClass) Valid ¶
func (c AllocClass) Valid() bool
Valid reports whether c is one of the PTX 9.5 .alloc_class qualifiers.
type Allocation ¶
type Allocation struct {
// contains filtered or unexported fields
}
Allocation is a TMEM region owned by the permit that allocated it. Rows is the logical row window; tcgen05.alloc allocates columns across all 128 rows (PTX ISA 9.4, section 9.7.18.1.2). Checked users obtain slices and Access handles. Legacy users balance BeginUser and CompleteUser before Release.
func (*Allocation) BeginUser ¶
func (a *Allocation) BeginUser() error
BeginUser starts an unverified legacy user. Checked allocations require Slice.BeginAccess instead.
func (*Allocation) Columns ¶
func (a *Allocation) Columns() uint32
func (*Allocation) CompleteUser ¶
func (a *Allocation) CompleteUser() error
CompleteUser completes an unverified legacy user. Checked allocations require the specific Access.Complete handle instead.
func (*Allocation) Offset ¶
func (a *Allocation) Offset() uint32
func (*Allocation) Rows ¶
func (a *Allocation) Rows() uint32
func (*Allocation) Slice ¶
Slice selects a positive rectangular view within a's logical row window and columns. The origin is relative to a. Legacy allocations are refused.
Example ¶
a, ids, p, x, err := exampleAllocation()
if err != nil {
fmt.Println(err)
return
}
// The hardware allocation is 32 columns; a logical view can be narrower.
s, err := x.Slice(0, 4, 32, 2)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(s.Address(31, 1))
fmt.Println(a.ReleaseCollective(p, x, ids, columnArgs(32)))
_, err = s.Address(0, 0)
fmt.Println(errors.Is(err, tilelayout.ErrClosed))
fmt.Println(a.RelinquishCollective(p, ids), a.Close())
Output: {31 5} <nil> <nil> true <nil> <nil>
type Allocator ¶
type Allocator struct {
// contains filtered or unexported fields
}
Allocator owns a finite target-specific TMEM column pool.
func New ¶
New constructs the legacy, unverified count-only host model. Its permits cannot be used with the checked collective or slice APIs.
func NewCollective ¶
func NewCollective(target Target, c graph.TMEMCollective, launch graph.LaunchRequirements) (*Allocator, error)
NewCollective constructs a checked, nonexclusive group1 model for one CTA on sm_100a. The actual grid must be 1x1x1. A zero launch.Cluster denotes an ordinary launch: only the validation copy is normalized to a singleton cluster so cudagroup can validate its logical CTA rank. This does not change launch, request a physical cluster, or prove native execution.
One execution permit may be acquired, once, to retain the CTA's allocation history and CTA-wide relinquishment. See PTX ISA 9.4, section 9.7.18.7.1: https://docs.nvidia.com/cuda/parallel-thread-execution/index.html.
Example ¶
a, _, err := exampleCollective()
if err != nil {
fmt.Println(err)
return
}
fmt.Println(a.Capability().MaxRows, a.Capability().ColumnUnit)
fmt.Println(a.Close())
Output: 128 32 <nil>
func (*Allocator) AcquireCollectivePermit ¶
AcquireCollectivePermit checks the exact declared issuing warp. The permit is the allocator's sole execution history; even relinquishment cannot reset it.
Example ¶
a, ids, err := exampleCollective()
if err != nil {
fmt.Println(err)
return
}
p, err := a.AcquireCollectivePermit(ids)
fmt.Println(p != nil, err)
fmt.Println(a.RelinquishCollective(p, ids), a.Close())
Output: true <nil> <nil> <nil>
func (*Allocator) AcquirePermit ¶
AcquirePermit starts a legacy execution with a declared participant count. It returns ErrPermission for a checked allocator.
func (*Allocator) Allocate ¶
func (a *Allocator) Allocate(p *Permit, participants, columns, rows uint32) (*Allocation, error)
Allocate allocates a legacy logical row window under p. Checked allocators return ErrPermission; use AllocateCollective for exact issuer admission.
As in PTX ISA 9.4 tcgen05.alloc, the column count must not increase between two allocations in the permit's execution order. The order covers every successful allocation under p, including ones already released, and violations return an error wrapping ErrInvalidUnit. Allocate returns ErrPermission after p has been relinquished.
func (*Allocator) AllocateCollective ¶
func (a *Allocator) AllocateCollective(p *Permit, issuers []graph.Issuer, columns []uint32, rows uint32) (*Allocation, error)
AllocateCollective validates issuing identities and uniform per-issuer column counts before allocating a logical row window. Counts must be legal allocation units and must not increase during the permit's execution.
Example ¶
a, ids, err := exampleCollective()
if err != nil {
fmt.Println(err)
return
}
p, err := a.AcquireCollectivePermit(ids)
if err != nil {
fmt.Println(err)
return
}
x, err := a.AllocateCollective(p, ids, columnArgs(32), 32)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(x.Columns(), x.Rows())
fmt.Println(a.ReleaseCollective(p, x, ids, columnArgs(32)))
fmt.Println(a.RelinquishCollective(p, ids), a.Close())
Output: 32 32 <nil> <nil> <nil>
func (*Allocator) Capability ¶
func (a *Allocator) Capability() TMEMCapability
func (*Allocator) Close ¶
Close closes the allocator. It returns ErrBusy while any permit has not been relinquished or any allocation is live, including an allocation whose permit has been relinquished. Closing a nil or closed allocator is a no-op.
func (*Allocator) EnableExclusive ¶
EnableExclusive enables .exclusive allocation on an empty allocator for a supported tcgen05 target and CTA group.
func (*Allocator) Exclusive ¶
Exclusive reports whether the allocator has 576-column .exclusive mode enabled.
func (*Allocator) Release ¶
func (a *Allocator) Release(p *Permit, x *Allocation, participants uint32) error
Release deallocates x. Only the permit that allocated x may release it, including after that permit has been relinquished; another permit gets ErrPermission. Release returns ErrBusy while x has asynchronous users and ErrClosed if x was already released. Checked allocators return ErrPermission.
func (*Allocator) ReleaseCollective ¶
func (a *Allocator) ReleaseCollective(p *Permit, x *Allocation, issuers []graph.Issuer, columns []uint32) error
ReleaseCollective checks the original column count and issuing identities. The owning permit can deallocate after relinquishment, once all accesses complete. The count-only Release method refuses checked allocations.
Example ¶
a, ids, p, x, err := exampleAllocation()
if err != nil {
fmt.Println(err)
return
}
fmt.Println(a.RelinquishCollective(p, ids))
// Relinquishment forbids new allocations but retains owning deallocation.
fmt.Println(a.ReleaseCollective(p, x, ids, columnArgs(32)), a.Close())
Output: <nil> <nil> <nil>
func (*Allocator) Relinquish ¶
Relinquish revokes p's authority to allocate, as tcgen05.relinquish_alloc_permit does for a CTA. It does not release p's live allocations: p remains their owner and must still release each one. Checked allocators return ErrPermission.
func (*Allocator) RelinquishCollective ¶
RelinquishCollective checks the issuing identities and permanently revokes allocation authority. Existing accesses and owning deallocation remain legal.
Example ¶
a, ids, err := exampleCollective()
if err != nil {
fmt.Println(err)
return
}
p, err := a.AcquireCollectivePermit(ids)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(a.RelinquishCollective(p, ids))
_, err = a.AcquireCollectivePermit(ids)
fmt.Println(err)
fmt.Println(a.Close())
Output: <nil> cudatmem: allocation permission required <nil>
type ArchProfile ¶
type ArchProfile struct {
Name string
// SupportsTMA and the fields below it report whether ptxas assembles the
// construct for this target, not how it performs on silicon.
SupportsTMA bool
SupportsMBarrier bool
SupportsMultimem bool
SupportsWGMMA bool
SupportsTCGen05 bool
SupportsTMEM bool
// FeatureSource names the assembler the Supports fields were read with.
// Empty means this target is not in the probed table and every Supports
// field is an unmeasured false.
FeatureSource string
// Estimated reports that this profile was synthesized for a target the
// tables do not describe. Its alignment fields are the architectural
// constants every target here shares; its Supports fields are unmeasured
// and its TMEM dimensions are zero because nothing said otherwise, not
// because the hardware lacks them.
Estimated bool
MinBufferAlignBytes int
MinBarrierAlignBytes int
MaxBoxWidthBytes int
MaxTMEMCapacityBytes int
MinTMEMAlignBytes int
TMEMBytesPerColumn int
TMEMColumnsPerSM int
TMEMAllocColUnit int
}
ArchProfile describes the architectural capabilities and physical constraints of a target NVIDIA GPU architecture.
The Supports fields are derived at startup from the probed feature table in [cudadevicetable] rather than written here. Hand-written copies of these flags existed in two packages and disagreed: this one had sm_90 supporting wgmma, which ptxas rejects because wgmma requires the sm_90a target.
func ArchProfileFor ¶
func ArchProfileFor(arch string) (ArchProfile, error)
ArchProfileFor returns the architecture profile for the specified architecture name.
A target neither this package nor the feature table describes gets a profile marked Estimated rather than an error. Refusing would make a GPU released after this code unusable for the work that does not depend on the missing facts, which is most of it; the marker and ProbedArchProfileFor are for the work that does. The argument must still look like a target: "sm_130a" is a plausible future part, "hopper" is a typo, and inventing a profile for a typo helps nobody.
func ProbedArchProfileFor ¶
func ProbedArchProfileFor(arch string) (ArchProfile, error)
ProbedArchProfileFor is ArchProfileFor restricted to targets something has measured. Use it where an estimate would be reported as a fact.
func (ArchProfile) SupportsFeature ¶
func (p ArchProfile) SupportsFeature(feature string) bool
SupportsFeature reports whether the architecture supports the given feature.
func (ArchProfile) ValidateFeature ¶
func (p ArchProfile) ValidateFeature(feature string) error
ValidateFeature returns an error if the specified feature is not supported on this architecture.
The explanation is assembled from the probed table rather than written here. The messages this replaced named the targets a feature requires -- "tcgen05 requires sm_100 or sm_100a", "wgmma is not supported on Blackwell sm_121a" -- and ptxas disagrees with the first of those: tcgen05 needs the sm_100a suffix and is rejected at sm_100. A sentence that restates a capability table drifts from it silently, because nothing reads the sentence.
type AsyncCopyPipeline ¶
type AsyncCopyPipeline struct {
// contains filtered or unexported fields
}
AsyncCopyPipeline models multi-stage producer-consumer asynchronous copy buffers and barriers.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
pipe, err := layout.NewAsyncCopyPipeline(2, 256)
if err != nil {
panic(err)
}
// Issue async copy into stage 0
_ = pipe.IssueCopy(0, 256)
_ = pipe.CommitGroup()
_ = pipe.WaitGroup(0)
// Consumer reads stage 0 after wait_group
_ = pipe.ReadStage(0)
hazards := pipe.CheckHazards()
fmt.Printf("Hazards detected: %d\n", len(hazards))
}
Output: Hazards detected: 0
func NewAsyncCopyPipeline ¶
func NewAsyncCopyPipeline(stages int, stageBytes uint64) (*AsyncCopyPipeline, error)
NewAsyncCopyPipeline initializes an async copy pipeline state machine with the given number of stages.
func (*AsyncCopyPipeline) ArriveExpectTx ¶
func (p *AsyncCopyPipeline) ArriveExpectTx(stage int, txBytes uint64) error
ArriveExpectTx signals mbarrier transaction arrival for TMA / cp.async.bulk.
func (*AsyncCopyPipeline) CheckHazards ¶
func (p *AsyncCopyPipeline) CheckHazards() []PipelineHazard
CheckHazards returns a list of all hazards detected during pipeline execution.
func (*AsyncCopyPipeline) CommitGroup ¶
func (p *AsyncCopyPipeline) CommitGroup() error
CommitGroup commits in-flight cp.async operations into a completion group.
func (*AsyncCopyPipeline) CompleteTx ¶
func (p *AsyncCopyPipeline) CompleteTx(stage int, txBytes uint64) error
CompleteTx signals completion of transferred transaction bytes by TMA.
func (*AsyncCopyPipeline) IssueCopy ¶
func (p *AsyncCopyPipeline) IssueCopy(stage int, bytes uint64) error
IssueCopy marks an async copy issued for the given stage buffer.
func (*AsyncCopyPipeline) NumStages ¶
func (p *AsyncCopyPipeline) NumStages() int
NumStages returns the number of stages in the pipeline.
func (*AsyncCopyPipeline) ReadStage ¶
func (p *AsyncCopyPipeline) ReadStage(stage int) error
ReadStage models a consumer thread reading from a stage buffer.
func (*AsyncCopyPipeline) WaitGroup ¶
func (p *AsyncCopyPipeline) WaitGroup(remaining int) error
WaitGroup waits until at most remaining commit groups are in flight. For cp.async.wait_group N, all groups beyond N are waited on and retired.
func (*AsyncCopyPipeline) WaitParity ¶
func (p *AsyncCopyPipeline) WaitParity(stage int, phase int) error
WaitParity waits for the mbarrier phase parity.
func (*AsyncCopyPipeline) WriteStage ¶
func (p *AsyncCopyPipeline) WriteStage(stage int) error
WriteStage models a producer or thread writing into a stage buffer.
type AsyncProxySpace ¶
type AsyncProxySpace string
AsyncProxySpace selects the state space a fence.proxy.async orders between the generic proxy and the async proxy (TMA, wgmma and tcgen05 operand reads).
const ( AsyncProxyAll AsyncProxySpace = "" AsyncProxyGlobal AsyncProxySpace = "global" )
The state spaces fence.proxy.async admits. AsyncProxyAll leaves the space unqualified and orders all of them.
type AttentionLayout ¶
type AttentionLayout struct {
Keys, HeadDim, TileSize int
Excluded []bool
// FullyMaskedPolicy must be "canonical-nan-exact-fp32" for an
// all-excluded row. Source emission does not qualify device NaN behavior.
FullyMaskedPolicy string
}
AttentionLayout binds a finite row to packed score/value tiles. Each tile contains TileSize score words, then TileSize*HeadDim value words, then zero padding to a 16-byte extent. The final tile's unused keys are not evaluated. Excluded uses true for exclusion; nil includes every key. Callers must prove included scores and all values finite, and excluded scores already -Inf. This layout alone does not prove equivalence to a source graph.
func (AttentionLayout) PayloadBytes ¶
func (l AttentionLayout) PayloadBytes() (int64, error)
PayloadBytes returns the padded extent of one validated tile. Keys, HeadDim and TileSize are bounded to [1,64], with TileSize no greater than Keys.
type Barrier ¶
type Barrier struct {
Offset int // Shared memory offset in bytes (must be 8-byte aligned)
ArrivalCount int // Expected arriving threads/tokens per phase
TransactionBytes int // Total transaction bytes expected via mbarrier.arrive.expect_tx
Phase int // Current phase counter (0, 1, 2, ...)
}
Barrier models the PTX mbarrier state used to synchronize an async pipeline stage.
func (*Barrier) AdvancePhase ¶
func (b *Barrier) AdvancePhase()
AdvancePhase increments the barrier phase counter, toggling parity.
type BarrierEvent ¶
type BarrierEvent struct {
Line int // instruction line number
Opcode string // instruction opcode
Kind BarrierEventKind // event kind
Phase int // barrier phase at time of event
Bytes int64 // bytes expected or completed, if applicable
BytesUnknown bool // byte size could not be resolved; Bytes is not a known zero
Count int // thread arrival count, if applicable
Parity int // parity value, if applicable
}
BarrierEvent records an operation applied to an mbarrier during static analysis.
type BarrierEventKind ¶
type BarrierEventKind string
EventKind identifies an mbarrier lifecycle event during static analysis.
const ( BarrierEventInit BarrierEventKind = "init" BarrierEventInval BarrierEventKind = "inval" BarrierEventExpectTx BarrierEventKind = "expect_tx" BarrierEventArrive BarrierEventKind = "arrive" BarrierEventCopy BarrierEventKind = "copy" BarrierEventWait BarrierEventKind = "wait" )
type BarrierExpectation ¶
type BarrierExpectation struct {
BarrierOffset int
ArrivalCount int // Expected thread arrival tokens (e.g. 1 for warp-specialized leader)
TransactionBytes int64 // Expected transaction byte count from TMA transfer
PhaseParity int // Expected phase parity bit (0 or 1)
}
BarrierExpectation models static mbarrier transaction and arrival counts expected for stage synchronization.
type BarrierOption ¶
type BarrierOption func(*BarrierTracker)
Option configures a BarrierTracker.
func WithAllowLegacyTMEM ¶
func WithAllowLegacyTMEM(allow bool) BarrierOption
WithAllowLegacyTMEM controls whether legacy unverified direct global-to-TMEM bulk copy strings are permitted during static validation (default: false, audit and reject).
func WithBarrierArrivalCount ¶
func WithBarrierArrivalCount(barrier string, count int) BarrierOption
WithBarrierArrivalCount sets the expected arrival count for a barrier if not literal in PTX.
func WithTargetArch ¶
func WithTargetArch(arch string) BarrierOption
WithTargetArch sets the target architecture for static PTX validation.
func WithTensorSize ¶
func WithTensorSize(tensorMap string, bytes int64) BarrierOption
WithTensorSize associates a tensor-map parameter or register name with a known transfer byte size.
type BarrierState ¶
type BarrierState struct {
Name string // symbol or register operand representing the barrier
Initialized bool // true if mbarrier.init was executed
Invalidated bool // true if mbarrier.inval was executed
InitLine int // line number where initialized
ExpectedArrivals int // expected arrival tokens per phase
PendingArrivals int // remaining arrival tokens needed for current phase
Phase int // current primary phase index (0, 1, 2, ...)
ExpectedTxBytes int64 // known valid expected byte subtotal in current phase
CompletedTxBytes int64 // known valid completed byte subtotal in current phase
// A total is unverified after an unresolved, negative or overflowing size.
ExpectedTxBytesUnknown bool
CompletedTxBytesUnknown bool
HasExpectedTx bool // true if an expect_tx operation was executed in current phase
Arrived bool // true if at least one arrive operation was executed in current phase
CopyCount int // number of async copy operations targeting this barrier in current phase
Events []BarrierEvent // chronological history of operations on this barrier
}
BarrierState tracks the lifecycle and transaction state of an individual mbarrier object.
func (*BarrierState) Parity ¶
func (s *BarrierState) Parity() int
Parity returns the current expected phase parity (0 or 1).
func (*BarrierState) TxPending ¶
func (s *BarrierState) TxPending() int64
TxPending subtracts the known completed subtotal from the expected subtotal. It is an exact pending count only when both transaction-byte unknown flags are false. Unknown totals must not be interpreted as a balanced phase.
type BarrierTracker ¶
type BarrierTracker struct {
// contains filtered or unexported fields
}
BarrierTracker tracks mbarrier states, arrival tokens, transaction byte counts, and phase parity across PTX instruction streams.
The zero value is not usable; use NewBarrierTracker.
func NewBarrierTracker ¶
func NewBarrierTracker(opts ...BarrierOption) *BarrierTracker
NewBarrierTracker constructs an initialized BarrierTracker configured with opts.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/isa/ptx"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
tracker := layout.NewBarrierTracker(
layout.WithTensorSize("tensor_a", 2048),
)
tracker.SetTensorSize("tensor_b", 1024)
const src = `
.version 8.8
.target sm_121a
.address_size 64
.visible .entry pipelined_kernel(.param .u64 tensor_b) {
.reg .b64 %rd_b, %state;
.reg .pred %p0;
.shared .align 8 .b64 bar;
ld.param.u64 %rd_b, [tensor_b];
mbarrier.init.shared::cta.b64 [bar], 1;
mbarrier.arrive.expect_tx.shared::cta.b64 %state, [bar], 1024;
cp.async.bulk.tensor.2d.shared::cta.global.mbarrier::complete_tx::bytes [0], [%rd_b, {0, 0}], [bar];
mbarrier.try_wait.parity.shared::cta.b64 %p0, [bar], 0;
ret;
}
`
mod, err := ptx.Parse(strings.NewReader(src))
if err != nil {
panic(err)
}
violations, err := tracker.Validate(mod)
if err != nil {
panic(err)
}
fmt.Printf("Violations: %d, bar phase: %d\n", len(violations), tracker.Barrier("bar").Phase)
}
Output: Violations: 0, bar phase: 1
func (*BarrierTracker) Barrier ¶
func (t *BarrierTracker) Barrier(name string) *BarrierState
Barrier returns the state of the named barrier, or nil if not encountered.
func (*BarrierTracker) Barriers ¶
func (t *BarrierTracker) Barriers() map[string]*BarrierState
Barriers returns a map of all tracked barriers keyed by name.
func (*BarrierTracker) Reset ¶
func (t *BarrierTracker) Reset()
Reset clears the tracker's transient barrier states and registers while preserving configured tensor sizes.
func (*BarrierTracker) SetTensorSize ¶
func (t *BarrierTracker) SetTensorSize(tensorMap string, bytes int64)
SetTensorSize associates a tensor-map parameter or register name with a known transfer byte size.
func (*BarrierTracker) Validate ¶
func (t *BarrierTracker) Validate(mod *ptx.Module) ([]ValidationError, error)
Validate audits all kernel definitions in mod and reports any pipeline or mbarrier protocol violations.
func (*BarrierTracker) ValidateKernel ¶
func (t *BarrierTracker) ValidateKernel(k *ptx.Kernel) ([]ValidationError, error)
ValidateKernel audits a single kernel instruction sequence and reports any pipeline or mbarrier protocol violations.
type Buffer ¶
type Buffer struct {
Space PipelineMemorySpace // Storage tier (MemorySpaceShared or MemorySpaceTMEM; default: MemorySpaceShared)
Offset int // Offset in bytes within the memory space
SizeBytes int // Total allocated byte capacity
Alignment int // Byte alignment of the buffer (must be at least 16)
StrideBytes int // Row stride in memory
}
Buffer models a memory allocation (in shared memory or TMEM) for a single pipeline stage.
type CPAsyncSpec ¶
CPAsyncSpec describes one Ampere-style cp.async copy of Bytes bytes from global to shared memory, the instruction behind Gluon's ampere.async_copy.async_load.
CacheGlobal selects .cg, which bypasses L1 and requires a 16-byte copy; otherwise the copy is .ca. A non-empty SrcSize names a 32-bit register holding how many source bytes to read; the remaining Bytes-SrcSize bytes of the destination are zero-filled. Setting it to 0 for masked-off lanes is how a predicated load is expressed without a branch.
type CTAGroup ¶
type CTAGroup int
CTAGroup identifies a 1-CTA or 2-CTA cooperative tcgen05 allocation group.
type Capability ¶
type Capability int
Capability is a compute capability scaled by ten, so sm_121a is 121 and sm_90 is 90. Comparisons are on this integer; the dotted form is presentation.
func CapabilityOf ¶
func CapabilityOf(target string) (Capability, error)
CapabilityOf parses the compute capability out of an exact PTX target such as "sm_121a".
This is a lexical fact about the target name and nothing more. It does not consult the device table and it does not mean a device of that capability is present. Use it to apply the documented capability fence; use Check to ask what an assembler actually reported.
func (Capability) String ¶
func (c Capability) String() string
String returns the dotted form, such as "12.1".
type Category ¶
type Category string
Category identifies the validation check category.
const ( CatTransactionMismatch Category = "transaction_mismatch" CatPhaseParity Category = "phase_parity" CatLatencyHiding Category = "latency_hiding" CatAlignmentStride Category = "alignment_stride" CatBufferCapacity Category = "buffer_capacity" CatHardwareConstraint Category = "hardware_constraint" )
type Cluster ¶
type Cluster struct {
// contains filtered or unexported fields
}
Cluster is a capability scope for emitting cluster-window operations. Obtain one with Open after the target has passed Check.
func Open ¶
Open returns a scope for a target whose cluster support was measured.
Open gates on Check, which establishes cluster instruction support. It does not establish distributed shared memory support: CheckDSMEM remains pending until a target-specific mapa.shared::cluster probe is recorded. This scope therefore permits emitting a DSMEM attempt, not claiming that the target's assembler or device accepts it.
func (*Cluster) EmitLoadU32 ¶
func (c *Cluster) EmitLoadU32(dst string, p ClusterPtr) (string, error)
EmitLoadU32 returns PTX loading a 32-bit word from a mapped cluster pointer into dst, a .u32 register.
func (*Cluster) EmitReadU32 ¶
func (c *Cluster) EmitReadU32(dst, addr, base string, plan *Plan, region Region, rank string) ([]string, error)
EmitReadU32 returns the combined mapping-and-load sequence for one 32-bit word from the CTA named by the rank register.
It is a convenience over [MapSharedRank] plus [EmitLoadU32] and not a separate mechanism: it emits exactly those two instructions, using addr as a scratch .u32 register for the mapped address. Reach for it when a single word is wanted and the mapping is not reused; reach for the pair when it is.
func (*Cluster) EmitStoreU32 ¶
func (c *Cluster) EmitStoreU32(p ClusterPtr, src string) (string, error)
EmitStoreU32 returns PTX storing a 32-bit word from src, a .u32 register, through a mapped cluster pointer.
It fails on a pointer from [MapSharedRank]. The read-only form exists so that this check is possible.
func (*Cluster) MapSharedRank ¶
func (c *Cluster) MapSharedRank(dst, base string, plan *Plan, region Region, rank string) (string, ClusterPtr, error)
MapSharedRank returns PTX mapping a region of the shared plan into the window of the cluster CTA named by the rank register, and a ClusterPtr describing the result.
dst and rank are .u32 registers; dst receives the mapped address. base is the operand naming the CTA-local shared address to be mapped: a register holding one, as produced by EmitSharedAddr. It is not an offset. mapa takes an address operand, so passing a bare integer emits an instruction that does not assemble -- which is why the region offset is folded into base by EmitSharedAddr rather than emitted here. Operand text is emitted verbatim as PTX; callers must supply valid register operands and ensure the runtime rank is in the cluster.
The returned pointer is read-only: see [MapSharedRankMut] for the writable form.
The mapped address is only meaningful while the target CTA is live. A cluster has no mechanism to keep a peer alive, so the caller must place cluster synchronization appropriate to the data dependency around every use -- see EmitClusterSync. This package does not insert it, because the required placement depends on the dependency and a library that guesses produces either a silent race or a barrier the caller cannot remove.
func (*Cluster) MapSharedRankMut ¶
func (c *Cluster) MapSharedRankMut(dst, base string, plan *Plan, region Region, rank string) (string, ClusterPtr, error)
MapSharedRankMut is [MapSharedRank] for a mapping that will be written through. The emitted instruction is identical; the distinction is carried in the returned pointer so that a store through a read-only mapping is caught before it is emitted.
type ClusterPtr ¶
type ClusterPtr struct {
// contains filtered or unexported fields
}
ClusterPtr names a PTX register holding a pointer into another CTA's shared memory, together with the provenance that makes it checkable.
It is deliberately not a string and deliberately not interchangeable with a CTA-local shared address. A local shared pointer and a mapped cluster pointer live in different address spaces -- 3 and 7 in the LLVM lowering -- and a dereference of one as the other is not a type error in PTX, so it must be a type error here. The zero value is unusable.
func (ClusterPtr) Mutable ¶
func (p ClusterPtr) Mutable() bool
Mutable reports whether the mapping was created for writing.
func (ClusterPtr) Reg ¶
func (p ClusterPtr) Reg() string
Reg returns the PTX register holding the mapped address.
On the zero value it returns ""; ClusterPtr.Valid reports whether p came from a mapping call.
func (ClusterPtr) Region ¶
func (p ClusterPtr) Region() Region
Region returns the CTA-local shared region the mapping was derived from. The region describes the peer CTA's layout, which is the same layout: every CTA in a cluster runs the same kernel with the same shared plan.
func (ClusterPtr) Valid ¶
func (p ClusterPtr) Valid() bool
Valid reports whether p came from a mapping call rather than a zero value.
type Column ¶
type Column uint32
Column counts logical TMEM columns, not bytes or hardware allocation units.
type CopyPlan ¶
type CopyPlan struct {
CommonDomain Layout
SourceResidual Layout
DestinationResidual Layout
Nullspace Layout
CollapseFactor int
VectorWidth int
VectorReason string
ElementCount int
// contains filtered or unexported fields
}
CopyPlan is a checked layout-derived copy plan. Obtain one with PlanCopy; its zero value is invalid. VectorWidth is the size of each vector transfer; residual transfers have size one. CollapseFactor is the greatest number of logical writes collapsed into one destination address.
Example ¶
package main
import (
"fmt"
tilelayout "github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
src, err := tilelayout.ParseLayout("(5,7):(7,1)")
if err != nil {
fmt.Println(err)
return
}
dst, err := tilelayout.ParseLayout("(7,5):(5,1)")
if err != nil {
fmt.Println(err)
return
}
plan, err := tilelayout.PlanCopy(src, dst)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(plan.CommonDomain, plan.SourceResidual, plan.DestinationResidual)
fmt.Println(plan.VectorWidth, plan.VectorReason)
}
Output: (1):(0) (5,7):(7,1) (7,5):(5,1) 1 no unit-stride source run over destination inverse
func CopyWithLayouts ¶
func CopyWithLayouts[T any](dst, src cuda.Slice[T], sourceLayout, destinationLayout Layout) (CopyPlan, error)
CopyWithLayouts plans and copies non-overlapping device slices. Layout and aliasing errors are returned before any device transfer.
func PlanCopy ¶
PlanCopy divides equal-sized layouts by their common domain, collapses the compatible destination's stride-zero nullspace, and orders its remaining coordinates using the destination's right inverse. The coalesced source over that inverse determines a unit-stride vector width. Only compatible coordinates are optimized; incompatible modes retain their iteration order. Vectorization failures yield scalar transfers and a diagnostic reason.
Unlike PyCuTe's stride-zero nullspace check, an additional safety check covers overlapping nonzero strides and aliases between incompatible tiles. Equal source addresses collapse; differing addresses return ErrWriteAfterWrite. ErrNullspaceInvariant is reserved for malformed owner-algebra results. Negative, basis and F2 strides are unsupported by the required algebra. The contiguous-run rule does not choose a particular CUDA instruction.
Example ¶
package main
import (
"fmt"
tilelayout "github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
layout, err := tilelayout.ParseLayout("4:1")
if err != nil {
fmt.Println(err)
return
}
plan, err := tilelayout.PlanCopy(layout, layout)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(plan.VectorWidth, plan.CollapseFactor)
}
Output: 4 1
type DatatypeBypass ¶
type DatatypeBypass struct {
Bypassed map[StorageLevel]map[TensorRole]bool
}
DatatypeBypass specifies per-level tensor retention versus bypass flags.
func NewDatatypeBypass ¶
func NewDatatypeBypass() DatatypeBypass
NewDatatypeBypass creates an empty or initialized datatype bypass map.
func (DatatypeBypass) IsBypassed ¶
func (b DatatypeBypass) IsBypassed(level StorageLevel, role TensorRole) bool
IsBypassed reports whether the given tensor is bypassed at storage level.
func (*DatatypeBypass) SetBypass ¶
func (b *DatatypeBypass) SetBypass(level StorageLevel, role TensorRole, bypassed bool)
SetBypass sets whether the given tensor is bypassed at storage level.
type Descriptor ¶
type Descriptor struct {
Target string
Rank int
Base uint64
Dims [MaxRank]uint64
Strides [MaxRank]uint64
Box [MaxRank]uint32
ElementBytes uint32
ElementType ElementType
Swizzle uint32
Interleave driver.TensorMapInterleave
L2Promotion driver.TensorMapL2promotion
OOBFill driver.TensorMapFloatOOBfill
}
Descriptor is validated tensor metadata. The CUDA Driver API owns creation of the eventual opaque CUtensorMap.
Dims, Strides and Box carry MaxRank entries; only the first Rank of each are read. Strides holds the Rank-1 global strides the driver expects, so Strides[Rank-1] is unused and Descriptor.Validate requires it to be zero.
The zero values of Interleave, L2Promotion and OOBFill select the driver's None for each, which is what the descriptor used before they were selectable.
func (Descriptor) AgreesWithTile ¶
func (d Descriptor) AgreesWithTile(t SwizzledTile) error
AgreesWithTile reports whether a descriptor and a shared tile address the same bytes.
A TMA store writes shared memory in the layout the descriptor names, and register loads read it in the layout the tile names. When the two disagree the result is wrong data, not an error: the hardware has no way to report it and neither side can detect it alone. This is the check that says so.
The comparison lives here rather than on the tile because the box extent is half of it, and a tile knows nothing about a descriptor. [cudalayout] is closed-form arithmetic with no device dependency; keeping the direction of the dependency downward is what lets it stay that way.
Agreement is element width, swizzle mode, and the box extent against the tile's own shape. The descriptor is validated first, because comparing against an unvalidated one compares against nothing.
func (Descriptor) EncodeTiled ¶
func (d Descriptor) EncodeTiled() (*driver.TensorMap, error)
EncodeTiled asks the CUDA Driver API to construct the opaque descriptor. No bytes are packed or interpreted by this package. The driver library must be loaded and expose cuTensorMapEncodeTiled at call time.
func (Descriptor) Validate ¶
func (d Descriptor) Validate() error
type DescriptorSlot ¶
type DescriptorSlot struct {
// contains filtered or unexported fields
}
A DescriptorSlot owns one Descriptor and the transfers issued through it. Each descriptor the slot holds has a generation, starting at 1. Issue records a transfer as in flight under the current generation; Complete retires it. Update installs a new descriptor and generation, and is refused while any transfer issued through the slot is in flight.
The slot is opt-in. It governs only transfers issued through it: a Descriptor or Transfer value used directly, and any tensor map built with Descriptor.EncodeTiled, are outside it and can be changed or reused without the slot knowing.
DescriptorSlot is a host model of descriptor ownership. It does not observe device execution: Complete is called by the host once it has evidence, such as an mbarrier phase, that the transfer finished. Whether native TMA transfers in fact stop reading the descriptor by then is a native gate this type does not check.
A DescriptorSlot is safe for concurrent use. Use NewDescriptorSlot; the zero value is not usable.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
d := layout.Descriptor{
Target: layout.TargetSM121a,
Rank: 2,
Base: 0x1000,
Dims: [layout.MaxRank]uint64{64, 32},
Strides: [layout.MaxRank]uint64{128},
Box: [layout.MaxRank]uint32{64, 1},
ElementBytes: 2,
}
s, err := layout.NewDescriptorSlot(d)
if err != nil {
fmt.Println(err)
return
}
cur, gen := s.Current()
h, _ := s.Issue(gen, layout.Transfer{Descriptor: cur, Direction: layout.GlobalToShared, Bytes: 128})
next := d
next.Base = 0x2000
fmt.Println(errors.Is(s.Update(next), layout.ErrInFlight))
fmt.Println(s.Complete(h))
fmt.Println(errors.Is(s.Complete(h), layout.ErrNotInFlight))
fmt.Println(s.Update(next), s.Generation())
fmt.Println(errors.Is(s.Complete(h), layout.ErrStaleGeneration))
_, err = s.Issue(gen, layout.Transfer{Descriptor: next, Direction: layout.GlobalToShared, Bytes: 128})
fmt.Println(errors.Is(err, layout.ErrStaleGeneration))
}
Output: true <nil> true <nil> 2 true true
func NewDescriptorSlot ¶
func NewDescriptorSlot(d Descriptor) (*DescriptorSlot, error)
NewDescriptorSlot returns a slot owning d at generation 1.
func (*DescriptorSlot) Complete ¶
func (s *DescriptorSlot) Complete(h TransferHandle) error
Complete retires the transfer h names. It returns an error wrapping ErrForeignHandle if this slot did not issue h, ErrStaleGeneration if h was issued under an earlier generation, and ErrNotInFlight if h was already completed.
func (*DescriptorSlot) Current ¶
func (s *DescriptorSlot) Current() (Descriptor, uint64)
Current returns the current descriptor and its generation, read together. Callers building a transfer should take both from one call: separate calls to DescriptorSlot.Descriptor and DescriptorSlot.Generation can straddle an Update and pair a descriptor with the wrong generation.
func (*DescriptorSlot) Descriptor ¶
func (s *DescriptorSlot) Descriptor() Descriptor
Descriptor returns the descriptor of the current generation.
func (*DescriptorSlot) Generation ¶
func (s *DescriptorSlot) Generation() uint64
Generation returns the current descriptor generation.
func (*DescriptorSlot) InFlight ¶
func (s *DescriptorSlot) InFlight() int
InFlight returns the number of transfers issued and not yet completed.
func (*DescriptorSlot) Issue ¶
func (s *DescriptorSlot) Issue(generation uint64, t Transfer) (TransferHandle, error)
Issue validates t and records it as in flight under generation, which must be the slot's current generation, as returned with the descriptor by DescriptorSlot.Current. A request for an earlier generation is refused with ErrStaleGeneration, even if the descriptor was since updated to an equal value, and one for a later generation with ErrFutureGeneration. The transfer's descriptor must equal the current one, or Issue returns an error wrapping ErrDescriptorMismatch.
The generation check is only as strong as the caller's value: a generation read again at issue time, rather than saved with the descriptor, will match whatever the slot holds then.
func (*DescriptorSlot) Update ¶
func (s *DescriptorSlot) Update(d Descriptor) error
Update installs d as a new generation. It returns an error wrapping ErrInFlight, and leaves the slot unchanged, while any transfer issued through the slot has not completed. Transfer sequence numbers continue across generations, so no handle is ever reissued.
type DeviceTopology ¶
type DeviceTopology struct {
DeviceIndex int
PCIBusID string
NUMANode int
NearestIBDev string
IBNUMANode int
}
DeviceTopology describes the host PCIe, NUMA, and InfiniBand HCA affinity of an NVIDIA GPU discovered from Linux procfs and sysfs without calling cuInit.
func DiscoverHostTopology ¶
func DiscoverHostTopology(fsRoot string) ([]DeviceTopology, error)
DiscoverHostTopology discovers NVIDIA GPUs and InfiniBand HCAs under fsRoot using procfs (<fsRoot>/proc/driver/nvidia/gpus/*) and sysfs (<fsRoot>/sys/bus/pci/devices/* and <fsRoot>/sys/class/infiniband/mlx5_*), pairing each GPU with the InfiniBand HCA on the same NUMA node (or the lowest-index HCA as fallback) without initializing CUDA.
Example ¶
package main
import (
"fmt"
"os"
"path/filepath"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
root, err := os.MkdirTemp("", "cudacluster-topo-*")
if err != nil {
fmt.Println("error:", err)
return
}
defer os.RemoveAll(root)
mustWrite := func(rel, data string) {
p := filepath.Join(root, filepath.FromSlash(rel))
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
panic(err)
}
if err := os.WriteFile(p, []byte(data), 0o644); err != nil {
panic(err)
}
}
mustWrite("proc/driver/nvidia/gpus/0000:17:00.0/information", "Model: H800\nNUMA Node: 0\n")
mustWrite("proc/driver/nvidia/gpus/0000:b7:00.0/information", "Model: H800\nNUMA Node: 1\n")
mustWrite("sys/class/infiniband/mlx5_0/device/numa_node", "0\n")
mustWrite("sys/class/infiniband/mlx5_1/device/numa_node", "1\n")
topo, err := layout.DiscoverHostTopology(root)
if err != nil {
fmt.Println("error:", err)
return
}
for _, d := range topo {
fmt.Printf("gpu=%d pci=%s numa=%d ib=%s ib_numa=%d\n",
d.DeviceIndex, d.PCIBusID, d.NUMANode, d.NearestIBDev, d.IBNUMANode)
}
}
Output: gpu=0 pci=0000:17:00.0 numa=0 ib=mlx5_0 ib_numa=0 gpu=1 pci=0000:b7:00.0 numa=1 ib=mlx5_1 ib_numa=1
type ElementType ¶
type ElementType uint8
ElementType names the element format a descriptor encodes. ElementBytes alone cannot distinguish the two-byte float formats, which share a width but not an exponent range, so a bfloat16 tensor has to say so.
const ( ElementTypeDefault ElementType = iota ElementTypeFloat16 ElementTypeBfloat16 ElementTypeFloat32 )
The element formats a tiled tensor map admits here. ElementTypeDefault is the zero value and keeps the format ElementBytes implies on its own: float16 at two bytes and float32 at four.
type EventKind ¶
type EventKind string
EventKind identifies a tcgen05 Tensor Memory lifecycle or datapath operation.
const ( EventAlloc EventKind = "tcgen05.alloc" EventDealloc EventKind = "tcgen05.dealloc" EventCp EventKind = "tcgen05.cp" EventMMA EventKind = "tcgen05.mma" EventCommit EventKind = "tcgen05.commit" EventWait EventKind = "tcgen05.wait" EventLd EventKind = "tcgen05.ld" EventSt EventKind = "tcgen05.st" EventShift EventKind = "tcgen05.shift" EventClusterSync EventKind = "cluster.sync" )
type ExecutionScope ¶
type ExecutionScope = cudahazard.ExecutionScope
ExecutionScope identifies the concurrency level at which memory operations interact.
type Fixture ¶
Fixture is a compile-only generated protocol fixture. PTX text is retained for an authorized toolchain check; this package does not claim execution.
func GenerateFixture ¶
type Fragment ¶
type Fragment struct {
// contains filtered or unexported fields
}
A Fragment is the warp-level register layout of one MMA base tile: how a 16x16 tile is distributed across the 32 lanes of a warp by mma.sync.
A Fragment is keyed by element width and layout because both change the mapping. It is distinct from Tile.Owner, which orders elements linearly and knows neither. Owner remains for callers that want a flat ownership model; a register tile that must agree with an MMA fragment uses a Fragment.
A Fragment is the logical mapping, which is what a load emitter must end up with, not the sequence it takes to get there. ThunderKittens reaches it by permuting the shared addresses of half the lanes for bank reasons and swapping the register halves back afterwards (include/ops/group/memory/tile/shared_to_register.cuh:79 and 100-104). An emitter must reproduce both steps or neither: doing the address permutation without the compensating swap transposes the pairs on half the lanes, and no comparison against this model can detect that, because the model is right.
The zero Fragment is invalid. Construct one with NewFragment.
func NewFragment ¶
func NewFragment(elementBytes int, layout FragmentLayout) (Fragment, error)
NewFragment returns the fragment layout for an element width and layout.
Element widths of 1, 2 and 4 bytes are modeled in the row layout. A one-byte column fragment returns ErrUnmodeled: its base tile is 16x32, so the column layout is not the transpose of a square tile, and no measurement of it exists. That is a gap in the evidence, not an unsupported combination, which is why it is not plain ErrUnsupported.
One byte means one byte of storage. A type whose unit is a pair of 4-bit values also has an element width of 1 and would be admitted here, and this package cannot tell it apart, because a Fragment is keyed on width alone. No such type was measured, and ThunderKittens' own register arithmetic for fp4 under-allocates by 2x, so do not read an fp4 answer out of this.
func (Fragment) Cols ¶
Cols returns the base tile column count. It is 16 at two and four bytes and 32 at one, where ThunderKittens doubles the base tile's column extent (util.cuh: TILE_COL_DIM is BASE_TILE_DIM*2 for a one-byte type).
func (Fragment) Element ¶
func (f Fragment) Element(o FragmentOwner) (row, col int, err error)
Element returns the tile position an owner slot holds. It is the inverse of Fragment.Owner.
func (Fragment) ElementBytes ¶
ElementBytes returns the element width the fragment was built for.
func (Fragment) ElementsPerSlot ¶
ElementsPerSlot returns the elements in one packed slot, along the layout's packed axis: a pair at two and four bytes, a four-vector at one.
The slot count stays 4 across all three widths, so this is the only place the one-byte packing appears. A Fragment that returned 2 here at one byte would report the right Fragment.PackedPerThread and address half the tile.
func (Fragment) ElementsPerThread ¶
ElementsPerThread returns the elements one lane holds: the tile's element count divided over the warp's 32 lanes.
func (Fragment) Layout ¶
func (f Fragment) Layout() FragmentLayout
Layout returns the fragment's layout.
func (Fragment) Owner ¶
func (f Fragment) Owner(row, col int) (FragmentOwner, error)
Owner returns the lane and register position holding the element at row, col.
func (Fragment) PackedPerThread ¶
PackedPerThread returns the packed slots one lane holds.
func (Fragment) RegistersPerThread ¶
RegistersPerThread returns the 32-bit registers one lane holds. A slot of two 16-bit elements occupies one register; a slot of two 32-bit elements occupies two.
type FragmentLayout ¶
type FragmentLayout uint8
FragmentLayout names the register layout of an MMA base tile. The two layouts are transposes of one another, and they differ in the order their packed slots visit the tile, not only in the element each lane starts from.
const ( // FragmentRow is the mma.sync row layout: lane l begins at // row l/4, column 2*(l%4). FragmentRow FragmentLayout = iota // FragmentCol is the column layout: lane l begins at // row 2*(l%4), column l/4. FragmentCol )
func (FragmentLayout) String ¶
func (l FragmentLayout) String() string
type FragmentOwner ¶
type FragmentOwner struct {
// Lane is the owning lane, in [0,32).
Lane int
// Slot is the packed register slot, in [0,PackedPerThread).
Slot int
// Index is the element's position within the packed slot, in
// [0,ElementsPerSlot). A slot is a vector of the packed type --
// ThunderKittens stores dtype data[packed_per_thread] where dtype is
// bf16_2, half_2 or float2 (rt_base.cuh:64-66), or fp8e4m3_4 at one
// byte -- so Index 0 is the .x component and 1 the .y. Whether a slot
// occupies one 32-bit register or two does not appear here; see
// [Fragment.RegistersPerThread], which answers that for occupancy and for
// declaring .reg .b32, not for addressing.
Index int
}
A FragmentOwner identifies the lane and register position holding one element of a fragment.
type HardwareConstraints ¶
type HardwareConstraints struct {
MaxRegistersPerBlock int // 32-bit registers per block
MaxThreadsPerBlock int // threads used to scale the per-thread register tile
TMAAlignmentBytes int // row-stride alignment in bytes
}
HardwareConstraints describes hardware limits for pruning.
type HazardMatrix ¶
type HazardMatrix = cudahazard.HazardMatrix
HazardMatrix tracks concurrent memory operations and classifies hazards across execution scopes.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
m := layout.NewHazardMatrix("sm_90")
// Thread 0 reads byte 0
_ = m.AddAccess(layout.MemoryAccess{
Scope: layout.ScopeCTA,
ThreadID: 0,
Space: layout.MemoryShared,
Offset: 0x1000,
SizeBytes: 1,
IsWrite: false,
Stage: 0,
})
// Thread 32 writes byte 1 (adjacent byte in same 32-bit word)
_ = m.AddAccess(layout.MemoryAccess{
Scope: layout.ScopeCTA,
ThreadID: 32,
Space: layout.MemoryShared,
Offset: 0x1001,
SizeBytes: 1,
IsWrite: true,
Stage: 0,
})
records, err := m.Evaluate()
if err != nil {
panic(err)
}
for _, r := range records {
fmt.Printf("WordConflict=%v ByteConflict=%v IsRace=%v\n", r.WordConflict, r.ByteConflict, r.IsRace)
}
}
Output: WordConflict=true ByteConflict=false IsRace=false
func NewHazardMatrix ¶
func NewHazardMatrix(targetArch string) *HazardMatrix
NewHazardMatrix initializes a hazard matrix for a given target GPU architecture.
type HazardRecord ¶
type HazardRecord = cudahazard.HazardRecord
HazardRecord records an evaluated interaction between two concurrent memory accesses.
type HazardType ¶
type HazardType = cudahazard.HazardType
HazardType classifies memory access conflicts.
type IndexFactorization ¶
type IndexFactorization struct {
Levels []StorageLevel
Factors map[StorageLevel]map[string]int
}
IndexFactorization maps problem dimensions to tiling factors across memory hierarchy levels.
func NewIndexFactorization ¶
func NewIndexFactorization(levels []StorageLevel, factors map[StorageLevel]map[string]int) IndexFactorization
NewIndexFactorization creates an index factorization with the given levels and factors.
func (IndexFactorization) TileShape ¶
func (f IndexFactorization) TileShape(level StorageLevel) map[string]int
TileShape returns the cumulative tile size along each dimension at or below level.
type Issue ¶
type Issue struct {
StageIndex int // Index of the affected stage (-1 for pipeline-wide issues)
Severity Severity // SeverityError or SeverityWarning
Category Category // Issue classification
Message string // Description of the problem and hardware consequence
}
Issue describes a specific problem found during pipeline verification.
func ValidatePhaseParity ¶
ValidatePhaseParity checks a sequence of producer arrival parities and consumer wait parities across pipeline iterations, detecting phase inversions and deadlocks.
type L2CachePolicySpec ¶
type L2CachePolicySpec struct {
PrimaryPolicy L2EvictionPolicy
SecondaryPolicy L2EvictionPolicy
Fraction float32
}
L2CachePolicySpec describes a 64-bit L2 cache eviction policy descriptor constructed by PTX createpolicy.fractional.L2 and passed to TMA transfers via .L2::cache_hint.
For persistent expert weights or KV cache blocks, set PrimaryPolicy to L2EvictLast with Fraction = 1.0. For streaming activations that should not displace resident weights, set PrimaryPolicy to L2EvictFirst (and optionally SecondaryPolicy to L2EvictUnchanged or L2EvictNormal) with a fractional quota such as 0.25.
func (L2CachePolicySpec) FormatPTX ¶
func (s L2CachePolicySpec) FormatPTX(dstReg, srcFractionReg string) (string, error)
FormatPTX emits the PTX createpolicy.fractional instruction writing a 64-bit L2 cache policy descriptor into dstReg from srcFractionReg.
func (L2CachePolicySpec) Validate ¶
func (s L2CachePolicySpec) Validate() error
Validate checks that the policy names and fraction are admitted by PTX createpolicy.fractional.L2.
type L2EvictionPolicy ¶
type L2EvictionPolicy string
L2EvictionPolicy names a PTX L2 cache eviction priority hint used with createpolicy.fractional.L2.
const ( L2EvictNormal L2EvictionPolicy = "evict_normal" L2EvictFirst L2EvictionPolicy = "evict_first" L2EvictLast L2EvictionPolicy = "evict_last" L2EvictUnchanged L2EvictionPolicy = "evict_unchanged" )
type Layout ¶
type Layout struct {
// contains filtered or unexported fields
}
A Layout is a function from coordinates to offsets, given by a hierarchical Shape and a congruent Stride, in the manner of CuTe.
The coordinate space is colexicographic: in an integral index, the first mode varies fastest. An offset is in whatever unit the strides are in; a Layout does not know about elements or bytes. TMASwizzleLayout documents that its offsets are bytes.
The zero Layout is invalid. Construct one with NewLayout, ParseLayout or CompactLayout, or obtain one from the algebra (Coalesce, Composition, Complement, LogicalDivide and the rest).
func Coalesce ¶
Coalesce returns the shortest flat layout computing the same function over integral coordinates as l.
Extent-1 modes are dropped, and adjacent modes merge when the second continues the first: s0:d0 followed by s1:(s0*d0) becomes (s0*s1):d0. Basis modes merge only along the same axis, and adjacent F2 modes always merge. The result is a single mode, or a flat tuple of modes.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
l, _ := layout.ParseLayout("((2,2),(2,3)):((1,2),(8,16))")
fmt.Println(layout.Coalesce(l))
fmt.Println(layout.CoalesceByMode(l))
}
Output: (4,6):(1,8) (4,6):(1,8)
func CoalesceByMode ¶
CoalesceByMode coalesces each top-level mode of l separately. The result has the same rank, so a coordinate given per top-level mode addresses the same offset in both.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
l, _ := layout.ParseLayout("(2,4):(1,2)")
fmt.Println(layout.Coalesce(l), layout.CoalesceByMode(l))
}
Output: 8:1 (2,4):(1,2)
func CompactLayout ¶
CompactLayout returns the colexicographic compact layout of shape: the first mode has stride 1 and each later mode's stride is the product of the extents before it.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
shape, _ := layout.ParseShape("(4,(2,3))")
l, _ := layout.CompactLayout(shape)
fmt.Println(l)
}
Output: (4,(2,3)):(1,(4,8))
func Complement ¶
Complement returns the minimal layout r, ordered by increasing offset, such that the concatenation (l', r) is injective and its size covers cotarget, where l' is l without its stride-0 modes. r addresses exactly the offsets l skips, then repeats l's footprint until the product of the two sizes is at least cotarget. As in CuTe, a stride-0 mode of l contributes nothing to its image and nothing to r.
l must be an integer layout with non-negative strides. Sorted by stride, each mode's stride must be a multiple of the footprint of the modes below it; otherwise no such r exists (l overlaps itself, or leaves holes that no ordered layout can fill), and Complement returns an error.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
l, _ := layout.ParseLayout("(2,2):(1,6)")
r, _ := layout.Complement(l, 24)
fmt.Println(r)
}
Output: (3,2):(2,12)
func ComposeByMode ¶
ComposeByMode composes each of a's first len(tiler) top-level modes with the corresponding tiler layout, and keeps a's remaining modes. It is CuTe's composition with a tuple of layouts as the tiler.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
a, _ := layout.ParseLayout("(12,(4,8)):(59,(13,1))")
t0, _ := layout.ParseLayout("3:4")
t1, _ := layout.ParseLayout("8:2")
r, _ := layout.ComposeByMode(a, []layout.Layout{t0, t1})
fmt.Println(r)
}
Output: (3,(2,4)):(236,(26,1))
func Composition ¶
Composition returns the layout a∘b, whose offset at coordinate i is a's offset at b's offset at i. The result has b's shape, refined where a's modes split it.
b must be an integer layout with non-negative strides. b's offsets are integral coordinates of a; offsets past a.Size() continue a's last mode, as in CuTe. For an integer or basis a the composition exists only under CuTe's divisibility conditions: walking a's coalesced modes, each of b's strides must divide or be divided by the extent it meets (the stride divisibility condition), and the extent split off must divide what remains of b's mode (the shape divisibility condition). b's modes must also not carry into one another when their offsets add in a's coordinates (the additivity condition), since the result evaluates them separately. A violated condition is an error, not an approximation. CuTe and pycute check only some of these conditions, and where they do not they can return a layout that is not a∘b: pycute composes (4,3):(1,8) with 6:1 as 4:1, losing two of b's six offsets.
For an F2 a, b must have power-of-two extents and offsets whose bit images are disjoint, so that b is itself F2-linear, and b's offsets must stay inside a's domain, and a's extents must be powers of two, so that a is F2-linear in its integral coordinate. The result is then an F2 layout.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
a, _ := layout.ParseLayout("(6,2):(8,2)")
b, _ := layout.ParseLayout("(4,3):(3,1)")
r, err := layout.Composition(a, b)
fmt.Println(r, err)
// Stride 4 meets extent 6, which neither divides: rejected rather than
// approximated.
a, _ = layout.ParseLayout("(6,2):(1,7)")
b, _ = layout.ParseLayout("4:4")
_, err = layout.Composition(a, b)
fmt.Println(errors.Is(err, layout.ErrUnsupported))
}
Output: ((2,2),3):((24,2),8) <nil> true
func GreatestCommonDomain ¶
GreatestCommonDomain returns the largest ordered factorization shared by a.Shape() and b.Shape(), with each factor's aligned logical stride. The result depends only on shapes, not on the operands' strides. It is a tiler admissible to both layouts, rather than an inverse of their memory offsets.
As in PyCuTe, the result is a flat tuple, even for a single factor. Shapes with no aligned common factor return (1):(0). Unlike PyCuTe's unbounded integers, an intermediate alignment that exceeds int returns ErrOverflow. Uninitialized layouts return ErrUninitialized.
Example ¶
a, _ := ParseLayout("(6,35):(1,6)")
b, _ := ParseLayout("(15,14):(1,15)")
t, err := GreatestCommonDomain(a, b)
fmt.Println(t, err)
Output: (3,7):(1,30) <nil>
func LogicalDivide ¶
LogicalDivide returns a∘(b, Complement(b, a.Size())): a rank-2 layout whose first mode is the tile b selects from a and whose second mode iterates over the tiles. b is subject to the conditions of Complement and Composition.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
a, _ := layout.ParseLayout("(4,2,3):(2,1,8)")
b, _ := layout.ParseLayout("4:2")
r, _ := layout.LogicalDivide(a, b)
fmt.Println(r)
}
Output: ((2,2),(2,3)):((4,1),(2,8))
func LogicalDivideByMode ¶
LogicalDivideByMode divides each of a's first len(tiler) top-level modes by the corresponding tiler layout, and keeps a's remaining modes.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
a, _ := layout.ParseLayout("(8,8):(1,8)")
tiler, _ := layout.ShapeTiler(4, 2)
r, _ := layout.LogicalDivideByMode(a, tiler)
fmt.Println(r)
}
Output: ((4,2),(2,4)):((1,4),(8,16))
func NewLayout ¶
NewLayout returns the layout shape:stride.
The stride must be congruent with the shape: the same tree, leaf for leaf. Extents must be positive and a tuple must be non-empty. Every leaf with a nonzero contribution must be of one kind; an integer stride of 0 may appear anywhere. An F2 stride's mode must have extent 1<<len(bits) and its bits must be non-negative. The layout's size and every offset it can produce must fit in an int. For basis strides, the coordinate vector length and its size in bytes must also fit in an int.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
l, err := layout.NewLayout(
layout.TupleShape(layout.IntShape(4), layout.IntShape(8)),
layout.TupleStride(layout.IntStride(8), layout.IntStride(1)))
fmt.Println(l, l.Size(), err)
_, err = layout.NewLayout(
layout.TupleShape(layout.IntShape(4), layout.IntShape(8)),
layout.IntStride(1))
fmt.Println(errors.Is(err, layout.ErrUnsupported))
}
Output: (4,8):(8,1) 32 <nil> true
func Nullspace ¶
Nullspace returns the logical coordinates of l's stride-zero modes, flattened in colexicographic order with their original domain strides. It preserves the shape of those modes, including size-one modes, as PyCuTe does. With no stride-zero modes it returns the trivial layout 1:0.
This is the full zero-offset set for nonnegative integer strides. Uninitialized, negative, basis and F2 layouts return an error; PyCuTe supports additional codomains that this operation does not implement.
Example ¶
l, _ := ParseLayout("(2,3,4):(0,1,0)")
n, err := Nullspace(l)
fmt.Println(n, err)
Output: (2,4):(1,6) <nil>
func ParseLayout ¶
ParseLayout parses "shape:stride" in CuTe notation, such as "((4,2),8):((2,16),1)", and checks it with NewLayout.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
l, err := layout.ParseLayout("((2,2),2):((4,1),2)")
if err != nil {
panic(err)
}
for i := range l.Size() {
o, _ := l.Index(i)
fmt.Print(o, " ")
}
fmt.Println()
}
Output: 0 4 1 5 2 6 3 7
func RightInverse ¶
RightInverse returns the largest contiguous right inverse r, with l(r(i)) == i for every i in [0, r.Size()). A layout without a unit-stride start returns the trivial layout 1:0, as PyCuTe does.
This operation supports nonnegative integer strides. Unlike PyCuTe, it returns an error for uninitialized, negative, basis and F2 layouts.
Example ¶
l, _ := ParseLayout("(4,2):(2,1)")
r, err := RightInverse(l)
fmt.Println(r, err)
Output: (2,4):(4,1) <nil>
func ShapeTiler ¶
ShapeTiler returns the by-mode tiler for a shape of integer extents: the layout n:1 for each extent n. This is how CuTe promotes a shape used as a tiler.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
a, _ := layout.ParseLayout("(6,8):(1,6)")
tiler, _ := layout.ShapeTiler(3, 4)
r, _ := layout.ComposeByMode(a, tiler)
fmt.Println(r)
}
Output: (3,4):(1,6)
func TMASwizzleLayout ¶
func TMASwizzleLayout(rows, cols, elementBytes int, mode TMASwizzle) (Layout, error)
TMASwizzleLayout returns the byte-offset layout of a rows x cols tile of elementBytes-byte elements under a tensor-map swizzle mode, as an F2 layout. Its offsets are bytes, and Offset(row, col) equals the SwizzledTile.ByteOffset of the same tile.
Under a swizzle the layout is (rows,(spanCols,groups)):(span,(e,rows*span)) before the XOR, where span is the mode's byte span, e is elementBytes, spanCols = span/e and groups = cols/spanCols: columns are split into spans and each span of every row is stored before the next span begins. Without a swizzle it is the row-major (rows,cols):(cols*e,e).
The tile must be one NewSwizzledTile accepts, and rows, spanCols and groups (cols without a swizzle) must be powers of two, since only then is the layout F2-linear.
Example ¶
The F2 layout of a tensor-map tile addresses the same bytes as SwizzledTile.
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
l, _ := layout.TMASwizzleLayout(8, 64, 2, layout.TMASwizzle128B)
tile, _ := layout.NewSwizzledTile(8, 64, 2, layout.TMASwizzle128B)
a, _ := l.Offset(3, 9)
b, _ := tile.ByteOffset(3, 9)
fmt.Println(a, b)
}
Output: 418 418
func ZippedDivide ¶
ZippedDivide divides a by mode, as LogicalDivideByMode does, and gathers the result into two modes: the tiles, (tile0, tile1, ...), and the rest, (rest0, rest1, ..., the undivided modes of a). Indexing the first mode walks within one tile; indexing the second picks the tile, as a CTA or warp index would.
Example ¶
ZippedDivide gathers the tiles into mode 0 and the tile index into mode 1: Offset(i, k) is element i of tile k.
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
a, _ := layout.ParseLayout("(8,8):(1,8)")
tiler, _ := layout.ShapeTiler(4, 2)
z, _ := layout.ZippedDivide(a, tiler)
o, _ := z.Offset(0, 3)
fmt.Println(z, o)
}
Output: ((4,2),(2,4)):((1,8),(4,16)) 20
func (Layout) BasisOffset ¶
BasisOffset returns the coordinate-valued offset of integral coordinate i for a layout with basis strides, in dst[:n] where n is one more than the largest axis. dst is reused if it is long enough.
Example ¶
A layout with basis strides maps into coordinates: this one is the identity over a 4x6 index space, tiled as (4,(2,3)).
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
l, _ := layout.ParseLayout("(4,(2,3)):(1@0,(1@1,2@1))")
var buf []int
for _, i := range []int{0, 5, 23} {
buf, _ = l.BasisOffset(i, buf)
fmt.Println(buf)
}
}
Output: [0 0] [1 1] [3 5]
func (Layout) Coordinate ¶
Coordinate appends to dst the flattened natural coordinate of integral coordinate i: the colexicographic decomposition of i over the leaf extents, first leaf fastest. It is the inverse of Layout.Offset on the domain.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
l, _ := layout.ParseLayout("((2,2),2):((4,1),2)")
crd, _ := l.Coordinate(5, nil)
fmt.Println(crd)
}
Output: [1 0 1]
func (Layout) Cosize ¶
Cosize returns one more than the largest offset the layout produces, the extent of storage it addresses. It is defined for integer layouts with non-negative strides and for F2 layouts.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
l, _ := layout.ParseLayout("(4,2):(1,8)")
n, _ := l.Cosize()
fmt.Println(l.Size(), n)
}
Output: 8 12
func (Layout) Equal ¶
Equal reports whether two layouts have the same shape and stride trees. Two layouts can be unequal and still compute the same function.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
a, _ := layout.ParseLayout("(2,4):(1,2)")
b, _ := layout.ParseLayout("8:1")
fmt.Println(a.Equal(b), layout.Coalesce(a).Equal(b))
}
Output: false true
func (Layout) Index ¶
Index returns the offset of integral coordinate i, 0 <= i < Size().
It does not allocate. It is defined for integer and F2 layouts; a layout with basis strides has a coordinate-valued codomain and uses Layout.BasisOffset.
func (Layout) Mode ¶
Mode returns top-level mode i as a layout of its own.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
l, _ := layout.ParseLayout("(4,(2,3)):(1,(4,8))")
m, _ := l.Mode(1)
fmt.Println(l.Rank(), m)
}
Output: 2 (2,3):(4,8)
func (Layout) Offset ¶
Offset returns the offset of a coordinate given in one of three forms:
- one integer, an integral coordinate as for Layout.Index;
- Rank() integers, one integral coordinate per top-level mode;
- one integer per leaf, the flattened natural coordinate.
When two forms have the same length they denote the same coordinate. It does not allocate.
Example ¶
Offset takes an integral coordinate, one integer per top-level mode, or one per leaf. All three name the same element here.
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
l, _ := layout.ParseLayout("((2,2),2):((4,1),2)")
a, _ := l.Offset(7)
b, _ := l.Offset(3, 1)
c, _ := l.Offset(1, 1, 1)
fmt.Println(a, b, c)
}
Output: 7 7 7
type Limits ¶
Limits bounds one block's shared allocation. All values are bytes. A zero Limits is intentionally unusable: resource figures must come from the actual target record or an explicitly recorded test target.
func LimitsFromDevice ¶
LimitsFromDevice returns limits only when the embedded record has probed values for the relevant attributes. It never substitutes a neighboring architecture or a documented-but-unmeasured default.
type LoopPermutation ¶
type LoopPermutation struct {
Orders map[StorageLevel][]string
}
LoopPermutation represents loop nest ordering at each storage level.
func NewLoopPermutation ¶
func NewLoopPermutation(orders map[StorageLevel][]string) LoopPermutation
NewLoopPermutation creates a loop permutation specification.
func (LoopPermutation) Validate ¶
func (p LoopPermutation) Validate(dimensions []string) error
Validate checks that each level's order contains the specified dimensions.
type Map ¶
type Map = Allocator
Map aliases Allocator for TMEM column-map capacity modeling.
func NewExclusiveMap ¶
NewExclusiveMap constructs a TMEM column map for .exclusive allocation per PTX ISA 9.4 section 9.7.18.7.1:
tcgen05.alloc.exclusive.cta_group::1.sync.aligned.shared::cta.b32 [sMemAddr], 576;
Exclusive allocation is supported on SM100A, SM103A, SM107A, SM100F, SM103F, and SM107F with either CTA group. An exclusive allocation may request any multiple of 32 columns up to 576 on SM107A/SM107F and up to 512 elsewhere.
type MapSpace ¶
type MapSpace struct {
Problem map[string]int
Factorization IndexFactorization
Permutation LoopPermutation
Spatial SpatialTiling
Bypass DatatypeBypass
}
MapSpace represents a four-axis loop nest decomposition.
type MemoryAccess ¶
type MemoryAccess = cudahazard.MemoryAccess
MemoryAccess describes an individual read or write access.
type MemorySpace ¶
type MemorySpace = cudahazard.MemorySpace
MemorySpace identifies the physical or virtual GPU memory space.
type Multicast ¶
type Multicast struct {
// SourceRank is the source CTA rank recorded at construction. It is a
// descriptive snapshot; methods use the private transaction state.
SourceRank uint32
// Destinations is a sorted copy of the ranks passed to NewMulticast;
// later changes to the caller's slice do not reach it. Value copies of
// a Multicast share this slice's backing array, so an element written
// through one copy is visible through the others. The transaction's
// destinations, byte count and completion state are private,
// synchronized state that this slice never reconfigures.
Destinations []uint32
// Mask is the destination bit mask recorded at construction. It is a
// descriptive snapshot; methods use the private transaction state.
Mask uint64
// Bytes is the byte count recorded at construction. It is a descriptive
// snapshot; methods use the private transaction state.
Bytes uint64
// contains filtered or unexported fields
}
Multicast is a handle for one host-side multicast transaction. Copying a Multicast copies the handle, not the transaction: both values share one completion state. Call NewMulticast to create a separate transaction.
The exported fields are descriptive snapshots from construction. Changing them does not reconfigure the transaction. The zero value is not usable: Complete reports an error, and CompleteAll and Participating report false. Methods synchronize shared completion state across copied handles. Direct concurrent access to the exported fields requires caller synchronization.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
m, _ := layout.NewMulticast(0, []uint32{1, 3}, 64)
copyHandle := m
_ = copyHandle.Complete(1, 64)
fmt.Println(m.CompleteAll())
_ = m.Complete(3, 64)
fmt.Println(copyHandle.CompleteAll())
separate, _ := layout.NewMulticast(0, []uint32{1, 3}, 64)
fmt.Println(separate.CompleteAll())
}
Output: false true false
func NewMulticast ¶
NewMulticast tracks transactions for CTA ranks 0 through 15. The source and every destination must be in that range.
func (*Multicast) Complete ¶
Complete records the transaction for one destination rank. Each rank completes exactly once across all copied handles; concurrent attempts are serialized, and a second completion returns an error wrapping ErrDuplicateCompletion without changing the recorded state.
func (Multicast) CompleteAll ¶
CompleteAll reports whether every constructor destination completed. Completion reads are synchronized across copied handles.
func (Multicast) Participating ¶
Participating reports whether rank was a destination at construction.
type MulticastConfig ¶
type MulticastConfig struct {
Descriptor Descriptor
Coordinates [MaxRank]int32
Cluster [3]uint32
SourceRank uint32
Destinations []uint32
Windows []SharedWindow
}
MulticastConfig describes a one-shot tiled load. Negative Coordinates and tails use the descriptor's zero-fill mode. No driver or device is consulted by NewMulticastPlan.
type MulticastPlan ¶
type MulticastPlan struct {
// contains filtered or unexported fields
}
MulticastPlan owns immutable validated metadata. Its zero value is unusable. It presently establishes physical storage for noninterleaved full-width swizzles and unswizzled boxes. Interleaved and narrow swizzled storage need an independently sourced physical byte-span contract before admission.
func NewMulticastPlan ¶
func NewMulticastPlan(c MulticastConfig) (*MulticastPlan, error)
NewMulticastPlan validates a multicast load without encoding its tensor map. A 16-bit mask represents at most sixteen CTAs; it does not imply that the chosen device admits a cluster of that size.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
"strings"
)
func main() {
d := layout.Descriptor{Target: layout.TargetSM100a, Rank: 1, Base: 0x1000, Dims: [5]uint64{32}, Box: [5]uint32{32}, ElementBytes: 4}
c := layout.MulticastConfig{Descriptor: d, Cluster: [3]uint32{2, 1, 1}, Destinations: []uint32{0, 1}, AvailableSharedBytes: 136, SharedLimitProvenance: "requested fixture allocation"}
for rank := uint32(0); rank < 2; rank++ {
c.Windows = append(c.Windows, layout.SharedWindow{Rank: rank, Descriptor: d, BarrierOffset: 128, ReservedBytes: 136})
}
p, err := layout.NewMulticastPlan(c)
if err != nil {
fmt.Println(err)
return
}
s, _ := p.Source()
r, _ := p.Requirements()
snapshot, _ := p.Descriptor()
fmt.Println(strings.Contains(s, ".multicast::cluster"), r.CTAs, r.TileBytes, r.SharedBytes, snapshot.Rank)
}
Output: true 2 128 136 1
func (*MulticastPlan) Descriptor ¶
func (p *MulticastPlan) Descriptor() (Descriptor, error)
Descriptor returns the tensor-map metadata to pass to EncodeTiled. The caller retains that opaque map and its allocation through stream completion.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func examplePlan() *layout.MulticastPlan {
d := layout.Descriptor{Target: layout.TargetSM100a, Rank: 1, Base: 0x1000, Dims: [5]uint64{32}, Box: [5]uint32{32}, ElementBytes: 4}
c := layout.MulticastConfig{Descriptor: d, Cluster: [3]uint32{1, 1, 1}, Destinations: []uint32{0}, AvailableSharedBytes: 136, SharedLimitProvenance: "requested fixture allocation", Windows: []layout.SharedWindow{{Rank: 0, Descriptor: d, BarrierOffset: 128, ReservedBytes: 136}}}
p, _ := layout.NewMulticastPlan(c)
return p
}
func main() {
d, err := examplePlan().Descriptor()
fmt.Println(err, d.Rank, d.ElementBytes)
}
Output: <nil> 1 4
func (*MulticastPlan) Requirements ¶
func (p *MulticastPlan) Requirements() (MulticastRequirements, error)
Requirements returns a copy of the checked launch contract.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func examplePlan() *layout.MulticastPlan {
d := layout.Descriptor{Target: layout.TargetSM100a, Rank: 1, Base: 0x1000, Dims: [5]uint64{32}, Box: [5]uint32{32}, ElementBytes: 4}
c := layout.MulticastConfig{Descriptor: d, Cluster: [3]uint32{1, 1, 1}, Destinations: []uint32{0}, AvailableSharedBytes: 136, SharedLimitProvenance: "requested fixture allocation", Windows: []layout.SharedWindow{{Rank: 0, Descriptor: d, BarrierOffset: 128, ReservedBytes: 136}}}
p, _ := layout.NewMulticastPlan(c)
return p
}
func main() {
r, err := examplePlan().Requirements()
fmt.Println(err, r.Cluster, r.Mask, r.SharedBytes)
}
Output: <nil> [1 1 1] 1 136
func (*MulticastPlan) Source ¶
func (p *MulticastPlan) Source() (string, error)
Source emits a real one-shot multicast kernel for the checked plan. Launch one cluster, a one-dimensional block of positive size, and SharedBytes of dynamic shared memory. Pass Coordinates in order and an opaque EncodeTiled map made from Descriptor. Output holds CTAs*TileBytes logical-order bytes; unselected output slots retain their caller-provided canaries. Status is published after the final retirement rendezvous. No host completion receipt can substitute for successful stream completion.
This is source emission, not compiler or native qualification. Its opcode and operand widths follow CCCL c339a526 and CUTLASS f614dc40. Swizzle reads use PTX's 128-byte pattern rows with a repeat-boundary-aligned tile base.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
"strings"
)
func examplePlan() *layout.MulticastPlan {
d := layout.Descriptor{Target: layout.TargetSM100a, Rank: 1, Base: 0x1000, Dims: [5]uint64{32}, Box: [5]uint32{32}, ElementBytes: 4}
c := layout.MulticastConfig{Descriptor: d, Cluster: [3]uint32{1, 1, 1}, Destinations: []uint32{0}, AvailableSharedBytes: 136, SharedLimitProvenance: "requested fixture allocation", Windows: []layout.SharedWindow{{Rank: 0, Descriptor: d, BarrierOffset: 128, ReservedBytes: 136}}}
p, _ := layout.NewMulticastPlan(c)
return p
}
func main() {
s, err := examplePlan().Source()
fmt.Println(err, strings.Contains(s, ".multicast::cluster"))
}
Output: <nil> true
type MulticastRequirements ¶
type MulticastRequirements struct {
Coordinates [MaxRank]int32
Cluster [3]uint32
CTAs uint32
Mask uint16
TileBytes uint32
TileOffset uint32
BarrierOffset uint32
OutputBytes uint64
}
MulticastRequirements is the launch contract of a source fixture. Cluster describes exactly one cluster, which must also be the launch grid. SharedBytes must be admitted against the actual target's queried resources. Input, tensor map and output ownership lasts through stream completion and the final cluster rendezvous. Source generation alone proves none of these.
type Mutant ¶
type Mutant string
Mutant names a deliberate defect injected into the reduction fixture.
Each one exists to make a passing test falsifiable. A DSMEM implementation that quietly hands back the calling CTA's own window passes every test that only checks for a plausible number, so the test that would catch it must be shown to fail when the defect is present.
const ( MutantNone Mutant = "" // MutantLocalWindow maps every rank to the calling CTA's own window. // The reduction then sums the local seed cluster_size times instead of // the distinct per-rank seeds, so the expected total is wrong. // TestNativeClusterRemoteWindowIsRemote must fail under it. MutantLocalWindow Mutant = "local-window" // MutantNoSync drops the cluster barrier between publishing a seed and // reading a peer's. The reduction then races. If it still produces the // right total deterministically, the fixture is not exercising a // cross-CTA dependency and proves nothing. MutantNoSync Mutant = "no-sync" )
The mutants. MutantNone is the fixture under test.
type Option ¶
Option configures NewTile.
func WithAlignment ¶
WithAlignment sets the base byte alignment requirement.
func WithStride ¶
WithStride sets the row stride in elements. It must cover the tile width.
func WithSwizzle ¶
WithSwizzle sets the software XOR permutation.
type Partition ¶
type Partition struct {
// contains filtered or unexported fields
}
Partition wraps a physical tensor layout with an explicit tile partition shape, defining how the tensor is mapped to thread blocks in a CUDA launch grid.
func NewPartition ¶
func NewPartition(ptr driver.DevicePtr, tensorShape, partitionShape shape.Shape, elemBytes int, opts ...PartitionOption) (Partition, error)
NewPartition creates a checked immutable tensor partition.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/driver"
"github.com/tmc/lib/nvidia/x/host/shape"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
tensorShape, err := shape.New(1024, 1024)
if err != nil {
panic(err)
}
tileShape, err := shape.New(64, 64)
if err != nil {
panic(err)
}
part, err := layout.NewPartition(driver.DevicePtr(0x1000), tensorShape, tileShape, 4)
if err != nil {
panic(err)
}
grid, err := part.Grid()
if err != nil {
panic(err)
}
fmt.Printf("grid: %s, tile stride: %d\n", grid, part.TileStride())
}
Output: grid: (16, 16, 1), tile stride: 1024
func NewPartitionFromTile ¶
func NewPartitionFromTile(ptr driver.DevicePtr, t Tile, partitionRows, partitionCols int) (Partition, error)
NewPartitionFromTile creates a 2D Partition from an existing Tile and partition dimensions.
func (Partition) ElementBytes ¶
ElementBytes returns the size of each element in bytes.
func (Partition) PartitionShape ¶
PartitionShape returns the tile partition shape.
func (Partition) PartitionStrides ¶
PartitionStrides returns the stride in elements between adjacent block tiles along each axis.
func (Partition) TensorShape ¶
TensorShape returns the full tensor shape.
func (Partition) TileStride ¶
TileStride returns the leading axis stride in elements (strides[0]).
func (Partition) TileStride32 ¶
TileStride32 returns the leading stride when it fits in int32.
func (Partition) ValidateDisjoint ¶
ValidateDisjoint verifies that strides guarantee non-overlapping tile offsets. Kernels must mask each coordinate against its tensor extent before accessing memory. For a partial physical inner axis, the next outer stride must contain the padded grid-by-tile envelope. This is conservative with per-coordinate masking: invalid inner coordinates do not access memory, but their unmasked physical offsets could wrap into an adjacent outer coordinate.
type PartitionMut ¶
type PartitionMut struct {
Partition
}
PartitionMut represents a mutable partitioned tensor view.
func NewPartitionMut ¶
func NewPartitionMut(ptr driver.DevicePtr, tensorShape, partitionShape shape.Shape, elemBytes int, opts ...PartitionOption) (PartitionMut, error)
NewPartitionMut creates a checked mutable tensor partition.
func (PartitionMut) AsReadOnly ¶
func (m PartitionMut) AsReadOnly() Partition
AsReadOnly returns an immutable copy of this partition view.
type PartitionOption ¶
PartitionOption configures NewPartition.
func WithPartitionStrides ¶
func WithPartitionStrides(strides []int) PartitionOption
WithPartitionStrides sets explicit element strides for the tensor.
type Permit ¶
type Permit struct {
// contains filtered or unexported fields
}
Permit models one CTA's tcgen05 allocation permit and the allocation sequence issued under it. Allocations made with a permit are owned by that permit and can be released only through it.
Permit identity is host-side bookkeeping: holding a *Permit does not prove that the corresponding device warp participates in the collective. New uses unverified participant counts. NewCollective checks the declared issuer identities; neither constructor observes device execution.
type PhysicalIndex ¶
type PhysicalIndex struct{ Row, Col, ElementOffset, ByteOffset int }
PhysicalIndex identifies one logical element in storage. ByteOffset is relative to the tile base; ElementOffset is the unswizzled element offset.
type Pipeline ¶
type Pipeline struct {
Config PipelineConfig
Stages []Stage
Arch ArchProfile
}
Pipeline models a multi-stage producer-consumer asynchronous memory pipeline synchronized with PTX transaction barriers.
func NewPipeline ¶
func NewPipeline(cfg PipelineConfig) (*Pipeline, error)
NewPipeline constructs a multi-stage pipeline from the given configuration, calculating memory layout and initializing stage barriers.
Example ¶
package main
import (
"fmt"
"log"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
box := layout.TMABox{
DimX: 64,
DimY: 32,
ElementSize: 2,
}
pipe, err := layout.NewPipeline(layout.PipelineConfig{
TargetArch: layout.ArchSM121a,
NumStages: 3,
Box: box,
MemoryLatencyCycles: 600,
ComputeIntervalCycles: 300,
})
if err != nil {
log.Fatal(err)
}
report := pipe.Validate()
fmt.Printf("Valid: %t\n", report.Valid())
fmt.Printf("Stages: %d\n", pipe.NumStages())
fmt.Printf("Stage 0 Payload: %d bytes\n", pipe.Stage(0).TMABox.PayloadBytes())
}
Output: Valid: true Stages: 3 Stage 0 Payload: 4096 bytes
Example (Tmem) ¶
package main
import (
"fmt"
"log"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
box := layout.TMABox{
DimX: 64,
DimY: 16,
ElementSize: 2, // 2048 bytes per stage
}
pipe, err := layout.NewPipeline(layout.PipelineConfig{
TargetArch: layout.ArchSM100a,
NumStages: 3,
MemorySpace: layout.MemorySpaceTMEM,
Box: box,
})
if err != nil {
log.Fatal(err)
}
report := pipe.Validate()
fmt.Printf("Valid: %t\n", report.Valid())
fmt.Printf("Stages: %d\n", pipe.NumStages())
fmt.Printf("Space: %s\n", pipe.Stage(0).Buffer.Space)
fmt.Printf("Total TMEM: %d bytes\n", pipe.TotalTMEMBytes())
fmt.Printf("TMEM Columns: %d\n", pipe.TotalTMEMColumns())
}
Output: Valid: true Stages: 3 Space: tmem Total TMEM: 6144 bytes TMEM Columns: 32
func (*Pipeline) EmitEpilogPTX ¶
EmitEpilogPTX generates PTX sequence to deallocate TMEM columns if the pipeline targeted TMEM.
func (*Pipeline) EmitPrologPTX ¶
EmitPrologPTX generates PTX sequence to initialize all stage mbarriers in the pipeline and, if targeting TMEM, allocates the required TMEM columns.
func (*Pipeline) EmitStageLoadPTX ¶
EmitStageLoadPTX generates PTX instructions to issue an asynchronous TMA load for the given stage.
func (*Pipeline) EmitStageWaitPTX ¶
EmitStageWaitPTX generates PTX instructions to wait for completion of the given stage.
func (*Pipeline) Simulate ¶
func (p *Pipeline) Simulate(iterations int) (*SimulationTrace, error)
Simulate executes an in-memory simulation of producer and consumer steps across the specified number of iterations, verifying that no deadlocks, phase inversions, or buffer overruns occur.
func (*Pipeline) TotalSharedBytes ¶
TotalSharedBytes returns the total shared memory span in bytes occupied by stage buffers (if residing in shared memory) and stage barriers in the pipeline.
func (*Pipeline) TotalTMEMBytes ¶
TotalTMEMBytes returns the total TMEM span in bytes occupied by stage buffers in the pipeline, or 0 if no stage resides in TMEM.
func (*Pipeline) TotalTMEMColumns ¶
TotalTMEMColumns returns the number of 512-byte TMEM columns required to hold all TMEM stages in the pipeline, rounded up to the hardware allocation unit.
type PipelineConfig ¶
type PipelineConfig struct {
TargetArch string // Target GPU architecture (e.g. ArchSM90, ArchSM100, ArchSM121a)
NumStages int // Number of pipeline stages (>= 2 for multi-stage buffering)
Box TMABox // TMA 2D box configuration for each stage
MemorySpace PipelineMemorySpace // Target memory space (MemorySpaceShared or MemorySpaceTMEM; default: MemorySpaceShared)
TMEMBaseOffset int // Base TMEM byte offset for stage buffers (when MemorySpace == MemorySpaceTMEM)
BarrierBaseOffset int // Base shared memory offset for mbarriers (always in shared memory)
ArrivalTokensPerStage int // Arriving threads/tokens per stage (default: 1)
MemoryLatencyCycles int // Estimated round-trip memory latency in clock cycles (e.g. 600)
ComputeIntervalCycles int // Estimated compute duration per stage in clock cycles (e.g. 300)
}
PipelineConfig specifies parameters for constructing a multi-stage pipeline.
type PipelineHazard ¶
PipelineHazard represents an ordering or synchronization defect in an asynchronous copy pipeline.
type PipelineMemorySpace ¶
type PipelineMemorySpace string
MemorySpace identifies the physical or logical storage tier targeted by a pipeline buffer.
const ( MemorySpaceGlobal PipelineMemorySpace = "global" MemorySpaceTMEM PipelineMemorySpace = "tmem" )
type PipelineScenario ¶
type PipelineScenario struct {
Name string
Fixed bool
IsTMA bool
NumStages int
StageBytes uint64
HasHazards bool
Hazards []PipelineHazard
Description string
}
PipelineScenario describes a configured test sequence evaluating async copy races.
func GenerateAsyncCopyScenario ¶
func GenerateAsyncCopyScenario(fixed bool) (PipelineScenario, error)
GenerateAsyncCopyScenario constructs a synthetic cp.async pipeline sequence modeling cuHadron memcpy races. When fixed is false, the required commit/wait_group synchronization is omitted, triggering a RAW hazard. When fixed is true, proper synchronization is included, resulting in 0 hazards.
func GenerateTMAScenario ¶
func GenerateTMAScenario(fixed bool) (PipelineScenario, error)
GenerateTMAScenario constructs a synthetic TMA cp.async.bulk pipeline sequence modeling cuHadron bulkcpy races. When fixed is false, mbarrier parity wait is omitted before consumer reads, triggering a hazard. When fixed is true, mbarrier transaction expect, completion, and wait are executed cleanly.
func GenerateTMASharedReadWriteScenario ¶
func GenerateTMASharedReadWriteScenario(fixed bool) (PipelineScenario, error)
GenerateTMASharedReadWriteScenario models a bulk copy reading a shared source while CTA threads write it (a WAR hazard), fixed by waiting for the read transaction and synchronizing before the write.
type PipelineSchedule ¶
type PipelineSchedule struct {
Stages int
Roles []Role
Steps []ScheduleStep
Expectations []BarrierExpectation
PayloadBytes int64
}
PipelineSchedule represents an explicit, finite producer-consumer schedule modeling stages, buffer ownership, barrier expectations, and epoch reuse.
func BuildWarpSpecializedSchedule ¶
func BuildWarpSpecializedSchedule(numStages int, payloadBytes int64, numIterations int) (*PipelineSchedule, error)
BuildWarpSpecializedSchedule generates an explicit finite schedule for a given stage count and payload byte size across numIterations iterations (epochs). It models producer prefetching, consumer waiting, and epoch reuse.
func (*PipelineSchedule) AttentionSource ¶
func (s *PipelineSchedule) AttentionSource(name string, layout AttentionLayout) (string, kernel.Schema, error)
AttentionSource emits a synchronous CUDA C++ attention kernel and its pointer ABI from this validated schedule. Launch exactly one 64-thread CTA; the first warp copies packed tiles and thread 32 consumes them in row order. packed must contain ceil(Keys/TileSize)*PayloadBytes bytes; out holds HeadDim floats. Their storage must be disjoint and float-aligned.
Shared storage is capped at 48 KiB and eight stages. Abstract StepIssueTMA steps become ordinary scalar copies; waits/releases become CTA barriers. No TMA, cp.async, overlap, occupancy, compilation or device qualification is asserted. The FP64 recurrence is reassociated relative to materialized FP32 attention; actual compiler/device output needs an independent policy check.
Example ¶
package main
import (
"fmt"
"strings"
tilelayout "github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
layout := tilelayout.AttentionLayout{Keys: 5, HeadDim: 3, TileSize: 2}
payload, err := layout.PayloadBytes()
if err != nil {
panic(err)
}
schedule, err := tilelayout.BuildWarpSpecializedSchedule(2, payload, 3)
if err != nil {
panic(err)
}
source, schema, err := schedule.AttentionSource("attention", layout)
if err != nil {
panic(err)
}
fmt.Println(payload, len(schema.Params), strings.Contains(source, "u[d]/l"))
}
Output: 32 2 true
func (*PipelineSchedule) CopySources ¶
func (s *PipelineSchedule) CopySources(name string) (synchronous, asynchronous string, err error)
CopySources connects a validated finite schedule to two standalone CUDA C++ copy fixtures. Both use one 64-thread CTA: the first warp produces, and the second consumes. Input and output must contain the full scheduled iteration extent, be disjoint, and have 16-byte alignment. Launch exactly one block.
The asynchronous fixture uses SM80+ cp.async, with per-producer completion waits followed by CTA publication barriers. It is not TMA/mbarrier lowering; it provides a separate ordinary-copy comparison for the same stage protocol. Compilation, physical output correctness and timing are separate gates.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
s, _ := layout.BuildWarpSpecializedSchedule(2, 128, 4)
syncSource, asyncSource, err := s.CopySources("copy")
fmt.Println(strings.Contains(syncSource, "__syncthreads"), strings.Contains(asyncSource, "cp.async"), err)
}
Output: true true <nil>
func (*PipelineSchedule) Validate ¶
func (s *PipelineSchedule) Validate() []ValidationError
Validate verifies the pipeline schedule against:
- Barrier initialization before use
- Transaction balance (expect_tx bytes == issued TMA bytes)
- Stage ownership and no overwrite before release
- Epoch reuse correctness (no stale epochs, strictly monotonic per stage)
- Phase parity alternating properly
type Plan ¶
type Plan struct {
// contains filtered or unexported fields
}
Plan assigns regions in separate static and dynamic allocation pools.
func (*Plan) DynamicBytes ¶
func (*Plan) FootprintBytes ¶
func (*Plan) StaticBytes ¶
func (*Plan) ValidateBase ¶
ValidateBase checks the actual shared allocation base and every region's resulting address. Base alignment is a caller contract; it is never fixed by silently adjusting the address.
type RedistributionPermutation ¶
type RedistributionPermutation struct{ Rows, Cols int }
RedistributionPermutation describes a transpose-like tile redistribution.
func TransposePermutation ¶
func TransposePermutation(rows, cols int) (RedistributionPermutation, error)
TransposePermutation returns the independent logical transpose mapping.
type Region ¶
type Region struct {
Name string
Offset, Size, Alignment int64
FirstStage, LastStage int
Dynamic bool
}
Region is a range relative to its static or dynamic allocation base.
type RegisterOwner ¶
type RegisterOwner struct{ Lane, Register int }
RegisterOwner identifies the lane and register slot owning an element. Lane is in [0,32); Register is a logical slot, independent of pressure.
type Report ¶
type Report struct {
Issues []Issue
MemoryLatencyCycles int
ComputeIntervalCycles int
StagesNeeded int
ActualStages int
LatencyHiddenPercent float64
}
Report collects all issues and performance metrics from pipeline analysis.
func ValidatePipeline ¶
ValidatePipeline performs comprehensive static verification of a pipeline, checking transaction counts, phase parity, latency hiding, alignment, and hardware constraints.
type Request ¶
type Request struct {
Name string
Size int64
Alignment int64
FirstStage int
LastStage int
Dynamic bool
}
Request describes one region. Stages are inclusive; a region ending at stage 2 may be reused by one beginning at stage 3.
func RequestForTile ¶
func RequestForTile(tile Tile, name string, firstStage, lastStage int, dynamic bool) (Request, error)
RequestForTile adapts the physical footprint and alignment of cudalayout's checked tile into an allocation request. Storage remains owned by this planner; cudalayout still owns indexing and software swizzle semantics.
type ResourceSummary ¶
type ResourceSummary struct {
WarpsPerBlock int
BlocksPerSM int
RegistersPerThread int
RegistersPerWarp int
TotalWarpsPerSM int
TotalRegsPerSM int
WithinLimits bool
Diagnostic string
}
ResourceSummary provides a factual diagnostic breakdown of physical resource consumption for search and validation without performance claims. A derived quantity that cannot be represented as int is left at zero and reported as unavailable in the validation errors; it is not a zero allocation. Negative inputs leave all derived quantities unavailable at zero.
type Role ¶
type Role string
Role identifies the functional responsibility of a warp or warpgroup in a specialized producer-consumer schedule.
const ( // RoleProducer issues asynchronous memory copies (e.g. TMA bulk loads) // into shared memory stages and signals mbarrier transactions. RoleProducer Role = "producer" // RoleConsumer waits on mbarrier phase arrival and consumes stage data // (e.g. via MMA/HMMA math or SIMT kernels) before releasing stage ownership. RoleConsumer Role = "consumer" )
type Row ¶
type Row uint32
Row counts logical TMEM rows, each containing one 32-bit cell per column.
type ScheduleStep ¶
type ScheduleStep struct {
StepIndex int
Role Role
Kind StepKind
Stage int
Epoch int
Bytes int64
Parity int
Desc string
}
ScheduleStep records a single protocol step executed by a role.
type Shape ¶
type Shape struct {
// contains filtered or unexported fields
}
A Shape is a hierarchical extent: an integer, or a tuple of Shapes.
A Shape is only a description. Its extents are checked when it is paired with a Stride by NewLayout, so a Shape holding a non-positive extent can be built and printed but not used. The zero Shape is the integer 0.
func ParseShape ¶
ParseShape parses a shape in CuTe notation, such as "((4,2),8)".
func TupleShape ¶
TupleShape returns the tuple of the given modes. The modes are copied.
func (Shape) String ¶
String formats the shape in CuTe notation, such as "((4,2),8)".
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
s := layout.TupleShape(layout.IntShape(4), layout.TupleShape(layout.IntShape(2), layout.IntShape(3)))
d := layout.TupleStride(layout.BasisStride(0, 1), layout.TupleStride(layout.IntStride(0), layout.F2Stride(8, 16)))
fmt.Println(s, s.Rank(), d, d.Rank())
}
Output: (4,(2,3)) 2 (1@0,(0,xor(8,16))) 2
type SharedWindow ¶
type SharedWindow struct {
}
SharedWindow describes a CTA's reservation. Every CTA in Cluster must name the same tensor map, tile offset and barrier offset. ReservedBytes is the size of that CTA's shared allocation, not a device capability default.
type SimulationTrace ¶
SimulationTrace captures the sequential history of producer-consumer execution.
type Slice ¶
type Slice struct {
// contains filtered or unexported fields
}
Slice is an immutable logical view of a checked allocation. Overlapping views are allowed; they do not establish disjointness or device ordering. Copies share the parent's lifetime. An idle view does not prevent Release. The zero value is invalid.
func (Slice) Address ¶
Address returns the modeled pool coordinate of an element relative to s. It validates lifetime and bounds; it does not authorize a scalar instruction.
Example ¶
a, ids, p, x, err := exampleAllocation()
if err != nil {
fmt.Println(err)
return
}
s, err := x.Slice(tilelayout.Row(0), tilelayout.Column(3), 32, 2)
if err != nil {
fmt.Println(err)
return
}
addr, err := s.Address(2, 1)
fmt.Println(addr.Row, addr.Column, err) // coordinates, not native pointer bits
fmt.Println(a.ReleaseCollective(p, x, ids, columnArgs(32)))
fmt.Println(a.RelinquishCollective(p, ids), a.Close())
Output: 2 4 <nil> <nil> <nil> <nil>
func (Slice) BeginAccess ¶
func (s Slice) BeginAccess(warp uint32, layout Tile, issuers []graph.Issuer, bases []Address) (*Access, error)
BeginAccess admits the unmodified .32x32b.x1 or .x2 .b32 load/store footprint: layout must be dense, unswizzled, 32 rows by one or two 32-bit columns, and match s. Other shapes, packing, register mappings, and native taddr encoding are unsupported. Tile.Owner and Fragment are not used as hardware mappings.
warp is the linear warp index in the actual launch block. All its 32 declared issuers must be present exactly once in CTA 0, with the same modeled base at s's origin. The row chunk is 32*(warp%4) through 32*(warp%4)+31. These rules follow PTX ISA 9.4 sections 9.7.18.2.3.1.1 and 9.7.18.8.1, .3, .4: https://docs.nvidia.com/cuda/parallel-thread-execution/index.html.
Success holds the parent live until Complete, including after its permit is relinquished. Callers still arrange actual uniform execution, synchronization and wait completion; declared metadata alone is not evidence of those events.
Example ¶
a, ids, p, x, err := exampleAllocation()
if err != nil {
fmt.Println(err)
return
}
s, err := x.Slice(0, 0, 32, 2)
if err != nil {
fmt.Println(err)
return
}
layout, err := tilelayout.NewTile(32, 2, 4)
if err != nil {
fmt.Println(err)
return
}
base, err := s.Address(0, 0)
if err != nil {
fmt.Println(err)
return
}
bases := make([]tilelayout.Address, 32)
for i := range bases {
bases[i] = base
}
use, err := s.BeginAccess(0, layout, ids, bases)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(errors.Is(a.ReleaseCollective(p, x, ids, columnArgs(32)), tilelayout.ErrBusy))
// A real caller waits for its operation before declaring completion.
fmt.Println(use.Complete())
fmt.Println(a.ReleaseCollective(p, x, ids, columnArgs(32)))
fmt.Println(a.RelinquishCollective(p, ids), a.Close())
Output: true <nil> <nil> <nil> <nil>
func (Slice) Sub ¶
Sub selects a positive rectangular subview, relative to s's origin.
Example ¶
a, ids, p, x, err := exampleAllocation()
if err != nil {
fmt.Println(err)
return
}
s, err := x.Slice(0, 0, 32, 32)
if err != nil {
fmt.Println(err)
return
}
child, err := s.Sub(0, 7, 32, 1)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(child.Address(31, 0))
fmt.Println(a.ReleaseCollective(p, x, ids, columnArgs(32)))
fmt.Println(a.RelinquishCollective(p, ids), a.Close())
Output: {31 7} <nil> <nil> <nil> <nil>
type SpatialTiling ¶
type SpatialTiling struct {
CTAMesh map[string]int // Spatial distribution across threadblocks (grid)
WarpMesh map[string]int // Spatial distribution across warps (block)
}
SpatialTiling describes distribution of loop iterations across parallel hardware units.
func NewSpatialTiling ¶
func NewSpatialTiling(ctaMesh, warpMesh map[string]int) SpatialTiling
NewSpatialTiling constructs a spatial tiling specification.
func (SpatialTiling) TotalWarps ¶
func (s SpatialTiling) TotalWarps() int
TotalWarps returns the number of warps in the threadblock spatial tiling, or zero for a non-positive factor or product overflow. Use Validate to check that mesh dimensions and subdivisions match a factorization.
func (SpatialTiling) Validate ¶
func (s SpatialTiling) Validate(factors IndexFactorization, problem map[string]int) error
Validate checks that each CTA mesh factor divides the number of shared tiles along its problem dimension, and each warp mesh factor divides the number of register tiles within a shared tile. Omitted dimensions have factor one. Products must fit int. This checks logical subdivisions, not launch geometry, reduction synchronization or device residency.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
f := layout.NewIndexFactorization(
[]layout.StorageLevel{layout.LevelRegister, layout.LevelShared, layout.LevelDRAM},
map[layout.StorageLevel]map[string]int{
layout.LevelRegister: {"M": 1},
layout.LevelShared: {"M": 4},
layout.LevelDRAM: {"M": 2},
})
s := layout.NewSpatialTiling(map[string]int{"M": 2}, map[string]int{"M": 4})
fmt.Println(s.Validate(f, map[string]int{"M": 8}))
fmt.Println(s.TotalWarps())
}
Output: <nil> 4
type Stage ¶
Stage models a single stage of an asynchronous multi-stage pipeline, binding a buffer allocation, a TMA box transfer, and an mbarrier.
type StageOwnership ¶
type StageOwnership struct {
StageIndex int
Owner Role
State StageState
Epoch int // 0-indexed epoch counter; stage can only advance after consumer release
Parity int // Phase parity (Epoch & 1)
}
StageOwnership models explicit ownership, buffer lifecycle, and epoch tracking for a single pipeline stage.
type StageState ¶
type StageState string
StageState represents the lifecycle status of a pipeline buffer stage.
const ( // StageIdle indicates the stage buffer is empty and unallocated for current epoch. StageIdle StageState = "idle" // StageProducing indicates the producer is actively issuing transfers into this stage. StageProducing StageState = "producing" // StageReady indicates all transaction bytes and arrival tokens have completed; // data is ready for consumer consumption. StageReady StageState = "ready" // StageConsuming indicates the consumer is actively reading/processing this stage. StageConsuming StageState = "consuming" )
type StepEvent ¶
type StepEvent struct {
Step int
StageIndex int
Action string // "produce" or "consume"
PhaseParity int
Success bool
ErrorMsg string
}
StepEvent records an action performed during pipeline execution simulation.
type StepKind ¶
type StepKind string
StepKind identifies the discrete protocol step in a warp-specialized schedule.
const ( StepInit StepKind = "init" // mbarrier.init StepAcquireStage StepKind = "acquire_stage" // Producer acquires idle stage for epoch StepArriveExpectTx StepKind = "arrive_expect_tx" // mbarrier.arrive.expect_tx StepIssueTMA StepKind = "issue_tma" // cp.async.bulk.tensor StepWaitParity StepKind = "wait_parity" // mbarrier.try_wait.parity StepConsumeStage StepKind = "consume_stage" // Consumer processes stage data StepReleaseStage StepKind = "release_stage" // Consumer releases stage; epoch advances )
type StorageLevel ¶
type StorageLevel int
StorageLevel identifies a tier in the CUDA memory hierarchy. Mapspace factors are multiplied from the first listed level through the selected level when computing that level's tile.
The constants are not in hierarchy order: LevelTensorMemory follows LevelDRAM so that it is outside the factor chain, whose levels must be listed in increasing order ending at LevelDRAM.
const ( // LevelRegister is the per-thread register tile. LevelRegister StorageLevel = iota LevelShared // LevelL2 is the L2-resident tile. LevelL2 // LevelDRAM is the full problem tile in device memory. LevelDRAM // LevelTensorMemory is the per-SM Tensor Memory tcgen05 instructions // address on sm_100 and its relatives. It sits beside shared memory, // not between two factor-chain levels: an accumulator held there is a // copy of the register tile, not a further split of the problem. No // mapspace factorization may list it. LevelTensorMemory )
func (StorageLevel) String ¶
func (s StorageLevel) String() string
String returns the stable name of s.
type Stride ¶
type Stride struct {
// contains filtered or unexported fields
}
A Stride is a hierarchical stride: a leaf, or a tuple of Strides.
A leaf is one of three kinds, and the kind decides how a coordinate in that mode contributes to an offset:
- IntStride d adds c*d, as in an ordinary strided layout.
- BasisStride d@axis adds c*d to component axis of a coordinate-valued offset, as CuTe's scaled basis strides E<axis> do.
- F2Stride b0, b1, ... XORs b_k into the offset for each set bit k of c. This is carry-less arithmetic over F2, the form XOR swizzles take.
The zero Stride is the integer stride 0.
func BasisStride ¶
BasisStride returns the stride d along coordinate axis, written d@axis.
func F2Stride ¶
F2Stride returns an F2-linear stride for a mode of extent 1<<len(bits). Coordinate bit k contributes bits[k], and contributions combine by XOR. The bits are copied.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
l, _ := layout.NewLayout(layout.IntShape(4), layout.F2Stride(3, 1))
for i := range l.Size() {
o, _ := l.Index(i)
fmt.Print(o, " ")
}
fmt.Println()
}
Output: 0 3 1 2
func ParseStride ¶
ParseStride parses a stride in CuTe notation, such as "((2,16),1)". A leaf written "d@axis" is a BasisStride. F2 strides have no written form.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
d, _ := layout.ParseStride("(1@0,(4@0,1@1))")
fmt.Println(d)
}
Output: (1@0,(4@0,1@1))
func TupleStride ¶
TupleStride returns the tuple of the given modes. The modes are copied.
type Swizzle ¶
type Swizzle uint8
Swizzle is a generic software XOR permutation, not a CUDA TMA swizzle mode. Its value is a byte span. Within each row, the byte column is XORed with (row*elementBytes)&(span-1). No bank-conflict behavior is promised.
type SwizzledTile ¶
type SwizzledTile struct {
// contains filtered or unexported fields
}
A SwizzledTile is a row-major shared-memory tile addressed under a tensor-map swizzle mode.
Columns are grouped into spans of Swizzle().Bytes() bytes. The groups are stored one after another, each holding every row's slice of that span, and within a group the byte offset is XORed with a multiple of 16 chosen by which 128-byte block the offset falls in. That is the addressing ThunderKittens' st::idx performs (include/types/shared/st.cuh:108-120) and the addressing the TMA unit performs for the same mode, so a tile built here and a descriptor carrying the same mode agree byte for byte.
A SwizzledTile is not self-validating and cannot be. It knows its own addressing, and NewSwizzledTile rejects a shape the mode cannot address, but whether it agrees with the descriptor a transfer actually uses is a fact about both. SwizzledTile.AgreesWith compares the mode alone; cudatma's Descriptor.AgreesWithTile compares the box extent too, and is where agreement is established. That check happens where a descriptor meets a tile, which may be later than construction, and is the last point before any device work.
The zero SwizzledTile is invalid. Construct one with NewSwizzledTile.
func NewSwizzledTile ¶
func NewSwizzledTile(rows, cols, elementBytes int, swizzle TMASwizzle) (SwizzledTile, error)
NewSwizzledTile returns a swizzled tile description.
The row byte width must be a multiple of the swizzle span, because a span that a row only partly fills would place a row's tail in the next group. With a swizzle, each element must fit within the 16-byte atom that the permutation moves; larger elements cannot be described by one byte offset. The complete byte footprint must fit in an int; otherwise it returns ErrOverflow. No storage is allocated.
func (SwizzledTile) AgreesWith ¶
func (t SwizzledTile) AgreesWith(descriptor TMASwizzle) error
AgreesWith reports whether a tile carries a given swizzle mode.
It is the half of the agreement a tile can establish alone. A shared tile written by a TMA store and read by register loads under a different mode produces wrong data rather than an error, and this catches that. The other half is the box extent, which lives on the descriptor: callers holding one should use cudatma's Descriptor.AgreesWithTile, which performs both.
func (SwizzledTile) BaseAlignment ¶
func (t SwizzledTile) BaseAlignment() int
BaseAlignment returns the byte alignment the tile's base address needs.
The swizzle XOR is computed from an offset taken modulo eight spans, so a base that is not a multiple of that repeat would shift the pattern and address different bytes than a descriptor does. An unswizzled tile needs only its element alignment.
func (SwizzledTile) ByteOffset ¶
func (t SwizzledTile) ByteOffset(row, col int) (int, error)
ByteOffset returns the byte offset of an element within the tile.
func (SwizzledTile) ElementBytes ¶
func (t SwizzledTile) ElementBytes() int
ElementBytes returns the element width.
func (SwizzledTile) Swizzle ¶
func (t SwizzledTile) Swizzle() TMASwizzle
Swizzle returns the tile's swizzle mode.
type SyncCheck ¶
type SyncCheck string
SyncCheck names the step of CheckSync that produced a witness.
const ( SyncCheckSpecialize SyncCheck = "specialize" // branch, loop or form outside the model SyncCheckSimulate SyncCheck = "simulate" // the reference schedule failed or deadlocked SyncCheckInit SyncCheck = "init" // a use is not ordered after mbarrier.init SyncCheckInval SyncCheck = "inval" // a use is not ordered before mbarrier.inval SyncCheckSeparation SyncCheck = "separation" // consecutive phases are not ordered SyncCheckWait SyncCheck = "wait" // a parity wait can observe another phase SyncCheckCompletion SyncCheck = "completion" // a phase can complete early SyncCheckCounter SyncCheck = "counter" // a counter can leave its bounds )
type SyncEvent ¶
type SyncEvent struct {
Kind SyncEventKind
Role int // performing role, or -1 for shared events
Line int // PTX line, or 0
Opcode string
// Barrier and Phase locate updates, waits and phase ends in the
// reference trace. Barrier is the mbarrier's symbol and offset, with
// "#n" appended for its nth re-initialization. A wait's Phase is the
// phase it targets, -1 for one that is ready at once.
Barrier string
Phase int
// Arrivals and Bytes are an update's change to the pending arrival and
// transaction counts.
Arrivals int64
Bytes int64
}
A SyncEvent is a vertex of the happens-before graph.
type SyncEventKind ¶
type SyncEventKind string
SyncEventKind is the kind of a vertex in the happens-before graph.
const ( SyncEventInit SyncEventKind = "init" SyncEventInval SyncEventKind = "inval" SyncEventUpdate SyncEventKind = "update" // a thread's arrive, expect_tx or complete_tx SyncEventAsyncIssue SyncEventKind = "async issue" // issue of a bulk copy, tcgen05 operation or commit SyncEventAsyncExec SyncEventKind = "async exec" // a bulk copy's writes or a tcgen05 operation SyncEventAsyncUpdate SyncEventKind = "async update" // a copy's complete_tx or a commit's arrival SyncEventTrack SyncEventKind = "track" // completion of the work a commit tracks SyncEventWaitIssue SyncEventKind = "wait issue" SyncEventWaitReturn SyncEventKind = "wait return" SyncEventBarSync SyncEventKind = "bar.sync" // one event shared by its participants SyncEventPhaseEnd SyncEventKind = "phase end" )
type SyncLaunch ¶
type SyncLaunch struct {
Block [3]int // threads per CTA; zero uses the kernel's .reqntid
Grid [3]int // CTAs per grid, read through %nctaid; zero means 1 per axis
CTA [3]int // the CTA whose threads are checked, read through %ctaid
// Args holds scalar kernel arguments by .param name. A parameter
// missing from Args loads as data.
Args map[string]int64
// TensorBytes holds the bytes one cp.async.bulk.tensor copy delivers,
// by the name of its tensor-map parameter. The PTX does not state it.
TensorBytes map[string]int64
// ElectLowest assumes elect.sync elects the lowest lane of its member
// mask. PTX guarantees only that the choice is deterministic.
ElectLowest bool
MaxLoopIterations int // per backward branch; zero means 4096
MaxSteps int // instructions per thread group; zero means 1<<22
}
SyncLaunch is the launch configuration CheckSync specializes a kernel for. Branches and loop bounds must follow from it alone.
type SyncResult ¶
type SyncResult struct {
Verdict SyncVerdict
Witness *SyncWitness // set unless Verdict is SyncAccepted or SyncNoBarriers
Roles []SyncRole
Events []SyncEvent
Assumptions []string // assumptions beyond the PTX the verdict depends on
// contains filtered or unexported fields
}
SyncResult is the outcome of CheckSync.
func CheckSync ¶
func CheckSync(k *ptx.Kernel, l SyncLaunch) (*SyncResult, error)
CheckSync checks that kernel k, specialized for launch l, is well-synchronized on its mbarriers: that every execution assigns each barrier update and wait to the same phase. It follows SentryWard's SyncCheck (arXiv 2611.33817, Algorithm 1): it simulates one schedule to completion, builds the candidate happens-before graph from it, and checks initialization, separation of consecutive phases, the phase each parity wait can observe, and that no phase can complete before all its updates.
Each thread's updates and waits are its own events, even where threads of a warp take the same path; bar.sync and bar.warp.sync are collective events, matched by occurrence.
CheckSync analyzes the threads of one CTA. It returns an error only for invalid arguments; kernels outside the model are SyncUnsupported.
Example ¶
package main
import (
"fmt"
"log"
"strings"
"github.com/tmc/lib/nvidia/x/isa/ptx"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
// Thread 0 hands thread 32 two values through bar, waiting each time
// for thread 32 to take the last one through ack.
const src = `
.version 8.8
.target sm_90a
.address_size 64
.visible .entry handoff()
.reqntid 64, 1, 1
{
.reg .pred %p<4>;
.reg .b32 %r<4>;
.shared .align 8 .b64 bar;
.shared .align 8 .b64 ack;
mov.u32 %r1, %tid.x;
setp.ne.u32 %p1, %r1, 0;
@%p1 bra $L_init_done;
mbarrier.init.shared::cta.b64 [bar], 1;
mbarrier.init.shared::cta.b64 [ack], 1;
$L_init_done:
bar.sync 0;
setp.eq.u32 %p1, %r1, 32;
@%p1 bra $L_consumer;
setp.ne.u32 %p1, %r1, 0;
@%p1 bra $L_done;
mbarrier.arrive.shared::cta.b64 _, [bar];
$L_a0:
mbarrier.try_wait.parity.shared::cta.b64 %p2, [ack], 0;
@!%p2 bra $L_a0;
mbarrier.arrive.shared::cta.b64 _, [bar];
bra.uni $L_done;
$L_consumer:
$L_w0:
mbarrier.try_wait.parity.shared::cta.b64 %p2, [bar], 0;
@!%p2 bra $L_w0;
mbarrier.arrive.shared::cta.b64 _, [ack];
$L_w1:
mbarrier.try_wait.parity.shared::cta.b64 %p2, [bar], 1;
@!%p2 bra $L_w1;
$L_done:
ret;
}
`
// In the mutant thread 0 waits for parity 1 of ack, a phase thread 32
// never completes, so the reference schedule deadlocks.
for _, s := range []string{src, strings.Replace(src, "[ack], 0;", "[ack], 1;", 1)} {
m, err := ptx.ParseString(s)
if err != nil {
log.Fatal(err)
}
r, err := layout.CheckSync(m.Kernels[0], layout.SyncLaunch{})
if err != nil {
log.Fatal(err)
}
fmt.Println(r.Verdict)
if r.Witness != nil {
fmt.Println(r.Witness.Check, r.Witness.Lines)
}
}
}
Output: accepted rejected simulate [25 35]
func (*SyncResult) HappensBefore ¶
func (r *SyncResult) HappensBefore(a, b int) bool
HappensBefore reports whether the graph has a nonempty path from event a to event b. Once CheckSync accepts, the graph orders every execution.
func (*SyncResult) Successors ¶
func (r *SyncResult) Successors(e int) []int
Successors returns the direct successors of event e.
type SyncRole ¶
type SyncRole struct {
Parent int // the role this one split from, or -1
Threads []int // linear thread indices within the CTA
Events []int // the role's events in program order
}
A SyncRole is a group of threads that take the same path. A role that splits ends where its threads diverge; its children continue from there.
type SyncVerdict ¶
type SyncVerdict string
SyncVerdict is the outcome of CheckSync.
const ( SyncAccepted SyncVerdict = "accepted" // well-synchronized for the launch SyncRejected SyncVerdict = "rejected" // a check failed; see Witness SyncUnsupported SyncVerdict = "unsupported" // outside the model; see Witness SyncNoBarriers SyncVerdict = "no barriers" // no mbarrier or collective sync events to check )
type SyncWitness ¶
type SyncWitness struct {
Check SyncCheck
Events []int // event ids, when the check ran on the graph
Lines []int // PTX lines
Message string
}
A SyncWitness explains a rejection or an unsupported construct.
type TMABox ¶
type TMABox struct {
DimX int // Horizontal box dimension in elements
DimY int // Vertical box dimension in elements
ElementSize int // Size of each element in bytes (e.g. 2 for fp16/bf16, 1 for fp8, 4 for tf32/fp32)
StrideBytes int // Stride between rows in shared memory (must be >= DimX * ElementSize and multiple of 16)
}
TMABox specifies the tile geometry and element layout for a 2D Tensor Memory Accelerator (TMA) bulk transfer (cp.async.bulk.tensor.2d).
func (TMABox) PayloadBytes ¶
PayloadBytes returns the total payload bytes transferred by this TMA box.
type TMAGather4Mode ¶
type TMAGather4Mode string
TMAGather4Mode selects between a 4-row non-contiguous TMA 2D gather load (global to shared::cta) and a 4-row non-contiguous scatter store (shared::cta to global).
const ( TMAGather4Load TMAGather4Mode = "gather4" TMAScatter4Store TMAGather4Mode = "scatter4" )
type TMAGather4Spec ¶
type TMAGather4Spec struct {
Target string
Mode TMAGather4Mode
ColDim int
ElemBytes int
RowIndices [4]int32
L2Policy *L2CachePolicySpec
}
TMAGather4Spec describes a Blackwell (sm_100a, sm_103a, sm_100f, sm_120a, sm_121a) 2D TMA .tile::gather4 or .tile::scatter4 transfer that gathers or scatters four non-contiguous global rows of width ColDim elements in a single instruction. sm_120a and sm_121a have only the gather.
Example ¶
policy := L2CachePolicySpec{
PrimaryPolicy: L2EvictFirst,
SecondaryPolicy: L2EvictUnchanged,
Fraction: 0.25,
}
policyPTX, _ := policy.FormatPTX("%0", "%1")
gather := TMAGather4Spec{
Target: TargetSM100a,
Mode: TMAGather4Load,
ColDim: 32,
ElemBytes: 4,
RowIndices: [4]int32{5, 18, 73, 211},
L2Policy: &policy,
}
gatherPTX, _ := gather.FormatPTX()
fmt.Println(policyPTX)
fmt.Println(gather.TransferBytes())
fmt.Println(gatherPTX)
Output: createpolicy.fractional.L2::evict_first.L2::evict_unchanged.b64 %0, %1; 512 cp.async.bulk.tensor.2d.shared::cta.global.tile::gather4.mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1, {%2, %3, %4, %5, %6}], [%7], %8;
func (TMAGather4Spec) FormatPTX ¶
func (s TMAGather4Spec) FormatPTX() (string, error)
FormatPTX emits the PTX cp.async.bulk.tensor.2d instruction for a 4-row .tile::gather4 load or .tile::scatter4 store, appending .L2::cache_hint when L2Policy is non-nil. The store completes through the bulk async-group.
func (TMAGather4Spec) TransferBytes ¶
func (s TMAGather4Spec) TransferBytes() int
TransferBytes returns the total payload size in bytes across all 4 gathered or scattered rows.
func (TMAGather4Spec) Validate ¶
func (s TMAGather4Spec) Validate() error
Validate checks target support, mode, element width, 16-byte row alignment, non-negative row coordinates, and optional L2 cache policy.
type TMAMulticastSpec ¶
type TMAMulticastSpec struct {
Target string
ClusterSize int
CTAMask uint16
TileBytes int
L2Policy *L2CachePolicySpec
}
TMAMulticastSpec describes a 2D TMA cluster multicast transfer (cp.async.bulk.tensor.2d.shared::cluster.global.tile.mbarrier::complete_tx::bytes.multicast::cluster) that broadcasts a global tile into the shared memory of every CTA selected by CTAMask within a thread block cluster.
func (TMAMulticastSpec) FormatPTX ¶
func (s TMAMulticastSpec) FormatPTX() (string, error)
FormatPTX emits the PTX cp.async.bulk.tensor.2d.shared::cluster.global.tile instruction with .multicast::cluster and optional .L2::cache_hint.
func (TMAMulticastSpec) RecipientCount ¶
func (s TMAMulticastSpec) RecipientCount() int
RecipientCount returns the number of destination CTAs selected in CTAMask.
func (TMAMulticastSpec) Validate ¶
func (s TMAMulticastSpec) Validate() error
Validate checks target support, cluster size, non-zero recipient bitmask, 16-byte tile alignment, and optional L2 cache policy.
type TMAReduceOp ¶
type TMAReduceOp string
TMAReduceOp names the element-wise reduction a TMA reduce store applies to global memory.
const ( TMAReduceAdd TMAReduceOp = "add" TMAReduceMin TMAReduceOp = "min" TMAReduceMax TMAReduceOp = "max" TMAReduceInc TMAReduceOp = "inc" TMAReduceDec TMAReduceOp = "dec" TMAReduceAnd TMAReduceOp = "and" TMAReduceOr TMAReduceOp = "or" TMAReduceXor TMAReduceOp = "xor" )
The reductions cp.reduce.async.bulk.tensor admits (PTX ISA 9.5 Section 9.7.10.28.5.4). Gluon exposes add, min, max, and, or and xor as tma.async_atomic_add and its siblings.
type TMAReduceSpec ¶
type TMAReduceSpec struct {
Target string
Rank int
Op TMAReduceOp
Type TMAReduceType
L2Policy *L2CachePolicySpec
}
TMAReduceSpec describes a tiled TMA reduce store from shared::cta into global memory:
cp.reduce.async.bulk.tensor.<rank>d.global.shared::cta.<op>.tile.bulk_group [tmap, {c0, ...}], [smem];
Each element update is atomic with .relaxed.gpu ordering. Completion is tracked by the bulk async-group: follow the reduce with cp.async.bulk.commit_group and cp.async.bulk.wait_group (or EmitWaitGroupAsyncProxy) before reusing the shared source.
It is the counterpart of Gluon's tma.async_atomic_add, async_atomic_min, async_atomic_max, async_atomic_and, async_atomic_or and async_atomic_xor.
func (TMAReduceSpec) FormatPTX ¶
func (s TMAReduceSpec) FormatPTX() (string, error)
FormatPTX returns the instruction as an inline-asm template. Operand %0 is the 64-bit tensor-map address, %1 through %rank are the s32 coordinates (innermost first), the next operand is the 32-bit shared::cta source address, and, when L2Policy is set, the last is the 64-bit cache policy built by L2CachePolicySpec.FormatPTX.
func (TMAReduceSpec) Validate ¶
func (s TMAReduceSpec) Validate() error
Validate checks the target, the rank, and the reduction and element type against the PTX ISA 9.5 table of valid combinations. Because cp.reduce.async.bulk.tensor takes its element type from the tensor map rather than the PTX instruction text, Type is checked against the ISA table here only; ptxas does not see it.
type TMAReduceType ¶
type TMAReduceType string
TMAReduceType names the element type of the tensor a TMA reduce store updates. The instruction takes its element type from the tensor map, so the type does not appear in the emitted PTX; it is carried here only so that TMAReduceSpec.Validate can refuse a reduction the hardware does not define.
const ( TMAReduceU32 TMAReduceType = "u32" TMAReduceS32 TMAReduceType = "s32" TMAReduceU64 TMAReduceType = "u64" TMAReduceS64 TMAReduceType = "s64" TMAReduceF32 TMAReduceType = "f32" TMAReduceF16 TMAReduceType = "f16" TMAReduceBF16 TMAReduceType = "bf16" TMAReduceB32 TMAReduceType = "b32" TMAReduceB64 TMAReduceType = "b64" )
The element types the PTX reduction table names.
type TMAStageState ¶
type TMAStageState struct {
StageID int
BufferBytes uint64
InFlight bool
GroupCommitted bool
ExpectedTxBytes uint64
CompletedTxBytes uint64
BarrierArrived bool
BarrierPhase int
ExpectedParity int
HasPendingWrites bool
}
StageState tracks the lifecycle of an individual buffer stage in an async pipeline.
type TMASwizzle ¶
type TMASwizzle uint8
TMASwizzle is a CUDA tensor-map swizzle mode. Its values correspond to CU_TENSOR_MAP_SWIZZLE_NONE, _32B, _64B and _128B, and a tile built with one addresses bytes the way the TMA unit does.
It is not Swizzle, which is this package's own generic XOR permutation and promises nothing about tensor maps. A shared tile a TMA descriptor writes must use a TMASwizzle, and the same mode the descriptor carries.
const ( TMASwizzleNone TMASwizzle = iota TMASwizzle32B TMASwizzle64B TMASwizzle128B )
func TMASwizzleFromBytes ¶
func TMASwizzleFromBytes(bytes int) (TMASwizzle, error)
TMASwizzleFromBytes returns the mode for a swizzle span in bytes. A span of 0 is TMASwizzleNone.
func (TMASwizzle) Bytes ¶
func (s TMASwizzle) Bytes() int
Bytes returns the swizzle span in bytes. The span of TMASwizzleNone is 0.
func (TMASwizzle) String ¶
func (s TMASwizzle) String() string
type TMATileSpec ¶
type TMATileSpec struct {
Target string
Rank int
Direction Direction
Multicast bool
L2Policy *L2CachePolicySpec
}
TMATileSpec describes a tiled TMA transfer of rank one through five between global memory and shared memory.
A non-multicast GlobalToShared load targets shared::cta and completes on an mbarrier with complete_tx byte accounting:
cp.async.bulk.tensor.<rank>d.shared::cta.global.tile.mbarrier::complete_tx::bytes [smem], [tmap, {c0, ...}], [mbar];
The shared::cta destination form (PTX 8.6) lowers to a bare UTMALDG on sm_90a, sm_100a and sm_121a, whereas shared::cluster on sm_121a emits a runtime non-local destination check and syscall branch ahead of UTMALDG.
With Multicast set the load uses shared::cluster with .multicast::cluster, writing the same tile into every CTA of the cluster selected by a 16-bit CTA mask and signaling each CTA's barrier at the same shared offset:
cp.async.bulk.tensor.<rank>d.shared::cluster.global.tile.mbarrier::complete_tx::bytes.multicast::cluster [smem], [tmap, {c0, ...}], [mbar], ctaMask;
A SharedToGlobal store completes through the bulk async-group:
cp.async.bulk.tensor.<rank>d.global.shared::cta.tile.bulk_group [tmap, {c0, ...}], [smem];
and is retired with cp.async.bulk.commit_group followed by BulkWaitGroup. These are the instructions behind Gluon's tma.async_load (including multicast=True), tma.async_store and tma.store_wait.
func (TMATileSpec) FormatPTX ¶
func (s TMATileSpec) FormatPTX() (string, error)
FormatPTX returns the instruction as an inline-asm template.
For a load, %0 is the 32-bit shared destination, %1 the 64-bit tensor-map address, %2 through %(rank+1) the s32 coordinates (innermost first), and the next operand the 32-bit mbarrier address; then the 16-bit CTA mask when Multicast is set, and the 64-bit cache policy when L2Policy is set. When Multicast is false, the instruction uses .shared::cta, so both %0 and the mbarrier must reside in the executing CTA's local shared memory (signaling a remote cluster CTA's mbarrier requires .shared::cluster).
For a store, %0 is the tensor-map address, %1 through %rank the coordinates, the next operand the 32-bit shared source, and then the cache policy when L2Policy is set.
func (TMATileSpec) Validate ¶
func (s TMATileSpec) Validate() error
Validate checks the target, rank and direction, and that Multicast is only requested for a load on a target that implements it in hardware.
ptxas accepts .multicast::cluster for sm_120a and sm_121a, but it does not lower it to a multicast TMA: ptxas 13.5 for sm_121a emits a CALL.ABS.NOINC to __cuda_syscall_cp_async_bulk_tensor_<rank>d_tile_multicast where sm_90a and sm_100a emit UTMALDG.<rank>D.MULTICAST. Validate refuses those targets rather than hand them a driver call in the load path.
type TMEMCapability ¶
type TMEMCapability struct {
Target Target
MaxColumns uint32
MaxRows uint32
ColumnUnit uint32
RowUnit uint32
}
Capability describes the target-specific hardware allocation limits used by this bounded model. MaxRows and MaxColumns follow PTX ISA 9.4 section 9.7.18.1 for sm_100a/sm_103a/sm_107a/sm_100f/sm_103f/sm_107f; target admission remains package policy.
type Target ¶
type Target string
Target is an exact architecture token, not a marketing family name.
func ParseTarget ¶
type TensorRole ¶
type TensorRole int
TensorRole classifies tensor arguments in a contraction or loop nest.
const ( // TensorA is the left input matrix of a contraction. TensorA TensorRole = iota // TensorB is the right input matrix of a contraction. TensorB // TensorC is the output or accumulator matrix of a contraction. TensorC )
type Tile ¶
type Tile struct {
// contains filtered or unexported fields
}
Tile is a checked row-major physical tile description. The zero value is invalid. Construct tiles with NewTile; dimensions and mapping are immutable.
Example (Accessors) ¶
t, _ := NewTile(2, 3, 2, WithStride(4), WithAlignment(16), WithSwizzle(SwizzleNone)) f, _ := t.FootprintBytes() fmt.Println(t.Rows(), t.Cols(), t.ElementBytes(), t.StrideElements(), t.AlignmentBytes(), t.Swizzle(), f)
Output: 2 3 2 4 16 none 16
func NewTile ¶
NewTile constructs a tile. Dimensions and element size are positive; the supported element sizes are 1, 2, and 4 bytes.
Example ¶
tile, _ := NewTile(2, 4, 2, WithStride(16), WithSwizzle(Swizzle32B)) p, _ := tile.Index(1, 2) fmt.Println(p.ElementOffset, p.ByteOffset, tile.StrideElements())
Output: 18 38 16
func (Tile) AlignmentBytes ¶
AlignmentBytes returns the required base address alignment in bytes.
func (Tile) Compatible ¶
Compatible reports whether two layouts can alias the same physical tile.
Example ¶
a, _ := NewTile(2, 2, 4) b, _ := NewTile(2, 2, 4) c, _ := NewTile(2, 2, 4, WithStride(4)) fmt.Println(a.Compatible(b), a.Compatible(c), len(a.Identity()))
Output: true false 64
func (Tile) ElementBytes ¶
ElementBytes returns the size of one storage element in bytes.
func (Tile) FootprintBytes ¶
FootprintBytes is the complete row-strided storage footprint, including padding. It is measured in bytes and is checked for host integer overflow.
func (Tile) Index ¶
func (t Tile) Index(row, col int) (PhysicalIndex, error)
Index maps a logical element to an unswizzled element and physical byte offset.
Example ¶
t, _ := NewTile(2, 3, 2) p, _ := t.Index(1, 2) fmt.Println(p.Row, p.Col, p.ElementOffset, p.ByteOffset)
Output: 1 2 5 10
func (Tile) Owner ¶
func (t Tile) Owner(row, col int) (RegisterOwner, error)
Owner maps a tile element to a deterministic 32-lane register tile. The mapping uses linear element order and therefore also handles tails.
Example ¶
t, _ := NewTile(2, 2, 4) o, _ := t.Owner(1, 0) r, c, _ := t.OwnerFor(o.Lane, o.Register) fmt.Println(o.Lane, o.Register, r, c)
Output: 2 0 1 0
func (Tile) StrideElements ¶
StrideElements returns the unswizzled row stride in elements.
func (Tile) TransposeOwners ¶
func (t Tile) TransposeOwners(row, col int) (RegisterOwner, error)
TransposeOwners maps a source element through a logical transpose and returns the destination register owner.
Example ¶
t, _ := NewTile(2, 3, 1) o, _ := t.TransposeOwners(1, 2) fmt.Println(o.Lane, o.Register)
Output: 5 0
type TileConfig ¶
TileConfig defines dimensions for cooperative threadblock staging.
func DefaultGEMMTile ¶
func DefaultGEMMTile() TileConfig
DefaultGEMMTile returns standard shared-memory tile dimensions for GEMM/GEMV.
func (TileConfig) SharedMemBytes ¶
func (tc TileConfig) SharedMemBytes() int
SharedMemBytes calculates the required shared memory scratchpad size in bytes for A and B tiles.
type TopK ¶
type TopK struct {
// contains filtered or unexported fields
}
TopK owns a loaded FP32 selection artifact. Its zero value is closed. Execute and Close are serialized; the device must remain live until Close succeeds.
func CompileTopK ¶
func CompileTopK(dev *cuda.Device, config TopKConfig) (*TopK, error)
CompileTopK compiles and loads the ordinary FP32 baseline. Geometry is one block per row with one thread and zero dynamic shared bytes. Compiler-allocated registers/local memory must be observed separately from the returned artifact; the native fixture records loaded attributes without treating missing facts as zero. A nonnil TopK returned with an error retains cleanup and must be closed.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
// Validate before attempting to compile or use a device.
_, err := layout.CompileTopK(nil, layout.TopKConfig{Rows: 1, Width: 33, RowStride: 33, K: 33})
fmt.Println(err)
}
Output: cudablock: unsupported topk configuration
func LoadTopK ¶
LoadTopK loads a retained ordinary FP32 artifact without compiling it. The artifact must declare TopKSource as its tracked cudablock_topk.cu dependency, the exact TopKSchema, and the topk_fp32 entry point. These checks bind trusted compilation receipts; they do not authenticate a compiler or prove that arbitrary supplied machine code implements the source. The descriptor and its slices are copied. The caller must exclude concurrent mutation during the call. Execute and Close follow CompileTopK's ownership rules. A nonnil result returned with an error must be closed.
Example ¶
_, err := LoadTopK(nil, TopKConfig{Rows: 1, Width: 1, RowStride: 1, K: 1}, nil)
fmt.Println(err != nil)
Output: true
func (*TopK) Artifact ¶
func (t *TopK) Artifact() *cudakernel.Artifact
Artifact returns a detached descriptor for the exact loaded image and ABI.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
var selection *layout.TopK
fmt.Println(selection.Artifact() == nil)
}
Output: true
func (*TopK) Close ¶
Close drains a failed invocation before releasing its borrows and unloading the module. Failed drains or cleanup retain ownership for a later retry.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
var selection *layout.TopK
fmt.Println(selection.Close())
}
Output: <nil>
func (*TopK) Execute ¶
func (t *TopK) Execute(stream *cuda.Stream, b TopKBuffers) error
Execute completes selection, validates every row's device status and count, then publishes indices/counts and optional values on the same stream. It never uses a CPU sorting path. An error before publication leaves output untouched. After any device completion failure the buffers remain borrowed; retry Close to drain them. Cancellation is not offered by this synchronous initial API.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
var selection *layout.TopK
fmt.Println(selection.Execute(nil, layout.TopKBuffers{}))
}
Output: cudablock: closed topk
type TopKBF16 ¶
type TopKBF16 struct {
// contains filtered or unexported fields
}
TopKBF16 owns a BF16-input selection artifact. Rows and stride are measured in BF16 elements. Decoding shifts the storage bits left 16 into an FP32 word; no rounding or FP16 conversion is performed. Every NaN payload rejects the invocation, including short rows. Infinities, signed zeros and lowest-index ties follow TopKConfig's decoded-value policy. Its zero value is closed. Execute and Close are serialized. Device and stream lifetimes match TopK.
func CompileTopKBF16 ¶
func CompileTopKBF16(dev *cuda.Device, config TopKConfig) (*TopKBF16, error)
CompileTopKBF16 compiles the ordinary one-thread-per-row BF16 baseline. Config limits and output extents match FP32; input uses two bytes per element. A nonnil result returned with an error retains cleanup and must be closed.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
_, err := layout.CompileTopKBF16(nil, layout.TopKConfig{})
fmt.Println(err)
}
Output: cudablock: unsupported topk configuration
func (*TopKBF16) Artifact ¶
Artifact returns a detached descriptor for the exact BF16-input image.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
var selection layout.TopKBF16
fmt.Println(selection.Artifact() == nil)
}
Output: true
func (*TopKBF16) Close ¶
Close drains failed work and retries cleanup through the shared TopK owner.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
var selection layout.TopKBF16
fmt.Println(selection.Close())
}
Output: <nil>
func (*TopKBF16) Execute ¶
func (t *TopKBF16) Execute(stream *cuda.Stream, b TopKBF16Buffers) error
Execute validates all rows before publishing outputs on the same stream. Scratch and status are diagnostic only. An error before publication leaves outputs untouched; publication/completion errors leave them undefined. Failed completion retains borrows until Close successfully drains the stream.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
var selection layout.TopKBF16
fmt.Println(selection.Execute(nil, layout.TopKBF16Buffers{}))
}
Output: cudablock: closed topk bf16
type TopKBF16Buffers ¶
type TopKBF16Buffers struct {
Input cuda.Slice[uint16]
Lengths cuda.Slice[int32]
Offsets cuda.Slice[int32]
ScratchIndices cuda.Slice[int32]
ScratchValues cuda.Slice[float32]
ScratchCounts cuda.Slice[int32]
Status cuda.Slice[int32]
Indices cuda.Slice[int32]
Values cuda.Slice[float32]
Counts cuda.Slice[int32]
}
TopKBF16Buffers holds caller-owned BF16 input and FP32/int32 output storage. Values are exactly decoded FP32, not rounded back to BF16. Field extents, device ownership, alias rejection and publication rules match TopKBuffers. Input is two-byte aligned; all other active views are four-byte aligned.
type TopKBuffers ¶
type TopKBuffers struct {
Input cuda.Slice[float32]
Lengths cuda.Slice[int32]
Offsets cuda.Slice[int32]
ScratchIndices cuda.Slice[int32]
ScratchValues cuda.Slice[float32]
ScratchCounts cuda.Slice[int32]
Status cuda.Slice[int32]
Indices cuda.Slice[int32]
Values cuda.Slice[float32]
Counts cuda.Slice[int32]
}
TopKBuffers holds caller-owned allocations. Lengths and Offsets contain one int32 per row; offsets must be nonnegative and every live output index must fit int32. ScratchIndices has Rows*K elements, ScratchCounts and Status have Rows elements. Indices and Counts are separate publication destinations. ScratchValues and Values have Rows*K elements when configured, otherwise both must be empty. No two active buffer ranges may overlap.
The caller must not write, read, free, close the device or stream, or submit concurrent work using these buffers during Execute. Scratch and status are diagnostic data, never admitted output. Outputs become usable only after a successful Execute; a publication or completion failure leaves them undefined.
type TopKConfig ¶
TopKConfig describes FP32 rows with contiguous columns and a stride measured in elements. Results are sorted by decreasing value, then increasing source index. Signed zeros compare equal; the selected value retains its source bits. Infinities are admitted. Any NaN, even in a short row, rejects the invocation. Unused indices are -1 and unused values are negative infinity.
func (TopKConfig) Extents ¶
func (c TopKConfig) Extents() (TopKExtents, error)
Extents checks the configuration before allocation or native calls. The initial domain is 1..65535 rows, width 1..4096, and K 1..32. Length zero is admitted by the per-row metadata, rather than by a zero-width allocation.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
c := layout.TopKConfig{Rows: 2, Width: 33, RowStride: 40, K: 32}
e, err := c.Extents()
fmt.Println(e.Input, e.Results, e.ScratchBytes, err)
}
Output: 73 64 272 <nil>
type TopKExtents ¶
TopKExtents gives the required element counts, excluding caller redzones. ScratchValues and output Values are needed only when Values is true.
type TopKStatus ¶
type TopKStatus int32
TopKStatus is a per-row device validation result. Only TopKOK admits output.
const ( TopKOK TopKStatus = iota TopKNaN TopKBadLength TopKBadOffset )
type TraceEvent ¶
type TraceEvent struct {
Kind EventKind
CTA int
Warp int
ActiveThreads int // e.g., 32 for alloc/ld/st, 1 (elect.sync) for mma/cp/commit
CTAGroup int // 1 or 2
Offset uint32 // TMEM column offset
Columns uint32 // TMEM column width
RowStart uint32 // row range [RowStart, RowStart+Rows)
Rows uint32
ScaleOffset uint32 // for block-scaled MMA: TMEM column holding scales staged by tcgen05.cp
HasScaleInTMEM bool
SourceAFromTMEM bool
SourceAOffset uint32
DecompressLUTB bool // for .decompress::lut::b on sm_107a/sm_107f: 2-column aligned LUT metadata in TMEM
LUTMetadataOffset uint32 // TMEM column offset of the 2-column LUT metadata table when DecompressLUTB is true
SyncRestrictReadA bool // for .sync_restrict::shared::read::mma::a on tcgen05.commit (sm_107a/sm_107f only)
}
TraceEvent records one device-side tcgen05 operation for protocol verification.
type TraceSummary ¶
type TraceSummary struct {
Target Target
CTAs int
CTAGroup int
MaxAllocatedColumns uint32
Allocations int
Deallocations int
Copies int
MMAs int
Commits int
Waits int
Loads int
Stores int
Shifts int
ClusterSyncs int
}
TraceSummary reports aggregate statistics for a verified tcgen05 trace.
func VerifyTrace ¶
func VerifyTrace(target Target, events []TraceEvent) (*TraceSummary, error)
VerifyTrace validates a sequence of device-side tcgen05 events against the cudatmem Allocator state machine and the sm_100a/sm_103a/sm_107a/sm_100f/sm_103f/sm_107f PTX 9.4 datapath rules:
- Single-thread elect.sync issue for tcgen05.mma, tcgen05.cp, tcgen05.commit.
- 4-warp 32-row epilogue datapath partitioning for tcgen05.ld and tcgen05.st.
- tcgen05.cp scale staging prior to block-scaled tcgen05.mma.
- TMEM-sourced operand A readiness (prior tcgen05.mma + commit + wait).
- 2-CTA (cta_group::2) matched allocation, CTA-0 MMA issue, and cluster.sync before dealloc.
- Underlying cudatmem.Allocator unit, ordering, busy-user, and leak checks.
- Rubin sm_107a/sm_107f 2-column aligned TMEM LUT metadata (.decompress::lut::b) and .sync_restrict::shared::read::mma::a commit admission.
type Transfer ¶
type Transfer struct {
Descriptor Descriptor
Direction Direction
Staged bool
Transfer is a checked operation description. GlobalToTMEM requires TargetSM100a, TargetSM103a, TargetSM107a, TargetSM100f, TargetSM103f, or TargetSM107f; Validate rejects sm_121a even when Staged is true.
type TransferHandle ¶
type TransferHandle struct {
// contains filtered or unexported fields
}
A TransferHandle names one transfer issued by a DescriptorSlot. Only DescriptorSlot.Issue creates a usable handle; the zero TransferHandle names no transfer.
func (TransferHandle) Generation ¶
func (h TransferHandle) Generation() uint64
Generation returns the descriptor generation the transfer was issued under, or 0 for the zero TransferHandle.
type UnicastRingConfig ¶
type UnicastRingConfig struct {
// Stages is the shared-memory ring buffer depth. Must be in [2, 8].
Stages int
// TileWidth is the 2D tile width in elements (innermost contiguous axis).
// Must be > 0.
TileWidth int
// TileHeight is the 2D tile height in rows. Must be > 0.
TileHeight int
// ElementBytes is the byte width of each tensor element. Must be 1, 2, or 4.
ElementBytes int
// SwizzleBytes is the shared-memory swizzle pattern width in bytes.
// Must be 0, 32, 64, or 128.
SwizzleBytes int
// TargetArch names the target SM architecture (for example "sm_90a",
// "sm_100a", or "sm_121a"). Targets below sm_90 are refused with
// [cudaerrors.ErrUnsupported].
TargetArch string
}
UnicastRingConfig describes a single-CTA multi-stage persistent shared-memory ring buffer fed by 2D Tensor Memory Accelerator (TMA) bulk asynchronous loads (cp.async.bulk.tensor.2d.shared::cta.global.mbarrier::complete_tx::bytes) and synchronized via per-stage shared mbarrier transaction byte counts.
func (UnicastRingConfig) SharedBytes ¶
func (c UnicastRingConfig) SharedBytes() int
SharedBytes returns the total shared-memory footprint in bytes required by the multi-stage ring buffer plus its 8-byte per-stage mbarrier array (Stages*TileBytes() + Stages*8).
func (UnicastRingConfig) TileBytes ¶
func (c UnicastRingConfig) TileBytes() int
TileBytes returns the byte footprint of a single 2D stage tile (TileWidth * TileHeight * ElementBytes). It returns 0 if any dimension is non-positive or if the product overflows int.
func (UnicastRingConfig) Validate ¶
func (c UnicastRingConfig) Validate() error
Validate checks that c describes an admitted single-CTA 2D TMA persistent ring configuration. Targets below sm_90 and tile sizes that violate 16-byte alignment or the PTX mbarrier transaction-byte ceiling (2^20 - 1) return an error wrapping [cudaerrors.ErrUnsupported].
type UnicastRingPlan ¶
type UnicastRingPlan struct {
// contains filtered or unexported fields
}
UnicastRingPlan holds a validated UnicastRingConfig and provides deterministic host reference simulation and standalone NVRTC-clean CUDA C++ device code generation. The zero value is not usable; construct one with NewUnicastRingPlan.
func NewUnicastRingPlan ¶
func NewUnicastRingPlan(cfg UnicastRingConfig) (*UnicastRingPlan, error)
NewUnicastRingPlan validates cfg and constructs a UnicastRingPlan.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
plan, err := layout.NewUnicastRingPlan(layout.UnicastRingConfig{
Stages: 3,
TileWidth: 64,
TileHeight: 32,
ElementBytes: 2,
SwizzleBytes: 128,
TargetArch: "sm_121a",
})
if err != nil {
panic(err)
}
src, err := plan.EmitCUDA("tma_unicast_stage_ring")
if err != nil {
panic(err)
}
fmt.Printf("target=%s stages=%d tile=%dB shared=%dB bulk2d=%t\n",
plan.Config().TargetArch,
plan.Config().Stages,
plan.Config().TileBytes(),
plan.Config().SharedBytes(),
strings.Contains(src, "cp.async.bulk.tensor.2d.shared::cta.global.mbarrier::complete_tx::bytes"),
)
}
Output: target=sm_121a stages=3 tile=4096B shared=12312B bulk2d=true
func (*UnicastRingPlan) Config ¶
func (p *UnicastRingPlan) Config() UnicastRingConfig
Config returns the validated UnicastRingConfig for the plan.
func (*UnicastRingPlan) EmitCUDA ¶
func (p *UnicastRingPlan) EmitCUDA(funcName string) (string, error)
EmitCUDA emits standalone NVRTC-clean CUDA C++ device code (with no <stdint.h> dependency) defining a persistent multi-stage 2D TMA ring helper named funcName. Thread 0 initializes the per-stage shared mbarrier array (mbarrier.init.shared::cta.b64), arrives with expected transaction bytes (mbarrier.arrive.expect_tx.shared::cta.b64), and issues cp.async.bulk.tensor.2d.shared::cta.global.mbarrier::complete_tx::bytes; consumer warps wait on each stage's rotating phase parity via mbarrier.try_wait.parity.shared::cta.b64.
func (*UnicastRingPlan) SimulateRingTransfer ¶
func (p *UnicastRingPlan) SimulateRingTransfer(src2D []byte, widthBytes, height int, tileCoords [][2]int) ([][]byte, error)
SimulateRingTransfer executes a deterministic CPU reference model of 2D boxed TMA tile extraction across tileCoords from a row-major 2D source tensor of height rows by widthBytes bytes per row. Each coordinate pair [2]int{x, y} specifies the starting element column x and starting row y of a TileWidth-by-TileHeight box. Elements falling outside [0, widthBytes/ElementBytes) horizontally or [0, height) vertically are zero-filled, matching hardware TMA out-of-bounds zero-fill semantics.
type ValidationError ¶
type ValidationError struct {
Line int // 1-based source line of the instruction
Opcode string // instruction opcode token (e.g. "mbarrier.arrive.expect_tx")
Violation string // category of protocol violation
Barrier string // barrier operand or symbol, if applicable
Phase int // pipeline or barrier phase index
Expected int64 // expected quantity (bytes, parity, arrival count), if applicable
Actual int64 // observed quantity, if applicable
Message string // human-readable explanation of the violation
}
ValidationError records a static pipeline or mbarrier protocol violation.
func ValidateKernel ¶
func ValidateKernel(k *ptx.Kernel, opts ...BarrierOption) ([]ValidationError, error)
ValidateKernel validates a single PTX kernel definition, reporting any pipeline or mbarrier protocol violations.
func ValidatePTX ¶
func ValidatePTX(mod *ptx.Module, opts ...BarrierOption) ([]ValidationError, error)
ValidatePTX validates all kernel definitions in the given PTX module, reporting any pipeline or mbarrier protocol violations.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/isa/ptx"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
const src = `
.version 8.8
.target sm_121a
.address_size 64
.visible .entry buggy_kernel() {
.reg .pred %p0;
.shared .align 8 .b64 bar;
mbarrier.init.shared::cta.b64 [bar], 1;
// Missing arrival before wait
mbarrier.try_wait.parity.shared::cta.b64 %p0, [bar], 0;
ret;
}
`
mod, err := ptx.Parse(strings.NewReader(src))
if err != nil {
panic(err)
}
violations, err := layout.ValidatePTX(mod)
if err != nil {
panic(err)
}
for _, v := range violations {
fmt.Printf("Violation: %s\n", v.Violation)
}
}
Output: Violation: missing barrier arrive
func (ValidationError) Error ¶
func (e ValidationError) Error() string
type XORSwizzle ¶
type XORSwizzle struct {
// contains filtered or unexported fields
}
An XORSwizzle is CuTe's Swizzle<B,M,S>: the F2-linear map that XORs the B bits of an offset starting at bit M+S into the B bits starting at bit M.
offset ^ ((offset >> S) & ((1<<B - 1) << M))
A negative S shifts left instead, moving low bits into high ones. Because the map is linear over F2, composing it with an F2 layout, or with an integer layout whose offsets never carry, gives another F2 layout; see XORSwizzle.Compose.
It is not Swizzle, this package's generic row-column permutation, and it is not TMASwizzle, a tensor-map mode; TMASwizzleXOR gives the XORSwizzle a tensor-map mode applies to byte offsets.
The zero XORSwizzle is Swizzle<0,0,0>, the identity.
func NewXORSwizzle ¶
func NewXORSwizzle(bits, base, shift int) (XORSwizzle, error)
NewXORSwizzle returns Swizzle<bits,base,shift>. bits and base must be non-negative, and |shift| must be at least bits so that the source and destination bit ranges do not overlap, which keeps the map invertible. The two bit ranges must fit below bit 62 and the host int sign bit.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
_, err := layout.NewXORSwizzle(3, 4, 2)
fmt.Println(errors.Is(err, layout.ErrUnsupported))
}
Output: true
func TMASwizzleXOR ¶
func TMASwizzleXOR(mode TMASwizzle) XORSwizzle
TMASwizzleXOR returns the XORSwizzle a tensor-map mode applies to byte offsets within a tile: Swizzle<1,4,3>, <2,4,3> and <3,4,3> for 32, 64 and 128 bytes, and the identity for TMASwizzleNone or an unknown mode.
func (XORSwizzle) Apply ¶
func (s XORSwizzle) Apply(offset int) int
Apply returns the swizzled offset. It is an involution: Apply(Apply(x)) == x.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
s := layout.TMASwizzleXOR(layout.TMASwizzle128B)
fmt.Println(s, s.Apply(0x80), s.Apply(0x390))
}
Output: Swizzle<3,4,3> 144 992
func (XORSwizzle) CheckDevice ¶
func (s XORSwizzle) CheckDevice(target string) error
CheckDevice reports whether s has been measured on target: whether a device addresses shared memory as s says, and whether the bank-conflict counts this package computes from s's offsets are the ones the hardware shows.
No instrument in this package has made that measurement, so for the targets this package knows (TargetSM100a, TargetSM121a) the answer is cuda.ErrHardwarePending: unknown, not refused. An unknown target is a caller error, ErrUnsupported.
Example ¶
No instrument has measured a swizzle on a device, so the answer is pending, not refused.
package main
import (
"errors"
"fmt"
"github.com/tmc/lib/nvidia/x/cuda"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
err := layout.TMASwizzleXOR(layout.TMASwizzle128B).CheckDevice(layout.TargetSM100a)
fmt.Println(errors.Is(err, cuda.ErrHardwarePending), errors.Is(err, cuda.ErrUnsupported))
}
Output: true false
func (XORSwizzle) Compose ¶
func (s XORSwizzle) Compose(l Layout) (Layout, error)
Compose returns s∘l, the layout whose offset at each coordinate is s.Apply of l's offset, as an F2 layout of l's shape.
l must be an F2 layout, or an integer layout whose offsets never carry: every mode that contributes has a power-of-two extent, its stride is non-negative, and the offsets of distinct coordinate bits share no set bit. Only then is l's offset the XOR of its bit images, which s maps one by one.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/tile/layout"
)
func main() {
s, _ := layout.NewXORSwizzle(1, 0, 2)
l, _ := layout.ParseLayout("8:1")
r, _ := s.Compose(l)
fmt.Println(r)
}
Output: 8:xor(1,2,5)
func (XORSwizzle) String ¶
func (s XORSwizzle) String() string
String formats s as "Swizzle<B,M,S>".
Source Files
¶
- agreement.go
- algebra.go
- arch.go
- asynccopy.go
- attention_source.go
- barrier.go
- blackwell.go
- block.go
- capability.go
- cluster_fixture.go
- copy.go
- discovery.go
- doc.go
- dsmem.go
- f2.go
- fixture.go
- fragment.go
- geometry.go
- hazard.go
- inverse.go
- layout.go
- lifetime.go
- mapspace.go
- mbarrier.go
- multicast_source.go
- partition.go
- partition_launch.go
- pipeline.go
- pipeline_race.go
- ptx.go
- ptx95.go
- reduce.go
- reduction_tree.go
- register.go
- resource.go
- schedule.go
- shape.go
- shared.go
- shared_fixture.go
- simulate.go
- slice.go
- spatial.go
- tile.go
- tma.go
- tmaswizzle.go
- tmem.go
- tmem_fixture.go
- topk.go
- topk_bf16.go
- topk_bf16_source.go
- topk_load.go
- topk_runtime.go
- topk_source.go
- topk_timing_source.go
- trace.go
- types.go
- unicast_ring.go
- validator.go
- wellsync.go
- wellsync_spec.go