Documentation
¶
Overview ¶
Package ptx parses and audits NVIDIA PTX modules, parses ptxas -v resource diagnostics, and verifies PTX barrier/fence schedules and recorded-run campaign verdicts.
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 (
"crypto/sha256"
"encoding/hex"
"fmt"
isaptx "github.com/tmc/lib/nvidia/x/isa/ptx"
)
func main() {
const ptx = `.version 8.7
.target sm_90
.address_size 64
.visible .entry race_kernel()
{
.reg .b32 %r0;
.reg .b64 %rd0;
atom.global.add.u32 %r0, [%rd0], 1;
bar.sync 0;
ret;
}
`
sites, err := isaptx.Analyze(ptx)
if err != nil {
panic(err)
}
fmt.Printf("sites found: %d\n", len(sites))
rewrite, err := isaptx.Perturb(ptx, isaptx.Options{
Seed: 42,
Intensity: 1.0,
})
if err != nil {
panic(err)
}
fmt.Printf("sites injected: %d\n", rewrite.Report.SitesInjected)
digest := sha256.Sum256([]byte(ptx))
verdict := isaptx.Classify(isaptx.RunRecord{
ExitCode: 0,
Exited: true,
Stdout: "PASS: verified\n",
PTXDigest: hex.EncodeToString(digest[:]),
ExpectedPTXDigest: hex.EncodeToString(digest[:]),
PTXDigestSource: "runner_receipt", // synthetic recorded outcome
})
fmt.Printf("verdict: %s\n", verdict)
}
Output: sites found: 2 sites injected: 2 verdict: Pass
Index ¶
- Constants
- Variables
- func CountAsyncCopyInstructions(ptxSrc string) int
- func EmitSetMaxNRegPTX(action string, regs int) (string, error)
- func HasMismatchMarker(output string) bool
- func HasSkipMarker(output string) bool
- func InstructionMinPTX(mnemonic string) string
- func InstructionMinTarget(mnemonic string) string
- func IsDataType(typ string) bool
- func IsDirective(name string) bool
- func IsInstructionKeyword(mnemonic string) bool
- func IsInstructionQualifier(mnemonic, qualifier string) bool
- func IsPackedType(typ string) bool
- func IsSpecialRegister(name string) bool
- func MergeModules(primaryPTX, libraryPTX string, opts MergeOptions) (string, error)
- func RunRecordedHelper(ctx context.Context, args []string) error
- func SplitOperands(s string) []string
- func TypeBitSize(typ string) int
- func VectorElementCount(typ string) int
- func WriteOutputReceipt(w io.Writer, out *outputcontract.RecordedOutput) error
- type Access
- type AsyncPipelineConfig
- type AsyncPipelinePlan
- func (p *AsyncPipelinePlan) Config() AsyncPipelineConfig
- func (p *AsyncPipelinePlan) CountAsyncCopyInstructions(ptxSrc string) int
- func (p *AsyncPipelinePlan) EmitCUDA(funcName string) (string, error)
- func (p *AsyncPipelinePlan) EstimateOverlap(numTiles int, loadCyclesPerTile, mathCyclesPerTile int64) (OverlapReport, error)
- type CampaignArmResults
- type CampaignArmSummary
- type CampaignArms
- type CampaignOptions
- type CampaignReport
- type Category
- type ConfirmationSummary
- type Diagnostic
- type Doc
- type DocKind
- type Function
- type HoverInfo
- type InjectionDecision
- type Instruction
- type Kernel
- type Label
- type Location
- type MergeOptions
- type MismatchIdentity
- type ModifierInfo
- type Module
- func (m *Module) AssertOpcodes(kernelName string, require, forbid []string) error
- func (m *Module) AuditArchitecture(kernelName string) error
- func (m *Module) AuditVersion(kernelName string) error
- func (m *Module) ExplainLoadError(err error) error
- func (m *Module) Kernel(name string) *Kernel
- func (m *Module) Summary(kernelName string) (*OpcodeSummary, error)
- type OpcodeSummary
- type OperandInfo
- type Options
- type OverlapReport
- type Param
- type Reach
- type RecordedCustody
- type RecordedProcess
- type RecordedRunOptions
- type RegBudgetConfig
- type RegBudgetReport
- type Report
- type Rewrite
- type RewriteReport
- type RunBound
- type RunRecord
- type SeedResult
- type SeedStatus
- type Site
- type SiteKind
- type Span
- type Target
- type TargetDeclaration
- type Tuning
- type Verdict
Examples ¶
- Package
- AddressOrigins
- Analyze
- CampaignArms
- Classify
- Explain
- InstructionCategory
- Label
- LookupDoc
- MergeModules
- MismatchIdentity
- Module.AssertOpcodes
- Module.AuditArchitecture
- NewAsyncPipelinePlan
- OpcodeSummary.CategoryCount
- ParsePTXASInfo
- Perturb
- Replay
- RunRecorded
- RunRecordedHelper
- SpecializeRegBudget
- StopRuns
- TargetDeclaration
- WriteOutputReceipt
Constants ¶
const DefaultMaxSleepNs = 64000
DefaultMaxSleepNs is the default maximum nanosleep delay ceiling (64 µs).
const PTXISAToolkit = "CUDA 13.5"
PTXISAToolkit identifies the toolkit for this ISA.
const PTXISAVersion = "9.5"
PTXISAVersion is the PTX ISA version the generated tables describe.
Variables ¶
var ( // ForbidSIMDFallbacks contains scalar integer arithmetic and bit extraction // opcodes emitted when packed SIMD operations (such as dp4a or dp2a) fall back // to scalar computation and lane unpacking. ForbidSIMDFallbacks = []string{ "mul.lo", "mul.wide", "mad.lo", "mad.wide", "shr", "bfe", "shf", } // ForbidFMAFallbacks contains separate multiply and add opcodes emitted when // fused multiply-add (fma) falls back to unfused arithmetic. ForbidFMAFallbacks = []string{ "mul", "add", } // ForbidWarpShuffleFallbacks contains shared memory opcodes emitted when // warp register shuffles (shfl.sync) fall back to shared memory staging. ForbidWarpShuffleFallbacks = []string{ "ld.shared", "st.shared", } )
Fallback opcode forbid lists for Module.AssertOpcodes.
These lists capture legal-but-unoptimized fallback sequences that compiler toolchains emit when they fail to lower to specialized hardware instructions. Auditing against these lists ensures that silent performance regressions fail the audit gate.
var ErrUnboundedRun = errors.New("cudaptx: run between stop points is not bounded")
ErrUnboundedRun reports a kernel in which some path can run without end between two stop points: a loop with no stop point in it whose trip count the analysis cannot prove.
var ErrVersionUnaudited = errors.New("cudaptx: module .version is newer than the generated tables")
ErrVersionUnaudited reports that a module's .version is newer than PTXISAVersion, the ISA version the generated tables describe. The instruction tables record the version each instruction was introduced in, so they can place a lower bound on a module they cover and can say nothing about one they do not. Unknown mnemonics and qualifiers fail the audit.
Module.AuditVersion returns an error wrapping ErrVersionUnaudited rather than reporting success, so that a module the tables cannot cover is an explicit unknown instead of a pass. Callers that want to proceed anyway test for it with errors.Is.
Functions ¶
func CountAsyncCopyInstructions ¶
CountAsyncCopyInstructions scans PTX or inline-PTX source and returns the number of cp.async.* instructions outside of comments.
func EmitSetMaxNRegPTX ¶
EmitSetMaxNRegPTX returns a Hopper/Blackwell inline PTX statement that dynamically increases or decreases the calling warp's register allocation.
Per the PTX ISA specification for setmaxnreg, action must be "inc" or "dec", regs must be in [24, 256], and regs must be a multiple of 8.
func HasMismatchMarker ¶
HasMismatchMarker reports whether output contains an explicit failure marker.
func HasSkipMarker ¶
HasSkipMarker reports whether output contains a recognized test skip marker.
func InstructionMinPTX ¶
InstructionMinPTX returns the earliest PTX ISA version that introduced the instruction, or an empty string if unknown.
func InstructionMinTarget ¶
InstructionMinTarget returns the minimum GPU architecture required by the instruction (e.g. "sm_90", "sm_100a"), "all", or an empty string if unknown.
func IsDataType ¶
IsDataType reports whether typ (with or without leading dot) is a recognized PTX fundamental, packed, sub-byte, or microscaling data type.
func IsDirective ¶
IsDirective reports whether name (with or without leading dot) is a recognized PTX directive statement or qualifier.
func IsInstructionKeyword ¶
IsInstructionKeyword reports whether mnemonic is a recognized PTX instruction keyword.
A false result does not mean the mnemonic is invalid: ptxas, not this table, decides what PTX is accepted, and a newer ISA has keywords this table does not. Use it to audit parser output, never to reject input.
func IsInstructionQualifier ¶
IsInstructionQualifier reports whether the PTX ISA documents qualifier (with or without its leading dot) for the instruction mnemonic, as in IsInstructionQualifier("ld", ".global"). It knows the vocabulary only: it does not check that qualifiers combine or come in a valid order. The mnemonic is matched in any case; the qualifier is matched exactly, since the ISA spells some in mixed case, as in .scale_vec::4X.
Like IsInstructionKeyword it audits; ptxas decides what is accepted.
func IsPackedType ¶
IsPackedType reports whether typ is a packed multi-element vector type (e.g. .f16x2, .s8x4).
func IsSpecialRegister ¶
IsSpecialRegister reports whether name is a predefined PTX special register or identifier, such as %tid, %ctaid, %clock64, %laneid, %cluster_ctaid, %dynamic_smem_size, etc.
func MergeModules ¶
func MergeModules(primaryPTX, libraryPTX string, opts MergeOptions) (string, error)
MergeModules splices the device functions and globals of libraryPTX into primaryPTX to produce a single whole-program PTX module that compiles without relocatable device code (-rdc).
Both primaryPTX and libraryPTX are validated with Parse, and the resulting merged PTX is re-validated with Parse before returning.
Example ¶
package main
import (
"fmt"
"log"
"github.com/tmc/lib/nvidia/x/isa/ptx"
)
func main() {
primaryPTX := `.version 8.0
.target sm_90
.address_size 64
.extern .global .align 4 .b8 I_VideoBuffer[];
.extern .func (.param .b32 retval) gpu_doom_tick(.param .u32 frame);
.visible .entry megakernel(.param .u32 step) {
.reg .b32 %r<3>;
ld.param.u32 %r1, [step];
{
.param .b32 p0;
st.param.u32 [p0+0], %r1;
.param .b32 ret0;
call.uni (ret0), gpu_doom_tick, (p0);
ld.param.b32 %r2, [ret0+0];
}
ret;
}`
libraryPTX := `.version 8.5
.target sm_90
.address_size 64
.visible .global .align 4 .b8 I_VideoBuffer[64000];
.visible .func (.param .b32 retval) gpu_doom_tick(.param .u32 frame) {
.reg .b32 %r<3>;
ld.param.u32 %r1, [frame];
add.s32 %r2, %r1, 1;
st.param.b32 [retval+0], %r2;
ret;
}`
merged, err := ptx.MergeModules(primaryPTX, libraryPTX, ptx.MergeOptions{
DropExternGlobals: []string{"I_VideoBuffer"},
})
if err != nil {
log.Fatalf("merge PTX: %v", err)
}
mod, err := ptx.ParseString(merged)
if err != nil {
log.Fatalf("parse merged PTX: %v", err)
}
fmt.Printf("Version: %s, Target: %s\n", mod.Version, mod.Target)
for _, k := range mod.Kernels {
fmt.Printf("%s: entry=%t body=%t\n", k.Name, k.Entry, k.Body)
}
}
Output: Version: 8.5, Target: sm_90 gpu_doom_tick: entry=false body=true megakernel: entry=true body=true
func RunRecordedHelper ¶
RunRecordedHelper runs the controlled protocol. Keeper and supervisor arguments are mode, absolute config path and SHA-256. The worker calls it with []string{"worker-ready"} before initializing CUDA. Successful transport does not imply a successful worker outcome. A caller must not initialize CUDA after helper refusal.
Example ¶
err := RunRecordedHelper(context.Background(), nil) fmt.Println(err)
Output: recorded helper: expected keeper or supervisor, config path and digest
func SplitOperands ¶
SplitOperands splits an instruction's operand text at top-level commas. Commas inside bracketed, braced, or parenthesized operands are retained.
func TypeBitSize ¶
TypeBitSize returns the size in bits of typ, or 0 if unknown.
func VectorElementCount ¶
VectorElementCount returns the number of vector elements in typ (1 for scalar, 2 for x2, 4 for x4).
func WriteOutputReceipt ¶
func WriteOutputReceipt(w io.Writer, out *outputcontract.RecordedOutput) error
WriteOutputReceipt writes completed output evidence to a recorded worker's stdout. The controller binds the receipt to its owned worker PID and loaded PTX receipt. This carries producer claims, not independent device attestation. Evidence must be immutable during the call. The wire format accepts at most 65536 values across all readbacks and references, 16 KiB of string metadata, and a one MiB JSON body.
Example ¶
var b bytes.Buffer
err := WriteOutputReceipt(&b, &outputcontract.RecordedOutput{PTXDigest: strings.Repeat("a", 64)})
fmt.Println(err == nil, strings.HasPrefix(b.String(), outputReceiptPrefix))
Output: true true
Types ¶
type Access ¶
type Access struct {
Inst int // index into Kernel.Instructions
Space string // "global" or "generic"
Width int // bytes one thread moves
Read bool
Write bool
// Param is the index into Kernel.Params of the parameter the address
// is computed from, or -1 if it reaches none: a pointer loaded from
// memory, or one that merges two parameters.
Param int
// The address is the parameter's value plus Offset plus some multiple
// of Stride. Stride is 0 when the offset is the same on every path,
// and positive when paths or loop iterations add different constants.
Offset, Stride int64
// Reached says whether the address is the parameter plus constants
// only (Exact), or also adds a register (Assumed), whose value the
// analysis does not know and assumes keeps the access aligned.
Reached Reach
}
An Access is one global or generic memory access in a kernel, with the parameter its address was computed from.
func AddressOrigins ¶
AddressOrigins returns the global and generic memory accesses of k, in instruction order, each traced back to the kernel parameter its address is computed from.
It follows a parameter's value from ld.param through mov, cvta.to.global, add, sub and mad into the address operands of ld, st, atom, red and cp.async, along every path of k's control flow graph. Where paths meet, the origins they carry merge: the same parameter at different offsets becomes a stride, and different parameters reach none. A loop is followed until its origins stop changing. A predicated definition merges with the value it may not replace. Adding a register to an address makes it Assumed. A pointer stored to memory and loaded back is not followed.
Shared, local, constant and parameter-space accesses are not reported. It returns an error for a kernel with no body or an indirect branch.
Example ¶
package main
import (
"fmt"
"log"
"github.com/tmc/lib/nvidia/x/isa/ptx"
)
// originsPTX wraps body in a kernel whose %rd3 and %rd4 hold parameters 0
// and 1 as global addresses, and %r1 the thread index.
func originsPTX(body string) string {
return `.version 8.0
.target sm_89
.address_size 64
.visible .entry k(.param .u64 k_param_0, .param .u64 k_param_1)
{
.reg .pred %p<4>;
.reg .b32 %r<8>;
.reg .f32 %f<8>;
.reg .b64 %rd<16>;
ld.param.u64 %rd1, [k_param_0];
ld.param.u64 %rd2, [k_param_1];
cvta.to.global.u64 %rd3, %rd1;
cvta.to.global.u64 %rd4, %rd2;
mov.u32 %r1, %tid.x;
setp.eq.s32 %p1, %r1, 0;
` + body + `
ret;
}`
}
func main() {
m, err := ptx.ParseString(originsPTX(`
ld.global.v4.f32 {%f1, %f2, %f3, %f4}, [%rd3+8];`))
if err != nil {
log.Fatal(err)
}
accesses, err := ptx.AddressOrigins(m.Kernel("k"))
if err != nil {
log.Fatal(err)
}
for _, a := range accesses {
fmt.Printf("param %d offset %d width %d: needs %d-byte alignment\n", a.Param, a.Offset, a.Width, a.Align())
}
}
Output: param 0 offset 8 width 16: needs 8-byte alignment
type AsyncPipelineConfig ¶
type AsyncPipelineConfig struct {
// TotalWarps is the total number of warps per CTA (for example 8 for 256
// threads). Must be >= 2.
TotalWarps int
// ProducerWarps is the number of warps dedicated to issuing asynchronous
// global-to-shared memory loads. Must be in [1, TotalWarps-1].
ProducerWarps int
// ConsumerWarps is the number of warps dedicated to consuming staged shared
// memory tiles for compute. Must equal TotalWarps - ProducerWarps.
ConsumerWarps int
// Stages is the multi-stage shared memory ring depth. Must be in [2, 8].
Stages int
// TileBytes is the byte capacity of each shared memory stage tile. Must be
// positive and a multiple of 16 for 16-byte cp.async.ca.shared.global
// transfers.
TileBytes int
// TargetArch is the target SM architecture (for example "sm_121a", "sm_90a",
// or "sm_80"). Must name a valid SM 80+ target supporting cp.async.
TargetArch string
}
AsyncPipelineConfig configures a warp-specialized producer/consumer software pipeline over a multi-stage shared memory ring buffer using hardware asynchronous global-to-shared copies (cp.async).
func (AsyncPipelineConfig) SharedBufferBytes ¶
func (c AsyncPipelineConfig) SharedBufferBytes() int
SharedBufferBytes returns the total shared memory ring buffer footprint in bytes across all pipeline stages (Stages * TileBytes).
func (AsyncPipelineConfig) Validate ¶
func (c AsyncPipelineConfig) Validate() error
Validate checks that c describes a well-formed warp-specialized cp.async pipeline configuration.
type AsyncPipelinePlan ¶
type AsyncPipelinePlan struct {
// contains filtered or unexported fields
}
AsyncPipelinePlan holds a validated warp-specialized asynchronous pipeline configuration and provides overlap cycle modeling, CUDA C++ code generation, and PTX instruction verification.
func NewAsyncPipelinePlan ¶
func NewAsyncPipelinePlan(cfg AsyncPipelineConfig) (*AsyncPipelinePlan, error)
NewAsyncPipelinePlan validates cfg and constructs an AsyncPipelinePlan.
Example ¶
package main
import (
"fmt"
"log"
"strings"
"github.com/tmc/lib/nvidia/x/isa/ptx"
)
func main() {
plan, err := ptx.NewAsyncPipelinePlan(ptx.AsyncPipelineConfig{
TotalWarps: 8,
ProducerWarps: 2,
ConsumerWarps: 6,
Stages: 3,
TileBytes: 4096,
TargetArch: "sm_121a",
})
if err != nil {
log.Fatalf("new async pipeline plan: %v", err)
}
rep, err := plan.EstimateOverlap(16, 120, 160)
if err != nil {
log.Fatalf("estimate overlap: %v", err)
}
cudaSrc, err := plan.EmitCUDA("ofa_async_pipeline")
if err != nil {
log.Fatalf("emit CUDA: %v", err)
}
fmt.Printf("smem=%d serial=%d pipelined=%d hidden=%.4f speedup=%.2fx has_cp_async=%t\n",
plan.Config().SharedBufferBytes(),
rep.SerialCycles,
rep.PipelinedCycles,
rep.HiddenLoadFraction,
rep.Speedup,
strings.Contains(cudaSrc, "cp.async.ca.shared.global [%0], [%1], 16;"),
)
}
Output: smem=12288 serial=4480 pipelined=2680 hidden=0.9375 speedup=1.67x has_cp_async=true
func (*AsyncPipelinePlan) Config ¶
func (p *AsyncPipelinePlan) Config() AsyncPipelineConfig
Config returns the validated AsyncPipelineConfig used by the plan.
func (*AsyncPipelinePlan) CountAsyncCopyInstructions ¶
func (p *AsyncPipelinePlan) CountAsyncCopyInstructions(ptxSrc string) int
CountAsyncCopyInstructions scans PTX or inline-PTX source and returns the number of cp.async.* instructions outside of comments.
func (*AsyncPipelinePlan) EmitCUDA ¶
func (p *AsyncPipelinePlan) EmitCUDA(funcName string) (string, error)
EmitCUDA emits a self-contained CUDA C++ __device__ __forceinline__ template function named funcName that implements a warp-specialized producer/consumer multi-stage cp.async pipeline.
func (*AsyncPipelinePlan) EstimateOverlap ¶
func (p *AsyncPipelinePlan) EstimateOverlap(numTiles int, loadCyclesPerTile, mathCyclesPerTile int64) (OverlapReport, error)
EstimateOverlap models synchronous execution (load + math per tile) against a pipelined schedule with prologue fill, steady-state max(load, math) overlap across the configured stages, and epilogue drain.
type CampaignArmResults ¶
type CampaignArmResults struct {
PlantedBug CampaignArmSummary `json:"planted_bug"`
CleanControl CampaignArmSummary `json:"clean_control"`
}
CampaignArmResults records the planted-bug and clean-control outcomes.
type CampaignArmSummary ¶
type CampaignArmSummary struct {
SourceDigest string `json:"source_sha256"`
SeedsInRange uint64 `json:"seeds_in_range"`
SeedsEvaluated uint64 `json:"seeds_evaluated"`
Findings int `json:"findings"`
ConfirmedFindings int `json:"confirmed_findings"`
VariantsExecuted int `json:"variants_executed"`
HarnessErrors int `json:"harness_errors"`
SkippedVariants int `json:"skipped_variants"`
Outcome string `json:"outcome"`
Error string `json:"error,omitempty"`
Report *CampaignReport `json:"report,omitempty"`
}
CampaignArmSummary records whether one calibration arm produced findings.
type CampaignArms ¶
type CampaignArms struct {
PlantedBugPTXSource string `json:"planted_bug_ptx_source"`
CleanPTXSource string `json:"clean_ptx_source"`
}
CampaignArms adds a known-racy PTX input and a clean control to a campaign. Both arms use the parent campaign's seed range and runner configuration.
Example ¶
package main
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
isaptx "github.com/tmc/lib/nvidia/x/isa/ptx"
"strings"
)
func main() {
const ptx = `.version 8.7
.target sm_90
.address_size 64
.visible .entry race_kernel() {
.reg .b32 %r0;
.reg .b64 %rd0;
atom.global.add.u32 %r0, [%rd0], 1;
ret;
}
`
report, err := isaptx.RunCampaign(context.Background(), isaptx.CampaignOptions{
PTXSource: ptx, SeedStart: 2, SeedEnd: 3, Intensity: 2, ConfirmRuns: 1,
Arms: &isaptx.CampaignArms{
PlantedBugPTXSource: ptx + "\n// planted bug\n",
CleanPTXSource: ptx + "\n// clean control\n",
},
RunVariant: func(_ context.Context, _ uint64, _ bool, input string) (isaptx.RunRecord, error) {
// A synthetic host workload; a device runner reports its loaded PTX.
digest := sha256.Sum256([]byte(input))
rec := isaptx.RunRecord{Exited: true, PTXDigest: hex.EncodeToString(digest[:])}
if strings.Contains(input, "planted bug") && strings.Contains(input, "nanosleep.u32") {
rec.Stdout = "MISMATCH planted bug"
return rec, nil
}
rec.Stdout = "PASS"
return rec, nil
},
})
if err != nil {
panic(err)
}
fmt.Println(report.Arms.PlantedBug.Outcome)
fmt.Println(report.Arms.CleanControl.Outcome)
}
Output: detected clean
type CampaignOptions ¶
type CampaignOptions struct {
// PTXSource is the baseline PTX source text.
PTXSource string
// Executable is the path to the executable that consumes the generated PTX.
Executable string
// Args contains additional command-line arguments for the executable.
Args []string
// WorkDir is the working directory for process execution.
WorkDir string
// ArtifactDir is the parent directory for campaign-owned run files. The
// default is ~/tmp.
ArtifactDir string
// KeepArtifacts retains PTX, stdout, stderr and replay scripts after the
// campaign returns. It applies to the default process runner.
KeepArtifacts bool
// SeedStart is the starting seed of the half-open interval.
SeedStart uint64
// SeedEnd is the ending seed of the half-open interval.
SeedEnd uint64
// Intensity scales perturbation probability and delay durations.
Intensity float64
// MaxSleepNs is the delay ceiling in nanoseconds (defaults to 64 µs).
MaxSleepNs uint32
// Timeout is the execution deadline per run before triggering Hang.
Timeout time.Duration
// PristineTimeout bounds baseline and health-check runs. Zero uses Timeout.
// A larger value can keep host scheduling noise from classifying a healthy
// reference run as a hang when variants use a deliberately short watchdog.
PristineTimeout time.Duration
// Focus is an optional substring to focus perturbation.
Focus string
// LaunchGeometry records the launch dimensions used by the external
// workload, for example "grid=4x1x1 block=128x1x1".
LaunchGeometry string
// InputReference identifies the input fixture or corpus record used by the
// external workload.
InputReference string
// OracleAttached requires a nonzero oracle liveness receipt from each run.
// Executables print CUDASCHEDULE_ORACLE_LIVENESS:pid modules accesses.
// The PID must match the executing process. RunVariant supplies its own
// trusted liveness record because the campaign does not own that process.
OracleAttached bool
// Arms asks RunCampaign to repeat its seed sweep for a known planted bug and
// a clean control, reporting whether each arm was detected as expected.
Arms *CampaignArms
// KeepGoing continues the sweep even if a GpuWedged verdict is encountered.
KeepGoing bool
// ConfirmRuns is the total number of executions for a finding (minimum 1).
// GpuWedged findings are not confirmed because further runs would reuse the
// device that failed the pristine health check. If a confirmation wedges,
// KeepGoing controls whether remaining confirmations and seeds run.
ConfirmRuns int
// CompareOutput treats stdout differences against baseline as OutputChanged.
CompareOutput bool
// DeviceProbe checks whether physical GPU hardware is available.
// Defaults to checking driver device files.
DeviceProbe func() bool
// BuildVariant prepares a runnable artifact from a PTX file. It receives an
// explicit pristine flag and returns the executable and arguments used for
// that run. The campaign appends ptxPath as the final argument. The seed is
// the campaign's start seed for pristine runs and is meaningful only when
// pristine is false. Builds have their own BuildTimeout, separate from Timeout.
BuildVariant func(ctx context.Context, seed uint64, pristine bool, ptxPath string) (string, []string, error)
// RunVariant is an optional runner hook for testing or external perturbation
// layers. The seed is meaningful only when pristine is false.
RunVariant func(ctx context.Context, seed uint64, pristine bool, ptx string) (RunRecord, error)
// BuildTimeout bounds artifact preparation separately from executable runtime.
// The default is five minutes.
BuildTimeout time.Duration
}
CampaignOptions configures a perturbation sweep over a seed range.
type CampaignReport ¶
type CampaignReport struct {
SeedStart uint64 `json:"seed_start"`
SeedEnd uint64 `json:"seed_end"`
Intensity float64 `json:"intensity"`
MaxSleepNs uint32 `json:"max_sleep_ns"`
Focus string `json:"focus,omitempty"`
ConfirmRuns int `json:"confirm_runs"`
SitesTotal int `json:"sites_total"`
SeedsDrawn int `json:"seeds_drawn"`
VariantsExecuted int `json:"variants_executed"`
EmptyDraws int `json:"empty_draws"`
HarnessErrors int `json:"harness_errors"`
Baseline RunRecord `json:"baseline"`
BaselineVerdict Verdict `json:"baseline_verdict"`
BaselineStatus string `json:"baseline_status"`
Seeds []SeedResult `json:"seeds"`
Arms *CampaignArmResults `json:"arms,omitempty"`
// CalibrationValidated requires a confirmed planted finding and a complete
// clean control with no findings, skips or harness errors. False means
// that other results from this campaign are not calibrated by these arms.
CalibrationValidated bool `json:"calibration_validated"`
// ArtifactsDir names the retained run directory when ArtifactsKept is true.
ArtifactsDir string `json:"artifacts_dir,omitempty"`
// ArtifactsKept reports whether the campaign left run files on disk.
ArtifactsKept bool `json:"artifacts_kept,omitempty"`
}
CampaignReport summarizes the results of a schedule perturbation campaign.
func RunCampaign ¶
func RunCampaign(ctx context.Context, opts CampaignOptions) (*CampaignReport, error)
RunCampaign sweeps a half-open seed interval and executes a perturbation campaign. Optional CampaignArms run the same sweep against planted-bug and clean control inputs. Without an available device or custom runner, it returns cudaerr.ErrHardwarePending. A failed baseline returns its report and an error before any variants run.
func (*CampaignReport) FindingCount ¶
func (cr *CampaignReport) FindingCount() int
FindingCount returns the total number of seeds that produced a schedule finding.
type Category ¶
type Category uint8
Category represents the functional category of a PTX instruction.
func InstructionCategory ¶
InstructionCategory reports the functional category for a PTX instruction mnemonic.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/isa/ptx"
)
func main() {
for _, mnemonic := range []string{"fma", "ld", "tcgen05", "fabric", "bra"} {
cat := ptx.InstructionCategory(mnemonic)
fmt.Printf("%s: %s (compute=%t, memory=%t)\n", mnemonic, cat, cat.IsCompute(), cat.IsMemory())
}
}
Output: fma: FloatingPoint (compute=true, memory=false) ld: DataMovement (compute=false, memory=true) tcgen05: TensorCore5thGen (compute=true, memory=false) fabric: Fabric (compute=false, memory=true) bra: ControlFlow (compute=false, memory=false)
func (Category) IsCompute ¶
IsCompute reports whether the category represents compute arithmetic, logic, or matrix operations.
func (Category) IsControlFlow ¶
IsControlFlow reports whether the category represents branching, calls, or exits.
func (Category) IsMatrix ¶
IsMatrix reports whether the category represents Tensor Core or MMA matrix operations.
type ConfirmationSummary ¶
type ConfirmationSummary struct {
// Attempts is the number of completed classifications, including the initial
// run. A confirmation wedge may stop before the configured run budget.
Attempts int `json:"attempts"`
Findings int `json:"findings"`
Confirmed bool `json:"confirmed"`
Outcomes []Verdict `json:"outcomes"`
// Runs preserves each actual classified attempt, including the initial run,
// in the same order as Outcomes. It includes loaded-artifact receipts.
Runs []RunRecord `json:"runs"`
}
ConfirmationSummary records confirmation runs for a finding.
type Diagnostic ¶
type Diagnostic struct {
Code string // such as "C7519"; empty if the line has none
Text string // the line, "ptxas info :" or "ptxas warning :" removed
}
A Diagnostic is a ptxas line about one function, such as
ptxas info : (C7519) Potential Performance Loss: wgmma.mma_async instructions are serialized due to program dependence on compiler-inserted WG.AR in divergent path in the function '_Z4gemmv' in line 1191
func (Diagnostic) WGMMASerialized ¶
func (d Diagnostic) WGMMASerialized() bool
WGMMASerialized reports whether d says ptxas serialized the function's wgmma.mma_async instructions, which it does for want of registers (C7512), for non-wgmma instructions writing wgmma inputs inside a pipeline stage (C7513), for a warpgroup arrive in a divergent path (C7519), and for other reasons.
type Doc ¶
type Doc struct {
Name string `json:"name"` // e.g. "fma", ".maxnreg", "%tid", ".f16x2", ".rn"
Kind DocKind `json:"kind"` // instruction, directive, register, type, modifier
Title string `json:"title,omitempty"` // Descriptive section title
Summary string `json:"summary,omitempty"` // 1-2 sentence overview
Syntax []string `json:"syntax,omitempty"` // Syntax prototypes
Description string `json:"description,omitempty"` // Detailed description prose
Semantics string `json:"semantics,omitempty"` // Algorithmic semantics if available
Category string `json:"category,omitempty"` // Category name (e.g. "Floating-Point Instructions")
MinPTX string `json:"min_ptx,omitempty"` // Earliest PTX ISA version
MinTarget string `json:"min_target,omitempty"` // Minimum SM architecture (e.g. "sm_20", "sm_90a", "all")
Notes string `json:"notes,omitempty"` // Additional usage notes or target restrictions
}
Doc contains structured reference documentation for a PTX instruction, directive, special register, data type, or modifier extracted from the PTX ISA documentation.
func AllDocs ¶
func AllDocs() []*Doc
AllDocs returns all reference documentation records sorted alphabetically by name.
func LookupDoc ¶
LookupDoc looks up reference documentation for a PTX entity (instruction mnemonic, directive, special register, data type, or modifier).
The lookup is case-insensitive. Prefixes (such as "." for directives, types, and modifiers, or "%" for special registers) are optional when unambiguous: LookupDoc("fma"), LookupDoc("%tid"), LookupDoc("tid"), LookupDoc(".maxnreg"), LookupDoc("maxnreg"), LookupDoc(".f16x2"), and LookupDoc(".rn") all resolve. Returns nil if no matching documentation is found.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/isa/ptx"
)
func main() {
doc := ptx.LookupDoc("fma")
if doc != nil {
fmt.Printf("%s: %s (Category: %s, Min PTX: %s, Target: %s)\n",
doc.Name, doc.Summary, doc.Category, doc.MinPTX, doc.MinTarget)
}
regDoc := ptx.LookupDoc("%tid")
if regDoc != nil {
fmt.Printf("%s: %s\n", regDoc.Name, regDoc.Summary)
}
}
Output: fma: Fused multiply-add. (Category: Floating-Point Instructions, Min PTX: 1.4, Target: sm_20) %tid: Thread identifier within a CTA.
type Function ¶
type Function struct {
Name string // mangled name
Arch string // target, such as "sm_90a"; empty if ptxas never named it
Entry bool // a kernel (entry function) rather than a device function
StackFrame int // bytes per thread
SpillStores int // bytes
SpillLoads int // bytes
// The fields below come from the "Used" line, which ptxas prints for
// entry functions only.
Registers int // registers per thread
Barriers int // named barriers
CumulativeStack int // bytes, including callees
LocalMem int // bytes; older toolkits only
ConstMem map[int]int // constant bank -> bytes
Textures int
Samplers int
Surfaces int
// MaxRegisters is the register limit ptxas reported overriding with
// -maxrregcount, or zero.
MaxRegisters int
// Diagnostics holds the ptxas warning and coded info lines that name
// this function, such as C7519.
Diagnostics []Diagnostic `json:",omitempty"`
}
A Function is one function's resources for one target architecture.
func (*Function) WGMMASerialized ¶
func (f *Function) WGMMASerialized() []Diagnostic
WGMMASerialized returns the diagnostics in which ptxas reported serializing the function's wgmma instructions.
type HoverInfo ¶
type HoverInfo struct {
Opcode string `json:"opcode"` // The instruction opcode or directive (e.g. "fma.rn.ftz.f32")
Mnemonic string `json:"mnemonic"` // Base mnemonic (e.g. "fma")
Doc *Doc `json:"doc,omitempty"` // Reference doc for the primary opcode or directive
Predicate string `json:"predicate,omitempty"` // Guard predicate if present (e.g. "@%p1")
Modifiers []ModifierInfo `json:"modifiers,omitempty"` // Explanations for all parsed modifiers/qualifiers
Operands []OperandInfo `json:"operands,omitempty"` // Breakdown of operands (identifying special registers)
MinPTX string `json:"min_ptx,omitempty"` // Minimum PTX version required
MinTarget string `json:"min_target,omitempty"` // Minimum GPU architecture required
}
HoverInfo holds structured documentation for a single PTX instruction statement or directive, suitable for interactive tooltips, side-by-side assembly views, or terminal inspection.
func Explain ¶
Explain parses a PTX statement string (instruction or directive) and returns structured hover and reference information.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/isa/ptx"
)
func main() {
stmt := "@%p1 fma.rn.ftz.f32 %f1, %f2, %f3, %f4;"
info := ptx.Explain(stmt)
fmt.Printf("Mnemonic: %s\n", info.Mnemonic)
fmt.Printf("Predicate: %s\n", info.Predicate)
for _, m := range info.Modifiers {
fmt.Printf("Modifier %s: %s\n", m.Name, m.Meaning)
}
}
Output: Mnemonic: fma Predicate: @%p1 Modifier .rn: Round to nearest even (IEEE 754 default) Modifier .ftz: Flush subnormal inputs and results to sign-preserving zero Modifier .f32: 32-bit single-precision floating point (IEEE 754)
type InjectionDecision ¶
type InjectionDecision struct {
Site Site `json:"site"`
BeforeNs uint32 `json:"before_ns"`
AfterNs uint32 `json:"after_ns"`
}
InjectionDecision records the sleep durations injected around a specific site.
type Instruction ¶
type Instruction struct {
Line int // 1-based line number of statement's first token
Predicate string // guard predicate, e.g. "@%p1", "@!%p2"
Opcode string // full opcode token, e.g. "fma.rn.f32"
Mnemonic string // base mnemonic, e.g. "fma"
Operands string // comma-separated operand text, unparsed
Loc Location // nearest lexically preceding .loc; zero if none
IntermediateLoc Location // the .loc_intermediate bound to this instruction; zero if none
InlinedAt []Location // .inlined_at chain, innermost first; nil if not inlined
Raw string // full raw statement text
}
Instruction represents a single PTX instruction statement. Authority: docs/ptx/04-syntax.md:37-55
func (Instruction) Category ¶
func (inst Instruction) Category() Category
Category returns the functional category for this instruction statement.
func (Instruction) Explain ¶
func (in Instruction) Explain() *HoverInfo
Explain returns structured hover information for the parsed instruction.
type Kernel ¶
type Kernel struct {
Name string // kernel or function name
Entry bool // true for .entry (kernel), false for .func (device function)
Linkage string // "visible", "extern", "weak", "common", or ""
Body bool // true if function has a body, false for bodiless declaration
Returns []Param // return parameters for .func
Params []Param // input parameters
Tuning Tuning // occupancy and launch bounds tuning directives
StartLine int // 1-based start line of function header
EndLine int // 1-based end line of function body
Instructions []Instruction // instruction sequence in execution order
Labels []Label // labels in source order, scoped to this function
}
Kernel represents a parsed .entry kernel or .func device function in PTX. Authority: docs/ptx/11-directives.md:403-715
func (*Kernel) AuditArchitecture ¶
AuditArchitecture verifies that the kernel's instructions are supported on target.
func (*Kernel) Summary ¶
func (k *Kernel) Summary() *OpcodeSummary
Summary returns opcode frequency statistics for this kernel.
type Label ¶
type Label struct {
Name string // identifier without the colon
Line int // 1-based source line
Instruction int // index of the next instruction; len(Instructions) at the end
}
Label is a branch label within one kernel or device function. Its name is scoped to that function, including labels in nested blocks.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/isa/ptx"
)
func main() {
m, err := ptx.ParseString(".visible .entry k() { loop: bra loop; }")
if err != nil {
fmt.Println(err)
return
}
label := m.Kernels[0].Labels[0]
fmt.Println(label.Name, label.Instruction)
}
Output: loop 0
type Location ¶
type Location struct {
File string // resolved filename, e.g. "vectorAdd.cu"
FileIndex int // .file index as written (1-based)
Line int // 1-based source line
Column int // 1-based source column
Intermediate bool // true if from .loc_intermediate directive (PTX ISA 9.4)
// FunctionName is the function_name attribute exactly as written: a label
// expression naming an offset in the DWARF .debug_str section, such as
// "info_string1" or ".debug_str+16" (docs/ptx/11-directives.md:1714-1718).
// It is not the function's name, which only .debug_str holds; it is
// recorded because it is the only thing that distinguishes two functions
// inlined at the same source position. Empty when the directive omits it.
FunctionName string
}
Location represents a source position from a .loc directive, with the file resolved through the module's .file table. The zero value means no location. Authority: docs/ptx/11-directives.md:1686-1791
type MergeOptions ¶
type MergeOptions struct {
// DropExternFuncs lists external device function names whose ".extern .func"
// forward declarations in primaryPTX should be removed when splicing libraryPTX.
// In addition, any function defined in libraryPTX is automatically dropped from
// ".extern .func" declarations in primaryPTX.
DropExternFuncs []string
// DropExternGlobals lists global symbol names whose ".extern .global" or
// placeholder ".global" declarations in primaryPTX should be removed because
// libraryPTX provides the authoritative definition.
DropExternGlobals []string
}
MergeOptions configures whole-program PTX splicing in MergeModules.
type MismatchIdentity ¶
MismatchIdentity identifies a logical output element and its comparison. Currently Policy must be "exact-uint64": equality of unsigned 64-bit values. The zero value is invalid. This is comparison identity, not a verdict.
Example ¶
id := MismatchIdentity{Index: 0, Policy: "exact-uint64"}
fmt.Println(id.Index, id.Policy)
Output: 0 exact-uint64
type ModifierInfo ¶
type ModifierInfo struct {
Name string `json:"name"` // e.g. ".rn", ".global", ".cta_group::1"
Meaning string `json:"meaning,omitempty"` // concise meaning e.g. "Round to nearest even"
Doc *Doc `json:"doc,omitempty"` // full reference doc if available
}
ModifierInfo describes an individual modifier on an instruction.
type Module ¶
type Module struct {
Version string // e.g. "8.8" or "8.0"
Target string // e.g. "sm_90"
// TargetDeclarations retains recognized .target directives in source order.
// Comments, quoted text and skipped intermediate source do not declare targets.
// Target remains the argument text of the last recognized declaration.
TargetDeclarations []TargetDeclaration
AddressSize int // 32 or 64
Files map[int]string // .file index -> filename map
Kernels []*Kernel // list of kernel and function definitions/declarations
// contains filtered or unexported fields
}
Module represents a fully parsed PTX source module. Authority: docs/ptx/11-directives.md:15-402
func Parse ¶
Parse reads PTX assembly and returns the module it describes.
Labels are unique within a kernel or device function. Direct bra and bra.uni instructions, including predicated instructions, must name a label preceding an instruction in the same function. Targets not declared as same-function labels, including register operands and external symbols, are errors. Other branch forms, including brx.idx, are preserved without resolving their targets. Outside this label and direct branch contract, Parse remains permissive; it is not a PTX validator.
func ParseBytes ¶
ParseBytes parses PTX assembly held in a byte slice.
func ParseString ¶
ParseString parses PTX assembly held in a string.
func (*Module) AssertOpcodes ¶
AssertOpcodes checks that all required opcodes are present and forbidden opcodes are absent. Opcode matching is case-insensitive and prefix-aware (e.g. "ld.global" matches "ld.global.v4.f32"). Common fallback forbid lists like ForbidSIMDFallbacks, ForbidFMAFallbacks, and ForbidWarpShuffleFallbacks can be passed to catch optimization regressions.
Example ¶
package main
import (
"fmt"
"log"
"github.com/tmc/lib/nvidia/x/isa/ptx"
)
func main() {
ptxText := `.version 8.0
.target sm_90
.address_size 64
.visible .entry VectorAdd(.param .u64 in1) {
fma.rn.f32 %f1, %f2, %f3, %f4;
ret;
}`
mod, err := ptx.ParseString(ptxText)
if err != nil {
log.Fatalf("parse PTX: %v", err)
}
err = mod.AssertOpcodes("VectorAdd", []string{"fma"}, []string{"st.global"})
if err != nil {
fmt.Printf("Audit failed: %v\n", err)
} else {
fmt.Println("Audit passed successfully")
}
}
Output: Audit passed successfully
func (*Module) AuditArchitecture ¶
AuditArchitecture checks that instructions in kernelName are supported on the module's target architecture. It rejects unknown instruction and qualifier vocabulary and checks documented special register and compound instruction requirements. If kernelName is empty, it checks all kernels. This is not an assembler or an operand and qualifier combination validator.
Example ¶
package main
import (
"fmt"
"log"
"github.com/tmc/lib/nvidia/x/isa/ptx"
)
func main() {
ptxText := `.version 9.0
.target sm_90a
.address_size 64
.visible .entry kernel() {
wgmma.fence.sync.aligned;
ret;
}`
mod, err := ptx.ParseString(ptxText)
if err != nil {
log.Fatalf("parse PTX: %v", err)
}
err = mod.AuditArchitecture("kernel")
if err != nil {
fmt.Println("Audit failed:", err)
} else {
fmt.Println("Architecture audit passed")
}
}
Output: Architecture audit passed
func (*Module) AuditVersion ¶
AuditVersion checks the module header and the PTX ISA version its instructions and special registers require. Unknown instruction and qualifier vocabulary fails the audit. If kernelName is empty it checks every kernel. Parsing remains permissive for callers that need to preserve raw PTX. This is not an assembler or an operand and qualifier combination validator.
It reports three kinds of defect, all of them decidable from the module text: a missing or malformed .version or .target directive; a .version newer than the generated tables describe, which is returned wrapping ErrVersionUnaudited; and an instruction introduced in a PTX ISA version later than the .version the module declares.
AuditVersion is the .version counterpart of Module.AuditArchitecture, which checks the same instructions against the .target architecture. Neither predicts whether a given driver will accept the module: the PTX ISA version a driver supports is a property of the loading toolkit, not of the module, and is not recorded here. Use Module.ExplainLoadError to interpret a load that the driver has already rejected.
func (*Module) ExplainLoadError ¶
ExplainLoadError wraps err with the header a driver rejected. It is meant for CUDA_ERROR_UNSUPPORTED_PTX_VERSION from a module load, which names neither the version that was rejected nor the version the driver wanted:
if err := mod.LoadData(src); errors.Is(err, driver.ErrUnsupportedPtxVersion) {
return parsed.ExplainLoadError(err)
}
The rejected .version and .target come from the module text. The cause does not: a driver reports no PTX ISA version of its own, so the message names the toolkit mismatch as the usual explanation without asserting it. Nothing here is a check, and ExplainLoadError makes no claim about modules that load. err is returned unchanged if it is nil.
type OpcodeSummary ¶
OpcodeSummary records instruction counts and opcodes for a kernel. It mirrors cudasass.OpcodeSummary so that the same audit can be written against PTX and against the SASS it lowers to.
func (*OpcodeSummary) CategoryCount ¶
func (s *OpcodeSummary) CategoryCount(cat Category) int
CategoryCount returns the number of instructions whose mnemonic belongs to cat.
Example ¶
package main
import (
"fmt"
"log"
"github.com/tmc/lib/nvidia/x/isa/ptx"
)
func main() {
ptxText := `.version 9.0
.target sm_90
.address_size 64
.visible .entry saxpy() {
ld.global.f32 %f1, [%rd1];
ld.global.f32 %f2, [%rd2];
fma.rn.f32 %f3, %f1, %f0, %f2;
st.global.f32 [%rd3], %f3;
ret;
}`
mod, err := ptx.ParseString(ptxText)
if err != nil {
log.Fatalf("parse PTX: %v", err)
}
sum, err := mod.Summary("saxpy")
if err != nil {
log.Fatalf("summary: %v", err)
}
fmt.Printf("Memory instructions: %d\n", sum.CategoryCount(ptx.CatDataMovement))
fmt.Printf("Floating point: %d\n", sum.CategoryCount(ptx.CatFloatingPoint))
fmt.Printf("Control flow: %d\n", sum.CategoryCount(ptx.CatControlFlow))
}
Output: Memory instructions: 3 Floating point: 1 Control flow: 1
func (*OpcodeSummary) Count ¶
func (s *OpcodeSummary) Count(prefix string) int
Count returns the number of instructions whose opcode matches the prefix. Matching is case-insensitive and stops at a dot, so that a prefix names whole opcode fields. For example, Count("ld.global") matches "ld.global.f32" and "ld.global.v4.f32" but not "ld.global_nc.f32".
type OperandInfo ¶
type OperandInfo struct {
Text string `json:"text"` // raw operand text e.g. "%tid.x", "[%r1+4]"
Doc *Doc `json:"doc,omitempty"` // reference doc if operand references a known special register
Summary string `json:"summary,omitempty"` // short summary if known special register
}
OperandInfo describes an individual operand in an instruction statement.
type OverlapReport ¶
type OverlapReport struct {
SerialCycles int64
PipelinedCycles int64
HiddenLoadFraction float64
Speedup float64
}
OverlapReport summarizes modeled cycle counts and load hiding for a multi-stage asynchronous producer/consumer pipeline compared against a synchronous load-then-compute baseline.
type Param ¶
type Param struct {
Name string // e.g. "in1" or "addone_param_0"
Space string // "param", "reg"
Type string // e.g. "u64", "f32", "b8"
Align int // .align byte requirement, or 0 if unspecified
Size int // array element count for vector/array params, 0 if scalar
}
Param represents a kernel or function parameter declaration. Authority: docs/ptx/11-directives.md:412-645
type RecordedCustody ¶
type RecordedCustody struct {
// Phase records the furthest observed source transition: keeper-ready,
// holder-started, supervisor-observed, worker-observed, worker-permitted.
Phase string `json:"phase"`
// SupervisorCreation is not-started before H exists, unknown after H starts,
// and observed only after the actual S peer identity has been retained.
SupervisorCreation string `json:"supervisor_creation"`
Controller RecordedProcess `json:"controller"`
Keeper RecordedProcess `json:"keeper"`
Holder RecordedProcess `json:"holder"`
Supervisor RecordedProcess `json:"supervisor"`
Worker RecordedProcess `json:"worker"`
Closed bool `json:"closed"`
WorkerReaped bool `json:"worker_reaped"`
StdoutDrained bool `json:"stdout_drained"`
StderrDrained bool `json:"stderr_drained"`
Directory string `json:"directory"`
}
RecordedCustody retains actual processes involved in one attempt. Closed requires checked retirement of holder and supervisor groups. Worker status comes from its direct supervisor, never from guardian success.
type RecordedProcess ¶
type RecordedProcess struct {
PID int `json:"pid"`
Parent int `json:"parent"`
Group int `json:"group"`
Start uint64 `json:"start"`
Executable string `json:"executable_sha256"`
}
RecordedProcess identifies a retained Linux process and its executable. A numeric PID alone is not an ownership or signal capability.
type RecordedRunOptions ¶
type RecordedRunOptions struct {
PristinePTX string // Pristine source for baseline and fresh health execution.
Executable string // Absolute prebuilt worker path.
ExecutableSHA256 string // Worker executable SHA-256.
Args []string // Worker arguments; the supplied PTX path is appended.
WorkDir string // Absolute worker working directory.
Helper string // Absolute cudarecorded helper path.
HelperSHA256 string // Helper executable SHA-256.
ArtifactDir string // Absolute parent for retained per-attempt artifacts.
LockScript string // Absolute source-reviewed gpu-lock script path.
LockDirectory string // Authoritative shared lock directory.
Label string // Caller label recorded by the real lock.
QueueTimeout time.Duration // Whole-second queue budget.
AdmissionTimeout time.Duration // Ownership and worker-ready ACK budget.
Timeout time.Duration // Candidate runtime after CUDA permit.
PristineTimeout time.Duration // Pristine runtime after CUDA permit.
CleanupTimeout time.Duration // Retirement and reaping budget.
LeaseLimit time.Duration // Whole-second real lock limit.
LeaseExpected time.Duration // Whole-second real lock estimate.
OutputLimit int // Maximum retained bytes per output stream.
OracleAttached bool // Require PID-bound instrumentation liveness.
RequireOutput bool // Require a worker-bound output-contract receipt.
CompareOutput bool // Execute a fresh pristine baseline before the candidate.
}
RecordedRunOptions specifies a prebuilt, source-reviewed worker and helper. The zero value is invalid. Limits and executable pins are explicit. The worker must call RunRecordedHelper with worker-ready before CUDA or probes.
type RegBudgetConfig ¶
type RegBudgetConfig struct {
// EntryMaxRegs maps .entry kernel names (for example "go_partitioned_vm")
// to a .maxnreg N directive to inject before the entry body's opening "{",
// or to replace an existing .maxnreg directive on that entry.
EntryMaxRegs map[string]int
// ColdNoInlineFuncs lists device .func names (for example
// "gpu_doom_worker_always") whose definitions should be isolated as cold
// callees with a leading `.pragma "nounroll";` directive in their body.
ColdNoInlineFuncs []string
// DynamicSetMaxNReg enables Hopper/Blackwell dynamic warp register
// reallocation helpers (setmaxnreg.inc / setmaxnreg.dec).
DynamicSetMaxNReg bool
}
RegBudgetConfig configures per-entry .maxnreg specialization and cold-callee isolation for whole-program megakernel PTX modules.
func (RegBudgetConfig) Validate ¶
func (c RegBudgetConfig) Validate() error
Validate checks that every entry in EntryMaxRegs has a non-empty kernel name and a register budget in the valid PTX ISA range [16, 255].
type RegBudgetReport ¶
type RegBudgetReport struct {
ModifiedEntries []string
IsolatedColdFuncs []string
EntryMaxRegs map[string]int
}
RegBudgetReport summarizes the transformations applied by SpecializeRegBudget.
func SpecializeRegBudget ¶
func SpecializeRegBudget(ptx string, cfg RegBudgetConfig) (string, RegBudgetReport, error)
SpecializeRegBudget rewrites ptx according to cfg by injecting or updating per-entry .maxnreg directives and isolating cold .func definitions with `.pragma "nounroll";`.
Example ¶
package main
import (
"fmt"
isaptx "github.com/tmc/lib/nvidia/x/isa/ptx"
"log"
)
func main() {
ptx := `.version 8.5
.target sm_90a
.address_size 64
.visible .func gpu_doom_worker_always(.param .u32 tid) {
.reg .b32 %r<2>;
ld.param.u32 %r1, [tid];
ret;
}
.visible .entry go_partitioned_vm(.param .u64 params_ptr) {
.reg .b32 %r<4>;
ret;
}`
specialized, rep, err := isaptx.SpecializeRegBudget(ptx, isaptx.RegBudgetConfig{
EntryMaxRegs: map[string]int{"go_partitioned_vm": 64},
ColdNoInlineFuncs: []string{"gpu_doom_worker_always"},
DynamicSetMaxNReg: true,
})
if err != nil {
log.Fatalf("specialize reg budget: %v", err)
}
mod, err := isaptx.ParseString(specialized)
if err != nil {
log.Fatalf("parse specialized PTX: %v", err)
}
incPTX, err := isaptx.EmitSetMaxNRegPTX("inc", 64)
if err != nil {
log.Fatalf("emit setmaxnreg: %v", err)
}
fmt.Printf("modified=%v isolated=%v maxnreg=%d\n",
rep.ModifiedEntries, rep.IsolatedColdFuncs, mod.Kernel("go_partitioned_vm").Tuning.MaxNReg)
fmt.Println(incPTX)
}
Output: modified=[go_partitioned_vm] isolated=[gpu_doom_worker_always] maxnreg=64 setmaxnreg.inc.sync.aligned.u32 64;
type Report ¶
type Report struct {
Targets []*Target
Warnings []string // "ptxas warning" lines not in a function's Diagnostics, prefix removed
Errors []string // "ptxas error" and "ptxas fatal" lines, prefix removed
Notes []string // other "ptxas info" lines, prefix removed
}
A Report is everything Parse found.
func ParsePTXASInfo ¶
Parse reads ptxas -v output, possibly mixed with other compiler output. It returns an error for a malformed or unknown resource field in a line it recognizes.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/isa/ptx"
)
func main() {
out := `ptxas info : 0 bytes gmem
ptxas info : Compiling entry function '_Z5spillPfPKf' for 'sm_90a'
ptxas info : Function properties for _Z5spillPfPKf
992 bytes stack frame, 2232 bytes spill stores, 2660 bytes spill loads
ptxas info : Used 32 registers, used 0 barriers, 992 bytes cumulative stack size
ptxas info : Compile time = 128.853 ms
`
r, err := ptx.ParsePTXASInfo(strings.NewReader(out))
if err != nil {
panic(err)
}
for _, f := range r.Functions() {
fmt.Printf("%s %s: %d registers, spills %v (%d B stored)\n", f.Arch, f.Name, f.Registers, f.Spills(), f.SpillStores)
}
}
Output: sm_90a _Z5spillPfPKf: 32 registers, spills true (2232 B stored)
func (*Report) WGMMASerialized ¶
WGMMASerialized returns, in report order, every function whose wgmma instructions ptxas reported serializing.
type Rewrite ¶
type Rewrite struct {
PTX string
Report RewriteReport
}
Rewrite is the result of perturbing a PTX module.
func Perturb ¶
Perturb applies seeded deterministic schedule perturbations to a PTX module. The same seed and options produce byte-identical output across runs. A draw that selects no site returns the original text and reports zero injected sites.
Example ¶
package main
import (
"fmt"
isaptx "github.com/tmc/lib/nvidia/x/isa/ptx"
)
func main() {
const ptx = `.version 8.7
.target sm_90
.address_size 64
.visible .entry example()
{
.reg .b32 %r0;
.reg .b64 %rd0;
fence.sc.gpu;
ret;
}
`
rewrite, err := isaptx.Perturb(ptx, isaptx.Options{
Seed: 1,
Intensity: 0.0, // empty draw
})
if err != nil {
panic(err)
}
fmt.Printf("injected: %d\n", rewrite.Report.SitesInjected)
}
Output: injected: 0
func Replay ¶
func Replay(src string, opts Options, decisions []InjectionDecision) (Rewrite, error)
Replay applies a recorded subset of injection decisions to pristine PTX. Every site must exactly match Analyze(src), and no site may occur twice. Decisions retain their supplied order. Options supplies the original seed, intensity and delay ceiling; Focus does not redraw or change decisions. Replaying the complete Perturb decision list with the original options produces the same PTX and report. An empty subset returns src unchanged.
Example ¶
package main
import (
"fmt"
isaptx "github.com/tmc/lib/nvidia/x/isa/ptx"
)
func main() {
const ptx = `.version 8.7
.target sm_90
.address_size 64
.visible .entry example() {
membar.gl;
ret;
}
`
opts := isaptx.Options{Seed: 17, Intensity: 2}
drawn, err := isaptx.Perturb(ptx, opts)
if err != nil {
panic(err)
}
replayed, err := isaptx.Replay(ptx, opts, drawn.Report.Decisions)
if err != nil {
panic(err)
}
fmt.Println(replayed.PTX == drawn.PTX)
empty, err := isaptx.Replay(ptx, opts, nil)
if err != nil {
panic(err)
}
fmt.Println(empty.PTX == ptx)
}
Output: true true
type RewriteReport ¶
type RewriteReport struct {
Seed uint64 `json:"seed"`
Intensity float64 `json:"intensity"`
SitesTotal int `json:"sites_total"`
SitesInjected int `json:"sites_injected"`
InjectedNsPerVisit uint64 `json:"injected_ns_per_visit"`
Decisions []InjectionDecision `json:"decisions"`
}
RewriteReport summarizes the perturbation applied to a PTX module.
type RunBound ¶
type RunBound struct {
// Stops are the indices into Kernel.Instructions of the stop points,
// ascending.
Stops []int
// MaxRun is the most PTX instructions one thread executes on any path
// from the kernel's entry, or from just after a stop point, to the next
// stop point or the end of the kernel, that stop point included.
MaxRun int64
}
A RunBound bounds how long one thread of a kernel runs between stop points, the instructions at which it reads a flag that can end its work.
func StopRuns ¶
StopRuns returns the stop points of k, the instructions for which stop reports true, and the longest run between them.
A loop bounds a run only if every cycle through it passes a stop point, or it is a counted loop: its one back edge is a branch on a setp that compares a register with an immediate, the register's only definition in the loop is an add or sub of an immediate in the same straight-line code as that setp and branch, and its only definition outside the loop is a mov of an immediate that every entry to the loop passes. The trip count is found by running the induction; a count above 2^24 is refused. A loop bounded only by a clock or a deadline, such as a bounded wait that polls %globaltimer, bounds the run's time but not its instructions, and is refused like an unbounded one, with ErrUnboundedRun.
A counted loop's cost is its trip count times the longest path through its body, so MaxRun is an upper bound, not an exact count.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/tmc/lib/nvidia/x/isa/ptx"
)
func main() {
// A tile loop: 100 trips of a counted inner loop, then a volatile
// read of the flag, which is the stop point.
src := `.version 9.5
.target sm_121a
.address_size 64
.visible .entry tile(.param .u64 tile_param_0)
{
.reg .pred %p<3>;
.reg .b32 %r<4>;
.reg .b64 %rd<3>;
ld.param.u64 %rd1, [tile_param_0];
cvta.to.global.u64 %rd2, %rd1;
TILE:
mov.b32 %r1, 0;
WORK:
add.s32 %r1, %r1, 1;
setp.ne.s32 %p1, %r1, 100;
@%p1 bra WORK;
ld.volatile.global.u32 %r2, [%rd2];
setp.eq.s32 %p2, %r2, 0;
@%p2 bra TILE;
ret;
}`
m, err := ptx.ParseString(src)
if err != nil {
fmt.Println(err)
return
}
k := m.Kernel("tile")
rb, err := ptx.StopRuns(k, func(i int) bool {
return strings.HasPrefix(k.Instructions[i].Opcode, "ld.volatile")
})
// The longest run is from the entry: ld.param, cvta and mov, 100
// trips of add, setp and bra, then the flag read.
fmt.Println(len(rb.Stops), rb.MaxRun, err)
}
Output: 1 304 <nil>
type RunRecord ¶
type RunRecord struct {
// Output retains the output-write oracle's completed readbacks and numerical
// policy. Classify recomputes its report rather than trusting supplied counts.
Output *outputcontract.RecordedOutput `json:"output_contract,omitempty"`
// Custody is present for controlled recorded-run attempts.
Custody *RecordedCustody `json:"custody,omitempty"`
// Mismatch identifies the comparison that failed in the executing runner.
// It is absent for older runners; consumers must not infer it from prose.
Mismatch *MismatchIdentity `json:"mismatch_identity,omitempty"`
ExitCode int `json:"exit_code"`
Exited bool `json:"exited"`
TimedOut bool `json:"timed_out"`
Signal string `json:"signal,omitempty"`
PristineRun bool `json:"pristine_run,omitempty"`
Stdout string `json:"stdout"`
Stderr string `json:"stderr"`
HarnessErr string `json:"harness_error,omitempty"`
// PTXDigest is the runner-reported SHA-256 digest of the loaded PTX.
PTXDigest string `json:"ptx_sha256,omitempty"`
// PTXDigestSource identifies the receipt as "runner_receipt".
PTXDigestSource string `json:"ptx_digest_source,omitempty"`
// ExpectedPTXDigest is the digest of the PTX source the campaign supplied.
ExpectedPTXDigest string `json:"expected_ptx_sha256,omitempty"`
// OracleAttached requires a liveness receipt from the instrumented runner.
OracleAttached bool `json:"oracle_attached,omitempty"`
OraclePID int `json:"oracle_pid,omitempty"`
OraclePatchedModules int `json:"oracle_patched_modules,omitempty"`
OracleInstrumentedAccesses uint64 `json:"oracle_instrumented_accesses,omitempty"`
PTXPath string `json:"ptx_path,omitempty"`
StdoutPath string `json:"stdout_path,omitempty"`
StderrPath string `json:"stderr_path,omitempty"`
ReplayScriptPath string `json:"replay_script_path,omitempty"`
Pristine *RunRecord `json:"pristine,omitempty"`
Baseline *RunRecord `json:"baseline,omitempty"`
CompareOutput bool `json:"compare_output,omitempty"`
}
RunRecord captures the recorded outcome of executing a kernel binary.
func RunRecorded ¶
func RunRecorded(ctx context.Context, seed uint64, recordedPTX string, opts RecordedRunOptions) (RunRecord, error)
RunRecorded executes supplied PTX, including an unchanged pristine candidate. It does not perturb, redraw or confirm. Its controller must be CUDA-free and outside an inherited lease. Artifacts are retained. Configuration and parent cancellation return errors. Execution and ownership failures are retained in HarnessErr. A timeout receives fresh pristine health only after complete retirement; a previous baseline is not reused as health.
Example ¶
_, err := RunRecorded(context.Background(), 0, "", RecordedRunOptions{})
fmt.Println(err != nil)
Output: true
type SeedResult ¶
type SeedResult struct {
Seed uint64 `json:"seed"`
Status SeedStatus `json:"status"`
Verdict Verdict `json:"verdict"`
Run *RunRecord `json:"run,omitempty"`
Report RewriteReport `json:"report"`
Confirmation *ConfirmationSummary `json:"confirmation,omitempty"`
PristineSourceDigest string `json:"pristine_source_sha256"`
LaunchGeometry string `json:"launch_geometry,omitempty"`
InputReference string `json:"input_reference,omitempty"`
MaxSleepNs uint32 `json:"max_sleep_ns"`
Focus string `json:"focus,omitempty"`
}
SeedResult records the outcome of a single seed in a campaign.
type SeedStatus ¶
type SeedStatus string
SeedStatus distinguishes a drawn seed from an executed variant.
const ( SeedExecuted SeedStatus = "executed" SeedEmptyDraw SeedStatus = "empty_draw" SeedHarnessError SeedStatus = "harness_error" )
type Site ¶
type Site struct {
Ordinal int `json:"ordinal"`
Callable string `json:"callable"`
Kind SiteKind `json:"kind"`
Span Span `json:"span"`
BlockIndex *int `json:"block_index,omitempty"`
Head string `json:"head"`
Text string `json:"text"`
Predicate string `json:"predicate,omitempty"`
}
Site represents a single schedule-sensitive location discovered in PTX assembly.
func Analyze ¶
Analyze parses a PTX module and returns all schedule-sensitive sites in source order. Control-flow recovery is fail-closed: malformed branches are reported instead of being silently treated as non-loops.
Example ¶
package main
import (
"fmt"
isaptx "github.com/tmc/lib/nvidia/x/isa/ptx"
)
func main() {
const ptx = `.version 8.7
.target sm_90
.address_size 64
.visible .entry example()
{
.reg .b32 %r0;
.reg .b64 %rd0;
red.global.add.u32 [%rd0], %r0;
ret;
}
`
sites, err := isaptx.Analyze(ptx)
if err != nil {
panic(err)
}
for _, s := range sites {
fmt.Printf("%s: %s\n", s.Kind, s.Head)
}
}
Output: Reduction: red.global.add.u32
type SiteKind ¶
type SiteKind int
SiteKind classifies a point in a PTX module where another thread's progress can be observed.
const ( // SiteAtomic is an atomic read-modify-write operation (atom.*). SiteAtomic SiteKind = iota + 1 // SiteReduction is a memory reduction with no returned value (red.*). SiteReduction // SiteBarrier is barrier and mbarrier synchronization (bar.*, barrier.*, mbarrier.*). SiteBarrier // SiteFence is memory ordering and fences (fence.*, membar.*). SiteFence // SiteOrderedMemory is memory access with an explicit ordering qualifier. SiteOrderedMemory // SiteWarpCollective is warp-wide collective communication (shfl.*, vote.*, match.*, elect.*, activemask, redux.*). SiteWarpCollective // SiteAsyncProxy is an asynchronous proxy pipeline operation (cp.async.*, cp.reduce.async.*, // wgmma.*, tcgen05.*, clusterlaunchcontrol.*). SiteAsyncProxy // SiteGridDependency is a programmatic dependent launch boundary (griddepcontrol.*). SiteGridDependency // SiteTensorMapMutation is a generic-proxy tensor map descriptor mutation (tensormap.replace.*). SiteTensorMapMutation // SiteBackedge is an intraprocedural branch back to the same or an earlier basic block. SiteBackedge )
type Target ¶
type Target struct {
Arch string // empty for a module with no Compiling line, which ptxas never names
GlobalMem int // bytes of __device__ data
ConstMem map[int]int // constant bank -> bytes
Functions []*Function // in report order
}
A Target holds the module-level resources for one architecture.
type TargetDeclaration ¶
type TargetDeclaration struct {
Line int // 1-based source line of the directive
Target string // argument text, including any comma-separated options
}
TargetDeclaration records a .target directive recognized by Parse. Recognition does not validate its architecture, options or placement.
Example ¶
package main
import (
"fmt"
"github.com/tmc/lib/nvidia/x/isa/ptx"
)
func main() {
m, err := ptx.ParseString("// .target sm_70\n.target sm_90, debug\n.target sm_90a\n")
if err != nil {
fmt.Println(err)
return
}
for _, declaration := range m.TargetDeclarations {
fmt.Println(declaration.Line, declaration.Target)
}
fmt.Println("last:", m.Target)
}
Output: 2 sm_90, debug 3 sm_90a last: sm_90a
type Tuning ¶
type Tuning struct {
MaxNReg int // .maxnreg limit
MaxNTID [3]int // .maxntid [nx, ny, nz]
ReqNTID [3]int // .reqntid [nx, ny, nz]
MinNCTAPerSM int // .minnctapersm
MaxNCTAPerSM int // .maxnctapersm
ReqNCTAPerCluster [3]int // .reqnctapercluster [cx, cy, cz]
MaxClusterRank int // .maxclusterrank
ExplicitCluster bool // .explicitcluster
}
Tuning retains kernel resource and launch bounds directives. Authority: docs/ptx/11-directives.md:925-1218, 11-directives.md:1830-1920
type Verdict ¶
type Verdict int
Verdict classifies the execution outcome of a PTX variant or baseline run.
const ( // VerdictPass indicates the perturbed run behaved like the baseline. VerdictPass Verdict = iota // VerdictSkipped indicates the run declined to execute (e.g. arch mismatch). VerdictSkipped // VerdictHang indicates the watchdog timer expired. VerdictHang // VerdictCrash indicates the process terminated abnormally or with a non-zero exit code. VerdictCrash // VerdictMismatch indicates an explicit correctness failure was detected in output. VerdictMismatch // VerdictOutputChanged indicates stdout differed from baseline without explicit failure (opt-in). VerdictOutputChanged // VerdictGpuWedged indicates the device stopped responding (timeout reproduced on pristine re-run). VerdictGpuWedged // VerdictHarnessError indicates the test harness failed before or during execution. VerdictHarnessError // VerdictEmptyDraw indicates the seed selected no perturbation and no run occurred. VerdictEmptyDraw )
func Classify ¶
Classify determines the verdict for a recorded run. It is a pure function of the recorded execution outcome with no hardware interaction. Missing, invalid or mismatched loaded-PTX receipts are HarnessError, including timeouts before a load receipt. Matching SHA-256 digests and PTXDigestSource "runner_receipt" are required for every executed outcome.
Example ¶
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
isaptx "github.com/tmc/lib/nvidia/x/isa/ptx"
)
func main() {
// Synthetic recorded evidence illustrates classification, not device proof.
digest := sha256.Sum256([]byte("synthetic recorded PTX workload"))
sha := hex.EncodeToString(digest[:])
rec := isaptx.RunRecord{
ExitCode: 0,
Exited: true,
Stdout: "MISMATCH at index 0\n",
PTXDigest: sha,
ExpectedPTXDigest: sha,
PTXDigestSource: "runner_receipt",
}
v := isaptx.Classify(rec)
fmt.Printf("%s (finding: %v)\n", v, v.IsFinding())
}
Output: Mismatch (finding: true)
func (Verdict) FindingLabel ¶
FindingLabel returns the human-readable label for schedule findings, or an empty string if the verdict is not a finding.
Source Files
¶
- async_pipeline.go
- audit.go
- audit_strict.go
- audit_tables.gen.go
- audit_targets.go
- campaign.go
- doc.go
- doc_data.go
- merge.go
- mismatch.go
- operands.go
- origins.go
- output_contract.go
- output_receipt.go
- parser.go
- perturb.go
- ptx.go
- ptxasinfo.go
- qualifier.go
- recorded_run.go
- recorded_run_child_linux.go
- recorded_run_config_linux.go
- recorded_run_controller_linux.go
- recorded_run_keeper_linux.go
- recorded_run_limits.go
- recorded_run_linux.go
- recorded_run_lock.go
- recorded_run_output.go
- recorded_run_protocol.go
- recorded_run_runtime_linux.go
- recorded_run_wire_linux.go
- regbudget.go
- replay.go
- runbound.go
- site.go
- tables.gen.go
- verdict.go
- version.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package ptxaddr reports local PTX address hazards for review.
|
Package ptxaddr reports local PTX address hazards for review. |
|
Package ptxast is a typed syntax tree for PTX, with a parser and a printer.
|
Package ptxast is a typed syntax tree for PTX, with a parser and a printer. |
|
Package ptxbuild builds PTX modules in Go.
|
Package ptxbuild builds PTX modules in Go. |
|
Package ptxequiv gives PTX kernels a bit-precise semantics for package equiv: Kernel.Effect translates a kernel into the guarded loads and stores of one symbolic thread, and Kernel.Run executes one thread on concrete values to replay counterexamples.
|
Package ptxequiv gives PTX kernels a bit-precise semantics for package equiv: Kernel.Effect translates a kernel into the guarded loads and stores of one symbolic thread, and Kernel.Run executes one thread on concrete values to replay counterexamples. |
|
Package ptxpass analyses and rewrites PTX syntax trees from package ptxast.
|
Package ptxpass analyses and rewrites PTX syntax trees from package ptxast. |