Gemma 4 on an 8GB GPU: llama.cpp, context, and RAG debugging
Gemma 4 on an 8GB GPU: llama.cpp, context, and RAG debugging
Search
Ask the AI

Gemma 4 on an 8GB GPU: llama.cpp, context, and RAG debugging

I deployed a Gemma 4 inference gateway on a laptop GPU with 8 GB of VRAM, then connected a translation client and added retrieval-augmented generation. During deployment, a download command exited 0 without fetching weights, a listening service could not establish connections, and some flags were silently ignored.

The sections below record the logs, measurements, and fixes, in order from model selection and inference to public access, translation, and retrieval. To estimate which model fits before downloading it, use the VRAM calculator.

1. Parameter count is a bad proxy for VRAM: official quantized checkpoints can be 2× larger than you expect

The easiest mistake during model selection is estimating VRAM as “parameters × bytes per parameter”. Gemma 4’s official QAT checkpoints carry a -qat-w4a16-ct suffix, so intuition says a 4B-class model should need 2–3 GB.

Query the actual safetensors byte counts instead:

gemma-4-E4B-it-qat-w4a16-ct     11.51 GB
gemma-4-12B-it-qat-w4a16-ct     10.26 GB
gemma-4-31B-it-qat-w4a16-ct     23.27 GB

E4B, nominally “4.5B effective parameters”, is larger than the 12B model. The reason is in config.json:

{
  "quantization_config": {
    "config_groups": {
      "group_0": {
        "targets": ["Linear"],
        "weights": { "num_bits": 4, "group_size": 32 }
      }
    }
  }
}

targets contains only Linear. Only linear layers are quantized to 4 bits; embeddings and per-layer embeddings (PLE) stay in bf16. The E-series uses a PLE architecture whose table is vocab_size × layers × per_layer_dim. For E4B that is 262144 × 42 × 256 ≈ 2.8B parameters, or 5.6 GB in bf16 by itself.

Check memory headroom before loading the 31B w4a16-ct checkpoint on a 24 GB card. The weight files total 23.27 GB, close to the card’s advertised capacity. Convert GB and GiB consistently, then use the actual available bytes, quantization format, and target context length to check space for weights, KV cache, and runtime overhead.

How to avoid it

Check the selected checkpoint’s file bytes before estimating runtime VRAM. This script sums every safetensors and GGUF file in the repository. If it contains several quantization variants, select one variant and all its shards. Record file size separately from the GPU memory that the runtime allocates.

curl -s "https://huggingface.co/api/models/<org>/<repo>?blobs=true" | python3 -c "
import json,sys
d=json.load(sys.stdin)
w=[(s['rfilename'], s.get('size') or 0) for s in d.get('siblings',[])
   if s['rfilename'].endswith(('.safetensors','.gguf'))]
print(f\"{sum(s for _,s in w)/1e9:.2f} GB\")"

Among the checkpoints compared here, GGUF q4_0 also quantizes the embeddings, giving an E4B file of 5.15 GB that suits this 8 GB card. Other quantizations or CPU offload can also fit. Throughput, batching and memory use in vLLM and llama.cpp depend on their versions, backends and workload; this deployment used llama.cpp + GGUF. The VRAM calculator can provide an initial estimate for the target context.

2. The download command exits 0 and fetches nothing

My prefetch step looked like this:

hf download "$MODEL_ID" --exclude '*.pth' '*.gguf' 'original/*'

It printed ✓ Downloaded, returned exit code 0, and the script moved on. Then the inference server failed to start.

In the CLI installed for this run, each --exclude consumed one glob. The next two patterns became explicit filenames, and the log shows that no files matched them. CLI parsers differ between versions; check hf download --help for the installed version.

UserWarning: Ignoring `--exclude` since filenames have been explicitly set.
Fetching 0 files: 0it [00:00, ?it/s]

The correct form repeats the flag:

hf download "$MODEL_ID" \
  --exclude '*.pth' --exclude '*.gguf' --exclude 'original/*'

After downloading, check that the files reached disk. I added a size check to the deployment script:

# The command above can return 0 having downloaded nothing.
# Verify by measuring what actually landed on disk.
WEIGHT_MB="$(du -sm "$HF_HOME_DIR" | cut -f1)"
[ "${WEIGHT_MB:-0}" -ge 500 ] || die "only ${WEIGHT_MB} MB on disk — download is incomplete"

This catches obvious failures such as an empty directory. du -sm reports the cache directory in MiB, and unrelated models or partial files can also pass the threshold. Verify completeness against the selected repository, revision, shard list and file checksums.

3. One flag changes prompt processing by 40×

Once the server was up, generation ran fine at 60+ tok/s, but prompt processing crawled. A 544-token input took over ten seconds.

The llama-bench pp512 result was 3254 tok/s, showing that this benchmark path could use the GPU. The server request exercises a different workload. Checking its flags produced these results:

configuration                prompt processing (544 tokens)
baseline (no flash attn)          39.6 t/s
+ flash-attn on                 1726.5 t/s
+ q8_0 KV cache                 1654.4 t/s

A greater than 40× difference. These measurements support enabling flash attention for this Gemma 4 E-series model, Vulkan backend and request. The E-series uses sliding window attention (SWA), but timing alone does not attribute the entire gap to SWA or a particular kernel path; that requires logs or source from the corresponding version.

For the model and Vulkan backend tested here, --flash-attn directly affects prompt processing speed. Check that it is enabled when deploying this combination. In llama.cpp b10216 and b12184 the default is auto, which enables flash attention unless the backend cannot run it on a layer’s device; the startup log reports the result.

4. Check --ctx-size and parallel slots against the startup log

In the original deployment, some model layers loaded on the CPU and prompt processing dropped to 1.3 tok/s. The saved command fragment uses --ctx-size 16384; the log records four slots with a limit of 16384 each. The surviving records do not establish that both came from the same version and startup. Interpret the log using the KV mode, total context and effective launch arguments. With unified KV, four slots can each have a 16384 limit while sharing one 16384 pool.

Correction, 2026-11-07: this section previously multiplied the 4 logged slots by 16384 to get a 65536-token total and tied that total to the CPU spill and the 1.3 tok/s result. In the automatic mode of llama.cpp b10216 and b12184, the server enables unified KV, so each of the 4 slots has a 16384 limit while all of them share one 16384-token pool.

The saved startup log was:

srv load_model: initializing, n_slots = 4, n_ctx_slot = 16384

The current server documentation describes automatic parallelism and unified KV; historical logs require their own version. The checked b10216 source also distinguishes a shared pool from independent slots. Multiplying the slot limit by the slot count gives the total only for independent slots. This example disables unified KV to allocate four slots of 32K each:

# Independent slots: per-slot context = total context / parallel slots
--ctx-size 131072 --parallel 4 --no-kv-unified    # 4 concurrent slots, 32K each

That division is also a useful tuning knob: translation clients fire dozens of concurrent short requests, so slot count matters more than depth. Coding assistants are the opposite.

5. Vulkan shader compilation adds work to the first measurement

After a restart, the first large prompt measured 21 tok/s. The identical request measured 900+ tok/s on the second try. I spent a while changing configuration that was never wrong.

Creating Vulkan compute pipelines can add work on first use, but these two requests also mix cold/warm state with reuse of an identical prompt. To isolate shader compilation, record compilation logs and the token counts actually processed or reused from the prompt cache. A representative prompt of several hundred tokens can exercise large-batch paths that a few-token warmup misses.

Warm up configurations A and B separately before comparing them. If shaders compile only on the first run, configuration A’s measured time will also include compilation.

6. Reasoning exhausts the token budget before the final answer

Gemma 4 has a thinking mode. This llama.cpp configuration parses reasoning into message.reasoning_content and the final answer into message.content. Field handling depends on the template, parser and service version.

Which produces responses like this:

{
  "choices": [{
    "finish_reason": "length",
    "message": {
      "content": "",
      "reasoning_content": "Thinking Process:\n\n1. **Analyze the Request:** ..."
    }
  }],
  "usage": { "completion_tokens": 150 }
}

content is an empty string, not null and not an error. Any client that reads only content reports “the model returned nothing”.

Two mitigations:

  • Budget max_tokens generously. Reasoning counts against completion tokens; a small budget truncates before the answer begins. 2048+ for non-trivial questions.
  • Handle reasoning_content in the client. Streaming delivers it as delta.reasoning_content. Ignore it and your UI freezes for tens of seconds while the model thinks, which looks indistinguishable from a hang.

Disabling reasoning: one method works, one does not

To reduce waiting time for translation, summarization, and classification, I tested two ways to disable reasoning:

// No effect — still produced 1239 characters of reasoning
{ "reasoning_budget": 0 }

// Works — zero reasoning
{ "chat_template_kwargs": { "enable_thinking": false } }

The difference on a single technical paragraph translated to Chinese:

reasoning on:   1762 chars of reasoning, 560 output tokens
reasoning off:     0 chars of reasoning,  61 output tokens

About a 9× difference in output tokens for this paragraph. I checked both translations and found no difference that changed its technical meaning. This was an inspection of one paragraph, without a separate blinded or cross-text quality evaluation.

7. A rate limit tuned by intuition reads as a network failure

After wiring the gateway into a browser translation extension, it reported: “Network connection failure (may be caused by server unresponsiveness, network instability or security policy restrictions).”

The server logs told a different story:

[error] limiting requests, excess: 40.800 by zone "api_zone",
        request: "POST /v1/chat/completions"

I had configured rate=120r/m (2 per second) with burst=40. Translating one page fires dozens of requests at once; the burst filled instantly and everything after it got a 503.

The burst budget was smaller than the translation extension’s normal burst. Rate limiting controls request rate, bursts and abusive traffic. Set rate and burst from the workload, inference capacity and acceptable waiting time. Nginx can delay or reject excess requests; requests waiting beyond the backend’s slots also face queue limits, timeouts and cancellation.

8. Port forwarding is correct, the SYN-ACK goes out, and the client keeps retransmitting

This was the hardest failure to diagnose. When I exposed the API directly to the internet, the forwarding rule was entirely correct (external port, internal IP, internal port, protocol), and external clients still could not complete a TCP handshake.

The packet capture showed repeated SYN packets after each SYN-ACK:

<client> > <server>:9443    Flags [S]     ← SYN arrives
<server>:9443 > <client>    Flags [S.]    ← SYN-ACK is sent
<client> > <server>:9443    Flags [S]     ← client retransmits
<client> > <server>:9443    Flags [S]

Packets arrived and replies left, but the client received nothing. The machine’s default gateway was not the router performing NAT. Its default route used another LAN device to reach a proxy. Replies bypassed the return path through the incoming DNAT mapping, so the client did not receive a response with the expected connection mapping. The incoming router already had connection-tracking state; the return path failed to use it.

Another server on the same LAN had working port forwarding all along, precisely because its default gateway was the router.

Fix: conntrack marking plus policy routing

Force replies for router-originated connections back out through the router:

# 1. Mark new connections that arrived via the router's DNAT
iptables -t mangle -A PREROUTING -i "$IFACE" ! -s "$LAN_NET" \
  -p tcp --dport "$PORT" -m conntrack --ctstate NEW \
  -j CONNMARK --set-mark "$MARK"

# 2. Restore the mark onto subsequent packets, including the locally
#    generated SYN-ACK
iptables -t mangle -A PREROUTING -i "$IFACE" -j CONNMARK --restore-mark
iptables -t mangle -A OUTPUT -j CONNMARK --restore-mark

# 3. Marked packets consult a table whose only route is via the router
ip route replace default via "$ROUTER" dev "$IFACE" table 100
ip rule add fwmark "$MARK" lookup 100

These rules describe this single-interface, same-LAN topology. Before adapting them, check next-hop reachability, the routes in table 100, fwmark and rule-priority conflicts, reverse-path filtering, and the existing firewall rules.

Two details are easy to get wrong.

First, --restore-mark belongs to the CONNMARK target, not the connmark match. Writing -m connmark --restore-mark fails outright with unknown option.

Second, the marking rule must exclude LAN sources (! -s $LAN_NET). Without it, replies to LAN clients connecting to the internal IP also get shoved into that default-route-only table, sent to the router, and lost. Every internal direct connection times out. That “fix one thing, break another” failure only surfaces if you regression-test after the fix.

Then there is NAT hairpinning

With the LAN exclusion in place, internal devices reaching the service via its public hostname (NAT hairpin) broke instead. That traffic has a LAN source address, so the first rule misses it, yet it does arrive through the router’s DNAT and needs the same return path.

In this same-layer-2 topology, packets forwarded by the router carry the router’s source MAC, which can match this hairpin path. A source MAC identifies the previous hop; it is not a general proof of DNAT or client identity:

iptables -t mangle -A PREROUTING -i "$IFACE" \
  -m mac --mac-source "$ROUTER_MAC" \
  -p tcp --dport "$PORT" -m conntrack --ctstate NEW \
  -j CONNMARK --set-mark "$MARK"

With that rule, serial hairpin requests went from 4/6 succeeding at an 8.96 s median to 8/8 at a 0.369 s median. Later records still show 3/4 successes for four concurrent hairpin requests. Pinning the hostname to the LAN IP at home gave 4/4, while eight concurrent requests from an external client gave 8/8. These are separate conditions: the serial improvement left a concurrent failure unresolved.

9. Domain-based routing changes the path used in a latency test

I initially measured “the tunnel path takes 1.5–4.8 s, the direct path takes 0.2 s.” Checking the routes showed that the requests used different proxy paths, so these measurements could not establish which access method was faster.

My machine runs proxy software that routes by domain name. Requests to api.example.com were proxied out to the internet and back. The server’s access log showed a carrier IP as the source, not the machine’s LAN address. The same machine hitting the raw IP went direct.

# The source IP the server sees is the ground truth
sudo tail -5 /var/log/nginx/<site>.access.log

# Force the physical interface, bypassing the TUN device
curl --interface en0 ...

The access log shows the last peer visible to the server. Establish the full path with routing, proxy configuration and packet captures. The curl --interface en0 example binds an interface; whether it bypasses TUN depends on system routing and proxy settings, so verify the actual egress.

Record the client’s location when comparing latency. From my home network, the direct path was roughly twice as fast. From a server abroad, the tunnel was 15× faster because that machine was close to the tunnel’s edge PoP. Each result applies to its own measurement location.

10. Four traps when adding RAG

I then added retrieval-augmented generation. Documents are split into chunks and embedded, stored in sqlite-vec + FTS5, and searched with hybrid retrieval. The retrieved passages are added to a system message.

10.1 The embedding batch size limit

Ingestion failed immediately with a 500:

input (573 tokens) is too large to process.
increase the physical batch size (current batch size: 512)

This run’s log shows an effective --ubatch-size of 512 tokens, below the 573-token chunk. The embedding model used here accepts 8192 input tokens, and this configuration increased the batch sizes. Other models and backends require checks of their input limits and available memory:

--ctx-size 8192 --batch-size 8192 --ubatch-size 8192

10.2 Split by heading first, by size second

My first implementation split recursively by character count, then labelled each chunk with the last markdown heading that it contained. Two consequences:

  • Small documents collapsed into a single chunk, and all retrieval granularity was lost.
  • When a chunk spanned several sections, content from the first section was labelled with the last section’s heading. Citations pointed at the wrong place, and the error was hard to notice.

The correct order is two-level: split into sections at headings (semantic boundaries), then subdivide oversized sections. Every chunk then belongs to exactly one section.

10.3 Heading detection must skip fenced code

A markdown heading regex matches shell comments inside fenced code blocks, because the two are textually identical:

```bash
# 3. Remember to remove this afterwards
sudo sed -i '/example/d' /etc/hosts
```

That comment became an H1, so a citation breadcrumb read README.md › 3. Remember to remove this afterwards.... The fix is to compute the fenced-block spans first and ignore heading matches that fall inside them.

10.4 CJK full-text search: both the tokenizer and the query need work

Two independent problems.

The tokenizer. SQLite FTS5’s default unicode61 separates tokens by character category, without segmenting continuous Chinese into words. A run of Chinese characters can become one long token, so words within it do not match as expected. Here trigram provides substring retrieval; its MATCH queries require at least 3 Unicode characters:

CREATE VIRTUAL TABLE chunks_fts USING fts5(
  text, content='chunks', content_rowid='id', tokenize='trigram'
);

The query. I first quoted the whole user question as a phrase. Under trigram, phrase matching is substring matching, so a natural-language question matches nothing at all. The entire full-text arm contributed zero results. The fix is to try the full phrase, then fall back to OR-ing the individual terms (3+ characters).

Two retrieval paths for this knowledge base

Dense and lexical retrieval have complementary blind spots.

  • In this corpus, vector search found passages for queries such as “How do I stop the model from reasoning?” whose wording differed from the source. Lexical search can also handle such questions through query terms and synonym strategies.
  • reasoning_budget, or a specific .gguf filename, are identifiers, and embeddings are notoriously insensitive to them. In testing, vector search failed to rank the correct passage; lexical search matched it exactly.

Fuse the two with Reciprocal Rank Fusion. It combines ranks, so the two incomparable score scales need no normalization:

K = 60
score = {}
for rank, cid in enumerate(vec_hits):
    score[cid] = score.get(cid, 0.0) + 1.0 / (K + rank + 1)
for rank, cid in enumerate(fts_hits):
    score[cid] = score.get(cid, 0.0) + 1.0 / (K + rank + 1)

11. The frontend has a silent failure too

The control panel toggles between a login view and the main interface using the hidden attribute. Both rendered simultaneously, so the login card was pushed out of the viewport.

The author stylesheet overrode the browser’s default rule for hidden. CSS compares origin and importance before specificity. The ID selector below triggered the problem, but an ordinary author rule with lower specificity can also override a normal user-agent rule:

#app { display: flex; }           /* ID selector — high specificity */
/* User-agent default: [hidden] { display: none } — loses, silently */

The element carried the hidden attribute while its computed style stayed flex. The fix is one explicit rule:

[hidden] { display: none !important; }

What these have in common

In retrospect the failures fall into three families:

  • Silent failure. Flags ignored, commands exiting 0 without acting, content returning an empty string instead of an error. The countermeasure is to verify every critical step against an independent fact. Do not trust a return code.
  • Context and batch size. Check the effective --ctx-size and --parallel values, including the context per slot for the 4 slots in the log. In this deployment, --ubatch-size defaulted to 512, and the default FTS5 tokenizer did not segment CJK. Check startup logs and actual output to confirm the applied configuration.
  • Unreliable measurement. Lazy shader compilation, proxy software routing by domain, conclusions that depend on vantage point. The countermeasure is to always include a control: a port that should fail, a known-good baseline, a second measurement location.

In the port-forwarding case, tcpdump identified the return-route problem. A listening service, configured forwarding rules, and firewalls disabled for testing were not enough to establish connectivity. Capturing the traffic showed whether the SYN arrived, whether a SYN-ACK was sent, and which route the reply used. Those checks identified where the repair was needed.

Leave a Reply

Scroll down