In this article I want to follow MedGemma 2 from a small image into the code that reads it. We will give it two fictional vital-sign cards, change the numbers, and see whether the answer changes with them. Then we will look inside the vision encoder, the language decoder and the generated C that connects the two.

I am interested in this from the runtime side. Our C-Kernel-Engine already had Gemma 4 circuits. MedGemma gives us a useful question: when a new checkpoint reuses an architecture, how much of the runtime can we reuse, and which details still need checking? In this case, two storage boundaries made the difference between having the right operations and actually reading the right numbers.

Two cards, the same question, different answers

These are the original fixtures used in the retained run. They contain invented values and no patient information. Click either image to open the exact PNG. The second card changes all three numbers while keeping the layout the same.

Fictional card A: pulse 72, respirations 16, oxygen 98
Card A · original 432 × 432 input. Expected fields: 72, 16, 98.
Fictional card B: pulse 83, respirations 19, oxygen 96
Card B · same layout, changed values. Expected fields: 83, 19, 96.
Exact image prompt used in the experimenttext
Transcribe the three values on this fictional vital signs card. Return only a JSON object with integer keys "pulse", "respirations", and "oxygen". Copy the values exactly.

The prompt’s phrase “integer keys” is awkward: the keys are strings and the values should be integers. I have kept the recorded prompt unchanged so the experiment remains identifiable. Both runtimes interpreted the requested fields correctly on these cards.

CaseExpected fields: pulse / respirations / oxygenCKE BF16CKE local Q4llama.cpp, both artifacts
Card A72 / 16 / 983/33/33/3 each
Card B83 / 19 / 963/33/33/3 each
Latest text record83 / 19 / 963/33/33/3 each
Third case · select the latest fictional recordtext
Copy the latest measured values from this fictional record. Return only one JSON object with the integer fields "pulse", "respirations", and "oxygen". 08:00 record: pulse 72, respirations 16, oxygen 98. 15:00 record: pulse 83, respirations 19, oxygen 96.

Changing the image changed the extracted values. The note also required choosing the 15:00 record rather than copying the first numbers encountered. Those are useful functional checks. They do not measure diagnosis, difficult handwriting, unit conversion, conflicting records or reliability on a hospital’s documents.

Read the raw output before calling it valid JSON

Here is CKE’s retained BF16 answer to card A, including the fences and visible whitespace glyph:

Raw image answer · uneditedtext
```json
{
 ▁"pulse": 72,
 ▁"respirations": 16,
 ▁"oxygen": 98
}
```

The scorer removes terminal color escapes, replaces ▁ with a normal space, finds a JSON object, then checks exact integer values. The raw response is therefore not already a strict JSON document. A consuming application needs a defined parsing boundary, and the tokenizer/formatting issue deserves its own regression test.

The field check, made explicitpython
clean = ansi_escape_pattern.sub("", raw).replace("▁", " ")
# Extract the JSON object from possible code fences, then parse it.
fields = json.loads(candidate_object)
correct = sum(
    type(fields.get(key)) is int and fields[key] == expected[key]
    for key in ("pulse", "respirations", "oxygen")
)

What changed from Gemma 4 to MedGemma 2?

Google describes MedGemma 2 as medically post-trained Gemma 4 with the base architecture preserved. E4B is the dense variant; A4B is a separate mixture-of-experts model. The medical post-training includes de-identified and licensed text, question-answer pairs, electronic health records, medical images and documents, with audio included for E4B. This generation uses Gemma 4’s native vision encoder without additional medical pretraining of that encoder. Google’s model card is the source for those training claims.

The publisher describes broader capabilities, including medical reasoning and multimodal workflows. Our experiment exercises text and single-image input with text output. It does not test audio, image volumes, video, tools or long-context reasoning. The released architecture and the particular CKE path we ran have different evidence boundaries.

For the rest of this article, the dimensions come from the retained CKE encoder and decoder configurations and the pinned circuit files. That also keeps “E4B” from becoming a misleading memory estimate: the artifact and all its tables still have to be stored, loaded and addressed.

The whole path: one image encoder, one text decoder

Follow the card and question into the generated answer
Follow the card and question into the generated answer. Open a block for shapes, equations and the pinned source JSON.

The image encoder produces feature vectors, not words such as “pulse.” The text tokenizer produces IDs, which select embedding rows. The bridge puts those two kinds of representation into the decoder’s shared feature space. In the recorded card request, five text tokens precede the image, 81 visual rows represent the image, and 43 text tokens follow it: 129 positions in total.

That ordering is important. The decoder must see the image inside the user turn and retain its keys and values while later text is appended. The bridge report names this a segmented append with persistent decoder KV state. Losing the cache between segments would lose the image context even if each individual kernel worked.

From dark pixels to 81 visual vectors

Open the image encoder: patches, attention, spatial merge and projection
Open the image encoder: patches, attention, spatial merge and projection. Open a block for shapes, equations and the pinned source JSON.

Start with one 16 × 16 RGB patch. It has 768 channel values. The 432-pixel width and height each contain 27 patches, so the input becomes a matrix with 729 rows and 768 columns. Pixel normalization uses channel mean 0.5 and standard deviation 0.5 after conversion to the expected scale.

The learned patch projection is a matrix multiplication: Z = XWᵀ. X contains the patch rows; W maps the 768 input components to 768 learned features. A row may now respond to a stroke, an edge or some learned combination of pixels. We have not visualized individual learned detectors, so those are intuitions about the operation rather than labels assigned to particular channels.

Positions tell the model where a patch lives. The retained circuit uses absolute two-dimensional position information and XY rotary encoding of queries and keys. Sixteen vision blocks then mix information across the image using 12 attention heads of dimension 64. The attention is bidirectional: a patch can gather context from elsewhere on the page.

A useful general expression is A = softmax(sQKᵀ), followed by Y = AV. Each row of A is a distribution over image positions. Q and K decide which patches relate; V supplies the features to mix. Here the retained vision contract has Q/K normalization and an attention scale of 1.0. Substituting a textbook scale without checking the provider would change this model.

The feed-forward branch then applies GeGLU: expand a row into two 3,072-wide projections, apply GELU to the gate branch, multiply the branches element by element, and project back to width 768. RMS normalization and residual additions surround these operations. Attention mixes positions; this feed-forward transform acts on each position’s features.

The footer merges 3 × 3 spatial neighborhoods, reducing the grid from 27 × 27 to 9 × 9. The circuit includes specific pool scaling and projector preparation, so “merge” should not be implemented by arbitrarily deleting patches. Finally a learned projection maps each of the 81 rows from width 768 to width 2,560. These rows are ready for the language decoder.

Forty-two layers reading the mixed sequence

Inspect the dense Gemma 4 decoder and its per-layer embeddings
Inspect the dense Gemma 4 decoder and its per-layer embeddings. Open a block for shapes, equations and the pinned source JSON.

The retained decoder configuration has hidden width 2,560, feed-forward width 10,240, eight query heads and two key/value heads. Its body includes sliding and full-attention variants, plus variants that reuse KV from an earlier layer. Local attention has a 512-position window. Full attention supplies a longer-range path according to the model’s layer schedule.

RMSNorm rescales a feature row using its root mean square and learned channel scales. With the appropriate checkpoint convention, its core calculation is x / sqrt(mean(x²) + ε). Projections form Q, K and V; normalization, rotary positions, masks and cache ownership complete the attention contract. A generic attention label hides several opportunities for two runtimes to disagree.

The dense feed-forward branch computes [GELU(xWg) ⊙ (xWu)]Wd. The gate and up matrices expand into 10,240 features, and the down matrix returns to 2,560. Per-layer embeddings add another token-dependent path prepared from learned tables and projections. These are precisely the tensors that made some quantized files fail import.

After the body, the footer applies final RMSNorm, the tied output head and the configured logit softcap. The head produces 262,144 vocabulary scores. Greedy selection chooses a token; incremental decode appends it and continues until a stop condition. The tested runtime reserved 512 positions. A model configuration capable of 131,072 positions does not turn this run into a 128K-context test.

How the JSON becomes native C

CKE’s circuit gives the compiler an operation order and contracts. The checkpoint supplies dimensions, layer kinds and tensor storage. Lowering connects those descriptions, resolves providers, assigns buffers and emits the C calls. Here is an actual excerpt of the pinned decoder template:

Header, one layer sequence and footerjson
{
  "header": [
    "bpe_tokenizer",
    "dense_embedding_lookup",
    "gemma4_per_layer_prepare"
  ],
  "sliding_attention_kv": [
    "attn_norm",
    "q_proj",
    "k_proj",
    "v_proj",
    "v_norm",
    "qk_norm",
    "rope_qk",
    "attn_sliding",
    "out_proj",
    "post_attention_norm",
    "residual_add",
    "ffn_norm",
    "mlp_gate_up",
    {
      "op": "geglu",
      "graph_slots": {
        "inputs": {
          "x": "mlp_scratch"
        },
        "outputs": {
          "out": "mlp_compact"
        }
      }
    },
    {
      "op": "mlp_down",
      "graph_slots": {
        "inputs": {
          "x": "mlp_compact"
        }
      }
    },
    "post_ffn_norm",
    "residual_add",
    "gemma4_per_layer_embed"
  ],
  "footer": [
    "final_rmsnorm",
    "weight_tying",
    "logits",
    "final_logit_softcap"
  ]
}

The JSON names operations; it does not contain the complete numerical implementation. Inspect the text circuit, the vision circuit and the importer together. The diagrams expose the same template sections so a reader can move from the conceptual block to its authored source.

The generated encoder and decoder are compiled shared libraries. Python prepares inputs and schedules the multimodal run; the measured neural operations execute in C. This evidence does not demonstrate a standalone, no-Python deployment package. Reference frameworks belong in a separate comparison workflow, not in the explanation of where these runtime calculations occur.

Two bugs at the boundary between bytes and mathematics

Follow BF16 import and actual tensor dtype into the selected native provider
Follow BF16 import and actual tensor dtype into the selected native provider. Open a block for shapes, equations and the pinned source JSON.

The first repair concerns BF16 storage. The importer preserves BF16 token and projection data where the consumer supports it. For two per-layer projections consumed as FP32, it widens the BF16 values exactly. In bit terms, placing a BF16 payload in the upper 16 bits of an FP32 representation preserves that BF16 numerical value. It does not restore the low mantissa bits discarded before the checkpoint was saved.

The second repair is easier to picture. A patch-projection weight was FP32, but a fixed provider binding selected an FP16 reader. Those formats have different element sizes and encodings. Reading the same memory with the wrong type changes both the interpreted values and how the reader steps through the array. The fix makes provider resolution follow the actual tensor dtype.

On matched pixels and an 81-token geometry, the recorded first-projection RMSE after correction was 0.000188. The final visual-prefix RMSE against llama.cpp improved from 1.026326 to 0.319171. That is a substantial improvement, with a remaining disagreement to investigate. The correct three-field answers do not erase it.

Why one Q4 works and another Q4 does not

Decoder artifactCKE at the tested revisionWhat was independently exercised
ggml-org BF16All three fixtures passedllama.cpp passed the same three
Local Q4_K_M-CKEAll three fixtures passedllama.cpp passed the same three
Published ggml-org Q4_K_MImport rejected: Q6_K per-layer token tablellama.cpp passed card A
Published ggml-org Q8_0Import rejected: Q8_0 per-layer token tablellama.cpp passed card A
Unsloth UD-Q4_K_XLIQ4_XS found in header; execution untestedNo execution result claimed

The local recipe keeps the per-layer token table in Q5_K, the global per-layer projection in BF16, and the per-layer gate/projection weights in FP32. The rest follows the selected Q4_K_M quantization profile. The public exports make different choices. Their unsupported tensor types are a compatibility gap at this source revision, rather than evidence that the model produced a wrong answer.

Decoder files: BF16 15.05 GB, local Q4 5.15 GB; unchanged projector 0.99 GB
File sizes from the pinned artifacts. The projector is additional to either decoder; conversion files, runtime buffers and loading workspace require further memory and disk.

Every comparison here retains the same BF16 projector file. The local quantization experiment changes decoder storage. It cannot establish what happens when the image encoder is quantized as well.

Run the BF16 path first

Use Linux x86-64 with a C compiler, Python and sufficient memory and disk for the source, original weights and generated artifacts. The measured machine is described below. The wrapper builds the generated libraries as part of bring-up. Its full developer environment includes reference tooling such as PyTorch; installing that environment should not be confused with executing the model through PyTorch.

1 · Checkout the tested source and prepare the developer environmentbash
git clone https://github.com/C-Kernel-Engine/C-Kernel-Engine.git
cd C-Kernel-Engine
git checkout d6ab700016689fc6b70af09bfa563e83ebcb81e3
python3 -m venv .venv
. .venv/bin/activate
python -m pip install -r version/v8/requirements.txt
python -m pip install Pillow
export CK_V8_PYTHON="$PWD/.venv/bin/python"

This pins the final PR head retained for the prefill retest. PR #1479 merged as e08adffaed91afcc0865f7a3cec2e1b31095df57. Use the pinned head for reproducing these results and review later fixes before applying the compatibility table to newer CKE versions.

2 · Download the exact decoder and projectorbash
hf download ggml-org/medgemma-2-E4B-it-GGUF   medgemma-2-E4B-it-BF16.gguf mmproj-medgemma-2-E4B-it-BF16.gguf   --revision d0468cf62617bbcdb51df0e5b82733c3b9d1fe19 --local-dir ./checkpoints/medgemma2
export MED_DIR="$PWD/checkpoints/medgemma2"
export MED_DECODER="$MED_DIR/medgemma-2-E4B-it-BF16.gguf"
export MED_PROJECTOR="$MED_DIR/mmproj-medgemma-2-E4B-it-BF16.gguf"
printf '%s  %s\n'   beb1922cb1b1d41dac92d5de6feca622f11b5f917a2179b811743300c0173ea4 "$MED_DECODER"   995f29c8222ca5fe3ebd5306bb733338d4da515a1059f301b999625a4dcb47fb "$MED_PROJECTOR"   | sha256sum --check

These are pinned converted GGUF files. Obtain access and accept the publisher’s applicable model terms where required. Direct validation against Google’s original Safetensors was not completed in this handoff; the independent runtime comparison uses llama.cpp on these GGUFs.

3 · Select providers and a writable workspacebash
: "${CK_MKL_LIBRARY:?Set the full path to your supported libmkl_rt.so.2}"
: "${CK_SLEEF_LIBRARY:?Set the full path to your supported libsleef.so.3}"
export CK_MKL_LIBRARY CK_SLEEF_LIBRARY
export CK_NUM_THREADS=6 OMP_NUM_THREADS=6 MKL_NUM_THREADS=6
export MKL_THREADING_LAYER=GNU
export LD_LIBRARY_PATH="$(dirname "$CK_MKL_LIBRARY")${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
export CK_V8_TMPDIR="$PWD/work/medgemma2/scratch"
export CK_CACHE_DIR="$PWD/work/medgemma2/cache"
export TMPDIR="$CK_V8_TMPDIR"
mkdir -p "$CK_V8_TMPDIR" "$CK_CACHE_DIR"

The measured setup used MKL 2024.2.0 and SLEEF’s shared runtime, with GNU threading for MKL. Set real library paths for your installation; the snippet deliberately stops if they are absent. Six threads reproduce the recorded setting, rather than a universal optimum. The CKE runbook covers the broader build workflow.

Save card A and card B from above into your current CKE directory. This is the measured image launch pattern:

4 · Image path → generated native encoder and decoderbash
version/v8/scripts/cks-v8-run run "$MED_DECODER" \
  --run "$PWD/runtimes/medgemma2-bf16" \
  --mmproj "$MED_PROJECTOR" --image-path "$PWD/card-a.png" \
  --context-len 512 --chat-template gemma4 --thinking-mode suppressed \
  --max-tokens 64 --temperature 0 \
  --prompt 'Transcribe the three values on this fictional vital signs card. Return only a JSON object with integer keys "pulse", "respirations", and "oxygen". Copy the values exactly.'

Repeat with card-b.png. Expect the three values to change from 72/16/98 to 83/19/96. Keep the raw answer, the bridge report and any failure logs. The first invocation can include conversion, code generation, compilation and initialization, so its wall-clock duration is not the decode rate.

5 · Text-only latest-record checkbash
version/v8/scripts/cks-v8-run run "$MED_DECODER" \
  --run "$PWD/runtimes/medgemma2-text" \
  --context-len 512 --chat-template gemma4 --thinking-mode suppressed \
  --max-tokens 64 --temperature 0 \
  --prompt 'Copy the latest measured values from this fictional record. Return only one JSON object with the integer fields "pulse", "respirations", and "oxygen". 08:00 record: pulse 72, respirations 16, oxygen 98. 15:00 record: pulse 83, respirations 19, oxygen 96.'

--context-len reserves the runtime’s token capacity. --max-tokens limits newly generated tokens. Zero temperature selects greedy decoding. The Gemma template and suppressed thinking match this workflow’s answer contract. Increasing context or changing templates creates a different test, even with identical weights.

Optional: reproduce the smaller local Q4 profile

This step uses llama.cpp’s quantizer as a weight-preparation tool. It is separate from CKE inference. The tested reference checkout was 458681e1d5d4a29a1463c4732e03226cf384b997.

Build the pinned quantizerbash
git clone https://github.com/ggml-org/llama.cpp.git ../llama-medgemma
 git -C ../llama-medgemma checkout 458681e1d5d4a29a1463c4732e03226cf384b997
cmake -S ../llama-medgemma -B ../llama-medgemma/build -DGGML_CUDA=OFF
cmake --build ../llama-medgemma/build --target llama-quantize -j6
export CKE_LLAMA_BIN="$(cd ../llama-medgemma/build/bin && pwd)"
Quantize with explicit per-tensor exceptionsbash
"$CKE_LLAMA_BIN/llama-quantize" \
  --tensor-type 'per_layer_token_embd.weight=q5_k' \
  --tensor-type 'per_layer_model_proj.weight=bf16' \
  --tensor-type 'blk\.[0-9]+\.inp_gate\.weight=f32' \
  --tensor-type 'blk\.[0-9]+\.proj\.weight=f32' \
  "$MED_DECODER" "$MED_DIR/medgemma-2-E4B-it-Q4_K_M-CKE.gguf" Q4_K_M 6
sha256sum "$MED_DIR/medgemma-2-E4B-it-Q4_K_M-CKE.gguf"
# Recorded artifact hash:
# c33965d8371282366083462529d7f1ad7487d09b201fddc3724ef392041589e4
export MED_DECODER="$MED_DIR/medgemma-2-E4B-it-Q4_K_M-CKE.gguf"
# Repeat image launch with a NEW --run directory:
# --run "$PWD/runtimes/medgemma2-local-q4"
# Keep MED_PROJECTOR unchanged.

Use a separate runtime directory so an earlier BF16 build is not mistaken for the Q4 result. If your artifact hash differs, retain the quantizer build, command and tensor inventory before comparing results. This is a local profile name; it is not an invitation to download any public file whose name contains Q4.

What happened on the actual CPU?

The retained tests ran on an AMD Ryzen 9 9950X3D: 16 physical cores, 32 logical CPUs, with six worker threads requested for these comparisons. The host exposes AVX2, AVX-512 and AVX-512 BF16; that capability list is not proof that every provider uses the same ISA. A publication-time inventory reports 161,760,178,176 bytes of OS-visible RAM, about 150.65 GiB. DIMM speed and exact memory timings were not recorded. This was a shared machine without pinned affinity or controlled background activity.

The newer retest uses three timed trials per mode after an excluded initial build/warmup. Each trial starts a fresh process with the built bundle. The same text request has 88 prompt tokens and 36 decode steps. The table shows median reported phase durations:

Artifact / modeCKE prefillllama.cpp prefillCKE decodellama.cpp decode
Local Q4 · auto7.674 s0.504 s2.963 s2.563 s
Local Q4 · explicit batched7.743 ssame comparator2.992 ssame comparator
BF16 · auto26.824 s0.456 s10.982 s7.309 s
Median timings show a large CKE prefill gap and a smaller local-Q4 decode gap
Three timed trials per mode; 88 prompt tokens, 36 decode steps, six threads, 512 context slots. Shared Ryzen 9 9950X3D. Phase timing excludes loading and compilation.

For local Q4, those medians correspond to roughly 12.15 decode tokens/s in CKE and 14.05 in llama.cpp. Prefill takes about 15.2 times as long in this comparison. BF16’s prefill gap is larger. The earlier single-run result—12.0 versus 13.4 decode tokens/s—belongs to an earlier measurement, not this three-run median.

Explicit batched prefill did not close the gap: auto and batched generated C matched after timestamp removal, and their timings were close. This is useful because it rules out the easy explanation that the test merely forgot to enable batching. The next investigation needs provider-level profiling: quantized activation preparation, projection calls, attention, per-layer embeddings and normalization.

The retained Q4 prefill source calls providers including gemm_nt_q4_k_q8_k_pairwise_split_min_parallel_dispatch. Counting such calls describes the generated program; measuring their time is a separate job. Loading also prepared 1,935,426,560 bytes of x8 weight data, outside the prefill phase. We should measure initialization, first answer latency and steady-state execution separately before making deployment recommendations.

All 15 timed trials returned the expected fields. The image trials in the original handoff reported 2.88–3.06 decode tokens/s with BF16 and 8.21–8.56 with local Q4, but those were not the repeated text benchmark. An image request also pays for preprocessing, vision execution and mixed-prefix handling. Keeping those workloads separate makes the comparison more useful.

What I would harden next

  1. Published artifact compatibility: support or explicitly document the Q6_K, Q8_0 and IQ4_XS per-layer table contracts, with importer and runtime tests for each.
  2. Output formatting: address the visible whitespace glyph at the tokenizer boundary and separately test strict JSON output.
  3. Numerical agreement: trace the remaining visual-prefix discrepancy layer by layer, using matched pixels, geometry and weights.
  4. Prefill: profile the actual generated path before changing kernels; retain the same prompt, precision, thread settings and phase definitions.
  5. Broader evidence: add harder documents, perturbations and failure cases. Audio, multi-image/volume input and clinical performance need their own evaluations.

For me, this is the useful part of the bring-up. The existing architecture was reusable, and the new checkpoint exposed concrete boundaries we could repair and measure. We can show a complete generated-C path while still making the remaining work visible.

PR history and reproducibility

Source-linked implementation

The change that enabled this checkpoint

1 directly relevant merged PR

The Gemma 4 circuits predate this bring-up. This entry identifies the checkpoint-specific repair, rather than claiming it introduced the entire architecture.

  1. #1479

    BF16 GGUF import and dtype-aware vision patch projection

    Preserve BF16 storage, widen the required per-layer projections, and select the patch provider from its tensor dtype. Add import and provider regression coverage.

    Tested final head d6ab7000 · merge e08adffa

The first card workflow used 4021acff0442ec5c72ec420eded17b2e192fce7a; the final prefill retest used the PR head pinned in the commands. The retained focused retest reports 11 tests and 33 subtests. Earlier PR validation totals belong to earlier runs. The local publication pass re-ran the retained field scorer; it did not rerun the large-model timing experiment.

Primary references: Google’s MedGemma 2 card, the pinned ggml-org artifacts, the separately inspected Unsloth export, the CKE decoder circuit and the CKE vision circuit.

Recommended reading on ShivasNotes

Lab hardware used in this article
Ryzen · AMD Ryzen 9 9950X3D workstation
Zen 5 · 16 cores, 32 threads · 128 MiB L3 · AVX-512 with BF16 and VNNI. Linux reports 150.7 GiB usable RAM. 4 TB NVMe and 12 TB HDD on an ASUS TUF X870E-PLUS WIFI7 board. Ubuntu 26.04 LTS. Lab inventory, 3 December 2026. Earlier runs used different memory configurations.
Read about the CKE hardware lab