The 146-second wait in my first RTX Spark post was the cost of a brand-new 100K-token prompt. A conversation doesn't work like that: each turn adds a few thousand tokens to a history Ollama has already read. So I measured the thing people actually do. Ten turns of about 5,000 tokens each, and the tenth turn, with 50,375 tokens of history, produced its first token in 5.3 seconds. The same conversation sent cold took 49.4 seconds.
The second test is the one every tokens-per-second post skips: does the code run? I took the three code prompts from the first post, gave the model room for a complete answer, and put the replies through the real tools. All three passed: ten pytest tests including two threading tests for the Python LRU cache, tsc --strict plus a timing check for the TypeScript token bucket, and go vet, go build and a run with hand-checked distances for Dijkstra in Go.
The growing chat
The script holds one conversation open against /api/chat. Every turn appends a fresh ~5K-token slice of text (PowerShell's own module files, as in the earlier posts) and asks a two-sentence question about it; the reply is kept in the history. After ten turns it unloads the model, changes the first line so the prefix cache can't match, and sends the whole conversation again.
| Model | qwen3-coder:30b, Q4_K_M, Ollama 0.40.11, f16 cache, 102,400-token context, all on the GPU |
| Turns | 10, each adding 4,400–5,700 tokens of new text plus a question; 128-token replies, temperature 0 |
| Cold run | The same 10-turn history with a new session line and one more question, after keep_alive: 0
|
| Machine | Surface Laptop Ultra, RTX Spark N1X, 64 GB; AC power, Balanced plan, 27 Oct 2026 |
| Turn | Prompt | New tokens | First token | New tokens read per second | Decode |
|---|---|---|---|---|---|
| 1 | 4,772 | 4,772 | 2.1 s | 2,262 | 71.7 tok/s |
| 2 | 9,218 | 4,446 | 2.4 s | 1,884 | 61.2 |
| 3 | 14,163 | 4,945 | 2.7 s | 1,805 | 60.4 |
| 4 | 19,878 | 5,715 | 3.4 s | 1,686 | 50.0 |
| 5 | 25,531 | 5,653 | 4.9 s | 1,161 | 45.5 |
| 6 | 30,537 | 5,006 | 4.1 s | 1,215 | 45.0 |
| 7 | 35,810 | 5,273 | 4.4 s | 1,201 | 41.1 |
| 8 | 40,617 | 4,807 | 4.5 s | 1,068 | 38.3 |
| 9 | 45,609 | 4,992 | 5.0 s | 992 | 36.0 |
| 10 | 50,375 | 4,766 | 5.3 s | 904 | 33.2 |
| Cold | 50,473 | 50,473 | 49.4 s | 1,022 | 29.7 |
Three things in that table:
The cache pays for the history, not the new text. The ten cached first-token waits add up to 38.8 seconds, less than the single cold resend of the final conversation. Each turn only reads what was added since the last one.
New tokens get slower to read as the history grows. Turn 1 read its 4,772 tokens at 2,262 a second; turn 10 read 4,766 at 904. The new tokens attend over everything before them, so reading 5K tokens at the end of a 45K history costs 2.5 times what it did at the start. That is the same slowdown the cold prefill shows between 1K and 57K tokens (2,433 to 1,149 tokens a second in the curve post), just arriving a turn at a time.
Decode doesn't care about the cache. Turn 10 replied at 33.2 tokens a second with a warm cache; the cold run of the same 50K tokens replied at 29.7. The curve post's line, 11.8 ms + 0.39 ms per 1,000 tokens, predicts 31.8 at 50K. Every reply token reads the whole cache whether the prefill was cached or not.
One thing to know about Ollama's numbers: on a cached turn, prompt_eval_count still reports the whole prompt, 50,375 tokens at turn 10, while prompt_eval_duration covers only the new part. Divide one by the other and you get a flattering 9,573 tokens a second. Time to first token is the number that means something; the "new tokens" column is the difference between consecutive turns.
Does the code compile?
The first post timed three code prompts with a 512-token cap, enough to measure decode speed and not enough for a complete answer. This time the cap was 3,072 tokens and the replies were checked.
| Prompt | Reply | Code checked | Check | Result |
|---|---|---|---|---|
| A thread-safe LRU cache in Python with unit tests | 2,634 tokens, 87.5 tok/s | 348 lines | pytest |
10 passed, including test_thread_safety (five threads, ten put/get pairs each) and test_concurrent_operations (five tasks of 100 mixed operations over 50 keys) |
| A token-bucket rate limiter in TypeScript | 1,119 tokens, 88.3 tok/s | 143 lines |
tsc --noEmit --strict, then a timing test |
Compiles. Burst of 5 allows exactly 5 of 8 requests; about 3 tokens back after 300 ms at 10/s; the bucket caps at capacity after 1.5 s idle |
| Dijkstra's shortest-path algorithm in Go | 2,142 tokens, 83.2 tok/s | 250 lines |
go vet, go build, run |
Builds and runs. Distances 0, 4, 2, 9, 11, 14 from vertex 0 on its six-node example; I checked them by hand |
The checks ran on a Linux box with Python 3.13, pytest 9, TypeScript 7.0 on Node 22 and Go 1.24, because the laptop has Python but no pytest, Node or Go. The generation ran on the laptop; only the compile and test steps moved.
Three notes from reading the code, since passing proves less than it sounds:
- The Python cache uses an
OrderedDictbehind anRLock, which is the textbook answer. The two threading tests check that nothing crashes and the size ends at, or stays under, the capacity of 3 after concurrent puts and gets; they don't try to catch a lost update, which is the bug a lock is there for. - The Go implementation is the O(V²) array scan, not the heap version. Correct, and what the prompt asked for; it would be the wrong choice for a large sparse graph, and the reply says so in its own complexity note.
- The TypeScript limiter takes its fill rate per millisecond, and one of its own usage comments gets that wrong (
1 / 1000is described as one token per millisecond; it is one per second). The code is right, the comment isn't.
One lesson for anyone wiring a local model into a harness: the replies don't stop at the code. The Go answer ends with its sample output in an untagged fence; my first extractor accepted untagged blocks, glued that output onto main.go, and the build failed on line 252 with a syntax error that had nothing to do with the model. The TypeScript answer ends with a nine-line usage snippet in a second typescript fence, which the fixed extractor still appends; it happens to compile, but it is not part of the module. Take the first block tagged with the language, or ask for one file and nothing else.
What it means
- Count turns, not tokens, for an interactive session. With the history cached, each turn costs about a second per 1,000 new tokens at the start and about five seconds per 5K by the time the conversation is 50K long. The 146-second wait only happens when the whole context is new: a restart, a different model, or a tool that rewrites the start of the prompt.
- Keep the start of the prompt stable. The cache matches a prefix. A system prompt with a timestamp, or an agent that reorders earlier messages, turns every turn into the cold case.
- Decode speed follows the context, warm or cold. Plan on 30 tokens a second at 50K and 20 at 100K with an f16 cache on this chip, as the curve post measured.
- Check the code, not the speed. At Q4_K_M, qwen3-coder:30b produced working code in three languages on the first try. Whether that holds for harder prompts is a different test; this one says the quantization isn't the thing breaking your build.
Script notes
Both scripts are at the end of the post. Two bugs cost me a run each, and both are in the fixed versions:
-
Measureis a built-in alias forMeasure-Object, and PowerShell resolves aliases before functions, so myMeasurefunction was never called. The function is nowMeasure-Turn. - Ollama's
prompt_eval_countincludes the cached prefix, so a running total of it over ten turns adds up to a 277K-token conversation that never existed. The script now reports the prompt size per turn and the new tokens as the difference.
The code check needs python with pytest, node and go on the PATH; it skips a language whose tools are missing and says so, rather than reporting a failure that belongs to the toolchain.
Sources
- Qwen3-Coder 30B on a Surface Laptop Ultra: run it on RTX Spark with Ollama, the first post, 26 Oct 2026
- Quantizing the KV cache in Ollama on RTX Spark: half the memory, a third slower, the second post, 27 Oct 2026
- Every 1,000 tokens of context costs 0.39 ms: decode speed from 1K to 100K on RTX Spark, the third post, 27 Oct 2026
- My runs of
growing-chat.ps1andcode-check.ps1on 27 Oct 2026, with the per-turn JSON, the three replies and the tool output
growing-chat.ps1
# The growing chat: does Ollama's prefix cache make turn 10 of a 50K-token conversation cheap?
# Each turn appends a ~5K-token slice of text plus a question to the same conversation, via /api/chat.
# Per turn it records the prompt size, the time to first token and the decode speed. At the end it sends the
# whole conversation cold (new session line, model reloaded) so cached turn N sits next to the uncached cost.
# Note: Ollama's prompt_eval_count is the whole prompt, cached or not, so prefill tok/s from it is not meaningful
# on cached turns; time to first token is the honest measure. new_tokens is the difference between turns.
# Writes growing-chat-<COMPUTER>-<kv>-<stamp>.json and .csv in the current directory.
param(
[string]$Model = 'qwen3-coder:30b',
[int]$Turns = 10,
[int]$TokensPerTurn = 5000,
[int]$NumCtx = 102400,
[int]$Reply = 128,
[string]$Api = 'http://localhost:11434'
)
$ErrorActionPreference = 'Stop'
$kvType = if ($env:OLLAMA_KV_CACHE_TYPE) { $env:OLLAMA_KV_CACHE_TYPE } else { 'f16' }
function Post-Ollama($path, $body) {
Invoke-RestMethod -Method Post -Uri ($Api + $path) -ContentType 'application/json' -Body ($body | ConvertTo-Json -Depth 10) -TimeoutSec 1800
}
function Unload-All {
foreach ($m in @((Invoke-RestMethod ($Api + '/api/ps')).models)) { Post-Ollama '/api/generate' @{ model = $m.name; keep_alive = 0 } | Out-Null }
Start-Sleep 3
}
$caps = @((Post-Ollama '/api/show' @{ model = $Model }).capabilities)
function Chat($messages, $n) {
$b = @{ model = $Model; messages = $messages; stream = $false; keep_alive = '15m'; options = @{ num_ctx = $NumCtx; num_predict = $n; temperature = 0; seed = 42 } }
if ($caps -contains 'thinking') { $b.think = $false }
$sw = [Diagnostics.Stopwatch]::StartNew(); $r = Post-Ollama '/api/chat' $b; $sw.Stop()
return $r, $sw.Elapsed.TotalSeconds
}
function Measure-Turn($r, $wall, $turn, $label, $contextTokens) {
[pscustomobject][ordered]@{
turn = $turn
label = $label
prompt_tokens = $r.prompt_eval_count # the whole prompt, cached part included
new_tokens = $r.prompt_eval_count - $contextTokens
first_token_s = [math]::Round(($r.load_duration + $r.prompt_eval_duration) / 1e9, 2)
new_tok_per_s = if ($r.prompt_eval_duration) { [math]::Round(($r.prompt_eval_count - $contextTokens) / ($r.prompt_eval_duration / 1e9), 0) } else { $null }
decode_tok_s = [math]::Round($r.eval_count / ($r.eval_duration / 1e9), 1)
output_tokens = $r.eval_count
wall_s = [math]::Round($wall, 1)
}
}
# Text slices from PowerShell's own files; each turn gets a different slice so nothing repeats
$corpus = (Get-ChildItem "$env:windir\System32\WindowsPowerShell\v1.0" -Recurse -File -Include *.ps1xml, *.psm1, *.psd1 -ErrorAction SilentlyContinue |
Sort-Object FullName | ForEach-Object { "`n### FILE: $($_.Name)`n" + [IO.File]::ReadAllText($_.FullName) }) -join ''
while ($corpus.Length -lt $NumCtx * 5) { $corpus += $corpus }
$stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$base = Join-Path (Get-Location) "growing-chat-$env:COMPUTERNAME-$kvType-$stamp"
$rows = @()
try {
Write-Host "=== $Model, $Turns turns x ~$TokensPerTurn tokens, num_ctx $NumCtx, KV cache $kvType ==="
Unload-All
Chat @(@{ role = 'user'; content = 'Reply with exactly: warm' }) 8 | Out-Null
# Calibrate characters per token
$sample = $corpus.Substring(0, 200000)
$r, $w = Chat @(@{ role = 'user'; content = "Calibration $(Get-Random)`n$sample" }) 1
$charsPerToken = $sample.Length / $r.prompt_eval_count
$chars = [int]($TokensPerTurn * $charsPerToken)
Write-Host ("calibration: {0:N2} chars/token" -f $charsPerToken)
Unload-All; Chat @(@{ role = 'user'; content = 'Reply with exactly: warm' }) 8 | Out-Null
$messages = @(@{ role = 'system'; content = "Session $([guid]::NewGuid()). You are reviewing PowerShell source files one batch at a time." })
$contextTokens = 0 # prompt size of the previous turn, so new_tokens can be derived
for ($t = 1; $t -le $Turns; $t++) {
$slice = $corpus.Substring(($t - 1) * $chars, $chars)
$messages += @{ role = 'user'; content = "Batch ${t}:`n$slice`n`nIn two sentences, what does batch $t define?" }
$r, $w = Chat $messages $Reply
$row = Measure-Turn $r $w $t 'cached' $contextTokens
$messages += @{ role = 'assistant'; content = $r.message.content }
$contextTokens = $r.prompt_eval_count
$rows += $row
Write-Host (" turn {0,2}: prompt {1,6} tokens ({2,5} new), first token {3,6} s, decode {4,5} tok/s" -f $t, $row.prompt_tokens, $row.new_tokens, $row.first_token_s, $row.decode_tok_s)
Start-Sleep 2
}
$totalContext = $contextTokens
# Cold comparison: the same final conversation, new session line, after unloading the model
Write-Host " cold: resending the full $totalContext-token conversation with a fresh session line"
Unload-All
Chat @(@{ role = 'user'; content = 'Reply with exactly: warm' }) 8 | Out-Null
$cold = @($messages | ForEach-Object { $_ })
$cold[0] = @{ role = 'system'; content = "Session $([guid]::NewGuid()). You are reviewing PowerShell source files one batch at a time." }
$cold += @{ role = 'user'; content = 'In two sentences, what did the last batch define?' }
$r, $w = Chat $cold $Reply
$coldRow = Measure-Turn $r $w ($Turns + 1) 'cold' 0
$rows += $coldRow
Write-Host (" cold: prompt {0,6} tokens, first token {1,6} s, decode {2,5} tok/s" -f $coldRow.prompt_tokens, $coldRow.first_token_s, $coldRow.decode_tok_s)
}
finally { Unload-All }
$out = [ordered]@{
computer = $env:COMPUTERNAME; date = (Get-Date).ToString('s')
model = $Model; num_ctx = $NumCtx; turns = $Turns; tokens_per_turn = $TokensPerTurn; reply_tokens = $Reply
ollama_version = (Invoke-RestMethod ($Api + '/api/version')).version
kv_cache_type = $kvType; flash_attention = $env:OLLAMA_FLASH_ATTENTION
rows = $rows
}
[IO.File]::WriteAllText("$base.json", ($out | ConvertTo-Json -Depth 8), (New-Object Text.UTF8Encoding $false))
$rows | Export-Csv "$base.csv" -NoTypeInformation
$rows | Format-Table turn, label, prompt_tokens, new_tokens, first_token_s, new_tok_per_s, decode_tok_s -AutoSize | Out-String | Write-Host
Write-Host "Results: $base.json / $base.csv"
code-check.ps1
# Does the code the laptop writes actually run?
# Re-sends the three code prompts from speed-bench.ps1 to each model, extracts the code blocks from the reply,
# and runs them through the real toolchain: pytest for Python, tsc --strict for TypeScript, go vet + go build for Go.
# Needs on PATH: python (with pytest installed), node/npx, go.
# Writes code-check-<COMPUTER>-<stamp>.json plus a folder per model with the generated files and tool output.
param(
[string[]]$Models = @('qwen3-coder:30b'), # add a Q8 tag, e.g. 'qwen3-coder:30b-a3b-q8_0', to compare quantizations
[int]$Reply = 3072, # 512 was enough for speed; a complete answer with tests needs more room
[int]$NumCtx = 16384,
[string]$Api = 'http://localhost:11434'
)
$ErrorActionPreference = 'Stop'
$tasks = @(
@{ name = 'python-lru'; lang = 'python'; file = 'test_lru_cache.py'
prompt = 'Write a thread-safe LRU cache in Python with unit tests.' }
@{ name = 'ts-token-bucket'; lang = 'typescript'; file = 'rate-limiter.ts'
prompt = 'Write a token-bucket rate limiter in TypeScript.' }
@{ name = 'go-dijkstra'; lang = 'go'; file = 'main.go'
prompt = "Implement Dijkstra's shortest-path algorithm in Go." }
)
function Post-Ollama($path, $body) {
Invoke-RestMethod -Method Post -Uri ($Api + $path) -ContentType 'application/json' -Body ($body | ConvertTo-Json -Depth 8) -TimeoutSec 1800
}
function Unload-All {
foreach ($m in @((Invoke-RestMethod ($Api + '/api/ps')).models)) { Post-Ollama '/api/generate' @{ model = $m.name; keep_alive = 0 } | Out-Null }
Start-Sleep 3
}
# Pull the fenced code blocks tagged with the language, in order, joined with blank lines.
# Untagged blocks are used only when no tagged block exists: models put sample output and usage snippets in
# untagged fences after the code, and gluing those onto a Go file breaks the build.
function Extract-Code($text, $lang) {
$tags = switch ($lang) { 'python' { 'python|py' } 'typescript' { 'typescript|ts' } 'go' { 'go|golang' } }
$all = [regex]::Matches($text, '(?ms)^```
[ \t]*(\w*)[^\n]*\n(.*?)(?:^
```|\z)')
$tagged = @($all | Where-Object { $_.Groups[1].Value -match "^($tags)$" })
if (-not $tagged) { $tagged = @($all | Where-Object { $_.Groups[1].Value -eq '' }) }
if (-not $tagged) { return $null }
(($tagged | ForEach-Object { $_.Groups[2].Value.TrimEnd() }) -join "`n`n")
}
function Run-Tool($dir, $cmd, $args) {
Push-Location $dir
try {
$output = & $cmd @args 2>&1 | Out-String
[pscustomobject]@{ command = "$cmd $($args -join ' ')"; exit_code = $LASTEXITCODE; output = $output.Trim() }
} finally { Pop-Location }
}
$have = @{}
foreach ($c in 'python', 'npx', 'go') { $have[$c] = [bool](Get-Command $c -ErrorAction SilentlyContinue) }
Write-Host ("toolchain: python={0} npx={1} go={2}" -f $have.python, $have.npx, $have.go)
$stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$root = Join-Path (Get-Location) "code-check-$env:COMPUTERNAME-$stamp"
New-Item -ItemType Directory -Path $root | Out-Null
$results = @()
try {
foreach ($model in $Models) {
Write-Host "=== $model ==="
Unload-All
$caps = @((Post-Ollama '/api/show' @{ model = $model }).capabilities)
$modelDir = Join-Path $root ($model -replace '[:/]', '-')
New-Item -ItemType Directory -Path $modelDir | Out-Null
foreach ($t in $tasks) {
$dir = Join-Path $modelDir $t.name
New-Item -ItemType Directory -Path $dir | Out-Null
$b = @{ model = $model; prompt = $t.prompt; stream = $false; keep_alive = '15m'; options = @{ num_ctx = $NumCtx; num_predict = $Reply; temperature = 0; seed = 42 } }
if ($caps -contains 'thinking') { $b.think = $false }
$sw = [Diagnostics.Stopwatch]::StartNew(); $r = Post-Ollama '/api/generate' $b; $sw.Stop()
[IO.File]::WriteAllText((Join-Path $dir 'reply.md'), $r.response, (New-Object Text.UTF8Encoding $false))
$code = Extract-Code $r.response $t.lang
$res = [ordered]@{
model = $model; task = $t.name; language = $t.lang
output_tokens = $r.eval_count; done_reason = $r.done_reason; decode_tok_s = [math]::Round($r.eval_count / ($r.eval_duration / 1e9), 1)
code_blocks_found = [bool]$code; code_lines = if ($code) { ($code -split "`n").Count } else { 0 }
checks = @(); passed = $false; skipped = $null
}
if ($r.done_reason -eq 'length') { Write-Warning " $($t.name): reply hit the $Reply-token limit; the code may be cut off" }
if (-not $code) { Write-Warning " $($t.name): no code block found"; $results += [pscustomobject]$res; continue }
[IO.File]::WriteAllText((Join-Path $dir $t.file), $code + "`n", (New-Object Text.UTF8Encoding $false))
try {
switch ($t.lang) {
'python' {
if (-not $have.python) { $res.skipped = 'python not on PATH'; break }
$res.checks += Run-Tool $dir 'python' @('-m', 'pytest', '-q', $t.file)
$res.passed = $res.checks[-1].exit_code -eq 0
}
'typescript' {
if (-not $have.npx) { $res.skipped = 'node/npx not on PATH'; break }
$res.checks += Run-Tool $dir 'npx' @('-y', '-p', 'typescript', 'tsc', '--noEmit', '--strict', '--target', 'es2020', $t.file)
$res.passed = $res.checks[-1].exit_code -eq 0
}
'go' {
if (-not $have.go) { $res.skipped = 'go not on PATH'; break }
Run-Tool $dir 'go' @('mod', 'init', 'codecheck') | Out-Null
$res.checks += Run-Tool $dir 'go' @('vet', './...')
$res.checks += Run-Tool $dir 'go' @('build', './...')
$res.passed = ($res.checks | Where-Object exit_code -ne 0).Count -eq 0
}
}
} catch { $res.checks += [pscustomobject]@{ command = 'toolchain'; exit_code = -1; output = "$_" } }
# Keep the tool output next to the code for the post
($res.checks | ForEach-Object { "> $($_.command)`nexit $($_.exit_code)`n$($_.output)`n" }) -join "`n" | Set-Content (Join-Path $dir 'check.log')
$verdict = if ($res.skipped) { "SKIP ($($res.skipped))" } elseif ($res.passed) { 'PASS' } else { 'FAIL' }
Write-Host (" {0,-16} {1} ({2} tokens, {3} lines, {4} tok/s)" -f $t.name, $verdict, $res.output_tokens, $res.code_lines, $res.decode_tok_s)
$results += [pscustomobject]$res
}
}
}
finally { Unload-All }
$out = [ordered]@{
computer = $env:COMPUTERNAME; date = (Get-Date).ToString('s')
ollama_version = (Invoke-RestMethod ($Api + '/api/version')).version
reply_tokens = $Reply
toolchain = [ordered]@{
python = if ($have.python) { (& python --version 2>&1 | Out-String).Trim() } else { 'missing' }
pytest = if ($have.python) { (& python -m pytest --version 2>&1 | Out-String).Trim() } else { 'missing' }
node = if ($have.npx) { (& node --version 2>&1 | Out-String).Trim() } else { 'missing' }
go = if ($have.go) { (& go version 2>&1 | Out-String).Trim() } else { 'missing' }
}
results = $results
}
[IO.File]::WriteAllText((Join-Path $root 'code-check.json'), ($out | ConvertTo-Json -Depth 8), (New-Object Text.UTF8Encoding $false))
$results | Format-Table model, task, passed, skipped, done_reason, output_tokens, code_lines -AutoSize | Out-String | Write-Host
Write-Host "Results and generated code: $root"

Top comments (1)
the prompt_eval_count line is the one i'd put on a sticker. it's the reason a lot of "look how fast ollama is" numbers are fiction — on a cached turn the count is the whole 50k but the duration is only the new 4.7k, so dividing them hands you 9,573 tok/s that never happened. time to first token is the only number that survives contact with a real conversation.
the "keep the start of the prompt stable" rule is the part that's going to bite people who wire this into an agent. most agent harnesses stamp a timestamp or re-sort the message list on every call, which silently turns every turn into the 49.4s cold case and the author would never know why their "fast" model got slow.
one thing i'd push on: warm 33.2 vs cold 29.7 decode is a 12% gap on the same 50k. is that within run-to-run noise on the N1X, or is the cached kv layout actually keeping decode a bit faster? curious whether the f16 vs q8 kv type moves that gap.