MedGemma 2 is Google's family of open-weight, multimodal, and tool-enabled foundation models for health AI from the Health AI Developer Foundations (HAI-DEF) program, built on the Gemma 4 architecture. With LiteRT-LM, you can deploy MedGemma 2 E4B directly on client devices across mobile, desktop, and web within ~4-5 GB of active RAM—helping developers build and validate offline health AI workflows, such as local guideline retrieval tools and speech-to-text applications, on 8 GB+ dedicated GPUs or shared-memory mobile and desktop devices with 12 GB+ of total RAM (leaving headroom for the OS and host app), without relying on cloud connectivity.
Key Capabilities
- Multimodal Health Understanding: Process health and medical text,
medical imagery (radiology, dermatology, pathology, and ophthalmology), and
audio inside a single
.litertlmbundle. - Local Guideline Grounding (RAG): Ground responses in local reference PDFs and institutional guidelines at inference time (on-device RAG paired with EmbeddingGemma 2) with inline source citations to support verification—so adopting updated guidelines may only require re-indexing before validation, without changing app logic or re-running fine-tuning.
- Native Tool Calling: Execute local single-turn function calls for structured extraction and developer-defined workflows.
- Hardware-Accelerated Edge Footprint: Mixed-precision INT4/INT8 Post-Training Quantization (PTQ) compresses active memory from ~16 GB (BF16) to ~4-5 GB across CPU, GPU, and Google Tensor TPU (Pixel 10 and Pixel 11).
- Two Flexible Deployment Paths: Prototype with pre-converted
.litertlmbase checkpoints, or fine-tune and validate on your own domain-specific health datasets (SafeTensors) and export a custom quantized.litertlmartifact.
Learn more about MedGemma 2 in the
Google Research MedGemma 2 announcement,
and explore the
HAI-DEF MedGemma documentation.
Visit
LiteRT Community on Hugging Face
and the
HAI-DEF Hugging Face Collection
for .litertlm models optimized for on-device execution.
Explore modular offline starter recipes in the HAI-DEF Cookbook.
Model Specifications & Runtime Configuration
The pre-converted MedGemma 2 E4B .litertlm bundle packages the quantized
Gemma 4 E4B language backbone, vision and audio encoders, tokenizer, and Jinja
chat/tool-calling template into a single portable artifact. For detailed
on-device performance benchmarks (prefill/decode throughput, time to first
token, and memory footprint across mobile, desktop, and web backends), see the
MedGemma 2 E4B LiteRT-LM model card.
| Specification | MedGemma 2 E4B (.litertlm) |
|---|---|
| Base Architecture | Gemma 4 E4B |
| Parameters | 4.5B effective non-embedding (8.0B total with per-layer embeddings) |
| Supported Modalities | Text, Images (280, 560, and up to 1,120 vision soft-token signatures), Audio (16 kHz mono PCM) |
| Quantization Scheme | Mixed-precision INT4/INT8 PTQ |
| Download Size | 4.69 GB |
| Active RAM Footprint | ~4-5 GB total active RAM (recommended: 8 GB+ dedicated VRAM on discrete GPUs, or 12 GB+ total device RAM for full apps on shared-memory phones and laptops to leave OS and app headroom; standalone native/CLI binaries can run in tighter RAM; host CPU memory is lower when offloaded to GPU or TPU) |
| Context Length | 8,192 tokens recommended (configurable up to 32,768 on LiteRT-LM; 128K architectural max) |
| Supported Outputs | Streaming text, bounded thinking traces, inline source citations, native tool calls |
| Hardware Backends | CPU and GPU (Android, iOS, macOS, Windows, Linux, WebGPU); Google Tensor TPU (Pixel 10 & Pixel 11) |
| Hugging Face Repository | litert-community/medgemma-2-e4b-it-litert-lm |
Context Window & Thinking Mode Guidance
- 8K Context & Bounded Thinking: Configure an
8,192-token context window (max_num_tokens=8192) to accommodate retrieved reference guideline passages alongside bounded reasoning traces before generating the final answer or tool call. UseThinkingConfig(or--thinking/--thinking-budgetin the CLI) to control reasoning token budgets per workload. - Memory Optimization for 2D Medical Imaging VQA: Single-turn,
non-thinking 2D medical image question-answering tasks (such as dermatology
or chest X-ray classification and captioning) fit comfortably within a
4,096-token context window (max_num_tokens=4096,enable_thinking=False), helping to lower peak RAM on memory-constrained devices. Allocating higher vision soft-token budgets (560 or 1,120) will increase peak accelerator memory usage. - Audio Input Formatting: Audio inputs should be formatted as 16 kHz mono
16-bit PCM WAV clips (benchmarked with 30-second clips). For the
pre-converted PTQ bundle, set the audio backend to CPU (
Backend.CPU()/.cpu()/"cpu"). - Google Tensor TPU Acceleration (Pixel 10 & Pixel 11): Dedicated TPU
execution offloads multimodal prefill and decode from CPU and GPU with a
smaller host CPU memory footprint (~181 MB text on Pixel 11 Pro XL; see the
model card for full metrics). Pixel TPU uses a dedicated compiled
.litertlmbundle (up to 8,192 context; 280, 560, and 1,120 vision signatures) and supports non-greedy sampling usingenable_npu_non_greedy_sampling.
Cross-Platform Code Examples With MedGemma 2
Use the following SDK examples to initialize MedGemma 2 E4B, run multimodal
prompts (text, images, and audio), and invoke local tools across platforms.
Requires LiteRT-LM >= 0.20.1 (Python >= 3.11 recommended; Python 3.10 is
deprecated in the 0.20.x series and will no longer be supported in v0.21.0).
Python
import litert_lm
def example_tool(query: str) -> dict[str, str]:
"""[Describe what your local tool does.]
Args:
query: [Describe the input parameter.]
"""
# Replace with your own local lookup, calculation, or integration logic.
return {"result": "[tool output]"}
# Initialize the Engine (audio encoder runs on CPU for the PTQ bundle).
with litert_lm.Engine(
"medgemma-2-e4b-it.litertlm",
backend=litert_lm.Backend.GPU(),
vision_backend=litert_lm.Backend.GPU(),
audio_backend=litert_lm.Backend.CPU(),
max_num_tokens=8192,
) as engine:
# 1. Text + Tool Calling (thinking mode must be enabled for tool calling)
with engine.create_conversation(
tools=[example_tool],
thinking_config=litert_lm.ThinkingConfig(
enable_thinking=True,
thinking_token_budget=4096,
),
) as conversation:
response = conversation.send_message("[add your prompt here]")
print(response["content"][0]["text"])
# 2. Vision (image + text, streaming)
with engine.create_conversation() as conversation:
stream = conversation.send_message_async(
litert_lm.Contents.of(
litert_lm.Content.ImageFile("[example_image.png]"),
"[add your vision prompt here]",
)
)
for chunk in stream:
for item in chunk.get("content", []):
if item.get("type") == "text":
print(item["text"], end="", flush=True)
print()
# 3. Audio (16 kHz mono WAV audio + text, streaming)
with engine.create_conversation() as conversation:
stream = conversation.send_message_async(
litert_lm.Contents.of(
litert_lm.Content.AudioFile("[example_audio_clip.wav]"),
"[add your audio prompt here]",
)
)
for chunk in stream:
for item in chunk.get("content", []):
if item.get("type") == "text":
print(item["text"], end="", flush=True)
print()
Kotlin
import android.content.Context
import com.google.ai.edge.litertlm.Backend
import com.google.ai.edge.litertlm.Content
import com.google.ai.edge.litertlm.Contents
import com.google.ai.edge.litertlm.ConversationConfig
import com.google.ai.edge.litertlm.Engine
import com.google.ai.edge.litertlm.EngineConfig
import com.google.ai.edge.litertlm.ThinkingConfig
import com.google.ai.edge.litertlm.Tool
import com.google.ai.edge.litertlm.ToolParam
import com.google.ai.edge.litertlm.ToolSet
import com.google.ai.edge.litertlm.tool
class ExampleToolSet : ToolSet {
@Tool(description = "[Describe what your local tool does.]")
fun exampleTool(
@ToolParam(description = "[Describe the input parameter.]") query: String,
): Map<String, String> {
return mapOf("result" to "[tool output]")
}
}
suspend fun runMedGemma2(
context: Context,
imageBytes: ByteArray,
audioBytes: ByteArray,
) {
// Configure EngineConfig (on Pixel 10/11 with the TPU bundle, use
// Backend.NPU(nativeLibraryDir = context.applicationInfo.nativeLibraryDir)).
val engineConfig = EngineConfig(
modelPath = "${context.filesDir.path}/medgemma-2-e4b-it.litertlm",
backend = Backend.GPU(),
visionBackend = Backend.GPU(),
audioBackend = Backend.CPU(),
maxNumTokens = 8192,
cacheDir = context.cacheDir.path,
)
Engine(engineConfig).use { engine ->
engine.initialize()
// 1. Text + Tool Calling (thinking mode must be enabled for tool calling)
val toolConfig = ConversationConfig(
systemInstruction = Contents.of("[add your system instructions here]"),
tools = listOf(tool(ExampleToolSet())),
thinkingConfig = ThinkingConfig(
enableThinking = true,
thinkingTokenBudget = 4096,
),
)
engine.createConversation(toolConfig).use { conversation ->
val response = conversation.sendMessage("[add your prompt here]")
println(response)
}
// 2. Vision (image + text, streaming)
engine.createConversation().use { conversation ->
val visionMessage = Contents.of(
Content.ImageBytes(imageBytes),
Content.Text("[add your vision prompt here]"),
)
conversation.sendMessageAsync(visionMessage).collect { chunk ->
print(chunk)
}
}
// 3. Audio (16 kHz mono WAV bytes + text, streaming)
engine.createConversation().use { conversation ->
val audioMessage = Contents.of(
Content.AudioBytes(audioBytes),
Content.Text("[add your audio prompt here]"),
)
conversation.sendMessageAsync(audioMessage).collect { chunk ->
print(chunk)
}
}
}
}
Swift
import Foundation
import LiteRTLM
struct ExampleTool: Tool {
static let name = "example_tool"
static let description = "[Describe what your local tool does.]"
@ToolParam(description = "[Describe the input parameter.]")
var query: String
func run() async throws -> Any {
return ["result": "[tool output]"]
}
}
func runMedGemma2() async throws {
// Initialize the Engine (Metal GPU for text/vision, CPU for audio).
let engineConfig = try EngineConfig(
modelPath: "medgemma-2-e4b-it.litertlm",
backend: .gpu,
visionBackend: .gpu,
audioBackend: .cpu(),
maxNumTokens: 8192,
cacheDir: NSTemporaryDirectory()
)
let engine = Engine(engineConfig: engineConfig)
try await engine.initialize()
// 1. Text + Tool Calling (thinking mode must be enabled for tool calling)
let samplerConfig = try SamplerConfig(topK: 64, topP: 0.95, temperature: 1.0)
let toolConfig = ConversationConfig(
systemMessage: Message("[add your system instructions here]"),
tools: [ExampleTool()],
samplerConfig: samplerConfig,
thinkingConfig: ThinkingConfig(
enableThinking: true,
thinkingTokenBudget: 4096
)
)
let toolConversation = try await engine.createConversation(with: toolConfig)
let textResponse = try await toolConversation.sendMessage(
Message("[add your prompt here]")
)
print(textResponse.toString)
// 2. Vision (image + text, streaming)
let visionConversation = try await engine.createConversation()
let visionMessage = Message(contents: [
Content.imageFile("[example_image.png]"),
Content.text("[add your vision prompt here]"),
])
for try await chunk in visionConversation.sendMessageStream(visionMessage) {
print(chunk.toString, terminator: "")
}
print()
// 3. Audio (16 kHz mono WAV file + text, streaming)
let audioConversation = try await engine.createConversation()
let audioMessage = Message(contents: [
Content.audioFile("[example_audio_clip.wav]"),
Content.text("[add your audio prompt here]"),
])
for try await chunk in audioConversation.sendMessageStream(audioMessage) {
print(chunk.toString, terminator: "")
}
print()
}
JavaScript
import { Backend, Engine } from '@litert-lm/core';
// Early Preview: browser WebGPU support for MedGemma 2 E4B.
// Obtain userAccessToken using Sign in with Hugging Face; never hardcode tokens.
async function runMedGemma2Web(
userAccessToken: string,
imageBlob: Blob,
audioBlob: Blob,
) {
const engine = await Engine.create({
model: {
url: 'hf://litert-community/medgemma-2-e4b-it-litert-lm',
accessToken: userAccessToken,
},
visionBackend: Backend.GPU,
audioBackend: Backend.CPU,
mainExecutorSettings: {
maxNumTokens: 8192,
},
});
// 1. Text + Tool Calling (thinking mode must be enabled for tool calling;
// dedicated thinking token budgets are available in Python, Kotlin, Swift, and CLI)
const toolConversation = await engine.createConversation({
preface: {
extra_context: {
enable_thinking: true,
},
tools: [
{
name: 'example_tool',
description: '[Describe what your local tool does.]',
parameters: {
type: 'object',
properties: {
query: { type: 'string', description: '[Describe the input parameter.]' },
},
required: ['query'],
},
},
],
},
});
const textResponse = await toolConversation.sendMessage('[add your prompt here]');
console.log(textResponse.tool_calls ?? textResponse.content);
// 2. Vision (image + text, streaming)
const visionConversation = await engine.createConversation();
const visionStream = visionConversation.sendMessageStreaming({
role: 'user',
content: [
{ type: 'image', data: imageBlob },
{ type: 'text', text: '[add your vision prompt here]' },
],
});
for await (const chunk of visionStream) {
for (const item of chunk.content) {
if (item.type === 'text') {
console.log(item.text);
}
}
}
// 3. Audio (16 kHz mono WAV Blob + text, streaming)
const audioConversation = await engine.createConversation();
const audioStream = audioConversation.sendMessageStreaming({
role: 'user',
content: [
{ type: 'audio', data: audioBlob },
{ type: 'text', text: '[add your audio prompt here]' },
],
});
for await (const chunk of audioStream) {
for (const item of chunk.content) {
if (item.type === 'text') {
console.log(item.text);
}
}
}
await engine.delete();
}
To test client-side browser WebGPU vision interactively, try the LiteRT-LM Web Chat Demo or the CLI & Web Playground in the MedGemma notebooks repository. For native C++ and cross-platform Flutter integrations, see the C++ Guide and Flutter Guide.
CLI
You can prototype with MedGemma 2 E4B from the terminal, inspect and
benchmark bundles (litert-lm describe, litert-lm benchmark), or expose a
local OpenAI-compatible HTTP endpoint in under a minute using the
LiteRT-LM CLI.
Interactive Multimodal Inference (litert-lm run)
Linux/macOS
# Install or upgrade the LiteRT-LM CLI (v0.20.1+)
uv tool install litert-lm
# Or with pip: pip install --upgrade litert-lm
# Authenticate with Hugging Face after accepting the HAI-DEF Terms of Use
# and Prohibited Use Policy
export HF_TOKEN="[hf_your_access_token]"
# 1. Text + Tool Calling (enable thinking mode and pass a Python tools preset)
litert-lm run \
--from-huggingface-repo=litert-community/medgemma-2-e4b-it-litert-lm \
medgemma-2-e4b-it.litertlm \
--backend=gpu \
--max-num-tokens=8192 \
--thinking \
--thinking-budget=4096 \
--preset="[example_tools_preset.py]" \
--prompt="[add your prompt here]"
# 2. Vision (image + text)
litert-lm run \
--from-huggingface-repo=litert-community/medgemma-2-e4b-it-litert-lm \
medgemma-2-e4b-it.litertlm \
--backend=gpu \
--vision-backend=gpu \
--max-num-tokens=8192 \
--attachment="[example_image.png]" \
--prompt="[add your vision prompt here]"
# 3. Audio (16 kHz mono WAV audio + text)
litert-lm run \
--from-huggingface-repo=litert-community/medgemma-2-e4b-it-litert-lm \
medgemma-2-e4b-it.litertlm \
--backend=gpu \
--audio-backend=cpu \
--max-num-tokens=8192 \
--attachment="[example_audio_clip.wav]" \
--prompt="[add your audio prompt here]"
Windows
# Install or upgrade the LiteRT-LM CLI (v0.20.1+)
uv tool install litert-lm
# Or with pip: pip install --upgrade litert-lm
# Authenticate with Hugging Face after accepting the HAI-DEF Terms of Use
# and Prohibited Use Policy
$env:HF_TOKEN = "[hf_your_access_token]"
# 1. Text + Tool Calling (enable thinking mode and pass a Python tools preset)
litert-lm run `
--from-huggingface-repo=litert-community/medgemma-2-e4b-it-litert-lm `
medgemma-2-e4b-it.litertlm `
--backend=gpu `
--max-num-tokens=8192 `
--thinking `
--thinking-budget=4096 `
--preset="[example_tools_preset.py]" `
--prompt="[add your prompt here]"
# 2. Vision (image + text)
litert-lm run `
--from-huggingface-repo=litert-community/medgemma-2-e4b-it-litert-lm `
medgemma-2-e4b-it.litertlm `
--backend=gpu `
--vision-backend=gpu `
--max-num-tokens=8192 `
--attachment="[example_image.png]" `
--prompt="[add your vision prompt here]"
# 3. Audio (16 kHz mono WAV audio + text)
litert-lm run `
--from-huggingface-repo=litert-community/medgemma-2-e4b-it-litert-lm `
medgemma-2-e4b-it.litertlm `
--backend=gpu `
--audio-backend=cpu `
--max-num-tokens=8192 `
--attachment="[example_audio_clip.wav]" `
--prompt="[add your audio prompt here]"
OpenAI-Compatible Local Server (litert-lm serve)
Run litert-lm serve to connect local agent frameworks, evaluation harnesses,
or desktop UIs to MedGemma 2 E4B over POST /v1/chat/completions.
First, import the model into your local registry and optionally configure
per-model defaults in ~/.litert-lm/config.json
(%USERPROFILE%\.litert-lm\config.json on Windows):
{
"models": {
"medgemma-2-e4b": {
"backend": "gpu",
"vision_backend": "gpu",
"audio_backend": "cpu",
"max_num_tokens": 8192,
"thinking": true,
"thinking_budget": 4096
}
}
}
Then start the server and send a chat completion request:
Linux/macOS
# Import the model under the "medgemma-2-e4b" alias
litert-lm import \
--from-huggingface-repo=litert-community/medgemma-2-e4b-it-litert-lm \
medgemma-2-e4b-it.litertlm \
medgemma-2-e4b
# Start the local OpenAI-compatible server (default port 9379)
litert-lm serve
# Send a chat completion request in another terminal
curl http://localhost:9379/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "medgemma-2-e4b",
"messages": [
{"role": "user", "content": "[add your prompt here]"}
]
}'
Windows
# Import the model under the "medgemma-2-e4b" alias
litert-lm import `
--from-huggingface-repo=litert-community/medgemma-2-e4b-it-litert-lm `
medgemma-2-e4b-it.litertlm `
medgemma-2-e4b
# Start the local OpenAI-compatible server (default port 9379)
litert-lm serve
# Send a chat completion request in another terminal
Invoke-RestMethod -Uri "http://localhost:9379/v1/chat/completions" `
-Method Post `
-ContentType "application/json" `
-Body '{"model": "medgemma-2-e4b", "messages": [{"role": "user", "content": "[add your prompt here]"}]}'
Fine-Tune and Convert Custom Models (SafeTensors to .litertlm)
Because MedGemma 2 is a
foundation model intended to be adapted and validated with local data, you can
fine-tune, quantize, and re-package your adapted checkpoint into a portable
.litertlm bundle.
Alongside the pre-converted PTQ checkpoint, explore three open, Apache 2.0-licensed End-to-End Fine-Tuning, PTQ, and LiteRT-LM Deployment Colab Notebooks in the MedGemma GitHub Repo—covering multimodal supervised fine-tuning, reinforcement learning for concise on-device reasoning, and local CLI, server, and WebGPU deployment:
- Adapt to Custom Multimodal Data (SFT ->
.litertlm): Fine-tune MedGemma 2 E4B on your own image-and-text health data (shown on SCIN dermatology), export a quantized.litertlmbundle, and verify local inference in one Colab workflow. - Compress Reasoning for Edge Budgets (GRPO ->
.litertlm): Help preserve reasoning quality, yet keep outputs concise enough for tight on-device latency and memory budgets, then package a compact.litertlmbundle with litert-torch and litert-quantizer. - Test & Serve Across CLI, Local API & WebGPU: Profile, benchmark, and
compare base versus fine-tuned multimodal
.litertlmmodels (on SCIN dermatology) across CLI, Python, a local OpenAI-compatible server, and 100% client-side browser WebGPU in the LiteRT-LM Web Chat Demo.
Disclaimer
HAI-DEF models, including MedGemma, are intended to be used as a starting point that enables efficient development of downstream healthcare applications involving medical text, images, audio, video, and tool-calling workflows. HAI-DEF models are not intended to be used without appropriate validation, adaptation and/or making meaningful modification by developers for their specific use case. The outputs generated by these models are not intended to directly inform clinical diagnosis, patient management decisions, treatment recommendations, or any other direct clinical practice applications, including mental and behavioral health applications. Performance benchmarks reported here highlight baseline capabilities and are not intended to imply that MedGemma is safe to use in any given medical application. Inaccurate model outputs beyond those shown here are possible. All model outputs should be considered preliminary and require independent verification, clinical correlation, and further investigation through established research and development methodologies. Please refer to terms of use and prohibited use policy for more details.