Files
leleka/benchmarks/tools/Compare-ConcurrentEpisodes.ps1
T

199 lines
12 KiB
PowerShell

<#
.SYNOPSIS
Paired, alternating comparison of one worker against a pool of two workers (iGPU + NPU) on two agent-shaped episodes
sent at the same time, through the control plane's /v1/responses.
.DESCRIPTION
Arm 'single' starts leleka-api with leleka-igpu-worker alone; arm 'pool' starts it with leleka-igpu-worker and
leleka-npu-worker in a pool (engine.extra_workers, control-plane/src/pool.rs). In each arm two episodes run at once
(two runspaces): each is the scripted episode of Compare-PrefillWorkers.ps1 (turn k carries k function_call /
function_call_output pairs of about -ToolTokens tokens of deterministic pseudo-source), with different outputs and
task text per episode, so the two do not share a prefix beyond the system part. Each turn waits for the previous one
of its episode. Recorded per turn: wall time and usage; per arm: the time until both episodes are done. One untimed
warm-up request per worker after readiness. Arms alternate in order for -Pairs pairs; only processes this script
starts are stopped. Results are appended as JSON lines to -Output (outside Git, or sanitize first).
Build first: cargo build --release -p leleka-control-plane -p leleka-igpu-worker -p leleka-npu-worker -p leleka-npu-service
#>
param(
[Parameter(Mandatory)] [string] $Model,
[Parameter(Mandatory)] [string] $Output,
[string] $OpenvinoRoot = $env:LELEKA_OPENVINO_ROOT, # needed by the pool arm only
[string] $RepoRoot,
[int] $Port = 8082,
[int] $Context = 16384,
[int] $SingleThreads = 10,
[int] $PoolThreads = 7,
[int] $Turns = 4,
[int] $Agents = 2,
# tokens of instructions shared by every agent (a system prompt and tool descriptions that the agents have in common)
[int] $SharedInstructionTokens = 0,
[int] $ToolTokens = 1500,
[int] $MaxOutput = 32,
[int] $Pairs = 3,
[int] $GpuMinTokens = 256,
[string] $LogDir,
# the two arms to pair: 'single' (one iGPU worker, one cache), 'slots' (the same worker with one cache slot per
# agent, --cache-slots), 'pool' (iGPU worker + NPU worker), or 'single-seq' (the single worker running the
# episodes one after the other, so its cache always holds the running episode)
[string[]] $Arms = @('single', 'pool')
)
$ErrorActionPreference = 'Stop'
if (-not $RepoRoot) { $RepoRoot = (Resolve-Path (Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Path) '..\..')).Path }
$bin = Join-Path $RepoRoot 'target\release'
if ($LogDir) { New-Item -ItemType Directory -Force $LogDir | Out-Null }
# deterministic filler that tokenizes to roughly 4 characters per token
function New-ToolOutput([int]$seed, [int]$tokens) {
$rng = New-Object System.Random $seed
$words = 'fn','let','mut','self','return','match','impl','struct','Vec','String','Result','Option','usize','for','in','if','else','pub','use','mod','const','loop','while','break'
$sb = New-Object Text.StringBuilder
$line = 0
while ($sb.Length -lt $tokens * 4) {
$n = $rng.Next(4, 10)
$parts = 1..$n | ForEach-Object { $words[$rng.Next(0, $words.Count)] + $rng.Next(0, 99) }
[void]$sb.Append("$line " + ($parts -join ' ') + ";`n")
$line++
}
$sb.ToString()
}
$tasks = 'Review the repository and summarize what each file does.', 'Find the functions that allocate in a loop and list them by file.',
'List every public type and the module that defines it.', 'Find unused imports and say which files have them.',
'Describe the error handling of each module.', 'Find every place that spawns a thread.', 'Summarize the tests and what they cover.',
'List the configuration options and their defaults.'
$episodes = @(0..($Agents - 1) | ForEach-Object {
$e = $_
@{ task = $tasks[$e % $tasks.Count] + " (agent $e)"; outputs = @(1..$Turns | ForEach-Object { New-ToolOutput (1000 * ($e + 1) + $_) $ToolTokens }) }
})
$instructions = if ($SharedInstructionTokens -gt 0) { "You are a coding agent. Follow these notes.`n" + (New-ToolOutput 7777 $SharedInstructionTokens) } else { $null }
function Start-Arm([string]$arm, [int]$pair) {
$work = Join-Path ([IO.Path]::GetTempPath()) ("leleka-cc-" + [Guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory $work | Out-Null
$threads = if ($arm -eq 'pool') { $PoolThreads } else { $SingleThreads }
$gpuArgs = @('--model', $Model, '--ctx', "$Context", '--threads', "$threads", '--gpu-min-tokens', "$GpuMinTokens")
if ($arm -eq 'slots') { $gpuArgs += @('--cache-slots', "$Agents") }
$engine = @{ executable = (Join-Path $bin 'leleka-igpu-worker.exe'); args = $gpuArgs; gptoss_gguf = $Model
startup_timeout_s = 300; generation_timeout_s = 1500 }
if ($arm -eq 'pool') {
$npuArgs = @('--model', $Model, '--ctx', "$Context", '--threads', "$threads", '--openvino-root', $OpenvinoRoot)
$engine.extra_workers = @(@{ executable = (Join-Path $bin 'leleka-npu-worker.exe'); args = $npuArgs })
}
$config = @{ bind = "127.0.0.1:$Port"; model = 'gpt-oss-20b'; engine = $engine } | ConvertTo-Json -Depth 6
[IO.File]::WriteAllText((Join-Path $work 'config.json'), $config, (New-Object Text.UTF8Encoding($false)))
$server = Start-Process (Join-Path $bin 'leleka-api.exe') -ArgumentList @('serve', '--config', (Join-Path $work 'config.json')) `
-PassThru -WindowStyle Hidden -RedirectStandardOutput (Join-Path $work 'out.txt') -RedirectStandardError (Join-Path $work 'err.txt')
$ready = $false
foreach ($i in 1..150) {
Start-Sleep 3
if ($server.HasExited) { throw "the control plane exited; see $work\err.txt" }
try { if ((Invoke-WebRequest "http://127.0.0.1:$Port/ready" -UseBasicParsing -TimeoutSec 3).StatusCode -eq 200) { $ready = $true; break } } catch {}
}
if (-not $ready) { throw "not ready; see $work\err.txt" }
[pscustomobject]@{ Server = $server; Work = $work; Arm = $arm; Pair = $pair }
}
function Stop-Arm($handle) {
Get-CimInstance Win32_Process -Filter "ParentProcessId=$($handle.Server.Id)" -ErrorAction SilentlyContinue |
ForEach-Object {
Get-CimInstance Win32_Process -Filter "ParentProcessId=$($_.ProcessId)" -ErrorAction SilentlyContinue |
ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }
Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue
}
if (-not $handle.Server.HasExited) { Stop-Process $handle.Server -Force }
Start-Sleep 3
if ($LogDir) {
Copy-Item (Join-Path $handle.Work 'err.txt') (Join-Path $LogDir "$($handle.Arm)-pair$($handle.Pair).err.txt") -ErrorAction SilentlyContinue
}
Remove-Item $handle.Work -Recurse -Force -ErrorAction SilentlyContinue
}
# one episode, run inside its own runspace
$episodeScript = {
param($Port, $Episode, $Index, $Turns, $MaxOutput, $Clock, $Instructions)
$tool = @{ type = 'function'; name = 'read_file'; description = 'Read a source file.'
parameters = @{ type = 'object'; properties = @{ path = @{ type = 'string' } }; required = @('path') } }
$uri = "http://127.0.0.1:$Port/v1/responses"
$rows = @()
foreach ($k in 1..$Turns) {
$items = @(@{ role = 'user'; content = $Episode.task })
foreach ($i in 1..$k) {
$items += @{ type = 'function_call'; call_id = "call_$i"; name = 'read_file'; arguments = "{`"path`":`"src/e$Index/file$i.rs`"}" }
$items += @{ type = 'function_call_output'; call_id = "call_$i"; output = $Episode.outputs[$i - 1] }
}
$body = @{ model = 'gpt-oss-20b'; input = $items; tools = @($tool); max_output_tokens = $MaxOutput; reasoning = @{ effort = 'low' } }
if ($Instructions) { $body.instructions = $Instructions }
$start = $Clock.Elapsed.TotalSeconds
$r = Invoke-RestMethod $uri -Method Post -Body ($body | ConvertTo-Json -Depth 10 -Compress) -ContentType 'application/json' -TimeoutSec 3000
$end = $Clock.Elapsed.TotalSeconds
# the answer, without ids and times, so arms can be compared
$answer = @(foreach ($o in $r.output) {
foreach ($c in @($o.content)) { $c.text }
if ($o.arguments) { "$($o.name)$($o.arguments)" }
}) -join "`n"
$sha = ([BitConverter]::ToString([Security.Cryptography.SHA256]::Create().ComputeHash([Text.Encoding]::UTF8.GetBytes($answer))) -replace '-', '').Substring(0, 12)
$rows += [pscustomobject]@{ episode = $Index; turn = $k; start_s = [math]::Round($start, 2); wall_s = [math]::Round($end - $start, 2)
input_tokens = $r.usage.input_tokens; cached_tokens = $r.usage.input_tokens_details.cached_tokens; output_tokens = $r.usage.output_tokens; output_sha = $sha }
}
$rows
}
function Run-Arm([string]$arm, [int]$pair) {
$handle = Start-Arm $arm $pair
try {
# one untimed warm-up per worker: two at once spread over a pool
$warm = 1..2 | ForEach-Object {
$ps = [powershell]::Create()
[void]$ps.AddScript({ param($Port) Invoke-RestMethod "http://127.0.0.1:$Port/v1/responses" -Method Post -ContentType 'application/json' `
-Body (@{ model = 'gpt-oss-20b'; input = 'Say OK.'; max_output_tokens = 8; reasoning = @{ effort = 'low' } } | ConvertTo-Json -Compress) -TimeoutSec 600 }).AddArgument($Port)
[pscustomobject]@{ PS = $ps; Async = $ps.BeginInvoke() }
}
$warm | ForEach-Object { [void]$_.PS.EndInvoke($_.Async); $_.PS.Dispose() }
$clock = [Diagnostics.Stopwatch]::StartNew()
$start = {
param($e)
$ps = [powershell]::Create()
[void]$ps.AddScript($episodeScript).AddArgument($Port).AddArgument($episodes[$e]).AddArgument($e + 1).AddArgument($Turns).AddArgument($MaxOutput).AddArgument($clock).AddArgument($instructions)
[pscustomobject]@{ PS = $ps; Async = $ps.BeginInvoke() }
}
$finish = {
param($j)
$out = $j.PS.EndInvoke($j.Async)
if ($j.PS.Streams.Error.Count -gt 0) { throw "episode failed: $($j.PS.Streams.Error[0])" }
$j.PS.Dispose()
$out
}
$rows = @()
if ($arm -eq 'single-seq') {
foreach ($e in 0..($Agents - 1)) { $rows += & $finish (& $start $e) }
} else {
$jobs = 0..($Agents - 1) | ForEach-Object { & $start $_ }
foreach ($j in $jobs) { $rows += & $finish $j }
}
$both = [math]::Round($clock.Elapsed.TotalSeconds, 2)
[pscustomobject]@{ Rows = $rows; Both = $both }
} finally { Stop-Arm $handle }
}
$meta = @{ kind = 'meta'; date = (Get-Date -Format 'yyyy-MM-dd HH:mm'); model = (Split-Path -Leaf $Model); turns = $Turns
agents = $Agents; shared_instruction_tokens = $SharedInstructionTokens; tool_tokens = $ToolTokens; max_output = $MaxOutput; pairs = $Pairs; context = $Context; single_threads = $SingleThreads
pool_threads = $PoolThreads; gpu_min_tokens = $GpuMinTokens; single = 'leleka-igpu-worker'; pool = 'leleka-igpu-worker + leleka-npu-worker' }
($meta | ConvertTo-Json -Compress) | Add-Content $Output
foreach ($p in 1..$Pairs) {
$answers = @{}
$order = if ($p % 2 -eq 1) { $Arms[0], $Arms[1] } else { $Arms[1], $Arms[0] }
foreach ($arm in $order) {
"pair $p, $arm"
$result = Run-Arm $arm $p
$answers[$arm] = @{}
foreach ($row in ($result.Rows | Sort-Object episode, turn)) {
$answers[$arm]["$($row.episode).$($row.turn)"] = $row.output_sha
$row | Add-Member arm $arm -PassThru | Add-Member pair $p -PassThru | ConvertTo-Json -Compress | Add-Content $Output
" episode $($row.episode) turn $($row.turn): start $($row.start_s) s, $($row.wall_s) s, input $($row.input_tokens), cached $($row.cached_tokens)"
}
([pscustomobject]@{ kind = 'arm'; arm = $arm; pair = $p; both_done_s = $result.Both } | ConvertTo-Json -Compress) | Add-Content $Output
" both episodes done after $($result.Both) s"
}
$differ = @($answers[$Arms[0]].Keys | Where-Object { $answers[$Arms[0]][$_] -ne $answers[$Arms[1]][$_] })
" answers identical between $($Arms[0]) and $($Arms[1]): $($differ.Count -eq 0)" + $(if ($differ.Count) { " (differ at $($differ -join ', '))" } else { '' })
([pscustomobject]@{ kind = 'compare'; pair = $p; identical_answers = ($differ.Count -eq 0); differing = $differ } | ConvertTo-Json -Compress) | Add-Content $Output
}