Documentation
¶
Overview ¶
Package tileir builds, parses, validates, assembles, and disassembles CUDA Tile IR modules and bytecode.
This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.
Example ¶
package main
import (
"fmt"
"log"
"strings"
"github.com/tmc/lib/nvidia/x/isa/tileir"
)
func main() {
const code = `
cuda_tile.module @demo {
cuda_tile.entry @scale(%A: !cuda_tile.tile<ptr<f32>>) {
%cst = cuda_tile.constant <f32: 2.0> : !cuda_tile.tile<f32>
cuda_tile.return
}
}
`
mod, err := tileir.ParseString(code)
if err != nil {
log.Fatal(err)
}
fn := mod.FindFunction("scale")
fmt.Println("Function:", fn.Name, "Entry:", fn.Entry)
for _, op := range fn.Operations {
fmt.Printf("Op: %s %s\n", op.OpCode, strings.Join(op.Results, ", "))
}
}
Output: Function: scale Entry: true Op: cuda_tile.constant %cst Op: cuda_tile.return
Index ¶
- Constants
- Variables
- func BytecodeVersions(ctx context.Context, opts ...Option) ([]string, error)
- func CompileSemanticTile(ctx context.Context, snap *graph.Snapshot, opts LowerOptions, major, minor int) (*kernel.Artifact, string, error)
- func DisassembleWithOutput(ctx context.Context, bytecode []byte, opts ...Option) (module *Module, output Output, err error)
- func EmitRemarksYAML(w io.Writer, remarks []Remark) error
- func EncodableOps() []string
- func EncodeBytecode(bm *BytecodeModule) ([]byte, error)
- func Explain(opcode string) string
- func ExtractFromELF(elfBytes []byte) ([]byte, error)
- func FormatIdentity(bits uint64, elem Type) string
- func GeneratePinnedTileCPP(kernelName string, params []kernel.Param, tileM, tileN, tileK int64) string
- func GenerateSemanticTileCPP(snap *graph.Snapshot, opts LowerOptions) (string, kernel.Schema, error)
- func HoverInfo(opcode string) string
- func IsBytecode(data []byte) bool
- func IsTileIRBytecode(data []byte) bool
- func Probe(dev *cuda.Device) error
- func SplitOperands(s string) []string
- func ValidateTileCPPSource(src string) error
- func ValidateTileCompileFlags(flags []string) error
- func Version(ctx context.Context, opts ...Option) (path, version string, err error)
- type AttentionCandidate
- type AttentionLowering
- type AttentionOptions
- type Block
- type BytecodeFunction
- type BytecodeGlobal
- type BytecodeModule
- type BytecodeVersion
- type Category
- type Chips
- type DriverJITError
- type Feature
- type FeatureError
- type Function
- func (f *Function) AllOperations() []*Operation
- func (f *Function) FilterOps(predicate func(*Operation) bool) []*Operation
- func (f *Function) OperationAtLine(line int) *Operation
- func (fn *Function) Summary() OpcodeSummary
- func (f *Function) Verify() ([]TokenHazard, []ShapeError)
- func (f *Function) VerifyShapes() []ShapeError
- func (f *Function) VerifyTokens() []TokenHazard
- type FunctionType
- type GatherScatterViewType
- func (g *GatherScatterViewType) IsFloat() bool
- func (g *GatherScatterViewType) IsInt() bool
- func (g *GatherScatterViewType) IsNumber() bool
- func (g *GatherScatterViewType) IsTile() bool
- func (g *GatherScatterViewType) Kind() TypeKind
- func (g *GatherScatterViewType) String() string
- func (g *GatherScatterViewType) TileType() *TileType
- type Global
- type HazardKind
- type Loaded
- type Location
- type LowerOptions
- type LoweringResult
- func LowerSemanticMatMul(snap *graph.Snapshot, opts LowerOptions) (*LoweringResult, error)
- func LowerSemanticMemory(snap *graph.Snapshot, opts LowerOptions) (*LoweringResult, error)
- func LowerSemanticRegion(snap *graph.Snapshot, opts LowerOptions) (*LoweringResult, error)
- func LowerSemanticVector(snap *graph.Snapshot, opts LowerOptions) (*LoweringResult, error)
- type MemorySource
- type Module
- func Disassemble(ctx context.Context, bytecode []byte, opts ...Option) (*Module, error)
- func DisassembleFile(ctx context.Context, path string, opts ...Option) (*Module, error)
- func Parse(r io.Reader) (*Module, error)
- func ParseBytes(b []byte) (*Module, error)
- func ParseString(s string) (*Module, error)
- func (m *Module) AllOperations() []*Operation
- func (m *Module) AssertOpcodes(kernelName string, require, forbid []string) error
- func (m *Module) AttachRemarks(remarks []Remark)
- func (m *Module) CheckOpTable() error
- func (m *Module) CheckOpTableVersion(v BytecodeVersion) error
- func (m *Module) CheckTarget(t Target) error
- func (m *Module) EncodeBytecode() ([]byte, error)
- func (m *Module) EncodeBytecodeVersion(v BytecodeVersion) ([]byte, error)
- func (m *Module) FindFunction(name string) *Function
- func (m *Module) String() string
- func (m *Module) Summary() OpcodeSummary
- func (m *Module) ToBytecode() (*BytecodeModule, error)
- func (m *Module) ToBytecodeVersion(v BytecodeVersion) (*BytecodeModule, error)
- func (m *Module) Verify() ([]TokenHazard, []ShapeError)
- func (m *Module) VerifyShapes() []ShapeError
- func (m *Module) VerifyTokens() []TokenHazard
- func (m *Module) WriteTo(w io.Writer) (int64, error)
- type OpDoc
- type OpcodeSummary
- type Operation
- type OptHintKind
- type OptHintValue
- type OptHints
- type Option
- func WithArch(major, minor int) Option
- func WithAssemblerEnv(env []string) Option
- func WithDebug() Option
- func WithExtraFlags(flags ...string) Option
- func WithFatbinaryPath(path string) Option
- func WithGPUName(name string) Option
- func WithLineInfo() Option
- func WithOptLevel(level int) Option
- func WithPath(path string) Option
- func WithPrintDebugInfo(debug bool) Option
- func WithRemarks(category string) Option
- func WithRemarksAnalysis(category string) Option
- func WithRemarksFailed(category string) Option
- func WithRemarksMissed(category string) Option
- func WithRemarksPassed(category string) Option
- func WithTempDir(dir string) Option
- func WithTileFatbin() Option
- type Output
- type Param
- type PartitionViewType
- func (p *PartitionViewType) IsFloat() bool
- func (p *PartitionViewType) IsInt() bool
- func (p *PartitionViewType) IsNumber() bool
- func (p *PartitionViewType) IsTile() bool
- func (p *PartitionViewType) Kind() TypeKind
- func (p *PartitionViewType) String() string
- func (p *PartitionViewType) TileType() *TileType
- type PointerType
- type PrimitiveType
- type Region
- type RegionBlock
- type Remark
- type Result
- type SemanticMemoryArtifact
- type SemanticMemoryBinding
- type SemanticVectorLayout
- type ShapeError
- type StridedViewType
- type Target
- type TensorViewType
- type TileType
- type TokenHazard
- type TokenType
- type Type
- type TypeError
- type TypeKind
Examples ¶
- Package
- AssembleSemanticMemory
- CompileSemanticTile
- DisassembleWithOutput
- Function (Location)
- GenerateSemanticTileCPP
- Load
- LookupDoc
- LowerOnlineAttention
- LowerSemanticMatMul
- LowerSemanticMemory
- LowerSemanticRegion
- LowerSemanticVector
- Module.AssertOpcodes
- Module.EncodeBytecode
- ParseOptHints
- ParseRemarksYAML
- ParseString
- ParseType
- SemanticMemoryBinding.BytecodeDigest
- SemanticMemoryBinding.References
- SemanticMemoryBinding.Verify
- SemanticVectorLayout.ValidatePointers
- SplitOperands
- WithAssemblerEnv
- WithTempDir
Constants ¶
const ( SectionEndOfBytecode uint8 = 0x00 SectionString uint8 = 0x01 SectionFunc uint8 = 0x02 SectionDebug uint8 = 0x03 SectionConstant uint8 = 0x04 SectionType uint8 = 0x05 SectionGlobal uint8 = 0x06 SectionProducer uint8 = 0x07 )
Section IDs defined by the Tile IR bytecode format specification.
const ( FuncVisibilityPrivate uint8 = 0x01 FuncKindKernel uint8 = 0x02 FuncHasOptHints uint8 = 0x04 )
Function entry flags.
const ( FeatureChip = "chip" FeatureOp = "operation" FeatureAttribute = "attribute" FeatureValue = "value" FeatureType = "type" )
The kinds of Feature.
const ( PadZero = "zero" PadNegZero = "neg_zero" PadNaN = "nan" PadPosInf = "pos_inf" PadNegInf = "neg_inf" )
The padding values of a view: what a load reads for the elements of a tile that lie outside the tensor view. All but PadZero are for floating-point element types only. The empty string is no padding value: the elements read are then unspecified.
const DynamicDim int64 = -1 << 63
DynamicDim is the shape and stride extent standing for a dynamic ("?") dimension. It matches MLIR's ShapedType::kDynamic, which the Tile IR bytecode stores verbatim as a little-endian int64.
Variables ¶
var ( // ForbidScalarMemoryFallbacks catches regressions where 2D/3D tensor views // degrade into scalar pointer offsets and loads. ForbidScalarMemoryFallbacks = []string{ "cuda_tile.load_ptr_tko", "cuda_tile.ptr_to_int", "cuda_tile.int_to_ptr", } // ForbidUnfusedFallbacks catches kernels where fused tensor core operations // fall back to unfused elementwise arithmetic. ForbidUnfusedFallbacks = []string{ "cuda_tile.mulf", "cuda_tile.addf", "cuda_tile.muli", "cuda_tile.addi", } // RequireTMAOperations requires tensor view loads and stores. RequireTMAOperations = []string{ "cuda_tile.load_view_tko", "cuda_tile.store_view_tko", } // RequireTensorCoreMMA requires Tensor Core matrix multiply operations. RequireTensorCoreMMA = []string{ "cuda_tile.mmaf", "cuda_tile.mmai", "cuda_tile.mmaf_scaled", } )
Fallback opcode forbid and requirement lists for Module.AssertOpcodes.
These lists capture unoptimized fallback sequences that compilers emit when falling back from specialized hardware acceleration (TMA, Tensor Cores) to scalar memory access or unfused arithmetic.
var ( // ErrUnsupportedTileOp is returned when a semantic region contains an operation // that cannot be lowered to Tile IR. ErrUnsupportedTileOp = errors.New("tileir: unsupported operation for tile lowering") // ErrInvalidHeader is returned when Tile C++ source violates the pinned contract. ErrInvalidHeader = errors.New("tileir: invalid tile c++ header: requires #include \"cuda_tile.h\"") // ErrInvalidTileGlobal is returned when Tile C++ source lacks __tile_global__. ErrInvalidTileGlobal = errors.New("tileir: tile c++ kernel must be marked __tile_global__") // ErrInvalidCompileFlags is returned when required NVRTC flags are missing or illegal. ErrInvalidCompileFlags = errors.New("tileir: invalid tile compilation flags") // ErrTileCompilerUnsupported is returned by CompileSemanticTile when the // loaded NVRTC predates tile-only compilation. NVRTC 13.0 through 13.2 // reject the --tile-only option. ErrTileCompilerUnsupported = errors.New("tileir: NVRTC does not support tile-only compilation") )
var ( Int1 = PrimitiveType{/* contains filtered or unexported fields */} Int4 = PrimitiveType{/* contains filtered or unexported fields */} Int8 = PrimitiveType{/* contains filtered or unexported fields */} Int16 = PrimitiveType{/* contains filtered or unexported fields */} Int32 = PrimitiveType{/* contains filtered or unexported fields */} Int64 = PrimitiveType{/* contains filtered or unexported fields */} Float16 = PrimitiveType{/* contains filtered or unexported fields */} BFloat16 = PrimitiveType{/* contains filtered or unexported fields */} Float32 = PrimitiveType{/* contains filtered or unexported fields */} TFloat32 = PrimitiveType{/* contains filtered or unexported fields */} Float64 = PrimitiveType{/* contains filtered or unexported fields */} Float8E4M3 = PrimitiveType{/* contains filtered or unexported fields */} Float8E5M2 = PrimitiveType{/* contains filtered or unexported fields */} Float8E8M0 = PrimitiveType{/* contains filtered or unexported fields */} Float4E2M1 = PrimitiveType{/* contains filtered or unexported fields */} Float8E5M3 = PrimitiveType{/* contains filtered or unexported fields */} )
Standard primitive types.
var DefaultBytecodeVersion = BytecodeVersion{Major: 13, Minor: 4}
DefaultBytecodeVersion is the version Module.ToBytecode and Module.EncodeBytecode write: 13.4, which both the CUDA 13.4 and 13.5 tileiras read. A tileiras refuses a file newer than itself.
var ErrArchSuffix = errors.New("tileiras: --gpu-name does not accept an architecture-specific suffix")
ErrArchSuffix is returned when a GPU name carries an architecture-specific suffix, such as "sm_121a". tileiras --gpu-name rejects the suffixed spelling even though ptxas and nvdisasm require it; drop the suffix ("sm_121").
var ErrDriverCannotJITTileIR = errors.New("tileiras: driver cannot JIT Tile IR")
ErrDriverCannotJITTileIR reports that the CUDA driver cannot compile Tile IR bytecode itself. The 580 driver cannot; the cuda-compat 13.5 driver (cuDriverGetVersion 13050) can.
var ErrMalformedBytecode = errors.New("malformed Tile IR bytecode")
ErrMalformedBytecode reports that Load refused bytecode before calling the driver, because it is not framed as a whole Tile IR module. An error the driver returns never matches it.
var ErrMalformedRemark = errors.New("tileiras: malformed compiler remark")
ErrMalformedRemark is returned when a compiler remark format is invalid or malformed.
var ErrNotFound = errors.New("tileir: executable not found in PATH or standard CUDA directories")
ErrNotFound is returned when tileiras or tileirdisasm cannot be located in PATH or standard CUDA directories.
var ErrOpTable = errors.New("tileir: operation does not match the cuda-tile operation table")
ErrOpTable matches, under errors.Is, every error Module.CheckOpTable reports.
var ErrRegions = errors.New("tileir: operations with regions are not encoded from the AST")
ErrRegions reports an operation with regions that the AST encoder does not write. It writes cuda_tile.for, cuda_tile.loop, cuda_tile.if, cuda_tile.reduce and cuda_tile.scan with their regions; it refuses every other region operation, such as cuda_tile.entry or cuda_tile.module written as an operation, rather than encode it without its body, and it refuses one of those five whose regions are missing. Errors matching ErrRegions also match ErrUnsupportedASTEncoding.
var ErrTarget = errors.New("tileir: target lacks a feature")
ErrTarget matches, under errors.Is, every error Target.Validate and Module.CheckTarget report.
var ErrUnsupportedASTEncoding = errors.New("tileir: AST bytecode encoding is unsupported")
ErrUnsupportedASTEncoding reports that the AST does not preserve the NVIDIA operation encoding needed to assemble an executable module.
var Magic = [8]byte{0x7f, 'T', 'i', 'l', 'e', 'I', 'R', 0x00}
Magic header bytes for CUDA Tile IR bytecode files.
var OpcodeNames = map[uint32]string{}/* 108 elements not displayed */
OpcodeNames maps Tile IR opcodes to their dialect-qualified mnemonics, spelled as NVIDIA's dialect spells them.
var OpcodeNumbers = func() map[string]uint32 { m := make(map[string]uint32, len(OpcodeNames)) for k, v := range OpcodeNames { m[v] = k } return m }()
OpcodeNumbers maps known Tile IR operation mnemonics to their numeric opcodes.
var PtrAttrs = []string{"none", "unicast", "multicast"}
PtrAttrs are the pointer classifications in the order of the vendor's PtrAttr enumeration (AttrDefs.td:22-27), which is their encoding: none, an ordinary local pointer, from Tile IR 13.4, and unicast and multicast, which need an NVLink fabric, from 13.5.
var Token = TokenType{}
Token is the canonical instance of TokenType.
Functions ¶
func BytecodeVersions ¶
BytecodeVersions returns the Tile IR bytecode versions read by the tileiras that Assemble would run with opts, as tileiras --list-versions lists them ("13.4"). It honors WithPath and WithAssemblerEnv.
func CompileSemanticTile ¶
func CompileSemanticTile(ctx context.Context, snap *graph.Snapshot, opts LowerOptions, major, minor int) (*kernel.Artifact, string, error)
CompileSemanticTile compiles the bounded semantic Tile C++ source through NVRTC into an authentic Tile IR artifact. It returns the successful compiler log; failed compilation diagnostics remain in the wrapped error. Compilation does not create a device context or execute a kernel; loading, output oracles and hardware qualification remain separate. The selected NVRTC library and headers must support CUDA 13.3 Tile C++. An NVRTC older than 13.3 is refused with ErrTileCompilerUnsupported before compilation; NVRTC_LIB_PATH selects the library.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/isa/tileir"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, _, err := tileir.CompileSemanticTile(ctx, nil, tileir.LowerOptions{}, 9, 0)
fmt.Println(err)
}
Output: context canceled
func DisassembleWithOutput ¶
func DisassembleWithOutput(ctx context.Context, bytecode []byte, opts ...Option) (module *Module, output Output, err error)
DisassembleWithOutput disassembles and parses bytecode while retaining raw output even when execution or parsing fails. Scratch files are removed before return; cleanup errors are joined with execution or parsing errors.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/isa/tileir"
)
func main() {
_, output, err := tileir.DisassembleWithOutput(context.Background(), nil)
fmt.Println(err != nil, len(output.Args))
}
Output: true 0
func EmitRemarksYAML ¶
EmitRemarksYAML writes a slice of Remarks as YAML into w, following the format parsed by ParseRemarksYAML.
func EncodableOps ¶
func EncodableOps() []string
EncodableOps returns the names of the operations that Module.EncodeBytecode writes, such as "cuda_tile.addf", in sorted order. It includes the operations with regions and the terminators of their blocks. Encoding still refuses an operation in the list whose types or attributes are outside what the encoder supports.
func EncodeBytecode ¶
func EncodeBytecode(bm *BytecodeModule) ([]byte, error)
EncodeBytecode encodes a BytecodeModule into binary Tile IR bytecode.
func Explain ¶
Explain returns a formatted multi-line summary of an operation suitable for CLI diagnostics.
func ExtractFromELF ¶
ExtractFromELF searches an ELF image (such as a CUBIN) for embedded Tile IR bytecode.
func FormatIdentity ¶
FormatIdentity returns the identity with the encoding bits of an operand of cuda_tile.reduce or cuda_tile.scan with elements of type elem, as the identities attribute holds it: "0e+00 : f32". The bits are two's complement for an integer and the bit pattern for a floating-point type.
func GeneratePinnedTileCPP ¶
func GeneratePinnedTileCPP(kernelName string, params []kernel.Param, tileM, tileN, tileK int64) string
GeneratePinnedTileCPP returns a deliberately unbuildable declaration. Shapes alone do not specify computation; use GenerateSemanticTileCPP for executable source.
func GenerateSemanticTileCPP ¶
func GenerateSemanticTileCPP(snap *graph.Snapshot, opts LowerOptions) (string, kernel.Schema, error)
GenerateSemanticTileCPP emits a CUDA 13.4 Tile C++ reference kernel and its pointer ABI from the existing semantic snapshot. Launch one tile block per output element (the largest output when there are several). The finite Float32 subset includes pointwise arithmetic, scalar constants, row-major matmul, and rank-one/two sum, max and mean reductions. Reductions are bounded to 64 terms and preserve their sequential accumulation order.
This path emits actual loads, arithmetic and stores. It does not use the incomplete AST bytecode encoder, does not promise tensor-core execution, and does not qualify NaN, infinity, signed-zero or reassociation behavior.
Example ¶
package main
import (
"fmt"
"strings"
cudair "github.com/tmc/lib/nvidia/x/ir/graph"
"github.com/tmc/lib/nvidia/x/isa/tileir"
)
func main() {
g := cudair.NewGraph()
a := g.AddInput("a", []int{2}, cudair.Float32)
g.AddReduce("sum", a, 0)
snap, _ := g.Snapshot()
source, schema, err := tileir.GenerateSemanticTileCPP(snap, tileir.LowerOptions{KernelName: "sum"})
fmt.Println(len(schema.Params), strings.Contains(source, "ct::add("), err)
}
Output: 2 true <nil>
func HoverInfo ¶
HoverInfo returns compact markdown documentation suitable for IDE LSP hover tooltips.
func IsBytecode ¶
IsBytecode reports whether data starts with the Tile IR bytecode magic number.
func IsTileIRBytecode ¶
IsTileIRBytecode checks if data begins with the Tile IR magic header.
func Probe ¶
Probe reports whether the CUDA driver compiles Tile IR for dev, by having it compile and load a module that does nothing. It returns nil if the driver did, a *DriverJITError if the driver has no Tile IR compiler, and another error if the probe failed for another reason.
A driver's diagnosis of a module it did not load is not evidence either way: one that compiles Tile IR reports some malformed modules, and modules of a bytecode version it does not read, in the words of one that does not. Load calls Probe before it believes that diagnosis.
func SplitOperands ¶
SplitOperands splits an operation's operand string at top-level commas. Commas nested inside angle brackets <...>, curly braces {...}, parentheses (...), square brackets [...], or quoted strings "..." are preserved.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/isa/tileir"
)
func main() {
ops := tileir.SplitOperands("%0, !cuda_tile.tile<64x64xf16>, {inbounds = true}")
for _, op := range ops {
fmt.Println(op)
}
}
Output: %0 !cuda_tile.tile<64x64xf16> {inbounds = true}
func ValidateTileCPPSource ¶
ValidateTileCPPSource verifies that a Tile C++ source strictly adheres to the pinned contract.
func ValidateTileCompileFlags ¶
ValidateTileCompileFlags ensures that NVRTC compilation options strictly adhere to the two-tier Option Splitting Model: Source flags (--enable-tile, --tile-only, --tilebc or --tilecubin, --std=c++20) are passed strictly to NVRTC; offline flags (-maxrregcount, -Xptxas, -O3) are forbidden.
func Version ¶
Version returns the path of the tileiras that Assemble would run with opts and the line of its --version output that names the toolkit release, such as "Cuda compilation tools, release 13.5, V13.5.37", or the first line if no line does, so that a record of an assembly can say which assembler made it. It honors WithPath and WithAssemblerEnv. It returns ErrNotFound if there is no tileiras.
Types ¶
type AttentionCandidate ¶
type AttentionCandidate interface {
Snapshot() *graph.Snapshot
Inputs() map[string][]float32
Identity() string
Output() []float32
Reference() []float32
}
AttentionCandidate is the input-bound portion of egraph.OnlineAttentionCandidate. Its methods must not be called concurrently with mutation. A candidate identity is a caller assertion, not qualification: LowerOnlineAttention independently checks the graph, inputs and both outputs. This interface avoids an import cycle with egraph's existing Tile IR consumer.
type AttentionLowering ¶
type AttentionLowering struct {
// contains filtered or unexported fields
}
AttentionLowering owns an input-bound typed online-attention kernel. Its zero value is invalid. The three pointer arguments are scores[N], values[N,D] and output[D], in that order. Launch exactly Grid(1,1,1). Callers must upload the exact Inputs bytes, use disjoint buffers and retain them through completion. Rebinding other values requires a new lowering and numerical check.
The typed module uses finite unrolling, token-ordered masked pointer accesses, FP64 online state and full exp, followed by FP32 output conversion. It covers the existing lane-07 bounds N,D in [1,64]. There are no nested regions and no C++ source fallback. Compiler/device math need independent qualification; host admission cannot establish CUDA exp bits, resources or performance.
func LowerOnlineAttention ¶
func LowerOnlineAttention(candidate AttentionCandidate, opts AttentionOptions) (*AttentionLowering, error)
LowerOnlineAttention lowers the exact readonly nine-node attention graph admitted by lane 07. It consumes a checked candidate through the narrow AttentionCandidate contract, validates that contract again, and emits actual pointer-memory Tile IR. Unrelated exp/reduction graphs remain unsupported by LowerSemanticRegion. Options must explicitly repeat the mask and numerical policy; they cannot silently turn a dense candidate into masked attention.
Excluded scores must already be -Inf, included scores and all values finite. A fully excluded row emits canonical FP32 NaNs and must match the unchanged graph's NaN bits. Nonempty rows are checked against cudaref and the candidate. Snapshot is immutable; all input/output/options slices are copied or consumed before return. No compiler, device allocation or launch occurs here.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/egraph"
"github.com/tmc/lib/nvidia/x/ir/graph"
"github.com/tmc/lib/nvidia/x/isa/tileir"
)
func main() {
g := graph.NewGraph()
s := g.AddInput("scores", []int{2}, graph.Float32)
v := g.AddInput("values", []int{2, 1}, graph.Float32)
e := g.AddUnary("exp", g.AddBinary("sub", s, g.AddReduce("max", s, 0)))
p := g.AddBinary("div", e, g.AddReduce("sum", e, 0))
out := g.AddMatMul(g.AddReshape(p, []int{1, 2}), v)
if err := g.SetOutputs(out); err != nil {
fmt.Println(err)
return
}
snapshot, err := g.Snapshot()
if err != nil {
fmt.Println(err)
return
}
candidate, err := egraph.NewCheckedOnlineAttentionCandidate(snapshot,
map[string][]float32{"scores": {0, 0}, "values": {3, -1}}, 1, egraph.AttentionCandidatePolicy{})
if err != nil {
fmt.Println(err)
return
}
lowered, err := tileir.LowerOnlineAttention(candidate, tileir.AttentionOptions{TileSize: 1})
if err != nil {
fmt.Println(err)
return
}
data, err := lowered.Result().Module.EncodeBytecode()
fmt.Println(lowered.Verify(), err, len(data) > 0, lowered.Result().Schema.TotalParamBytes)
fmt.Println(lowered.Inputs()["values"], len(lowered.Identity()))
}
Output: <nil> <nil> true 24 [3 -1] 64
func (*AttentionLowering) Identity ¶
func (a *AttentionLowering) Identity() string
Identity returns the bound candidate, input, mask, policy and bytecode digest.
func (*AttentionLowering) Inputs ¶
func (a *AttentionLowering) Inputs() map[string][]float32
Inputs returns detached input values under their semantic names.
func (*AttentionLowering) Result ¶
func (a *AttentionLowering) Result() *LoweringResult
Result returns the existing backend lowering, usable by AssembleSemanticMemory. The returned structure is borrowed. Verify detects edits to its module, ABI, grid or semantic source map. Source is empty: this route emits typed bytecode.
func (*AttentionLowering) Verify ¶
func (a *AttentionLowering) Verify() error
Verify checks the retained module/ABI/source-map binding. It does not inspect device buffers, authenticate a candidate or establish compiler acceptance.
type AttentionOptions ¶
type AttentionOptions struct {
KernelName string
TileSize int
Excluded []bool
Absolute, Relative float64
}
AttentionOptions declares the finite online-row recipe and its input-bound comparison policy. Excluded is nil for dense attention, otherwise true marks a score which must already be -Inf. It does not introduce a mask operator. Absolute and Relative permit abs(got-want) <= Absolute+Relative*abs(want). Their zero values require identical FP32 bits, including signed zero.
type BytecodeFunction ¶
type BytecodeFunction struct {
Name string
SignatureIndex int
Signature Type
EntryFlag uint8
IsEntry bool
IsPrivate bool
HasOptHints bool
OptHints string
OptHintsBytes []byte
LocIndex int // index of the function's list in the Debug section, or 0
Loc Location // source location, if LocIndex is not 0
BodyBytes []byte
Operations []*Operation
// BodyDecodeError is nonnil when the body is preserved as opaque bytes.
// Operations is then nil; no partial or guessed AST is published.
BodyDecodeError error
}
BytecodeFunction represents a decoded function record from the function table.
type BytecodeGlobal ¶
type BytecodeGlobal struct {
SymbolName string
TypeIndex int
Type Type
ConstantIndex int
Value string
Alignment uint64
Constant bool
Private bool
}
BytecodeGlobal is a global of the global section: the fields the file holds, with Type and Value, the printed elements, resolved.
type BytecodeModule ¶
type BytecodeModule struct {
Version BytecodeVersion
Producer string
Strings []string
Types []Type
Constants [][]byte
Functions []*BytecodeFunction
Globals []*BytecodeGlobal
// ASTDecodeError records unsupported module metadata. Such a module cannot
// be converted to an AST or re-encoded by this bounded codec.
ASTDecodeError error
// contains filtered or unexported fields
}
BytecodeModule represents a decoded binary Tile IR module.
func DecodeBytecode ¶
func DecodeBytecode(r io.Reader) (*BytecodeModule, error)
DecodeBytecode decodes a binary Tile IR bytecode stream from an io.Reader.
func DecodeBytecodeBytes ¶
func DecodeBytecodeBytes(data []byte) (*BytecodeModule, error)
DecodeBytecodeBytes decodes a binary Tile IR bytecode byte slice.
func (*BytecodeModule) ToModule ¶
func (bm *BytecodeModule) ToModule() *Module
ToModule converts a fully decoded supported body subset into an AST Module. It returns nil if any function has BodyDecodeError; raw bodies remain available for byte-preserving inspection and re-encoding.
type BytecodeVersion ¶
BytecodeVersion captures the major, minor, and tag version components.
func ASTBytecodeVersions ¶
func ASTBytecodeVersions() []BytecodeVersion
ASTBytecodeVersions returns the bytecode versions Module.EncodeBytecodeVersion writes, oldest first.
func ChooseBytecodeVersion ¶
func ChooseBytecodeVersion(readable []string) (BytecodeVersion, error)
ChooseBytecodeVersion returns the newest version in ASTBytecodeVersions that a reader lists in readable, such as the output of tileiras --list-versions ("13.4", "13.5"). That listing is the way to choose: an older tileiras has accepted an empty module of a version whose function bodies it then refused, so assembling a probe module of each version says less than the listing does.
func ParseBytecodeVersion ¶
func ParseBytecodeVersion(s string) (BytecodeVersion, error)
ParseBytecodeVersion parses a version written as "13.4".
func (BytecodeVersion) String ¶
func (v BytecodeVersion) String() string
type Category ¶
type Category uint8
Category identifies the functional category of a Tile IR operation.
const ( CatUnknown Category = iota CatTileMemory // TMA loads/stores, views, partition views CatComputeMMA // Tensor Core matrix multiply-accumulate CatComputeElement // Elementwise vector arithmetic and transcendental functions CatComputeInteger // Packed integer arithmetic CatShapeLayout // Reshape, permute, broadcast, convert_layout CatReduction // Reductions and scans across tile dimensions CatSyncToken // Token creation and join operations CatControlFlow // Loops, conditionals, returns CatIndexing // Grid/Block ID and tensor shape queries CatTypeCast // Bitcast, floating-point conversions )
func OpcodeCategory ¶
OpcodeCategory returns the functional category of the operation opcode.
type Chips ¶
type Chips struct {
Min int // if nonzero, only chips numbered Min or more
Only []int // if not empty, only these chips
}
Chips is a set of chips, each named by the number of its architecture: 121 for sm_121. The zero Chips is every chip.
type DriverJITError ¶
A DriverJITError is the error Load returns when the driver cannot JIT Tile IR. It matches ErrDriverCannotJITTileIR and the driver's error under errors.Is.
func (*DriverJITError) Error ¶
func (e *DriverJITError) Error() string
func (*DriverJITError) Unwrap ¶
func (e *DriverJITError) Unwrap() []error
type Feature ¶
type Feature struct {
Kind string // one of the Feature constants
Name string // "cuda_tile.fpowi", "cuda_tile.ftoi saturating", "f4E2M1FN", "sm_107"
// Since is the first bytecode version with the feature. For a chip
// it is the first version that may name the chip.
Since BytecodeVersion
// Chips is the chips with the feature, and ChipSource is where that
// restriction is recorded. Unverified says the restriction is copied
// from another front end and nothing here confirms it.
Chips Chips
ChipSource string
Unverified bool
}
A Feature is one thing a module may use that some target lacks.
func Features ¶
func Features() []Feature
Features returns the features Module.CheckTarget knows: every chip, every operation, every attribute and attribute value newer than its operation, and every element type that is newer than the dialect or restricted to some chips. Versions are those of the cuda-tile TableGen sources. The list is sorted by kind, then name.
Note: f8E8M0FNU is present since bytecode 13.2, but tileiras V13.2.86 refuses ftof to f8E8M0FNU with rounding_mode zero or positive_inf; use tileiras 13.3 or later. Also, tileiras 13.4 (Cuda compilation tools, release 13.4, V13.4.59) fails (exit status 5) on direct cuda_tile.ftoi from f8E4M3FN, f8E5M2 or f8E8M0FNU and traps (SIGTRAP) on cuda_tile.load_view_tko of a gather_scatter_view of f8E8M0FNU; tileiras 13.5 (V13.5.37) accepts both.
type FeatureError ¶
type FeatureError struct {
Target Target
Feature Feature
// Func and Op are the function and operation that use the feature.
// Op is nil for the type of a parameter and for the target itself.
Func string
Op *Operation
}
A FeatureError reports a feature a target lacks.
func (*FeatureError) Error ¶
func (e *FeatureError) Error() string
func (*FeatureError) Is ¶
func (e *FeatureError) Is(target error) bool
func (*FeatureError) Need ¶
func (e *FeatureError) Need() string
Need returns the error without the function: what the feature needs and what the target is.
type Function ¶
type Function struct {
Name string
Entry bool // true for kernel entry points (cuda_tile.entry)
Params []*Param
Returns []string
Blocks []*Block
Operations []*Operation
Loc Location
LocRef string // raw location symbol, e.g. "#loc1"
StartLine int
EndLine int
OptHints string
Remarks []Remark
}
Function represents a kernel entry point or device function in Tile IR.
Example (Location) ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/isa/tileir"
)
func main() {
m := &tileir.Module{Functions: []*tileir.Function{{
Name: "k",
Entry: true,
Loc: tileir.Location{File: "example.com/m/k.go", Line: 3, Column: 1},
Operations: []*tileir.Operation{
{OpCode: "cuda_tile.return", Loc: tileir.Location{File: "example.com/m/k.go", Line: 5, Column: 1}},
},
}}}
code, err := m.EncodeBytecode()
if err != nil {
fmt.Println(err)
return
}
bm, err := tileir.DecodeBytecodeBytes(code)
if err != nil {
fmt.Println(err)
return
}
fn := bm.Functions[0]
fmt.Println(fn.Name, "at", fn.Loc)
fmt.Println(fn.Operations[0].OpCode, "at", fn.Operations[0].Loc)
}
Output: k at example.com/m/k.go:3:1 cuda_tile.return at example.com/m/k.go:5:1
func (*Function) AllOperations ¶
AllOperations returns the operations of f in program order, each followed by the operations of its regions: f.Operations holds only the top level, so the body of a cuda_tile.for is reached only through it.
func (*Function) FilterOps ¶
FilterOps returns the operations, at any depth of nesting, matching a predicate function.
func (*Function) OperationAtLine ¶
OperationAtLine returns the operation, at any depth of nesting, located on the given line number, or nil.
func (*Function) Summary ¶
func (fn *Function) Summary() OpcodeSummary
Summary returns opcode frequency statistics for this function.
func (*Function) Verify ¶
func (f *Function) Verify() ([]TokenHazard, []ShapeError)
Verify runs all static verifications (token hazards and shape errors) on the function.
func (*Function) VerifyShapes ¶
func (f *Function) VerifyShapes() []ShapeError
VerifyShapes validates that tile shapes and dimensions are mathematically compatible.
func (*Function) VerifyTokens ¶
func (f *Function) VerifyTokens() []TokenHazard
VerifyTokens verifies token lifetimes, DAG dependencies, and memory coherence.
type FunctionType ¶
FunctionType represents a function signature with input parameter types and result types.
func NewFunction ¶
func NewFunction(inputs, results []Type) *FunctionType
NewFunction constructs a new FunctionType.
func (*FunctionType) IsFloat ¶
func (f *FunctionType) IsFloat() bool
func (*FunctionType) IsInt ¶
func (f *FunctionType) IsInt() bool
func (*FunctionType) IsNumber ¶
func (f *FunctionType) IsNumber() bool
func (*FunctionType) IsTile ¶
func (f *FunctionType) IsTile() bool
func (*FunctionType) Kind ¶
func (f *FunctionType) Kind() TypeKind
func (*FunctionType) String ¶
func (f *FunctionType) String() string
type GatherScatterViewType ¶
type GatherScatterViewType struct {
TileShape []int64
View *TensorViewType
SparseDim int
Padding string // one of the Pad constants, or ""
}
GatherScatterViewType is a view of a tensor view in which one dimension, SparseDim, is reached by an index for each element of the tile and the others by a start offset and a contiguous run of TileShape elements. A load or store takes, for each dimension, the start offset of that run as a scalar and, for SparseDim, a rank-one tile of TileShape[SparseDim] element indices in its place.
An element index outside the tensor view makes a row of padding: a load reads Padding for it and a store writes nothing. So does an element of a run that reaches outside the tensor view.
func (*GatherScatterViewType) IsFloat ¶
func (g *GatherScatterViewType) IsFloat() bool
func (*GatherScatterViewType) IsInt ¶
func (g *GatherScatterViewType) IsInt() bool
func (*GatherScatterViewType) IsNumber ¶
func (g *GatherScatterViewType) IsNumber() bool
func (*GatherScatterViewType) IsTile ¶
func (g *GatherScatterViewType) IsTile() bool
func (*GatherScatterViewType) Kind ¶
func (g *GatherScatterViewType) Kind() TypeKind
func (*GatherScatterViewType) String ¶
func (g *GatherScatterViewType) String() string
func (*GatherScatterViewType) TileType ¶
func (g *GatherScatterViewType) TileType() *TileType
TileType returns the type of the tiles of the view: TileShape elements of the tensor view's element type.
type Global ¶
type Global struct {
Name string // the symbol, without the @
Type string // the type of Value, a rank-one tile
TypeVal Type // parsed Type, if resolved
Value string // the elements, as a constant prints them: dense<"0x...">
Alignment int64 // of the memory in bytes, or 0 for the element's
Constant bool // no kernel writes the memory (Tile IR 13.3)
Private bool // the host does not reach the memory (Tile IR 13.3)
Loc Location
}
A Global is memory of the module, cuda_tile.global (Ops.td:2550-2611): a rank-one tile of elements, set to Value when the module is loaded, that a kernel reaches through the pointer cuda_tile.get_global returns. It prints as
cuda_tile.global @name {alignment = 4, value = dense<"0x...">} : !cuda_tile.tile<4xf32>
with the unit attribute constant and symbol_visibility = private in the dictionary when they are set.
type HazardKind ¶
type HazardKind int
HazardKind describes the category of a static synchronization hazard.
const ( HazardUnconsumedToken HazardKind = iota HazardUnsynchronizedRead HazardUnsynchronizedWrite HazardDanglingAsyncTransfer HazardImpureBody )
func (HazardKind) String ¶
func (k HazardKind) String() string
String returns the string representation of the hazard kind.
type Loaded ¶
type Loaded struct {
Module driver.Module // zero if loading failed
DriverVersion int // cuDriverGetVersion, such as 13050; 0 if unknown
InfoLog string
ErrorLog string
}
A Loaded is the result of Load: the module the driver compiled, if it compiled one, and what the driver said. It is returned on failure too, if the driver was asked.
func Load ¶
Load passes Tile IR bytecode to the CUDA driver (cuModuleLoadDataEx) in dev's primary context, so that the driver compiles it for dev, and returns the module and the driver's logs. The caller unloads a nonzero Module with dev's context current, even when Load also returns an error.
No tileiras process runs, and nothing is produced but the loaded module: there is no CUBIN to cache or inspect, and no remarks. Use Assemble for those, or for a driver that cannot JIT Tile IR, for which Load returns a *DriverJITError.
The driver takes a module without its length and finds the end itself, so Load first checks that bytecode is framed as a whole module: a header, sections that lie inside it, and the end marker last. It returns a nil Loaded and an error matching ErrMalformedBytecode, without calling the driver, if it is not. The driver given a module cut short reads the memory after it, and its answer depends on what is there.
Load returns a *DriverJITError only if the driver also fails Probe: a driver that compiles Tile IR answers some modules it rejects as one that does not would.
Example ¶
ExampleLoad needs a GPU and a driver with a Tile IR compiler, so it is compiled but not run.
package main
import (
"errors"
"fmt"
"log"
"os"
"github.com/tmc/lib/nvidia/x/cuda"
"github.com/tmc/lib/nvidia/x/isa/tileir"
)
func main() {
dev, err := cuda.NewDevice(0)
if err != nil {
log.Fatal(err)
}
defer dev.Close()
bytecode, err := os.ReadFile("rmsnorm_2048.tilebc")
if err != nil {
log.Fatal(err)
}
res, err := tileir.Load(dev, bytecode)
if errors.Is(err, tileir.ErrDriverCannotJITTileIR) {
fmt.Printf("driver %d cannot JIT Tile IR; assemble with tileiras instead\n", res.DriverVersion)
return
}
if err != nil {
log.Fatalf("%v\n%s", err, res.ErrorLog)
}
fmt.Printf("loaded with driver %d\n", res.DriverVersion)
}
Output:
func LoadLineInfo ¶
LoadLineInfo is like Load but asks the driver for line-number information (CU_JIT_GENERATE_LINE_INFO), as tileiras --lineinfo does. If bytecode has a debug section the CUBIN the driver compiles then has a line table naming the files and lines of that section, and CUPTI delivers that CUBIN to a subscriber of module loads. Measured with cuda-compat 13.5 on a GB10: the instructions are those Load compiles; without the option the driver ignores the debug section, and with the option and no debug section the line table names the file "<unknown>".
type Location ¶
type Location struct {
File string // resolved source file path
Line int // 1-based source line
Column int // 1-based source column
Scope string // subprogram or lexical block name
}
Location represents a source code coordinate attached to an operation or function.
type LowerOptions ¶
LowerOptions configures the translation from a validated cudair.Snapshot to tileir.Module.
type LoweringResult ¶
type LoweringResult struct {
Module *Module
Schema kernel.Schema
Source string
// Grid is the standalone launch grid for a bound pointer-memory region.
// Legacy analysis lowerings leave it zero; their launch policy is external.
Grid [3]uint32
// Memory binds a pointer-memory module to its source/ABI map.
// It is nil for legacy analysis and C++ lowerings.
Memory *SemanticMemoryBinding
// Vector describes the logical extent and launch of a vector memory route.
Vector *SemanticVectorLayout
}
LoweringResult bundles the translated Module AST, ABI schema, and source attribution.
func LowerSemanticMatMul ¶
func LowerSemanticMatMul(snap *graph.Snapshot, opts LowerOptions) (*LoweringResult, error)
LowerSemanticMatMul lowers readonly contiguous row-major FP32 A[M,K] and B[K,N] to their sole matrix-product output. Each dimension must be 1..4. TileM/N/K must be zero or one; the scalar operations are fully unrolled, accumulating widened products in FP64 in increasing K order before one FP32 conversion per output. No Tensor Core instruction is promised.
The pointer ABI is A, B, output, regardless of graph input order. The caller must launch exactly Grid(1,1,1), provide distinct FP32-aligned nonaliasing buffers of at least 4*M*K, 4*K*N and 4*M*N bytes without address wrap, and prevent concurrent writes. This function does not allocate, compile or execute device storage. Source locations remain in Memory's sidecar.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/graph"
"github.com/tmc/lib/nvidia/x/isa/tileir"
)
func main() {
g := graph.NewGraph()
a := g.AddInput("a", []int{2, 3}, graph.Float32)
b := g.AddInput("b", []int{3, 4}, graph.Float32)
product := g.AddMatMul(a, b)
product.Name = "product"
if err := g.SetOutputs(product); err != nil {
fmt.Println(err)
return
}
snap, err := g.Snapshot()
if err != nil {
fmt.Println(err)
return
}
r, err := tileir.LowerSemanticMatMul(snap, tileir.LowerOptions{})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(r.Grid, r.Schema.TotalParamBytes, r.Memory.Verify(r))
}
Output: [1 1 1] 24 <nil>
func LowerSemanticMemory ¶
func LowerSemanticMemory(snap *graph.Snapshot, opts LowerOptions) (*LoweringResult, error)
LowerSemanticMemory lowers exactly two readonly contiguous FP32 inputs of shape [1] and their single add output to a void pointer-memory kernel. The caller must launch Grid(1,1,1), supply three distinct nonaliasing device buffers with at least one FP32 each, and prevent concurrent writes. This function allocates no device storage and emits no C++ helper source.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/graph"
"github.com/tmc/lib/nvidia/x/isa/tileir"
)
func exampleMemory() *tileir.LoweringResult {
g := graph.NewGraph()
x := g.AddInput("x", []int{1}, graph.Float32)
y := g.AddInput("y", []int{1}, graph.Float32)
_ = g.SetOutputs(g.AddBinary("add", x, y))
snapshot, err := g.Snapshot()
if err != nil {
return nil
}
r, err := tileir.LowerSemanticMemory(snapshot, tileir.LowerOptions{})
if err != nil {
return nil
}
return r
}
func main() {
r := exampleMemory()
fmt.Println(r.Module.Functions[0].Name, r.Grid, r.Schema.TotalParamBytes)
}
Output: tile_singleton_add [1 1 1] 24
func LowerSemanticRegion ¶
func LowerSemanticRegion(snap *graph.Snapshot, opts LowerOptions) (*LoweringResult, error)
LowerSemanticRegion lowers a validated semantic region (cudair.Snapshot) to a typed Tile IR Module.
It validates operations, maps parameter ABIs, retains semantic node IDs in operation attributes, attaches Go source coordinates to Module.Locations, and validates token dependencies and shapes.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/graph"
"github.com/tmc/lib/nvidia/x/isa/tileir"
)
func main() {
g := graph.NewGraph()
a := g.AddInput("a", []int{5, 3}, graph.Float32)
g.AddReduce("sum", a, 1)
snap, err := g.Snapshot()
if err != nil {
panic(err)
}
r, err := tileir.LowerSemanticRegion(snap, tileir.LowerOptions{KernelName: "row_sum", TileM: 4})
if err != nil {
panic(err)
}
fmt.Println(r.Module.Functions[0].Name, len(r.Schema.Params), r.Grid)
}
Output: row_sum 2 [2 1 1]
func LowerSemanticVector ¶
func LowerSemanticVector(snap *graph.Snapshot, opts LowerOptions) (*LoweringResult, error)
LowerSemanticVector lowers a contiguous readonly FP32 vector add to typed pointer-memory bytecode. Inputs and output must have identical rank-one shapes. TileM selects a power-of-two width1..1024 (default128); TileN/K must be zero or one. The caller supplies three distinct, FP32-aligned, nonaliasing device buffers of Vector.BufferBytes and launches exactly Grid, without concurrent writes or pointer-address wrap. Empty vectors have no pointer ABI, memory instructions or device work: the caller skips launch. This function does not invoke a compiler, allocate or execute device memory.
Example ¶
g := graph.NewGraph()
x := g.AddInput("x", []int{5}, graph.Float32)
y := g.AddInput("y", []int{5}, graph.Float32)
_ = g.SetOutputs(g.AddBinary("add", x, y))
s, _ := g.Snapshot()
r, err := LowerSemanticVector(s, LowerOptions{TileM: 4})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(r.Grid, r.Vector.Length, r.Vector.BufferBytes)
Output: [2 1 1] 5 20
type MemorySource ¶
type MemorySource struct {
NodeID int
Role string
ABIIndex int // -1 for arithmetic rather than a pointer parameter
Operations []int
Values []string
Location graph.SourceLocation
}
MemorySource records the semantic origin of emitted SSA values and ABI roles. Locations live in this sidecar; this route does not emit debug bytecode.
type Module ¶
type Module struct {
Name string
Producer string
Functions []*Function
Globals []*Global
Comments []string
Locations map[string]Location
}
Module represents a parsed or decoded Tile IR translation unit.
func Disassemble ¶
Disassemble disassembles Tile IR bytecode using tileirdisasm and parses it into a Module AST.
func DisassembleFile ¶
DisassembleFile reads a Tile IR bytecode file and returns its parsed Module AST.
func ParseBytes ¶
ParseBytes parses textual Tile IR from a byte slice.
func ParseString ¶
ParseString parses textual Tile IR from a string.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/isa/tileir"
)
func main() {
tileIR := `entry @vector_add(%arg0: tile<ptr<f32>>, %arg1: tile<ptr<f32>>) {
%c0 = constant <i32: 0> : tile<i32> loc(#loc)
return loc(#loc)
}
#loc = loc("vector_add.cu":12:4)
`
mod, err := tileir.ParseString(tileIR)
if err != nil {
panic(err)
}
fn := mod.FindFunction("vector_add")
fmt.Printf("Function: %s, Params: %d, Ops: %d\n", fn.Name, len(fn.Params), len(fn.Operations))
fmt.Printf("First Op: %s at %s\n", fn.Operations[0].OpCode, fn.Operations[0].Loc)
}
Output: Function: vector_add, Params: 2, Ops: 2 First Op: constant at vector_add.cu:12:4
func (*Module) AllOperations ¶
AllOperations returns a slice of all operations across all functions in the module.
func (*Module) AssertOpcodes ¶
AssertOpcodes checks that required opcodes are present and forbidden fallback opcodes are absent. If kernelName is non-empty, the assertion evaluates against the named kernel; otherwise it evaluates across the entire module.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/isa/tileir"
)
func main() {
const code = `
cuda_tile.module @gemm {
cuda_tile.entry @matmul(%A: !cuda_tile.tile<ptr<f16>>, %B: !cuda_tile.tile<ptr<f16>>, %C: !cuda_tile.tile<ptr<f32>>) {
%tok0 = cuda_tile.make_token : !cuda_tile.token
%vA = cuda_tile.load_view_tko %A, %tok0 : (!cuda_tile.tile<ptr<f16>>, !cuda_tile.token) -> !cuda_tile.tile<64x64xf16>
%vB = cuda_tile.load_view_tko %B, %tok0 : (!cuda_tile.tile<ptr<f16>>, !cuda_tile.token) -> !cuda_tile.tile<64x64xf16>
%cst = cuda_tile.constant <f32: 0.0> : !cuda_tile.tile<64x64xf32>
%acc = cuda_tile.mmaf %vA, %vB, %cst : (!cuda_tile.tile<64x64xf16>, !cuda_tile.tile<64x64xf16>, !cuda_tile.tile<64x64xf32>) -> !cuda_tile.tile<64x64xf32>
cuda_tile.return
}
}
`
mod, _ := tileir.ParseString(code)
err := mod.AssertOpcodes("matmul", []string{"cuda_tile.mmaf"}, tileir.ForbidScalarMemoryFallbacks)
fmt.Println("Audit passed:", err == nil)
}
Output: Audit passed: true
func (*Module) AttachRemarks ¶
AttachRemarks correlates compiler optimization remarks emitted by tileiras to Operation and Function AST nodes by matching DebugLoc line/file coordinates and function symbol names.
func (*Module) CheckOpTable ¶
CheckOpTable is Module.CheckOpTableVersion at DefaultBytecodeVersion.
func (*Module) CheckOpTableVersion ¶
func (m *Module) CheckOpTableVersion(v BytecodeVersion) error
CheckOpTableVersion reports an error for every operation, attribute or type in m that NVIDIA's operation table does not define for bytecode version v. The table is opSpecs, generated from the cuda-tile TableGen sources (see nvidia/internal/cmd/gentileops).
An operation must be spelled "cuda_tile.<mnemonic>", name an opSpecs entry, and exist at v. Its attributes must be a dictionary whose keys are attributes of that operation that exist at v, and it must set every attribute the table requires at v. A required attribute newer than v may be set to its default, which a reader of version v supplies. Its result count must be the table's, and its operand count must lie between the operation's plain operands and its plain plus optional operands (with no upper bound for a variadic operand). Every parameter and result type must parse.
An operation's regions, if it has any, must number the table's count, and each must hold one nonempty block that ends in a terminator and has no other; the operations inside are checked like any other. For cuda_tile.for, the results, the iteration block arguments after the induction variable and the cuda_tile.continue operands must each number the init values. For cuda_tile.reduce, the results and the cuda_tile.yield operands must each number the operands, and the block arguments twice that. An operation written without its regions is checked as before; the encoder refuses it.
CheckOpTableVersion checks the table only. It does not check attribute values, operand types or SSA dominance, and passing it does not mean the module encodes or computes anything in particular. Every error matches ErrOpTable.
func (*Module) CheckTarget ¶
CheckTarget reports a FeatureError for every use in m of a feature that t lacks: an operation, attribute, attribute value or element type newer than t.Version, or one that t.Arch does not have. A required attribute newer than t.Version may have its default value, which the encoder leaves out. If t itself is not valid, CheckTarget returns the error of Target.Validate.
CheckTarget agrees with Module.CheckOpTableVersion about versions, and reports what that cannot: which feature, and where. It does not check anything else about m.
func (*Module) EncodeBytecode ¶
EncodeBytecode encodes the complete supported AST subset, or returns no bytes and an error. The package function separately preserves decoded raw bodies.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/isa/tileir"
)
func main() {
m := &tileir.Module{Functions: []*tileir.Function{{Name: "one", Entry: true,
Operations: []*tileir.Operation{
{OpCode: "cuda_tile.constant", Results: []string{"%one"},
TypeVal: tileir.NewTile([]int64{4}, tileir.Float32), Attributes: "{value = 1.0}"},
{OpCode: "cuda_tile.return"},
},
}}}
data, err := m.EncodeBytecode()
if err != nil {
fmt.Println(err)
return
}
bm, err := tileir.DecodeBytecodeBytes(data)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(bm.Functions[0].Name, len(bm.Functions[0].Operations))
}
Output: one 2
func (*Module) EncodeBytecodeVersion ¶
func (m *Module) EncodeBytecodeVersion(v BytecodeVersion) ([]byte, error)
EncodeBytecodeVersion is like EncodeBytecode but writes bytecode version v. ChooseBytecodeVersion picks v for a given tileiras.
Note: tileiras V13.2.86 refuses ftof to f8E8M0FNU with rounding_mode zero or positive_inf; use tileiras 13.3 or later.
func (*Module) FindFunction ¶
FindFunction returns the function with the given symbol name, or nil if not found.
func (*Module) Summary ¶
func (m *Module) Summary() OpcodeSummary
Summary returns aggregated opcode frequency statistics across all functions in the module.
func (*Module) ToBytecode ¶
func (m *Module) ToBytecode() (*BytecodeModule, error)
ToBytecode serializes the supported straight-line numeric, token, vector, pointer-memory and view-memory subset, plus cuda_tile.for, cuda_tile.loop, cuda_tile.if, cuda_tile.reduce and cuda_tile.scan, at DefaultBytecodeVersion. The view-memory operations are make_tensor_view, make_partition_view, make_strided_view, make_gather_scatter_view, get_tensor_shape, get_index_space_shape, load_view_tko and store_view_tko; a partition or strided view must have the identity dim_map. It preserves typed SSA operands, constant bits, supported attributes and function return types. It refuses constructs outside this subset, including other region operations, attention, globals, location references and unknown attributes. It writes the locations in Function.Loc and Operation.Loc as a debug section; a module with no locations has no debug section. Module names, comments and SSA spelling are not wire identities.
It first checks m with Module.CheckOpTableVersion; a module that fails that check is refused with an error matching both ErrUnsupportedASTEncoding and ErrOpTable.
func (*Module) ToBytecodeVersion ¶
func (m *Module) ToBytecodeVersion(v BytecodeVersion) (*BytecodeModule, error)
ToBytecodeVersion is like ToBytecode but writes bytecode version v, which must be one of ASTBytecodeVersions. It refuses an operation, attribute or enum value that v does not contain; a required attribute newer than v must have its default value, and is not written. A producer is dropped from a file older than 13.3, which has no place for one.
func (*Module) Verify ¶
func (m *Module) Verify() ([]TokenHazard, []ShapeError)
Verify checks all functions in the module for token hazards and shape errors.
func (*Module) VerifyShapes ¶
func (m *Module) VerifyShapes() []ShapeError
VerifyShapes runs shape verification across all functions in the module.
func (*Module) VerifyTokens ¶
func (m *Module) VerifyTokens() []TokenHazard
VerifyTokens runs token hazard verification across all functions in the module.
type OpDoc ¶
type OpDoc struct {
OpCode string `json:"opcode"` // e.g. "cuda_tile.load_view_tko"
Mnemonic string `json:"mnemonic"` // e.g. "load_view_tko"
Category Category `json:"category"` // Functional classification
Summary string `json:"summary"` // 1-2 sentence overview
Syntax []string `json:"syntax,omitempty"` // MLIR textual prototype(s)
Description string `json:"description,omitempty"` // Architectural behavior prose
MinArch string `json:"min_arch,omitempty"` // e.g. "sm_90" (Hopper) or "sm_100" (Blackwell)
TokenInputs int `json:"token_inputs,omitempty"` // Number of consumed tokens
TokenOutputs int `json:"token_outputs,omitempty"` // Number of produced tokens
OperandTypes []string `json:"operand_types,omitempty"` // Acceptable operand type constraints
ResultTypes []string `json:"result_types,omitempty"` // Acceptable result type constraints
HardwareLowering string `json:"hardware_lowering,omitempty"` // Target PTX/SASS instruction (e.g. "cp.async.bulk.tensor", "wgmma")
FallbackHazards []string `json:"fallback_hazards,omitempty"` // Fallback hazards if rejected by compiler
}
OpDoc represents structured reference documentation and semantic constraints for a Tile IR operation.
func LookupDoc ¶
LookupDoc returns documentation for a Tile IR operation. Lookup is case-insensitive and the "cuda_tile." prefix is optional. Example: LookupDoc("cuda_tile.mmaf"), LookupDoc("mmaf"), and LookupDoc("load_view_tko") all resolve.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/isa/tileir"
)
func main() {
doc := tileir.LookupDoc("cuda_tile.mmaf")
fmt.Printf("%s: %s [%s]\n", doc.OpCode, doc.Category, doc.HardwareLowering)
}
Output: cuda_tile.mmaf: Tensor Core MMA [wgmma.mma_async / mma.sync]
type OpcodeSummary ¶
OpcodeSummary records instruction counts and categories for a function or module. It mirrors cudaptx.OpcodeSummary to provide consistent auditing across the GPU compiler stack.
func (*OpcodeSummary) CategoryCount ¶
func (s *OpcodeSummary) CategoryCount(cat Category) int
CategoryCount returns the number of operations classified under cat.
func (*OpcodeSummary) Count ¶
func (s *OpcodeSummary) Count(prefix string) int
Count returns the number of operations whose opcode matches prefix.
Matching is case-insensitive and the "cuda_tile." prefix may be omitted. A prefix matches a whole mnemonic or any mnemonic beginning with it, so Count("mma") counts cuda_tile.mmaf, cuda_tile.mmai and cuda_tile.mmaf_scaled together, and Count("load_view_tko") counts exactly that operation.
type Operation ¶
type Operation struct {
Line int // 1-based line number in Tile IR text
Results []string // SSA result value names, e.g. ["%cst_16_i32"]
OpCode string // mnemonic or opcode, e.g. "cuda_tile.mmaf" or "constant"
Operands []string // operand value names, e.g. ["%arg0", "%arg1"]
Type string // result type string, e.g. "tile<16x16xf32>"
TypeVal Type // parsed type value if resolved
Attributes string // inline attributes, e.g. "{inbounds = true}"
Loc Location // resolved source location
LocRef string // raw location symbol, e.g. "#loc10"
Raw string // full raw text of the operation line
Remarks []Remark // compiler remarks attached to this operation
Regions []*Region // nested regions, e.g. the body of cuda_tile.for
}
Operation represents an individual SSA statement in Tile IR.
func (*Operation) IsConstant ¶
IsConstant reports whether this operation creates a constant value.
func (*Operation) IsMMA ¶
IsMMA reports whether this operation represents a Tensor Core matrix multiplication.
func (*Operation) IsTMA ¶
IsTMA reports whether this operation represents an asynchronous TMA memory transfer.
func (*Operation) String ¶
String returns op as one line of Tile IR text. It returns op.Raw, trimmed, only when Raw parses to op's results, opcode, operands, attributes, type and location reference; otherwise it prints those fields, which are what the encoder reads. Text and bytecode therefore never describe different operations, and an operation read by the parser and left alone prints as it was read.
An operation with regions prints on several lines, from its fields and never from Raw: the fields, " {", each region's blocks, and "}".
type OptHintKind ¶
type OptHintKind uint8
OptHintKind identifies the value kind of an entry in an architecture's optimization_hints dictionary.
const ( OptHintBool OptHintKind = iota + 1 OptHintInt OptHintString )
type OptHintValue ¶
type OptHintValue struct {
Kind OptHintKind
Bool bool
Int int64
Str string
}
OptHintValue is one typed value inside an optimization_hints architecture dictionary.
func (OptHintValue) String ¶
func (v OptHintValue) String() string
String formats v in MLIR OptimizationHintsAttr assembly form (without type suffix, matching NVIDIA/cuda-tile OptimizationHintsAttr::print).
type OptHints ¶
type OptHints map[string]map[string]OptHintValue
OptHints represents a CUDA Tile optimization_hints attribute: a map from architecture key (for example "sm_103", "sm_100", or "default") to a map of hint key (for example "latency", "allow_tma", "occupancy", "num_cta_in_cga") to typed value.
func ParseOptHints ¶
ParseOptHints parses textual optimization_hints syntax such as "<>", "<{}>", or "<sm_103 = {latency = 4, allow_tma = true}>".
Example ¶
package main
import (
"fmt"
"log"
"github.com/tmc/lib/nvidia/x/isa/tileir"
)
func main() {
hints, err := tileir.ParseOptHints("<sm_103 = {latency = 4, allow_tma = true}>")
if err != nil {
log.Fatal(err)
}
fmt.Println(hints.String())
}
Output: <sm_103 = {allow_tma = true, latency = 4}>
type Option ¶
type Option func(*config)
Option configures execution of the tileiras assembler.
func WithArch ¶
WithArch specifies the target architecture by major and minor numbers (e.g. 9, 0 -> "sm_90").
func WithAssemblerEnv ¶
WithAssemblerEnv sets the environment of tileiras subprocesses. A nil environment inherits the current process environment.
Example ¶
package main
import (
"context"
"fmt"
"log"
"os"
"path/filepath"
"github.com/tmc/lib/nvidia/x/isa/tileir"
)
func main() {
dir, err := os.MkdirTemp("", "tileiras-example-")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
bin := filepath.Join(dir, "tileiras")
script := []byte("#!/bin/sh\n[ \"$CUDA_HOME\" = /toolkit ] || exit 1\necho 'tileiras 13.5'\n")
if err := os.WriteFile(bin, script, 0o700); err != nil {
log.Fatal(err)
}
_, version, err := tileir.Version(context.Background(), tileir.WithPath(bin),
tileir.WithAssemblerEnv([]string{"CUDA_HOME=/toolkit"}))
if err != nil {
log.Fatal(err)
}
fmt.Println(version)
}
Output: tileiras 13.5
func WithDebug ¶
func WithDebug() Option
WithDebug enables generation of device debug information (-g).
func WithExtraFlags ¶
WithExtraFlags supplies additional command-line flags to tileiras.
func WithFatbinaryPath ¶
WithFatbinaryPath specifies an explicit path to the fatbinary packaging executable.
func WithGPUName ¶
WithGPUName specifies the target GPU architecture name, e.g. "sm_90", "sm_100", "sm_121".
The name must be unsuffixed. tileiras rejects the architecture-specific spelling "sm_121a" that ptxas and nvdisasm require; Assemble reports ErrArchSuffix for such a name rather than invoking the assembler.
func WithLineInfo ¶
func WithLineInfo() Option
WithLineInfo enables line number generation (--lineinfo).
func WithOptLevel ¶
WithOptLevel specifies the optimization level (0 to 3). Default is 3.
func WithPath ¶
WithPath specifies an explicit path to the tileiras executable. WithPath specifies an explicit path to the tileiras or tileirdisasm executable.
func WithPrintDebugInfo ¶
WithPrintDebugInfo specifies whether to annotate disassembly with debug locations (-g).
func WithRemarks ¶
WithRemarks enables compiler remarks for a category ("all", "memory", "tensorcore", "none").
func WithRemarksAnalysis ¶
WithRemarksAnalysis enables analysis remarks for a category.
func WithRemarksFailed ¶
WithRemarksFailed enables failed remarks for a category.
func WithRemarksMissed ¶
WithRemarksMissed enables missed remarks for a category.
func WithRemarksPassed ¶
WithRemarksPassed enables passed remarks for a category.
func WithTempDir ¶
WithTempDir selects a scratch parent. Empty uses the operating system default.
Example ¶
package main
import (
"context"
"fmt"
"github.com/tmc/lib/nvidia/x/isa/tileir"
)
func main() {
_, _, err := tileir.DisassembleWithOutput(context.Background(), nil, tileir.WithTempDir("."))
fmt.Println(err != nil)
}
Output: true
func WithTileFatbin ¶
func WithTileFatbin() Option
WithTileFatbin requests output packaged as a CUDA fatbinary (.fatbin) containing both the assembled ELF CUBIN and the Tile IR bitcode.
type Param ¶
type Param struct {
Name string // e.g. "%arg0"
Type string // e.g. "tile<ptr<f32>>"
TypeVal Type // parsed type representation if available
}
Param represents a function parameter.
type PartitionViewType ¶
type PartitionViewType struct {
TileShape []int64
View *TensorViewType
DimMap []int32
Padding string // one of the Pad constants, or ""
}
PartitionViewType is a view of a tensor view as a grid of tiles of TileShape that starts at the origin, without gaps or overlap. Tile (i, j, ...) holds elements i*TileShape[0] through (i+1)*TileShape[0]-1 of dimension 0, and so on. A tile at the far edge may reach outside the tensor view: a load reads Padding there and a store writes nothing there.
DimMap maps each tile dimension to a dimension of the tensor view; nil is the identity. The identity is not printed, whichever way it is written.
func (*PartitionViewType) IsFloat ¶
func (p *PartitionViewType) IsFloat() bool
func (*PartitionViewType) IsInt ¶
func (p *PartitionViewType) IsInt() bool
func (*PartitionViewType) IsNumber ¶
func (p *PartitionViewType) IsNumber() bool
func (*PartitionViewType) IsTile ¶
func (p *PartitionViewType) IsTile() bool
func (*PartitionViewType) Kind ¶
func (p *PartitionViewType) Kind() TypeKind
func (*PartitionViewType) String ¶
func (p *PartitionViewType) String() string
func (*PartitionViewType) TileType ¶
func (p *PartitionViewType) TileType() *TileType
TileType returns the type of the tiles of the view: TileShape elements of the tensor view's element type.
type PointerType ¶
type PointerType struct {
Pointee Type
// Attr is the pointer's classification, "none", "unicast" or
// "multicast", or "" if it has none. "none" and "" are distinct
// types. See [PtrAttrs].
Attr string
}
PointerType represents a typed global device pointer.
func NewPointer ¶
func NewPointer(pointee Type) *PointerType
NewPointer constructs a new PointerType.
func (*PointerType) IsFloat ¶
func (p *PointerType) IsFloat() bool
func (*PointerType) IsInt ¶
func (p *PointerType) IsInt() bool
func (*PointerType) IsNumber ¶
func (p *PointerType) IsNumber() bool
func (*PointerType) IsTile ¶
func (p *PointerType) IsTile() bool
func (*PointerType) Kind ¶
func (p *PointerType) Kind() TypeKind
func (*PointerType) String ¶
func (p *PointerType) String() string
type PrimitiveType ¶
type PrimitiveType struct {
// contains filtered or unexported fields
}
PrimitiveType represents scalar integer and floating-point types.
func (PrimitiveType) IsFloat ¶
func (p PrimitiveType) IsFloat() bool
func (PrimitiveType) IsInt ¶
func (p PrimitiveType) IsInt() bool
func (PrimitiveType) IsNumber ¶
func (p PrimitiveType) IsNumber() bool
func (PrimitiveType) IsTile ¶
func (p PrimitiveType) IsTile() bool
func (PrimitiveType) Kind ¶
func (p PrimitiveType) Kind() TypeKind
func (PrimitiveType) String ¶
func (p PrimitiveType) String() string
type Region ¶
type Region struct {
Blocks []*RegionBlock
}
A Region is the body of an operation such as cuda_tile.for or cuda_tile.reduce, or a branch of a cuda_tile.if. Every region operation in cuda-tile v13.5.0 has single-block regions (Ops.td, "let regions": SizedRegion<1>), but for the else branch of an if, which may have no block (MaxSizedRegion<1>).
type RegionBlock ¶
A RegionBlock is one block of a Region: its arguments, then its operations, the last of which is a terminator such as cuda_tile.yield or cuda_tile.continue.
type Remark ¶
type Remark struct {
Kind string // "Passed", "Failed", "Missed", "Analysis"
Pass string // e.g. "Memory", "Tensor-core", "Hints"
Name string // e.g. "RemarkMemoryTmaLoadFailed", "RemarkMemoryLoadInstructionSelected"
File string // source file path from DebugLoc
Line int // source line number from DebugLoc
Column int // source column number from DebugLoc
Function string // enclosing function or kernel name
RemarkId int // internal remark identifier
Remark string // descriptive message text
Instruction string // instruction type, e.g. "TMA Load instruction", "FMA"
Shape string // shape descriptor, e.g. "[16, 16]"
Reason string // failure or missed reason if reported
Args map[string]string // raw key-value arguments
}
Remark represents a compiler optimization remark emitted by tileiras.
func ParseRemarksYAML ¶
ParseRemarksYAML parses YAML-formatted remarks emitted by tileiras --remark-format=yaml.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/isa/tileir"
)
func main() {
yamlData := []byte(`--- !Failure
Pass: Memory
Name: RemarkMemoryTmaLoadFailed
DebugLoc: { File: 'kernel.cu', Line: 14, Column: 5 }
Function: matrix
Args:
- RemarkId: 5
- Remark: Failed to select TMA load instruction
- Reason: non-contiguous stride along dim 1
...
`)
remarks, err := tileir.ParseRemarksYAML(yamlData)
if err != nil {
panic(err)
}
for _, rmk := range remarks {
if rmk.IsTMAFailure() {
fmt.Printf("TMA Bottleneck at line %d: %s (Reason: %s)\n", rmk.Line, rmk.Remark, rmk.Reason)
}
}
}
Output: TMA Bottleneck at line 14: Failed to select TMA load instruction (Reason: non-contiguous stride along dim 1)
func (Remark) IsTMAFailure ¶
IsTMAFailure reports whether this remark records a failed TMA load or store selection.
func (Remark) IsTensorCoreFailure ¶
IsTensorCoreFailure reports whether an MMA operation failed to use Tensor Cores and fell back to FMA.
func (Remark) IsTensorCoreMMA ¶
IsTensorCoreMMA reports whether an MMA operation was optimized to use Tensor Cores.
type Result ¶
type Result struct {
CUBIN []byte // Assembled device CUBIN ELF image
Fatbin []byte // Packaged fatbinary image, if WithTileFatbin was requested
Remarks []Remark // Compiler optimization remarks
Log string // Raw compiler output (stdout/stderr)
}
Result encapsulates assembled binary outputs and parsed compiler remarks.
func (*Result) TMAFailures ¶
TMAFailures returns all remarks indicating TMA instruction-selection bottlenecks.
func (*Result) TensorCoreFailures ¶
TensorCoreFailures returns all remarks indicating an MMA operation failed to use Tensor Cores.
type SemanticMemoryArtifact ¶
type SemanticMemoryArtifact struct {
Artifact *kernel.Artifact
BytecodeDigest string
Remarks []Remark
Log string
}
SemanticMemoryArtifact contains the assembled CUBIN descriptor and observed diagnostics. Toolchain version is unobserved unless reported by the tool; the current tileiras Result has no version field. No launch is performed.
func AssembleSemanticMemory ¶
func AssembleSemanticMemory(ctx context.Context, r *LoweringResult, target string) (*SemanticMemoryArtifact, error)
AssembleSemanticMemory serializes a bound pointer-memory lowering and invokes tileiras.Assemble for an unsuffixed target. A successful artifact still requires separately qualified compiler/device execution and caller buffers.
Example ¶
package main
import (
"context"
"errors"
"fmt"
"github.com/tmc/lib/nvidia/x/isa/tileir"
)
func main() {
// Suffix rejection is a pure preflight; no assembler is invoked.
_, err := tileir.AssembleSemanticMemory(context.Background(), nil, "sm_90a")
fmt.Println(errors.Is(err, tileir.ErrArchSuffix))
}
Output: true
type SemanticMemoryBinding ¶
type SemanticMemoryBinding struct {
// contains filtered or unexported fields
}
SemanticMemoryBinding binds a pointer-memory lowering's bytes, ABI, launch grid and source map. Its zero value is not usable. Accessors return copies.
func (*SemanticMemoryBinding) BytecodeDigest ¶
func (b *SemanticMemoryBinding) BytecodeDigest() string
BytecodeDigest returns the SHA-256 digest of the admitted typed bytecode.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/graph"
"github.com/tmc/lib/nvidia/x/isa/tileir"
)
func exampleMemory() *tileir.LoweringResult {
g := graph.NewGraph()
x := g.AddInput("x", []int{1}, graph.Float32)
y := g.AddInput("y", []int{1}, graph.Float32)
_ = g.SetOutputs(g.AddBinary("add", x, y))
snapshot, err := g.Snapshot()
if err != nil {
return nil
}
r, err := tileir.LowerSemanticMemory(snapshot, tileir.LowerOptions{})
if err != nil {
return nil
}
return r
}
func main() {
r := exampleMemory()
fmt.Println(len(r.Memory.BytecodeDigest()))
}
Output: 64
func (*SemanticMemoryBinding) References ¶
func (b *SemanticMemoryBinding) References() []MemorySource
References returns detached semantic/source/ABI records.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/graph"
"github.com/tmc/lib/nvidia/x/isa/tileir"
)
func exampleMemory() *tileir.LoweringResult {
g := graph.NewGraph()
x := g.AddInput("x", []int{1}, graph.Float32)
y := g.AddInput("y", []int{1}, graph.Float32)
_ = g.SetOutputs(g.AddBinary("add", x, y))
snapshot, err := g.Snapshot()
if err != nil {
return nil
}
r, err := tileir.LowerSemanticMemory(snapshot, tileir.LowerOptions{})
if err != nil {
return nil
}
return r
}
func main() {
r := exampleMemory()
for _, source := range r.Memory.References() {
fmt.Println(source.Role, source.ABIIndex)
}
}
Output: input 0 input 1 add -1 output 2
func (*SemanticMemoryBinding) Verify ¶
func (b *SemanticMemoryBinding) Verify(r *LoweringResult) error
Verify checks that the lowering still matches its bound bytes, source map, pointer ABI and grid. It does not validate caller device buffers or aliases.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/ir/graph"
"github.com/tmc/lib/nvidia/x/isa/tileir"
)
func exampleMemory() *tileir.LoweringResult {
g := graph.NewGraph()
x := g.AddInput("x", []int{1}, graph.Float32)
y := g.AddInput("y", []int{1}, graph.Float32)
_ = g.SetOutputs(g.AddBinary("add", x, y))
snapshot, err := g.Snapshot()
if err != nil {
return nil
}
r, err := tileir.LowerSemanticMemory(snapshot, tileir.LowerOptions{})
if err != nil {
return nil
}
return r
}
func main() {
r := exampleMemory()
fmt.Println(r.Memory.Verify(r))
r.Grid[0] = 2
fmt.Println(r.Memory.Verify(r) != nil)
}
Output: <nil> true
type SemanticVectorLayout ¶
type SemanticVectorLayout struct {
Length int64
TileSize int64
BufferBytes uint64
NoDeviceWork bool
}
SemanticVectorLayout describes a logical vector's source launch contract. Changes invalidate its SemanticMemoryBinding. BufferBytes is per ABI role.
func (*SemanticVectorLayout) ValidatePointers ¶
func (v *SemanticVectorLayout) ValidatePointers(pointers [3]uint64) error
ValidatePointers checks three numeric device-address ranges for extent, FP32 alignment and nonaliasing before ABI packing. It does not establish device placement, allocation ownership or lifetime. Empty layouts perform no address checks because they must not be launched.
Example ¶
v := &SemanticVectorLayout{Length: 5, TileSize: 4, BufferBytes: 20}
fmt.Println(v.ValidatePointers([3]uint64{0x1000, 0x1014, 0x1028}))
fmt.Println(v.ValidatePointers([3]uint64{0x1000, 0x1004, 0x1028}) != nil)
Output: <nil> true
type ShapeError ¶
ShapeError represents a tile dimension or rank mismatch.
func (ShapeError) String ¶
func (e ShapeError) String() string
type StridedViewType ¶
type StridedViewType struct {
TileShape []int64
TraversalStrides []int64
View *TensorViewType
DimMap []int32
Padding string // one of the Pad constants, or ""
}
StridedViewType is a view of a tensor view as tiles of TileShape that start at multiples of TraversalStrides: tile (i, j, ...) starts at element i*TraversalStrides[0] of dimension 0, and so on. A stride larger than the tile leaves gaps between tiles, and a smaller one makes them overlap. Its index space has ceil(extent/stride) tiles along each dimension, and a tile at the far edge may reach outside the tensor view: a load reads Padding there and a store writes nothing there.
DimMap maps each tile dimension to a dimension of the tensor view; nil is the identity. The identity is not printed, whichever way it is written.
func (*StridedViewType) IsFloat ¶
func (s *StridedViewType) IsFloat() bool
func (*StridedViewType) IsInt ¶
func (s *StridedViewType) IsInt() bool
func (*StridedViewType) IsNumber ¶
func (s *StridedViewType) IsNumber() bool
func (*StridedViewType) IsTile ¶
func (s *StridedViewType) IsTile() bool
func (*StridedViewType) Kind ¶
func (s *StridedViewType) Kind() TypeKind
func (*StridedViewType) String ¶
func (s *StridedViewType) String() string
func (*StridedViewType) TileType ¶
func (s *StridedViewType) TileType() *TileType
TileType returns the type of the tiles of the view: TileShape elements of the tensor view's element type.
type Target ¶
type Target struct {
Version BytecodeVersion
// Arch is the chip as the assembler's --gpu-name spells it, such as
// "sm_121". An empty Arch is any chip: no chip restriction is
// checked.
Arch string
}
A Target is what a module is compiled for: a bytecode version and, optionally, a chip.
func (Target) Validate ¶
Validate reports whether t is a target Module.EncodeBytecodeVersion can write for: its version is one of ASTBytecodeVersions, and its chip, if any, is one Tile IR names at that version.
type TensorViewType ¶
type TensorViewType struct {
Shape []int64
Strides []int64
ElementType Type
// Attr is the classification of the pointer the view is made from,
// as in [PointerType].
Attr string
}
TensorViewType models an N-dimensional view into a global memory tensor.
Strides has the same length as Shape when present; a nil Strides encodes as an empty stride list, which the assembler accepts only for a rank-0 view. Dynamic extents are represented by DynamicDim.
func (*TensorViewType) IsFloat ¶
func (v *TensorViewType) IsFloat() bool
func (*TensorViewType) IsInt ¶
func (v *TensorViewType) IsInt() bool
func (*TensorViewType) IsNumber ¶
func (v *TensorViewType) IsNumber() bool
func (*TensorViewType) IsTile ¶
func (v *TensorViewType) IsTile() bool
func (*TensorViewType) Kind ¶
func (v *TensorViewType) Kind() TypeKind
func (*TensorViewType) String ¶
func (v *TensorViewType) String() string
type TileType ¶
TileType represents a statically shaped multidimensional tile.
func (*TileType) NumElements ¶
NumElements returns the total element count in the tile, or 1 for rank 0.
type TokenHazard ¶
type TokenHazard struct {
Op *Operation
Kind HazardKind
Message string
}
TokenHazard represents a static synchronization hazard in Tile IR.
func (TokenHazard) String ¶
func (h TokenHazard) String() string
type TokenType ¶
type TokenType struct{}
TokenType represents a synchronization token for ordering asynchronous TMA transfers.
type Type ¶
type Type interface {
Kind() TypeKind
String() string
IsTile() bool
IsNumber() bool
IsFloat() bool
IsInt() bool
}
Type represents any valid Tile IR data or structural type.
func ParseType ¶
ParseType parses a Tile IR textual type specification into a Type.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/isa/tileir"
)
func main() {
t1, _ := tileir.ParseType("!cuda_tile.tile<16x32xbf16>")
t2, _ := tileir.ParseType("ptr<f32>")
fmt.Printf("%s (isTile=%v)\n", t1, t1.IsTile())
fmt.Printf("%s (isTile=%v)\n", t2, t2.IsTile())
}
Output: !cuda_tile.tile<16x32xbf16> (isTile=true) !cuda_tile.ptr<f32> (isTile=false)
type TypeKind ¶
type TypeKind uint8
TypeKind identifies the variant of a Tile IR type.
const ( // Primitive integer types (tags 0-4, 22). KindInt1 TypeKind = 0 KindInt8 TypeKind = 1 KindInt16 TypeKind = 2 KindInt32 TypeKind = 3 KindInt64 TypeKind = 4 KindInt4 TypeKind = 22 // Floating point types (tags 5-11, 18, 19, 0x82). KindFloat16 TypeKind = 5 KindBFloat16 TypeKind = 6 KindFloat32 TypeKind = 7 KindTFloat32 TypeKind = 8 KindFloat64 TypeKind = 9 KindFloat8E4M3 TypeKind = 10 KindFloat8E5M2 TypeKind = 11 KindFloat8E8M0 TypeKind = 18 KindFloat4E2M1 TypeKind = 19 KindFloat8E5M3 TypeKind = 0x82 // Structural / composite types (tags 12-17, 20-21). KindPointer TypeKind = 12 KindTile TypeKind = 13 KindTensorView TypeKind = 14 KindPartitionView TypeKind = 15 KindFunction TypeKind = 16 KindToken TypeKind = 17 KindGatherScatter TypeKind = 20 KindStridedView TypeKind = 21 )
Source Files
¶
- assemble_semantic.go
- assembler_remarks.go
- ast.go
- ast_arith.go
- ast_atomic.go
- ast_bitwise.go
- ast_bytecode.go
- ast_compare.go
- ast_constant.go
- ast_control.go
- ast_convert.go
- ast_global.go
- ast_griddep.go
- ast_math.go
- ast_matmul.go
- ast_memory.go
- ast_multimem.go
- ast_pack.go
- ast_reduce.go
- ast_region.go
- ast_shape.go
- ast_utility.go
- ast_view.go
- attention.go
- audit.go
- bytecode.go
- debug_bytecode.go
- disasm.go
- doc.go
- doc_data.go
- emit.go
- frame.go
- load.go
- lower.go
- operands.go
- opspec.go
- opspec_gen.go
- opt_hints.go
- optable.go
- parser.go
- printer.go
- probe.go
- reduction.go
- region_bytecode.go
- remarks.go
- semantic_matmul.go
- semantic_memory.go
- semantic_vector.go
- target.go
- tileiras.go
- types.go
- verify.go
- version.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package refmath has the float64 mathematical functions that the Tile IR interpreter and CPU implementations of Tile IR operations compute with as the reference for what a device computes.
|
Package refmath has the float64 mathematical functions that the Tile IR interpreter and CPU implementations of Tile IR operations compute with as the reference for what a device computes. |
|
Package tilebuild constructs CUDA Tile IR operations for github.com/tmc/lib/nvidia/x/tileir modules.
|
Package tilebuild constructs CUDA Tile IR operations for github.com/tmc/lib/nvidia/x/tileir modules. |
|
Package tileprintf formats what the Tile IR operation print_tko prints: a C printf format whose expressions each print a tile of integers or floats.
|
Package tileprintf formats what the Tile IR operation print_tko prints: a C printf format whose expressions each print a tile of integers or floats. |