A comprehensive, research-focused tutorial for AWS Trainium and Inferentia. This tutorial provides what researchers and organizations need to leverage AWS Neuron hardware for cost-effective ML research and production deployment.
✅ Hardware-validated on real Trainium. On the default path, TorchNeuron, 5 of the 6 single-device examples are auto-validated on
trn2.3xlarge(Neuron SDK 2.33.38, torch-neuronx 2.14.3.0.1), each with a captured provenance artifact.antibody_affinity_slmstays unvalidated until its fp32 5-seed sweep runs under the harness (a manual fp32 run gave Spearman 0.430±0.091). On the optional PyTorch/XLA path (torch-neuronx 2.9.0.2.15) all 6 are validated acrosstrn1.2xlargeandtrn2.3xlarge. The multi-process examples (qwen3_lora,ddp_ner,tp_full_finetune) are validated by manualtorchrunlaunch:ddp_nerruns native DDP on TorchNeuron, and the two optimum-neuron examples are XLA-only. SeeVALIDATED.md. Every performance number traces to a real run; nothing is hand-typed. (Compile cost works differently on the two paths. PyTorch/XLA compiles the whole model graph before it runs, unlike a GPU, so the satellite CNN's first run ontrn1.2xlargespent ~40 min compiling. Eager TorchNeuron compiles each op, and each new shape, the first time it sees it. That's a core lesson, explained in the CUDA→Neuron chapter.)
This tutorial targets Neuron SDK 2.33.0 (released October 19, 2026). Its default path is TorchNeuron, AWS's native PyTorch backend (
torch-neuronx2.14, PyTorch 2.14): Trainium is an ordinary PyTorch device (.to("neuron"), eager), with optionaltorch.compile(backend="neuron"). Every example defaults todevice="auto", which picks TorchNeuron if it's available, else PyTorch/XLA, else CPU, and prints one line saying which ran. Things to keep in mind:
- TorchNeuron is AWS public beta as of Neuron 2.33, and runs on Trn2/Trn3 only. This tutorial defaults to it anyway, for four reasons. AWS's docs present it as the future path and call PyTorch/XLA legacy. PyTorch 2.9 is the last XLA release. In Neuron 2.34, PyTorch/XLA inference and the NxD Inference APIs end on Trn2/Trn3. And eager
.to("neuron")is the closest thing to CUDA-style PyTorch. The measured costs: warm NER throughput was 199.5 samples/s on eager TorchNeuron vs 228.5 on PyTorch/XLA, at about the same F1; eager mode compiles per op and per shape on first use; and the S3 compile cache (NEURON_COMPILE_CACHE_URL) had no effect on TorchNeuron. See TorchNeuron vs XLA and Running on TorchNeuron.- PyTorch/XLA is optional (
torch_xla,xm.xla_device(),xm.mark_step(); the sametorch-neuronx 2.9.0.2.15build from 2.31 through 2.33). Select it withdevice="xla"(or an example's env override, e.g.NER_DEVICE=xla). It's the only path on Trn1, and it's still required by the optimum-neuron examples (qwen3_lora,tp_full_finetune), the Inf2 serving step of the train→serve pipeline (torch_neuronx.trace), and the satellite example'storchrunpath.- Trainium is now the path for both training and inference. AWS has not announced an Inferentia3. NxD Inference dropped Inf2/Trn1 in Neuron 2.29, and in 2.34 the NxD Inference APIs and PyTorch/XLA inference end on Trn2/Trn3: AWS's replacements for Trn2/Trn3 serving (vLLM Neuron for LLMs, TorchNeuron +
torch.compile) are both still beta as of 2.33. Inferentia2 remains GA and useful for cost-optimized, latency-sensitive, smaller-model inference, but new work should generally target Trainium2 (Trn2). See the Inferentia decision guide.
- FinOps-First Approach: Built-in cost controls and monitoring
- Ephemeral Computing: Auto-terminating resources to prevent runaway costs
- Complete Workflows: End-to-end examples from training to inference
- Advanced Patterns: NKI development, RAG implementations, distributed training
- Cost Monitoring: local cost report + static dashboard (no AWS credentials in the browser)
- Domain-Specific Examples: Climate science, biomedical, social sciences
- Training: 30-75% savings vs comparable NVIDIA GPU instances
- Inference: substantial savings with spot instances on Inf2 (Trn2 spot capacity was never available in our tests; see Using Trn2)
- Example: Llama 2 7B training - ~$144 (Trainium2) vs ~$295 (H100)
⚠️ On the numbers in this tutorial: cost figures are illustrative estimates based on published on-demand/spot pricing and public benchmarks, not measured results from a single controlled run unless explicitly stated. Spot prices vary by region and time. Always confirm current pricing in the AWS pricing pages before planning a budget, and treat throughput/cost tables as planning aids rather than guarantees.
Pick the path that matches your goal — they differ by an order of magnitude in time and cost:
| Path | What you do | Time | AWS cost* |
|---|---|---|---|
| Read + laptop smoke tests | Read the core docs; run each example's CPU *_SMOKE path on your laptop (proves the code, no Trainium) |
~3–4 hrs | $0 |
| Guided hands-on, Trn2 (default path) | The above + one trn2.3xlarge in an EC2 Capacity Block; run 2–3 examples end-to-end on TorchNeuron |
~half a day (inside the block) | one prepaid block, ~$32–54 |
| Guided hands-on, Trn1 (cheaper) | The above + one trn1.2xlarge on spot; run 2–3 examples on PyTorch/XLA (device="auto" picks it there) |
~half a day | ~$1–3 |
| Full hardware lab | Run all examples on Trainium, including the multi-core (qwen3_lora, ddp_ner) and train→serve pipeline |
~1–2 days (mostly unattended) | ~$10–25 on Trn1; on Trn2, one or two prepaid Capacity Blocks |
* trn1.2xlarge is ≈ $0.40/hr spot / ~$1.34/hr on-demand (us-east/us-west, illustrative — confirm
current pricing). For trn2.3xlarge, spot and on-demand never had capacity in our tests (Oct 2026), but
EC2 Capacity Blocks did, at about $32–54 per block, prepaid and non-refundable; see
Using Trn2. Auto-terminating scripts + budget alerts (Quick Start
steps 1–2) keep this bounded.
Expect compile time to matter, especially on a first run. That's a central lesson of the tutorial, not a bug, and it plays out differently on the two paths:
- PyTorch/XLA pays an ahead-of-time compile of the whole graph (minutes for small models, ~40 min
for the satellite CNN on
trn1.2xlarge). An S3 compile cache makes it a one-time cost, so warm re-runs finish in ~1–2 min. - TorchNeuron in eager mode compiles each op, and each new input shape, the first time it sees it.
In the harness, the five validated TorchNeuron defaults (eager, except
cv_utilization_spike, which usestorch.compile) each took 106–256 s of wall clock ontrn2.3xlarge. The S3 cache lesson is XLA-only:NEURON_COMPILE_CACHE_URLhad no effect on TorchNeuron in our tests.torch.compile(backend="neuron")compiles whole graphs, and a cold NER run with it took 49 min.
Budget generously for your first launch.
New to this tutorial? Follow this path — each step builds on the last:
- Local setup guide — get your machine ready (Python 3.12 + uv, AWS CLI).
- Quick start — your first success: run the NER smoke test, then a real Trainium run.
- Choose your path — honest verdict on whether Trainium fits your workload, and which example to start from.
- Full tutorial — the in-depth chapters (FinOps, CUDA→Neuron migration, the complete workflow) with its own table of contents.
- Trainium development best practices — the
compile / bf16 / static-shape rules. Best read after your first real Trainium run, when its
"we hit a
nanat step 0 / 7 recompiles" field notes match what you just saw (read it earlier for the rules, and revisit).
Hit an error? Jump to Neuron tools & debugging (symptom→tool table).
Using Claude Code or Kiro? Optional capstone: Agentic Neuron development — AWS's official agents + skills (NKI kernels, autoport, profiling) installed into your assistant.
# 1. Set up AWS credentials (SSO preferred: `aws configure sso` + `aws sso login`; or `aws configure`)
aws sso login --profile research && export AWS_PROFILE=research
# 2. Create budget alerts (--email is required — alerts are time-sensitive)
python scripts/setup_budget.py --limit 500 --email [email protected]
# 3. Launch an ephemeral, auto-terminating trn2.3xlarge (TorchNeuron) inside an EC2 Capacity
# Block you've bought: pass the block's region and reservation ID (see "Using Trn2" in
# docs/quick-start.md for how to find and buy one)
python scripts/ephemeral_instance.py \
--name "bert-test" \
--instance-type "trn2.3xlarge" \
--region ap-southeast-4 \
--capacity-reservation-id cr-... \
--max-hours 4
# ...or the cheaper PyTorch/XLA alternative, on spot (no Capacity Block needed):
# python scripts/ephemeral_instance.py --name "bert-test" --instance-type "trn1.2xlarge" --max-hours 4
# 4. Monitor costs (console summary + ml_costs.png)
python scripts/cost_monitor.py
# ...or write a report for the static dashboard (see monitoring/README.md)
python scripts/cost_monitor.py --json monitoring/cost_report.jsontrn2.3xlarge is the default starting instance: one Trainium2 chip running TorchNeuron, the path every
example's device="auto" takes first. Trn2 capacity is scarce: in our tests spot and on-demand never
had it, so plan on an EC2 Capacity Block (prepaid). The instance ends at --max-hours or ~30 min before
the block ends, whichever comes first. Without a reservation, a Trn2 launch usually fails on capacity
and the script prints how to find and buy a block. See Using Trn2.
trn1.2xlarge is the cheaper alternative and is usually available on spot. It runs PyTorch/XLA
(TorchNeuron doesn't run on Trn1), and device="auto" picks XLA there. Either way the script
resolves the current Neuron DLAMI from SSM and activates its venv.
aws-trainium-tutorial-for-research/
├── README.md # This file
├── docs/ # Full tutorial + best-practices + troubleshooting
├── scripts/ # Utility scripts (budget, ephemeral instance, monitor)
├── validation/ # Hardware-validation harness + provenance artifacts
├── examples/
│ ├── use_cases/ # biomedical_ner, satellite_landcover, cv_utilization_spike, distill/antibody/crystal SLMs, qwen3_lora (hardware status in VALIDATED.md)
│ ├── complete_workflow/ # Trainium → Inferentia pipeline
│ ├── debugging/ · distributed/ # failure walkthrough; DDP / tensor-parallel examples
│ └── _legacy/ # older templates (deployment, integration, …), not maintained
├── advanced/ # Advanced NKI patterns (illustrative)
├── monitoring/ # Static cost dashboard (reads cost_report.json; no credentials in browser)
└── VALIDATED.md # Generated: which examples are hardware-validated
The reference example: a real disease-NER fine-tune on the NCBI-disease corpus, validated on a
real trn2.3xlarge on TorchNeuron (eval_f1 = 0.850 ± 0.005, n=4 seeds) and on the optional
PyTorch/XLA path (eval_f1 = 0.848 on trn1.2xlarge); see VALIDATED.md. It's the
model the other examples aim to match: real data, honest metrics, the Trainium-native lessons baked in.
# Laptop smoke test (CPU, proves the code path — F1 will be near zero on the tiny 1-epoch
# subset; this checks plumbing, NOT accuracy. The 0.850 above is the full Trainium run):
NER_SMOKE=1 python examples/use_cases/biomedical_ner.py
# Real run — execute this ON a Trainium instance / DLAMI (on trn2.3xlarge it reaches eval_f1 ≈ 0.85).
# device="auto" takes TorchNeuron, else PyTorch/XLA, else CPU, and prints which. Off-Trainium that
# means a slow full CPU run (`device=auto -> cpu`), so only run it on a Neuron box:
python examples/use_cases/biomedical_ner.py
# Force the optional PyTorch/XLA path (needs the XLA venv; automatic on Trn1):
NER_DEVICE=xla python examples/use_cases/biomedical_ner.pySee examples/use_cases/biomedical_ner.md and the
Trainium development best practices it demonstrates.
examples/complete_workflow/trainium_to_inferentia_pipeline.py
shows the full lifecycle — train on Trainium (XLA path), then compile the trained model for
Inferentia serving with torch_neuronx.trace — with real run_instances calls, runtime DLAMI
resolution, and auto-termination. It uses PyTorch/XLA throughout, because Inf2 serving needs it; it
doesn't use the TorchNeuron default. It's a teaching template (edit the S3 bucket; it's not a hardened
service).
Note: This is advanced material — skim it on a first read. The snippet below is illustrative pseudocode to convey the shape of an NKI kernel and the NeuronCore memory hierarchy — it is not a drop-in, runnable kernel. The terms it uses (SBUF/PSUM on-chip memories, the 128×128 systolic array) are explained from scratch in the novel kernels chapter; the real
neuronxcc.nki.languageAPI operates on tiles with explicit partition/free-axis reductions and masking. For working kernels, start from the official NKI documentation and samples.⚠️ If you make kernels in a factory that captures constants, setNKI_ENABLE_TRACE_CACHE=0: an open NKI bug (aws-neuron-sdk#1454) can silently reuse the wrong kernel. See the novel kernels chapter.
# Custom Flash Attention kernel for Trainium (ILLUSTRATIVE — not runnable as-is)
@nki.jit
def flash_attention_kernel(q_tensor, k_tensor, v_tensor, scale):
# Optimized for NeuronCore v2 memory hierarchy
# - SBUF: 24MB on-chip memory
# - PSUM: 2MB for matrix multiply results
# - Native 128x128 matrix operations
q_tile = nl.load(q_tensor)
k_tile = nl.load(k_tensor)
v_tile = nl.load(v_tensor)
scores = nl.matmul(q_tile, k_tile.transpose())
attn_weights = nl.softmax(scores * scale)
output = nl.matmul(attn_weights, v_tile)
return output-
Clone the repository:
git clone https://github.com/scttfrdmn/aws-trainium-tutorial-for-research cd aws-trainium-tutorial-for-research -
Set up the environment with uv (this repo standardizes on uv + Python 3.12 — pinned in
.python-version):# Install uv if you don't have it: https://docs.astral.sh/uv/getting-started/installation/ uv python install 3.12 # the one supported version (pinned in .python-version) uv venv uv pip install -e ".[dev,science]" # dev tooling + the science deps the examples need # (rasterio, pymatgen, biopython, …). `make install-dev` is equivalent. # Neuron wheels come from the AWS Neuron index (run on a Neuron instance, not your laptop). # On a Neuron DLAMI it's simpler to activate the bundled venv, e.g. TorchNeuron on the 2.33 # multi-framework DLAMI: source /opt/aws_neuronx_venv_torch_neuronx_2_14_0/bin/activate make install-neuron # TorchNeuron (default; Trn2/Trn3): torch-neuronx==2.14.*, neuronx-cc==2.*, nki # ...or, in a separate venv, the optional PyTorch/XLA stack (Trn1; optimum-neuron examples): # make install-neuron-xla # torch-neuronx==2.9.*, neuronx-cc==2.*
-
Configure AWS:
python scripts/aws_environment_checker.py
-
Run the tests to confirm your setup:
uv run pytest -m "not aws and not neuron"
We welcome contributions! Please see CONTRIBUTING.md for guidelines.
MIT License - see LICENSE for details.
- AWS Neuron Community: AWS Neuron SDK GitHub
- GitHub Issues: Report bugs or request features
- Documentation: Full tutorial · Quick start · Choose your path
If you use this tutorial in your research, please cite:
@misc{aws_trainium_tutorial2026,
title={AWS Trainium \& Inferentia: Complete Tutorial for Academic Researchers},
author={Friedman, Scott},
year={2026},
publisher={GitHub},
url={https://github.com/scttfrdmn/aws-trainium-tutorial-for-research}
}