.. meta::
   :description: Tutorial for optimizing a model to meet a latency and throughput SLA on AWS Trainium using the Neuron Agentic Development Framework Optimization agent.
   :keywords: framework optimization, AutoBridge, tutorial, SLA, latency, throughput, TTFT, parallelism, profiling, config sweep, Neuron Agentic Development, Trainium, vLLM Neuron
   :date-modified: 2026-11-13

.. _framework-optimization-tutorial:

Tutorial: Optimize a model to meet a latency and throughput SLA using the Framework Optimization skill
======================================================================================================

This tutorial walks you through optimizing a served model until it meets a joint latency and
throughput target on a single trn2.48xlarge instance. You give the Framework Optimization
agent a model and an SLA. It reconciles that SLA into one serving config, measures where the
time goes, sweeps the serving knobs, and only then considers kernel work.

The agent is an orchestrator. It does not plan parallelism, capture profiles, or write kernels
itself; it delegates each of those to the specialist agent that owns it, verifies what comes
back against the artifacts on disk, and refuses to move to the next stage until the current one
is closed. You stay in the conversation and read the evidence as it accumulates.

By the end of this tutorial you will have a recommended serving config, a measured
result for each operating point in your SLA, the artifact path behind every number, and an
optimization tracker that records each change and the delta it bought.

Prerequisites
-------------

Choose a machine
^^^^^^^^^^^^^^^^

Unlike the planner, this workflow measures. Run it on the trn2.48xlarge instance you intend to
serve on, with the Neuron runtime, a vLLM Neuron checkout, and the model weights already in
place. A profile captured on different hardware does not describe your deployment.

Install Neuron Agentic Development
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

If you have not already installed the package, follow the
:ref:`Getting Started guide <neuron-agentic-development-getting-started>`, and make sure the
deploy step completed.

.. code-block:: bash

   # For Claude Code
   deploy-neuron-agentic-development-to-claude

   # For Kiro
   deploy-neuron-agentic-development-to-kiro

Set the project root
^^^^^^^^^^^^^^^^^^^^

Every artifact this campaign produces lands under one project root, which is what keeps the
plan, the per-operator floors, the profiles, and the sweep results in a single evidence trail
instead of four unrelated directories.

.. code-block:: bash

   export NEURON_PROJECT_ROOT=~/autobridge-tutorial
   mkdir -p $NEURON_PROJECT_ROOT
   cd $NEURON_PROJECT_ROOT

   # ~/.claude for Claude Code, ~/.kiro for Kiro
   export NEURON_AGENTIC_DEVELOPMENT_ROOT=~/.claude
   S=$NEURON_AGENTIC_DEVELOPMENT_ROOT/skills/neuron-framework-optimization/scripts/framework_loop.py

Confirm the model serves
^^^^^^^^^^^^^^^^^^^^^^^^

Bring the model up once on your own, with whatever config you have today, and run a short
benchmark. The campaign starts from a working deployment; a model that does not serve is a
porting task, not an optimization task. See
:ref:`Port a model to vLLM Neuron <autoport-vllm-neuron-tutorial>` if you are not there yet.

Step 1. State the target
------------------------

Start the agent at the top level of the session. It needs to spawn specialist agents, and a
subagent cannot spawn its own subagents, so launching this one as a subagent leaves it unable
to delegate.

.. code-block:: bash

   kiro-cli chat --agent neuron-framework-optimization-agent

For Claude Code, start ``claude`` in the project directory and describe the task; the agent is
selected from your request.

State the model, the hardware, and both halves of the target in one sentence.

.. code-block:: text

   Optimize Qwen3-32B on this trn2.48xlarge to TTFT under 400 ms at single request and
   at least 5000 output tok/s aggregate. The serving checkout is at ~/vllm-neuron and the
   weights are at /models/Qwen3-32B.

The first thing the agent does is classify the ask, because that decides what "met" means. A
TTFT target alone is a latency ask and the verdict rests on one request. An aggregate tok/s
target alone is a throughput ask and the verdict rests on a concurrent multi-replica run. Give
it both, as above, and it is a joint ask: both operating points must hold on one config.

Expect the agent to restate the classification back to you before it does anything else. If it
has read your target differently than you meant it, correct it here rather than after a
profile.

Step 2. Watch Gate A reconcile the SLA into one config
------------------------------------------------------

Gate A is the first of two decision gates, and it exists because the most expensive failure in
this workflow is declaring a target impossible before anyone has written it as a config. The
agent delegates to the parallelism planner, which sweeps tensor parallelism and reports where
each operating point lands.

Two things are worth knowing while you read the planner's output. Latency usually bottoms out
at an interior tensor-parallel degree and regresses past it, so the planner is not looking for
the largest TP that fits; it is looking for the turn. Throughput then comes from filling the
node's remaining cores with independent replicas, so the recipe is a ``DP × TP`` pair rather
than a single number. On a trn2.48xlarge at LNC2 you have 64 logical cores to spend, and the
whole recipe has to fit inside them.

A joint target that looks impossible as two separate requirements is often met by one pair. The
skill's worked example is a 22 ms latency target together with 45,000 tok/s on 32 logical
cores, which no single instant satisfies and which ``DP=2 × TP=16`` nonetheless meets.

When the plan is settled, the agent records it:

.. code-block:: bash

   python3.12 $S check plan
   python3.12 $S complete plan \
       --artifacts agent_artifacts/plan/target_config.json \
       --ask-type joint --dp 2 --tp 16 --cores-per-node 64 \
       --findings "DP=2 x TP=16 meets both points"

The gate refuses to close the stage without that reconciliation, and refuses it again if
``DP × TP`` exceeds the node. This is the mechanism that keeps the rest of the campaign pointed
at one deployable config.

Step 3. Check the floor before you measure anything
---------------------------------------------------

The agent now delegates to the hardware entitlement agent, which computes a per-operator lower
bound for the chosen config and names which operator binds: compute, weight HBM reads, KV cache
reads, or communication. Knowing the binding operator before you profile turns profiling into
confirming a hypothesis rather than fishing.

The floor is then recorded against your SLA, one call per metric:

.. code-block:: bash

   python3.12 $S feasibility --metric ttft_ms   --floor 323.1 --sla 400  --direction max
   python3.12 $S feasibility --metric out_tok_s --floor 6100  --sla 5000 --direction min

Because the floor is a lower bound, a floor that already misses the SLA cannot be recovered by
any kernel or compiler work, and the orchestrator blocks profiling until the config changes.
The in-scope fixes are precision, the tensor- and data-parallel split within the node, batch
size and sequence packing, KV cache dtype, block sizing, and context bucketing. Splitting
prefill and decode across pools or reaching for a second node is outside this workflow's scope,
and the agent will report a documented miss rather than cross that line.

One detail to check yourself at this stage: the serving precision in the run-spec must match
the deployment. KV cache precision is the binding term for decode, so a deployment that serves
FP8 KV but a run-spec that omits it gets modeled around twice too high, which is enough to
report a reachable SLA as unreachable.

Step 4. Capture a real profile
------------------------------

The device capture is the one hard input of this workflow, so the gate on it is a content check
rather than a formality. The agent delegates to the profiling agent and captures prefill and
decode separately, because the two phases bind on different things and a trace containing both
cannot tell you which.

.. code-block:: bash

   python3.12 $S check profile
   # ... profiling agent captures the traces ...
   python3.12 $S complete profile --phase decode \
       --artifacts agent_artifacts/data/profiles/decode/capture \
       --findings "decode capture, TP16, bs112"

``complete profile`` requires a capture-class artifact and a verified phase. Benchmark stdout
and server logs are rejected: a run with numbers but no trace did not profile. If the capture
fails, the agent records a blocker with the command and the on-device error, which keeps the
failure in the audit trail without opening the analysis stage on evidence that does not exist.

Device time comes from the live ``nc_exec_running`` system trace. An isolated NEFF replay
undercounts multi-rank collective traffic substantially and is treated as a lower bound only.
If your SLA is end-to-end rather than device time, expect the agent to name the host overhead
the trace does not span instead of calling the target met on device time alone.

Step 5. Read where the time goes
--------------------------------

The profile analysis agent queries the ingested trace and reports which graphs ran, what the
roofline floor is for each step, which engine binds, how much of the step is collectives, and
which model component is responsible.

The rule to hold the analysis to is that every claim of the form "X binds because Y" cites the
profile artifact in the same breath. A mechanism you cannot point at in the capture is a
hypothesis, and a hypothesis is not allowed to steer the sweep, the kernel work, or the
verdict. Serving-log metrics can tell you which phase occupies the device; they never license a
*because*.

Step 6. Sweep the serving knobs before touching kernels
-------------------------------------------------------

This is the stage that most often produces the largest win, and the orchestrator will not open
kernel work until it is closed. On this stack a block-count sweep alone has been worth roughly
1.7x, which no kernel change would have surfaced.

The sweep is anchored to the operating point the planner chose. It does not re-pick tensor or
data parallelism and it does not invent a batch size; it turns the deployment knobs the planner
does not emit, for two reasons. The first is to realize the planned operating point: lifting the
KV budget cap, ``max-num-seqs``, and the decode bucket so that a plan of 112 concurrent requests
actually runs 112 rather than a cap-limited 12. That batch-fill gap is usually the single
biggest lever. The second is to lower the per-step floor at that point, through
``--optimization-level`` (Neuron defaults to O1), weight quantization, and block and bucket
packing.

.. code-block:: bash

   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 decode device time"

The stage closes only on a measured device-time improvement, and it names the axes that were
swept. If the planner's operating point turns out to be unrealizable with these knobs, the right
outcome is not a winner picked from a smaller arbitrary config: the agent records the point as
blocked and returns to planning to derive a deployable one.

Step 7. Kernel work on the binding operator only
------------------------------------------------

With the config exhausted, the agent delegates implementation to the NKI agent for kernels and
to the Autoport vLLM Neuron agent for framework code, and to the compiler artifact debugging
agent when a build fails. Rank operators by measured device time and attack the top one: a
correct kernel for a secondary operator moves nothing end to end.

Validate any new kernel at the production shape and batch rather than a minimal case, then
re-profile. The fix counts only if both halves moved, the mechanism in the profile and the
end-to-end metric. A mechanism that moved while the metric stayed flat means the attribution was
wrong, and that becomes the next thing to investigate.

Step 8. Calibrate, audit, and read the verdict
----------------------------------------------

Before reporting, the agent compares the analytic floor from steps 2 and 3 against what the
machine actually did:

.. code-block:: bash

   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

Reporting is blocked until at least one calibration exists, because a report that never compares
the floor to a measured run cannot honestly say whether the SLA was met. Two rules shape what
the verdict is allowed to say. An aggregate number must come from a concurrent multi-replica
run; a per-replica figure multiplied by N is tagged as projected and cannot carry a met verdict.
And a verdict of ceiling or infeasible is refused while the measured result sits two or more
times off its own floor with in-scope work untried, because a large gap like that is a mandate
to keep going rather than a wall. The honest interim answer there is "not yet", with the untried
layers named.

Run the coverage audit before you accept any verdict:

.. code-block:: bash

   python3.12 $S audit
   python3.12 $S status

The audit works on partial state and reports any stage whose artifact is the wrong class, a
server log sitting where a profile should be, for example, as not run. It is worth running even
when a campaign stalls, precisely because that is when the evidence trail is thinnest.

What you end up with
--------------------

Two deliverables, both backed by on-disk artifacts. The first is an optimization tracker at
``docs/performance/<model>_optimization_tracker.md``: a timeline with one row per landed change
and the measured delta it bought, a per-component breakdown, reproduction commands you can
paste, and a ranked table of what is still binding. The second is the report, which states the
target against the measured result, the exact serving config to deploy, what each delegated
agent contributed, and the stop-condition verdict.

The campaign stops when both Gate A operating points are met. A documented miss is a legitimate
outcome and is more useful than a number without an artifact behind it: it tells you the best
achieved result, the binding operator, the remaining headroom, and what it would take to close
it.

Next steps
----------

- To understand the gates, the stage machine, and the evidence rules in depth, read the
  :ref:`Model Optimization deep dive <neuron-framework-optimization>`.
- To choose a serving config without hardware, see the
  :ref:`Parallelism Planner tutorial <parallelism-planner-tutorial>`.
- To localize the binding operator for one config, see the
  :ref:`Hardware Entitlement tutorial <hardware-entitlement-tutorial>`.
- To capture and read profiles yourself, see the
  :ref:`Profiling tutorial <profiling-vllm-neuron-tutorial>` and the
  :ref:`Profile Analysis tutorial <profile-analysis-vllm-neuron-tutorial>`.
