optimum-neuron / gemma3
AGENTS.md270 starsChanged 10 months agoApache-2.0View on GitHub
This directory contains the Neuron-optimized Gemma3 inference implementation. It follows HF Transformers architecture with Neuron-specific changes derived from NxDI. Gemma3 has several architectural differences from Llama that require special handling: This differs from the Llama two-norm pattern (pre-attention + pre-MLP only). `Gemma3NxDModelForCausalLM.convert_hf_to_neuron_s
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository32 other files it gives its agents.
- AGENTS.mdAGENTS.md
- optimum/neuron/cache/AGENTS.mdAGENTS.md
- optimum/neuron/models/inference/AGENTS.mdAGENTS.md
- optimum/neuron/models/inference/backend/modules/attention/AGENTS.mdAGENTS.md
- optimum/neuron/models/inference/granite/AGENTS.mdAGENTS.md
- optimum/neuron/models/inference/llama4/AGENTS.mdAGENTS.md
- optimum/neuron/models/inference/llama/AGENTS.mdAGENTS.md
- optimum/neuron/models/inference/mixtral/AGENTS.mdAGENTS.md
- optimum/neuron/models/inference/phi3/AGENTS.mdAGENTS.md
- optimum/neuron/models/inference/qwen2/AGENTS.mdAGENTS.md
- optimum/neuron/models/inference/qwen3/AGENTS.mdAGENTS.md
- optimum/neuron/models/inference/qwen3_moe/AGENTS.mdAGENTS.md
- optimum/neuron/models/inference/smollm3/AGENTS.mdAGENTS.md
- optimum/neuron/models/inference/smolvlm/AGENTS.mdAGENTS.md
- optimum/neuron/vllm/AGENTS.mdAGENTS.md
- tests/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- optimum/neuron/cache/CLAUDE.mdCLAUDE.md
- optimum/neuron/models/inference/CLAUDE.mdCLAUDE.md
- optimum/neuron/models/inference/gemma3/CLAUDE.mdCLAUDE.md
- optimum/neuron/models/inference/granite/CLAUDE.mdCLAUDE.md
- optimum/neuron/models/inference/llama4/CLAUDE.mdCLAUDE.md
- optimum/neuron/models/inference/llama/CLAUDE.mdCLAUDE.md
- optimum/neuron/models/inference/mixtral/CLAUDE.mdCLAUDE.md
- optimum/neuron/models/inference/phi3/CLAUDE.mdCLAUDE.md
- optimum/neuron/models/inference/qwen2/CLAUDE.mdCLAUDE.md
- optimum/neuron/models/inference/qwen3/CLAUDE.mdCLAUDE.md
- optimum/neuron/models/inference/qwen3_moe/CLAUDE.mdCLAUDE.md
- optimum/neuron/models/inference/smollm3/CLAUDE.mdCLAUDE.md
- optimum/neuron/models/inference/smolvlm/CLAUDE.mdCLAUDE.md
- optimum/neuron/vllm/CLAUDE.mdCLAUDE.md
- .github/copilot-instructions.mdCopilot instructions
The file
We split this AGENTS.md into the rules it gives an agent
3 rules. About 0 are common, 0 are distinctive, and 3 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 30
All layer norms in the model use this class: input_layernorm, post_attention_layernorm, pre_feedforward_layernorm, …
- Very specific: line 31
Do not replace with a standard RMSNorm — the weight convention would break numerical parity.
- Very specific: line 51
If head_dim is greater than 128 (for example, Gemma3-270m has head_dim=256, while models like Gemma3-27B use head_dim=128), flash attention …
≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Gemma3 Inference Model Guide
This directory contains the Neuron-optimized Gemma3 inference implementation. It follows HF Transformers architecture with Neuron-specific changes derived from NxDI.
HF reference
- Transformers Gemma3 modeling: https://github.com/huggingface/transformers/tree/main/src/transformers/models/gemma3
Gemma3-specific architecture
Gemma3 has several architectural differences from Llama that require special handling:
Mixed sliding window / full attention
- Each decoder layer has an
attention_typeof either"sliding_attention"or"full_attention"(fromconfig.layer_types). - Two separate attention masks are computed per forward pass and routed per layer.
- Sliding attention layers use a banded causal mask of width
config.sliding_window. - Full attention layers use the standard full causal lower-triangular mask.
Dual RoPE bases
- Sliding attention layers use
config.rope_local_base_freq(e.g. 10000). - Full attention layers use
config.rope_theta(e.g. 1000000). - RoPE cos/sin caches are maintained separately per attention type to avoid reuse of incorrect embeddings.
Q-K normalization
- Query and key projections are normalized after linear projection using
NeuronGemma3RMSNorm. - HF names these
q_norm/k_norm; they are renamed toq_layernorm/k_layernormin the state dict conversion to matchNeuronAttentionBaseexpectations.
Custom RMSNorm: NeuronGemma3RMSNorm
- Applies
(1.0 + weight)scaling instead of plainweightscaling. - Weights are initialized to zeros (so the effective scale starts at 1.0).
- All layer norms in the model use this class:
input_layernorm,post_attention_layernorm,pre_feedforward_layernorm,post_feedforward_layernorm,q_layernorm,k_layernorm, and the finalnorm. - Do not replace with a standard
RMSNorm— the weight convention would break numerical parity.
Four normalization layers per decoder block
input_layernorm→ applied before attentionpost_attention_layernorm→ applied to attention output before residual addpre_feedforward_layernorm→ applied before MLPpost_feedforward_layernorm→ applied to MLP output before residual add
This differs from the Llama two-norm pattern (pre-attention + pre-MLP only).
Scaled word embeddings: NeuronGemma3TextScaledWordEmbedding
- Wraps
ParallelEmbeddingand multiplies outputs bysqrt(hidden_size). - The nested structure requires a state dict remap:
embed_tokens.weight→embed_tokens.embedding.weight. - Tied weights (
lm_head.weight) are copied fromembed_tokens.embedding.weight.
GELU activation in MLP
- Uses
nn.GELU(approximate="tanh")instead of SiLU (as in Llama/Qwen3).
head_dim > 128 bypass
- The NKI flash attention kernel supports
par_dimup to 128 only. - If
head_dimis greater than 128 (for example, Gemma3-270m hashead_dim=256, while models like Gemma3-27B usehead_dim=128), flash attention is automatically disabled. - This check lives in
NeuronAttentionBase.get_flash_attention_strategy()and applies to all models; no Gemma3-specific override is needed.
What differs vs HF
- Parallel layers: TP-aware linear/embedding layers replace HF modules.
- Attention base:
NeuronAttentionBasefor TP-aware heads and static shapes. - KV cache/static shapes: Uses
KVCacheManagerand fixed shapes. - Mixed mask routing:
NxDGemma3Model.forward()computes two masks and dispatches per layer (not in HF). - Dual RoPE cache: Separate
(cos, sin)caches per attention type accumulated across layers. - Custom RMSNorm:
NeuronGemma3RMSNormreplaces HFGemma3RMSNormusing the hardware-optimizedAwsNeuronRmsNormop. - Scaled embedding wrapper:
NeuronGemma3TextScaledWordEmbeddingwrapsParallelEmbedding.
State dict conversion
Gemma3NxDModelForCausalLM.convert_hf_to_neuron_state_dict() performs:
| From (HF key) | To (Neuron key) |
embed_tokens.weight | embed_tokens.embedding.weight |
layers.*.self_attn.q_norm.weight | layers.*.self_attn.q_layernorm.weight |
layers.*.self_attn.k_norm.weight | layers.*.self_attn.k_layernorm.weight |
| All other norm/MLP/proj keys | unchanged |
What was removed from NxDI
Reference: NxDI Gemma3 implementation
Removed NKI Kernel Implementations
- MLP TKG kernel - Advanced small batch optimization
- Quantized MLP kernels - INT8 quantization with fused operations
- NKI-based MLP - Hand-tuned kernel implementations
Why removed: Requires neuronxcc.nki private APIs. Optimum relies on compiler auto-optimization.
Removed Serving/Speculative Features
- EAGLE draft models - Speculative decoding support
- Medusa heads - Multi-head speculative sampling
- Flash Decoding - Multi-query decode parallelism
- LoRA serving - Dynamic adapter switching
- Context parallelism - MLP splitting for long contexts
Why removed: Production serving features handled by vLLM integration.
Removed Configuration/Infrastructure
- NxDI config classes - Replaced by
NxDNeuronConfig - Module registration system - Plugin architecture
- Preshard hooks - Weight sharding orchestration
Why removed: Optimum uses HF Transformers config with neuron_config.json.
What Optimum Neuron Keeps
- Parallel layers with TP-aware sharding
NeuronAttentionBasewith GQA and flash attention- Mixed sliding window / full attention per layer
- Dual RoPE base routing
- Q-K normalization
- State dict conversion (QKV fusion, embedding remap, norm rename)
- Decoder layer composition
Optimum Neuron prioritizes stability and HF ecosystem compatibility.
VLM (image-text-to-text) support
Gemma3 supports vision-language inference via Gemma3NxDModelForImageTextToText, registered as ("gemma3", "image-text-to-text").
Architecture
Two compiled bundles:
model_vision.pt:NeuronGemma3VisionEncoder— SigLIP vision transformer + multi-modal projectormodel_text.pt:NxDGemma3VLMDecoderModel— Gemma3 text decoder with image embedding injection
Class hierarchy:
Gemma3NxDModelForImageTextToText→NxDModelForImageTextToText(base VLM class)NxDGemma3VLMDecoderModel→NxDGemma3Model(inherits mixed sliding/full attention)NeuronGemma3VisionEncoder→ containsNeuronGemma3SigLIPVisionTransformer+NeuronGemma3MultiModalProjector
TP-sharded vision encoder
The SigLIP vision encoder (27 layers at 896×896) exceeds Neuron compiler instruction limits when batch_size * max_num_images > 2 without tensor parallelism. The vision encoder uses ColumnParallelLinear/RowParallelLinear in attention Q/K/V/out and MLP fc1/fc2 to distribute across TP ranks.
Key classes:
NeuronGemma3SigLIPAttention— TP-sharded multi-head attentionNeuronGemma3SigLIPMLP— TP-sharded MLPNeuronGemma3SigLIPEncoderLayer/NeuronGemma3SigLIPEncoder— layer stack
Multi-modal projector
NeuronGemma3MultiModalProjector downsamples vision features using AvgPool2d then projects via RMSNorm + linear from vision hidden dim to text hidden dim. Attribute names (mm_input_projection_weight, mm_soft_emb_norm) match HF for direct state dict loading.
Position embeddings
Gemma3 uses standard sequential position IDs [0, 1, ..., num_patches - 1] (via NeuronGemma3SigLIPVisionEmbeddings), NOT Idefics3-style fractional-coordinate bucketing used by SmolVLM.
Image injection
During context encoding, NxDGemma3VLMDecoderModel.forward() computes text embeddings, then replaces embeddings at image_token_id positions with vision features using torch.where.
VLM state dict conversion
Gemma3NxDModelForImageTextToText:
_STATE_DICT_MODEL_PREFIX = "language_model.model."— strips HF nesting for text weights_get_vision_encoder_state_dict(): remapsvision_tower.vision_model.*→vision_model.*, keepsmulti_modal_projector.*as-isconvert_hf_to_neuron_state_dict(): preserveslanguage_model.lm_head.weight→lm_head.weight, removes remaining vision/projector/language_model keys, delegates to CausalLM converter
Constraints
- Chunked prefill not supported (
_supports_chunked_prefill = False): the mixed sliding/full attention masks are not compatible with chunked prefill.prefill_chunk_sizeis forced to 0. - No image tiling: unlike SmolVLM/Idefics3, Gemma3 processes each image at full resolution. Each image produces exactly
mm_tokens_per_imagefeatures. max_num_images: set to 5 in_get_neuron_config(). This determines the vision batch size (batch_size * max_num_images).
Key files
- optimum/neuron/models/inference/gemma3/modeling_gemma3.py
- optimum/neuron/models/inference/backend/modules/attention/attention_base.py
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

