[aj@blog] "blog.ayjc.net" 02:46 03-Dec-26

OpenCode and Ollama but with 256K context on an RTX 5090

About a year ago, I wrote a walkthrough on OpenCode and Ollama for running a local coding agent on your own GPU. The most important step in that post was bumping up the context window, because Ollama defaulted to 4,096 tokens and tool calls would break without more room. Raising it to 16K was enough to get OpenCode’s tools working, though I concluded at the time that local models were really only suited for “simple scripts or apps that don’t require massive context.”

This post is a follow-up to that setup. On my RTX 5090 Linux workstation, OpenCode now runs Qwen3.8-27B with its full native 262,144-token context window, entirely in VRAM, at around 128 tokens per second. Getting there only took a systemd drop-in, a two-line Modelfile, and a small update to the OpenCode config. Most of the actual work was measuring things so I could rely on real numbers instead of guesses.

Here is how the old setup compares to the new one:

December 2025 December 2026
Model gpt-oss:20b qwen3.8:27b (Q4_K_M + MTP)
GPU 24 GB class RTX 5090, 32 GB
OpenCode context 16,384 262,144
Placement GPU 100% GPU, 28.8 of 31.8 GiB
Generation not measured ~128 t/s short, ~109 t/s after a 104K-token prompt

My new setup

My workstation runs Fedora 45, Ollama 0.40.16 as a systemd service, and OpenCode 1.19.5. Since I have not been using local models very often, my configuration had drifted a bit over the past year:

  • The Ollama service had no tuning at all: no custom context length and no KV cache settings.
  • My OpenCode config still pointed to gemma4:31b-16k. I had tried that model earlier in 2026 using the same 16K pattern from my original post.
  • For my Matrix terminal evaluation harness, I had created a qwen3.8-27b-eval variant with num_ctx 65536. At the time, 64K felt like a reasonable ceiling on a 32 GB card, but it turns out I had a lot more headroom than I thought.

Because that 64K number was just a guess, I wanted to measure what the card could actually handle.

Why 256K can fit at all

A quick glossary

The rest of this post gets into how Ollama and Qwen3.8 use GPU memory. If you have not tuned local models before, here is a quick rundown of the terms I am using below:

  • Weights and quantization (Q4_K_M): Weights are the model’s learned parameters (roughly 17 GB of data loaded into VRAM). Quantization compresses those numbers to fewer bits, around 4 bits each for Q4_K_M, so a 27B model can fit on a consumer GPU.
  • KV cache (Key-Value cache): A scratchpad in VRAM where the model stores notes about every token in the current conversation so it does not have to re-read the entire prompt for every word it generates. Unlike the weights, the KV cache grows with your context window (num_ctx), and at 256K tokens it is usually the first thing to run out of VRAM.
  • Cache precision (f16 vs. q8_0): How many bytes each entry in the KV cache uses. f16 (16-bit floating point) is the default at 2 bytes per number, while q8_0 compresses entries to 8-bit integers, nearly cutting the cache size in half with minimal impact on quality.
  • Full attention vs. linear attention (and recurrent state): Standard full attention lets a layer look back at every earlier token, which requires a KV cache that scales with context length. Linear attention (Gated DeltaNet in Qwen3.8) instead folds past context into a fixed-size summary called the recurrent state, using the same small slice of VRAM whether your prompt is 4K or 256K tokens.
  • Flash attention: A more memory-efficient algorithm for computing attention on the GPU. Ollama requires it to be enabled before you can quantize the KV cache to q8_0.
  • MTP (multi-token prediction) and speculative decoding: Normally, a model writes one token per pass over its weights, so speed is limited by how fast the GPU can read VRAM. Speculative decoding uses a small drafter to guess several upcoming tokens at once, and the main model verifies them in a single pass. MTP builds that drafter directly into the model instead of requiring a separate draft model.
  • Vision projector: A small adapter bundled with multimodal models like Qwen3.8 that translates images into tokens the language model understands. It takes up a fixed chunk of VRAM even when you only send text prompts.
  • Prefill vs. decode: Prefill is the model reading your prompt and populating the KV cache before the first word appears (fast and parallel, often thousands of tokens per second). Decode is generating the reply token by token (much slower, anywhere from tens to around 130 tokens per second).
  • Spilling to CPU: When a model and its KV cache exceed your GPU’s VRAM, Ollama quietly offloads some layers into system RAM and runs them on the CPU. Everything still works, but generation gets much slower.

How Qwen3.8 fits

With a standard dense 27B model, running a 256K context window on a 32 GB card is out of the question because the KV cache alone would need more VRAM than the GPU has. Qwen3.8 is not a standard full-attention model, though. Running ollama show -v qwen3.8:27b prints the architecture details:

qwen35.block_count                65
qwen35.full_attention_interval    4
qwen35.attention.head_count_kv    4
qwen35.attention.key_length       256
qwen35.attention.value_length     256
qwen35.nextn_predict_layers       1
qwen35.ssm.state_size             128

Only every fourth layer uses full attention. The rest are linear-attention (Gated DeltaNet) layers that keep a small, fixed-size state, which means only 16 of the 64 transformer layers need a KV cache that grows with context length. The 65th block is a built-in multi-token prediction (MTP) head that Ollama uses for speculative decoding.

That makes the KV cache math much easier to work with:

16 layers × 2 (K and V) × 4 KV heads × 256 dims × 2 bytes (f16) = 64 KiB per token
KV cache type Per token 128K 256K
f16 (default) 64 KiB 8 GiB 16 GiB
q8_0 34 KiB 4.25 GiB 8.5 GiB

On paper, the full 256K window needs about 8.5 GiB of cache at q8_0, on top of roughly 17 GiB for the weights and vision projector. That looked like it should fit inside 31.8 GiB, so the next step was to run a load test and see how much headroom was actually left.

Measure the baseline first

Before changing any settings, I loaded the stock model at two context sizes using a per-request num_ctx and the default f16 cache:

curl -s localhost:11434/api/generate -d '{
  "model": "qwen3.8:27b", "prompt": "hi", "stream": false,
  "options": { "num_ctx": 131072, "num_predict": 1 }
}'
ollama ps
nvidia-smi --query-gpu=memory.used --format=csv,noheader
Context KV type VRAM used Placement
64K f16 22.7 GiB 100% GPU
128K f16 27.2 GiB 100% GPU
256K f16 ~36 GiB (projected) won’t fit

The Ollama systemd journal matched the math:

llama_kv_cache: size = 8192.00 MiB (131072 cells, 16 layers, 1/1 seqs), K (f16): 4096.00 MiB, V (f16): 4096.00 MiB
llama_memory_recurrent: size = 748.12 MiB (1 cells, 64 layers, 1 seqs 4 rs_seq)

A few other details in the logs stood out:

  • Flash attention was already enabled. Ollama 0.40 starts its bundled llama-server with --flash-attn auto, and the log confirmed Flash Attention enabled. Last year you still had to turn this on manually.
  • The MTP drafter has its own KV cache. It took up 512 MiB at 128K, and it stays at f16.
  • The recurrent state is fixed at 748 MiB, no matter how large the context window gets.

From those numbers, it was pretty clear that f16 tops out somewhere between 128K and 256K, while switching to q8_0 should let the full 256K window fit.

Change 1: the Ollama service

Because the KV cache type is a server-wide setting, it needs to go in the systemd unit. I added a drop-in override with sudo systemctl edit ollama:

[Service]
Environment="OLLAMA_FLASH_ATTENTION=1"
Environment="OLLAMA_KV_CACHE_TYPE=q8_0"
Environment="OLLAMA_MAX_LOADED_MODELS=1"
Environment="OLLAMA_KEEP_ALIVE=30m"

Here is what each line is doing:

  • OLLAMA_KV_CACHE_TYPE=q8_0 is the main change. It nearly cuts the KV cache size in half with very little quality loss.
  • OLLAMA_FLASH_ATTENTION=1 is technically redundant on this version of Ollama, but since KV cache quantization depends on flash attention, I like setting it explicitly.
  • OLLAMA_MAX_LOADED_MODELS=1 keeps a second model from loading alongside a 29 GiB model and pushing it off the GPU.
  • OLLAMA_KEEP_ALIVE=30m keeps the model warm in VRAM while I review diffs between OpenCode turns, instead of unloading after the default 5 minutes.

I intentionally left OLLAMA_CONTEXT_LENGTH unset. In last year’s post, I used that variable to set a global default, but setting it to 262144 here would also apply to the 31B Gemma models I have installed, which cannot fit anywhere near that much context. It makes more sense to set the context size per model instead.

Change 2: a 256K model alias

Last year I created context variants interactively using /set parameter num_ctx and /save. A Modelfile accomplishes the same thing and is much easier to reproduce later:

cat > Modelfile.qwen3.8-27b-256k <<EOF
FROM qwen3.8:27b
PARAMETER num_ctx 262144
EOF
ollama create qwen3.8:27b-256k -f Modelfile.qwen3.8-27b-256k

This alias reuses the existing weight layers, so it does not take up any extra disk space.

You really do need this alias for OpenCode. OpenCode talks to Ollama over the OpenAI-compatible /v1 endpoint, and that API does not have a field for num_ctx. Without the context length baked into the model itself, OpenCode falls back to Ollama’s default (32K on a 32 GB card).

Change 3: the OpenCode config

The provider block in ~/.config/opencode/opencode.json looks mostly the same as last year’s, with a limit block added for each model:

{
  "$schema": "https://opencode.ai/config.json",
  "model": "ollama/qwen3.8:27b-256k",
  "provider": {
    "ollama": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "Ollama (local)",
      "options": {
        "baseURL": "http://localhost:11434/v1"
      },
      "models": {
        "qwen3.8:27b-256k": {
          "name": "Qwen3.8 27B (256k context)",
          "tools": true,
          "reasoning": true,
          "limit": { "context": 262144, "output": 32768 }
        },
        "gemma4:31b-16k": {
          "name": "Gemma 4 31b (16k context)",
          "limit": { "context": 16384, "output": 8192 }
        }
      }
    }
  }
}

The limit.context field tells OpenCode how large the context window is so it can track usage and compact the conversation before it overflows, since a custom provider cannot discover that automatically. Setting it to the same 262144 value as the Modelfile keeps the client and server in sync. I also set the top-level model to the new alias so I do not have to select it with /models every time I start a session.

Verifying the full window

After restarting Ollama, I loaded the 256K alias and checked ollama ps and the systemd journal to confirm everything loaded where it was supposed to:

$ ollama ps
NAME                SIZE     PROCESSOR    CONTEXT    UNTIL
qwen3.8:27b-256k    19 GB    100% GPU     262144     29 minutes from now

$ journalctl -u ollama | grep "kv_cache: size"
llama_kv_cache: size = 8704.00 MiB (262144 cells, 16 layers, 1/1 seqs), K (q8_0): 4352.00 MiB, V (q8_0): 4352.00 MiB

The full context fits on the GPU, and the cache is running at q8_0. nvidia-smi reported 29,472 MiB of 32,607 MiB (28.8 of 31.8 GiB) in use, leaving roughly 3 GiB of headroom. Here is the breakdown from the load log:

Component VRAM
Main KV cache, q8_0, 256K 8,704 MiB
MTP draft KV cache, f16, 256K 1,024 MiB
Linear-attention recurrent state 748 MiB
Largest compute buffer 1,380 MiB
Weights, vision projector, and the rest remainder of 28.8 GiB

Horizontal stacked bar chart comparing Qwen3.8-27B VRAM usage at 256K context on an RTX 5090 (31.8 GiB usable): f16 projects to roughly 36 GiB and overflows the GPU limit, while q8_0 cuts the main KV cache from 16.0 GiB to 8.5 GiB so the full 28.8 GiB fits with about 3.1 GiB of headroom.

That MTP draft cache is easy to overlook. It ignores OLLAMA_KV_CACHE_TYPE and stays at f16, so it takes up a full gigabyte of VRAM at 256K. I had already run into this same hidden cache when sizing Qwen3.8 on my 24 GB RTX 4090 in Kubernetes, where it helped cap the card at 116K.

The 3 tokens per second scare

My very first benchmark request came back at 3.0 tokens per second. Since this GPU should push well over 100 t/s, I immediately assumed some layers had quietly spilled over to the CPU.

Fortunately, that was not what happened. ollama ps still showed 100% GPU, and the next two requests came back at 129.6 and 126.8 t/s. The first request after loading a model pays a one-time warmup cost for CUDA initialization and speculative-decoding setup. Because that test only generated 17 tokens, the warmup time completely skewed the average. If you are benchmarking Ollama, always throw away the first run.

Benchmarks

All of these runs used the 256K alias with the q8_0 KV cache and thinking disabled, on an already-warm model.

Short prompts: A three-paragraph response generated at around 127–130 t/s. Speculative decoding helped a lot here; the logs showed roughly 40% draft acceptance, averaging 2.6 tokens accepted per draft. With all 27B parameters active on every token, generation speed is mostly bottlenecked by memory bandwidth, and MTP helps work around that by verifying multiple tokens in a single pass over the weights.

Long prompt: To make sure the model could actually use the context window, I concatenated a bunch of Python source files into a 103,848-token prompt and asked for the very first file path listed in it:

prompt tokens: 103848   prefill t/s: 2119.9   prefill s: 49.0
decode t/s: 108.6
answer: The very first file path listed is `/usr/lib/python3.15/site-packages/OpenSSL/SSL.py`. ...
  • Prefill: about 2,100 tokens per second, so a 100K-token prompt takes just under a minute before the first output token shows up.
  • Generation: about 109 t/s even with that much context loaded.
  • Recall: the model accurately pulled a detail from the very beginning of the prompt.
  • VRAM: stayed steady at 28.8 GiB.

OpenCode: For the final test, I wanted to see the coding agent itself in action. I created a tiny Python file with an obvious bug and ran OpenCode non-interactively:

printf 'def add(a, b):\n    return a - b\n' > calc.py
opencode run "Read calc.py and fix the bug in it. Reply with one sentence."
→ Read calc.py
← Edit calc.py
-    return a - b
+    return a + b

Fixed the bug in `add()` at calc.py:2, which was subtracting instead of adding.

OpenCode read the file, made the edit, and stopped cleanly. In last year’s post, the model stumbled trying to call a git tool that did not exist before eventually falling back to bash. This time it picked the right tools on the first try.

Putting 256K to work: building a VRAM dashboard

A two-line bug fix only shows that tool calling works. To test whether a 256K context window actually helps on real work, I gave OpenCode an empty folder and a bigger assignment: build a Python terminal dashboard that checks my GPU and Ollama setup, calculates how much VRAM different models need at context sizes from 16K to 256K, writes a test suite, and verifies itself live against the RTX 5090.

I sent the prompt and did not touch the session again until it finished.

Metric Result
Runtime 13m 37s (hands-off, single session)
Context used 66.5K tokens (25% of 256K; no compaction)
Code written 2,137 lines across 10 files (app code and tests)
Test suite 62 / 62 tests passing

Using 66.5K tokens without hitting any limit is the main takeaway. Last year’s 16K setup would have started forgetting or compacting its own files a quarter of the way through this build. With 256K available, OpenCode kept the entire project, its tests, and live command output in memory at once.

The best part was watching it test and debug its own work. When OpenCode ran the dashboard against the real Ollama service on my GPU, it hit several real snags and fixed them without any nudging:

  • It caught and fixed code that relied on older options from the terminal UI library.
  • It reworked how it read Ollama’s text output after multi-word values like 100% GPU broke its column parsing.
  • It stopped misreading a model’s bundled vision adapter as the main model, and fixed a bug where 27.3B parameters was being treated as a byte count.
  • It added a “total VRAM” view after noticing that checking against currently free memory while Qwen3.8 was already loaded made every single option look out of memory.

Here is what the finished dashboard looks like running on my workstation:

┌─ OLLAMA-VRAM // GPU STATUS ────────────────────────────────────────────────────────────────────────────────┐
│ GPU 0  NVIDIA GeForce RTX 5090   ████████████████████████████████░░░░  used 28.3 GiB · free 3.2 GiB ·      │
│ total 31.8 GiB                                                                                             │
│ LOADED  qwen3.8:27b-256k   19 GB   100% GPU   ctx 262144   llamacpp   13 minutes from now                  │
└────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
┌─ MODEL ────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ MODEL     qwen3.8:27b-256k                                                                                 │
│ arch qwen35   27.3B params   quant Q4_K_M   ctx cap 262144                                                 │
│ attention  hybrid 17/65 full-attn · 48 SSM · kv 4×256                                                      │
│ recurrent state  0.1 GiB (fixed, context-free)                                                             │
└────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
┌─ CONTEXT MATRIX // qwen3.8:27b-256k ───────────────────────────────────────────────────────────────────────┐
│ ┌───────┬──────────────┬──────────────┬──────────────┬──────────────┬──────────────┬───────────┐           │
│ │cache  │          16K │          32K │          64K │         128K │         256K │    MAX-FIT│           │
│ ├───────┼──────────────┼──────────────┼──────────────┼──────────────┼──────────────┼───────────┤           │
│ │f16    │ [ OK ] 19.2G │ [ OK ] 20.2G │ [ OK ] 22.3G │ [ OK ] 26.6G │ [OOM ] 35.1G │     207.1K│           │
│ │q8_0   │ [ OK ] 18.6G │ [ OK ] 19.2G │ [ OK ] 20.2G │ [ OK ] 22.3G │ [ OK ] 26.6G │ 256K (cap)│           │
│ │q4_0   │ [ OK ] 18.4G │ [ OK ] 18.6G │ [ OK ] 19.2G │ [ OK ] 20.2G │ [ OK ] 22.3G │ 256K (cap)│           │
│ └───────┴──────────────┴──────────────┴──────────────┴──────────────┴──────────────┴───────────┘           │
│                                                                                                            │
│ total = weights + kv + state + overhead   GiB per cell   (budget: total VRAM)                              │
│ weights 17.0 GiB · state 0.1 GiB · overhead 1.0 GiB · total 31.8 GiB                                       │
│                                                                                                            │
│ [ OK ] fits with headroom   [WARN] < 2 GiB headroom   [OOM ] spills to CPU                                 │
└────────────────────────────────────────────────────────────────────────────────────────────────────────────┘

It was not spotless, and a couple of rough edges still needed a human look:

  • Awkward default: By default, the tool still checks against currently free GPU memory. If you inspect a model that is already loaded, every cell shows out of memory unless you explicitly tell it to check against total VRAM instead.
  • Estimates come up a little short: The table predicts 26.6 GiB for 256K with q8_0 right underneath the live status bar showing 28.3 GiB actually in use. Its formula missed some of Qwen3.8’s extra overhead, like the hidden draft cache and compute buffers I saw in the logs earlier.

Even with those two caveats, going from an empty folder to a working, tested 2,100-line Python tool in under 14 minutes, completely offline on a single GPU, is a big step up from where local coding agents were a year ago.

What I learned

  • Check the model metadata before sizing anything. Seeing full_attention_interval 4 turned what I assumed was a 64 GiB cache problem into a 16 GiB one, and q8_0 brought that down to 8.5 GiB. Relying on a dense-model rule of thumb would have kept me stuck at 64K.
  • Measure two points, then extrapolate. Loading a model at 64K and 128K with a per-request num_ctx only takes a minute, and the systemd journal gives you the exact per-token cache cost.
  • Watch out for caches that ignore your settings. The MTP draft cache stays at f16 and scales with context length, which adds an extra gigabyte at 256K that is easy to miss in a quick estimate.
  • Bake the context window into a Modelfile alias for OpenCode. Because the OpenAI-compatible endpoint cannot pass num_ctx, the alias is what actually enforces the window size.
  • Match limit.context in OpenCode to your Modelfile. That way the client and server agree on how much room is available before compaction needs to kick in.
  • Avoid a global context length if you host multiple models of different sizes on the same Ollama server.
  • Trust ollama ps and nvidia-smi instead of your first benchmark. Confirm you are at 100% GPU and discard the warmup run.

Closing thoughts

At the end of last year’s post, I wrote that local models were useful for simple scripts and small apps that do not require massive context. On this hardware, at least the context part of that statement no longer holds up. A 27B local model can now match the context window of many hosted models, run at an interactive speed, and keep every token on my local network.

Fitting 256K in VRAM does not guarantee the model can reason across all 256K as well as a frontier model. The VRAM dashboard build showed it can stay coherent past 66K tokens on a multi-file task, and pushing it harder in my Matrix evaluation will be the next step.

These open-weight models are improving over time but not as quickly as the models coming from the labs like Anthropic and OpenAI. As far as my homelab goes, I finally feel like the local models are smart enough to do boring stuff like update all the dependencies across half a dozen systems. My time is the most valuable commodity these days so there is no way I am going to suffer through doing real work with a model like this. I am excited for the next year and I hope that soon we can have capable models that run even on a modest laptop.

Sources