PART-1: Port and Run Google's Gemma 4 26B-A4B (MoE) on AWS Trainium2
Walk through porting a sparse Mixture-of-Experts LLM to AWS Neuron, compiling it at TP=4 on a single Trainium2 chip, and benchmarking it across context lengths and concurrency plus a tiered storage design that keeps the working set fast and the environment recoverable.
PART-1: Port and Run Google's Gemma 4 26B-A4B (MoE) on AWS Trainium2
A step-by-step guide to port, compile, and benchmark the sparse Mixture-of-Experts Gemma 4 26B-A4B model on an AWS Trainium2-powered Trn2 instance, with a storage strategy tuned for both performance and resiliency.
Introduction
Enterprises want the capabilities of large language models, but two realities get in the way: cost and control. Running a 20B+ model on GPUs for every request is expensive and supply-constrained, and many organizations, whether in regulated industries or simply handling sensitive prompts and documents, can't send that data to a third-party inference API. They want a capable open model running in their own environment, at a predictable cost.
Two things make that practical today. First, sparse Mixture-of-Experts (MoE) architectures. By activating only a small fraction of their parameters per token, modern MoE models deliver the quality of a very large model at the compute cost of a much smaller one, which brings serious capability within reach of a single accelerator. Second, purpose-built AI silicon. A new generation of accelerators is designed specifically for cost-efficient, scalable training and inference, offering a compelling price-performance alternative to running everything on GPUs.
This blog brings the two together. We will port, compile, and run Google's Gemma 4 26B-A4B on a single AWS Trainium2 -powered
trn2.3xlarge instance, the small, cost-optimized Trainium2 box, using NeuronX Distributed Inference (NxDI) . Gemma 4 26B-A4B has ~25.2B total parameters but activates only ~3.8B per token (128 routed experts, top-8 routing, plus a shared dense branch), and it runs entirely on AWS Neuron cores , inside your own account, so your data never leaves your environment.By the end, you will have:
- A Neuron-compiled Gemma 4 26B-A4B running at tensor-parallel degree TP=4 on a single Trainium2 chip
- A tiered storage architecture that matches each AWS storage service to its job: instance-store NVMe for the fast working set, Amazon EBS
gp3as the durable anchor, and FSx for Lustre for shared data, with one-command recovery after an ephemeral wipe
- Benchmarks across context lengths (256 to 8K tokens) and concurrency (batch 1 to 8), with steady-state decode of ~104–119 tok/s and aggregate throughput scaling to ~318 tok/s at batch 8
Note: This is Part 1, text inference. Gemma 4 is natively multimodal. Enabling the vision (image-to-text) path is the subject of Part 2.
Model architecture
Gemma 4 26B-A4B is a text decoder with a heterogeneous attention stack and a sparse MoE feed-forward network.
Field | Value |
|---|---|
Total / active parameters | ~25.2B / ~3.8B (MoE) |
Layers | 30 |
Experts | 128 routed + 1 shared dense, top-k = 8 |
Attention heads | 16 query / 8 KV (GQA 2:1) |
Attention pattern | Heterogeneous: sliding-window (head_dim 256) interleaved with global (head_dim 512) |
Positional encoding | Partial RoPE (0.25) on global layers |
Extras | Final logit soft-cap (30), scaled embeddings, parallel dense + MoE branch |
Weights | ~50 GB (bfloat16 safetensors) |
The MoE structure is the key to running it economically: only 8 of 128 experts are consulted per token, so the arithmetic per step stays close to a ~4B dense model even though all 128 experts must be resident in memory.
Trn2.3xlarge and AWS Trainium2: hardware at a glance
A
trn2.3xlarge instance packs one Trainium2 chip, connected to a host with 12 vCPUs, 32 GiB of host memory, and one 470 GB local NVMe SSD for instance storage.High Bandwidth Memory (HBM)
The Trainium2 chip carries 96 GiB of HBM at 2.9 TB/s of memory bandwidth — enough to hold all 128 experts of the MoE resident in bfloat16.
Compute
Logical NeuronCore Configuration (LNC)
Trainium2 introduces Logical NeuronCore Configuration (LNC) — a mechanism that fuses the compute and memory of multiple physical cores into one logical core. At the default LNC=2, every 2 physical cores are grouped into 1 logical core, giving 4 Logical NeuronCores per
trn2.3xlarge (8 physical ÷ 2). These 4 logical cores are what you shard the model across.
Why trn2.3xlarge, and why TP=4
trn2.3xlarge is the entry point to Trainium2 — one chip, 4 logical cores, 96 GiB HBM — which makes it the right box to port, validate, and cost-optimize an inference workload before scaling out to the 16-chip trn2.48xlarge for production volume.For Gemma 4 26B-A4B, the tensor-parallel degree isn't just a tuning knob — TP=4 is required:
- The full MoE keeps all 128 experts resident (~50 GB in bfloat16). Split across 2 cores (TP=2), each shard needs ~25 GB — which exceeds the ~24 GiB available per logical core and fails to compile with an out-of-memory error (
NCC_EVRF009).
- At TP=4, each shard is ~12.6 GB and fits comfortably. So on this box, TP=4 is both the maximum and the minimum that works.
Note: Because a compiled Neuron artifact (NEFF) is fixed to its tensor-parallel degree and shape, everything in this guide is at TP=4. Scaling to higher TP for higher throughput belongs on a
trn2.48xlarge — with 16 Trainium2 chips (128 physical cores, i.e. 64 logical NeuronCores at LNC=2) it supports tensor-parallel degrees up to TP=64 — and is out of scope for this single-chip guide.
How the model gets "ported" to Neuron
Running a PyTorch model on Trainium isn't a matter of loading weights and calling
.generate() . The model has to be ported: its architecture is re-expressed with Neuron-aware building blocks, sharded for tensor parallelism, and then compiled into a hardware-specific binary called a NEFF (Neuron Executable File Format).For Gemma 4 26B-A4B we used the NxDI contrib port (community contribution PR #172 ), which implements the model as
NeuronGemma4ForCausalLM . A Neuron port like this does three things the stock HuggingFace model does not:- Re-maps the architecture to Neuron modules. Each HuggingFace layer (attention, the 128-expert MoE block, the heterogeneous sliding-window/global attention, partial RoPE, logit soft-capping) is expressed with NxDI's distributed layers so the compiler can shard and place them across NeuronCores.
- Sets tensor parallelism. The port shards weights across the 4 logical cores (TP=4), including the MoE experts.
- Compiles to NEFF, once. The Neuron compiler traces the graph at a fixed shape (context length, batch size) and emits a NEFF that is reused for every subsequent inference call.
The port is environment-variable driven through a single entry script,
scripts/smoke_compile.py , so a compile is fully declarative — you set the shape and TP degree and run one command.The porting skill behind it
This port wasn't hand-written from scratch. It was produced with Neuron Agentic Development — AWS's agentic tooling for Trainium, which ships two skills that map exactly to the workflow above:
-
neuron-framework-autoportports a HuggingFace model to NxD Inference end to end: it re-expresses the architecture with Neuron-aware modules, wires up tensor-parallel sharding, and generates the declarative compile entry points.
-
neuron-framework-equivalencethen validates numerical equivalence of the ported model against the original — the greedy-token parity check you see reported in the PR (11/12 greedy cases at 100% first-16-token match versus a HuggingFace CPU bfloat16 reference).
Why this matters in practice — the key benefits we saw on this project:
- Non-standard architectures stop being blockers. Gemma 4 is full of details that would sink a naive port — heterogeneous sliding-window/global attention with 256/512 head dims, partial RoPE, logit soft-capping, a 128-expert MoE with a parallel dense branch. The skill handles the architecture re-expression systematically instead of leaving each quirk to trial and error.
- Correctness is built in, not bolted on. Every port comes with a CPU-reference parity report, so you know the Neuron graph is faithful before you invest in benchmarking and deployment.
- Day-one model availability. You don't wait for a model to appear in the official NxDI model hub — new architectures land as contrib ports (like the PR #172 port used here) within days of release.
- Reproducible, declarative output. The generated port follows one consistent pattern (env-var-driven compile, standard validation scripts), so everything in this guide transfers to the next model you port.
- No extra setup. The skills are included by default in the Deep Learning AMIs and containers — including the Neuron DLAMI this guide runs on.
Storage architecture: matching AWS storage services to the workload
Storage is not an afterthought for a 26B model — it's a first-class design decision. The workload imposes three distinct storage demands, and each maps to a different AWS storage service with different durability, throughput, latency, and cost characteristics. Picking the wrong service for a given demand either slows you down or loses your work.
The three demands:
- A hot working set that loads fast — ~50 GB of weights plus a set of NEFF artifacts per compiled context length. Model load and, especially, the compiler's scratch I/O are throughput- and latency-sensitive.
- Durable retention of expensive artifacts — the weights (a ~50 GB download) and every NEFF (each compile is tens of minutes, up to ~2 hours at 16K). Losing these to an instance stop is costly.
- Shared, reusable data — prompts, logs, benchmark inputs, and datasets that should outlive any single instance and be reachable across sessions.
The AWS storage services in play
Attribute | EC2 instance store (local NVMe) | Amazon EBS gp3 | Amazon FSx for Lustre |
|---|---|---|---|
Attachment | Physically attached to the host | Network-attached block volume | Managed parallel file system (network) |
Persistence | Ephemeral — survives reboot, lost on stop / hibernate / terminate | Persists independently of instance lifecycle | Persists (lifecycle depends on deployment type) |
Durability | No durability guarantee (single physical device) | Replicated within one AZ (~99.8–99.9%); snapshot to S3 for cross-AZ/region | Scratch: not replicated (speed-first). Persistent: replicated within AZ |
Throughput / latency | Highest throughput, lowest latency (no network hop) | Baseline 125 MB/s + 3,000 IOPS; provisionable up to 1,000 MB/s + 16,000 IOPS independent of capacity | Hundreds of MB/s per TiB, aggregates to GB/s; sub-millisecond latency |
Cost model | Included in instance price | Per-GB + independently provisioned IOPS/throughput | Per-TiB of provisioned capacity/throughput |
Best-fit role here | Hot working set + compiler scratch | Durable anchor for weights + NEFFs | Shared scratch / datasets / logs |
How we mapped services to demands
Demand | Service chosen | Mount | Why this service (not the others) |
|---|---|---|---|
Hot working set + compile scratch | Instance store NVMe (1 × 470 GB; ~438 GiB usable after XFS formatting) | /data | Local NVMe has no network hop, so it delivers the highest sequential throughput and lowest latency — exactly what a 50 GB load and a write-heavy compiler workdir need. Putting this on EBS would cap I/O at the volume's provisioned throughput and add network latency to every compiler scratch operation. |
Durable retention of weights + NEFFs | Amazon EBS gp3 | /mnt/ebs | EBS persists independently of the instance and is AZ-replicated, so a stop/terminate doesn't erase it. gp3 is the right EBS type because it decouples throughput/IOPS from capacity — we size the volume for the data footprint (weights + several NEFF sets) and, if a restore needs to be faster, provision throughput without over-buying capacity. Instance store can't serve this role (ephemeral); FSx would be over-engineered for a straight backup. |
Shared prompts / logs / datasets | Amazon FSx for Lustre (2.15) | /fsx | A parallel file system gives high aggregate throughput and sub-ms latency for shared artifacts, and can be linked to S3. It survives across instances so benchmark inputs and logs aren't trapped on ephemeral disk. |
The key insight: performance and durability are different tiers
The trap is treating "where the model lives" as one decision. Instance store is the fastest place to run from but offers no durability — it is wiped on stop, hibernate, or terminate (it only survives a reboot). EBS is durable and independent of the instance but is network-attached, so it's not where you want the compiler thrashing scratch files. So we deliberately split the two concerns:
- Run from the fast tier: weights and NEFFs live on instance-store NVMe (
/data) for fastest load and compile.
- Persist on the durable tier: after the first successful download and compile, we mirror weights + all NEFFs to the EBS
gp3volume (/mnt/ebs). This is the durable anchor.
For an even stronger durability posture, an EBS snapshot pushes the volume to Amazon S3, giving cross-AZ/region protection and a fast way to re-hydrate a new instance's EBS from a known-good baseline.
Security note: because this durable tier holds the model weights and compiled artifacts at rest, create the
gp3 volume with encryption enabled (snapshots of an encrypted volume are automatically encrypted too). Enforcing EBS encryption by default at the account level — or organization-wide via an SCP — removes the risk of an unencrypted volume slipping through.Resiliency in practice. We codified recovery into a single script,
_recover_ephemeral.sh . If an automated janitor (or a manual stop) wipes /data , one command:- Re-formats and mounts the fresh instance-store NVMe at
/data,
- Restores the weights and all compiled NEFFs from
/mnt/ebs(skipping the ~tens-of-minutes recompile),
- Re-mounts FSx.
# after an instance stop wiped /data:bash ~/gemma4-demo/_recover_ephemeral.sh# weights: /data/model_weights/gemma-4-26b-a4b-it ✅# NEFFs: /data/compiled_gemma4_tp4* ✅ (restored, no recompile)This is the difference between a ~2-minute recovery and a ~40-minute rebuild (or ~2 hours if a 16K NEFF is in the mix). On a Capacity-Block-backed instance, where a stop can be triggered outside your control, the durable EBS tier plus this recovery script is what keeps the environment reproducible — the fast tier gives you performance, the durable tier gives you resiliency, and the script bridges them.
Tip: to make a brand-new instance self-hydrate, restore from an EBS snapshot (weights + NEFFs baked in) or sync the artifacts from Amazon S3 on boot — either way you skip both the 50 GB download and the compile entirely, turning environment bring-up into a pull rather than a rebuild.
Prerequisites
- Account: Active AWS account with permissions to launch EC2 instances and manage related resources.
- Service quota: Running On-Demand Trn instances quota sufficient for a
trn2.3xlarge(12 vCPUs).
- Instance:
trn2.3xlargevia an EC2 Capacity Block reservation (on-demand Trainium2 commonly returnsInsufficientInstanceCapacity). Tag itauto-stop=noif your org runs an idle-instance janitor.
- Key pair to SSH into the instance.
- IAM instance role: attach an instance profile with scoped, least-privilege permissions — FSx describe/mount, EBS snapshot create/restore, and AWS Secrets Manager read for the HuggingFace token — rather than embedding long-lived credentials on the box.
- AMI: Deep Learning AMI Neuron PyTorch 2.9 (Ubuntu 24.04) — ships Neuron SDK 2.30 + NxDI 0.10.
- Storage: an Amazon EBS
gp3volume sized for the weights + NEFF footprint, as the durable tier (the instance already provides fast ephemeral NVMe for the working set; FSx for Lustre optional for shared data). Enable EBS encryption at volume creation — this volume holds the model weights at rest; better still, enforce EBS encryption by default account-wide (or via SCP across an organization). See the storage architecture section for the tiering rationale.
- HuggingFace account with accepted license for
google/gemma-4-26b-a4b-it.
Step 1: Environment setup
Launch your instance using the Capacity Block, SSH in, and confirm the Neuron devices:
neuron-lsOutput — one Trainium2 device, 4 logical NeuronCores, 96 GB HBM:
instance-type: trn2.3xlargelogical-neuroncore-config: 2+--------+--------+----------+--------+--------------+----------+------+| NEURON | NEURON | NEURON | NEURON | PCI | CPU | NUMA || DEVICE | CORES | CORE IDS | MEMORY | BDF | AFFINITY | NODE |+--------+--------+----------+--------+--------------+----------+------+| 0 | 4 | 0-3 | 96 GB | 0000:33:00.0 | 0-11 | 0 |+--------+--------+----------+--------+--------------+----------+------+Prepare the performance tier — format and mount the fast local NVMe at
/data :lsblk -o NAME,SIZE,MOUNTPOINT,FSTYPE # identify the large unmounted NVMe (e.g. nvme2n1)sudo mkfs.xfs -f /dev/nvme2n1sudo mkdir -p /data && sudo mount /dev/nvme2n1 /datasudo chown -R ubuntu:ubuntu /datadf -h /dataMount the durable 200 GB EBS backup tier (attach the volume at launch, then):
sudo mkdir -p /mnt/ebs && sudo mount /dev/nvme1n1 /mnt/ebs # gp3 200 GB, xfs, encrypteddf -H /mnt/ebsMake the mounts survive reboots. A plain
mount command is transient — it does not persist across an OS reboot or kernel update. Register the durable tiers in /etc/fstab , keyed by UUID (device names like /dev/nvme1n1 can change between boots):# EBS gp3 — persist by UUID:UUID=$(sudo blkid -s UUID -o value /dev/nvme1n1)echo "UUID=$UUID /mnt/ebs xfs defaults,nofail 0 2" | sudo tee -a /etc/fstab
# FSx for Lustre (if used):echo "fs-xxxx.fsx.us-east-1.amazonaws.com@tcp:/mountname /fsx lustre defaults,_netdev,nofail 0 0" | sudo tee -a /etc/fstabThe
nofail option ensures the instance still boots even if a network-attached volume is temporarily unavailable, and _netdev defers the FSx mount until networking is up — both per AWS EBS/FSx best practices. (The instance-store NVMe at /data is deliberately not in fstab: its contents don't survive a stop, so it's re-formatted and re-mounted by the recovery script instead.)Activate the Neuron virtual environment and confirm NxDI:
source /opt/aws_neuronx_venv_pytorch_2_9_nxd_inference/bin/activatepython3 -c "import torch, torch_neuronx; print(torch.__version__, torch_neuronx.__version__)"python3 -c "import neuronx_distributed_inference as n; print('NxDI', n.__version__)" # 0.10.0Clone NxDI and check out the Gemma 4 contrib port (PR #172):
git clone https://github.com/aws-neuron/neuronx-distributed-inference.gitcd neuronx-distributed-inferencegit fetch origin pull/172/head:pr-172-gemma4 && git checkout pr-172-gemma4ls contrib/models/gemma-4-26b-a4b-it/src/modeling_gemma4_neuron.py # the Neuron port
Step 2: Download the model from HuggingFace
Gemma is a gated model — accept the license on the model page, then create a token at huggingface.co/settings/tokens . Rather than pasting the token into shell history or files on the instance, store it in AWS Secrets Manager and let the instance role (from Prerequisites) fetch it at runtime. Download the ~50 GB of weights to the fast NVMe tier:
# token stored once in Secrets Manager; retrieved via the instance role — no plaintext on diskexport HF_TOKEN=$(aws secretsmanager get-secret-value \ --secret-id gemma4/hf-token --query SecretString --output text)mkdir -p /data/model_weightshuggingface-cli download google/gemma-4-26b-a4b-it \ --local-dir /data/model_weights/gemma-4-26b-a4b-it --token $HF_TOKENThen mirror it to the durable EBS tier so a future wipe doesn't cost you the download:
rsync -a /data/model_weights/ /mnt/ebs/model_weights/
Step 3: Compile the model (single-pass full MoE, TP=4)
Compilation converts the model into NEFF artifacts — a one-time step per shape that's then reused for every inference call. The port is env-var driven, so a compile is one declarative command:
cd ~/neuronx-distributed-inference/contrib/models/gemma-4-26b-a4b-itsource /opt/aws_neuronx_venv_pytorch_2_9_nxd_inference/bin/activate
export GEMMA4_MODEL_PATH=/data/model_weights/gemma-4-26b-a4b-it \ GEMMA4_TP_DEGREE=4 GEMMA4_MOE_TP_DEGREE=4 NEURON_RT_NUM_CORES=4
# Choose the context window (seq_len) and output dir for this build:GEMMA4_SEQ_LEN=2048 GEMMA4_BATCH_SIZE=1 \GEMMA4_COMPILED_PATH=/data/compiled_gemma4_tp4_seq2048 \PYTHONPATH=src python scripts/smoke_compile.py # -> "Smoke compile + load OK"A few things worth knowing:
- It's a single-pass, full-MoE compile — all 128 experts compile in one pass at TP=4. (
GEMMA4_DISABLE_MOE=1gives a fast dense-only smoke test if you just want to sanity-check the toolchain.)
-
attn_kernel_enabledmust be off for Gemma 4 — its non-standard attention head dimensions (256/512) aren't supported by the flash-attention kernel; the port falls back to standard attention.
- The NEFF is fixed to its (seq_len, batch) shape. Compile one directory per context length you want to serve — e.g.
/data/compiled_gemma4_tp4_seq2048,..._seq4096,..._seq8192.
When each build succeeds, back the NEFFs up to EBS alongside the weights:
rsync -a /data/compiled_gemma4_tp4_seq2048/ /mnt/ebs/compiled_gemma4_tp4_seq2048/
Step 4: Run inference and benchmark
With a compiled NEFF in place, load and generate. We benchmarked with a fixed 128-token input → 128-token output, greedy decoding, warmup + 3 timed iterations, at TP=4 / bfloat16.
cd ~/gemma4-demoGEMMA4_COMPILED_PATH=/data/compiled_gemma4_tp4_seq2048 GEMMA4_SEQ_LEN=2048 GEMMA4_BATCH_SIZE=1 \GEMMA4_INPUT_TOKENS=128 GEMMA4_OUTPUT_TOKENS=128 NEURON_RT_NUM_CORES=4 python benchmark.pyBenchmark — context sweep (batch = 1)
How latency scales as we compile larger context windows:
Metric | 256 | 2K | 4K | 8K |
|---|---|---|---|---|
Compiled seq_len | 256 | 2,048 | 4,096 | 8,192 |
TTFT (prefill) | ~341 ms | ~619 ms | ~1,022 ms | ~2,196 ms |
Decode throughput | ~119 tok/s | ~117 tok/s | ~113 tok/s | ~104 tok/s |
Aggregate throughput | ~90 tok/s | ~75 tok/s | ~60 tok/s | ~38 tok/s |
E2E latency (128→128) | ~1.40 s | ~1.71 s | ~2.14 s | ~3.41 s |
Two takeaways:
- Steady-state decode is nearly flat (~104–119 tok/s) — token generation is almost independent of the compiled window.
- TTFT grows with the compiled window (341 ms → 2.2 s) because the prefill graph is sized for the full context; for short generations this dominates end-to-end latency.
Benchmark — concurrency sweep (seq_len = 256)
How aggregate throughput scales when we batch concurrent requests on the same 4 cores:
Metric | batch 1 | batch 2 | batch 4 | batch 8 |
|---|---|---|---|---|
Aggregate throughput (incl. prefill) | ~90 tok/s | ~111 tok/s | ~167 tok/s | ~210 tok/s |
Aggregate decode throughput | ~117 tok/s | ~153 tok/s | ~244 tok/s | ~318 tok/s |
Per-sequence throughput | ~90 tok/s | ~56 tok/s | ~42 tok/s | ~26 tok/s |
TTFT (prefill of B×128) | ~341 ms | ~641 ms | ~984 ms | ~1,690 ms |
HBM status | ✅ | ✅ | ✅ | ✅ |
- Aggregate decode throughput scales ~2.7× (117 → 318 tok/s) from batch 1 → 8 — batching is the lever for total tokens/second.
- Per-sequence throughput falls (90 → 26 tok/s) as sequences share decode steps — the usual latency-for-throughput tradeoff. All batches fit HBM at this context.
How far can context go?
We also probed the ceiling at 16K: it compiles and runs (sliding-window attention keeps the KV cache small), but TTFT jumps to ~8.5 s and the uncached prefill-graph compile balloons to ~2h10m on this small host. 8K is the practical interactive ceiling on
trn2.3xlarge ; larger contexts belong on a trn2.48xlarge .
Conclusion
We ported Google's sparse-MoE Gemma 4 26B-A4B to AWS Trainium2, compiled it to NEFF at TP=4 on a single
trn2.3xlarge , and benchmarked it across context and concurrency — landing steady-state decode of ~104–119 tok/s and aggregate throughput up to ~318 tok/s at batch 8. Just as importantly, we put a tiered storage architecture behind it — matching each AWS storage service to its role (instance-store NVMe for the fast working set, Amazon EBS gp3 as the durable anchor, FSx for Lustre for shared data) — with a one-command recovery script, so the environment is both fast and reproducible even when the instance is stopped.In Part 2, we'll go beyond text and enable Gemma 4's multimodal (image-to-text) capability on the same instance.
Need guidance on AWS Trainium adoption? Contact your AWS account team to discuss your ML inference requirements and use cases. To learn more:
Disclaimer: This article showcases how you can port and run an open-source model like Gemma 4 26B-A4B on AWS Trainium-powered Amazon EC2 instances. We used the model available on HuggingFace and did not fine-tune or customize it for a production application. Benchmarks were measured on a single trn2.3xlarge and will vary with instance type, configuration, and workload. Any opinions in this article are those of the 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