@localmode/bench 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +87 -5
- package/dist/index.cjs +7 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +398 -21
- package/dist/index.d.ts +398 -21
- package/dist/index.js +7 -7
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types.ts","../src/protocol.ts","../src/adapter.ts","../src/timing.ts","../src/trace.ts","../src/memory.ts","../src/env.ts","../src/fingerprint.ts","../src/stats.ts","../src/validate.ts","../src/datasets/tiny-mmlu.ts","../src/datasets/stsb/stsb-subset.ts","../src/quality.ts","../src/runner.ts","../src/canonical.ts","../src/aggregate.ts"],"names":["BENCH_PROTOCOL_VERSION","BENCH_SCHEMA_VERSION","PROMPT_PP128","PROMPT_PP512","GENERATION_BUDGET","LLM_WORKLOADS","embedTexts","topics","texts","i","topic","EMBED_TEXTS","EMBED_WORKLOADS","QUALITY_WORKLOADS","WORKLOADS_BY_ID","w","RUN_POLICIES","USAGE_FIDELITY","hrNow","inferTimerResolutionUs","samples","deltas","prev","guard","t","minDelta","sleep","ms","abortSignal","resolve","reject","abortDomException","id","onAbort","err","TraceRecorder","type","detail","onVisibility","PressureObserverCtor","observer","records","last","wakeLock","sentinel","dispose","memoryApiAvailable","sampleMemoryBytes","timeoutMs","api","result","legacy","GPU_LIMIT_KEYS","captureEnvironment","options","nav","browser","os","identifyBrowserAndOS","gpu","probeWebGPU","probeWebGLRenderer","probeWasmSimd","probeStorage","probeBattery","uaData","high","list","primary","b","ua","parseUABrowser","parseUAOS","rules","name","re","m","platform","adapter","info","limits","adapterLimits","key","v","str","canvas","gl","ext","renderer","est","getBattery","battery","lcg","seed","s","runFingerprint","n","minDurationMs","rand","a","c","flopsPerIter","iterations","start","elapsed","matmul","checksum","j","acc","k","T_95","sorted","values","quantile","q","pos","lo","hi","median","mean","sum","stddev","geomean","summarize","sd","ci95","spearman","ra","ranks","rb","pearson","idx","x","y","out","avgRank","ma","mb","num","da","db","xa","xb","den","PLAUSIBILITY_RULES_VERSION","DECODE_ENVELOPE_CHARS_PER_SEC","EMBED_ENVELOPE_TEXTS_PER_SEC","SOFTWARE_RENDERER_PATTERNS","validateRunShape","value","errors","push","msg","run","harness","env","validateCellShape","index","cell","at","model","it","iter","isLLMIterations","summarizeCell","highVarianceCv","approxPromptTokens","ttfts","decodeRates","chunkRates","genChars","prefillRates","first","ttftMs","decodeChars","decodeMs","iters","durations","d","metrics","summarizeRun","promptTokensByWorkload","lookup","checkPlausibility","flags","flag","code","message","severity","cellId","grid","monotonic","chunkChars","summary","size","envelope","e","quantumMs","offGrid","total","vendor","gpuIdentity","p","hasGpuLane","validateSubmission","shapeErrors","summaries","byId","client","server","f","TINY_MMLU","STSB_SUBSET","LETTERS","formatMMLUPrompt","item","choices","parseMMLUAnswer","response","trimmed","letterMatch","lower","runMMLUFidelity","items","subset","details","correct","ok","cosine","dot","na","nb","runSTSQuality","pairs","sims","humanScores","pair","embeddings","runBenchmarkSuite","policy","hooks","trace","memApi","cells","environment","throwIfAborted","fingerprint","baselineMemory","groups","groupCells","totalCells","cellIndex","group","groupCellsResults","runModelGroup","waitForPressure","generateRunId","map","ctx","isEmbedding","results","baseCell","workload","finishCell","availability","loaded","loadRecord","warmupMs","postLoadMemory","cached","progress","loadStart","firstCellId","loadEnd","decimate","warmupStart","consumeStream","error","safeDispose","attachedLoad","runLLMCell","runEmbedCell","done","postRun","reloaded","end","warmCell","gates","hiddenBefore","countHidden","startT","chunks","text","providerUsage","finishReason","endT","gated","chunk","deadline","state","max","step","signal","cryptoObj","bytes","hex","canonicalJson","stringify","sha256Hex","subtle","hash","computeRunDigest","_omitted","rest","verifyRunDigest","deviceClassOf","HEADLINE_MIN_SUBMISSIONS","aggregateRuns","runs","minSubmissions","buckets","deviceClass","byCellId","bucket","pushUnique","rows","maybeMedian","round2","csvField","rowsToCSV","lines","r","runsToLongCSV","base","loadMs","loadCached","cellBase","ttft","decodeRate","chars"],"mappings":"AAQO,IAAMA,CAAAA,CAAyB,mBAAA,CAGzBC,CAAAA,CAAuB,ECKpC,IAAMC,GAAe,CACnB,qFAAA,CACA,uFAAA,CACA,uFAAA,CACA,wFAAA,CACA,uFAAA,CACA,kFACF,CAAA,CAAE,IAAA,CAAK,GAAG,CAAA,CAGJC,EAAAA,CAAe,CACnB,gGAAA,CACA,+FAAA,CACA,6FAAA,CACA,6FAAA,CACA,2FAAA,CACA,+FAAA,CACA,yFAAA,CACA,4FAAA,CACA,+FACA,6FAAA,CACA,6FAAA,CACA,+FAAA,CACA,+FAAA,CACA,8FAAA,CACA,4FAAA,CACA,+FAAA,CACA,iGAAA,CACA,kGAAA,CACA,iGAAA,CACA,+FAAA,CACA,8FAAA,CACA,sGAAA,CACA,gGAAA,CACA,8FACA,8FACF,CAAA,CAAE,IAAA,CAAK,GAAG,CAAA,CAGGC,CAAAA,CAAoB,GAAA,CAGpBC,EAAAA,CAA4C,CACvD,CACE,EAAA,CAAI,kBAAA,CACJ,IAAA,CAAM,cAAA,CACN,MAAO,kBAAA,CACP,MAAA,CAAQH,EAAAA,CACR,kBAAA,CAAoB,GAAA,CACpB,SAAA,CAAWE,CAAAA,CACX,WAAA,CAAa,CACf,CAAA,CACA,CACE,EAAA,CAAI,kBAAA,CACJ,IAAA,CAAM,eACN,KAAA,CAAO,0BAAA,CACP,MAAA,CAAQD,EAAAA,CACR,kBAAA,CAAoB,GAAA,CACpB,SAAA,CAAWC,CAAAA,CACX,WAAA,CAAa,CACf,CACF,EAGA,SAASE,EAAAA,EAAuB,CAC9B,IAAMC,CAAAA,CAAS,CACb,kFAAA,CACA,2EAAA,CACA,0EAAA,CACA,8EAAA,CACA,4EAAA,CACA,gFAAA,CACA,uEAAA,CACA,sEACF,CAAA,CACMC,CAAAA,CAAkB,GACxB,IAAA,IAASC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AA,CAAI,CAAA,CAAGwU,CAAAA,CAAMC,EAAYC,CAAAA,CAC9CZ,CAAAA,CAAOtK,CAAAA,CAAG,IAAA,CAAOA,EAAG,MAAM,CAAA,CAAG6K,CAAAA,CAAQC,CAAAA,CAAYjL,EAAK,MAAM,CAAA,CAC3D,GAAA,CAAI0K,CAAQ,EACZ,IAAA,CAAK,GAAG,CACb,EACF,CAAC,EACH,CACF,CACA,OAAOE,EAAM,IAAA,CAAK;AAAA,CAAI,CAAA,CAAI;AAAA,CAC5B","file":"index.js","sourcesContent":["/**\n * Protocol types for the LocalMode LocalMode Bench — the cross-runtime in-browser\n * AI benchmark. A `BenchRunResult` is the unit of submission: it carries raw\n * per-chunk timing traces (never just client-computed aggregates) so that all\n * published statistics can be recomputed and audited server-side.\n */\n\n/** Protocol identifier embedded in every result. Bump only with a spec change. */\nexport const BENCH_PROTOCOL_VERSION = 'localmode-bench/1';\n\n/** Result JSON schema version (independent of the protocol semantics version). */\nexport const BENCH_SCHEMA_VERSION = 1;\n\n/** Benchmark suite presets. `custom` = user-picked cells. */\nexport type BenchSuiteId = 'quick' | 'standard' | 'thorough' | 'custom';\n\n/**\n * A benchmark runtime lane. Transformers.js is split into two lanes because\n * WebGPU vs WASM is the paper's core comparison axis.\n */\nexport type BenchRuntimeId =\n | 'transformers-webgpu'\n | 'transformers-wasm'\n | 'webllm'\n | 'wllama'\n | 'litert'\n | 'chrome-ai'\n | 'mediapipe';\n\n/** Workload kinds. Quality lanes are separate from timed performance lanes. */\nexport type BenchWorkloadKind =\n | 'llm-generate'\n | 'embed-single'\n | 'embed-batch'\n | 'quality-mmlu'\n | 'quality-sts';\n\n/** A fixed LLM generation workload (public prompt, deterministic settings). */\nexport interface LLMWorkloadSpec {\n id: string;\n kind: 'llm-generate';\n /** Human-readable label, e.g. \"Chat pp128/tg128\". */\n label: string;\n prompt: string;\n systemPrompt?: string;\n /**\n * Approximate prompt token count (reference estimate; exact counts are\n * tokenizer-specific and computed post-hoc from the stored prompt).\n */\n approxPromptTokens: number;\n /** Generation budget. Decode metrics use the actual generated length. */\n maxTokens: number;\n /** Always 0 for performance runs (deterministic where the runtime allows). */\n temperature: number;\n}\n\n/** A fixed embedding workload over deterministic public texts. */\nexport interface EmbedWorkloadSpec {\n id: string;\n kind: 'embed-single' | 'embed-batch';\n label: string;\n /** Fixed input texts. Length 1 for single-latency, N for batch throughput. */\n texts: string[];\n}\n\n/** Quality-fidelity workloads (temp 0, scored, untimed-region rules relaxed). */\nexport interface QualityWorkloadSpec {\n id: string;\n kind: 'quality-mmlu' | 'quality-sts';\n label: string;\n /** Number of items to evaluate (subset of the bundled dataset). */\n items: number;\n}\n\nexport type BenchWorkloadSpec = LLMWorkloadSpec | EmbedWorkloadSpec | QualityWorkloadSpec;\n\n/** Static reference to a model as benchmarked in one runtime lane. */\nexport interface BenchModelRef {\n /** Cross-runtime pairing id, e.g. \"qwen3-0.6b\" — same weights family. */\n benchModelId: string;\n runtimeId: BenchRuntimeId;\n /** The provider-native model id passed to the runtime. */\n providerModelId: string;\n displayName: string;\n /** \"llm\" or \"embedding\". */\n task: 'llm' | 'embedding';\n parameterCount?: string;\n quantization?: string;\n sizeBytes?: number;\n contextLength?: number;\n /** Direct model URL when applicable (wllama GGUF, litert). */\n url?: string;\n requiresWebGPU?: boolean;\n}\n\n/** One recorded stream chunk: wall-clock timestamp + delta length in chars. */\nexport interface BenchChunk {\n /** `performance.now()` at chunk receipt (ms, page-relative). */\n t: number;\n /** Character length of this chunk's text delta. */\n c: number;\n}\n\n/** Provider-reported usage, recorded as auxiliary data (often estimated). */\nexport interface ProviderUsage {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n durationMs: number;\n /** How trustworthy the provider counts are for this runtime. */\n fidelity: 'measured' | 'estimated' | 'chunk-count';\n}\n\n/** One timed LLM generation iteration with its raw trace. */\nexport interface LLMIteration {\n /** `performance.now()` just before the stream is requested. */\n startT: number;\n /** Per-chunk receipt trace. TTFT derives from the first entry with c > 0. */\n chunks: BenchChunk[];\n /** `performance.now()` after the terminal chunk. */\n endT: number;\n /** Full generated text (enables post-hoc exact tokenization + auditing). */\n text: string;\n providerUsage?: ProviderUsage;\n finishReason?: string;\n /** Validity-gate events that fired during this iteration (empty = valid). */\n gates: string[];\n}\n\n/** One timed embedding iteration. */\nexport interface EmbedIteration {\n startT: number;\n endT: number;\n /** Number of texts embedded in this iteration. */\n count: number;\n /** Embedding dimensions reported by the model. */\n dimensions: number;\n gates: string[];\n}\n\n/** Model-load phase record for a cell (null when the cell reused a live model). */\nexport interface LoadRecord {\n /** Provider cache probe before load: true=warm, false=cold, undefined=unknown. */\n cached: boolean | undefined;\n startT: number;\n endT: number;\n /** Progress milestones (coarse, at most ~50 samples). */\n progress?: Array<{ t: number; pct: number }>;\n /** Catalog-declared download size, when known. */\n declaredBytes?: number;\n}\n\n/** Memory sampling at protocol points (Chromium-only APIs; absent elsewhere). */\nexport interface MemorySample {\n /** Bytes reported at suite baseline, after load, after timed runs. */\n baseline?: number;\n postLoad?: number;\n postRun?: number;\n api: 'uaSpecific' | 'legacyHeap' | 'none';\n}\n\n/** Quality lane outcome attached to a cell. */\nexport interface QualityResult {\n taskId: string;\n /** Primary score: accuracy (MMLU) or Spearman rho (STS). */\n score: number;\n n: number;\n /** Per-item correctness or per-pair cosine, for auditability. */\n details?: number[];\n}\n\nexport type BenchCellStatus = 'ok' | 'invalid' | 'error' | 'skipped';\n\n/** One benchmark cell: (runtime x model x workload) with its raw iterations. */\nexport interface BenchCellResult {\n /** `${runtimeId}/${benchModelId}/${workloadId}` */\n cellId: string;\n runtimeId: BenchRuntimeId;\n runtimeVersion?: string;\n model: BenchModelRef;\n workloadId: string;\n workloadKind: BenchWorkloadKind;\n /** Backend actually used (probed, never the requested one). */\n resolvedBackend: string;\n load: LoadRecord | null;\n /** Untimed warmup duration (ms), when a warmup ran. */\n warmupMs?: number;\n iterations: LLMIteration[] | EmbedIteration[];\n memory?: MemorySample;\n quality?: QualityResult;\n status: BenchCellStatus;\n invalidReasons?: string[];\n error?: { name: string; message: string };\n}\n\n/** Trace events global to the suite run (validity accounting). */\nexport interface TraceEvent {\n t: number;\n type:\n | 'suite-start'\n | 'suite-end'\n | 'visibility-hidden'\n | 'visibility-visible'\n | 'wakelock-acquired'\n | 'wakelock-released'\n | 'pressure-change'\n | 'gpu-device-lost'\n | 'cooldown-start'\n | 'cooldown-end'\n | 'abort';\n detail?: string;\n}\n\n/** Browser identification with its provenance. */\nexport interface BrowserInfo {\n name: string;\n version: string;\n source: 'ua-ch' | 'ua-parse';\n brands?: Array<{ brand: string; version: string }>;\n}\n\n/** OS identification. Version is 'unknown-frozen' on engines with frozen UAs. */\nexport interface OSInfo {\n platform: string;\n version: string;\n architecture?: string;\n bitness?: string;\n model?: string;\n}\n\n/** WebGPU adapter identity + selected limits (all fields may be empty strings). */\nexport interface GPUInfo {\n available: boolean;\n vendor?: string;\n architecture?: string;\n device?: string;\n description?: string;\n isFallbackAdapter?: boolean;\n features?: string[];\n limits?: Record<string, number>;\n}\n\n/** Full environment capture for a run. Clamped fields are labeled as such. */\nexport interface EnvironmentCapture {\n capturedAt: string;\n browser: BrowserInfo;\n os: OSInfo;\n hardware: {\n /** navigator.hardwareConcurrency — clamped/randomized on Gecko/WebKit. */\n cores: number | null;\n coresClamped: boolean;\n /** navigator.deviceMemory (GB) — Chromium-only, capped at 8. */\n deviceMemoryGB: number | null;\n deviceMemoryCapped: boolean;\n };\n gpu: GPUInfo;\n /** WebGL renderer string, a secondary GPU identity signal. */\n webglRenderer: string | null;\n flags: {\n crossOriginIsolated: boolean;\n sharedArrayBuffer: boolean;\n wasmSimd: boolean;\n };\n storage: { quotaBytes?: number; usageBytes?: number } | null;\n power: { batterySupported: boolean; charging?: boolean; level?: number };\n pressure: { supported: boolean; lastState?: string };\n /** Inferred performance.now() quantum in microseconds (grid inference). */\n timerResolutionUs: number | null;\n screen: { width: number; height: number; dpr: number } | null;\n languages?: string[];\n /** Free-text device self-report — displayed as \"user-reported\", never trusted. */\n userReportedDevice?: string;\n}\n\n/** Deterministic JS matmul microbenchmark result (hardware fingerprint). */\nexport interface FingerprintResult {\n /** Millions of fused multiply-adds per second. */\n mflops: number;\n n: number;\n iterations: number;\n durationMs: number;\n /** Checksum of the final matrix — proves the work actually ran. */\n checksum: number;\n}\n\n/** Statistical summary of one metric across iterations. */\nexport interface MetricSummary {\n n: number;\n median: number;\n mean: number;\n sd: number;\n iqr: number;\n min: number;\n max: number;\n /** 95% confidence interval half-width (Student-t). */\n ci95: number;\n /** Coefficient of variation (sd/mean), 0 when mean is 0. */\n cv: number;\n}\n\n/** Derived per-cell summary (recomputable from the raw trace by anyone). */\nexport interface CellSummary {\n cellId: string;\n status: BenchCellStatus;\n /** LLM lanes. */\n ttftMs?: MetricSummary;\n decodeCharsPerSec?: MetricSummary;\n decodeChunksPerSec?: MetricSummary;\n prefillTokPerSecApprox?: MetricSummary;\n generatedChars?: MetricSummary;\n /** Embedding lanes. */\n singleLatencyMs?: MetricSummary;\n batchTextsPerSec?: MetricSummary;\n /** Load phase. */\n loadMs?: number;\n loadCached?: boolean;\n qualityScore?: number;\n highVariance: boolean;\n}\n\n/** The unit of submission: one full suite run on one device. */\nexport interface BenchRunResult {\n protocol: typeof BENCH_PROTOCOL_VERSION;\n schemaVersion: typeof BENCH_SCHEMA_VERSION;\n runId: string;\n createdAt: string;\n harness: { name: string; version: string; appVersion?: string };\n suite: BenchSuiteId;\n environment: EnvironmentCapture;\n fingerprint: FingerprintResult | null;\n cells: BenchCellResult[];\n events: TraceEvent[];\n /** Client-computed summaries (advisory; server recomputes from the trace). */\n clientSummaries?: CellSummary[];\n /** Server-issued anti-forgery nonce (verified tier only). */\n nonce?: string;\n /** SHA-256 of the canonical JSON of this object without `digest`. */\n digest?: string;\n}\n\n/** A plausibility/integrity finding attached by validation. */\nexport interface PlausibilityFlag {\n code: string;\n cellId?: string;\n message: string;\n severity: 'warn' | 'reject';\n}\n\n/** Outcome of full validation (shape + recompute + plausibility). */\nexport interface ValidationReport {\n ok: boolean;\n shapeErrors: string[];\n flags: PlausibilityFlag[];\n summaries: CellSummary[];\n}\n","/**\n * Protocol constants: fixed public workloads and the run policy. These are\n * part of the versioned benchmark spec — any change to prompts, token budgets,\n * or policy numbers requires a protocol version bump (see BENCH_PROTOCOL_VERSION).\n *\n * Metric naming follows llama-bench conventions (ppN = prefill on an\n * N-token prompt, tgN = token generation over N tokens) and MLPerf Client\n * definitions (TTFT; decode rate excludes the first token).\n */\n\nimport type { EmbedWorkloadSpec, LLMWorkloadSpec, QualityWorkloadSpec } from './types.js';\n\n/**\n * ~128-token prompt (measured 512 chars). Original text, public domain.\n * Exact per-tokenizer counts are computed post-hoc from this fixed string.\n */\nconst PROMPT_PP128 = [\n 'You are helping a small public library plan its move to a new building across town.',\n 'The collection holds forty thousand books, two thousand audio recordings, and a local',\n 'history archive that must stay in labeled order. Volunteers are available on weekends',\n 'only, and the budget covers one rental truck. Describe a practical week-by-week moving',\n 'plan that keeps the library partially open, protects the archive, and finishes within',\n 'eight weeks. Be specific about labeling, sequencing, and volunteer coordination.',\n].join(' ');\n\n/** ~512-token prompt (measured 2178 chars). Original text, public domain. */\nconst PROMPT_PP512 = [\n 'Read the following notes from a town planning meeting and then answer the question at the end.',\n 'The town of Milbrook has grown from eight thousand residents to eleven thousand in six years.',\n 'The old water treatment plant, built fifty years ago, operates at ninety two percent of its',\n 'rated capacity during summer months. An engineering survey found that the intake pipes show',\n 'corrosion consistent with their age but no immediate risk of failure. Replacing the plant',\n 'entirely would cost an estimated thirty one million dollars and take four years, during which',\n 'a temporary treatment module would be rented at two hundred thousand dollars per month.',\n 'Upgrading the existing plant in three phases would cost nineteen million dollars, take six',\n 'years, and raise capacity by forty percent, but phase two requires shutting one of the three',\n 'treatment trains for nine months. The town engineer favors the upgrade because the town can',\n 'fund it from reserves plus a small bond, avoiding a rate increase larger than four percent.',\n 'The finance director notes that construction costs have risen eleven percent in two years and',\n 'argues that delaying the full replacement will only make it more expensive, and that a larger',\n 'bond issued now at current rates would cost less over thirty years than a later one. Several',\n 'residents raised concerns about summer watering restrictions during phase two, and a local',\n 'manufacturer that employs three hundred people said an unreliable water supply would force it',\n 'to install its own storage tanks at significant cost. The mayor asked both officials to prepare',\n 'a comparison covering total cost of ownership over thirty years, resilience during construction,',\n 'capacity margins in the final state, and the effect on household water rates under three growth',\n 'scenarios: flat, moderate, and rapid. The engineer also mentioned that federal infrastructure',\n 'grants covering up to twenty percent of qualifying water projects open for applications next',\n 'spring, though awards are competitive and would delay the start by at least eight months either way.',\n 'Question: Write a balanced recommendation memo to the town council. Weigh both options against',\n 'the four criteria the mayor listed, account for the grant opportunity, and end with a clear',\n 'recommendation and two conditions under which the council should switch to the other option.',\n].join(' ');\n\n/** Fixed generation budget for timed lanes (tg128, MLPerf-Client-sized). */\nexport const GENERATION_BUDGET = 128;\n\n/** LLM performance workloads. */\nexport const LLM_WORKLOADS: readonly LLMWorkloadSpec[] = [\n {\n id: 'chat-pp128-tg128',\n kind: 'llm-generate',\n label: 'Chat pp128/tg128',\n prompt: PROMPT_PP128,\n approxPromptTokens: 128,\n maxTokens: GENERATION_BUDGET,\n temperature: 0,\n },\n {\n id: 'chat-pp512-tg128',\n kind: 'llm-generate',\n label: 'Long-context pp512/tg128',\n prompt: PROMPT_PP512,\n approxPromptTokens: 512,\n maxTokens: GENERATION_BUDGET,\n temperature: 0,\n },\n] as const;\n\n/** Deterministic embedding corpus: 32 fixed ~200-char sentences. */\nfunction embedTexts(): string[] {\n const topics = [\n 'the maintenance schedule for a fleet of electric delivery vans in a coastal city',\n 'a beginner guide to fermenting vegetables safely at home in small batches',\n 'the migration patterns of shorebirds along the Atlantic flyway in autumn',\n 'how a public library catalogs and preserves regional oral history recordings',\n 'the tradeoffs between timber framing and steel framing for small workshops',\n 'a training plan that prepares a new runner for a half marathon in twenty weeks',\n 'the way tide pools support diverse life despite extreme daily changes',\n 'budgeting practices for a volunteer-run community theater production',\n ];\n const texts: string[] = [];\n for (let i = 0; i < 32; i++) {\n const topic = topics[i % topics.length];\n texts.push(\n `Document ${i + 1}: This passage explains ${topic}. It covers the key steps, ` +\n `common mistakes, expected costs, and a short checklist that a careful reader ` +\n `can apply immediately, with concrete numbers where they matter.`,\n );\n }\n return texts;\n}\n\nconst EMBED_TEXTS = embedTexts();\n\n/** Embedding performance workloads. */\nexport const EMBED_WORKLOADS: readonly EmbedWorkloadSpec[] = [\n {\n id: 'embed-single',\n kind: 'embed-single',\n label: 'Embedding single-query latency',\n texts: [EMBED_TEXTS[0]],\n },\n {\n id: 'embed-batch32',\n kind: 'embed-batch',\n label: 'Embedding batch-32 throughput',\n texts: EMBED_TEXTS,\n },\n] as const;\n\n/** Quality-fidelity workloads (separate lane, temperature 0). */\nexport const QUALITY_WORKLOADS: readonly QualityWorkloadSpec[] = [\n { id: 'quality-mmlu-25', kind: 'quality-mmlu', label: 'tinyMMLU fidelity (25 items)', items: 25 },\n { id: 'quality-mmlu-100', kind: 'quality-mmlu', label: 'tinyMMLU fidelity (100 items)', items: 100 },\n { id: 'quality-sts-100', kind: 'quality-sts', label: 'STS-B Spearman (100 pairs)', items: 100 },\n] as const;\n\n/** All workloads indexed by id. */\nexport const WORKLOADS_BY_ID: ReadonlyMap<\n string,\n LLMWorkloadSpec | EmbedWorkloadSpec | QualityWorkloadSpec\n> = new Map(\n [...LLM_WORKLOADS, ...EMBED_WORKLOADS, ...QUALITY_WORKLOADS].map((w) => [w.id, w]),\n);\n\n/** Run policy for a suite (part of the versioned protocol). */\nexport interface RunPolicy {\n /** Untimed warmup generations per cell (absorbs shader compile/JIT). */\n warmupRuns: number;\n /** Timed iterations per cell. */\n timedRuns: number;\n /** Idle cool-down between cells (thermal recovery), ms. */\n cooldownMs: number;\n /** Gate the next cell on Compute Pressure <= 'fair' when available. */\n pressureGate: boolean;\n /** Max wait for the pressure gate before proceeding anyway, ms. */\n pressureGateTimeoutMs: number;\n /** After a cold load, dispose + reload to also measure the warm load. */\n measureWarmReload: boolean;\n /** CV above this fraction marks a summary metric as high-variance. */\n highVarianceCv: number;\n}\n\n/** Policies per suite preset. */\nexport const RUN_POLICIES: Record<'quick' | 'standard' | 'thorough', RunPolicy> = {\n quick: {\n warmupRuns: 1,\n timedRuns: 3,\n cooldownMs: 5_000,\n pressureGate: true,\n pressureGateTimeoutMs: 15_000,\n measureWarmReload: false,\n highVarianceCv: 0.05,\n },\n standard: {\n warmupRuns: 1,\n timedRuns: 3,\n cooldownMs: 8_000,\n pressureGate: true,\n pressureGateTimeoutMs: 30_000,\n measureWarmReload: true,\n highVarianceCv: 0.05,\n },\n thorough: {\n warmupRuns: 1,\n timedRuns: 5,\n cooldownMs: 10_000,\n pressureGate: true,\n pressureGateTimeoutMs: 30_000,\n measureWarmReload: true,\n highVarianceCv: 0.05,\n },\n};\n","/**\n * Runtime adapter contract. Adapters wire a browser ML runtime (Transformers.js,\n * WebLLM, wllama, LiteRT, Chrome Built-in AI, MediaPipe) to the runner. They are\n * injected by the harness host (e.g. the localmode.ai bench page) so this\n * package stays free of provider dependencies — the same pattern the LocalMode\n * blocks use for provider wiring.\n *\n * The runner consumes the `@localmode/core` model interfaces structurally\n * (type-only peer dependency): any object with a compatible `doStream`/`doEmbed`\n * works, including models from other libraries.\n */\n\nimport type { BenchModelRef, BenchRuntimeId, ProviderUsage } from './types.js';\n\n/** Structural subset of `@localmode/core`'s StreamChunk. */\nexport interface BenchStreamChunk {\n text: string;\n done: boolean;\n finishReason?: string;\n usage?: {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n durationMs: number;\n };\n}\n\n/** Structural subset of `@localmode/core`'s LanguageModel. */\nexport interface BenchLanguageModel {\n readonly modelId: string;\n readonly provider: string;\n doStream?(options: {\n prompt: string;\n systemPrompt?: string;\n maxTokens?: number;\n temperature?: number;\n abortSignal?: AbortSignal;\n }): AsyncIterable<BenchStreamChunk>;\n doGenerate(options: {\n prompt: string;\n systemPrompt?: string;\n maxTokens?: number;\n temperature?: number;\n abortSignal?: AbortSignal;\n }): Promise<{ text: string; finishReason: string; usage: ProviderUsage | Omit<ProviderUsage, 'fidelity'> }>;\n}\n\n/** Structural subset of `@localmode/core`'s EmbeddingModel. */\nexport interface BenchEmbeddingModel {\n readonly modelId: string;\n readonly provider: string;\n readonly dimensions: number;\n doEmbed(options: { values: string[]; abortSignal?: AbortSignal }): Promise<{\n embeddings: Float32Array[];\n }>;\n}\n\n/** Availability probe result for a runtime lane on this device. */\nexport interface AdapterAvailability {\n ok: boolean;\n /** Human-readable reason when not available ('no WebGPU adapter', ...). */\n reason?: string;\n}\n\n/** Load-progress callback payload (normalized percent when known). */\nexport interface AdapterLoadProgress {\n pct?: number;\n}\n\n/** A loaded LLM handle: the model plus its resolved execution backend. */\nexport interface LoadedLLM {\n model: BenchLanguageModel;\n /** Backend actually in use — 'webgpu' | 'wasm' | 'gpu' | 'cpu' | 'chrome-builtin'. */\n resolvedBackend: string;\n dispose(): Promise<void>;\n}\n\n/** A loaded embedding-model handle. */\nexport interface LoadedEmbedder {\n model: BenchEmbeddingModel;\n resolvedBackend: string;\n dispose(): Promise<void>;\n}\n\n/** Adapter for an LLM runtime lane. */\nexport interface LLMRuntimeAdapter {\n readonly runtimeId: BenchRuntimeId;\n readonly displayName: string;\n /** Underlying runtime library version, when known (recorded per cell). */\n readonly runtimeVersion?: string;\n /** Is this lane usable on the current device/browser? */\n isAvailable(): Promise<AdapterAvailability>;\n /** Provider cache probe — true=warm, false=cold, undefined=unknown. */\n isModelCached(model: BenchModelRef): Promise<boolean | undefined>;\n /** Load (download + compile) the model. Must NOT run any inference. */\n load(\n model: BenchModelRef,\n options: { onProgress?: (p: AdapterLoadProgress) => void; abortSignal?: AbortSignal },\n ): Promise<LoadedLLM>;\n}\n\n/** Adapter for an embedding runtime lane. */\nexport interface EmbeddingRuntimeAdapter {\n readonly runtimeId: BenchRuntimeId;\n readonly displayName: string;\n readonly runtimeVersion?: string;\n isAvailable(): Promise<AdapterAvailability>;\n isModelCached(model: BenchModelRef): Promise<boolean | undefined>;\n load(\n model: BenchModelRef,\n options: { onProgress?: (p: AdapterLoadProgress) => void; abortSignal?: AbortSignal },\n ): Promise<LoadedEmbedder>;\n}\n\n/** Usage fidelity per runtime — how trustworthy provider token counts are. */\nexport const USAGE_FIDELITY: Record<BenchRuntimeId, ProviderUsage['fidelity']> = {\n 'transformers-webgpu': 'estimated',\n 'transformers-wasm': 'estimated',\n webllm: 'chunk-count',\n wllama: 'estimated',\n litert: 'estimated',\n 'chrome-ai': 'estimated',\n mediapipe: 'estimated',\n};\n","/**\n * Wall-clock timing helpers. All benchmark timestamps use `performance.now()`\n * (5 µs resolution on cross-origin-isolated Chromium, coarser elsewhere);\n * decode rates are derived from endpoint timestamps, never from averaged\n * per-token deltas, because per-token gaps sit at or below timer quantization.\n */\n\n/** Monotonic high-resolution timestamp in ms (performance.now, Date fallback). */\nexport function hrNow(): number {\n return typeof performance !== 'undefined' ? performance.now() : Date.now();\n}\n\n/**\n * Infer the effective `performance.now()` quantum by sampling timer deltas.\n * Genuine traces sit on this grid; the value is recorded in the environment\n * capture and used by the timer-grid integrity check.\n *\n * @param samples - Number of distinct increments to observe (default 64).\n * @returns Inferred quantum in microseconds, or null outside a browser.\n * @example\n * const q = inferTimerResolutionUs(); // 5 on isolated Chromium\n */\nexport function inferTimerResolutionUs(samples = 64): number | null {\n if (typeof performance === 'undefined') return null;\n const deltas: number[] = [];\n let prev = performance.now();\n let guard = 0;\n while (deltas.length < samples && guard < 2_000_000) {\n const t = performance.now();\n if (t > prev) {\n deltas.push(t - prev);\n prev = t;\n }\n guard++;\n }\n if (deltas.length === 0) return null;\n const minDelta = Math.min(...deltas);\n return Math.round(minDelta * 1000 * 100) / 100;\n}\n\n/** Await a real delay (setTimeout) — used for cool-downs between cells. */\nexport function sleep(ms: number, abortSignal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (abortSignal?.aborted) {\n reject(abortDomException());\n return;\n }\n const id = setTimeout(() => {\n abortSignal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n function onAbort() {\n clearTimeout(id);\n reject(abortDomException());\n }\n abortSignal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\n/** A DOMException('AbortError') that also works in non-DOM environments. */\nexport function abortDomException(): Error {\n if (typeof DOMException !== 'undefined') return new DOMException('Aborted', 'AbortError');\n const err = new Error('Aborted');\n err.name = 'AbortError';\n return err;\n}\n","/**\n * Suite-level trace recorder: validity-relevant events (tab visibility, wake\n * lock, compute pressure, GPU device loss, aborts) with wall-clock timestamps.\n * Iterations that overlap a hidden period are invalidated, never retried\n * silently — the trace is part of the submitted, auditable record.\n */\n\nimport type { TraceEvent } from './types.js';\nimport { hrNow } from './timing.js';\n\ntype PressureRecord = { state: string };\ninterface PressureObserverLike {\n observe(source: string, options?: { sampleInterval?: number }): Promise<void> | void;\n disconnect(): void;\n}\n\n/** Records trace events and tracks the current validity-gate state. */\nexport class TraceRecorder {\n private readonly events: TraceEvent[] = [];\n private disposers: Array<() => void> = [];\n private hidden = false;\n private lastPressureState: string | undefined;\n private wakeLockSentinel: { release(): Promise<void>; addEventListener?: unknown } | null = null;\n\n /** Append an event at the current timestamp. */\n record(type: TraceEvent['type'], detail?: string): void {\n this.events.push({ t: hrNow(), type, ...(detail !== undefined ? { detail } : {}) });\n }\n\n /** True while the page is hidden (timed regions overlapping this are invalid). */\n get isHidden(): boolean {\n return this.hidden;\n }\n\n /** Last observed compute-pressure state ('nominal'|'fair'|'serious'|'critical'). */\n get pressureState(): string | undefined {\n return this.lastPressureState;\n }\n\n /** All recorded events (live reference; snapshot with `[...events]`). */\n get all(): readonly TraceEvent[] {\n return this.events;\n }\n\n /**\n * Attach browser listeners (visibility, compute pressure) and request a\n * screen wake lock. Safe to call outside a browser (records nothing).\n */\n async attach(): Promise<void> {\n if (typeof document !== 'undefined') {\n const onVisibility = () => {\n this.hidden = document.visibilityState === 'hidden';\n this.record(this.hidden ? 'visibility-hidden' : 'visibility-visible');\n };\n document.addEventListener('visibilitychange', onVisibility);\n this.disposers.push(() => document.removeEventListener('visibilitychange', onVisibility));\n this.hidden = document.visibilityState === 'hidden';\n }\n\n const PressureObserverCtor = (\n globalThis as { PressureObserver?: new (cb: (records: PressureRecord[]) => void) => PressureObserverLike }\n ).PressureObserver;\n if (PressureObserverCtor) {\n try {\n const observer = new PressureObserverCtor((records) => {\n const last = records[records.length - 1];\n if (last) {\n this.lastPressureState = last.state;\n this.record('pressure-change', last.state);\n }\n });\n await observer.observe('cpu', { sampleInterval: 1_000 });\n this.disposers.push(() => observer.disconnect());\n } catch {\n // Pressure observation is best-effort context, never a failure.\n }\n }\n\n const wakeLock = typeof navigator !== 'undefined'\n ? (navigator as { wakeLock?: { request(type: 'screen'): Promise<{ release(): Promise<void>; addEventListener(t: string, cb: () => void): void }> } }).wakeLock\n : undefined;\n if (wakeLock) {\n try {\n const sentinel = await wakeLock.request('screen');\n this.wakeLockSentinel = sentinel;\n this.record('wakelock-acquired');\n sentinel.addEventListener('release', () => {\n this.record('wakelock-released');\n this.wakeLockSentinel = null;\n });\n } catch {\n // Wake lock denial (battery saver, etc.) is recorded implicitly by absence.\n }\n }\n }\n\n /** Release listeners and the wake lock. */\n async dispose(): Promise<void> {\n for (const dispose of this.disposers) dispose();\n this.disposers = [];\n if (this.wakeLockSentinel) {\n try {\n await this.wakeLockSentinel.release();\n } catch {\n // Already released.\n }\n this.wakeLockSentinel = null;\n }\n }\n}\n","/**\n * Memory sampling at protocol points (baseline / post-load / post-run).\n * Uses `performance.measureUserAgentSpecificMemory()` (Chromium, requires\n * cross-origin isolation, resolves at the next GC — up to ~20 s), with the\n * legacy Chromium JS-heap as fallback. Never call inside a timed region.\n */\n\n/** Which memory API is usable in this context. */\nexport function memoryApiAvailable(): 'uaSpecific' | 'legacyHeap' | 'none' {\n if (\n typeof performance !== 'undefined' &&\n 'measureUserAgentSpecificMemory' in performance &&\n typeof crossOriginIsolated !== 'undefined' &&\n crossOriginIsolated\n ) {\n return 'uaSpecific';\n }\n if (\n typeof performance !== 'undefined' &&\n 'memory' in performance &&\n typeof (performance as { memory?: { usedJSHeapSize?: number } }).memory?.usedJSHeapSize ===\n 'number'\n ) {\n return 'legacyHeap';\n }\n return 'none';\n}\n\n/**\n * Sample total page memory in bytes, or null when unavailable / timed out.\n * The UA-specific measurement is raced against `timeoutMs` because it only\n * resolves at the next garbage collection.\n *\n * @param timeoutMs - Max wait for the GC-gated measurement (default 25000).\n * @example\n * const bytes = await sampleMemoryBytes(); // 734003200 | null\n */\nexport async function sampleMemoryBytes(timeoutMs = 25_000): Promise<number | null> {\n const api = memoryApiAvailable();\n if (api === 'uaSpecific') {\n try {\n const result = await Promise.race([\n (\n performance as unknown as {\n measureUserAgentSpecificMemory: () => Promise<{ bytes: number }>;\n }\n ).measureUserAgentSpecificMemory(),\n new Promise<null>((resolve) => setTimeout(() => resolve(null), timeoutMs)),\n ]);\n if (result && typeof result.bytes === 'number') return result.bytes;\n } catch {\n // fall through to legacy\n }\n }\n if (api !== 'none') {\n const legacy = (performance as { memory?: { usedJSHeapSize?: number } }).memory;\n if (typeof legacy?.usedJSHeapSize === 'number') return legacy.usedJSHeapSize;\n }\n return null;\n}\n","/**\n * Environment capture. Records identity + capability signals with honest\n * provenance: UA Client Hints on Chromium; UA parsing elsewhere with the OS\n * version marked 'unknown-frozen' (UA strings are frozen by design on Gecko\n * and WebKit). Clamped fields (cores, deviceMemory) are labeled clamped.\n */\n\nimport type { BrowserInfo, EnvironmentCapture, GPUInfo, OSInfo } from './types.js';\nimport { inferTimerResolutionUs } from './timing.js';\n\n/** Minimal structural types for APIs TypeScript's DOM lib may not carry. */\ninterface UADataBrand {\n brand: string;\n version: string;\n}\ninterface NavigatorUAData {\n brands: UADataBrand[];\n getHighEntropyValues(hints: string[]): Promise<Record<string, unknown>>;\n}\n\n/** WebGPU limits worth recording (identity + capacity signals, all numbers). */\nconst GPU_LIMIT_KEYS = [\n 'maxBufferSize',\n 'maxStorageBufferBindingSize',\n 'maxComputeWorkgroupStorageSize',\n 'maxComputeInvocationsPerWorkgroup',\n 'maxComputeWorkgroupSizeX',\n] as const;\n\n/**\n * Capture the full benchmark environment. Never throws — every probe is\n * individually guarded and absent signals are recorded as absent.\n *\n * @param options.userReportedDevice - Optional free-text device self-report\n * (displayed as \"user-reported\", never treated as ground truth).\n * @example\n * const env = await captureEnvironment();\n */\nexport async function captureEnvironment(options?: {\n userReportedDevice?: string;\n}): Promise<EnvironmentCapture> {\n const nav = typeof navigator !== 'undefined' ? navigator : undefined;\n\n const { browser, os } = await identifyBrowserAndOS(nav);\n const gpu = await probeWebGPU(nav);\n\n return {\n capturedAt: new Date().toISOString(),\n browser,\n os,\n hardware: {\n cores: nav?.hardwareConcurrency ?? null,\n coresClamped: browser.name !== 'Chrome' && browser.name !== 'Edge',\n deviceMemoryGB:\n nav && 'deviceMemory' in nav ? ((nav as { deviceMemory?: number }).deviceMemory ?? null) : null,\n deviceMemoryCapped: true,\n },\n gpu,\n webglRenderer: probeWebGLRenderer(),\n flags: {\n crossOriginIsolated: typeof crossOriginIsolated !== 'undefined' ? crossOriginIsolated : false,\n sharedArrayBuffer: typeof SharedArrayBuffer !== 'undefined',\n wasmSimd: probeWasmSimd(),\n },\n storage: await probeStorage(nav),\n power: await probeBattery(nav),\n pressure: {\n supported: typeof globalThis !== 'undefined' && 'PressureObserver' in globalThis,\n },\n timerResolutionUs: inferTimerResolutionUs(),\n screen:\n typeof screen !== 'undefined'\n ? {\n width: screen.width,\n height: screen.height,\n dpr: typeof devicePixelRatio !== 'undefined' ? devicePixelRatio : 1,\n }\n : null,\n languages: nav?.languages ? [...nav.languages].slice(0, 3) : undefined,\n userReportedDevice: options?.userReportedDevice,\n };\n}\n\n/** Identify the browser + OS with provenance. */\nasync function identifyBrowserAndOS(\n nav: Navigator | undefined,\n): Promise<{ browser: BrowserInfo; os: OSInfo }> {\n const uaData = nav && 'userAgentData' in nav\n ? ((nav as { userAgentData?: NavigatorUAData }).userAgentData)\n : undefined;\n\n if (uaData) {\n try {\n const high = await uaData.getHighEntropyValues([\n 'platform',\n 'platformVersion',\n 'architecture',\n 'bitness',\n 'model',\n 'fullVersionList',\n ]);\n const list =\n (high.fullVersionList as UADataBrand[] | undefined) ?? uaData.brands ?? [];\n const primary =\n list.find((b) => !/not.?a.?brand/i.test(b.brand) && b.brand !== 'Chromium') ??\n list.find((b) => !/not.?a.?brand/i.test(b.brand));\n return {\n browser: {\n name: primary?.brand ?? 'Chromium',\n version: primary?.version ?? 'unknown',\n source: 'ua-ch',\n brands: list.map((b) => ({ brand: b.brand, version: b.version })),\n },\n os: {\n platform: String(high.platform ?? 'unknown'),\n version: String(high.platformVersion ?? 'unknown'),\n architecture: high.architecture ? String(high.architecture) : undefined,\n bitness: high.bitness ? String(high.bitness) : undefined,\n model: high.model ? String(high.model) : undefined,\n },\n };\n } catch {\n // fall through to UA parsing\n }\n }\n\n const ua = nav?.userAgent ?? '';\n return { browser: parseUABrowser(ua), os: parseUAOS(ua) };\n}\n\n/** Conservative UA parsing: browser + major version only. */\nfunction parseUABrowser(ua: string): BrowserInfo {\n const rules: Array<[string, RegExp]> = [\n ['Firefox', /Firefox\\/(\\d+[\\d.]*)/],\n ['Edge', /Edg(?:e|A|iOS)?\\/(\\d+[\\d.]*)/],\n ['Safari', /Version\\/(\\d+[\\d.]*).*Safari/],\n ['Chrome', /Chrome\\/(\\d+[\\d.]*)/],\n ];\n for (const [name, re] of rules) {\n const m = ua.match(re);\n if (m) return { name, version: m[1], source: 'ua-parse' };\n }\n return { name: 'unknown', version: 'unknown', source: 'ua-parse' };\n}\n\n/** OS from UA. Version is 'unknown-frozen' — UA OS versions are frozen/capped. */\nfunction parseUAOS(ua: string): OSInfo {\n let platform = 'unknown';\n if (/Windows/.test(ua)) platform = 'Windows';\n else if (/iPhone|iPad|iPod/.test(ua)) platform = 'iOS';\n else if (/Mac OS X/.test(ua)) platform = 'macOS';\n else if (/Android/.test(ua)) platform = 'Android';\n else if (/Linux/.test(ua)) platform = 'Linux';\n return { platform, version: 'unknown-frozen' };\n}\n\n/** Structural WebGPU types (the TS DOM lib may not include WebGPU). */\ninterface GPUAdapterLike {\n info?: Record<string, unknown>;\n limits?: unknown;\n features?: Iterable<string>;\n}\ninterface GPULike {\n requestAdapter(): Promise<GPUAdapterLike | null>;\n}\n\n/** Probe the WebGPU adapter identity via the `adapter.info` attribute. */\nasync function probeWebGPU(nav: Navigator | undefined): Promise<GPUInfo> {\n const gpu = nav && 'gpu' in nav ? (nav as { gpu?: GPULike }).gpu : undefined;\n if (!gpu) return { available: false };\n try {\n const adapter = await Promise.race([\n gpu.requestAdapter(),\n new Promise<null>((resolve) => setTimeout(() => resolve(null), 3_000)),\n ]);\n if (!adapter) return { available: false };\n const info = adapter.info ?? {};\n const limits: Record<string, number> = {};\n const adapterLimits = adapter.limits as Record<string, number> | undefined;\n if (adapterLimits) {\n for (const key of GPU_LIMIT_KEYS) {\n const v = adapterLimits[key];\n if (typeof v === 'number') limits[key] = v;\n }\n }\n return {\n available: true,\n vendor: str(info.vendor),\n architecture: str(info.architecture),\n device: str(info.device),\n description: str(info.description),\n isFallbackAdapter:\n typeof info.isFallbackAdapter === 'boolean' ? info.isFallbackAdapter : undefined,\n features: adapter.features ? [...(adapter.features as Iterable<string>)].sort() : undefined,\n limits,\n };\n } catch {\n return { available: false };\n }\n}\n\nfunction str(v: unknown): string | undefined {\n return typeof v === 'string' && v.length > 0 ? v : undefined;\n}\n\n/** WebGL renderer string (secondary GPU identity signal). */\nfunction probeWebGLRenderer(): string | null {\n try {\n if (typeof document === 'undefined') return null;\n const canvas = document.createElement('canvas');\n const gl =\n (canvas.getContext('webgl2') as WebGL2RenderingContext | null) ??\n (canvas.getContext('webgl') as WebGLRenderingContext | null);\n if (!gl) return null;\n const ext = gl.getExtension('WEBGL_debug_renderer_info');\n const renderer = ext\n ? (gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) as string)\n : (gl.getParameter(gl.RENDERER) as string);\n return typeof renderer === 'string' ? renderer : null;\n } catch {\n return null;\n }\n}\n\n/** WASM SIMD support via WebAssembly.validate of a canonical SIMD module. */\nfunction probeWasmSimd(): boolean {\n try {\n // Minimal module containing a v128 operation (standard detection bytes).\n return WebAssembly.validate(\n new Uint8Array([\n 0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 10, 1, 8, 0, 65, 0,\n 253, 15, 253, 98, 11,\n ]),\n );\n } catch {\n return false;\n }\n}\n\nasync function probeStorage(\n nav: Navigator | undefined,\n): Promise<{ quotaBytes?: number; usageBytes?: number } | null> {\n try {\n if (!nav?.storage?.estimate) return null;\n const est = await nav.storage.estimate();\n return { quotaBytes: est.quota ?? undefined, usageBytes: est.usage ?? undefined };\n } catch {\n return null;\n }\n}\n\nasync function probeBattery(\n nav: Navigator | undefined,\n): Promise<{ batterySupported: boolean; charging?: boolean; level?: number }> {\n try {\n const getBattery = nav && 'getBattery' in nav\n ? (nav as { getBattery?: () => Promise<{ charging: boolean; level: number }> }).getBattery\n : undefined;\n if (!getBattery) return { batterySupported: false };\n const battery = await getBattery.call(nav);\n return { batterySupported: true, charging: battery.charging, level: battery.level };\n } catch {\n return { batterySupported: false };\n }\n}\n","/**\n * Deterministic single-thread JS matmul microbenchmark. Every submission runs\n * it; the resulting MFLOPS is a hardware fingerprint that claimed inference\n * rates must plausibly correlate with, and the checksum proves the work ran.\n */\n\nimport type { FingerprintResult } from './types.js';\nimport { hrNow } from './timing.js';\n\n/** Deterministic LCG so every device multiplies the same matrices. */\nfunction lcg(seed: number): () => number {\n let s = seed >>> 0;\n return () => {\n s = (Math.imul(s, 1664525) + 1013904223) >>> 0;\n return s / 0xffffffff;\n };\n}\n\n/**\n * Run the fingerprint microbenchmark: repeated n x n f32 matmuls for at least\n * `minDurationMs`, single-threaded, deterministic inputs.\n *\n * @param options.n - Matrix dimension (default 160; ~8.2 MFLOP per iteration).\n * @param options.minDurationMs - Minimum wall time to run (default 600).\n * @returns MFLOPS, iteration count, and a checksum of the final product.\n * @example\n * const fp = await runFingerprint(); // { mflops: 1800.4, ... }\n */\nexport async function runFingerprint(options?: {\n n?: number;\n minDurationMs?: number;\n}): Promise<FingerprintResult> {\n const n = options?.n ?? 160;\n const minDurationMs = options?.minDurationMs ?? 600;\n const rand = lcg(0xbe7c4);\n const a = new Float32Array(n * n);\n const b = new Float32Array(n * n);\n for (let i = 0; i < n * n; i++) {\n a[i] = rand() - 0.5;\n b[i] = rand() - 0.5;\n }\n const c = new Float32Array(n * n);\n const flopsPerIter = 2 * n * n * n;\n let iterations = 0;\n const start = hrNow();\n let elapsed = 0;\n while (elapsed < minDurationMs) {\n matmul(a, b, c, n);\n iterations++;\n elapsed = hrNow() - start;\n // Yield to the event loop every few iterations so validity-gate listeners\n // (visibilitychange, abort) can run during the fingerprint.\n if (iterations % 4 === 0) await Promise.resolve();\n }\n let checksum = 0;\n for (let i = 0; i < n * n; i += 97) checksum += c[i];\n return {\n mflops: (flopsPerIter * iterations) / (elapsed * 1000),\n n,\n iterations,\n durationMs: elapsed,\n checksum: Math.fround(checksum),\n };\n}\n\n/** Naive row-major matmul (deliberately unoptimized and stable across engines). */\nfunction matmul(a: Float32Array, b: Float32Array, c: Float32Array, n: number): void {\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) {\n let acc = 0;\n for (let k = 0; k < n; k++) acc += a[i * n + k] * b[k * n + j];\n c[i * n + j] = acc;\n }\n }\n}\n","/**\n * Statistics for benchmark reporting: median headline, mean ± SD, IQR, 95% CI\n * (Student-t for the small n this protocol uses), CV, and geometric mean for\n * cross-workload aggregation (never across devices).\n */\n\nimport type { MetricSummary } from './types.js';\n\n/** Two-sided 95% Student-t critical values by degrees of freedom (1..30). */\nconst T_95: number[] = [\n 12.706, 4.303, 3.182, 2.776, 2.571, 2.447, 2.365, 2.306, 2.262, 2.228, 2.201, 2.179, 2.16,\n 2.145, 2.131, 2.12, 2.11, 2.101, 2.093, 2.086, 2.08, 2.074, 2.069, 2.064, 2.06, 2.056, 2.052,\n 2.048, 2.045, 2.042,\n];\n\n/** Sorted copy helper. */\nfunction sorted(values: readonly number[]): number[] {\n return [...values].sort((a, b) => a - b);\n}\n\n/**\n * Linear-interpolated quantile (type-7, the R/NumPy default).\n *\n * @param values - Sample values (need not be sorted).\n * @param q - Quantile in [0, 1].\n * @returns The interpolated quantile.\n * @throws {RangeError} When `values` is empty or `q` is out of range.\n * @example\n * quantile([1, 2, 3, 4], 0.5); // 2.5\n */\nexport function quantile(values: readonly number[], q: number): number {\n if (values.length === 0) throw new RangeError('quantile() requires a non-empty sample');\n if (q < 0 || q > 1) throw new RangeError(`quantile q must be in [0,1], got ${q}`);\n const s = sorted(values);\n const pos = (s.length - 1) * q;\n const lo = Math.floor(pos);\n const hi = Math.ceil(pos);\n if (lo === hi) return s[lo];\n return s[lo] + (s[hi] - s[lo]) * (pos - lo);\n}\n\n/** Median of a sample. @see quantile */\nexport function median(values: readonly number[]): number {\n return quantile(values, 0.5);\n}\n\n/** Arithmetic mean. @throws {RangeError} on an empty sample. */\nexport function mean(values: readonly number[]): number {\n if (values.length === 0) throw new RangeError('mean() requires a non-empty sample');\n let sum = 0;\n for (const v of values) sum += v;\n return sum / values.length;\n}\n\n/** Sample standard deviation (n-1 denominator). Returns 0 for n < 2. */\nexport function stddev(values: readonly number[]): number {\n if (values.length < 2) return 0;\n const m = mean(values);\n let acc = 0;\n for (const v of values) acc += (v - m) * (v - m);\n return Math.sqrt(acc / (values.length - 1));\n}\n\n/**\n * Geometric mean. Used to aggregate across workloads within one device run\n * (Speedometer/JetStream convention). All values must be positive.\n *\n * @throws {RangeError} on an empty sample or non-positive values.\n */\nexport function geomean(values: readonly number[]): number {\n if (values.length === 0) throw new RangeError('geomean() requires a non-empty sample');\n let acc = 0;\n for (const v of values) {\n if (v <= 0) throw new RangeError(`geomean() requires positive values, got ${v}`);\n acc += Math.log(v);\n }\n return Math.exp(acc / values.length);\n}\n\n/**\n * Full summary of one metric across timed iterations.\n *\n * @param values - One value per timed iteration (ms, tok/s, ...).\n * @returns Median headline plus dispersion measures; `ci95` is the Student-t\n * 95% half-width (0 when n < 2).\n * @example\n * summarize([102, 99, 104]).median; // 102\n */\nexport function summarize(values: readonly number[]): MetricSummary {\n if (values.length === 0) throw new RangeError('summarize() requires a non-empty sample');\n const n = values.length;\n const m = mean(values);\n const sd = stddev(values);\n const s = sorted(values);\n const ci95 = n >= 2 ? (T_95[Math.min(n - 2, T_95.length - 1)] * sd) / Math.sqrt(n) : 0;\n return {\n n,\n median: median(values),\n mean: m,\n sd,\n iqr: quantile(values, 0.75) - quantile(values, 0.25),\n min: s[0],\n max: s[n - 1],\n ci95,\n cv: m === 0 ? 0 : sd / Math.abs(m),\n };\n}\n\n/**\n * Spearman rank correlation between two equal-length samples, with average\n * ranks for ties. Used by the STS embedding-quality lane.\n *\n * @returns rho in [-1, 1].\n * @throws {RangeError} when lengths differ or n < 2.\n */\nexport function spearman(a: readonly number[], b: readonly number[]): number {\n if (a.length !== b.length) throw new RangeError('spearman() requires equal-length samples');\n if (a.length < 2) throw new RangeError('spearman() requires n >= 2');\n const ra = ranks(a);\n const rb = ranks(b);\n return pearson(ra, rb);\n}\n\n/** Average ranks (1-based) with tie handling. */\nfunction ranks(values: readonly number[]): number[] {\n const idx = values.map((v, i) => [v, i] as const).sort((x, y) => x[0] - y[0]);\n const out = new Array<number>(values.length);\n let i = 0;\n while (i < idx.length) {\n let j = i;\n while (j + 1 < idx.length && idx[j + 1][0] === idx[i][0]) j++;\n const avgRank = (i + j) / 2 + 1;\n for (let k = i; k <= j; k++) out[idx[k][1]] = avgRank;\n i = j + 1;\n }\n return out;\n}\n\n/** Pearson correlation. Returns 0 when either sample has zero variance. */\nfunction pearson(a: readonly number[], b: readonly number[]): number {\n const ma = mean(a);\n const mb = mean(b);\n let num = 0;\n let da = 0;\n let db = 0;\n for (let i = 0; i < a.length; i++) {\n const xa = a[i] - ma;\n const xb = b[i] - mb;\n num += xa * xb;\n da += xa * xa;\n db += xb * xb;\n }\n const den = Math.sqrt(da * db);\n return den === 0 ? 0 : num / den;\n}\n","/**\n * Validation: structural schema checks, deterministic summary recomputation\n * from raw traces (the same code runs client- and server-side), and versioned\n * plausibility/integrity checks for community submissions. Flags are attached,\n * never silently dropped — flagged runs are quarantined publicly.\n */\n\nimport type {\n BenchCellResult,\n BenchRunResult,\n CellSummary,\n EmbedIteration,\n LLMIteration,\n MetricSummary,\n PlausibilityFlag,\n ValidationReport,\n} from './types.js';\nimport { BENCH_PROTOCOL_VERSION, BENCH_SCHEMA_VERSION } from './types.js';\nimport { summarize } from './stats.js';\n\n/** Version of the plausibility rule set (recorded alongside moderation). */\nexport const PLAUSIBILITY_RULES_VERSION = 1;\n\n/** Decode-rate envelopes (chars/sec) per model-size class — deliberately loose. */\nconst DECODE_ENVELOPE_CHARS_PER_SEC: Array<{ maxBytes: number; max: number }> = [\n { maxBytes: 500_000_000, max: 4_000 },\n { maxBytes: 1_000_000_000, max: 2_500 },\n { maxBytes: 2_000_000_000, max: 1_500 },\n { maxBytes: Number.POSITIVE_INFINITY, max: 1_000 },\n];\n\n/** Max plausible embedding throughput (texts/sec) — loose upper bound. */\nconst EMBED_ENVELOPE_TEXTS_PER_SEC = 2_000;\n\n/** GPU-identity substrings that mean the \"GPU\" is a software or virtual renderer. */\nconst SOFTWARE_RENDERER_PATTERNS: readonly RegExp[] = [\n /swiftshader/i,\n /llvmpipe/i,\n /softpipe/i,\n /\\bwarp\\b/i,\n /microsoft basic render/i,\n /parallels/i,\n /vmware/i,\n /virtio/i,\n /virtualbox/i,\n];\n\n/**\n * Structural validation of a submitted result. Returns human-readable errors\n * (empty array = shape ok). Deliberately hand-rolled: this package is\n * zero-dependency and the checks double as executable schema documentation.\n */\nexport function validateRunShape(value: unknown): string[] {\n const errors: string[] = [];\n const push = (msg: string) => {\n if (errors.length < 50) errors.push(msg);\n };\n if (typeof value !== 'object' || value === null) return ['result must be an object'];\n const run = value as Record<string, unknown>;\n\n if (run.protocol !== BENCH_PROTOCOL_VERSION) push(`protocol must be \"${BENCH_PROTOCOL_VERSION}\"`);\n if (run.schemaVersion !== BENCH_SCHEMA_VERSION) push(`schemaVersion must be ${BENCH_SCHEMA_VERSION}`);\n if (typeof run.runId !== 'string' || run.runId.length < 8 || run.runId.length > 64) {\n push('runId must be a string (8-64 chars)');\n }\n if (typeof run.createdAt !== 'string' || Number.isNaN(Date.parse(run.createdAt as string))) {\n push('createdAt must be an ISO date string');\n }\n const harness = run.harness as Record<string, unknown> | undefined;\n if (!harness || typeof harness.name !== 'string' || typeof harness.version !== 'string') {\n push('harness {name, version} is required');\n }\n if (!['quick', 'standard', 'thorough', 'custom'].includes(run.suite as string)) {\n push('suite must be quick|standard|thorough|custom');\n }\n const env = run.environment as Record<string, unknown> | undefined;\n if (!env || typeof env !== 'object') push('environment is required');\n else {\n const browser = env.browser as Record<string, unknown> | undefined;\n if (!browser || typeof browser.name !== 'string') push('environment.browser.name is required');\n if (!env.os || typeof (env.os as Record<string, unknown>).platform !== 'string') {\n push('environment.os.platform is required');\n }\n }\n if (!Array.isArray(run.cells)) push('cells must be an array');\n else if ((run.cells as unknown[]).length === 0) push('cells must not be empty');\n else if ((run.cells as unknown[]).length > 500) push('cells exceeds the 500-cell limit');\n else {\n (run.cells as unknown[]).forEach((c, i) => validateCellShape(c, i, push));\n }\n if (!Array.isArray(run.events)) push('events must be an array');\n return errors;\n}\n\nfunction validateCellShape(value: unknown, index: number, push: (m: string) => void): void {\n if (typeof value !== 'object' || value === null) {\n push(`cells[${index}] must be an object`);\n return;\n }\n const cell = value as Record<string, unknown>;\n const at = `cells[${index}]`;\n if (typeof cell.cellId !== 'string') push(`${at}.cellId must be a string`);\n if (typeof cell.runtimeId !== 'string') push(`${at}.runtimeId must be a string`);\n if (typeof cell.workloadId !== 'string') push(`${at}.workloadId must be a string`);\n if (!['ok', 'invalid', 'error', 'skipped'].includes(cell.status as string)) {\n push(`${at}.status must be ok|invalid|error|skipped`);\n }\n const model = cell.model as Record<string, unknown> | undefined;\n if (!model || typeof model.benchModelId !== 'string' || typeof model.providerModelId !== 'string') {\n push(`${at}.model {benchModelId, providerModelId} is required`);\n }\n if (!Array.isArray(cell.iterations)) {\n push(`${at}.iterations must be an array`);\n return;\n }\n (cell.iterations as unknown[]).forEach((it, j) => {\n if (typeof it !== 'object' || it === null) {\n push(`${at}.iterations[${j}] must be an object`);\n return;\n }\n const iter = it as Record<string, unknown>;\n if (typeof iter.startT !== 'number' || typeof iter.endT !== 'number') {\n push(`${at}.iterations[${j}] needs numeric startT/endT`);\n }\n if ('chunks' in iter && !Array.isArray(iter.chunks)) {\n push(`${at}.iterations[${j}].chunks must be an array`);\n }\n if ('text' in iter && typeof iter.text === 'string' && (iter.text as string).length > 20_000) {\n push(`${at}.iterations[${j}].text exceeds 20000 chars`);\n }\n });\n}\n\n/** True when the iteration array is the LLM shape (has chunk traces). */\nfunction isLLMIterations(iterations: BenchCellResult['iterations']): iterations is LLMIteration[] {\n return iterations.length > 0 && 'chunks' in iterations[0];\n}\n\n/**\n * Recompute a cell's summary purely from its raw iteration traces.\n * This function IS the metric definition:\n * - TTFT = first non-empty chunk timestamp − startT\n * - decode rate = (chars after first chunk) / (endT_lastChunk − t_firstChunk)\n * - prefill tok/s ≈ approxPromptTokens / TTFT (approximate by construction)\n */\nexport function summarizeCell(\n cell: BenchCellResult,\n highVarianceCv = 0.05,\n approxPromptTokens?: number,\n): CellSummary {\n const out: CellSummary = {\n cellId: cell.cellId,\n status: cell.status,\n highVariance: false,\n };\n if (cell.load) {\n out.loadMs = cell.load.endT - cell.load.startT;\n out.loadCached = cell.load.cached;\n }\n if (cell.quality) out.qualityScore = cell.quality.score;\n if (cell.iterations.length === 0) return out;\n\n if (isLLMIterations(cell.iterations)) {\n const ttfts: number[] = [];\n const decodeRates: number[] = [];\n const chunkRates: number[] = [];\n const genChars: number[] = [];\n const prefillRates: number[] = [];\n for (const it of cell.iterations) {\n const first = it.chunks.find((c) => c.c > 0);\n if (!first) continue;\n const ttftMs = first.t - it.startT;\n ttfts.push(ttftMs);\n const last = it.chunks[it.chunks.length - 1];\n const decodeChars = it.chunks.reduce((acc, c) => acc + c.c, 0) - first.c;\n const decodeMs = last.t - first.t;\n if (decodeMs > 0 && decodeChars > 0) {\n decodeRates.push((decodeChars / decodeMs) * 1000);\n chunkRates.push(((it.chunks.length - 1) / decodeMs) * 1000);\n }\n genChars.push(it.chunks.reduce((acc, c) => acc + c.c, 0));\n if (approxPromptTokens && ttftMs > 0) prefillRates.push((approxPromptTokens / ttftMs) * 1000);\n }\n if (ttfts.length > 0) out.ttftMs = summarize(ttfts);\n if (decodeRates.length > 0) out.decodeCharsPerSec = summarize(decodeRates);\n if (chunkRates.length > 0) out.decodeChunksPerSec = summarize(chunkRates);\n if (genChars.length > 0) out.generatedChars = summarize(genChars);\n if (prefillRates.length > 0) out.prefillTokPerSecApprox = summarize(prefillRates);\n } else {\n const iters = cell.iterations as EmbedIteration[];\n const durations = iters.map((it) => it.endT - it.startT).filter((d) => d > 0);\n if (durations.length > 0) {\n if (iters[0].count === 1) out.singleLatencyMs = summarize(durations);\n else {\n out.batchTextsPerSec = summarize(\n iters.filter((it) => it.endT - it.startT > 0).map((it) => (it.count / (it.endT - it.startT)) * 1000),\n );\n }\n }\n }\n\n const metrics: Array<MetricSummary | undefined> = [\n out.ttftMs,\n out.decodeCharsPerSec,\n out.singleLatencyMs,\n out.batchTextsPerSec,\n ];\n out.highVariance = metrics.some((m) => m !== undefined && m.n >= 2 && m.cv > highVarianceCv);\n return out;\n}\n\n/** Recompute all cell summaries for a run (workload prompt sizes looked up). */\nexport function summarizeRun(\n run: BenchRunResult,\n highVarianceCv = 0.05,\n promptTokensByWorkload?: ReadonlyMap<string, number>,\n): CellSummary[] {\n const defaults = new Map<string, number>([\n ['chat-pp128-tg128', 128],\n ['chat-pp512-tg128', 512],\n ]);\n const lookup = promptTokensByWorkload ?? defaults;\n return run.cells.map((cell) => summarizeCell(cell, highVarianceCv, lookup.get(cell.workloadId)));\n}\n\n/**\n * Versioned plausibility/integrity checks over a submitted run. Returns flags;\n * `severity: 'reject'` flags route the run to quarantine, `warn` flags are\n * displayed. Rules (v1): timestamp monotonicity, decode-rate envelopes,\n * duration consistency, timer-grid conformance, fingerprint sanity,\n * environment cross-field consistency.\n */\nexport function checkPlausibility(run: BenchRunResult): PlausibilityFlag[] {\n const flags: PlausibilityFlag[] = [];\n const flag = (code: string, message: string, severity: 'warn' | 'reject', cellId?: string) =>\n flags.push({ code, message, severity, ...(cellId ? { cellId } : {}) });\n\n // Fingerprint sanity: the matmul must have run and be within silicon reality.\n if (!run.fingerprint) {\n flag('fingerprint-missing', 'no hardware fingerprint in submission', 'reject');\n } else if (\n run.fingerprint.mflops <= 1 ||\n run.fingerprint.mflops > 100_000 ||\n !Number.isFinite(run.fingerprint.checksum)\n ) {\n flag('fingerprint-implausible', `fingerprint mflops=${run.fingerprint.mflops}`, 'reject');\n }\n\n const grid = run.environment.timerResolutionUs;\n\n for (const cell of run.cells) {\n if (cell.status !== 'ok') continue;\n\n if (cell.load && cell.load.endT < cell.load.startT) {\n flag('load-time-reversed', 'load endT precedes startT', 'reject', cell.cellId);\n }\n\n if (isLLMIterations(cell.iterations)) {\n for (const it of cell.iterations) {\n // Monotonic chunk timestamps within [startT, endT].\n let prev = it.startT;\n let monotonic = true;\n for (const c of it.chunks) {\n if (c.t < prev) monotonic = false;\n prev = c.t;\n }\n if (!monotonic || it.endT < prev) {\n flag('trace-not-monotonic', 'chunk timestamps are not monotonic', 'reject', cell.cellId);\n break;\n }\n // Text length must equal the chunk-length sum.\n const chunkChars = it.chunks.reduce((acc, c) => acc + c.c, 0);\n if (it.text.length !== chunkChars) {\n flag('text-chunk-mismatch', `text length ${it.text.length} != chunk sum ${chunkChars}`, 'reject', cell.cellId);\n break;\n }\n }\n\n const summary = summarizeCell(cell);\n if (summary.decodeCharsPerSec) {\n const size = cell.model.sizeBytes ?? Number.POSITIVE_INFINITY;\n const envelope = DECODE_ENVELOPE_CHARS_PER_SEC.find((e) => size <= e.maxBytes);\n if (envelope && summary.decodeCharsPerSec.median > envelope.max) {\n flag(\n 'decode-rate-envelope',\n `decode ${Math.round(summary.decodeCharsPerSec.median)} chars/s exceeds envelope ${envelope.max} for model size`,\n 'reject',\n cell.cellId,\n );\n }\n }\n if (summary.ttftMs && summary.ttftMs.median < 1) {\n flag('ttft-implausible', `median TTFT ${summary.ttftMs.median}ms < 1ms`, 'reject', cell.cellId);\n }\n\n // Timer-grid conformance: chunk timestamps should sit on the reported grid.\n if (grid !== null && grid !== undefined && grid >= 4) {\n const quantumMs = grid / 1000;\n let offGrid = 0;\n let total = 0;\n for (const it of cell.iterations) {\n for (const c of it.chunks) {\n total++;\n const remainder = Math.abs(c.t / quantumMs - Math.round(c.t / quantumMs));\n if (remainder > 0.01) offGrid++;\n }\n }\n if (total >= 20 && offGrid / total > 0.5) {\n flag('timer-grid', `${offGrid}/${total} chunk timestamps off the ${grid}us timer grid`, 'warn', cell.cellId);\n }\n }\n } else if (cell.iterations.length > 0) {\n const summary = summarizeCell(cell);\n if (summary.batchTextsPerSec && summary.batchTextsPerSec.median > EMBED_ENVELOPE_TEXTS_PER_SEC) {\n flag(\n 'embed-rate-envelope',\n `embedding throughput ${Math.round(summary.batchTextsPerSec.median)} texts/s exceeds envelope`,\n 'reject',\n cell.cellId,\n );\n }\n if (summary.singleLatencyMs && summary.singleLatencyMs.median < 0.05) {\n flag('embed-latency-implausible', 'sub-50us embedding latency', 'reject', cell.cellId);\n }\n }\n }\n\n // Cross-field consistency: Apple GPU should not report a Windows platform.\n const vendor = run.environment.gpu.vendor?.toLowerCase() ?? '';\n const platform = run.environment.os.platform.toLowerCase();\n if (vendor === 'apple' && platform.includes('windows')) {\n flag('env-cross-field', 'Apple GPU adapter with Windows platform', 'reject');\n }\n\n // Software/virtual renderer detection: cloud VMs and virtualized desktops\n // expose SwiftShader/WARP-class adapters whose \"GPU\" numbers are CPU numbers.\n // A GPU-lane result from such an environment is rejected; a WASM/CPU-only run\n // is merely annotated (software rendering does not affect those lanes).\n const gpuIdentity = [\n run.environment.gpu.vendor,\n run.environment.gpu.architecture,\n run.environment.gpu.device,\n run.environment.gpu.description,\n run.environment.webglRenderer,\n ]\n .filter(Boolean)\n .join(' ');\n if (SOFTWARE_RENDERER_PATTERNS.some((p) => p.test(gpuIdentity))) {\n const hasGpuLane = run.cells.some(\n (cell) => cell.status === 'ok' && /webgpu|^gpu$/.test(cell.resolvedBackend),\n );\n flag(\n 'software-renderer',\n `GPU identity matches a software/virtual renderer: \"${gpuIdentity.slice(0, 120)}\"`,\n hasGpuLane ? 'reject' : 'warn',\n );\n }\n\n return flags;\n}\n\n/**\n * Full validation pipeline for a submission: shape, digest-independent\n * summary recompute, client-summary agreement (>1% relative disagreement on\n * medians is flagged), and plausibility rules.\n */\nexport function validateSubmission(run: BenchRunResult): ValidationReport {\n const shapeErrors = validateRunShape(run);\n if (shapeErrors.length > 0) {\n return { ok: false, shapeErrors, flags: [], summaries: [] };\n }\n const summaries = summarizeRun(run);\n const flags = checkPlausibility(run);\n\n if (run.clientSummaries) {\n const byId = new Map(summaries.map((s) => [s.cellId, s]));\n for (const client of run.clientSummaries) {\n const server = byId.get(client.cellId);\n if (!server) continue;\n for (const key of ['ttftMs', 'decodeCharsPerSec', 'singleLatencyMs', 'batchTextsPerSec'] as const) {\n const c = client[key]?.median;\n const s = server[key]?.median;\n if (c !== undefined && s !== undefined && s !== 0 && Math.abs(c - s) / Math.abs(s) > 0.01) {\n flags.push({\n code: 'client-summary-disagrees',\n cellId: client.cellId,\n message: `${key} client median ${c} vs recomputed ${s}`,\n severity: 'reject',\n });\n }\n }\n }\n }\n\n return {\n ok: flags.every((f) => f.severity !== 'reject'),\n shapeErrors: [],\n flags,\n summaries,\n };\n}\n","/**\n * tinyMMLU — 100 IRT-anchored items from the MMLU benchmark, selected by the\n * tinyBenchmarks project (Maia Polo et al., \"tinyBenchmarks: evaluating LLMs\n * with fewer examples\", arXiv:2402.14992). Source dataset:\n * https://huggingface.co/datasets/tinyBenchmarks/tinyMMLU (test split, 100 rows).\n * Upstream MMLU (cais/mmlu) and the tinyBenchmarks repository are MIT-licensed.\n *\n * Used by the quality-fidelity lane: scores measure runtime/quantization\n * fidelity of a model build, not model capability (public sets are assumed\n * to be in training data).\n */\n\n/** One multiple-choice item: four choices, `answer` is the 0-based correct index. */\nexport interface MMLUItem {\n question: string;\n subject: string;\n choices: [string, string, string, string];\n answer: 0 | 1 | 2 | 3;\n}\n\n/** The 100-item tinyMMLU test split (order preserved from the source dataset). */\nexport const TINY_MMLU: readonly MMLUItem[] = [\n {\n \"question\": \"The number of days it takes to build a new house has a variance of 386. A sample of 40 new homes shows an average building time of 83 days. With what confidence can we assert that the average building time for a new house is between 80 and 90 days?\",\n \"subject\": \"high_school_statistics\",\n \"choices\": [\n \"15.4%\",\n \"17.8%\",\n \"20.0%\",\n \"82.1%\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"According to trials on diabetes prevention, high-risk individuals can reduce their risk to develop diabetes by doing the following:\",\n \"subject\": \"nutrition\",\n \"choices\": [\n \"Eating a very low carbohydrate diet\",\n \"Consuming a diet high in monounsaturated fats\",\n \"Losing 5-7% of body weight through a hypocaloric low fat diet and 30 minutes of daily activity\",\n \"Initiating metformin 850 mg BID and practicing daily vigorous exercise\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"Which of the following is true regarding the complications of a large goitre?\",\n \"subject\": \"clinical_knowledge\",\n \"choices\": [\n \"It causes stridor due to compression of the oesophagus\",\n \"Dysphagia is an indication for surgery\",\n \"It causes hoarseness due to compression of the trachea\",\n \"It causes a more florid thyrotoxicosis than a smaller goitre\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"Doses of substances used in animal toxicity studies are usually many times greater than those experienced by people because:\",\n \"subject\": \"nutrition\",\n \"choices\": [\n \"Animals are generally much less sensitive than people\",\n \"Such tests can detect only very large risks because of the fact that only small numbers of animals can be used\",\n \"It is difficult in such studies to determine whether the observed toxic effects were caused by the substance\",\n \"It is the only way to ensure results are applicable to people\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"Rowena can paint a room in $14$ hours, while Ruby can paint it in $6$ hours. If Rowena paints for $x$ hours and Ruby paints for $y$ hours, they will finish half of the painting, while if Rowena paints for $y$ hours and Ruby paints for $x$ hours they will paint the whole room. Find the ordered pair $(x,y)$.\",\n \"subject\": \"high_school_mathematics\",\n \"choices\": [\n \"(\\\\frac{11}{10}, \\\\frac{11}{10})\",\n \"(\\\\frac{231}{20}, \\\\frac{21}{20})\",\n \"(\\\\frac{231}{40}, \\\\frac{21}{40})\",\n \"(1,1)\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"Which of the following statements would Macedo disagree with?\",\n \"subject\": \"moral_disputes\",\n \"choices\": [\n \"States should give special weight to their own citizens.\",\n \"Immigration policies can have powerful economic effects.\",\n \"Self-governance is morally irrelevant to the immigration debate.\",\n \"There are reasons to think U.S. immigration policy has had detrimental effects on income distribution among citizens.\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"A 17-year-old girl is brought to the physician by her mother because she has not had a menstrual period for 6 months. The patient is unconcerned about the lack of menses. Menarche occurred at the age of 12 years, and menses had occurred at regular 28-day intervals until they became irregular 1 year ago. She is a member of her high school gymnastics team. She appears emaciated. She is 163 cm (5 ft 4 in) tall and weighs 40 kg (88 lb); BMI is 15 kg/m2 . Her pulse is 54/min, and blood pressure is 80/50 mm Hg. Which of the following is the most likely cause of this patient's amenorrhea?\",\n \"subject\": \"professional_medicine\",\n \"choices\": [\n \"Hyperthyroidism\",\n \"Hypogonadotropic hypogonadism\",\n \"Hypothyroidism\",\n \"Polycystic ovarian syndrome\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"The Yang-shao culture gave way to the Lung-Shan sometime after:\",\n \"subject\": \"prehistory\",\n \"choices\": [\n \"6,000 B.P.\",\n \"5,000 B.P.\",\n \"4,000 B.P.\",\n \"3,000 B.P.\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"Cultural homogenization.\",\n \"subject\": \"business_ethics\",\n \"choices\": [\n \"1,3,4\",\n \"1,2,3\",\n \"1,2,3,4\",\n \"2,3,4\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"Of the ways of escaping moral arguments that he discusses, Hare claims:\",\n \"subject\": \"philosophy\",\n \"choices\": [\n \"none of them are successful.\",\n \"some, but not all of them are successful.\",\n \"all are entirely successful.\",\n \"all might be successful, but at a price.\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"An employee of large manufacturing firm finds the work dull, and pursues the job only for the money. The employee performs minimally, and is not motivated so produce highest quantity or better quality. According to F. Herzberg's two-factor theory, the best way 10 increase this worker's self-motivation would be to\",\n \"subject\": \"professional_psychology\",\n \"choices\": [\n \"offer a raise and incentive pay for greater productivity\",\n \"redesign the job to provide a challenge and a sense of accomplishment\",\n \"increase opportunities for informed social interaction\",\n \"provide the employee with a job tide carrying greater prestige\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"In an e-commerce environment that requires that the information technology (IT) system be available on a continuous basis, more emphasis will be placed on which of the following aspects of the planning than in a traditional organization?\",\n \"subject\": \"professional_accounting\",\n \"choices\": [\n \"Maintain appropriate written source documents so the data can be re-entered if it is lost or compromised\",\n \"Maintain redundant systems for instant availability to assure the flow of transactions\",\n \"Review additional expenses to obtain the required amount of business interruption insurance coverage for the organization\",\n \"Assure that appropriate data backups are stored in an off-site location\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"The Space Shuttle orbits 300 km above the Earth’s surface; the Earth’s radius is 6400 km. What is the acceleration due to Earth’s gravity experienced by the Space Shuttle?\",\n \"subject\": \"high_school_physics\",\n \"choices\": [\n \"4.9 m/s^2\",\n \"8.9 m/s^2\",\n \"9.8 m/s^2\",\n \"10.8 m/s^2\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"Statement 1 | The image of a group of 6 elements under a homomorphism may have 12 elements. Statement 2 | There is a homomorphism of some group of 6 elements into some group of 12 elements.\",\n \"subject\": \"abstract_algebra\",\n \"choices\": [\n \"True, True\",\n \"False, False\",\n \"True, False\",\n \"False, True\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"At which of the following locations does bile enter the digestive tract?\",\n \"subject\": \"anatomy\",\n \"choices\": [\n \"Gastroesophageal sphincter\",\n \"Duodenum\",\n \"Ileocecum\",\n \"Jejunum\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"This question refers to the following information.\\nIs it not unity alone that can weld us into an effective force, capable of creating our own progress and making our valuable contribution to world peace? Which independent African state will claim that its financial structure and banking institutions are fully harnessed to its national development? Which will claim that its material resources and human energies are available for its own national aspirations? We are fast learning that political independence is not enough to rid us of the consequences of colonial rule. We have been too busy nursing our separate states to understand fully the basic need for union, rooted in common purpose, common planning and common endeavour.\\nGhana's president, Kwame Nkrumah, addressing the Organization of African Unity, 1963\\nThe speaker in the passage above is espousing which of the following causes?\",\n \"subject\": \"high_school_world_history\",\n \"choices\": [\n \"Nationalism\",\n \"Socialism\",\n \"Pan-Africanism\",\n \"Neocolonialism\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"Monte Alban is located in the ________ and was built by the _________.\",\n \"subject\": \"prehistory\",\n \"choices\": [\n \"Valley of Mexico; Aztec.\",\n \"Valley of Oaxaca; Zapotec.\",\n \"Amazon floodplain; Olmec.\",\n \"Yucatán Peninsula; Maya.\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"Sauna use, sometimes referred to as \\\"sauna bathing,\\\" is characterized by short-term passive exposure to extreme heat. This exposure elicits mild hyperthermia – an increase in the body's core temperature – that induces a thermoregulatory response involving neuroendocrine, cardiovascular, and cytoprotective mechanisms that work together to restore homeostasis and condition the body for future heat stressors… In recent decades, sauna bathing has emerged as a means to increase lifespan and improve overall health, based on compelling data from observational, interventional, and mechanistic studies. Of particular interest are the findings from studies of participants in the Kuopio Ischemic Heart Disease Risk Factor (KIHD) Study, an ongoing prospective population-based cohort study of health outcomes in more than 2,300 middle-aged men from eastern Finland, which identified strong links between sauna use and reduced death and disease… The KIHD findings showed that men who used the sauna two to three times per week were 27 percent less likely to die from cardiovascular-related causes than men who didn't use the sauna.[2] Furthermore, the benefits they experienced were found to be dose-dependent: Men who used the sauna roughly twice as often, about four to seven times per week, experienced roughly twice the benefits – and were 50 percent less likely to die from cardiovascular-related causes.[2] In addition, frequent sauna users were found to be 40 percent less likely to die from all causes of premature death. These findings held true even when considering age, activity levels, and lifestyle factors that might have influenced the men's health.[2]... The KIHD also revealed that frequent sauna use reduced the risk of developing dementia and Alzheimer's disease in a dose-dependent manner. Men who used the sauna two to three times per week had a 66 percent lower risk of developing dementia and a 65 percent lower risk of developing Alzheimer's disease, compared to men who used the sauna only one time per week… The health benefits associated with sauna use extended to other aspects of mental health, as well. Men participating in the KIHD study who used the sauna four to seven times per week were 77 percent less likely to develop psychotic disorders, regardless of the men's dietary habits, socioeconomic status, physical activity, and inflammatory status (as measured by C-reactive protein)…Exposure to high temperature stresses the body, eliciting a rapid, robust response. The skin and core body temperatures increase markedly, and sweating ensues. The skin heats first, rising to 40°C (104°F), and then changes in core body temperature occur, rising slowly from 37°C (98.6°F, or normal) to 38°C (100.4°F) and then rapidly increasing to 39°C (102.2°F)… Cardiac output, a measure of the amount of work the heart performs in response to the body's need for oxygen, increases by 60 to 70 percent, while the heart rate (the number of beats per minute) increases and the stroke volume (the amount of blood pumped) remains unchanged.[5] During this time, approximately 50 to 70 percent of the body's blood flow is redistributed from the core to the skin to facilitate sweating. The average person loses approximately 0.5 kg of sweat while sauna bathing.[11] Acute heat exposure also induces a transient increase in overall plasma volume to mitigate the decrease in core blood volume. This increase in plasma volume not only provides a reserve source of fluid for sweating, but it also acts like the water in a car's radiator, cooling the body to prevent rapid increases in core body temperature and promoting heat tolerance… Repeated sauna use acclimates the body to heat and optimizes the body's response to future exposures, likely due to a biological phenomenon known as hormesis, a compensatory defense response following exposure to a mild stressor that is disproportionate to the magnitude of the stressor. Hormesis triggers a vast array of protective mechanisms that not only repair cell damage but also provide protection from subsequent exposures to more devastating stressors… The physiological responses to sauna use are remarkably similar to those experienced during moderate- to vigorous-intensity exercise. In fact, sauna use has been proposed as an alternative to exercise for people who are unable to engage in physical activity due to chronic disease or physical limitations.[13]\\n\\nBased on the article, which of the following statements is the author likely to agree with?\",\n \"subject\": \"college_medicine\",\n \"choices\": [\n \"Heart surgery patients who cannot run on treadmills may benefit from sauna use.\",\n \"Patients on a diet would benefit from sauna use.\",\n \"Salt restriction would be equal to sauna use for hypertensive patients.\",\n \"Patients with skin conditions may be cured with sauna use.\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"A department store had suffered a succession of thefts of merchandise over a period of months. From reports by employees and customers, the department store's manager concluded that the losses were due, wholly or in large part, to the depredations of a female shoplifter, aged 30 to 40 years, about 5 feet 5 inches in height, with red hair and green eyes, who usually wore a suit. This information was passed on to all of the employees of the department store. One day, a woman entered the store to purchase accessories. The woman was 5 feet 5 inches tall, 37 years old, red-haired and green-eyed, and dressed in a smartly tailored suit. She carried a large shopping bag. The manager noticed her as she picked up, examined, and put down a number of gloves and scarves. After a while, she looked about tentatively, and then started to walk out, swinging her bag. The manager intercepted her and, standing in front of her, politely asked the woman if she would accompany her to the store manager's office. When the woman asked for an explanation, the manager told her of the store's recent experience and the suspicion that the woman might be concealing pilfered merchandise in her bag. Flushing angrily, the woman replied, \\\"Very well,\\\" and followed her to the office. Once there, the manager began to question the woman quite intensively. After the questioning, the manager then asked the woman's permission to inspect the contents of her shopping bag. At first, the woman curtly refused and announced that she had had enough of this nonsense. When she rose to go, the manager told her, \\\"Listen, unless you let me look inside that bag, I'm going to call the police. \\\" The woman replied, \\\"Very well,\\\" and handed her the bag. The manager inspected the contents of the bag thoroughly but did not find any pilfered merchandise. She then gave the woman permission to leave. The total length of the woman's detention was 30 minutes. If the woman asserts a claim for false imprisonment against the department store, she will most likely\",\n \"subject\": \"professional_law\",\n \"choices\": [\n \"prevail, because she was detained for an unreasonably long period of time.\",\n \"prevail, because the manager did not have reasonable grounds to suspect that the woman had committed a theft.\",\n \"not prevail, because under the circumstances, the manager had reasonable grounds to suspect that the woman had committed a theft.\",\n \"not prevail, because the manager gave the woman permission to leave after conducting her investigation.\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"Which language family is most widely spoken in North America and Europe and includes Baltic, Celtic, Germanic, and Greek?\",\n \"subject\": \"high_school_geography\",\n \"choices\": [\n \"Dravidian\",\n \"Uralic-Altaic\",\n \"Sino-Tibetan\",\n \"Indo-European\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"For which of these two scenarios does the main character (who uses I/me/my) do something clearly morally wrong, according to ordinary moral standards in the US as of 2020? Scenario 1 | I decided to cook a potato for my girlfriend. Scenario 2 | I cornered the rat forcing it to go outside\",\n \"subject\": \"moral_scenarios\",\n \"choices\": [\n \"Wrong, Wrong\",\n \"Wrong, Not wrong\",\n \"Not wrong, Wrong\",\n \"Not wrong, Not wrong\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"How does rubella cause foetal abnormalities?\",\n \"subject\": \"virology\",\n \"choices\": [\n \"By crossing the placenta early in pregnancy and infecting the foetus\",\n \"By only infecting the placenta\",\n \"By inducing cytokines and chemokines in the mother\",\n \"By raising the temperature of the mother and inducing an abnormal immune reaction to the foetus\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"Find the opposite of the number −7.\",\n \"subject\": \"elementary_mathematics\",\n \"choices\": [\n \"7\",\n \"−7\",\n \"0.7\",\n \"−7.7\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"Silver metal, often amalgamated with mercury, is used to reduce substances to a desired oxidation state. If the silver metal amalgam cannot be used because of concerns about mercury, which of the following would be a reasonable and safe substitute?\",\n \"subject\": \"high_school_chemistry\",\n \"choices\": [\n \"H+(aq)\",\n \"Na(s)\",\n \"Ca2+(aq)\",\n \"Mg(s)\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"A 52-year-old man is brought to the emergency department 30 minutes after he had an episode of chest pain radiating to his jaw while shoveling snow. His pulse is 80/min, and blood pressure is 130/70 mm Hg. The lungs are clear to auscultation. Cardiac examination shows an S4. While undergoing an ECG, the patient says that he feels the chest pain returning. The most appropriate immediate treatment is a drug with which of the following mechanisms of action?\",\n \"subject\": \"professional_medicine\",\n \"choices\": [\n \"Increases cAMP concentration\",\n \"Increases nitric oxide concentration\",\n \"Inhibits potassium flux\",\n \"Inhibits sodium flux\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"For which of these two scenarios does the main character (who uses I/me/my) do something clearly morally wrong, according to ordinary moral standards in the US as of 2020? Scenario 1 | I voted twice in the presidential election. Scenario 2 | I rolled the grocery cart to my car.\",\n \"subject\": \"moral_scenarios\",\n \"choices\": [\n \"Wrong, Wrong\",\n \"Wrong, Not wrong\",\n \"Not wrong, Wrong\",\n \"Not wrong, Not wrong\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"A mechanism is a sequence of elementary reactions that add up to the overall reaction stoichiometry. A substance that is produced in one elementary reaction and consumed in another is called\",\n \"subject\": \"high_school_chemistry\",\n \"choices\": [\n \"a catalyst\",\n \"an intermediate\",\n \"a reactant\",\n \"a complex\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"A 22-year-old woman comes to the office because of urticaria. This is her first episode of urticaria and it has occurred and then resolved several times in the past week. The history and physical examination disclose no abnormalities. Which of the following is the most appropriate course of action?\",\n \"subject\": \"professional_medicine\",\n \"choices\": [\n \"Determine the serum IgE concentration\",\n \"Determine the total eosinophil count\",\n \"Refer her to an allergist\",\n \"Treat the symptoms\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"For which of these two scenarios does the main character (who uses I/me/my) do something clearly morally wrong, according to ordinary moral standards in the US as of 2020? Scenario 1 | I spent my afternoon swimming in the pool. Scenario 2 | I made my partner scream for help the entire evening.\",\n \"subject\": \"moral_scenarios\",\n \"choices\": [\n \"Wrong, Wrong\",\n \"Wrong, Not wrong\",\n \"Not wrong, Wrong\",\n \"Not wrong, Not wrong\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"If you were to travel at a speed close to the speed of light, you could notice that your own\",\n \"subject\": \"conceptual_physics\",\n \"choices\": [\n \"mass changes.\",\n \"pulse decreases.\",\n \"Both of these.\",\n \"Neither of these.\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"Form A of a standardized personality test was given in the fall and again in the spring co the same group of people. The reliability estimate that resulted from this research is referred to as\",\n \"subject\": \"professional_psychology\",\n \"choices\": [\n \"external consistency\",\n \"equivalence\",\n \"stability\",\n \"internal consistency\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"All of the following statements are true EXCEPT\",\n \"subject\": \"high_school_biology\",\n \"choices\": [\n \"thyroxine increases the rate of metabolism\",\n \"insulin decreases storage of glycogen\",\n \"vasopressin stimulates water reabsorption in the kidney\",\n \"epinephrine increases blood sugar levels and heart rate\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"For which of these two scenarios does the main character (who uses I/me/my) do something clearly morally wrong, according to ordinary moral standards in the US as of 2020? Scenario 1 | I stopped by and gave my girlfriend some flowers before driving home to my wife. Scenario 2 | I copied and pasted so I could write my paper with sources found on the internet.\",\n \"subject\": \"moral_scenarios\",\n \"choices\": [\n \"Wrong, Wrong\",\n \"Wrong, Not wrong\",\n \"Not wrong, Wrong\",\n \"Not wrong, Not wrong\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"The majority of Kurds are found in which country?\",\n \"subject\": \"high_school_geography\",\n \"choices\": [\n \"Iran\",\n \"Iraq\",\n \"Turkey\",\n \"Egypt\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"Including the bottom how many sides are on a square-based pyramid?\",\n \"subject\": \"miscellaneous\",\n \"choices\": [\n \"three\",\n \"four\",\n \"five\",\n \"six\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"One of the following is the primary function of an oscillator\",\n \"subject\": \"electrical_engineering\",\n \"choices\": [\n \"produces sinusoidal oscillations\",\n \"generates non sinusoidal waveforms\",\n \"generates sustained oscillations at a constant amplitude and specific frequency\",\n \"none of the above\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"In what ways, if any, can the environment be considered a security concern?\",\n \"subject\": \"security_studies\",\n \"choices\": [\n \"Environmental security entails a consideration of the security of the global environment, as well as its nested sub-systems and social systems beyond the boundaries of the nation state.\",\n \"Environmental security is a critical security project in that it questions who and what is to be secured and from what threat by orthodox security policies, or whether linkages between environmental, security and development issues can be made.\",\n \"Environmental security is a practical endeavour to assess how environmental change causes violent conflict within and between countries, and the ways in which environmental security can undermine national security.\",\n \"All of these options. The environment is both an object to be secured and a source of risk, although it may mean different things to different people. Whilst deepening the concept of security it has both critical and practical dimensions although the utility of the concept is contested.\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"________ are a business ethics management tool that have grown over the last few decades. Areas which these typically cover are compliance, corruption and environmental issues. However, they are constantly evolving, with for example, the onus on __________ having grown in recent years.\",\n \"subject\": \"business_ethics\",\n \"choices\": [\n \"Annual reports, Company financial performance\",\n \"Annual report, Internet - social media and networking\",\n \"Codes of ethics, Company financial performance\",\n \"Codes of ethics, Internet - social media and networking\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"If an iron nucleus split in two, its fission fragments would have\",\n \"subject\": \"conceptual_physics\",\n \"choices\": [\n \"less mass per nucleon\",\n \"more mass per nucleon\",\n \"the same mass per nucleon\",\n \"either more or less mass per nucleon\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"In one metropolitan region, technical writers have an annual salary that is approximately normally distributed with a mean of $55,800. The first quartile of salaries is $48,815. What is the standard deviation?\",\n \"subject\": \"high_school_statistics\",\n \"choices\": [\n \"$6,984 \",\n \"$10,356 \",\n \"$10,476 \",\n \"$13,968 \"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"What is the communal meal offered at the place of worship called in Sikhism?\",\n \"subject\": \"world_religions\",\n \"choices\": [\n \"Sangat\",\n \"Langar\",\n \"Gurdwara\",\n \"Panth\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"For which of these two scenarios does the main character (who uses I/me/my) do something clearly morally wrong, according to ordinary moral standards in the US as of 2020? Scenario 1 | I knew my overweight teacher was dieting, so I offered her a big sundae. Scenario 2 | I found a wallet in the park and became its new owner.\",\n \"subject\": \"moral_scenarios\",\n \"choices\": [\n \"Wrong, Wrong\",\n \"Wrong, Not wrong\",\n \"Not wrong, Wrong\",\n \"Not wrong, Not wrong\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"A state law imposes penalties for \\\"any public statement containing false or misleading information about a service or product.\\\" An airline falsely claimed in an advertisement that its competitor had an inferior safety record. The claim was based on erroneous information, found on the website of a nonprofit consumer advocacy group, that the airline assumed to be true. The airline was charged under the state law for making a false statement. No federal statute applies. Which of the following best supports the airline in a defense based on the First Amendment?\",\n \"subject\": \"professional_law\",\n \"choices\": [\n \"Its statement about the safety record was made without malice.\",\n \"Its statement about the safety record was protected noncommercial speech.\",\n \"The state law is a prior restraint.\",\n \"The state law is overbroad.\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"When Berger & Luckmann said that reality is socially constructed, they meant:\",\n \"subject\": \"sociology\",\n \"choices\": [\n \"scientists are guided in their work by social values and interests, so they define and measure phenomena that will support their theories\",\n \"people negotiate shared definitions of their situation and live according to these, often forgetting that these social worlds are not fixed and external\",\n \"sociologists decide what constitutes social reality and measure only that\",\n \"terms like 'reality' have no deeper meaning beyond the level of discourse\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"If c > 0 and f(x) = e^x - cx for all real numbers x, then the minimum value of f is\",\n \"subject\": \"college_mathematics\",\n \"choices\": [\n \"f(c)\",\n \"f(e^c)\",\n \"f(1/c)\",\n \"f(log c)\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"These factors increase risk of osteoporotic fracture:\",\n \"subject\": \"nutrition\",\n \"choices\": [\n \"High bone mineral density\",\n \"High body weight\",\n \"High lean mass\",\n \"Poor muscle strength\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"To prevent desiccation and injury, the embryos of terrestrial vertebrates are encased within a fluid secreted by the\",\n \"subject\": \"college_biology\",\n \"choices\": [\n \"amnion\",\n \"chorion\",\n \"allantois\",\n \"yolk sac\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"Let A be a finite set with m elements, and let B be a finite set with n elements. The number of distinct functions mapping A into B is\",\n \"subject\": \"college_computer_science\",\n \"choices\": [\n \"n^m\",\n \"n!/(n - m)!\",\n \"n!\",\n \"n!/(m!(n - m)!)\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"A disk of radius 0.1 m initially at rest undergoes an angular acceleration of 2.0 rad/s^2. If the disk only rotates, find the total distance traveled by a point on the rim of the disk in 4.0 s.\",\n \"subject\": \"high_school_physics\",\n \"choices\": [\n \"0.4 m\",\n \"0.8 m\",\n \"1.2 m\",\n \"1.6 m\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"Identify the only construct that is not pertinent to developmental models on intelligence:\",\n \"subject\": \"professional_psychology\",\n \"choices\": [\n \"Investment theory\",\n \"The positive manifold\",\n \"G theory\",\n \"Primary mental ability theory\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"Which of the following statements does NOT accurately describe voting behavior in the United States?\",\n \"subject\": \"high_school_government_and_politics\",\n \"choices\": [\n \"Registered voters between the ages of 35 and 45 are more likely to vote than are those under the age of 21.\",\n \"A registered voter who has attained his or her General Educational Development (GED) is less likely to vote than a high school dropout.\",\n \"Registered voters are more likely to vote in general elections than they are in primary elections.\",\n \"More women than men have voted in every presidential election since 1980.\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"For which of these two scenarios does the main character (who uses I/me/my) do something clearly morally wrong, according to ordinary moral standards in the US as of 2020? Scenario 1 | When I checked out from the hotel I turned in the dirty towels. Scenario 2 | I always kept my whiskey bottles out of reach of my 3-year-old son.\",\n \"subject\": \"moral_scenarios\",\n \"choices\": [\n \"Wrong, Wrong\",\n \"Wrong, Not wrong\",\n \"Not wrong, Wrong\",\n \"Not wrong, Not wrong\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"A state imposes a graduated income tax upon net income calculated under federal law. Section 22 of the city's reform act of 2010, which is to become effective on January 1, 2010, provides: \\\"Any parent or guardian financially responsible for the education of his ward may claim a direct tax credit against his income tax liability equal to the amount of tuition of a child or children of high school age who does not attend a public high school. \\\" Other provisions define \\\"tuition\\\" very broadly but limit the credit to tuition paid to schools meeting the educational requirements as determined by the state. On December 1, 2009, the parents of two students who attend a public high school in the state sue for a declaratory judgment and injunction in federal court, claiming that Section 22 violates the establishment clause of the First Amendment. The federal court will most likely\",\n \"subject\": \"professional_law\",\n \"choices\": [\n \"dismiss the action, because the suit involves a political question.\",\n \"dismiss the action, because the plaintiffs lack standing as taxpayers.\",\n \"dismiss the action, because the issues are not ripe.\",\n \"dismiss the action, because the issues being litigated are moot.\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"A member of the president's cabinet is said to have \\\"gone native\\\" when that cabinet member\",\n \"subject\": \"high_school_government_and_politics\",\n \"choices\": [\n \"resigns to take a position as a consultant to lobbying groups\",\n \"cedes control of his or her department to lifelong bureaucrats within the department\",\n \"places his or her department's priorities above the president's\",\n \"accepts bribes or expensive favors from businesses regulated by his or her department\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"Order the following (risk, return) pairs from least to most favourable, assuming the perspective of a rational and risk-averse investor: (2,2),(2,3) and (4,2). Risk is measured in standard deviations and return in percentage. HINT: Imagine a scatter diagram with standard deviation on the x-axis and return on the y-axis.\",\n \"subject\": \"professional_accounting\",\n \"choices\": [\n \"(4,2),(2,2),(2,3)\",\n \"(2,2),(2,3),(4,2)\",\n \"(2,2),(4,2),(2,3)\",\n \"(2,3),(2,2),(4,2)\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"What is the main reason why many Critical Race Theorists are hostile to concepts such as 'justice', 'neutrality', and 'truth'?\",\n \"subject\": \"jurisprudence\",\n \"choices\": [\n \"Because of their vagueness.\",\n \"Because they have failed to produce racial justice.\",\n \"Because they are unrelated to contemporary conditions.\",\n \"Because these ideas are alien to most people of colour.\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"What is personal (ratione personae) immunity?\",\n \"subject\": \"international_law\",\n \"choices\": [\n \"Personal immunity is afforded to all physical persons\",\n \"Personal immunity is that which is afforded in a personal capacity and hence does not cover conduct of the State as such\",\n \"Personal immunity is afforded only to particular persons irrespective if their conduct was undertaken in a private or public capacity\",\n \"Personal immunity is afforded to State officials for conduct undertaken in a public capacity\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"Who is an 'injured State' in the law of international responsibility?\",\n \"subject\": \"international_law\",\n \"choices\": [\n \"A State is 'injured' in case that it has suffered a damage from the internationally wrongful conduct\",\n \"A State is 'injured' in cases that there has been a violation of a peremptory norm of international law\",\n \"A State is 'injured' should it acknowledge the existence of the internationally wrongful conduct\",\n \"A State is 'injured' if the obligation breached was owed to it individually or if it was owed to a group of States, including that State, and it was specially affected\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"A national association brought suit in federal court against a city. The suit charged the city with violating several federal statutes. During the trial, the association's attorney called the city attorney as an adverse witness. The city attorney asserted the attorney-client privilege and objected that the matters communicated to him were intended to be confidential. The issues raised by the objections of the city attorney should be resolved under\",\n \"subject\": \"professional_law\",\n \"choices\": [\n \"federal privilege law.\",\n \"the privilege law of the forum state.\",\n \"either federal privilege law or the privilege law of the forum state as determined by the court.\",\n \"either federal privilege law or the privilege law of the forum state, whichever the court determines is more likely to admit the evidence.\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"There are three main types of buying situations in an organization, referred to by Robinson, Faris, and Wind (1967) as _____________.\",\n \"subject\": \"marketing\",\n \"choices\": [\n \"Repeat purchases.\",\n \"Buyphases.\",\n \"Buyclasses.\",\n \"Tenders.\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"For which of these two scenarios does the main character (who uses I/me/my) do something clearly morally wrong, according to ordinary moral standards in the US as of 2020? Scenario 1 | My mom asked me to deep clean the bath so I covered it in bleach. Scenario 2 | For the funeral, I wore my clown costume to honor the dead.\",\n \"subject\": \"moral_scenarios\",\n \"choices\": [\n \"Wrong, Wrong\",\n \"Wrong, Not wrong\",\n \"Not wrong, Wrong\",\n \"Not wrong, Not wrong\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"A ________ campaign occurs when people from two or more opposing sides of an argument have emotional convictions about a decision that has the power to impact their lives.\",\n \"subject\": \"public_relations\",\n \"choices\": [\n \"public relations\",\n \"public issues\",\n \"crisis management\",\n \"consumer relations\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"One afternoon a motorist was driving her car when she struck a pedestrian who entered the intersection. The pedestrian was seriously injured in the accident and sued the motorist to recover damages for personal injuries. There were no witnesses to the accident. The motorist claims that the traffic light was green at the time she entered the intersection. The pedestrian now has amnesia and cannot remember how the accident occurred. At trial, the pedestrian's attorney calls a witness to testify. The witness proposes to testify that she was in the emergency room at the hospital when the pedestrian was brought in following the accident. The witness further testifies that while the pedestrian was being treated for his injuries, the nurse asked him, \\\"How did you get hurt?\\\" The pedestrian replied, \\\"The car ran the red light and struck me as I was walking through the intersection. \\\"Upon objection, this evidence is\",\n \"subject\": \"professional_law\",\n \"choices\": [\n \"admissible as a statement made for purposes of medical treatment and diagnosis.\",\n \"admissible as a present sense impression.\",\n \"inadmissible, because the witness was eavesdropping on a confidential communication between the pedestrian and a hospital representative.\",\n \"inadmissible, because it is hearsay not within any recognized exception.\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"Which of the following samples would be considered most representative of male college students?\",\n \"subject\": \"high_school_psychology\",\n \"choices\": [\n \"A group of thirty fraternity brothers from Penn State\",\n \"A random sample taken between classes in the business wing of various universities\",\n \"Sixty male members of each class from Princeton, Yale, Harvard, Dartmouth, and Columbia\",\n \"Twenty male members of each class from a cross-section of colleges and universities\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"Which statement below is the least likely to follow logically from Dworkin's notion of law as integrity?\",\n \"subject\": \"jurisprudence\",\n \"choices\": [\n \"It is likely to generate more individual rights and greater liberty.\",\n \"It renders a community more genuine.\",\n \"It opens the door to authoritarianism.\",\n \"It improves the moral justification for the exercise of political power.\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"X-chromosome inactivation\",\n \"subject\": \"medical_genetics\",\n \"choices\": [\n \"results in genetically turning off one of the two X chromosomes in female mammals\",\n \"takes place in humans so that the same X chromosome is inactive in all of the cells of a female\",\n \"is the cause of the Y chromosome being genetically inactive\",\n \"occurs in fruit flies but not in mammals\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"In the fetus, the ductus arteriosus passes blood from the\",\n \"subject\": \"anatomy\",\n \"choices\": [\n \"pulmonary vein to the aorta.\",\n \"aorta to pulmonary vein.\",\n \"pulmonary artery to the aorta.\",\n \"aorta to the pulmonary artery.\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"The follicular phase is to the __________ as the luteal phase is to the secretory phase.\",\n \"subject\": \"human_sexuality\",\n \"choices\": [\n \"postovulatory\",\n \"menstrual\",\n \"proliferative\",\n \"myometrial\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"Buffer-overflow may remain as a bug in apps if __________ are not done fully.\",\n \"subject\": \"computer_security\",\n \"choices\": [\n \"boundary hacks\",\n \"memory checks\",\n \"boundary checks\",\n \"buffer checks\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"Let T be a depth-first search tree of a connected undirected graph G. For each vertex v of T, let pre(v) be the number of nodes visited up to and including v during a preorder traversal of T, and post(v) be the number of nodes visited up to and including v during a postorder traversal of T. The lowest common ancestor of vertices u and v in T is a vertex w of T such that w is an ancestor of both u and v, and no child of w is an ancestor of both u and v. Let (u, v) be an edge in G that is not in T, such that pre(u) < pre(v). Which of the following statements about u and v must be true?\\nI. post(u) < post(v)\\nII. u is an ancestor of v in T.\\nIII. If w is the lowest common ancestor of u and v in T, then w = u.\",\n \"subject\": \"college_computer_science\",\n \"choices\": [\n \"I only\",\n \"II only\",\n \"III only\",\n \"II and III\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"This question refers to the following information.\\nEvery two months His Majesty sends from Lima 60,000 pesos to pay for the mita of the Indians. Up on the Huanacavelica range there are 3,000 or 4,000 Indians working in the mercury mine, with picks and hammers, breaking up the ore. And when they have filled up their little sacks, the poor fellows, loaded down, climb up those ladders and rigging, so distressing that a man can hardly get up them. That is the way they work in this mine, with many lights and the loud noise of the pounding and great confusion. Nor is that the greatest evil; that is due to thievish and undisciplined superintendents. According to His Majesty's warrant, the mine owners at Potosí have a right to the mita of 13,300 Indians. These mita Indians earn each day 4 reals. Besides these there are others not under obligation, who hire themselves out voluntarily: these each get from 12 to 16 reals, and some up to 24, according to how well they wield their picks or their reputation for knowing how to get the ore out.\\nAntonio Vasquez de Espinosa, report on mining in Huanacavelica and Potosí, 1620s\\nThe third principal reason the local Yakut and Tungus natives are ruined is that from the time they first came under Russian control, they have been forced to pay yasak tribute. Some have paid in sables, others in red foxes, still others in cash. At first there were plenty of furbearing animals there, but now there are no sables and not many foxes in those lands, from the shores of the Arctic Ocean all the way south to the great Lena River. Moreover, almost half the natives cannot hunt because they no longer have horses, many of which have been pawned to the yasak collectors.\\nHeinrich von Füch, \\\"On the Treatment of Natives in Northeast Siberia,\\\" 1744\\nBoth passages are best seen in the context of which of the following broad developments?\",\n \"subject\": \"high_school_world_history\",\n \"choices\": [\n \"Emerging systems of coerced labor\",\n \"The expansion of chattel slavery\",\n \"Increased reliance on prison-camp workforces\",\n \"Colonization of overseas territories by joint-stock companies\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"A soccer team has $90.00 to buy soccer balls. If one soccer ball costs $15.60, what is the greatest number of soccer balls the team can buy?\",\n \"subject\": \"elementary_mathematics\",\n \"choices\": [\n \"4\",\n \"5\",\n \"6\",\n \"7\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"Current estimates of how many people exercise on a regular basis suggest that _____ do\",\n \"subject\": \"human_aging\",\n \"choices\": [\n \"Less than 50%\",\n \"More than 75%\",\n \"Less than 25%\",\n \"More than 50%\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"An object carries a charge of –1 C. How many excess electrons does it contain?\",\n \"subject\": \"high_school_physics\",\n \"choices\": [\n \"6.25 × 10^18\",\n \"8.00 × 10^18\",\n \"1.60 × 10^19\",\n \"3.20 × 10^19\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"According to Socrates, it is important that we discover what makes a particular action (e.g., a merciful or just act) the kind of action that it is, because without such knowledge:\",\n \"subject\": \"philosophy\",\n \"choices\": [\n \"no one in society will ever do any action that really is merciful or just, only those actions that they think are merciful or just.\",\n \"the primary purpose of human existence--which is to think and to know--is replaced by a focus on morality (acting and doing).\",\n \"we can refer only to how people characterize actions without knowing why such actions should be characterized that way.\",\n \"there would be no way to distinguish one kind of action (e.g., a merciful action) from another kind of action (e.g., a just action).\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"A woman leased a condo from the owner for a period of one year. After six months, the owner gave the woman a written option to purchase the condo for $100,000 before the expiration of the lease. With the owner's approval, the woman spent $10,000 to have the kitchen remodeled to her personal specifications. One month before the end of the lease, the owner notified the woman that he was revoking the option to purchase the condo. One week later, the woman delivered a written notice of acceptance of the option, but the owner refused to sell. If the woman initiates suit for breach of contract, which of the following is her strongest argument that an enforceable contract was formed between her and the owner?\",\n \"subject\": \"professional_law\",\n \"choices\": [\n \"Because the woman had until the expiration of the lease to accept the offer, the owner's revocation would be ineffective.\",\n \"Because the owner was a merchant, the written offer was irrevocable for a period not exceeding three months.\",\n \"Because the owner's offer invited a return promise as acceptance, the woman manifested her intent to accept by remodeling the kitchen.\",\n \"After the woman paid to have the kitchen remodeled, an option contract resulted, because the owner knew the woman was relying on the offer to her detriment.\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"What does the presence of discouraged workers do to the measurement of the unemployment rate?\",\n \"subject\": \"high_school_macroeconomics\",\n \"choices\": [\n \"Discouraged workers are counted as \\\"out of the labor force\\\" thus the unemployment rate is understated making the economy look stronger than it is.\",\n \"Discouraged workers are counted as \\\"out of the labor force\\\" thus the unemployment rate is understated making the economy look weaker than it is.\",\n \"Discouraged workers are not surveyed so there is no impact on the unemployment rate.\",\n \"Discouraged workers are counted as \\\"unemployed\\\" thus the unemployment rate is understated making the economy look stronger than it is.\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"In the film 'The Talented Mr Ripley' who plays Mr Ripley?\",\n \"subject\": \"miscellaneous\",\n \"choices\": [\n \"Jude Law\",\n \"Matt Damon\",\n \"Dustin Hoffman\",\n \"Ben Affleck\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"Which of the following allows gas exchange in the lungs?\",\n \"subject\": \"anatomy\",\n \"choices\": [\n \"Alveoli\",\n \"Bronchi\",\n \"Bronchioles\",\n \"Capillaries\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"Anscombe criticizes as absurd Kant’s idea of:\",\n \"subject\": \"philosophy\",\n \"choices\": [\n \"the thing in itself.\",\n \"the categorical imperative.\",\n \"the phenomenal self.\",\n \"legislating for oneself.\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"Select the best translation into predicate logic. Some firefighters rescue victims from danger. (Dx: x is danger; Fx: x is a firefighter; Vx: x is a victim; Rxyz: x rescues y from z)\",\n \"subject\": \"formal_logic\",\n \"choices\": [\n \"(∃x){Fx • (∀y)[Dy ⊃ (∃z)(Vz • Rxyz)]}\",\n \"(∃x){Fx • (∃y)[Vy • (∃z)(Dz • Rxyz)]}\",\n \"(∃x){Fx • (∃y)(∃z)[(Vy • Dz) • Rxzy]}\",\n \"(∀x){Fx ⊃ (∃y)[Vy . (∃z)(Dz • Rxyz)]}\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"During a clinical study examining the effects of exercise, men between the ages of 20 and 30 years are evaluated during a 15- minute session on a treadmill. The average pulse for the last 2 minutes of the session is 175/min. During the last minute of exercise, various measurements are taken. Compared with the measurement before the session, which of the following is most likely to be decreased?\",\n \"subject\": \"professional_medicine\",\n \"choices\": [\n \"Pulse pressure\",\n \"Stroke volume\",\n \"Systolic blood pressure\",\n \"Total peripheral resistance\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"Which of the following was described as “the slow agency of existing causes”?\",\n \"subject\": \"prehistory\",\n \"choices\": [\n \"natural selection\",\n \"catastrophism\",\n \"uniformitarianism\",\n \"unilineal evolution\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"A car gets 24 miles per gallon of gasoline (mi/gal). How many gallons of gasoline would the car need to travel 144 miles?\",\n \"subject\": \"elementary_mathematics\",\n \"choices\": [\n \"6.5 gallons\",\n \"6 gallons\",\n \"5.5 gallons\",\n \"5 gallons\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"A school psychologist is providing feedback to a student's parents regarding the student's performance on a measure of academic achievement. To explain the concept of grade equivalent, the school psychologist should explain that it is\",\n \"subject\": \"high_school_psychology\",\n \"choices\": [\n \"the average score on that measure obtained by students in a given grade\",\n \"the average score on that measure obtained by students at a given age\",\n \"the grade in which a student should be placed in school\",\n \"utilized to determine accountability among peers\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"Global and regional international trade agreements work by using which of the following mechanisms?\",\n \"subject\": \"us_foreign_policy\",\n \"choices\": [\n \"Reciprocity across multiple issues\",\n \"Reputational concerns of the actors\",\n \"Side payments for adjusting to the organization (such as the Common Agricultural Policy in the EU)\",\n \"ALL of the above\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"When did Mohenjo-daro develop into a complex urban center?\",\n \"subject\": \"prehistory\",\n \"choices\": [\n \"during the Early Shang Dynasty, from 1,000 to 400 B.P.\",\n \"during the Qin Dynasty, from 3,500 to 3,000 B.P.\",\n \"during the Mature Harappan period, from 4,500 to 4,000 B.P.\",\n \"during the Early Harappan period, from 8,500 to 6,000 B.P.\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"The Traditional Religion Advocacy Party (TRAP) has successfully lobbied the State of Texarkana for a statute named \\\"Equal Rights for All Religions.\\\" The law requires broadcasters that air segments discussing Christianity to allow equal time for segments on Judaism, Islam, Hinduism, and Buddhism. The American Atheism Association (AAA) has put together a broadcast segment about atheism, rejecting all religions, but four of the five Texarkana stations have declined to air the segment because they believe it would violate the statute. AAA has filed suit against the state, challenging the constitutionality of the statute. What is the strongest argument AAA can make in support of striking down the Equal Rights for All Religions statute?\",\n \"subject\": \"professional_law\",\n \"choices\": [\n \"The First Amendment prohibits government interference with freedom of the press.\",\n \"The fact that the statute involves only broadcast media and not print media is an Equal Protection violation.\",\n \"The First Amendment prohibits government interference with the free exercise of religion.\",\n \"The statute is not narrowly tailored to promote a compelling governmental interest.\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"Adaptive thermogenesis refers to:\",\n \"subject\": \"nutrition\",\n \"choices\": [\n \"A decrease in heat loss when exposed to cold\",\n \"A decrease in non-shivering thermogenesis when exposed to cold\",\n \"An increase in basal metabolic rate that is not fully explained by a change in body composition during chronic overfeeding\",\n \"A decrease in spontaneous physical activity during chronic overfeeding.\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"In all of her relationships Helen is typically uncomfortable feeling close to another person or having that person feel close to her. According to attachment theory Helen would best be described as:\",\n \"subject\": \"human_sexuality\",\n \"choices\": [\n \"a secure lover\",\n \"an avoidant lover\",\n \"an anxious-ambivalent lover\",\n \"a passionate lover\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"In primates, the location of which of the following determines if it is a quadruped or biped?\",\n \"subject\": \"prehistory\",\n \"choices\": [\n \"the feet\",\n \"the skull\",\n \"the foramen magnum\",\n \"the ulna\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"What is the meaning of collective security?\",\n \"subject\": \"international_law\",\n \"choices\": [\n \"The right to self-defence by more than one nation acting in concert\",\n \"The right of one's allies to defend the victim State\",\n \"The authorisation of armed force by the UN Security Council\",\n \"The authorisation of peacekeeping missions by the UN General Assembly\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"In the comic strip 'Peanuts' what is Schroeder known for doing?\",\n \"subject\": \"miscellaneous\",\n \"choices\": [\n \"Dancing\",\n \"playing football\",\n \"playing the piano\",\n \"Flying an imaginary plane\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"A writer's latest novel created a debate among critics regarding whether the sexual references and the graphic practices in the book made it obscene. While the publisher was readying the book for distribution, the head of a state commission for morality contacted her to tell her that the book was obscene and that she should collect all copies and turn them over for seizure by the government. He also advised that the commission was putting the book on a list of obscene works that retailers should not handle. She responded that dozens of retailers already had the book for an opening day promotion. The commission seized all of the books from the retailers and destroyed them, without any due process procedural safeguards to the author or the publisher. The author and publisher appealed the case and eventually received a writ of certiorari issued by the U.S. Supreme Court. Will the Court uphold the procedure that was used to declare the book obscene and to restrain its distribution?\",\n \"subject\": \"professional_law\",\n \"choices\": [\n \"Yes, if the authorities determine the book to be obscene, then they may seize and prevent its prospective distribution for the protection of the public.\",\n \"Yes, the determination of obscenity can be made prior to publication because the local authorities have a right to determine the local \\\"community morals\\\" standard.\",\n \"No, the state must first give the publisher and author a preliminary hearing before a magistrate to get a determination if the book is obscene.\",\n \"No, the state cannot exercise prior restraint over published material because that has a chilling effect on free speech; a full judicial determination, with a criminal trial, is required before there can be a finding of a work being obscene.\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"This question refers to the following information.\\n\\\"But you, my dear Pangloss,\\\" said Candide, \\\"how can it be that I behold you again?\\\"\\n\\\"It is true,\\\" said Pangloss, \\\"that you saw me hanged&….A surgeon purchased my body, carried home, and dissected me. He began with making a crucial incision on me from the navel to the clavicula. One could not have been worse hanged than I was. The executioner of the Holy Inquisition was a sub-deacon, and knew how to burn people marvellously well, but he was not accustomed to hanging. The cord was wet and did not slip properly, and besides it was badly tied; in short, I still drew my breath, when the crucial incision made me give such a frightful scream that my surgeon fell flat upon his back&…[At length he] sewed up my wounds; his wife even nursed me. I was upon my legs at the end of fifteen days&….\\nOne day I took it into my head to step into a mosque, where I saw an old Iman and a very pretty young devotee who was saying her paternosters&….She dropped her bouquet; I picked it up, and presented it to her with a profound reverence. I was so long in delivering it that the Iman began to get angry, and seeing that I was a Christian he called out for help. They carried me before the cadi, who ordered me a hundred lashes on the soles of the feet and sent me to the galleys. I was chained to the very same galley and the same bench as the young Baron. On board this galley there were four young men from Marseilles, five Neapolitan priests, and two monks from Corfu, who told us similar adventures happened daily. The Baron maintained that he had suffered greater injustice than I&….We were continually disputing, and received twenty lashes with a bull's pizzle when the concatenation of universal events brought you to our galley, and you were good enough to ransom us.\\\"\\n\\\"Well, my dear Pangloss,\\\" said Candide to him, \\\"when you had been hanged, dissected, whipped, and were tugging at the oar, did you always think that everything happens for the best?\\\"\\n\\\"I am still of my first opinion,\\\" answered Pangloss, \\\"for I am a philosopher and I cannot retract, especially as Leibnitz could never be wrong; and besides, the pre-established harmony is the finest thing in the world, and so is his plenum and materia subtilis.\\\"\\nVoltaire, French Enlightenment writer, Candide, 1759\\nThe themes of the passage and the mode in which Pangloss tells them show the influence of\",\n \"subject\": \"high_school_european_history\",\n \"choices\": [\n \"Medievalism\",\n \"Empiricism\",\n \"Rationalism\",\n \"Romanticism\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"Which of the following is the symplastic pathway for the movement of sucrose from the site of photosynthesis in mesophyll cells into the phloem?\",\n \"subject\": \"college_biology\",\n \"choices\": [\n \"Fibers, phloem parenchyma, companion cell, sieve tube\",\n \"Phloem parenchyma, fibers, bundle sheath, tracheids\",\n \"Companion cells, phloem parenchyma, fibers, sieve tube\",\n \"Bundle sheath, phloem parenchyma, companion cell, sieve tube\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"A 45-year-old man comes to the physician because of right shoulder pain that began after he chopped wood 2 days ago. Examination of the right upper extremity shows no obvious bone deformities or point tenderness. The pain is reproduced when the patient is asked to externally rotate the shoulder against resistance; there is no weakness. In addition to the teres minor, inflammation of which of the following tendons is most likely in this patient?\",\n \"subject\": \"professional_medicine\",\n \"choices\": [\n \"Infraspinatus\",\n \"Pectoralis\",\n \"Subscapularis\",\n \"Supraspinatus\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"Use the following key to translate the given formula of PL to natural, English sentences.\\nA: Marina reads a Percy Jackson book.\\nB: Izzy plays Minecraft.\\nC: Emily stops working.\\nD: Russell makes dinner.\\nE: Ashleigh stops by.\\n~C ∨ D\",\n \"subject\": \"formal_logic\",\n \"choices\": [\n \"If Emily doesn't stop working then Russell makes dinner.\",\n \"Emily stops working unless Russell makes dinner.\",\n \"Emily stops working unless Russell doesn't make dinner.\",\n \"Emily doesn't stop working unless Russell makes dinner.\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"The weight percent of sodium hydroxide dissolved in water is 50%. What is the mole fraction of sodium hydroxide?\",\n \"subject\": \"high_school_chemistry\",\n \"choices\": [\n \"31.00%\",\n \"0.164\",\n \"0.311\",\n \"0.5\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"In a certain region, the electric field varies with the radius away from origin by the equation Er = –6r^2 + 4r + 3, where r is given in meters and E in N/C. The potential difference between the origin and the point (3, 4) is\",\n \"subject\": \"high_school_physics\",\n \"choices\": [\n \"–165 V\",\n \"–120 V\",\n \"64 V\",\n \"185 V\"\n ],\n \"answer\": 3\n }\n] as const satisfies readonly MMLUItem[];\n","/**\n * STS Benchmark subset — the first 100 pairs of the STS-B test split\n * (semantic textual similarity; human scores 0-5). Source:\n * https://huggingface.co/datasets/mteb/stsbenchmark-sts (test split).\n *\n * LICENSE: CC BY-SA 4.0 (share-alike). This file and any redistribution of the\n * pairs below remain under CC BY-SA 4.0 — see LICENSE-CC-BY-SA.md in this\n * directory. Kept isolated from the MIT-licensed code and datasets on purpose.\n *\n * Used by the embedding quality lane: Spearman correlation of cosine\n * similarities against the human scores.\n */\n\n/** One sentence pair with its human similarity score (0-5). */\nexport interface STSPair {\n s1: string;\n s2: string;\n score: number;\n}\n\n/** 100-pair STS-B test subset (order preserved from the source dataset). */\nexport const STSB_SUBSET: readonly STSPair[] = [\n {\n \"s1\": \"A girl is styling her hair.\",\n \"s2\": \"A girl is brushing her hair.\",\n \"score\": 2.5\n },\n {\n \"s1\": \"A group of men play soccer on the beach.\",\n \"s2\": \"A group of boys are playing soccer on the beach.\",\n \"score\": 3.6\n },\n {\n \"s1\": \"One woman is measuring another woman's ankle.\",\n \"s2\": \"A woman measures another woman's ankle.\",\n \"score\": 5.0\n },\n {\n \"s1\": \"A man is cutting up a cucumber.\",\n \"s2\": \"A man is slicing a cucumber.\",\n \"score\": 4.2\n },\n {\n \"s1\": \"A man is playing a harp.\",\n \"s2\": \"A man is playing a keyboard.\",\n \"score\": 1.5\n },\n {\n \"s1\": \"A woman is cutting onions.\",\n \"s2\": \"A woman is cutting tofu.\",\n \"score\": 1.8\n },\n {\n \"s1\": \"A man is riding an electric bicycle.\",\n \"s2\": \"A man is riding a bicycle.\",\n \"score\": 3.5\n },\n {\n \"s1\": \"A man is playing the drums.\",\n \"s2\": \"A man is playing the guitar.\",\n \"score\": 2.2\n },\n {\n \"s1\": \"A man is playing guitar.\",\n \"s2\": \"A lady is playing the guitar.\",\n \"score\": 2.2\n },\n {\n \"s1\": \"A man is playing a guitar.\",\n \"s2\": \"A man is playing a trumpet.\",\n \"score\": 1.714\n },\n {\n \"s1\": \"A man is playing a guitar.\",\n \"s2\": \"A man is playing a trumpet.\",\n \"score\": 1.714\n },\n {\n \"s1\": \"A man is cutting an onion.\",\n \"s2\": \"A man cuts an onion.\",\n \"score\": 5.0\n },\n {\n \"s1\": \"A man is cycling.\",\n \"s2\": \"A man is talking.\",\n \"score\": 0.6\n },\n {\n \"s1\": \"A man is slicing open a fish.\",\n \"s2\": \"A man is cutting up a fish.\",\n \"score\": 4.4\n },\n {\n \"s1\": \"A man is slicing a tomato.\",\n \"s2\": \"A man is slicing a bun.\",\n \"score\": 2.0\n },\n {\n \"s1\": \"A man is playing a guitar.\",\n \"s2\": \"A man is playing a keyboard.\",\n \"score\": 1.8\n },\n {\n \"s1\": \"A baby panda goes down a slide.\",\n \"s2\": \"A panda slides down a slide.\",\n \"score\": 4.4\n },\n {\n \"s1\": \"A man is singing and playing a guitar.\",\n \"s2\": \"A man is playing a guitar.\",\n \"score\": 3.6\n },\n {\n \"s1\": \"A man attacks a woman.\",\n \"s2\": \"A man slaps a woman.\",\n \"score\": 3.6\n },\n {\n \"s1\": \"A man is driving a car.\",\n \"s2\": \"A man is riding a horse.\",\n \"score\": 1.2\n },\n {\n \"s1\": \"A woman is cutting tofu.\",\n \"s2\": \"A woman is cutting an onion.\",\n \"score\": 2.4\n },\n {\n \"s1\": \"The woman is styling her hair.\",\n \"s2\": \"The woman is slicing herbs.\",\n \"score\": 0.2\n },\n {\n \"s1\": \"Two zebras play in an open field.\",\n \"s2\": \"Two zebras are playing in a field.\",\n \"score\": 4.2\n },\n {\n \"s1\": \"A man is cutting a potato.\",\n \"s2\": \"A man is slicing some potato.\",\n \"score\": 4.4\n },\n {\n \"s1\": \"A man is slicing an onion.\",\n \"s2\": \"A woman is slicing a pumpkin.\",\n \"score\": 2.25\n },\n {\n \"s1\": \"A man is dancing.\",\n \"s2\": \"A man and woman is dancing.\",\n \"score\": 2.0\n },\n {\n \"s1\": \"A man is riding a motorcycle.\",\n \"s2\": \"A woman is riding a horse.\",\n \"score\": 0.75\n },\n {\n \"s1\": \"A woman is slicing garlics.\",\n \"s2\": \"A woman is slicing an onion.\",\n \"score\": 2.2\n },\n {\n \"s1\": \"A man is speaking.\",\n \"s2\": \"A man is cooking.\",\n \"score\": 0.8\n },\n {\n \"s1\": \"A little boy is singing and playing a guitar.\",\n \"s2\": \"A man is singing and playing the guitar.\",\n \"score\": 2.2\n },\n {\n \"s1\": \"A turtle is swimming in water.\",\n \"s2\": \"A turtle is walking underwater.\",\n \"score\": 3.2\n },\n {\n \"s1\": \"A young woman is putting stickers all over her face.\",\n \"s2\": \"A woman is applying stickers to her face.\",\n \"score\": 4.8\n },\n {\n \"s1\": \"A woman is wrapping tofu.\",\n \"s2\": \"A woman is balling dough.\",\n \"score\": 1.4\n },\n {\n \"s1\": \"A cat is eating some corn.\",\n \"s2\": \"A cat is eating corn on the cob.\",\n \"score\": 4.25\n },\n {\n \"s1\": \"A man is eating a food.\",\n \"s2\": \"A man is eating a piece of bread.\",\n \"score\": 3.4\n },\n {\n \"s1\": \"A man is playing a guitar.\",\n \"s2\": \"A man is eating pasta.\",\n \"score\": 0.533\n },\n {\n \"s1\": \"A man is kicking pots of water.\",\n \"s2\": \"A man is picking flowers.\",\n \"score\": 0.4\n },\n {\n \"s1\": \"A man is cutting a pipe with scissors.\",\n \"s2\": \"A man is cutting carpet with a knife.\",\n \"score\": 1.2\n },\n {\n \"s1\": \"A woman is dancing in the rain.\",\n \"s2\": \"A woman dances in the rain out side.\",\n \"score\": 5.0\n },\n {\n \"s1\": \"A woman is taking a bath.\",\n \"s2\": \"A woman is riding a horse.\",\n \"score\": 0.538\n },\n {\n \"s1\": \"A man mixes vegetables in a pot.\",\n \"s2\": \"A person is stirring vegetables in a pot.\",\n \"score\": 3.75\n },\n {\n \"s1\": \"A woman is talking on a cell phone.\",\n \"s2\": \"A man and woman are talking on the phone.\",\n \"score\": 3.0\n },\n {\n \"s1\": \"A man is playing a guitar.\",\n \"s2\": \"A man is singing while playing the guitar.\",\n \"score\": 3.6\n },\n {\n \"s1\": \"A man is playing a guitar.\",\n \"s2\": \"A man is driving a car.\",\n \"score\": 0.5\n },\n {\n \"s1\": \"A man is cutting apple by his hand.\",\n \"s2\": \"A man is cutting carpet with a knife.\",\n \"score\": 1.5\n },\n {\n \"s1\": \"A man is opening a door.\",\n \"s2\": \"A man is cutting an onion.\",\n \"score\": 0.8\n },\n {\n \"s1\": \"A man is slicing a tomato.\",\n \"s2\": \"A man is riding a horse.\",\n \"score\": 0.8\n },\n {\n \"s1\": \"A man is cutting paper with a sword.\",\n \"s2\": \"A woman is cutting a tomato.\",\n \"score\": 0.6\n },\n {\n \"s1\": \"A boy studies a calendar.\",\n \"s2\": \"A boy is looking at a calendar.\",\n \"score\": 4.4\n },\n {\n \"s1\": \"The ballerina is dancing.\",\n \"s2\": \"A man is dancing.\",\n \"score\": 1.75\n },\n {\n \"s1\": \"A woman is dancing.\",\n \"s2\": \"A woman is playing violin.\",\n \"score\": 0.4\n },\n {\n \"s1\": \"A woman is slicing some tomatoes.\",\n \"s2\": \"A woman is chopping a potato.\",\n \"score\": 1.4\n },\n {\n \"s1\": \"A woman is water skiing.\",\n \"s2\": \"A woman is slicing fish.\",\n \"score\": 0.4\n },\n {\n \"s1\": \"A man is playing a flute.\",\n \"s2\": \"A man is riding a scooter.\",\n \"score\": 0.8\n },\n {\n \"s1\": \"A man is playing the piano.\",\n \"s2\": \"A man played the guitar.\",\n \"score\": 2.0\n },\n {\n \"s1\": \"A woman is picking a can.\",\n \"s2\": \"A man is playing a guitar.\",\n \"score\": 0.133\n },\n {\n \"s1\": \"A man puts three pieces of meat into a pan.\",\n \"s2\": \"A man is putting meat in a pan.\",\n \"score\": 4.0\n },\n {\n \"s1\": \"A woman is cutting an onion.\",\n \"s2\": \"A woman is cleaning a garden.\",\n \"score\": 0.267\n },\n {\n \"s1\": \"Some men are sawing.\",\n \"s2\": \"Men are sawing logs.\",\n \"score\": 3.4\n },\n {\n \"s1\": \"A car is driven down the road.\",\n \"s2\": \"A girl is walking down a road.\",\n \"score\": 1.2\n },\n {\n \"s1\": \"The man is kissing and hugging the woman.\",\n \"s2\": \"A man is hugging and kissing a woman.\",\n \"score\": 5.0\n },\n {\n \"s1\": \"A train is moving.\",\n \"s2\": \"A man is doing yoga.\",\n \"score\": 0.0\n },\n {\n \"s1\": \"Someone is slicing an onion.\",\n \"s2\": \"A woman is cutting onion.\",\n \"score\": 3.8\n },\n {\n \"s1\": \"A woman is playing in the ocean.\",\n \"s2\": \"A woman is preparing shrimp to cook.\",\n \"score\": 0.75\n },\n {\n \"s1\": \"A person is playing an electronic keyboard.\",\n \"s2\": \"A kid is playing keyboard.\",\n \"score\": 3.4\n },\n {\n \"s1\": \"A man is holding a leaf.\",\n \"s2\": \"A monkey is fighting a man.\",\n \"score\": 0.0\n },\n {\n \"s1\": \"A woman is peeling shrimp.\",\n \"s2\": \"A man is squeezing water.\",\n \"score\": 0.2\n },\n {\n \"s1\": \"A man is sitting and smoking.\",\n \"s2\": \"A man is smoking a cigarette.\",\n \"score\": 4.0\n },\n {\n \"s1\": \"A man is playing a guitar.\",\n \"s2\": \"A woman is riding a horse.\",\n \"score\": 0.5\n },\n {\n \"s1\": \"A man is standing in front of the window and looking outside.\",\n \"s2\": \"A man is staring out the window.\",\n \"score\": 3.8\n },\n {\n \"s1\": \"A skunk is looking here and there.\",\n \"s2\": \"A skunk looks at the camera.\",\n \"score\": 2.4\n },\n {\n \"s1\": \"A man is playing the guitar and singing.\",\n \"s2\": \"A man sings with a guitar.\",\n \"score\": 4.75\n },\n {\n \"s1\": \"A woman opens a window.\",\n \"s2\": \"A man is crawling.\",\n \"score\": 0.0\n },\n {\n \"s1\": \"People are dancing outside.\",\n \"s2\": \"A group of people are dancing.\",\n \"score\": 3.75\n },\n {\n \"s1\": \"The man is using a camera to hammer a nail.\",\n \"s2\": \"Someone is banging a camera lense against a nail.\",\n \"score\": 2.6\n },\n {\n \"s1\": \"A woman is filing her nails.\",\n \"s2\": \"A man is peeling a carrot.\",\n \"score\": 0.0\n },\n {\n \"s1\": \"A boy is crawling into a dog house.\",\n \"s2\": \"A boy is playing a wooden flute.\",\n \"score\": 0.75\n },\n {\n \"s1\": \"A woman is swimming underwater.\",\n \"s2\": \"A man is slicing some carrots.\",\n \"score\": 0.0\n },\n {\n \"s1\": \"A machine is sharpening a pencil.\",\n \"s2\": \"The machine shaved the end of the pencil.\",\n \"score\": 3.8\n },\n {\n \"s1\": \"A monkey is playing drums.\",\n \"s2\": \"A gorilla plays the drums.\",\n \"score\": 2.8\n },\n {\n \"s1\": \"A man is opening a box and taking out paper.\",\n \"s2\": \"A woman is peeling a potato.\",\n \"score\": 0.0\n },\n {\n \"s1\": \"A woman is dancing.\",\n \"s2\": \"A woman plays the clarinet.\",\n \"score\": 0.8\n },\n {\n \"s1\": \"A person is drawing on a large touchscreen.\",\n \"s2\": \"A man is drawing on a digital dry erase board.\",\n \"score\": 3.0\n },\n {\n \"s1\": \"The men played follow the leader on the grass.\",\n \"s2\": \"The rhino grazed on the grass.\",\n \"score\": 1.0\n },\n {\n \"s1\": \"A woman is cracking eggs.\",\n \"s2\": \"A man is talking to a woman.\",\n \"score\": 0.0\n },\n {\n \"s1\": \"A woman peels garlic with her hands.\",\n \"s2\": \"The woman is slicing herbs.\",\n \"score\": 1.0\n },\n {\n \"s1\": \"The polar bears fought over the kill.\",\n \"s2\": \"Polar bears are fighting each other.\",\n \"score\": 3.4\n },\n {\n \"s1\": \"A man is doing trick with play cards.\",\n \"s2\": \"A man is performing a card trick.\",\n \"score\": 5.0\n },\n {\n \"s1\": \"The cat is licking a bottle.\",\n \"s2\": \"A cat plays with a small bottle.\",\n \"score\": 2.333\n },\n {\n \"s1\": \"A person is slicing an onion.\",\n \"s2\": \"A person cuts ginger.\",\n \"score\": 1.4\n },\n {\n \"s1\": \"A person is peeling a potato with a potato peeler.\",\n \"s2\": \"A man is cutting tomatoes with a cleaver.\",\n \"score\": 0.75\n },\n {\n \"s1\": \"Two women are dancing and singing in front of a crowd.\",\n \"s2\": \"The women are singing and dancing.\",\n \"score\": 3.538\n },\n {\n \"s1\": \"A man is seasoning some carrots.\",\n \"s2\": \"A woman is slicing garlic.\",\n \"score\": 0.8\n },\n {\n \"s1\": \"Two men pushed carts through the woods.\",\n \"s2\": \"Two men are pushing carts.\",\n \"score\": 3.5\n },\n {\n \"s1\": \"A man is playing a football.\",\n \"s2\": \"A man is maneuvering a soccer ball with his feet.\",\n \"score\": 2.0\n },\n {\n \"s1\": \"The lady peeled the potatoe.\",\n \"s2\": \"A woman is peeling a potato.\",\n \"score\": 4.75\n },\n {\n \"s1\": \"A woman is slicing some tofu.\",\n \"s2\": \"A woman is cutting a block of tofu into small cubes.\",\n \"score\": 4.0\n },\n {\n \"s1\": \"Someone typed on a keyboard.\",\n \"s2\": \"Someone is typing.\",\n \"score\": 4.5\n },\n {\n \"s1\": \"Three young men run, jump, and kick off of a Coke machine.\",\n \"s2\": \"Three men are jumping off a wall.\",\n \"score\": 1.5\n },\n {\n \"s1\": \"A young Asian girl is applying eyeliner.\",\n \"s2\": \"A girl is putting on eye makeup.\",\n \"score\": 2.4\n }\n];\n","/**\n * Quality-fidelity lane. Scores measure runtime/quantization fidelity of a\n * model build (do this runtime's weights + kernels reproduce expected answers),\n * NOT model capability — the bundled public sets are assumed to be in every\n * model's training data. Always run at temperature 0, outside timed regions.\n */\n\nimport type { QualityResult } from './types.js';\nimport type { BenchEmbeddingModel, BenchLanguageModel } from './adapter.js';\nimport { TINY_MMLU } from './datasets/tiny-mmlu.js';\nimport { STSB_SUBSET } from './datasets/stsb/stsb-subset.js';\nimport { spearman } from './stats.js';\nimport { abortDomException } from './timing.js';\n\nconst LETTERS = ['A', 'B', 'C', 'D'] as const;\n\n/** Fixed MCQ prompt template (part of the versioned protocol). */\nexport function formatMMLUPrompt(item: (typeof TINY_MMLU)[number]): string {\n const choices = item.choices.map((c, i) => `${LETTERS[i]}. ${c}`).join('\\n');\n return (\n `The following is a multiple choice question about ${item.subject.replace(/_/g, ' ')}.\\n\\n` +\n `${item.question}\\n${choices}\\n\\n` +\n `Answer with only the letter (A, B, C, or D) of the correct choice.\\nAnswer:`\n );\n}\n\n/**\n * Parse the answer letter from a model response. Accepts \"B\", \"B.\", \"(B)\",\n * \"Answer: B\", or a response beginning with the exact choice text.\n *\n * @returns 0-3, or null when no unambiguous answer is present.\n */\nexport function parseMMLUAnswer(response: string, choices: readonly string[]): number | null {\n const trimmed = response.trim();\n const letterMatch = trimmed.match(/(?:^|answer\\s*(?:is)?\\s*[:-]?\\s*)\\(?([ABCD])\\)?(?=[\\s.,)!]|$)/i);\n if (letterMatch) return LETTERS.indexOf(letterMatch[1].toUpperCase() as (typeof LETTERS)[number]);\n const lower = trimmed.toLowerCase();\n for (let i = 0; i < choices.length; i++) {\n if (lower.startsWith(choices[i].toLowerCase().slice(0, Math.max(8, choices[i].length)))) return i;\n }\n return null;\n}\n\n/**\n * Run the tinyMMLU fidelity task on a language model (temperature 0,\n * `maxTokens` 8, greedy answer parsing). Unparseable answers count as wrong.\n *\n * @param model - Any structurally-compatible LanguageModel.\n * @param items - Number of items from the 100-item set (25 or 100 in v1).\n * @returns Accuracy in [0,1] with per-item correctness details.\n */\nexport async function runMMLUFidelity(\n model: BenchLanguageModel,\n items: number,\n options?: { abortSignal?: AbortSignal; onProgress?: (done: number, total: number) => void },\n): Promise<QualityResult> {\n const subset = TINY_MMLU.slice(0, items);\n const details: number[] = [];\n let correct = 0;\n for (let i = 0; i < subset.length; i++) {\n if (options?.abortSignal?.aborted) throw abortDomException();\n const item = subset[i];\n const result = await model.doGenerate({\n prompt: formatMMLUPrompt(item),\n maxTokens: 8,\n temperature: 0,\n abortSignal: options?.abortSignal,\n });\n const parsed = parseMMLUAnswer(result.text, item.choices);\n const ok = parsed === item.answer ? 1 : 0;\n correct += ok;\n details.push(ok);\n options?.onProgress?.(i + 1, subset.length);\n }\n return {\n taskId: `tinymmlu-${items}`,\n score: subset.length === 0 ? 0 : correct / subset.length,\n n: subset.length,\n details,\n };\n}\n\n/** Cosine similarity of two vectors. */\nfunction cosine(a: Float32Array, b: Float32Array): number {\n let dot = 0;\n let na = 0;\n let nb = 0;\n for (let i = 0; i < a.length; i++) {\n dot += a[i] * b[i];\n na += a[i] * a[i];\n nb += b[i] * b[i];\n }\n const den = Math.sqrt(na) * Math.sqrt(nb);\n return den === 0 ? 0 : dot / den;\n}\n\n/**\n * Run the STS-B embedding-quality task: Spearman correlation of cosine\n * similarities against human scores over the bundled pair subset.\n *\n * @param model - Any structurally-compatible EmbeddingModel.\n * @param pairs - Number of pairs from the 100-pair set.\n * @returns Spearman rho with per-pair cosine details.\n */\nexport async function runSTSQuality(\n model: BenchEmbeddingModel,\n pairs: number,\n options?: { abortSignal?: AbortSignal; onProgress?: (done: number, total: number) => void },\n): Promise<QualityResult> {\n const subset = STSB_SUBSET.slice(0, pairs);\n const sims: number[] = [];\n const humanScores: number[] = [];\n for (let i = 0; i < subset.length; i++) {\n if (options?.abortSignal?.aborted) throw abortDomException();\n const pair = subset[i];\n const { embeddings } = await model.doEmbed({\n values: [pair.s1, pair.s2],\n abortSignal: options?.abortSignal,\n });\n sims.push(cosine(embeddings[0], embeddings[1]));\n humanScores.push(pair.score);\n options?.onProgress?.(i + 1, subset.length);\n }\n return {\n taskId: `stsb-${pairs}`,\n score: sims.length >= 2 ? spearman(sims, humanScores) : 0,\n n: subset.length,\n details: sims.map((s) => Math.round(s * 10_000) / 10_000),\n };\n}\n","/**\n * The suite runner: executes (runtime x model x workload) cells under the\n * versioned run policy — cache probe, load, untimed warmup, N timed runs with\n * raw per-chunk traces, validity gates, memory protocol points, cool-downs —\n * and assembles the submittable BenchRunResult.\n */\n\nimport type {\n BenchCellResult,\n BenchModelRef,\n BenchRunResult,\n BenchSuiteId,\n EmbedIteration,\n EmbedWorkloadSpec,\n LLMIteration,\n LLMWorkloadSpec,\n LoadRecord,\n MemorySample,\n QualityWorkloadSpec,\n} from './types.js';\nimport { BENCH_PROTOCOL_VERSION, BENCH_SCHEMA_VERSION } from './types.js';\nimport type {\n EmbeddingRuntimeAdapter,\n LLMRuntimeAdapter,\n LoadedEmbedder,\n LoadedLLM,\n} from './adapter.js';\nimport { USAGE_FIDELITY } from './adapter.js';\nimport type { RunPolicy } from './protocol.js';\nimport { hrNow, sleep, abortDomException } from './timing.js';\nimport { TraceRecorder } from './trace.js';\nimport { memoryApiAvailable, sampleMemoryBytes } from './memory.js';\nimport { captureEnvironment } from './env.js';\nimport { runFingerprint } from './fingerprint.js';\nimport { summarizeRun } from './validate.js';\nimport { runMMLUFidelity, runSTSQuality } from './quality.js';\n\n/** One planned cell. Cells sharing (runtimeId, model) reuse the loaded model. */\nexport interface PlannedCell {\n model: BenchModelRef;\n workload: LLMWorkloadSpec | EmbedWorkloadSpec | QualityWorkloadSpec;\n}\n\n/** Progress callbacks for a host UI. */\nexport interface RunnerHooks {\n onCellStart?(cellId: string, index: number, total: number): void;\n onCellFinish?(cell: BenchCellResult): void;\n onLoadProgress?(cellId: string, pct: number | undefined): void;\n onIteration?(cellId: string, iteration: number, total: number): void;\n onPhase?(phase: string): void;\n}\n\n/** Inputs to a suite run. */\nexport interface RunSuiteOptions {\n suite: BenchSuiteId;\n cells: PlannedCell[];\n policy: RunPolicy;\n llmAdapters: ReadonlyMap<string, LLMRuntimeAdapter>;\n embedAdapters: ReadonlyMap<string, EmbeddingRuntimeAdapter>;\n harness: { name: string; version: string; appVersion?: string };\n hooks?: RunnerHooks;\n abortSignal?: AbortSignal;\n /** Skip the fingerprint microbenchmark (tests only; submissions require it). */\n skipFingerprint?: boolean;\n userReportedDevice?: string;\n}\n\n/**\n * Run a benchmark suite and return the full, submittable result (raw traces\n * included; `clientSummaries` computed with the same code the server uses).\n *\n * Cells are grouped by (runtime, model): the model loads once, its workloads\n * run back-to-back, then it is disposed before the next model (peak-memory\n * hygiene). Validity gates never retry silently — affected iterations carry\n * their gate events and the cell is marked invalid.\n *\n * @throws {DOMException} AbortError when `abortSignal` aborts.\n * @example\n * const result = await runBenchmarkSuite({ suite: 'quick', cells, policy, ... });\n */\nexport async function runBenchmarkSuite(options: RunSuiteOptions): Promise<BenchRunResult> {\n const { policy, hooks, abortSignal } = options;\n const trace = new TraceRecorder();\n await trace.attach();\n trace.record('suite-start', options.suite);\n\n const memApi = memoryApiAvailable();\n const cells: BenchCellResult[] = [];\n\n try {\n hooks?.onPhase?.('environment');\n const environment = await captureEnvironment({\n userReportedDevice: options.userReportedDevice,\n });\n\n hooks?.onPhase?.('fingerprint');\n throwIfAborted(abortSignal);\n const fingerprint = options.skipFingerprint ? null : await runFingerprint();\n\n const baselineMemory = memApi !== 'none' ? await sampleMemoryBytes() : null;\n\n // Group cells so each (runtime, model) loads exactly once.\n const groups = groupCells(options.cells);\n const totalCells = options.cells.length;\n let cellIndex = 0;\n\n for (const group of groups) {\n throwIfAborted(abortSignal);\n const groupCellsResults = await runModelGroup(group, {\n ...options,\n trace,\n memApi,\n baselineMemory,\n cellIndexRef: () => cellIndex++,\n totalCells,\n });\n cells.push(...groupCellsResults);\n\n trace.record('cooldown-start');\n await sleep(policy.cooldownMs, abortSignal).catch((e) => {\n if ((e as Error).name === 'AbortError') throw e;\n });\n if (policy.pressureGate) await waitForPressure(trace, policy.pressureGateTimeoutMs, abortSignal);\n trace.record('cooldown-end');\n }\n\n trace.record('suite-end');\n const result: BenchRunResult = {\n protocol: BENCH_PROTOCOL_VERSION,\n schemaVersion: BENCH_SCHEMA_VERSION,\n runId: generateRunId(),\n createdAt: new Date().toISOString(),\n harness: options.harness,\n suite: options.suite,\n environment,\n fingerprint,\n cells,\n events: [...trace.all],\n };\n result.clientSummaries = summarizeRun(result, policy.highVarianceCv);\n return result;\n } finally {\n await trace.dispose();\n }\n}\n\n/** Cells grouped per (runtimeId, benchModelId + providerModelId). */\ninterface ModelGroup {\n key: string;\n model: BenchModelRef;\n workloads: Array<LLMWorkloadSpec | EmbedWorkloadSpec | QualityWorkloadSpec>;\n}\n\nfunction groupCells(cells: PlannedCell[]): ModelGroup[] {\n const map = new Map<string, ModelGroup>();\n for (const cell of cells) {\n const key = `${cell.model.runtimeId}/${cell.model.benchModelId}/${cell.model.providerModelId}`;\n let group = map.get(key);\n if (!group) {\n group = { key, model: cell.model, workloads: [] };\n map.set(key, group);\n }\n group.workloads.push(cell.workload);\n }\n return [...map.values()];\n}\n\ninterface GroupContext extends RunSuiteOptions {\n trace: TraceRecorder;\n memApi: MemorySample['api'];\n baselineMemory: number | null;\n cellIndexRef: () => number;\n totalCells: number;\n}\n\n/** Load one model, run all its workloads, dispose. Errors isolate per group. */\nasync function runModelGroup(group: ModelGroup, ctx: GroupContext): Promise<BenchCellResult[]> {\n const { model } = group;\n const isEmbedding = model.task === 'embedding';\n const adapter = isEmbedding\n ? ctx.embedAdapters.get(model.runtimeId)\n : ctx.llmAdapters.get(model.runtimeId);\n\n const results: BenchCellResult[] = [];\n const baseCell = (workload: ModelGroup['workloads'][number]): BenchCellResult => ({\n cellId: `${model.runtimeId}/${model.benchModelId}/${workload.id}`,\n runtimeId: model.runtimeId,\n runtimeVersion: adapter?.runtimeVersion,\n model,\n workloadId: workload.id,\n workloadKind: workload.kind,\n resolvedBackend: 'unknown',\n load: null,\n iterations: [],\n status: 'skipped',\n });\n\n if (!adapter) {\n for (const workload of group.workloads) {\n const cell = baseCell(workload);\n cell.invalidReasons = [`no adapter registered for ${model.runtimeId}`];\n results.push(finishCell(cell, ctx));\n }\n return results;\n }\n\n const availability = await adapter.isAvailable();\n if (!availability.ok) {\n for (const workload of group.workloads) {\n const cell = baseCell(workload);\n cell.invalidReasons = [`runtime unavailable: ${availability.reason ?? 'unknown'}`];\n results.push(finishCell(cell, ctx));\n }\n return results;\n }\n\n // Load phase (recorded once, attached to the group's first cell).\n let loaded: LoadedLLM | LoadedEmbedder | null = null;\n let loadRecord: LoadRecord | null = null;\n let warmupMs: number | undefined;\n let postLoadMemory: number | null = null;\n\n try {\n throwIfAborted(ctx.abortSignal);\n const cached = await adapter.isModelCached(model);\n const progress: Array<{ t: number; pct: number }> = [];\n const loadStart = hrNow();\n const firstCellId = `${model.runtimeId}/${model.benchModelId}/${group.workloads[0].id}`;\n loaded = await adapter.load(model, {\n abortSignal: ctx.abortSignal,\n onProgress: (p) => {\n if (typeof p.pct === 'number' && (progress.length === 0 || p.pct - progress[progress.length - 1].pct >= 2)) {\n progress.push({ t: hrNow(), pct: Math.round(p.pct * 100) / 100 });\n }\n ctx.hooks?.onLoadProgress?.(firstCellId, p.pct);\n },\n });\n const loadEnd = hrNow();\n loadRecord = {\n cached,\n startT: loadStart,\n endT: loadEnd,\n progress: progress.length > 0 ? decimate(progress, 50) : undefined,\n declaredBytes: model.sizeBytes,\n };\n\n if (ctx.memApi !== 'none') postLoadMemory = await sampleMemoryBytes();\n\n // Untimed warmup (absorbs shader compilation / JIT / first-inference costs).\n if (ctx.policy.warmupRuns > 0) {\n const warmupStart = hrNow();\n for (let i = 0; i < ctx.policy.warmupRuns; i++) {\n throwIfAborted(ctx.abortSignal);\n if (isEmbedding) {\n await (loaded as LoadedEmbedder).model.doEmbed({\n values: ['warmup probe'],\n abortSignal: ctx.abortSignal,\n });\n } else {\n await consumeStream(\n (loaded as LoadedLLM).model,\n { prompt: 'Reply with the single word: ready', maxTokens: 4, temperature: 0 },\n ctx.abortSignal,\n );\n }\n }\n warmupMs = hrNow() - warmupStart;\n }\n } catch (error) {\n if ((error as Error).name === 'AbortError') {\n if (loaded) await safeDispose(loaded);\n throw error;\n }\n for (const workload of group.workloads) {\n const cell = baseCell(workload);\n cell.status = 'error';\n cell.load = loadRecord;\n cell.error = { name: (error as Error).name ?? 'Error', message: (error as Error).message ?? String(error) };\n results.push(finishCell(cell, ctx));\n }\n if (loaded) await safeDispose(loaded);\n return results;\n }\n\n // Workload cells over the live model.\n let attachedLoad = false;\n for (const workload of group.workloads) {\n throwIfAborted(ctx.abortSignal);\n const cell = baseCell(workload);\n cell.resolvedBackend = loaded.resolvedBackend;\n if (!attachedLoad) {\n cell.load = loadRecord;\n cell.warmupMs = warmupMs;\n attachedLoad = true;\n }\n const index = ctx.cellIndexRef();\n ctx.hooks?.onCellStart?.(cell.cellId, index, ctx.totalCells);\n\n try {\n switch (workload.kind) {\n case 'llm-generate':\n await runLLMCell(cell, loaded as LoadedLLM, workload, ctx);\n break;\n case 'embed-single':\n case 'embed-batch':\n await runEmbedCell(cell, loaded as LoadedEmbedder, workload, ctx);\n break;\n case 'quality-mmlu': {\n const total = workload.items;\n cell.quality = await runMMLUFidelity((loaded as LoadedLLM).model, total, {\n abortSignal: ctx.abortSignal,\n onProgress: (done) => ctx.hooks?.onIteration?.(cell.cellId, done, total),\n });\n cell.status = 'ok';\n break;\n }\n case 'quality-sts': {\n const total = workload.items;\n cell.quality = await runSTSQuality((loaded as LoadedEmbedder).model, total, {\n abortSignal: ctx.abortSignal,\n onProgress: (done) => ctx.hooks?.onIteration?.(cell.cellId, done, total),\n });\n cell.status = 'ok';\n break;\n }\n }\n } catch (error) {\n if ((error as Error).name === 'AbortError') {\n await safeDispose(loaded);\n throw error;\n }\n cell.status = 'error';\n cell.error = { name: (error as Error).name ?? 'Error', message: (error as Error).message ?? String(error) };\n }\n\n if (ctx.memApi !== 'none' && cell.status === 'ok') {\n const postRun = await sampleMemoryBytes(5_000);\n cell.memory = {\n api: ctx.memApi,\n baseline: ctx.baselineMemory ?? undefined,\n postLoad: postLoadMemory ?? undefined,\n postRun: postRun ?? undefined,\n };\n }\n results.push(finishCell(cell, ctx));\n }\n\n await safeDispose(loaded);\n\n // Warm-reload lane: after a cold load, reload to measure the cache-hit path.\n if (ctx.policy.measureWarmReload && loadRecord?.cached === false) {\n try {\n throwIfAborted(ctx.abortSignal);\n const start = hrNow();\n const reloaded = await adapter.load(model, { abortSignal: ctx.abortSignal });\n const end = hrNow();\n await safeDispose(reloaded);\n const warmCell: BenchCellResult = {\n cellId: `${model.runtimeId}/${model.benchModelId}/warm-reload`,\n runtimeId: model.runtimeId,\n runtimeVersion: adapter.runtimeVersion,\n model,\n workloadId: 'warm-reload',\n workloadKind: 'llm-generate',\n resolvedBackend: reloaded.resolvedBackend,\n load: { cached: true, startT: start, endT: end, declaredBytes: model.sizeBytes },\n iterations: [],\n status: 'ok',\n };\n results.push(finishCell(warmCell, ctx));\n } catch (error) {\n if ((error as Error).name === 'AbortError') throw error;\n // Warm-reload is auxiliary; a failure here never invalidates the group.\n }\n }\n\n return results;\n}\n\n/** Timed LLM iterations with raw chunk traces. */\nasync function runLLMCell(\n cell: BenchCellResult,\n loaded: LoadedLLM,\n workload: LLMWorkloadSpec,\n ctx: GroupContext,\n): Promise<void> {\n const iterations: LLMIteration[] = [];\n for (let i = 0; i < ctx.policy.timedRuns; i++) {\n throwIfAborted(ctx.abortSignal);\n ctx.hooks?.onIteration?.(cell.cellId, i + 1, ctx.policy.timedRuns);\n const gates: string[] = [];\n if (ctx.trace.isHidden) gates.push('started-hidden');\n const hiddenBefore = countHidden(ctx.trace);\n\n const startT = hrNow();\n const { chunks, text, providerUsage, finishReason } = await consumeStream(\n loaded.model,\n {\n prompt: workload.prompt,\n systemPrompt: workload.systemPrompt,\n maxTokens: workload.maxTokens,\n temperature: workload.temperature,\n },\n ctx.abortSignal,\n );\n const endT = hrNow();\n if (countHidden(ctx.trace) > hiddenBefore) gates.push('hidden-during-run');\n\n iterations.push({\n startT,\n chunks,\n endT,\n text,\n providerUsage: providerUsage\n ? { ...providerUsage, fidelity: USAGE_FIDELITY[cell.runtimeId] }\n : undefined,\n finishReason,\n gates,\n });\n }\n cell.iterations = iterations;\n const gated = iterations.some((it) => it.gates.length > 0);\n cell.status = gated ? 'invalid' : 'ok';\n if (gated) cell.invalidReasons = ['validity gate fired during a timed region'];\n}\n\n/** Timed embedding iterations. */\nasync function runEmbedCell(\n cell: BenchCellResult,\n loaded: LoadedEmbedder,\n workload: EmbedWorkloadSpec,\n ctx: GroupContext,\n): Promise<void> {\n const iterations: EmbedIteration[] = [];\n for (let i = 0; i < ctx.policy.timedRuns; i++) {\n throwIfAborted(ctx.abortSignal);\n ctx.hooks?.onIteration?.(cell.cellId, i + 1, ctx.policy.timedRuns);\n const gates: string[] = [];\n if (ctx.trace.isHidden) gates.push('started-hidden');\n const hiddenBefore = countHidden(ctx.trace);\n\n const startT = hrNow();\n const { embeddings } = await loaded.model.doEmbed({\n values: workload.texts,\n abortSignal: ctx.abortSignal,\n });\n const endT = hrNow();\n if (countHidden(ctx.trace) > hiddenBefore) gates.push('hidden-during-run');\n\n iterations.push({\n startT,\n endT,\n count: workload.texts.length,\n dimensions: embeddings[0]?.length ?? loaded.model.dimensions,\n gates,\n });\n }\n cell.iterations = iterations;\n const gated = iterations.some((it) => it.gates.length > 0);\n cell.status = gated ? 'invalid' : 'ok';\n if (gated) cell.invalidReasons = ['validity gate fired during a timed region'];\n}\n\n/** Drain a model stream, timestamping every chunk (falls back to doGenerate). */\nasync function consumeStream(\n model: LoadedLLM['model'],\n options: { prompt: string; systemPrompt?: string; maxTokens: number; temperature: number },\n abortSignal?: AbortSignal,\n): Promise<{\n chunks: Array<{ t: number; c: number }>;\n text: string;\n providerUsage?: Omit<import('./types.js').ProviderUsage, 'fidelity'>;\n finishReason?: string;\n}> {\n const chunks: Array<{ t: number; c: number }> = [];\n let text = '';\n let providerUsage: Omit<import('./types.js').ProviderUsage, 'fidelity'> | undefined;\n let finishReason: string | undefined;\n\n if (model.doStream) {\n for await (const chunk of model.doStream({ ...options, abortSignal })) {\n const t = hrNow();\n if (chunk.text.length > 0) {\n chunks.push({ t, c: chunk.text.length });\n text += chunk.text;\n }\n if (chunk.done) {\n providerUsage = chunk.usage;\n finishReason = chunk.finishReason;\n }\n }\n } else {\n const result = await model.doGenerate({ ...options, abortSignal });\n const t = hrNow();\n text = result.text;\n chunks.push({ t, c: result.text.length });\n providerUsage = result.usage;\n finishReason = result.finishReason;\n }\n return { chunks, text, providerUsage, finishReason };\n}\n\n/** Count visibility-hidden events recorded so far. */\nfunction countHidden(trace: TraceRecorder): number {\n let n = 0;\n for (const e of trace.all) if (e.type === 'visibility-hidden') n++;\n return n;\n}\n\n/** Wait until compute pressure recovers to nominal/fair (best-effort). */\nasync function waitForPressure(\n trace: TraceRecorder,\n timeoutMs: number,\n abortSignal?: AbortSignal,\n): Promise<void> {\n const deadline = hrNow() + timeoutMs;\n while (hrNow() < deadline) {\n const state = trace.pressureState;\n if (state === undefined || state === 'nominal' || state === 'fair') return;\n await sleep(1_000, abortSignal);\n }\n}\n\n/** Downsample a progress array to at most `max` entries (keeps endpoints). */\nfunction decimate<T>(items: T[], max: number): T[] {\n if (items.length <= max) return items;\n const out: T[] = [];\n const step = (items.length - 1) / (max - 1);\n for (let i = 0; i < max; i++) out.push(items[Math.round(i * step)]);\n return out;\n}\n\nfunction finishCell(cell: BenchCellResult, ctx: GroupContext): BenchCellResult {\n ctx.hooks?.onCellFinish?.(cell);\n return cell;\n}\n\nasync function safeDispose(loaded: LoadedLLM | LoadedEmbedder): Promise<void> {\n try {\n await loaded.dispose();\n } catch {\n // Disposal failures must never corrupt a completed result.\n }\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) throw abortDomException();\n}\n\n/** UUID v4 via Web Crypto, with a deterministic-format fallback. */\nfunction generateRunId(): string {\n const cryptoObj = globalThis.crypto as Crypto | undefined;\n if (cryptoObj?.randomUUID) return cryptoObj.randomUUID();\n const bytes = new Uint8Array(16);\n if (cryptoObj?.getRandomValues) cryptoObj.getRandomValues(bytes);\n else for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n","/**\n * Canonical JSON serialization + SHA-256 digest for run results. The digest\n * covers the canonical form of the result WITHOUT its `digest` field, so any\n * party can recompute and verify it (isomorphic: browser and Node).\n */\n\nimport type { BenchRunResult } from './types.js';\n\n/**\n * Deterministic JSON: object keys sorted lexicographically at every level,\n * arrays in order, no whitespace. Non-finite numbers serialize as null\n * (JSON.stringify semantics) so digests stay portable.\n *\n * @example\n * canonicalJson({ b: 1, a: [2, { d: 3, c: 4 }] }); // '{\"a\":[2,{\"c\":4,\"d\":3}],\"b\":1}'\n */\nexport function canonicalJson(value: unknown): string {\n return stringify(value);\n}\n\nfunction stringify(value: unknown): string {\n if (value === null || typeof value === 'number' || typeof value === 'boolean') {\n return JSON.stringify(value);\n }\n if (typeof value === 'string') return JSON.stringify(value);\n if (typeof value === 'undefined') return 'null';\n if (Array.isArray(value)) return `[${value.map((v) => stringify(v)).join(',')}]`;\n if (typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([k, v]) => `${JSON.stringify(k)}:${stringify(v)}`);\n return `{${entries.join(',')}}`;\n }\n throw new TypeError(`canonicalJson: unsupported value type ${typeof value}`);\n}\n\n/** SHA-256 hex of a UTF-8 string via Web Crypto (browser + Node >= 19). */\nexport async function sha256Hex(text: string): Promise<string> {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) throw new Error('Web Crypto (crypto.subtle) is not available in this environment');\n const bytes = new TextEncoder().encode(text);\n const hash = await subtle.digest('SHA-256', bytes);\n return [...new Uint8Array(hash)].map((b) => b.toString(16).padStart(2, '0')).join('');\n}\n\n/**\n * Compute the run digest: SHA-256 of the canonical JSON of the result with\n * `digest` removed.\n *\n * @example\n * result.digest = await computeRunDigest(result);\n */\nexport async function computeRunDigest(result: BenchRunResult): Promise<string> {\n const { digest: _omitted, ...rest } = result;\n return sha256Hex(canonicalJson(rest));\n}\n\n/** Verify a result's embedded digest. Returns false when absent or wrong. */\nexport async function verifyRunDigest(result: BenchRunResult): Promise<boolean> {\n if (!result.digest) return false;\n return (await computeRunDigest(result)) === result.digest;\n}\n","/**\n * Aggregation for the public leaderboard and for paper analysis. Runs group\n * into device-class rows; medians are taken per submission first, then across\n * submissions (median-of-medians). Nothing is ever averaged across devices.\n */\n\nimport type { BenchRunResult, CellSummary } from './types.js';\nimport { summarizeRun } from './validate.js';\nimport { median } from './stats.js';\n\n/** Device class derived from environment identity signals. */\nexport function deviceClassOf(run: BenchRunResult): string {\n const env = run.environment;\n const gpu = env.gpu.available\n ? [env.gpu.vendor ?? 'gpu', env.gpu.architecture].filter(Boolean).join('-')\n : 'no-webgpu';\n return [env.os.platform.toLowerCase().replace(/\\s+/g, '-'), gpu].join('/');\n}\n\n/** One leaderboard row: a (deviceClass, runtime, model, workload) group. */\nexport interface LeaderboardRow {\n deviceClass: string;\n runtimeId: string;\n benchModelId: string;\n modelName: string;\n workloadId: string;\n /** Number of distinct submissions contributing. */\n submissions: number;\n /** Median-of-medians metrics (only those applicable to the workload). */\n ttftMs?: number;\n decodeCharsPerSec?: number;\n singleLatencyMs?: number;\n batchTextsPerSec?: number;\n loadColdMs?: number;\n loadWarmMs?: number;\n qualityScore?: number;\n resolvedBackends: string[];\n browsers: string[];\n /** True when any contributing submission had a high-variance metric. */\n highVariance: boolean;\n /** Rows below the min-N threshold are provisional. */\n provisional: boolean;\n}\n\n/** Minimum concordant submissions for a non-provisional headline row. */\nexport const HEADLINE_MIN_SUBMISSIONS = 3;\n\n/**\n * Aggregate validated runs into leaderboard rows.\n *\n * @param runs - Validated (non-quarantined) run results.\n * @param minSubmissions - Min submissions before a row loses `provisional`.\n * @example\n * const rows = aggregateRuns(allRuns);\n */\nexport function aggregateRuns(\n runs: readonly BenchRunResult[],\n minSubmissions = HEADLINE_MIN_SUBMISSIONS,\n): LeaderboardRow[] {\n interface Bucket {\n row: Omit<\n LeaderboardRow,\n | 'submissions'\n | 'ttftMs'\n | 'decodeCharsPerSec'\n | 'singleLatencyMs'\n | 'batchTextsPerSec'\n | 'loadColdMs'\n | 'loadWarmMs'\n | 'qualityScore'\n | 'provisional'\n >;\n ttft: number[];\n decode: number[];\n single: number[];\n batch: number[];\n loadCold: number[];\n loadWarm: number[];\n quality: number[];\n runIds: Set<string>;\n }\n const buckets = new Map<string, Bucket>();\n\n for (const run of runs) {\n const deviceClass = deviceClassOf(run);\n const summaries = run.clientSummaries ?? summarizeRun(run);\n const byCellId = new Map<string, CellSummary>(summaries.map((s) => [s.cellId, s]));\n\n for (const cell of run.cells) {\n if (cell.status !== 'ok') continue;\n const summary = byCellId.get(cell.cellId);\n if (!summary) continue;\n const key = [deviceClass, cell.runtimeId, cell.model.benchModelId, cell.workloadId].join('|');\n let bucket = buckets.get(key);\n if (!bucket) {\n bucket = {\n row: {\n deviceClass,\n runtimeId: cell.runtimeId,\n benchModelId: cell.model.benchModelId,\n modelName: cell.model.displayName,\n workloadId: cell.workloadId,\n resolvedBackends: [],\n browsers: [],\n highVariance: false,\n },\n ttft: [],\n decode: [],\n single: [],\n batch: [],\n loadCold: [],\n loadWarm: [],\n quality: [],\n runIds: new Set(),\n };\n buckets.set(key, bucket);\n }\n bucket.runIds.add(run.runId);\n pushUnique(bucket.row.resolvedBackends, cell.resolvedBackend);\n pushUnique(bucket.row.browsers, run.environment.browser.name);\n bucket.row.highVariance ||= summary.highVariance;\n if (summary.ttftMs) bucket.ttft.push(summary.ttftMs.median);\n if (summary.decodeCharsPerSec) bucket.decode.push(summary.decodeCharsPerSec.median);\n if (summary.singleLatencyMs) bucket.single.push(summary.singleLatencyMs.median);\n if (summary.batchTextsPerSec) bucket.batch.push(summary.batchTextsPerSec.median);\n if (summary.loadMs !== undefined) {\n (summary.loadCached ? bucket.loadWarm : bucket.loadCold).push(summary.loadMs);\n }\n if (summary.qualityScore !== undefined) bucket.quality.push(summary.qualityScore);\n }\n }\n\n const rows: LeaderboardRow[] = [];\n for (const bucket of buckets.values()) {\n rows.push({\n ...bucket.row,\n submissions: bucket.runIds.size,\n ttftMs: maybeMedian(bucket.ttft),\n decodeCharsPerSec: maybeMedian(bucket.decode),\n singleLatencyMs: maybeMedian(bucket.single),\n batchTextsPerSec: maybeMedian(bucket.batch),\n loadColdMs: maybeMedian(bucket.loadCold),\n loadWarmMs: maybeMedian(bucket.loadWarm),\n qualityScore: maybeMedian(bucket.quality),\n provisional: bucket.runIds.size < minSubmissions,\n });\n }\n rows.sort(\n (a, b) =>\n a.deviceClass.localeCompare(b.deviceClass) ||\n a.benchModelId.localeCompare(b.benchModelId) ||\n a.runtimeId.localeCompare(b.runtimeId) ||\n a.workloadId.localeCompare(b.workloadId),\n );\n return rows;\n}\n\nfunction pushUnique(list: string[], value: string): void {\n if (value && !list.includes(value)) list.push(value);\n}\n\nfunction maybeMedian(values: number[]): number | undefined {\n return values.length > 0 ? round2(median(values)) : undefined;\n}\n\nfunction round2(v: number): number {\n return Math.round(v * 100) / 100;\n}\n\n/** Escape one CSV field (RFC 4180). */\nfunction csvField(value: unknown): string {\n const s = value === undefined || value === null ? '' : String(value);\n return /[\",\\n]/.test(s) ? `\"${s.replace(/\"/g, '\"\"')}\"` : s;\n}\n\n/** Leaderboard rows as CSV. */\nexport function rowsToCSV(rows: readonly LeaderboardRow[]): string {\n const header = [\n 'deviceClass', 'runtimeId', 'benchModelId', 'modelName', 'workloadId', 'submissions',\n 'ttftMs', 'decodeCharsPerSec', 'singleLatencyMs', 'batchTextsPerSec',\n 'loadColdMs', 'loadWarmMs', 'qualityScore', 'resolvedBackends', 'browsers',\n 'highVariance', 'provisional',\n ];\n const lines = [header.join(',')];\n for (const r of rows) {\n lines.push(\n [\n r.deviceClass, r.runtimeId, r.benchModelId, r.modelName, r.workloadId, r.submissions,\n r.ttftMs, r.decodeCharsPerSec, r.singleLatencyMs, r.batchTextsPerSec,\n r.loadColdMs, r.loadWarmMs, r.qualityScore, r.resolvedBackends.join(';'), r.browsers.join(';'),\n r.highVariance, r.provisional,\n ]\n .map(csvField)\n .join(','),\n );\n }\n return lines.join('\\n') + '\\n';\n}\n\n/**\n * Long-format per-iteration CSV for paper analysis (one row per timed\n * iteration, with full environment identity columns) — feed to R/pandas.\n */\nexport function runsToLongCSV(runs: readonly BenchRunResult[]): string {\n const header = [\n 'runId', 'createdAt', 'suite', 'deviceClass', 'browser', 'browserVersion', 'os', 'gpuVendor',\n 'gpuArchitecture', 'cores', 'deviceMemoryGB', 'crossOriginIsolated', 'fingerprintMflops',\n 'runtimeId', 'runtimeVersion', 'benchModelId', 'providerModelId', 'quantization', 'sizeBytes',\n 'workloadId', 'resolvedBackend', 'iteration', 'ttftMs', 'decodeCharsPerSec', 'generatedChars',\n 'durationMs', 'loadMs', 'loadCached', 'status',\n ];\n const lines = [header.join(',')];\n for (const run of runs) {\n const env = run.environment;\n const base = [\n run.runId, run.createdAt, run.suite, deviceClassOf(run), env.browser.name,\n env.browser.version, env.os.platform, env.gpu.vendor ?? '', env.gpu.architecture ?? '',\n env.hardware.cores ?? '', env.hardware.deviceMemoryGB ?? '', env.flags.crossOriginIsolated,\n run.fingerprint ? round2(run.fingerprint.mflops) : '',\n ];\n for (const cell of run.cells) {\n const loadMs = cell.load ? round2(cell.load.endT - cell.load.startT) : '';\n const loadCached = cell.load ? String(cell.load.cached) : '';\n const cellBase = [\n cell.runtimeId, cell.runtimeVersion ?? '', cell.model.benchModelId,\n cell.model.providerModelId, cell.model.quantization ?? '', cell.model.sizeBytes ?? '',\n cell.workloadId, cell.resolvedBackend,\n ];\n if (cell.iterations.length === 0) {\n lines.push([...base, ...cellBase, '', '', '', '', '', loadMs, loadCached, cell.status].map(csvField).join(','));\n continue;\n }\n cell.iterations.forEach((it, i) => {\n let ttft = '';\n let decodeRate = '';\n let chars = '';\n if ('chunks' in it) {\n const first = it.chunks.find((c) => c.c > 0);\n if (first) {\n ttft = String(round2(first.t - it.startT));\n const last = it.chunks[it.chunks.length - 1];\n const decodeChars = it.chunks.reduce((a, c) => a + c.c, 0) - first.c;\n const ms = last.t - first.t;\n if (ms > 0) decodeRate = String(round2((decodeChars / ms) * 1000));\n chars = String(it.chunks.reduce((a, c) => a + c.c, 0));\n }\n }\n lines.push(\n [...base, ...cellBase, i + 1, ttft, decodeRate, chars,\n round2(it.endT - it.startT), loadMs, loadCached, cell.status]\n .map(csvField)\n .join(','),\n );\n });\n }\n }\n return lines.join('\\n') + '\\n';\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../src/protocol.ts","../src/adapter.ts","../src/timing.ts","../src/trace.ts","../src/memory.ts","../src/env.ts","../src/fingerprint.ts","../src/stats.ts","../src/datasets/tiny-mmlu.ts","../src/datasets/stsb/stsb-subset.ts","../src/quality.ts","../src/validate.ts","../src/runner.ts","../src/canonical.ts","../src/aggregate.ts"],"names":["BENCH_PROTOCOL_VERSION","BENCH_SCHEMA_VERSION","PROMPT_PP128","PROMPT_PP512","GENERATION_BUDGET","MIN_GENERATED_CHARS","LLM_WORKLOADS","embedTexts","topics","texts","i","topic","EMBED_TEXTS","EMBED_WORKLOADS","QUALITY_WORKLOADS","WORKLOADS_BY_ID","w","RUNTIME_EXECUTION_ORDER","orderCells","cells","rank","id","a","b","RUN_POLICIES","USAGE_FIDELITY","hrNow","inferTimerResolutionUs","samples","deltas","prev","guard","t","minDelta","sleep","ms","abortSignal","resolve","reject","abortDomException","onAbort","err","TraceRecorder","type","detail","onVisibility","PressureObserverCtor","observer","records","last","wakeLock","sentinel","dispose","memoryApiAvailable","sampleMemoryBytes","timeoutMs","api","result","legacy","GPU_LIMIT_KEYS","captureEnvironment","options","nav","ua","browser","os","uaData","identifyBrowserAndOS","gpu","probeWebGPU","webgl","probeWebGL","wasm","detectWasmFeatures","engine","detectEngine","attempt","memory","probePerformanceMemory","screenInfo","probeScreen","parseGpuModel","probeApis","probeDevice","probeStorage","probeBattery","probeNetwork","probeLocale","fn","high","list","primary","parseUserAgent","parseUABrowser","parseUAOS","rules","name","re","m","platform","deriveDeviceType","signals","maxTouchPoints","formFactors","mobile","set","f","mobileBit","mq","q","displayMode","adapter","info","limits","adapterLimits","key","v","str","num","SOFTWARE_RENDERER","canvas","contextKind","gl","ext","vendor","renderer","angle","inner","parts","depth","current","ch","model","validate","bytes","compiles","has","W","support","pages","webgpu","webgl2","g","n","present","obj","opfs","storage","persisted","builtInAi","mem","scheme","conn","online","resolved","est","details","getBattery","battery","finite","lcg","seed","s","runFingerprint","minDurationMs","rand","c","flopsPerIter","iterations","start","elapsed","matmul","checksum","j","acc","k","T_95","sorted","values","quantile","pos","lo","hi","median","mean","sum","stddev","geomean","summarize","sd","ci95","spearman","ra","ranks","rb","pearson","idx","x","y","out","avgRank","ma","mb","da","db","xa","xb","den","TINY_MMLU","STSB_SUBSET","LETTERS","MMLU_MAX_TOKENS","MMLU_OUTPUT_CAP","formatMMLUPrompt","item","promptSuffix","choices","stripReasoning","response","closed","open","parseMMLUAnswer","trimmed","emphasisFree","keyed","leadingLower","lower","runMMLUFidelity","items","subset","outputs","correct","parsed","output","answer","ok","cosine","dot","na","nb","runSTSQuality","pairs","sims","humanScores","pair","embeddings","PLAUSIBILITY_RULES_VERSION","STREAM_COHERENCE_MIN_SPAN_RATIO","DECODE_ENVELOPE_CHARS_PER_SEC","EMBED_ENVELOPE_TEXTS_PER_SEC","SOFTWARE_RENDERER_PATTERNS","validateRunShape","value","errors","push","msg","run","harness","env","validateCellShape","index","cell","at","quality","o","it","iter","isLLMIterations","isIncrementalStream","nonEmpty","span","total","summarizeCell","highVarianceCv","approxPromptTokens","incremental","ttfts","decodeRates","chunkRates","genChars","prefillRates","totals","overallRates","totalChars","totalMs","first","ttftMs","decodeChars","decodeMs","iters","durations","d","metrics","summarizeRun","promptTokensByWorkload","lookup","checkPlausibility","flags","flag","code","message","severity","cellId","grid","monotonic","chunkChars","summary","size","envelope","e","quantumMs","offGrid","score","recomputed","agree","gpuIdentity","p","hasGpuLane","validateSubmission","shapeErrors","summaries","byId","client","server","runBenchmarkSuite","policy","hooks","trace","memApi","environment","throwIfAborted","fingerprint","baselineMemory","groups","groupCells","totalCells","cellIndex","group","groupCellsResults","runModelGroup","waitForPressure","generateRunId","map","ctx","isEmbedding","results","baseCell","workload","finishCell","availability","loaded","loadRecord","warmupMs","postLoadMemory","cached","progress","loadStart","firstCellId","loadEnd","decimate","warmupStart","consumeStream","error","safeDispose","atError","describeError","attachedLoad","runLLMCell","runEmbedCell","done","sample","reloaded","end","warmCell","gates","hiddenBefore","countHidden","startT","chunks","text","providerUsage","finishReason","endT","gated","reasons","gate","chunk","deadline","state","max","step","cause","causeMessage","signal","cryptoObj","hex","canonicalJson","stringify","sha256Hex","subtle","hash","computeRunDigest","_omitted","rest","verifyRunDigest","deviceClassOf","HEADLINE_MIN_SUBMISSIONS","aggregateRuns","runs","minSubmissions","buckets","deviceClass","byCellId","bucket","pushUnique","rows","maybeMedian","round2","csvField","rowsToCSV","lines","r","runsToLongCSV","base","loadMs","loadCached","cellBase","ttft","decodeRate","chars","overall","isIncremental"],"mappings":"AAQO,IAAMA,CAAAA,CAAyB,mBAAA,CAGzBC,CAAAA,CAAuB,MCU9BC,EAAAA,CAAe,CACnB,qFAAA,CACA,uFAAA,CACA,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,CAAK,GAAG,CACb,EACF,CAAC,EACH,CACF,CACA,OAAOE,EAAM,IAAA,CAAK;AAAA,CAAI,CAAA,CAAI;AAAA,CAC5B","file":"index.js","sourcesContent":["/**\n * Protocol types for the LocalMode LocalMode Bench — the cross-runtime in-browser\n * AI benchmark. A `BenchRunResult` is the unit of submission: it carries raw\n * per-chunk timing traces (never just client-computed aggregates) so that all\n * published statistics can be recomputed and audited server-side.\n */\n\n/** Protocol identifier embedded in every result. Bump only with a spec change. */\nexport const BENCH_PROTOCOL_VERSION = 'localmode-bench/2';\n\n/** Result JSON schema version (independent of the protocol semantics version). */\nexport const BENCH_SCHEMA_VERSION = 2;\n\n/** Benchmark suite presets. `custom` = user-picked cells. */\nexport type BenchSuiteId = 'quick' | 'standard' | 'thorough' | 'custom';\n\n/**\n * A benchmark runtime lane. Transformers.js is split into two lanes because\n * WebGPU vs WASM is the paper's core comparison axis.\n */\nexport type BenchRuntimeId =\n | 'transformers-webgpu'\n | 'transformers-wasm'\n | 'webllm'\n | 'wllama'\n | 'litert'\n | 'chrome-ai'\n | 'mediapipe';\n\n/** Workload kinds. Quality lanes are separate from timed performance lanes. */\nexport type BenchWorkloadKind =\n | 'llm-generate'\n | 'embed-single'\n | 'embed-batch'\n | 'quality-mmlu'\n | 'quality-sts';\n\n/** A fixed LLM generation workload (public prompt, deterministic settings). */\nexport interface LLMWorkloadSpec {\n id: string;\n kind: 'llm-generate';\n /** Human-readable label, e.g. \"Chat pp128/tg128\". */\n label: string;\n prompt: string;\n systemPrompt?: string;\n /**\n * Approximate prompt token count (reference estimate; exact counts are\n * tokenizer-specific and computed post-hoc from the stored prompt).\n */\n approxPromptTokens: number;\n /** Generation budget. Decode metrics use the actual generated length. */\n maxTokens: number;\n /** Always 0 for performance runs (deterministic where the runtime allows). */\n temperature: number;\n}\n\n/** A fixed embedding workload over deterministic public texts. */\nexport interface EmbedWorkloadSpec {\n id: string;\n kind: 'embed-single' | 'embed-batch';\n label: string;\n /** Fixed input texts. Length 1 for single-latency, N for batch throughput. */\n texts: string[];\n}\n\n/** Quality-fidelity workloads (temp 0, scored, untimed-region rules relaxed). */\nexport interface QualityWorkloadSpec {\n id: string;\n kind: 'quality-mmlu' | 'quality-sts';\n label: string;\n /** Number of items to evaluate (subset of the bundled dataset). */\n items: number;\n}\n\nexport type BenchWorkloadSpec = LLMWorkloadSpec | EmbedWorkloadSpec | QualityWorkloadSpec;\n\n/** Static reference to a model as benchmarked in one runtime lane. */\nexport interface BenchModelRef {\n /** Cross-runtime pairing id, e.g. \"qwen3-0.6b\" — same weights family. */\n benchModelId: string;\n runtimeId: BenchRuntimeId;\n /** The provider-native model id passed to the runtime. */\n providerModelId: string;\n displayName: string;\n /** \"llm\" or \"embedding\". */\n task: 'llm' | 'embedding';\n parameterCount?: string;\n quantization?: string;\n sizeBytes?: number;\n contextLength?: number;\n /** Direct model URL when applicable (wllama GGUF, litert). */\n url?: string;\n requiresWebGPU?: boolean;\n /**\n * Appended to the quality-lane instruction line for every runtime of this\n * pairing (e.g. \" /no_think\" to hold Qwen3 in non-thinking mode). Uniform\n * across runtimes by construction, so fidelity comparisons stay valid.\n */\n qualityPromptSuffix?: string;\n}\n\n/** One recorded stream chunk: wall-clock timestamp + delta length in chars. */\nexport interface BenchChunk {\n /** `performance.now()` at chunk receipt (ms, page-relative). */\n t: number;\n /** Character length of this chunk's text delta. */\n c: number;\n}\n\n/** Provider-reported usage, recorded as auxiliary data (often estimated). */\nexport interface ProviderUsage {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n durationMs: number;\n /** How trustworthy the provider counts are for this runtime. */\n fidelity: 'measured' | 'estimated' | 'chunk-count';\n}\n\n/** One timed LLM generation iteration with its raw trace. */\nexport interface LLMIteration {\n /** `performance.now()` just before the stream is requested. */\n startT: number;\n /** Per-chunk receipt trace. TTFT derives from the first entry with c > 0. */\n chunks: BenchChunk[];\n /** `performance.now()` after the terminal chunk. */\n endT: number;\n /** Full generated text (enables post-hoc exact tokenization + auditing). */\n text: string;\n providerUsage?: ProviderUsage;\n finishReason?: string;\n /** Validity-gate events that fired during this iteration (empty = valid). */\n gates: string[];\n}\n\n/** One timed embedding iteration. */\nexport interface EmbedIteration {\n startT: number;\n endT: number;\n /** Number of texts embedded in this iteration. */\n count: number;\n /** Embedding dimensions reported by the model. */\n dimensions: number;\n gates: string[];\n}\n\n/** Model-load phase record for a cell (null when the cell reused a live model). */\nexport interface LoadRecord {\n /** Provider cache probe before load: true=warm, false=cold, undefined=unknown. */\n cached: boolean | undefined;\n startT: number;\n endT: number;\n /** Progress milestones (coarse, at most ~50 samples). */\n progress?: Array<{ t: number; pct: number }>;\n /** Catalog-declared download size, when known. */\n declaredBytes?: number;\n}\n\n/** Memory sampling at protocol points (Chromium-only APIs; absent elsewhere). */\nexport interface MemorySample {\n /** Bytes reported at suite baseline, after load, after timed runs. */\n baseline?: number;\n postLoad?: number;\n postRun?: number;\n /** Bytes at the moment a cell errored (load or workload failure). */\n atError?: number;\n api: 'uaSpecific' | 'legacyHeap' | 'none';\n}\n\n/** Quality lane outcome attached to a cell. */\nexport interface QualityResult {\n taskId: string;\n /** Primary score: accuracy (MMLU) or Spearman rho (STS). */\n score: number;\n n: number;\n /** Per-item correctness or per-pair cosine, for auditability. */\n details?: number[];\n /**\n * Raw model outputs per item (MMLU lanes; capped at 400 chars each) so the\n * score is recomputable server-side and parse failures are auditable.\n */\n outputs?: string[];\n /** Fraction of items whose answer was parseable (MMLU lanes). */\n parseRate?: number;\n}\n\nexport type BenchCellStatus = 'ok' | 'invalid' | 'error' | 'skipped';\n\n/** One benchmark cell: (runtime x model x workload) with its raw iterations. */\nexport interface BenchCellResult {\n /** `${runtimeId}/${benchModelId}/${workloadId}` */\n cellId: string;\n runtimeId: BenchRuntimeId;\n runtimeVersion?: string;\n model: BenchModelRef;\n workloadId: string;\n workloadKind: BenchWorkloadKind;\n /** Backend actually used (probed, never the requested one). */\n resolvedBackend: string;\n load: LoadRecord | null;\n /** Untimed warmup duration (ms), when a warmup ran. */\n warmupMs?: number;\n iterations: LLMIteration[] | EmbedIteration[];\n memory?: MemorySample;\n quality?: QualityResult;\n status: BenchCellStatus;\n invalidReasons?: string[];\n /** Error that ended the cell; `cause` carries the wrapped provider error's message when present. */\n error?: { name: string; message: string; cause?: string };\n}\n\n/** Trace events global to the suite run (validity accounting). */\nexport interface TraceEvent {\n t: number;\n type:\n | 'suite-start'\n | 'suite-end'\n | 'visibility-hidden'\n | 'visibility-visible'\n | 'wakelock-acquired'\n | 'wakelock-released'\n | 'pressure-change'\n | 'gpu-device-lost'\n | 'cooldown-start'\n | 'cooldown-end'\n | 'abort';\n detail?: string;\n}\n\n/** Browser identification with its provenance. */\nexport interface BrowserInfo {\n name: string;\n version: string;\n source: 'ua-ch' | 'ua-parse';\n brands?: Array<{ brand: string; version: string }>;\n /** Rendering engine, derived from the UA (Blink / Gecko / WebKit). */\n engine?: 'Blink' | 'Gecko' | 'WebKit' | 'unknown';\n /** `navigator.vendor` (e.g. \"Google Inc.\", \"Apple Computer, Inc.\"). */\n vendor?: string;\n /** `navigator.webdriver` — true under browser automation. */\n webdriver?: boolean;\n /** `navigator.pdfViewerEnabled`, a cheap headless/kiosk signal. */\n pdfViewerEnabled?: boolean;\n}\n\n/** OS identification. Version is 'unknown-frozen' on engines with frozen UAs. */\nexport interface OSInfo {\n platform: string;\n version: string;\n architecture?: string;\n bitness?: string;\n /** Device model from UA-CH (Android only; empty elsewhere by spec). */\n model?: string;\n /** Whether the OS is running in a WoW64-style emulation layer (UA-CH `wow64`). */\n wow64?: boolean;\n /** `navigator.platform` (legacy, frozen but still informative: \"MacIntel\", \"Win32\", \"iPhone\"). */\n navigatorPlatform?: string;\n}\n\n/** Form-factor classification, derived from UA-CH form factors, the UA, and touch. */\nexport type DeviceType = 'phone' | 'tablet' | 'desktop' | 'xr' | 'tv' | 'unknown';\n\n/** Device / form-factor signals. */\nexport interface DeviceInfo {\n type: DeviceType;\n /** UA-CH `mobile` bit (Chromium) or a UA-derived guess elsewhere. */\n mobile: boolean;\n /** UA-CH `formFactors` (Chromium 125+): Desktop / Mobile / Tablet / XR / EInk / Watch / Automotive. */\n formFactors?: string[];\n /** `navigator.maxTouchPoints`. */\n maxTouchPoints: number;\n /** `(pointer: coarse)` media query — primary input is a touch surface. */\n pointerCoarse?: boolean;\n /** `(hover: none)` media query — no hover-capable primary input. */\n hoverNone?: boolean;\n /** Standalone / fullscreen display mode (installed PWA or kiosk). */\n displayMode?: string;\n}\n\n/** WebGPU adapter identity + selected limits (all fields may be empty strings). */\nexport interface GPUInfo {\n available: boolean;\n vendor?: string;\n architecture?: string;\n device?: string;\n description?: string;\n /** Adapter-reported subgroup sizes (Chromium 130+ `info.subgroupMinSize/MaxSize`). */\n subgroupMinSize?: number;\n subgroupMaxSize?: number;\n isFallbackAdapter?: boolean;\n features?: string[];\n limits?: Record<string, number>;\n /** `navigator.gpu.getPreferredCanvasFormat()`. */\n preferredCanvasFormat?: string;\n /** WGSL language features the implementation reports (`navigator.gpu.wgslLanguageFeatures`). */\n wgslLanguageFeatures?: string[];\n}\n\n/** WebGL identity + capacity signals (a second, older GPU identity channel). */\nexport interface WebGLInfo {\n /** Best context available: 'webgl2', 'webgl', or null when neither creates. */\n contextKind: 'webgl2' | 'webgl' | null;\n /** UNMASKED_VENDOR_WEBGL when the debug extension exists, else VENDOR. */\n vendor?: string;\n /** UNMASKED_RENDERER_WEBGL when the debug extension exists, else RENDERER. */\n renderer?: string;\n version?: string;\n shadingLanguageVersion?: string;\n maxTextureSize?: number;\n maxRenderbufferSize?: number;\n maxVertexUniformVectors?: number;\n maxFragmentUniformVectors?: number;\n /** Number of extensions exposed (identity signal without shipping the whole list). */\n extensionCount?: number;\n /** Whether the renderer string names a software rasterizer (SwiftShader, llvmpipe, ...). */\n softwareRenderer?: boolean;\n}\n\n/**\n * WebAssembly proposal support, each probed by validating a canonical module\n * (the same byte sequences `wasm-feature-detect` uses). Missing keys mean the\n * probe itself failed, not that the feature is absent.\n */\nexport interface WasmFeatureSupport {\n simd: boolean;\n relaxedSimd: boolean;\n threads: boolean;\n bulkMemory: boolean;\n exceptions: boolean;\n /** Exception handling with `exnref` (the newer, standardized form). */\n exceptionsFinal: boolean;\n extendedConst: boolean;\n gc: boolean;\n memory64: boolean;\n multiMemory: boolean;\n multiValue: boolean;\n mutableGlobals: boolean;\n referenceTypes: boolean;\n saturatedFloatToInt: boolean;\n signExtensions: boolean;\n tailCall: boolean;\n typedFunctionReferences: boolean;\n /** 128-bit wide arithmetic (`i64.add128` family). */\n wideArithmetic: boolean;\n /** JavaScript Promise Integration (`WebAssembly.Suspending`). */\n jspi: boolean;\n /** Type reflection (`WebAssembly.Function`). */\n typeReflection: boolean;\n /** `WebAssembly.compileStreaming` exists. */\n streamingCompilation: boolean;\n /** JS String Builtins (`js-string` import module), probed via the imports/builtins option. */\n jsStringBuiltins: boolean;\n /** Type-level `WebAssembly.Memory` growth limit reachable in this engine (pages of 64 KiB). */\n maxMemoryPages?: number;\n}\n\n/**\n * Availability of the browser APIs the runtimes and the paper care about.\n * Each entry is a plain presence check (the feature exists on this page),\n * not a functional test. Chrome Built-in AI is reported by its\n * `availability()` string where the API exists.\n */\nexport interface APIAvailability {\n webgpu: boolean;\n webgl2: boolean;\n webnn: boolean;\n /** OPFS: `navigator.storage.getDirectory` exists AND resolved. */\n opfs: boolean;\n /** Result of `navigator.storage.persisted()` where supported. */\n persistedStorage?: boolean;\n indexedDB: boolean;\n cacheApi: boolean;\n serviceWorker: boolean;\n webWorkers: boolean;\n offscreenCanvas: boolean;\n webLocks: boolean;\n broadcastChannel: boolean;\n wakeLock: boolean;\n computePressure: boolean;\n performanceMemory: boolean;\n measureUserAgentSpecificMemory: boolean;\n schedulerYield: boolean;\n webCodecs: boolean;\n audioWorklet: boolean;\n mediaDevices: boolean;\n webTransport: boolean;\n /** Chrome Built-in AI (Gemini Nano) surfaces, by `availability()` verdict when reachable. */\n promptApi?: string;\n summarizerApi?: string;\n translatorApi?: string;\n languageDetectorApi?: string;\n}\n\n/** Network Information API (Chromium + Android) snapshot at capture time. */\nexport interface NetworkInfo {\n supported: boolean;\n effectiveType?: string;\n /** Connection type (wifi / cellular / ethernet / ...) where the UA exposes it. */\n type?: string;\n downlinkMbps?: number;\n rttMs?: number;\n saveData?: boolean;\n online?: boolean;\n}\n\n/** Display / viewport snapshot. */\nexport interface DisplayInfo {\n width: number;\n height: number;\n availWidth?: number;\n availHeight?: number;\n dpr: number;\n colorDepth?: number;\n orientation?: string;\n viewportWidth?: number;\n viewportHeight?: number;\n /** `(dynamic-range: high)` media query. */\n hdr?: boolean;\n /** `(color-gamut: p3)` media query. */\n wideGamut?: boolean;\n /** `screen.isExtended` (Window Management API) — more than one display attached. */\n isExtended?: boolean;\n /** Reduced-motion / forced-colors preferences, cheap OS-level signals. */\n prefersReducedMotion?: boolean;\n prefersColorScheme?: 'light' | 'dark' | 'no-preference';\n}\n\n/** Locale / clock signals. */\nexport interface LocaleInfo {\n timeZone?: string;\n /** Minutes offset from UTC at capture time (`Date#getTimezoneOffset`). */\n timeZoneOffsetMinutes?: number;\n locale?: string;\n /** `Intl.DateTimeFormat().resolvedOptions().calendar`. */\n calendar?: string;\n}\n\n/**\n * Full environment capture for a run. Every field beyond the first block is\n * additive and best-effort: a probe that fails records nothing for its key and\n * never affects the others. Clamped or capped fields are labeled as such.\n */\nexport interface EnvironmentCapture {\n capturedAt: string;\n browser: BrowserInfo;\n os: OSInfo;\n hardware: {\n /** navigator.hardwareConcurrency — clamped/randomized on Gecko/WebKit. */\n cores: number | null;\n coresClamped: boolean;\n /** navigator.deviceMemory (GB) — Chromium-only, capped at 8. */\n deviceMemoryGB: number | null;\n deviceMemoryCapped: boolean;\n /** `performance.memory.jsHeapSizeLimit` (Chromium) — the V8 heap ceiling for this tab. */\n jsHeapSizeLimitBytes?: number;\n /** `performance.memory.usedJSHeapSize` at capture (the idle baseline). */\n jsHeapUsedBytes?: number;\n };\n gpu: GPUInfo;\n /** WebGL renderer string, a secondary GPU identity signal. */\n webglRenderer: string | null;\n /** Detailed WebGL identity + capacity (superset of `webglRenderer`). */\n webgl?: WebGLInfo;\n /**\n * GPU model parsed from the WebGL renderer string (ANGLE unwrapped),\n * e.g. \"Apple M4\", \"NVIDIA GeForce RTX 4070\", \"Mali-G78 MP20\". Absent when\n * no WebGL context could be created.\n */\n gpuModel?: string;\n flags: {\n crossOriginIsolated: boolean;\n sharedArrayBuffer: boolean;\n wasmSimd: boolean;\n /** `window.isSecureContext`. */\n secureContext?: boolean;\n /** Full WebAssembly proposal matrix (superset of `wasmSimd`). */\n wasm?: WasmFeatureSupport;\n };\n /** Presence checks for the APIs the runtimes depend on. */\n apis?: APIAvailability;\n device?: DeviceInfo;\n storage: { quotaBytes?: number; usageBytes?: number; usageDetails?: Record<string, number> } | null;\n power: {\n batterySupported: boolean;\n charging?: boolean;\n level?: number;\n /** Seconds until full / empty (Infinity serialized as absent). */\n chargingTimeSec?: number;\n dischargingTimeSec?: number;\n };\n pressure: { supported: boolean; lastState?: string };\n /** Inferred performance.now() quantum in microseconds (grid inference). */\n timerResolutionUs: number | null;\n screen: { width: number; height: number; dpr: number } | null;\n /** Detailed display snapshot (superset of `screen`). */\n display?: DisplayInfo;\n network?: NetworkInfo;\n locale?: LocaleInfo;\n languages?: string[];\n /** Raw `navigator.userAgent` — kept verbatim so future parsers can re-derive fields. */\n userAgent?: string;\n /** Page origin the run executed on (distinguishes production from local/staging). */\n pageOrigin?: string;\n /** `document.visibilityState` at capture; a hidden tab is throttled. */\n visibilityState?: string;\n /** Free-text device self-report — displayed as \"user-reported\", never trusted. */\n userReportedDevice?: string;\n}\n\n/** Deterministic JS matmul microbenchmark result (hardware fingerprint). */\nexport interface FingerprintResult {\n /** Millions of fused multiply-adds per second. */\n mflops: number;\n n: number;\n iterations: number;\n durationMs: number;\n /** Checksum of the final matrix — proves the work actually ran. */\n checksum: number;\n}\n\n/** Statistical summary of one metric across iterations. */\nexport interface MetricSummary {\n n: number;\n median: number;\n mean: number;\n sd: number;\n iqr: number;\n min: number;\n max: number;\n /** 95% confidence interval half-width (Student-t). */\n ci95: number;\n /** Coefficient of variation (sd/mean), 0 when mean is 0. */\n cv: number;\n}\n\n/** Derived per-cell summary (recomputable from the raw trace by anyone). */\nexport interface CellSummary {\n cellId: string;\n status: BenchCellStatus;\n /** LLM lanes. */\n ttftMs?: MetricSummary;\n decodeCharsPerSec?: MetricSummary;\n decodeChunksPerSec?: MetricSummary;\n prefillTokPerSecApprox?: MetricSummary;\n generatedChars?: MetricSummary;\n /** Request wall time (startT → endT), all LLM lanes. */\n totalMs?: MetricSummary;\n /** End-to-end chars/s over the whole request (prefill + decode conflated). */\n overallCharsPerSec?: MetricSummary;\n /**\n * False when the chunk trace is not genuinely incremental (single chunk, or\n * the visible stream spans <20% of the request) — TTFT and decode metrics\n * are then omitted because they would be timing artifacts, not measurements.\n */\n streamIncremental?: boolean;\n /** Embedding lanes. */\n singleLatencyMs?: MetricSummary;\n batchTextsPerSec?: MetricSummary;\n /** Load phase. */\n loadMs?: number;\n loadCached?: boolean;\n qualityScore?: number;\n /** Fraction of MMLU items whose answer parsed; a low value marks a format failure, not a fidelity one. */\n qualityParseRate?: number;\n highVariance: boolean;\n}\n\n/** Identity of the software that produced a run. */\nexport interface HarnessInfo {\n name: string;\n version: string;\n appVersion?: string;\n /**\n * Versions of the runtime packages bundled into the harness at build time\n * (e.g. `{ \"@huggingface/transformers\": \"4.2.0\", \"@wllama/wllama\": \"3.5.1\" }`),\n * keyed by npm package name. Per-cell `runtimeVersion` names the same value\n * for the runtime that produced that cell.\n */\n runtimeVersions?: Record<string, string>;\n /** Git commit of the harness build where the host exposes it. */\n commit?: string;\n}\n\n/** The unit of submission: one full suite run on one device. */\nexport interface BenchRunResult {\n protocol: typeof BENCH_PROTOCOL_VERSION;\n schemaVersion: typeof BENCH_SCHEMA_VERSION;\n runId: string;\n createdAt: string;\n harness: HarnessInfo;\n suite: BenchSuiteId;\n environment: EnvironmentCapture;\n fingerprint: FingerprintResult | null;\n cells: BenchCellResult[];\n events: TraceEvent[];\n /** Client-computed summaries (advisory; server recomputes from the trace). */\n clientSummaries?: CellSummary[];\n /** Server-issued anti-forgery nonce (verified tier only). */\n nonce?: string;\n /** SHA-256 of the canonical JSON of this object without `digest`. */\n digest?: string;\n}\n\n/** A plausibility/integrity finding attached by validation. */\nexport interface PlausibilityFlag {\n code: string;\n cellId?: string;\n message: string;\n severity: 'warn' | 'reject';\n}\n\n/** Outcome of full validation (shape + recompute + plausibility). */\nexport interface ValidationReport {\n ok: boolean;\n shapeErrors: string[];\n flags: PlausibilityFlag[];\n summaries: CellSummary[];\n}\n","/**\n * Protocol constants: fixed public workloads and the run policy. These are\n * part of the versioned benchmark spec — any change to prompts, token budgets,\n * or policy numbers requires a protocol version bump (see BENCH_PROTOCOL_VERSION).\n *\n * Metric naming follows llama-bench conventions (ppN = prefill on an\n * N-token prompt, tgN = token generation over N tokens) and MLPerf Client\n * definitions (TTFT; decode rate excludes the first token).\n */\n\nimport type {\n BenchRuntimeId,\n EmbedWorkloadSpec,\n LLMWorkloadSpec,\n QualityWorkloadSpec,\n} from './types.js';\n\n/**\n * ~128-token prompt (measured 512 chars). Original text, public domain.\n * Exact per-tokenizer counts are computed post-hoc from this fixed string.\n */\nconst PROMPT_PP128 = [\n 'You are helping a small public library plan its move to a new building across town.',\n 'The collection holds forty thousand books, two thousand audio recordings, and a local',\n 'history archive that must stay in labeled order. Volunteers are available on weekends',\n 'only, and the budget covers one rental truck. Describe a practical week-by-week moving',\n 'plan that keeps the library partially open, protects the archive, and finishes within',\n 'eight weeks. Be specific about labeling, sequencing, and volunteer coordination.',\n].join(' ');\n\n/** ~512-token prompt (measured 2178 chars). Original text, public domain. */\nconst PROMPT_PP512 = [\n 'Read the following notes from a town planning meeting and then answer the question at the end.',\n 'The town of Milbrook has grown from eight thousand residents to eleven thousand in six years.',\n 'The old water treatment plant, built fifty years ago, operates at ninety two percent of its',\n 'rated capacity during summer months. An engineering survey found that the intake pipes show',\n 'corrosion consistent with their age but no immediate risk of failure. Replacing the plant',\n 'entirely would cost an estimated thirty one million dollars and take four years, during which',\n 'a temporary treatment module would be rented at two hundred thousand dollars per month.',\n 'Upgrading the existing plant in three phases would cost nineteen million dollars, take six',\n 'years, and raise capacity by forty percent, but phase two requires shutting one of the three',\n 'treatment trains for nine months. The town engineer favors the upgrade because the town can',\n 'fund it from reserves plus a small bond, avoiding a rate increase larger than four percent.',\n 'The finance director notes that construction costs have risen eleven percent in two years and',\n 'argues that delaying the full replacement will only make it more expensive, and that a larger',\n 'bond issued now at current rates would cost less over thirty years than a later one. Several',\n 'residents raised concerns about summer watering restrictions during phase two, and a local',\n 'manufacturer that employs three hundred people said an unreliable water supply would force it',\n 'to install its own storage tanks at significant cost. The mayor asked both officials to prepare',\n 'a comparison covering total cost of ownership over thirty years, resilience during construction,',\n 'capacity margins in the final state, and the effect on household water rates under three growth',\n 'scenarios: flat, moderate, and rapid. The engineer also mentioned that federal infrastructure',\n 'grants covering up to twenty percent of qualifying water projects open for applications next',\n 'spring, though awards are competitive and would delay the start by at least eight months either way.',\n 'Question: Write a balanced recommendation memo to the town council. Weigh both options against',\n 'the four criteria the mayor listed, account for the grant opportunity, and end with a clear',\n 'recommendation and two conditions under which the council should switch to the other option.',\n].join(' ');\n\n/** Fixed generation budget for timed lanes (tg128, MLPerf-Client-sized). */\nexport const GENERATION_BUDGET = 128;\n\n/**\n * Minimum generated characters for a timed iteration to count as a decode\n * measurement (part of the versioned protocol). An instruct model that emits\n * EOS after a handful of characters - typically an untemplated prompt or a\n * tokenizer mismatch - produces no decode phase to time; such iterations are\n * gated `degenerate-output` and the cell is marked invalid rather than scored.\n */\nexport const MIN_GENERATED_CHARS = 16;\n\n/** LLM performance workloads. */\nexport const LLM_WORKLOADS: readonly LLMWorkloadSpec[] = [\n {\n id: 'chat-pp128-tg128',\n kind: 'llm-generate',\n label: 'Chat pp128/tg128',\n prompt: PROMPT_PP128,\n approxPromptTokens: 128,\n maxTokens: GENERATION_BUDGET,\n temperature: 0,\n },\n {\n id: 'chat-pp512-tg128',\n kind: 'llm-generate',\n label: 'Long-context pp512/tg128',\n prompt: PROMPT_PP512,\n approxPromptTokens: 512,\n maxTokens: GENERATION_BUDGET,\n temperature: 0,\n },\n] as const;\n\n/** Deterministic embedding corpus: 32 fixed ~200-char sentences. */\nfunction embedTexts(): string[] {\n const topics = [\n 'the maintenance schedule for a fleet of electric delivery vans in a coastal city',\n 'a beginner guide to fermenting vegetables safely at home in small batches',\n 'the migration patterns of shorebirds along the Atlantic flyway in autumn',\n 'how a public library catalogs and preserves regional oral history recordings',\n 'the tradeoffs between timber framing and steel framing for small workshops',\n 'a training plan that prepares a new runner for a half marathon in twenty weeks',\n 'the way tide pools support diverse life despite extreme daily changes',\n 'budgeting practices for a volunteer-run community theater production',\n ];\n const texts: string[] = [];\n for (let i = 0; i < 32; i++) {\n const topic = topics[i % topics.length];\n texts.push(\n `Document ${i + 1}: This passage explains ${topic}. It covers the key steps, ` +\n `common mistakes, expected costs, and a short checklist that a careful reader ` +\n `can apply immediately, with concrete numbers where they matter.`,\n );\n }\n return texts;\n}\n\nconst EMBED_TEXTS = embedTexts();\n\n/** Embedding performance workloads. */\nexport const EMBED_WORKLOADS: readonly EmbedWorkloadSpec[] = [\n {\n id: 'embed-single',\n kind: 'embed-single',\n label: 'Embedding single-query latency',\n texts: [EMBED_TEXTS[0]],\n },\n {\n id: 'embed-batch32',\n kind: 'embed-batch',\n label: 'Embedding batch-32 throughput',\n texts: EMBED_TEXTS,\n },\n] as const;\n\n/** Quality-fidelity workloads (separate lane, temperature 0). */\nexport const QUALITY_WORKLOADS: readonly QualityWorkloadSpec[] = [\n { id: 'quality-mmlu-25', kind: 'quality-mmlu', label: 'tinyMMLU fidelity (25 items)', items: 25 },\n { id: 'quality-mmlu-100', kind: 'quality-mmlu', label: 'tinyMMLU fidelity (100 items)', items: 100 },\n { id: 'quality-sts-100', kind: 'quality-sts', label: 'STS-B Spearman (100 pairs)', items: 100 },\n] as const;\n\n/** All workloads indexed by id. */\nexport const WORKLOADS_BY_ID: ReadonlyMap<\n string,\n LLMWorkloadSpec | EmbedWorkloadSpec | QualityWorkloadSpec\n> = new Map(\n [...LLM_WORKLOADS, ...EMBED_WORKLOADS, ...QUALITY_WORKLOADS].map((w) => [w.id, w]),\n);\n\n/**\n * Fixed runtime execution order (part of the versioned protocol). This makes\n * the order deterministic so runtime interleaving is not a confounder across\n * runs; it is a reproducibility measure, not a correctness fix. (The\n * Transformers.js ORT-web lanes fail during session creation regardless of\n * where they run in the order - a separate open runtime/adapter issue.) The\n * order runs the WASM-arena runtimes first and the multi-GB-heap runtimes last.\n * Within a runtime, catalog order is preserved.\n */\nexport const RUNTIME_EXECUTION_ORDER: readonly BenchRuntimeId[] = [\n 'transformers-webgpu',\n 'transformers-wasm',\n 'chrome-ai',\n 'webllm',\n 'mediapipe',\n 'litert',\n 'wllama',\n] as const;\n\n/**\n * Sort planned cells into the protocol execution order (stable within a\n * runtime). The runner applies this itself; exported for hosts and tests.\n */\nexport function orderCells<T extends { model: { runtimeId: BenchRuntimeId } }>(\n cells: readonly T[],\n): T[] {\n const rank = new Map(RUNTIME_EXECUTION_ORDER.map((id, i) => [id, i]));\n return [...cells].sort(\n (a, b) =>\n (rank.get(a.model.runtimeId) ?? RUNTIME_EXECUTION_ORDER.length) -\n (rank.get(b.model.runtimeId) ?? RUNTIME_EXECUTION_ORDER.length),\n );\n}\n\n/** Run policy for a suite (part of the versioned protocol). */\nexport interface RunPolicy {\n /** Untimed warmup generations per cell (absorbs shader compile/JIT). */\n warmupRuns: number;\n /** Timed iterations per cell. */\n timedRuns: number;\n /** Idle cool-down between cells (thermal recovery), ms. */\n cooldownMs: number;\n /** Gate the next cell on Compute Pressure <= 'fair' when available. */\n pressureGate: boolean;\n /** Max wait for the pressure gate before proceeding anyway, ms. */\n pressureGateTimeoutMs: number;\n /** After a cold load, dispose + reload to also measure the warm load. */\n measureWarmReload: boolean;\n /** CV above this fraction marks a summary metric as high-variance. */\n highVarianceCv: number;\n}\n\n/** Policies per suite preset. */\nexport const RUN_POLICIES: Record<'quick' | 'standard' | 'thorough', RunPolicy> = {\n quick: {\n warmupRuns: 1,\n timedRuns: 3,\n cooldownMs: 5_000,\n pressureGate: true,\n pressureGateTimeoutMs: 15_000,\n measureWarmReload: false,\n highVarianceCv: 0.05,\n },\n standard: {\n warmupRuns: 1,\n timedRuns: 3,\n cooldownMs: 8_000,\n pressureGate: true,\n pressureGateTimeoutMs: 30_000,\n measureWarmReload: true,\n highVarianceCv: 0.05,\n },\n thorough: {\n warmupRuns: 1,\n timedRuns: 5,\n cooldownMs: 10_000,\n pressureGate: true,\n pressureGateTimeoutMs: 30_000,\n measureWarmReload: true,\n highVarianceCv: 0.05,\n },\n};\n","/**\n * Runtime adapter contract. Adapters wire a browser ML runtime (Transformers.js,\n * WebLLM, wllama, LiteRT, Chrome Built-in AI, MediaPipe) to the runner. They are\n * injected by the harness host (e.g. the localmode.ai bench page) so this\n * package stays free of provider dependencies — the same pattern the LocalMode\n * blocks use for provider wiring.\n *\n * The runner consumes the `@localmode/core` model interfaces structurally\n * (type-only peer dependency): any object with a compatible `doStream`/`doEmbed`\n * works, including models from other libraries.\n */\n\nimport type { BenchModelRef, BenchRuntimeId, ProviderUsage } from './types.js';\n\n/** Structural subset of `@localmode/core`'s StreamChunk. */\nexport interface BenchStreamChunk {\n text: string;\n done: boolean;\n finishReason?: string;\n usage?: {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n durationMs: number;\n };\n}\n\n/** Structural subset of `@localmode/core`'s LanguageModel. */\nexport interface BenchLanguageModel {\n readonly modelId: string;\n readonly provider: string;\n doStream?(options: {\n prompt: string;\n systemPrompt?: string;\n maxTokens?: number;\n temperature?: number;\n abortSignal?: AbortSignal;\n }): AsyncIterable<BenchStreamChunk>;\n doGenerate(options: {\n prompt: string;\n systemPrompt?: string;\n maxTokens?: number;\n temperature?: number;\n abortSignal?: AbortSignal;\n }): Promise<{ text: string; finishReason: string; usage: ProviderUsage | Omit<ProviderUsage, 'fidelity'> }>;\n}\n\n/** Structural subset of `@localmode/core`'s EmbeddingModel. */\nexport interface BenchEmbeddingModel {\n readonly modelId: string;\n readonly provider: string;\n readonly dimensions: number;\n doEmbed(options: { values: string[]; abortSignal?: AbortSignal }): Promise<{\n embeddings: Float32Array[];\n }>;\n}\n\n/** Availability probe result for a runtime lane on this device. */\nexport interface AdapterAvailability {\n ok: boolean;\n /** Human-readable reason when not available ('no WebGPU adapter', ...). */\n reason?: string;\n}\n\n/** Load-progress callback payload (normalized percent when known). */\nexport interface AdapterLoadProgress {\n pct?: number;\n}\n\n/** A loaded LLM handle: the model plus its resolved execution backend. */\nexport interface LoadedLLM {\n model: BenchLanguageModel;\n /** Backend actually in use — 'webgpu' | 'wasm' | 'gpu' | 'cpu' | 'chrome-builtin'. */\n resolvedBackend: string;\n dispose(): Promise<void>;\n}\n\n/** A loaded embedding-model handle. */\nexport interface LoadedEmbedder {\n model: BenchEmbeddingModel;\n resolvedBackend: string;\n dispose(): Promise<void>;\n}\n\n/** Adapter for an LLM runtime lane. */\nexport interface LLMRuntimeAdapter {\n readonly runtimeId: BenchRuntimeId;\n readonly displayName: string;\n /** Underlying runtime library version, when known (recorded per cell). */\n readonly runtimeVersion?: string;\n /** Is this lane usable on the current device/browser? */\n isAvailable(): Promise<AdapterAvailability>;\n /** Provider cache probe — true=warm, false=cold, undefined=unknown. */\n isModelCached(model: BenchModelRef): Promise<boolean | undefined>;\n /** Load (download + compile) the model. Must NOT run any inference. */\n load(\n model: BenchModelRef,\n options: { onProgress?: (p: AdapterLoadProgress) => void; abortSignal?: AbortSignal },\n ): Promise<LoadedLLM>;\n}\n\n/** Adapter for an embedding runtime lane. */\nexport interface EmbeddingRuntimeAdapter {\n readonly runtimeId: BenchRuntimeId;\n readonly displayName: string;\n readonly runtimeVersion?: string;\n isAvailable(): Promise<AdapterAvailability>;\n isModelCached(model: BenchModelRef): Promise<boolean | undefined>;\n load(\n model: BenchModelRef,\n options: { onProgress?: (p: AdapterLoadProgress) => void; abortSignal?: AbortSignal },\n ): Promise<LoadedEmbedder>;\n}\n\n/** Usage fidelity per runtime — how trustworthy provider token counts are. */\nexport const USAGE_FIDELITY: Record<BenchRuntimeId, ProviderUsage['fidelity']> = {\n 'transformers-webgpu': 'estimated',\n 'transformers-wasm': 'estimated',\n webllm: 'chunk-count',\n wllama: 'estimated',\n litert: 'estimated',\n 'chrome-ai': 'estimated',\n mediapipe: 'estimated',\n};\n","/**\n * Wall-clock timing helpers. All benchmark timestamps use `performance.now()`\n * (5 µs resolution on cross-origin-isolated Chromium, coarser elsewhere);\n * decode rates are derived from endpoint timestamps, never from averaged\n * per-token deltas, because per-token gaps sit at or below timer quantization.\n */\n\n/** Monotonic high-resolution timestamp in ms (performance.now, Date fallback). */\nexport function hrNow(): number {\n return typeof performance !== 'undefined' ? performance.now() : Date.now();\n}\n\n/**\n * Infer the effective `performance.now()` quantum by sampling timer deltas.\n * Genuine traces sit on this grid; the value is recorded in the environment\n * capture and used by the timer-grid integrity check.\n *\n * @param samples - Number of distinct increments to observe (default 64).\n * @returns Inferred quantum in microseconds, or null outside a browser.\n * @example\n * const q = inferTimerResolutionUs(); // 5 on isolated Chromium\n */\nexport function inferTimerResolutionUs(samples = 64): number | null {\n if (typeof performance === 'undefined') return null;\n const deltas: number[] = [];\n let prev = performance.now();\n let guard = 0;\n while (deltas.length < samples && guard < 2_000_000) {\n const t = performance.now();\n if (t > prev) {\n deltas.push(t - prev);\n prev = t;\n }\n guard++;\n }\n if (deltas.length === 0) return null;\n const minDelta = Math.min(...deltas);\n return Math.round(minDelta * 1000 * 100) / 100;\n}\n\n/** Await a real delay (setTimeout) — used for cool-downs between cells. */\nexport function sleep(ms: number, abortSignal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (abortSignal?.aborted) {\n reject(abortDomException());\n return;\n }\n const id = setTimeout(() => {\n abortSignal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n function onAbort() {\n clearTimeout(id);\n reject(abortDomException());\n }\n abortSignal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\n/** A DOMException('AbortError') that also works in non-DOM environments. */\nexport function abortDomException(): Error {\n if (typeof DOMException !== 'undefined') return new DOMException('Aborted', 'AbortError');\n const err = new Error('Aborted');\n err.name = 'AbortError';\n return err;\n}\n","/**\n * Suite-level trace recorder: validity-relevant events (tab visibility, wake\n * lock, compute pressure, GPU device loss, aborts) with wall-clock timestamps.\n * Iterations that overlap a hidden period are invalidated, never retried\n * silently — the trace is part of the submitted, auditable record.\n */\n\nimport type { TraceEvent } from './types.js';\nimport { hrNow } from './timing.js';\n\ntype PressureRecord = { state: string };\ninterface PressureObserverLike {\n observe(source: string, options?: { sampleInterval?: number }): Promise<void> | void;\n disconnect(): void;\n}\n\n/** Records trace events and tracks the current validity-gate state. */\nexport class TraceRecorder {\n private readonly events: TraceEvent[] = [];\n private disposers: Array<() => void> = [];\n private hidden = false;\n private lastPressureState: string | undefined;\n private wakeLockSentinel: { release(): Promise<void>; addEventListener?: unknown } | null = null;\n\n /** Append an event at the current timestamp. */\n record(type: TraceEvent['type'], detail?: string): void {\n this.events.push({ t: hrNow(), type, ...(detail !== undefined ? { detail } : {}) });\n }\n\n /** True while the page is hidden (timed regions overlapping this are invalid). */\n get isHidden(): boolean {\n return this.hidden;\n }\n\n /** Last observed compute-pressure state ('nominal'|'fair'|'serious'|'critical'). */\n get pressureState(): string | undefined {\n return this.lastPressureState;\n }\n\n /** All recorded events (live reference; snapshot with `[...events]`). */\n get all(): readonly TraceEvent[] {\n return this.events;\n }\n\n /**\n * Attach browser listeners (visibility, compute pressure) and request a\n * screen wake lock. Safe to call outside a browser (records nothing).\n */\n async attach(): Promise<void> {\n if (typeof document !== 'undefined') {\n const onVisibility = () => {\n this.hidden = document.visibilityState === 'hidden';\n this.record(this.hidden ? 'visibility-hidden' : 'visibility-visible');\n };\n document.addEventListener('visibilitychange', onVisibility);\n this.disposers.push(() => document.removeEventListener('visibilitychange', onVisibility));\n this.hidden = document.visibilityState === 'hidden';\n }\n\n const PressureObserverCtor = (\n globalThis as { PressureObserver?: new (cb: (records: PressureRecord[]) => void) => PressureObserverLike }\n ).PressureObserver;\n if (PressureObserverCtor) {\n try {\n const observer = new PressureObserverCtor((records) => {\n const last = records[records.length - 1];\n if (last) {\n this.lastPressureState = last.state;\n this.record('pressure-change', last.state);\n }\n });\n await observer.observe('cpu', { sampleInterval: 1_000 });\n this.disposers.push(() => observer.disconnect());\n } catch {\n // Pressure observation is best-effort context, never a failure.\n }\n }\n\n const wakeLock = typeof navigator !== 'undefined'\n ? (navigator as { wakeLock?: { request(type: 'screen'): Promise<{ release(): Promise<void>; addEventListener(t: string, cb: () => void): void }> } }).wakeLock\n : undefined;\n if (wakeLock) {\n try {\n const sentinel = await wakeLock.request('screen');\n this.wakeLockSentinel = sentinel;\n this.record('wakelock-acquired');\n sentinel.addEventListener('release', () => {\n this.record('wakelock-released');\n this.wakeLockSentinel = null;\n });\n } catch {\n // Wake lock denial (battery saver, etc.) is recorded implicitly by absence.\n }\n }\n }\n\n /** Release listeners and the wake lock. */\n async dispose(): Promise<void> {\n for (const dispose of this.disposers) dispose();\n this.disposers = [];\n if (this.wakeLockSentinel) {\n try {\n await this.wakeLockSentinel.release();\n } catch {\n // Already released.\n }\n this.wakeLockSentinel = null;\n }\n }\n}\n","/**\n * Memory sampling at protocol points (baseline / post-load / post-run).\n * Uses `performance.measureUserAgentSpecificMemory()` (Chromium, requires\n * cross-origin isolation, resolves at the next GC — up to ~20 s), with the\n * legacy Chromium JS-heap as fallback. Never call inside a timed region.\n */\n\n/** Which memory API is usable in this context. */\nexport function memoryApiAvailable(): 'uaSpecific' | 'legacyHeap' | 'none' {\n if (\n typeof performance !== 'undefined' &&\n 'measureUserAgentSpecificMemory' in performance &&\n typeof crossOriginIsolated !== 'undefined' &&\n crossOriginIsolated\n ) {\n return 'uaSpecific';\n }\n if (\n typeof performance !== 'undefined' &&\n 'memory' in performance &&\n typeof (performance as { memory?: { usedJSHeapSize?: number } }).memory?.usedJSHeapSize ===\n 'number'\n ) {\n return 'legacyHeap';\n }\n return 'none';\n}\n\n/**\n * Sample total page memory in bytes, or null when unavailable / timed out.\n * The UA-specific measurement is raced against `timeoutMs` because it only\n * resolves at the next garbage collection.\n *\n * @param timeoutMs - Max wait for the GC-gated measurement (default 25000).\n * @example\n * const bytes = await sampleMemoryBytes(); // 734003200 | null\n */\nexport async function sampleMemoryBytes(timeoutMs = 25_000): Promise<number | null> {\n const api = memoryApiAvailable();\n if (api === 'uaSpecific') {\n try {\n const result = await Promise.race([\n (\n performance as unknown as {\n measureUserAgentSpecificMemory: () => Promise<{ bytes: number }>;\n }\n ).measureUserAgentSpecificMemory(),\n new Promise<null>((resolve) => setTimeout(() => resolve(null), timeoutMs)),\n ]);\n if (result && typeof result.bytes === 'number') return result.bytes;\n } catch {\n // fall through to legacy\n }\n }\n if (api !== 'none') {\n const legacy = (performance as { memory?: { usedJSHeapSize?: number } }).memory;\n if (typeof legacy?.usedJSHeapSize === 'number') return legacy.usedJSHeapSize;\n }\n return null;\n}\n","/**\n * Environment capture. Records identity + capability signals with honest\n * provenance: UA Client Hints on Chromium; UA parsing elsewhere with the OS\n * version marked 'unknown-frozen' (UA strings are frozen by design on Gecko\n * and WebKit). Clamped fields (cores, deviceMemory) are labeled clamped.\n *\n * Everything a browser will disclose is recorded, whether or not the current\n * analysis uses it: WebGPU + WebGL identity, the WebAssembly proposal matrix,\n * API availability, form factor, display, network, locale, power. Every probe\n * is individually guarded; a failing probe records nothing for its key.\n */\n\nimport type {\n APIAvailability,\n BrowserInfo,\n DeviceInfo,\n DeviceType,\n DisplayInfo,\n EnvironmentCapture,\n GPUInfo,\n LocaleInfo,\n NetworkInfo,\n OSInfo,\n WasmFeatureSupport,\n WebGLInfo,\n} from './types.js';\nimport { inferTimerResolutionUs } from './timing.js';\n\n/** Minimal structural types for APIs TypeScript's DOM lib may not carry. */\ninterface UADataBrand {\n brand: string;\n version: string;\n}\ninterface NavigatorUAData {\n brands: UADataBrand[];\n mobile?: boolean;\n platform?: string;\n getHighEntropyValues(hints: string[]): Promise<Record<string, unknown>>;\n}\n\n/** WebGPU limits worth recording (identity + capacity signals, all numbers). */\nconst GPU_LIMIT_KEYS = [\n 'maxBufferSize',\n 'maxStorageBufferBindingSize',\n 'maxUniformBufferBindingSize',\n 'maxComputeWorkgroupStorageSize',\n 'maxComputeInvocationsPerWorkgroup',\n 'maxComputeWorkgroupSizeX',\n 'maxComputeWorkgroupSizeY',\n 'maxComputeWorkgroupSizeZ',\n 'maxComputeWorkgroupsPerDimension',\n 'maxBindGroups',\n 'maxStorageBuffersPerShaderStage',\n 'maxTextureDimension2D',\n] as const;\n\n/**\n * Capture the full benchmark environment. Never throws — every probe is\n * individually guarded and absent signals are recorded as absent.\n *\n * @param options.userReportedDevice - Optional free-text device self-report\n * (displayed as \"user-reported\", never treated as ground truth).\n * @example\n * const env = await captureEnvironment();\n */\nexport async function captureEnvironment(options?: {\n userReportedDevice?: string;\n}): Promise<EnvironmentCapture> {\n const nav = typeof navigator !== 'undefined' ? navigator : undefined;\n const ua = nav?.userAgent ?? '';\n\n const { browser, os, uaData } = await identifyBrowserAndOS(nav);\n const gpu = await probeWebGPU(nav);\n const webgl = probeWebGL();\n const wasm = await detectWasmFeatures();\n // UA Client Hints exist only on Chromium, so their presence settles the engine\n // even where the UA string is spoofed; the UA decides for everything else.\n const engine = browser.source === 'ua-ch' ? 'Blink' : detectEngine(ua);\n\n attempt(() => {\n browser.engine = engine;\n if (nav?.vendor) browser.vendor = nav.vendor;\n if (nav && typeof nav.webdriver === 'boolean') browser.webdriver = nav.webdriver;\n if (nav && 'pdfViewerEnabled' in nav) {\n browser.pdfViewerEnabled = Boolean((nav as { pdfViewerEnabled?: boolean }).pdfViewerEnabled);\n }\n if (nav?.platform) os.navigatorPlatform = nav.platform;\n });\n\n const memory = probePerformanceMemory();\n const screenInfo = probeScreen();\n\n return {\n capturedAt: new Date().toISOString(),\n browser,\n os,\n hardware: {\n cores: nav?.hardwareConcurrency ?? null,\n // Chromium reports the real logical core count; Gecko and WebKit clamp or\n // randomize it, so the label follows the engine, not the brand name.\n coresClamped: engine !== 'Blink',\n deviceMemoryGB:\n nav && 'deviceMemory' in nav ? ((nav as { deviceMemory?: number }).deviceMemory ?? null) : null,\n deviceMemoryCapped: true,\n jsHeapSizeLimitBytes: memory?.limit,\n jsHeapUsedBytes: memory?.used,\n },\n gpu,\n webglRenderer: webgl?.renderer ?? null,\n webgl: webgl ?? undefined,\n // WebGPU's adapter description is authoritative where a browser fills it in\n // (Chromium leaves it empty); the WebGL renderer string is the fallback.\n gpuModel: gpu.description ?? parseGpuModel(webgl?.renderer ?? null),\n flags: {\n crossOriginIsolated: typeof crossOriginIsolated !== 'undefined' ? crossOriginIsolated : false,\n sharedArrayBuffer: typeof SharedArrayBuffer !== 'undefined',\n wasmSimd: wasm.simd,\n secureContext: typeof isSecureContext !== 'undefined' ? isSecureContext : undefined,\n wasm,\n },\n apis: await probeApis(nav, gpu.available, webgl?.contextKind === 'webgl2'),\n device: probeDevice(nav, ua, uaData),\n storage: await probeStorage(nav),\n power: await probeBattery(nav),\n pressure: {\n supported: typeof globalThis !== 'undefined' && 'PressureObserver' in globalThis,\n },\n timerResolutionUs: inferTimerResolutionUs(),\n screen: screenInfo ? { width: screenInfo.width, height: screenInfo.height, dpr: screenInfo.dpr } : null,\n display: screenInfo ?? undefined,\n network: probeNetwork(nav),\n locale: probeLocale(),\n languages: nav?.languages ? [...nav.languages].slice(0, 3) : undefined,\n userAgent: ua || undefined,\n pageOrigin: attempt(() => (typeof location !== 'undefined' ? location.origin : undefined)),\n visibilityState: attempt(() =>\n typeof document !== 'undefined' ? document.visibilityState : undefined,\n ),\n userReportedDevice: options?.userReportedDevice,\n };\n}\n\n/** Run a synchronous probe; any throw yields undefined. */\nfunction attempt<T>(fn: () => T): T | undefined {\n try {\n return fn();\n } catch {\n return undefined;\n }\n}\n\n/** Identify the browser + OS with provenance. */\nasync function identifyBrowserAndOS(\n nav: Navigator | undefined,\n): Promise<{ browser: BrowserInfo; os: OSInfo; uaData?: NavigatorUAData }> {\n const uaData = nav && 'userAgentData' in nav\n ? ((nav as { userAgentData?: NavigatorUAData }).userAgentData)\n : undefined;\n\n if (uaData) {\n try {\n const high = await uaData.getHighEntropyValues([\n 'platform',\n 'platformVersion',\n 'architecture',\n 'bitness',\n 'model',\n 'fullVersionList',\n 'wow64',\n 'formFactors',\n ]);\n const list =\n (high.fullVersionList as UADataBrand[] | undefined) ?? uaData.brands ?? [];\n const primary =\n list.find((b) => !/not.?a.?brand/i.test(b.brand) && b.brand !== 'Chromium') ??\n list.find((b) => !/not.?a.?brand/i.test(b.brand));\n return {\n browser: {\n name: primary?.brand ?? 'Chromium',\n version: primary?.version ?? 'unknown',\n source: 'ua-ch',\n brands: list.map((b) => ({ brand: b.brand, version: b.version })),\n },\n os: {\n platform: String(high.platform ?? 'unknown'),\n version: String(high.platformVersion ?? 'unknown'),\n architecture: high.architecture ? String(high.architecture) : undefined,\n bitness: high.bitness ? String(high.bitness) : undefined,\n model: high.model ? String(high.model) : undefined,\n wow64: typeof high.wow64 === 'boolean' ? high.wow64 : undefined,\n },\n uaData: Object.assign(uaData, {\n formFactorsHint: Array.isArray(high.formFactors) ? (high.formFactors as string[]) : undefined,\n }),\n };\n } catch {\n // fall through to UA parsing\n }\n }\n\n const ua = nav?.userAgent ?? '';\n return { ...parseUserAgent(ua), uaData };\n}\n\n/**\n * UA-string fallback for browsers without UA Client Hints (every WebKit\n * browser). Conservative: browser name + version token, platform, and the OS\n * version only where the UA genuinely carries one.\n *\n * @example\n * parseUserAgent('... CriOS/145.0.7632.72 Mobile/15E148 Safari/604.1').browser.name; // 'Chrome iOS'\n */\nexport function parseUserAgent(ua: string): { browser: BrowserInfo; os: OSInfo } {\n return { browser: parseUABrowser(ua), os: parseUAOS(ua) };\n}\n\n/** Browser + version from the UA. iOS shells (CriOS/FxiOS/EdgiOS) are WebKit and named as such. */\nfunction parseUABrowser(ua: string): BrowserInfo {\n const rules: Array<[string, RegExp]> = [\n ['Firefox iOS', /FxiOS\\/(\\d+[\\d.]*)/],\n ['Firefox', /Firefox\\/(\\d+[\\d.]*)/],\n ['Edge', /Edg(?:e|A|iOS)?\\/(\\d+[\\d.]*)/],\n ['Chrome iOS', /CriOS\\/(\\d+[\\d.]*)/],\n ['Safari', /Version\\/(\\d+[\\d.]*).*Safari/],\n ['Chrome', /Chrome\\/(\\d+[\\d.]*)/],\n ];\n for (const [name, re] of rules) {\n const m = ua.match(re);\n if (m) return { name, version: m[1], source: 'ua-parse' };\n }\n return { name: 'unknown', version: 'unknown', source: 'ua-parse' };\n}\n\n/**\n * OS from the UA. Chromium's reduced UA freezes desktop and Android versions,\n * so those stay 'unknown-frozen'; iOS UAs carry the real OS version.\n */\nfunction parseUAOS(ua: string): OSInfo {\n let platform = 'unknown';\n if (/Windows/.test(ua)) platform = 'Windows';\n else if (/iPhone|iPad|iPod/.test(ua)) platform = 'iOS';\n else if (/Mac OS X/.test(ua)) platform = 'macOS';\n else if (/Android/.test(ua)) platform = 'Android';\n else if (/CrOS/.test(ua)) platform = 'Chrome OS';\n else if (/Linux/.test(ua)) platform = 'Linux';\n if (platform === 'iOS') {\n const m = ua.match(/OS (\\d+(?:[_.]\\d+)*) like Mac OS X/);\n if (m) return { platform, version: m[1].replace(/_/g, '.') };\n }\n return { platform, version: 'unknown-frozen' };\n}\n\n/**\n * Rendering engine from the UA. Every iOS browser is WebKit regardless of its\n * brand (App Store policy), so the iOS check comes first.\n *\n * @example\n * detectEngine('... CriOS/145.0 ...'); // 'WebKit'\n */\nexport function detectEngine(ua: string): BrowserInfo['engine'] {\n if (!ua) return 'unknown';\n if (/iPhone|iPad|iPod/.test(ua)) return 'WebKit';\n if (/Gecko\\/\\d|Firefox\\//.test(ua) && !/like Gecko/.test(ua)) return 'Gecko';\n if (/Chrome\\/|Chromium\\/|Edg\\//.test(ua)) return 'Blink';\n if (/AppleWebKit\\//.test(ua)) return 'WebKit';\n return 'unknown';\n}\n\n/** Inputs to the form-factor derivation, each optional. */\nexport interface DeviceTypeSignals {\n ua: string;\n maxTouchPoints: number;\n /** UA-CH `formFactors` high-entropy hint (Chromium 125+). */\n formFactors?: string[];\n /** UA-CH `mobile` bit. */\n mobile?: boolean;\n}\n\n/**\n * Derive a form factor. UA-CH form factors win when present; otherwise the UA\n * decides, with `maxTouchPoints` unmasking an iPad that reports itself as a\n * Mac (iPadOS 13+ default) and separating Android tablets (no `Mobile` token)\n * from phones.\n *\n * @example\n * deriveDeviceType({ ua: navigator.userAgent, maxTouchPoints: navigator.maxTouchPoints });\n */\nexport function deriveDeviceType(signals: DeviceTypeSignals): DeviceType {\n const { ua, maxTouchPoints, formFactors, mobile } = signals;\n if (formFactors && formFactors.length > 0) {\n const set = new Set(formFactors.map((f) => f.toLowerCase()));\n if (set.has('xr')) return 'xr';\n if (set.has('automotive') || set.has('tv')) return 'tv';\n if (set.has('tablet')) return 'tablet';\n if (set.has('mobile') || set.has('watch')) return 'phone';\n if (set.has('desktop') || set.has('eink')) return 'desktop';\n }\n if (/iPad/.test(ua)) return 'tablet';\n if (/iPhone|iPod/.test(ua)) return 'phone';\n if (/Macintosh/.test(ua) && maxTouchPoints > 1) return 'tablet';\n if (/Android/.test(ua)) return /Mobile/.test(ua) ? 'phone' : 'tablet';\n if (/CrKey|SmartTV|Tizen|Web0S|BRAVIA|AppleTV/i.test(ua)) return 'tv';\n if (/Quest|OculusBrowser|VR\\b|XR\\b/i.test(ua)) return 'xr';\n if (mobile === true) return 'phone';\n if (/Windows|Macintosh|Linux|CrOS/.test(ua)) return 'desktop';\n return 'unknown';\n}\n\n/** Form-factor + input capability probes. */\nfunction probeDevice(\n nav: Navigator | undefined,\n ua: string,\n uaData: (NavigatorUAData & { formFactorsHint?: string[] }) | undefined,\n): DeviceInfo | undefined {\n if (!nav) return undefined;\n return attempt(() => {\n const maxTouchPoints = typeof nav.maxTouchPoints === 'number' ? nav.maxTouchPoints : 0;\n const formFactors = uaData?.formFactorsHint;\n const mobileBit = uaData?.mobile;\n const type = deriveDeviceType({ ua, maxTouchPoints, formFactors, mobile: mobileBit });\n const mq = (q: string): boolean | undefined =>\n typeof matchMedia === 'function' ? attempt(() => matchMedia(q).matches) : undefined;\n const displayMode = ['fullscreen', 'standalone', 'minimal-ui', 'browser'].find(\n (m) => mq(`(display-mode: ${m})`) === true,\n );\n return {\n type,\n mobile: mobileBit ?? (type === 'phone' || type === 'tablet'),\n formFactors,\n maxTouchPoints,\n pointerCoarse: mq('(pointer: coarse)'),\n hoverNone: mq('(hover: none)'),\n displayMode,\n };\n });\n}\n\n/** Structural WebGPU types (the TS DOM lib may not include WebGPU). */\ninterface GPUAdapterLike {\n info?: Record<string, unknown>;\n limits?: unknown;\n features?: Iterable<string>;\n}\ninterface GPULike {\n requestAdapter(): Promise<GPUAdapterLike | null>;\n getPreferredCanvasFormat?(): string;\n wgslLanguageFeatures?: Iterable<string>;\n}\n\n/** Probe the WebGPU adapter identity via the `adapter.info` attribute. */\nasync function probeWebGPU(nav: Navigator | undefined): Promise<GPUInfo> {\n const gpu = nav && 'gpu' in nav ? (nav as { gpu?: GPULike }).gpu : undefined;\n if (!gpu) return { available: false };\n try {\n const adapter = await Promise.race([\n gpu.requestAdapter(),\n new Promise<null>((resolve) => setTimeout(() => resolve(null), 3_000)),\n ]);\n if (!adapter) return { available: false };\n const info = adapter.info ?? {};\n const limits: Record<string, number> = {};\n const adapterLimits = adapter.limits as Record<string, number> | undefined;\n if (adapterLimits) {\n for (const key of GPU_LIMIT_KEYS) {\n const v = adapterLimits[key];\n if (typeof v === 'number') limits[key] = v;\n }\n }\n return {\n available: true,\n vendor: str(info.vendor),\n architecture: str(info.architecture),\n device: str(info.device),\n description: str(info.description),\n subgroupMinSize: num(info.subgroupMinSize),\n subgroupMaxSize: num(info.subgroupMaxSize),\n isFallbackAdapter:\n typeof info.isFallbackAdapter === 'boolean' ? info.isFallbackAdapter : undefined,\n features: adapter.features ? [...(adapter.features as Iterable<string>)].sort() : undefined,\n limits,\n preferredCanvasFormat: attempt(() => gpu.getPreferredCanvasFormat?.()),\n wgslLanguageFeatures: attempt(() =>\n gpu.wgslLanguageFeatures ? [...gpu.wgslLanguageFeatures].sort() : undefined,\n ),\n };\n } catch {\n return { available: false };\n }\n}\n\nfunction str(v: unknown): string | undefined {\n return typeof v === 'string' && v.length > 0 ? v : undefined;\n}\n\nfunction num(v: unknown): number | undefined {\n return typeof v === 'number' && Number.isFinite(v) ? v : undefined;\n}\n\n/** Software rasterizers that mean \"no real GPU behind this context\". */\nconst SOFTWARE_RENDERER = /swiftshader|llvmpipe|softpipe|software|mesa offscreen|microsoft basic render/i;\n\n/** WebGL identity + capacity (the UNMASKED strings when the debug extension exists). */\nfunction probeWebGL(): WebGLInfo | null {\n try {\n if (typeof document === 'undefined') return null;\n const canvas = document.createElement('canvas');\n let contextKind: WebGLInfo['contextKind'] = 'webgl2';\n let gl: WebGLRenderingContext | WebGL2RenderingContext | null = canvas.getContext(\n 'webgl2',\n ) as WebGL2RenderingContext | null;\n if (!gl) {\n contextKind = 'webgl';\n gl = canvas.getContext('webgl') as WebGLRenderingContext | null;\n }\n if (!gl) return { contextKind: null };\n const ext = gl.getExtension('WEBGL_debug_renderer_info');\n const vendor = ext\n ? (gl.getParameter(ext.UNMASKED_VENDOR_WEBGL) as string)\n : (gl.getParameter(gl.VENDOR) as string);\n const renderer = ext\n ? (gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) as string)\n : (gl.getParameter(gl.RENDERER) as string);\n const info: WebGLInfo = {\n contextKind,\n vendor: str(vendor),\n renderer: str(renderer),\n version: str(gl.getParameter(gl.VERSION)),\n shadingLanguageVersion: str(gl.getParameter(gl.SHADING_LANGUAGE_VERSION)),\n maxTextureSize: num(gl.getParameter(gl.MAX_TEXTURE_SIZE)),\n maxRenderbufferSize: num(gl.getParameter(gl.MAX_RENDERBUFFER_SIZE)),\n maxVertexUniformVectors: num(gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS)),\n maxFragmentUniformVectors: num(gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS)),\n extensionCount: attempt(() => gl!.getSupportedExtensions()?.length),\n softwareRenderer: typeof renderer === 'string' ? SOFTWARE_RENDERER.test(renderer) : undefined,\n };\n attempt(() => gl!.getExtension('WEBGL_lose_context')?.loseContext());\n return info;\n } catch {\n return null;\n }\n}\n\n/**\n * GPU model from a WebGL renderer string. ANGLE wraps the model as\n * `ANGLE (<vendor>, <model>[ (0x...)] <backend...>, <api>)`; Metal adds a\n * `ANGLE Metal Renderer: ` prefix. Native strings are returned as-is.\n *\n * @example\n * parseGpuModel('ANGLE (Apple, ANGLE Metal Renderer: Apple M4, Unspecified Version)'); // 'Apple M4'\n */\nexport function parseGpuModel(renderer: string | null | undefined): string | undefined {\n if (!renderer) return undefined;\n const angle = renderer.match(/^ANGLE \\((.*)\\)$/);\n if (!angle) return renderer.trim() || undefined;\n const inner = angle[1];\n // Split on top-level commas only; \"Adreno (TM) 740\" and \"(LLVM 15.0.7, 256 bits)\" keep their parens.\n const parts: string[] = [];\n let depth = 0;\n let current = '';\n for (const ch of inner) {\n if (ch === '(') depth++;\n if (ch === ')') depth--;\n if (ch === ',' && depth === 0) {\n parts.push(current.trim());\n current = '';\n } else {\n current += ch;\n }\n }\n parts.push(current.trim());\n // Three-part ANGLE strings are (vendor, model, backend); two-part ones are (vendor, model).\n let model = parts.length >= 2 ? parts[1] : parts[0];\n model = model.replace(/^ANGLE Metal Renderer:\\s*/i, '');\n // Drop the PCI id and the Direct3D shader-model suffix that follow the model on Windows.\n model = model\n .replace(/\\s*\\(0x[0-9a-fA-F]+\\)/g, '')\n .replace(/\\s+Direct3D\\d+.*$/i, '')\n .trim();\n return model || undefined;\n}\n\n/**\n * WebAssembly proposal support, probed the way `wasm-feature-detect` does:\n * validate or compile the smallest module that uses each feature. The byte\n * sequences are those of wasm-feature-detect 1.9.0, inlined so the harness\n * keeps its zero-dependency contract.\n *\n * @example\n * const wasm = await detectWasmFeatures(); // { simd: true, threads: true, ... }\n */\nexport async function detectWasmFeatures(): Promise<WasmFeatureSupport> {\n const validate = (bytes: number[]): boolean => {\n try {\n return WebAssembly.validate(new Uint8Array(bytes));\n } catch {\n return false;\n }\n };\n const compiles = (bytes: number[]): boolean => {\n try {\n new WebAssembly.Module(new Uint8Array(bytes));\n return true;\n } catch {\n return false;\n }\n };\n const has = (fn: () => boolean): boolean => {\n try {\n return fn();\n } catch {\n return false;\n }\n };\n const wasm = typeof WebAssembly !== 'undefined' ? WebAssembly : undefined;\n const W = wasm as unknown as Record<string, unknown> | undefined;\n\n const support: WasmFeatureSupport = {\n simd: validate([0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 10, 1, 8, 0, 65, 0, 253, 15, 253, 98, 11]),\n relaxedSimd: validate([0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 96, 0, 1, 123, 3, 2, 1, 0, 10, 15, 1, 13, 0, 65, 1, 253, 15, 65, 2, 253, 15, 253, 128, 2, 11]),\n threads: has(() => {\n if (typeof MessageChannel !== 'undefined') new MessageChannel().port1.postMessage(new SharedArrayBuffer(1));\n return validate([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 5, 4, 1, 3, 1, 1, 10, 11, 1, 9, 0, 65, 0, 254, 16, 2, 0, 26, 11]);\n }),\n bulkMemory: validate([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 5, 3, 1, 0, 1, 10, 14, 1, 12, 0, 65, 0, 65, 0, 65, 0, 252, 10, 0, 0, 11]),\n exceptions: validate([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 8, 1, 6, 0, 6, 64, 25, 11, 11]),\n exceptionsFinal: compiles([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 16, 1, 14, 0, 2, 105, 31, 64, 1, 3, 0, 0, 11, 0, 11, 26, 11]),\n extendedConst: validate([0, 97, 115, 109, 1, 0, 0, 0, 5, 3, 1, 0, 1, 11, 9, 1, 0, 65, 1, 65, 2, 106, 11, 0]),\n gc: validate([0, 97, 115, 109, 1, 0, 0, 0, 1, 5, 1, 95, 1, 120, 0]),\n memory64: validate([0, 97, 115, 109, 1, 0, 0, 0, 5, 3, 1, 4, 1]),\n multiMemory: compiles([0, 97, 115, 109, 1, 0, 0, 0, 5, 5, 2, 0, 0, 0, 0]),\n multiValue: validate([0, 97, 115, 109, 1, 0, 0, 0, 1, 6, 1, 96, 0, 2, 127, 127, 3, 2, 1, 0, 10, 8, 1, 6, 0, 65, 0, 65, 0, 11]),\n mutableGlobals: validate([0, 97, 115, 109, 1, 0, 0, 0, 2, 8, 1, 1, 97, 1, 98, 3, 127, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 5, 1, 1, 97, 3, 1]),\n referenceTypes: validate([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 7, 1, 5, 0, 208, 112, 26, 11]),\n saturatedFloatToInt: validate([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 12, 1, 10, 0, 67, 0, 0, 0, 0, 252, 0, 26, 11]),\n signExtensions: validate([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 8, 1, 6, 0, 65, 0, 192, 26, 11]),\n tailCall: validate([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10, 6, 1, 4, 0, 18, 0, 11]),\n typedFunctionReferences: compiles([0, 97, 115, 109, 1, 0, 0, 0, 1, 16, 3, 96, 1, 127, 1, 127, 96, 1, 100, 0, 1, 127, 96, 0, 1, 127, 3, 4, 3, 1, 0, 2, 9, 5, 1, 3, 0, 1, 1, 10, 28, 3, 11, 0, 65, 10, 65, 42, 32, 0, 20, 0, 106, 11, 7, 0, 32, 0, 65, 1, 106, 11, 6, 0, 210, 1, 16, 0, 11]),\n wideArithmetic: validate([0, 97, 115, 109, 1, 0, 0, 0, 1, 10, 1, 96, 4, 126, 126, 126, 126, 2, 126, 126, 3, 2, 1, 0, 10, 14, 1, 12, 0, 32, 0, 32, 1, 32, 2, 32, 3, 252, 19, 11]),\n jspi: has(() => Boolean(W && 'Suspending' in W)),\n typeReflection: has(() => Boolean(W && 'Function' in W)),\n streamingCompilation: has(() => Boolean(W && typeof W.compileStreaming === 'function')),\n jsStringBuiltins: false,\n };\n\n // JS String Builtins: a module importing `wasm:js-string.test` instantiates\n // only when the engine accepts the `builtins` option and implements the module.\n support.jsStringBuiltins = await (async () => {\n try {\n if (!wasm) return false;\n const bytes = new Uint8Array([\n 0, 97, 115, 109, 1, 0, 0, 0, 1, 6, 1, 96, 1, 111, 1, 127, 2, 23, 1, 14, 119, 97, 115, 109, 58,\n 106, 115, 45, 115, 116, 114, 105, 110, 103, 4, 116, 101, 115, 116, 0, 0,\n ]);\n await (wasm.instantiate as (b: BufferSource, i?: unknown, o?: unknown) => Promise<unknown>)(\n bytes,\n {},\n { builtins: ['js-string'] },\n );\n return true;\n } catch {\n return false;\n }\n })();\n\n // Largest `maximum` the engine accepts on a 32-bit memory; 65536 pages = 4 GiB.\n for (const pages of [65536, 32768, 16384]) {\n try {\n new WebAssembly.Memory({ initial: 1, maximum: pages });\n support.maxMemoryPages = pages;\n break;\n } catch {\n // try the next smaller ceiling\n }\n }\n return support;\n}\n\n/** Presence checks for the APIs the runtimes depend on. */\nasync function probeApis(\n nav: Navigator | undefined,\n webgpu: boolean,\n webgl2: boolean,\n): Promise<APIAvailability | undefined> {\n if (!nav) return undefined;\n const g = globalThis as unknown as Record<string, unknown>;\n const n = nav as unknown as Record<string, unknown>;\n const present = (obj: Record<string, unknown> | undefined, key: string): boolean =>\n attempt(() => Boolean(obj && key in obj)) ?? false;\n\n const opfs = await (async () => {\n try {\n const storage = nav.storage as unknown as { getDirectory?: () => Promise<unknown> } | undefined;\n if (!storage?.getDirectory) return false;\n await storage.getDirectory();\n return true;\n } catch {\n return false;\n }\n })();\n const persisted = await (async () => {\n try {\n const storage = nav.storage as unknown as { persisted?: () => Promise<boolean> } | undefined;\n return storage?.persisted ? await storage.persisted() : undefined;\n } catch {\n return undefined;\n }\n })();\n\n const builtInAi = async (key: string): Promise<string | undefined> => {\n try {\n const api = g[key] as { availability?: () => Promise<string> } | undefined;\n if (!api?.availability) return undefined;\n return await Promise.race([\n api.availability(),\n new Promise<string>((resolve) => setTimeout(() => resolve('timeout'), 2_000)),\n ]);\n } catch {\n return 'error';\n }\n };\n\n return {\n webgpu,\n webgl2,\n webnn: present(n, 'ml'),\n opfs,\n persistedStorage: persisted,\n indexedDB: present(g, 'indexedDB'),\n cacheApi: present(g, 'caches'),\n serviceWorker: present(n, 'serviceWorker'),\n webWorkers: present(g, 'Worker'),\n offscreenCanvas: present(g, 'OffscreenCanvas'),\n webLocks: present(n, 'locks'),\n broadcastChannel: present(g, 'BroadcastChannel'),\n wakeLock: present(n, 'wakeLock'),\n computePressure: present(g, 'PressureObserver'),\n performanceMemory: present(\n typeof performance !== 'undefined' ? (performance as unknown as Record<string, unknown>) : undefined,\n 'memory',\n ),\n measureUserAgentSpecificMemory: present(\n typeof performance !== 'undefined' ? (performance as unknown as Record<string, unknown>) : undefined,\n 'measureUserAgentSpecificMemory',\n ),\n schedulerYield: present(g.scheduler as Record<string, unknown> | undefined, 'yield'),\n webCodecs: present(g, 'VideoDecoder'),\n audioWorklet: present(g, 'AudioWorklet'),\n mediaDevices: present(n, 'mediaDevices'),\n webTransport: present(g, 'WebTransport'),\n promptApi: await builtInAi('LanguageModel'),\n summarizerApi: await builtInAi('Summarizer'),\n translatorApi: await (async () => {\n // Translator.availability needs a language pair; a common pair keeps the verdict comparable.\n try {\n const api = g.Translator as\n | { availability?: (o: { sourceLanguage: string; targetLanguage: string }) => Promise<string> }\n | undefined;\n if (!api?.availability) return undefined;\n return await Promise.race([\n api.availability({ sourceLanguage: 'en', targetLanguage: 'es' }),\n new Promise<string>((resolve) => setTimeout(() => resolve('timeout'), 2_000)),\n ]);\n } catch {\n return 'error';\n }\n })(),\n languageDetectorApi: await builtInAi('LanguageDetector'),\n };\n}\n\n/** `performance.memory` (Chromium) idle snapshot. */\nfunction probePerformanceMemory(): { limit?: number; used?: number } | undefined {\n return attempt(() => {\n const mem = (performance as unknown as { memory?: { jsHeapSizeLimit?: number; usedJSHeapSize?: number } })\n .memory;\n if (!mem) return undefined;\n return { limit: num(mem.jsHeapSizeLimit), used: num(mem.usedJSHeapSize) };\n });\n}\n\n/** Display + viewport + media-query preferences. */\nfunction probeScreen(): DisplayInfo | null {\n if (typeof screen === 'undefined') return null;\n try {\n const mq = (q: string): boolean | undefined =>\n typeof matchMedia === 'function' ? attempt(() => matchMedia(q).matches) : undefined;\n const scheme = mq('(prefers-color-scheme: dark)')\n ? 'dark'\n : mq('(prefers-color-scheme: light)')\n ? 'light'\n : 'no-preference';\n return {\n width: screen.width,\n height: screen.height,\n availWidth: num(screen.availWidth),\n availHeight: num(screen.availHeight),\n dpr: typeof devicePixelRatio !== 'undefined' ? devicePixelRatio : 1,\n colorDepth: num(screen.colorDepth),\n orientation: attempt(() => screen.orientation?.type),\n viewportWidth: typeof innerWidth !== 'undefined' ? innerWidth : undefined,\n viewportHeight: typeof innerHeight !== 'undefined' ? innerHeight : undefined,\n hdr: mq('(dynamic-range: high)'),\n wideGamut: mq('(color-gamut: p3)'),\n isExtended: attempt(() => (screen as unknown as { isExtended?: boolean }).isExtended),\n prefersReducedMotion: mq('(prefers-reduced-motion: reduce)'),\n prefersColorScheme: scheme,\n };\n } catch {\n return null;\n }\n}\n\n/** Network Information API snapshot (Chromium desktop + Android; absent elsewhere). */\nfunction probeNetwork(nav: Navigator | undefined): NetworkInfo | undefined {\n if (!nav) return undefined;\n return attempt(() => {\n const conn = (nav as unknown as {\n connection?: { effectiveType?: string; type?: string; downlink?: number; rtt?: number; saveData?: boolean };\n }).connection;\n const online = typeof nav.onLine === 'boolean' ? nav.onLine : undefined;\n if (!conn) return { supported: false, online };\n return {\n supported: true,\n effectiveType: str(conn.effectiveType),\n type: str(conn.type),\n downlinkMbps: num(conn.downlink),\n rttMs: num(conn.rtt),\n saveData: typeof conn.saveData === 'boolean' ? conn.saveData : undefined,\n online,\n };\n });\n}\n\n/** Time zone + locale from Intl; the offset from Date. */\nfunction probeLocale(): LocaleInfo | undefined {\n return attempt(() => {\n const resolved = Intl.DateTimeFormat().resolvedOptions();\n return {\n timeZone: str(resolved.timeZone),\n timeZoneOffsetMinutes: new Date().getTimezoneOffset(),\n locale: str(resolved.locale),\n calendar: str(resolved.calendar),\n };\n });\n}\n\nasync function probeStorage(\n nav: Navigator | undefined,\n): Promise<EnvironmentCapture['storage']> {\n try {\n if (!nav?.storage?.estimate) return null;\n const est = await nav.storage.estimate();\n const details = (est as { usageDetails?: Record<string, number> }).usageDetails;\n return {\n quotaBytes: est.quota ?? undefined,\n usageBytes: est.usage ?? undefined,\n usageDetails: details && Object.keys(details).length > 0 ? { ...details } : undefined,\n };\n } catch {\n return null;\n }\n}\n\nasync function probeBattery(nav: Navigator | undefined): Promise<EnvironmentCapture['power']> {\n try {\n const getBattery = nav && 'getBattery' in nav\n ? (nav as {\n getBattery?: () => Promise<{\n charging: boolean;\n level: number;\n chargingTime?: number;\n dischargingTime?: number;\n }>;\n }).getBattery\n : undefined;\n if (!getBattery) return { batterySupported: false };\n const battery = await getBattery.call(nav);\n const finite = (v: number | undefined): number | undefined =>\n typeof v === 'number' && Number.isFinite(v) ? v : undefined;\n return {\n batterySupported: true,\n charging: battery.charging,\n level: battery.level,\n chargingTimeSec: finite(battery.chargingTime),\n dischargingTimeSec: finite(battery.dischargingTime),\n };\n } catch {\n return { batterySupported: false };\n }\n}\n","/**\n * Deterministic single-thread JS matmul microbenchmark. Every submission runs\n * it; the resulting MFLOPS is a hardware fingerprint that claimed inference\n * rates must plausibly correlate with, and the checksum proves the work ran.\n */\n\nimport type { FingerprintResult } from './types.js';\nimport { hrNow } from './timing.js';\n\n/** Deterministic LCG so every device multiplies the same matrices. */\nfunction lcg(seed: number): () => number {\n let s = seed >>> 0;\n return () => {\n s = (Math.imul(s, 1664525) + 1013904223) >>> 0;\n return s / 0xffffffff;\n };\n}\n\n/**\n * Run the fingerprint microbenchmark: repeated n x n f32 matmuls for at least\n * `minDurationMs`, single-threaded, deterministic inputs.\n *\n * @param options.n - Matrix dimension (default 160; ~8.2 MFLOP per iteration).\n * @param options.minDurationMs - Minimum wall time to run (default 600).\n * @returns MFLOPS, iteration count, and a checksum of the final product.\n * @example\n * const fp = await runFingerprint(); // { mflops: 1800.4, ... }\n */\nexport async function runFingerprint(options?: {\n n?: number;\n minDurationMs?: number;\n}): Promise<FingerprintResult> {\n const n = options?.n ?? 160;\n const minDurationMs = options?.minDurationMs ?? 600;\n const rand = lcg(0xbe7c4);\n const a = new Float32Array(n * n);\n const b = new Float32Array(n * n);\n for (let i = 0; i < n * n; i++) {\n a[i] = rand() - 0.5;\n b[i] = rand() - 0.5;\n }\n const c = new Float32Array(n * n);\n const flopsPerIter = 2 * n * n * n;\n let iterations = 0;\n const start = hrNow();\n let elapsed = 0;\n while (elapsed < minDurationMs) {\n matmul(a, b, c, n);\n iterations++;\n elapsed = hrNow() - start;\n // Yield to the event loop every few iterations so validity-gate listeners\n // (visibilitychange, abort) can run during the fingerprint.\n if (iterations % 4 === 0) await Promise.resolve();\n }\n let checksum = 0;\n for (let i = 0; i < n * n; i += 97) checksum += c[i];\n return {\n mflops: (flopsPerIter * iterations) / (elapsed * 1000),\n n,\n iterations,\n durationMs: elapsed,\n checksum: Math.fround(checksum),\n };\n}\n\n/** Naive row-major matmul (deliberately unoptimized and stable across engines). */\nfunction matmul(a: Float32Array, b: Float32Array, c: Float32Array, n: number): void {\n for (let i = 0; i < n; i++) {\n for (let j = 0; j < n; j++) {\n let acc = 0;\n for (let k = 0; k < n; k++) acc += a[i * n + k] * b[k * n + j];\n c[i * n + j] = acc;\n }\n }\n}\n","/**\n * Statistics for benchmark reporting: median headline, mean ± SD, IQR, 95% CI\n * (Student-t for the small n this protocol uses), CV, and geometric mean for\n * cross-workload aggregation (never across devices).\n */\n\nimport type { MetricSummary } from './types.js';\n\n/** Two-sided 95% Student-t critical values by degrees of freedom (1..30). */\nconst T_95: number[] = [\n 12.706, 4.303, 3.182, 2.776, 2.571, 2.447, 2.365, 2.306, 2.262, 2.228, 2.201, 2.179, 2.16,\n 2.145, 2.131, 2.12, 2.11, 2.101, 2.093, 2.086, 2.08, 2.074, 2.069, 2.064, 2.06, 2.056, 2.052,\n 2.048, 2.045, 2.042,\n];\n\n/** Sorted copy helper. */\nfunction sorted(values: readonly number[]): number[] {\n return [...values].sort((a, b) => a - b);\n}\n\n/**\n * Linear-interpolated quantile (type-7, the R/NumPy default).\n *\n * @param values - Sample values (need not be sorted).\n * @param q - Quantile in [0, 1].\n * @returns The interpolated quantile.\n * @throws {RangeError} When `values` is empty or `q` is out of range.\n * @example\n * quantile([1, 2, 3, 4], 0.5); // 2.5\n */\nexport function quantile(values: readonly number[], q: number): number {\n if (values.length === 0) throw new RangeError('quantile() requires a non-empty sample');\n if (q < 0 || q > 1) throw new RangeError(`quantile q must be in [0,1], got ${q}`);\n const s = sorted(values);\n const pos = (s.length - 1) * q;\n const lo = Math.floor(pos);\n const hi = Math.ceil(pos);\n if (lo === hi) return s[lo];\n return s[lo] + (s[hi] - s[lo]) * (pos - lo);\n}\n\n/** Median of a sample. @see quantile */\nexport function median(values: readonly number[]): number {\n return quantile(values, 0.5);\n}\n\n/** Arithmetic mean. @throws {RangeError} on an empty sample. */\nexport function mean(values: readonly number[]): number {\n if (values.length === 0) throw new RangeError('mean() requires a non-empty sample');\n let sum = 0;\n for (const v of values) sum += v;\n return sum / values.length;\n}\n\n/** Sample standard deviation (n-1 denominator). Returns 0 for n < 2. */\nexport function stddev(values: readonly number[]): number {\n if (values.length < 2) return 0;\n const m = mean(values);\n let acc = 0;\n for (const v of values) acc += (v - m) * (v - m);\n return Math.sqrt(acc / (values.length - 1));\n}\n\n/**\n * Geometric mean. Used to aggregate across workloads within one device run\n * (Speedometer/JetStream convention). All values must be positive.\n *\n * @throws {RangeError} on an empty sample or non-positive values.\n */\nexport function geomean(values: readonly number[]): number {\n if (values.length === 0) throw new RangeError('geomean() requires a non-empty sample');\n let acc = 0;\n for (const v of values) {\n if (v <= 0) throw new RangeError(`geomean() requires positive values, got ${v}`);\n acc += Math.log(v);\n }\n return Math.exp(acc / values.length);\n}\n\n/**\n * Full summary of one metric across timed iterations.\n *\n * @param values - One value per timed iteration (ms, tok/s, ...).\n * @returns Median headline plus dispersion measures; `ci95` is the Student-t\n * 95% half-width (0 when n < 2).\n * @example\n * summarize([102, 99, 104]).median; // 102\n */\nexport function summarize(values: readonly number[]): MetricSummary {\n if (values.length === 0) throw new RangeError('summarize() requires a non-empty sample');\n const n = values.length;\n const m = mean(values);\n const sd = stddev(values);\n const s = sorted(values);\n const ci95 = n >= 2 ? (T_95[Math.min(n - 2, T_95.length - 1)] * sd) / Math.sqrt(n) : 0;\n return {\n n,\n median: median(values),\n mean: m,\n sd,\n iqr: quantile(values, 0.75) - quantile(values, 0.25),\n min: s[0],\n max: s[n - 1],\n ci95,\n cv: m === 0 ? 0 : sd / Math.abs(m),\n };\n}\n\n/**\n * Spearman rank correlation between two equal-length samples, with average\n * ranks for ties. Used by the STS embedding-quality lane.\n *\n * @returns rho in [-1, 1].\n * @throws {RangeError} when lengths differ or n < 2.\n */\nexport function spearman(a: readonly number[], b: readonly number[]): number {\n if (a.length !== b.length) throw new RangeError('spearman() requires equal-length samples');\n if (a.length < 2) throw new RangeError('spearman() requires n >= 2');\n const ra = ranks(a);\n const rb = ranks(b);\n return pearson(ra, rb);\n}\n\n/** Average ranks (1-based) with tie handling. */\nfunction ranks(values: readonly number[]): number[] {\n const idx = values.map((v, i) => [v, i] as const).sort((x, y) => x[0] - y[0]);\n const out = new Array<number>(values.length);\n let i = 0;\n while (i < idx.length) {\n let j = i;\n while (j + 1 < idx.length && idx[j + 1][0] === idx[i][0]) j++;\n const avgRank = (i + j) / 2 + 1;\n for (let k = i; k <= j; k++) out[idx[k][1]] = avgRank;\n i = j + 1;\n }\n return out;\n}\n\n/** Pearson correlation. Returns 0 when either sample has zero variance. */\nfunction pearson(a: readonly number[], b: readonly number[]): number {\n const ma = mean(a);\n const mb = mean(b);\n let num = 0;\n let da = 0;\n let db = 0;\n for (let i = 0; i < a.length; i++) {\n const xa = a[i] - ma;\n const xb = b[i] - mb;\n num += xa * xb;\n da += xa * xa;\n db += xb * xb;\n }\n const den = Math.sqrt(da * db);\n return den === 0 ? 0 : num / den;\n}\n","/**\n * tinyMMLU — 100 IRT-anchored items from the MMLU benchmark, selected by the\n * tinyBenchmarks project (Maia Polo et al., \"tinyBenchmarks: evaluating LLMs\n * with fewer examples\", arXiv:2402.14992). Source dataset:\n * https://huggingface.co/datasets/tinyBenchmarks/tinyMMLU (test split, 100 rows).\n * Upstream MMLU (cais/mmlu) and the tinyBenchmarks repository are MIT-licensed.\n *\n * Used by the quality-fidelity lane: scores measure runtime/quantization\n * fidelity of a model build, not model capability (public sets are assumed\n * to be in training data).\n */\n\n/** One multiple-choice item: four choices, `answer` is the 0-based correct index. */\nexport interface MMLUItem {\n question: string;\n subject: string;\n choices: [string, string, string, string];\n answer: 0 | 1 | 2 | 3;\n}\n\n/** The 100-item tinyMMLU test split (order preserved from the source dataset). */\nexport const TINY_MMLU: readonly MMLUItem[] = [\n {\n \"question\": \"The number of days it takes to build a new house has a variance of 386. A sample of 40 new homes shows an average building time of 83 days. With what confidence can we assert that the average building time for a new house is between 80 and 90 days?\",\n \"subject\": \"high_school_statistics\",\n \"choices\": [\n \"15.4%\",\n \"17.8%\",\n \"20.0%\",\n \"82.1%\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"According to trials on diabetes prevention, high-risk individuals can reduce their risk to develop diabetes by doing the following:\",\n \"subject\": \"nutrition\",\n \"choices\": [\n \"Eating a very low carbohydrate diet\",\n \"Consuming a diet high in monounsaturated fats\",\n \"Losing 5-7% of body weight through a hypocaloric low fat diet and 30 minutes of daily activity\",\n \"Initiating metformin 850 mg BID and practicing daily vigorous exercise\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"Which of the following is true regarding the complications of a large goitre?\",\n \"subject\": \"clinical_knowledge\",\n \"choices\": [\n \"It causes stridor due to compression of the oesophagus\",\n \"Dysphagia is an indication for surgery\",\n \"It causes hoarseness due to compression of the trachea\",\n \"It causes a more florid thyrotoxicosis than a smaller goitre\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"Doses of substances used in animal toxicity studies are usually many times greater than those experienced by people because:\",\n \"subject\": \"nutrition\",\n \"choices\": [\n \"Animals are generally much less sensitive than people\",\n \"Such tests can detect only very large risks because of the fact that only small numbers of animals can be used\",\n \"It is difficult in such studies to determine whether the observed toxic effects were caused by the substance\",\n \"It is the only way to ensure results are applicable to people\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"Rowena can paint a room in $14$ hours, while Ruby can paint it in $6$ hours. If Rowena paints for $x$ hours and Ruby paints for $y$ hours, they will finish half of the painting, while if Rowena paints for $y$ hours and Ruby paints for $x$ hours they will paint the whole room. Find the ordered pair $(x,y)$.\",\n \"subject\": \"high_school_mathematics\",\n \"choices\": [\n \"(\\\\frac{11}{10}, \\\\frac{11}{10})\",\n \"(\\\\frac{231}{20}, \\\\frac{21}{20})\",\n \"(\\\\frac{231}{40}, \\\\frac{21}{40})\",\n \"(1,1)\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"Which of the following statements would Macedo disagree with?\",\n \"subject\": \"moral_disputes\",\n \"choices\": [\n \"States should give special weight to their own citizens.\",\n \"Immigration policies can have powerful economic effects.\",\n \"Self-governance is morally irrelevant to the immigration debate.\",\n \"There are reasons to think U.S. immigration policy has had detrimental effects on income distribution among citizens.\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"A 17-year-old girl is brought to the physician by her mother because she has not had a menstrual period for 6 months. The patient is unconcerned about the lack of menses. Menarche occurred at the age of 12 years, and menses had occurred at regular 28-day intervals until they became irregular 1 year ago. She is a member of her high school gymnastics team. She appears emaciated. She is 163 cm (5 ft 4 in) tall and weighs 40 kg (88 lb); BMI is 15 kg/m2 . Her pulse is 54/min, and blood pressure is 80/50 mm Hg. Which of the following is the most likely cause of this patient's amenorrhea?\",\n \"subject\": \"professional_medicine\",\n \"choices\": [\n \"Hyperthyroidism\",\n \"Hypogonadotropic hypogonadism\",\n \"Hypothyroidism\",\n \"Polycystic ovarian syndrome\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"The Yang-shao culture gave way to the Lung-Shan sometime after:\",\n \"subject\": \"prehistory\",\n \"choices\": [\n \"6,000 B.P.\",\n \"5,000 B.P.\",\n \"4,000 B.P.\",\n \"3,000 B.P.\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"Cultural homogenization.\",\n \"subject\": \"business_ethics\",\n \"choices\": [\n \"1,3,4\",\n \"1,2,3\",\n \"1,2,3,4\",\n \"2,3,4\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"Of the ways of escaping moral arguments that he discusses, Hare claims:\",\n \"subject\": \"philosophy\",\n \"choices\": [\n \"none of them are successful.\",\n \"some, but not all of them are successful.\",\n \"all are entirely successful.\",\n \"all might be successful, but at a price.\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"An employee of large manufacturing firm finds the work dull, and pursues the job only for the money. The employee performs minimally, and is not motivated so produce highest quantity or better quality. According to F. Herzberg's two-factor theory, the best way 10 increase this worker's self-motivation would be to\",\n \"subject\": \"professional_psychology\",\n \"choices\": [\n \"offer a raise and incentive pay for greater productivity\",\n \"redesign the job to provide a challenge and a sense of accomplishment\",\n \"increase opportunities for informed social interaction\",\n \"provide the employee with a job tide carrying greater prestige\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"In an e-commerce environment that requires that the information technology (IT) system be available on a continuous basis, more emphasis will be placed on which of the following aspects of the planning than in a traditional organization?\",\n \"subject\": \"professional_accounting\",\n \"choices\": [\n \"Maintain appropriate written source documents so the data can be re-entered if it is lost or compromised\",\n \"Maintain redundant systems for instant availability to assure the flow of transactions\",\n \"Review additional expenses to obtain the required amount of business interruption insurance coverage for the organization\",\n \"Assure that appropriate data backups are stored in an off-site location\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"The Space Shuttle orbits 300 km above the Earth’s surface; the Earth’s radius is 6400 km. What is the acceleration due to Earth’s gravity experienced by the Space Shuttle?\",\n \"subject\": \"high_school_physics\",\n \"choices\": [\n \"4.9 m/s^2\",\n \"8.9 m/s^2\",\n \"9.8 m/s^2\",\n \"10.8 m/s^2\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"Statement 1 | The image of a group of 6 elements under a homomorphism may have 12 elements. Statement 2 | There is a homomorphism of some group of 6 elements into some group of 12 elements.\",\n \"subject\": \"abstract_algebra\",\n \"choices\": [\n \"True, True\",\n \"False, False\",\n \"True, False\",\n \"False, True\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"At which of the following locations does bile enter the digestive tract?\",\n \"subject\": \"anatomy\",\n \"choices\": [\n \"Gastroesophageal sphincter\",\n \"Duodenum\",\n \"Ileocecum\",\n \"Jejunum\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"This question refers to the following information.\\nIs it not unity alone that can weld us into an effective force, capable of creating our own progress and making our valuable contribution to world peace? Which independent African state will claim that its financial structure and banking institutions are fully harnessed to its national development? Which will claim that its material resources and human energies are available for its own national aspirations? We are fast learning that political independence is not enough to rid us of the consequences of colonial rule. We have been too busy nursing our separate states to understand fully the basic need for union, rooted in common purpose, common planning and common endeavour.\\nGhana's president, Kwame Nkrumah, addressing the Organization of African Unity, 1963\\nThe speaker in the passage above is espousing which of the following causes?\",\n \"subject\": \"high_school_world_history\",\n \"choices\": [\n \"Nationalism\",\n \"Socialism\",\n \"Pan-Africanism\",\n \"Neocolonialism\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"Monte Alban is located in the ________ and was built by the _________.\",\n \"subject\": \"prehistory\",\n \"choices\": [\n \"Valley of Mexico; Aztec.\",\n \"Valley of Oaxaca; Zapotec.\",\n \"Amazon floodplain; Olmec.\",\n \"Yucatán Peninsula; Maya.\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"Sauna use, sometimes referred to as \\\"sauna bathing,\\\" is characterized by short-term passive exposure to extreme heat. This exposure elicits mild hyperthermia – an increase in the body's core temperature – that induces a thermoregulatory response involving neuroendocrine, cardiovascular, and cytoprotective mechanisms that work together to restore homeostasis and condition the body for future heat stressors… In recent decades, sauna bathing has emerged as a means to increase lifespan and improve overall health, based on compelling data from observational, interventional, and mechanistic studies. Of particular interest are the findings from studies of participants in the Kuopio Ischemic Heart Disease Risk Factor (KIHD) Study, an ongoing prospective population-based cohort study of health outcomes in more than 2,300 middle-aged men from eastern Finland, which identified strong links between sauna use and reduced death and disease… The KIHD findings showed that men who used the sauna two to three times per week were 27 percent less likely to die from cardiovascular-related causes than men who didn't use the sauna.[2] Furthermore, the benefits they experienced were found to be dose-dependent: Men who used the sauna roughly twice as often, about four to seven times per week, experienced roughly twice the benefits – and were 50 percent less likely to die from cardiovascular-related causes.[2] In addition, frequent sauna users were found to be 40 percent less likely to die from all causes of premature death. These findings held true even when considering age, activity levels, and lifestyle factors that might have influenced the men's health.[2]... The KIHD also revealed that frequent sauna use reduced the risk of developing dementia and Alzheimer's disease in a dose-dependent manner. Men who used the sauna two to three times per week had a 66 percent lower risk of developing dementia and a 65 percent lower risk of developing Alzheimer's disease, compared to men who used the sauna only one time per week… The health benefits associated with sauna use extended to other aspects of mental health, as well. Men participating in the KIHD study who used the sauna four to seven times per week were 77 percent less likely to develop psychotic disorders, regardless of the men's dietary habits, socioeconomic status, physical activity, and inflammatory status (as measured by C-reactive protein)…Exposure to high temperature stresses the body, eliciting a rapid, robust response. The skin and core body temperatures increase markedly, and sweating ensues. The skin heats first, rising to 40°C (104°F), and then changes in core body temperature occur, rising slowly from 37°C (98.6°F, or normal) to 38°C (100.4°F) and then rapidly increasing to 39°C (102.2°F)… Cardiac output, a measure of the amount of work the heart performs in response to the body's need for oxygen, increases by 60 to 70 percent, while the heart rate (the number of beats per minute) increases and the stroke volume (the amount of blood pumped) remains unchanged.[5] During this time, approximately 50 to 70 percent of the body's blood flow is redistributed from the core to the skin to facilitate sweating. The average person loses approximately 0.5 kg of sweat while sauna bathing.[11] Acute heat exposure also induces a transient increase in overall plasma volume to mitigate the decrease in core blood volume. This increase in plasma volume not only provides a reserve source of fluid for sweating, but it also acts like the water in a car's radiator, cooling the body to prevent rapid increases in core body temperature and promoting heat tolerance… Repeated sauna use acclimates the body to heat and optimizes the body's response to future exposures, likely due to a biological phenomenon known as hormesis, a compensatory defense response following exposure to a mild stressor that is disproportionate to the magnitude of the stressor. Hormesis triggers a vast array of protective mechanisms that not only repair cell damage but also provide protection from subsequent exposures to more devastating stressors… The physiological responses to sauna use are remarkably similar to those experienced during moderate- to vigorous-intensity exercise. In fact, sauna use has been proposed as an alternative to exercise for people who are unable to engage in physical activity due to chronic disease or physical limitations.[13]\\n\\nBased on the article, which of the following statements is the author likely to agree with?\",\n \"subject\": \"college_medicine\",\n \"choices\": [\n \"Heart surgery patients who cannot run on treadmills may benefit from sauna use.\",\n \"Patients on a diet would benefit from sauna use.\",\n \"Salt restriction would be equal to sauna use for hypertensive patients.\",\n \"Patients with skin conditions may be cured with sauna use.\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"A department store had suffered a succession of thefts of merchandise over a period of months. From reports by employees and customers, the department store's manager concluded that the losses were due, wholly or in large part, to the depredations of a female shoplifter, aged 30 to 40 years, about 5 feet 5 inches in height, with red hair and green eyes, who usually wore a suit. This information was passed on to all of the employees of the department store. One day, a woman entered the store to purchase accessories. The woman was 5 feet 5 inches tall, 37 years old, red-haired and green-eyed, and dressed in a smartly tailored suit. She carried a large shopping bag. The manager noticed her as she picked up, examined, and put down a number of gloves and scarves. After a while, she looked about tentatively, and then started to walk out, swinging her bag. The manager intercepted her and, standing in front of her, politely asked the woman if she would accompany her to the store manager's office. When the woman asked for an explanation, the manager told her of the store's recent experience and the suspicion that the woman might be concealing pilfered merchandise in her bag. Flushing angrily, the woman replied, \\\"Very well,\\\" and followed her to the office. Once there, the manager began to question the woman quite intensively. After the questioning, the manager then asked the woman's permission to inspect the contents of her shopping bag. At first, the woman curtly refused and announced that she had had enough of this nonsense. When she rose to go, the manager told her, \\\"Listen, unless you let me look inside that bag, I'm going to call the police. \\\" The woman replied, \\\"Very well,\\\" and handed her the bag. The manager inspected the contents of the bag thoroughly but did not find any pilfered merchandise. She then gave the woman permission to leave. The total length of the woman's detention was 30 minutes. If the woman asserts a claim for false imprisonment against the department store, she will most likely\",\n \"subject\": \"professional_law\",\n \"choices\": [\n \"prevail, because she was detained for an unreasonably long period of time.\",\n \"prevail, because the manager did not have reasonable grounds to suspect that the woman had committed a theft.\",\n \"not prevail, because under the circumstances, the manager had reasonable grounds to suspect that the woman had committed a theft.\",\n \"not prevail, because the manager gave the woman permission to leave after conducting her investigation.\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"Which language family is most widely spoken in North America and Europe and includes Baltic, Celtic, Germanic, and Greek?\",\n \"subject\": \"high_school_geography\",\n \"choices\": [\n \"Dravidian\",\n \"Uralic-Altaic\",\n \"Sino-Tibetan\",\n \"Indo-European\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"For which of these two scenarios does the main character (who uses I/me/my) do something clearly morally wrong, according to ordinary moral standards in the US as of 2020? Scenario 1 | I decided to cook a potato for my girlfriend. Scenario 2 | I cornered the rat forcing it to go outside\",\n \"subject\": \"moral_scenarios\",\n \"choices\": [\n \"Wrong, Wrong\",\n \"Wrong, Not wrong\",\n \"Not wrong, Wrong\",\n \"Not wrong, Not wrong\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"How does rubella cause foetal abnormalities?\",\n \"subject\": \"virology\",\n \"choices\": [\n \"By crossing the placenta early in pregnancy and infecting the foetus\",\n \"By only infecting the placenta\",\n \"By inducing cytokines and chemokines in the mother\",\n \"By raising the temperature of the mother and inducing an abnormal immune reaction to the foetus\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"Find the opposite of the number −7.\",\n \"subject\": \"elementary_mathematics\",\n \"choices\": [\n \"7\",\n \"−7\",\n \"0.7\",\n \"−7.7\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"Silver metal, often amalgamated with mercury, is used to reduce substances to a desired oxidation state. If the silver metal amalgam cannot be used because of concerns about mercury, which of the following would be a reasonable and safe substitute?\",\n \"subject\": \"high_school_chemistry\",\n \"choices\": [\n \"H+(aq)\",\n \"Na(s)\",\n \"Ca2+(aq)\",\n \"Mg(s)\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"A 52-year-old man is brought to the emergency department 30 minutes after he had an episode of chest pain radiating to his jaw while shoveling snow. His pulse is 80/min, and blood pressure is 130/70 mm Hg. The lungs are clear to auscultation. Cardiac examination shows an S4. While undergoing an ECG, the patient says that he feels the chest pain returning. The most appropriate immediate treatment is a drug with which of the following mechanisms of action?\",\n \"subject\": \"professional_medicine\",\n \"choices\": [\n \"Increases cAMP concentration\",\n \"Increases nitric oxide concentration\",\n \"Inhibits potassium flux\",\n \"Inhibits sodium flux\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"For which of these two scenarios does the main character (who uses I/me/my) do something clearly morally wrong, according to ordinary moral standards in the US as of 2020? Scenario 1 | I voted twice in the presidential election. Scenario 2 | I rolled the grocery cart to my car.\",\n \"subject\": \"moral_scenarios\",\n \"choices\": [\n \"Wrong, Wrong\",\n \"Wrong, Not wrong\",\n \"Not wrong, Wrong\",\n \"Not wrong, Not wrong\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"A mechanism is a sequence of elementary reactions that add up to the overall reaction stoichiometry. A substance that is produced in one elementary reaction and consumed in another is called\",\n \"subject\": \"high_school_chemistry\",\n \"choices\": [\n \"a catalyst\",\n \"an intermediate\",\n \"a reactant\",\n \"a complex\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"A 22-year-old woman comes to the office because of urticaria. This is her first episode of urticaria and it has occurred and then resolved several times in the past week. The history and physical examination disclose no abnormalities. Which of the following is the most appropriate course of action?\",\n \"subject\": \"professional_medicine\",\n \"choices\": [\n \"Determine the serum IgE concentration\",\n \"Determine the total eosinophil count\",\n \"Refer her to an allergist\",\n \"Treat the symptoms\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"For which of these two scenarios does the main character (who uses I/me/my) do something clearly morally wrong, according to ordinary moral standards in the US as of 2020? Scenario 1 | I spent my afternoon swimming in the pool. Scenario 2 | I made my partner scream for help the entire evening.\",\n \"subject\": \"moral_scenarios\",\n \"choices\": [\n \"Wrong, Wrong\",\n \"Wrong, Not wrong\",\n \"Not wrong, Wrong\",\n \"Not wrong, Not wrong\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"If you were to travel at a speed close to the speed of light, you could notice that your own\",\n \"subject\": \"conceptual_physics\",\n \"choices\": [\n \"mass changes.\",\n \"pulse decreases.\",\n \"Both of these.\",\n \"Neither of these.\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"Form A of a standardized personality test was given in the fall and again in the spring co the same group of people. The reliability estimate that resulted from this research is referred to as\",\n \"subject\": \"professional_psychology\",\n \"choices\": [\n \"external consistency\",\n \"equivalence\",\n \"stability\",\n \"internal consistency\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"All of the following statements are true EXCEPT\",\n \"subject\": \"high_school_biology\",\n \"choices\": [\n \"thyroxine increases the rate of metabolism\",\n \"insulin decreases storage of glycogen\",\n \"vasopressin stimulates water reabsorption in the kidney\",\n \"epinephrine increases blood sugar levels and heart rate\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"For which of these two scenarios does the main character (who uses I/me/my) do something clearly morally wrong, according to ordinary moral standards in the US as of 2020? Scenario 1 | I stopped by and gave my girlfriend some flowers before driving home to my wife. Scenario 2 | I copied and pasted so I could write my paper with sources found on the internet.\",\n \"subject\": \"moral_scenarios\",\n \"choices\": [\n \"Wrong, Wrong\",\n \"Wrong, Not wrong\",\n \"Not wrong, Wrong\",\n \"Not wrong, Not wrong\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"The majority of Kurds are found in which country?\",\n \"subject\": \"high_school_geography\",\n \"choices\": [\n \"Iran\",\n \"Iraq\",\n \"Turkey\",\n \"Egypt\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"Including the bottom how many sides are on a square-based pyramid?\",\n \"subject\": \"miscellaneous\",\n \"choices\": [\n \"three\",\n \"four\",\n \"five\",\n \"six\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"One of the following is the primary function of an oscillator\",\n \"subject\": \"electrical_engineering\",\n \"choices\": [\n \"produces sinusoidal oscillations\",\n \"generates non sinusoidal waveforms\",\n \"generates sustained oscillations at a constant amplitude and specific frequency\",\n \"none of the above\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"In what ways, if any, can the environment be considered a security concern?\",\n \"subject\": \"security_studies\",\n \"choices\": [\n \"Environmental security entails a consideration of the security of the global environment, as well as its nested sub-systems and social systems beyond the boundaries of the nation state.\",\n \"Environmental security is a critical security project in that it questions who and what is to be secured and from what threat by orthodox security policies, or whether linkages between environmental, security and development issues can be made.\",\n \"Environmental security is a practical endeavour to assess how environmental change causes violent conflict within and between countries, and the ways in which environmental security can undermine national security.\",\n \"All of these options. The environment is both an object to be secured and a source of risk, although it may mean different things to different people. Whilst deepening the concept of security it has both critical and practical dimensions although the utility of the concept is contested.\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"________ are a business ethics management tool that have grown over the last few decades. Areas which these typically cover are compliance, corruption and environmental issues. However, they are constantly evolving, with for example, the onus on __________ having grown in recent years.\",\n \"subject\": \"business_ethics\",\n \"choices\": [\n \"Annual reports, Company financial performance\",\n \"Annual report, Internet - social media and networking\",\n \"Codes of ethics, Company financial performance\",\n \"Codes of ethics, Internet - social media and networking\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"If an iron nucleus split in two, its fission fragments would have\",\n \"subject\": \"conceptual_physics\",\n \"choices\": [\n \"less mass per nucleon\",\n \"more mass per nucleon\",\n \"the same mass per nucleon\",\n \"either more or less mass per nucleon\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"In one metropolitan region, technical writers have an annual salary that is approximately normally distributed with a mean of $55,800. The first quartile of salaries is $48,815. What is the standard deviation?\",\n \"subject\": \"high_school_statistics\",\n \"choices\": [\n \"$6,984 \",\n \"$10,356 \",\n \"$10,476 \",\n \"$13,968 \"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"What is the communal meal offered at the place of worship called in Sikhism?\",\n \"subject\": \"world_religions\",\n \"choices\": [\n \"Sangat\",\n \"Langar\",\n \"Gurdwara\",\n \"Panth\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"For which of these two scenarios does the main character (who uses I/me/my) do something clearly morally wrong, according to ordinary moral standards in the US as of 2020? Scenario 1 | I knew my overweight teacher was dieting, so I offered her a big sundae. Scenario 2 | I found a wallet in the park and became its new owner.\",\n \"subject\": \"moral_scenarios\",\n \"choices\": [\n \"Wrong, Wrong\",\n \"Wrong, Not wrong\",\n \"Not wrong, Wrong\",\n \"Not wrong, Not wrong\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"A state law imposes penalties for \\\"any public statement containing false or misleading information about a service or product.\\\" An airline falsely claimed in an advertisement that its competitor had an inferior safety record. The claim was based on erroneous information, found on the website of a nonprofit consumer advocacy group, that the airline assumed to be true. The airline was charged under the state law for making a false statement. No federal statute applies. Which of the following best supports the airline in a defense based on the First Amendment?\",\n \"subject\": \"professional_law\",\n \"choices\": [\n \"Its statement about the safety record was made without malice.\",\n \"Its statement about the safety record was protected noncommercial speech.\",\n \"The state law is a prior restraint.\",\n \"The state law is overbroad.\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"When Berger & Luckmann said that reality is socially constructed, they meant:\",\n \"subject\": \"sociology\",\n \"choices\": [\n \"scientists are guided in their work by social values and interests, so they define and measure phenomena that will support their theories\",\n \"people negotiate shared definitions of their situation and live according to these, often forgetting that these social worlds are not fixed and external\",\n \"sociologists decide what constitutes social reality and measure only that\",\n \"terms like 'reality' have no deeper meaning beyond the level of discourse\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"If c > 0 and f(x) = e^x - cx for all real numbers x, then the minimum value of f is\",\n \"subject\": \"college_mathematics\",\n \"choices\": [\n \"f(c)\",\n \"f(e^c)\",\n \"f(1/c)\",\n \"f(log c)\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"These factors increase risk of osteoporotic fracture:\",\n \"subject\": \"nutrition\",\n \"choices\": [\n \"High bone mineral density\",\n \"High body weight\",\n \"High lean mass\",\n \"Poor muscle strength\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"To prevent desiccation and injury, the embryos of terrestrial vertebrates are encased within a fluid secreted by the\",\n \"subject\": \"college_biology\",\n \"choices\": [\n \"amnion\",\n \"chorion\",\n \"allantois\",\n \"yolk sac\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"Let A be a finite set with m elements, and let B be a finite set with n elements. The number of distinct functions mapping A into B is\",\n \"subject\": \"college_computer_science\",\n \"choices\": [\n \"n^m\",\n \"n!/(n - m)!\",\n \"n!\",\n \"n!/(m!(n - m)!)\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"A disk of radius 0.1 m initially at rest undergoes an angular acceleration of 2.0 rad/s^2. If the disk only rotates, find the total distance traveled by a point on the rim of the disk in 4.0 s.\",\n \"subject\": \"high_school_physics\",\n \"choices\": [\n \"0.4 m\",\n \"0.8 m\",\n \"1.2 m\",\n \"1.6 m\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"Identify the only construct that is not pertinent to developmental models on intelligence:\",\n \"subject\": \"professional_psychology\",\n \"choices\": [\n \"Investment theory\",\n \"The positive manifold\",\n \"G theory\",\n \"Primary mental ability theory\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"Which of the following statements does NOT accurately describe voting behavior in the United States?\",\n \"subject\": \"high_school_government_and_politics\",\n \"choices\": [\n \"Registered voters between the ages of 35 and 45 are more likely to vote than are those under the age of 21.\",\n \"A registered voter who has attained his or her General Educational Development (GED) is less likely to vote than a high school dropout.\",\n \"Registered voters are more likely to vote in general elections than they are in primary elections.\",\n \"More women than men have voted in every presidential election since 1980.\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"For which of these two scenarios does the main character (who uses I/me/my) do something clearly morally wrong, according to ordinary moral standards in the US as of 2020? Scenario 1 | When I checked out from the hotel I turned in the dirty towels. Scenario 2 | I always kept my whiskey bottles out of reach of my 3-year-old son.\",\n \"subject\": \"moral_scenarios\",\n \"choices\": [\n \"Wrong, Wrong\",\n \"Wrong, Not wrong\",\n \"Not wrong, Wrong\",\n \"Not wrong, Not wrong\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"A state imposes a graduated income tax upon net income calculated under federal law. Section 22 of the city's reform act of 2010, which is to become effective on January 1, 2010, provides: \\\"Any parent or guardian financially responsible for the education of his ward may claim a direct tax credit against his income tax liability equal to the amount of tuition of a child or children of high school age who does not attend a public high school. \\\" Other provisions define \\\"tuition\\\" very broadly but limit the credit to tuition paid to schools meeting the educational requirements as determined by the state. On December 1, 2009, the parents of two students who attend a public high school in the state sue for a declaratory judgment and injunction in federal court, claiming that Section 22 violates the establishment clause of the First Amendment. The federal court will most likely\",\n \"subject\": \"professional_law\",\n \"choices\": [\n \"dismiss the action, because the suit involves a political question.\",\n \"dismiss the action, because the plaintiffs lack standing as taxpayers.\",\n \"dismiss the action, because the issues are not ripe.\",\n \"dismiss the action, because the issues being litigated are moot.\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"A member of the president's cabinet is said to have \\\"gone native\\\" when that cabinet member\",\n \"subject\": \"high_school_government_and_politics\",\n \"choices\": [\n \"resigns to take a position as a consultant to lobbying groups\",\n \"cedes control of his or her department to lifelong bureaucrats within the department\",\n \"places his or her department's priorities above the president's\",\n \"accepts bribes or expensive favors from businesses regulated by his or her department\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"Order the following (risk, return) pairs from least to most favourable, assuming the perspective of a rational and risk-averse investor: (2,2),(2,3) and (4,2). Risk is measured in standard deviations and return in percentage. HINT: Imagine a scatter diagram with standard deviation on the x-axis and return on the y-axis.\",\n \"subject\": \"professional_accounting\",\n \"choices\": [\n \"(4,2),(2,2),(2,3)\",\n \"(2,2),(2,3),(4,2)\",\n \"(2,2),(4,2),(2,3)\",\n \"(2,3),(2,2),(4,2)\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"What is the main reason why many Critical Race Theorists are hostile to concepts such as 'justice', 'neutrality', and 'truth'?\",\n \"subject\": \"jurisprudence\",\n \"choices\": [\n \"Because of their vagueness.\",\n \"Because they have failed to produce racial justice.\",\n \"Because they are unrelated to contemporary conditions.\",\n \"Because these ideas are alien to most people of colour.\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"What is personal (ratione personae) immunity?\",\n \"subject\": \"international_law\",\n \"choices\": [\n \"Personal immunity is afforded to all physical persons\",\n \"Personal immunity is that which is afforded in a personal capacity and hence does not cover conduct of the State as such\",\n \"Personal immunity is afforded only to particular persons irrespective if their conduct was undertaken in a private or public capacity\",\n \"Personal immunity is afforded to State officials for conduct undertaken in a public capacity\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"Who is an 'injured State' in the law of international responsibility?\",\n \"subject\": \"international_law\",\n \"choices\": [\n \"A State is 'injured' in case that it has suffered a damage from the internationally wrongful conduct\",\n \"A State is 'injured' in cases that there has been a violation of a peremptory norm of international law\",\n \"A State is 'injured' should it acknowledge the existence of the internationally wrongful conduct\",\n \"A State is 'injured' if the obligation breached was owed to it individually or if it was owed to a group of States, including that State, and it was specially affected\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"A national association brought suit in federal court against a city. The suit charged the city with violating several federal statutes. During the trial, the association's attorney called the city attorney as an adverse witness. The city attorney asserted the attorney-client privilege and objected that the matters communicated to him were intended to be confidential. The issues raised by the objections of the city attorney should be resolved under\",\n \"subject\": \"professional_law\",\n \"choices\": [\n \"federal privilege law.\",\n \"the privilege law of the forum state.\",\n \"either federal privilege law or the privilege law of the forum state as determined by the court.\",\n \"either federal privilege law or the privilege law of the forum state, whichever the court determines is more likely to admit the evidence.\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"There are three main types of buying situations in an organization, referred to by Robinson, Faris, and Wind (1967) as _____________.\",\n \"subject\": \"marketing\",\n \"choices\": [\n \"Repeat purchases.\",\n \"Buyphases.\",\n \"Buyclasses.\",\n \"Tenders.\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"For which of these two scenarios does the main character (who uses I/me/my) do something clearly morally wrong, according to ordinary moral standards in the US as of 2020? Scenario 1 | My mom asked me to deep clean the bath so I covered it in bleach. Scenario 2 | For the funeral, I wore my clown costume to honor the dead.\",\n \"subject\": \"moral_scenarios\",\n \"choices\": [\n \"Wrong, Wrong\",\n \"Wrong, Not wrong\",\n \"Not wrong, Wrong\",\n \"Not wrong, Not wrong\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"A ________ campaign occurs when people from two or more opposing sides of an argument have emotional convictions about a decision that has the power to impact their lives.\",\n \"subject\": \"public_relations\",\n \"choices\": [\n \"public relations\",\n \"public issues\",\n \"crisis management\",\n \"consumer relations\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"One afternoon a motorist was driving her car when she struck a pedestrian who entered the intersection. The pedestrian was seriously injured in the accident and sued the motorist to recover damages for personal injuries. There were no witnesses to the accident. The motorist claims that the traffic light was green at the time she entered the intersection. The pedestrian now has amnesia and cannot remember how the accident occurred. At trial, the pedestrian's attorney calls a witness to testify. The witness proposes to testify that she was in the emergency room at the hospital when the pedestrian was brought in following the accident. The witness further testifies that while the pedestrian was being treated for his injuries, the nurse asked him, \\\"How did you get hurt?\\\" The pedestrian replied, \\\"The car ran the red light and struck me as I was walking through the intersection. \\\"Upon objection, this evidence is\",\n \"subject\": \"professional_law\",\n \"choices\": [\n \"admissible as a statement made for purposes of medical treatment and diagnosis.\",\n \"admissible as a present sense impression.\",\n \"inadmissible, because the witness was eavesdropping on a confidential communication between the pedestrian and a hospital representative.\",\n \"inadmissible, because it is hearsay not within any recognized exception.\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"Which of the following samples would be considered most representative of male college students?\",\n \"subject\": \"high_school_psychology\",\n \"choices\": [\n \"A group of thirty fraternity brothers from Penn State\",\n \"A random sample taken between classes in the business wing of various universities\",\n \"Sixty male members of each class from Princeton, Yale, Harvard, Dartmouth, and Columbia\",\n \"Twenty male members of each class from a cross-section of colleges and universities\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"Which statement below is the least likely to follow logically from Dworkin's notion of law as integrity?\",\n \"subject\": \"jurisprudence\",\n \"choices\": [\n \"It is likely to generate more individual rights and greater liberty.\",\n \"It renders a community more genuine.\",\n \"It opens the door to authoritarianism.\",\n \"It improves the moral justification for the exercise of political power.\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"X-chromosome inactivation\",\n \"subject\": \"medical_genetics\",\n \"choices\": [\n \"results in genetically turning off one of the two X chromosomes in female mammals\",\n \"takes place in humans so that the same X chromosome is inactive in all of the cells of a female\",\n \"is the cause of the Y chromosome being genetically inactive\",\n \"occurs in fruit flies but not in mammals\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"In the fetus, the ductus arteriosus passes blood from the\",\n \"subject\": \"anatomy\",\n \"choices\": [\n \"pulmonary vein to the aorta.\",\n \"aorta to pulmonary vein.\",\n \"pulmonary artery to the aorta.\",\n \"aorta to the pulmonary artery.\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"The follicular phase is to the __________ as the luteal phase is to the secretory phase.\",\n \"subject\": \"human_sexuality\",\n \"choices\": [\n \"postovulatory\",\n \"menstrual\",\n \"proliferative\",\n \"myometrial\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"Buffer-overflow may remain as a bug in apps if __________ are not done fully.\",\n \"subject\": \"computer_security\",\n \"choices\": [\n \"boundary hacks\",\n \"memory checks\",\n \"boundary checks\",\n \"buffer checks\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"Let T be a depth-first search tree of a connected undirected graph G. For each vertex v of T, let pre(v) be the number of nodes visited up to and including v during a preorder traversal of T, and post(v) be the number of nodes visited up to and including v during a postorder traversal of T. The lowest common ancestor of vertices u and v in T is a vertex w of T such that w is an ancestor of both u and v, and no child of w is an ancestor of both u and v. Let (u, v) be an edge in G that is not in T, such that pre(u) < pre(v). Which of the following statements about u and v must be true?\\nI. post(u) < post(v)\\nII. u is an ancestor of v in T.\\nIII. If w is the lowest common ancestor of u and v in T, then w = u.\",\n \"subject\": \"college_computer_science\",\n \"choices\": [\n \"I only\",\n \"II only\",\n \"III only\",\n \"II and III\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"This question refers to the following information.\\nEvery two months His Majesty sends from Lima 60,000 pesos to pay for the mita of the Indians. Up on the Huanacavelica range there are 3,000 or 4,000 Indians working in the mercury mine, with picks and hammers, breaking up the ore. And when they have filled up their little sacks, the poor fellows, loaded down, climb up those ladders and rigging, so distressing that a man can hardly get up them. That is the way they work in this mine, with many lights and the loud noise of the pounding and great confusion. Nor is that the greatest evil; that is due to thievish and undisciplined superintendents. According to His Majesty's warrant, the mine owners at Potosí have a right to the mita of 13,300 Indians. These mita Indians earn each day 4 reals. Besides these there are others not under obligation, who hire themselves out voluntarily: these each get from 12 to 16 reals, and some up to 24, according to how well they wield their picks or their reputation for knowing how to get the ore out.\\nAntonio Vasquez de Espinosa, report on mining in Huanacavelica and Potosí, 1620s\\nThe third principal reason the local Yakut and Tungus natives are ruined is that from the time they first came under Russian control, they have been forced to pay yasak tribute. Some have paid in sables, others in red foxes, still others in cash. At first there were plenty of furbearing animals there, but now there are no sables and not many foxes in those lands, from the shores of the Arctic Ocean all the way south to the great Lena River. Moreover, almost half the natives cannot hunt because they no longer have horses, many of which have been pawned to the yasak collectors.\\nHeinrich von Füch, \\\"On the Treatment of Natives in Northeast Siberia,\\\" 1744\\nBoth passages are best seen in the context of which of the following broad developments?\",\n \"subject\": \"high_school_world_history\",\n \"choices\": [\n \"Emerging systems of coerced labor\",\n \"The expansion of chattel slavery\",\n \"Increased reliance on prison-camp workforces\",\n \"Colonization of overseas territories by joint-stock companies\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"A soccer team has $90.00 to buy soccer balls. If one soccer ball costs $15.60, what is the greatest number of soccer balls the team can buy?\",\n \"subject\": \"elementary_mathematics\",\n \"choices\": [\n \"4\",\n \"5\",\n \"6\",\n \"7\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"Current estimates of how many people exercise on a regular basis suggest that _____ do\",\n \"subject\": \"human_aging\",\n \"choices\": [\n \"Less than 50%\",\n \"More than 75%\",\n \"Less than 25%\",\n \"More than 50%\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"An object carries a charge of –1 C. How many excess electrons does it contain?\",\n \"subject\": \"high_school_physics\",\n \"choices\": [\n \"6.25 × 10^18\",\n \"8.00 × 10^18\",\n \"1.60 × 10^19\",\n \"3.20 × 10^19\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"According to Socrates, it is important that we discover what makes a particular action (e.g., a merciful or just act) the kind of action that it is, because without such knowledge:\",\n \"subject\": \"philosophy\",\n \"choices\": [\n \"no one in society will ever do any action that really is merciful or just, only those actions that they think are merciful or just.\",\n \"the primary purpose of human existence--which is to think and to know--is replaced by a focus on morality (acting and doing).\",\n \"we can refer only to how people characterize actions without knowing why such actions should be characterized that way.\",\n \"there would be no way to distinguish one kind of action (e.g., a merciful action) from another kind of action (e.g., a just action).\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"A woman leased a condo from the owner for a period of one year. After six months, the owner gave the woman a written option to purchase the condo for $100,000 before the expiration of the lease. With the owner's approval, the woman spent $10,000 to have the kitchen remodeled to her personal specifications. One month before the end of the lease, the owner notified the woman that he was revoking the option to purchase the condo. One week later, the woman delivered a written notice of acceptance of the option, but the owner refused to sell. If the woman initiates suit for breach of contract, which of the following is her strongest argument that an enforceable contract was formed between her and the owner?\",\n \"subject\": \"professional_law\",\n \"choices\": [\n \"Because the woman had until the expiration of the lease to accept the offer, the owner's revocation would be ineffective.\",\n \"Because the owner was a merchant, the written offer was irrevocable for a period not exceeding three months.\",\n \"Because the owner's offer invited a return promise as acceptance, the woman manifested her intent to accept by remodeling the kitchen.\",\n \"After the woman paid to have the kitchen remodeled, an option contract resulted, because the owner knew the woman was relying on the offer to her detriment.\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"What does the presence of discouraged workers do to the measurement of the unemployment rate?\",\n \"subject\": \"high_school_macroeconomics\",\n \"choices\": [\n \"Discouraged workers are counted as \\\"out of the labor force\\\" thus the unemployment rate is understated making the economy look stronger than it is.\",\n \"Discouraged workers are counted as \\\"out of the labor force\\\" thus the unemployment rate is understated making the economy look weaker than it is.\",\n \"Discouraged workers are not surveyed so there is no impact on the unemployment rate.\",\n \"Discouraged workers are counted as \\\"unemployed\\\" thus the unemployment rate is understated making the economy look stronger than it is.\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"In the film 'The Talented Mr Ripley' who plays Mr Ripley?\",\n \"subject\": \"miscellaneous\",\n \"choices\": [\n \"Jude Law\",\n \"Matt Damon\",\n \"Dustin Hoffman\",\n \"Ben Affleck\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"Which of the following allows gas exchange in the lungs?\",\n \"subject\": \"anatomy\",\n \"choices\": [\n \"Alveoli\",\n \"Bronchi\",\n \"Bronchioles\",\n \"Capillaries\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"Anscombe criticizes as absurd Kant’s idea of:\",\n \"subject\": \"philosophy\",\n \"choices\": [\n \"the thing in itself.\",\n \"the categorical imperative.\",\n \"the phenomenal self.\",\n \"legislating for oneself.\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"Select the best translation into predicate logic. Some firefighters rescue victims from danger. (Dx: x is danger; Fx: x is a firefighter; Vx: x is a victim; Rxyz: x rescues y from z)\",\n \"subject\": \"formal_logic\",\n \"choices\": [\n \"(∃x){Fx • (∀y)[Dy ⊃ (∃z)(Vz • Rxyz)]}\",\n \"(∃x){Fx • (∃y)[Vy • (∃z)(Dz • Rxyz)]}\",\n \"(∃x){Fx • (∃y)(∃z)[(Vy • Dz) • Rxzy]}\",\n \"(∀x){Fx ⊃ (∃y)[Vy . (∃z)(Dz • Rxyz)]}\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"During a clinical study examining the effects of exercise, men between the ages of 20 and 30 years are evaluated during a 15- minute session on a treadmill. The average pulse for the last 2 minutes of the session is 175/min. During the last minute of exercise, various measurements are taken. Compared with the measurement before the session, which of the following is most likely to be decreased?\",\n \"subject\": \"professional_medicine\",\n \"choices\": [\n \"Pulse pressure\",\n \"Stroke volume\",\n \"Systolic blood pressure\",\n \"Total peripheral resistance\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"Which of the following was described as “the slow agency of existing causes”?\",\n \"subject\": \"prehistory\",\n \"choices\": [\n \"natural selection\",\n \"catastrophism\",\n \"uniformitarianism\",\n \"unilineal evolution\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"A car gets 24 miles per gallon of gasoline (mi/gal). How many gallons of gasoline would the car need to travel 144 miles?\",\n \"subject\": \"elementary_mathematics\",\n \"choices\": [\n \"6.5 gallons\",\n \"6 gallons\",\n \"5.5 gallons\",\n \"5 gallons\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"A school psychologist is providing feedback to a student's parents regarding the student's performance on a measure of academic achievement. To explain the concept of grade equivalent, the school psychologist should explain that it is\",\n \"subject\": \"high_school_psychology\",\n \"choices\": [\n \"the average score on that measure obtained by students in a given grade\",\n \"the average score on that measure obtained by students at a given age\",\n \"the grade in which a student should be placed in school\",\n \"utilized to determine accountability among peers\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"Global and regional international trade agreements work by using which of the following mechanisms?\",\n \"subject\": \"us_foreign_policy\",\n \"choices\": [\n \"Reciprocity across multiple issues\",\n \"Reputational concerns of the actors\",\n \"Side payments for adjusting to the organization (such as the Common Agricultural Policy in the EU)\",\n \"ALL of the above\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"When did Mohenjo-daro develop into a complex urban center?\",\n \"subject\": \"prehistory\",\n \"choices\": [\n \"during the Early Shang Dynasty, from 1,000 to 400 B.P.\",\n \"during the Qin Dynasty, from 3,500 to 3,000 B.P.\",\n \"during the Mature Harappan period, from 4,500 to 4,000 B.P.\",\n \"during the Early Harappan period, from 8,500 to 6,000 B.P.\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"The Traditional Religion Advocacy Party (TRAP) has successfully lobbied the State of Texarkana for a statute named \\\"Equal Rights for All Religions.\\\" The law requires broadcasters that air segments discussing Christianity to allow equal time for segments on Judaism, Islam, Hinduism, and Buddhism. The American Atheism Association (AAA) has put together a broadcast segment about atheism, rejecting all religions, but four of the five Texarkana stations have declined to air the segment because they believe it would violate the statute. AAA has filed suit against the state, challenging the constitutionality of the statute. What is the strongest argument AAA can make in support of striking down the Equal Rights for All Religions statute?\",\n \"subject\": \"professional_law\",\n \"choices\": [\n \"The First Amendment prohibits government interference with freedom of the press.\",\n \"The fact that the statute involves only broadcast media and not print media is an Equal Protection violation.\",\n \"The First Amendment prohibits government interference with the free exercise of religion.\",\n \"The statute is not narrowly tailored to promote a compelling governmental interest.\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"Adaptive thermogenesis refers to:\",\n \"subject\": \"nutrition\",\n \"choices\": [\n \"A decrease in heat loss when exposed to cold\",\n \"A decrease in non-shivering thermogenesis when exposed to cold\",\n \"An increase in basal metabolic rate that is not fully explained by a change in body composition during chronic overfeeding\",\n \"A decrease in spontaneous physical activity during chronic overfeeding.\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"In all of her relationships Helen is typically uncomfortable feeling close to another person or having that person feel close to her. According to attachment theory Helen would best be described as:\",\n \"subject\": \"human_sexuality\",\n \"choices\": [\n \"a secure lover\",\n \"an avoidant lover\",\n \"an anxious-ambivalent lover\",\n \"a passionate lover\"\n ],\n \"answer\": 1\n },\n {\n \"question\": \"In primates, the location of which of the following determines if it is a quadruped or biped?\",\n \"subject\": \"prehistory\",\n \"choices\": [\n \"the feet\",\n \"the skull\",\n \"the foramen magnum\",\n \"the ulna\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"What is the meaning of collective security?\",\n \"subject\": \"international_law\",\n \"choices\": [\n \"The right to self-defence by more than one nation acting in concert\",\n \"The right of one's allies to defend the victim State\",\n \"The authorisation of armed force by the UN Security Council\",\n \"The authorisation of peacekeeping missions by the UN General Assembly\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"In the comic strip 'Peanuts' what is Schroeder known for doing?\",\n \"subject\": \"miscellaneous\",\n \"choices\": [\n \"Dancing\",\n \"playing football\",\n \"playing the piano\",\n \"Flying an imaginary plane\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"A writer's latest novel created a debate among critics regarding whether the sexual references and the graphic practices in the book made it obscene. While the publisher was readying the book for distribution, the head of a state commission for morality contacted her to tell her that the book was obscene and that she should collect all copies and turn them over for seizure by the government. He also advised that the commission was putting the book on a list of obscene works that retailers should not handle. She responded that dozens of retailers already had the book for an opening day promotion. The commission seized all of the books from the retailers and destroyed them, without any due process procedural safeguards to the author or the publisher. The author and publisher appealed the case and eventually received a writ of certiorari issued by the U.S. Supreme Court. Will the Court uphold the procedure that was used to declare the book obscene and to restrain its distribution?\",\n \"subject\": \"professional_law\",\n \"choices\": [\n \"Yes, if the authorities determine the book to be obscene, then they may seize and prevent its prospective distribution for the protection of the public.\",\n \"Yes, the determination of obscenity can be made prior to publication because the local authorities have a right to determine the local \\\"community morals\\\" standard.\",\n \"No, the state must first give the publisher and author a preliminary hearing before a magistrate to get a determination if the book is obscene.\",\n \"No, the state cannot exercise prior restraint over published material because that has a chilling effect on free speech; a full judicial determination, with a criminal trial, is required before there can be a finding of a work being obscene.\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"This question refers to the following information.\\n\\\"But you, my dear Pangloss,\\\" said Candide, \\\"how can it be that I behold you again?\\\"\\n\\\"It is true,\\\" said Pangloss, \\\"that you saw me hanged&….A surgeon purchased my body, carried home, and dissected me. He began with making a crucial incision on me from the navel to the clavicula. One could not have been worse hanged than I was. The executioner of the Holy Inquisition was a sub-deacon, and knew how to burn people marvellously well, but he was not accustomed to hanging. The cord was wet and did not slip properly, and besides it was badly tied; in short, I still drew my breath, when the crucial incision made me give such a frightful scream that my surgeon fell flat upon his back&…[At length he] sewed up my wounds; his wife even nursed me. I was upon my legs at the end of fifteen days&….\\nOne day I took it into my head to step into a mosque, where I saw an old Iman and a very pretty young devotee who was saying her paternosters&….She dropped her bouquet; I picked it up, and presented it to her with a profound reverence. I was so long in delivering it that the Iman began to get angry, and seeing that I was a Christian he called out for help. They carried me before the cadi, who ordered me a hundred lashes on the soles of the feet and sent me to the galleys. I was chained to the very same galley and the same bench as the young Baron. On board this galley there were four young men from Marseilles, five Neapolitan priests, and two monks from Corfu, who told us similar adventures happened daily. The Baron maintained that he had suffered greater injustice than I&….We were continually disputing, and received twenty lashes with a bull's pizzle when the concatenation of universal events brought you to our galley, and you were good enough to ransom us.\\\"\\n\\\"Well, my dear Pangloss,\\\" said Candide to him, \\\"when you had been hanged, dissected, whipped, and were tugging at the oar, did you always think that everything happens for the best?\\\"\\n\\\"I am still of my first opinion,\\\" answered Pangloss, \\\"for I am a philosopher and I cannot retract, especially as Leibnitz could never be wrong; and besides, the pre-established harmony is the finest thing in the world, and so is his plenum and materia subtilis.\\\"\\nVoltaire, French Enlightenment writer, Candide, 1759\\nThe themes of the passage and the mode in which Pangloss tells them show the influence of\",\n \"subject\": \"high_school_european_history\",\n \"choices\": [\n \"Medievalism\",\n \"Empiricism\",\n \"Rationalism\",\n \"Romanticism\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"Which of the following is the symplastic pathway for the movement of sucrose from the site of photosynthesis in mesophyll cells into the phloem?\",\n \"subject\": \"college_biology\",\n \"choices\": [\n \"Fibers, phloem parenchyma, companion cell, sieve tube\",\n \"Phloem parenchyma, fibers, bundle sheath, tracheids\",\n \"Companion cells, phloem parenchyma, fibers, sieve tube\",\n \"Bundle sheath, phloem parenchyma, companion cell, sieve tube\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"A 45-year-old man comes to the physician because of right shoulder pain that began after he chopped wood 2 days ago. Examination of the right upper extremity shows no obvious bone deformities or point tenderness. The pain is reproduced when the patient is asked to externally rotate the shoulder against resistance; there is no weakness. In addition to the teres minor, inflammation of which of the following tendons is most likely in this patient?\",\n \"subject\": \"professional_medicine\",\n \"choices\": [\n \"Infraspinatus\",\n \"Pectoralis\",\n \"Subscapularis\",\n \"Supraspinatus\"\n ],\n \"answer\": 0\n },\n {\n \"question\": \"Use the following key to translate the given formula of PL to natural, English sentences.\\nA: Marina reads a Percy Jackson book.\\nB: Izzy plays Minecraft.\\nC: Emily stops working.\\nD: Russell makes dinner.\\nE: Ashleigh stops by.\\n~C ∨ D\",\n \"subject\": \"formal_logic\",\n \"choices\": [\n \"If Emily doesn't stop working then Russell makes dinner.\",\n \"Emily stops working unless Russell makes dinner.\",\n \"Emily stops working unless Russell doesn't make dinner.\",\n \"Emily doesn't stop working unless Russell makes dinner.\"\n ],\n \"answer\": 3\n },\n {\n \"question\": \"The weight percent of sodium hydroxide dissolved in water is 50%. What is the mole fraction of sodium hydroxide?\",\n \"subject\": \"high_school_chemistry\",\n \"choices\": [\n \"31.00%\",\n \"0.164\",\n \"0.311\",\n \"0.5\"\n ],\n \"answer\": 2\n },\n {\n \"question\": \"In a certain region, the electric field varies with the radius away from origin by the equation Er = –6r^2 + 4r + 3, where r is given in meters and E in N/C. The potential difference between the origin and the point (3, 4) is\",\n \"subject\": \"high_school_physics\",\n \"choices\": [\n \"–165 V\",\n \"–120 V\",\n \"64 V\",\n \"185 V\"\n ],\n \"answer\": 3\n }\n] as const satisfies readonly MMLUItem[];\n","/**\n * STS Benchmark subset — the first 100 pairs of the STS-B test split\n * (semantic textual similarity; human scores 0-5). Source:\n * https://huggingface.co/datasets/mteb/stsbenchmark-sts (test split).\n *\n * LICENSE: CC BY-SA 4.0 (share-alike). This file and any redistribution of the\n * pairs below remain under CC BY-SA 4.0 — see LICENSE-CC-BY-SA.md in this\n * directory. Kept isolated from the MIT-licensed code and datasets on purpose.\n *\n * Used by the embedding quality lane: Spearman correlation of cosine\n * similarities against the human scores.\n */\n\n/** One sentence pair with its human similarity score (0-5). */\nexport interface STSPair {\n s1: string;\n s2: string;\n score: number;\n}\n\n/** 100-pair STS-B test subset (order preserved from the source dataset). */\nexport const STSB_SUBSET: readonly STSPair[] = [\n {\n \"s1\": \"A girl is styling her hair.\",\n \"s2\": \"A girl is brushing her hair.\",\n \"score\": 2.5\n },\n {\n \"s1\": \"A group of men play soccer on the beach.\",\n \"s2\": \"A group of boys are playing soccer on the beach.\",\n \"score\": 3.6\n },\n {\n \"s1\": \"One woman is measuring another woman's ankle.\",\n \"s2\": \"A woman measures another woman's ankle.\",\n \"score\": 5.0\n },\n {\n \"s1\": \"A man is cutting up a cucumber.\",\n \"s2\": \"A man is slicing a cucumber.\",\n \"score\": 4.2\n },\n {\n \"s1\": \"A man is playing a harp.\",\n \"s2\": \"A man is playing a keyboard.\",\n \"score\": 1.5\n },\n {\n \"s1\": \"A woman is cutting onions.\",\n \"s2\": \"A woman is cutting tofu.\",\n \"score\": 1.8\n },\n {\n \"s1\": \"A man is riding an electric bicycle.\",\n \"s2\": \"A man is riding a bicycle.\",\n \"score\": 3.5\n },\n {\n \"s1\": \"A man is playing the drums.\",\n \"s2\": \"A man is playing the guitar.\",\n \"score\": 2.2\n },\n {\n \"s1\": \"A man is playing guitar.\",\n \"s2\": \"A lady is playing the guitar.\",\n \"score\": 2.2\n },\n {\n \"s1\": \"A man is playing a guitar.\",\n \"s2\": \"A man is playing a trumpet.\",\n \"score\": 1.714\n },\n {\n \"s1\": \"A man is playing a guitar.\",\n \"s2\": \"A man is playing a trumpet.\",\n \"score\": 1.714\n },\n {\n \"s1\": \"A man is cutting an onion.\",\n \"s2\": \"A man cuts an onion.\",\n \"score\": 5.0\n },\n {\n \"s1\": \"A man is cycling.\",\n \"s2\": \"A man is talking.\",\n \"score\": 0.6\n },\n {\n \"s1\": \"A man is slicing open a fish.\",\n \"s2\": \"A man is cutting up a fish.\",\n \"score\": 4.4\n },\n {\n \"s1\": \"A man is slicing a tomato.\",\n \"s2\": \"A man is slicing a bun.\",\n \"score\": 2.0\n },\n {\n \"s1\": \"A man is playing a guitar.\",\n \"s2\": \"A man is playing a keyboard.\",\n \"score\": 1.8\n },\n {\n \"s1\": \"A baby panda goes down a slide.\",\n \"s2\": \"A panda slides down a slide.\",\n \"score\": 4.4\n },\n {\n \"s1\": \"A man is singing and playing a guitar.\",\n \"s2\": \"A man is playing a guitar.\",\n \"score\": 3.6\n },\n {\n \"s1\": \"A man attacks a woman.\",\n \"s2\": \"A man slaps a woman.\",\n \"score\": 3.6\n },\n {\n \"s1\": \"A man is driving a car.\",\n \"s2\": \"A man is riding a horse.\",\n \"score\": 1.2\n },\n {\n \"s1\": \"A woman is cutting tofu.\",\n \"s2\": \"A woman is cutting an onion.\",\n \"score\": 2.4\n },\n {\n \"s1\": \"The woman is styling her hair.\",\n \"s2\": \"The woman is slicing herbs.\",\n \"score\": 0.2\n },\n {\n \"s1\": \"Two zebras play in an open field.\",\n \"s2\": \"Two zebras are playing in a field.\",\n \"score\": 4.2\n },\n {\n \"s1\": \"A man is cutting a potato.\",\n \"s2\": \"A man is slicing some potato.\",\n \"score\": 4.4\n },\n {\n \"s1\": \"A man is slicing an onion.\",\n \"s2\": \"A woman is slicing a pumpkin.\",\n \"score\": 2.25\n },\n {\n \"s1\": \"A man is dancing.\",\n \"s2\": \"A man and woman is dancing.\",\n \"score\": 2.0\n },\n {\n \"s1\": \"A man is riding a motorcycle.\",\n \"s2\": \"A woman is riding a horse.\",\n \"score\": 0.75\n },\n {\n \"s1\": \"A woman is slicing garlics.\",\n \"s2\": \"A woman is slicing an onion.\",\n \"score\": 2.2\n },\n {\n \"s1\": \"A man is speaking.\",\n \"s2\": \"A man is cooking.\",\n \"score\": 0.8\n },\n {\n \"s1\": \"A little boy is singing and playing a guitar.\",\n \"s2\": \"A man is singing and playing the guitar.\",\n \"score\": 2.2\n },\n {\n \"s1\": \"A turtle is swimming in water.\",\n \"s2\": \"A turtle is walking underwater.\",\n \"score\": 3.2\n },\n {\n \"s1\": \"A young woman is putting stickers all over her face.\",\n \"s2\": \"A woman is applying stickers to her face.\",\n \"score\": 4.8\n },\n {\n \"s1\": \"A woman is wrapping tofu.\",\n \"s2\": \"A woman is balling dough.\",\n \"score\": 1.4\n },\n {\n \"s1\": \"A cat is eating some corn.\",\n \"s2\": \"A cat is eating corn on the cob.\",\n \"score\": 4.25\n },\n {\n \"s1\": \"A man is eating a food.\",\n \"s2\": \"A man is eating a piece of bread.\",\n \"score\": 3.4\n },\n {\n \"s1\": \"A man is playing a guitar.\",\n \"s2\": \"A man is eating pasta.\",\n \"score\": 0.533\n },\n {\n \"s1\": \"A man is kicking pots of water.\",\n \"s2\": \"A man is picking flowers.\",\n \"score\": 0.4\n },\n {\n \"s1\": \"A man is cutting a pipe with scissors.\",\n \"s2\": \"A man is cutting carpet with a knife.\",\n \"score\": 1.2\n },\n {\n \"s1\": \"A woman is dancing in the rain.\",\n \"s2\": \"A woman dances in the rain out side.\",\n \"score\": 5.0\n },\n {\n \"s1\": \"A woman is taking a bath.\",\n \"s2\": \"A woman is riding a horse.\",\n \"score\": 0.538\n },\n {\n \"s1\": \"A man mixes vegetables in a pot.\",\n \"s2\": \"A person is stirring vegetables in a pot.\",\n \"score\": 3.75\n },\n {\n \"s1\": \"A woman is talking on a cell phone.\",\n \"s2\": \"A man and woman are talking on the phone.\",\n \"score\": 3.0\n },\n {\n \"s1\": \"A man is playing a guitar.\",\n \"s2\": \"A man is singing while playing the guitar.\",\n \"score\": 3.6\n },\n {\n \"s1\": \"A man is playing a guitar.\",\n \"s2\": \"A man is driving a car.\",\n \"score\": 0.5\n },\n {\n \"s1\": \"A man is cutting apple by his hand.\",\n \"s2\": \"A man is cutting carpet with a knife.\",\n \"score\": 1.5\n },\n {\n \"s1\": \"A man is opening a door.\",\n \"s2\": \"A man is cutting an onion.\",\n \"score\": 0.8\n },\n {\n \"s1\": \"A man is slicing a tomato.\",\n \"s2\": \"A man is riding a horse.\",\n \"score\": 0.8\n },\n {\n \"s1\": \"A man is cutting paper with a sword.\",\n \"s2\": \"A woman is cutting a tomato.\",\n \"score\": 0.6\n },\n {\n \"s1\": \"A boy studies a calendar.\",\n \"s2\": \"A boy is looking at a calendar.\",\n \"score\": 4.4\n },\n {\n \"s1\": \"The ballerina is dancing.\",\n \"s2\": \"A man is dancing.\",\n \"score\": 1.75\n },\n {\n \"s1\": \"A woman is dancing.\",\n \"s2\": \"A woman is playing violin.\",\n \"score\": 0.4\n },\n {\n \"s1\": \"A woman is slicing some tomatoes.\",\n \"s2\": \"A woman is chopping a potato.\",\n \"score\": 1.4\n },\n {\n \"s1\": \"A woman is water skiing.\",\n \"s2\": \"A woman is slicing fish.\",\n \"score\": 0.4\n },\n {\n \"s1\": \"A man is playing a flute.\",\n \"s2\": \"A man is riding a scooter.\",\n \"score\": 0.8\n },\n {\n \"s1\": \"A man is playing the piano.\",\n \"s2\": \"A man played the guitar.\",\n \"score\": 2.0\n },\n {\n \"s1\": \"A woman is picking a can.\",\n \"s2\": \"A man is playing a guitar.\",\n \"score\": 0.133\n },\n {\n \"s1\": \"A man puts three pieces of meat into a pan.\",\n \"s2\": \"A man is putting meat in a pan.\",\n \"score\": 4.0\n },\n {\n \"s1\": \"A woman is cutting an onion.\",\n \"s2\": \"A woman is cleaning a garden.\",\n \"score\": 0.267\n },\n {\n \"s1\": \"Some men are sawing.\",\n \"s2\": \"Men are sawing logs.\",\n \"score\": 3.4\n },\n {\n \"s1\": \"A car is driven down the road.\",\n \"s2\": \"A girl is walking down a road.\",\n \"score\": 1.2\n },\n {\n \"s1\": \"The man is kissing and hugging the woman.\",\n \"s2\": \"A man is hugging and kissing a woman.\",\n \"score\": 5.0\n },\n {\n \"s1\": \"A train is moving.\",\n \"s2\": \"A man is doing yoga.\",\n \"score\": 0.0\n },\n {\n \"s1\": \"Someone is slicing an onion.\",\n \"s2\": \"A woman is cutting onion.\",\n \"score\": 3.8\n },\n {\n \"s1\": \"A woman is playing in the ocean.\",\n \"s2\": \"A woman is preparing shrimp to cook.\",\n \"score\": 0.75\n },\n {\n \"s1\": \"A person is playing an electronic keyboard.\",\n \"s2\": \"A kid is playing keyboard.\",\n \"score\": 3.4\n },\n {\n \"s1\": \"A man is holding a leaf.\",\n \"s2\": \"A monkey is fighting a man.\",\n \"score\": 0.0\n },\n {\n \"s1\": \"A woman is peeling shrimp.\",\n \"s2\": \"A man is squeezing water.\",\n \"score\": 0.2\n },\n {\n \"s1\": \"A man is sitting and smoking.\",\n \"s2\": \"A man is smoking a cigarette.\",\n \"score\": 4.0\n },\n {\n \"s1\": \"A man is playing a guitar.\",\n \"s2\": \"A woman is riding a horse.\",\n \"score\": 0.5\n },\n {\n \"s1\": \"A man is standing in front of the window and looking outside.\",\n \"s2\": \"A man is staring out the window.\",\n \"score\": 3.8\n },\n {\n \"s1\": \"A skunk is looking here and there.\",\n \"s2\": \"A skunk looks at the camera.\",\n \"score\": 2.4\n },\n {\n \"s1\": \"A man is playing the guitar and singing.\",\n \"s2\": \"A man sings with a guitar.\",\n \"score\": 4.75\n },\n {\n \"s1\": \"A woman opens a window.\",\n \"s2\": \"A man is crawling.\",\n \"score\": 0.0\n },\n {\n \"s1\": \"People are dancing outside.\",\n \"s2\": \"A group of people are dancing.\",\n \"score\": 3.75\n },\n {\n \"s1\": \"The man is using a camera to hammer a nail.\",\n \"s2\": \"Someone is banging a camera lense against a nail.\",\n \"score\": 2.6\n },\n {\n \"s1\": \"A woman is filing her nails.\",\n \"s2\": \"A man is peeling a carrot.\",\n \"score\": 0.0\n },\n {\n \"s1\": \"A boy is crawling into a dog house.\",\n \"s2\": \"A boy is playing a wooden flute.\",\n \"score\": 0.75\n },\n {\n \"s1\": \"A woman is swimming underwater.\",\n \"s2\": \"A man is slicing some carrots.\",\n \"score\": 0.0\n },\n {\n \"s1\": \"A machine is sharpening a pencil.\",\n \"s2\": \"The machine shaved the end of the pencil.\",\n \"score\": 3.8\n },\n {\n \"s1\": \"A monkey is playing drums.\",\n \"s2\": \"A gorilla plays the drums.\",\n \"score\": 2.8\n },\n {\n \"s1\": \"A man is opening a box and taking out paper.\",\n \"s2\": \"A woman is peeling a potato.\",\n \"score\": 0.0\n },\n {\n \"s1\": \"A woman is dancing.\",\n \"s2\": \"A woman plays the clarinet.\",\n \"score\": 0.8\n },\n {\n \"s1\": \"A person is drawing on a large touchscreen.\",\n \"s2\": \"A man is drawing on a digital dry erase board.\",\n \"score\": 3.0\n },\n {\n \"s1\": \"The men played follow the leader on the grass.\",\n \"s2\": \"The rhino grazed on the grass.\",\n \"score\": 1.0\n },\n {\n \"s1\": \"A woman is cracking eggs.\",\n \"s2\": \"A man is talking to a woman.\",\n \"score\": 0.0\n },\n {\n \"s1\": \"A woman peels garlic with her hands.\",\n \"s2\": \"The woman is slicing herbs.\",\n \"score\": 1.0\n },\n {\n \"s1\": \"The polar bears fought over the kill.\",\n \"s2\": \"Polar bears are fighting each other.\",\n \"score\": 3.4\n },\n {\n \"s1\": \"A man is doing trick with play cards.\",\n \"s2\": \"A man is performing a card trick.\",\n \"score\": 5.0\n },\n {\n \"s1\": \"The cat is licking a bottle.\",\n \"s2\": \"A cat plays with a small bottle.\",\n \"score\": 2.333\n },\n {\n \"s1\": \"A person is slicing an onion.\",\n \"s2\": \"A person cuts ginger.\",\n \"score\": 1.4\n },\n {\n \"s1\": \"A person is peeling a potato with a potato peeler.\",\n \"s2\": \"A man is cutting tomatoes with a cleaver.\",\n \"score\": 0.75\n },\n {\n \"s1\": \"Two women are dancing and singing in front of a crowd.\",\n \"s2\": \"The women are singing and dancing.\",\n \"score\": 3.538\n },\n {\n \"s1\": \"A man is seasoning some carrots.\",\n \"s2\": \"A woman is slicing garlic.\",\n \"score\": 0.8\n },\n {\n \"s1\": \"Two men pushed carts through the woods.\",\n \"s2\": \"Two men are pushing carts.\",\n \"score\": 3.5\n },\n {\n \"s1\": \"A man is playing a football.\",\n \"s2\": \"A man is maneuvering a soccer ball with his feet.\",\n \"score\": 2.0\n },\n {\n \"s1\": \"The lady peeled the potatoe.\",\n \"s2\": \"A woman is peeling a potato.\",\n \"score\": 4.75\n },\n {\n \"s1\": \"A woman is slicing some tofu.\",\n \"s2\": \"A woman is cutting a block of tofu into small cubes.\",\n \"score\": 4.0\n },\n {\n \"s1\": \"Someone typed on a keyboard.\",\n \"s2\": \"Someone is typing.\",\n \"score\": 4.5\n },\n {\n \"s1\": \"Three young men run, jump, and kick off of a Coke machine.\",\n \"s2\": \"Three men are jumping off a wall.\",\n \"score\": 1.5\n },\n {\n \"s1\": \"A young Asian girl is applying eyeliner.\",\n \"s2\": \"A girl is putting on eye makeup.\",\n \"score\": 2.4\n }\n];\n","/**\n * Quality-fidelity lane. Scores measure runtime/quantization fidelity of a\n * model build (do this runtime's weights + kernels reproduce expected answers),\n * NOT model capability — the bundled public sets are assumed to be in every\n * model's training data. Always run at temperature 0, outside timed regions.\n */\n\nimport type { QualityResult } from './types.js';\nimport type { BenchEmbeddingModel, BenchLanguageModel } from './adapter.js';\nimport { TINY_MMLU } from './datasets/tiny-mmlu.js';\nimport { STSB_SUBSET } from './datasets/stsb/stsb-subset.js';\nimport { spearman } from './stats.js';\nimport { abortDomException } from './timing.js';\n\nconst LETTERS = ['A', 'B', 'C', 'D'] as const;\n\n/**\n * Generation budget for MMLU items (part of the versioned protocol). Large\n * enough to absorb an empty Qwen3-style `<think></think>` block plus a\n * verbose \"The answer is B.\" — the v1 budget of 8 truncated before any\n * parseable letter on thinking-mode builds, scoring fidelity as 0.\n */\nexport const MMLU_MAX_TOKENS = 48;\n\n/** Cap on each stored raw output (auditability without payload bloat). */\nexport const MMLU_OUTPUT_CAP = 400;\n\n/** Fixed MCQ prompt template (part of the versioned protocol). */\nexport function formatMMLUPrompt(\n item: (typeof TINY_MMLU)[number],\n promptSuffix?: string,\n): string {\n const choices = item.choices.map((c, i) => `${LETTERS[i]}. ${c}`).join('\\n');\n return (\n `The following is a multiple choice question about ${item.subject.replace(/_/g, ' ')}.\\n\\n` +\n `${item.question}\\n${choices}\\n\\n` +\n `Answer with only the letter (A, B, C, or D) of the correct choice.${promptSuffix ?? ''}\\nAnswer:`\n );\n}\n\n/**\n * Remove reasoning blocks from a response. Closed `<think>...</think>` blocks\n * are dropped; an unterminated block drops the remainder (the answer never\n * surfaced within the generation budget).\n */\nfunction stripReasoning(response: string): string {\n const closed = response.replace(/<think>[\\s\\S]*?<\\/think>/gi, ' ');\n const open = closed.search(/<think>/i);\n return open === -1 ? closed : closed.slice(0, open);\n}\n\n/**\n * Parse the answer letter from a model response. Reasoning blocks are\n * stripped first; markdown emphasis around the letter is ignored. Accepts\n * \"B\", \"B.\", \"(B)\", \"**B**\", \"Answer: B\", \"Option C\", \"choice (B)\", or a\n * response beginning with the exact choice text. Letters are matched\n * case-sensitively after a keyword so the article \"a\" (\"the answer is a\n * bit unclear\") is never read as answer A; a lowercase letter counts only\n * when it is the whole reply or leads it as \"b.\" / \"b)\".\n *\n * @returns 0-3, or null when no unambiguous answer is present.\n */\nexport function parseMMLUAnswer(response: string, choices: readonly string[]): number | null {\n const trimmed = stripReasoning(response).trim();\n const emphasisFree = trimmed.replace(/[*`_]/g, '').trim();\n const keyed = emphasisFree.match(\n /(?:^|(?:[Aa]nswer|ANSWER)\\s*(?:is)?\\s*[:-]?\\s*|(?:[Oo]ption|OPTION|[Cc]hoice|CHOICE)\\s*[:-]?\\s*)\\(?([ABCD])\\)?(?=[\\s.,)!]|$)/,\n );\n if (keyed) return LETTERS.indexOf(keyed[1] as (typeof LETTERS)[number]);\n const leadingLower = emphasisFree.match(/^\\(?([abcd])(?:\\)|\\.|$)/);\n if (leadingLower) return LETTERS.indexOf(leadingLower[1].toUpperCase() as (typeof LETTERS)[number]);\n const lower = trimmed.toLowerCase();\n for (let i = 0; i < choices.length; i++) {\n if (lower.startsWith(choices[i].toLowerCase().slice(0, Math.max(8, choices[i].length)))) return i;\n }\n return null;\n}\n\n/**\n * Run the tinyMMLU fidelity task on a language model (temperature 0,\n * `MMLU_MAX_TOKENS` budget, greedy answer parsing). Unparseable answers count\n * as wrong; raw outputs and the parse rate are recorded so the score is\n * auditable and recomputable server-side.\n *\n * @param model - Any structurally-compatible LanguageModel.\n * @param items - Number of items from the 100-item set (25 or 100).\n * @returns Accuracy in [0,1] with per-item correctness details and outputs.\n */\nexport async function runMMLUFidelity(\n model: BenchLanguageModel,\n items: number,\n options?: {\n abortSignal?: AbortSignal;\n onProgress?: (done: number, total: number) => void;\n /** Appended to the instruction line of every item (from the model catalog). */\n promptSuffix?: string;\n },\n): Promise<QualityResult> {\n const subset = TINY_MMLU.slice(0, items);\n const details: number[] = [];\n const outputs: string[] = [];\n let correct = 0;\n let parsed = 0;\n for (let i = 0; i < subset.length; i++) {\n if (options?.abortSignal?.aborted) throw abortDomException();\n const item = subset[i];\n const result = await model.doGenerate({\n prompt: formatMMLUPrompt(item, options?.promptSuffix),\n maxTokens: MMLU_MAX_TOKENS,\n temperature: 0,\n abortSignal: options?.abortSignal,\n });\n // Score exactly the text that is stored: the server re-parses `outputs`\n // and rejects any disagreement, so client and server must see one string.\n const output = result.text.slice(0, MMLU_OUTPUT_CAP);\n const answer = parseMMLUAnswer(output, item.choices);\n if (answer !== null) parsed++;\n const ok = answer === item.answer ? 1 : 0;\n correct += ok;\n details.push(ok);\n outputs.push(output);\n options?.onProgress?.(i + 1, subset.length);\n }\n return {\n taskId: `tinymmlu-${items}`,\n score: subset.length === 0 ? 0 : correct / subset.length,\n n: subset.length,\n details,\n outputs,\n parseRate: subset.length === 0 ? 0 : parsed / subset.length,\n };\n}\n\n/** Cosine similarity of two vectors. */\nfunction cosine(a: Float32Array, b: Float32Array): number {\n let dot = 0;\n let na = 0;\n let nb = 0;\n for (let i = 0; i < a.length; i++) {\n dot += a[i] * b[i];\n na += a[i] * a[i];\n nb += b[i] * b[i];\n }\n const den = Math.sqrt(na) * Math.sqrt(nb);\n return den === 0 ? 0 : dot / den;\n}\n\n/**\n * Run the STS-B embedding-quality task: Spearman correlation of cosine\n * similarities against human scores over the bundled pair subset.\n *\n * @param model - Any structurally-compatible EmbeddingModel.\n * @param pairs - Number of pairs from the 100-pair set.\n * @returns Spearman rho with per-pair cosine details.\n */\nexport async function runSTSQuality(\n model: BenchEmbeddingModel,\n pairs: number,\n options?: { abortSignal?: AbortSignal; onProgress?: (done: number, total: number) => void },\n): Promise<QualityResult> {\n const subset = STSB_SUBSET.slice(0, pairs);\n const sims: number[] = [];\n const humanScores: number[] = [];\n for (let i = 0; i < subset.length; i++) {\n if (options?.abortSignal?.aborted) throw abortDomException();\n const pair = subset[i];\n const { embeddings } = await model.doEmbed({\n values: [pair.s1, pair.s2],\n abortSignal: options?.abortSignal,\n });\n sims.push(cosine(embeddings[0], embeddings[1]));\n humanScores.push(pair.score);\n options?.onProgress?.(i + 1, subset.length);\n }\n return {\n taskId: `stsb-${pairs}`,\n score: sims.length >= 2 ? spearman(sims, humanScores) : 0,\n n: subset.length,\n details: sims.map((s) => Math.round(s * 10_000) / 10_000),\n };\n}\n","/**\n * Validation: structural schema checks, deterministic summary recomputation\n * from raw traces (the same code runs client- and server-side), and versioned\n * plausibility/integrity checks for community submissions. Flags are attached,\n * never silently dropped — flagged runs are quarantined publicly.\n */\n\nimport type {\n BenchCellResult,\n BenchRunResult,\n CellSummary,\n EmbedIteration,\n LLMIteration,\n MetricSummary,\n PlausibilityFlag,\n ValidationReport,\n} from './types.js';\nimport { BENCH_PROTOCOL_VERSION, BENCH_SCHEMA_VERSION } from './types.js';\nimport { summarize } from './stats.js';\nimport { parseMMLUAnswer } from './quality.js';\nimport { TINY_MMLU } from './datasets/tiny-mmlu.js';\nimport { MIN_GENERATED_CHARS } from './protocol.js';\n\n/** Version of the plausibility rule set (recorded alongside moderation). */\nexport const PLAUSIBILITY_RULES_VERSION = 2;\n\n/**\n * Minimum fraction of the request that the visible chunk stream must span for\n * the trace to count as incremental. LiteRT-LM's web surface delivers every\n * chunk in a terminal burst (~0.8ms of a 30s request), so TTFT/decode derived\n * from such a trace are timing artifacts; a real token stream spans most of\n * the request by construction.\n */\nexport const STREAM_COHERENCE_MIN_SPAN_RATIO = 0.2;\n\n/** Decode-rate envelopes (chars/sec) per model-size class — deliberately loose. */\nconst DECODE_ENVELOPE_CHARS_PER_SEC: Array<{ maxBytes: number; max: number }> = [\n { maxBytes: 500_000_000, max: 4_000 },\n { maxBytes: 1_000_000_000, max: 2_500 },\n { maxBytes: 2_000_000_000, max: 1_500 },\n { maxBytes: Number.POSITIVE_INFINITY, max: 1_000 },\n];\n\n/** Max plausible embedding throughput (texts/sec) — loose upper bound. */\nconst EMBED_ENVELOPE_TEXTS_PER_SEC = 2_000;\n\n/** GPU-identity substrings that mean the \"GPU\" is a software or virtual renderer. */\nconst SOFTWARE_RENDERER_PATTERNS: readonly RegExp[] = [\n /swiftshader/i,\n /llvmpipe/i,\n /softpipe/i,\n /\\bwarp\\b/i,\n /microsoft basic render/i,\n /parallels/i,\n /vmware/i,\n /virtio/i,\n /virtualbox/i,\n];\n\n/**\n * Structural validation of a submitted result. Returns human-readable errors\n * (empty array = shape ok). Deliberately hand-rolled: this package is\n * zero-dependency and the checks double as executable schema documentation.\n */\nexport function validateRunShape(value: unknown): string[] {\n const errors: string[] = [];\n const push = (msg: string) => {\n if (errors.length < 50) errors.push(msg);\n };\n if (typeof value !== 'object' || value === null) return ['result must be an object'];\n const run = value as Record<string, unknown>;\n\n if (run.protocol !== BENCH_PROTOCOL_VERSION) push(`protocol must be \"${BENCH_PROTOCOL_VERSION}\"`);\n if (run.schemaVersion !== BENCH_SCHEMA_VERSION) push(`schemaVersion must be ${BENCH_SCHEMA_VERSION}`);\n if (typeof run.runId !== 'string' || run.runId.length < 8 || run.runId.length > 64) {\n push('runId must be a string (8-64 chars)');\n }\n if (typeof run.createdAt !== 'string' || Number.isNaN(Date.parse(run.createdAt as string))) {\n push('createdAt must be an ISO date string');\n }\n const harness = run.harness as Record<string, unknown> | undefined;\n if (!harness || typeof harness.name !== 'string' || typeof harness.version !== 'string') {\n push('harness {name, version} is required');\n }\n if (!['quick', 'standard', 'thorough', 'custom'].includes(run.suite as string)) {\n push('suite must be quick|standard|thorough|custom');\n }\n const env = run.environment as Record<string, unknown> | undefined;\n if (!env || typeof env !== 'object') push('environment is required');\n else {\n const browser = env.browser as Record<string, unknown> | undefined;\n if (!browser || typeof browser.name !== 'string') push('environment.browser.name is required');\n if (!env.os || typeof (env.os as Record<string, unknown>).platform !== 'string') {\n push('environment.os.platform is required');\n }\n }\n if (!Array.isArray(run.cells)) push('cells must be an array');\n else if ((run.cells as unknown[]).length === 0) push('cells must not be empty');\n else if ((run.cells as unknown[]).length > 500) push('cells exceeds the 500-cell limit');\n else {\n (run.cells as unknown[]).forEach((c, i) => validateCellShape(c, i, push));\n }\n if (!Array.isArray(run.events)) push('events must be an array');\n return errors;\n}\n\nfunction validateCellShape(value: unknown, index: number, push: (m: string) => void): void {\n if (typeof value !== 'object' || value === null) {\n push(`cells[${index}] must be an object`);\n return;\n }\n const cell = value as Record<string, unknown>;\n const at = `cells[${index}]`;\n if (typeof cell.cellId !== 'string') push(`${at}.cellId must be a string`);\n if (typeof cell.runtimeId !== 'string') push(`${at}.runtimeId must be a string`);\n if (typeof cell.workloadId !== 'string') push(`${at}.workloadId must be a string`);\n if (!['ok', 'invalid', 'error', 'skipped'].includes(cell.status as string)) {\n push(`${at}.status must be ok|invalid|error|skipped`);\n }\n const model = cell.model as Record<string, unknown> | undefined;\n if (!model || typeof model.benchModelId !== 'string' || typeof model.providerModelId !== 'string') {\n push(`${at}.model {benchModelId, providerModelId} is required`);\n }\n const quality = cell.quality as Record<string, unknown> | undefined;\n if (quality && Array.isArray(quality.outputs)) {\n if ((quality.outputs as unknown[]).some((o) => typeof o !== 'string' || (o as string).length > 500)) {\n push(`${at}.quality.outputs must be strings of at most 500 chars`);\n }\n }\n if (!Array.isArray(cell.iterations)) {\n push(`${at}.iterations must be an array`);\n return;\n }\n (cell.iterations as unknown[]).forEach((it, j) => {\n if (typeof it !== 'object' || it === null) {\n push(`${at}.iterations[${j}] must be an object`);\n return;\n }\n const iter = it as Record<string, unknown>;\n if (typeof iter.startT !== 'number' || typeof iter.endT !== 'number') {\n push(`${at}.iterations[${j}] needs numeric startT/endT`);\n }\n if ('chunks' in iter && !Array.isArray(iter.chunks)) {\n push(`${at}.iterations[${j}].chunks must be an array`);\n }\n if ('text' in iter && typeof iter.text === 'string' && (iter.text as string).length > 20_000) {\n push(`${at}.iterations[${j}].text exceeds 20000 chars`);\n }\n });\n}\n\n/** True when the iteration array is the LLM shape (has chunk traces). */\nfunction isLLMIterations(iterations: BenchCellResult['iterations']): iterations is LLMIteration[] {\n return iterations.length > 0 && 'chunks' in iterations[0];\n}\n\n/**\n * True when an iteration's chunk trace is genuinely incremental: at least two\n * chunks, and the visible stream spans at least\n * `STREAM_COHERENCE_MIN_SPAN_RATIO` of the request wall time. Anything else\n * (a doGenerate fallback's single chunk, or a runtime that computes the whole\n * generation and flushes it in a terminal burst) carries no usable TTFT or\n * decode timing.\n */\nexport function isIncrementalStream(it: LLMIteration): boolean {\n const nonEmpty = it.chunks.filter((c) => c.c > 0);\n if (nonEmpty.length < 2) return false;\n const span = nonEmpty[nonEmpty.length - 1].t - nonEmpty[0].t;\n const total = it.endT - it.startT;\n return total > 0 && span / total >= STREAM_COHERENCE_MIN_SPAN_RATIO;\n}\n\n/**\n * Recompute a cell's summary purely from its raw iteration traces.\n * This function IS the metric definition:\n * - TTFT = first non-empty chunk timestamp − startT\n * - decode rate = (chars after first chunk) / (endT_lastChunk − t_firstChunk)\n * - prefill tok/s ≈ approxPromptTokens / TTFT (approximate by construction)\n * - overall rate = total chars / (endT − startT), always derivable\n * TTFT/decode/prefill are derived only when EVERY iteration passes the\n * stream-coherence test (`streamIncremental`); overall rate and total wall\n * time are reported for all LLM lanes.\n */\nexport function summarizeCell(\n cell: BenchCellResult,\n highVarianceCv = 0.05,\n approxPromptTokens?: number,\n): CellSummary {\n const out: CellSummary = {\n cellId: cell.cellId,\n status: cell.status,\n highVariance: false,\n };\n if (cell.load) {\n out.loadMs = cell.load.endT - cell.load.startT;\n out.loadCached = cell.load.cached;\n }\n if (cell.quality) {\n out.qualityScore = cell.quality.score;\n if (cell.quality.parseRate !== undefined) out.qualityParseRate = cell.quality.parseRate;\n }\n if (cell.iterations.length === 0) return out;\n\n if (isLLMIterations(cell.iterations)) {\n const incremental = cell.iterations.every(isIncrementalStream);\n out.streamIncremental = incremental;\n const ttfts: number[] = [];\n const decodeRates: number[] = [];\n const chunkRates: number[] = [];\n const genChars: number[] = [];\n const prefillRates: number[] = [];\n const totals: number[] = [];\n const overallRates: number[] = [];\n for (const it of cell.iterations) {\n const totalChars = it.chunks.reduce((acc, c) => acc + c.c, 0);\n const totalMs = it.endT - it.startT;\n if (totalMs > 0) {\n totals.push(totalMs);\n if (totalChars > 0) overallRates.push((totalChars / totalMs) * 1000);\n }\n genChars.push(totalChars);\n if (!incremental) continue;\n const first = it.chunks.find((c) => c.c > 0);\n if (!first) continue;\n const ttftMs = first.t - it.startT;\n ttfts.push(ttftMs);\n const last = it.chunks[it.chunks.length - 1];\n const decodeChars = totalChars - first.c;\n const decodeMs = last.t - first.t;\n if (decodeMs > 0 && decodeChars > 0) {\n decodeRates.push((decodeChars / decodeMs) * 1000);\n chunkRates.push(((it.chunks.length - 1) / decodeMs) * 1000);\n }\n if (approxPromptTokens && ttftMs > 0) prefillRates.push((approxPromptTokens / ttftMs) * 1000);\n }\n if (ttfts.length > 0) out.ttftMs = summarize(ttfts);\n if (decodeRates.length > 0) out.decodeCharsPerSec = summarize(decodeRates);\n if (chunkRates.length > 0) out.decodeChunksPerSec = summarize(chunkRates);\n if (genChars.length > 0) out.generatedChars = summarize(genChars);\n if (prefillRates.length > 0) out.prefillTokPerSecApprox = summarize(prefillRates);\n if (totals.length > 0) out.totalMs = summarize(totals);\n if (overallRates.length > 0) out.overallCharsPerSec = summarize(overallRates);\n } else {\n const iters = cell.iterations as EmbedIteration[];\n const durations = iters.map((it) => it.endT - it.startT).filter((d) => d > 0);\n if (durations.length > 0) {\n if (iters[0].count === 1) out.singleLatencyMs = summarize(durations);\n else {\n out.batchTextsPerSec = summarize(\n iters.filter((it) => it.endT - it.startT > 0).map((it) => (it.count / (it.endT - it.startT)) * 1000),\n );\n }\n }\n }\n\n const metrics: Array<MetricSummary | undefined> = [\n out.ttftMs,\n out.decodeCharsPerSec,\n out.overallCharsPerSec,\n out.singleLatencyMs,\n out.batchTextsPerSec,\n ];\n out.highVariance = metrics.some((m) => m !== undefined && m.n >= 2 && m.cv > highVarianceCv);\n return out;\n}\n\n/** Recompute all cell summaries for a run (workload prompt sizes looked up). */\nexport function summarizeRun(\n run: BenchRunResult,\n highVarianceCv = 0.05,\n promptTokensByWorkload?: ReadonlyMap<string, number>,\n): CellSummary[] {\n const defaults = new Map<string, number>([\n ['chat-pp128-tg128', 128],\n ['chat-pp512-tg128', 512],\n ]);\n const lookup = promptTokensByWorkload ?? defaults;\n return run.cells.map((cell) => summarizeCell(cell, highVarianceCv, lookup.get(cell.workloadId)));\n}\n\n/**\n * Versioned plausibility/integrity checks over a submitted run. Returns flags;\n * `severity: 'reject'` flags route the run to quarantine, `warn` flags are\n * displayed. Rules (v1): timestamp monotonicity, decode-rate envelopes,\n * duration consistency, timer-grid conformance, fingerprint sanity,\n * environment cross-field consistency.\n */\nexport function checkPlausibility(run: BenchRunResult): PlausibilityFlag[] {\n const flags: PlausibilityFlag[] = [];\n const flag = (code: string, message: string, severity: 'warn' | 'reject', cellId?: string) =>\n flags.push({ code, message, severity, ...(cellId ? { cellId } : {}) });\n\n // Fingerprint sanity: the matmul must have run and be within silicon reality.\n if (!run.fingerprint) {\n flag('fingerprint-missing', 'no hardware fingerprint in submission', 'reject');\n } else if (\n run.fingerprint.mflops <= 1 ||\n run.fingerprint.mflops > 100_000 ||\n !Number.isFinite(run.fingerprint.checksum)\n ) {\n flag('fingerprint-implausible', `fingerprint mflops=${run.fingerprint.mflops}`, 'reject');\n }\n\n const grid = run.environment.timerResolutionUs;\n\n for (const cell of run.cells) {\n if (cell.status !== 'ok') continue;\n\n if (cell.load && cell.load.endT < cell.load.startT) {\n flag('load-time-reversed', 'load endT precedes startT', 'reject', cell.cellId);\n }\n\n if (isLLMIterations(cell.iterations)) {\n for (const it of cell.iterations) {\n // Monotonic chunk timestamps within [startT, endT].\n let prev = it.startT;\n let monotonic = true;\n for (const c of it.chunks) {\n if (c.t < prev) monotonic = false;\n prev = c.t;\n }\n if (!monotonic || it.endT < prev) {\n flag('trace-not-monotonic', 'chunk timestamps are not monotonic', 'reject', cell.cellId);\n break;\n }\n // Text length must equal the chunk-length sum.\n const chunkChars = it.chunks.reduce((acc, c) => acc + c.c, 0);\n if (it.text.length !== chunkChars) {\n flag('text-chunk-mismatch', `text length ${it.text.length} != chunk sum ${chunkChars}`, 'reject', cell.cellId);\n break;\n }\n }\n\n const summary = summarizeCell(cell);\n // A healthy timed iteration generates real text. The runner gates\n // near-empty generations as invalid; an `ok` cell carrying them means\n // the client skipped that gate.\n if (\n cell.iterations.some((it) => (it as LLMIteration).text.length < MIN_GENERATED_CHARS)\n ) {\n flag(\n 'degenerate-generation',\n `an ok cell has a timed iteration with fewer than ${MIN_GENERATED_CHARS} generated chars`,\n 'reject',\n cell.cellId,\n );\n }\n const size = cell.model.sizeBytes ?? Number.POSITIVE_INFINITY;\n const envelope = DECODE_ENVELOPE_CHARS_PER_SEC.find((e) => size <= e.maxBytes);\n if (envelope && summary.decodeCharsPerSec && summary.decodeCharsPerSec.median > envelope.max) {\n flag(\n 'decode-rate-envelope',\n `decode ${Math.round(summary.decodeCharsPerSec.median)} chars/s exceeds envelope ${envelope.max} for model size`,\n 'reject',\n cell.cellId,\n );\n }\n // Overall rate conflates prefill + decode, so it is bounded by the same\n // envelope: it can never legitimately exceed the pure decode rate.\n if (envelope && summary.overallCharsPerSec && summary.overallCharsPerSec.median > envelope.max) {\n flag(\n 'overall-rate-envelope',\n `overall ${Math.round(summary.overallCharsPerSec.median)} chars/s exceeds envelope ${envelope.max} for model size`,\n 'reject',\n cell.cellId,\n );\n }\n if (summary.ttftMs && summary.ttftMs.median < 1) {\n flag('ttft-implausible', `median TTFT ${summary.ttftMs.median}ms < 1ms`, 'reject', cell.cellId);\n }\n\n // Timer-grid conformance: chunk timestamps should sit on the reported grid.\n if (grid !== null && grid !== undefined && grid >= 4) {\n const quantumMs = grid / 1000;\n let offGrid = 0;\n let total = 0;\n for (const it of cell.iterations) {\n for (const c of it.chunks) {\n total++;\n const remainder = Math.abs(c.t / quantumMs - Math.round(c.t / quantumMs));\n if (remainder > 0.01) offGrid++;\n }\n }\n if (total >= 20 && offGrid / total > 0.5) {\n flag('timer-grid', `${offGrid}/${total} chunk timestamps off the ${grid}us timer grid`, 'warn', cell.cellId);\n }\n }\n } else if (cell.quality?.taskId.startsWith('tinymmlu') && cell.quality.outputs) {\n // MMLU scores are recomputable from the stored raw outputs: re-parse\n // every output against the bundled item set and compare with the\n // submitted per-item details and score.\n const { outputs, details, score, n } = cell.quality;\n if (outputs.length !== n || !details || details.length !== n) {\n flag('quality-outputs-mismatch', 'quality outputs/details length disagrees with n', 'reject', cell.cellId);\n } else {\n let recomputed = 0;\n let agree = true;\n for (let i = 0; i < n; i++) {\n const item = TINY_MMLU[i];\n if (!item) break;\n const ok = parseMMLUAnswer(outputs[i], item.choices) === item.answer ? 1 : 0;\n recomputed += ok;\n if (ok !== details[i]) agree = false;\n }\n if (!agree || Math.abs(recomputed / n - score) > 1e-9) {\n flag(\n 'quality-details-mismatch',\n `submitted MMLU score ${score} disagrees with recompute ${recomputed / n} from raw outputs`,\n 'reject',\n cell.cellId,\n );\n }\n }\n } else if (cell.iterations.length > 0) {\n const summary = summarizeCell(cell);\n if (summary.batchTextsPerSec && summary.batchTextsPerSec.median > EMBED_ENVELOPE_TEXTS_PER_SEC) {\n flag(\n 'embed-rate-envelope',\n `embedding throughput ${Math.round(summary.batchTextsPerSec.median)} texts/s exceeds envelope`,\n 'reject',\n cell.cellId,\n );\n }\n if (summary.singleLatencyMs && summary.singleLatencyMs.median < 0.05) {\n flag('embed-latency-implausible', 'sub-50us embedding latency', 'reject', cell.cellId);\n }\n }\n }\n\n // Cross-field consistency: Apple GPU should not report a Windows platform.\n const vendor = run.environment.gpu.vendor?.toLowerCase() ?? '';\n const platform = run.environment.os.platform.toLowerCase();\n if (vendor === 'apple' && platform.includes('windows')) {\n flag('env-cross-field', 'Apple GPU adapter with Windows platform', 'reject');\n }\n\n // Software/virtual renderer detection: cloud VMs and virtualized desktops\n // expose SwiftShader/WARP-class adapters whose \"GPU\" numbers are CPU numbers.\n // A GPU-lane result from such an environment is rejected; a WASM/CPU-only run\n // is merely annotated (software rendering does not affect those lanes).\n const gpuIdentity = [\n run.environment.gpu.vendor,\n run.environment.gpu.architecture,\n run.environment.gpu.device,\n run.environment.gpu.description,\n run.environment.webglRenderer,\n ]\n .filter(Boolean)\n .join(' ');\n if (SOFTWARE_RENDERER_PATTERNS.some((p) => p.test(gpuIdentity))) {\n const hasGpuLane = run.cells.some(\n (cell) => cell.status === 'ok' && /webgpu|^gpu$/.test(cell.resolvedBackend),\n );\n flag(\n 'software-renderer',\n `GPU identity matches a software/virtual renderer: \"${gpuIdentity.slice(0, 120)}\"`,\n hasGpuLane ? 'reject' : 'warn',\n );\n }\n\n return flags;\n}\n\n/**\n * Full validation pipeline for a submission: shape, digest-independent\n * summary recompute, client-summary agreement (>1% relative disagreement on\n * medians is flagged), and plausibility rules.\n */\nexport function validateSubmission(run: BenchRunResult): ValidationReport {\n const shapeErrors = validateRunShape(run);\n if (shapeErrors.length > 0) {\n return { ok: false, shapeErrors, flags: [], summaries: [] };\n }\n const summaries = summarizeRun(run);\n const flags = checkPlausibility(run);\n\n if (run.clientSummaries) {\n const byId = new Map(summaries.map((s) => [s.cellId, s]));\n for (const client of run.clientSummaries) {\n const server = byId.get(client.cellId);\n if (!server) continue;\n for (const key of [\n 'ttftMs',\n 'decodeCharsPerSec',\n 'totalMs',\n 'overallCharsPerSec',\n 'singleLatencyMs',\n 'batchTextsPerSec',\n ] as const) {\n const c = client[key]?.median;\n const s = server[key]?.median;\n if (c !== undefined && s !== undefined && s !== 0 && Math.abs(c - s) / Math.abs(s) > 0.01) {\n flags.push({\n code: 'client-summary-disagrees',\n cellId: client.cellId,\n message: `${key} client median ${c} vs recomputed ${s}`,\n severity: 'reject',\n });\n }\n }\n }\n }\n\n return {\n ok: flags.every((f) => f.severity !== 'reject'),\n shapeErrors: [],\n flags,\n summaries,\n };\n}\n","/**\n * The suite runner: executes (runtime x model x workload) cells under the\n * versioned run policy — cache probe, load, untimed warmup, N timed runs with\n * raw per-chunk traces, validity gates, memory protocol points, cool-downs —\n * and assembles the submittable BenchRunResult.\n */\n\nimport type {\n BenchCellResult,\n BenchModelRef,\n BenchRunResult,\n BenchSuiteId,\n EmbedIteration,\n EmbedWorkloadSpec,\n HarnessInfo,\n LLMIteration,\n LLMWorkloadSpec,\n LoadRecord,\n MemorySample,\n QualityWorkloadSpec,\n} from './types.js';\nimport { BENCH_PROTOCOL_VERSION, BENCH_SCHEMA_VERSION } from './types.js';\nimport type {\n EmbeddingRuntimeAdapter,\n LLMRuntimeAdapter,\n LoadedEmbedder,\n LoadedLLM,\n} from './adapter.js';\nimport { USAGE_FIDELITY } from './adapter.js';\nimport { MIN_GENERATED_CHARS, orderCells, type RunPolicy } from './protocol.js';\nimport { hrNow, sleep, abortDomException } from './timing.js';\nimport { TraceRecorder } from './trace.js';\nimport { memoryApiAvailable, sampleMemoryBytes } from './memory.js';\nimport { captureEnvironment } from './env.js';\nimport { runFingerprint } from './fingerprint.js';\nimport { summarizeRun } from './validate.js';\nimport { runMMLUFidelity, runSTSQuality } from './quality.js';\n\n/** One planned cell. Cells sharing (runtimeId, model) reuse the loaded model. */\nexport interface PlannedCell {\n model: BenchModelRef;\n workload: LLMWorkloadSpec | EmbedWorkloadSpec | QualityWorkloadSpec;\n}\n\n/** Progress callbacks for a host UI. */\nexport interface RunnerHooks {\n onCellStart?(cellId: string, index: number, total: number): void;\n onCellFinish?(cell: BenchCellResult): void;\n onLoadProgress?(cellId: string, pct: number | undefined): void;\n onIteration?(cellId: string, iteration: number, total: number): void;\n onPhase?(phase: string): void;\n}\n\n/** Inputs to a suite run. */\nexport interface RunSuiteOptions {\n suite: BenchSuiteId;\n cells: PlannedCell[];\n policy: RunPolicy;\n llmAdapters: ReadonlyMap<string, LLMRuntimeAdapter>;\n embedAdapters: ReadonlyMap<string, EmbeddingRuntimeAdapter>;\n harness: HarnessInfo;\n hooks?: RunnerHooks;\n abortSignal?: AbortSignal;\n /** Skip the fingerprint microbenchmark (tests only; submissions require it). */\n skipFingerprint?: boolean;\n userReportedDevice?: string;\n}\n\n/**\n * Run a benchmark suite and return the full, submittable result (raw traces\n * included; `clientSummaries` computed with the same code the server uses).\n *\n * Cells are grouped by (runtime, model): the model loads once, its workloads\n * run back-to-back, then it is disposed before the next model (peak-memory\n * hygiene). Validity gates never retry silently — affected iterations carry\n * their gate events and the cell is marked invalid.\n *\n * @throws {DOMException} AbortError when `abortSignal` aborts.\n * @example\n * const result = await runBenchmarkSuite({ suite: 'quick', cells, policy, ... });\n */\nexport async function runBenchmarkSuite(options: RunSuiteOptions): Promise<BenchRunResult> {\n const { policy, hooks, abortSignal } = options;\n const trace = new TraceRecorder();\n await trace.attach();\n trace.record('suite-start', options.suite);\n\n const memApi = memoryApiAvailable();\n const cells: BenchCellResult[] = [];\n\n try {\n hooks?.onPhase?.('environment');\n const environment = await captureEnvironment({\n userReportedDevice: options.userReportedDevice,\n });\n\n hooks?.onPhase?.('fingerprint');\n throwIfAborted(abortSignal);\n const fingerprint = options.skipFingerprint ? null : await runFingerprint();\n\n const baselineMemory = memApi !== 'none' ? await sampleMemoryBytes() : null;\n\n // Deterministic protocol execution order (reproducibility), then group\n // cells so each (runtime, model) loads exactly once.\n const groups = groupCells(orderCells(options.cells));\n const totalCells = options.cells.length;\n let cellIndex = 0;\n\n for (const group of groups) {\n throwIfAborted(abortSignal);\n const groupCellsResults = await runModelGroup(group, {\n ...options,\n trace,\n memApi,\n baselineMemory,\n cellIndexRef: () => cellIndex++,\n totalCells,\n });\n cells.push(...groupCellsResults);\n\n trace.record('cooldown-start');\n await sleep(policy.cooldownMs, abortSignal).catch((e) => {\n if ((e as Error).name === 'AbortError') throw e;\n });\n if (policy.pressureGate) await waitForPressure(trace, policy.pressureGateTimeoutMs, abortSignal);\n trace.record('cooldown-end');\n }\n\n trace.record('suite-end');\n const result: BenchRunResult = {\n protocol: BENCH_PROTOCOL_VERSION,\n schemaVersion: BENCH_SCHEMA_VERSION,\n runId: generateRunId(),\n createdAt: new Date().toISOString(),\n harness: options.harness,\n suite: options.suite,\n environment,\n fingerprint,\n cells,\n events: [...trace.all],\n };\n result.clientSummaries = summarizeRun(result, policy.highVarianceCv);\n return result;\n } finally {\n await trace.dispose();\n }\n}\n\n/** Cells grouped per (runtimeId, benchModelId + providerModelId). */\ninterface ModelGroup {\n key: string;\n model: BenchModelRef;\n workloads: Array<LLMWorkloadSpec | EmbedWorkloadSpec | QualityWorkloadSpec>;\n}\n\nfunction groupCells(cells: PlannedCell[]): ModelGroup[] {\n const map = new Map<string, ModelGroup>();\n for (const cell of cells) {\n const key = `${cell.model.runtimeId}/${cell.model.benchModelId}/${cell.model.providerModelId}`;\n let group = map.get(key);\n if (!group) {\n group = { key, model: cell.model, workloads: [] };\n map.set(key, group);\n }\n group.workloads.push(cell.workload);\n }\n return [...map.values()];\n}\n\ninterface GroupContext extends RunSuiteOptions {\n trace: TraceRecorder;\n memApi: MemorySample['api'];\n baselineMemory: number | null;\n cellIndexRef: () => number;\n totalCells: number;\n}\n\n/** Load one model, run all its workloads, dispose. Errors isolate per group. */\nasync function runModelGroup(group: ModelGroup, ctx: GroupContext): Promise<BenchCellResult[]> {\n const { model } = group;\n const isEmbedding = model.task === 'embedding';\n const adapter = isEmbedding\n ? ctx.embedAdapters.get(model.runtimeId)\n : ctx.llmAdapters.get(model.runtimeId);\n\n const results: BenchCellResult[] = [];\n const baseCell = (workload: ModelGroup['workloads'][number]): BenchCellResult => ({\n cellId: `${model.runtimeId}/${model.benchModelId}/${workload.id}`,\n runtimeId: model.runtimeId,\n runtimeVersion: adapter?.runtimeVersion,\n model,\n workloadId: workload.id,\n workloadKind: workload.kind,\n resolvedBackend: 'unknown',\n load: null,\n iterations: [],\n status: 'skipped',\n });\n\n if (!adapter) {\n for (const workload of group.workloads) {\n const cell = baseCell(workload);\n cell.invalidReasons = [`no adapter registered for ${model.runtimeId}`];\n results.push(finishCell(cell, ctx));\n }\n return results;\n }\n\n const availability = await adapter.isAvailable();\n if (!availability.ok) {\n for (const workload of group.workloads) {\n const cell = baseCell(workload);\n cell.invalidReasons = [`runtime unavailable: ${availability.reason ?? 'unknown'}`];\n results.push(finishCell(cell, ctx));\n }\n return results;\n }\n\n // Load phase (recorded once, attached to the group's first cell).\n let loaded: LoadedLLM | LoadedEmbedder | null = null;\n let loadRecord: LoadRecord | null = null;\n let warmupMs: number | undefined;\n let postLoadMemory: number | null = null;\n\n try {\n throwIfAborted(ctx.abortSignal);\n const cached = await adapter.isModelCached(model);\n const progress: Array<{ t: number; pct: number }> = [];\n const loadStart = hrNow();\n const firstCellId = `${model.runtimeId}/${model.benchModelId}/${group.workloads[0].id}`;\n loaded = await adapter.load(model, {\n abortSignal: ctx.abortSignal,\n onProgress: (p) => {\n if (typeof p.pct === 'number' && (progress.length === 0 || p.pct - progress[progress.length - 1].pct >= 2)) {\n progress.push({ t: hrNow(), pct: Math.round(p.pct * 100) / 100 });\n }\n ctx.hooks?.onLoadProgress?.(firstCellId, p.pct);\n },\n });\n const loadEnd = hrNow();\n loadRecord = {\n cached,\n startT: loadStart,\n endT: loadEnd,\n progress: progress.length > 0 ? decimate(progress, 50) : undefined,\n declaredBytes: model.sizeBytes,\n };\n\n if (ctx.memApi !== 'none') postLoadMemory = await sampleMemoryBytes();\n\n // Untimed warmup (absorbs shader compilation / JIT / first-inference costs).\n if (ctx.policy.warmupRuns > 0) {\n const warmupStart = hrNow();\n for (let i = 0; i < ctx.policy.warmupRuns; i++) {\n throwIfAborted(ctx.abortSignal);\n if (isEmbedding) {\n await (loaded as LoadedEmbedder).model.doEmbed({\n values: ['warmup probe'],\n abortSignal: ctx.abortSignal,\n });\n } else {\n await consumeStream(\n (loaded as LoadedLLM).model,\n { prompt: 'Reply with the single word: ready', maxTokens: 4, temperature: 0 },\n ctx.abortSignal,\n );\n }\n }\n warmupMs = hrNow() - warmupStart;\n }\n } catch (error) {\n if ((error as Error).name === 'AbortError') {\n if (loaded) await safeDispose(loaded);\n throw error;\n }\n const atError = ctx.memApi !== 'none' ? await sampleMemoryBytes(5_000) : null;\n for (const workload of group.workloads) {\n const cell = baseCell(workload);\n cell.status = 'error';\n cell.load = loadRecord;\n cell.error = describeError(error);\n if (ctx.memApi !== 'none') {\n cell.memory = {\n api: ctx.memApi,\n baseline: ctx.baselineMemory ?? undefined,\n postLoad: postLoadMemory ?? undefined,\n atError: atError ?? undefined,\n };\n }\n results.push(finishCell(cell, ctx));\n }\n if (loaded) await safeDispose(loaded);\n return results;\n }\n\n // Workload cells over the live model.\n let attachedLoad = false;\n for (const workload of group.workloads) {\n throwIfAborted(ctx.abortSignal);\n const cell = baseCell(workload);\n cell.resolvedBackend = loaded.resolvedBackend;\n if (!attachedLoad) {\n cell.load = loadRecord;\n cell.warmupMs = warmupMs;\n attachedLoad = true;\n }\n const index = ctx.cellIndexRef();\n ctx.hooks?.onCellStart?.(cell.cellId, index, ctx.totalCells);\n\n try {\n switch (workload.kind) {\n case 'llm-generate':\n await runLLMCell(cell, loaded as LoadedLLM, workload, ctx);\n break;\n case 'embed-single':\n case 'embed-batch':\n await runEmbedCell(cell, loaded as LoadedEmbedder, workload, ctx);\n break;\n case 'quality-mmlu': {\n const total = workload.items;\n cell.quality = await runMMLUFidelity((loaded as LoadedLLM).model, total, {\n abortSignal: ctx.abortSignal,\n onProgress: (done) => ctx.hooks?.onIteration?.(cell.cellId, done, total),\n promptSuffix: model.qualityPromptSuffix,\n });\n cell.status = 'ok';\n break;\n }\n case 'quality-sts': {\n const total = workload.items;\n cell.quality = await runSTSQuality((loaded as LoadedEmbedder).model, total, {\n abortSignal: ctx.abortSignal,\n onProgress: (done) => ctx.hooks?.onIteration?.(cell.cellId, done, total),\n });\n cell.status = 'ok';\n break;\n }\n }\n } catch (error) {\n if ((error as Error).name === 'AbortError') {\n await safeDispose(loaded);\n throw error;\n }\n cell.status = 'error';\n cell.error = describeError(error);\n }\n\n if (ctx.memApi !== 'none' && (cell.status === 'ok' || cell.status === 'error')) {\n const sample = await sampleMemoryBytes(5_000);\n cell.memory = {\n api: ctx.memApi,\n baseline: ctx.baselineMemory ?? undefined,\n postLoad: postLoadMemory ?? undefined,\n ...(cell.status === 'ok' ? { postRun: sample ?? undefined } : { atError: sample ?? undefined }),\n };\n }\n results.push(finishCell(cell, ctx));\n }\n\n await safeDispose(loaded);\n\n // Warm-reload lane: after a cold load, reload to measure the cache-hit path.\n if (ctx.policy.measureWarmReload && loadRecord?.cached === false) {\n try {\n throwIfAborted(ctx.abortSignal);\n const start = hrNow();\n const reloaded = await adapter.load(model, { abortSignal: ctx.abortSignal });\n const end = hrNow();\n await safeDispose(reloaded);\n const warmCell: BenchCellResult = {\n cellId: `${model.runtimeId}/${model.benchModelId}/warm-reload`,\n runtimeId: model.runtimeId,\n runtimeVersion: adapter.runtimeVersion,\n model,\n workloadId: 'warm-reload',\n workloadKind: 'llm-generate',\n resolvedBackend: reloaded.resolvedBackend,\n load: { cached: true, startT: start, endT: end, declaredBytes: model.sizeBytes },\n iterations: [],\n status: 'ok',\n };\n results.push(finishCell(warmCell, ctx));\n } catch (error) {\n if ((error as Error).name === 'AbortError') throw error;\n // Warm-reload is auxiliary; a failure here never invalidates the group.\n }\n }\n\n return results;\n}\n\n/** Timed LLM iterations with raw chunk traces. */\nasync function runLLMCell(\n cell: BenchCellResult,\n loaded: LoadedLLM,\n workload: LLMWorkloadSpec,\n ctx: GroupContext,\n): Promise<void> {\n const iterations: LLMIteration[] = [];\n for (let i = 0; i < ctx.policy.timedRuns; i++) {\n throwIfAborted(ctx.abortSignal);\n ctx.hooks?.onIteration?.(cell.cellId, i + 1, ctx.policy.timedRuns);\n const gates: string[] = [];\n if (ctx.trace.isHidden) gates.push('started-hidden');\n const hiddenBefore = countHidden(ctx.trace);\n\n const startT = hrNow();\n const { chunks, text, providerUsage, finishReason } = await consumeStream(\n loaded.model,\n {\n prompt: workload.prompt,\n systemPrompt: workload.systemPrompt,\n maxTokens: workload.maxTokens,\n temperature: workload.temperature,\n },\n ctx.abortSignal,\n );\n const endT = hrNow();\n if (countHidden(ctx.trace) > hiddenBefore) gates.push('hidden-during-run');\n if (text.length < MIN_GENERATED_CHARS) gates.push('degenerate-output');\n\n iterations.push({\n startT,\n chunks,\n endT,\n text,\n providerUsage: providerUsage\n ? { ...providerUsage, fidelity: USAGE_FIDELITY[cell.runtimeId] }\n : undefined,\n finishReason,\n gates,\n });\n }\n cell.iterations = iterations;\n const gated = iterations.some((it) => it.gates.length > 0);\n cell.status = gated ? 'invalid' : 'ok';\n if (gated) {\n const reasons = new Set<string>();\n for (const it of iterations) {\n for (const gate of it.gates) {\n reasons.add(\n gate === 'degenerate-output'\n ? `degenerate output: fewer than ${MIN_GENERATED_CHARS} generated chars in a timed iteration`\n : 'validity gate fired during a timed region',\n );\n }\n }\n cell.invalidReasons = [...reasons];\n }\n}\n\n/** Timed embedding iterations. */\nasync function runEmbedCell(\n cell: BenchCellResult,\n loaded: LoadedEmbedder,\n workload: EmbedWorkloadSpec,\n ctx: GroupContext,\n): Promise<void> {\n const iterations: EmbedIteration[] = [];\n for (let i = 0; i < ctx.policy.timedRuns; i++) {\n throwIfAborted(ctx.abortSignal);\n ctx.hooks?.onIteration?.(cell.cellId, i + 1, ctx.policy.timedRuns);\n const gates: string[] = [];\n if (ctx.trace.isHidden) gates.push('started-hidden');\n const hiddenBefore = countHidden(ctx.trace);\n\n const startT = hrNow();\n const { embeddings } = await loaded.model.doEmbed({\n values: workload.texts,\n abortSignal: ctx.abortSignal,\n });\n const endT = hrNow();\n if (countHidden(ctx.trace) > hiddenBefore) gates.push('hidden-during-run');\n\n iterations.push({\n startT,\n endT,\n count: workload.texts.length,\n dimensions: embeddings[0]?.length ?? loaded.model.dimensions,\n gates,\n });\n }\n cell.iterations = iterations;\n const gated = iterations.some((it) => it.gates.length > 0);\n cell.status = gated ? 'invalid' : 'ok';\n if (gated) cell.invalidReasons = ['validity gate fired during a timed region'];\n}\n\n/** Drain a model stream, timestamping every chunk (falls back to doGenerate). */\nasync function consumeStream(\n model: LoadedLLM['model'],\n options: { prompt: string; systemPrompt?: string; maxTokens: number; temperature: number },\n abortSignal?: AbortSignal,\n): Promise<{\n chunks: Array<{ t: number; c: number }>;\n text: string;\n providerUsage?: Omit<import('./types.js').ProviderUsage, 'fidelity'>;\n finishReason?: string;\n}> {\n const chunks: Array<{ t: number; c: number }> = [];\n let text = '';\n let providerUsage: Omit<import('./types.js').ProviderUsage, 'fidelity'> | undefined;\n let finishReason: string | undefined;\n\n if (model.doStream) {\n for await (const chunk of model.doStream({ ...options, abortSignal })) {\n const t = hrNow();\n if (chunk.text.length > 0) {\n chunks.push({ t, c: chunk.text.length });\n text += chunk.text;\n }\n if (chunk.done) {\n providerUsage = chunk.usage;\n finishReason = chunk.finishReason;\n }\n }\n } else {\n const result = await model.doGenerate({ ...options, abortSignal });\n const t = hrNow();\n text = result.text;\n chunks.push({ t, c: result.text.length });\n providerUsage = result.usage;\n finishReason = result.finishReason;\n }\n return { chunks, text, providerUsage, finishReason };\n}\n\n/** Count visibility-hidden events recorded so far. */\nfunction countHidden(trace: TraceRecorder): number {\n let n = 0;\n for (const e of trace.all) if (e.type === 'visibility-hidden') n++;\n return n;\n}\n\n/** Wait until compute pressure recovers to nominal/fair (best-effort). */\nasync function waitForPressure(\n trace: TraceRecorder,\n timeoutMs: number,\n abortSignal?: AbortSignal,\n): Promise<void> {\n const deadline = hrNow() + timeoutMs;\n while (hrNow() < deadline) {\n const state = trace.pressureState;\n if (state === undefined || state === 'nominal' || state === 'fair') return;\n await sleep(1_000, abortSignal);\n }\n}\n\n/** Downsample a progress array to at most `max` entries (keeps endpoints). */\nfunction decimate<T>(items: T[], max: number): T[] {\n if (items.length <= max) return items;\n const out: T[] = [];\n const step = (items.length - 1) / (max - 1);\n for (let i = 0; i < max; i++) out.push(items[Math.round(i * step)]);\n return out;\n}\n\n/** Serialize an error for a cell, keeping the wrapped provider cause's message. */\nfunction describeError(error: unknown): NonNullable<BenchCellResult['error']> {\n const e = error as { name?: string; message?: string; cause?: unknown } | undefined;\n const cause = e?.cause;\n const causeMessage =\n cause instanceof Error ? cause.message : typeof cause === 'string' ? cause : undefined;\n return {\n name: e?.name ?? 'Error',\n message: e?.message ?? String(error),\n ...(causeMessage ? { cause: causeMessage } : {}),\n };\n}\n\nfunction finishCell(cell: BenchCellResult, ctx: GroupContext): BenchCellResult {\n ctx.hooks?.onCellFinish?.(cell);\n return cell;\n}\n\nasync function safeDispose(loaded: LoadedLLM | LoadedEmbedder): Promise<void> {\n try {\n await loaded.dispose();\n } catch {\n // Disposal failures must never corrupt a completed result.\n }\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) throw abortDomException();\n}\n\n/** UUID v4 via Web Crypto, with a deterministic-format fallback. */\nfunction generateRunId(): string {\n const cryptoObj = globalThis.crypto as Crypto | undefined;\n if (cryptoObj?.randomUUID) return cryptoObj.randomUUID();\n const bytes = new Uint8Array(16);\n if (cryptoObj?.getRandomValues) cryptoObj.getRandomValues(bytes);\n else for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256);\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = [...bytes].map((b) => b.toString(16).padStart(2, '0')).join('');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n","/**\n * Canonical JSON serialization + SHA-256 digest for run results. The digest\n * covers the canonical form of the result WITHOUT its `digest` field, so any\n * party can recompute and verify it (isomorphic: browser and Node).\n */\n\nimport type { BenchRunResult } from './types.js';\n\n/**\n * Deterministic JSON: object keys sorted lexicographically at every level,\n * arrays in order, no whitespace. Non-finite numbers serialize as null\n * (JSON.stringify semantics) so digests stay portable.\n *\n * @example\n * canonicalJson({ b: 1, a: [2, { d: 3, c: 4 }] }); // '{\"a\":[2,{\"c\":4,\"d\":3}],\"b\":1}'\n */\nexport function canonicalJson(value: unknown): string {\n return stringify(value);\n}\n\nfunction stringify(value: unknown): string {\n if (value === null || typeof value === 'number' || typeof value === 'boolean') {\n return JSON.stringify(value);\n }\n if (typeof value === 'string') return JSON.stringify(value);\n if (typeof value === 'undefined') return 'null';\n if (Array.isArray(value)) return `[${value.map((v) => stringify(v)).join(',')}]`;\n if (typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([k, v]) => `${JSON.stringify(k)}:${stringify(v)}`);\n return `{${entries.join(',')}}`;\n }\n throw new TypeError(`canonicalJson: unsupported value type ${typeof value}`);\n}\n\n/** SHA-256 hex of a UTF-8 string via Web Crypto (browser + Node >= 19). */\nexport async function sha256Hex(text: string): Promise<string> {\n const subtle = globalThis.crypto?.subtle;\n if (!subtle) throw new Error('Web Crypto (crypto.subtle) is not available in this environment');\n const bytes = new TextEncoder().encode(text);\n const hash = await subtle.digest('SHA-256', bytes);\n return [...new Uint8Array(hash)].map((b) => b.toString(16).padStart(2, '0')).join('');\n}\n\n/**\n * Compute the run digest: SHA-256 of the canonical JSON of the result with\n * `digest` removed.\n *\n * @example\n * result.digest = await computeRunDigest(result);\n */\nexport async function computeRunDigest(result: BenchRunResult): Promise<string> {\n const { digest: _omitted, ...rest } = result;\n return sha256Hex(canonicalJson(rest));\n}\n\n/** Verify a result's embedded digest. Returns false when absent or wrong. */\nexport async function verifyRunDigest(result: BenchRunResult): Promise<boolean> {\n if (!result.digest) return false;\n return (await computeRunDigest(result)) === result.digest;\n}\n","/**\n * Aggregation for the public leaderboard and for paper analysis. Runs group\n * into device-class rows; medians are taken per submission first, then across\n * submissions (median-of-medians). Nothing is ever averaged across devices.\n */\n\nimport type { BenchRunResult, CellSummary } from './types.js';\nimport { isIncrementalStream, summarizeRun } from './validate.js';\nimport { median } from './stats.js';\n\n/** Device class derived from environment identity signals. */\nexport function deviceClassOf(run: BenchRunResult): string {\n const env = run.environment;\n const gpu = env.gpu.available\n ? [env.gpu.vendor ?? 'gpu', env.gpu.architecture].filter(Boolean).join('-')\n : 'no-webgpu';\n return [env.os.platform.toLowerCase().replace(/\\s+/g, '-'), gpu].join('/');\n}\n\n/** One leaderboard row: a (deviceClass, runtime, model, workload) group. */\nexport interface LeaderboardRow {\n deviceClass: string;\n runtimeId: string;\n benchModelId: string;\n modelName: string;\n workloadId: string;\n /** Number of distinct submissions contributing. */\n submissions: number;\n /** Median-of-medians metrics (only those applicable to the workload). */\n ttftMs?: number;\n decodeCharsPerSec?: number;\n /** End-to-end chars/s (prefill + decode); the only rate for lanes whose stream is not incremental. */\n overallCharsPerSec?: number;\n singleLatencyMs?: number;\n batchTextsPerSec?: number;\n loadColdMs?: number;\n loadWarmMs?: number;\n qualityScore?: number;\n /** Median MMLU parse rate; below 1 the quality score is format-limited. */\n qualityParseRate?: number;\n resolvedBackends: string[];\n browsers: string[];\n /** True when any contributing submission had a high-variance metric. */\n highVariance: boolean;\n /** Rows below the min-N threshold are provisional. */\n provisional: boolean;\n}\n\n/** Minimum concordant submissions for a non-provisional headline row. */\nexport const HEADLINE_MIN_SUBMISSIONS = 3;\n\n/**\n * Aggregate validated runs into leaderboard rows.\n *\n * @param runs - Validated (non-quarantined) run results.\n * @param minSubmissions - Min submissions before a row loses `provisional`.\n * @example\n * const rows = aggregateRuns(allRuns);\n */\nexport function aggregateRuns(\n runs: readonly BenchRunResult[],\n minSubmissions = HEADLINE_MIN_SUBMISSIONS,\n): LeaderboardRow[] {\n interface Bucket {\n row: Omit<\n LeaderboardRow,\n | 'submissions'\n | 'ttftMs'\n | 'decodeCharsPerSec'\n | 'overallCharsPerSec'\n | 'singleLatencyMs'\n | 'batchTextsPerSec'\n | 'loadColdMs'\n | 'loadWarmMs'\n | 'qualityScore'\n | 'qualityParseRate'\n | 'provisional'\n >;\n ttft: number[];\n decode: number[];\n overall: number[];\n single: number[];\n batch: number[];\n loadCold: number[];\n loadWarm: number[];\n quality: number[];\n parseRate: number[];\n runIds: Set<string>;\n }\n const buckets = new Map<string, Bucket>();\n\n for (const run of runs) {\n const deviceClass = deviceClassOf(run);\n const summaries = run.clientSummaries ?? summarizeRun(run);\n const byCellId = new Map<string, CellSummary>(summaries.map((s) => [s.cellId, s]));\n\n for (const cell of run.cells) {\n if (cell.status !== 'ok') continue;\n const summary = byCellId.get(cell.cellId);\n if (!summary) continue;\n const key = [deviceClass, cell.runtimeId, cell.model.benchModelId, cell.workloadId].join('|');\n let bucket = buckets.get(key);\n if (!bucket) {\n bucket = {\n row: {\n deviceClass,\n runtimeId: cell.runtimeId,\n benchModelId: cell.model.benchModelId,\n modelName: cell.model.displayName,\n workloadId: cell.workloadId,\n resolvedBackends: [],\n browsers: [],\n highVariance: false,\n },\n ttft: [],\n decode: [],\n overall: [],\n single: [],\n batch: [],\n loadCold: [],\n loadWarm: [],\n quality: [],\n parseRate: [],\n runIds: new Set(),\n };\n buckets.set(key, bucket);\n }\n bucket.runIds.add(run.runId);\n pushUnique(bucket.row.resolvedBackends, cell.resolvedBackend);\n pushUnique(bucket.row.browsers, run.environment.browser.name);\n bucket.row.highVariance ||= summary.highVariance;\n if (summary.ttftMs) bucket.ttft.push(summary.ttftMs.median);\n if (summary.decodeCharsPerSec) bucket.decode.push(summary.decodeCharsPerSec.median);\n if (summary.overallCharsPerSec) bucket.overall.push(summary.overallCharsPerSec.median);\n if (summary.singleLatencyMs) bucket.single.push(summary.singleLatencyMs.median);\n if (summary.batchTextsPerSec) bucket.batch.push(summary.batchTextsPerSec.median);\n if (summary.loadMs !== undefined) {\n (summary.loadCached ? bucket.loadWarm : bucket.loadCold).push(summary.loadMs);\n }\n if (summary.qualityScore !== undefined) bucket.quality.push(summary.qualityScore);\n if (summary.qualityParseRate !== undefined) bucket.parseRate.push(summary.qualityParseRate);\n }\n }\n\n const rows: LeaderboardRow[] = [];\n for (const bucket of buckets.values()) {\n rows.push({\n ...bucket.row,\n submissions: bucket.runIds.size,\n ttftMs: maybeMedian(bucket.ttft),\n decodeCharsPerSec: maybeMedian(bucket.decode),\n overallCharsPerSec: maybeMedian(bucket.overall),\n singleLatencyMs: maybeMedian(bucket.single),\n batchTextsPerSec: maybeMedian(bucket.batch),\n loadColdMs: maybeMedian(bucket.loadCold),\n loadWarmMs: maybeMedian(bucket.loadWarm),\n qualityScore: maybeMedian(bucket.quality),\n qualityParseRate: maybeMedian(bucket.parseRate),\n provisional: bucket.runIds.size < minSubmissions,\n });\n }\n rows.sort(\n (a, b) =>\n a.deviceClass.localeCompare(b.deviceClass) ||\n a.benchModelId.localeCompare(b.benchModelId) ||\n a.runtimeId.localeCompare(b.runtimeId) ||\n a.workloadId.localeCompare(b.workloadId),\n );\n return rows;\n}\n\nfunction pushUnique(list: string[], value: string): void {\n if (value && !list.includes(value)) list.push(value);\n}\n\nfunction maybeMedian(values: number[]): number | undefined {\n return values.length > 0 ? round2(median(values)) : undefined;\n}\n\nfunction round2(v: number): number {\n return Math.round(v * 100) / 100;\n}\n\n/** Escape one CSV field (RFC 4180). */\nfunction csvField(value: unknown): string {\n const s = value === undefined || value === null ? '' : String(value);\n return /[\",\\n]/.test(s) ? `\"${s.replace(/\"/g, '\"\"')}\"` : s;\n}\n\n/** Leaderboard rows as CSV. */\nexport function rowsToCSV(rows: readonly LeaderboardRow[]): string {\n const header = [\n 'deviceClass', 'runtimeId', 'benchModelId', 'modelName', 'workloadId', 'submissions',\n 'ttftMs', 'decodeCharsPerSec', 'overallCharsPerSec', 'singleLatencyMs', 'batchTextsPerSec',\n 'loadColdMs', 'loadWarmMs', 'qualityScore', 'qualityParseRate', 'resolvedBackends', 'browsers',\n 'highVariance', 'provisional',\n ];\n const lines = [header.join(',')];\n for (const r of rows) {\n lines.push(\n [\n r.deviceClass, r.runtimeId, r.benchModelId, r.modelName, r.workloadId, r.submissions,\n r.ttftMs, r.decodeCharsPerSec, r.overallCharsPerSec, r.singleLatencyMs, r.batchTextsPerSec,\n r.loadColdMs, r.loadWarmMs, r.qualityScore, r.qualityParseRate, r.resolvedBackends.join(';'), r.browsers.join(';'),\n r.highVariance, r.provisional,\n ]\n .map(csvField)\n .join(','),\n );\n }\n return lines.join('\\n') + '\\n';\n}\n\n/**\n * Long-format per-iteration CSV for paper analysis (one row per timed\n * iteration, with full environment identity columns) — feed to R/pandas.\n */\nexport function runsToLongCSV(runs: readonly BenchRunResult[]): string {\n const header = [\n 'runId', 'createdAt', 'suite', 'deviceClass', 'browser', 'browserVersion', 'os', 'gpuVendor',\n 'gpuArchitecture', 'cores', 'deviceMemoryGB', 'crossOriginIsolated', 'fingerprintMflops',\n 'runtimeId', 'runtimeVersion', 'benchModelId', 'providerModelId', 'quantization', 'sizeBytes',\n 'workloadId', 'resolvedBackend', 'iteration', 'ttftMs', 'decodeCharsPerSec', 'generatedChars',\n 'overallCharsPerSec', 'streamIncremental', 'durationMs', 'loadMs', 'loadCached', 'status',\n ];\n const lines = [header.join(',')];\n for (const run of runs) {\n const env = run.environment;\n const base = [\n run.runId, run.createdAt, run.suite, deviceClassOf(run), env.browser.name,\n env.browser.version, env.os.platform, env.gpu.vendor ?? '', env.gpu.architecture ?? '',\n env.hardware.cores ?? '', env.hardware.deviceMemoryGB ?? '', env.flags.crossOriginIsolated,\n run.fingerprint ? round2(run.fingerprint.mflops) : '',\n ];\n for (const cell of run.cells) {\n const loadMs = cell.load ? round2(cell.load.endT - cell.load.startT) : '';\n const loadCached = cell.load ? String(cell.load.cached) : '';\n const cellBase = [\n cell.runtimeId, cell.runtimeVersion ?? '', cell.model.benchModelId,\n cell.model.providerModelId, cell.model.quantization ?? '', cell.model.sizeBytes ?? '',\n cell.workloadId, cell.resolvedBackend,\n ];\n if (cell.iterations.length === 0) {\n lines.push([...base, ...cellBase, '', '', '', '', '', '', '', loadMs, loadCached, cell.status].map(csvField).join(','));\n continue;\n }\n cell.iterations.forEach((it, i) => {\n let ttft = '';\n let decodeRate = '';\n let chars = '';\n let overall = '';\n let incremental = '';\n if ('chunks' in it) {\n const totalChars = it.chunks.reduce((a, c) => a + c.c, 0);\n chars = String(totalChars);\n const totalMs = it.endT - it.startT;\n if (totalMs > 0 && totalChars > 0) overall = String(round2((totalChars / totalMs) * 1000));\n // TTFT/decode only from genuinely incremental streams (same rule as\n // summarizeCell) — a terminal-burst trace carries no decode timing.\n const isIncremental = isIncrementalStream(it);\n incremental = String(isIncremental);\n const first = it.chunks.find((c) => c.c > 0);\n if (isIncremental && first) {\n ttft = String(round2(first.t - it.startT));\n const last = it.chunks[it.chunks.length - 1];\n const decodeChars = totalChars - first.c;\n const ms = last.t - first.t;\n if (ms > 0) decodeRate = String(round2((decodeChars / ms) * 1000));\n }\n }\n lines.push(\n [...base, ...cellBase, i + 1, ttft, decodeRate, chars, overall, incremental,\n round2(it.endT - it.startT), loadMs, loadCached, cell.status]\n .map(csvField)\n .join(','),\n );\n });\n }\n }\n return lines.join('\\n') + '\\n';\n}\n"]}
|