AWS Builder Center

Fine-tuning DINOv3 on AWS Trainium with plain PyTorch and TorchNeuron

TorchNeuron lets you train on AWS Trainium with the PyTorch code you already write: change the device to "neuron" and your training loop, torch.compile and distributed training run as they do on other accelerators. This post shows what that looks like on a real fine-tuning workload.

TorchNeuron in practice: native PyTorch on AWS Trainium, from eager mode to torch.compile and DDP

Code:  aws-samples/sample-dinov3-torchneuron-finetune . Everything below was measured on  trn2.3xlarge  with Neuron SDK 2.33 (torch 2.14.0, torch-neuronx 2.14.3, neuronx-cc 2.28) on 2026-11-06.
Until recently, PyTorch on AWS Trainium meant PyTorch/XLA: lazy tensors,  xm.mark_step() , an XLA-specific optimizer step, and a mental model unlike the one you use on GPUs. Neuron SDK 2.33 introduces TorchNeuron as a public beta. TorchNeuron is a native PyTorch backend that registers Trainium as an ordinary device,  "neuron" , through PyTorch's  PrivateUse1  extension point. You get standard eager execution, a  torch.compile  backend and a  torch.distributed  backend, with no Neuron-specific training API.
This post evaluates TorchNeuron on a real workload: fine-tuning Meta's DINOv3 vision backbone on a small image-classification dataset. The model serves as the example workload. The post answers four questions about TorchNeuron:
  • How much of a standard PyTorch training loop has to change?
  • Does everything actually run on the NeuronCore, and how do you check?
  • What performance does  torch.compile(backend="neuron")  add, and at what cost?
  • Do mixed precision and  torchrun  + DDP work the way you expect?

Key takeaways

  • The device string is the change. On one NeuronCore, the training loop is unmodified PyTorch with  "neuron"  in place of  "cuda" . There's no  mark_step() , special optimizer or wrapper class. DDP adds the  "neuron"  backend and the usual distributed sampler.
  • Everything ran on Trainium. TorchNeuron's op tracking reported zero CPU-fallback ops in every run: eager, compiled, fp32, bf16 and DDP.
  •  torch.compile  is one line and doubles throughput.  backend="neuron"  captured the whole training step as one graph with zero graph breaks. It ran at 408-438 images/s against 205-225 in eager mode for training, and 2.4x faster for inference (737 vs 302 images/s).
  • Eager and compiled results matched bit for bit over 40 training steps in our runs, and compiled and eager inference gave identical test accuracy. Neuron documents that small differences are normal, so don't rely on exact equality.
  • bf16 autocast and DDP work with the standard PyTorch APIs. Autocast took one core to 640 images/s.  torchrun  over the 4 logical NeuronCores of a  trn2.3xlarge  reached 1,163 images/s.
  • The cost is compile time, once. Expect about 3 minutes on a cold first step. With a warm cache, the next run's first step took 7 seconds.

The workload



Model
DINOv3 ViT-S/16 (21.6M params); ViT-B/16 (86M) as a second size
Weights
timm's conversions  timm/vit_*_patch16_dinov3.lvd1689m  of Meta's checkpoints, under the
 DINOv3 License 
. They download without a click-through, but downloading or using them means you accept that license
Data
 Oxford-IIIT Pet 
, loaded from the Hugging Face copy
  timm/oxford-iiit-pet  
(CC BY-SA 4.0). 37 breeds, 3,680 train / 3,669 test images, 224 x 224
Training
Last 2 transformer blocks + a new head trainable (3.56M params), AdamW, batch 32 per NeuronCore
Hardware
 trn2.3xlarge : one Trainium2 device, 4 logical NeuronCores (LNC=2), 96 GB device memory
Software
Neuron DLAMI (Ubuntu 24.04) SDK 2.33, venv  /opt/aws_neuronx_venv_torch_neuronx_2_14_0 
The repo also supports a linear probe and full fine-tuning ( --mode linear|lastn|full ). All the numbers below use  lastn  unless noted.

1. Eager mode: the loop is just PyTorch

Here is the core of  src/dinoft/train.py , simplified (logging, DDP and  --compile  removed):
device = "neuron" # "cuda" on a GPU: this is the change
model = build_model("vit_small_patch16_dinov3.lvd1689m", num_classes=37, mode="lastn").to(device)
optimizer = torch.optim.AdamW(param_groups(model, lr=1e-3, backbone_lr_scale=0.1))

for x, y, _ in train_loader:
x, y = x.to(device), y.to(device)
loss = F.cross_entropy(model(x), y, label_smoothing=0.1)
loss.backward()
torch.nn.utils.clip_grad_norm_([p for p in model.parameters() if p.requires_grad], 1.0)
optimizer.step()
scheduler.step()
optimizer.zero_grad(set_to_none=True)
Compared with the PyTorch/XLA path, there's no lazy tensor to flush, no  xm.mark_step() , no  xm.optimizer_step()  and no device-specific data loader. Standard PyTorch features behave as they do anywhere else:
  •  requires_grad = False  freezes layers, and autograd builds a backward graph only for what trains.
  •  torch.optim.AdamW  and  torch.nn.utils.clip_grad_norm_  run on device unchanged.
  • Checkpoints are an ordinary  state_dict()  moved to the CPU.
  •  .item()  and moving a tensor to the CPU synchronize with the device, as on CUDA. So log every N steps, not every step.
On Trainium hardware,  import torch  loads TorchNeuron automatically through PyTorch's backend autoload mechanism ( tutorial ). That load also registers the  "neuron"  process-group backend. You need  import torch_neuronx  only to call its own APIs, such as the fallback report below or NKI kernels.

2. Verify that everything ran on the NeuronCore

TorchNeuron has a property to understand before you measure anything: an op with no Neuron implementation falls back to the CPU silently. Your code still runs, just slower. So the first thing to measure on a new model isn't speed, it's coverage. TorchNeuron tracks fallbacks for you:
import torch_neuronx
torch_neuronx.clear_op_tracking()
# ... one training step: forward, backward, optimizer ...
print("CPU fallback ops:", torch_neuronx.get_fallback_ops())
 train.py  prints this after step 1 and stores it in  metrics.json . DINOv3 uses patch embedding, RoPE attention, LayerScale, GELU MLPs, LayerNorm, and AdamW with weight decay. For it the list was empty in every configuration we ran: eager and compiled, fp32 and bf16, one core and DDP. To turn a silent fallback into an error during bring-up, set  TORCH_NEURONX_FALLBACK_ONLY_FOR_UNIMPLEMENTED_OPS=1 .

3. Keep shapes static

TorchNeuron compiles each distinct input shape to a Neuron executable (a NEFF) and caches it. A new shape means a new compile, and  torch.compile  on Neuron supports only  dynamic=False . For an image model, keeping shapes static is a data-loader job, done in  src/dinoft/data.py :
  • Images are resized and cropped to a fixed 224 x 224 on the CPU, so the patch grid, and the RoPE tables that depend on it, never change.
  • Training uses  drop_last=True , so every step sees exactly 32 images.
  • Evaluation can't drop test images, so the last batch is padded to 32 and carries a  valid  mask. Simplified from  pad_collate  in  data.py :
def collate(samples):
xs = torch.stack([s[0] for s in samples])
ys = torch.tensor([s[1] for s in samples])
valid = torch.ones(len(samples), dtype=torch.bool)
pad = batch_size - len(samples)
if pad > 0: # repeat the last sample, mark it invalid
xs = torch.cat([xs, xs[-1:].expand(pad, *xs.shape[1:])])
ys = torch.cat([ys, ys[-1:].expand(pad)])
valid = torch.cat([valid, torch.zeros(pad, dtype=torch.bool)])
return xs, ys, valid
Because every batch has the same shape, one training run, meaning all epochs of training plus evaluation after each epoch, needs only two compiled graphs: one for the training step and one for the evaluation forward pass. Under  torch.compile , Dynamo reported exactly two graphs for such a run.

4.  torch.compile(backend="neuron") : one line, about 2x

Neuron's  best practices  say to validate correctness in eager mode first, then compile:
model = torch.compile(model, backend="neuron", dynamic=False) # --compile
TorchDynamo traces the model, AOTAutograd produces the forward and backward graphs, and TorchNeuron lowers them through StableHLO to  neuronx-cc . ViT-S/16, one NeuronCore, batch 32. Training is 40 steps on two separate instances, and inference is the full test set on a third:

eager
 torch.compile 

training images/s (steps 3+)
224.8 / 204.5
438.1 / 408.5
~2.0x
inference images/s (test set)
302
737
2.4x
first training step, cold cache
158 s / 175 s
204 s / 196 s
one-time
Dynamo capture, training step only
n/a
697 captured calls, 1 graph, 0 breaks

What this shows about TorchNeuron:
  1. Eager mode compiles too. Eager isn't "no compile": TorchNeuron compiles op by op and caches the result, so the first eager step is also slow. The cost is paid once per shape.
  1. The speedup comes from whole-graph compilation. In eager mode every op is its own launch. Compiled, the forward and backward passes run as whole graphs that  neuronx-cc  can fuse and schedule. For inference the forward graph alone is 2.4x faster.
  1. Check that the compile really happened.  train.py  records Dynamo's counters ( unique_graphs ,  calls_captured , graph breaks) in  metrics.json . One graph and zero breaks means the entire step runs as compiled code, so  --fullgraph , which turns any break into an error, has nothing to reject. We confirmed the zero-break count. We did not run  --fullgraph  itself on Neuron.
  1. Numerics held. Eager and compiled losses matched bit for bit for all 40 steps on both instances (3.610936 -> 2.865475). Eager and compiled inference on the same checkpoint gave the same test accuracy. Neuron's  training tutorial  says to expect small differences, because the compiled graph orders operations differently. So treat bit-equality as a property of this model and compiler version, not a guarantee.
Supported  torch.compile  settings in this beta, per the  best practices :  dynamic=False ,  mode="default" , and  fullgraph=True  or  False .  options=  is not supported. Pass compiler flags through  NEURON_CC_FLAGS .

5. Persist the compile cache

TorchNeuron caches compiled work on disk in three directories, all under  /tmp  by default, so they don't survive a reboot ( environment variables ):
variable
default
holds
 TORCH_NEURONX_NEFF_CACHE_DIR 
 /tmp/neff_cache 
compiled NEFFs
 TORCH_NEURONX_HLO_CACHE_DIR 
 /tmp/hlo_cache 
HLO lowerings, shared by eager mode and  torch.compile 
 TORCH_NEURONX_NEFF_LOCAL_CACHE_DIR 
 /tmp/local_cache 
file locks and scratch only
Point the first two somewhere persistent:
export TORCH_NEURONX_NEFF_CACHE_DIR=$PWD/.neuron-cache/neff
export TORCH_NEURONX_HLO_CACHE_DIR=$PWD/.neuron-cache/hlo
To reuse compiled NEFFs across instances, you can put  TORCH_NEURONX_NEFF_CACHE_DIR  on a shared mount such as Amazon FSx. Keep  TORCH_NEURONX_NEFF_LOCAL_CACHE_DIR  on a local POSIX file system, because file locks are not reliable on NFS or Lustre ( torch.compile guide ).
In the experiment matrix, a 3-epoch run that followed a 40-step timing run with the same shapes started its first step in 7 seconds, against about 200 seconds cold. If you iterate on hyperparameters but not on shapes, you pay the compile once.

6. Mixed precision: standard  torch.autocast 

bf16 uses the stock PyTorch API with  device_type="neuron" , as Neuron's  best practices  recommend for mixed precision:
with torch.autocast(device_type="neuron", dtype=torch.bfloat16):
logits = model(x)
The weights and AdamW state stay fp32. Compiled, on one core, this took ViT-S/16 from 438 to 640 images/s (1.46x). The loss curve tracked fp32 to the third decimal over 40 steps (2.8652 vs 2.8655 at step 39). There were no fallbacks.

7. Data parallel with  torchrun  and the  "neuron"  backend

Distributed training uses the standard  torch.distributed  APIs. TorchNeuron provides the  "neuron"  process-group backend, the Trainium counterpart of  "nccl" . The one rule is ordering: initialize the process group before allocating any Neuron tensor. The backend uses  LOCAL_RANK  to give each worker its own NeuronCore, and after that plain  "neuron"  means "my core":
dist.init_process_group(backend="neuron") # before any .to("neuron")
model = DDP(model.to("neuron"))
torchrun --standalone --nproc-per-node=4 -m dinoft.train --device neuron --compile
With 4 workers at 32 images each, the compiled step reached 1,162.7 images/s, 2.65-2.85x a single core. Two TorchNeuron-specific observations:
  • DDP splits the compiled graph. Dynamo reported 7 graph breaks under DDP, against 0 on one core. They come from DDP's own hooks and logging ( _inside_ddp_forward ,  Logger.set_runtime_stats_and_log ) and from Neuron's kernel lowering. So  --fullgraph  can't be used under DDP. Those breaks and the gradient all-reduce on the critical path are the likely reasons scaling is below 4x. We did not profile it.
  • Next steps are documented, not used here. Neuron's  distributed guide  describes HostCC overlap ( TORCH_NEURONX_ENABLE_HOST_CC=1 ) and FSDP2 for better multi-core efficiency.
One issue is not Neuron-specific but affects any DDP evaluation:  DistributedSampler  pads the test set with duplicate images. Our first DDP run reported accuracy over 3,672 images instead of 3,669.  EvalShard  in  data.py  pads with entries flagged invalid instead.

8. Did it train correctly?

Throughput is only meaningful if training is correct. As a correctness check, fine-tuning on Trainium reached the accuracy you would expect from DINOv3 on this dataset after 3 epochs (single run, untuned defaults):
configuration
test accuracy
ViT-S/16, last 2 blocks, 1 NeuronCore
92.9 %
ViT-S/16, last 2 blocks, 4 NeuronCores (DDP)
88.9 % (4x fewer optimizer steps, LR not rescaled)
ViT-B/16, last 2 blocks, 1 NeuronCore
96.0 %
The full table is in   results/  , including the linear probe and full fine-tuning, and the per-run  metrics.json .

Throughput summary

Training images/s after warm-up, no eval, batch 32 per worker,  trn2.3xlarge :
configuration
images/s
ViT-S/16, 1 NeuronCore, eager, fp32
204.5-224.8
ViT-S/16, 1 NeuronCore,  torch.compile , fp32
408.5-438.1
ViT-S/16, 1 NeuronCore,  torch.compile , bf16 autocast
639.9
ViT-S/16, 4 NeuronCores, DDP,  torch.compile , fp32
1,162.7
ViT-B/16, 1 NeuronCore,  torch.compile , fp32
185.7
Ranges span two instances. These are short, untuned runs: no NKI kernels, no adaptive eager, no batch-size sweep. Treat them as a starting point, not a benchmark.

Limits of the public beta

  • TorchNeuron runs on Trn2 and Trn3 only. Inf2 and Trn1 stay on the PyTorch/XLA path.
  • Static shapes only. Dynamic shapes and symbolic ints are not supported. Pad or bucket variable inputs.
  • Silent CPU fallback by default. Check  get_fallback_ops()  on every new model.
  • Compile time is real: seconds to a few minutes per new shape. Plan for it, and persist the caches.
  • Under DDP, expect graph breaks from DDP itself.

Reproduce it

# on a trn2.3xlarge with the Neuron DLAMI (SDK 2.33)
source /opt/aws_neuronx_venv_torch_neuronx_2_14_0/bin/activate
git clone https://github.com/aws-samples/sample-dinov3-torchneuron-finetune.git
cd sample-dinov3-torchneuron-finetune
bash scripts/install_neuron_deps.sh # exact tested pins; leaves the Neuron torch build alone
bash scripts/run_experiments.sh runs # the whole matrix, ~25 min; writes runs/summary.md
The README walks through getting a Trn2 instance, a cost estimate, inference with  python -m dinoft.predict , and clean-up. Off Trainium,  uv sync --extra cpu --extra dev && uv run pytest  runs the CPU test suite: a compiled training step, 2-rank DDP over gloo, and inference.

Acknowledgements and references

This post uses DINOv3 by Meta AI, under the  DINOv3 License . The weights are timm's conversions of the original checkpoints. Fine-tuned models derived from them are covered by the same license.
  • R. Wightman. PyTorch Image Models (timm). 2019.  GitHub , doi:10.5281/zenodo.4414861.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article