2.7x faster Qwen on an 8 GB RTX 4060
A custom CUDA runtime for Qwen3.8 9B that decodes 2.7x faster than llama.cpp on an 8 GB RTX 4060, with the same output, and an 8-bit KV cache that doubles the context window.
- Kind
- Write-up
- Published
- Dec 2, 2026
- Read
- 12 min
- Tags
- CUDA / Inference / Qwen
TL;DR
- Why bother? Local coding models on consumer GPUs feel slow, and llama.cpp tops out at 44 tok/s on my 8 GB RTX 4060.
- What I built: qwen-coder-kernel, a custom CUDA runtime for Qwen3.8 9B, with an OpenAI-compatible server so it plugs straight into OpenCode.
- How it works: Three methods. Kernels that run at the card's memory bandwidth limit, speculative decoding that checks up to 12 tokens at once, and a prefix cache so agent steps only process what's new.
- Result: 2.7x decode speed vs llama.cpp (119 tok/s vs 44), up to 352 tok/s on code edits, with exactly the same output.
- Bonus: An 8-bit KV cache that's 47% smaller, which doubles the context window from 40k to 80k tokens on the same 8 GB card.
Intro
As a software engineer, most of my time with LLMs has been spent on the application side: prompting them, wrapping them in pipelines, and wiring them into agents. I'd always treated the model itself as a black box that takes text in and gives tokens back. At the same time, I'd been running a local coding model in OpenCode on my own PC, and honestly, it felt slow.
That changed at the Pillars Engineering Inference with Ihsaan workshop. I walked in thinking of inference as "call the model, get tokens back." I walked out realizing that every token is a hardware problem: how many bytes you move, how often, and how much of the GPU sits idle while you do it.
So I set myself a challenge: get the most out of the graphics card already sitting in my PC, without buying new hardware or swapping the model. What started as a small experiment turned into qwen-coder-kernel, a custom CUDA runtime that runs a 9B Qwen coding model 2.7x faster than llama.cpp on an 8 GB RTX 4060, with output that matches token for token.
1. The setup
Here's what I was working with. My baseline was llama.cpp, the go-to tool for running models locally, which generated 44 tokens per second (tok/s) on my card.
| GPU | NVIDIA RTX 4060, 8 GB of memory |
| Model | Qwen3.8 9B, compressed to 4-bit (5.78 GB) |
| Coding tool | OpenCode, connected through a small server I wrote |
| Baseline | llama.cpp at 44 tok/s |
Two rules shaped everything:
- 8 GB is tight: The model alone fills most of the card, leaving very little room for anything extra.
- Same output, guaranteed: Every speedup had to produce exactly the same text as running the model the normal way. Faster, not different.
One quirk of this model comes up later. Most of its layers keep a running "memory" that updates with every token, instead of the usual list of past tokens. That makes long prompts cheap, but it also means you can't just undo the last few tokens by deleting them.
2. Why is decode even slow?
This was the biggest idea I took from the workshop. To generate one token, the GPU has to read every weight in the model from memory, about 4.9 GB for this model. My card can move roughly 246 GB per second, so no matter how clever the code is, one token takes at least ~20 ms. That works out to a ceiling of about 45 tok/s.
So llama.cpp's 44 tok/s was already right at the limit. When I profiled a single step, over 90% of the time was spent just reading weights. The actual math was almost free.
Think of it like a delivery truck that has to drive the whole route for every single package. Driving faster only helps so much. That leaves two real options:
- Make every trip as fast as the road allows (Method 1)
- Carry more packages per trip (Method 2)
The third method came from looking at how a coding agent actually uses the model, and realizing it kept making the same trip over and over (Method 3).
3. Method 1: kernels that hit the bandwidth floor
A kernel is just a small program that runs on the GPU. I wrote my own for every step of the model, with one goal: make each trip through the weights as close to that ~20 ms limit as possible.
The main tricks:
- Keep the weights compressed: The model is stored in 4-bit form. Instead of unpacking it into a bigger format first, my kernels work on the compressed numbers directly, so there's less data to move.
- Cut the overhead between steps: One token involves dozens of small GPU jobs. I record them once and replay the whole sequence in one go (a feature called CUDA graphs), so the GPU isn't waiting around between jobs.
- Combine small steps: Where two steps happen back to back, I merge them into one, so the data doesn't make an extra round trip through memory.
That got me to 46 tok/s, slightly ahead of llama.cpp. Not a huge jump on its own, but it meant every trip was now running at the speed limit. Reading the prompt also got a separate set of kernels built for processing many tokens at once, which made it over 20x faster than going one token at a time.
The real point of Method 1 is to make one trip as cheap as possible, so that Method 2 can make every trip count for more.
4. Method 2: enter speculative decoding
This is where the 2.7x comes from. If every trip costs the same ~20 ms, the trick is to carry more tokens per trip. Checking 4 tokens in one pass costs about the same as checking 1.
Each round, the model:
- Guesses the next few tokens using a fast, cheap method.
- Checks all the guesses at once with the full model, in a single trip through the weights.
- Keeps every guess up to the first wrong one, plus the full model's own answer at that spot.
Since the full model checks every token, the final text is exactly what it would have written on its own. Only the speed changes.
4.1 Two kinds of drafts
- A built-in guesser: This model ships with a small extra layer that predicts a few tokens ahead. It's cheap to run and already loaded, so it costs almost no extra memory.
- Copying from the prompt: Coding answers often repeat text from the prompt, like a function you asked it to refactor. If the last few tokens match something in the prompt, whatever came next there is a free guess. When this works, it can guess 10+ tokens in a row.
A small decision-maker picks whichever guesser has been working better, round by round.
4.2 The rollback problem
Remember that running "memory" from the setup? When a guess is wrong, the model has already absorbed it, and you can't just delete it. My fix was to have the checking step save a small checkpoint after each token, so a wrong guess simply rewinds to the last good checkpoint. No extra copying, no redoing work.
4.3 The bug that hid a 1.6x speedup
This one was my favourite to track down. On a "refactor this function" prompt, the exact same code ran at ~155 tok/s some runs and 250 tok/s others, with identical output.
The cause: the decision-maker started out assuming copying from the prompt would only be right 70% of the time, and it only updated that guess when it actually tried it. Meanwhile, the built-in guesser was right 90%+ of the time on code. So copying always looked worse, never got tried, and never got the chance to prove it was great for refactors.
The fix was to start it with a more optimistic guess and keep nudging it to try again every so often. Refactor jumped from ~155 to 250 tok/s, and later to 352. The best part: a bad guess can never change the output, only cost a little time.
5. Method 3: batched prefill and prefix caching
Fast token generation wasn't enough on its own, because a coding agent doesn't send one prompt. OpenCode sends a ~6,000-token set of instructions, then resends the entire conversation on every step: every tool call, file read and reply. If the model re-read all of that each time, the speedup from Methods 1 and 2 would disappear.
Two pieces fix this:
- Reading prompts in big batches: Instead of reading the prompt one token at a time, the model reads hundreds at once, which keeps the GPU fully busy. A 6,000-token prompt now loads in about 3 seconds.
- Remembering past work: As the model reads a conversation, it saves a checkpoint at the end of each message. On the next request, it picks up from the latest matching checkpoint and only reads what's new.
In a real OpenCode session ("fix two bugs in stats.py and run it"), the instructions were read once, every later step started in under half a second, and the whole task took 13.6 seconds from start to finish.
5.1 Doubling the context window with an 8-bit KV cache
Coding agents burn through context fast. A system prompt, a few files and some tool output can hit 40,000 tokens quickly, and on 8 GB that was my ceiling.
The culprit is the KV cache: the model's notes on every token it has already read, so it never has to reprocess them. Mine stored each value as a 16-bit number, which came to about 36 KB per token, or 1.4 GB at 40,000 tokens.
The fix was to store those notes as 8-bit numbers instead, with one small scale factor for every 32 values to keep them accurate. That makes the cache 47% smaller, so about 1.9x as many tokens fit in the same memory, and the model's weights don't change at all.
- Context window: 40,000 → 80,000 tokens, a 2x (+100%) increase on the same 8 GB card. I tested a 78,000-token prompt and still got a sensible answer at 57 tok/s.
- Speed: Unchanged. Decoding at long context is even slightly faster, since there's less cache to read.
- Accuracy: The model's scores line up with the 16-bit version almost exactly (0.9995 correlation), and its top pick for the next token was the same in every test I ran.
Since it's a tiny bit less exact than the 16-bit version, I've kept it as an opt-in setting (--kv8) until I've used it in more real coding sessions.
6. What the profiler taught me
The most surprising part of this project was how often my "obvious" fixes did nothing. The real wins almost always came from measuring first with a profiler (a tool that shows exactly where the GPU spends its time) and following what it said. A few examples:
- The GPU was running out of scratch space: Checking lots of guesses at once was slower than it should have been. I first tried cutting the math, which changed nothing. The real problem was a limit I'd set on each GPU thread's working memory. Raising it, plus letting one load of data serve several checks, made those checks up to 40% faster.
- Too much passing notes: One part of the model had GPU threads constantly passing numbers to each other, and that hand-off was the bottleneck, not the math. Reorganizing the work so they passed notes far less often made it 2.7x faster.
- Data traffic jams: The profiler showed some reads piling up on the same memory slots. Spreading them out cut that step's time by 30%.
Rules I'll keep using:
- Measure before you optimize. Several fixes that sounded great made no difference or made things worse.
- Test small pieces in isolation. Testing one kernel in seconds, without loading the whole 6 GB model, made trying ideas much faster.
- Compare fairly. Run old and new versions back to back on the same inputs. A warm GPU and changing test files both fooled me early on.
- Passing tests isn't proof. One bug still produced the right output for 24 tokens. Check that your tests actually fail when the code is broken.
7. Results
On six coding tasks, speculative decode runs at 100–352 tok/s against llama.cpp's 44. These are six coding chat requests over the repo's own source, from benchmarks/decode_bench.py.
| Task | Decode |
|---|---|
| Refactor a function (1,138 tokens) | 352 tok/s |
| Add comments, return the code (1,073) | 206 tok/s |
| Implement from a description (86) | 116 tok/s |
| Translate to Python (984) | 111 tok/s |
| Explain code (1,680) | 109 tok/s |
| Write tests (2,368) | 100 tok/s |
The biggest speedups show up when the answer copies code from the prompt, like refactoring, because the copying guesser can get long runs right. Tasks that write brand-new code, like tests, still land around 100 tok/s.
The 2.7x headline comes from my first head-to-head comparison against llama.cpp, before the later improvements:
| Task | llama.cpp | My kernel | Speedup |
|---|---|---|---|
| Write tests | 44 tok/s | 119 tok/s | 2.7x |
| Refactor | 44 tok/s | 127 tok/s | 2.9x |
| Explain code | 44 tok/s | 106 tok/s | 2.4x |
One honest caveat: llama.cpp still reads a brand-new prompt faster than mine does. That's exactly why the "remembering past work" piece of Method 3 matters so much for coding agents.
8. What's left
- Generating tokens: This is now within about 10% of the card's speed limit. Going faster would mean better guesses, not faster code.
- Reading prompts: There's still room here, maybe 20–35% faster with a bigger rewrite. For a coding agent that saves about a second per session, so I've left it for now.
- Longer conversations: The 8-bit KV cache from section 5.1 is opt-in for now. I want to run it through more real agent sessions before making it the default.
- Unlocking the tensor cores: GeForce cards run one kind of tensor-core math (16-bit inputs with 32-bit totals) at half speed. gpu-unlock is a Linux kernel module that lifts that cap, and it lists the RTX 4060 as experimental. It won't speed up generating tokens or my 8-bit matrix math, but my attention kernel uses exactly the capped math. At long context, attention is about 30% of reading a prompt chunk, so this could make long prompts up to ~15% faster. First I'd need to get the runtime building on Linux, since it's Windows-only today.
9. Closing thoughts
Before the workshop, I would have asked "how do I make this faster?" Now I ask three questions instead: what's the hardware limit, how close am I to it, and what does the workload actually do? For a coding agent, all three pointed to the same three levers: make each pass cheap, get more tokens out of each pass, and never read the same prompt twice. Proof that you don't always need a bigger GPU, just a better understanding of the one you have.
The code, benchmarks and the full optimization log are on GitHub. If you have an 8 GB NVIDIA card, it runs as a local provider for OpenCode, Continue or Aider, so give it a try.