This document is relevant for: Inf1, Inf2, Trn1, Trn2, Trn3
Deep dive: Optimize a model to meet its SLA with the Framework Optimization skill#
Why read this guide? This guide is for engineers who own a served model’s latency or throughput number and need to move it. It explains the Framework Optimization skill, an agent-driven workflow that takes a model and a target and drives the specialist Neuron performance agents in a fixed order: parallelism planning, hardware entitlement, profiling, profile analysis, configuration sweep, and kernel work. The skill’s value is not any single measurement. It is the order, the gates that keep the order honest, and the rule that every number in the final report resolves to an artifact on disk.
How to use this guide: Read it before your first campaign on a new model, or when a previous optimization attempt produced a conclusion you cannot reproduce. Skip to The stage machine if you already understand the gates. For the hands-on path, start with the tutorial.
This topic covers the scope boundary, the two decision gates, the stage machine that enforces the order, the evidence rules that decide what counts as a measurement, and the verdict vocabulary. You need experience with transformer inference, tensor parallelism, and roofline analysis to follow it.
Prerequisites#
Before you start, you must be familiar with the following:
Inference phases and metrics: Prefill against decode, and what time-to-first-token (TTFT), inter-token latency (ITL), and aggregate output throughput each measure.
Parallelism: How tensor and data parallelism split work across NeuronCores. See Parallelism Techniques for LLM Inference.
Roofline reasoning: The difference between compute-bound, memory-bandwidth-bound, and collective-bound work.
The specialist skills this one drives: the Parallelism Planner, Hardware Entitlement, Profiling, and Profile Analysis guides.
Overview#
Optimization work fails in two characteristic ways, and neither is a wrong measurement. The first is declaring a target infeasible before anyone has written it down as a serving config. The second is hand-rolling a benchmark harness or a parallelism scheme that an existing agent already provides, or accepting a delegated conclusion without checking the evidence behind it. The two gates in this workflow exist to catch exactly those.
The skill is an orchestration layer. The agent that runs it classifies the ask, reconciles it into one serving config, and then delegates each unit of real work to the agent that owns it:
Sub-task |
Agent |
|---|---|
Parallelism and |
|
Entitlement and binding-operator localization |
|
Profile capture |
|
Bottleneck localization |
|
Kernels |
|
Model and framework code |
|
The orchestrator must therefore run as the active agent in a session. A subagent cannot spawn its own subagents, so a Framework Optimization agent launched as a subagent loses the ability to delegate and the whole model collapses. When that happens the correct behavior is to stop and say so, not to quietly substitute a hand-written benchmark for a delegated one.
Scope: the serving mode the planner recommends#
The parallelism planner emits two serving modes and both are in scope here. colocated is one
replica set serving both prefill and decode inside one node, with TP × DP no greater than the
node’s logical cores, which is 64 on a trn2.48xlarge at LNC2; data-parallel replicas are
independent replicas on that same node. disaggregated is a prefill server (kv_producer)
and a decode server (kv_consumer) sized independently, where di_placement: single_node
splits one node between the two roles and separate_nodes gives each role a whole node.
single_node is the default. No instance is wider than one node in either mode.
The mode is an input, taken from the run-spec and the planner, not a lever. Gate A records it and checks each server role against the budget its placement allows, so a plan the planner recommends is a plan this workflow accepts. Switching modes to escape a missed target is not permitted, because every profile, floor, and sweep result already in hand was measured under the old one.
What the planner leaves unplanned stays unplanned here: the P:D replica ratio, and the KV connector and the transfer between the two roles. Each role is planned and profiled in isolation, with the decode server treated as though TTFT and the initial KV blocks are already paid. A disaggregated run therefore ends at a per-role plan, floor, and profile, not at an end-to-end met verdict, which would require one finite-rate run in which both the latency and the throughput leg hold at once.
When a joint target cannot be met in the planned mode, the correct output is a documented miss, which names the best achieved result, the binding operator, the remaining headroom, and what closing it would take.
Gate A: reconcile the target before profiling#
Gate A runs before any measurement, and before anyone is allowed to use the word infeasible. It has two parts: classify the ask, then reconcile it into a config.
Classify the ask#
The ask type decides what “met” means and which operating points have to hold.
Ask type |
What the user gave |
What “met” means |
|---|---|---|
Latency-optimized (prefill) |
A TTFT or single-request latency target only |
The latency operating point holds |
Throughput-optimized (decode) |
An aggregate decode throughput target only |
The throughput operating point holds |
Joint SLA |
Both targets, required together |
Both operating points hold on one config |
The agent restates the classification before acting, which is the cheapest moment to correct a misread target.
Reconcile into one config#
The two operating points are always the same two. The latency point is a minimum-latency single
request, which lands at an interior-optimum tensor-parallel degree: on collective-bound,
short-sequence, or small-activation models latency bottoms out partway up the TP range and
regresses beyond it, so defaulting to maximum TP is wrong. The throughput point is the aggregate
at concurrency, which comes from filling the node’s remaining cores with independent replicas,
DP = cores / TP, plus a sequence-packing sweep.
For a joint ask the target is restated as a (latency point, throughput point) pair and
satisfied by one DP × TP recipe. The reason this gate exists is that joint targets look
impossible when the two halves are considered separately: a 22 ms latency target together with
45,000 tok/s on 32 logical cores is met by DP=2 × TP=16, even though no single instant shows
both numbers at once.
If the latency point prefers one TP and the throughput point another, that is a real conflict, and it is resolved on the in-scope axes: precision where the checkpoint supports FP8, batch size and sequence packing, KV cache dtype, block sizing, context bucketing, or kernel work on the binding operator.
Serving precision is the detail most likely to produce a wrong answer here. The model’s
config.json carries only the model dtype, while the serving precision is a separate
author-supplied block that silently falls back to it. KV precision is the binding term for
decode, so a deployment serving FP8 KV against a run-spec that omits kv_dtype_bytes gets
modeled around twice too high. That has been enough to report a reachable throughput SLA as
unreachable. Reconcile the precision block against the actual launch flags before recording
feasibility, and treat the planner’s warning about an unset KV dtype as a stop.
Gate B: delegate, then verify#
Gate B governs everything the agent does not do itself. Its first half is the delegation table above. Its second half is that a delegated result is not evidence until it has been checked, by five questions asked of every claim:
Does the artifact exist on disk?
Does the artifact contain what is claimed? Grep or query it rather than trusting the summary.
Does the code path support the claim?
Is the claim scoped correctly?
Recompute anything computed or aggregated, and distrust those numbers hardest.
The same suspicion applies to report files that were already in the workspace when the campaign started. A confident document dated today is not evidence. A delegated conclusion of the form “unfixable except by some large effort” needs the exact command, log, or on-device number attached before anyone acts on it.
The stage machine#
The order is mechanically enforced rather than advisory. The skill ships
scripts/framework_loop.py, which holds the run state and refuses to open a stage until its
predecessors are complete with artifacts that exist on disk. State for a run lives under
$NEURON_PROJECT_ROOT/agent_artifacts/autobridge/<run-id>/.
S=skills/neuron-framework-optimization/scripts/framework_loop.py
python3.12 $S check <stage> # non-zero exit means do not proceed
# ... stage work ...
python3.12 $S complete <stage> --artifacts <paths> --findings "<one line>"
python3.12 $S status # the run's stage table
The stage order is plan → entitlement → profile → analyze → model_optimize →
kernel_optimize → report. A stage that cites an artifact which later disappears re-closes its
gate. Hand-editing state.json to get past a gate falsifies the evidence trail; when a gate
closes, the fix is the underlying gap.
Each stage has a specific owner and a specific thing it must produce.
plan delegates to the parallelism planner and emits the DP × TP recipe. It closes only
with the Gate A reconciliation attached, and refuses to close if the recipe does not fit the
node:
python3.12 $S complete plan --artifacts agent_artifacts/plan/target_config.json \
--ask-type joint --dp 2 --tp 16 --cores-per-node 64 --findings "both points met"
--serving defaults to colocated. A disaggregated plan adds --serving disaggregated,
--di-placement {single_node,separate_nodes}, and --prefill-dp/--prefill-tp, where
--dp/--tp then describe the decode server; the gate validates each role against its own
core budget and refuses a plan that records only one of the two roles.
entitlement delegates to the hardware entitlement agent to name which operator binds: compute, weight HBM, KV HBM, or communication. The point of doing this before profiling is that it turns the profile into confirmation of a hypothesis rather than a search. The stage is followed by a feasibility record, which is a gate rather than a note:
python3.12 $S feasibility --metric ttft_ms --floor 323.1 --sla 400 --direction max
Because the floor is a lower bound, a floor that already misses the SLA cannot be recovered by kernel or compiler work, and profiling stays blocked until the config or precision changes and the record is re-filed as resolved.
profile delegates to the profiling agent and is content-gated. complete profile requires
a capture-class artifact, a trace or a non-empty capture directory, plus a verified --phase
of prefill or decode. Benchmark stdout and server logs are rejected: a run with numbers but no
trace did not profile. When a capture fails, the agent records a blocker with the command and
the on-device error, which preserves the failure in the audit trail without opening analysis on
evidence that does not exist.
A cheap reduced-layer pass before the full-depth capture is worth the extra step. Building the
same architecture and config with the layer count cut to a small k shakes out
config-agnostic problems at a fraction of the compile and capture cost, before the capture the
verdict actually rests on.
analyze delegates to the profile analysis agent, which queries the ingested trace rather than hand-rolling timers or subtracting across captures. The binding operator must be confirmed here, because a correct kernel for a secondary operator is wasted work. Every sentence of the form “X binds because Y” cites the profile path in the same breath; a mechanism that cannot be pointed at in the capture is a hypothesis and may not steer the sweep, the kernel work, or the verdict.
model_optimize is the configuration sweep, and the orchestrator will not open kernel work until it closes. The sweep is anchored to the operating point the planner chose. It does not re-pick parallelism and does not invent a batch size; it owns the deployment knobs the planner does not emit, and it turns each one for one of two reasons:
Realize the planned operating point. Lift the KV budget cap,
gpu-memory-utilization,num_gpu_blocks_override,block-size,max-num-seqs, and the decode bucket geometry so the realized batch reaches the planned one. A plan of 112 concurrent requests that runs a cap-limited 12 is the batch-fill gap, and closing it is usually the single largest win.Lower the per-step floor at that point.
--optimization-level(which Neuron defaults to O1), weight quantization, and block and bucket packing, each tested against the entitlement floor for the binding operator.
python3.12 $S complete model_optimize \
--swept num_gpu_blocks_override max_num_seqs quantization \
--artifacts agent_artifacts/autobridge/$RUN_ID/sweep_blocks.txt \
--findings "blocks 16384 = +1.7x"
The stage closes only on a measured device-time improvement and only with the swept axes named. On this stack a block-count sweep alone has been worth roughly 1.7x, which no kernel change would have surfaced. If the planned operating point proves unrealizable with these knobs, the sweep does not crown a winner from a smaller arbitrary config: it records the point as blocked and returns to planning for a deployable one.
kernel_optimize delegates implementation to the NKI agent and the Autoport vLLM Neuron agent, and build failures to the compiler artifact debugging agent. Operators are ranked by measured device time and the top one is attacked first. A new kernel is validated at the production shape and batch rather than a minimal case, and then re-profiled, because the fix is real only if both the mechanism and the end-to-end metric moved. A mechanism that moved while the metric stayed flat means the attribution was wrong, and that becomes the new top task.
report requires a calibration first. Recording floor against actual is what lets the report state honestly whether the target was met:
python3.12 $S calibrate --metric ttft_ms --floor 323.1 --actual 361.4 \
--direction max --evidence measured --verdict met \
--artifacts agent_artifacts/bench/ttft_bench.txt
Evidence rules#
Three rules decide what counts as a measurement, and all three exist because a plausible number is more dangerous than a missing one.
Device time comes from the live system trace. Read it from nc_exec_running, never from
an isolated NEFF replay, which undercounts multi-rank collective traffic substantially and is
usable only as a lower bound. Wall-clock is never quoted as if it were a device measurement.
State which quantity the SLA is defined on: device time is the trustworthy lower bound, and if
the target is end-to-end, name the host overhead the device trace does not span instead of
declaring the target met on device time alone.
No capture means no mechanism claim and no ceiling verdict. This follows from the content gate on the profile stage, and it is the rule that keeps a confident narrative from standing in for a trace.
Aggregates are measured, never projected. A node-level aggregate comes from a concurrent multi-replica run. A per-replica figure multiplied by N is tagged projected, cannot carry a met verdict, and a conjunctive SLA additionally needs one finite-rate run in which both legs hold together.
Verdicts and the stop condition#
The campaign stops when both Gate A operating points are met. It does not chase a single instant in which latency and throughput both peak, because the coupling between them makes that impossible.
The verdict vocabulary is constrained on purpose. A result sitting two or more times off its own
analytic floor, with in-scope layers untried, cannot be reported as a ceiling or as infeasible;
the orchestrator refuses those words at that gap. A large achieved-against-entitled gap is a
mandate to keep going, whatever entitled-against-required says, and the admissible interim
verdict is not_yet with the untried layers named. The words final and infeasible require
stakeholder sign-off. Reporting a miss honestly, with the best achieved number, the binding
operator, the remaining headroom, and the untried work, is a legitimate output and is more
useful than a verdict the evidence does not support.
Before any verdict, the coverage audit runs:
python3.12 $S audit
The audit works on partial state and reports any stage whose artifact is the wrong class, such as a server log standing in for a profile, as not run. It is most valuable exactly when a campaign stalled or was interrupted, because that is when the trail is thinnest.
Dead ends and confirmed levers#
The skill carries a curated list of both, so that compile cycles are not spent rediscovering them.
On collective-bound vLLM Neuron models, the following have been tested and do not pay:
fusing replicated-TP, reduce-scatter, and all-gather into an all-reduce, which cuts collective
count but not bytes on the sequence-parallel data dependency; windowed-einsum and collective
matmul overlap, whose enabling flags are specific to the XLA GPU backend and are not wired into
the Trainium path; -O3 and --model-type=transformer at TP greater than one, which is
noise on collective-heavy graphs; and vLLM async scheduling for prefill-only pooling, which is a
generative-decode feature.
One hardware constraint is worth knowing because it looks like a bug. The device backend requires
the device index to equal the local rank, so each replica’s visible-device window must be
zero-based within its own process. A second replica on a contiguous 16-31 block works, while
a split 0-3 plus 12-15 window in one launch does not.
On the other side, two levers are confirmed and should be applied directly rather than
re-derived. An NCC_IXRO002 undefined SB memory-location failure at LNC2 on an all-PyTorch
graph is a known single-flag fix: sweep the modular-flow MAC threshold above the graph’s MAC
count, rather than reaching for a single logical NeuronCore, which is TP1-only. And a README or
design note claiming that a fused operator corrupts memory on an older compiler should be
re-tested on the current compiler before anyone builds a fallback around the claim, because such
claims go stale and a direct on-device test takes minutes.
Standalone kernel mode#
The same skill has a second, narrower entry point. Handed a kernel_loop_job.json with
integration.mode set explicitly to standalone, the agent skips the seven-stage machine
entirely, does not run framework_loop.py, and runs only the inner kernel loop on a single
kernel: stage the tree, synthesize the per-shape stub, establish a baseline, iterate, and
finalize. The deliverable is the winning commit, the finalized loop state, and the kernel diff.
The inner loop is identical in both modes. Only what follows finalize differs: standalone
stops there, while a full campaign continues into vendoring, integration, and validation against
the model, and closes the kernel_optimize gate only on a win. integration.mode defaults
to the full campaign when absent.
Outputs#
A completed campaign leaves two documents, both of which resolve every number to a path.
The optimization tracker at docs/performance/<model>_optimization_tracker.md is the running
record: a timeline table with one row per landed change and its measured delta, a per-component
and per-kernel breakdown, copy-pasteable reproduction commands, and a ranked table of what is
still binding.
The optimization report states the target against the measured result, the exact serving config
to deploy, including the DP × TP recipe, per-replica parameters, environment, and device
windows, the integration summary, each delegated agent’s contribution, the confirmed levers and
dead ends encountered, and the stop-condition verdict.
Limitations#
The serving mode comes from the planner. See Scope: the serving mode the planner recommends. Colocated and disaggregated plans are both accepted, but no instance spans more than one node, the P:D ratio and the KV transfer are not planned, and a disaggregated run yields per-role results rather than an end-to-end verdict.
Measurement requires the target hardware. Unlike the planner, this workflow profiles. A capture from different hardware does not describe your deployment.
The agent must run at top level. Launched as a subagent, it cannot delegate.
The analytic floors are bounds, not predictions. They tell you what cannot be beaten, and the calibration step is what connects them to a measured run.
Next steps#
Walk the workflow end to end in the Model Optimization tutorial.
Understand the recipe this skill starts from in the Parallelism Planner deep dive.
Understand the floors it gates on in the Hardware Entitlement deep dive.
This document is relevant for: Inf1, Inf2, Trn1, Trn2, Trn3