Skip to content

AI, fully local on your computer.

14.8 KB
Raw Blame
import type { ModelPlacement, PlacementDevice } from '../../../shared/types'

// Where a model's start actually put it (benchmark.md "Your model"). llama.cpp's load log
// is the only place the real outcome of `--fit` is reported: the layer split, the bytes each
// device holds for the weights, and the context-cache buffers. This parser reads the whole set,
// for the chat runtime and for the translation sidecar's device hint (its split and
// `holdsGpuBuffers`, #671). For chat, one observation per successful start goes to the observer
// below (the read-speed.ts idiom: a module-level latch plus one persister registered by the IPC
// layer, so producers never touch settings).
//
// Lines, across the naming drift between builds (`llm_load_tensors:` / `load_tensors:`,
// `llama_kv_cache_unified:` / `llama_kv_cache:`):
//   load_tensors: offloaded 65/65 layers to GPU
//   load_tensors:   CUDA0 model buffer size = 18942.52 MiB
//   load_tensors:   CPU_Mapped model buffer size =   400.00 MiB
//   llama_kv_cache: CUDA0 KV buffer size = 1360.00 MiB
//   llama_memory_recurrent: Vulkan0 RS buffer size = 184.25 MiB
//   ggml_metal_init: recommendedMaxWorkingSetSize = 51539.61 MB
// A device whose name starts with "CPU" (CPU, CPU_Mapped) or ends in "_Host" (Vulkan_Host,
// CUDA_Host: pinned host memory the backend keeps CPU-side) is the CPU side; everything else
// is a GPU. The lines are printed from log verbosity 4 up (`-lv 4`, CHAT_SERVER_ARGS).
//
// The RS buffer is the RECURRENT state of a hybrid (Gated-DeltaNet) model — the other half of
// its context cache, allocated PER SEQUENCE, so `-np 4` pays it four times while the KV cache
// is merely sliced. It gets its own pair of fields rather than being folded into the KV ones:
// records written before #329 carry KV-only figures under `gpuKvMb`, and model-benchmarks.md
// §6.6 rests on telling a cell-sized KV cache from a per-sequence recurrent state. It is real
// card memory (29–1,795 MiB on the captured logs) and the ESTIMATE side already counts it
// (`estimatedContextCacheGib` = "KV + recurrent state"), so omitting it made the OBSERVED
// figure the low one.
//
// Compute buffers are counted ONCE PER CONTEXT PER DEVICE, taking the MAX of what that context
// printed — llama.cpp keeps one such buffer per context per backend and only GROWS it when a
// graph is re-reserved. A speculative start (`--spec-type draft-mtp`) constructs TWO contexts
// (main + draft) and prints THREE `sched_reserve` blocks: adding the draft implementation
// re-reserves the draft context and REPRINTS its unchanged size. Summing every line counted
// that buffer a third time (1,665.34 MiB where 1,145.28 was allocated). MAX, not "skip a
// repeated block": a re-reserve may legitimately print a LARGER figure, and that is the size.
// `llama_context: constructing llama_context` is the context boundary. The rule ASSUMES each
// llama_context is constructed ONCE per server process — true of all 33 captured logs, the
// `--fit-target` runs included. A future build whose fit loop tore a context down and rebuilt
// it would reprint `constructing llama_context` and be counted as a second context: that is a
// parser regression to recognise as one, not a mystery.
//
// Two lines are deliberately NOT counted:
//   `sched_reserve: Vulkan_Host compute buffer size = 128.16 MiB` — host memory, present on
//   full offloads too, so it is not spill and never card memory (dropped below, by isCpuDevice);
//   `~llama_context: Vulkan0 compute buffer size of 679.1215 MiB, does not match expectation of
//   625.2188 MiB` — a teardown warning with no `= N MiB`, so it matches nothing. It must never
//   be summed: it reports the same buffer the reserve already accounted for.
//
// The `device_info` block names each device TWICE over — by ggml's label (`Vulkan0`, the name
// the buffer lines use) and by the driver's name (the one `--list-devices` prints too):
//   device_info:
//     - Vulkan0 : Intel(R) Iris(R) Xe Graphics (16384 MiB, 15000 MiB free)
//     - Vulkan1 : NVIDIA GeForce RTX 3090 (24822 MiB, 22900 MiB free)
// The parser keeps every GPU row (`devices`) with the compute buffer reserved on it, so the
// snapshot can attribute the free-at-start and working figures to the device it actually
// selected (PR #303 audit DR2) instead of the first row / the sum over all devices — which
// on a hybrid box described the iGPU while the budget described the dGPU. The legacy summary
// `gpuFreeAtStartMb` still takes the FIRST row, which on a hybrid box IS the iGPU (the captured
// 20/33 log lists the Radeon first and puts every buffer on the RTX): the fix is to attribute
// through `devices`, and re-pointing the summary field is left to #332.

const OFFLOAD_RE = /offloaded\s+(\d+)\s*\/\s*(\d+)\s+layers to GPU/
const MODEL_BUFFER_RE = /(\S+) model buffer size\s*=\s*([\d.]+)\s*MiB/
const KV_BUFFER_RE = /(\S+) KV buffer size\s*=\s*([\d.]+)\s*MiB/
/** `llama_memory_recurrent:    Vulkan0 RS buffer size =   184.25 MiB` (the recurrent state). */
const RS_BUFFER_RE = /(\S+) RS buffer size\s*=\s*([\d.]+)\s*MiB/
/** `llama_context: constructing llama_context` — the boundary between compute-buffer owners. */
const CONTEXT_START_RE = /llama_context: constructing llama_context/
/** `sched_reserve:    Vulkan0 compute buffer size =  2860.00 MiB` (the working buffers). */
const COMPUTE_BUFFER_RE = /(\S+) compute buffer size\s*=\s*([\d.]+)\s*MiB/
const METAL_BUDGET_RE = /recommendedMaxWorkingSetSize\s*=\s*([\d.]+)\s*MB/
/**
 * `device_info` rows: `  - Vulkan0 : NVIDIA GeForce RTX 3090 (24822 MiB, 2703 MiB free)` —
 * label, name, total, free. The name is matched lazily up to the LAST `(<total> MiB, <free>
 * MiB free)` group so a name with its own parentheses ("… Graphics 630 (CFL GT2)") survives.
 */
const DEVICE_INFO_RE = /-\s+(\S+)\s+:\s+(.*?)\s*\((\d+)\s*MiB,\s*(\d+)\s*MiB free\)\s*$/

/** What one start's log said; every figure null until its line is seen. */
export interface PlacementReading {
  gpuLayers: number | null
  totalLayers: number | null
  gpuModelMb: number | null
  cpuModelMb: number | null
  gpuKvMb: number | null
  cpuKvMb: number | null
  /** Recurrent (RS) state on GPU devices, MiB summed; null when the model prints no RS line. */
  gpuRsMb: number | null
  /** Recurrent (RS) state on the CPU side, MiB summed; null when the model prints no RS line. */
  cpuRsMb: number | null
  metalMaxWorkingSetMb: number | null
  /** Free MiB on the first GPU device when the server started (the `device_info` block). */
  gpuFreeAtStartMb: number | null
  /** Working (compute) buffers reserved on GPU devices, MiB summed. */
  gpuComputeMb: number | null
  /** Every GPU row of the `device_info` block, in order, with the compute buffer filed under its label. */
  devices: PlacementDevice[]
}

export interface PlacementParser {
  /** Feed a stderr chunk (chunks can split lines; the parser reassembles them). */
  onStderrData: (text: string) => void
  /** The reading so far. */
  reading: () => PlacementReading
  /**
   * #653: did this start put anything on a graphics device? True when the log filed a model, KV,
   * recurrent-state or compute buffer of more than 0 MiB under a device its own `device_info` block
   * lists as a GPU (that label, or `<label>_<suffix>`, a mapped buffer of it).
   *
   * NOT the offload line. b9849 and b11146 print `offloaded 37/37 layers to GPU` on a machine with
   * no usable device and under `--device none`, every buffer on the processor (`CPU_REPACK`), so the
   * layer count says nothing about a card (`placement-b11146-gpuless-37of37-cpu.txt`). Nor "any
   * buffer `isCpuDevice` does not claim": that rule is a blacklist, and ggml's CPU backend has extra
   * buffer types it does not name, such as `AMX` on a Sapphire Rapids CPU (the shipped
   * `ggml-cpu-sapphirerapids.dll` carries it). A start that offloads 0 layers beside a visible card
   * still reserves its compute buffer there and runs the prefill on it
   * (`placement-b11146-ngl0-0of37-compute.txt`: 74 % card load, 302 tok/s against 56 with
   * `--device none`), so that buffer counts as the card in use. Not a field of the reading on
   * purpose: the reading is the persisted `ModelPlacement` shape.
   */
  holdsGpuBuffers: () => boolean
  /**
   * #671: `holdsGpuBuffers` as evidence BOTH ways, for a reader that has no probe to fall back on
   * (the translation sidecar). `true` = GPU buffers; `false` = the log filed buffers and every one
   * under a CPU-side label (`CPU`, `CPU_Mapped`, `CPU_REPACK`, `<Backend>_Host`), as a start with no
   * usable graphics device or under `--device none` does (both still print `offloaded 49/49 layers
   * to GPU`); `null` = nothing to judge by: no buffer filed, or one under a label that is neither
   * CPU-side nor a listed GPU — ggml's `AMX`, or a `device_info` block this parser cannot read,
   * which must not turn a start on the card into "the processor".
   */
  gpuBufferEvidence: () => boolean | null
}

function isCpuDevice(name: string): boolean {
  const upper = name.toUpperCase()
  return upper.startsWith('CPU') || upper.endsWith('_HOST')
}

const round2 = (mb: number): number => Math.round(mb * 100) / 100

/** One parser per start attempt: a retried rung gets a fresh reading. */
export function createPlacementParser(): PlacementParser {
  const r: Omit<PlacementReading, 'devices'> = {
    gpuLayers: null,
    totalLayers: null,
    gpuModelMb: null,
    cpuModelMb: null,
    gpuKvMb: null,
    cpuKvMb: null,
    gpuRsMb: null,
    cpuRsMb: null,
    metalMaxWorkingSetMb: null,
    gpuFreeAtStartMb: null,
    gpuComputeMb: null
  }
  /** The GPU rows of the `device_info` block, in log order. */
  const rows: Array<Omit<PlacementDevice, 'computeMb'>> = []
  /** Compute buffers of CLOSED contexts by device LABEL — joined onto the rows in `reading()`. */
  const computeByLabel = new Map<string, number>()
  /** The OPEN context's largest compute buffer per device label (one buffer per context per backend). */
  const openContext = new Map<string, number>()
  /** #653: the labels every non-empty model / KV / RS / compute buffer was filed under. */
  const bufferLabels = new Set<string>()
  let pending = ''
  const add = (
    key: 'gpuModelMb' | 'cpuModelMb' | 'gpuKvMb' | 'cpuKvMb' | 'gpuRsMb' | 'cpuRsMb' | 'gpuComputeMb',
    mb: number
  ): void => {
    r[key] = round2((r[key] ?? 0) + mb)
  }
  const filed = (label: string, mb: number): void => {
    if (mb > 0) bufferLabels.add(label)
  }
  /** Bank the open context's buffers and start a fresh one (contexts SUM, lines within one MAX). */
  const closeContext = (): void => {
    for (const [label, mb] of openContext) {
      add('gpuComputeMb', mb)
      computeByLabel.set(label, round2((computeByLabel.get(label) ?? 0) + mb))
    }
    openContext.clear()
  }
  const line = (text: string): void => {
    const off = OFFLOAD_RE.exec(text)
    if (off) {
      r.gpuLayers = Number(off[1])
      r.totalLayers = Number(off[2])
      return
    }
    const model = MODEL_BUFFER_RE.exec(text)
    if (model) {
      add(isCpuDevice(model[1]) ? 'cpuModelMb' : 'gpuModelMb', Number(model[2]))
      filed(model[1], Number(model[2]))
      return
    }
    const kv = KV_BUFFER_RE.exec(text)
    if (kv) {
      add(isCpuDevice(kv[1]) ? 'cpuKvMb' : 'gpuKvMb', Number(kv[2]))
      filed(kv[1], Number(kv[2]))
      return
    }
    const rs = RS_BUFFER_RE.exec(text)
    if (rs) {
      add(isCpuDevice(rs[1]) ? 'cpuRsMb' : 'gpuRsMb', Number(rs[2]))
      filed(rs[1], Number(rs[2]))
      return
    }
    if (CONTEXT_START_RE.test(text)) {
      closeContext()
      return
    }
    const compute = COMPUTE_BUFFER_RE.exec(text)
    if (compute) {
      filed(compute[1], Number(compute[2]))
      // The `<Backend>_Host` compute buffer is host memory and appears on full offloads too,
      // so it is dropped rather than counted as spill.
      if (!isCpuDevice(compute[1])) {
        const mb = Number(compute[2])
        openContext.set(compute[1], Math.max(openContext.get(compute[1]) ?? 0, mb))
      }
      return
    }
    const metal = METAL_BUDGET_RE.exec(text)
    if (metal) {
      r.metalMaxWorkingSetMb = Math.round(Number(metal[1]))
      return
    }
    // Every GPU row is kept (label ↔ name is what lets the snapshot pick the selected device);
    // the FIRST one's free figure is the legacy summary field, the fit works against what was
    // free right then.
    const dev = DEVICE_INFO_RE.exec(text)
    if (dev && !isCpuDevice(dev[1])) {
      rows.push({ label: dev[1], name: dev[2], totalMb: Number(dev[3]), freeMb: Number(dev[4]) })
      if (r.gpuFreeAtStartMb == null) r.gpuFreeAtStartMb = Number(dev[4])
    }
  }
  // A CPU-side label never counts, even one a row label would match by prefix (`Vulkan_Host`
  // against a numberless `Vulkan` row; ggml numbers its devices today, so this is a backstop).
  const holdsGpuBuffers = (): boolean =>
    [...bufferLabels].some(
      (label) => !isCpuDevice(label) && rows.some((row) => label === row.label || label.startsWith(`${row.label}_`))
    )
  return {
    onStderrData: (text) => {
      pending += text
      let nl = pending.indexOf('\n')
      while (nl >= 0) {
        line(pending.slice(0, nl))
        pending = pending.slice(nl + 1)
        nl = pending.indexOf('\n')
      }
    },
    // A log can end mid-context (the last context is never "closed" by a following one), so the
    // reading FLUSHES the open one — on a copy, never destructively: `reading()` is called more
    // than once per start and must give the same answer each time.
    reading: () => {
      const byLabel = new Map(computeByLabel)
      let gpuComputeMb = r.gpuComputeMb
      for (const [label, mb] of openContext) {
        byLabel.set(label, round2((byLabel.get(label) ?? 0) + mb))
        gpuComputeMb = round2((gpuComputeMb ?? 0) + mb)
      }
      return {
        ...r,
        gpuComputeMb,
        devices: rows.map((row) => ({ ...row, computeMb: byLabel.get(row.label) ?? null }))
      }
    },
    holdsGpuBuffers,
    gpuBufferEvidence: () => {
      if (holdsGpuBuffers()) return true
      return bufferLabels.size > 0 && [...bufferLabels].every(isCpuDevice) ? false : null
    }
  }
}

let latest: ModelPlacement | null = null
let observer: ((placement: ModelPlacement) => void) | null = null

/** Record one successful start's placement (the ladder calls this once the rung is healthy). */
export function recordModelPlacement(placement: ModelPlacement): void {
  latest = placement
  try {
    observer?.(placement)
  } catch {
    /* persistence is an observer concern; it must never throw into a start */
  }
}

/** The last placement recorded this session, or null. */
export function latestModelPlacement(): ModelPlacement | null {
  return latest
}

/** Register the single persister (the IPC layer). Last registration wins. */
export function setModelPlacementObserver(cb: ((placement: ModelPlacement) => void) | null): void {
  observer = cb
}

/** Test seam. */
export function resetModelPlacementForTests(): void {
  latest = null
  observer = null
}