layout

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 28 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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 (Shared)
package main

import (
	"fmt"
	"github.com/tmc/lib/nvidia/x/tile/layout"
)

func main() {
	p, err := layout.NewPlan(layout.Limits{StaticMax: 49152, DynamicMax: 101376, TotalMax: 101376, Source: "sm_121a device record"})
	if err != nil {
		panic(err)
	}
	r, err := p.Add(layout.Request{Name: "stage0", Size: 4096, Alignment: 128, FirstStage: 0, LastStage: 0, Dynamic: true})
	if err != nil {
		panic(err)
	}
	fmt.Println(r.Offset, p.FootprintBytes())
}
Output:
0 4096
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

Examples

Constants

View Source
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.

View Source
const (
	FeatureTMA      = "tma"
	FeatureMBarrier = "mbarrier"
	FeatureMultimem = "multimem"
	FeatureWGMMA    = "wgmma"
	FeatureTCGen05  = "tcgen05"
	FeatureTMEM     = "tmem"
)

Feature identifiers for PTX / GPU instructions and hardware capabilities.

View Source
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).

View Source
const (
	TargetSM90a  = "sm_90a"
	TargetSM120a = "sm_120a"
)
View Source
const (
	ScopeSubwarp    = cudahazard.ScopeSubwarp
	ScopeWarp       = cudahazard.ScopeWarp
	ScopeCTA        = cudahazard.ScopeCTA
	ScopeCluster    = cudahazard.ScopeCluster
	ScopeDevice     = cudahazard.ScopeDevice
	ScopeHostDevice = cudahazard.ScopeHostDevice
	ScopeMultiGPU   = cudahazard.ScopeMultiGPU
)
View Source
const (
	MemoryShared  = cudahazard.MemoryShared
	MemoryDSMEM   = cudahazard.MemoryDSMEM
	MemoryGlobal  = cudahazard.MemoryGlobal
	MemoryUnified = cudahazard.MemoryUnified
)
View Source
const (
	HazardNone       = cudahazard.HazardNone
	HazardReadWrite  = cudahazard.HazardReadWrite
	HazardWriteWrite = cudahazard.HazardWriteWrite
	HazardWriteRead  = cudahazard.HazardWriteRead
)
View Source
const (
	SM121MaxOptinSharedMemBytes = 101376 // 99 KB max opt-in
	SM121TotalSharedMemBytes    = 102400 // 100 KB total SM smem
	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.

View Source
const (
	TargetSM100a = "sm_100a"
	TargetSM103a = "sm_103a"
	TargetSM107a = "sm_107a"
	TargetSM100f = "sm_100f"
	TargetSM103f = "sm_103f"
	TargetSM107f = "sm_107f"
	TargetSM121a = "sm_121a"
)
View Source
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.

View Source
const Header = `` /* 5989-byte string literal not displayed */

Header is the embedded CUDA C++ header defining warp and block collective primitives.

View Source
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.

View Source
const MaxRank = 5

MaxRank is the greatest tensor rank a tiled tensor map admits.

View Source
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.

View Source
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

View Source
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.

View Source
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")
)
View Source
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")
)
View Source
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.

View Source
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)
)
View Source
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")
)
View Source
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
)
View Source
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")
)
View Source
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")
)
View Source
var ErrDuplicateCompletion = errors.New("duplicate completion")

ErrDuplicateCompletion reports a second completion from a multicast destination rank that has already completed.

View Source
var ErrTopKUnsupported = errors.New("cudablock: unsupported topk configuration")

ErrTopKUnsupported reports a row count, width or K outside the initial domain.

Functions

func AuditTensormapReplaceAllocClass

func AuditTensormapReplaceAllocClass(m *ptx.Module) error

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

func BindPartitionArgs(p Partition) []any

BindPartitionArgs returns the pointer, all non-innermost strides in axis order, then every partition extent in axis order.

func BindPartitionArgs32

func BindPartitionArgs32(p Partition) ([]any, error)

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

func BulkWaitGroup(pending int, read bool) (string, error)

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

func ByteRangeOverlap(aOffset uint64, aSize uint32, bOffset uint64, bSize uint32) bool

ByteRangeOverlap reports whether two byte intervals [aOffset, aOffset+aSize) and [bOffset, bOffset+bSize) intersect.

func CanonicalArch

func CanonicalArch(arch string) string

CanonicalArch normalizes an architecture string like "sm90", "SM_121A", or "sm_121a" into canonical form.

func Check

func Check(target string) error

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

func CheckClusterHardware(arch string) error

CheckClusterHardware checks whether the target architecture supports thread block clusters and DSMEM.

func CheckDSMEM

func CheckDSMEM(target string) error

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

func CheckTopKStatus(status []int32) error

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

func Copy[T any](plan CopyPlan, dst, src cuda.Slice[T]) error

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

func EmitArriveExpectTx(mbarAddr string, txBytes int) string

EmitArriveExpectTx returns a PTX instruction string arriving on an mbarrier and registering an expected transaction byte count for TMA.

func EmitArriveExpectTxRemote

func EmitArriveExpectTxRemote(mbarAddr string, txBytes int) (string, error)

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

func EmitBlockRank(dst string) string

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

func EmitCPAsyncMBarrierArrive(mbarAddr string, noinc bool) (string, error)

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

func EmitCPAsyncWaitGroup(pending int) (string, error)

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

func EmitClusterBarrier(relaxed bool) string

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

func EmitClusterCTAID(dst string, dim Dim) (string, error)

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

func EmitClusterNCTAID(dst string, dim Dim) (string, error)

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

func EmitClusterSize(dst string) string

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

func EmitInlineAsmArriveExpectTx(mbarOffset, txBytes int) string

EmitInlineAsmArriveExpectTx returns a CUDA C++ inline assembly snippet for arrive-expect-tx.

func EmitInlineAsmInit

func EmitInlineAsmInit(mbarOffset, arrivalCount int) string

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

func EmitInlineAsmTMEMAlloc(dstSharedOffset int, nCols int) string

EmitInlineAsmTMEMAlloc returns a CUDA C++ inline assembly snippet allocating nCols in TMEM.

func EmitInlineAsmTMEMDealloc

func EmitInlineAsmTMEMDealloc(taddrReg string, nCols int) string

EmitInlineAsmTMEMDealloc returns a CUDA C++ inline assembly snippet deallocating nCols from TMEM.

func EmitInlineAsmWait

func EmitInlineAsmWait(mbarOffset int, phaseParity int) string

EmitInlineAsmWait returns a CUDA C++ inline assembly snippet implementing a spin-wait loop on phase parity.

func EmitMBarrierArrive

func EmitMBarrierArrive(mbarAddr string, count int, remote bool) (string, error)

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

func EmitMBarrierExpectTx(mbarAddr string, txBytes int, remote bool) (string, error)

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

func EmitMBarrierInit(mbarAddr string, arrivalCount int) string

EmitMBarrierInit returns a PTX instruction string initializing an mbarrier in shared memory with the given arrival count.

func EmitMBarrierInvalidate

func EmitMBarrierInvalidate(mbarAddr string) (string, error)

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

func EmitPrefetchTile2DL2(desc, c0, c1, policy string) (string, error)

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

func EmitQueryAllocClassLarge(predicate, desc string) (string, error)

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

func EmitQueryAllocClassLargeSharedCTA(predicate, desc string) (string, error)

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

func EmitSharedAddr(dst, symbol string, plan *Plan, region Region) (string, error)

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

func EmitTMABulkAsync2D(dstSmem, descAddr, coord0, coord1, mbarAddr string) string

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

func EmitTMABulkAsync2DCluster(dstSmem, descAddr, coord0, coord1, mbarAddr string) string

EmitTMABulkAsync2DCluster returns a PTX instruction string issuing a 2D TMA bulk asynchronous copy targeted across a CTA cluster.

func EmitTMABulkAsync2DTMEM

func EmitTMABulkAsync2DTMEM(dstTmem, descAddr, coord0, coord1, mbarAddr string) string

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

func EmitTMABulkAsyncTMEM(dstTmem, srcGlobal string, sizeBytes int, mbarAddr string) string

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

func EmitTMEMAlloc(dstSharedAddr string, nCols int) string

EmitTMEMAlloc returns a PTX instruction string allocating nCols of Tensor Memory (TMEM).

func EmitTMEMDealloc

func EmitTMEMDealloc(taddrReg string, nCols int) string

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

func EmitWaitGroupAsyncProxy(pending int) (string, error)

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

func EmitWaitLoop(mbarAddr string, phaseParity int, labelPrefix string) string

EmitWaitLoop returns a spin-wait loop in PTX using nanosleep to minimize power/replay overhead.

func EmitWaitParity

func EmitWaitParity(mbarAddr string, phaseParity int, predReg string) string

EmitWaitParity returns a single PTX try_wait instruction testing completion of a phase parity.

func ExpectedReduction

func ExpectedReduction(clusterSize int) uint32

ExpectedReduction returns the total the unmutated fixture must produce: the sum of the distinct per-rank seeds.

func FixtureSource

func FixtureSource(target string, elements int) (string, error)

FixtureSource emits an ordinary synchronous global-to-shared fixture.

func FixtureSourceForTarget

func FixtureSourceForTarget(t Tile, target string) (string, error)

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

func GenerateMutantCUDA(kind string) (string, error)

GenerateMutantCUDA returns deliberate source mutants for the native oracle. Both must fail the all-lane populated-output comparison when executed.

func InferLaunchGrid

func InferLaunchGrid(explicit shape.Grid3D, partitions []Partition) (shape.Grid3D, error)

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

func MulticastSource(target string) (string, error)

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

func NormalizeUnsetNUMA(node int) int

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

func PTX95AllocClassFixtureSource(target string) (string, error)

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:

  1. 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.
  2. 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.
  3. 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

func ReadProcNvidiaGPUNUMANode(fsRoot string, pciBusID string) (int, error)

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

func ReadSysfsIBNUMANode(fsRoot string, ibDevName string) (int, error)

ReadSysfsIBNUMANode reads the raw NUMA node for an InfiniBand HCA from <fsRoot>/sys/class/infiniband/<ibDevName>/device/numa_node.

func ReadSysfsPCINUMANode

func ReadSysfsPCINUMANode(fsRoot string, pciBusID string) (int, error)

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

func ReductionFixture(target string, clusterSize int, mut Mutant) (string, error)

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

func SameReductionTree(a, b Layout, levels ...int) bool

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

func StagedCopyFixture(plan *Plan, target string, elements int) (string, int64, error)

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

func StagedCopyFixtureSource(target string, elements int) (string, error)

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

func TMAFixtureSource(target string) (string, error)

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

func TileFixtureSource(t Tile) (string, error)

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

func TopKSchema() (kernel.Schema, error)

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

func ValidateCollective(c graph.TMEMCollective, issuers []graph.Issuer, args []uint32) error

ValidateCollective consumes cudagroup's exact TMEM participation contract.

func ValidateFixture

func ValidateFixture(f Fixture) error

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.

func WordOverlap

func WordOverlap(aOffset uint64, aSize uint32, bOffset uint64, bSize uint32) bool

WordOverlap reports whether two memory accesses touch the same aligned 32-bit word.

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

func (a *Access) Complete() error

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

type Address struct {
	Row    Row
	Column Column
}

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

func (a *Allocation) Slice(row Row, column Column, rows, columns uint32) (Slice, error)

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

func New(target Target) (*Allocator, error)

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

func (a *Allocator) AcquireCollectivePermit(issuers []graph.Issuer) (*Permit, error)

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

func (a *Allocator) AcquirePermit(participants uint32) (*Permit, error)

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) CTAGroup

func (a *Allocator) CTAGroup() CTAGroup

CTAGroup returns the CTA group configured on the allocator.

func (*Allocator) Capability

func (a *Allocator) Capability() TMEMCapability

func (*Allocator) Close

func (a *Allocator) Close() error

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

func (a *Allocator) EnableExclusive(group CTAGroup) error

EnableExclusive enables .exclusive allocation on an empty allocator for a supported tcgen05 target and CTA group.

func (*Allocator) Exclusive

func (a *Allocator) Exclusive() bool

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

func (a *Allocator) Relinquish(p *Permit) error

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

func (a *Allocator) RelinquishCollective(p *Permit, issuers []graph.Issuer) error

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 = ""
	AsyncProxySharedCTA     AsyncProxySpace = "shared::cta"
	AsyncProxySharedCluster AsyncProxySpace = "shared::cluster"
	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.

func (Barrier) Parity

func (b Barrier) Parity() int

Parity returns the current phase parity (0 or 1).

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

type CPAsyncSpec struct {
	Bytes       int
	CacheGlobal bool
	SrcSize     string
}

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.

func (CPAsyncSpec) FormatPTX

func (s CPAsyncSpec) FormatPTX(dst, src string) (string, error)

FormatPTX returns the cp.async instruction copying from the global address src into the shared address dst:

cp.async.ca.shared.global [dst], [src], bytes{, srcsize};

type CTAGroup

type CTAGroup int

CTAGroup identifies a 1-CTA or 2-CTA cooperative tcgen05 allocation group.

const (
	CTAGroup1 CTAGroup = 1
	CTAGroup2 CTAGroup = 2
)

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

func Open(target string) (*Cluster, error)

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

func PlanCopy(src, dst Layout) (CopyPlan, error)

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 CopyRun

type CopyRun struct {
	SourceOffset      int
	DestinationOffset int
	Length            int
}

CopyRun describes a contiguous transfer. Offsets and Length are in elements.

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 Dim

type Dim int

Dim names one axis of a cluster's CTA grid.

const (
	DimX Dim = iota
	DimY
	DimZ
)

The three cluster axes.

func (Dim) String

func (d Dim) String() string

String returns the PTX suffix for the axis.

type Direction

type Direction uint8
const (
	GlobalToShared Direction = iota + 1
	SharedToGlobal
	GlobalToTMEM
)

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.

func (ElementType) String

func (e ElementType) String() string

String implements fmt.Stringer.

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

type Fixture struct {
	Target Target
	PTX    string
	CUDA   string
}

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

func GenerateFixture(target Target) (Fixture, error)

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

func (f Fragment) Cols() int

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

func (f Fragment) ElementBytes() int

ElementBytes returns the element width the fragment was built for.

func (Fragment) ElementsPerSlot

func (f Fragment) ElementsPerSlot() int

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

func (f Fragment) ElementsPerThread() int

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

func (f Fragment) PackedPerThread() int

PackedPerThread returns the packed slots one lane holds.

func (Fragment) RegistersPerThread

func (f Fragment) RegistersPerThread() int

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.

func (Fragment) Rows

func (f Fragment) Rows() int

Rows returns the base tile row count.

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 {
	MaxSharedMemoryPerBlock int // bytes per block
	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.

func (IndexFactorization) Validate

func (f IndexFactorization) Validate(problemExtents map[string]int) error

Validate checks that all factors are positive and their product equals problemExtents.

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

func ValidatePhaseParity(numStages int, producerParities, consumerParities []int) []Issue

ValidatePhaseParity checks a sequence of producer arrival parities and consumer wait parities across pipeline iterations, detecting phase inversions and deadlocks.

func (Issue) String

func (iss Issue) String() string

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

func Coalesce(l Layout) Layout

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

func CoalesceByMode(l Layout) Layout

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

func CompactLayout(shape Shape) (Layout, error)

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

func Complement(l Layout, cotarget int) (Layout, error)

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

func ComposeByMode(a Layout, tiler []Layout) (Layout, error)

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

func Composition(a, b Layout) (Layout, error)

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

func GreatestCommonDomain(a, b Layout) (Layout, error)

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

func LogicalDivide(a, b Layout) (Layout, error)

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

func LogicalDivideByMode(a Layout, tiler []Layout) (Layout, error)

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

func NewLayout(shape Shape, stride Stride) (Layout, error)

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

func Nullspace(l Layout) (Layout, error)

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

func ParseLayout(s string) (Layout, error)

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

func RightInverse(l Layout) (Layout, error)

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

func ShapeTiler(extents ...int) ([]Layout, error)

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

func ZippedDivide(a Layout, tiler []Layout) (Layout, error)

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

func (l Layout) BasisOffset(i int, dst []int) ([]int, error)

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

func (l Layout) Coordinate(i int, dst []int) ([]int, error)

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

func (l Layout) Cosize() (int, error)

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

func (l Layout) Equal(m Layout) bool

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

func (l Layout) Index(i int) (int, error)

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

func (l Layout) Mode(i int) (Layout, error)

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

func (l Layout) Offset(crd ...int) (int, error)

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

func (Layout) Rank

func (l Layout) Rank() int

Rank returns the number of top-level modes.

func (Layout) Shape

func (l Layout) Shape() Shape

Shape returns the layout's shape.

func (Layout) Size

func (l Layout) Size() int

Size returns the number of coordinates in the layout's domain.

func (Layout) Stride

func (l Layout) Stride() Stride

Stride returns the layout's stride.

func (Layout) String

func (l Layout) String() string

String formats the layout as "shape:stride".

type Limits

type Limits struct {
	StaticMax  int64
	DynamicMax int64
	TotalMax   int64
	Source     string
}

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

func LimitsFromDevice(arch string) (Limits, error)

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

func NewExclusiveMap(target Target, group CTAGroup) (*Map, error)

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

func NewMulticast(source uint32, destinations []uint32, bytes uint64) (Multicast, error)

NewMulticast tracks transactions for CTA ranks 0 through 15. The source and every destination must be in that range.

func (*Multicast) Complete

func (m *Multicast) Complete(rank uint32, bytes uint64) error

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

func (m Multicast) CompleteAll() bool

CompleteAll reports whether every constructor destination completed. Completion reads are synchronized across copied handles.

func (Multicast) Participating

func (m Multicast) Participating(rank uint32) bool

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
	AvailableSharedBytes  uint64
	SharedLimitProvenance string
}

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
	SharedBytes   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

type Option func(*Tile) error

Option configures NewTile.

func WithAlignment

func WithAlignment(bytes int) Option

WithAlignment sets the base byte alignment requirement.

func WithStride

func WithStride(stride int) Option

WithStride sets the row stride in elements. It must cover the tile width.

func WithSwizzle

func WithSwizzle(s Swizzle) Option

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

func (p Partition) ElementBytes() int

ElementBytes returns the size of each element in bytes.

func (Partition) Grid

func (p Partition) Grid() (shape.Grid3D, error)

Grid calculates the CUDA launch grid needed for this partition.

func (Partition) IsMutable

func (p Partition) IsMutable() bool

IsMutable reports whether this partition allows write access.

func (Partition) PartitionShape

func (p Partition) PartitionShape() shape.Shape

PartitionShape returns the tile partition shape.

func (Partition) PartitionStrides

func (p Partition) PartitionStrides() []int

PartitionStrides returns the stride in elements between adjacent block tiles along each axis.

func (Partition) Ptr

func (p Partition) Ptr() driver.DevicePtr

Ptr returns the underlying base device pointer.

func (Partition) Strides

func (p Partition) Strides() []int

Strides returns a copy of the tensor strides.

func (Partition) TensorShape

func (p Partition) TensorShape() shape.Shape

TensorShape returns the full tensor shape.

func (Partition) TileStride

func (p Partition) TileStride() int

TileStride returns the leading axis stride in elements (strides[0]).

func (Partition) TileStride32

func (p Partition) TileStride32() (int32, error)

TileStride32 returns the leading stride when it fits in int32.

func (Partition) ValidateDisjoint

func (p Partition) ValidateDisjoint() error

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

type PartitionOption func(*Partition) error

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

func (p *Pipeline) EmitEpilogPTX() string

EmitEpilogPTX generates PTX sequence to deallocate TMEM columns if the pipeline targeted TMEM.

func (*Pipeline) EmitPrologPTX

func (p *Pipeline) EmitPrologPTX() string

EmitPrologPTX generates PTX sequence to initialize all stage mbarriers in the pipeline and, if targeting TMEM, allocates the required TMEM columns.

func (*Pipeline) EmitStageLoadPTX

func (p *Pipeline) EmitStageLoadPTX(stageIdx int, descAddr, coord0, coord1 string) string

EmitStageLoadPTX generates PTX instructions to issue an asynchronous TMA load for the given stage.

func (*Pipeline) EmitStageWaitPTX

func (p *Pipeline) EmitStageWaitPTX(stageIdx int, phaseParity int) string

EmitStageWaitPTX generates PTX instructions to wait for completion of the given stage.

func (*Pipeline) NumStages

func (p *Pipeline) NumStages() int

NumStages returns the number of pipeline stages.

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) Stage

func (p *Pipeline) Stage(i int) *Stage

Stage returns a pointer to the stage at index i, or nil if out of bounds.

func (*Pipeline) TotalSharedBytes

func (p *Pipeline) TotalSharedBytes() int

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

func (p *Pipeline) TotalTMEMBytes() int

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

func (p *Pipeline) TotalTMEMColumns() int

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.

func (*Pipeline) Validate

func (p *Pipeline) Validate() *Report

Validate performs comprehensive static verification of the pipeline.

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)
	SharedMemBaseOffset   int                 // Base shared memory offset for stage buffers (when MemorySpace == 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

type PipelineHazard struct {
	StageID     int
	Kind        string
	Description string
}

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 (
	MemorySpaceShared PipelineMemorySpace = "shared"
	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 NewPlan

func NewPlan(limits Limits) (*Plan, error)

NewPlan validates target resource limits.

func (*Plan) Add

func (p *Plan) Add(r Request) (Region, error)

Add assigns a checked aligned offset using first-fit stage reuse.

func (*Plan) DynamicBytes

func (p *Plan) DynamicBytes() int64

func (*Plan) FootprintBytes

func (p *Plan) FootprintBytes() int64

func (*Plan) Limits

func (p *Plan) Limits() Limits

func (*Plan) Regions

func (p *Plan) Regions() []Region

Regions returns a copy of the assigned regions.

func (*Plan) StaticBytes

func (p *Plan) StaticBytes() int64

func (*Plan) ValidateBase

func (p *Plan) ValidateBase(base uint64) error

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.

func (RedistributionPermutation) Map

func (p RedistributionPermutation) Map(row, col int) (int, int, error)
Example
p, _ := TransposePermutation(2, 3)
r, c, _ := p.Map(1, 2)
fmt.Println(r, c)
Output:
2 1

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

func ValidatePipeline(p *Pipeline) *Report

ValidatePipeline performs comprehensive static verification of a pipeline, checking transaction counts, phase parity, latency hiding, alignment, and hardware constraints.

func (*Report) Errors

func (r *Report) Errors() []Issue

Errors returns all issues with SeverityError.

func (*Report) String

func (r *Report) String() string

func (*Report) Valid

func (r *Report) Valid() bool

Valid reports whether the pipeline passed validation without any errors.

func (*Report) Warnings

func (r *Report) Warnings() []Issue

Warnings returns all issues with SeverityWarning.

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 {
	SharedMemBytes      int
	WarpsPerBlock       int
	BlocksPerSM         int
	RegistersPerThread  int
	RegistersPerWarp    int
	TotalWarpsPerSM     int
	TotalSharedMemPerSM 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 Severity

type Severity int

Severity indicates the seriousness of a static validation issue.

const (
	SeverityError Severity = iota + 1
	SeverityWarning
)

func (Severity) String

func (s Severity) String() string

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 IntShape

func IntShape(n int) Shape

IntShape returns the integer shape n.

func ParseShape

func ParseShape(s string) (Shape, error)

ParseShape parses a shape in CuTe notation, such as "((4,2),8)".

func TupleShape

func TupleShape(modes ...Shape) Shape

TupleShape returns the tuple of the given modes. The modes are copied.

func (Shape) Rank

func (s Shape) Rank() int

Rank returns the number of top-level modes: 1 for an integer.

func (Shape) String

func (s Shape) String() 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 {
	Rank          uint32
	Descriptor    Descriptor
	TileOffset    uint64
	BarrierOffset uint64
	ReservedBytes uint64
}

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

type SimulationTrace struct {
	StepsCompleted int
	Events         []StepEvent
}

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

func (s Slice) Address(row Row, column Column) (Address, error)

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

func (s Slice) Sub(row Row, column Column, rows, columns uint32) (Slice, error)

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

type Stage struct {
	Index         int
	Buffer        Buffer
	TMABox        TMABox
	Barrier       Barrier
	ArrivalTokens int
}

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 is the block's shared-memory tile.
	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

func BasisStride(axis, d int) Stride

BasisStride returns the stride d along coordinate axis, written d@axis.

func F2Stride

func F2Stride(bits ...int) Stride

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 IntStride

func IntStride(d int) Stride

IntStride returns the integer stride d.

func ParseStride

func ParseStride(s string) (Stride, error)

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

func TupleStride(modes ...Stride) Stride

TupleStride returns the tuple of the given modes. The modes are copied.

func (Stride) Rank

func (d Stride) Rank() int

Rank returns the number of top-level modes: 1 for a leaf.

func (Stride) String

func (d Stride) String() string

String formats the stride in CuTe notation. A basis stride prints as "d@axis" and an F2 stride as "xor(b0,b1,...)".

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.

const (
	SwizzleNone Swizzle = 0
	Swizzle32B  Swizzle = 32
	Swizzle64B  Swizzle = 64
	Swizzle128B Swizzle = 128
)

func (Swizzle) String

func (s Swizzle) String() string

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) Bytes

func (t SwizzledTile) Bytes() int

Bytes returns the tile's total size.

func (SwizzledTile) Cols

func (t SwizzledTile) Cols() int

Cols returns the tile column count.

func (SwizzledTile) ElementBytes

func (t SwizzledTile) ElementBytes() int

ElementBytes returns the element width.

func (SwizzledTile) Rows

func (t SwizzledTile) Rows() int

Rows returns the tile row count.

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

func (b TMABox) PayloadBytes() int

PayloadBytes returns the total payload bytes transferred by this TMA box.

func (TMABox) RowBytes

func (b TMABox) RowBytes() int

RowBytes returns the byte width of a single row in the 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.

const (
	SM90A  Target = "sm_90a"
	SM100A Target = "sm_100a"
	SM103A Target = "sm_103a"
	SM107A Target = "sm_107a"
	SM100F Target = "sm_100f"
	SM103F Target = "sm_103f"
	SM107F Target = "sm_107f"
	SM121A Target = "sm_121a"
)

func ParseTarget

func ParseTarget(s string) (Target, error)

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
)

func (TensorRole) String

func (r TensorRole) String() string

String returns the stable name of r.

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

func NewTile(rows, cols, elementBytes int, opts ...Option) (Tile, error)

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

func (t Tile) AlignmentBytes() int

AlignmentBytes returns the required base address alignment in bytes.

func (Tile) Cols

func (t Tile) Cols() int

Cols returns the logical column count, excluding padding.

func (Tile) Compatible

func (t Tile) Compatible(other Tile) bool

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

func (t Tile) ElementBytes() int

ElementBytes returns the size of one storage element in bytes.

func (Tile) FootprintBytes

func (t Tile) FootprintBytes() (int, error)

FootprintBytes is the complete row-strided storage footprint, including padding. It is measured in bytes and is checked for host integer overflow.

func (Tile) Identity

func (t Tile) Identity() string

Identity returns a stable identity for the complete layout description.

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) OwnerFor

func (t Tile) OwnerFor(lane, register int) (row, col int, err error)

OwnerFor returns the logical element represented by an owner slot.

func (Tile) Rows

func (t Tile) Rows() int

Rows returns the logical row count.

func (Tile) StrideElements

func (t Tile) StrideElements() int

StrideElements returns the unswizzled row stride in elements.

func (Tile) Swizzle

func (t Tile) Swizzle() Swizzle

Swizzle returns the software permutation span.

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

type TileConfig struct {
	TileM        int
	TileN        int
	TileK        int
	BlockThreads int
	ElemBytes    int
}

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

func LoadTopK(dev *cuda.Device, config TopKConfig, artifact *kernel.Artifact) (*TopK, error)

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

func (t *TopK) Close() error

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

func (t *TopKBF16) Artifact() *kernel.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

func (t *TopKBF16) Close() error

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

type TopKConfig struct {
	Rows, Width, RowStride, K int
	Values                    bool
}

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

type TopKExtents struct {
	Input, RowMetadata, Results int
	ScratchBytes                uint64
}

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:

  1. Single-thread elect.sync issue for tcgen05.mma, tcgen05.cp, tcgen05.commit.
  2. 4-warp 32-row epilogue datapath partitioning for tcgen05.ld and tcgen05.st.
  3. tcgen05.cp scale staging prior to block-scaled tcgen05.mma.
  4. TMEM-sourced operand A readiness (prior tcgen05.mma + commit + wait).
  5. 2-CTA (cta_group::2) matched allocation, CTA-0 MMA issue, and cluster.sync before dealloc.
  6. Underlying cudatmem.Allocator unit, ordering, busy-user, and leak checks.
  7. 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
	SharedOffset, Bytes uint64
}

Transfer is a checked operation description. GlobalToTMEM requires TargetSM100a, TargetSM103a, TargetSM107a, TargetSM100f, TargetSM103f, or TargetSM107f; Validate rejects sm_121a even when Staged is true.

func (Transfer) Validate

func (t Transfer) Validate() error

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>".

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL