Metadata-Version: 2.4
Name: ptx-vet
Version: 0.1.0
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Compilers
Classifier: Topic :: Software Development :: Quality Assurance
License-File: LICENSE
Summary: Fast static verifier, 32-lane SMEM bank simulator, and register/pipeline analyzer for NVIDIA PTX
License: Apache-2.0
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Repository, https://github.com/rdyro/ptx-vet

# ptx-vet

Fast static verifier, 32-lane SMEM bank simulator, and register/pipeline analyzer for NVIDIA PTX.

Zero-dependency Rust binary for auditing any [NVIDIA PTX](https://docs.nvidia.com/cuda/parallel-thread-execution/) (hand-written PTX, `nvcc -ptx` / CUDA C++, Triton, CUTLASS, or JAX Mosaic GPU/Pallas) targeting Turing (`sm_75`) through Blackwell (`sm_100a`/`sm_103a`/`sm_120a`) and Rubin (`sm_107a`/`sm_130a`). Builds a typed IR (CFG, dominators, natural loops, scoped register liveness) with 44 static rules, 32-lane warp SMEM bank-conflict simulation, symbolic Tensor Core fragment tracking, `cp.async`/barrier stage verification, graph-coloring register allocation, and an opt-in `ptxas -v` pass.

## Interactive Guide

**[Download the Interactive Guide (`ptx-vet-guide.html`)](https://github.com/rdyro/ptx-vet/releases/download/guide/ptx-vet-guide.html)** and open it directly in your browser (source: [`docs/guide.html`](docs/guide.html)).

A self-contained, single-file interactive handbook auto-attached as a rolling GitHub Release asset by `.github/workflows/guide-release.yml`:

- **Architecture & Profiles**: IR pipeline, CFG/loop/liveness passes, verification profiles, and SM target matrix.
- **Interactive Rule Explorer**: searchable, filterable reference for all 46 built-in rules (44 static + 2 `--ptxas`).
- **32-Lane SMEM Bank Lab**: live bank-conflict and swizzle visualizer across all 32 warp lanes.
- **Live Custom-Rule Workbench**: interactive declarative TOML rule builder and compiled Rust rule walkthrough.
- **End-to-End Case Study**: step-by-step `sm_120a` FP16 MMA GEMM optimization walkthrough (`v0` to `v4`) driven by `ptx-vet`.

You can also open [`docs/guide.html`](docs/guide.html) locally (`open docs/guide.html` on macOS or `xdg-open docs/guide.html` on Linux).

## Build

```bash
cargo build --release
cargo test
cargo clippy --all-targets -- -D warnings
```

## CLI Quick Reference

```bash
# Default profile (core + ml; exit 0 pass, 1 reject, 2 error)
ptx-vet examples/ptx/pass_hopper_wgmma_tma.ptx
ptx-vet -j4 --ptxas experiments/mma_gemm_sm120a/kernels/v*.ptx

# Scientific profile (core rules only: allows FP64, exact IEEE math, and scalar FMA solvers)
ptx-vet --profile scientific --ptxas examples/ptx/pass_subtle_fp64_mma_scientific.ptx

# Diagnostic and authoring modes (report flags compose with --ptxas, --deny-warnings, and each other)
ptx-vet --reg-report --dyn-smem 98304 experiments/mma_gemm_sm120a/kernels/v3_cp_async_3stage_stmatrix.ptx
ptx-vet --ptxas --reg-report --warp-report experiments/mma_gemm_sm120a/kernels/v0_spill_conflict_unpiped.ptx
ptx-vet --alloc-regs kernel_named.ptx | ptx-vet --ptxas -
ptx-vet --tc-report --warp 0 experiments/mma_gemm_sm120a/kernels/v3_cp_async_3stage_stmatrix.ptx
ptx-vet --stage-report experiments/mma_gemm_sm120a/kernels/v3_cp_async_3stage_stmatrix.ptx
ptx-vet --warp-report --warp 0 experiments/mma_gemm_sm120a/kernels/v2_swizzled_1way.ptx
ptx-vet --diff-layout experiments/mma_gemm_sm120a/kernels/epilogue_stmatrix.ptx --warp 0 experiments/mma_gemm_sm120a/kernels/epilogue_st_shared.ptx

# Rule filtering, custom TOML rules, and JSON output
ptx-vet --arch sm_120a --profile strict --rules rules/example.toml experiments/mma_gemm_sm120a/kernels/v4_unrolled_dbuf_l2swiz.ptx
ptx-vet --only smem-bank-conflict-sim,tc-fragment-mismatch --json experiments/mma_gemm_sm120a/kernels/v2_swizzled_1way.ptx
ptx-vet --list-rules
```

## Workflows

### 1. Hand-Written PTX Authoring & Optimization

Iterate in milliseconds before touching a GPU using the runnable `sm_120a` kernels under `experiments/mma_gemm_sm120a/kernels/` (`v0` through `v4`) and `experiments/rms_norm_sm120a/kernels/`:

**Parallel vetting and `ptxas -v` ground truth**

```bash
ptx-vet -j4 --ptxas experiments/mma_gemm_sm120a/kernels/v*.ptx
```

Vets files across 4 workers and appends `ptxas -v` stats (`registers`, `spill_stores`/`spill_loads`, static `+dyn` SMEM, `active_ctas_per_sm`, SM occupancy %). Pass `--dyn-smem <bytes>` (or annotate kernels with `// @dyn_smem <bytes>`) to fold dynamic `.extern .shared` allocations into occupancy and enforce `smem-optin-overflow`. Non-zero physical spills trigger `ptxas-physical-spill`, and `ptxas` assembly errors emit `ptxas-assemble-error` while preserving all static findings.

**Register pressure, spill culprits, and CTA/SM boundaries**

```bash
ptx-vet --reg-report experiments/mma_gemm_sm120a/kernels/v0_spill_conflict_unpiped.ptx
```

Reports peak live 32-bit virtual registers, peak line, live counts by register prefix, top-10 `peak_culprits` (highlighting `0-use-in-loop` hoisted registers to rematerialize or defer), per-loop live-across-backedge counts, and the next lower hardware register boundary for an additional resident CTA/SM.

**Named registers and inline helpers**

Author kernels with symbolic register names or scoped `{ .reg ... }` blocks, then graph-color into reused PTX pools and pipe straight to `ptxas`:

```bash
ptx-vet --alloc-regs kernel_named.ptx | ptx-vet --ptxas -
```

Wrap inline helpers in `// @helper <name> out:%rA, %rB` ... `// @endhelper` so `scoped-reg-collision` rejects writes to outer live registers omitted from `out:`.

**Tensor Core fragments, SMEM banks, stage rings, and refactor proofs**

```bash
ptx-vet --tc-report --warp 0 experiments/mma_gemm_sm120a/kernels/v3_cp_async_3stage_stmatrix.ptx
ptx-vet --warp-report --warp 0 experiments/mma_gemm_sm120a/kernels/v0_spill_conflict_unpiped.ptx
ptx-vet --stage-report experiments/mma_gemm_sm120a/kernels/v3_cp_async_3stage_stmatrix.ptx
ptx-vet --diff-layout experiments/mma_gemm_sm120a/kernels/epilogue_stmatrix.ptx --warp 0 experiments/mma_gemm_sm120a/kernels/epilogue_st_shared.ptx
```

- `--tc-report` and `tc-fragment-mismatch` track `ldmatrix` -> `mma.sync` -> `stmatrix` provenance, `.trans` consistency, duplicate registers, and duplicate 8x8 SMEM subtiles.
- `--warp-report` prints all `>=2`-way SMEM bank conflicts and alignment checks across CFG paths; `smem-bank-conflict-sim` rejects misaligned multi-byte SMEM ops and flags in-loop bank conflicts (`4-7`-way Warn, `>=8`-way Reject).
- `--stage-report` prints `cp.async` prologue depth, per-iteration commit/wait counts, barrier counts, and an event timeline (`CP_ASYNC`, `COMMIT`, `CONSUME`, `WAIT(N)`, `CTA_BAR`).
- `--diff-layout` checks 32-lane byte-provenance equivalence of `mma.sync` operands and SMEM epilogue stores across swizzle or scheduling refactors.
- Report/diff flags simulate a single warp (`--warp`, default 0); `tc-fragment-mismatch` and `smem-bank-conflict-sim` auto-probe warps 0/1/4/8 by CTA size.

---

### 2. Auditing CUDA C++ Kernels (`nvcc -ptx`)

Audit existing CUDA C++ kernels without rewriting them in raw PTX by lowering translation units to PTX and running `--profile scientific`:

```bash
nvcc -ptx -O3 -std=c++17 -arch=sm_120 solver.cu -o solver.ptx
ptx-vet --profile scientific --ptxas --warp-report --json solver.ptx
```

- `--profile scientific` runs `core` rules only, suppressing the five `ml` rules (`accidental-fp64`, `unapprox-fp32-in-loop`, `ftz-norm-rsqrt`, `f32-fma-loop-missed-tc`, `legacy-mma-on-blackwell-dc`) while still catching spills, bank conflicts, integer `div`/`rem`, 32-bit pointer-offset wraps, sync hazards, and missing launch bounds.
- **Separable compilation**: static analysis works on single-TU PTX even with external `__device__` calls; `--ptxas` requires whole-program PTX so `ptxas` resolves cross-TU symbols.
- Use `--allow narrow-gmem-in-loop,narrow-smem-store` on runtime-sized scalar loops when focusing on spills, `div`/`rem`, atomics, and safety.

---

### 3. Profiles, Custom TOML Rules, and CI Integration

**Profiles** (`--profile`):
- `default` (`core` + `ml`): ML, attention, GEMM, and Tensor Core kernels.
- `scientific` (`core` only): FP64/FP32 numerical solvers and non-Tensor-Core kernels.
- `memory`: memory, pipeline, spill, TMEM/reg-pool, and occupancy rules only.
- `strict` (`core` + `ml` + `strict`): adds `sm_90+` opt-in architecture rules (does not invoke `ptxas` unless `--ptxas` is also passed).

**Custom rules and overrides** (`--rules <file.toml>`, see `rules/example.toml` for another starter template):

```toml
[config]
profile = "scientific"
allow = ["narrow-gmem-in-loop"]
warn = ["u32-gmem-offset-overflow"]

[[rule]]
id = "no-f16-cvt-flood-in-loop"
severity = "reject"
mode = "forbid"            # forbid | require
gen = ["hopper", "blackwell-dc", "rubin"]
opcode = "cvt"
mods_all = ["f32", "f16"]
min_loop_depth = 1
min_count = 8
require_tensor_core = true
why = "Frequent fp16->fp32 casts inside a Tensor Core loop."
fix = "Feed fp16/bf16 directly into wgmma or tcgen05.mma."
```

**CI invocation** (`--deny-warnings` exits 1 on warnings; `--check-funcs` inspects non-`.entry` device functions):

```bash
ptx-vet -j4 --ptxas --deny-warnings --check-funcs --json \
  experiments/mma_gemm_sm120a/kernels/v4_unrolled_dbuf_l2swiz.ptx \
  experiments/rms_norm_sm120a/kernels/rms_norm_generic_sm120a.ptx
```

## Practical PTX Authoring Habits

- **Avoid hand-numbered virtual register pools**: author with named registers, `{ .reg ... }` scopes, and `// @helper name out:%rA` annotations, then compact via `ptx-vet --alloc-regs kernel.ptx | ptx-vet --ptxas -` so `scoped-reg-collision` and `loop-ptr-reg-clobber` guard every boundary.
- **Check `ptxas` CSE spills after every unroll or pipeline edit**: virtual PTX liveness (`--reg-report`) and physical `ptxas` register usage diverge when `ptxas` hoists repeated address expressions past a `128r`/`255r` cliff. Keep per-step address math cheap and watch `threads * regs <= 65,536`.
- **Widen 32-bit stride/byte offsets early**: `mul.lo`/`mad.lo` + `shl.b32` widened via `cvt.u64.u32` wraps modulo `4 GB`. Use `mul.wide.u32` / `mad.wide.u32`, `add.u64`, and `shl.b64`.
- **Verify silent layout & ring bugs before GPU launch**: run `--tc-report`, `--warp-report`, `--stage-report`, and `--diff-layout` to catch duplicate 8x8 subtiles, `.trans` mismatches, `%pm0..%pm7` shadowing, and off-by-one `cp.async.wait_group N` / WAR races.
- **Pair static verification with a non-uniform GPU oracle**: always validate numerical output against an FP32 GPU reference on non-tile-multiple shapes (e.g. prime dimensions).

## Built-In Rules (44 Static + 2 Opt-In `--ptxas`)

Run `ptx-vet --list-rules` for exact severity, tier, and minimum SM per rule.

- **Correctness and layout safety (`core`)**: `ptx-syntax-invalid`, `reg-def-use-safety`, `gmem-256b-legality`, `divergent-sync-hazard`, `tma-store-ordering-hazard`, `smem-static-oob`, `smem-loop-barrier-hazard`, `unguarded-gmem-tail-oob`, `u32-gmem-offset-overflow`, `named-barrier-invalid`, `loop-ptr-reg-clobber`, `scoped-reg-collision`, `tc-fragment-mismatch`, `smem-stage-race`, `smem-bank-conflict-sim`.
- **Memory, pipeline, compute, and occupancy (`core`)**: `local-mem-spill`, `scalar-smem-for-mma`, `narrow-smem-store`, `narrow-gmem-in-loop`, `manual-gmem-to-smem-staging`, `cp-async-l1-pollution`, `streaming-gmem-l1-policy`, `unpipelined-async-wait`, `unpipelined-tma-loop`, `hot-loop-layout-relayout`, `int-divrem-in-loop`, `excessive-bar-sync`, `serializing-atomics-in-loop`, `wgmma-sync-hazard`, `tcgen05-sync-hazard`, `tma-tcgen-single-thread-issue`, `generic-addr-space-in-loop`, `tmem-and-reg-pool-lifecycle`, `smem-optin-overflow`, `register-pressure-cliff`, `missing-launch-bounds`.
- **ML-specific (`ml`, disabled under `--profile scientific`)**: `accidental-fp64`, `f32-fma-loop-missed-tc`, `unapprox-fp32-in-loop`, `ftz-norm-rsqrt`, `legacy-mma-on-blackwell-dc`.
- **Opt-in (`strict`)**: `legacy-mma-on-hopper-plus`, `missing-tma-on-hopper-plus`, `missing-warp-specialization`.
- **Assembler pass (`--ptxas`, any profile)**: `ptxas-physical-spill`, `ptxas-assemble-error`.

## Python Package & Bridge

Built via `maturin` (`bindings = "bin"`), bundling both the native `ptx-vet` CLI binary and the `ptx_vet` Python module in a single wheel (~0.9 MB):

```bash
pip install .      # builds and installs both `ptx-vet` CLI and `ptx_vet` Python module
```

```python
from ptx_vet import vet_mgpu_kernel, vet_ptx, warp_report, diff_layout

rep = vet_ptx(ptx_str, arch="sm_120a", ptxas=True, dyn_smem=98304)
sim = warp_report(ptx_str, warp=0)
diff = diff_layout(orig_ptx, edited_ptx, warp=0)
reports = vet_mgpu_kernel(fn, x, y, profile="strict", dyn_smem=98304, rules_files=["rules/example.toml"])
```

You can also invoke the CLI via `python -m ptx_vet ...`.

## Validation & Calibration Sources

Rules, edge-case handling, and false-positive thresholds were hardened by authoring and auditing real kernels across:

- **[Gemma 4 (`jax-llm-examples`)](https://github.com/jax-ml/jax-llm-examples)**: hand-written `sm_120a` and `sm_100a` prefill, FlashDecoding, and Q4 GEMV PTX kernels that drove `--alloc-regs`, `--reg-report`, `--tc-report`, `--stage-report`, `gmem-256b-legality`, `ftz-norm-rsqrt`, and Hopper/Blackwell async rules.
- **[TurboMPC](https://github.com/ToyotaResearchInstitute/turbompc)**: Toyota Research Institute's CUDA C++ ADMM/PCG optimal-control solver (22 kernels / 48 instantiations lowered via `nvcc -ptx`), used to validate `--profile scientific`, `u32-gmem-offset-overflow`, `int-divrem-in-loop`, and `ptxas-physical-spill`.
- **[ThunderKittens](https://github.com/HazyResearch/ThunderKittens)** and **[Mixture-of-Kittens](https://github.com/cursor/mixture-of-kittens)**: Hopper, Blackwell, and Rubin PTX corpora used to calibrate 3-valued branch-narrowed SMEM bank simulation, TMA publish-drain waits, `sm_107a`, and `tcgen05`/TMEM rules.
- **[JAX Pallas / Mosaic GPU](https://docs.jax.dev/en/latest/pallas/gpu/index.html)** (including Tokamax kernels): Hopper/Blackwell WGMMA, TMA, and `tcgen05` PTX dumps used to calibrate async sync hazards and register-pool checks.

## Companion Files

- [`docs/guide.html`](docs/guide.html) ([direct download](https://github.com/rdyro/ptx-vet/releases/download/guide/ptx-vet-guide.html)): self-contained interactive handbook (rule explorer, 32-lane SMEM bank lab, live TOML workbench, and case study).
- [`pyproject.toml`](pyproject.toml) and [`python/ptx_vet/`](python/ptx_vet/): `maturin` (`bindings = "bin"`) packaging and Python bridge (including optional JAX Mosaic GPU helper).
- `SKILL.md`: agent workflow reference for PTX editing and verification loops.
- `rules/example.toml`: starter declarative rule and `[config]` override template.
- `examples/ptx/` and `examples/mgpu_dogfood.py`: runnable pass/fail PTX fixtures and Mosaic GPU dogfooding harness.
- `experiments/rms_norm_sm120a/` and `experiments/mma_gemm_sm120a/`: raw PTX 8.8 `sm_120a` example kernels.

## License

Licensed under the Apache License, Version 2.0. See `LICENSE` for details.

