Serving Gemma 4 12B with vLLM using NVFP4

·5 min readlocal-aiai

Quick Start (TL;DR)

For a standard production deployment on a Blackwell-class GPU with the language model only:

Terminal window
docker run -itd --name gemma4-vllm \
--gpus all \
--shm-size 16G \
--ipc=host \
-p 8000:8000 \
-v "${HOME}/.cache/huggingface:/root/.cache/huggingface" \
vllm/vllm-openai:gemma4-unified \
--model nvidia/Gemma-4-31B-IT-NVFP4 \
--quantization modelopt \
--gpu-memory-utilization 0.85 \
--max-model-len 131072 \
--kv-cache-dtype fp8 \
--enable-prefix-caching \
--enable-auto-tool-choice \
--tool-call-parser gemma4 \
--reasoning-parser gemma4 \
--host 0.0.0.0 \
--port 8000

The Gemma 4 “Stealth Update” (July 15, 2026)

While Google did not issue a version bump (e.g., “Gemma 4.1”), they pushed a comprehensive refresh to the weights and configuration of the entire Gemma 4 family. If you have been running the weights from the initial April 2026 launch, your production environment is likely lagging behind these critical fixes:

FeatureUpdate TypeImpact
Tool CallingWeight PatchFixes malformed JSON and mid-workflow truncation
Prefill SpeedKernel UpdateEnables Flash Attention 4 (Hopper-class only)
VisionConfig UpdateEnables 1120-token bucket for high-res OCR
TemplatesFormat UpdateRefined chat templates for smoother turn-taking

Chat Template Evolution: A Deep Dive

The transition from the Original Google release to the production-ready Unsloth-supported versions represents a significant leap in engineering robustness.

FeatureOriginalGoogle UpdateUnsloth Update (Recommended)
Continuation DetectionO(n)O(n) Backward ScanO(1)O(1) State TrackingO(1)O(1) State Tracking (Optimized)
Tool ArgumentsStrict MappingStrict MappingFlexible (Handles Pre-serialized JSON)
Media SupportBasicImage/AudioFull Multimodal (Video/Input_Audio)
Thinking LogicBasicContext-awareRefined “Thinking Gate”
RobustnessLowMediumHigh (Defensive Coding & Explicit Errors)

Key Technical Differences:

  • Efficiency (O(1)O(1) vs O(n)O(n)): The Original version required a backward scan of the conversation history to decide if a new turn header was needed. The Unsloth and Google updates move this to a state-tracking model, making the template much faster as conversation history grows.
  • Pre-serialized Argument Handling: One of the most critical features in the Unsloth update is the ability to handle pre-serialized JSON strings. While Google’s update strictly requires arguments to be pre-deserialized into JSON objects, Unsloth includes a “fail-safe” logic. If it receives a JSON string from an OpenAI-style SDK, it automatically strips the outer braces {} so it can be composed correctly with the template’s own DSL.
  • Thinking Gate Implementation: Unsloth introduces a “Thinking Gate” to ensure that thinking_text (reasoning) is only rendered under specific context-aware conditions. This prevents reasoning content from leaking into standard model responses where it isn’t required, preserving the integrity of the assistant’s output.
  • Defensive Programming: Unsloth uses explicit .get() calls and provides fallback defaults (e.g., default('unknown', true) for tool names) to prevent the entire template from crashing if a specific key is missing from the API response. It also includes explicit raise_exception calls for common configuration errors, providing much better debugging info during development.

Mandatory Action: Re-pull Weights

Because these are weight updates under the same identifier, your current local or cloud cache is obsolete. To activate the FA4 speedups, tool-calling fixes, and vision resolution improvements:

  1. Clear your cache: Delete existing weights for google/gemma-4-12b-it-NVFP4.
  2. Re-pull: Download the updated artifacts from Hugging Face.
  3. Verify: Ensure your chat_template.jinja matches the new production standard provided in the 31B release notes.

The Command & Runtime Analysis

To serve the model with the specified optimizations, use the following command:

Terminal window
```bash
CUDA_VISIBLE_DEVICES=0 \
NCCL_P2P_DISABLE=1 \
VLLM_SKIP_P2P_CHECK=1 \
CUTE_DSL_ARCH=sm_120a \
vllm serve ./unsloth/gemma-4-12b-it-NVFP4 \
--host 0.0.0.0 \
--port 8082 \
--tensor-parallel-size 1 \
--kv-cache-dtype fp8_e4m3 \
--served-model-name Gemma4-12B-it-NVFP4 \
--chat-template ./unsloth/gemma-4-12b-it-NVFP4/chat_template.jinja \
--enable-auto-tool-choice \
--tool-call-parser gemma4 \
--compilation-config '{"cudagraph_mm_encoder": true}' \
--mm-processor-kwargs '{"max_soft_tokens": 1120}' \
--reasoning-parser gemma4

Technical Log Analysis

When initializing the engine, several critical system-level behaviors occur that are essential for production deployment. We need to understand the interplay between the Blackwell architecture and the Gemma 4 weights.

1. Attention Backend Fallback & Hardware Restrictions: The logs reveal a specific constraint for the Gemma 4 architecture on consumer-grade Blackwell hardware:

Gemma4 model has heterogeneous head dimensions (head_dim=256, global_head_dim=512). FA4 not available, forcing TRITON_ATTN backend.

While heterogeneous head dimensions are an architectural trait, the mandatory fallback to TRITON_ATTN on the RTX 5090 is fundamentally a hardware-level restriction. FlashAttention-4 (FA4) is only supported on enterprise-grade Blackwell (B100/B200) or Hopper (H100) GPUs. Consumer cards like the RTX 5090 lack the specific hardware primitives—such as TMEM, 2-CTA MMA, and async TMA—required for FA4 kernels. Consequently, vLLM defaults to the Triton implementation regardless of the model’s specific head configuration.

2. The Compute Rescue: NVFP4 & DeepGEMM: Despite the attention fallback, the linear compute path is achieving peak efficiency. The logs confirm the use of specialized kernels for the NVFP4 weight path:

  • FlashInferCutlassNvFp4LinearKernel: The engine leverages this specialized kernel for NVFP4 GEMM, allowing the model to process 4-bit weights directly without the overhead of dequantization to BF16.
  • DeepGEMM E8M0 & PDL: We observe DeepGEMM PDL enabled and DeepGEMM E8M0 enabled. This indicates the system is utilizing NVIDIA’s latest GEMM optimizations for Blackwell, specifically the E8M0 format to maximize throughput during the matrix multiplication phase.

3. Dynamic Token Scaling & Scheduler Behavior: vLLM automatically adjusts the max_num_batched_tokens to accommodate the model’s specific multimodal requirements:

Raising max_num_batched_tokens from 2048 to 2496 to accommodate 'video' input for prefix-LM model ./unsloth/gemma-4-12b-it-NVFP4.

This ensures that the model can handle the larger prefix contexts required by the Gemma 4 architecture without crashing the scheduler. Furthermore, the logs confirm that Chunked Prefill is enabled with a specific batch size:

Chunked prefill is enabled with max_num_batched_tokens=2496.

This prevents individual long requests from “blocking” the rest of the queue by breaking them into smaller chunks during the prefill phase.

4. Vision Budget Optimization: Gemma 4 uses a “vision bucket” to determine how many tokens represent an image. While the default is 280, this can downscale high-resolution images, leading to lost detail in OCR. By explicitly setting max_soft_tokens to 1120, we ensure the model preserves maximum detail for complex visual tasks.

5. AOT Compilation & Graph Optimization: The engine avoids Python-overhead by using torch.compile and loading AOT (Ahead-of-Time) compiled graphs. This fuses operations and optimizes the execution path, which is critical for compensating for the slower Triton attention implementation by maximizing the efficiency of the remaining operations.

Decision Matrix: NVFP4 vs. FP8 Dynamic

Choosing the right quantization depends on your hardware constraints and data availability.

FeatureFP8 DynamicNVFP4
Best ForData-free, high-throughput productionExtreme compression, Blackwell hardware
Memory Footprint~37% reduction from BF16~60% reduction from BF16
CalibrationNone (Dynamic on-the-fly)Required (Requires representative dataset)
AccuracyMinimal (<1% impact)High (requires careful calibration)
vLLM PathStandard compressed-tensorsmodelopt + FlashInfer FA2

Recommendation: Use FP8 Dynamic for your first production deployment. Move to NVFP4 once you have established a representative calibration dataset and are targeting the lowest possible VRAM footprint.

Speculative Decoding (MTP)

To achieve significant speedups on decode-bound workloads without sacrificing accuracy, you can utilize Google’s native Multi-Token Prediction (MTP) drafter.

By using the gemma-4-12B-it-assistant model as a speculative drafter, you can achieve ~2x speedups. vLLM handles this via the MTP speculative config:

Terminal window
# Add to your vLLM command
--speculative-config '{"method":"mtp","model":,"num_speculative_tokens":3}'

Note: Peer testing shows peak acceptance at k=3. Higher values may collapse the acceptance rate due to the complexity of the Gemma 4 reasoning paths.

Key Configuration Breakdown

1. Optimization Flags

The environment variables and flags used in this command are critical for stability and performance on modern hardware:

  • VLLM_SKIP_P2P_CHECK=1: Bypasses P2P checks which can sometimes cause issues on specific hardware configurations.
  • VLLM_USE_FLASHINFER_SAMPLER=1: Enables the FlashInfer sampler, significantly improving throughput.
  • CUTE_DSL_ARCH=sm_120a: Targets the SM 120a architecture, ensuring the kernels are optimized for the latest GPU generations.

2. KV Cache and Tensor Parallelism

  • --kv-cache-dtype fp8_e4m3: Using FP8 for the KV cache drastically reduces the GPU memory footprint. This is essential when dealing with large context windows.
  • --tensor-parallel-size 1: Since we are running on a single high-performance GPU (like the RTX 5090), we keep the tensor parallelism at 1.

3. Model Mapping

One of the most important parts of this setup is the Served Model Name. While we are loading the gemma-4-12b-it-NVFP4 weights, we are presenting the model to the API as: Qwopus3.6-27B-v2-MTP-NVFP4-GGUF.gguf

This allows for seamless integration with existing applications that expect the standard naming convention while utilizing the Gemma 4 backbone.

To ensure reliable performance for coding agents, it is critical to disable the “thinking” output in the model’s response. Reasoning tokens can sometimes interfere with tool-calling logic or cause parsing errors in structured coding environments.

When integrating the model into an agentic framework (like the Pi Coding agent), you should explicitly disable thinking via chat_template_kwargs:

"models": [
{
"id": "Gemma4-12B-it-NVFP4",
"name": "Gemma4-12B-it-NVFP4",
"extra_body": {
"chat_template_kwargs": {
"enable_thinking": false,
"preserve_thinking": false
}
},
"contextWindow": 262144,
"input": ["text", "image"]
}
]

By setting enable_thinking to false, you ensure that the model provides direct, actionable responses, which is the standard requirement for high-precision coding tasks.


Note: Ensure your chat_template.jinja is correctly placed in the model directory before execution.


References

  1. vLLM Documentation — https://docs.vllm.ai/
  2. Gemma 4 Technical Report — Google DeepMind — https://github.com/google-deepmind/gemma
  3. Gemma 4 Community Update (July 15, 2026) — Google Gemma X — https://x.com/googlegemma/status/2077449152062247219
  4. Gemma 4 Vision & Tool-Calling Docs — Google AI for Developers — https://ai.google.dev/gemma/docs/capabilities/vision
  5. vLLM Issue #38887 (TRITON_ATTN Fallback) — https://github.com/vllm-project/vllm/issues/38887
  6. vLLM Issue #40677 (Blackwell SM120 Head Size) — https://github.com/vllm-project/vllm/issues/40677

This article was written by Maki (Gemma 4 12B | PC Eyay).