/tt-model-bringup:functional-decoderfrom Tenstorrent Model Bring-up
Guides implementation of functionally correct TTNN decoder layers for HuggingFace transformer models, including weight loading, prefill/decode forward passes, and validation against HF reference.
Ships in Tenstorrent Model Bring-up. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Before using this workflow, follow the dependency and environment setup in the model-bringup entrypoint. Resolve its package root from this installed skill's location; do not assume this plugin is copied into the target tt-metal checkout.
If this skill is used as part of $model-bringup, follow that skill's mission, workspace, and reporting contract. This stage turns the HF decoder layer (or multiple layers if there are different kinds in the HF model) into complete, working, tested TTNN code. It's called "functional" because it should be functionally complete and ready to ship - this is not a minimal prototype, it's the heart of everything else that follows. You should bring up the decoder on a single 1x1 device mesh. No need to use multiple devices at this stage.
Implement:
models/autoports/<model>/tt/functional_decoder.py
Derive <model> from the HF model id: lowercase it and replace every non-alphanumeric character with an underscore, for example org/Model-1.2B-Instruct becomes org_model_1_2b_instruct. Downstream verification gates and tooling resolve the autoport directory from the HF model id, so do not add extra qualifiers such as hardware or experiment names.
with a model-appropriate FunctionalDecoder that subclasses models.common.lightweightmodule.LightweightModule and exposes a real weight-loading boundary:
class FunctionalDecoder(LightweightModule):
@classmethod
def from_state_dict(cls, state_dict, *, hf_config, layer_idx, mesh_device, **kwargs): ...
def prefill_forward(self, ...): ...
def decode_forward(self, ...): ...
Implement forward signatures that fit the model. Keep them keyword-friendly. Record the signatures in the README.
Start by understanding the HF model. Load AutoConfig, inspect the installed configuration_*.py and modeling_*.py, and identify the decoder layer, attention, RoPE, cache API, MLP/MoE path, residual order, norm behavior, activation, bias flags, head shapes, and layer-kind differences. Trace through the model's execution line by line to make sure you understand it.
Before writing final tests, derive the model capability contract from the HF config and model code. For decoder-layer bringup this includes the target context/sequence length, cache and position semantics, layer kinds, mode switches such as sliding vs full attention, and the externally visible prefill/decode behavior later stages must preserve. Small shapes are useful for debugging, but stage completion requires evidence for the advertised contract or a hard physical device limit reason for the largest feasible reduction.
Support logical sequence lengths, not only friendly aligned lengths. If the implementation chunks, pads, or tiles prefill internally, public prefill inputs should still accept any valid seq_len <= supported_context unless the HF model itself has a real semantic restriction. Round or pad internally, mask padded tokens, and slice outputs back to the logical length. Do not leave checks such as seq_len % 1024 == 0 on the public model path just because the current chunking helper wants that shape.
Implement correctness first. BF16, tile layout, and DRAM memory are fine while proving semantics. Move weight conversion, reshaping, dtype selection, ttnn.as_tensor, and cache construction into from_state_dict or setup helpers. Keep runtime prefill/decode free of hidden torch, from_torch, to_torch, or host fallback except explicit test boundaries.
For MoE models, validate the real router/gate and active experts end-to-end. Component tests for gate or experts are useful diagnostics, but the decoder result should include the gate-selected expert path a real model run would use. For non-Galaxy bringup, use the GPT-OSS active-expert pattern as the default: router/top-k scores as a sparsity tensor, ttnn.sparse_matmul for gate/up/down projections, score weighting, and a model-appropriate reduce over experts. Do not start from Galaxy-only fused MoE paths unless you have direct evidence that the target hardware and ops support them.
When PCC is low, debug it. Split the decoder into components, check HF parity, raise fidelity where useful, simplify the failing shape, and keep narrowing until the cause is understood. If a bug is tricky enough that ordinary narrowing stalls, use $autofix; it will run $autodebug if needed, then verify or refute each proposed bug before keeping any fix. If the cause is a tt-metal bug, make a reproducer or an on-branch workaround and record the evidence.
Implement chunked prefill during functional bringup. A bounded physical chunk size can reuse working shapes while preserving arbitrary logical prompt lengths, it plays nicely with tracing and makes it easier to optimize L1 usage.
Read existing implementations before designing the path:
TT-Transformers generator: prefill_forward_single_user_text slices tokens relative to the new input, but selects cache pages and sets RoPE/attention positions using absolute offsets. Its helpers operate on padded physical lengths; do not copy their divisibility restrictions into the public API.
TT-Transformers attention: chunk-local page tables drive cache writes, while chunked_scaled_dot_product_attention reads the accumulated cache with a causal chunk offset. This path explicitly rejects sliding-window attention.
Gemma4 generator: true last-token indices, intermediate-chunk handling, per-layer page-table routing, and bounded sliding-cache tails need model-specific treatment. Its traced-chunk path excludes bounded sliding KV. Inspect the target revision and layer contracts rather than transplanting these exceptions.
Keep chunk start, valid token count, and padded physical length distinct. For continuation, absolute position is cached-prefix length plus the offset in the new input. Preserve prior K/V, write new K/V to the intended request's pages, and let each query attend to the valid prefix and causal current chunk. Padding must not become visible to attention or overwrite live cache entries.
Fill the required K/V for every intermediate chunk. Select generation logits from the final logical token, not a padded row; preserve all logical outputs when the layer or readiness caller requests them. The generator owns orchestration; the decoder exposes the cache/position inputs it needs.
Exercise increasing lengths on the same loaded instance, including just below/at/above a chunk boundary and multiple chunks plus a tail, then reuse a short request. Compare with HF and a feasible unchunked control, including follow-on decode that consumes the filled cache. Distinguish fresh requests, which reset request state, from explicit prefix continuation. Change tokens and page ownership to expose stale state; check each supported layer kind and sliding-window boundary.
Test explicit continuation at the starts a vLLM prefix-cache hit, a chunk continuation, and a preemption resume produce: the smallest block, the least common multiple of the block sizes, a tile-unaligned start, the sliding window and one past it, and the last token. At the layer level compare the layer's contribution (output minus residual input) per row over a window of resumed rows against the full-prefill run; whole-output PCC on one layer hides attention errors behind the residual passthrough (a no-history control still scored 0.9997 on it). Add a negative control that drops the prefix history or zeroes the sliding-window snapshot and confirm it fails the same per-row gate; a control that still agrees means the test cannot see a broken resume. The full-model stage reuses this path for prefill_logits_continuation, and the serving stages depend on it for prefix caching; see prefill features.
Let one prefill call carry several rows with different lengths and starts. Keep per-row cache writes, positions, and last-token selection independent, and plan for running the dense work once across rows; the per-row full-decoder loop is a functional baseline, not the optimized target.
Keep later tracing straightforward: separate host chunk planning from device execution, and follow $tt-enable-tracing for stable buffers and input refresh. Prepare/compile all supported physical shapes and op paths before recording the first trace; the first chunk, continuation chunks, and tails may need different traces or an eager path, whose persistent setup must also precede capture. Tensor-valued offsets only permit reuse when the op supports them and the remaining program signature is unchanged. Refresh positions, valid lengths and page tables before replay, and restore cache state after warmup/capture. A new logical length within a prepared physical bucket must reuse its trace, not trigger recapture. A passing fixed-input replay does not prove increasing-length requests work.
If after working on a chunked prefill implementation you have strong evidence that it would still produce a more performant model whilst still remaining trace-safe when interleaving prefill and decode with a variety of sequence lengths, then present that evidence clearly before proceeding with the alternative path.
Use PCC >= 0.995 as the default acceptance bar for prefill and decode unless the model gives a concrete reason to choose a different bar. Done means all of these are true and recorded:
models/autoports/<model>/doc/context_contract.json records the HF-advertised context, the current supported context, the largest context tested in prefill and decode, and any hard-physical-limit reduction with byte/probe evidence.TT_METAL_WATCHER=10. If the command cannot run in the environment, record the exact environment failure and replacement evidence; do not skip asserts or weaken the test.Use this reference while bringing up a TTNN decoder layer. It folds in relevant local knowledge from personal skills and repo reading so the repo-local skill is portable.
models/common/modules/attention/attention_1d.py: general config-first attention with prefill/decode split, paged KV cache, trace-friendly current-position tensors, Q/K norm hooks, and CCL integration.models/common/modules/mlp/mlp_1d.py, models/common/modules/rmsnorm/rmsnorm_1d.py, and models/common/modules/rope/rope_1d.py: common patterns for decode-vs-prefill memory layout, on-device RoPE embedding, and local/distributed norm paths.models/common/modules/lazy_weight.py: setup-time TTNN tensor conversion and deterministic cache-key pattern without runtime torch imports.models/tt_transformers/tt/decoder.py: standard transformer block composition and residual order.models/tt_transformers/tt/generator.py and models/tt_transformers/tt/model.py: production trace capture/replay, stable trace input tensors, decode preparation, and vLLM-facing contracts.models/tt_transformers/tt/generator_vllm.py: paged KV-cache allocation, per-layer page-table routing, and hybrid attention contracts.models/demos/gpt_oss/tt/layer.py and models/demos/gpt_oss/tt/attention/: model-specific standard attention with paged prefill/decode and MoE-adjacent tests.models/demos/gpt_oss/tt/experts/README.md, models/demos/gpt_oss/tt/experts/decode.py, models/demos/gpt_oss/tt/experts/prefill.py, models/demos/gpt_oss/tt/experts/weights.py, models/demos/gpt_oss/tt/experts/config.py, and models/demos/gpt_oss/tt/topk.py: default MoE active-expert pattern using ttnn.sparse_matmul.models/demos/gemma4/tt/layer.py and models/demos/gemma4/tt/attention/: strong examples for many norms, layer scales, sliding/full layer types, shared KV, and model-specific RoPE.models/demos/deepseek_v3/tt/decoder_block/ and models/demos/deepseek_v3/tt/mla/: examples for dense-vs-MoE decoder kinds, MLA, row-sharded behavior, and specialized paged-cache updates.tech_reports/LLMs/llms.md and tech_reports/LLMs/vLLM_integration.md: TTNN LLM conventions for paged cache, prefill/decode shape differences, tracing, and vLLM integration.ttnn.bfloat16, ttnn.TILE_LAYOUT, and ttnn.DRAM_MEMORY_CONFIG where that simplifies correctness; optimize memory layout after PCC is stable.ttnn.linear unless the local TTNN helper already does it.models/common attention, Q/K weights may need HF-to-TTNN RoPE permutation handling such as reverse_permute; inspect the module contract and tests.from_state_dict can load a real checkpoint path when available. Treat the real HF state dict as the canonical key and shape contract. Normal CI tests should use synthetic weights generated from those stats so they do not require HF weight downloads.ttnn.experimental.paged_fill_cache; decode uses ttnn.experimental.paged_update_cache and ttnn.transformer.paged_scaled_dot_product_attention_decode.ttnn.bfloat8_b, prefill should cast the K/V tensors passed to paged_fill_cache to the destination cache dtype before filling. Do not blindly apply the same cast to decode: paged_update_cache update tensors must remain a supported compute dtype such as BF16/FLOAT32, even when the destination cache is BFP8.chunk_start + round_up(q_len, chunk) inside the page-table extent and choose a decode key chunk that divides the extent. The paged decode SDPA also reads the sharded query from the core its program grid assigns to each user, so the user shard rectangle must match that grid (8 wide or a single row on Blackhole); derive the physical decode batch from it instead of a divisor search.(1, batch, seq_len, hidden) style tensor shapes; decode commonly uses (1, seq_len=1, batch, hidden).max_position_embeddings or the model's equivalent field. Do not create a smaller model config. Do not hide a smaller implementation behind a smaller max_model_len.$tt-enable-tracing before accepting an eager-only decode path.trace_region_size=0, TTNN can auto-detect the right size these days.tt-perf-report with start/end signposts for the measured window.tt-perf-report --csv may expose filtered kernel time as Device Time in microseconds rather than raw nanoseconds; convert accordingly and note the column used.execute_trace. Before accepting the traced decoder, run representative repeated replay with TT_METAL_TRACE_ALLOC_TRACKING=1, cover every captured control-flow path, and resolve every unsafe allocation under the target tt-metal checkout's tech_reports/AdvancedPerformanceOptimizationsForModels/TraceCorrectness.md.tt-perf-reporttt-perf-report is a Python CLI published separately from tt-metal. Install it in the active tt-metal Python environment, not in a random system Python:
python -m pip install tt-perf-report
tt-perf-report --help
The input is the post-processed Tracy ops CSV, usually named like ops_perf_results_YYYY_MM_DD_HH_MM_SS.csv. Generate that CSV with the normal Tracy profiler flow, for example:
python -m tracy -r -p -v -m pytest <test-path> -k "<selector>"
If Tracy collection fails, the LLM tech report notes a device-only fallback:
TT_METAL_DEVICE_PROFILER=1 pytest <test-path> -k "<selector>"
python tools/tracy/process_ops_logs.py --date
For functional-decoder artifacts, copy the relevant ops CSV into the artifact directory before running tt-perf-report:
export ARTIFACT_DIR="models/autoports/<model>/doc/functional_decoder"
cp <ops_perf_results_*.csv> "$ARTIFACT_DIR/tracy/<layer_kind_id>/decode_ops.csv"
tt-perf-report "$ARTIFACT_DIR/tracy/<layer_kind_id>/decode_ops.csv" \
--start-signpost PERF_DECODE \
--end-signpost PERF_DECODE_END \
--csv "$ARTIFACT_DIR/tracy/<layer_kind_id>/decode_perf_report.csv" \
--no-advice \
> "$ARTIFACT_DIR/tracy/<layer_kind_id>/decode_perf_report.console.log"
tt-perf-report "$ARTIFACT_DIR/tracy/<layer_kind_id>/decode_ops.csv" \
--start-signpost PERF_DECODE \
--end-signpost PERF_DECODE_END \
--no-summary \
--no-advice \
> "$ARTIFACT_DIR/tracy/<layer_kind_id>/decode_perf_report.txt"
Use the same shape for prefill, with PREFILL signpost names and prefill_* filenames. If the installed tt-perf-report version does not support one of these flags, run tt-perf-report --help, use the closest supported flag set, and record the exact command in the bringup log.
The *_perf_report.txt file is for the human-readable table. Do not redirect the stdout from a --csv run into that filename; --csv mode prints command/status boilerplate such as "Writing CSV output..." rather than the rendered report table. Keep that chatter in *_perf_report.console.log if it is useful for provenance.
When calculating latency from the report, prefer the filtered tt-perf-report CSV for the signposted window. Check the time column units. Some versions expose Device Time in microseconds; raw Tracy ops CSVs often expose DEVICE KERNEL DURATION [ns]. Record which column and unit you used in functional_decoder.md.
TT_METAL_WATCHER=<n> enables watcher and sets the polling interval in seconds unless the value has an ms suffix.TT_METAL_LOGS_PATH=<dir> redirects generated logs; watcher writes under <dir>/generated/watcher/.TT_METAL_WATCHER=2, TT_METAL_WATCHER_APPEND=1, TT_METAL_WATCHER_NOINLINE=1, and TT_METAL_WATCHER_DISABLE_ETH=1.TT_METAL_LOGS_PATH per command over appending unrelated runs into one log.ttnn.from_torch, or ttnn.to_torch except at explicit boundaries.from_state_dict, input construction, final PCC comparison, and a named temporary prefill-to-decode boundary are allowed in the test harness.models/tt_transformers/tt/model.py contains host-side last-token extraction patterns for batched prefill. Treat that as an existing production compromise, not as a pattern to copy silently.tt-smi, import/open-device probes, Tracy/profile runs, and tests that touch the device.ttnn hits SFPI/JIT mismatches, prefer a source-built tt-metal environment whose headers and compiler match.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
tt-metal, ttnn, transformer-decoders, model-bringup, huggingface
14 skills in this plugin
/benchmark-modelReport a text model's accuracy on fixed lm-eval subsets and 4K-input vLLM serving performance at concurrency 1 and 32. Use after optimized-vLLM for the final model-bringup report or to benchmark a supported model./datatype-sweepSweep and select TTNN model weight, activation, KV-cache, CCL datatype, and compute-fidelity policies for the fastest configuration that satisfies minimum full-model top-1 and top-5 accuracy. Use after optimized-full-model and before vLLM, or whenever a runnable TTNN full model needs evidence-backed precision selection./full-modelBuild a complete TTNN autoregressive model and generator from a HuggingFace model plus one or more working TTNN block or decoder implementations. Use when assembling embeddings, block stack, final norm, logits, KV-cache handling, and generation into a full model, validating end-to-end behavior, and reporting full-model accuracy plus generator-level performance. Repo-specific file contracts belong in a project orchestration skill such as model-bringup.npx claudepluginhub tenstorrent/skills --plugin tt-model-bringupOther plugins' skills for the same job