The first decoder spawned OS threads for each of about 385 matrix-vector products per token, which made it slower with more threads (257 ms per token at 5 threads, 538 ms at 12). It now keeps a pool of parked workers; the products of a layer are grouped into four regions (QKV, output projection, expert gate+up, expert down) and participants claim row chunks from a shared counter, which suits the mixed fast and slow cores. Weights are referenced through shared handles into the mapped file so jobs are 'static. Adds a per-phase profile, a page pre-touch for the mapping, and a real-model runner option for it. Measured on the reference laptop (quiet machine, single runs, short context, NOT paired; indicative only): 120 to 160 ms per token at 5 to 10 threads cold, 115 ms (8.7 tokens/s) at 10 threads with pre-touched pages. Same 16 greedy tokens as llama.cpp. The synthetic end-to-end tests still match the independent f64 reference and give identical logits at every thread count. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
287 lines
15 KiB
PowerShell
287 lines
15 KiB
PowerShell
<#
|
|
.SYNOPSIS
|
|
Measures decode and prefill speed of a llama.cpp-style server (Bionic / LM Studio engines) on the reference laptop.
|
|
|
|
.DESCRIPTION
|
|
Baseline harness for STRA-209. It starts one engine (or several, in rotating rounds), waits for readiness,
|
|
runs fixed greedy chat requests (one at a time or several in parallel), reads the server's own timings, and
|
|
writes one JSON record with the machine state before and after (Capture-MachineState.ps1). It measures an
|
|
ENGINE; it says nothing about quality.
|
|
|
|
Protocol (charter 4.3/4.4, Gate D):
|
|
* same model file, prompts, greedy sampling, token caps and prompt-cache OFF for every engine;
|
|
* engines are alternated in rotating order each round, so slow drift of the machine hits all engines alike;
|
|
* the machine must be quiet (browsers, Docker/WSL closed, no other model server) unless
|
|
-AllowNoisyMachine is given, which is recorded in the result as an override;
|
|
* one untimed warm-up request per server start; load time is recorded separately from request timings;
|
|
* only processes started by this script are ever stopped; no credential is read or recorded.
|
|
|
|
-BionicProfile reproduces the flags of the server Bionic 1.1.8 started on 2026-10-14 (see STRA-209), minus
|
|
its API key, chat-template file and port: --jinja --fit on --fit-ctx 16384 --ctx-checkpoints 32
|
|
-b 2048 -ub 512 -t 5 --parallel 4 -ctk f16 -ctv f16 -fa on --kv-offload --kv-unified --load-mode mmap+mlock.
|
|
Flags the engine's --help does not list are dropped and the drop is recorded.
|
|
|
|
.PARAMETER Engines
|
|
Backend folders, for example %USERPROFILE%\.lmstudio\extensions\backends\llama.cpp-win-x86_64-vulkan-avx2-2.56.0.
|
|
.PARAMETER Model
|
|
Path of the GGUF file.
|
|
.PARAMETER ExtraArgsByEngine
|
|
Hashtable folder-name -> extra command line text, e.g. @{ 'llama.cpp-win-x86_64-avx2-2.55.0' = '-ngl 0' }.
|
|
Applied after (and so overriding) the profile.
|
|
.PARAMETER Concurrency
|
|
Number of identical requests sent at the same time (1 or 2 for the owner's agent use).
|
|
.PARAMETER ExistingUrl
|
|
Measure an already running server instead of starting one (no engine, no start/stop).
|
|
.EXAMPLE
|
|
.\Measure-LlamaServer.ps1 -Engines $vulkan,$cpu -Model D:\m\gpt-oss-20b-MXFP4.gguf -BionicProfile -ExtraArgsByEngine @{ 'llama.cpp-win-x86_64-avx2-2.55.0' = '-ngl 0' } -Rounds 3 -Runs 5 -Concurrency 1 -HashModel
|
|
#>
|
|
[CmdletBinding()]
|
|
param(
|
|
[string[]] $Engines = @(),
|
|
[string] $Model,
|
|
[string] $ExistingUrl,
|
|
[hashtable] $ExtraArgsByEngine = @{},
|
|
[switch] $BionicProfile,
|
|
[int] $Threads = 0,
|
|
[int] $Context = 0,
|
|
[int] $Port = 18089,
|
|
[int] $Rounds = 3,
|
|
[int] $Runs = 5,
|
|
[int] $Concurrency = 1,
|
|
[int] $DecodeTokens = 200,
|
|
[int] $LongPromptFunctions = 110,
|
|
[int] $ReadyTimeoutSeconds = 1200,
|
|
[string] $OutDir = (Join-Path $env:LOCALAPPDATA ('Temp\leleka-bench\' + [DateTime]::UtcNow.ToString('yyyyMMddTHHmmssZ'))),
|
|
[switch] $HashModel,
|
|
[switch] $AllowNoisyMachine,
|
|
[switch] $SkipRamCheck
|
|
)
|
|
|
|
$ErrorActionPreference = 'Stop'
|
|
. (Join-Path $PSScriptRoot 'Capture-MachineState.ps1')
|
|
Add-Type -AssemblyName System.Net.Http
|
|
|
|
$BionicArgs = '--jinja --fit on --fit-ctx 16384 --ctx-checkpoints 32 -b 2048 -ub 512 -t 5 --parallel 4 -ctk f16 -ctv f16 -fa on --kv-offload --kv-unified --load-mode mmap+mlock'
|
|
|
|
function New-LongPrompt([int] $functions) {
|
|
# Deterministic synthetic code context (about 35 tokens per line), then a question whose answer
|
|
# needs retrieval from the middle.
|
|
$sb = New-Object System.Text.StringBuilder
|
|
[void]$sb.AppendLine('Below is a module. Read it and answer the question at the end.')
|
|
for ($i = 1; $i -le $functions; $i++) {
|
|
$k = ($i * 7919) % 1000
|
|
[void]$sb.AppendLine("int helper_$i(int value) { /* adds offset $k and clamps */ int r = value + $k; if (r > 100000) { r = 100000; } return r; }")
|
|
}
|
|
$target = [int]($functions / 2)
|
|
[void]$sb.AppendLine("Question: what constant offset does helper_$target add? Reply with the number only.")
|
|
return $sb.ToString()
|
|
}
|
|
|
|
$cases = @(
|
|
[ordered]@{ id = 'short-decode'; max_tokens = $DecodeTokens
|
|
content = 'Explain in plain words how a hash table handles collisions, then give a short C example.' },
|
|
[ordered]@{ id = 'long-prefill'; max_tokens = 32
|
|
content = (New-LongPrompt $LongPromptFunctions) }
|
|
)
|
|
|
|
function Get-ChatBody($case) {
|
|
return ([ordered]@{
|
|
model = 'bench'; stream = $false; temperature = 0; seed = 1; cache_prompt = $false
|
|
max_tokens = $case.max_tokens
|
|
messages = @(@{ role = 'user'; content = $case.content })
|
|
} | ConvertTo-Json -Depth 6)
|
|
}
|
|
|
|
function ConvertTo-Row($r, $caseId, [int] $wallMs) {
|
|
$t = $r.timings
|
|
$text = [string]$r.choices[0].message.content + '|' + [string]$r.choices[0].message.reasoning_content
|
|
$sha = [BitConverter]::ToString([Security.Cryptography.SHA256]::Create().ComputeHash([Text.Encoding]::UTF8.GetBytes($text))).Replace('-', '').ToLower()
|
|
return [ordered]@{
|
|
case = $caseId; wall_ms = $wallMs
|
|
prompt_n = [int]$t.prompt_n; prompt_ms = [double]$t.prompt_ms; prompt_per_second = [double]$t.prompt_per_second
|
|
predicted_n = [int]$t.predicted_n; predicted_ms = [double]$t.predicted_ms; predicted_per_second = [double]$t.predicted_per_second
|
|
finish_reason = [string]$r.choices[0].finish_reason; output_sha256 = $sha
|
|
}
|
|
}
|
|
|
|
# Sends $n identical requests at once; returns one row per request plus the batch wall time.
|
|
function Invoke-Chat([string] $base, $case, [int] $n) {
|
|
$body = Get-ChatBody $case
|
|
$client = New-Object System.Net.Http.HttpClient
|
|
$client.Timeout = [TimeSpan]::FromSeconds(1800)
|
|
try {
|
|
$sw = [Diagnostics.Stopwatch]::StartNew()
|
|
$tasks = @(1..$n | ForEach-Object {
|
|
$content = New-Object System.Net.Http.StringContent($body, [Text.Encoding]::UTF8, 'application/json')
|
|
$client.PostAsync("$base/v1/chat/completions", $content)
|
|
})
|
|
[void][System.Threading.Tasks.Task]::WaitAll([System.Threading.Tasks.Task[]]$tasks)
|
|
$sw.Stop()
|
|
$rows = @()
|
|
foreach ($t in $tasks) {
|
|
$resp = $t.Result
|
|
if (-not $resp.IsSuccessStatusCode) { throw "request failed: HTTP $([int]$resp.StatusCode)" }
|
|
$json = $resp.Content.ReadAsStringAsync().Result | ConvertFrom-Json
|
|
$rows += (ConvertTo-Row $json $case.id ([int]$sw.ElapsedMilliseconds))
|
|
}
|
|
return [ordered]@{ rows = $rows; wall_ms = [int]$sw.ElapsedMilliseconds }
|
|
} finally { $client.Dispose() }
|
|
}
|
|
|
|
function Wait-Ready([string] $base, [int] $timeoutSeconds, $proc) {
|
|
$deadline = [DateTime]::UtcNow.AddSeconds($timeoutSeconds)
|
|
while ([DateTime]::UtcNow -lt $deadline) {
|
|
if ($proc -and $proc.HasExited) { throw "server exited with code $($proc.ExitCode) before becoming ready" }
|
|
try {
|
|
$h = Invoke-WebRequest -UseBasicParsing -Uri "$base/health" -TimeoutSec 5
|
|
if ($h.StatusCode -eq 200) { return }
|
|
} catch { }
|
|
Start-Sleep -Seconds 2
|
|
}
|
|
throw "server not ready after $timeoutSeconds s"
|
|
}
|
|
|
|
function Measure-OneServer([string] $label, [string] $base, [int] $round) {
|
|
[void](Invoke-Chat $base ([ordered]@{ id = 'warmup'; max_tokens = 16; content = 'Say hello.' }) 1) # untimed warm-up
|
|
$rows = @()
|
|
foreach ($case in $cases) {
|
|
for ($i = 1; $i -le $Runs; $i++) {
|
|
$batch = Invoke-Chat $base $case $Concurrency
|
|
$aggTokens = ($batch.rows | ForEach-Object { $_.predicted_n } | Measure-Object -Sum).Sum
|
|
$agg = if ($batch.wall_ms -gt 0) { 1000.0 * $aggTokens / $batch.wall_ms } else { 0 }
|
|
$k = 0
|
|
foreach ($row in $batch.rows) {
|
|
$k++
|
|
$row.engine = $label; $row.round = $round; $row.run = $i; $row.concurrency = $Concurrency; $row.request = $k
|
|
$row.aggregate_tokens_per_wall_second = [math]::Round($agg, 3)
|
|
$rows += $row
|
|
}
|
|
$dec = ($batch.rows | ForEach-Object { '{0:N1}' -f $_.predicted_per_second }) -join ' / '
|
|
$pre = ($batch.rows | ForEach-Object { '{0:N1}' -f $_.prompt_per_second }) -join ' / '
|
|
Write-Host (" [{0}] round {1} {2} run {3} x{4}: decode {5} t/s, prefill {6} t/s, ({7} prompt tokens each), wall {8:N1} s" -f $label, $round, $case.id, $i, $Concurrency, $dec, $pre, $batch.rows[0].prompt_n, ($batch.wall_ms / 1000.0))
|
|
}
|
|
}
|
|
return $rows
|
|
}
|
|
|
|
function Invoke-NativeText([string] $exe, [string[]] $arguments) {
|
|
# Windows PowerShell 5.1 turns native stderr output into a terminating error under
|
|
# -ErrorAction Stop; llama-server prints its version and help to stderr, so relax it here.
|
|
$old = $ErrorActionPreference
|
|
$ErrorActionPreference = 'Continue'
|
|
try { return @(& $exe @arguments 2>&1 | ForEach-Object { "$_" }) } finally { $ErrorActionPreference = $old }
|
|
}
|
|
|
|
function Get-EffectiveArgs([string] $engineDir, [string] $label) {
|
|
$text = @()
|
|
if ($BionicProfile) { $text += $BionicArgs }
|
|
if ($Threads -gt 0) { $text += "-t $Threads -tb $Threads" }
|
|
if ($ExtraArgsByEngine.ContainsKey($label)) { $text += $ExtraArgsByEngine[$label] }
|
|
$tokens = ($text -join ' ') -split '\s+' | Where-Object { $_ }
|
|
# Drop flags this engine's --help does not list (versions differ), and record the drop.
|
|
$help = (Invoke-NativeText (Join-Path $engineDir 'llama-server.exe') @('--help')) -join "`n"
|
|
$kept = New-Object System.Collections.ArrayList
|
|
$dropped = @()
|
|
for ($i = 0; $i -lt $tokens.Count; $i++) {
|
|
$t = $tokens[$i]
|
|
if ($t -like '-*' -and $t -notmatch '^-\d') {
|
|
$known = $help -match ('(^|[\s,|])' + [regex]::Escape($t) + '([\s,|=\[<]|$)')
|
|
$takesValue = ($i + 1 -lt $tokens.Count) -and ($tokens[$i + 1] -notlike '-*' -or $tokens[$i + 1] -match '^-\d')
|
|
if (-not $known) { $dropped += $t; if ($takesValue) { $i++ }; continue }
|
|
}
|
|
[void]$kept.Add($t)
|
|
}
|
|
return [ordered]@{ args = @($kept); dropped = $dropped }
|
|
}
|
|
|
|
New-Item -ItemType Directory -Force -Path $OutDir | Out-Null
|
|
$result = [ordered]@{ schema = 1; tool = 'Measure-LlamaServer.ps1'; started_utc = (Get-UtcNow); parameters = [ordered]@{ threads = $Threads; context = $Context; rounds = $Rounds; runs = $Runs; concurrency = $Concurrency; decode_tokens = $DecodeTokens; long_prompt_functions = $LongPromptFunctions; bionic_profile = [bool]$BionicProfile } }
|
|
$result.cases = $cases | ForEach-Object { [ordered]@{ id = $_.id; max_tokens = $_.max_tokens; prompt_chars = $_.content.Length } }
|
|
|
|
if (-not $ExistingUrl) {
|
|
if (-not $Model -or -not (Test-Path $Model)) { throw "model file not found: $Model" }
|
|
if ($Engines.Count -eq 0) { throw 'give -Engines or -ExistingUrl' }
|
|
$fi = Get-Item $Model
|
|
$result.model = [ordered]@{ path = $fi.FullName; bytes = $fi.Length; last_write_utc = $fi.LastWriteTimeUtc.ToString('yyyy-MM-ddTHH:mm:ssZ') }
|
|
if ($HashModel) { Write-Host 'hashing model...'; $result.model.sha256 = (Get-FileHash -Algorithm SHA256 $Model).Hash.ToLower() }
|
|
$others = @(Get-Process -Name 'llama-server' -ErrorAction SilentlyContinue)
|
|
if ($others.Count -gt 0) { throw "another llama-server is running (PID $($others.Id -join ', ')); stop it first so the baseline is not shared with it" }
|
|
}
|
|
|
|
$quiet = @(Test-QuietMachine)
|
|
$result.quiet_gate = [ordered]@{ reasons = $quiet; overridden = [bool]($quiet.Count -gt 0 -and $AllowNoisyMachine) }
|
|
if ($quiet.Count -gt 0) {
|
|
$quiet | ForEach-Object { Write-Warning "machine not quiet: $_" }
|
|
if (-not $AllowNoisyMachine) { throw 'machine is not quiet; close the listed applications or pass -AllowNoisyMachine (recorded as an override)' }
|
|
}
|
|
if (-not $ExistingUrl -and -not $SkipRamCheck) {
|
|
$free = (Get-CimInstance Win32_OperatingSystem).FreePhysicalMemory * 1KB
|
|
if ($free -lt $fi.Length * 1.1) { throw ("free RAM {0:N1} GB is below 1.1 x the model size {1:N1} GB; a swapping run is not a baseline (use -SkipRamCheck to override)" -f ($free/1GB), ($fi.Length/1GB)) }
|
|
}
|
|
|
|
$result.machine_before = Get-MachineState
|
|
$all = @()
|
|
$result.engines = @()
|
|
|
|
if ($ExistingUrl) {
|
|
$all += Measure-OneServer 'existing' $ExistingUrl 1
|
|
} else {
|
|
$effective = @{}
|
|
foreach ($e in $Engines) {
|
|
$exe = Join-Path $e 'llama-server.exe'
|
|
if (-not (Test-Path $exe)) { throw "no llama-server.exe in $e" }
|
|
$label = Split-Path $e -Leaf
|
|
$ver = (Invoke-NativeText $exe @('--version') | Where-Object { $_ -match 'version' } | Select-Object -First 1)
|
|
$eff = Get-EffectiveArgs $e $label
|
|
$effective[$label] = $eff
|
|
if ($eff.dropped.Count -gt 0) { Write-Warning "$label does not list: $($eff.dropped -join ' '); dropped" }
|
|
$result.engines += [ordered]@{ label = $label; dir = $e; version = $ver; arguments = $eff.args; dropped_arguments = $eff.dropped }
|
|
}
|
|
$load = @{}
|
|
for ($round = 1; $round -le $Rounds; $round++) {
|
|
$order = @(); for ($k = 0; $k -lt $Engines.Count; $k++) { $order += $Engines[($k + $round - 1) % $Engines.Count] } # rotate
|
|
foreach ($e in $order) {
|
|
$label = Split-Path $e -Leaf
|
|
$args = @('-m', "`"$Model`"", '--port', $Port, '--host', '127.0.0.1', '--no-webui') + $effective[$label].args
|
|
if ($Context -gt 0) { $args += @('-c', $Context) }
|
|
Write-Host "round ${round}: starting $label"
|
|
$proc = Start-Process -FilePath (Join-Path $e 'llama-server.exe') -ArgumentList $args -WorkingDirectory $e -PassThru -WindowStyle Hidden `
|
|
-RedirectStandardOutput (Join-Path $OutDir "$label-r$round.out.log") -RedirectStandardError (Join-Path $OutDir "$label-r$round.err.log")
|
|
try {
|
|
$sw = [Diagnostics.Stopwatch]::StartNew()
|
|
Wait-Ready "http://127.0.0.1:$Port" $ReadyTimeoutSeconds $proc
|
|
$load["$label#$round"] = [int]$sw.Elapsed.TotalSeconds
|
|
$all += Measure-OneServer $label "http://127.0.0.1:$Port" $round
|
|
} finally {
|
|
if (-not $proc.HasExited) { Stop-Process -Id $proc.Id -Force }
|
|
$proc.WaitForExit(30000) | Out-Null
|
|
}
|
|
}
|
|
}
|
|
$result.load_seconds = $load
|
|
}
|
|
|
|
$result.machine_after = Get-MachineState
|
|
$result.rows = $all
|
|
$summary = @()
|
|
foreach ($g in ($all | Group-Object { $_.engine + '|' + $_.case + '|' + $_.concurrency })) {
|
|
$dec = @($g.Group | ForEach-Object { $_.predicted_per_second } | Sort-Object)
|
|
$pre = @($g.Group | ForEach-Object { $_.prompt_per_second } | Sort-Object)
|
|
$agg = @($g.Group | Where-Object { $_.request -eq 1 } | ForEach-Object { $_.aggregate_tokens_per_wall_second } | Sort-Object)
|
|
$summary += [ordered]@{
|
|
engine = $g.Group[0].engine; case = $g.Group[0].case; concurrency = $g.Group[0].concurrency; n = $g.Count
|
|
decode_tps_per_request_median = $dec[[int](($dec.Count - 1) / 2)]; decode_tps_min = $dec[0]; decode_tps_max = $dec[-1]
|
|
aggregate_tokens_per_wall_second_median = $agg[[int](($agg.Count - 1) / 2)]
|
|
prefill_tps_median = $pre[[int](($pre.Count - 1) / 2)]; prefill_tps_min = $pre[0]; prefill_tps_max = $pre[-1]
|
|
distinct_outputs = @($g.Group | ForEach-Object { $_.output_sha256 } | Sort-Object -Unique).Count
|
|
}
|
|
}
|
|
$result.summary = $summary
|
|
$result.finished_utc = Get-UtcNow
|
|
$path = Join-Path $OutDir 'result.json'
|
|
$result | ConvertTo-Json -Depth 8 | Set-Content -Path $path -Encoding UTF8
|
|
Write-Host ''
|
|
$table = $summary | ForEach-Object { [pscustomobject]$_ } | Format-Table engine, case, concurrency, n, decode_tps_per_request_median, aggregate_tokens_per_wall_second_median, prefill_tps_median, distinct_outputs -AutoSize | Out-String
|
|
Write-Host $table
|
|
Write-Host "result: $path"
|