.. meta::
   :description: Tutorial for planning tensor, context, and data parallelism for LLM inference on Trainium using the Neuron Agentic Development Parallelism Planner skill.
   :keywords: parallelism planner, tutorial, tensor parallelism, context parallelism, LLM inference, Neuron Agentic Development, Trainium, ITL, TTFT
   :date-modified: 2026-11-13

.. _parallelism-planner-tutorial:

Tutorial: Plan a serving config using the Parallelism Planner skill
====================================================================

This tutorial walks you through choosing a parallelism config for serving Granite-4.1-8B on a
trn2.48xlarge instance with the Parallelism Planner agent. You write a run-spec that describes
the model, the hardware, and your latency targets. The agent validates its analytic engine
against an oracle, sweeps every candidate config, and recommends one. You then inspect the
recommended config in detail.

By the end of this tutorial you will have a recommended tensor-parallel and data-parallel
config with predicted decode ITL, prefill TTFT, per-node throughput, and the binding
constraint, ready to validate on hardware.

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

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

The planner is an analytic model. It does not need Neuron hardware, model weights, or a
compiled model. You can run this tutorial on a laptop, a CPU-only instance, or the Trainium
instance you will later deploy on.

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

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

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 up Python
^^^^^^^^^^^^^

The planner CLI needs only the Python 3.12 standard library. Oracle validation needs
``torch``. The CPU build is enough because the oracle runs on the ``meta`` device. The
optional figures need ``matplotlib``.

.. code-block:: bash

   python3.12 -m venv ~/planner-venv
   source ~/planner-venv/bin/activate
   pip install torch --index-url https://download.pytorch.org/whl/cpu
   pip install matplotlib

Point at the skill
^^^^^^^^^^^^^^^^^^

.. code-block:: bash

   # ~/.claude for Claude Code, ~/.kiro for Kiro
   export NEURON_AGENTIC_DEVELOPMENT_ROOT=~/.claude
   SKILL=$NEURON_AGENTIC_DEVELOPMENT_ROOT/skills/neuron-parallelism-planner/scripts

Step 1. Write the run-spec
--------------------------

The run-spec is the planner's only input. It names three files that must sit in the same
directory, because paths resolve relative to the run-spec.

Create a project directory and a model directory inside it.

.. code-block:: bash

   mkdir -p ~/planner-tutorial/granite
   cd ~/planner-tutorial

**Hardware constants.** Copy the trn2 constants that ship with the skill.

.. code-block:: bash

   cp $NEURON_AGENTIC_DEVELOPMENT_ROOT/skills/neuron-parallelism-planner/references/trn2_constants.json granite/

**Model config.** Save the model's unmodified HuggingFace ``config.json`` as
``granite/granite4-8b-hf.json``. For Granite-4.1-8B, the full config is also written out at the
end of the skill's ``samples/granite4-8b-walkthrough.md``. The fields the planner uses are:

.. code-block:: json

   {
     "architectures": ["GraniteForCausalLM"],
     "hidden_size": 4096,
     "intermediate_size": 12800,
     "num_hidden_layers": 40,
     "num_attention_heads": 32,
     "num_key_value_heads": 8,
     "vocab_size": 100352,
     "max_position_embeddings": 131072,
     "tie_word_embeddings": true,
     "torch_dtype": "bfloat16"
   }

Granite is a dense GQA model, which the planner supports. If you adapt this tutorial to your
own model, first check that its architecture is listed in
:ref:`planner-supported-architectures`. Linear-attention, recurrent, and state-space layers
are not supported, and the parser does not reject them. Such a model would be silently
mis-modeled.

**Run-spec.** Save the following as ``granite/granite4-8b-run.json``.

.. code-block:: json

   {
     "model": "granite-4.1-8B (dense)",
     "hardware_name": "trn2",
     "hf_config": "granite4-8b-hf.json",
     "hardware": "trn2_constants.json",
     "serving": "colocated",
     "decode_itl_ceiling_ms": 50,
     "prefill_itps_floor": 30000,
     "configs": [
       {"label": "TP=8", "regime": "decode_heavy", "TP": 8, "PP": 1, "CP": 1,
        "bucket": 8192, "bs": 8}
     ]
   }

The two SLA fields say: every decode step must finish within 50 ms, and prefill must process at
least 30,000 input tokens per second, which is a 0.27 s TTFT ceiling at 8k context. The planner
does not read ``configs``; the Hardware Entitlement tutorial reuses this run-spec and does.

.. note::
   The planner plans servers within one node. With ``"serving": "colocated"`` (this tutorial) one
   replica serves both prefill and decode within one trn2.48xlarge (64 logical NeuronCores at
   LNC2). ``"serving": "disaggregated"`` plans one prefill server and one decode server, each
   within one node (see :ref:`planner-tutorial-disaggregated`).

Step 2. Invoke the Parallelism Planner agent
--------------------------------------------

Open your agentic IDE in ``~/planner-tutorial``.

For Kiro, start the agent directly.

.. code-block:: bash

   kiro-cli chat --agent neuron-parallelism-planner-agent

For Claude Code, start ``claude`` in the project directory. The agent is selected automatically
from your request.

Ask for a plan.

.. code-block:: text

   Plan a serving config for Granite-4.1-8B on trn2.48xlarge using the run-spec at
   granite/granite4-8b-run.json. I need decode ITL under 50 ms and at least 30,000
   input tokens/s for prefill. Maximize throughput per node.

The agent confirms the run-spec and the SLAs, then works through the steps below.

Step 3. What happens during planning
------------------------------------

**Architecture parse.** The agent parses the HF config into a model description. Granite parses
as 40 layers of full attention with 32 query heads and 8 KV heads (head_dim 128), a dense FFN,
and tied embeddings. That is 16.76 GB of BF16 weights. The agent checks this against the model
card's 8B parameter count.

**Oracle validation.** The agent runs ``validate_oracle.py``, which compares the analytic
engine's FLOP and weight counts against a shape-exact ``torch`` oracle on the ``meta`` device.

.. code-block:: bash

   python3.12 $SKILL/validate_oracle.py ./granite/granite4-8b-run.json

.. code-block:: text

   === decode S4096 bs8 ===
   segment                     oracle FLOP    analytic FLOP      d%    oracle wt(MB)  analytic wt(MB)      d%
   attention/global         48,318,382,080   48,318,382,080   +0.0%           3355.4           3355.4   +0.0%
   ffn/dense               100,663,296,000  100,663,296,000   +0.0%          12582.9          12582.9   +0.0%
   lm_head                   6,576,668,672    6,576,668,672   +0.0%            822.1            822.1   +0.0%
   TOTAL                   155,558,346,752  155,558,346,752   +0.0%          16760.4          16760.4   +0.0%

   === prefill S2048 bs1 ===
   attention/global       9,620,726,743,040 8,247,008,296,960  +16.7%           3355.4           3355.4   +0.0%
   ...

Weights and decode FLOPs match exactly. The +16.7% on prefill attention is expected: the oracle
counts the full score rectangle, while the engine charges only the causal (lower-triangle)
pairs.

**Sweep.** The agent sweeps the TP and CP grid across six context buckets from 8k up to the
model's 128k maximum. Each config is costed at the largest batch the
KV budget admits and at the powers of two below it.

**Selection.** For each bucket, the agent keeps the candidates that meet both SLAs and picks the
one with the highest throughput per node, assuming the node is filled with independent replicas.
A candidate that another candidate beats on throughput, ITL, and TTFT at once is dropped from
the reported Pareto set.

Step 4. Read the recommendation
-------------------------------

You can run the same sweep yourself.

.. code-block:: bash

   PYTHONPATH=$SKILL python3.12 -m planner ./granite/granite4-8b-run.json

The sweep prints a summary and writes ``result.json`` and ``execution_breakdown.json`` to
``agent_artifacts/tmp/``. The 8k bucket of the summary:

.. code-block:: text

   --- 8k ---
     SELECTED TP8            cores=8   TTFT=0.22s ITL=15ms sla_met=True tput/node=22222
         TP16 CP2       cores=16  bs=82   ITL=  16.1ms tput/node=    20369 bind=attention:kv_load
         TP32 CP4       cores=32  bs=164  ITL=  20.9ms tput/node=    15697 bind=attention:kv_load
         TP16           cores=16  bs=41   ITL=  15.3ms tput/node=    10713 bind=attention:kv_load
         TP32 CP2       cores=32  bs=82   ITL=  19.3ms tput/node=     8517 bind=attention:kv_load
         TP32           cores=32  bs=41   ITL=  18.5ms tput/node=     4441 bind=attention:kv_load

``bs`` is the sequences per replica at each configuration's top batch, ``tput/node`` the output
tokens per second for the node, and ``bind`` the component and term that dominates the step. In
``result.json``, ``contexts["8192"]`` holds the same bucket: ``selection_status``,
``selected_candidate_id``, the ``pareto_candidates`` the pick was chosen from, and the
``branch_ladder`` of the selected candidate. The selected candidate's ``configuration_id`` points
into the ``configurations`` registry, whose ``launch`` block reads ``tensor_parallel_size`` 8,
``data_parallel_size`` 1, and ``instance_count`` 8.

How to read it:

- **The recommendation is TP=8, deployed as 8 independent instances** across the node's 64
  cores. The planner predicts a batch of up to 41 per replica at about 14.8 ms ITL and 0.22 s
  TTFT, and about 22,000 output tokens per second for the node.
- **The batch follows the serving stack's memory policy.** The planner uses vLLM Neuron's KV
  cache allocation and HBM usage settings (30 percent of the usable HBM per core by default,
  6.48 GiB on trn2) as the policy for the largest batch, which holds 41 sequences of 8k
  context at TP8. Set ``kv_gmu_budget_cap_fraction`` in the run-spec to match a launch that
  changes it.
- **Throughput per node falls sharply past TP=8.** Granite has 8 KV heads. At TP=16, each
  KV head is stored on two ranks, and at TP=32 on four. The per-rank KV budget is the same,
  so TP16 holds the same 41 sequences as TP8 on twice the cores, and per-node throughput
  halves at each step.
- **CP recovers that loss, and only that loss.** At TP16, CP2 splits the duplicated KV
  cache's sequence across the two ranks that would otherwise each hold a full copy. That
  doubles the batch the replica can hold (82) compared to plain TP16, and TP32 CP4 reclaims
  the 4× replication (164). CP is not offered beyond the replication it reclaims, so no TP8 CP
  config is in the grid.
- **Every candidate binds on attention KV reads** (``attention:kv_load``) at its top batch:
  the batch-scaled KV read dominates the decode step.
- **ITL grows with TP at the top batch**, because a larger footprint pays larger collectives
  and, with CP, holds a larger batch. This answers the throughput-capacity question, not the
  lowest-latency one.

Further down, the selection changes as context grows: the pick is TP8 through 28k, TP16 CP2 at
44k and 76k, and TP32 CP4 at 128k. At 44k, the TTFT ceiling is 45,056 ÷ 30,000 = 1.50 s. The
planner predicts 1.61 s for TP8 on a 44k prompt, so it fails the gate, and the pick moves to
TP16 CP2 (1.14 s).

Step 5. Inspect the recommended config
--------------------------------------

Before you deploy, look at one exact operating point. Batch 16 at 8k context is a conservative
first point to compare with hardware.

.. code-block:: bash

   PYTHONPATH=$SKILL python3.12 -m planner ./granite/granite4-8b-run.json \
     --cell --tp 8 --cp 1 --bs 16 --ctx 8192

.. code-block:: text

   === granite-4.1-8B (dense) on trn2 | cell TP8 CP1 DP1 bs16 ctx8k regime=decode ===
   cores(world)=8  step_ms=8.569  comm_ms=1.864  binding=attention:kv_load
   decode otps=1867/replica  tput/node(x8)=14938

   component/type                       layers       W_MB      KV_MB     Act_MB    FLOP_G  load_ms  flop_ms  time_ms  bind
   attention/global                         40     419.43     2684.4       10.5    17.448    4.350    0.110    4.350  kv_load
   ffn/dense                                40    1572.86        0.0       10.5    25.166    2.211    0.159    2.211  weight_load
   lm_head                                   1     102.76        0.0        0.5     1.644    0.144    0.010    0.144  weight_load
   model total                                    2095.05     2684.4       21.5    44.258

The predicted decode step is ``4.350 + 2.211 + 0.144 = 6.705 ms`` of component floors plus
1.864 ms of collectives, for 8.569 ms in total. Attention is KV-read-bound, the FFN is
weight-read-bound, and every component's compute time is tiny by comparison. A faster matmul
kernel would not move this config. Fewer HBM bytes would, for example an FP8 KV cache or FP8
weights.

Step 6. Explore the latency and throughput tradeoff (optional)
--------------------------------------------------------------

**Tighten the ITL ceiling.** Rerun with a 10 ms ITL ceiling.

.. code-block:: bash

   PYTHONPATH=$SKILL python3.12 -m planner ./granite/granite4-8b-run.json --decode-itl-ceiling-ms 10

The 8k pick stays TP8 but moves down the batch ladder: ``recommended_max_num_seqs`` drops from
41 to 16 (the Step 5 cell: the planner predicts 8.57 ms and 14,938 tokens/s per node), because
every power-of-two batch below the top is itself a candidate. Only when no candidate meets every
SLA does ``selection_status`` read ``no_candidate_meets_sla`` with ``selected_candidate_id``
null; the candidates are still reported so you can see the gap.

**Draw the interactivity frontier.** ``--visualize`` sweeps batch size below the maximum for
every config, writes the figures, and prints the path of each.

.. code-block:: bash

   PYTHONPATH=$SKILL python3.12 -m planner ./granite/granite4-8b-run.json --visualize

Open ``agent_artifacts/tmp/pareto_per_node_granite_4_1_8b_dense.png``. Each curve is one config
swept over batch size. The bold frontier is the best per-node throughput available at each ITL.
For Granite at 8k, the frontier is all TP8. Moving along it from low batch to high batch trades
lower ITL for higher throughput. Pick the point on the frontier that meets your ITL target.

**Model FP8.** Copy the run-spec, add ``"weight_dtype_bytes": 1`` and
``"compute_precision": "fp8"``, and rerun to compare against the BF16 baseline.

Step 7. Check the results
-------------------------

.. code-block:: text

   ~/planner-tutorial/
   ├── granite/
   │   ├── granite4-8b-run.json                     # Your run-spec
   │   ├── granite4-8b-hf.json                      # Pristine HF config
   │   └── trn2_constants.json                      # Hardware constants
   └── agent_artifacts/tmp/
       ├── result.json                              # Picks, candidates, launch settings, ladder
       ├── execution_breakdown.json                 # Component and collective times
       ├── roofline_granite_4_1_8b_dense.png        # --visualize
       ├── pareto_granite_4_1_8b_dense.png          # --visualize
       ├── pareto_per_node_granite_4_1_8b_dense.png # --visualize: interactivity frontier
       └── prefill_footprint_granite_4_1_8b_dense.png

``result.json`` and ``execution_breakdown.json`` are overwritten by the next run.

.. _planner-tutorial-disaggregated:

Plan single-node disaggregated inference
----------------------------------------

Disaggregated inference (DI) runs prefill and decode in separate vLLM servers: the prefill
server (``kv_role: kv_producer``) computes each prompt's KV cache and hands it to the decode
server (``kv_role: kv_consumer``), which generates every output token. With
``"serving": "disaggregated"`` the planner recommends both servers for one node, each on half
its logical cores (``TP × DP = 32`` on trn2.48xlarge; replicas come from that server's
``data_parallel_size``). The planner fixes each server's core budget: half the node per server
by default; it does not size the prefill-to-decode ratio. The prefill server is swept over
TP × DCP × DP at one prompt per engine, gated on the TTFT ceiling, and ranked by prompt tokens
per second across its replicas.
The decode server is gated on the ITL ceiling and ranked by server throughput.

**Run-spec.** Copy the Step 1 run-spec to ``granite/granite4-8b-di-run.json`` and change two
keys: set ``serving`` to ``disaggregated`` and add ``contexts``, a strictly increasing list of
context lengths within the model's maximum (required, no default). The decode server is planned
at each context and the prefill server on a prompt of that length; this walkthrough uses 8k.
``prefill_itps_floor`` gates the prefill server and ``decode_itl_ceiling_ms`` the decode server.

.. code-block:: json

   {
     "serving": "disaggregated",
     "contexts": [8192]
   }

**Run the planner.** The same command plans both servers. Point ``--project-root`` at a
separate, existing directory to keep the colocated results.

.. code-block:: bash

   mkdir -p ~/planner-tutorial/di
   PYTHONPATH=$SKILL python3.12 -m planner ./granite/granite4-8b-di-run.json \
     --project-root ~/planner-tutorial/di

**Read the recommendation.** ``result.json`` carries both roles: ``prefill.contexts[<ctx>]`` is
the prefill server (``selection_status``, ``selected_candidate_id``, and the Pareto
``candidates``) and the top-level ``contexts`` block is the decode server, in the colocated
shape. The summary for this run-spec at 8k:

.. code-block:: text

   --- 8k ---
     PREFILL  TP8 x DP4      cores=32  TTFT=0.22s ceiling=0.27s input tok/s/server=151373 sla_met=True bind=ffn:flop
         TP4 x DP8      cores=32  TTFT=0.32s input tok/s/server=   202942 bind=ffn:flop (misses SLA)
         TP16 x DP2     cores=32  TTFT=0.17s input tok/s/server=    98191 bind=ffn:flop
         TP32           cores=32  TTFT=0.14s input tok/s/server=    56524 bind=ffn:flop
     DECODE   TP8 x DP4 mlp_dp=2 cores=32  bs=41 ITL=14ms sla_met=True tput/server=11641
         TP4 x DP8 mlp_dp=4 cores=32  bs=16   ITL=  11.7ms tput/server=    10957 bind=attention:kv_load
         TP8 x DP4 mlp_dp=4 cores=32  bs=16   ITL=   7.6ms tput/server=     8377 bind=attention:kv_load

The prefill server is a TP8 × DP4 mesh (4 replicas) at 216.5 ms TTFT against the 273 ms ceiling;
the decode server is TP8 × DP4 with ``mlp_dp_size`` 2 at 41 sequences per replica, 14.09 ms ITL,
and 11,641 tokens/s for the 32-core server, bound by attention KV reads.

The decode pick's ``component_routes`` shows the per-component sharding: attention stays on the
engine's TP8 group while the FFN takes a data-parallel route over pairs of engines.

.. code-block:: json

   [
     {"component_id": "attention/global", "layer_count": 40, "component_dp_size": 1,
      "dcp_size": 1, "attention_route": "standard_tensor_parallel"},
     {"component_id": "ffn/dense", "layer_count": 40, "component_dp_size": 2},
     {"component_id": "lm_head", "layer_count": 1, "component_dp_size": 1}
   ]

Like the colocated figures, these are analytic predictions to validate on hardware.

Each role's launch block is the recipe for one ``vllm serve`` process: the prefill server's
carries ``kv_transfer_config`` with ``kv_role: kv_producer`` and ``max_num_seqs`` 1; the decode
server's carries the mesh and its ``neuron_config`` (``mlp_dp_size`` is the FFN's per-component
route, see :ref:`planner-component-aware`), with the batch on the ``branch_ladder`` rung's
``launch.server_max_num_seqs``. The KV connector, ports, and the prefill-to-decode replica ratio
are launch settings covered by the
:doc:`vLLM Neuron DI tutorial </vllm-neuron/docs/tutorials/tutorial-di-1p1d-xpyd>`.
``prefill.limitations`` states the plan's scope: the TTFT covers the prefill pass alone, and the
KV transfer and the P:D ratio are not modeled.

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

The recommendation is a prediction. To validate it:

1. Run :ref:`hardware-entitlement-tutorial` on the same run-spec to get per-operator floors for
   the chosen config.
2. Deploy TP=8 with vLLM on a trn2.48xlarge, then profile it with the
   ``neuron-framework-profiling-vllm-neuron`` skill. For a disaggregated plan, launch the
   prefill and decode servers from their two launch blocks and profile each server on its own.
3. Compare measured per-segment time against the ``--cell`` breakdown with the
   ``neuron-framework-profile-analysis-vllm-neuron`` skill.

Troubleshooting
---------------

**The agent asks for missing SLAs.** The default objective needs both an ITL ceiling and a
prefill SLA. Provide them, or say which single metric you care about: lowest TTFT, or highest
decode throughput with no latency limit.

**"error: a run-spec path is required" or "run-spec not found".** Pass the path to the run-spec
file. The planner has no default model and does not look up models by name.

**KeyError: 'configs'.** The run-spec loader requires the ``configs`` key. Add it, with an empty
list if you have no cells to name.

**"run-spec serving='disaggregated' requires a non-empty 'contexts' list".** Disaggregated
planning has no default contexts. Add a strictly increasing ``contexts`` list within the model's
maximum context; a longer context fails with "exceeds model max context".

**"--visualize is not yet supported by the disaggregated planner".** Figures are available for
colocated runs; read ``result.json`` for a disaggregated plan.

**"refusing to write generated artifacts inside the skill package".** You are running from inside
the skill directory. ``cd`` to your project directory, or pass ``--project-root``.

**ModuleNotFoundError: torch.** Only ``validate_oracle.py`` needs ``torch``. Install the CPU
build into the interpreter you use.

**Weight bytes in validate_oracle.py differ by more than 1%.** The architecture was not parsed
as expected. Check tied embeddings, MoE field names, and that the parsed layer count matches
``num_hidden_layers``.

**The agent proposes nothing that meets my SLA.** The planner plans servers within one node in
the serving mode the run-spec names, and reports the best candidate for that mode and the gap.
Relax an SLA, use the per-node Pareto figure to pick a lower batch, model FP8, or plan
disaggregated inference with ``"serving": "disaggregated"`` and a ``"contexts"`` list (see
:ref:`planner-tutorial-disaggregated`).

Related resources
-----------------

- :doc:`/tools/neuron-agentic-development/developer_guides/neuron-parallelism-planner` for the deep dive on how the Parallelism Planner skill works internally.
- :doc:`/tools/neuron-agentic-development/tutorials/hardware-entitlement-tutorial` for per-operator floors of the config you chose.
- :doc:`/tools/neuron-agentic-development/getting-started` for installation and setup.
- :ref:`nxdi-vllm-user-guide-v1` for deploying the chosen config with vLLM.
- :doc:`/vllm-neuron/docs/tutorials/tutorial-di-1p1d-xpyd` for launching the prefill and decode servers of a disaggregated plan.
- :doc:`/vllm-neuron/docs/getting-started/quickstart-online-serving` for deploying the chosen config with vLLM Neuron.
- `Neuron Agentic Development GitHub <https://github.com/aws-neuron/neuron-agentic-development>`_ for source code and issue tracker.
