@orkestrel/train 0.0.1 → 0.0.2

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/core/constants.ts","../../../src/core/validators.ts","../../../src/core/fitters/SerialFitter.ts","../../../src/core/fitters/ThreadFitter.ts","../../../src/core/trainers/Trainer.ts","../../../src/core/helpers.ts","../../../src/core/finetuners/Finetuner.ts","../../../src/core/factories.ts"],"sourcesContent":["import type {\n\tAdapterTarget,\n\tArchitectureFamily,\n\tGGUFFormat,\n\tSectionTarget,\n\tThreadProgram,\n} from '@orkestrel/infer'\nimport type {\n\tFinetunerSchedule,\n\tMergeGGUFFormat,\n\tPEFTTargetSpec,\n\tPrecisionFormat,\n\tSectionTargetSpec,\n} from './types.js'\n\n/**\n * Holds the stratified fold count a trainer runs when its options name none.\n *\n * @remarks\n * One fold of the first repeat is the held calibration split, so with 5 folds a label of 17 rows\n * holds 3 or 4 rows out for calibration and fits on the rest. A label needs at least as many rows as\n * folds.\n *\n * @example\n * ```ts\n * TRAINER_FOLDS // 5\n * ```\n */\nexport const TRAINER_FOLDS = 5\n\n/**\n * Holds the fewest stratified folds a trainer runs.\n *\n * @remarks\n * The held fold leaves the others for the cross-validation that chooses the L2 strength, which needs\n * at least two.\n *\n * @example\n * ```ts\n * TRAINER_FOLD_FLOOR // 3\n * ```\n */\nexport const TRAINER_FOLD_FLOOR = 3\n\n/**\n * Holds the fold assignment count a trainer runs when its options name none.\n *\n * @example\n * ```ts\n * TRAINER_REPEATS // 1\n * ```\n */\nexport const TRAINER_REPEATS = 1\n\n/**\n * Holds the seed of the first fold assignment when a trainer's options name none.\n *\n * @example\n * ```ts\n * TRAINER_SEED // 0\n * ```\n */\nexport const TRAINER_SEED = 0\n\n/**\n * Holds the L2 grid a trainer chooses from when its options name none.\n *\n * @remarks\n * Round one's grid. The rare-class and layer probes fixed 0.1 from it; a caller who wants that\n * passes `[0.1]` and skips the choice.\n *\n * @example\n * ```ts\n * TRAINER_PENALTIES.includes(0.1) // true\n * ```\n */\nexport const TRAINER_PENALTIES: readonly number[] = Object.freeze([1e-4, 1e-3, 1e-2, 1e-1, 1])\n\n/**\n * Holds the number of full-batch Adam steps one head fit runs.\n *\n * @example\n * ```ts\n * FIT_STEPS // 300\n * ```\n */\nexport const FIT_STEPS = 300\n\n/**\n * Holds the Adam learning rate of a head fit.\n *\n * @example\n * ```ts\n * FIT_RATE // 0.01\n * ```\n */\nexport const FIT_RATE = 0.01\n\n/**\n * Holds Adam's first moment decay and the gain of each incoming gradient.\n *\n * @remarks\n * The gain is written as its own literal, 0.1, as the probes wrote it, because `1 - 0.9` rounds to\n * another double.\n *\n * @example\n * ```ts\n * ADAM_FIRST.decay // 0.9\n * ```\n */\nexport const ADAM_FIRST = Object.freeze({ decay: 0.9, gain: 0.1 })\n\n/**\n * Holds Adam's second moment decay and the gain of each incoming squared gradient.\n *\n * @example\n * ```ts\n * ADAM_SECOND.decay // 0.999\n * ```\n */\nexport const ADAM_SECOND = Object.freeze({ decay: 0.999, gain: 0.001 })\n\n/**\n * Holds the term Adam adds to each step's denominator.\n *\n * @example\n * ```ts\n * ADAM_EPSILON // 1e-8\n * ```\n */\nexport const ADAM_EPSILON = 1e-8\n\n/**\n * Maps each control slot of a thread fitter's shared protocol to its index in the control buffer.\n *\n * @remarks\n * `generation` counts the batches the calling thread has posted, `count` holds the posted batch's job\n * count, `next` hands out job indexes through `Atomics.add`, `idle` counts the workers that have\n * claimed past the last job, `halt` is 1 after an abort or a fault stops the workers, `fault` holds one\n * more than the index of the first job that threw, or 0, and `ready` counts the workers that started.\n *\n * @example\n * ```ts\n * FIT_SLOTS.next // 2\n * ```\n */\nexport const FIT_SLOTS = Object.freeze({\n\tgeneration: 0,\n\tcount: 1,\n\tnext: 2,\n\tidle: 3,\n\thalt: 4,\n\tfault: 5,\n\tready: 6,\n})\n\n/**\n * Holds the longest time, in milliseconds, a thread fitter blocks in its host's `wait` before it\n * reads the signal.\n *\n * @remarks\n * The fitter blocks the calling thread in slices of this length and yields a turn between them, so a\n * timer or another task can abort the signal. A fit job runs for seconds on a full-size problem, so\n * the fitter bounds no job by time: it stops the workers when the signal aborts between two slices.\n *\n * @example\n * ```ts\n * FIT_SLICE // 25\n * ```\n */\nexport const FIT_SLICE = 25\n\n/**\n * Holds the fewest jobs a thread fitter's shared regions hold at once.\n *\n * @remarks\n * A fitter's regions hold this many jobs or its host's size, whichever is more, and a longer job list\n * runs in batches of that many. A trainer's largest batch under the defaults is 25 jobs: 5 repeats of\n * 5 folds.\n *\n * @example\n * ```ts\n * FIT_BATCH // 64\n * ```\n */\nexport const FIT_BATCH = 64\n\n/**\n * Holds the most UTF-16 code units of a worker fault's text a thread fitter reports, its ending 0\n * included.\n *\n * @example\n * ```ts\n * FIT_MESSAGE // 256\n * ```\n */\nexport const FIT_MESSAGE = 256\n\n/**\n * Holds the program a thread fitter runs on every worker: the fit arithmetic and the job loop.\n *\n * @remarks\n * A worker starts from text, because the package ships one bundle per face. The program is written by\n * hand rather than built from the fit helpers' own text, because a function's text is the text the\n * running build holds: Vite's module runner, which runs the tests, rewrites an imported binding such\n * as `ADAM_FIRST` to a property of a generated import record, and a consumer's minifier renames every\n * binding. The arithmetic follows `computeStandard`, `buildFeatureMatrix`, `computeClassWeights`,\n * `computeProbabilities`, `computeErrors`, `computeGradient`, and `stepAdam` operation for operation,\n * and the tests hold every head it fits byte-equal to `SerialFitter`'s. The program reads the\n * generation, counts itself into the `ready` slot, reports ready, and waits for a batch. For each batch, it\n * claims job indexes through `Atomics.add` until they run out, fits each claimed job whole, writes the\n * job's means, scales, and model into the job's own result slot, then counts itself idle. It checks\n * the `halt` slot before each claim and each Adam step. A job that throws records its index and text\n * once and halts every worker.\n *\n * @example\n * ```ts\n * FIT_PROGRAM.source.startsWith('function serveThread(setup, post) {') // true\n * ```\n */\nexport const FIT_PROGRAM: ThreadProgram = Object.freeze({\n\tsource: `function serveThread(setup, post) {\n\tconst control = new Int32Array(setup.control)\n\tconst features = new Float32Array(setup.features)\n\tconst labels = new Int32Array(setup.labels)\n\tconst members = new Uint8Array(setup.members)\n\tconst penalties = new Float64Array(setup.penalties)\n\tconst results = new Float64Array(setup.results)\n\tconst message = new Uint16Array(setup.message)\n\tlet seen = Atomics.load(control, ${FIT_SLOTS.generation})\n\tAtomics.add(control, ${FIT_SLOTS.ready}, 1)\n\tpost({ ready: true })\n\tfor (;;) {\n\t\tAtomics.wait(control, ${FIT_SLOTS.generation}, seen)\n\t\tseen = Atomics.load(control, ${FIT_SLOTS.generation})\n\t\tconst count = Atomics.load(control, ${FIT_SLOTS.count})\n\t\tfor (;;) {\n\t\t\tif (Atomics.load(control, ${FIT_SLOTS.halt}) !== 0) break\n\t\t\tconst job = Atomics.add(control, ${FIT_SLOTS.next}, 1)\n\t\t\tif (job >= count) break\n\t\t\ttry {\n\t\t\t\tfitJob(\n\t\t\t\t\tsetup,\n\t\t\t\t\tcontrol,\n\t\t\t\t\tfeatures,\n\t\t\t\t\tlabels,\n\t\t\t\t\tmembers.subarray(job * setup.rows, (job + 1) * setup.rows),\n\t\t\t\t\tpenalties[job],\n\t\t\t\t\tresults.subarray(job * setup.stride, (job + 1) * setup.stride),\n\t\t\t\t)\n\t\t\t} catch (error) {\n\t\t\t\tif (Atomics.compareExchange(control, ${FIT_SLOTS.fault}, 0, job + 1) === 0) {\n\t\t\t\t\tconst text = error instanceof Error ? error.message : String(error)\n\t\t\t\t\tconst length = Math.min(text.length, message.length - 1)\n\t\t\t\t\tfor (let unit = 0; unit < length; unit += 1) message[unit] = text.charCodeAt(unit)\n\t\t\t\t\tmessage[length] = 0\n\t\t\t\t}\n\t\t\t\tAtomics.store(control, ${FIT_SLOTS.halt}, 1)\n\t\t\t}\n\t\t}\n\t\tAtomics.add(control, ${FIT_SLOTS.idle}, 1)\n\t\tAtomics.notify(control, ${FIT_SLOTS.idle})\n\t}\n}\n\nfunction fitJob(setup, control, features, labels, member, penalty, result) {\n\tconst columns = setup.columns\n\tconst classes = setup.classes\n\tconst picked = []\n\tfor (let row = 0; row < setup.rows; row += 1) if (member[row] === 1) picked.push(row)\n\tconst count = picked.length\n\tconst mean = new Float64Array(columns)\n\tfor (let column = 0; column < columns; column += 1) {\n\t\tlet sum = 0\n\t\tfor (let place = 0; place < count; place += 1) sum += features[picked[place] * columns + column] / count\n\t\tmean[column] = sum\n\t}\n\tconst variance = new Float64Array(columns)\n\tfor (let column = 0; column < columns; column += 1) {\n\t\tlet sum = 0\n\t\tfor (let place = 0; place < count; place += 1) {\n\t\t\tconst gap = features[picked[place] * columns + column] - mean[column]\n\t\t\tsum += (gap * gap) / count\n\t\t}\n\t\tvariance[column] = sum\n\t}\n\tconst scale = new Float64Array(columns)\n\tfor (let column = 0; column < columns; column += 1) {\n\t\tconst deviation = Math.sqrt(variance[column])\n\t\tscale[column] = deviation > 0 ? deviation : 1\n\t}\n\tconst values = new Float64Array(count * columns)\n\tfor (let place = 0; place < count; place += 1) {\n\t\tfor (let column = 0; column < columns; column += 1) {\n\t\t\tvalues[place * columns + column] = (features[picked[place] * columns + column] - mean[column]) / scale[column]\n\t\t}\n\t}\n\tconst transpose = new Float64Array(count * columns)\n\tfor (let column = 0; column < columns; column += 1) {\n\t\tfor (let place = 0; place < count; place += 1) transpose[column * count + place] = values[place * columns + column]\n\t}\n\tconst matrix = { rows: count, columns, values, transpose }\n\tconst targets = picked.map((row) => labels[row])\n\tconst counts = new Array(classes).fill(0)\n\tfor (const label of targets) counts[label] += 1\n\tconst weights = Float64Array.from(targets, (label) => count / (classes * counts[label]))\n\tconst outputs = classes === 2 ? 1 : classes\n\tconst size = outputs * (columns + 1)\n\tlet state = { model: new Float64Array(size), first: new Float64Array(size), second: new Float64Array(size) }\n\tfor (let step = 1; step <= ${FIT_STEPS}; step += 1) {\n\t\tif (Atomics.load(control, ${FIT_SLOTS.halt}) !== 0) return\n\t\tconst probabilities = computeProbabilities(state.model, matrix, outputs)\n\t\tconst errors = computeErrors(probabilities, targets, weights, outputs)\n\t\tconst gradient = computeGradient(errors, matrix, outputs, state.model, penalty)\n\t\tstate = stepAdam(state, gradient, step, ${FIT_RATE})\n\t}\n\tresult.set(mean, 0)\n\tresult.set(scale, columns)\n\tresult.set(state.model, 2 * columns)\n}\n\nfunction computeLogistic(value) {\n\tif (value >= 0) return 1 / (1 + Math.exp(-value))\n\tconst exponent = Math.exp(value)\n\treturn exponent / (1 + exponent)\n}\n\nfunction computeProbabilities(model, matrix, outputs) {\n\tconst { rows, columns, values } = matrix\n\tconst stride = columns + 1\n\tconst blocked = rows - (rows % 4)\n\tconst logits = new Float64Array(rows * outputs)\n\tfor (let row = 0; row < blocked; row += 4) {\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tconst weight = output * stride\n\t\t\tconst bias = model[weight + columns]\n\t\t\tconst one = row * columns\n\t\t\tconst two = one + columns\n\t\t\tconst three = two + columns\n\t\t\tconst four = three + columns\n\t\t\tlet first = bias\n\t\t\tlet second = bias\n\t\t\tlet third = bias\n\t\t\tlet fourth = bias\n\t\t\tfor (let column = 0; column < columns; column += 1) {\n\t\t\t\tconst coefficient = model[weight + column]\n\t\t\t\tfirst += coefficient * values[one + column]\n\t\t\t\tsecond += coefficient * values[two + column]\n\t\t\t\tthird += coefficient * values[three + column]\n\t\t\t\tfourth += coefficient * values[four + column]\n\t\t\t}\n\t\t\tlogits[row * outputs + output] = first\n\t\t\tlogits[(row + 1) * outputs + output] = second\n\t\t\tlogits[(row + 2) * outputs + output] = third\n\t\t\tlogits[(row + 3) * outputs + output] = fourth\n\t\t}\n\t}\n\tfor (let row = blocked; row < rows; row += 1) {\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tlet sum = model[output * stride + columns]\n\t\t\tfor (let column = 0; column < columns; column += 1) {\n\t\t\t\tsum += model[output * stride + column] * values[row * columns + column]\n\t\t\t}\n\t\t\tlogits[row * outputs + output] = sum\n\t\t}\n\t}\n\tconst probabilities = new Float64Array(rows * outputs)\n\tif (outputs === 1) {\n\t\tfor (let row = 0; row < rows; row += 1) probabilities[row] = computeLogistic(logits[row])\n\t\treturn probabilities\n\t}\n\tfor (let row = 0; row < rows; row += 1) {\n\t\tlet peak = Number.NEGATIVE_INFINITY\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tpeak = Math.max(peak, logits[row * outputs + output])\n\t\t}\n\t\tlet mass = 0\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tmass += Math.exp(logits[row * outputs + output] - peak)\n\t\t}\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tprobabilities[row * outputs + output] = Math.exp(logits[row * outputs + output] - peak) / mass\n\t\t}\n\t}\n\treturn probabilities\n}\n\nfunction computeErrors(probabilities, labels, weights, outputs) {\n\tconst rows = labels.length\n\tconst errors = new Float64Array(outputs * rows)\n\tfor (let output = 0; output < outputs; output += 1) {\n\t\tfor (let row = 0; row < rows; row += 1) {\n\t\t\tconst target = labels[row] === output ? 1 : 0\n\t\t\terrors[output * rows + row] = ((probabilities[row * outputs + output] - target) * weights[row]) / rows\n\t\t}\n\t}\n\treturn errors\n}\n\nfunction computeGradient(errors, matrix, outputs, model, penalty) {\n\tconst { rows, columns, transpose } = matrix\n\tconst stride = columns + 1\n\tconst blocked = columns - (columns % 4)\n\tconst gradient = new Float64Array(outputs * stride)\n\tfor (let column = 0; column < blocked; column += 4) {\n\t\tconst one = column * rows\n\t\tconst two = one + rows\n\t\tconst three = two + rows\n\t\tconst four = three + rows\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tconst error = output * rows\n\t\t\tconst weight = output * stride\n\t\t\tlet first = 0\n\t\t\tlet second = 0\n\t\t\tlet third = 0\n\t\t\tlet fourth = 0\n\t\t\tfor (let row = 0; row < rows; row += 1) {\n\t\t\t\tconst term = errors[error + row]\n\t\t\t\tfirst += term * transpose[one + row]\n\t\t\t\tsecond += term * transpose[two + row]\n\t\t\t\tthird += term * transpose[three + row]\n\t\t\t\tfourth += term * transpose[four + row]\n\t\t\t}\n\t\t\tgradient[weight + column] = first + penalty * model[weight + column]\n\t\t\tgradient[weight + column + 1] = second + penalty * model[weight + column + 1]\n\t\t\tgradient[weight + column + 2] = third + penalty * model[weight + column + 2]\n\t\t\tgradient[weight + column + 3] = fourth + penalty * model[weight + column + 3]\n\t\t}\n\t}\n\tfor (let column = blocked; column < columns; column += 1) {\n\t\tconst base = column * rows\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tconst error = output * rows\n\t\t\tlet sum = 0\n\t\t\tfor (let row = 0; row < rows; row += 1) {\n\t\t\t\tsum += errors[error + row] * transpose[base + row]\n\t\t\t}\n\t\t\tgradient[output * stride + column] = sum + penalty * model[output * stride + column]\n\t\t}\n\t}\n\tfor (let output = 0; output < outputs; output += 1) {\n\t\tconst error = output * rows\n\t\tlet bias = 0\n\t\tfor (let row = 0; row < rows; row += 1) bias += errors[error + row]\n\t\tgradient[output * stride + columns] = bias\n\t}\n\treturn gradient\n}\n\nfunction stepAdam(state, gradient, step, rate) {\n\tconst firstScale = 1 - Math.pow(${ADAM_FIRST.decay}, step)\n\tconst secondScale = 1 - Math.pow(${ADAM_SECOND.decay}, step)\n\tconst first = new Float64Array(gradient.length)\n\tconst second = new Float64Array(gradient.length)\n\tconst model = new Float64Array(state.model.length)\n\tfor (let index = 0; index < first.length; index += 1) {\n\t\tconst value = gradient[index]\n\t\tfirst[index] = ${ADAM_FIRST.decay} * state.first[index] + ${ADAM_FIRST.gain} * value\n\t\tsecond[index] = ${ADAM_SECOND.decay} * state.second[index] + ${ADAM_SECOND.gain} * value * value\n\t}\n\tfor (let index = 0; index < model.length; index += 1) {\n\t\tmodel[index] =\n\t\t\tstate.model[index] -\n\t\t\t(rate * (first[index] / firstScale)) / (Math.sqrt(second[index] / secondScale) + ${ADAM_EPSILON})\n\t}\n\treturn { model, first, second }\n}\n`,\n})\n\n/**\n * Holds the number of Adam steps a calibration fit runs.\n *\n * @example\n * ```ts\n * CALIBRATION_STEPS // 2000\n * ```\n */\nexport const CALIBRATION_STEPS = 2000\n\n/**\n * Holds the Adam learning rate of a calibration fit.\n *\n * @example\n * ```ts\n * CALIBRATION_RATE // 0.01\n * ```\n */\nexport const CALIBRATION_RATE = 0.01\n\n/**\n * Holds the weight of the unit Gaussian prior on the log temperature and on each calibration bias.\n *\n * @remarks\n * The prior counts as one held row, so it moves a calibration fitted on hundreds of rows by little\n * and holds it finite when the held rows separate.\n *\n * @example\n * ```ts\n * CALIBRATION_PRIOR // 1\n * ```\n */\nexport const CALIBRATION_PRIOR = 1\n\n/**\n * Lists the members of a training row, in the order a refusal names them.\n *\n * @example\n * ```ts\n * ROW_KEYS // ['state', 'label']\n * ```\n */\nexport const ROW_KEYS: readonly string[] = Object.freeze(['state', 'label'])\n\n/**\n * Holds the extension of a head file's name.\n *\n * @example\n * ```ts\n * HEAD_FILE_EXTENSION // '.gguf'\n * ```\n */\nexport const HEAD_FILE_EXTENSION = '.gguf'\n\n/**\n * Holds the `general.type` value written into every GGUF v3 training checkpoint.\n *\n * @example\n * ```ts\n * CHECKPOINT_TYPE // 'checkpoint'\n * ```\n */\nexport const CHECKPOINT_TYPE = 'checkpoint'\n\n/**\n * Holds the schema version written to `orkestrel.checkpoint.version`.\n *\n * @example\n * ```ts\n * CHECKPOINT_VERSION // 1\n * ```\n */\nexport const CHECKPOINT_VERSION = 1\n\n/**\n * Lists the admitted training checkpoint modes.\n *\n * @example\n * ```ts\n * CHECKPOINT_MODES // ['adapter', 'section']\n * ```\n */\nexport const CHECKPOINT_MODES: readonly ['adapter', 'section'] = Object.freeze([\n\t'adapter',\n\t'section',\n])\n\n/**\n * Maps each GGUF metadata key of a training checkpoint to its canonical key name.\n *\n * @example\n * ```ts\n * CHECKPOINT_KEYS.version // 'orkestrel.checkpoint.version'\n * ```\n */\nexport const CHECKPOINT_KEYS = Object.freeze({\n\ttype: 'general.type',\n\tversion: 'orkestrel.checkpoint.version',\n\tmode: 'orkestrel.checkpoint.mode',\n\tbase: 'orkestrel.checkpoint.base',\n\tdataset: 'orkestrel.checkpoint.dataset',\n\tstep: 'orkestrel.checkpoint.step',\n\tepoch: 'orkestrel.checkpoint.epoch',\n\tcursor: 'orkestrel.checkpoint.cursor',\n\tseed: 'orkestrel.checkpoint.seed',\n\trng: 'orkestrel.checkpoint.rng',\n\tfold: 'orkestrel.checkpoint.fold',\n\tconfig: 'orkestrel.checkpoint.config',\n\ttargets: 'orkestrel.checkpoint.targets',\n} as const)\n\n/**\n * Maps each tensor role in a target triple to its GGUF tensor name prefix.\n *\n * @example\n * ```ts\n * CHECKPOINT_TENSOR_PREFIXES.first // 'adam.m.'\n * ```\n */\nexport const CHECKPOINT_TENSOR_PREFIXES = Object.freeze({\n\tparameters: 'param.',\n\tfirst: 'adam.m.',\n\tsecond: 'adam.v.',\n} as const)\n\n/**\n * Holds the frozen pattern that every valid checkpoint store identifier matches.\n *\n * @remarks\n * Admits 1 to 128 ASCII letters, digits, underscores, hyphens, and interior single periods, while\n * refusing empty strings, `.`, `..`, path separators, NUL bytes, trailing or repeated periods, and\n * case-insensitive Windows reserved device names (`CON`, `PRN`, `AUX`, `NUL`, `COM1`–`COM9`,\n * `LPT1`–`LPT9`, bare or before `.`).\n *\n * @example\n * ```ts\n * CHECKPOINT_ID_PATTERN.test('run-1.step_10') // true\n * CHECKPOINT_ID_PATTERN.test('../parent') // false\n * CHECKPOINT_ID_PATTERN.test('nul.step1') // false\n * ```\n */\nexport const CHECKPOINT_ID_PATTERN: RegExp = Object.freeze(\n\t/^(?!(?:[Cc][Oo][Nn]|[Pp][Rr][Nn]|[Aa][Uu][Xx]|[Nn][Uu][Ll]|[Cc][Oo][Mm][1-9]|[Ll][Pp][Tt][1-9])(?:\\.|$))[A-Za-z0-9](?:[A-Za-z0-9_-]|\\.(?=[A-Za-z0-9_-])){0,127}$/u,\n)\n\n/**\n * Holds the extension appended to stored checkpoint GGUF files.\n *\n * @example\n * ```ts\n * CHECKPOINT_FILE_EXTENSION // '.gguf'\n * ```\n */\nexport const CHECKPOINT_FILE_EXTENSION = '.gguf'\n\n/**\n * Holds the canonical Hugging Face PEFT layer prefix for Llama-family adapters and the alias prefix\n * admitted on Qwen3.5 PEFT import.\n *\n * @example\n * ```ts\n * PEFT_LAYERS_PREFIX // 'base_model.model.model.layers.'\n * ```\n */\nexport const PEFT_LAYERS_PREFIX = 'base_model.model.model.layers.'\n\n/**\n * Holds the canonical Hugging Face PEFT layer prefix for Qwen3.5 adapters.\n *\n * @example\n * ```ts\n * PEFT_QWEN35_PREFIX // 'base_model.model.model.language_model.layers.'\n * ```\n */\nexport const PEFT_QWEN35_PREFIX = 'base_model.model.model.language_model.layers.'\n\n/**\n * Holds the base Hugging Face safetensors layer prefix for Llama checkpoints and Qwen3.5 aliases.\n *\n * @example\n * ```ts\n * PEFT_BASE_LAYERS_PREFIX // 'model.layers.'\n * ```\n */\nexport const PEFT_BASE_LAYERS_PREFIX = 'model.layers.'\n\n/**\n * Holds the canonical base Hugging Face safetensors layer prefix for Qwen3.5 checkpoints.\n *\n * @example\n * ```ts\n * PEFT_BASE_QWEN35_PREFIX // 'model.language_model.layers.'\n * ```\n */\nexport const PEFT_BASE_QWEN35_PREFIX = 'model.language_model.layers.'\n\n/**\n * Maps each GGUF LoRA target stem to its Hugging Face PEFT module path, leaf stem, and admitted\n * decoder families.\n *\n * @example\n * ```ts\n * PEFT_TARGET_SPECS.attn_qkv.module // 'linear_attn.in_proj_qkv'\n * ```\n */\nexport const PEFT_TARGET_SPECS: Readonly<Record<AdapterTarget, PEFTTargetSpec>> = Object.freeze({\n\tattn_q: Object.freeze({\n\t\tmodule: 'self_attn.q_proj',\n\t\tleaf: 'q_proj',\n\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t}),\n\tattn_k: Object.freeze({\n\t\tmodule: 'self_attn.k_proj',\n\t\tleaf: 'k_proj',\n\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t}),\n\tattn_v: Object.freeze({\n\t\tmodule: 'self_attn.v_proj',\n\t\tleaf: 'v_proj',\n\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t}),\n\tattn_output: Object.freeze({\n\t\tmodule: 'self_attn.o_proj',\n\t\tleaf: 'o_proj',\n\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t}),\n\tattn_qkv: Object.freeze({\n\t\tmodule: 'linear_attn.in_proj_qkv',\n\t\tleaf: 'in_proj_qkv',\n\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t}),\n\tattn_gate: Object.freeze({\n\t\tmodule: 'linear_attn.in_proj_z',\n\t\tleaf: 'in_proj_z',\n\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t}),\n\tssm_beta: Object.freeze({\n\t\tmodule: 'linear_attn.in_proj_b',\n\t\tleaf: 'in_proj_b',\n\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t}),\n\tssm_alpha: Object.freeze({\n\t\tmodule: 'linear_attn.in_proj_a',\n\t\tleaf: 'in_proj_a',\n\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t}),\n\tssm_out: Object.freeze({\n\t\tmodule: 'linear_attn.out_proj',\n\t\tleaf: 'out_proj',\n\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t}),\n\tffn_gate: Object.freeze({\n\t\tmodule: 'mlp.gate_proj',\n\t\tleaf: 'gate_proj',\n\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t}),\n\tffn_up: Object.freeze({\n\t\tmodule: 'mlp.up_proj',\n\t\tleaf: 'up_proj',\n\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t}),\n\tffn_down: Object.freeze({\n\t\tmodule: 'mlp.down_proj',\n\t\tleaf: 'down_proj',\n\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t}),\n})\n\n/**\n * Matches one Hugging Face PEFT LoRA safetensors tensor name under either the canonical Llama\n * prefix or the canonical Qwen3.5 `language_model` prefix.\n *\n * @example\n * ```ts\n * PEFT_TENSOR_PATTERN.test('base_model.model.model.layers.0.self_attn.q_proj.lora_A.weight') // true\n * ```\n */\nexport const PEFT_TENSOR_PATTERN: RegExp = Object.freeze(\n\t/^base_model\\.model\\.model\\.(language_model\\.)?layers\\.(0|[1-9][0-9]*)\\.([a-z0-9_]+\\.[a-z0-9_]+)\\.lora_(A|B)\\.weight$/u,\n)\n\n/**\n * Lists the output tensor formats admitted for targeted merged tensors in `mergeGGUF`.\n *\n * @example\n * ```ts\n * MERGE_GGUF_FORMATS // ['F32', 'BF16', 'Q8_0', 'Q4_K']\n * ```\n */\nexport const MERGE_GGUF_FORMATS: readonly MergeGGUFFormat[] = Object.freeze([\n\t'F32',\n\t'BF16',\n\t'Q8_0',\n\t'Q4_K',\n])\n\n/**\n * Lists the base GGUF tensor formats that `mergeGGUF` widens when a LoRA pair targets the tensor.\n *\n * @example\n * ```ts\n * MERGE_SOURCE_FORMATS.includes('Q8_0') // true\n * ```\n */\nexport const MERGE_SOURCE_FORMATS: readonly GGUFFormat[] = Object.freeze([\n\t'F32',\n\t'F16',\n\t'BF16',\n\t'Q5_0',\n\t'Q8_0',\n\t'Q4_K',\n\t'Q6_K',\n])\n\n/**\n * Holds the default maximum slice size in bytes when streaming untargeted tensors during merge.\n *\n * @example\n * ```ts\n * MERGE_CHUNK_BYTES // 1048576\n * ```\n */\nexport const MERGE_CHUNK_BYTES = 1_048_576\n\n/**\n * Holds the default row strip height processed per slice when merging targeted weight tensors.\n *\n * @example\n * ```ts\n * MERGE_ROW_STRIP // 256\n * ```\n */\nexport const MERGE_ROW_STRIP = 256\n\n/**\n * Lists the default candidate LoRA scales swept by `calibrateAdapter`.\n *\n * @example\n * ```ts\n * ADAPTER_CALIBRATION_SCALES // [0, 0.25, 0.5, 0.75, 1, 1.25, 1.5]\n * ```\n */\nexport const ADAPTER_CALIBRATION_SCALES: readonly number[] = Object.freeze([\n\t0, 0.25, 0.5, 0.75, 1, 1.25, 1.5,\n])\n\n/**\n * Lists the precision and quantization formats admitted by full-vs-compressed shift comparisons.\n *\n * @example\n * ```ts\n * PRECISION_FORMATS // ['BF16', 'Q8_0', 'Q4_K_M']\n * ```\n */\nexport const PRECISION_FORMATS: readonly PrecisionFormat[] = Object.freeze([\n\t'BF16',\n\t'Q8_0',\n\t'Q4_K_M',\n])\n\n/**\n * Holds the default peak learning rate for `Finetuner`.\n *\n * @example\n * ```ts\n * FINETUNER_RATE // 0.0001\n * ```\n */\nexport const FINETUNER_RATE = 1e-4\n\n/**\n * Holds the default decoupled AdamW weight decay for `Finetuner`.\n *\n * @example\n * ```ts\n * FINETUNER_DECAY // 0.01\n * ```\n */\nexport const FINETUNER_DECAY = 0.01\n\n/**\n * Holds the default AdamW first-moment decay (`beta1`) for `Finetuner`.\n *\n * @example\n * ```ts\n * FINETUNER_FIRST // 0.9\n * ```\n */\nexport const FINETUNER_FIRST = 0.9\n\n/**\n * Holds the default AdamW second-moment decay (`beta2`) for `Finetuner`.\n *\n * @example\n * ```ts\n * FINETUNER_SECOND // 0.999\n * ```\n */\nexport const FINETUNER_SECOND = 0.999\n\n/**\n * Holds the default AdamW denominator stability floor for `Finetuner`.\n *\n * @example\n * ```ts\n * FINETUNER_EPSILON // 1e-8\n * ```\n */\nexport const FINETUNER_EPSILON = 1e-8\n\n/**\n * Holds the default global L2 gradient norm clip ceiling for `Finetuner`.\n *\n * @example\n * ```ts\n * FINETUNER_CLIP // 1\n * ```\n */\nexport const FINETUNER_CLIP = 1\n\n/**\n * Holds the default linear warmup step count for `Finetuner`.\n *\n * @example\n * ```ts\n * FINETUNER_WARMUP // 0\n * ```\n */\nexport const FINETUNER_WARMUP = 0\n\n/**\n * Lists the learning-rate decay schedules admitted by `Finetuner`.\n *\n * @example\n * ```ts\n * FINETUNER_SCHEDULES // ['cosine', 'constant']\n * ```\n */\nexport const FINETUNER_SCHEDULES: readonly FinetunerSchedule[] = Object.freeze([\n\t'cosine',\n\t'constant',\n])\n\n/**\n * Holds the default epoch count for `Finetuner`.\n *\n * @example\n * ```ts\n * FINETUNER_EPOCHS // 1\n * ```\n */\nexport const FINETUNER_EPOCHS = 1\n\n/**\n * Holds the default mini-batch example accumulation count for `Finetuner`.\n *\n * @example\n * ```ts\n * FINETUNER_BATCH // 1\n * ```\n */\nexport const FINETUNER_BATCH = 1\n\n/**\n * Holds the default token length limit for `Finetuner` examples.\n *\n * @example\n * ```ts\n * FINETUNER_LIMIT // 2048\n * ```\n */\nexport const FINETUNER_LIMIT = 2048\n\n/**\n * Holds the default deterministic PRNG seed for `Finetuner`.\n *\n * @example\n * ```ts\n * FINETUNER_SEED // 0\n * ```\n */\nexport const FINETUNER_SEED = 0\n\n/**\n * Holds the `general.type` value written into every GGUF v3 section patch file.\n *\n * @example\n * ```ts\n * SECTION_PATCH_TYPE // 'patch'\n * ```\n */\nexport const SECTION_PATCH_TYPE = 'patch'\n\n/**\n * Holds the schema version written to `orkestrel.patch.version` in every section patch GGUF file.\n *\n * @example\n * ```ts\n * SECTION_PATCH_VERSION // 1\n * ```\n */\nexport const SECTION_PATCH_VERSION = 1\n\n/**\n * Maps each full-rank `SectionTarget` stem to its Hugging Face safetensors tensor suffix, root\n * placement flag, and admitted decoder families.\n *\n * @example\n * ```ts\n * SECTION_SAFETENSORS_SPECS.ffn_down.suffix // 'mlp.down_proj.weight'\n * ```\n */\nexport const SECTION_SAFETENSORS_SPECS: Readonly<Record<SectionTarget, SectionTargetSpec>> =\n\tObject.freeze({\n\t\tattn_norm: Object.freeze({\n\t\t\tsuffix: 'input_layernorm.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t\t}),\n\t\tattn_q: Object.freeze({\n\t\t\tsuffix: 'self_attn.q_proj.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t\t}),\n\t\tattn_k: Object.freeze({\n\t\t\tsuffix: 'self_attn.k_proj.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t\t}),\n\t\tattn_v: Object.freeze({\n\t\t\tsuffix: 'self_attn.v_proj.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t\t}),\n\t\tattn_q_norm: Object.freeze({\n\t\t\tsuffix: 'self_attn.q_norm.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t\t}),\n\t\tattn_k_norm: Object.freeze({\n\t\t\tsuffix: 'self_attn.k_norm.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t\t}),\n\t\tattn_output: Object.freeze({\n\t\t\tsuffix: 'self_attn.o_proj.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t\t}),\n\t\tattn_qkv: Object.freeze({\n\t\t\tsuffix: 'linear_attn.in_proj_qkv.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t\t}),\n\t\tattn_gate: Object.freeze({\n\t\t\tsuffix: 'linear_attn.in_proj_z.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t\t}),\n\t\tssm_beta: Object.freeze({\n\t\t\tsuffix: 'linear_attn.in_proj_b.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t\t}),\n\t\tssm_alpha: Object.freeze({\n\t\t\tsuffix: 'linear_attn.in_proj_a.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t\t}),\n\t\tssm_conv1d: Object.freeze({\n\t\t\tsuffix: 'linear_attn.conv1d.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t\t}),\n\t\tssm_dt: Object.freeze({\n\t\t\tsuffix: 'linear_attn.dt_bias',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t\t}),\n\t\tssm_a: Object.freeze({\n\t\t\tsuffix: 'linear_attn.A_log',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t\t}),\n\t\tssm_norm: Object.freeze({\n\t\t\tsuffix: 'linear_attn.norm.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t\t}),\n\t\tssm_out: Object.freeze({\n\t\t\tsuffix: 'linear_attn.out_proj.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t\t}),\n\t\tffn_norm: Object.freeze({\n\t\t\tsuffix: 'post_attention_layernorm.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama']),\n\t\t}),\n\t\tpost_attention_norm: Object.freeze({\n\t\t\tsuffix: 'post_attention_layernorm.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t\t}),\n\t\tffn_gate: Object.freeze({\n\t\t\tsuffix: 'mlp.gate_proj.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t\t}),\n\t\tffn_up: Object.freeze({\n\t\t\tsuffix: 'mlp.up_proj.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t\t}),\n\t\tffn_down: Object.freeze({\n\t\t\tsuffix: 'mlp.down_proj.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t\t}),\n\t\ttoken_embd: Object.freeze({\n\t\t\tsuffix: 'embed_tokens.weight',\n\t\t\ttop: true,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t\t}),\n\t\toutput_norm: Object.freeze({\n\t\t\tsuffix: 'norm.weight',\n\t\t\ttop: true,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t\t}),\n\t\toutput: Object.freeze({\n\t\t\tsuffix: 'lm_head.weight',\n\t\t\ttop: true,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t\t}),\n\t})\n","import type {\n\tByteSinkInterface,\n\tCheckpoint,\n\tCheckpointMode,\n\tCheckpointTarget,\n\tFinetuneRow,\n\tFinetunerSchedule,\n\tMergeGGUFFormat,\n\tPEFTBundle,\n\tPEFTConfig,\n\tPrecisionFormat,\n\tTrainerRow,\n} from './types.js'\nimport {\n\tholds,\n\tisArray,\n\tisBoundedJSONRecord,\n\tisFiniteNumber,\n\tisFloat32Array,\n\tisFunction,\n\tisObject,\n\tisRecord,\n\tisSafeInteger,\n\tisString,\n\tisUint8Array,\n} from '@orkestrel/contract'\nimport { SHA256_PATTERN } from '@orkestrel/infer'\nimport { CHECKPOINT_ID_PATTERN, ROW_KEYS } from './constants.js'\n\n/**\n * Checks whether a value is a training row: a plain record of a string `state`, a string `label`,\n * and an optional non-empty string `group`.\n *\n * @remarks\n * A row is owned data, so a record carrying any other member, an empty `group`, or a non-string\n * `group` is refused. Never throws, whatever the value's accessors do.\n *\n * @param value - The value to inspect\n * @returns True if the value is a training row; false otherwise\n *\n * @example\n * ```ts\n * isTrainerRow({ state: 'user: hi', label: 'chatter' }) // true\n * isTrainerRow({ state: 'user: hi', label: 'chatter', group: 'conv-1' }) // true\n * isTrainerRow({ state: 'user: hi', label: 'chatter', group: '' }) // false\n * ```\n */\nexport function isTrainerRow(value: unknown): value is TrainerRow {\n\treturn holds(() => {\n\t\tif (!isRecord(value)) return false\n\t\tconst keys = Object.keys(value)\n\t\tif (!ROW_KEYS.every((key) => Object.hasOwn(value, key))) return false\n\t\tif (!keys.every((key) => ROW_KEYS.includes(key) || key === 'group')) return false\n\t\tif (!isString(value['state']) || !isString(value['label'])) return false\n\t\tif (Object.hasOwn(value, 'group')) {\n\t\t\treturn isString(value['group']) && value['group'].length > 0\n\t\t}\n\t\treturn true\n\t})\n}\n\n/**\n * Checks whether a value is a valid checkpoint store identifier matching `CHECKPOINT_ID_PATTERN`.\n *\n * @remarks\n * Never throws, whatever the value's accessors or prototype do.\n *\n * @param value - The value to inspect\n * @returns True if the value is a valid checkpoint identifier; false otherwise\n *\n * @example\n * ```ts\n * isCheckpointId('run-1.step_10') // true\n * isCheckpointId('../parent') // false\n * ```\n */\nexport function isCheckpointId(value: unknown): value is string {\n\treturn holds(() => isString(value) && CHECKPOINT_ID_PATTERN.test(value))\n}\n\n/**\n * Checks whether a value is an admitted checkpoint training mode (`'adapter'` or `'section'`).\n *\n * @param value - The value to inspect\n * @returns True if the value is an admitted mode; false otherwise\n *\n * @example\n * ```ts\n * isCheckpointMode('adapter') // true\n * isCheckpointMode('other') // false\n * ```\n */\nexport function isCheckpointMode(value: unknown): value is CheckpointMode {\n\treturn value === 'adapter' || value === 'section'\n}\n\n/**\n * Checks whether a value is a valid checkpoint target with positive dimensions and finite\n * single-precision parameter and Adam moment arrays of matching length.\n *\n * @remarks\n * Never throws, whatever the value's accessors do.\n *\n * @param value - The value to inspect\n * @returns True if the value is a valid checkpoint target; false otherwise\n *\n * @example\n * ```ts\n * isCheckpointTarget({\n * \tname: 'blk.0.attn_q.lora_a',\n * \trows: 1,\n * \tcolumns: 2,\n * \tparameters: Float32Array.of(0.1, 0.2),\n * \tfirst: Float32Array.of(0, 0),\n * \tsecond: Float32Array.of(0, 0),\n * }) // true\n * ```\n */\nexport function isCheckpointTarget(value: unknown): value is CheckpointTarget {\n\treturn holds(() => {\n\t\tif (!isRecord(value)) return false\n\t\tconst allowed: readonly string[] = ['name', 'rows', 'columns', 'parameters', 'first', 'second']\n\t\tconst keys = Object.keys(value)\n\t\tif (!allowed.every((key) => Object.hasOwn(value, key))) return false\n\t\tif (!keys.every((key) => allowed.includes(key))) return false\n\t\tconst { name, rows, columns, parameters, first, second } = value\n\t\tif (!isString(name) || name.length === 0 || name.includes('\\0')) return false\n\t\tif (!isSafeInteger(rows) || rows < 1 || !isSafeInteger(columns) || columns < 1) return false\n\t\tconst total = rows * columns\n\t\tif (!Number.isSafeInteger(total)) return false\n\t\tif (!isFloat32Array(parameters) || !isFloat32Array(first) || !isFloat32Array(second)) {\n\t\t\treturn false\n\t\t}\n\t\tif (parameters.length !== total || first.length !== total || second.length !== total) {\n\t\t\treturn false\n\t\t}\n\t\treturn (\n\t\t\tparameters.every(Number.isFinite) &&\n\t\t\tfirst.every(Number.isFinite) &&\n\t\t\tsecond.every(Number.isFinite)\n\t\t)\n\t})\n}\n\n/**\n * Checks whether a value is a valid resumable training checkpoint record.\n *\n * @remarks\n * Refuses undeclared members, missing required members, malformed digests, negative or fractional\n * counters, out-of-range generator states, non-finite seeds or tensors, duplicate target names, or\n * an explicit `undefined` `fold`. Never throws.\n *\n * @param value - The value to inspect\n * @returns True if the value is a valid checkpoint; false otherwise\n *\n * @example\n * ```ts\n * isCheckpoint({\n * \tmode: 'adapter',\n * \tbase: '0'.repeat(64),\n * \tdataset: '1'.repeat(64),\n * \tstep: 1,\n * \tepoch: 0,\n * \tcursor: 2,\n * \tseed: 7,\n * \trng: 7,\n * \tconfig: { rate: 0.01 },\n * \ttargets: [target],\n * }) // true\n * ```\n */\nexport function isCheckpoint(value: unknown): value is Checkpoint {\n\treturn holds(() => {\n\t\tif (!isRecord(value)) return false\n\t\tconst required: readonly string[] = [\n\t\t\t'mode',\n\t\t\t'base',\n\t\t\t'dataset',\n\t\t\t'step',\n\t\t\t'epoch',\n\t\t\t'cursor',\n\t\t\t'seed',\n\t\t\t'rng',\n\t\t\t'config',\n\t\t\t'targets',\n\t\t]\n\t\tconst keys = Object.keys(value)\n\t\tif (!required.every((key) => Object.hasOwn(value, key))) return false\n\t\tif (!keys.every((key) => key === 'fold' || required.includes(key))) {\n\t\t\treturn false\n\t\t}\n\t\tconst { mode, base, dataset, step, epoch, cursor, seed, rng, config, targets } = value\n\t\tif (!isCheckpointMode(mode)) return false\n\t\tif (!isString(base) || !SHA256_PATTERN.test(base)) return false\n\t\tif (!isString(dataset) || !SHA256_PATTERN.test(dataset)) return false\n\t\tif (!isSafeInteger(step) || step < 0) return false\n\t\tif (!isSafeInteger(epoch) || epoch < 0) return false\n\t\tif (!isSafeInteger(cursor) || cursor < 0) return false\n\t\tif (!isFiniteNumber(seed)) return false\n\t\tif (!isSafeInteger(rng) || rng < 0 || rng > 0xffff_ffff) return false\n\t\tif (Object.hasOwn(value, 'fold')) {\n\t\t\tconst fold = value['fold']\n\t\t\tif (!isSafeInteger(fold) || fold < 0) return false\n\t\t}\n\t\tif (!isBoundedJSONRecord(config)) return false\n\t\tif (!isArray(targets) || targets.length === 0 || !targets.every(isCheckpointTarget))\n\t\t\treturn false\n\t\treturn new Set(targets.map((target) => target.name)).size === targets.length\n\t})\n}\n\n/**\n * Checks whether a value is an admitted `adapter_config.json` wire record for standard LoRA\n * adapters (`peft_type: 'LORA'`, `bias: 'none'`, neither `use_rslora` nor `use_dora` enabled).\n *\n * @remarks\n * Never throws, whatever the value's accessors or prototype do.\n *\n * @param value - The value to inspect\n * @returns True if the value is a supported PEFT LoRA configuration; false otherwise\n *\n * @example\n * ```ts\n * isPEFTConfig({ peft_type: 'LORA', r: 4, lora_alpha: 8, target_modules: ['q_proj'], bias: 'none' }) // true\n * isPEFTConfig({ peft_type: 'LORA', r: 4, lora_alpha: 8, target_modules: ['q_proj'], bias: 'all' }) // false\n * ```\n */\nexport function isPEFTConfig(value: unknown): value is PEFTConfig {\n\treturn holds(() => {\n\t\tif (!isRecord(value)) return false\n\t\tif (value['peft_type'] !== 'LORA') return false\n\t\tconst rank = value['r']\n\t\tif (!isSafeInteger(rank) || rank < 1) return false\n\t\tconst alpha = value['lora_alpha']\n\t\tif (!isFiniteNumber(alpha) || alpha <= 0) return false\n\t\tconst modules = value['target_modules']\n\t\tif (\n\t\t\t!isArray(modules) ||\n\t\t\tmodules.length === 0 ||\n\t\t\t!modules.every((entry) => isString(entry) && entry.length > 0)\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\tif (value['bias'] !== 'none') return false\n\t\tif (Object.hasOwn(value, 'use_rslora') && value['use_rslora'] !== false) return false\n\t\tif (Object.hasOwn(value, 'use_dora') && value['use_dora'] !== false) return false\n\t\tif (Object.hasOwn(value, 'task_type') && !isString(value['task_type'])) return false\n\t\tif (\n\t\t\tObject.hasOwn(value, 'base_model_name_or_path') &&\n\t\t\t!isString(value['base_model_name_or_path'])\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t})\n}\n\n/**\n * Checks whether a value is a `PEFTBundle` carrying a valid `config` and `Uint8Array` `weights`.\n *\n * @remarks\n * Never throws, whatever the value's accessors or prototype do.\n *\n * @param value - The value to inspect\n * @returns True if the value is a PEFT bundle; false otherwise\n *\n * @example\n * ```ts\n * isPEFTBundle({ config, weights: new Uint8Array(8) }) // true\n * ```\n */\nexport function isPEFTBundle(value: unknown): value is PEFTBundle {\n\treturn holds(() => {\n\t\tif (!isRecord(value)) return false\n\t\treturn isPEFTConfig(value['config']) && isUint8Array(value['weights'])\n\t})\n}\n\n/**\n * Checks whether a value is an admitted output tensor format for `mergeGGUF` (`'F32'`, `'BF16'`,\n * `'Q8_0'`, or `'Q4_K'`).\n *\n * @param value - The value to inspect\n * @returns True if the value is an admitted merge GGUF format; false otherwise\n *\n * @example\n * ```ts\n * isMergeGGUFFormat('Q8_0') // true\n * isMergeGGUFFormat('F16') // false\n * ```\n */\nexport function isMergeGGUFFormat(value: unknown): value is MergeGGUFFormat {\n\treturn value === 'F32' || value === 'BF16' || value === 'Q8_0' || value === 'Q4_K'\n}\n\n/**\n * Checks whether a value is an admitted precision format for full-vs-compressed decision shift\n * comparisons (`'BF16'`, `'Q8_0'`, or `'Q4_K_M'`).\n *\n * @param value - The value to inspect\n * @returns True if the value is an admitted precision format; false otherwise\n *\n * @example\n * ```ts\n * isPrecisionFormat('Q4_K_M') // true\n * isPrecisionFormat('F32') // false\n * ```\n */\nexport function isPrecisionFormat(value: unknown): value is PrecisionFormat {\n\treturn value === 'BF16' || value === 'Q8_0' || value === 'Q4_K_M'\n}\n\n/**\n * Checks whether a value implements `ByteSinkInterface` (`write`, `close`, and optional `abort`).\n *\n * @remarks\n * Accepts both plain objects and class instances. Never throws.\n *\n * @param value - The value to inspect\n * @returns True if the value implements `ByteSinkInterface`; false otherwise\n *\n * @example\n * ```ts\n * isByteSink({ write() {}, close() {} }) // true\n * ```\n */\nexport function isByteSink(value: unknown): value is ByteSinkInterface {\n\treturn holds(() => {\n\t\tif (!isObject(value)) return false\n\t\tif (!isFunction(Reflect.get(value, 'write')) || !isFunction(Reflect.get(value, 'close'))) {\n\t\t\treturn false\n\t\t}\n\t\tconst abort: unknown = Reflect.get(value, 'abort')\n\t\treturn abort === undefined || isFunction(abort)\n\t})\n}\n\n/**\n * Checks whether a value is an admitted `Finetuner` learning-rate decay schedule (`'cosine'` or\n * `'constant'`).\n *\n * @param value - The value to inspect\n * @returns True if the value is an admitted schedule; false otherwise\n *\n * @example\n * ```ts\n * isFinetunerSchedule('cosine') // true\n * isFinetunerSchedule('linear') // false\n * ```\n */\nexport function isFinetunerSchedule(value: unknown): value is FinetunerSchedule {\n\treturn value === 'cosine' || value === 'constant'\n}\n\n/**\n * Checks whether a value is a structurally valid `FinetuneRow` carrying either a string `prompt`\n * or a non-empty `messages` array, a string `completion`, optional non-empty `group` and `label`,\n * and a record `provenance`.\n *\n * @remarks\n * Never throws, whatever the value's accessors do. Provenance field content and hosted-model\n * markers are verified separately by `checkRowProvenance`.\n *\n * @param value - The value to inspect\n * @returns True if the value is structurally a `FinetuneRow`; false otherwise\n *\n * @example\n * ```ts\n * isFinetuneRow({ prompt: 'user: hi\\nassistant: ', completion: 'hello', provenance }) // true\n * ```\n */\nexport function isFinetuneRow(value: unknown): value is FinetuneRow {\n\treturn holds(() => {\n\t\tif (!isRecord(value)) return false\n\t\tconst allowed: readonly string[] = [\n\t\t\t'prompt',\n\t\t\t'messages',\n\t\t\t'completion',\n\t\t\t'group',\n\t\t\t'label',\n\t\t\t'provenance',\n\t\t]\n\t\tconst keys = Object.keys(value)\n\t\tif (!keys.every((key) => allowed.includes(key))) return false\n\t\tif (!isString(value['completion'])) return false\n\t\tconst hasPrompt = Object.hasOwn(value, 'prompt') && value['prompt'] !== undefined\n\t\tconst hasMessages = Object.hasOwn(value, 'messages') && value['messages'] !== undefined\n\t\tif (hasPrompt === hasMessages) return false\n\t\tif (hasPrompt && !isString(value['prompt'])) return false\n\t\tif (\n\t\t\thasMessages &&\n\t\t\t(!isArray(value['messages']) ||\n\t\t\t\tvalue['messages'].length === 0 ||\n\t\t\t\t!value['messages'].every(isRecord))\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\tif (Object.hasOwn(value, 'group') && value['group'] !== undefined) {\n\t\t\tif (!isString(value['group']) || value['group'].length === 0) return false\n\t\t}\n\t\tif (Object.hasOwn(value, 'label') && value['label'] !== undefined) {\n\t\t\tif (!isString(value['label']) || value['label'].length === 0) return false\n\t\t}\n\t\treturn isRecord(value['provenance'])\n\t})\n}\n","import type { HeadWeights } from '@orkestrel/infer'\nimport type { AdamState, FitJob, FitTask, FitterContext, FitterInterface } from '../types.js'\nimport { checkSignal, InferError, yieldTurn } from '@orkestrel/infer'\nimport { FIT_RATE, FIT_STEPS } from '../constants.js'\nimport {\n\tbuildFeatureMatrix,\n\tbuildHeadWeights,\n\tcheckFitJobs,\n\tcheckFitterContext,\n\tcollectRows,\n\tcomputeClassWeights,\n\tcomputeErrors,\n\tcomputeGradient,\n\tcomputeOutputs,\n\tcomputeProbabilities,\n\tcomputeStandard,\n\tstepAdam,\n} from '../helpers.js'\n\n/**\n * Fits one head per job in turn on the calling thread.\n *\n * @remarks\n * The trainer's default fitter. `start` checks the context as `checkFitterContext` states and keeps\n * its own copy of the rows. `fit` checks the jobs as `checkFitJobs` states, then fits each job on its\n * rows, standardized on them, with inverse-frequency class weights, by `FIT_STEPS` full-batch Adam\n * steps at `FIT_RATE` from zero, yielding the thread and checking the signal before each step; on\n * abort it rejects with the `ABORT` code. A second `start` throws with the `ARGUMENT` code, as does a\n * `fit` before `start`; after `destroy`, both throw with the `DESTROYED` code.\n *\n * @example\n * ```ts\n * const fitter = new SerialFitter()\n * await fitter.start({ features, labels: [0, 0, 1, 1], classes: 2 })\n * const [head] = await fitter.fit([{ rows: [0, 1, 2, 3], penalty: 0.1 }])\n * await fitter.destroy()\n * ```\n */\nexport class SerialFitter implements FitterInterface {\n\t#context: FitterContext | undefined\n\t#destroyed = false\n\n\t/**\n\t * Takes the rows every later fit reads.\n\t *\n\t * @param context - The features, the labels, and the label count\n\t * @param signal - Cancels the start; it then rejects with the `ABORT` code\n\t */\n\tasync start(context: FitterContext, signal?: AbortSignal): Promise<void> {\n\t\tif (this.#destroyed) {\n\t\t\tthrow new InferError('The fitter has been destroyed.', { code: 'DESTROYED' })\n\t\t}\n\t\tif (this.#context !== undefined) {\n\t\t\tthrow new InferError('The fitter has already started; destroy it and create another.', {\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t})\n\t\t}\n\t\tcheckFitterContext(context)\n\t\tcheckSignal(signal, 'The fit start')\n\t\tthis.#context = {\n\t\t\tfeatures: context.features.map((feature) => Float32Array.from(feature)),\n\t\t\tlabels: [...context.labels],\n\t\t\tclasses: context.classes,\n\t\t}\n\t}\n\n\t/**\n\t * Fits one head per job and returns the heads in job order.\n\t *\n\t * @param jobs - The fits to run\n\t * @param signal - Cancels the fits; they then reject with the `ABORT` code\n\t * @returns Each job's head weights, in job order\n\t */\n\tasync fit(jobs: readonly FitJob[], signal?: AbortSignal): Promise<readonly HeadWeights[]> {\n\t\tconst context = this.#context\n\t\tif (context === undefined) {\n\t\t\tthrow this.#destroyed\n\t\t\t\t? new InferError('The fitter has been destroyed.', { code: 'DESTROYED' })\n\t\t\t\t: new InferError('The fitter has not started; start it with the rows its jobs read.', {\n\t\t\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\t\t})\n\t\t}\n\t\tcheckFitJobs(jobs, context.labels, context.classes)\n\t\tcheckSignal(signal, 'The fit')\n\t\tconst heads: HeadWeights[] = []\n\t\tfor (const job of jobs) heads.push(await this.#fit(context, job, signal))\n\t\treturn heads\n\t}\n\n\t/** Releases the rows; a second call does nothing. */\n\tasync destroy(): Promise<void> {\n\t\tthis.#destroyed = true\n\t\tthis.#context = undefined\n\t}\n\n\t// Fits one job on its rows, standardized on them, with inverse-frequency class weights.\n\tasync #fit(\n\t\tcontext: FitterContext,\n\t\tjob: FitJob,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<HeadWeights> {\n\t\tconst rows = collectRows(context.features, job.rows)\n\t\tconst labels = collectRows(context.labels, job.rows)\n\t\tconst standard = computeStandard(rows)\n\t\tconst matrix = buildFeatureMatrix(rows, standard)\n\t\tconst outputs = computeOutputs(context.classes)\n\t\tconst size = outputs * (matrix.columns + 1)\n\t\tconst task: FitTask = {\n\t\t\tmatrix,\n\t\t\tlabels,\n\t\t\tweights: computeClassWeights(labels, context.classes),\n\t\t\toutputs,\n\t\t\tpenalty: job.penalty,\n\t\t}\n\t\tconst state: AdamState = {\n\t\t\tmodel: new Float64Array(size),\n\t\t\tfirst: new Float64Array(size),\n\t\t\tsecond: new Float64Array(size),\n\t\t}\n\t\tconst fitted = await this.#descend(task, state, 1, signal)\n\t\treturn buildHeadWeights(fitted.model, standard, context.classes)\n\t}\n\n\t// Takes the Adam steps from `step` to FIT_STEPS, yielding the thread and checking the signal before\n\t// each one.\n\tasync #descend(\n\t\ttask: FitTask,\n\t\tstate: AdamState,\n\t\tstep: number,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<AdamState> {\n\t\tif (step > FIT_STEPS) return state\n\t\tcheckSignal(signal, 'The fit')\n\t\tawait yieldTurn()\n\t\tconst probabilities = computeProbabilities(state.model, task.matrix, task.outputs)\n\t\tconst errors = computeErrors(probabilities, task.labels, task.weights, task.outputs)\n\t\tconst gradient = computeGradient(errors, task.matrix, task.outputs, state.model, task.penalty)\n\t\treturn this.#descend(task, stepAdam(state, gradient, step, FIT_RATE), step + 1, signal)\n\t}\n}\n","import type { HeadWeights, ThreadHostInterface } from '@orkestrel/infer'\nimport type { FitJob, FitSetup, FitterContext, FitterInterface } from '../types.js'\nimport { checkSignal, InferError, yieldTurn } from '@orkestrel/infer'\nimport { FIT_BATCH, FIT_PROGRAM, FIT_SLICE, FIT_SLOTS } from '../constants.js'\nimport { buildFitSetup, checkFitJobs, checkFitterContext, readFitWeights } from '../helpers.js'\n\n/**\n * Fits one head per job across the worker threads of a host, over one shared copy of the rows.\n *\n * @remarks\n * The fitter owns its host: `start` copies the context's features and labels into shared memory once\n * and starts the host's workers on `FIT_PROGRAM`, and `destroy` stops the workers and destroys the\n * host. `fit` writes each batch's jobs into the shared job regions, wakes the workers, and waits in\n * the host's `wait` for slices of `FIT_SLICE` milliseconds, yielding a turn and reading the signal\n * between them. Each worker claims job indexes through `Atomics.add` and fits each claimed job whole,\n * through the same arithmetic as `SerialFitter`, into the job's own result slot, so the heads are read\n * by job index and are byte-identical to `SerialFitter`'s at any worker count and in any completion\n * order. A list longer than the regions hold, `FIT_BATCH` jobs or the host's size if more, runs in\n * batches.\n *\n * Construction refuses a host without `SharedArrayBuffer`, such as a page that is not\n * `crossOriginIsolated`, with the `HOST` code. `start` checks the context as `checkFitterContext`\n * states and rejects as the host's `start` does, the `HOST` and `THREAD` codes included. `fit` checks\n * the jobs as `checkFitJobs` states. On abort, `fit` halts every worker at its next Adam step and\n * rejects with the `ABORT` code; a job that throws on its worker halts every worker and fails the call\n * with the `THREAD` code, naming the job and its text. After either, and after a failed start, `fit`\n * throws with the `THREAD` code, so destroy the fitter. A second `start` throws with the `ARGUMENT`\n * code, as does a `fit` before `start`; after `destroy`, both throw with the `DESTROYED` code. No job\n * is bounded by time: a worker that dies without reporting, such as one the host's memory limit ends,\n * leaves `fit` waiting until the signal aborts.\n *\n * @example\n * ```ts\n * const fitter = new ThreadFitter(createNodeThreadHost({ size: 4 }))\n * await fitter.start({ features, labels: [0, 0, 1, 1], classes: 2 })\n * const [head] = await fitter.fit([{ rows: [0, 1, 2, 3], penalty: 0.1 }])\n * await fitter.destroy()\n * ```\n */\nexport class ThreadFitter implements FitterInterface {\n\treadonly #host: ThreadHostInterface\n\t#setup: FitSetup | undefined\n\t#destroyed = false\n\n\t/**\n\t * Creates a fitter over a thread host it then owns.\n\t *\n\t * @param host - The host whose workers run the jobs\n\t */\n\tconstructor(host: ThreadHostInterface) {\n\t\tif (typeof SharedArrayBuffer !== 'function') {\n\t\t\tthrow new InferError(\n\t\t\t\t'A thread fitter shares its rows with the workers through a SharedArrayBuffer, which this host lacks; on a page, serve the document with Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp, or fit without threads.',\n\t\t\t\t{ code: 'HOST' },\n\t\t\t)\n\t\t}\n\t\tthis.#host = host\n\t}\n\n\t/**\n\t * Copies the rows into shared memory and starts the host's workers on them.\n\t *\n\t * @param context - The features, the labels, and the label count\n\t * @param signal - Cancels the start; it then rejects with the `ABORT` code\n\t */\n\tasync start(context: FitterContext, signal?: AbortSignal): Promise<void> {\n\t\tif (this.#destroyed) {\n\t\t\tthrow new InferError('The fitter has been destroyed.', { code: 'DESTROYED' })\n\t\t}\n\t\tif (this.#setup !== undefined) {\n\t\t\tthrow new InferError('The fitter has already started; destroy it and create another.', {\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t})\n\t\t}\n\t\tcheckFitterContext(context)\n\t\tcheckSignal(signal, 'The fit start')\n\t\tconst setup = buildFitSetup(context, Math.max(FIT_BATCH, this.#host.size))\n\t\tthis.#setup = setup\n\t\tawait this.#host.start(FIT_PROGRAM, setup, signal)\n\t}\n\n\t/**\n\t * Fits one head per job across the workers and returns the heads in job order.\n\t *\n\t * @param jobs - The fits to run\n\t * @param signal - Cancels the fits; they then reject with the `ABORT` code\n\t * @returns Each job's head weights, in job order\n\t */\n\tasync fit(jobs: readonly FitJob[], signal?: AbortSignal): Promise<readonly HeadWeights[]> {\n\t\tconst setup = this.#setup\n\t\tif (setup === undefined) {\n\t\t\tthrow this.#destroyed\n\t\t\t\t? new InferError('The fitter has been destroyed.', { code: 'DESTROYED' })\n\t\t\t\t: new InferError('The fitter has not started; start it with the rows its jobs read.', {\n\t\t\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\t\t})\n\t\t}\n\t\tconst control = new Int32Array(setup.control)\n\t\tif (Atomics.load(control, FIT_SLOTS.ready) < this.#host.size) {\n\t\t\tthrow new InferError(\n\t\t\t\t'Not every worker of the thread fitter is running, because its start failed; destroy it and create another.',\n\t\t\t\t{ code: 'THREAD' },\n\t\t\t)\n\t\t}\n\t\tif (Atomics.load(control, FIT_SLOTS.halt) !== 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t'The thread fitter halted its workers after an abort or a failed job; destroy it and create another.',\n\t\t\t\t{ code: 'THREAD' },\n\t\t\t)\n\t\t}\n\t\tcheckFitJobs(jobs, new Int32Array(setup.labels), setup.classes)\n\t\tcheckSignal(signal, 'The fit')\n\t\tconst firsts = Array.from(\n\t\t\t{ length: Math.ceil(jobs.length / setup.capacity) },\n\t\t\t(_, batch) => batch * setup.capacity,\n\t\t)\n\t\tconst batches: Array<readonly HeadWeights[]> = []\n\t\tfor (const first of firsts) {\n\t\t\tbatches.push(await this.#run(setup, jobs.slice(first, first + setup.capacity), first, signal))\n\t\t}\n\t\treturn batches.flat()\n\t}\n\n\t/** Halts the workers and destroys the host; a second call does nothing. */\n\tasync destroy(): Promise<void> {\n\t\tthis.#destroyed = true\n\t\tconst setup = this.#setup\n\t\tthis.#setup = undefined\n\t\tif (setup !== undefined) Atomics.store(new Int32Array(setup.control), FIT_SLOTS.halt, 1)\n\t\tawait this.#host.destroy()\n\t}\n\n\t// Posts one batch of jobs, waits until every worker has claimed past its last job, and reads each\n\t// job's head from its own result slot.\n\tasync #run(\n\t\tsetup: FitSetup,\n\t\tbatch: readonly FitJob[],\n\t\tfirst: number,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<readonly HeadWeights[]> {\n\t\tconst control = new Int32Array(setup.control)\n\t\tconst chosen = batch.map((job) => new Set(job.rows))\n\t\tnew Uint8Array(setup.members).set(\n\t\t\tUint8Array.from({ length: batch.length * setup.rows }, (_, flat) =>\n\t\t\t\tchosen[Math.floor(flat / setup.rows)]?.has(flat % setup.rows) === true ? 1 : 0,\n\t\t\t),\n\t\t)\n\t\tnew Float64Array(setup.penalties).set(batch.map((job) => job.penalty))\n\t\tAtomics.store(control, FIT_SLOTS.count, batch.length)\n\t\tAtomics.store(control, FIT_SLOTS.next, 0)\n\t\tAtomics.store(control, FIT_SLOTS.idle, 0)\n\t\tAtomics.add(control, FIT_SLOTS.generation, 1)\n\t\tAtomics.notify(control, FIT_SLOTS.generation)\n\t\tawait this.#wait(control, signal)\n\t\tconst fault = Atomics.load(control, FIT_SLOTS.fault)\n\t\tif (fault !== 0) {\n\t\t\tconst units = new Uint16Array(setup.message)\n\t\t\tconst end = units.indexOf(0)\n\t\t\tconst text = String.fromCharCode(...units.subarray(0, end < 0 ? units.length : end))\n\t\t\tthrow new InferError(`Fit job ${first + fault - 1} threw on a worker thread: ${text}`, {\n\t\t\t\tcode: 'THREAD',\n\t\t\t\tcontext: { job: first + fault - 1 },\n\t\t\t})\n\t\t}\n\t\tconst results = new Float64Array(setup.results)\n\t\treturn batch.map((_, job) => readFitWeights(results, job, setup))\n\t}\n\n\t// Blocks in the host's wait in slices until every worker is idle, yielding a turn between slices and\n\t// halting the workers when the signal aborts.\n\tasync #wait(control: Int32Array, signal: AbortSignal | undefined): Promise<void> {\n\t\tfor (;;) {\n\t\t\tconst idle = Atomics.load(control, FIT_SLOTS.idle)\n\t\t\tif (idle >= this.#host.size) return\n\t\t\tthis.#host.wait(control, FIT_SLOTS.idle, idle, FIT_SLICE)\n\t\t\tawait yieldTurn()\n\t\t\tif (signal?.aborted === true) {\n\t\t\t\tAtomics.store(control, FIT_SLOTS.halt, 1)\n\t\t\t\tcheckSignal(signal, 'The fit')\n\t\t\t}\n\t\t}\n\t}\n}\n","import type { JudgeQuestion } from '@orkestrel/agent'\nimport type {\n\tBackboneInterface,\n\tCalibration,\n\tHeadRecord,\n\tThreadHostInterface,\n} from '@orkestrel/infer'\nimport type {\n\tFitterInterface,\n\tFoldOutcome,\n\tFoldSplit,\n\tTrainerInterface,\n\tTrainerOptions,\n\tTrainerResult,\n\tTrainerRow,\n\tTrainerSelection,\n\tTrainerSettings,\n} from '../types.js'\nimport { buildHeadGGUF, checkSignal, computeSignature, InferError } from '@orkestrel/infer'\nimport { SerialFitter } from '../fitters/SerialFitter.js'\nimport { ThreadFitter } from '../fitters/ThreadFitter.js'\nimport {\n\tadmitRows,\n\tassignFolds,\n\tbuildOperatingTable,\n\tbuildSplits,\n\tcheckFolds,\n\tcheckLabels,\n\tcollectRows,\n\tcomputeAccuracy,\n\tcomputeDatasetDigest,\n\tcomputeDistributions,\n\tcomputeHeadLogits,\n\tcomputeLabelAUCs,\n\tencodeStates,\n\textractScores,\n\tfitCalibration,\n\tinferRowLabels,\n\tinferStrata,\n\tpoolOutcomes,\n\tresolveTrainerSettings,\n\tselectPenalty,\n} from '../helpers.js'\n\n/**\n * Fits and calibrates a frozen-feature decision head over an `@orkestrel/infer` backbone's features, and writes\n * the head file `@orkestrel/infer`'s `createHead` loads.\n *\n * @remarks\n * `execute` admits the rows, maps each to a head label, and assigns stratified folds over the rows'\n * own labels before it embeds anything, so a refusal costs no forward. It then embeds every row's\n * state at the depth, mean-pooled, and:\n *\n * - **Chooses the L2 strength.** With more than one penalty, it cross-validates each one over the\n * first repeat's folds other than the held fold, inside the rows the head fits on, and keeps the\n * highest mean label-against-rest AUC, the stronger penalty on a tie.\n * - **Cross-validates.** Each repeat fits one head per fold on the other folds' rows, standardized on\n * them, with inverse-frequency class weights, by `FIT_STEPS` full-batch Adam steps at `FIT_RATE`\n * from zero, and scores the fold's rows through the head's own arithmetic. The AUCs and the\n * accuracy average the repeats.\n * - **Keeps the head the held fold scored.** Fold 0 of the first repeat is the held split, and its\n * fold's head is the head the file carries, so the fit never read a held row.\n * - **Calibrates on the held rows.** It fits a temperature and per-label biases on the held rows'\n * logits alone, as `fitCalibration` states.\n * - **Reports an operating table** per label from the first repeat's out-of-fold logits under the\n * head's calibration; the caller picks the cutoff.\n *\n * Every penalty's inner fits run as one batch of independent jobs, and every repeat's fold fits as\n * another. Without the `threads` option, a `SerialFitter` runs them in turn on the calling thread.\n * With it, the trainer calls `threads` once per `execute`, before the first forward, and runs the\n * batches through a `ThreadFitter` over the host it returns; the result is byte-identical. The\n * trainer owns that host: it destroys it before `execute` settles, on every path. It never holds a\n * host it did not create, so it destroys none.\n *\n * Every refusal rejects with a `InferError`: the `ARGUMENT` code for rows `admitRows`,\n * `inferRowLabels`, `checkLabels`, `checkFolds`, or `encodeStates` refuses; the `HOST` code, before\n * any forward, when `threads` is given on a host without `SharedArrayBuffer`; the codes the host's\n * own `start` rejects with, after the forwards; and the `ABORT` code when the signal aborts, checked\n * before the rows are read, before each forward, before the fits start, and before each optimizer\n * step of a head fit, or between the slices a threaded fit waits in. The constructor throws as\n * `resolveTrainerSettings` states.\n *\n * @example\n * ```ts\n * const trainer = new Trainer({ backbone, depth: 18, question, target: 'correction' })\n * const result = await trainer.execute(rows, signal)\n * const head = await createHead(new MemorySource(result.bytes), { backbone })\n * ```\n */\nexport class Trainer implements TrainerInterface {\n\treadonly #backbone: BackboneInterface\n\treadonly #question: JudgeQuestion\n\treadonly #settings: TrainerSettings\n\treadonly #threads: (() => ThreadHostInterface) | undefined\n\n\t/**\n\t * Creates a trainer over a backbone and a question.\n\t *\n\t * @param options - The backbone, the depth, the question, the cross-validation settings, and the\n\t * thread host factory\n\t */\n\tconstructor(options: TrainerOptions) {\n\t\tthis.#settings = resolveTrainerSettings(options)\n\t\tthis.#backbone = options.backbone\n\t\tthis.#question = options.question\n\t\tthis.#threads = options.threads\n\t}\n\n\t/**\n\t * Embeds the rows, cross-validates, fits, and calibrates a head, and returns its file.\n\t *\n\t * @param rows - The labelled rows\n\t * @param signal - Cancels the run; it then rejects with the `ABORT` code\n\t * @returns The head file and the readings of its fit\n\t */\n\tasync execute(rows: readonly TrainerRow[], signal?: AbortSignal): Promise<TrainerResult> {\n\t\tcheckSignal(signal, 'The training')\n\t\tconst settings = this.#settings\n\t\tconst admitted = admitRows(rows)\n\t\tconst labels = inferRowLabels(admitted, settings)\n\t\tcheckLabels(labels, settings)\n\t\tconst strata = inferStrata(admitted)\n\t\tconst groups = admitted.some((row) => row.group !== undefined)\n\t\t\t? admitted.map((row) => row.group)\n\t\t\t: undefined\n\t\tconst assignments = Array.from({ length: settings.repeats }, (_, repeat) =>\n\t\t\tassignFolds(strata, settings.folds, settings.seed + repeat, groups),\n\t\t)\n\t\tfor (const assignment of assignments) checkFolds(assignment, labels, settings, groups)\n\t\tconst tokens = encodeStates(admitted, this.#backbone.tokenizer, this.#backbone.limit)\n\t\tconst fitter = await this.#createFitter()\n\t\ttry {\n\t\t\tconst features = await this.#extract(tokens, signal)\n\t\t\tawait fitter.start({ features, labels, classes: settings.labels.length }, signal)\n\t\t\treturn await this.#train(admitted, labels, assignments, features, fitter, signal)\n\t\t} finally {\n\t\t\tawait fitter.destroy()\n\t\t}\n\t}\n\n\t// Creates the fitter one execute runs its fits through, destroying the host it created when the\n\t// thread fitter refuses that host.\n\tasync #createFitter(): Promise<FitterInterface> {\n\t\tconst threads = this.#threads\n\t\tif (threads === undefined) return new SerialFitter()\n\t\tconst host = threads()\n\t\ttry {\n\t\t\treturn new ThreadFitter(host)\n\t\t} catch (error) {\n\t\t\tawait host.destroy()\n\t\t\tthrow error\n\t\t}\n\t}\n\n\t// Embeds each row's tokens in turn at the settings' depth.\n\tasync #extract(\n\t\ttokens: ReadonlyArray<readonly number[]>,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<readonly Float32Array[]> {\n\t\tconst features: Float32Array[] = []\n\t\tfor (const state of tokens) {\n\t\t\tfeatures.push(await this.#backbone.embed(state, this.#settings.depth, signal))\n\t\t}\n\t\treturn features\n\t}\n\n\t// Chooses the penalty, cross-validates every repeat, calibrates the held head, and writes its file.\n\tasync #train(\n\t\tadmitted: readonly TrainerRow[],\n\t\tlabels: readonly number[],\n\t\tassignments: ReadonlyArray<readonly number[]>,\n\t\tfeatures: readonly Float32Array[],\n\t\tfitter: FitterInterface,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<TrainerResult> {\n\t\tconst settings = this.#settings\n\t\tconst backbone = this.#backbone\n\t\tconst [primary = []] = assignments\n\t\tconst selection =\n\t\t\tsettings.penalties.length > 1\n\t\t\t\t? await this.#select(fitter, features, labels, primary, signal)\n\t\t\t\t: []\n\t\tconst penalty = selection.length > 0 ? selectPenalty(selection) : (settings.penalties[0] ?? 0)\n\t\tconst splits = assignments.map((assignment) =>\n\t\t\tbuildSplits(assignment, settings.folds, undefined),\n\t\t)\n\t\tconst [fitted = []] = await this.#validate(fitter, features, splits.flat(), [penalty], signal)\n\t\tconst repeats = splits.map((_, repeat) =>\n\t\t\tfitted.slice(repeat * settings.folds, (repeat + 1) * settings.folds),\n\t\t)\n\t\tconst all = admitted.map((_, row) => row)\n\t\tconst classes = settings.labels.length\n\t\tconst identity: Calibration = { temperature: 1, bias: settings.labels.map(() => 0) }\n\t\tconst pooled = splits.map((repeat, index) =>\n\t\t\tpoolOutcomes(\n\t\t\t\trepeat,\n\t\t\t\t(repeats[index] ?? []).map((outcome) => outcome.logits),\n\t\t\t\tall,\n\t\t\t\tclasses,\n\t\t\t),\n\t\t)\n\t\tconst distributions = pooled.map((logits) =>\n\t\t\tcomputeDistributions(logits, classes, identity, backbone.strict),\n\t\t)\n\t\tconst aucs = distributions.map((values) => computeLabelAUCs(values, labels, classes))\n\t\tconst [deployed] = repeats[0] ?? []\n\t\tif (deployed === undefined) {\n\t\t\tthrow new InferError('The first repeat fitted no fold to keep.', { code: 'ARGUMENT' })\n\t\t}\n\t\tconst held = primary.flatMap((fold, row) => (fold === 0 ? [row] : []))\n\t\tconst calibration = fitCalibration(\n\t\t\tcomputeHeadLogits(deployed.weights, collectRows(features, held)),\n\t\t\tcollectRows(labels, held),\n\t\t\tclasses,\n\t\t\tbackbone.strict,\n\t\t)\n\t\tconst operating = computeDistributions(\n\t\t\tpooled[0] ?? new Float64Array(0),\n\t\t\tclasses,\n\t\t\tcalibration,\n\t\t\tbackbone.strict,\n\t\t)\n\t\tconst readings = settings.labels.map((label, position) => ({\n\t\t\tlabel,\n\t\t\trows: labels.filter((value) => value === position).length,\n\t\t\tauc: aucs.reduce((sum, values) => sum + (values[position] ?? 0), 0) / aucs.length,\n\t\t\ttable: buildOperatingTable(\n\t\t\t\textractScores(operating, classes, position),\n\t\t\t\tlabels.map((value) => value === position),\n\t\t\t),\n\t\t}))\n\t\tconst accuracies = distributions.map((values) => computeAccuracy(values, labels, classes))\n\t\tconst record: HeadRecord = {\n\t\t\tbase: backbone.digest,\n\t\t\tdepth: settings.depth,\n\t\t\tpooling: 'mean',\n\t\t\tsignature: await computeSignature(this.#question),\n\t\t\tlabels: [...settings.labels],\n\t\t\tcalibration,\n\t\t\tdataset: await computeDatasetDigest(admitted),\n\t\t\tseed: settings.seed,\n\t\t\tmetrics: {\n\t\t\t\tauc: readings.reduce((sum, reading) => sum + reading.auc, 0) / readings.length,\n\t\t\t\taccuracy: accuracies.reduce((sum, value) => sum + value, 0) / accuracies.length,\n\t\t\t\tpenalty,\n\t\t\t\trows: admitted.length,\n\t\t\t\theld: held.length,\n\t\t\t\tfolds: settings.folds,\n\t\t\t\trepeats: settings.repeats,\n\t\t\t},\n\t\t}\n\t\treturn {\n\t\t\tbytes: buildHeadGGUF(record, deployed.weights),\n\t\t\trecord,\n\t\t\tweights: deployed.weights,\n\t\t\tlabels: readings,\n\t\t\tselection,\n\t\t\theld,\n\t\t}\n\t}\n\n\t// Reads each penalty's mean label AUC over the first repeat's folds but the held one, inside the\n\t// rows the head fits on.\n\tasync #select(\n\t\tfitter: FitterInterface,\n\t\tfeatures: readonly Float32Array[],\n\t\tlabels: readonly number[],\n\t\tassignment: readonly number[],\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<readonly TrainerSelection[]> {\n\t\tconst settings = this.#settings\n\t\tconst classes = settings.labels.length\n\t\tconst splits = buildSplits(assignment, settings.folds, 0)\n\t\tconst fitted = assignment.flatMap((fold, row) => (fold === 0 ? [] : [row]))\n\t\tconst identity: Calibration = { temperature: 1, bias: settings.labels.map(() => 0) }\n\t\tconst groups = await this.#validate(fitter, features, splits, settings.penalties, signal)\n\t\treturn settings.penalties.map((penalty, index) => {\n\t\t\tconst distributions = computeDistributions(\n\t\t\t\tpoolOutcomes(\n\t\t\t\t\tsplits,\n\t\t\t\t\t(groups[index] ?? []).map((outcome) => outcome.logits),\n\t\t\t\t\tfitted,\n\t\t\t\t\tclasses,\n\t\t\t\t),\n\t\t\t\tclasses,\n\t\t\t\tidentity,\n\t\t\t\tthis.#backbone.strict,\n\t\t\t)\n\t\t\tconst aucs = computeLabelAUCs(distributions, collectRows(labels, fitted), classes)\n\t\t\treturn { penalty, auc: aucs.reduce((sum, auc) => sum + auc, 0) / aucs.length }\n\t\t})\n\t}\n\n\t// Fits one head per penalty and split as one batch, penalty by penalty, and scores each split's rows\n\t// through its head; returns each penalty's outcomes in split order.\n\tasync #validate(\n\t\tfitter: FitterInterface,\n\t\tfeatures: readonly Float32Array[],\n\t\tsplits: readonly FoldSplit[],\n\t\tpenalties: readonly number[],\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<ReadonlyArray<readonly FoldOutcome[]>> {\n\t\tconst jobs = penalties.flatMap((penalty) =>\n\t\t\tsplits.map((split) => ({ rows: split.train, penalty })),\n\t\t)\n\t\tconst heads = await fitter.fit(jobs, signal)\n\t\treturn penalties.map((_, group) =>\n\t\t\tsplits.map((split, index) => {\n\t\t\t\tconst weights = heads[group * splits.length + index]\n\t\t\t\tif (weights === undefined) {\n\t\t\t\t\tthrow new InferError(\n\t\t\t\t\t\t`The fitter returned ${heads.length} heads for ${jobs.length} jobs.`,\n\t\t\t\t\t\t{ code: 'ARGUMENT' },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\treturn { weights, logits: computeHeadLogits(weights, collectRows(features, split.test)) }\n\t\t\t}),\n\t\t)\n\t}\n}\n","import type { ConversationSnapshot, JudgeAnswer, Judgment, Message } from '@orkestrel/agent'\nimport type { CSVParseResult, ParseOptions } from '@orkestrel/csv'\nimport type {\n\tAdapterInterface,\n\tAdapterOptions,\n\tAdapterPair,\n\tAdapterTarget,\n\tArchitecture,\n\tArchitectureFamily,\n\tByteSourceInterface,\n\tCalibration,\n\tChatTemplateInterface,\n\tDigest,\n\tGGUFFormat,\n\tGGUFTensor,\n\tGGUFValue,\n\tHeadWeights,\n\tSafetensorsFormat,\n\tSafetensorsTensor,\n\tSectionEntry,\n\tSectionFormat,\n\tSectionInterface,\n\tSectionOptions,\n\tSectionTarget,\n\tTokenizerInterface,\n\tTokenSpan,\n\tTrainPlan,\n} from '@orkestrel/infer'\nimport type {\n\tTemplateDocument,\n\tTemplateFillValues,\n\tTemplateTreeInterface,\n} from '@orkestrel/template'\nimport type {\n\tAdamState,\n\tAdapterCalibrationOptions,\n\tAdapterCalibrationResult,\n\tAdapterCombinationEntry,\n\tAdapterCombinationOptions,\n\tAdapterScaleCandidate,\n\tByteSinkInterface,\n\tChangeCountOptions,\n\tChangeCountResult,\n\tCheckpoint,\n\tCheckpointReadOptions,\n\tCheckpointTarget,\n\tConversationRow,\n\tConversationRowOptions,\n\tFeatureMatrix,\n\tFeatureStandard,\n\tFinetuneRow,\n\tFinetunerOptions,\n\tFinetunerSchedule,\n\tFinetunerSettings,\n\tFitJob,\n\tFitSetup,\n\tFitterContext,\n\tFlipCountOptions,\n\tFlipCountResult,\n\tFoldSplit,\n\tFormatChangeEntry,\n\tFormatChangeOptions,\n\tFormatChangeResult,\n\tHeadTraceOptions,\n\tHeadTraceResult,\n\tHeadTraceToken,\n\tJudgmentRowOptions,\n\tJudgmentRowResult,\n\tMergeGGUFFormat,\n\tMergeGGUFOptions,\n\tMergeSafetensorsOptions,\n\tPEFTBundle,\n\tPEFTConfig,\n\tPEFTConversionOptions,\n\tPrecisionFormat,\n\tRefitHeadOptions,\n\tRefitHeadResult,\n\tRefitHeadTrace,\n\tRowProvenance,\n\tSafetensorsWriteEntry,\n\tSectionReadOptions,\n\tSectionTraceBlock,\n\tSectionTraceOptions,\n\tSectionTraceResult,\n\tSectionTraceTarget,\n\tTensorWeightDiff,\n\tTrainerCSVOptions,\n\tTrainerCut,\n\tTrainerOptions,\n\tTrainerRow,\n\tTrainerSelection,\n\tTrainerSettings,\n\tWeightDiffOptions,\n\tWeightDiffResult,\n} from './types.js'\nimport {\n\tcollectQuestionKeys,\n\tisConversationSnapshot,\n\tisJudgeQuestion,\n\tmatchesJSON,\n\tmeasureAnswer,\n\tscanJudgmentTies,\n} from '@orkestrel/agent'\nimport {\n\tattempt,\n\tcanonicalStringify,\n\tdescribeFaults,\n\tholds,\n\tisArray,\n\tisBoolean,\n\tisBoundedJSONRecord,\n\tisFiniteNumber,\n\tisFloat32Array,\n\tisFunction,\n\tisObject,\n\tisRecord,\n\tisSafeInteger,\n\tisString,\n\tisUint8Array,\n\tparseJSON,\n\tseededRandom,\n} from '@orkestrel/contract'\nimport { isCSVError, parseCSV } from '@orkestrel/csv'\nimport {\n\tAdapter,\n\tADAPTER_KEYS,\n\tADAPTER_TARGET_SPECS,\n\tADAPTER_TARGETS,\n\talignOffset,\n\tARCHITECTURE_FAMILIES,\n\tBACKWARD_SEGMENT,\n\tbuildChatMessages,\n\tbuildGGUF,\n\tcheckAdapterBinding,\n\tcheckAdapterOptions,\n\tcheckHeadWeights,\n\tcheckSectionBinding,\n\tcheckSectionOptions,\n\tcheckSignal,\n\tcheckTrainPlan,\n\tcomputeElements,\n\tcomputeTensorBytes,\n\tdigestBytes,\n\tencodeGGUFBigInts,\n\tencodeGGUFNumbers,\n\tencodeGGUFTensor,\n\texponentiate,\n\tfindTensorOverlap,\n\tGGUF_ALIGNMENT,\n\tGGUF_BLOCKS,\n\tGGUF_KEYS,\n\tGGUF_MAGIC,\n\tGGUF_VERSION,\n\tinterleaveRotary,\n\tisSectionFormat,\n\tisSectionTarget,\n\tjoinBytes,\n\tInferError,\n\tmatchesCount,\n\tmatchesElements,\n\tmatchesTokenBound,\n\tMemorySource,\n\tnarrowHalf,\n\tquoteFaultText,\n\treadAdapter,\n\treadArchitecture,\n\treadGGUF,\n\treadGGUFFile,\n\treadMetadataInteger,\n\treadMetadataNumber,\n\treadMetadataString,\n\treadMetadataStrings,\n\treadNamedTensor,\n\treadSafetensors,\n\treadSafetensorsEntry,\n\treadSection,\n\tresolveAlignment,\n\troundAway,\n\tSAFETENSORS_FORMATS,\n\tSAFETENSORS_HEADER_LIMIT,\n\tSection,\n\tSECTION_KEYS,\n\tSECTION_TARGET_SUFFIXES,\n\tSECTION_TARGETS,\n\tSECTION_TENSOR_PATTERN,\n\tSHA256_PATTERN,\n\tUTF8_ENCODER,\n\twidenHalf,\n\twidenTensor,\n} from '@orkestrel/infer'\nimport { createNDJSONParser } from '@orkestrel/ndjson'\nimport {\n\tcompileTemplate,\n\tevaluateTemplate,\n\tisTemplateDocument,\n\tisTemplateError,\n} from '@orkestrel/template'\nimport {\n\tADAM_EPSILON,\n\tADAM_FIRST,\n\tADAM_SECOND,\n\tADAPTER_CALIBRATION_SCALES,\n\tCALIBRATION_PRIOR,\n\tCALIBRATION_RATE,\n\tCALIBRATION_STEPS,\n\tCHECKPOINT_KEYS,\n\tCHECKPOINT_TENSOR_PREFIXES,\n\tCHECKPOINT_TYPE,\n\tCHECKPOINT_VERSION,\n\tFINETUNER_BATCH,\n\tFINETUNER_CLIP,\n\tFINETUNER_DECAY,\n\tFINETUNER_EPOCHS,\n\tFINETUNER_EPSILON,\n\tFINETUNER_FIRST,\n\tFINETUNER_LIMIT,\n\tFINETUNER_RATE,\n\tFINETUNER_SECOND,\n\tFINETUNER_SEED,\n\tFINETUNER_WARMUP,\n\tFIT_MESSAGE,\n\tFIT_SLOTS,\n\tHEAD_FILE_EXTENSION,\n\tMERGE_CHUNK_BYTES,\n\tMERGE_ROW_STRIP,\n\tMERGE_SOURCE_FORMATS,\n\tPEFT_BASE_LAYERS_PREFIX,\n\tPEFT_BASE_QWEN35_PREFIX,\n\tPEFT_LAYERS_PREFIX,\n\tPEFT_QWEN35_PREFIX,\n\tPEFT_TARGET_SPECS,\n\tPEFT_TENSOR_PATTERN,\n\tPRECISION_FORMATS,\n\tROW_KEYS,\n\tSECTION_PATCH_TYPE,\n\tSECTION_PATCH_VERSION,\n\tSECTION_SAFETENSORS_SPECS,\n\tTRAINER_FOLD_FLOOR,\n\tTRAINER_FOLDS,\n\tTRAINER_PENALTIES,\n\tTRAINER_REPEATS,\n\tTRAINER_SEED,\n} from './constants.js'\nimport { Trainer } from './trainers/Trainer.js'\nimport {\n\tisByteSink,\n\tisCheckpoint,\n\tisCheckpointId,\n\tisCheckpointMode,\n\tisCheckpointTarget,\n\tisFinetuneRow,\n\tisFinetunerSchedule,\n\tisMergeGGUFFormat,\n\tisPrecisionFormat,\n\tisTrainerRow,\n} from './validators.js'\n\n/**\n * Resolves a trainer's options into its settings, applying each default and refusing each value it\n * cannot run.\n *\n * @remarks\n * Thrown with the `ARGUMENT` code when the question fails `isJudgeQuestion`, which admits at least\n * two candidate keys, or offers an empty candidate key, the depth is not an integer from 1 to the backbone's layers, a target\n * accompanies a question that is not a noul, the folds are not an integer of at least\n * `TRAINER_FOLD_FLOOR`, the repeats are not a positive integer, the seed is not a safe integer, the\n * penalties are empty or hold a value that is not finite and non-negative, or `threads` is given and\n * is not a function.\n *\n * @param options - The trainer's options\n * @returns The settings\n *\n * @example\n * ```ts\n * resolveTrainerSettings({ backbone, depth: 18, question: { form: 'noul' } }).labels // ['true', 'false']\n * ```\n */\nexport function resolveTrainerSettings(options: TrainerOptions): TrainerSettings {\n\tconst { backbone, depth, question, target } = options\n\tif (!isJudgeQuestion(question)) {\n\t\tthrow new InferError(\n\t\t\t'The trainer question is not a judge question: pass a choice, a score, or a noul as @orkestrel/agent defines them.',\n\t\t\t{ code: 'ARGUMENT' },\n\t\t)\n\t}\n\tconst labels = collectQuestionKeys(question)\n\tif (labels.some((label) => label.length === 0)) {\n\t\tthrow new InferError(\n\t\t\t'The trainer question offers an empty candidate key; a head names each label by a non-empty key.',\n\t\t\t{ code: 'ARGUMENT', context: { labels: labels.length } },\n\t\t)\n\t}\n\tconst { layers } = backbone.architecture\n\tif (!matchesCount(depth, 1) || depth > layers) {\n\t\tthrow new InferError(\n\t\t\t`The trainer depth is ${depth}; the backbone embeds at an integer depth from 1 to ${layers}.`,\n\t\t\t{ code: 'ARGUMENT', context: { depth, layers } },\n\t\t)\n\t}\n\tif (target !== undefined && question.form !== 'noul') {\n\t\tthrow new InferError(\n\t\t\t`The target ${quoteFaultText(target)} names the rows a noul's \"true\" reads, and the question is a ${question.form}; drop the target and label each row with one of the question's candidate keys.`,\n\t\t\t{ code: 'ARGUMENT', context: { form: question.form } },\n\t\t)\n\t}\n\tconst folds = options.folds ?? TRAINER_FOLDS\n\tif (!matchesCount(folds, TRAINER_FOLD_FLOOR)) {\n\t\tthrow new InferError(\n\t\t\t`The trainer runs ${folds} folds; it runs an integer of at least ${TRAINER_FOLD_FLOOR}, one of which holds the calibration rows.`,\n\t\t\t{ code: 'ARGUMENT', context: { folds } },\n\t\t)\n\t}\n\tconst repeats = options.repeats ?? TRAINER_REPEATS\n\tif (!matchesCount(repeats, 1)) {\n\t\tthrow new InferError(`The trainer runs ${repeats} repeats; it runs a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { repeats },\n\t\t})\n\t}\n\tconst seed = options.seed ?? TRAINER_SEED\n\tif (!Number.isSafeInteger(seed)) {\n\t\tthrow new InferError(`The trainer seed is ${seed}; it is a safe integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { seed },\n\t\t})\n\t}\n\tconst penalties = options.penalties ?? TRAINER_PENALTIES\n\tif (\n\t\tpenalties.length === 0 ||\n\t\t!penalties.every((penalty) => Number.isFinite(penalty) && penalty >= 0)\n\t) {\n\t\tthrow new InferError(\n\t\t\t'The trainer penalties are one or more finite, non-negative L2 strengths.',\n\t\t\t{ code: 'ARGUMENT', context: { penalties: penalties.length } },\n\t\t)\n\t}\n\tif (options.threads !== undefined && typeof options.threads !== 'function') {\n\t\tthrow new InferError(\n\t\t\t'The trainer threads option is a function that creates a thread host, such as () => createNodeThreadHost({ size: 15 }).',\n\t\t\t{ code: 'ARGUMENT' },\n\t\t)\n\t}\n\treturn { depth, labels: [...labels], target, folds, repeats, seed, penalties: [...penalties] }\n}\n\n/**\n * Admits a list of training rows, copying each one.\n *\n * @remarks\n * Thrown with the `ARGUMENT` code when the list is empty or an entry fails `isTrainerRow`; the\n * message names the entry's index and its faults.\n *\n * @param rows - The rows to admit\n * @returns Owned copies of the rows\n *\n * @example\n * ```ts\n * admitRows([{ state: 'user: hi', label: 'chatter' }]).length // 1\n * ```\n */\nexport function admitRows(rows: readonly unknown[]): readonly TrainerRow[] {\n\tif (rows.length === 0) {\n\t\tthrow new InferError('The trainer received no rows; pass at least one row of each label.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\treturn rows.map((row, index) => {\n\t\tif (isTrainerRow(row)) {\n\t\t\treturn row.group === undefined\n\t\t\t\t? { state: row.state, label: row.label }\n\t\t\t\t: { state: row.state, label: row.label, group: row.group }\n\t\t}\n\t\tthrow new InferError(renderRowRefusal(row, `The row at index ${index}`), {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { row: index },\n\t\t})\n\t})\n}\n\n/**\n * Renders the refusal of a value that is not a training row, naming each fault.\n *\n * @remarks\n * Each member name the value carries is JSON-encoded and capped, so a malformed row cannot fake or\n * balloon the message.\n *\n * @param value - The refused value\n * @param subject - The words that open the message and locate the value\n * @returns The refusal message\n *\n * @example\n * ```ts\n * renderRowRefusal({ state: 'user: hi' }, 'Record 3')\n * // 'Record 3 lacks \"label\"; a training row is a JSON object of a string \"state\", a string \"label\", and an optional non-empty string \"group\".'\n * ```\n */\nexport function renderRowRefusal(value: unknown, subject: string): string {\n\tconst shape =\n\t\t'a training row is a JSON object of a string \"state\", a string \"label\", and an optional non-empty string \"group\".'\n\tif (!isRecord(value)) return `${subject} is not a JSON object; ${shape}`\n\tconst keys = Object.keys(value)\n\tconst missing = ROW_KEYS.filter((key) => !keys.includes(key)).map((key) => quoteFaultText(key))\n\tconst unexpected = keys\n\t\t.filter((key) => !ROW_KEYS.includes(key) && key !== 'group')\n\t\t.map((key) => quoteFaultText(key))\n\tconst checked = [...ROW_KEYS, ...(keys.includes('group') ? ['group'] : [])]\n\tconst mistyped = checked\n\t\t.filter((key) => keys.includes(key))\n\t\t.filter((key) => !holds(() => isString(value[key])))\n\t\t.map((key) => quoteFaultText(key))\n\tconst emptyGroup =\n\t\tkeys.includes('group') && holds(() => isString(value['group']) && value['group'].length === 0)\n\tconst extra = unexpected.length > 5 ? ` and ${unexpected.length - 5} more` : ''\n\tconst faults = [\n\t\tmissing.length > 0 ? `lacks ${missing.join(' and ')}` : '',\n\t\tunexpected.length > 0 ? `carries ${unexpected.slice(0, 5).join(', ')}${extra}` : '',\n\t\tmistyped.length > 0 ? `holds ${mistyped.join(' and ')} as a value that is not a string` : '',\n\t\temptyGroup ? 'holds \"group\" as an empty string' : '',\n\t].filter((fault) => fault.length > 0)\n\tconst found = faults.length > 0 ? faults.join(', ') : 'carries a member a row does not declare'\n\treturn `${subject} ${found}; ${shape}`\n}\n\n/**\n * Encodes each row's state with a backbone's tokenizer, refusing a state the backbone cannot embed.\n *\n * @remarks\n * Thrown with the `ARGUMENT` code, naming the row's index, when a state holds more UTF-8 bytes than\n * `limit` tokens can cover (`matchesTokenBound`), which is refused before the state is encoded, or\n * when a state encodes to no token or to more than `limit` tokens.\n *\n * @param rows - The rows\n * @param tokenizer - The backbone's tokenizer\n * @param limit - The most tokens one embedding admits\n * @returns Each row's token ids, in row order\n *\n * @example\n * ```ts\n * encodeStates(rows, backbone.tokenizer, backbone.limit)[0].length // 9\n * ```\n */\nexport function encodeStates(\n\trows: readonly TrainerRow[],\n\ttokenizer: TokenizerInterface,\n\tlimit: number,\n): ReadonlyArray<readonly number[]> {\n\treturn rows.map((row, index) => {\n\t\tif (!matchesTokenBound(tokenizer, row.state, limit)) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The row at index ${index} holds more UTF-8 bytes than ${limit} tokens of at most ${tokenizer.span} bytes can cover; the backbone embeds a state of 1 to ${limit} tokens.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { row: index, limit, span: tokenizer.span } },\n\t\t\t)\n\t\t}\n\t\tconst tokens = tokenizer.encode(row.state)\n\t\tif (tokens.length === 0 || tokens.length > limit) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The row at index ${index} encodes to ${tokens.length} tokens; the backbone embeds a state of 1 to ${limit} tokens.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { row: index, tokens: tokens.length, limit } },\n\t\t\t)\n\t\t}\n\t\treturn tokens\n\t})\n}\n\n/**\n * Infers each row's head label index from its label and the trainer's settings.\n *\n * @remarks\n * Without a target, a row's label is its head label. With one, a row carrying the target reads\n * `true` and every other row reads `false`. Thrown with the `ARGUMENT` code, naming the row's index,\n * when a head label is not one of the question's candidate keys.\n *\n * @param rows - The rows\n * @param settings - The trainer's settings\n * @returns Each row's index into `settings.labels`, in row order\n *\n * @example\n * ```ts\n * inferRowLabels([{ state: 's', label: 'correction' }], { ...settings, target: 'correction' }) // [0]\n * ```\n */\nexport function inferRowLabels(\n\trows: readonly TrainerRow[],\n\tsettings: TrainerSettings,\n): readonly number[] {\n\tconst { labels, target } = settings\n\treturn rows.map((row, index) => {\n\t\tconst label = target === undefined ? row.label : row.label === target ? 'true' : 'false'\n\t\tconst position = labels.indexOf(label)\n\t\tif (position >= 0) return position\n\t\tthrow new InferError(\n\t\t\t`The row at index ${index} carries the label ${quoteFaultText(row.label)}, which the question does not offer; label each row with one of ${labels.map((name) => quoteFaultText(name)).join(', ')}.`,\n\t\t\t{ code: 'ARGUMENT', context: { row: index } },\n\t\t)\n\t})\n}\n\n/**\n * Refuses rows that do not cover a question's labels or that hold a label with fewer rows than\n * folds.\n *\n * @remarks\n * Thrown with the `ARGUMENT` code, naming the label, when no row reads one of the question's labels,\n * or a label's rows number fewer than `settings.folds`, so some fold could not hold one.\n *\n * @param labels - Each row's head label index\n * @param settings - The trainer's settings\n *\n * @example\n * ```ts\n * checkLabels([0, 0, 0, 1, 1], { ...settings, folds: 3 }) // throws: the second label has 2 rows\n * ```\n */\nexport function checkLabels(labels: readonly number[], settings: TrainerSettings): void {\n\tconst counts = settings.labels.map(\n\t\t(_, position) => labels.filter((label) => label === position).length,\n\t)\n\tconst empty = settings.labels.findIndex((_, position) => counts[position] === 0)\n\tif (empty >= 0) {\n\t\tconst label = settings.labels[empty] ?? ''\n\t\tthrow new InferError(\n\t\t\t`No row reads the question's label ${quoteFaultText(label)}${settings.target === undefined || label !== 'true' ? '' : `, which the rows labelled ${quoteFaultText(settings.target)} read`}; the rows cover a question only when each of its labels has rows.`,\n\t\t\t{ code: 'ARGUMENT', context: { label } },\n\t\t)\n\t}\n\tconst short = settings.labels.findIndex((_, position) => (counts[position] ?? 0) < settings.folds)\n\tif (short >= 0) {\n\t\tconst label = settings.labels[short] ?? ''\n\t\tconst rows = counts[short] ?? 0\n\t\tthrow new InferError(\n\t\t\t`The label ${quoteFaultText(label)} has ${rows} rows; ${settings.folds} folds need at least ${settings.folds} rows of each label, so pass more rows of it or run fewer folds.`,\n\t\t\t{ code: 'ARGUMENT', context: { label, rows, folds: settings.folds } },\n\t\t)\n\t}\n}\n\n/**\n * Infers each row's stratum: the position of its label among the labels in the order they first\n * appear.\n *\n * @param rows - The rows\n * @returns Each row's stratum, in row order\n *\n * @example\n * ```ts\n * inferStrata([{ state: 'a', label: 'b' }, { state: 'c', label: 'a' }, { state: 'd', label: 'b' }]) // [0, 1, 0]\n * ```\n */\nexport function inferStrata(rows: readonly TrainerRow[]): readonly number[] {\n\tconst order = new Map(\n\t\t[...new Set(rows.map((row) => row.label))].map((label, place) => [label, place]),\n\t)\n\treturn rows.map((row) => order.get(row.label) ?? 0)\n}\n\n/**\n * Assigns each row a stratified fold under a seed, keeping rows sharing a group in one fold when\n * groups are supplied.\n *\n * @remarks\n * Without `groups`, or when every entry in `groups` is `undefined`, each stratum's rows take one\n * draw each from one `seededRandom(seed)` stream in stratum order and then row order, sort by it,\n * lay end to end, and take fold `p` modulo `folds`, so each stratum splits across folds with counts\n * differing by at most one. When `groups` carries at least one group identifier, rows sharing a\n * group stay in one fold while groups stratify greedily across strata; ungrouped rows act as\n * singleton groups. Thrown with the `ARGUMENT` code when `groups` length differs from `strata`, a\n * defined group is empty, `folds` is not a positive integer, or fewer than `folds` distinct groups\n * exist.\n *\n * @param strata - Each row's stratum, from 0\n * @param folds - The number of folds\n * @param seed - The seed of the draws\n * @param groups - Optional per-row group identifiers kept together in one fold\n * @returns Each row's fold, in row order\n *\n * @example\n * ```ts\n * assignFolds([0, 0, 0, 1, 1], 5, 7) // the stratum-0 rows take folds 0, 1, 2 and the others 3, 4\n * ```\n */\nexport function assignFolds(\n\tstrata: readonly number[],\n\tfolds: number,\n\tseed: number,\n\tgroups?: ReadonlyArray<string | undefined>,\n): readonly number[] {\n\tif (groups !== undefined && groups.length !== strata.length) {\n\t\tthrow new InferError(\n\t\t\t`The fold assignment received ${groups.length} groups for ${strata.length} rows; pass one group entry per row.`,\n\t\t\t{ code: 'ARGUMENT', context: { groups: groups.length, rows: strata.length } },\n\t\t)\n\t}\n\tif (groups !== undefined) {\n\t\tconst blank = groups.findIndex((group) => group !== undefined && group.length === 0)\n\t\tif (blank >= 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The group at index ${blank} is empty; a row group is a non-empty string or undefined.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { row: blank } },\n\t\t\t)\n\t\t}\n\t}\n\tif (groups === undefined || groups.every((group) => group === undefined)) {\n\t\tconst random = seededRandom(seed)\n\t\tconst count = strata.reduce((top, stratum) => Math.max(top, stratum + 1), 0)\n\t\tconst sequence = Array.from({ length: count }, (_, stratum) => stratum).flatMap((stratum) =>\n\t\t\tstrata\n\t\t\t\t.flatMap((value, row) => (value === stratum ? [row] : []))\n\t\t\t\t.map((row) => ({ row, key: random() }))\n\t\t\t\t.toSorted((one, two) => one.key - two.key)\n\t\t\t\t.map((entry) => entry.row),\n\t\t)\n\t\tconst places = new Map(sequence.map((row, place) => [row, place % folds]))\n\t\treturn strata.map((_, row) => places.get(row) ?? 0)\n\t}\n\tif (!matchesCount(folds, 1)) {\n\t\tthrow new InferError(`The fold count is ${folds}; pass a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { folds },\n\t\t})\n\t}\n\tconst grouped = Map.groupBy(\n\t\tstrata.map((_, row) => row),\n\t\t(row) => {\n\t\t\tconst group = groups[row]\n\t\t\treturn group === undefined ? `r:${row}` : `g:${group}`\n\t\t},\n\t)\n\tconst distinct = grouped.size\n\tif (distinct < folds) {\n\t\tthrow new InferError(\n\t\t\t`The rows hold ${distinct} distinct groups; ${folds} folds need at least ${folds} distinct groups.`,\n\t\t\t{ code: 'ARGUMENT', context: { groups: distinct, folds } },\n\t\t)\n\t}\n\tconst stratumCount = strata.reduce((top, stratum) => Math.max(top, stratum + 1), 0)\n\tconst stratumTotals = Array.from(\n\t\t{ length: stratumCount },\n\t\t(_, stratum) => strata.filter((value) => value === stratum).length,\n\t)\n\tconst random = seededRandom(seed)\n\tconst foldOrder = Array.from({ length: folds }, (_, fold) => ({ fold, key: random() }))\n\t\t.toSorted((one, two) => one.key - two.key)\n\t\t.map((entry) => entry.fold)\n\tconst entries = [...grouped.values()]\n\t\t.map((rows) => {\n\t\t\tconst counts = Array.from(\n\t\t\t\t{ length: stratumCount },\n\t\t\t\t(_, stratum) => rows.filter((row) => strata[row] === stratum).length,\n\t\t\t)\n\t\t\tconst rarest = counts.reduce(\n\t\t\t\t(low, count, stratum) =>\n\t\t\t\t\tcount > 0 ? Math.min(low, stratumTotals[stratum] ?? Number.POSITIVE_INFINITY) : low,\n\t\t\t\tNumber.POSITIVE_INFINITY,\n\t\t\t)\n\t\t\treturn { rows, counts, rarest, key: random() }\n\t\t})\n\t\t.toSorted(\n\t\t\t(one, two) =>\n\t\t\t\tone.rarest - two.rarest || two.rows.length - one.rows.length || one.key - two.key,\n\t\t)\n\tconst emptyCounts = Array.from({ length: folds }, () =>\n\t\tArray.from({ length: stratumCount }, () => 0),\n\t)\n\tconst emptyTotals = Array.from({ length: folds }, () => 0)\n\tconst steps: Array<{\n\t\treadonly rows: readonly number[]\n\t\treadonly fold: number\n\t\treadonly counts: ReadonlyArray<readonly number[]>\n\t\treadonly totals: readonly number[]\n\t}> = []\n\tfor (const entry of entries) {\n\t\tconst prior = steps.at(-1)\n\t\tconst currentCounts = prior?.counts ?? emptyCounts\n\t\tconst currentTotals = prior?.totals ?? emptyTotals\n\t\tconst chosen = foldOrder.reduce(\n\t\t\t(best, fold) => {\n\t\t\t\tconst foldCounts = currentCounts[fold] ?? []\n\t\t\t\tconst delta = entry.counts.reduce((sum, add, stratum) => {\n\t\t\t\t\tif (add === 0) return sum\n\t\t\t\t\tconst target = (stratumTotals[stratum] ?? 1) / folds\n\t\t\t\t\tconst before = foldCounts[stratum] ?? 0\n\t\t\t\t\treturn sum + (2 * before * add + add * add) / (target * target)\n\t\t\t\t}, 0)\n\t\t\t\tconst total = currentTotals[fold] ?? 0\n\t\t\t\tif (delta < best.delta || (delta === best.delta && total < best.total)) {\n\t\t\t\t\treturn { fold, delta, total }\n\t\t\t\t}\n\t\t\t\treturn best\n\t\t\t},\n\t\t\t{ fold: foldOrder[0] ?? 0, delta: Number.POSITIVE_INFINITY, total: Number.POSITIVE_INFINITY },\n\t\t).fold\n\t\tconst nextCounts = currentCounts.map((counts, fold) =>\n\t\t\tfold === chosen\n\t\t\t\t? counts.map((count, stratum) => count + (entry.counts[stratum] ?? 0))\n\t\t\t\t: counts,\n\t\t)\n\t\tconst nextTotals = currentTotals.map((total, fold) =>\n\t\t\tfold === chosen ? total + entry.rows.length : total,\n\t\t)\n\t\tsteps.push({ rows: entry.rows, fold: chosen, counts: nextCounts, totals: nextTotals })\n\t}\n\tconst places = new Map(steps.flatMap((step) => step.rows.map((row) => [row, step.fold] as const)))\n\treturn strata.map((_, row) => places.get(row) ?? 0)\n}\n\n/**\n * Refuses a fold assignment that leaves a head label out of some fold or splits a row group across\n * folds.\n *\n * @remarks\n * A label whose rows span several strata or groups can miss a fold even with as many rows as folds.\n * When `groups` is supplied, any defined group appearing in more than one fold is refused. Thrown\n * with the `ARGUMENT` code naming the label and fold, or the leaked group and its folds.\n *\n * @param assignment - Each row's fold\n * @param labels - Each row's head label index\n * @param settings - The trainer's settings\n * @param groups - Optional per-row group identifiers that must not span multiple folds\n *\n * @example\n * ```ts\n * checkFolds([0, 1, 2, 0, 1, 1], [0, 0, 0, 1, 1, 1], { ...settings, folds: 3 }) // throws: label 1 misses fold 2\n * ```\n */\nexport function checkFolds(\n\tassignment: readonly number[],\n\tlabels: readonly number[],\n\tsettings: TrainerSettings,\n\tgroups?: ReadonlyArray<string | undefined>,\n): void {\n\tif (groups !== undefined) {\n\t\tif (groups.length !== assignment.length) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The fold check received ${groups.length} groups for ${assignment.length} rows; pass one group entry per row.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { groups: groups.length, rows: assignment.length } },\n\t\t\t)\n\t\t}\n\t\tconst lastFold = new Map(\n\t\t\tgroups.flatMap((group, row) =>\n\t\t\t\tgroup === undefined ? [] : [[group, assignment[row] ?? -1] as const],\n\t\t\t),\n\t\t)\n\t\tconst leakedRow = groups.findIndex(\n\t\t\t(group, row) => group !== undefined && assignment[row] !== lastFold.get(group),\n\t\t)\n\t\tif (leakedRow >= 0) {\n\t\t\tconst leaked = groups[leakedRow] ?? ''\n\t\t\tconst spanned = [\n\t\t\t\t...new Set(\n\t\t\t\t\tgroups.flatMap((group, row) => (group === leaked ? [assignment[row] ?? -1] : [])),\n\t\t\t\t),\n\t\t\t].toSorted((one, two) => one - two)\n\t\t\tthrow new InferError(\n\t\t\t\t`The group ${quoteFaultText(leaked)} spans folds ${spanned.join(' and ')}; every row of one group must stay in one fold.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { group: leaked, folds: spanned } },\n\t\t\t)\n\t\t}\n\t}\n\tconst gaps = settings.labels.flatMap((label, position) =>\n\t\tArray.from({ length: settings.folds }, (_, fold) => fold)\n\t\t\t.filter(\n\t\t\t\t(fold) => !labels.some((value, row) => value === position && assignment[row] === fold),\n\t\t\t)\n\t\t\t.map((fold) => ({ label, fold })),\n\t)\n\tconst [gap] = gaps\n\tif (gap === undefined) return\n\tthrow new InferError(\n\t\t`The label ${quoteFaultText(gap.label)} has no row in fold ${gap.fold}, because its rows span categories the folds stratify apart; pass more rows of it or run fewer folds.`,\n\t\t{ code: 'ARGUMENT', context: { label: gap.label, fold: gap.fold } },\n\t)\n}\n\n/**\n * Builds the fold splits of an assignment: each fold's rows to score and the other rows to fit.\n *\n * @remarks\n * A `skip` fold takes no part: no split scores it, and no split fits on its rows. The trainer skips\n * the held fold when it chooses the L2 strength inside the rows the head fits on.\n *\n * @param assignment - Each row's fold\n * @param folds - The number of folds\n * @param skip - The fold to leave out, or undefined to keep every fold\n * @returns One split per kept fold, in fold order\n *\n * @example\n * ```ts\n * buildSplits([0, 1, 2, 1], 3, 0) // [{ train: [2], test: [1, 3] }, { train: [1, 3], test: [2] }]\n * ```\n */\nexport function buildSplits(\n\tassignment: readonly number[],\n\tfolds: number,\n\tskip: number | undefined,\n): readonly FoldSplit[] {\n\treturn Array.from({ length: folds }, (_, fold) => fold)\n\t\t.filter((fold) => fold !== skip)\n\t\t.map((fold) => ({\n\t\t\ttrain: assignment.flatMap((value, row) => (value === fold || value === skip ? [] : [row])),\n\t\t\ttest: assignment.flatMap((value, row) => (value === fold ? [row] : [])),\n\t\t}))\n}\n\n/**\n * Collects the entries of a list at the given indexes, in index order.\n *\n * @remarks\n * Thrown with the `ARGUMENT` code when an index names no entry.\n *\n * @param values - The list\n * @param indexes - The indexes to collect\n * @returns The entries\n *\n * @example\n * ```ts\n * collectRows(['a', 'b', 'c'], [2, 0]) // ['c', 'a']\n * ```\n */\nexport function collectRows<T>(values: readonly T[], indexes: readonly number[]): readonly T[] {\n\treturn indexes.map((index) => {\n\t\tconst value = values[index]\n\t\tif (value !== undefined) return value\n\t\tthrow new InferError(`No row sits at index ${index} of ${values.length} rows.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { index, rows: values.length },\n\t\t})\n\t})\n}\n\n/**\n * Computes per-row class weights inverse to each class's frequency, with a mean of 1 over the rows.\n *\n * @remarks\n * A row's weight is `rows / (classes * count of its class)`; with two classes it is the balanced\n * weighting. Thrown with the `ARGUMENT` code when a class has no row.\n *\n * @param labels - Each row's class\n * @param classes - The number of classes\n * @returns Each row's weight\n *\n * @example\n * ```ts\n * computeClassWeights([0, 0, 0, 1], 2) // Float64Array [0.667, 0.667, 0.667, 2]\n * ```\n */\nexport function computeClassWeights(labels: readonly number[], classes: number): Float64Array {\n\tconst counts = Array.from(\n\t\t{ length: classes },\n\t\t(_, label) => labels.filter((value) => value === label).length,\n\t)\n\tconst empty = counts.findIndex((count) => count === 0)\n\tif (empty >= 0) {\n\t\tthrow new InferError(\n\t\t\t`Class ${empty} has no row among ${labels.length}; its inverse-frequency weight is undefined.`,\n\t\t\t{ code: 'ARGUMENT', context: { label: empty } },\n\t\t)\n\t}\n\treturn Float64Array.from(\n\t\tlabels,\n\t\t(label) => labels.length / (classes * (counts[label] ?? Number.NaN)),\n\t)\n}\n\n/**\n * Computes the number of model outputs a head over a label count fits.\n *\n * @remarks\n * A two-label head fits one logistic output, the first label's log-odds, as the probes' binary arm\n * did; any other count fits one softmax output per label.\n *\n * @param classes - The number of labels\n * @returns The number of outputs\n *\n * @example\n * ```ts\n * computeOutputs(2) // 1\n * computeOutputs(7) // 7\n * ```\n */\nexport function computeOutputs(classes: number): number {\n\treturn classes === 2 ? 1 : classes\n}\n\n/**\n * Computes each column's mean and population deviation over feature rows, with a constant column\n * scaled by 1.\n *\n * @remarks\n * Sums each column's terms in row order, dividing each by the row count, as the probes' readout did.\n *\n * @param rows - The feature rows, of one width\n * @returns The standardization\n *\n * @example\n * ```ts\n * computeStandard([Float32Array.of(1, 5), Float32Array.of(3, 5)]) // mean [2, 5], scale [1, 1]\n * ```\n */\nexport function computeStandard(rows: readonly Float32Array[]): FeatureStandard {\n\tconst count = rows.length\n\tconst columns = rows[0]?.length ?? 0\n\tconst mean = new Float64Array(columns)\n\tfor (let column = 0; column < columns; column += 1) {\n\t\tlet sum = 0\n\t\tfor (let row = 0; row < count; row += 1) sum += (rows[row]?.[column] ?? 0) / count\n\t\tmean[column] = sum\n\t}\n\tconst variance = new Float64Array(columns)\n\tfor (let column = 0; column < columns; column += 1) {\n\t\tlet sum = 0\n\t\tfor (let row = 0; row < count; row += 1) {\n\t\t\tconst gap = (rows[row]?.[column] ?? 0) - (mean[column] ?? 0)\n\t\t\tsum += (gap * gap) / count\n\t\t}\n\t\tvariance[column] = sum\n\t}\n\tconst scale = Float64Array.from(variance, (value) => {\n\t\tconst deviation = Math.sqrt(value)\n\t\treturn deviation > 0 ? deviation : 1\n\t})\n\treturn { mean, scale }\n}\n\n/**\n * Builds the standardized matrix of feature rows, row by row and column by column.\n *\n * @param rows - The feature rows\n * @param standard - The standardization to apply\n * @returns The matrix\n *\n * @example\n * ```ts\n * buildFeatureMatrix([Float32Array.of(1), Float32Array.of(3)], { mean: Float64Array.of(2), scale: Float64Array.of(1) }).values\n * // Float64Array [-1, 1]\n * ```\n */\nexport function buildFeatureMatrix(\n\trows: readonly Float32Array[],\n\tstandard: FeatureStandard,\n): FeatureMatrix {\n\tconst count = rows.length\n\tconst columns = standard.mean.length\n\tconst values = new Float64Array(count * columns)\n\tfor (let row = 0; row < count; row += 1) {\n\t\tfor (let column = 0; column < columns; column += 1) {\n\t\t\tvalues[row * columns + column] =\n\t\t\t\t((rows[row]?.[column] ?? 0) - (standard.mean[column] ?? 0)) / (standard.scale[column] ?? 1)\n\t\t}\n\t}\n\tconst transpose = new Float64Array(count * columns)\n\tfor (let column = 0; column < columns; column += 1) {\n\t\tfor (let row = 0; row < count; row += 1) {\n\t\t\ttranspose[column * count + row] = values[row * columns + column] ?? 0\n\t\t}\n\t}\n\treturn { rows: count, columns, values, transpose }\n}\n\n/**\n * Computes the logistic function without overflow on either side.\n *\n * @param value - The log-odds\n * @returns The probability\n *\n * @example\n * ```ts\n * computeLogistic(0) // 0.5\n * ```\n */\nexport function computeLogistic(value: number): number {\n\tif (value >= 0) return 1 / (1 + Math.exp(-value))\n\tconst exponent = Math.exp(value)\n\treturn exponent / (1 + exponent)\n}\n\n/**\n * Computes a model's probabilities over standardized rows.\n *\n * @remarks\n * The model holds, per output, the column weights then the bias. One output is a logistic model, the\n * first label's probability per row; more is a softmax, `outputs` probabilities per row. Each sum\n * starts at the bias and adds the columns in order, as the probes' readout did.\n *\n * @param model - The parameters, `outputs * (columns + 1)` values\n * @param matrix - The standardized rows\n * @param outputs - The number of outputs\n * @returns The probabilities, row by row\n *\n * @example\n * ```ts\n * computeProbabilities(new Float64Array(3), matrix, 1) // 0.5 for every row\n * ```\n */\nexport function computeProbabilities(\n\tmodel: Float64Array,\n\tmatrix: FeatureMatrix,\n\toutputs: number,\n): Float64Array {\n\tconst { rows, columns, values } = matrix\n\tconst stride = columns + 1\n\tconst blocked = rows - (rows % 4)\n\tconst logits = new Float64Array(rows * outputs)\n\t// Four rows share each weight read, and each row keeps its own sum in column order.\n\tfor (let row = 0; row < blocked; row += 4) {\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tconst weight = output * stride\n\t\t\tconst bias = model[weight + columns] ?? 0\n\t\t\tconst one = row * columns\n\t\t\tconst two = one + columns\n\t\t\tconst three = two + columns\n\t\t\tconst four = three + columns\n\t\t\tlet first = bias\n\t\t\tlet second = bias\n\t\t\tlet third = bias\n\t\t\tlet fourth = bias\n\t\t\tfor (let column = 0; column < columns; column += 1) {\n\t\t\t\tconst coefficient = model[weight + column] ?? 0\n\t\t\t\tfirst += coefficient * (values[one + column] ?? 0)\n\t\t\t\tsecond += coefficient * (values[two + column] ?? 0)\n\t\t\t\tthird += coefficient * (values[three + column] ?? 0)\n\t\t\t\tfourth += coefficient * (values[four + column] ?? 0)\n\t\t\t}\n\t\t\tlogits[row * outputs + output] = first\n\t\t\tlogits[(row + 1) * outputs + output] = second\n\t\t\tlogits[(row + 2) * outputs + output] = third\n\t\t\tlogits[(row + 3) * outputs + output] = fourth\n\t\t}\n\t}\n\tfor (let row = blocked; row < rows; row += 1) {\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tlet sum = model[output * stride + columns] ?? 0\n\t\t\tfor (let column = 0; column < columns; column += 1) {\n\t\t\t\tsum += (model[output * stride + column] ?? 0) * (values[row * columns + column] ?? 0)\n\t\t\t}\n\t\t\tlogits[row * outputs + output] = sum\n\t\t}\n\t}\n\tconst probabilities = new Float64Array(rows * outputs)\n\tif (outputs === 1) {\n\t\tfor (let row = 0; row < rows; row += 1) probabilities[row] = computeLogistic(logits[row] ?? 0)\n\t\treturn probabilities\n\t}\n\tfor (let row = 0; row < rows; row += 1) {\n\t\tlet peak = Number.NEGATIVE_INFINITY\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tpeak = Math.max(peak, logits[row * outputs + output] ?? 0)\n\t\t}\n\t\tlet mass = 0\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tmass += Math.exp((logits[row * outputs + output] ?? 0) - peak)\n\t\t}\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tprobabilities[row * outputs + output] =\n\t\t\t\tMath.exp((logits[row * outputs + output] ?? 0) - peak) / mass\n\t\t}\n\t}\n\treturn probabilities\n}\n\n/**\n * Computes each output's weighted error over the rows, output by output.\n *\n * @remarks\n * An error is `(probability - target) * weight / rows`, where the target is 1 when the row's label is\n * the output's label: the gradient of the mean weighted cross-entropy at each output's logit. With one\n * output, its label is label 0.\n *\n * @param probabilities - The probabilities, row by row\n * @param labels - Each row's label index\n * @param weights - Each row's class weight\n * @param outputs - The number of outputs\n * @returns The errors, `outputs` runs of one value per row\n *\n * @example\n * ```ts\n * computeErrors(Float64Array.of(0.5, 0.5), [0, 1], Float64Array.of(1, 1), 1) // Float64Array [-0.25, 0.25]\n * ```\n */\nexport function computeErrors(\n\tprobabilities: Float64Array,\n\tlabels: readonly number[],\n\tweights: Float64Array,\n\toutputs: number,\n): Float64Array {\n\tconst rows = labels.length\n\tconst errors = new Float64Array(outputs * rows)\n\tfor (let output = 0; output < outputs; output += 1) {\n\t\tfor (let row = 0; row < rows; row += 1) {\n\t\t\tconst target = labels[row] === output ? 1 : 0\n\t\t\terrors[output * rows + row] =\n\t\t\t\t(((probabilities[row * outputs + output] ?? 0) - target) * (weights[row] ?? 0)) / rows\n\t\t}\n\t}\n\treturn errors\n}\n\n/**\n * Computes the gradient of the mean weighted cross-entropy plus an L2 penalty on every weight but the\n * biases.\n *\n * @remarks\n * Each column's term sums its errors times the column's values in row order, then adds `penalty`\n * times the weight, as the probes' optimizer did.\n *\n * @param errors - The errors, output by output\n * @param matrix - The standardized rows\n * @param outputs - The number of outputs\n * @param model - The parameters the penalty reads\n * @param penalty - The L2 strength\n * @returns The gradient, laid out as the model\n *\n * @example\n * ```ts\n * computeGradient(computeErrors(probabilities, labels, weights, 1), matrix, 1, model, 0.1)\n * ```\n */\nexport function computeGradient(\n\terrors: Float64Array,\n\tmatrix: FeatureMatrix,\n\toutputs: number,\n\tmodel: Float64Array,\n\tpenalty: number,\n): Float64Array {\n\tconst { rows, columns, transpose } = matrix\n\tconst stride = columns + 1\n\tconst blocked = columns - (columns % 4)\n\tconst gradient = new Float64Array(outputs * stride)\n\t// Keep columns outside outputs so each step streams transpose once while preserving row-order sums.\n\tfor (let column = 0; column < blocked; column += 4) {\n\t\tconst one = column * rows\n\t\tconst two = one + rows\n\t\tconst three = two + rows\n\t\tconst four = three + rows\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tconst error = output * rows\n\t\t\tconst weight = output * stride\n\t\t\tlet first = 0\n\t\t\tlet second = 0\n\t\t\tlet third = 0\n\t\t\tlet fourth = 0\n\t\t\tfor (let row = 0; row < rows; row += 1) {\n\t\t\t\tconst term = errors[error + row] ?? 0\n\t\t\t\tfirst += term * (transpose[one + row] ?? 0)\n\t\t\t\tsecond += term * (transpose[two + row] ?? 0)\n\t\t\t\tthird += term * (transpose[three + row] ?? 0)\n\t\t\t\tfourth += term * (transpose[four + row] ?? 0)\n\t\t\t}\n\t\t\tgradient[weight + column] = first + penalty * (model[weight + column] ?? 0)\n\t\t\tgradient[weight + column + 1] = second + penalty * (model[weight + column + 1] ?? 0)\n\t\t\tgradient[weight + column + 2] = third + penalty * (model[weight + column + 2] ?? 0)\n\t\t\tgradient[weight + column + 3] = fourth + penalty * (model[weight + column + 3] ?? 0)\n\t\t}\n\t}\n\tfor (let column = blocked; column < columns; column += 1) {\n\t\tconst base = column * rows\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tconst error = output * rows\n\t\t\tlet sum = 0\n\t\t\tfor (let row = 0; row < rows; row += 1) {\n\t\t\t\tsum += (errors[error + row] ?? 0) * (transpose[base + row] ?? 0)\n\t\t\t}\n\t\t\tgradient[output * stride + column] = sum + penalty * (model[output * stride + column] ?? 0)\n\t\t}\n\t}\n\tfor (let output = 0; output < outputs; output += 1) {\n\t\tconst error = output * rows\n\t\tlet bias = 0\n\t\tfor (let row = 0; row < rows; row += 1) bias += errors[error + row] ?? 0\n\t\tgradient[output * stride + columns] = bias\n\t}\n\treturn gradient\n}\n\n/**\n * Takes one Adam step, returning the next parameters and moment estimates.\n *\n * @param state - The parameters and moments before the step\n * @param gradient - The gradient at the parameters\n * @param step - The step's number, from 1\n * @param rate - The learning rate\n * @returns The state after the step\n *\n * @example\n * ```ts\n * stepAdam(state, gradient, 1, 0.01).model\n * ```\n */\nexport function stepAdam(\n\tstate: AdamState,\n\tgradient: Float64Array,\n\tstep: number,\n\trate: number,\n): AdamState {\n\tconst firstScale = 1 - Math.pow(ADAM_FIRST.decay, step)\n\tconst secondScale = 1 - Math.pow(ADAM_SECOND.decay, step)\n\tconst first = new Float64Array(gradient.length)\n\tconst second = new Float64Array(gradient.length)\n\tconst model = new Float64Array(state.model.length)\n\tfor (let index = 0; index < first.length; index += 1) {\n\t\tconst value = gradient[index] ?? 0\n\t\tfirst[index] = ADAM_FIRST.decay * (state.first[index] ?? 0) + ADAM_FIRST.gain * value\n\t\tsecond[index] =\n\t\t\tADAM_SECOND.decay * (state.second[index] ?? 0) + ADAM_SECOND.gain * value * value\n\t}\n\tfor (let index = 0; index < model.length; index += 1) {\n\t\tmodel[index] =\n\t\t\t(state.model[index] ?? 0) -\n\t\t\t(rate * ((first[index] ?? 0) / firstScale)) /\n\t\t\t\t(Math.sqrt((second[index] ?? 0) / secondScale) + ADAM_EPSILON)\n\t}\n\treturn { model, first, second }\n}\n\n/**\n * Builds a head's weights from a fitted model and its standardization, in single precision.\n *\n * @remarks\n * A softmax model's outputs become the label rows. A logistic model's output becomes the first\n * label's row and bias, and every other label's row and bias are zero, so the head's softmax gives\n * the first label the logistic probability.\n *\n * @param model - The fitted parameters\n * @param standard - The standardization the fit read\n * @param classes - The number of labels\n * @returns The head weights\n *\n * @example\n * ```ts\n * buildHeadWeights(model, standard, 2).matrix.length === 2 * standard.mean.length // true\n * ```\n */\nexport function buildHeadWeights(\n\tmodel: Float64Array,\n\tstandard: FeatureStandard,\n\tclasses: number,\n): HeadWeights {\n\tconst columns = standard.mean.length\n\tconst stride = columns + 1\n\tconst zero = computeOutputs(classes) === 1\n\treturn {\n\t\tmatrix: Float32Array.from({ length: classes * columns }, (_, index) => {\n\t\t\tconst label = Math.floor(index / columns)\n\t\t\treturn zero && label > 0 ? 0 : (model[label * stride + (index % columns)] ?? 0)\n\t\t}),\n\t\tbias: Float32Array.from({ length: classes }, (_, label) =>\n\t\t\tzero && label > 0 ? 0 : (model[label * stride + columns] ?? 0),\n\t\t),\n\t\tmean: Float32Array.from(standard.mean),\n\t\tscale: Float32Array.from(standard.scale),\n\t}\n}\n\n/**\n * Refuses a fitter context whose rows a fit cannot read.\n *\n * @remarks\n * Thrown with the `ARGUMENT` code when `classes` is not an integer of at least 2, the context holds no\n * row, the labels do not number one per row, a feature's width differs from the first one's, or a\n * label is not an integer from 0 to `classes - 1`; the message names the row.\n *\n * @param context - The features, the labels, and the label count\n *\n * @example\n * ```ts\n * checkFitterContext({ features: [Float32Array.of(1)], labels: [0, 1], classes: 2 }) // throws: 1 feature, 2 labels\n * ```\n */\nexport function checkFitterContext(context: FitterContext): void {\n\tconst { features, labels, classes } = context\n\tif (!matchesCount(classes, 2)) {\n\t\tthrow new InferError(\n\t\t\t`The fitter context holds ${classes} classes; a head fits an integer of at least 2 labels.`,\n\t\t\t{ code: 'ARGUMENT', context: { classes } },\n\t\t)\n\t}\n\tif (features.length === 0 || labels.length !== features.length) {\n\t\tthrow new InferError(\n\t\t\t`The fitter context holds ${features.length} features and ${labels.length} labels; pass at least one row and one label per row.`,\n\t\t\t{ code: 'ARGUMENT', context: { features: features.length, labels: labels.length } },\n\t\t)\n\t}\n\tconst width = features[0]?.length ?? 0\n\tconst uneven = features.findIndex((feature) => feature.length !== width)\n\tif (uneven >= 0) {\n\t\tthrow new InferError(\n\t\t\t`The feature at index ${uneven} holds ${features[uneven]?.length ?? 0} values and the first holds ${width}; every feature has one width.`,\n\t\t\t{ code: 'ARGUMENT', context: { row: uneven, width } },\n\t\t)\n\t}\n\tconst stray = labels.findIndex((label) => !matchesCount(label, 0) || label >= classes)\n\tif (stray >= 0) {\n\t\tthrow new InferError(\n\t\t\t`The label at index ${stray} is ${labels[stray] ?? Number.NaN}; each label is an integer from 0 to ${classes - 1}.`,\n\t\t\t{ code: 'ARGUMENT', context: { row: stray } },\n\t\t)\n\t}\n}\n\n/**\n * Refuses a fit job list that a fitter over rows with these labels cannot run.\n *\n * @remarks\n * Thrown with the `ARGUMENT` code, naming the job's index, when a job's penalty is not finite and\n * non-negative, its rows are not strictly ascending indexes of the labelled rows, or its rows hold no\n * row of some label, so that label's class weight is undefined.\n *\n * @param jobs - The jobs\n * @param labels - Each row's head label index\n * @param classes - The number of head labels\n *\n * @example\n * ```ts\n * checkFitJobs([{ rows: [2, 1], penalty: 0.1 }], [0, 1, 0], 2) // throws: the rows are not ascending\n * ```\n */\nexport function checkFitJobs(\n\tjobs: readonly FitJob[],\n\tlabels: ArrayLike<number>,\n\tclasses: number,\n): void {\n\tfor (const [index, job] of jobs.entries()) {\n\t\tconst { rows, penalty } = job\n\t\tif (!Number.isFinite(penalty) || penalty < 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t`Fit job ${index} has the penalty ${penalty}; a penalty is a finite, non-negative L2 strength.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { job: index } },\n\t\t\t)\n\t\t}\n\t\tconst disorder = rows.findIndex(\n\t\t\t(row, place) =>\n\t\t\t\t!matchesCount(row, 0) || row >= labels.length || row <= (rows[place - 1] ?? -1),\n\t\t)\n\t\tif (disorder >= 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t`Fit job ${index} lists ${rows[disorder] ?? Number.NaN} at place ${disorder}; a job lists row indexes from 0 to ${labels.length - 1}, strictly ascending.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { job: index, place: disorder } },\n\t\t\t)\n\t\t}\n\t\tconst missing = Array.from({ length: classes }, (_, label) => label).find(\n\t\t\t(label) => !rows.some((row) => labels[row] === label),\n\t\t)\n\t\tif (missing !== undefined) {\n\t\t\tthrow new InferError(\n\t\t\t\t`Fit job ${index} fits on no row of label ${missing}; a job holds at least one row of every label, so each class weight is defined.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { job: index, label: missing } },\n\t\t\t)\n\t\t}\n\t}\n}\n\n/**\n * Builds the shared memory a thread fitter hands every worker of `FIT_PROGRAM`, with the context's\n * features and labels copied in.\n *\n * @remarks\n * The control buffer holds one 32-bit slot per `FIT_SLOTS` entry, all 0. The job regions hold\n * `capacity` jobs, and the message region `FIT_MESSAGE` code units. A result takes the fit's column\n * means, its column scales, and its `computeOutputs(classes) * (columns + 1)` parameters. Requires\n * `SharedArrayBuffer`, which a page holds only when `crossOriginIsolated`.\n *\n * @param context - The features, the labels, and the label count\n * @param capacity - The most jobs the regions hold at once\n * @returns The setup record\n *\n * @example\n * ```ts\n * buildFitSetup({ features: [Float32Array.of(1, 2)], labels: [0], classes: 2 }, 64).stride // 7\n * ```\n */\nexport function buildFitSetup(context: FitterContext, capacity: number): FitSetup {\n\tconst rows = context.features.length\n\tconst columns = context.features[0]?.length ?? 0\n\tconst { classes } = context\n\tconst stride = 2 * columns + computeOutputs(classes) * (columns + 1)\n\tconst features = new SharedArrayBuffer(rows * columns * Float32Array.BYTES_PER_ELEMENT)\n\tconst values = new Float32Array(features)\n\tfor (const [row, feature] of context.features.entries()) values.set(feature, row * columns)\n\tconst labels = new SharedArrayBuffer(rows * Int32Array.BYTES_PER_ELEMENT)\n\tnew Int32Array(labels).set(context.labels)\n\treturn {\n\t\tcontrol: new SharedArrayBuffer(Object.keys(FIT_SLOTS).length * Int32Array.BYTES_PER_ELEMENT),\n\t\tfeatures,\n\t\tlabels,\n\t\tmembers: new SharedArrayBuffer(capacity * rows),\n\t\tpenalties: new SharedArrayBuffer(capacity * Float64Array.BYTES_PER_ELEMENT),\n\t\tresults: new SharedArrayBuffer(capacity * stride * Float64Array.BYTES_PER_ELEMENT),\n\t\tmessage: new SharedArrayBuffer(FIT_MESSAGE * Uint16Array.BYTES_PER_ELEMENT),\n\t\trows,\n\t\tcolumns,\n\t\tclasses,\n\t\tcapacity,\n\t\tstride,\n\t}\n}\n\n/**\n * Reads one job's head weights from a thread fitter's result region.\n *\n * @remarks\n * The job's slot holds `setup.stride` doubles: the column means, the column scales, then the model.\n * The weights are built as `buildHeadWeights` builds them, so they copy every value out of the\n * region.\n *\n * @param results - The result region, as doubles\n * @param job - The job's index within its batch\n * @param setup - The setup whose shape the region follows\n * @returns The job's head weights\n *\n * @example\n * ```ts\n * readFitWeights(new Float64Array(setup.results), 0, setup).mean.length === setup.columns // true\n * ```\n */\nexport function readFitWeights(results: Float64Array, job: number, setup: FitSetup): HeadWeights {\n\tconst { columns, stride } = setup\n\tconst start = job * stride\n\treturn buildHeadWeights(\n\t\tresults.subarray(start + 2 * columns, start + stride),\n\t\t{\n\t\t\tmean: results.subarray(start, start + columns),\n\t\t\tscale: results.subarray(start + columns, start + 2 * columns),\n\t\t},\n\t\tsetup.classes,\n\t)\n}\n\n/**\n * Computes a head's logits over feature rows, before calibration, as `@orkestrel/infer`'s head computes them.\n *\n * @remarks\n * Each feature element is standardized as `(value - mean) / scale` in double precision, and each\n * label's logit starts at its bias and adds its weights times the standardized elements in order.\n *\n * @param weights - The head's weights\n * @param rows - The feature rows\n * @returns The logits, row by row\n *\n * @example\n * ```ts\n * computeHeadLogits(weights, [feature]).length === weights.bias.length // true\n * ```\n */\nexport function computeHeadLogits(\n\tweights: HeadWeights,\n\trows: readonly Float32Array[],\n): Float64Array {\n\tconst { matrix, bias, mean, scale } = weights\n\tconst classes = bias.length\n\tconst width = mean.length\n\tconst logits = new Float64Array(rows.length * classes)\n\tfor (let row = 0; row < rows.length; row += 1) {\n\t\tconst standard = Array.from(\n\t\t\trows[row] ?? [],\n\t\t\t(value, column) => (value - (mean[column] ?? 0)) / (scale[column] ?? 1),\n\t\t)\n\t\tfor (let label = 0; label < classes; label += 1) {\n\t\t\tlet sum = bias[label] ?? 0\n\t\t\tfor (let column = 0; column < width; column += 1) {\n\t\t\t\tsum += (matrix[label * width + column] ?? 0) * (standard[column] ?? 0)\n\t\t\t}\n\t\t\tlogits[row * classes + label] = sum\n\t\t}\n\t}\n\treturn logits\n}\n\n/**\n * Computes the calibrated distribution of each row's logits, as `@orkestrel/infer`'s head computes it.\n *\n * @remarks\n * Each logit is divided by the temperature and shifted by its label's bias, and the softmax\n * subtracts the row's peak. If `strict` is `true`, it exponentiates through `@orkestrel/infer`'s `exponentiate`;\n * if `false`, through `Math.exp`.\n *\n * @param logits - The logits, row by row\n * @param classes - The number of labels\n * @param calibration - The temperature and per-label bias\n * @param strict - If `true`, the arithmetic exponential; if `false`, the host's\n * @returns The probabilities, row by row\n *\n * @example\n * ```ts\n * computeDistributions(Float64Array.of(0, 0), 2, { temperature: 1, bias: [0, 0] }, false) // [0.5, 0.5]\n * ```\n */\nexport function computeDistributions(\n\tlogits: Float64Array,\n\tclasses: number,\n\tcalibration: Calibration,\n\tstrict: boolean,\n): Float64Array {\n\tconst rows = Math.floor(logits.length / classes)\n\treturn Float64Array.from(\n\t\tArray.from({ length: rows }, (_, row) => {\n\t\t\tconst scaled = Array.from(\n\t\t\t\tlogits.subarray(row * classes, (row + 1) * classes),\n\t\t\t\t(logit, label) => logit / calibration.temperature + (calibration.bias[label] ?? 0),\n\t\t\t)\n\t\t\tconst peak = Math.max(...scaled)\n\t\t\tconst masses = scaled.map((value) =>\n\t\t\t\tstrict ? exponentiate(value - peak) : Math.exp(value - peak),\n\t\t\t)\n\t\t\tconst total = masses.reduce((sum, mass) => sum + mass, 0)\n\t\t\treturn masses.map((mass) => mass / total)\n\t\t}).flat(),\n\t)\n}\n\n/**\n * Pools the folds' per-row values over a list of rows, each read from the split that scored it.\n *\n * @remarks\n * Thrown with the `ARGUMENT` code when a listed row sits in no split's scored rows.\n *\n * @param splits - The splits, each with its scored rows\n * @param outcomes - Each split's values, `width` per scored row, in split order\n * @param rows - The rows to pool, in output order\n * @param width - The number of values per row\n * @returns The pooled values, row by row\n *\n * @example\n * ```ts\n * poolOutcomes([{ train: [1], test: [0] }, { train: [0], test: [1] }], [Float64Array.of(5), Float64Array.of(6)], [0, 1], 1)\n * // Float64Array [5, 6]\n * ```\n */\nexport function poolOutcomes(\n\tsplits: readonly FoldSplit[],\n\toutcomes: readonly Float64Array[],\n\trows: readonly number[],\n\twidth: number,\n): Float64Array {\n\tconst places = new Map(\n\t\tsplits.flatMap((split, index) =>\n\t\t\tsplit.test.map((row, place) => [row, { index, place }] as const),\n\t\t),\n\t)\n\treturn Float64Array.from({ length: rows.length * width }, (_, flat) => {\n\t\tconst row = rows[Math.floor(flat / width)] ?? -1\n\t\tconst entry = places.get(row)\n\t\tif (entry === undefined) {\n\t\t\tthrow new InferError(`Row ${row} sits in no fold's scored rows.`, {\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\tcontext: { row },\n\t\t\t})\n\t\t}\n\t\treturn outcomes[entry.index]?.[entry.place * width + (flat % width)] ?? Number.NaN\n\t})\n}\n\n/**\n * Extracts one column of row-by-row values.\n *\n * @param values - The values, row by row\n * @param width - The number of values per row\n * @param column - The column to extract\n * @returns The column's values, in row order\n *\n * @example\n * ```ts\n * extractScores(Float64Array.of(1, 2, 3, 4), 2, 1) // [2, 4]\n * ```\n */\nexport function extractScores(\n\tvalues: Float64Array,\n\twidth: number,\n\tcolumn: number,\n): readonly number[] {\n\treturn Array.from(\n\t\t{ length: Math.floor(values.length / width) },\n\t\t(_, row) => values[row * width + column] ?? Number.NaN,\n\t)\n}\n\n/**\n * Computes the ROC AUC of scores against positive marks: the chance a positive row outranks a\n * negative one, ties counted half.\n *\n * @remarks\n * Thrown with the `ARGUMENT` code when a score is not finite, the lists differ in length, or the\n * marks hold no positive or no negative row.\n *\n * @param scores - Each row's score\n * @param positive - Whether each row is positive\n * @returns The AUC, from 0 to 1\n *\n * @example\n * ```ts\n * computeAUC([0.1, 0.4, 0.35, 0.8], [false, false, true, true]) // 0.75\n * ```\n */\nexport function computeAUC(scores: readonly number[], positive: readonly boolean[]): number {\n\tif (scores.length !== positive.length || !scores.every((score) => Number.isFinite(score))) {\n\t\tthrow new InferError('An AUC reads one finite score per marked row.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { scores: scores.length, marks: positive.length },\n\t\t})\n\t}\n\tconst order = scores\n\t\t.map((_, row) => row)\n\t\t.toSorted((one, two) => (scores[one] ?? 0) - (scores[two] ?? 0))\n\tconst ends = order.flatMap((row, place) => {\n\t\tconst next = order[place + 1]\n\t\treturn next === undefined || scores[next] !== scores[row] ? [place + 1] : []\n\t})\n\tconst groups = ends.map((end, index) => {\n\t\tconst members = order.slice(ends[index - 1] ?? 0, end)\n\t\tconst positives = members.filter((row) => positive[row] === true).length\n\t\treturn { positives, negatives: members.length - positives }\n\t})\n\tconst positives = groups.reduce((total, group) => total + group.positives, 0)\n\tconst negatives = groups.reduce((total, group) => total + group.negatives, 0)\n\tif (positives === 0 || negatives === 0) {\n\t\tthrow new InferError(\n\t\t\t`An AUC needs positive and negative rows; these marks hold ${positives} and ${negatives}.`,\n\t\t\t{ code: 'ARGUMENT', context: { positives, negatives } },\n\t\t)\n\t}\n\tlet below = 0\n\tlet area = 0\n\tfor (let index = 0; index < groups.length; index += 1) {\n\t\tconst group = groups[index] ?? { positives: 0, negatives: 0 }\n\t\tarea += group.positives * (below + group.negatives / 2)\n\t\tbelow += group.negatives\n\t}\n\treturn area / (positives * negatives)\n}\n\n/**\n * Computes each label's label-against-rest AUC of row-by-row distributions.\n *\n * @param distributions - The probabilities, row by row\n * @param labels - Each row's label index\n * @param classes - The number of labels\n * @returns Each label's AUC, in label order\n *\n * @example\n * ```ts\n * computeLabelAUCs(Float64Array.of(0.9, 0.1, 0.2, 0.8), [0, 1], 2) // [1, 1]\n * ```\n */\nexport function computeLabelAUCs(\n\tdistributions: Float64Array,\n\tlabels: readonly number[],\n\tclasses: number,\n): readonly number[] {\n\treturn Array.from({ length: classes }, (_, label) =>\n\t\tcomputeAUC(\n\t\t\textractScores(distributions, classes, label),\n\t\t\tlabels.map((value) => value === label),\n\t\t),\n\t)\n}\n\n/**\n * Computes the share of rows whose most probable label is their own, the first label on a tie.\n *\n * @param distributions - The probabilities, row by row\n * @param labels - Each row's label index\n * @param classes - The number of labels\n * @returns The accuracy, from 0 to 1\n *\n * @example\n * ```ts\n * computeAccuracy(Float64Array.of(0.9, 0.1, 0.6, 0.4), [0, 1], 2) // 0.5\n * ```\n */\nexport function computeAccuracy(\n\tdistributions: Float64Array,\n\tlabels: readonly number[],\n\tclasses: number,\n): number {\n\tconst right = labels.filter((label, row) => {\n\t\tconst values = Array.from(distributions.subarray(row * classes, (row + 1) * classes))\n\t\tconst choice = values.reduce(\n\t\t\t(best, value, index) => (value > (values[best] ?? Number.NEGATIVE_INFINITY) ? index : best),\n\t\t\t0,\n\t\t)\n\t\treturn choice === label\n\t}).length\n\treturn right / labels.length\n}\n\n/**\n * Selects the L2 strength with the highest AUC, the stronger penalty on a tie.\n *\n * @remarks\n * Thrown with the `ARGUMENT` code when the readings are empty.\n *\n * @param selection - Each strength's reading\n * @returns The chosen strength\n *\n * @example\n * ```ts\n * selectPenalty([{ penalty: 0.01, auc: 0.9 }, { penalty: 0.1, auc: 0.9 }]) // 0.1\n * ```\n */\nexport function selectPenalty(selection: readonly TrainerSelection[]): number {\n\tconst [first, ...rest] = selection\n\tif (first === undefined) {\n\t\tthrow new InferError('A penalty choice reads at least one strength.', { code: 'ARGUMENT' })\n\t}\n\treturn rest.reduce(\n\t\t(best, entry) =>\n\t\t\tentry.auc > best.auc || (entry.auc === best.auc && entry.penalty > best.penalty)\n\t\t\t\t? entry\n\t\t\t\t: best,\n\t\tfirst,\n\t).penalty\n}\n\n/**\n * Builds an operating table: at each distinct score of a positive row, falling, the positive rows\n * and the negative rows that reach it.\n *\n * @remarks\n * Each point catches more positives than the one before, so the table lists every cutoff worth\n * choosing; a caller picks the cutoff its costs favor.\n *\n * @param scores - Each row's score\n * @param positive - Whether each row is positive\n * @returns The table, by falling cutoff\n *\n * @example\n * ```ts\n * buildOperatingTable([0.9, 0.8, 0.7, 0.6, 0.2], [true, false, true, false, false])\n * // [{ cutoff: 0.9, caught: 1, mistaken: 0 }, { cutoff: 0.7, caught: 2, mistaken: 1 }]\n * ```\n */\nexport function buildOperatingTable(\n\tscores: readonly number[],\n\tpositive: readonly boolean[],\n): readonly TrainerCut[] {\n\tconst cutoffs = [...new Set(scores.filter((_, row) => positive[row] === true))].toSorted(\n\t\t(one, two) => two - one,\n\t)\n\treturn cutoffs.map((cutoff) => ({\n\t\tcutoff,\n\t\tcaught: scores.filter((score, row) => score >= cutoff && positive[row] === true).length,\n\t\tmistaken: scores.filter((score, row) => score >= cutoff && positive[row] !== true).length,\n\t}))\n}\n\n/**\n * Computes the gradient of the calibration objective at its parameters.\n *\n * @remarks\n * Parameter 0 is the log temperature, and parameter `k` from 1 is label `k`'s bias; label 0's bias\n * stays 0, because the softmax ignores a shift common to every label. The objective is the mean\n * negative log likelihood of the rows' labels under `softmax(logit / temperature + bias)`, plus\n * `CALIBRATION_PRIOR / (2 * rows)` times the sum of the squared parameters.\n *\n * @param parameters - The log temperature, then each bias after label 0's\n * @param logits - The rows' logits, row by row\n * @param labels - Each row's label index\n * @param classes - The number of labels\n * @param strict - If `true`, uses `@orkestrel/infer`'s arithmetic `exponentiate`; if `false`, uses `Math.exp`\n * @returns The gradient, laid out as the parameters\n *\n * @example\n * ```ts\n * computeCalibrationGradient(new Float64Array(2), Float64Array.of(0, 0), [0], 2) // Float64Array [0, 0.5]\n * ```\n */\nexport function computeCalibrationGradient(\n\tparameters: Float64Array,\n\tlogits: Float64Array,\n\tlabels: readonly number[],\n\tclasses: number,\n\tstrict = false,\n): Float64Array {\n\tconst rows = labels.length\n\tconst logTemperature = parameters[0] ?? 0\n\tconst temperature = strict ? exponentiate(logTemperature) : Math.exp(logTemperature)\n\tconst scaled = Float64Array.from(logits, (logit, index) => {\n\t\tconst label = index % classes\n\t\treturn logit / temperature + (label === 0 ? 0 : (parameters[label] ?? 0))\n\t})\n\tconst residuals = new Float64Array(rows * classes)\n\tfor (let row = 0; row < rows; row += 1) {\n\t\tlet peak = Number.NEGATIVE_INFINITY\n\t\tfor (let label = 0; label < classes; label += 1) {\n\t\t\tpeak = Math.max(peak, scaled[row * classes + label] ?? 0)\n\t\t}\n\t\tlet mass = 0\n\t\tfor (let label = 0; label < classes; label += 1) {\n\t\t\tconst shifted = (scaled[row * classes + label] ?? 0) - peak\n\t\t\tmass += strict ? exponentiate(shifted) : Math.exp(shifted)\n\t\t}\n\t\tfor (let label = 0; label < classes; label += 1) {\n\t\t\tconst shifted = (scaled[row * classes + label] ?? 0) - peak\n\t\t\tconst weight = strict ? exponentiate(shifted) : Math.exp(shifted)\n\t\t\tresiduals[row * classes + label] = weight / mass - (labels[row] === label ? 1 : 0)\n\t\t}\n\t}\n\treturn Float64Array.from({ length: classes }, (_, parameter) => {\n\t\tconst prior = (CALIBRATION_PRIOR * (parameters[parameter] ?? 0)) / rows\n\t\tif (parameter === 0) {\n\t\t\tlet slope = 0\n\t\t\tfor (let index = 0; index < residuals.length; index += 1) {\n\t\t\t\tslope += (residuals[index] ?? 0) * (-(logits[index] ?? 0) / temperature)\n\t\t\t}\n\t\t\treturn slope / rows + prior\n\t\t}\n\t\tlet sum = 0\n\t\tfor (let row = 0; row < rows; row += 1) sum += residuals[row * classes + parameter] ?? 0\n\t\treturn sum / rows + prior\n\t})\n}\n\n/**\n * Fits a temperature and per-label biases to rows' logits and labels.\n *\n * @remarks\n * Runs `CALIBRATION_STEPS` Adam steps at `CALIBRATION_RATE` from a temperature of 1 and zero biases\n * on the objective `computeCalibrationGradient` states. The rows are the held rows a head's fit never\n * read. Label 0's bias is 0. When `strict` is `true`, every exponential runs through\n * `@orkestrel/infer`'s `exponentiate` so calibrated head files stay bit-equal across Node and\n * Chromium.\n *\n * @param logits - The rows' logits, row by row\n * @param labels - Each row's label index\n * @param classes - The number of labels\n * @param strict - If `true`, uses `@orkestrel/infer`'s arithmetic `exponentiate`; if `false`, uses `Math.exp`\n * @returns The calibration\n *\n * @example\n * ```ts\n * fitCalibration(heldLogits, heldLabels, 2).temperature // 1.6\n * ```\n */\nexport function fitCalibration(\n\tlogits: Float64Array,\n\tlabels: readonly number[],\n\tclasses: number,\n\tstrict = false,\n): Calibration {\n\tconst initial: AdamState = {\n\t\tmodel: new Float64Array(classes),\n\t\tfirst: new Float64Array(classes),\n\t\tsecond: new Float64Array(classes),\n\t}\n\tconst fitted = Array.from({ length: CALIBRATION_STEPS }, (_, index) => index + 1).reduce(\n\t\t(state, step) =>\n\t\t\tstepAdam(\n\t\t\t\tstate,\n\t\t\t\tcomputeCalibrationGradient(state.model, logits, labels, classes, strict),\n\t\t\t\tstep,\n\t\t\t\tCALIBRATION_RATE,\n\t\t\t),\n\t\tinitial,\n\t)\n\tconst logTemperature = fitted.model[0] ?? 0\n\treturn {\n\t\ttemperature: strict ? exponentiate(logTemperature) : Math.exp(logTemperature),\n\t\tbias: Array.from({ length: classes }, (_, label) =>\n\t\t\tlabel === 0 ? 0 : (fitted.model[label] ?? 0),\n\t\t),\n\t}\n}\n\n/**\n * Computes the digest of a list of rows: the SHA-256 of one JSON line per row, `[state, label]`\n * when `group` is absent and `[state, label, group]` when present, joined by line feeds.\n *\n * @remarks\n * The order of the rows is part of the digest, because it fixes the folds. Ungrouped datasets encode\n * identically to `[state, label]`. Rejects as `@orkestrel/infer`'s `digestBytes` states.\n *\n * @param rows - The rows\n * @returns The digest\n *\n * @example\n * ```ts\n * await computeDatasetDigest([{ state: 'user: hi', label: 'chatter' }]) // 64 hexadecimal characters\n * ```\n */\nexport async function computeDatasetDigest(rows: readonly TrainerRow[]): Promise<Digest> {\n\treturn digestBytes(\n\t\tUTF8_ENCODER.encode(\n\t\t\trows\n\t\t\t\t.map((row) =>\n\t\t\t\t\trow.group === undefined\n\t\t\t\t\t\t? JSON.stringify([row.state, row.label])\n\t\t\t\t\t\t: JSON.stringify([row.state, row.label, row.group]),\n\t\t\t\t)\n\t\t\t\t.join('\\n'),\n\t\t),\n\t)\n}\n\n/**\n * Computes a head file's name: its SHA-256 digest, which `@orkestrel/infer`'s `HeadInterface.digest` reports,\n * followed by `HEAD_FILE_EXTENSION`.\n *\n * @remarks\n * Rejects as `@orkestrel/infer`'s `digestBytes` states.\n *\n * @param bytes - The head file's bytes\n * @returns The name\n *\n * @example\n * ```ts\n * await computeHeadName(result.bytes) // '3f2a…9c.gguf'\n * ```\n */\nexport async function computeHeadName(bytes: Uint8Array<ArrayBuffer>): Promise<string> {\n\treturn `${await digestBytes(bytes)}${HEAD_FILE_EXTENSION}`\n}\n\n/**\n * Reads training rows from NDJSON text chunks, each line one row.\n *\n * @remarks\n * Feeds every chunk to a strict `@orkestrel/ndjson` parser, which reassembles a line split across\n * chunks, skips blank lines, and reads a last line that has no line feed. A line that is not a JSON\n * object rejects with the parser's `NDJSONError`. A record that fails `isTrainerRow` rejects with\n * the `FORMAT` code naming its place among the records and its faults. The signal is checked before\n * each chunk; on abort it rejects with the `ABORT` code.\n *\n * @param chunks - The text, in chunks\n * @param signal - Cancels the read\n * @returns The rows, in line order\n *\n * @example\n * ```ts\n * await readTrainerRows(['{\"state\":\"user: hi\",\"label\":\"chatter\"}\\n']) // [{ state: 'user: hi', label: 'chatter' }]\n * ```\n */\nexport async function readTrainerRows(\n\tchunks: AsyncIterable<string> | Iterable<string>,\n\tsignal?: AbortSignal,\n): Promise<readonly TrainerRow[]> {\n\tcheckSignal(signal, 'The row read')\n\tconst parser = createNDJSONParser()\n\tconst batches: Array<ReadonlyArray<Record<string, unknown>>> = []\n\tfor await (const chunk of chunks) {\n\t\tcheckSignal(signal, 'The row read')\n\t\tbatches.push(parser.parse(chunk))\n\t}\n\tconst records = [...batches.flat(), ...parser.parse('\\n')]\n\treturn records.map((record, index) => {\n\t\tif (isTrainerRow(record)) {\n\t\t\treturn record.group === undefined\n\t\t\t\t? { state: record.state, label: record.label }\n\t\t\t\t: { state: record.state, label: record.label, group: record.group }\n\t\t}\n\t\tthrow new InferError(renderRowRefusal(record, `Record ${index + 1}`), {\n\t\t\tcode: 'FORMAT',\n\t\t\tcontext: { record: index + 1 },\n\t\t})\n\t})\n}\n\n/**\n * Reads training rows from CSV text through `@orkestrel/csv`, validating every row against\n * `isTrainerRow`.\n *\n * @remarks\n * Parses with `header: true`, `blanks: false`, `ragged: 'error'`, and `strict: true`, admitting\n * `(state, label)` or `(state, label, group)` headers by default, or custom header mappings through\n * `options.columns`. An empty `group` cell omits `group` on that row so mixed grouped and ungrouped\n * CSVs produce valid `TrainerRow` values. Throws `InferError` with code `ARGUMENT` for invalid\n * arguments, column mappings, or delimiters, and code `FORMAT` for malformed CSV syntax, missing\n * required headers, unexpected default columns, or rows failing `isTrainerRow`.\n *\n * @param text - The UTF-8 CSV text (leading BOM optional)\n * @param options - Optional column mapping and field delimiter\n * @returns The validated rows, in source order\n *\n * @example\n * ```ts\n * readTrainerCSV('state,label\\n\"user: hi\",chatter\\n') // [{ state: 'user: hi', label: 'chatter' }]\n * ```\n */\nexport function readTrainerCSV(text: string, options?: TrainerCSVOptions): readonly TrainerRow[] {\n\tif (!isString(text)) {\n\t\tthrow new InferError('The CSV input must be a string.', { code: 'ARGUMENT' })\n\t}\n\tif (options !== undefined && !isRecord(options)) {\n\t\tthrow new InferError('The CSV options must be a plain object.', { code: 'ARGUMENT' })\n\t}\n\tconst columnsOption = options?.columns\n\tif (columnsOption !== undefined) {\n\t\tif (!isRecord(columnsOption)) {\n\t\t\tthrow new InferError('The CSV columns mapping must be a plain object.', { code: 'ARGUMENT' })\n\t\t}\n\t\tconst allowedKeys = ['state', 'label', 'group']\n\t\tconst extraKeys = Object.keys(columnsOption).filter((key) => !allowedKeys.includes(key))\n\t\tif (extraKeys.length > 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The CSV columns mapping carries unsupported keys: ${extraKeys.map(quoteFaultText).join(', ')}.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { keys: extraKeys } },\n\t\t\t)\n\t\t}\n\t\tfor (const key of allowedKeys) {\n\t\t\tif (Object.hasOwn(columnsOption, key)) {\n\t\t\t\tconst mapped = columnsOption[key]\n\t\t\t\tif (!isString(mapped) || mapped.length === 0) {\n\t\t\t\t\tthrow new InferError(`The CSV ${key} column mapping must be a non-empty string.`, {\n\t\t\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\t\t\tcontext: { key },\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tconst stateColumn = isString(columnsOption?.state) ? columnsOption.state : 'state'\n\tconst labelColumn = isString(columnsOption?.label) ? columnsOption.label : 'label'\n\tconst explicitGroup = isString(columnsOption?.group) ? columnsOption.group : undefined\n\tif (\n\t\tstateColumn === labelColumn ||\n\t\t(explicitGroup !== undefined &&\n\t\t\t(explicitGroup === stateColumn || explicitGroup === labelColumn))\n\t) {\n\t\tthrow new InferError('The CSV column mappings for state, label, and group must be distinct.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: {\n\t\t\t\tstate: stateColumn,\n\t\t\t\tlabel: labelColumn,\n\t\t\t\t...(explicitGroup === undefined ? {} : { group: explicitGroup }),\n\t\t\t},\n\t\t})\n\t}\n\tconst delimiter = options?.delimiter\n\tif (delimiter !== undefined && !isString(delimiter)) {\n\t\tthrow new InferError('The CSV delimiter must be a single-character string.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tconst parseOptions: ParseOptions = {\n\t\theader: true,\n\t\tblanks: false,\n\t\tragged: 'error',\n\t\tstrict: true,\n\t\t...(delimiter === undefined ? {} : { delimiter }),\n\t}\n\tconst parsedOutcome = attempt<CSVParseResult>(() => parseCSV(text, parseOptions))\n\tif (!parsedOutcome.success) {\n\t\tconst caught = parsedOutcome.error\n\t\tif (isCSVError(caught)) {\n\t\t\tthrow new InferError(caught.message, {\n\t\t\t\tcode: caught.code === 'INVALID_OPTION' ? 'ARGUMENT' : 'FORMAT',\n\t\t\t\tcause: caught,\n\t\t\t\tcontext: {\n\t\t\t\t\tcode: caught.code,\n\t\t\t\t\t...(caught.line === undefined ? {} : { line: caught.line }),\n\t\t\t\t\t...(caught.column === undefined ? {} : { column: caught.column }),\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t\tthrow caught\n\t}\n\tconst { columns, rows } = parsedOutcome.value.table\n\tif (columns.length === 0 && rows.length === 0) return []\n\tconst requiredColumns =\n\t\texplicitGroup === undefined\n\t\t\t? [stateColumn, labelColumn]\n\t\t\t: [stateColumn, labelColumn, explicitGroup]\n\tconst missingColumns = requiredColumns.filter((column) => !columns.includes(column))\n\tif (missingColumns.length > 0) {\n\t\tthrow new InferError(\n\t\t\t`The CSV header lacks required column ${missingColumns.map(quoteFaultText).join(', ')}.`,\n\t\t\t{ code: 'FORMAT', context: { missing: missingColumns } },\n\t\t)\n\t}\n\tconst groupColumn =\n\t\texplicitGroup ??\n\t\t(stateColumn !== 'group' && labelColumn !== 'group' && columns.includes('group')\n\t\t\t? 'group'\n\t\t\t: undefined)\n\tif (columnsOption === undefined) {\n\t\tconst admitted =\n\t\t\tgroupColumn === undefined\n\t\t\t\t? [stateColumn, labelColumn]\n\t\t\t\t: [stateColumn, labelColumn, groupColumn]\n\t\tconst unexpected = columns.filter((column) => !admitted.includes(column))\n\t\tif (unexpected.length > 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The CSV header carries unsupported column ${unexpected.map(quoteFaultText).join(', ')}.`,\n\t\t\t\t{ code: 'FORMAT', context: { columns: unexpected } },\n\t\t\t)\n\t\t}\n\t}\n\treturn rows.map((record, index) => {\n\t\tconst stateValue = record[stateColumn]\n\t\tconst labelValue = record[labelColumn]\n\t\tconst groupValue = groupColumn === undefined ? undefined : record[groupColumn]\n\t\tconst candidate =\n\t\t\tgroupColumn === undefined || groupValue === ''\n\t\t\t\t? { state: stateValue, label: labelValue }\n\t\t\t\t: { state: stateValue, label: labelValue, group: groupValue }\n\t\tif (isTrainerRow(candidate)) {\n\t\t\treturn candidate.group === undefined\n\t\t\t\t? { state: candidate.state, label: candidate.label }\n\t\t\t\t: { state: candidate.state, label: candidate.label, group: candidate.group }\n\t\t}\n\t\tthrow new InferError(renderRowRefusal(candidate, `Row ${index + 1}`), {\n\t\t\tcode: 'FORMAT',\n\t\t\tcontext: { row: index + 1 },\n\t\t})\n\t})\n}\n\n/**\n * Infers the training label a judge answer reads: the one candidate that holds the greatest\n * probability, as the `measureAnswer` function of `@orkestrel/agent` names its winner.\n *\n * @remarks\n * A choice reads its option name, a score its level index as text, and a noul `'true'` or `'false'`,\n * the candidate keys `collectQuestionKeys` lists. When more than one candidate holds the greatest\n * probability, such as a noul of exactly 0.5, or no candidate holds it, as with a `NaN`, it returns\n * `undefined` rather than the first candidate, because a stored choice keeps the key order its store\n * returned. Thrown as a `JudgeError` with the `PROTOCOL` code, by `measureAnswer`, when a choice or\n * score holds fewer than 2 candidates.\n *\n * @param answer - The answer whose distribution is read\n * @returns The label, or undefined when no single candidate holds the greatest probability\n *\n * @example\n * ```ts\n * inferAnswerLabel({ form: 'choice', probabilities: { refund: 0.7, chatter: 0.2, fact: 0.1 } }) // 'refund'\n * inferAnswerLabel({ form: 'score', probabilities: [0.1, 0.6, 0.3] }) // '1'\n * inferAnswerLabel({ form: 'noul', noul: 0.5 }) // undefined\n * ```\n */\nexport function inferAnswerLabel(answer: JudgeAnswer): string | undefined {\n\tconst candidates =\n\t\tanswer.form === 'noul' ? [answer.noul, 1 - answer.noul] : Object.values(answer.probabilities)\n\tconst peak = Math.max(...candidates)\n\tif (candidates.filter((value) => value === peak).length !== 1) return undefined\n\treturn measureAnswer(answer).winner\n}\n\n/**\n * Collects training rows from recorded judgments of one question, so a head trains on what a\n * conversation's judge recorded and on the corrections recorded beside it.\n *\n * @remarks\n * Keeps each record whose question equals `options.question` as a JSON value, through the\n * `matchesJSON` function of `@orkestrel/agent`, and that `options.filter` keeps. A kept record with\n * an answer becomes the row `{ state, label }`: its rendered `state`, the text the judge read, and\n * the label `inferAnswerLabel` reads. A kept record with no answer is counted in `refusals`, and one whose\n * answer names no single candidate in `ties`; neither becomes a row. Pass a snapshot's\n * `judgments ?? []`, or the `judgments()` list of a conversation's store. Thrown with the `ARGUMENT`\n * code when the question fails `isJudgeQuestion` or the filter is given and is not a function, and,\n * naming the record's index and id, when a kept answer fails `scanJudgmentTies` against the question,\n * such as an answer of another form.\n *\n * @param judgments - The recorded judgments, in the order the rows take\n * @param options - The question and the filter\n * @returns The rows, the refusal count, and the tie count\n *\n * @example\n * ```ts\n * const { rows, refusals } = collectJudgmentRows(conversation.judgments.judgments(), { question: refund })\n * rows[0] // { state: 'user: refund me', label: 'true' }\n * ```\n */\nexport function collectJudgmentRows(\n\tjudgments: readonly Judgment[],\n\toptions: JudgmentRowOptions,\n): JudgmentRowResult {\n\tconst { question, filter } = options\n\tif (!isJudgeQuestion(question)) {\n\t\tthrow new InferError(\n\t\t\t'The judgment question is not a judge question: pass the choice, score, or noul the records answer, as @orkestrel/agent defines them.',\n\t\t\t{ code: 'ARGUMENT' },\n\t\t)\n\t}\n\tif (filter !== undefined && typeof filter !== 'function') {\n\t\tthrow new InferError(\n\t\t\t\"The judgment filter is a function that keeps a record when it returns true, such as (judgment) => judgment.model === 'reviewer'.\",\n\t\t\t{ code: 'ARGUMENT' },\n\t\t)\n\t}\n\tconst kept = judgments.flatMap((judgment, index) =>\n\t\tmatchesJSON(judgment.question, question) && (filter === undefined || filter(judgment) === true)\n\t\t\t? [{ index, id: judgment.id, answer: judgment.answer, state: judgment.state }]\n\t\t\t: [],\n\t)\n\tconst readings = kept.flatMap(({ index, id, answer, state }) => {\n\t\tif (answer === undefined) return []\n\t\tconst faults = scanJudgmentTies(question, answer)\n\t\tif (faults.length > 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The judgment at index ${index}, ${quoteFaultText(id)}, holds an answer that does not fit its ${question.form} question (${describeFaults(faults)}); an answer holds the question's form, a probability in [0, 1] for each candidate, a choice's criteria keys, and a score's levels.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { judgment: index, faults } },\n\t\t\t)\n\t\t}\n\t\treturn [{ state, label: inferAnswerLabel(answer) }]\n\t})\n\tconst rows = readings.flatMap(({ state, label }) =>\n\t\tlabel === undefined ? [] : [{ state, label }],\n\t)\n\treturn { rows, refusals: kept.length - readings.length, ties: readings.length - rows.length }\n}\n\n/**\n * Traces a mean-pooled decision head across every causal prefix of a state, reconstructing each\n * token's normalized vector in double precision and projecting its additive share onto each label's\n * logit.\n *\n * @remarks\n * Tokenizes `state`, checks `1 <= tokens.length <= backbone.limit`, reads all causal prefix\n * embeddings in one `O(L)` forward through `backbone.prefixes(tokens, { depth: record.depth, signal })`\n * when available (falling back to per-prefix `backbone.embed` on custom backbones that omit\n * `prefixes`), reconstructs `u_0 = e_1` and `u_t = (t + 1) * e_{t + 1} - t * e_t` in `Float64`, and\n * projects each token's share\n * `s_{t,k} = (1 / L) * sum_c (matrix[k * D + c] / scale[c]) * (u_t[c] - mean[c])`. For every label\n * `k`, `weights.bias[k] + sum_t s_{t,k}` equals `logits[k]`, and `probabilities` matches\n * `Head.predict(embedding)`. Rejects with the `BINDING` code when `record.base` differs from\n * `backbone.digest`, the `ABORT` code when `signal` aborts, and the `ARGUMENT` code for invalid\n * depth, pooling, weight shapes, calibration, or token count.\n *\n * @param options - The backbone, head record, head weights, state text, and optional abort signal\n * @returns Each token's attribution, the full embedding, the logits, and calibrated probabilities\n *\n * @example\n * ```ts\n * const trace = await traceHead({ backbone, record, weights, state: 'user: refund me' })\n * trace.tokens.length // 15\n * ```\n */\nexport async function traceHead(options: HeadTraceOptions): Promise<HeadTraceResult> {\n\tconst { backbone, record, weights, state, signal } = options\n\tcheckSignal(signal, 'The head trace')\n\tif (record.base !== backbone.digest) {\n\t\tthrow new InferError(\n\t\t\t`The head binds base ${quoteFaultText(record.base)}, not backbone ${quoteFaultText(backbone.digest)}.`,\n\t\t\t{ code: 'BINDING', context: { expected: record.base, actual: backbone.digest } },\n\t\t)\n\t}\n\tif (record.pooling !== 'mean') {\n\t\tthrow new InferError(\n\t\t\t`The head pooling is ${quoteFaultText(record.pooling)}; tracing requires mean pooling.`,\n\t\t\t{ code: 'ARGUMENT', context: { pooling: record.pooling } },\n\t\t)\n\t}\n\tconst { dimension, layers } = backbone.architecture\n\tif (!matchesCount(record.depth, 1) || record.depth > layers) {\n\t\tthrow new InferError(\n\t\t\t`The head depth is ${record.depth}; the backbone embeds at an integer depth from 1 to ${layers}.`,\n\t\t\t{ code: 'ARGUMENT', context: { depth: record.depth, layers } },\n\t\t)\n\t}\n\tconst classes = record.labels.length\n\tif (classes < 2) {\n\t\tthrow new InferError(`The head lists ${classes} labels; a head distributes over at least 2.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { labels: classes },\n\t\t})\n\t}\n\tcheckHeadWeights(weights, classes)\n\tconst { matrix, mean, scale } = weights\n\tif (mean.length !== dimension) {\n\t\tthrow new InferError(\n\t\t\t`The head weights have width ${mean.length}; the backbone embeds width ${dimension}.`,\n\t\t\t{ code: 'ARGUMENT', context: { classes, dimension, width: mean.length } },\n\t\t)\n\t}\n\tif (\n\t\t!Number.isFinite(record.calibration.temperature) ||\n\t\trecord.calibration.temperature <= 0 ||\n\t\trecord.calibration.bias.length !== classes ||\n\t\t!record.calibration.bias.every(Number.isFinite)\n\t) {\n\t\tthrow new InferError(\n\t\t\t`The head calibration requires a positive finite temperature and ${classes} finite label biases.`,\n\t\t\t{ code: 'ARGUMENT', context: { classes } },\n\t\t)\n\t}\n\tif (!matchesTokenBound(backbone.tokenizer, state, backbone.limit)) {\n\t\tthrow new InferError(\n\t\t\t`The state holds more UTF-8 bytes than ${backbone.limit} tokens of at most ${backbone.tokenizer.span} bytes can cover; the backbone embeds a state of 1 to ${backbone.limit} tokens.`,\n\t\t\t{ code: 'ARGUMENT', context: { limit: backbone.limit, span: backbone.tokenizer.span } },\n\t\t)\n\t}\n\tconst tokenIds = backbone.tokenizer.encode(state)\n\tconst length = tokenIds.length\n\tif (length === 0 || length > backbone.limit) {\n\t\tthrow new InferError(\n\t\t\t`The state encodes to ${length} tokens; the backbone embeds a state of 1 to ${backbone.limit} tokens.`,\n\t\t\t{ code: 'ARGUMENT', context: { tokens: length, limit: backbone.limit } },\n\t\t)\n\t}\n\tconst prefixes: Float32Array[] = []\n\tif (typeof backbone.prefixes === 'function') {\n\t\tcheckSignal(signal, 'The head trace')\n\t\tconst packed = await backbone.prefixes(Uint32Array.from(tokenIds), {\n\t\t\tdepth: record.depth,\n\t\t\t...(signal === undefined ? {} : { signal }),\n\t\t})\n\t\tconst expected = length * dimension\n\t\tif (packed.length !== expected) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The backbone prefixes returned ${packed.length} feature values for ${length} tokens; expected ${expected}.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { tokens: length, dimension, actual: packed.length } },\n\t\t\t)\n\t\t}\n\t\tfor (let position = 0; position < length; position += 1) {\n\t\t\tprefixes.push(packed.subarray(position * dimension, (position + 1) * dimension))\n\t\t}\n\t} else {\n\t\tfor (let end = 1; end <= length; end += 1) {\n\t\t\tcheckSignal(signal, 'The head trace')\n\t\t\tconst prefix = await backbone.embed(tokenIds.slice(0, end), record.depth, signal)\n\t\t\tif (prefix.length !== dimension) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The backbone returned ${prefix.length} feature values for prefix length ${end}; expected ${dimension}.`,\n\t\t\t\t\t{ code: 'ARGUMENT', context: { prefix: end, dimension, actual: prefix.length } },\n\t\t\t\t)\n\t\t\t}\n\t\t\tprefixes.push(prefix)\n\t\t}\n\t}\n\tconst tokens: readonly HeadTraceToken[] = tokenIds.map((token, position) => {\n\t\tconst current = prefixes[position] ?? new Float32Array(dimension)\n\t\tconst previous = position > 0 ? prefixes[position - 1] : undefined\n\t\tconst vector = new Float64Array(dimension)\n\t\tfor (let column = 0; column < dimension; column += 1) {\n\t\t\tvector[column] =\n\t\t\t\tposition === 0\n\t\t\t\t\t? (current[column] ?? 0)\n\t\t\t\t\t: (position + 1) * (current[column] ?? 0) - position * (previous?.[column] ?? 0)\n\t\t}\n\t\tconst shares = new Float64Array(classes)\n\t\tfor (let label = 0; label < classes; label += 1) {\n\t\t\tlet sum = 0\n\t\t\tfor (let column = 0; column < dimension; column += 1) {\n\t\t\t\tsum +=\n\t\t\t\t\t((matrix[label * dimension + column] ?? 0) / (scale[column] ?? 1)) *\n\t\t\t\t\t((vector[column] ?? 0) - (mean[column] ?? 0))\n\t\t\t}\n\t\t\tshares[label] = sum / length\n\t\t}\n\t\treturn { token, text: backbone.tokenizer.decode([token]), vector, shares }\n\t})\n\tconst embedding = Float32Array.from(prefixes[length - 1] ?? new Float32Array(dimension))\n\tconst logits = computeHeadLogits(weights, [embedding])\n\tconst probabilities = Array.from(\n\t\tcomputeDistributions(logits, classes, record.calibration, backbone.strict),\n\t)\n\treturn { labels: [...record.labels], tokens, embedding, logits, probabilities }\n}\n\n/**\n * Counts labelled prediction flips between baseline and candidate outputs and computes the 95%\n * one-sided upper bound on the negative flip rate.\n *\n * @remarks\n * Partitions every index into `kept` (right to right), `negative` (right to wrong), `positive`\n * (wrong to right), and `wrong` (wrong to wrong), and records every index where `before` differs\n * from `after` in `changed`. When `negative` is 0, `bound` uses the rule of three\n * (`Math.min(1, 3 / total)`); when `negative` is positive, `bound` uses the 95% one-sided Wilson\n * score upper bound (`z = 1.6448536269514722`). Thrown with the `ARGUMENT` code when `expected` is\n * empty or the three lists differ in length.\n *\n * @typeParam T - The label value type compared with strict equality\n * @param options - The expected labels, baseline predictions, and candidate predictions\n * @returns The partition counts, negative flip rate, 95% upper bound, and exact row indexes\n *\n * @example\n * ```ts\n * countFlips({ expected: ['a', 'b'], before: ['a', 'a'], after: ['a', 'b'] }).positive // 1\n * ```\n */\nexport function countFlips<T = string>(options: FlipCountOptions<T>): FlipCountResult {\n\tconst { expected, before, after } = options\n\tconst total = expected.length\n\tif (total === 0 || before.length !== total || after.length !== total) {\n\t\tthrow new InferError(\n\t\t\t`The flip comparison received ${total} expected, ${before.length} baseline, and ${after.length} candidate entries; pass three non-empty arrays of one length.`,\n\t\t\t{\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\tcontext: { expected: total, before: before.length, after: after.length },\n\t\t\t},\n\t\t)\n\t}\n\tconst kept = expected.flatMap((value, index) =>\n\t\tbefore[index] === value && after[index] === value ? [index] : [],\n\t)\n\tconst negative = expected.flatMap((value, index) =>\n\t\tbefore[index] === value && after[index] !== value ? [index] : [],\n\t)\n\tconst positive = expected.flatMap((value, index) =>\n\t\tbefore[index] !== value && after[index] === value ? [index] : [],\n\t)\n\tconst wrong = expected.flatMap((value, index) =>\n\t\tbefore[index] !== value && after[index] !== value ? [index] : [],\n\t)\n\tconst changed = before.flatMap((value, index) => (value === after[index] ? [] : [index]))\n\tconst rate = negative.length / total\n\tconst z = 1.6448536269514722\n\tconst z2 = z * z\n\tconst bound =\n\t\tnegative.length === 0\n\t\t\t? Math.min(1, 3 / total)\n\t\t\t: Math.min(\n\t\t\t\t\t1,\n\t\t\t\t\t(rate +\n\t\t\t\t\t\tz2 / (2 * total) +\n\t\t\t\t\t\tz * Math.sqrt((rate * (1 - rate)) / total + z2 / (4 * total * total))) /\n\t\t\t\t\t\t(1 + z2 / total),\n\t\t\t\t)\n\treturn {\n\t\ttotal,\n\t\tkept: kept.length,\n\t\tnegative: negative.length,\n\t\tpositive: positive.length,\n\t\twrong: wrong.length,\n\t\tchanged: changed.length,\n\t\trate,\n\t\tbound,\n\t\tindexes: { kept, negative, positive, wrong, changed },\n\t}\n}\n\n/**\n * Counts label-free decision shifts between baseline and candidate outputs and lists each shifted\n * row index, optionally recording the compared precision formats (`'BF16'`, `'Q8_0'`, `'Q4_K_M'`).\n *\n * @remarks\n * Intended for comparing full and compressed model decisions without requiring ground-truth labels.\n * Thrown with the `ARGUMENT` code when `before` is empty, differs in length from `after`, or\n * `formats` carries an unsupported precision format.\n *\n * @typeParam T - The decision value type compared with strict equality\n * @param options - The baseline and candidate predictions and optional precision formats\n * @returns The total, unchanged, and changed counts, the change rate, shifted row indexes, and optional formats\n *\n * @example\n * ```ts\n * countChanges({ before: ['admit', 'refuse'], after: ['admit', 'admit'] }).indexes // [1]\n * ```\n */\nexport function countChanges<T = string>(options: ChangeCountOptions<T>): ChangeCountResult {\n\tconst { before, after, formats } = options\n\tconst total = before.length\n\tif (total === 0 || after.length !== total) {\n\t\tthrow new InferError(\n\t\t\t`The change comparison received ${total} baseline and ${after.length} candidate entries; pass two non-empty arrays of one length.`,\n\t\t\t{ code: 'ARGUMENT', context: { before: total, after: after.length } },\n\t\t)\n\t}\n\tif (formats !== undefined) {\n\t\tif (\n\t\t\t!isRecord(formats) ||\n\t\t\t!isPrecisionFormat(formats.before) ||\n\t\t\t!isPrecisionFormat(formats.after)\n\t\t) {\n\t\t\tthrow new InferError(\n\t\t\t\t'The change comparison formats must name \"BF16\", \"Q8_0\", or \"Q4_K_M\" for both before and after.',\n\t\t\t\t{ code: 'ARGUMENT' },\n\t\t\t)\n\t\t}\n\t}\n\tconst indexes = before.flatMap((value, index) => (value === after[index] ? [] : [index]))\n\tconst changed = indexes.length\n\treturn {\n\t\ttotal,\n\t\tunchanged: total - changed,\n\t\tchanged,\n\t\trate: changed / total,\n\t\tindexes,\n\t\t...(formats === undefined ? {} : { formats: { before: formats.before, after: formats.after } }),\n\t}\n}\n\n/**\n * Compares full-vs-compressed outputs across `'BF16'`, `'Q8_0'`, and `'Q4_K_M'` formats before and\n * optionally after adaptation using `countChanges` and optional `countFlips`.\n *\n * @remarks\n * Validates `reference` (default `'BF16'`) and every supplied format key against\n * `isPrecisionFormat`, verifies matching non-empty row lengths across all supplied arrays, and\n * emits per-format shift and optional flip entries in `PRECISION_FORMATS` order. Thrown with the\n * `ARGUMENT` code when `base` omits the reference format, carries unknown formats, has mismatched\n * lengths, or supplies nothing to compare.\n *\n * @typeParam T - The decision value type compared with strict equality\n * @param options - The reference format, baseline format outputs, optional adapted outputs, and optional expected labels\n * @returns The reference and per-format shift and optional flip reports\n *\n * @example\n * ```ts\n * const report = countFormatChanges({\n * \tbase: { BF16: ['met', 'unmet'], Q8_0: ['met', 'unmet'], Q4_K_M: ['met', 'met'] },\n * })\n * report.formats.map((entry) => entry.format) // ['Q8_0', 'Q4_K_M']\n * ```\n */\nexport function countFormatChanges<T = string>(\n\toptions: FormatChangeOptions<T>,\n): FormatChangeResult {\n\tif (!isRecord(options)) {\n\t\tthrow new InferError('The format change options must be a plain object carrying base.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tconst reference: PrecisionFormat = options.reference ?? 'BF16'\n\tif (!isPrecisionFormat(reference)) {\n\t\tthrow new InferError(\n\t\t\t`The reference format ${quoteFaultText(String(reference))} must be \"BF16\", \"Q8_0\", or \"Q4_K_M\".`,\n\t\t\t{ code: 'ARGUMENT', context: { reference } },\n\t\t)\n\t}\n\tif (!isRecord(options.base)) {\n\t\tthrow new InferError('The format change base outputs must be a plain object keyed by format.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tconst badBaseKey = Object.keys(options.base).find((key) => !isPrecisionFormat(key))\n\tif (badBaseKey !== undefined) {\n\t\tthrow new InferError(\n\t\t\t`The base format key ${quoteFaultText(badBaseKey)} is not one of \"BF16\", \"Q8_0\", or \"Q4_K_M\".`,\n\t\t\t{ code: 'ARGUMENT', context: { format: badBaseKey } },\n\t\t)\n\t}\n\tif (options.adapted !== undefined) {\n\t\tif (!isRecord(options.adapted)) {\n\t\t\tthrow new InferError(\n\t\t\t\t'The format change adapted outputs must be a plain object keyed by format.',\n\t\t\t\t{ code: 'ARGUMENT' },\n\t\t\t)\n\t\t}\n\t\tconst badAdaptedKey = Object.keys(options.adapted).find((key) => !isPrecisionFormat(key))\n\t\tif (badAdaptedKey !== undefined) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The adapted format key ${quoteFaultText(badAdaptedKey)} is not one of \"BF16\", \"Q8_0\", or \"Q4_K_M\".`,\n\t\t\t\t{ code: 'ARGUMENT', context: { format: badAdaptedKey } },\n\t\t\t)\n\t\t}\n\t}\n\tconst refBase = options.base[reference]\n\tif (!isArray(refBase) || refBase.length === 0) {\n\t\tthrow new InferError(\n\t\t\t`The base outputs must include a non-empty array for reference format ${quoteFaultText(reference)}.`,\n\t\t\t{ code: 'ARGUMENT', context: { reference } },\n\t\t)\n\t}\n\tconst total = refBase.length\n\tconst expected = options.expected\n\tif (expected !== undefined && (!isArray(expected) || expected.length !== total)) {\n\t\tthrow new InferError(\n\t\t\t`The expected labels must hold ${total} entries matching reference format ${quoteFaultText(reference)}.`,\n\t\t\t{ code: 'ARGUMENT', context: { expected: isArray(expected) ? expected.length : -1, total } },\n\t\t)\n\t}\n\tconst refAdapted = options.adapted?.[reference]\n\tif (refAdapted !== undefined && (!isArray(refAdapted) || refAdapted.length !== total)) {\n\t\tthrow new InferError(\n\t\t\t`The adapted outputs for ${quoteFaultText(reference)} must hold ${total} entries.`,\n\t\t\t{ code: 'ARGUMENT', context: { format: reference, total } },\n\t\t)\n\t}\n\tfor (const format of PRECISION_FORMATS) {\n\t\tconst baseSeries = options.base[format]\n\t\tif (baseSeries !== undefined && (!isArray(baseSeries) || baseSeries.length !== total)) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The base outputs for ${quoteFaultText(format)} must hold ${total} entries.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { format, total } },\n\t\t\t)\n\t\t}\n\t\tconst adaptedSeries = options.adapted?.[format]\n\t\tif (adaptedSeries !== undefined) {\n\t\t\tif (!isArray(adaptedSeries) || adaptedSeries.length !== total) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The adapted outputs for ${quoteFaultText(format)} must hold ${total} entries.`,\n\t\t\t\t\t{ code: 'ARGUMENT', context: { format, total } },\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (baseSeries === undefined) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The adapted outputs include ${quoteFaultText(format)}, which is absent from base outputs.`,\n\t\t\t\t\t{ code: 'ARGUMENT', context: { format } },\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (format !== reference && refAdapted === undefined) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The adapted outputs include ${quoteFaultText(format)} without reference format ${quoteFaultText(reference)}.`,\n\t\t\t\t\t{ code: 'ARGUMENT', context: { format, reference } },\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\tconst otherFormats = PRECISION_FORMATS.filter(\n\t\t(format) => format !== reference && options.base[format] !== undefined,\n\t)\n\tif (otherFormats.length === 0 && refAdapted === undefined) {\n\t\tthrow new InferError(\n\t\t\t`The format change comparison requires at least one other format beside ${quoteFaultText(reference)} or adapted outputs for ${quoteFaultText(reference)}.`,\n\t\t\t{ code: 'ARGUMENT', context: { reference } },\n\t\t)\n\t}\n\tconst formats: readonly FormatChangeEntry[] = otherFormats.map((format) => {\n\t\tconst baseSeries = options.base[format] ?? []\n\t\tconst base = countChanges({\n\t\t\tbefore: refBase,\n\t\t\tafter: baseSeries,\n\t\t\tformats: { before: reference, after: format },\n\t\t})\n\t\tconst flips =\n\t\t\texpected === undefined\n\t\t\t\t? undefined\n\t\t\t\t: countFlips({ expected, before: refBase, after: baseSeries })\n\t\tconst adaptedSeries = options.adapted?.[format]\n\t\tconst adapted =\n\t\t\tadaptedSeries === undefined || refAdapted === undefined\n\t\t\t\t? undefined\n\t\t\t\t: countChanges({\n\t\t\t\t\t\tbefore: refAdapted,\n\t\t\t\t\t\tafter: adaptedSeries,\n\t\t\t\t\t\tformats: { before: reference, after: format },\n\t\t\t\t\t})\n\t\tconst delta =\n\t\t\tadaptedSeries === undefined\n\t\t\t\t? undefined\n\t\t\t\t: countChanges({\n\t\t\t\t\t\tbefore: baseSeries,\n\t\t\t\t\t\tafter: adaptedSeries,\n\t\t\t\t\t\tformats: { before: format, after: format },\n\t\t\t\t\t})\n\t\tconst gain =\n\t\t\tadaptedSeries === undefined || expected === undefined\n\t\t\t\t? undefined\n\t\t\t\t: countFlips({ expected, before: baseSeries, after: adaptedSeries })\n\t\treturn {\n\t\t\tformat,\n\t\t\tbase,\n\t\t\t...(adapted === undefined ? {} : { adapted }),\n\t\t\t...(delta === undefined ? {} : { delta }),\n\t\t\t...(flips === undefined ? {} : { flips }),\n\t\t\t...(gain === undefined ? {} : { gain }),\n\t\t}\n\t})\n\tconst delta =\n\t\trefAdapted === undefined\n\t\t\t? undefined\n\t\t\t: countChanges({\n\t\t\t\t\tbefore: refBase,\n\t\t\t\t\tafter: refAdapted,\n\t\t\t\t\tformats: { before: reference, after: reference },\n\t\t\t\t})\n\tconst gain =\n\t\trefAdapted === undefined || expected === undefined\n\t\t\t? undefined\n\t\t\t: countFlips({ expected, before: refBase, after: refAdapted })\n\treturn {\n\t\treference,\n\t\ttotal,\n\t\t...(delta === undefined ? {} : { delta }),\n\t\t...(gain === undefined ? {} : { gain }),\n\t\tformats,\n\t}\n}\n\n/**\n * Refuses a provenance record that omits any required field or names a hosted-model service or\n * family marker.\n *\n * @remarks\n * Requires non-empty trimmed strings for `source`, `licence`, `generator`, `date`, and `digest`.\n * Normalizes each field with NFKC, strips format and combining characters, folds Cyrillic and\n * Greek visual confusables to ASCII Latin, normalizes Unicode dashes to `-`, lower-cases the\n * result, and refuses token-bounded hosted-model markers (`anthropic`, `openai`, `google`, `xai`,\n * `claude`, `gpt-`, `gemini`, `grok`, or `chatgpt`) with the `ARGUMENT` code.\n *\n * @param provenance - The provenance record to check\n *\n * @example\n * ```ts\n * checkRowProvenance({\n * \tsource: 'local-reason-berth',\n * \tlicence: 'MIT',\n * \tgenerator: 'orkestrel-reason-local',\n * \tdate: '2026-11-30',\n * \tdigest: '0'.repeat(64),\n * })\n * ```\n */\nexport function checkRowProvenance(provenance: RowProvenance): void {\n\tif (!isRecord(provenance)) {\n\t\tthrow new InferError(\n\t\t\t'The provenance is not a plain object; every row carries source, licence, generator, date, and digest.',\n\t\t\t{ code: 'ARGUMENT' },\n\t\t)\n\t}\n\tconst fields = ['source', 'licence', 'generator', 'date', 'digest'] as const\n\tconst confusables: Readonly<Record<string, string>> = {\n\t\t'\\u0410': 'a',\n\t\t'\\u0430': 'a',\n\t\t'\\u0412': 'b',\n\t\t'\\u0432': 'b',\n\t\t'\\u0421': 'c',\n\t\t'\\u0441': 'c',\n\t\t'\\u0415': 'e',\n\t\t'\\u0435': 'e',\n\t\t'\\u041D': 'h',\n\t\t'\\u043D': 'h',\n\t\t'\\u0406': 'i',\n\t\t'\\u0456': 'i',\n\t\t'\\u0408': 'j',\n\t\t'\\u0458': 'j',\n\t\t'\\u041A': 'k',\n\t\t'\\u043A': 'k',\n\t\t'\\u041C': 'm',\n\t\t'\\u043C': 'm',\n\t\t'\\u041E': 'o',\n\t\t'\\u043E': 'o',\n\t\t'\\u0420': 'p',\n\t\t'\\u0440': 'p',\n\t\t'\\u0405': 's',\n\t\t'\\u0455': 's',\n\t\t'\\u0422': 't',\n\t\t'\\u0442': 't',\n\t\t'\\u0423': 'y',\n\t\t'\\u0443': 'y',\n\t\t'\\u0425': 'x',\n\t\t'\\u0445': 'x',\n\t\t'\\u0391': 'a',\n\t\t'\\u03B1': 'a',\n\t\t'\\u0392': 'b',\n\t\t'\\u0395': 'e',\n\t\t'\\u03B5': 'e',\n\t\t'\\u0397': 'h',\n\t\t'\\u0399': 'i',\n\t\t'\\u03B9': 'i',\n\t\t'\\u039A': 'k',\n\t\t'\\u03BA': 'k',\n\t\t'\\u039C': 'm',\n\t\t'\\u039D': 'n',\n\t\t'\\u03BD': 'v',\n\t\t'\\u039F': 'o',\n\t\t'\\u03BF': 'o',\n\t\t'\\u03A1': 'p',\n\t\t'\\u03C1': 'p',\n\t\t'\\u03A4': 't',\n\t\t'\\u03C4': 't',\n\t\t'\\u03A5': 'y',\n\t\t'\\u03C5': 'u',\n\t\t'\\u03A7': 'x',\n\t\t'\\u03C7': 'x',\n\t}\n\tconst markers: ReadonlyArray<readonly [marker: string, pattern: RegExp]> = [\n\t\t['anthropic', /anthropic/u],\n\t\t['openai', /openai|(?<![a-z0-9])open[\\s\\-_.]+ai(?![a-z])/u],\n\t\t['google', /google/u],\n\t\t['xai', /(?<![a-z0-9])x[\\s\\-_.]*ai(?![a-z0-9])/u],\n\t\t['claude', /claude/u],\n\t\t['chatgpt', /chatgpt|(?<![a-z0-9])chat[\\s\\-_.]+gpt(?![a-z])/u],\n\t\t['gpt-', /gpt-|(?<![a-z0-9])gpt(?:[\\s\\-_.]*(?:\\d|4o)|(?![a-z0-9]))/u],\n\t\t['gemini', /gemini/u],\n\t\t['grok', /grok/u],\n\t]\n\tfor (const field of fields) {\n\t\tconst value = provenance[field]\n\t\tif (!isString(value) || value.trim().length === 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The provenance lacks a non-empty ${quoteFaultText(field)}; every row carries source, licence, generator, date, and digest.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { field } },\n\t\t\t)\n\t\t}\n\t\tconst normalized = Array.from(\n\t\t\tvalue\n\t\t\t\t.normalize('NFKC')\n\t\t\t\t.replace(/\\p{Cf}|\\p{Mn}/gu, '')\n\t\t\t\t.replace(/\\p{Pd}/gu, '-'),\n\t\t\t(character) => confusables[character] ?? character,\n\t\t)\n\t\t\t.join('')\n\t\t\t.toLowerCase()\n\t\tif (normalized.trim().length === 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The provenance lacks a non-empty ${quoteFaultText(field)}; every row carries source, licence, generator, date, and digest.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { field } },\n\t\t\t)\n\t\t}\n\t\tconst matched = markers.find(([, pattern]) => pattern.test(normalized))\n\t\tif (matched !== undefined) {\n\t\t\tconst [marker] = matched\n\t\t\tthrow new InferError(\n\t\t\t\t`The provenance ${field} ${quoteFaultText(value)} carries hosted-model marker ${quoteFaultText(marker)}; no row written or labelled by a hosted model may enter a fit.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { field, marker } },\n\t\t\t)\n\t\t}\n\t}\n}\n\n/**\n * Collects grouped prompt-completion training rows from `@orkestrel/agent` conversation snapshots,\n * checking row provenance first and rendering each turn prefix through `@orkestrel/template`.\n *\n * @remarks\n * Verifies `options.provenance` through `checkRowProvenance` before inspecting snapshots or emitting\n * any row, validates every snapshot with `isConversationSnapshot` and a non-empty `id`, and emits\n * one `{ prompt, completion, group, provenance }` row per non-empty assistant turn that follows at\n * least one preceding message, with `group` set to `snapshot.id`. Template compilation or evaluation\n * failures translate `TemplateError` into `InferError` (`FORMAT` for syntax or subset refusals,\n * `ARGUMENT` for evaluation refusals).\n *\n * @param snapshots - The conversation snapshots to collect from, in order\n * @param options - The template tree or Jinja source, provenance record, and optional context values\n * @returns The rendered prompt-completion rows grouped by conversation id\n *\n * @example\n * ```ts\n * const rows = collectConversationRows([conversation.snapshot()], {\n * \ttemplate: '{% for m in messages %}{{ m.role }}: {{ m.content }}\\n{% endfor %}assistant: ',\n * \tprovenance,\n * })\n * rows[0]?.group === conversation.id // true\n * ```\n */\nexport function collectConversationRows(\n\tsnapshots: readonly ConversationSnapshot[],\n\toptions: ConversationRowOptions,\n): readonly ConversationRow[] {\n\tif (!isRecord(options)) {\n\t\tthrow new InferError(\n\t\t\t'The conversation row options must be a plain object carrying template and provenance.',\n\t\t\t{ code: 'ARGUMENT' },\n\t\t)\n\t}\n\tcheckRowProvenance(options.provenance)\n\tconst provenance: RowProvenance = {\n\t\tsource: options.provenance.source,\n\t\tlicence: options.provenance.licence,\n\t\tgenerator: options.provenance.generator,\n\t\tdate: options.provenance.date,\n\t\tdigest: options.provenance.digest,\n\t}\n\tif (options.context !== undefined && !isRecord(options.context)) {\n\t\tthrow new InferError('The conversation row context option must be a plain object.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tconst source = isString(options.template) ? options.template : undefined\n\tconst compiled = source !== undefined ? attempt(() => compileTemplate(source)) : undefined\n\tif (compiled !== undefined && !compiled.success) {\n\t\tconst code =\n\t\t\tisTemplateError(compiled.error) && compiled.error.code === 'FORMAT' ? 'FORMAT' : 'ARGUMENT'\n\t\tthrow new InferError(\n\t\t\t`The conversation template failed to compile: ${compiled.error instanceof Error ? compiled.error.message : String(compiled.error)}`,\n\t\t\t{ code, cause: compiled.error },\n\t\t)\n\t}\n\tconst tree = source === undefined ? options.template : undefined\n\tif (\n\t\ttree !== undefined &&\n\t\t(!isObject(tree) ||\n\t\t\ttypeof Reflect.get(tree, 'evaluate') !== 'function' ||\n\t\t\t!isTemplateDocument(Reflect.get(tree, 'document')))\n\t) {\n\t\tthrow new InferError(\n\t\t\t'The conversation template must be a Jinja template string or a TemplateTreeInterface.',\n\t\t\t{ code: 'ARGUMENT' },\n\t\t)\n\t}\n\tif (!isArray(snapshots)) {\n\t\tthrow new InferError(\n\t\t\t'The conversation snapshots must be an array of ConversationSnapshot values.',\n\t\t\t{ code: 'ARGUMENT' },\n\t\t)\n\t}\n\tconst checkedSnapshots = snapshots.map((snapshot, index) => {\n\t\tif (!isConversationSnapshot(snapshot) || snapshot.id.length === 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The conversation snapshot at index ${index} is not a valid ConversationSnapshot with a non-empty id.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { snapshot: index } },\n\t\t\t)\n\t\t}\n\t\treturn snapshot\n\t})\n\treturn checkedSnapshots.flatMap((snapshot) =>\n\t\tsnapshot.messages.flatMap((message, turnIndex) => {\n\t\t\tif (message.role !== 'assistant' || message.content.length === 0 || turnIndex === 0) return []\n\t\t\tconst messages = buildChatMessages(snapshot.messages.slice(0, turnIndex))\n\t\t\tconst values: TemplateFillValues = {\n\t\t\t\t...(options.context ?? {}),\n\t\t\t\tmessages,\n\t\t\t\tadd_generation_prompt: true,\n\t\t\t}\n\t\t\tconst rendered = attempt(() =>\n\t\t\t\tcompiled !== undefined\n\t\t\t\t\t? evaluateTemplate(compiled.value, values)\n\t\t\t\t\t: (tree?.evaluate(values) ?? ''),\n\t\t\t)\n\t\t\tif (!rendered.success) {\n\t\t\t\tconst code =\n\t\t\t\t\tisTemplateError(rendered.error) && rendered.error.code === 'FORMAT'\n\t\t\t\t\t\t? 'FORMAT'\n\t\t\t\t\t\t: 'ARGUMENT'\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The conversation template failed on ${quoteFaultText(snapshot.id)} turn ${turnIndex}: ${rendered.error instanceof Error ? rendered.error.message : String(rendered.error)}`,\n\t\t\t\t\t{ code, cause: rendered.error, context: { group: snapshot.id, turn: turnIndex } },\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn [\n\t\t\t\t{ prompt: rendered.value, completion: message.content, group: snapshot.id, provenance },\n\t\t\t]\n\t\t}),\n\t)\n}\n\n/**\n * Checks that a checkpoint identifier satisfies `CHECKPOINT_ID_PATTERN` and refuses malformed,\n * empty, or path-traversing identifiers.\n *\n * @remarks\n * Thrown with the `ARGUMENT` code when `id` fails `isCheckpointId`.\n *\n * @param id - The checkpoint identifier to verify\n *\n * @example\n * ```ts\n * checkCheckpointId('run-1.step_10')\n * ```\n */\nexport function checkCheckpointId(id: string): void {\n\tif (!isCheckpointId(id)) {\n\t\tthrow new InferError(\n\t\t\t`The checkpoint identifier ${quoteFaultText(String(id))} is invalid; use 1 to 128 ASCII letters, digits, hyphens, underscores, or interior periods.`,\n\t\t\t{ code: 'ARGUMENT', context: { id: String(id) } },\n\t\t)\n\t}\n}\n\n/**\n * Builds the bytes of a self-describing GGUF v3 training checkpoint file from its metadata and\n * single-precision parameter and Adam moment triples.\n *\n * @remarks\n * Encodes `general.type = \"checkpoint\"`, `orkestrel.checkpoint.version = 1`, canonicalized JSON\n * `config`, ordered `targets`, and `F32` little-endian tensors `param.<k>`, `adam.m.<k>`, and\n * `adam.v.<k>` aligned to `GGUF_ALIGNMENT`. Omits `orkestrel.checkpoint.fold` completely when\n * `checkpoint.fold` is undefined. Thrown with the `ARGUMENT` code when the checkpoint fails\n * `isCheckpoint`.\n *\n * @param checkpoint - The training checkpoint to serialize\n * @returns The GGUF v3 checkpoint file bytes\n *\n * @example\n * ```ts\n * const bytes = buildCheckpointGGUF(checkpoint)\n * readGGUFHeader(bytes).metadata.get('general.type') // { encoding: 'string', value: 'checkpoint' }\n * ```\n */\nexport function buildCheckpointGGUF(checkpoint: Checkpoint): Uint8Array<ArrayBuffer> {\n\tif (!isCheckpoint(checkpoint)) {\n\t\tthrow new InferError(\n\t\t\t'The checkpoint record is invalid: verify mode, base and dataset digests, non-negative counters, finite seed, uint32 rng, JSON config, and non-empty unique F32 target triples.',\n\t\t\t{ code: 'ARGUMENT' },\n\t\t)\n\t}\n\tconst canonicalConfig = canonicalStringify(checkpoint.config)\n\tif (canonicalConfig === undefined) {\n\t\tthrow new InferError('The checkpoint config cannot serialize to canonical JSON.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tconst integerEntries: ReadonlyArray<readonly [key: string, value: number]> = [\n\t\t[CHECKPOINT_KEYS.step, checkpoint.step],\n\t\t[CHECKPOINT_KEYS.epoch, checkpoint.epoch],\n\t\t[CHECKPOINT_KEYS.cursor, checkpoint.cursor],\n\t\t...(checkpoint.fold === undefined ? [] : ([[CHECKPOINT_KEYS.fold, checkpoint.fold]] as const)),\n\t]\n\tconst metadata = new Map<string, GGUFValue>([\n\t\t[CHECKPOINT_KEYS.type, { encoding: 'string', value: CHECKPOINT_TYPE }],\n\t\t[GGUF_KEYS.alignment, { encoding: 'uint32', value: GGUF_ALIGNMENT }],\n\t\t[CHECKPOINT_KEYS.version, { encoding: 'uint32', value: CHECKPOINT_VERSION }],\n\t\t[CHECKPOINT_KEYS.mode, { encoding: 'string', value: checkpoint.mode }],\n\t\t[CHECKPOINT_KEYS.base, { encoding: 'string', value: checkpoint.base }],\n\t\t[CHECKPOINT_KEYS.dataset, { encoding: 'string', value: checkpoint.dataset }],\n\t\t...integerEntries.map(([key, value]): readonly [string, GGUFValue] => [\n\t\t\tkey,\n\t\t\tvalue <= 0xffff_ffff\n\t\t\t\t? { encoding: 'uint32', value }\n\t\t\t\t: { encoding: 'uint64', value: BigInt(value) },\n\t\t]),\n\t\t[CHECKPOINT_KEYS.seed, { encoding: 'float64', value: checkpoint.seed }],\n\t\t[CHECKPOINT_KEYS.rng, { encoding: 'uint32', value: checkpoint.rng }],\n\t\t[CHECKPOINT_KEYS.config, { encoding: 'string', value: canonicalConfig }],\n\t\t[\n\t\t\tCHECKPOINT_KEYS.targets,\n\t\t\t{\n\t\t\t\tencoding: 'array',\n\t\t\t\telement: 'string',\n\t\t\t\tvalue: checkpoint.targets.map((target) => target.name),\n\t\t\t},\n\t\t],\n\t])\n\tconst parts: ReadonlyArray<\n\t\treadonly [name: string, dimensions: readonly number[], values: Float32Array]\n\t> = checkpoint.targets.flatMap((target) => [\n\t\t[\n\t\t\t`${CHECKPOINT_TENSOR_PREFIXES.parameters}${target.name}`,\n\t\t\t[target.columns, target.rows],\n\t\t\ttarget.parameters,\n\t\t],\n\t\t[\n\t\t\t`${CHECKPOINT_TENSOR_PREFIXES.first}${target.name}`,\n\t\t\t[target.columns, target.rows],\n\t\t\ttarget.first,\n\t\t],\n\t\t[\n\t\t\t`${CHECKPOINT_TENSOR_PREFIXES.second}${target.name}`,\n\t\t\t[target.columns, target.rows],\n\t\t\ttarget.second,\n\t\t],\n\t])\n\tconst ends = parts.map((_, index) =>\n\t\tparts\n\t\t\t.slice(0, index + 1)\n\t\t\t.reduce((total, [, , values]) => alignOffset(total + 4 * values.length, GGUF_ALIGNMENT), 0),\n\t)\n\tconst data = new Uint8Array(ends.at(-1) ?? 0)\n\tconst view = new DataView(data.buffer)\n\tfor (const [index, [, , values]] of parts.entries()) {\n\t\tconst offset = ends[index - 1] ?? 0\n\t\tfor (let element = 0; element < values.length; element += 1) {\n\t\t\tview.setFloat32(offset + 4 * element, values[element] ?? Number.NaN, true)\n\t\t}\n\t}\n\treturn buildGGUF(\n\t\tmetadata,\n\t\tparts.map(([name, dimensions], index) => ({\n\t\t\tname,\n\t\t\tdimensions,\n\t\t\tformat: 'F32',\n\t\t\toffset: ends[index - 1] ?? 0,\n\t\t})),\n\t\tdata,\n\t)\n}\n\n/**\n * Reads and validates a self-describing GGUF v3 training checkpoint from a byte source, verifying\n * optional base and dataset bindings.\n *\n * @remarks\n * Refuses malformed GGUF headers, wrong `general.type` or version, negative or fractional\n * counters, missing or mismatched `param.<k>` / `adam.m.<k>` / `adam.v.<k>` triples, non-`F32`\n * tensor dtypes, shape mismatches across a triple, and non-finite values with the `FORMAT` code.\n * Refuses mismatched expected `base` or `dataset` digests with the `BINDING` code, and an aborted\n * signal with the `ABORT` code.\n *\n * @param source - The byte source holding the GGUF v3 checkpoint\n * @param options - Optional expected bindings and abort signal\n * @returns The decoded and validated checkpoint\n *\n * @example\n * ```ts\n * const checkpoint = await readCheckpointGGUF(new MemorySource(bytes), { base: backbone.digest })\n * checkpoint.mode // 'adapter'\n * ```\n */\nexport async function readCheckpointGGUF(\n\tsource: ByteSourceInterface,\n\toptions: CheckpointReadOptions = {},\n): Promise<Checkpoint> {\n\tcheckSignal(options.signal, 'The checkpoint read')\n\tconst [bytes, , header] = await readGGUFFile(source, 'The checkpoint read', options.signal)\n\tconst { metadata, tensors } = header\n\tconst fileType = readMetadataString(metadata, CHECKPOINT_KEYS.type)\n\tif (fileType !== CHECKPOINT_TYPE) {\n\t\tthrow new InferError(\n\t\t\t`The GGUF general.type is ${quoteFaultText(String(fileType))}; expected ${quoteFaultText(CHECKPOINT_TYPE)}.`,\n\t\t\t{ code: 'FORMAT', context: { type: fileType } },\n\t\t)\n\t}\n\tconst version = readMetadataInteger(metadata, CHECKPOINT_KEYS.version)\n\tif (version !== CHECKPOINT_VERSION) {\n\t\tthrow new InferError(\n\t\t\t`The checkpoint version is ${String(version)}; expected ${CHECKPOINT_VERSION}.`,\n\t\t\t{ code: 'FORMAT', context: { version } },\n\t\t)\n\t}\n\tconst mode = readMetadataString(metadata, CHECKPOINT_KEYS.mode)\n\tif (!isCheckpointMode(mode)) {\n\t\tthrow new InferError(\n\t\t\t`The checkpoint mode is ${quoteFaultText(String(mode))}; expected \"adapter\" or \"section\".`,\n\t\t\t{ code: 'FORMAT', context: { mode } },\n\t\t)\n\t}\n\tconst base = readMetadataString(metadata, CHECKPOINT_KEYS.base)\n\tif (base === undefined || !SHA256_PATTERN.test(base)) {\n\t\tthrow new InferError(\n\t\t\t`The checkpoint base digest ${quoteFaultText(String(base))} is missing or malformed.`,\n\t\t\t{ code: 'FORMAT', context: { key: CHECKPOINT_KEYS.base } },\n\t\t)\n\t}\n\tconst dataset = readMetadataString(metadata, CHECKPOINT_KEYS.dataset)\n\tif (dataset === undefined || !SHA256_PATTERN.test(dataset)) {\n\t\tthrow new InferError(\n\t\t\t`The checkpoint dataset digest ${quoteFaultText(String(dataset))} is missing or malformed.`,\n\t\t\t{ code: 'FORMAT', context: { key: CHECKPOINT_KEYS.dataset } },\n\t\t)\n\t}\n\tconst step = readMetadataInteger(metadata, CHECKPOINT_KEYS.step)\n\tconst epoch = readMetadataInteger(metadata, CHECKPOINT_KEYS.epoch)\n\tconst cursor = readMetadataInteger(metadata, CHECKPOINT_KEYS.cursor)\n\tif (\n\t\tstep === undefined ||\n\t\tstep < 0 ||\n\t\tepoch === undefined ||\n\t\tepoch < 0 ||\n\t\tcursor === undefined ||\n\t\tcursor < 0\n\t) {\n\t\tthrow new InferError(\n\t\t\t'The checkpoint counters step, epoch, and cursor must be non-negative safe integers.',\n\t\t\t{ code: 'FORMAT', context: { step, epoch, cursor } },\n\t\t)\n\t}\n\tconst seed = readMetadataNumber(metadata, CHECKPOINT_KEYS.seed)\n\tif (seed === undefined || !isFiniteNumber(seed)) {\n\t\tthrow new InferError(`The checkpoint seed ${String(seed)} must be a finite number.`, {\n\t\t\tcode: 'FORMAT',\n\t\t\tcontext: { seed },\n\t\t})\n\t}\n\tconst rng = readMetadataInteger(metadata, CHECKPOINT_KEYS.rng)\n\tif (rng === undefined || rng < 0 || rng > 0xffff_ffff) {\n\t\tthrow new InferError(\n\t\t\t`The checkpoint rng state ${String(rng)} must be an unsigned 32-bit integer.`,\n\t\t\t{\n\t\t\t\tcode: 'FORMAT',\n\t\t\t\tcontext: { rng },\n\t\t\t},\n\t\t)\n\t}\n\tconst fold = readMetadataInteger(metadata, CHECKPOINT_KEYS.fold)\n\tif (fold !== undefined && (!isSafeInteger(fold) || fold < 0)) {\n\t\tthrow new InferError(\n\t\t\t`The checkpoint fold ${fold} must be a non-negative integer when present.`,\n\t\t\t{ code: 'FORMAT', context: { fold } },\n\t\t)\n\t}\n\tconst configText = readMetadataString(metadata, CHECKPOINT_KEYS.config)\n\tconst parsedConfig = configText === undefined ? undefined : parseJSON(configText)\n\tconst canonicalConfigText =\n\t\tparsedConfig === undefined ? undefined : canonicalStringify(parsedConfig)\n\tconst config = canonicalConfigText === undefined ? undefined : parseJSON(canonicalConfigText)\n\tif (!isBoundedJSONRecord(config)) {\n\t\tthrow new InferError('The checkpoint config must be a valid JSON object.', {\n\t\t\tcode: 'FORMAT',\n\t\t\tcontext: { key: CHECKPOINT_KEYS.config },\n\t\t})\n\t}\n\tconst targetNames = readMetadataStrings(metadata, CHECKPOINT_KEYS.targets)\n\tif (\n\t\ttargetNames === undefined ||\n\t\ttargetNames.length === 0 ||\n\t\ttargetNames.some((name) => name.length === 0 || name.includes('\\0')) ||\n\t\tnew Set(targetNames).size !== targetNames.length\n\t) {\n\t\tthrow new InferError(\n\t\t\t'The checkpoint targets list must hold one or more unique non-empty target names.',\n\t\t\t{ code: 'FORMAT', context: { key: CHECKPOINT_KEYS.targets } },\n\t\t)\n\t}\n\tconst tensorMap = new Map(tensors.map((tensor) => [tensor.name, tensor] as const))\n\tif (tensorMap.size !== tensors.length || tensors.length !== targetNames.length * 3) {\n\t\tthrow new InferError(\n\t\t\t`The checkpoint holds ${tensors.length} tensors (${tensorMap.size} unique); expected ${targetNames.length * 3} tensors for ${targetNames.length} targets.`,\n\t\t\t{ code: 'FORMAT', context: { tensors: tensors.length, targets: targetNames.length } },\n\t\t)\n\t}\n\tconst targets: readonly CheckpointTarget[] = targetNames.map((name) => {\n\t\tconst tripleNames = [\n\t\t\t`${CHECKPOINT_TENSOR_PREFIXES.parameters}${name}`,\n\t\t\t`${CHECKPOINT_TENSOR_PREFIXES.first}${name}`,\n\t\t\t`${CHECKPOINT_TENSOR_PREFIXES.second}${name}`,\n\t\t] as const\n\t\tconst tripleTensors = tripleNames.map((tensorName) => {\n\t\t\tconst tensor = tensorMap.get(tensorName)\n\t\t\tif (tensor === undefined) {\n\t\t\t\tthrow new InferError(`The checkpoint lacks tensor ${quoteFaultText(tensorName)}.`, {\n\t\t\t\t\tcode: 'FORMAT',\n\t\t\t\t\tcontext: { target: name, tensor: tensorName },\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (tensor.format !== 'F32') {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The checkpoint tensor ${quoteFaultText(tensorName)} has dtype ${tensor.format}; expected F32.`,\n\t\t\t\t\t{ code: 'FORMAT', context: { tensor: tensorName, format: tensor.format } },\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (\n\t\t\t\ttensor.dimensions.length !== 2 ||\n\t\t\t\t!isSafeInteger(tensor.dimensions[0]) ||\n\t\t\t\ttensor.dimensions[0] < 1 ||\n\t\t\t\t!isSafeInteger(tensor.dimensions[1]) ||\n\t\t\t\ttensor.dimensions[1] < 1\n\t\t\t) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The checkpoint tensor ${quoteFaultText(tensorName)} must have positive 2D dimensions.`,\n\t\t\t\t\t{ code: 'FORMAT', context: { tensor: tensorName, dimensions: tensor.dimensions } },\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn tensor\n\t\t})\n\t\tconst [paramTensor, firstTensor, secondTensor] = tripleTensors\n\t\tif (\n\t\t\tparamTensor === undefined ||\n\t\t\tfirstTensor === undefined ||\n\t\t\tsecondTensor === undefined ||\n\t\t\t!matchesElements(paramTensor.dimensions, firstTensor.dimensions) ||\n\t\t\t!matchesElements(paramTensor.dimensions, secondTensor.dimensions)\n\t\t) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The checkpoint target ${quoteFaultText(name)} has mismatched triple tensor dimensions.`,\n\t\t\t\t{ code: 'FORMAT', context: { target: name } },\n\t\t\t)\n\t\t}\n\t\tconst [columns = 0, rows = 0] = paramTensor.dimensions\n\t\tconst [parameters, first, second] = tripleNames.map((tensorName) => {\n\t\t\tconst values = readNamedTensor(bytes, header, tensorName, [columns, rows])\n\t\t\tif (!values.every(Number.isFinite)) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The checkpoint tensor ${quoteFaultText(tensorName)} contains non-finite values.`,\n\t\t\t\t\t{ code: 'FORMAT', context: { tensor: tensorName } },\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn values\n\t\t})\n\t\tif (parameters === undefined || first === undefined || second === undefined) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The checkpoint target ${quoteFaultText(name)} triple could not be read.`,\n\t\t\t\t{\n\t\t\t\t\tcode: 'FORMAT',\n\t\t\t\t\tcontext: { target: name },\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\treturn { name, rows, columns, parameters, first, second }\n\t})\n\tif (options.base !== undefined && base !== options.base) {\n\t\tthrow new InferError(\n\t\t\t`The checkpoint binds base ${quoteFaultText(base)}, not expected ${quoteFaultText(options.base)}.`,\n\t\t\t{ code: 'BINDING', context: { field: 'base', expected: options.base, actual: base } },\n\t\t)\n\t}\n\tif (options.dataset !== undefined && dataset !== options.dataset) {\n\t\tthrow new InferError(\n\t\t\t`The checkpoint binds dataset ${quoteFaultText(dataset)}, not expected ${quoteFaultText(options.dataset)}.`,\n\t\t\t{\n\t\t\t\tcode: 'BINDING',\n\t\t\t\tcontext: { field: 'dataset', expected: options.dataset, actual: dataset },\n\t\t\t},\n\t\t)\n\t}\n\treturn {\n\t\tmode,\n\t\tbase,\n\t\tdataset,\n\t\tstep,\n\t\tepoch,\n\t\tcursor,\n\t\tseed,\n\t\trng,\n\t\t...(fold === undefined ? {} : { fold }),\n\t\tconfig,\n\t\ttargets,\n\t}\n}\n\n/**\n * Advances one single-precision checkpoint target by one Adam optimizer step, returning fresh\n * `Float32Array` parameters and moments.\n *\n * @remarks\n * Uses `ADAM_FIRST`, `ADAM_SECOND`, and `ADAM_EPSILON`, rounding each updated moment and parameter\n * to IEEE 754 single precision with `Math.fround` so resumed steps from a GGUF `F32` checkpoint\n * match uninterrupted runs bit-for-bit. Thrown with the `ARGUMENT` code when target, gradient,\n * step, or rate is invalid.\n *\n * @param target - The target parameters and moments before the step\n * @param gradient - The single-precision gradient matching `target.parameters.length`\n * @param step - The 1-based optimizer step number\n * @param rate - The non-negative finite learning rate\n * @returns The updated checkpoint target\n *\n * @example\n * ```ts\n * const next = stepCheckpointAdam(target, Float32Array.of(0.5, -0.5), 1, 0.01)\n * ```\n */\nexport function stepCheckpointAdam(\n\ttarget: CheckpointTarget,\n\tgradient: Float32Array,\n\tstep: number,\n\trate: number,\n): CheckpointTarget {\n\tif (!isCheckpointTarget(target)) {\n\t\tthrow new InferError('The checkpoint target is invalid.', { code: 'ARGUMENT' })\n\t}\n\tif (\n\t\t!isFloat32Array(gradient) ||\n\t\tgradient.length !== target.parameters.length ||\n\t\t!gradient.every(Number.isFinite)\n\t) {\n\t\tthrow new InferError(\n\t\t\t`The gradient must be a finite Float32Array of length ${target.parameters.length}.`,\n\t\t\t{ code: 'ARGUMENT', context: { expected: target.parameters.length } },\n\t\t)\n\t}\n\tif (!isSafeInteger(step) || step < 1) {\n\t\tthrow new InferError(`The Adam step ${step} must be a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { step },\n\t\t})\n\t}\n\tif (!isFiniteNumber(rate) || rate < 0) {\n\t\tthrow new InferError(`The learning rate ${rate} must be a finite non-negative number.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { rate },\n\t\t})\n\t}\n\tconst length = target.parameters.length\n\tconst firstScale = 1 - Math.pow(ADAM_FIRST.decay, step)\n\tconst secondScale = 1 - Math.pow(ADAM_SECOND.decay, step)\n\tconst parameters = new Float32Array(length)\n\tconst first = new Float32Array(length)\n\tconst second = new Float32Array(length)\n\tfor (let index = 0; index < length; index += 1) {\n\t\tconst value = gradient[index] ?? 0\n\t\tconst m = Math.fround(ADAM_FIRST.decay * (target.first[index] ?? 0) + ADAM_FIRST.gain * value)\n\t\tconst v = Math.fround(\n\t\t\tADAM_SECOND.decay * (target.second[index] ?? 0) + ADAM_SECOND.gain * value * value,\n\t\t)\n\t\tfirst[index] = m\n\t\tsecond[index] = v\n\t\tparameters[index] = Math.fround(\n\t\t\t(target.parameters[index] ?? 0) -\n\t\t\t\t(rate * (m / firstScale)) / (Math.sqrt(v / secondScale) + ADAM_EPSILON),\n\t\t)\n\t}\n\treturn {\n\t\tname: target.name,\n\t\trows: target.rows,\n\t\tcolumns: target.columns,\n\t\tparameters,\n\t\tfirst,\n\t\tsecond,\n\t}\n}\n\n/**\n * Advances an explicit unsigned 32-bit Mulberry32 generator state by one draw, matching\n * `@orkestrel/contract`'s `seededRandom` sequence bit-for-bit.\n *\n * @remarks\n * Thrown with the `ARGUMENT` code when `state` is not an unsigned 32-bit integer.\n *\n * @param state - The current unsigned 32-bit generator state\n * @returns The drawn value in `[0, 1)` and the next unsigned 32-bit state\n *\n * @example\n * ```ts\n * const [value, next] = stepRandom(42)\n * ```\n */\nexport function stepRandom(state: number): readonly [value: number, next: number] {\n\tif (!isSafeInteger(state) || state < 0 || state > 0xffff_ffff) {\n\t\tthrow new InferError(`The generator state ${state} must be an unsigned 32-bit integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { state },\n\t\t})\n\t}\n\tconst next = (state + 0x6d2b79f5) >>> 0\n\tconst mixed = Math.imul(next ^ (next >>> 15), next | 1)\n\tconst final = mixed ^ (mixed + Math.imul(mixed ^ (mixed >>> 7), mixed | 61))\n\treturn [((final ^ (final >>> 14)) >>> 0) / 4294967296, next]\n}\n\n/**\n * Validates an untrusted `adapter_config.json` value and returns an owned `PEFTConfig` record.\n *\n * @remarks\n * Refuses unsupported PEFT options (`peft_type !== 'LORA'`, `use_rslora: true`, `use_dora: true`,\n * and `bias !== 'none'`) with the `UNSUPPORTED` code, and malformed shapes or numeric values with\n * the `FORMAT` code.\n *\n * @param value - The raw configuration record to validate\n * @returns The validated `PEFTConfig`\n *\n * @example\n * ```ts\n * checkPEFTConfig({ peft_type: 'LORA', r: 4, lora_alpha: 8, target_modules: ['q_proj'], bias: 'none' }).r // 4\n * ```\n */\nexport function checkPEFTConfig(value: unknown): PEFTConfig {\n\tif (!isRecord(value)) {\n\t\tthrow new InferError('The PEFT adapter configuration must be a plain object.', {\n\t\t\tcode: 'FORMAT',\n\t\t})\n\t}\n\tconst peftType = value['peft_type']\n\tif (!isString(peftType)) {\n\t\tthrow new InferError('The PEFT adapter configuration requires a string peft_type.', {\n\t\t\tcode: 'FORMAT',\n\t\t\tcontext: { field: 'peft_type' },\n\t\t})\n\t}\n\tif (peftType !== 'LORA') {\n\t\tthrow new InferError(\n\t\t\t`The PEFT adapter declares peft_type ${quoteFaultText(peftType)}; only \"LORA\" is supported.`,\n\t\t\t{ code: 'UNSUPPORTED', context: { field: 'peft_type', value: peftType } },\n\t\t)\n\t}\n\tif (Object.hasOwn(value, 'use_rslora')) {\n\t\tconst rslora = value['use_rslora']\n\t\tif (typeof rslora !== 'boolean') {\n\t\t\tthrow new InferError('The PEFT adapter field use_rslora must be a boolean when present.', {\n\t\t\t\tcode: 'FORMAT',\n\t\t\t\tcontext: { field: 'use_rslora' },\n\t\t\t})\n\t\t}\n\t\tif (rslora) {\n\t\t\tthrow new InferError('Rank-stabilized LoRA (use_rslora: true) is unsupported.', {\n\t\t\t\tcode: 'UNSUPPORTED',\n\t\t\t\tcontext: { field: 'use_rslora', value: true },\n\t\t\t})\n\t\t}\n\t}\n\tif (Object.hasOwn(value, 'use_dora')) {\n\t\tconst dora = value['use_dora']\n\t\tif (typeof dora !== 'boolean') {\n\t\t\tthrow new InferError('The PEFT adapter field use_dora must be a boolean when present.', {\n\t\t\t\tcode: 'FORMAT',\n\t\t\t\tcontext: { field: 'use_dora' },\n\t\t\t})\n\t\t}\n\t\tif (dora) {\n\t\t\tthrow new InferError('Weight-decomposed LoRA (use_dora: true) is unsupported.', {\n\t\t\t\tcode: 'UNSUPPORTED',\n\t\t\t\tcontext: { field: 'use_dora', value: true },\n\t\t\t})\n\t\t}\n\t}\n\tconst bias = value['bias']\n\tif (!isString(bias)) {\n\t\tthrow new InferError('The PEFT adapter configuration requires a string bias.', {\n\t\t\tcode: 'FORMAT',\n\t\t\tcontext: { field: 'bias' },\n\t\t})\n\t}\n\tif (bias !== 'none') {\n\t\tthrow new InferError(\n\t\t\t`The PEFT adapter declares bias ${quoteFaultText(bias)}; only \"none\" is supported.`,\n\t\t\t{ code: 'UNSUPPORTED', context: { field: 'bias', value: bias } },\n\t\t)\n\t}\n\tconst rank = value['r']\n\tif (!isSafeInteger(rank) || rank < 1) {\n\t\tthrow new InferError('The PEFT adapter rank r must be a positive integer.', {\n\t\t\tcode: 'FORMAT',\n\t\t\tcontext: { field: 'r' },\n\t\t})\n\t}\n\tconst alpha = value['lora_alpha']\n\tif (!isFiniteNumber(alpha) || alpha <= 0) {\n\t\tthrow new InferError('The PEFT adapter lora_alpha must be a positive finite number.', {\n\t\t\tcode: 'FORMAT',\n\t\t\tcontext: { field: 'lora_alpha' },\n\t\t})\n\t}\n\tconst modules = value['target_modules']\n\tif (\n\t\t!isArray(modules) ||\n\t\tmodules.length === 0 ||\n\t\t!modules.every((entry): entry is string => isString(entry) && entry.length > 0)\n\t) {\n\t\tthrow new InferError('The PEFT adapter target_modules must be a non-empty list of strings.', {\n\t\t\tcode: 'FORMAT',\n\t\t\tcontext: { field: 'target_modules' },\n\t\t})\n\t}\n\tconst taskType = Object.hasOwn(value, 'task_type') ? value['task_type'] : undefined\n\tif (taskType !== undefined && !isString(taskType)) {\n\t\tthrow new InferError('The PEFT adapter field task_type must be a string when present.', {\n\t\t\tcode: 'FORMAT',\n\t\t\tcontext: { field: 'task_type' },\n\t\t})\n\t}\n\tconst baseModel = Object.hasOwn(value, 'base_model_name_or_path')\n\t\t? value['base_model_name_or_path']\n\t\t: undefined\n\tif (baseModel !== undefined && !isString(baseModel)) {\n\t\tthrow new InferError(\n\t\t\t'The PEFT adapter field base_model_name_or_path must be a string when present.',\n\t\t\t{ code: 'FORMAT', context: { field: 'base_model_name_or_path' } },\n\t\t)\n\t}\n\treturn {\n\t\tpeft_type: 'LORA',\n\t\tr: rank,\n\t\tlora_alpha: alpha,\n\t\ttarget_modules: [...modules],\n\t\tbias: 'none',\n\t\t...(Object.hasOwn(value, 'use_rslora') ? { use_rslora: false } : {}),\n\t\t...(Object.hasOwn(value, 'use_dora') ? { use_dora: false } : {}),\n\t\t...(taskType === undefined ? {} : { task_type: taskType }),\n\t\t...(baseModel === undefined ? {} : { base_model_name_or_path: baseModel }),\n\t}\n}\n\n/**\n * Encodes single-precision float values to little-endian `F32`, IEEE 754 `F16`, or round-to-nearest-even\n * `BF16` bytes.\n *\n * @remarks\n * Uses `@orkestrel/infer`'s `narrowHalf` for `F16` conversion and IEEE 754 round-to-nearest-ties-to-even\n * for `BF16` conversion.\n *\n * @param values - The single-precision values to encode\n * @param format - The target safetensors dtype (`'F32'`, `'F16'`, or `'BF16'`)\n * @returns The encoded little-endian bytes\n *\n * @example\n * ```ts\n * encodeSafetensorsValues(Float32Array.of(1.5), 'BF16').length // 2\n * ```\n */\nexport function encodeSafetensorsValues(\n\tvalues: Float32Array,\n\tformat: SafetensorsFormat,\n): Uint8Array<ArrayBuffer> {\n\tif (format === 'F32') {\n\t\tconst out = new Uint8Array(values.length * 4)\n\t\tconst view = new DataView(out.buffer)\n\t\tfor (let index = 0; index < values.length; index += 1) {\n\t\t\tview.setFloat32(4 * index, values[index] ?? 0, true)\n\t\t}\n\t\treturn out\n\t}\n\tconst words = new Uint32Array(values.buffer, values.byteOffset, values.length)\n\tconst out = new Uint8Array(values.length * 2)\n\tconst view = new DataView(out.buffer)\n\tif (format === 'F16') {\n\t\tfor (let index = 0; index < values.length; index += 1) {\n\t\t\tview.setUint16(2 * index, narrowHalf(words[index] ?? 0), true)\n\t\t}\n\t\treturn out\n\t}\n\tfor (let index = 0; index < values.length; index += 1) {\n\t\tconst bits = words[index] ?? 0\n\t\tconst isNaN = (bits & 0x7f80_0000) === 0x7f80_0000 && (bits & 0x007f_ffff) !== 0\n\t\tconst encoded = isNaN\n\t\t\t? ((bits >>> 16) | 0x0040) & 0xffff\n\t\t\t: ((bits + (0x7fff + ((bits >>> 16) & 1))) >>> 16) & 0xffff\n\t\tview.setUint16(2 * index, encoded, true)\n\t}\n\treturn out\n}\n\n/**\n * Encodes single-precision weights into GGUF `Q8_0` blocks (34 bytes per 32-element block: a\n * little-endian IEEE 754 binary16 scale followed by 32 signed 8-bit quants).\n *\n * @remarks\n * Uses `@orkestrel/infer`'s `narrowHalf`, `widenHalf`, and `roundAway` so blocks match `GGUF_BLOCKS.Q8_0`\n * and decode identically through `widenTensor(bytes, 'Q8_0')` and llama.cpp's `dequantize_row_q8_0`.\n * Throws `InferError` with code `ARGUMENT` when `values.length` is not divisible by 32 or any value\n * is non-finite.\n *\n * @param values - The finite single-precision weights (length divisible by 32)\n * @returns The encoded `Q8_0` bytes\n *\n * @example\n * ```ts\n * encodeQ80Values(new Float32Array(32).fill(1)).length // 34\n * ```\n */\nexport function encodeQ80Values(values: Float32Array): Uint8Array<ArrayBuffer> {\n\tconst { elements, bytes: blockBytes } = GGUF_BLOCKS.Q8_0\n\tif (values.length % elements !== 0) {\n\t\tthrow new InferError(\n\t\t\t`A Q8_0 tensor holds a multiple of ${elements} values; it received ${values.length}.`,\n\t\t\t{ code: 'ARGUMENT', context: { format: 'Q8_0', values: values.length, block: elements } },\n\t\t)\n\t}\n\tconst blocks = values.length / elements\n\tconst out = new Uint8Array(blocks * blockBytes)\n\tconst view = new DataView(out.buffer)\n\tconst scratch = new Float32Array(1)\n\tconst scratchBits = new Uint32Array(scratch.buffer)\n\tfor (let block = 0; block < blocks; block += 1) {\n\t\tconst valueOffset = block * elements\n\t\tlet amax = 0\n\t\tfor (let index = 0; index < elements; index += 1) {\n\t\t\tconst value = values[valueOffset + index] ?? 0\n\t\t\tif (!Number.isFinite(value)) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The Q8_0 value at index ${valueOffset + index} must be finite; it received ${String(value)}.`,\n\t\t\t\t\t{ code: 'ARGUMENT', context: { format: 'Q8_0', index: valueOffset + index } },\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst magnitude = Math.abs(value)\n\t\t\tif (magnitude > amax) amax = magnitude\n\t\t}\n\t\tconst rawScale = Math.fround(amax / 127)\n\t\tscratch[0] = rawScale > 65_504 ? 65_504 : rawScale\n\t\tconst dBits = narrowHalf(scratchBits[0] ?? 0)\n\t\tconst halfScale = widenHalf(dBits)\n\t\tconst inverse = halfScale === 0 ? 0 : Math.fround(1 / halfScale)\n\t\tconst outOffset = block * blockBytes\n\t\tview.setUint16(outOffset, dBits, true)\n\t\tfor (let index = 0; index < elements; index += 1) {\n\t\t\tconst value = values[valueOffset + index] ?? 0\n\t\t\tconst quantized =\n\t\t\t\tinverse === 0 ? 0 : Math.max(-128, Math.min(127, roundAway(Math.fround(value * inverse))))\n\t\t\tview.setInt8(outOffset + 2 + index, quantized)\n\t\t}\n\t}\n\treturn out\n}\n\n/**\n * Encodes single-precision weights into GGUF `Q4_K` superblocks (144 bytes per 256-element block:\n * binary16 superblock scale `d`, binary16 minimum scale `dmin`, 12 packed bytes of 6-bit sub-block\n * scales and minimums, and 128 bytes of 4-bit nibbles).\n *\n * @remarks\n * Uses 1-step least-squares scale and minimum refinement per 32-element sub-block and packs scales\n * and nibbles to match `@orkestrel/infer`'s `decodeQ4K` and llama.cpp's `dequantize_row_q4_K`.\n * Throws `InferError` with code `ARGUMENT` when `values.length` is not divisible by 256 or any value\n * is non-finite.\n *\n * @param values - The finite single-precision weights (length divisible by 256)\n * @returns The encoded `Q4_K` bytes\n *\n * @example\n * ```ts\n * encodeQ4KValues(new Float32Array(256).fill(1)).length // 144\n * ```\n */\nexport function encodeQ4KValues(values: Float32Array): Uint8Array<ArrayBuffer> {\n\tconst { elements, bytes: blockBytes } = GGUF_BLOCKS.Q4_K\n\tif (values.length % elements !== 0) {\n\t\tthrow new InferError(\n\t\t\t`A Q4_K tensor holds a multiple of ${elements} values; it received ${values.length}.`,\n\t\t\t{ code: 'ARGUMENT', context: { format: 'Q4_K', values: values.length, block: elements } },\n\t\t)\n\t}\n\tconst blocks = values.length / elements\n\tconst out = new Uint8Array(blocks * blockBytes)\n\tconst view = new DataView(out.buffer)\n\tconst rawScales = new Float64Array(8)\n\tconst rawMins = new Float64Array(8)\n\tconst quantizedScales = new Uint8Array(8)\n\tconst quantizedMins = new Uint8Array(8)\n\tconst quants = new Uint8Array(elements)\n\tconst scratch = new Float32Array(1)\n\tconst scratchBits = new Uint32Array(scratch.buffer)\n\tfor (let block = 0; block < blocks; block += 1) {\n\t\tconst valueOffset = block * elements\n\t\tlet maxScale = 0\n\t\tlet maxMin = 0\n\t\tfor (let sub = 0; sub < 8; sub += 1) {\n\t\t\tconst subOffset = valueOffset + sub * 32\n\t\t\tlet actualMin = Number.POSITIVE_INFINITY\n\t\t\tlet actualMax = Number.NEGATIVE_INFINITY\n\t\t\tfor (let lane = 0; lane < 32; lane += 1) {\n\t\t\t\tconst value = values[subOffset + lane] ?? 0\n\t\t\t\tif (!Number.isFinite(value)) {\n\t\t\t\t\tthrow new InferError(\n\t\t\t\t\t\t`The Q4_K value at index ${subOffset + lane} must be finite; it received ${String(value)}.`,\n\t\t\t\t\t\t{ code: 'ARGUMENT', context: { format: 'Q4_K', index: subOffset + lane } },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tif (value < actualMin) actualMin = value\n\t\t\t\tif (value > actualMax) actualMax = value\n\t\t\t}\n\t\t\tconst low = actualMin < 0 ? actualMin : 0\n\t\t\tconst span = actualMax - low\n\t\t\tif (span <= 0) {\n\t\t\t\trawScales[sub] = 0\n\t\t\t\trawMins[sub] = -low\n\t\t\t} else {\n\t\t\t\tconst baseScale = span / 15\n\t\t\t\tconst baseMin = -low\n\t\t\t\tlet sumX = 0\n\t\t\t\tlet sumQ = 0\n\t\t\t\tlet sumQ2 = 0\n\t\t\t\tlet sumXQ = 0\n\t\t\t\tfor (let lane = 0; lane < 32; lane += 1) {\n\t\t\t\t\tconst value = values[subOffset + lane] ?? 0\n\t\t\t\t\tconst nibble = Math.max(0, Math.min(15, roundAway((value + baseMin) / baseScale)))\n\t\t\t\t\tsumX += value\n\t\t\t\t\tsumQ += nibble\n\t\t\t\t\tsumQ2 += nibble * nibble\n\t\t\t\t\tsumXQ += value * nibble\n\t\t\t\t}\n\t\t\t\tconst denom = 32 * sumQ2 - sumQ * sumQ\n\t\t\t\tif (denom > 0) {\n\t\t\t\t\tconst candidateScale = (32 * sumXQ - sumX * sumQ) / denom\n\t\t\t\t\tconst candidateMin = (candidateScale * sumQ - sumX) / 32\n\t\t\t\t\tif (candidateScale > 0 && candidateMin >= 0) {\n\t\t\t\t\t\trawScales[sub] = candidateScale\n\t\t\t\t\t\trawMins[sub] = candidateMin\n\t\t\t\t\t} else if (candidateMin < 0 && sumQ2 > 0 && sumXQ > 0) {\n\t\t\t\t\t\trawScales[sub] = sumXQ / sumQ2\n\t\t\t\t\t\trawMins[sub] = 0\n\t\t\t\t\t} else {\n\t\t\t\t\t\trawScales[sub] = baseScale\n\t\t\t\t\t\trawMins[sub] = baseMin\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\trawScales[sub] = baseScale\n\t\t\t\t\trawMins[sub] = baseMin\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst subScale = rawScales[sub] ?? 0\n\t\t\tconst subMin = rawMins[sub] ?? 0\n\t\t\tif (subScale > maxScale) maxScale = subScale\n\t\t\tif (subMin > maxMin) maxMin = subMin\n\t\t}\n\t\tconst dRaw = Math.fround(maxScale / 63)\n\t\tscratch[0] = dRaw > 65_504 ? 65_504 : dRaw\n\t\tconst dBits = narrowHalf(scratchBits[0] ?? 0)\n\t\tconst d = widenHalf(dBits)\n\t\tconst dminRaw = Math.fround(maxMin / 63)\n\t\tscratch[0] = dminRaw > 65_504 ? 65_504 : dminRaw\n\t\tconst dminBits = narrowHalf(scratchBits[0] ?? 0)\n\t\tconst dmin = widenHalf(dminBits)\n\t\tfor (let sub = 0; sub < 8; sub += 1) {\n\t\t\tconst sc = d > 0 ? Math.max(0, Math.min(63, roundAway((rawScales[sub] ?? 0) / d))) : 0\n\t\t\tconst mn = dmin > 0 ? Math.max(0, Math.min(63, roundAway((rawMins[sub] ?? 0) / dmin))) : 0\n\t\t\tquantizedScales[sub] = sc\n\t\t\tquantizedMins[sub] = mn\n\t\t\tconst step = Math.fround(d * sc)\n\t\t\tconst shift = Math.fround(dmin * mn)\n\t\t\tconst subOffset = valueOffset + sub * 32\n\t\t\tfor (let lane = 0; lane < 32; lane += 1) {\n\t\t\t\tconst value = values[subOffset + lane] ?? 0\n\t\t\t\tquants[sub * 32 + lane] =\n\t\t\t\t\tstep > 0 ? Math.max(0, Math.min(15, roundAway((value + shift) / step))) : 0\n\t\t\t}\n\t\t}\n\t\tconst outOffset = block * blockBytes\n\t\tview.setUint16(outOffset, dBits, true)\n\t\tview.setUint16(outOffset + 2, dminBits, true)\n\t\tfor (let group = 0; group < 4; group += 1) {\n\t\t\tconst scLo = quantizedScales[group] ?? 0\n\t\t\tconst scHi = quantizedScales[group + 4] ?? 0\n\t\t\tconst minLo = quantizedMins[group] ?? 0\n\t\t\tconst minHi = quantizedMins[group + 4] ?? 0\n\t\t\tout[outOffset + 4 + group] = (scLo & 63) | ((scHi >>> 4) << 6)\n\t\t\tout[outOffset + 8 + group] = (minLo & 63) | ((minHi >>> 4) << 6)\n\t\t\tout[outOffset + 12 + group] = (scHi & 0xf) | ((minHi & 0xf) << 4)\n\t\t}\n\t\tfor (let run = 0; run < 4; run += 1) {\n\t\t\tfor (let lane = 0; lane < 32; lane += 1) {\n\t\t\t\tconst low = quants[run * 64 + lane] ?? 0\n\t\t\t\tconst high = quants[run * 64 + 32 + lane] ?? 0\n\t\t\t\tout[outOffset + 16 + run * 32 + lane] = (low & 0xf) | ((high & 0xf) << 4)\n\t\t\t}\n\t\t}\n\t}\n\treturn out\n}\n\n/**\n * Encodes a single-precision tensor strip into an admitted `mergeGGUF` output format (`'F32'`,\n * `'BF16'`, `'Q8_0'`, or `'Q4_K'`).\n *\n * @param values - The single-precision values to encode\n * @param format - The target merged GGUF format\n * @returns The encoded little-endian tensor bytes\n *\n * @example\n * ```ts\n * encodeGGUFValues(new Float32Array(32).fill(1), 'Q8_0').length // 34\n * ```\n */\nexport function encodeGGUFValues(\n\tvalues: Float32Array,\n\tformat: MergeGGUFFormat,\n): Uint8Array<ArrayBuffer> {\n\tif (format === 'Q8_0') return encodeQ80Values(values)\n\tif (format === 'Q4_K') return encodeQ4KValues(values)\n\treturn encodeSafetensorsValues(values, format)\n}\n\n/**\n * Permutes `heads` head blocks of `block` floats across `outer` outer slices between Hugging Face\n * grouped order (`[keys, heads / keys]`) and GGUF tiled order (`[heads / keys, keys]`).\n *\n * @remarks\n * If `tiled` is `true`, maps Hugging Face grouped order to GGUF tiled order; if `false`, maps GGUF\n * tiled order back to Hugging Face grouped order. When `heads === keys`, returns a fresh copy with\n * identity order. Thrown with the `ARGUMENT` code when dimensions are invalid or inconsistent.\n *\n * @param values - The flat single-precision tensor slice of length `outer * heads * block`\n * @param outer - The number of outer rows preceding the head axis\n * @param heads - The number of value heads (`delta.values`)\n * @param keys - The number of key heads dividing `heads` (`delta.keys`)\n * @param block - The number of contiguous floats inside each head block\n * @param tiled - If `true`, converts grouped to tiled order; if `false`, converts tiled to grouped order\n * @returns The permuted single-precision array\n *\n * @example\n * ```ts\n * Array.from(permuteHeadBlocks(Float32Array.of(0, 1, 2, 3), 1, 4, 2, 1, true)) // [0, 2, 1, 3]\n * ```\n */\nexport function permuteHeadBlocks(\n\tvalues: Float32Array,\n\touter: number,\n\theads: number,\n\tkeys: number,\n\tblock: number,\n\ttiled: boolean,\n): Float32Array<ArrayBuffer> {\n\tif (\n\t\t!isSafeInteger(outer) ||\n\t\touter < 1 ||\n\t\t!isSafeInteger(heads) ||\n\t\theads < 1 ||\n\t\t!isSafeInteger(keys) ||\n\t\tkeys < 1 ||\n\t\t!isSafeInteger(block) ||\n\t\tblock < 1 ||\n\t\theads % keys !== 0 ||\n\t\tvalues.length !== outer * heads * block\n\t) {\n\t\tthrow new InferError(\n\t\t\t'The head permutation extents are invalid for the supplied tensor slice.',\n\t\t\t{\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\tcontext: { outer, heads, keys, block, length: values.length },\n\t\t\t},\n\t\t)\n\t}\n\tif (heads === keys) return Float32Array.from(values)\n\tconst ratio = heads / keys\n\tconst out = new Float32Array(values.length)\n\tconst sliceStride = heads * block\n\tfor (let row = 0; row < outer; row += 1) {\n\t\tconst rowOffset = row * sliceStride\n\t\tfor (let dstHead = 0; dstHead < heads; dstHead += 1) {\n\t\t\tconst srcHead = tiled\n\t\t\t\t? (dstHead % keys) * ratio + Math.floor(dstHead / keys)\n\t\t\t\t: (dstHead % ratio) * keys + Math.floor(dstHead / ratio)\n\t\t\tconst srcStart = rowOffset + srcHead * block\n\t\t\tconst dstStart = rowOffset + dstHead * block\n\t\t\tfor (let offset = 0; offset < block; offset += 1) {\n\t\t\t\tout[dstStart + offset] = values[srcStart + offset] ?? 0\n\t\t\t}\n\t\t}\n\t}\n\treturn out\n}\n\n/**\n * Permutes one Qwen3.5 Gated DeltaNet `AdapterPair` between Hugging Face grouped value-head order\n * and GGUF tiled value-head order when `architecture.delta.values !== architecture.delta.keys`.\n *\n * @remarks\n * Permutes `up` output rows on the `attn_qkv` value slice, `attn_gate`, `ssm_alpha`, and\n * `ssm_beta`, and permutes `down` input columns on `ssm_out`. Returns `pair` unchanged when\n * `architecture` omits `delta`, when `delta.values === delta.keys`, or when `pair.target` is an\n * attention or feed-forward target. Thrown with the `BINDING` code when a DeltaNet target's extents\n * disagree with `architecture.delta`.\n *\n * @param pair - The LoRA adapter pair\n * @param architecture - Optional base architecture carrying `delta` head counts\n * @param tiled - If `true`, converts Hugging Face grouped order to GGUF tiled order; if `false`, the inverse\n * @returns The permuted pair, or `pair` unchanged when identity applies\n *\n * @example\n * ```ts\n * permuteDeltaPair(pair, undefined, true) === pair // true\n * ```\n */\nexport function permuteDeltaPair(\n\tpair: AdapterPair,\n\tarchitecture: Architecture | undefined,\n\ttiled: boolean,\n): AdapterPair {\n\tconst delta = architecture?.delta\n\tif (delta === undefined || delta.values === delta.keys) return pair\n\tconst { keys, values, head } = delta\n\tif (\n\t\t!isSafeInteger(keys) ||\n\t\tkeys < 1 ||\n\t\t!isSafeInteger(values) ||\n\t\tvalues < 1 ||\n\t\tvalues % keys !== 0 ||\n\t\t!isSafeInteger(head) ||\n\t\thead < 1\n\t) {\n\t\tthrow new InferError('The delta architecture head counts are invalid for permutation.', {\n\t\t\tcode: 'FORMAT',\n\t\t\tcontext: { keys, values, head },\n\t\t})\n\t}\n\tif (pair.target === 'attn_qkv') {\n\t\tconst prefixRows = 2 * keys * head\n\t\tconst expectedRows = prefixRows + values * head\n\t\tif (pair.rows !== expectedRows) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The attn_qkv pair ${quoteFaultText(pair.name)} has ${pair.rows} rows; expected ${expectedRows}.`,\n\t\t\t\t{ code: 'BINDING', context: { name: pair.name, rows: pair.rows, expected: expectedRows } },\n\t\t\t)\n\t\t}\n\t\tconst prefixFloats = prefixRows * pair.rank\n\t\tconst valueSlice = permuteHeadBlocks(\n\t\t\tpair.up.subarray(prefixFloats),\n\t\t\t1,\n\t\t\tvalues,\n\t\t\tkeys,\n\t\t\thead * pair.rank,\n\t\t\ttiled,\n\t\t)\n\t\tconst up = new Float32Array(pair.up.length)\n\t\tup.set(pair.up.subarray(0, prefixFloats), 0)\n\t\tup.set(valueSlice, prefixFloats)\n\t\treturn { ...pair, up }\n\t}\n\tif (pair.target === 'attn_gate') {\n\t\tconst expectedRows = values * head\n\t\tif (pair.rows !== expectedRows) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The attn_gate pair ${quoteFaultText(pair.name)} has ${pair.rows} rows; expected ${expectedRows}.`,\n\t\t\t\t{ code: 'BINDING', context: { name: pair.name, rows: pair.rows, expected: expectedRows } },\n\t\t\t)\n\t\t}\n\t\treturn {\n\t\t\t...pair,\n\t\t\tup: permuteHeadBlocks(pair.up, 1, values, keys, head * pair.rank, tiled),\n\t\t}\n\t}\n\tif (pair.target === 'ssm_alpha' || pair.target === 'ssm_beta') {\n\t\tif (pair.rows !== values) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The ${pair.target} pair ${quoteFaultText(pair.name)} has ${pair.rows} rows; expected ${values}.`,\n\t\t\t\t{ code: 'BINDING', context: { name: pair.name, rows: pair.rows, expected: values } },\n\t\t\t)\n\t\t}\n\t\treturn {\n\t\t\t...pair,\n\t\t\tup: permuteHeadBlocks(pair.up, 1, values, keys, pair.rank, tiled),\n\t\t}\n\t}\n\tif (pair.target === 'ssm_out') {\n\t\tconst expectedColumns = values * head\n\t\tif (pair.columns !== expectedColumns) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The ssm_out pair ${quoteFaultText(pair.name)} has ${pair.columns} columns; expected ${expectedColumns}.`,\n\t\t\t\t{\n\t\t\t\t\tcode: 'BINDING',\n\t\t\t\t\tcontext: { name: pair.name, columns: pair.columns, expected: expectedColumns },\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\treturn {\n\t\t\t...pair,\n\t\t\tdown: permuteHeadBlocks(pair.down, pair.rank, values, keys, head, tiled),\n\t\t}\n\t}\n\treturn pair\n}\n\n/**\n * Reorders rows of a GGUF adjacent-pair rotary projection back into Hugging Face split-half\n * order, inverting `@orkestrel/infer`'s `interleaveRotary`.\n *\n * @remarks\n * Maps GGUF row `2j` and `2j + 1` inside each head of size `head` back to split-half rows `j` and\n * `j + head / 2`. Thrown with the `ARGUMENT` code when `heads`, `row`, or `bytes.length` do not\n * split cleanly into `heads` heads of an even row count.\n *\n * @param bytes - The row-major GGUF projection bytes\n * @param heads - The number of heads the rows split into\n * @param row - The byte length of one row\n * @returns A fresh array of the deinterleaved rows\n *\n * @example\n * ```ts\n * Array.from(deinterleaveRotary(Uint8Array.of(0, 2, 1, 3), 1, 1)) // [0, 1, 2, 3]\n * ```\n */\nexport function deinterleaveRotary(\n\tbytes: Uint8Array,\n\theads: number,\n\trow: number,\n): Uint8Array<ArrayBuffer> {\n\tif (!isSafeInteger(heads) || heads < 1 || !isSafeInteger(row) || row < 1) {\n\t\tthrow new InferError(\n\t\t\t`A rotary projection requires positive integer heads (${heads}) and row byte width (${row}).`,\n\t\t\t{ code: 'ARGUMENT', context: { bytes: bytes.length, heads, row } },\n\t\t)\n\t}\n\tconst rows = bytes.length / row\n\tconst head = rows / heads\n\tif (!Number.isInteger(rows) || !Number.isInteger(head) || head < 2 || head % 2 !== 0) {\n\t\tthrow new InferError(\n\t\t\t`A rotary projection of ${bytes.length} bytes in rows of ${row} does not split into ${heads} heads of an even size.`,\n\t\t\t{ code: 'ARGUMENT', context: { bytes: bytes.length, heads, row } },\n\t\t)\n\t}\n\tconst half = head / 2\n\tconst reordered = new Uint8Array(bytes.length)\n\tfor (let index = 0; index < rows; index += 1) {\n\t\tconst within = index % head\n\t\tconst destination = index - within + (within % 2) * half + Math.floor(within / 2)\n\t\treordered.set(bytes.subarray(index * row, (index + 1) * row), destination * row)\n\t}\n\treturn reordered\n}\n\n/**\n * Permutes `up` output rows of one rotary-interleaved `attn_q` or `attn_k` `AdapterPair` between\n * Hugging Face split-half order and GGUF adjacent-pair order.\n *\n * @remarks\n * Uses `@orkestrel/infer`'s `interleaveRotary` when `interleaved` is `true` (PEFT to GGUF) and\n * `deinterleaveRotary` when `interleaved` is `false` (GGUF to PEFT or safetensors merge), with\n * `architecture.queries` heads on `attn_q` and `architecture.groups` heads on `attn_k`. Returns\n * `pair` unchanged when `architecture` is absent, when the family is non-interleaved (`qwen35`),\n * or when `pair.target` is neither `attn_q` nor `attn_k`. Thrown with the `BINDING` code when\n * `pair.rows` disagrees with `heads * architecture.head`.\n *\n * @param pair - The LoRA adapter pair\n * @param architecture - Optional base architecture carrying rotary head counts\n * @param interleaved - If `true`, converts Hugging Face split-half to GGUF interleaved order; if `false`, the inverse\n * @returns The permuted pair, or `pair` unchanged when no rotary permutation applies\n *\n * @example\n * ```ts\n * permuteRotaryPair(pair, undefined, true) === pair // true\n * ```\n */\nexport function permuteRotaryPair(\n\tpair: AdapterPair,\n\tarchitecture: Architecture | undefined,\n\tinterleaved: boolean,\n): AdapterPair {\n\tif (architecture === undefined || !ARCHITECTURE_FAMILIES[architecture.family].interleaved) {\n\t\treturn pair\n\t}\n\tif (pair.target !== 'attn_q' && pair.target !== 'attn_k') return pair\n\tconst heads = pair.target === 'attn_q' ? architecture.queries : architecture.groups\n\tconst expectedRows = heads * architecture.head\n\tif (pair.rows !== expectedRows) {\n\t\tthrow new InferError(\n\t\t\t`The ${pair.target} pair ${quoteFaultText(pair.name)} has ${pair.rows} rows; expected ${expectedRows}.`,\n\t\t\t{ code: 'BINDING', context: { name: pair.name, rows: pair.rows, expected: expectedRows } },\n\t\t)\n\t}\n\tconst upBytes = new Uint8Array(pair.up.buffer, pair.up.byteOffset, pair.up.byteLength)\n\tconst rowBytes = pair.rank * 4\n\tconst reordered = interleaved\n\t\t? interleaveRotary(upBytes, heads, rowBytes)\n\t\t: deinterleaveRotary(upBytes, heads, rowBytes)\n\treturn { ...pair, up: new Float32Array(reordered.buffer) }\n}\n\n/**\n * Refuses omitting `architecture` when an adapter targets layout-sensitive projections requiring\n * head counts: `llama` rotary projections (`attn_q`, `attn_k`) or `qwen35` DeltaNet projections\n * (`attn_qkv`, `attn_gate`, `ssm_alpha`, `ssm_beta`, `ssm_out`).\n *\n * @remarks\n * Prevents silent row-order corruption when converting between GGUF and Hugging Face PEFT or\n * merging into Hugging Face safetensors. Thrown with the `ARGUMENT` code when `architecture` is\n * absent and any target in `targets` requires head-layout metadata.\n *\n * @param family - The decoder architecture family\n * @param targets - The LoRA targets present in the adapter\n * @param architecture - Optional base architecture supplied by the caller\n *\n * @example\n * ```ts\n * checkAdapterArchitecture('llama', ['ffn_down'], undefined)\n * ```\n */\nexport function checkAdapterArchitecture(\n\tfamily: ArchitectureFamily,\n\ttargets: readonly AdapterTarget[],\n\tarchitecture: Architecture | undefined,\n): void {\n\tif (architecture !== undefined) return\n\tconst requiredTarget =\n\t\tfamily === 'llama'\n\t\t\t? targets.find((target) => target === 'attn_q' || target === 'attn_k')\n\t\t\t: targets.find(\n\t\t\t\t\t(target) =>\n\t\t\t\t\t\ttarget === 'attn_qkv' ||\n\t\t\t\t\t\ttarget === 'attn_gate' ||\n\t\t\t\t\t\ttarget === 'ssm_alpha' ||\n\t\t\t\t\t\ttarget === 'ssm_beta' ||\n\t\t\t\t\t\ttarget === 'ssm_out',\n\t\t\t\t)\n\tif (requiredTarget !== undefined) {\n\t\tthrow new InferError(\n\t\t\t`Converting or merging ${quoteFaultText(family)} target ${quoteFaultText(requiredTarget)} requires the base architecture option to preserve head layout.`,\n\t\t\t{ code: 'ARGUMENT', context: { family, target: requiredTarget } },\n\t\t)\n\t}\n}\n\n/**\n * Adds a scaled LoRA delta `factor * (up[rowStart..rowStart+rowCount) @ down)` into one row strip\n * of a widened base weight matrix, accumulating in double precision and rounding each element with\n * `Math.fround`.\n *\n * @remarks\n * Operates on one strip at a time so streaming merges keep peak memory bounded independent of model\n * size. Thrown with the `ARGUMENT` code when strip extents or `factor` are invalid.\n *\n * @param base - The widened base strip of length `rowCount * pair.columns`\n * @param pair - The LoRA adapter pair in the base matrix's layout\n * @param rowStart - The zero-based first output row in the full base matrix\n * @param rowCount - The number of rows in `base`\n * @param factor - The effective LoRA scale `scale * (pair.alpha / pair.rank)`\n * @returns The merged single-precision strip\n *\n * @example\n * ```ts\n * addLoRAStrip(Float32Array.of(1, 2), pair, 0, 1, 1)\n * ```\n */\nexport function addLoRAStrip(\n\tbase: Float32Array,\n\tpair: AdapterPair,\n\trowStart: number,\n\trowCount: number,\n\tfactor: number,\n): Float32Array<ArrayBuffer> {\n\tconst { columns, rows, rank, down, up } = pair\n\tif (\n\t\t!isSafeInteger(rowStart) ||\n\t\trowStart < 0 ||\n\t\t!isSafeInteger(rowCount) ||\n\t\trowCount < 1 ||\n\t\trowStart + rowCount > rows ||\n\t\tbase.length !== rowCount * columns ||\n\t\t!isFiniteNumber(factor)\n\t) {\n\t\tthrow new InferError('The LoRA merge strip extents or factor are invalid.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { rowStart, rowCount, rows, columns, length: base.length, factor },\n\t\t})\n\t}\n\tconst out = new Float32Array(base.length)\n\tfor (let localRow = 0; localRow < rowCount; localRow += 1) {\n\t\tconst upOffset = (rowStart + localRow) * rank\n\t\tconst rowOffset = localRow * columns\n\t\tfor (let column = 0; column < columns; column += 1) {\n\t\t\tlet dot = 0\n\t\t\tfor (let inner = 0; inner < rank; inner += 1) {\n\t\t\t\tdot += (up[upOffset + inner] ?? 0) * (down[inner * columns + column] ?? 0)\n\t\t\t}\n\t\t\tout[rowOffset + column] = Math.fround((base[rowOffset + column] ?? 0) + factor * dot)\n\t\t}\n\t}\n\treturn out\n}\n\n/**\n * Serializes tensor entries and optional string metadata into one safetensors binary buffer.\n *\n * @remarks\n * Validates unique non-empty tensor names, admitted `SAFETENSORS_FORMATS` dtypes, non-negative\n * integer shapes, exact byte lengths, and the `SAFETENSORS_HEADER_LIMIT` header ceiling. Refuses\n * invalid entries with the `ARGUMENT` code.\n *\n * @param entries - The ordered tensors to serialize\n * @param metadata - Optional `__metadata__` string map stored in the safetensors header\n * @returns The serialized safetensors file bytes\n *\n * @example\n * ```ts\n * buildSafetensors([{ name: 'w', format: 'F32', shape: [1, 2], bytes: new Uint8Array(8) }]).length > 8 // true\n * ```\n */\nexport function buildSafetensors(\n\tentries: readonly SafetensorsWriteEntry[],\n\tmetadata?: Readonly<Record<string, string>>,\n): Uint8Array<ArrayBuffer> {\n\tconst seen = new Set<string>()\n\tconst layout: Array<{\n\t\treadonly name: string\n\t\treadonly format: SafetensorsFormat\n\t\treadonly shape: readonly number[]\n\t\treadonly bytes: Uint8Array\n\t\treadonly start: number\n\t\treadonly end: number\n\t}> = []\n\tlet dataLength = 0\n\tfor (let index = 0; index < entries.length; index += 1) {\n\t\tconst entry = entries[index]\n\t\tif (entry === undefined) continue\n\t\tif (!isString(entry.name) || entry.name.length === 0 || entry.name === '__metadata__') {\n\t\t\tthrow new InferError(\n\t\t\t\t`The safetensors tensor name ${quoteFaultText(entry.name)} is invalid.`,\n\t\t\t\t{\n\t\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\t\tcontext: { name: entry.name },\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\tif (seen.has(entry.name)) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The safetensors tensor name ${quoteFaultText(entry.name)} is duplicated.`,\n\t\t\t\t{\n\t\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\t\tcontext: { name: entry.name },\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\tseen.add(entry.name)\n\t\tif (!SAFETENSORS_FORMATS.some((admitted) => admitted === entry.format)) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The safetensors tensor ${quoteFaultText(entry.name)} declares unsupported format ${quoteFaultText(entry.format)}.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { name: entry.name, format: entry.format } },\n\t\t\t)\n\t\t}\n\t\tif (\n\t\t\t!isArray(entry.shape) ||\n\t\t\t!entry.shape.every((extent) => isSafeInteger(extent) && extent >= 0)\n\t\t) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The safetensors tensor ${quoteFaultText(entry.name)} carries an invalid shape.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { name: entry.name } },\n\t\t\t)\n\t\t}\n\t\tconst elements = entry.shape.reduce((product, extent) => product * extent, 1)\n\t\tconst expectedBytes = elements * GGUF_BLOCKS[entry.format].bytes\n\t\tif (!isSafeInteger(expectedBytes) || entry.bytes.byteLength !== expectedBytes) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The safetensors tensor ${quoteFaultText(entry.name)} carries ${entry.bytes.byteLength} bytes; expected ${expectedBytes}.`,\n\t\t\t\t{\n\t\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\t\tcontext: { name: entry.name, actual: entry.bytes.byteLength, expected: expectedBytes },\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\tconst start = dataLength\n\t\tconst end = start + expectedBytes\n\t\tdataLength = end\n\t\tlayout.push({\n\t\t\tname: entry.name,\n\t\t\tformat: entry.format,\n\t\t\tshape: [...entry.shape],\n\t\t\tbytes: entry.bytes,\n\t\t\tstart,\n\t\t\tend,\n\t\t})\n\t}\n\tconst headerEntries: Array<readonly [string, unknown]> = []\n\tif (metadata !== undefined) {\n\t\tconst metaPairs = Object.entries(metadata)\n\t\tif (!metaPairs.every(([, value]) => isString(value))) {\n\t\t\tthrow new InferError('Safetensors __metadata__ values must be strings.', { code: 'ARGUMENT' })\n\t\t}\n\t\tif (metaPairs.length > 0) {\n\t\t\theaderEntries.push(['__metadata__', Object.fromEntries(metaPairs)])\n\t\t}\n\t}\n\tfor (const item of layout) {\n\t\theaderEntries.push([\n\t\t\titem.name,\n\t\t\t{ dtype: item.format, shape: item.shape, data_offsets: [item.start, item.end] },\n\t\t])\n\t}\n\tconst headerBytes = UTF8_ENCODER.encode(JSON.stringify(Object.fromEntries(headerEntries)))\n\tif (headerBytes.byteLength > SAFETENSORS_HEADER_LIMIT) {\n\t\tthrow new InferError(\n\t\t\t`The safetensors header spans ${headerBytes.byteLength} bytes, past the ${SAFETENSORS_HEADER_LIMIT}-byte limit.`,\n\t\t\t{ code: 'ARGUMENT', context: { length: headerBytes.byteLength } },\n\t\t)\n\t}\n\tconst total = 8 + headerBytes.byteLength + dataLength\n\tconst out = new Uint8Array(total)\n\tnew DataView(out.buffer).setBigUint64(0, BigInt(headerBytes.byteLength), true)\n\tout.set(headerBytes, 8)\n\tconst dataStart = 8 + headerBytes.byteLength\n\tfor (const item of layout) {\n\t\tout.set(item.bytes, dataStart + item.start)\n\t}\n\treturn out\n}\n\n/**\n * Serializes validated LoRA adapter options or an `AdapterInterface` into GGUF v3 adapter bytes\n * readable by `@orkestrel/infer`'s `readAdapter` and `llama-server --lora`.\n *\n * @remarks\n * Writes `general.type = \"adapter\"`, `adapter.type = \"lora\"`, `general.architecture`,\n * `adapter.lora.alpha`, optional `orkestrel.base`, and canonical `F32` `.lora_a` (`[columns, rank]`)\n * and `.lora_b` (`[rank, rows]`) tensors aligned to `GGUF_ALIGNMENT`. Refuses per-pair alpha drift\n * with the `UNSUPPORTED` code.\n *\n * @param options - The validated adapter options or live adapter\n * @returns The serialized GGUF v3 LoRA adapter bytes\n *\n * @example\n * ```ts\n * const bytes = buildAdapterGGUF(adapter)\n * ```\n */\nexport function buildAdapterGGUF(\n\toptions: AdapterOptions | AdapterInterface,\n): Uint8Array<ArrayBuffer> {\n\tcheckAdapterOptions(options)\n\tconst mismatchedAlpha = options.pairs.find((pair) => pair.alpha !== options.alpha)\n\tif (mismatchedAlpha !== undefined) {\n\t\tthrow new InferError(\n\t\t\t`The adapter pair ${quoteFaultText(mismatchedAlpha.name)} carries alpha ${mismatchedAlpha.alpha}, differing from adapter alpha ${options.alpha}.`,\n\t\t\t{\n\t\t\t\tcode: 'UNSUPPORTED',\n\t\t\t\tcontext: {\n\t\t\t\t\tname: mismatchedAlpha.name,\n\t\t\t\t\tpairAlpha: mismatchedAlpha.alpha,\n\t\t\t\t\talpha: options.alpha,\n\t\t\t\t},\n\t\t\t},\n\t\t)\n\t}\n\tconst ordered = [...options.pairs].toSorted(\n\t\t(left, right) =>\n\t\t\tleft.layer - right.layer ||\n\t\t\tADAPTER_TARGETS.indexOf(left.target) - ADAPTER_TARGETS.indexOf(right.target),\n\t)\n\tconst metadata = new Map<string, GGUFValue>([\n\t\t[ADAPTER_KEYS.role, { encoding: 'string', value: 'adapter' }],\n\t\t[ADAPTER_KEYS.format, { encoding: 'string', value: 'lora' }],\n\t\t[GGUF_KEYS.architecture, { encoding: 'string', value: options.family }],\n\t\t[ADAPTER_KEYS.alpha, { encoding: 'float32', value: options.alpha }],\n\t\t...(options.base === undefined\n\t\t\t? []\n\t\t\t: [[ADAPTER_KEYS.base, { encoding: 'string', value: options.base }] as const]),\n\t])\n\tconst items = ordered.flatMap((pair) => [\n\t\t{\n\t\t\tname: `${pair.name}.lora_a`,\n\t\t\tdimensions: [pair.columns, pair.rank],\n\t\t\tbytes: encodeSafetensorsValues(pair.down, 'F32'),\n\t\t},\n\t\t{\n\t\t\tname: `${pair.name}.lora_b`,\n\t\t\tdimensions: [pair.rank, pair.rows],\n\t\t\tbytes: encodeSafetensorsValues(pair.up, 'F32'),\n\t\t},\n\t])\n\tconst tensors: GGUFTensor[] = []\n\tlet offset = 0\n\tfor (let index = 0; index < items.length; index += 1) {\n\t\tconst item = items[index]\n\t\tif (item === undefined) continue\n\t\ttensors.push({\n\t\t\tname: item.name,\n\t\t\tdimensions: item.dimensions,\n\t\t\tformat: 'F32',\n\t\t\toffset,\n\t\t})\n\t\toffset = alignOffset(offset + item.bytes.byteLength, GGUF_ALIGNMENT)\n\t}\n\tconst data = new Uint8Array(offset)\n\tfor (let index = 0; index < items.length; index += 1) {\n\t\tconst item = items[index]\n\t\tconst tensor = tensors[index]\n\t\tif (item === undefined || tensor === undefined) continue\n\t\tdata.set(item.bytes, tensor.offset)\n\t}\n\treturn buildGGUF(metadata, tensors, data)\n}\n\n/**\n * Serializes validated LoRA adapter options or an `AdapterInterface` into a Hugging Face `PEFTBundle`\n * (`adapter_config.json` record and `adapter_model.safetensors` bytes).\n *\n * @remarks\n * Uses `PEFT_LAYERS_PREFIX` for `llama` and `PEFT_QWEN35_PREFIX` for `qwen35`, reverses each\n * 2-element GGUF dimension tuple to safetensors row-major shape (`[rank, columns]` and `[rows, rank]`),\n * deinterleaves `llama` `attn_q` and `attn_k` rotary `up` rows to Hugging Face split-half order,\n * and applies the inverse 4B value-head permutation when `conversion.architecture.delta` has\n * `values !== keys`. Refuses omitting `conversion.architecture` with `ARGUMENT` whenever `llama`\n * targets `attn_q`/`attn_k` or `qwen35` targets DeltaNet projections, refuses mixed ranks or\n * per-pair alpha drift with `UNSUPPORTED`, and refuses family or target mismatches with `BINDING`.\n *\n * @param options - The validated adapter options or live adapter\n * @param conversion - Conversion context carrying `architecture` or `family`\n * @returns The serialized `PEFTBundle`\n *\n * @example\n * ```ts\n * const bundle = buildAdapterPEFT(adapter, { architecture })\n * bundle.config.peft_type // 'LORA'\n * ```\n */\nexport function buildAdapterPEFT(\n\toptions: AdapterOptions | AdapterInterface,\n\tconversion: PEFTConversionOptions = {},\n): PEFTBundle {\n\tcheckAdapterOptions(options)\n\tif (conversion.family !== undefined && conversion.family !== options.family) {\n\t\tthrow new InferError(\n\t\t\t`The conversion family ${quoteFaultText(conversion.family)} disagrees with adapter family ${quoteFaultText(options.family)}.`,\n\t\t\t{ code: 'BINDING', context: { expected: conversion.family, actual: options.family } },\n\t\t)\n\t}\n\tcheckAdapterArchitecture(\n\t\toptions.family,\n\t\toptions.pairs.map((pair) => pair.target),\n\t\tconversion.architecture,\n\t)\n\tif (conversion.architecture !== undefined) {\n\t\tcheckAdapterBinding(new Adapter(options), conversion.architecture)\n\t}\n\tconst [firstPair] = options.pairs\n\tif (firstPair === undefined) {\n\t\tthrow new InferError('The adapter holds no LoRA pairs.', { code: 'ARGUMENT' })\n\t}\n\tconst rank = firstPair.rank\n\tconst mismatchedRank = options.pairs.find((pair) => pair.rank !== rank)\n\tif (mismatchedRank !== undefined) {\n\t\tthrow new InferError(\n\t\t\t`The adapter pair ${quoteFaultText(mismatchedRank.name)} has rank ${mismatchedRank.rank}, differing from PEFT rank ${rank}.`,\n\t\t\t{\n\t\t\t\tcode: 'UNSUPPORTED',\n\t\t\t\tcontext: { name: mismatchedRank.name, rank: mismatchedRank.rank, expected: rank },\n\t\t\t},\n\t\t)\n\t}\n\tconst mismatchedAlpha = options.pairs.find((pair) => pair.alpha !== options.alpha)\n\tif (mismatchedAlpha !== undefined) {\n\t\tthrow new InferError(\n\t\t\t`The adapter pair ${quoteFaultText(mismatchedAlpha.name)} carries alpha ${mismatchedAlpha.alpha}, differing from adapter alpha ${options.alpha}.`,\n\t\t\t{\n\t\t\t\tcode: 'UNSUPPORTED',\n\t\t\t\tcontext: {\n\t\t\t\t\tname: mismatchedAlpha.name,\n\t\t\t\t\tpairAlpha: mismatchedAlpha.alpha,\n\t\t\t\t\talpha: options.alpha,\n\t\t\t\t},\n\t\t\t},\n\t\t)\n\t}\n\tconst ordered = [...options.pairs].toSorted(\n\t\t(left, right) =>\n\t\t\tleft.layer - right.layer ||\n\t\t\tADAPTER_TARGETS.indexOf(left.target) - ADAPTER_TARGETS.indexOf(right.target),\n\t)\n\tconst prefix = options.family === 'qwen35' ? PEFT_QWEN35_PREFIX : PEFT_LAYERS_PREFIX\n\tconst leafOrder: string[] = []\n\tconst entries: SafetensorsWriteEntry[] = []\n\tfor (const rawPair of ordered) {\n\t\tconst spec = PEFT_TARGET_SPECS[rawPair.target]\n\t\tif (!spec.families.includes(options.family)) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The LoRA target ${quoteFaultText(rawPair.target)} is not admitted by family ${quoteFaultText(options.family)}.`,\n\t\t\t\t{ code: 'BINDING', context: { target: rawPair.target, family: options.family } },\n\t\t\t)\n\t\t}\n\t\tconst pair = permuteRotaryPair(\n\t\t\tpermuteDeltaPair(rawPair, conversion.architecture, false),\n\t\t\tconversion.architecture,\n\t\t\tfalse,\n\t\t)\n\t\tif (!leafOrder.includes(spec.leaf)) leafOrder.push(spec.leaf)\n\t\tconst stem = `${prefix}${pair.layer}.${spec.module}`\n\t\tentries.push(\n\t\t\t{\n\t\t\t\tname: `${stem}.lora_A.weight`,\n\t\t\t\tformat: 'F32',\n\t\t\t\tshape: [pair.rank, pair.columns],\n\t\t\t\tbytes: encodeSafetensorsValues(pair.down, 'F32'),\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `${stem}.lora_B.weight`,\n\t\t\t\tformat: 'F32',\n\t\t\t\tshape: [pair.rows, pair.rank],\n\t\t\t\tbytes: encodeSafetensorsValues(pair.up, 'F32'),\n\t\t\t},\n\t\t)\n\t}\n\tconst config: PEFTConfig = {\n\t\tpeft_type: 'LORA',\n\t\tr: rank,\n\t\tlora_alpha: options.alpha,\n\t\ttarget_modules: leafOrder,\n\t\tbias: 'none',\n\t\tuse_rslora: false,\n\t\tuse_dora: false,\n\t\ttask_type: 'CAUSAL_LM',\n\t}\n\treturn { config, weights: buildSafetensors(entries, { format: 'pt' }) }\n}\n\n/**\n * Reads and validates a Hugging Face `PEFTBundle` into `AdapterOptions` ready for `new Adapter(...)`\n * or `buildAdapterGGUF(...)`.\n *\n * @remarks\n * Admits canonical `PEFT_LAYERS_PREFIX` for `llama` and both `PEFT_QWEN35_PREFIX` and the\n * `PEFT_LAYERS_PREFIX` alias for `qwen35`. Widens `F32`, `F16`, and `BF16` tensors to single\n * precision, interleaves `llama` `attn_q` and `attn_k` rotary `up` rows to GGUF order, applies\n * the 4B value-head permutation when `options.architecture.delta` has `values !== keys`, refuses\n * omitting `options.architecture` with `ARGUMENT` whenever `llama` targets `attn_q`/`attn_k` or\n * `qwen35` targets DeltaNet projections, refuses unsupported PEFT options (`use_rslora`,\n * `use_dora`, `bias !== 'none'`, `peft_type !== 'LORA'`) with `UNSUPPORTED`, and refuses malformed\n * tensors with `FORMAT`.\n *\n * @param bundle - The PEFT configuration and safetensors weights\n * @param options - Conversion family, architecture, base digest, and abort signal\n * @returns The validated `AdapterOptions`\n *\n * @example\n * ```ts\n * const adapterOptions = await readAdapterPEFT(bundle, { architecture })\n * ```\n */\nexport async function readAdapterPEFT(\n\tbundle: PEFTBundle,\n\toptions: PEFTConversionOptions = {},\n): Promise<AdapterOptions> {\n\tcheckSignal(options.signal, 'The PEFT adapter read')\n\tif (!isObject(bundle)) {\n\t\tthrow new InferError('The PEFT bundle must be an object carrying config and weights.', {\n\t\t\tcode: 'FORMAT',\n\t\t})\n\t}\n\tconst config = checkPEFTConfig(Reflect.get(bundle, 'config'))\n\tconst weights: unknown = Reflect.get(bundle, 'weights')\n\tif (!isUint8Array(weights)) {\n\t\tthrow new InferError('The PEFT bundle requires Uint8Array weights.', { code: 'FORMAT' })\n\t}\n\tif (\n\t\toptions.family !== undefined &&\n\t\toptions.architecture !== undefined &&\n\t\toptions.family !== options.architecture.family\n\t) {\n\t\tthrow new InferError(\n\t\t\t`The conversion family ${quoteFaultText(options.family)} disagrees with architecture family ${quoteFaultText(options.architecture.family)}.`,\n\t\t\t{\n\t\t\t\tcode: 'BINDING',\n\t\t\t\tcontext: { family: options.family, architecture: options.architecture.family },\n\t\t\t},\n\t\t)\n\t}\n\tif (options.base !== undefined && !SHA256_PATTERN.test(options.base)) {\n\t\tthrow new InferError(\n\t\t\t`The base digest ${quoteFaultText(options.base)} must be a 64-character lowercase SHA-256 hex string.`,\n\t\t\t{ code: 'ARGUMENT', context: { base: options.base } },\n\t\t)\n\t}\n\tconst [tensors, dataStart] = readSafetensors(weights)\n\tif (tensors.length === 0) {\n\t\tthrow new InferError('The PEFT safetensors file holds no LoRA tensors.', { code: 'FORMAT' })\n\t}\n\tconst moduleToTarget = new Map<string, AdapterTarget>(\n\t\tADAPTER_TARGETS.map((target) => [PEFT_TARGET_SPECS[target].module, target]),\n\t)\n\tconst grouped = new Map<\n\t\tstring,\n\t\t{\n\t\t\treadonly layer: number\n\t\t\treadonly target: AdapterTarget\n\t\t\treadonly a?: SafetensorsTensor\n\t\t\treadonly b?: SafetensorsTensor\n\t\t}\n\t>()\n\tconst languageModelFlags: boolean[] = []\n\tconst qwenOnlyFlags: boolean[] = []\n\tfor (const tensor of tensors) {\n\t\tconst match = PEFT_TENSOR_PATTERN.exec(tensor.name)\n\t\tconst languageModel = match?.[1]\n\t\tconst rawLayer = match?.[2]\n\t\tconst modulePath = match?.[3]\n\t\tconst side = match?.[4]\n\t\tif (\n\t\t\tmatch === null ||\n\t\t\trawLayer === undefined ||\n\t\t\tmodulePath === undefined ||\n\t\t\t(side !== 'A' && side !== 'B')\n\t\t) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The PEFT tensor ${quoteFaultText(tensor.name)} does not name a supported LoRA target pair.`,\n\t\t\t\t{ code: 'FORMAT', context: { name: tensor.name } },\n\t\t\t)\n\t\t}\n\t\tconst target = moduleToTarget.get(modulePath)\n\t\tif (target === undefined) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The PEFT tensor ${quoteFaultText(tensor.name)} names unsupported module ${quoteFaultText(modulePath)}.`,\n\t\t\t\t{ code: 'FORMAT', context: { name: tensor.name, module: modulePath } },\n\t\t\t)\n\t\t}\n\t\tconst layer = Number(rawLayer)\n\t\tif (!isSafeInteger(layer) || layer < 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The PEFT tensor ${quoteFaultText(tensor.name)} names an out-of-range layer index.`,\n\t\t\t\t{ code: 'FORMAT', context: { name: tensor.name, layer: rawLayer } },\n\t\t\t)\n\t\t}\n\t\tconst [dim0, dim1] = tensor.dimensions\n\t\tif (\n\t\t\ttensor.dimensions.length !== 2 ||\n\t\t\tdim0 === undefined ||\n\t\t\tdim1 === undefined ||\n\t\t\t!isSafeInteger(dim0) ||\n\t\t\tdim0 < 1 ||\n\t\t\t!isSafeInteger(dim1) ||\n\t\t\tdim1 < 1\n\t\t) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The PEFT tensor ${quoteFaultText(tensor.name)} has extents [${tensor.dimensions.join(', ')}]; LoRA tensors are 2D with positive extents.`,\n\t\t\t\t{ code: 'FORMAT', context: { name: tensor.name, dimensions: tensor.dimensions } },\n\t\t\t)\n\t\t}\n\t\tif (languageModel !== undefined) languageModelFlags.push(true)\n\t\tif (!PEFT_TARGET_SPECS[target].families.includes('llama')) qwenOnlyFlags.push(true)\n\t\tconst name = `blk.${layer}.${target}.weight`\n\t\tconst prior = grouped.get(name)\n\t\tif ((side === 'A' && prior?.a !== undefined) || (side === 'B' && prior?.b !== undefined)) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The PEFT adapter holds a duplicate lora_${side} tensor for ${quoteFaultText(name)}.`,\n\t\t\t\t{ code: 'FORMAT', context: { name, side } },\n\t\t\t)\n\t\t}\n\t\tgrouped.set(name, {\n\t\t\tlayer,\n\t\t\ttarget,\n\t\t\t...(prior?.a === undefined ? {} : { a: prior.a }),\n\t\t\t...(prior?.b === undefined ? {} : { b: prior.b }),\n\t\t\t...(side === 'A' ? { a: tensor } : { b: tensor }),\n\t\t})\n\t}\n\tconst family: ArchitectureFamily =\n\t\toptions.architecture?.family ??\n\t\toptions.family ??\n\t\t(languageModelFlags.length > 0 || qwenOnlyFlags.length > 0 ? 'qwen35' : 'llama')\n\tif (family === 'llama' && (languageModelFlags.length > 0 || qwenOnlyFlags.length > 0)) {\n\t\tthrow new InferError(\n\t\t\t'The PEFT adapter contains Qwen3.5 prefix or Gated DeltaNet targets incompatible with llama.',\n\t\t\t{ code: 'BINDING', context: { family } },\n\t\t)\n\t}\n\tconst ordered = [...grouped.entries()].toSorted(\n\t\t([, left], [, right]) =>\n\t\t\tleft.layer - right.layer ||\n\t\t\tADAPTER_TARGETS.indexOf(left.target) - ADAPTER_TARGETS.indexOf(right.target),\n\t)\n\tcheckAdapterArchitecture(\n\t\tfamily,\n\t\tordered.map(([, entry]) => entry.target),\n\t\toptions.architecture,\n\t)\n\tconst pairs: AdapterPair[] = []\n\tfor (const [name, entry] of ordered) {\n\t\tif (entry.a === undefined || entry.b === undefined) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The PEFT adapter pair ${quoteFaultText(name)} is incomplete; every LoRA target requires both lora_A and lora_B.`,\n\t\t\t\t{ code: 'FORMAT', context: { name } },\n\t\t\t)\n\t\t}\n\t\tconst [columns, rankA] = entry.a.dimensions\n\t\tconst [rankB, rows] = entry.b.dimensions\n\t\tif (\n\t\t\tcolumns === undefined ||\n\t\t\trankA === undefined ||\n\t\t\trankB === undefined ||\n\t\t\trows === undefined ||\n\t\t\trankA !== rankB ||\n\t\t\trankA !== config.r\n\t\t) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The PEFT adapter pair ${quoteFaultText(name)} has ranks (${String(rankA)}, ${String(rankB)}) disagreeing with config r=${config.r}.`,\n\t\t\t\t{ code: 'FORMAT', context: { name, rankA, rankB, expected: config.r } },\n\t\t\t)\n\t\t}\n\t\tconst down = widenTensor(\n\t\t\tweights.subarray(\n\t\t\t\tdataStart + entry.a.offset,\n\t\t\t\tdataStart + entry.a.offset + computeTensorBytes(entry.a),\n\t\t\t),\n\t\t\tentry.a.format,\n\t\t)\n\t\tconst up = widenTensor(\n\t\t\tweights.subarray(\n\t\t\t\tdataStart + entry.b.offset,\n\t\t\t\tdataStart + entry.b.offset + computeTensorBytes(entry.b),\n\t\t\t),\n\t\t\tentry.b.format,\n\t\t)\n\t\tif (!down.every(Number.isFinite) || !up.every(Number.isFinite)) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The PEFT adapter pair ${quoteFaultText(name)} holds a non-finite weight value.`,\n\t\t\t\t{ code: 'FORMAT', context: { name } },\n\t\t\t)\n\t\t}\n\t\tconst spec = ADAPTER_TARGET_SPECS[entry.target]\n\t\tconst rawPair: AdapterPair = {\n\t\t\tname,\n\t\t\tlayer: entry.layer,\n\t\t\tgroup: spec.group,\n\t\t\tslot: spec.slot,\n\t\t\ttarget: entry.target,\n\t\t\tcolumns,\n\t\t\trows,\n\t\t\trank: rankA,\n\t\t\talpha: config.lora_alpha,\n\t\t\tdown,\n\t\t\tup,\n\t\t}\n\t\tpairs.push(\n\t\t\tpermuteRotaryPair(\n\t\t\t\tpermuteDeltaPair(rawPair, options.architecture, true),\n\t\t\t\toptions.architecture,\n\t\t\t\ttrue,\n\t\t\t),\n\t\t)\n\t}\n\tconst ownedBytes = new Uint8Array(weights)\n\tconst digest = await digestBytes(ownedBytes)\n\tcheckSignal(options.signal, 'The PEFT adapter read')\n\tconst adapterOptions: AdapterOptions = {\n\t\tdigest,\n\t\tfamily,\n\t\talpha: config.lora_alpha,\n\t\t...(options.base === undefined ? {} : { base: options.base }),\n\t\tpairs: Object.freeze(pairs),\n\t}\n\tif (options.architecture !== undefined) {\n\t\tcheckAdapterBinding(new Adapter(adapterOptions), options.architecture)\n\t}\n\treturn adapterOptions\n}\n\n/**\n * Converts a GGUF v3 LoRA adapter into a Hugging Face `PEFTBundle`.\n *\n * @remarks\n * Reads the GGUF adapter through `@orkestrel/infer`'s `readAdapter`, checks optional family and\n * architecture binding, deinterleaves `llama` `attn_q` and `attn_k` rotary `up` rows, applies the\n * inverse 4B value-head permutation when `options.architecture` has `delta.values !== delta.keys`,\n * refuses omitting `options.architecture` with `ARGUMENT` for `llama` `attn_q`/`attn_k` or\n * `qwen35` DeltaNet targets, and serializes `adapter_config.json` and `adapter_model.safetensors`.\n *\n * @param source - The GGUF v3 LoRA adapter byte source or byte array\n * @param options - Conversion family, architecture, and abort signal\n * @returns The converted `PEFTBundle`\n *\n * @example\n * ```ts\n * const bundle = await ggufToPEFT(ggufBytes, { architecture })\n * ```\n */\nexport async function ggufToPEFT(\n\tsource: ByteSourceInterface | Uint8Array,\n\toptions: PEFTConversionOptions = {},\n): Promise<PEFTBundle> {\n\tcheckSignal(options.signal, 'The GGUF-to-PEFT conversion')\n\tconst byteSource: ByteSourceInterface = isUint8Array(source)\n\t\t? new MemorySource(new Uint8Array(source))\n\t\t: source\n\tconst adapterOptions = await readAdapter(byteSource, options.signal)\n\treturn buildAdapterPEFT(adapterOptions, options)\n}\n\n/**\n * Converts a Hugging Face `PEFTBundle` into GGUF v3 LoRA adapter bytes.\n *\n * @remarks\n * Validates `bundle.config` and `bundle.weights` through `readAdapterPEFT`, interleaves `llama`\n * `attn_q` and `attn_k` rotary `up` rows, applies the 4B value-head permutation when\n * `options.architecture` has `delta.values !== delta.keys`, refuses omitting `options.architecture`\n * with `ARGUMENT` for `llama` `attn_q`/`attn_k` or `qwen35` DeltaNet targets, and serializes\n * canonical `F32` GGUF v3 LoRA bytes through `buildAdapterGGUF`.\n *\n * @param bundle - The PEFT configuration and safetensors weights\n * @param options - Conversion family, architecture, base digest, and abort signal\n * @returns The serialized GGUF v3 LoRA adapter bytes\n *\n * @example\n * ```ts\n * const ggufBytes = await peftToGGUF(bundle, { architecture })\n * ```\n */\nexport async function peftToGGUF(\n\tbundle: PEFTBundle,\n\toptions: PEFTConversionOptions = {},\n): Promise<Uint8Array<ArrayBuffer>> {\n\tconst adapterOptions = await readAdapterPEFT(bundle, options)\n\treturn buildAdapterGGUF(adapterOptions)\n}\n\n/**\n * Streams an async chunk iterable into a `ByteSinkInterface`, closing on completion and aborting\n * the sink on error or signal cancellation.\n *\n * @remarks\n * Returns the total number of bytes written. Thrown with the `ARGUMENT` code when `sink` fails\n * `isByteSink`, and with the `ABORT` code when `signal` aborts.\n *\n * @param chunks - The async iterable of byte chunks to write\n * @param sink - The destination byte sink\n * @param signal - Cancels the write between chunks\n * @returns Total bytes written to `sink`\n *\n * @example\n * ```ts\n * const written = await writeByteSink(mergeGGUF({ source, adapter }), sink)\n * ```\n */\nexport async function writeByteSink(\n\tchunks: AsyncIterable<Uint8Array>,\n\tsink: ByteSinkInterface,\n\tsignal?: AbortSignal,\n): Promise<number> {\n\tif (!isByteSink(sink)) {\n\t\tthrow new InferError('The destination must implement ByteSinkInterface.', { code: 'ARGUMENT' })\n\t}\n\tcheckSignal(signal, 'The byte sink write')\n\tconst sizes: number[] = []\n\ttry {\n\t\tfor await (const chunk of chunks) {\n\t\t\tcheckSignal(signal, 'The byte sink write')\n\t\t\tawait sink.write(chunk)\n\t\t\tsizes.push(chunk.byteLength)\n\t\t}\n\t\tcheckSignal(signal, 'The byte sink write')\n\t\tawait sink.close()\n\t} catch (error) {\n\t\tawait attempt(() => sink.abort?.(error))\n\t\tthrow error\n\t}\n\treturn sizes.reduce((sum, length) => sum + length, 0)\n}\n\n/**\n * Reads only the safetensors JSON header from a `ByteSourceInterface` without buffering the tensor\n * payload bytes.\n *\n * @remarks\n * Validates the 8-byte little-endian header length, the `SAFETENSORS_HEADER_LIMIT` ceiling,\n * well-formed UTF-8 JSON, every tensor descriptor through `@orkestrel/infer`'s `readSafetensorsEntry`,\n * and non-overlapping byte ranges through `findTensorOverlap`.\n *\n * @param source - The safetensors byte source\n * @param signal - Cancels the header read; rejects with the `ABORT` code\n * @returns The parsed tensor descriptors, the data section start offset, and optional string metadata\n *\n * @example\n * ```ts\n * const header = await readSafetensorsHeader(source)\n * header.tensors.length // tensor count\n * ```\n */\nexport async function readSafetensorsHeader(\n\tsource: ByteSourceInterface,\n\tsignal?: AbortSignal,\n): Promise<{\n\treadonly tensors: readonly SafetensorsTensor[]\n\treadonly offset: number\n\treadonly metadata?: Readonly<Record<string, string>>\n}> {\n\tcheckSignal(signal, 'The safetensors header read')\n\tif (source.size < 8) {\n\t\tthrow new InferError(\n\t\t\t`The safetensors file holds ${source.size} bytes, fewer than its 8-byte header length.`,\n\t\t\t{ code: 'FORMAT', context: { size: source.size } },\n\t\t)\n\t}\n\tconst prefix = await source.read(0, 8, signal)\n\tconst declared = new DataView(prefix.buffer, prefix.byteOffset, prefix.byteLength).getBigUint64(\n\t\t0,\n\t\ttrue,\n\t)\n\tconst maxLength = Math.min(SAFETENSORS_HEADER_LIMIT, source.size - 8)\n\tif (declared > BigInt(maxLength)) {\n\t\tthrow new InferError(\n\t\t\t`The safetensors header declares ${declared} bytes, past the file or the ${SAFETENSORS_HEADER_LIMIT}-byte limit.`,\n\t\t\t{ code: 'FORMAT', context: { length: String(declared) } },\n\t\t)\n\t}\n\tconst headerLength = Number(declared)\n\tconst headerBytes = await source.read(8, headerLength, signal)\n\tconst decoded = attempt(() => new TextDecoder('utf-8', { fatal: true }).decode(headerBytes))\n\tif (!decoded.success) {\n\t\tthrow new InferError('The safetensors header is not well-formed UTF-8.', { code: 'FORMAT' })\n\t}\n\tconst parsed = parseJSON(decoded.value)\n\tif (!isRecord(parsed)) {\n\t\tthrow new InferError('The safetensors header must be a JSON object.', { code: 'FORMAT' })\n\t}\n\tconst dataStart = 8 + headerLength\n\tconst available = source.size - dataStart\n\tconst rawMetadata = Object.hasOwn(parsed, '__metadata__') ? parsed['__metadata__'] : undefined\n\tif (\n\t\trawMetadata !== undefined &&\n\t\t(!isRecord(rawMetadata) || !Object.values(rawMetadata).every(isString))\n\t) {\n\t\tthrow new InferError('The safetensors __metadata__ member must map strings to strings.', {\n\t\t\tcode: 'FORMAT',\n\t\t})\n\t}\n\tconst metadata =\n\t\trawMetadata === undefined\n\t\t\t? undefined\n\t\t\t: Object.fromEntries(\n\t\t\t\t\tObject.entries(rawMetadata).filter((entry): entry is [string, string] =>\n\t\t\t\t\t\tisString(entry[1]),\n\t\t\t\t\t),\n\t\t\t\t)\n\tconst tensors = Object.entries(parsed)\n\t\t.filter(([name]) => name !== '__metadata__')\n\t\t.map(([name, entry]) => readSafetensorsEntry(name, entry, available))\n\tconst overlap = findTensorOverlap(tensors)\n\tif (overlap !== undefined) {\n\t\tthrow new InferError(\n\t\t\t`The safetensors entry ${quoteFaultText(overlap.name)} overlaps another entry.`,\n\t\t\t{ code: 'FORMAT', context: { name: overlap.name } },\n\t\t)\n\t}\n\treturn {\n\t\ttensors,\n\t\toffset: dataStart,\n\t\t...(metadata === undefined ? {} : { metadata }),\n\t}\n}\n\n/**\n * Streams a LoRA- or section-merged (or combined) safetensors file from a base safetensors\n * `ByteSourceInterface`, an optional `AdapterInterface`, and an optional `SectionInterface`, never\n * holding the base file in memory.\n *\n * @remarks\n * Reads only the base header, validates all adapter and section bindings before yielding any byte,\n * requires `options.architecture` (`ARGUMENT`) whenever `llama` targets `attn_q`/`attn_k` or\n * `qwen35` targets DeltaNet projections, deinterleaves `llama` `attn_q`/`attn_k` rotary rows and\n * permutes 4B DeltaNet value heads into Hugging Face layout, emits the output safetensors header\n * upfront, copies untargeted tensors in `chunk`-byte slices, and replaces full-rank `section`\n * tensors, adds scaled LoRA `adapter` deltas, or both in `strip`-row strips preserving each\n * tensor's base dtype (`F32`, `F16`, or `BF16`). When both `section` and `adapter` target the same\n * weight tensor, `section` replaces the base weight first and `adapter` adds its scaled delta on\n * top. Checks `signal` between slices and strips.\n *\n * @param options - The base byte source, optional adapter and section, architecture, optional base/scale, slice sizes, and signal\n * @returns An async generator yielding merged safetensors file chunks\n *\n * @example\n * ```ts\n * for await (const chunk of mergeSafetensors({ source, adapter, section, architecture })) {\n * \tawait sink.write(chunk)\n * }\n * ```\n */\nexport async function* mergeSafetensors(\n\toptions: MergeSafetensorsOptions,\n): AsyncGenerator<Uint8Array<ArrayBuffer>, void, void> {\n\tconst { source, adapter, section, architecture, base, signal } = options\n\tcheckSignal(signal, 'The safetensors merge')\n\tif (adapter === undefined && section === undefined) {\n\t\tthrow new InferError('The safetensors merge requires at least one of adapter or section.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tif (adapter !== undefined && section !== undefined && adapter.family !== section.family) {\n\t\tthrow new InferError(\n\t\t\t`The adapter targets family ${quoteFaultText(adapter.family)}, while the section targets ${quoteFaultText(section.family)}.`,\n\t\t\t{ code: 'BINDING', context: { adapter: adapter.family, section: section.family } },\n\t\t)\n\t}\n\tconst scale = options.scale ?? adapter?.scale ?? 1\n\tif (!isFiniteNumber(scale)) {\n\t\tthrow new InferError(`The merge scale ${scale} must be a finite number.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { scale },\n\t\t})\n\t}\n\tconst chunkBytes = options.chunk ?? MERGE_CHUNK_BYTES\n\tif (!isSafeInteger(chunkBytes) || chunkBytes < 1) {\n\t\tthrow new InferError(`The merge chunk size ${chunkBytes} must be a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { chunk: chunkBytes },\n\t\t})\n\t}\n\tconst stripRows = options.strip ?? MERGE_ROW_STRIP\n\tif (!isSafeInteger(stripRows) || stripRows < 1) {\n\t\tthrow new InferError(`The merge strip height ${stripRows} must be a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { strip: stripRows },\n\t\t})\n\t}\n\tif (adapter !== undefined) {\n\t\tif (base !== undefined && adapter.base !== undefined && adapter.base !== base) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The adapter binds to base ${quoteFaultText(adapter.base)}; the safetensors base is ${quoteFaultText(base)}.`,\n\t\t\t\t{ code: 'BINDING', context: { base: adapter.base, expected: base } },\n\t\t\t)\n\t\t}\n\t\tcheckAdapterArchitecture(\n\t\t\tadapter.family,\n\t\t\tadapter.pairs.map((pair) => pair.target),\n\t\t\tarchitecture,\n\t\t)\n\t\tif (architecture !== undefined) {\n\t\t\tcheckAdapterBinding(adapter, architecture, base)\n\t\t}\n\t}\n\tif (section !== undefined) {\n\t\tif (base !== undefined && section.base !== undefined && section.base !== base) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The section patch binds to base ${quoteFaultText(section.base)}; the safetensors base is ${quoteFaultText(base)}.`,\n\t\t\t\t{ code: 'BINDING', context: { base: section.base, expected: base } },\n\t\t\t)\n\t\t}\n\t\tif (architecture === undefined) {\n\t\t\tconst sensitive = section.entries.find((entry) =>\n\t\t\t\tsection.family === 'llama'\n\t\t\t\t\t? entry.target === 'attn_q' || entry.target === 'attn_k'\n\t\t\t\t\t: entry.target === 'attn_qkv' ||\n\t\t\t\t\t\tentry.target === 'attn_gate' ||\n\t\t\t\t\t\tentry.target === 'ssm_alpha' ||\n\t\t\t\t\t\tentry.target === 'ssm_beta' ||\n\t\t\t\t\t\tentry.target === 'ssm_conv1d' ||\n\t\t\t\t\t\tentry.target === 'ssm_dt' ||\n\t\t\t\t\t\tentry.target === 'ssm_a' ||\n\t\t\t\t\t\tentry.target === 'ssm_out',\n\t\t\t)\n\t\t\tif (sensitive !== undefined) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`Merging ${quoteFaultText(section.family)} section target ${quoteFaultText(sensitive.target)} into safetensors requires the base architecture option to preserve head layout.`,\n\t\t\t\t\t{ code: 'ARGUMENT', context: { family: section.family, target: sensitive.target } },\n\t\t\t\t)\n\t\t\t}\n\t\t} else {\n\t\t\tcheckSectionBinding(section, architecture, base)\n\t\t}\n\t}\n\tconst header = await readSafetensorsHeader(source, signal)\n\tconst byName = new Map<string, SafetensorsTensor>(\n\t\theader.tensors.map((tensor) => [tensor.name, tensor]),\n\t)\n\tconst targetedAdapters = new Map<string, AdapterPair>()\n\tif (adapter !== undefined) {\n\t\tfor (const rawPair of adapter.pairs) {\n\t\t\tconst spec = PEFT_TARGET_SPECS[rawPair.target]\n\t\t\tif (!spec.families.includes(adapter.family)) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The LoRA target ${quoteFaultText(rawPair.target)} is not admitted by family ${quoteFaultText(adapter.family)}.`,\n\t\t\t\t\t{ code: 'BINDING', context: { target: rawPair.target, family: adapter.family } },\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst canonicalName =\n\t\t\t\tadapter.family === 'qwen35'\n\t\t\t\t\t? `${PEFT_BASE_QWEN35_PREFIX}${rawPair.layer}.${spec.module}.weight`\n\t\t\t\t\t: `${PEFT_BASE_LAYERS_PREFIX}${rawPair.layer}.${spec.module}.weight`\n\t\t\tconst aliasName = `${PEFT_BASE_LAYERS_PREFIX}${rawPair.layer}.${spec.module}.weight`\n\t\t\tconst matched =\n\t\t\t\tbyName.get(canonicalName) ??\n\t\t\t\t(adapter.family === 'qwen35' ? byName.get(aliasName) : undefined)\n\t\t\tif (matched === undefined) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The base safetensors file lacks target tensor ${quoteFaultText(canonicalName)}.`,\n\t\t\t\t\t{ code: 'BINDING', context: { name: canonicalName, pair: rawPair.name } },\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst [columns, rows] = matched.dimensions\n\t\t\tif (matched.dimensions.length !== 2 || columns !== rawPair.columns || rows !== rawPair.rows) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The adapter pair ${quoteFaultText(rawPair.name)} has shape [${rawPair.columns}, ${rawPair.rows}]; the base tensor ${quoteFaultText(matched.name)} has [${matched.dimensions.join(', ')}].`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'BINDING',\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tname: matched.name,\n\t\t\t\t\t\t\tdimensions: [rawPair.columns, rawPair.rows],\n\t\t\t\t\t\t\texpected: matched.dimensions,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\ttargetedAdapters.set(\n\t\t\t\tmatched.name,\n\t\t\t\tpermuteRotaryPair(permuteDeltaPair(rawPair, architecture, false), architecture, false),\n\t\t\t)\n\t\t}\n\t}\n\tconst targetedSections = new Map<string, SectionEntry>()\n\tconst appendedSections: Array<{\n\t\treadonly name: string\n\t\treadonly entry: SectionEntry\n\t\treadonly format: SafetensorsFormat\n\t}> = []\n\tif (section !== undefined) {\n\t\tconst fallbackFormat = header.tensors[0]?.format ?? 'F32'\n\t\tfor (const rawEntry of section.entries) {\n\t\t\tconst spec = SECTION_SAFETENSORS_SPECS[rawEntry.target]\n\t\t\tif (!spec.families.includes(section.family)) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The section target ${quoteFaultText(rawEntry.target)} is not admitted by family ${quoteFaultText(section.family)}.`,\n\t\t\t\t\t{ code: 'BINDING', context: { target: rawEntry.target, family: section.family } },\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst canonicalName = spec.top\n\t\t\t\t? rawEntry.target === 'output'\n\t\t\t\t\t? spec.suffix\n\t\t\t\t\t: section.family === 'qwen35'\n\t\t\t\t\t\t? `model.language_model.${spec.suffix}`\n\t\t\t\t\t\t: `model.${spec.suffix}`\n\t\t\t\t: section.family === 'qwen35'\n\t\t\t\t\t? `${PEFT_BASE_QWEN35_PREFIX}${rawEntry.layer}.${spec.suffix}`\n\t\t\t\t\t: `${PEFT_BASE_LAYERS_PREFIX}${rawEntry.layer}.${spec.suffix}`\n\t\t\tconst aliasName = spec.top\n\t\t\t\t? rawEntry.target === 'output'\n\t\t\t\t\t? spec.suffix\n\t\t\t\t\t: `model.${spec.suffix}`\n\t\t\t\t: `${PEFT_BASE_LAYERS_PREFIX}${rawEntry.layer}.${spec.suffix}`\n\t\t\tconst matched =\n\t\t\t\tbyName.get(canonicalName) ??\n\t\t\t\t(section.family === 'qwen35' ? byName.get(aliasName) : undefined)\n\t\t\tconst permuted = permuteSectionEntry(rawEntry, architecture, false)\n\t\t\tconst transformed =\n\t\t\t\trawEntry.target === 'ssm_a'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t...permuted,\n\t\t\t\t\t\t\tvalues: Float32Array.from(permuted.values, (value) => {\n\t\t\t\t\t\t\t\tif (value >= 0) {\n\t\t\t\t\t\t\t\t\tthrow new InferError(\n\t\t\t\t\t\t\t\t\t\t`The section target ${quoteFaultText(rawEntry.name)} holds non-negative decay ${value}; Hugging Face A_log requires negative ssm_a.`,\n\t\t\t\t\t\t\t\t\t\t{ code: 'FORMAT', context: { name: rawEntry.name, value } },\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn Math.fround(Math.log(-value))\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t}\n\t\t\t\t\t: permuted\n\t\t\tif (matched === undefined) {\n\t\t\t\tif (rawEntry.target === 'output') {\n\t\t\t\t\tconst embed =\n\t\t\t\t\t\tbyName.get('model.language_model.embed_tokens.weight') ??\n\t\t\t\t\t\tbyName.get('model.embed_tokens.weight')\n\t\t\t\t\tif (\n\t\t\t\t\t\tembed !== undefined &&\n\t\t\t\t\t\tembed.dimensions.length === 2 &&\n\t\t\t\t\t\tembed.dimensions[0] === rawEntry.columns &&\n\t\t\t\t\t\tembed.dimensions[1] === rawEntry.rows\n\t\t\t\t\t) {\n\t\t\t\t\t\tappendedSections.push({\n\t\t\t\t\t\t\tname: canonicalName,\n\t\t\t\t\t\t\tentry: transformed,\n\t\t\t\t\t\t\tformat: embed.format ?? fallbackFormat,\n\t\t\t\t\t\t})\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The base safetensors file lacks target tensor ${quoteFaultText(canonicalName)}.`,\n\t\t\t\t\t{ code: 'BINDING', context: { name: canonicalName, entry: rawEntry.name } },\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst shapeMatches =\n\t\t\t\trawEntry.rows === 1\n\t\t\t\t\t? matched.dimensions.length === 1 && matched.dimensions[0] === rawEntry.columns\n\t\t\t\t\t: rawEntry.target === 'ssm_conv1d'\n\t\t\t\t\t\t? (matched.dimensions.length === 2 &&\n\t\t\t\t\t\t\t\tmatched.dimensions[0] === rawEntry.columns &&\n\t\t\t\t\t\t\t\tmatched.dimensions[1] === rawEntry.rows) ||\n\t\t\t\t\t\t\t(matched.dimensions.length === 3 &&\n\t\t\t\t\t\t\t\tmatched.dimensions[0] === rawEntry.columns &&\n\t\t\t\t\t\t\t\tmatched.dimensions[1] === 1 &&\n\t\t\t\t\t\t\t\tmatched.dimensions[2] === rawEntry.rows)\n\t\t\t\t\t\t: matched.dimensions.length === 2 &&\n\t\t\t\t\t\t\tmatched.dimensions[0] === rawEntry.columns &&\n\t\t\t\t\t\t\tmatched.dimensions[1] === rawEntry.rows\n\t\t\tif (!shapeMatches) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The section entry ${quoteFaultText(rawEntry.name)} has shape [${rawEntry.columns}, ${rawEntry.rows}]; the base tensor ${quoteFaultText(matched.name)} has [${matched.dimensions.join(', ')}].`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'BINDING',\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tname: matched.name,\n\t\t\t\t\t\t\tdimensions: [rawEntry.columns, rawEntry.rows],\n\t\t\t\t\t\t\texpected: matched.dimensions,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\ttargetedSections.set(matched.name, transformed)\n\t\t}\n\t}\n\tconst headerEntries: Array<readonly [string, unknown]> = []\n\tif (header.metadata !== undefined && Object.keys(header.metadata).length > 0) {\n\t\theaderEntries.push(['__metadata__', header.metadata])\n\t}\n\tconst plannedSafetensors: ReadonlyArray<{\n\t\treadonly name: string\n\t\treadonly dtype: SafetensorsFormat\n\t\treadonly shape: readonly number[]\n\t\treadonly byteLength: number\n\t}> = [\n\t\t...header.tensors.map((tensor) => ({\n\t\t\tname: tensor.name,\n\t\t\tdtype: tensor.format,\n\t\t\tshape: tensor.dimensions.toReversed(),\n\t\t\tbyteLength: computeTensorBytes(tensor),\n\t\t})),\n\t\t...appendedSections.map((appended) => ({\n\t\t\tname: appended.name,\n\t\t\tdtype: appended.format,\n\t\t\tshape: [appended.entry.rows, appended.entry.columns],\n\t\t\tbyteLength: appended.entry.values.length * GGUF_BLOCKS[appended.format].bytes,\n\t\t})),\n\t]\n\tlet outOffset = 0\n\tfor (let index = 0; index < plannedSafetensors.length; index += 1) {\n\t\tconst item = plannedSafetensors[index]\n\t\tif (item === undefined) continue\n\t\theaderEntries.push([\n\t\t\titem.name,\n\t\t\t{\n\t\t\t\tdtype: item.dtype,\n\t\t\t\tshape: item.shape,\n\t\t\t\tdata_offsets: [outOffset, outOffset + item.byteLength],\n\t\t\t},\n\t\t])\n\t\toutOffset += item.byteLength\n\t}\n\tconst headerBytes = UTF8_ENCODER.encode(JSON.stringify(Object.fromEntries(headerEntries)))\n\tif (headerBytes.byteLength > SAFETENSORS_HEADER_LIMIT) {\n\t\tthrow new InferError(\n\t\t\t`The merged safetensors header spans ${headerBytes.byteLength} bytes, past the ${SAFETENSORS_HEADER_LIMIT}-byte limit.`,\n\t\t\t{ code: 'FORMAT', context: { length: headerBytes.byteLength } },\n\t\t)\n\t}\n\tconst lengthPrefix = new Uint8Array(8)\n\tnew DataView(lengthPrefix.buffer).setBigUint64(0, BigInt(headerBytes.byteLength), true)\n\tyield lengthPrefix\n\tyield headerBytes\n\tfor (const tensor of header.tensors) {\n\t\tcheckSignal(signal, 'The safetensors merge')\n\t\tconst pair = scale === 0 ? undefined : targetedAdapters.get(tensor.name)\n\t\tconst patchEntry = targetedSections.get(tensor.name)\n\t\tconst srcStart = header.offset + tensor.offset\n\t\tconst totalBytes = computeTensorBytes(tensor)\n\t\tif (pair === undefined && patchEntry === undefined) {\n\t\t\tfor (let pos = 0; pos < totalBytes; pos += chunkBytes) {\n\t\t\t\tcheckSignal(signal, 'The safetensors merge')\n\t\t\t\tconst sliceLength = Math.min(chunkBytes, totalBytes - pos)\n\t\t\t\tyield await source.read(srcStart + pos, sliceLength, signal)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tconst columns = patchEntry?.columns ?? pair?.columns ?? 1\n\t\tconst rows = patchEntry?.rows ?? pair?.rows ?? 1\n\t\tconst factor = pair === undefined ? 0 : scale * (pair.alpha / pair.rank)\n\t\tconst rowBytes = columns * GGUF_BLOCKS[tensor.format].bytes\n\t\tfor (let rowStart = 0; rowStart < rows; rowStart += stripRows) {\n\t\t\tcheckSignal(signal, 'The safetensors merge')\n\t\t\tconst rowCount = Math.min(stripRows, rows - rowStart)\n\t\t\tconst baseStrip =\n\t\t\t\tpatchEntry !== undefined\n\t\t\t\t\t? patchEntry.values.slice(rowStart * columns, (rowStart + rowCount) * columns)\n\t\t\t\t\t: widenTensor(\n\t\t\t\t\t\t\tawait source.read(srcStart + rowStart * rowBytes, rowCount * rowBytes, signal),\n\t\t\t\t\t\t\ttensor.format,\n\t\t\t\t\t\t)\n\t\t\tconst merged =\n\t\t\t\tpair !== undefined ? addLoRAStrip(baseStrip, pair, rowStart, rowCount, factor) : baseStrip\n\t\t\tyield encodeSafetensorsValues(merged, tensor.format)\n\t\t}\n\t}\n\tfor (const appended of appendedSections) {\n\t\tconst { entry, format: outFormat } = appended\n\t\tfor (let rowStart = 0; rowStart < entry.rows; rowStart += stripRows) {\n\t\t\tcheckSignal(signal, 'The safetensors merge')\n\t\t\tconst rowCount = Math.min(stripRows, entry.rows - rowStart)\n\t\t\tconst strip = entry.values.slice(\n\t\t\t\trowStart * entry.columns,\n\t\t\t\t(rowStart + rowCount) * entry.columns,\n\t\t\t)\n\t\t\tyield encodeSafetensorsValues(strip, outFormat)\n\t\t}\n\t}\n}\n\n/**\n * Streams a LoRA- or section-merged (or combined) GGUF v3 file from a base GGUF\n * `ByteSourceInterface`, keeping untargeted quantized tensors unchanged and memory strictly\n * bounded.\n *\n * @remarks\n * Reads only the base GGUF header through `@orkestrel/infer`'s `readGGUF`, validates architecture,\n * adapter binding (`checkAdapterBinding`), and section binding (`checkSectionBinding`) before\n * yielding any byte, copies all metadata verbatim, streams untargeted quantized tensors (`Q8_0`,\n * `Q4_K`, `Q6_K`, `Q5_0`, and float formats) byte-for-byte unchanged in `chunk`-byte slices, and\n * replaces full-rank `section` tensors, adds scaled LoRA `adapter` deltas, or both row-strip by\n * row-strip into `format` (`'F32'` default, `'BF16'`, `'Q8_0'`, or `'Q4_K'`) aligned to the file's\n * GGUF alignment. 1D section tensors (normalization gains, biases, and decay factors) and 4-tap\n * convolutions keep `'F32'` when `format` is quantized so `@orkestrel/infer` and `llama.cpp` load\n * them cleanly. When both `section` and `adapter` target the same tensor, `section` replaces the\n * base weight first and `adapter` adds its scaled delta on top.\n *\n * @param options - The base byte source, optional adapter and section, output format, optional base/scale, slice sizes, and signal\n * @returns An async generator yielding merged GGUF v3 file chunks\n *\n * @example\n * ```ts\n * for await (const chunk of mergeGGUF({ source, adapter, section, format: 'Q8_0' })) {\n * \tawait sink.write(chunk)\n * }\n * ```\n */\nexport async function* mergeGGUF(\n\toptions: MergeGGUFOptions,\n): AsyncGenerator<Uint8Array<ArrayBuffer>, void, void> {\n\tconst { source, adapter, section, base, signal } = options\n\tcheckSignal(signal, 'The GGUF merge')\n\tif (adapter === undefined && section === undefined) {\n\t\tthrow new InferError('The GGUF merge requires at least one of adapter or section.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tif (adapter !== undefined && section !== undefined && adapter.family !== section.family) {\n\t\tthrow new InferError(\n\t\t\t`The adapter targets family ${quoteFaultText(adapter.family)}, while the section targets ${quoteFaultText(section.family)}.`,\n\t\t\t{ code: 'BINDING', context: { adapter: adapter.family, section: section.family } },\n\t\t)\n\t}\n\tconst format: MergeGGUFFormat = options.format ?? 'F32'\n\tif (!isMergeGGUFFormat(format)) {\n\t\tthrow new InferError(\n\t\t\t`The GGUF merge format ${quoteFaultText(String(format))} must be \"F32\", \"BF16\", \"Q8_0\", or \"Q4_K\".`,\n\t\t\t{ code: 'ARGUMENT', context: { format } },\n\t\t)\n\t}\n\tconst scale = options.scale ?? adapter?.scale ?? 1\n\tif (!isFiniteNumber(scale)) {\n\t\tthrow new InferError(`The merge scale ${scale} must be a finite number.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { scale },\n\t\t})\n\t}\n\tconst chunkBytes = options.chunk ?? MERGE_CHUNK_BYTES\n\tif (!isSafeInteger(chunkBytes) || chunkBytes < 1) {\n\t\tthrow new InferError(`The merge chunk size ${chunkBytes} must be a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { chunk: chunkBytes },\n\t\t})\n\t}\n\tconst stripRows = options.strip ?? MERGE_ROW_STRIP\n\tif (!isSafeInteger(stripRows) || stripRows < 1) {\n\t\tthrow new InferError(`The merge strip height ${stripRows} must be a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { strip: stripRows },\n\t\t})\n\t}\n\tconst headerSummary = await readGGUF(source, signal).then((header) => {\n\t\tconst architecture = readArchitecture(header.metadata)\n\t\tif (adapter !== undefined) checkAdapterBinding(adapter, architecture, base)\n\t\tif (section !== undefined) checkSectionBinding(section, architecture, base)\n\t\tconst alignment = resolveAlignment(header.metadata.get(GGUF_KEYS.alignment)) ?? GGUF_ALIGNMENT\n\t\treturn {\n\t\t\talignment,\n\t\t\tmetadataCount: header.metadata.size,\n\t\t\toffset: header.offset,\n\t\t\ttensors: header.tensors,\n\t\t}\n\t})\n\tconst { alignment, metadataCount, offset: srcOffset, tensors: srcTensors } = headerSummary\n\tconst byName = new Map<string, GGUFTensor>(srcTensors.map((tensor) => [tensor.name, tensor]))\n\tconst targetedAdapters = new Map<string, AdapterPair>()\n\tif (adapter !== undefined) {\n\t\tfor (const pair of adapter.pairs) {\n\t\t\tconst baseTensor = byName.get(pair.name)\n\t\t\tif (baseTensor === undefined) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The base GGUF file lacks target tensor ${quoteFaultText(pair.name)}.`,\n\t\t\t\t\t{ code: 'BINDING', context: { name: pair.name } },\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (\n\t\t\t\tbaseTensor.dimensions.length !== 2 ||\n\t\t\t\tbaseTensor.dimensions[0] !== pair.columns ||\n\t\t\t\tbaseTensor.dimensions[1] !== pair.rows\n\t\t\t) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The adapter pair ${quoteFaultText(pair.name)} has shape [${pair.columns}, ${pair.rows}]; the base GGUF tensor has [${baseTensor.dimensions.join(', ')}].`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'BINDING',\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tname: pair.name,\n\t\t\t\t\t\t\tdimensions: [pair.columns, pair.rows],\n\t\t\t\t\t\t\texpected: baseTensor.dimensions,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (!MERGE_SOURCE_FORMATS.includes(baseTensor.format)) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The targeted base GGUF tensor ${quoteFaultText(pair.name)} uses unsupported format ${quoteFaultText(baseTensor.format)}.`,\n\t\t\t\t\t{ code: 'UNSUPPORTED', context: { name: pair.name, format: baseTensor.format } },\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst block = GGUF_BLOCKS[baseTensor.format]\n\t\t\tif (pair.columns % block.elements !== 0) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The targeted base GGUF tensor ${quoteFaultText(pair.name)} has width ${pair.columns}, not divisible by ${block.elements}.`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'FORMAT',\n\t\t\t\t\t\tcontext: { name: pair.name, columns: pair.columns, block: block.elements },\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst outBlock = GGUF_BLOCKS[format]\n\t\t\tif (scale !== 0 && pair.columns % outBlock.elements !== 0) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The merged ${format} tensor ${quoteFaultText(pair.name)} has width ${pair.columns}, not divisible by ${outBlock.elements}.`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'FORMAT',\n\t\t\t\t\t\tcontext: { name: pair.name, columns: pair.columns, format, block: outBlock.elements },\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\ttargetedAdapters.set(pair.name, pair)\n\t\t}\n\t}\n\tconst targetedSections = new Map<string, SectionEntry>()\n\tconst appendedSections: SectionEntry[] = []\n\tif (section !== undefined) {\n\t\tfor (const entry of section.entries) {\n\t\t\tconst baseTensor = byName.get(entry.name)\n\t\t\tif (baseTensor === undefined) {\n\t\t\t\tif (entry.name === 'output.weight') {\n\t\t\t\t\tconst embed = byName.get('token_embd.weight')\n\t\t\t\t\tif (\n\t\t\t\t\t\tembed !== undefined &&\n\t\t\t\t\t\tembed.dimensions.length === 2 &&\n\t\t\t\t\t\tembed.dimensions[0] === entry.columns &&\n\t\t\t\t\t\tembed.dimensions[1] === entry.rows\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst outBlock = GGUF_BLOCKS[format]\n\t\t\t\t\t\tif (entry.columns % outBlock.elements !== 0) {\n\t\t\t\t\t\t\tthrow new InferError(\n\t\t\t\t\t\t\t\t`The merged ${format} tensor ${quoteFaultText(entry.name)} has width ${entry.columns}, not divisible by ${outBlock.elements}.`,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcode: 'FORMAT',\n\t\t\t\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\t\t\t\tname: entry.name,\n\t\t\t\t\t\t\t\t\t\tcolumns: entry.columns,\n\t\t\t\t\t\t\t\t\t\tformat,\n\t\t\t\t\t\t\t\t\t\tblock: outBlock.elements,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tappendedSections.push(entry)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The base GGUF file lacks target tensor ${quoteFaultText(entry.name)}.`,\n\t\t\t\t\t{ code: 'BINDING', context: { name: entry.name } },\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst dimsMatch =\n\t\t\t\tentry.rows === 1\n\t\t\t\t\t? baseTensor.dimensions.length === 1 && baseTensor.dimensions[0] === entry.columns\n\t\t\t\t\t: baseTensor.dimensions.length === 2 &&\n\t\t\t\t\t\tbaseTensor.dimensions[0] === entry.columns &&\n\t\t\t\t\t\tbaseTensor.dimensions[1] === entry.rows\n\t\t\tif (!dimsMatch) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The section entry ${quoteFaultText(entry.name)} has shape [${entry.columns}, ${entry.rows}]; the base GGUF tensor has [${baseTensor.dimensions.join(', ')}].`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'BINDING',\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tname: entry.name,\n\t\t\t\t\t\t\tdimensions: [entry.columns, entry.rows],\n\t\t\t\t\t\t\texpected: baseTensor.dimensions,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst keepFloat = entry.rows === 1 || entry.target === 'ssm_conv1d'\n\t\t\tconst outBlock = GGUF_BLOCKS[format]\n\t\t\tif (!keepFloat && entry.columns % outBlock.elements !== 0) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The merged ${format} tensor ${quoteFaultText(entry.name)} has width ${entry.columns}, not divisible by ${outBlock.elements}.`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'FORMAT',\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tname: entry.name,\n\t\t\t\t\t\t\tcolumns: entry.columns,\n\t\t\t\t\t\t\tformat,\n\t\t\t\t\t\t\tblock: outBlock.elements,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\ttargetedSections.set(entry.name, entry)\n\t\t}\n\t}\n\tconst plannedGGUF: ReadonlyArray<{\n\t\treadonly name: string\n\t\treadonly dimensions: readonly number[]\n\t\treadonly format: GGUFFormat\n\t}> = [\n\t\t...srcTensors.map((tensor) => {\n\t\t\tconst hasAdapter = scale !== 0 && targetedAdapters.has(tensor.name)\n\t\t\tconst patchEntry = targetedSections.get(tensor.name)\n\t\t\tconst keepFloat =\n\t\t\t\tpatchEntry !== undefined && (patchEntry.rows === 1 || patchEntry.target === 'ssm_conv1d')\n\t\t\tconst nextFormat: GGUFFormat =\n\t\t\t\thasAdapter || patchEntry !== undefined\n\t\t\t\t\t? keepFloat && (format === 'Q8_0' || format === 'Q4_K' || format === 'BF16')\n\t\t\t\t\t\t? 'F32'\n\t\t\t\t\t\t: format\n\t\t\t\t\t: tensor.format\n\t\t\treturn { name: tensor.name, dimensions: tensor.dimensions, format: nextFormat }\n\t\t}),\n\t\t...appendedSections.map((entry) => ({\n\t\t\tname: entry.name,\n\t\t\tdimensions: [entry.columns, entry.rows],\n\t\t\tformat,\n\t\t})),\n\t]\n\tconst outTensors: GGUFTensor[] = []\n\tlet outOffset = 0\n\tfor (let index = 0; index < plannedGGUF.length; index += 1) {\n\t\tconst spec = plannedGGUF[index]\n\t\tif (spec === undefined) continue\n\t\tconst next: GGUFTensor = {\n\t\t\tname: spec.name,\n\t\t\tdimensions: spec.dimensions,\n\t\t\tformat: spec.format,\n\t\t\toffset: outOffset,\n\t\t}\n\t\toutTensors.push(next)\n\t\toutOffset = alignOffset(outOffset + computeTensorBytes(next), alignment)\n\t}\n\tconst srcTensorSection = joinBytes(srcTensors.map((tensor) => encodeGGUFTensor(tensor)))\n\tconst tailStart = Math.max(24, srcOffset - srcTensorSection.byteLength - alignment)\n\tconst tail = await source.read(tailStart, srcOffset - tailStart, signal)\n\tconst maxCandidate = tail.byteLength - srcTensorSection.byteLength\n\tconst matchedOffset = Array.from({ length: maxCandidate + 1 }, (_, index) => index).find(\n\t\t(candidate) => {\n\t\t\tif (\n\t\t\t\talignOffset(tailStart + candidate + srcTensorSection.byteLength, alignment) !== srcOffset\n\t\t\t) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tfor (let byteIndex = 0; byteIndex < srcTensorSection.byteLength; byteIndex += 1) {\n\t\t\t\tif (tail[candidate + byteIndex] !== srcTensorSection[byteIndex]) return false\n\t\t\t}\n\t\t\tfor (\n\t\t\t\tlet padIndex = candidate + srcTensorSection.byteLength;\n\t\t\t\tpadIndex < tail.byteLength;\n\t\t\t\tpadIndex += 1\n\t\t\t) {\n\t\t\t\tif (tail[padIndex] !== 0) return false\n\t\t\t}\n\t\t\treturn true\n\t\t},\n\t)\n\tif (matchedOffset === undefined) {\n\t\tthrow new InferError('The base GGUF header tensor table could not be located verbatim.', {\n\t\t\tcode: 'FORMAT',\n\t\t})\n\t}\n\tconst metadataEnd = tailStart + matchedOffset\n\tyield joinBytes([\n\t\tencodeGGUFNumbers('uint32', [GGUF_MAGIC, GGUF_VERSION]),\n\t\tencodeGGUFBigInts('uint64', [BigInt(outTensors.length), BigInt(metadataCount)]),\n\t])\n\tfor (let pos = 24; pos < metadataEnd; pos += chunkBytes) {\n\t\tcheckSignal(signal, 'The GGUF merge')\n\t\tconst sliceLength = Math.min(chunkBytes, metadataEnd - pos)\n\t\tyield await source.read(pos, sliceLength, signal)\n\t}\n\tconst outTensorSection = joinBytes(outTensors.map((tensor) => encodeGGUFTensor(tensor)))\n\tyield outTensorSection\n\tconst headerLength = metadataEnd + outTensorSection.byteLength\n\tconst headerPadded = alignOffset(headerLength, alignment)\n\tif (headerPadded > headerLength) {\n\t\tyield new Uint8Array(headerPadded - headerLength)\n\t}\n\tfor (let index = 0; index < srcTensors.length; index += 1) {\n\t\tcheckSignal(signal, 'The GGUF merge')\n\t\tconst srcTensor = srcTensors[index]\n\t\tconst outTensor = outTensors[index]\n\t\tif (srcTensor === undefined || outTensor === undefined) continue\n\t\tconst srcStart = srcOffset + srcTensor.offset\n\t\tconst pair = scale === 0 ? undefined : targetedAdapters.get(srcTensor.name)\n\t\tconst patchEntry = targetedSections.get(srcTensor.name)\n\t\tconst outBytes = computeTensorBytes(outTensor)\n\t\tif (pair === undefined && patchEntry === undefined) {\n\t\t\tconst srcBytes = computeTensorBytes(srcTensor)\n\t\t\tfor (let pos = 0; pos < srcBytes; pos += chunkBytes) {\n\t\t\t\tcheckSignal(signal, 'The GGUF merge')\n\t\t\t\tconst sliceLength = Math.min(chunkBytes, srcBytes - pos)\n\t\t\t\tyield await source.read(srcStart + pos, sliceLength, signal)\n\t\t\t}\n\t\t} else {\n\t\t\tconst columns = patchEntry?.columns ?? pair?.columns ?? 1\n\t\t\tconst rows = patchEntry?.rows ?? pair?.rows ?? 1\n\t\t\tconst factor = pair === undefined ? 0 : scale * (pair.alpha / pair.rank)\n\t\t\tconst block = GGUF_BLOCKS[srcTensor.format]\n\t\t\tconst rowBytes = (columns / block.elements) * block.bytes\n\t\t\tconst targetFormat: MergeGGUFFormat = isMergeGGUFFormat(outTensor.format)\n\t\t\t\t? outTensor.format\n\t\t\t\t: 'F32'\n\t\t\tfor (let rowStart = 0; rowStart < rows; rowStart += stripRows) {\n\t\t\t\tcheckSignal(signal, 'The GGUF merge')\n\t\t\t\tconst rowCount = Math.min(stripRows, rows - rowStart)\n\t\t\t\tconst baseStrip =\n\t\t\t\t\tpatchEntry !== undefined\n\t\t\t\t\t\t? patchEntry.values.slice(rowStart * columns, (rowStart + rowCount) * columns)\n\t\t\t\t\t\t: widenTensor(\n\t\t\t\t\t\t\t\tawait source.read(srcStart + rowStart * rowBytes, rowCount * rowBytes, signal),\n\t\t\t\t\t\t\t\tsrcTensor.format,\n\t\t\t\t\t\t\t)\n\t\t\t\tconst merged =\n\t\t\t\t\tpair !== undefined ? addLoRAStrip(baseStrip, pair, rowStart, rowCount, factor) : baseStrip\n\t\t\t\tyield encodeGGUFValues(merged, targetFormat)\n\t\t\t}\n\t\t}\n\t\tconst pad = alignOffset(outBytes, alignment) - outBytes\n\t\tif (pad > 0) yield new Uint8Array(pad)\n\t}\n\tfor (let index = 0; index < appendedSections.length; index += 1) {\n\t\tconst entry = appendedSections[index]\n\t\tconst outTensor = outTensors[srcTensors.length + index]\n\t\tif (entry === undefined || outTensor === undefined) continue\n\t\tconst outBytes = computeTensorBytes(outTensor)\n\t\tfor (let rowStart = 0; rowStart < entry.rows; rowStart += stripRows) {\n\t\t\tcheckSignal(signal, 'The GGUF merge')\n\t\t\tconst rowCount = Math.min(stripRows, entry.rows - rowStart)\n\t\t\tconst strip = entry.values.slice(\n\t\t\t\trowStart * entry.columns,\n\t\t\t\t(rowStart + rowCount) * entry.columns,\n\t\t\t)\n\t\t\tyield encodeGGUFValues(strip, format)\n\t\t}\n\t\tconst pad = alignOffset(outBytes, alignment) - outBytes\n\t\tif (pad > 0) yield new Uint8Array(pad)\n\t}\n}\n\n/**\n * Scores labelled development rows with an initial head, traces every misclassified row through\n * `traceHead`, refits a replacement head through `Trainer` over augmented training rows, and reports labelled\n * flips through `countFlips`.\n *\n * @remarks\n * Validates `record` binding (`BINDING`), `record.pooling === 'mean'`, `record.labels` parity with\n * `question`, `weights`, `calibration`, `train`, `development`, and optional `augment` before any\n * backbone forward. Each development row is embedded once, scored before and after refitting, and\n * misclassified rows are traced in row order. When `augment` is omitted, each misclassified\n * development row is appended `weight` times (default `1`), carrying `group: row.group ?? \"refit:<index>\"`\n * whenever `weight > 1` so duplicates remain in one cross-validation fold. Rejects with `ABORT`\n * when `signal` aborts.\n *\n * @param options - The backbone, question, initial head, training rows, development rows, and trainer options\n * @returns The refitted trainer result, misclassified row traces, flip counts, augmented rows, and predictions\n *\n * @example\n * ```ts\n * const refit = await refitTracedHead({\n * \tbackbone,\n * \tquestion,\n * \trecord,\n * \tweights,\n * \ttrain,\n * \tdevelopment,\n * \tfolds: 3,\n * })\n * refit.flips.total === development.length // true\n * ```\n */\nexport async function refitTracedHead(options: RefitHeadOptions): Promise<RefitHeadResult> {\n\tif (!isRecord(options)) {\n\t\tthrow new InferError('The head refit options must be a plain object.', { code: 'ARGUMENT' })\n\t}\n\tconst {\n\t\tbackbone,\n\t\tquestion,\n\t\trecord,\n\t\tweights,\n\t\ttrain,\n\t\tdevelopment,\n\t\taugment,\n\t\ttarget,\n\t\tfolds,\n\t\trepeats,\n\t\tseed,\n\t\tpenalties,\n\t\tthreads,\n\t\tsignal,\n\t} = options\n\tcheckSignal(signal, 'The head refit')\n\tconst weight = options.weight ?? 1\n\tif (!matchesCount(weight, 1)) {\n\t\tthrow new InferError(`The refit augmentation weight is ${weight}; pass a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { weight },\n\t\t})\n\t}\n\tif (record.base !== backbone.digest) {\n\t\tthrow new InferError(\n\t\t\t`The head binds base ${quoteFaultText(record.base)}, not backbone ${quoteFaultText(backbone.digest)}.`,\n\t\t\t{ code: 'BINDING', context: { expected: record.base, actual: backbone.digest } },\n\t\t)\n\t}\n\tif (record.pooling !== 'mean') {\n\t\tthrow new InferError(\n\t\t\t`The head pooling is ${quoteFaultText(record.pooling)}; traced refitting requires mean pooling.`,\n\t\t\t{ code: 'ARGUMENT', context: { pooling: record.pooling } },\n\t\t)\n\t}\n\tconst trainerOptions: TrainerOptions = {\n\t\tbackbone,\n\t\tdepth: record.depth,\n\t\tquestion,\n\t\t...(target === undefined ? {} : { target }),\n\t\t...(folds === undefined ? {} : { folds }),\n\t\t...(repeats === undefined ? {} : { repeats }),\n\t\t...(seed === undefined ? {} : { seed }),\n\t\t...(penalties === undefined ? {} : { penalties }),\n\t\t...(threads === undefined ? {} : { threads }),\n\t}\n\tconst settings = resolveTrainerSettings(trainerOptions)\n\tconst classes = settings.labels.length\n\tif (\n\t\trecord.labels.length !== classes ||\n\t\trecord.labels.some((label, index) => label !== settings.labels[index])\n\t) {\n\t\tthrow new InferError(\n\t\t\t'The head record labels do not match the candidate labels of the question.',\n\t\t\t{ code: 'ARGUMENT', context: { record: record.labels.length, question: classes } },\n\t\t)\n\t}\n\tcheckHeadWeights(weights, classes)\n\tconst { dimension } = backbone.architecture\n\tif (weights.mean.length !== dimension) {\n\t\tthrow new InferError(\n\t\t\t`The head weights have width ${weights.mean.length}; the backbone embeds width ${dimension}.`,\n\t\t\t{ code: 'ARGUMENT', context: { classes, dimension, width: weights.mean.length } },\n\t\t)\n\t}\n\tif (\n\t\t!Number.isFinite(record.calibration.temperature) ||\n\t\trecord.calibration.temperature <= 0 ||\n\t\trecord.calibration.bias.length !== classes ||\n\t\t!record.calibration.bias.every(Number.isFinite)\n\t) {\n\t\tthrow new InferError(\n\t\t\t`The head calibration requires a positive finite temperature and ${classes} finite label biases.`,\n\t\t\t{ code: 'ARGUMENT', context: { classes } },\n\t\t)\n\t}\n\tconst admittedTrain = admitRows(train)\n\tconst admittedDev = admitRows(development)\n\tconst admittedAugment = augment === undefined ? undefined : admitRows(augment)\n\tconst devLabelIndexes = inferRowLabels(admittedDev, settings)\n\tconst expected = devLabelIndexes.map((index) => settings.labels[index] ?? '')\n\tconst devTokens = encodeStates(admittedDev, backbone.tokenizer, backbone.limit)\n\tconst features: Float32Array[] = []\n\tfor (const tokens of devTokens) {\n\t\tcheckSignal(signal, 'The head refit')\n\t\tfeatures.push(await backbone.embed(tokens, record.depth, signal))\n\t}\n\tconst initialDistributions = computeDistributions(\n\t\tcomputeHeadLogits(weights, features),\n\t\tclasses,\n\t\trecord.calibration,\n\t\tbackbone.strict,\n\t)\n\tconst before = admittedDev.map((_, rowIndex) => {\n\t\tconst offset = rowIndex * classes\n\t\tconst scores = Array.from({ length: classes }, (__, labelIndex) => ({\n\t\t\tlabelIndex,\n\t\t\tscore: initialDistributions[offset + labelIndex] ?? Number.NEGATIVE_INFINITY,\n\t\t}))\n\t\tconst winner = scores.reduce((best, entry) => (entry.score > best.score ? entry : best))\n\t\treturn settings.labels[winner.labelIndex] ?? ''\n\t})\n\tconst mistakes = expected.flatMap((label, index) => (before[index] === label ? [] : [index]))\n\tconst traces: RefitHeadTrace[] = []\n\tfor (const index of mistakes) {\n\t\tcheckSignal(signal, 'The head refit')\n\t\tconst row = admittedDev[index]\n\t\tif (row === undefined) continue\n\t\tconst trace = await traceHead({\n\t\t\tbackbone,\n\t\t\trecord,\n\t\t\tweights,\n\t\t\tstate: row.state,\n\t\t\t...(signal === undefined ? {} : { signal }),\n\t\t})\n\t\ttraces.push({\n\t\t\tindex,\n\t\t\trow,\n\t\t\texpected: expected[index] ?? '',\n\t\t\tpredicted: before[index] ?? '',\n\t\t\ttrace,\n\t\t})\n\t}\n\tconst addedRows: readonly TrainerRow[] =\n\t\tadmittedAugment !== undefined\n\t\t\t? admittedAugment\n\t\t\t: mistakes.flatMap((index) => {\n\t\t\t\t\tconst row = admittedDev[index]\n\t\t\t\t\tif (row === undefined) return []\n\t\t\t\t\tif (weight === 1) return [row]\n\t\t\t\t\tconst group = row.group ?? `refit:${index}`\n\t\t\t\t\treturn Array.from({ length: weight }, () => ({\n\t\t\t\t\t\tstate: row.state,\n\t\t\t\t\t\tlabel: row.label,\n\t\t\t\t\t\tgroup,\n\t\t\t\t\t}))\n\t\t\t\t})\n\tconst augmented: readonly TrainerRow[] = [...admittedTrain, ...addedRows]\n\tconst trainer = new Trainer(trainerOptions)\n\tconst result = await trainer.execute(augmented, signal)\n\tconst refittedDistributions = computeDistributions(\n\t\tcomputeHeadLogits(result.weights, features),\n\t\tclasses,\n\t\tresult.record.calibration,\n\t\tbackbone.strict,\n\t)\n\tconst after = admittedDev.map((_, rowIndex) => {\n\t\tconst offset = rowIndex * classes\n\t\tconst scores = Array.from({ length: classes }, (__, labelIndex) => ({\n\t\t\tlabelIndex,\n\t\t\tscore: refittedDistributions[offset + labelIndex] ?? Number.NEGATIVE_INFINITY,\n\t\t}))\n\t\tconst winner = scores.reduce((best, entry) => (entry.score > best.score ? entry : best))\n\t\treturn settings.labels[winner.labelIndex] ?? ''\n\t})\n\tconst flips = countFlips({ expected, before, after })\n\treturn { result, traces, flips, augmented, before, after }\n}\n\n/**\n * Sweeps candidate LoRA scales through zero-copy `adapter.scaled(scale)` views over a held fold\n * verified against group leaks through `checkFolds`, selecting the highest-scoring scale with zero\n * negative flips whenever one exists.\n *\n * @remarks\n * Validates `adapter`, `rows`, `scales`, `folds`, `fold`, `seed`, and optional `assignment` through\n * `checkFolds` before invoking `evaluate` so leaked groups reject immediately with `ARGUMENT` and\n * zero evaluations. When `baseline` is omitted, `adapter.scaled(0)` is evaluated once and reused if\n * `0` also appears in `scales`. Selects the scale maximizing `score` among candidates with\n * `flips.negative === 0` (`safe: true`), breaking ties by higher `flips.positive` then smaller\n * `Math.abs(scale)`. When every candidate causes negative flips (`safe: false`), selects the scale\n * with the fewest negative flips, breaking ties by highest `score` then smaller `Math.abs(scale)`.\n *\n * @param options - The adapter, rows, held-fold evaluator, candidate scales, fold settings, and signal\n * @returns The selected scale, zero-copy scaled adapter view, flip report, safety flag, and all candidates\n *\n * @example\n * ```ts\n * const calibrated = await calibrateAdapter({\n * \tadapter,\n * \trows,\n * \tfolds: 3,\n * \tevaluate: (scaled, held) => ({ predictions: held.map((row) => row.label) }),\n * })\n * calibrated.safe // true\n * ```\n */\nexport async function calibrateAdapter(\n\toptions: AdapterCalibrationOptions,\n): Promise<AdapterCalibrationResult> {\n\tif (!isRecord(options)) {\n\t\tthrow new InferError('The adapter calibration options must be a plain object.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tconst { adapter, rows, evaluate, signal } = options\n\tcheckSignal(signal, 'The adapter calibration')\n\tcheckAdapterOptions(adapter)\n\tif (typeof adapter.scaled !== 'function') {\n\t\tthrow new InferError('The adapter must expose a scaled(scale) zero-copy view method.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tif (typeof evaluate !== 'function') {\n\t\tthrow new InferError('The adapter calibration evaluate option must be a function.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tconst scales = options.scales ?? ADAPTER_CALIBRATION_SCALES\n\tif (\n\t\t!isArray(scales) ||\n\t\tscales.length === 0 ||\n\t\t!scales.every((scale) => isFiniteNumber(scale)) ||\n\t\tnew Set(scales).size !== scales.length\n\t) {\n\t\tthrow new InferError(\n\t\t\t'The adapter calibration scales must be a non-empty array of unique finite numbers.',\n\t\t\t{ code: 'ARGUMENT', context: { scales: isArray(scales) ? scales.length : -1 } },\n\t\t)\n\t}\n\tconst folds = options.folds ?? TRAINER_FOLDS\n\tif (!matchesCount(folds, 2)) {\n\t\tthrow new InferError(\n\t\t\t`The adapter calibration runs ${folds} folds; pass an integer of at least 2.`,\n\t\t\t{ code: 'ARGUMENT', context: { folds } },\n\t\t)\n\t}\n\tconst fold = options.fold ?? 0\n\tif (!isSafeInteger(fold) || fold < 0 || fold >= folds) {\n\t\tthrow new InferError(\n\t\t\t`The held fold index is ${fold}; pass an integer from 0 to ${folds - 1}.`,\n\t\t\t{ code: 'ARGUMENT', context: { fold, folds } },\n\t\t)\n\t}\n\tconst seed = options.seed ?? TRAINER_SEED\n\tif (!Number.isSafeInteger(seed)) {\n\t\tthrow new InferError(`The adapter calibration seed is ${seed}; pass a safe integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { seed },\n\t\t})\n\t}\n\tconst admitted = admitRows(rows)\n\tconst strata = inferStrata(admitted)\n\tconst distinctLabels = [...new Set(admitted.map((row) => row.label))]\n\tconst groups = admitted.some((row) => row.group !== undefined)\n\t\t? admitted.map((row) => row.group)\n\t\t: undefined\n\tconst assignment: readonly number[] =\n\t\toptions.assignment === undefined\n\t\t\t? assignFolds(strata, folds, seed, groups)\n\t\t\t: [...options.assignment]\n\tif (\n\t\tassignment.length !== admitted.length ||\n\t\t!assignment.every((value) => isSafeInteger(value) && value >= 0 && value < folds)\n\t) {\n\t\tthrow new InferError(\n\t\t\t`The fold assignment must hold ${admitted.length} integer fold indexes from 0 to ${folds - 1}.`,\n\t\t\t{\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\tcontext: { assignment: assignment.length, rows: admitted.length, folds },\n\t\t\t},\n\t\t)\n\t}\n\tconst foldSettings: TrainerSettings = {\n\t\tdepth: 1,\n\t\tlabels: distinctLabels,\n\t\ttarget: undefined,\n\t\tfolds,\n\t\trepeats: 1,\n\t\tseed,\n\t\tpenalties: [0],\n\t}\n\tcheckFolds(assignment, strata, foldSettings, groups)\n\tconst held = assignment.flatMap((value, index) => (value === fold ? [index] : []))\n\tconst heldRows = collectRows(admitted, held)\n\tconst expected: readonly string[] =\n\t\toptions.expected === undefined ? heldRows.map((row) => row.label) : [...options.expected]\n\tif (expected.length !== held.length || !expected.every(isString)) {\n\t\tthrow new InferError(\n\t\t\t`The expected held-fold labels must hold ${held.length} strings matching the held fold.`,\n\t\t\t{ code: 'ARGUMENT', context: { expected: expected.length, held: held.length } },\n\t\t)\n\t}\n\tconst baselineProvided = options.baseline\n\tif (\n\t\tbaselineProvided !== undefined &&\n\t\t(!isArray(baselineProvided) ||\n\t\t\tbaselineProvided.length !== held.length ||\n\t\t\t!baselineProvided.every(isString))\n\t) {\n\t\tthrow new InferError(\n\t\t\t`The baseline held-fold predictions must hold ${held.length} strings matching the held fold.`,\n\t\t\t{\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\tcontext: {\n\t\t\t\t\tbaseline: isArray(baselineProvided) ? baselineProvided.length : -1,\n\t\t\t\t\theld: held.length,\n\t\t\t\t},\n\t\t\t},\n\t\t)\n\t}\n\tconst cachedZero =\n\t\tbaselineProvided === undefined\n\t\t\t? await evaluate(adapter.scaled(0), heldRows, held, signal)\n\t\t\t: undefined\n\tif (cachedZero !== undefined) {\n\t\tif (\n\t\t\t!isRecord(cachedZero) ||\n\t\t\t!isArray(cachedZero.predictions) ||\n\t\t\tcachedZero.predictions.length !== held.length ||\n\t\t\t!cachedZero.predictions.every(isString)\n\t\t) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The baseline evaluation at scale 0 must return ${held.length} string predictions.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { scale: 0, held: held.length } },\n\t\t\t)\n\t\t}\n\t\tif (cachedZero.score !== undefined && !isFiniteNumber(cachedZero.score)) {\n\t\t\tthrow new InferError('The baseline evaluation score at scale 0 must be a finite number.', {\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\tcontext: { scale: 0 },\n\t\t\t})\n\t\t}\n\t}\n\tconst baseline: readonly string[] =\n\t\tbaselineProvided === undefined ? [...(cachedZero?.predictions ?? [])] : [...baselineProvided]\n\tconst candidates: AdapterScaleCandidate[] = []\n\tfor (const scale of scales) {\n\t\tcheckSignal(signal, 'The adapter calibration')\n\t\tconst evaluation =\n\t\t\tscale === 0 && cachedZero !== undefined\n\t\t\t\t? cachedZero\n\t\t\t\t: await evaluate(adapter.scaled(scale), heldRows, held, signal)\n\t\tif (\n\t\t\t!isRecord(evaluation) ||\n\t\t\t!isArray(evaluation.predictions) ||\n\t\t\tevaluation.predictions.length !== held.length ||\n\t\t\t!evaluation.predictions.every(isString)\n\t\t) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The evaluation at scale ${scale} must return ${held.length} string predictions.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { scale, held: held.length } },\n\t\t\t)\n\t\t}\n\t\tif (evaluation.score !== undefined && !isFiniteNumber(evaluation.score)) {\n\t\t\tthrow new InferError(`The evaluation score at scale ${scale} must be a finite number.`, {\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\tcontext: { scale },\n\t\t\t})\n\t\t}\n\t\tconst predictions = [...evaluation.predictions]\n\t\tconst flips = countFlips({ expected, before: baseline, after: predictions })\n\t\tconst score = evaluation.score ?? (flips.kept + flips.positive) / flips.total\n\t\tcandidates.push({ scale, score, flips, predictions })\n\t}\n\tconst zeroFlip = candidates.filter((entry) => entry.flips.negative === 0)\n\tconst safe = zeroFlip.length > 0\n\tconst pool = safe ? zeroFlip : candidates\n\tconst chosen = pool.reduce((best, candidate) => {\n\t\tif (!safe && candidate.flips.negative !== best.flips.negative) {\n\t\t\treturn candidate.flips.negative < best.flips.negative ? candidate : best\n\t\t}\n\t\tif (candidate.score !== best.score) {\n\t\t\treturn candidate.score > best.score ? candidate : best\n\t\t}\n\t\tif (candidate.flips.positive !== best.flips.positive) {\n\t\t\treturn candidate.flips.positive > best.flips.positive ? candidate : best\n\t\t}\n\t\tconst bestDistance = Math.abs(best.scale)\n\t\tconst candidateDistance = Math.abs(candidate.scale)\n\t\tif (candidateDistance !== bestDistance) {\n\t\t\treturn candidateDistance < bestDistance ? candidate : best\n\t\t}\n\t\treturn candidate.scale < best.scale ? candidate : best\n\t})\n\treturn {\n\t\tscale: chosen.scale,\n\t\tadapter: adapter.scaled(chosen.scale),\n\t\tscore: chosen.score,\n\t\tflips: chosen.flips,\n\t\tsafe,\n\t\theld,\n\t\tassignment,\n\t\tcandidates,\n\t}\n}\n\n/**\n * Streams a bounded-memory weight comparison between two GGUF `ByteSourceInterface` files,\n * reporting per-tensor Frobenius norm, relative delta, max abs delta, and raw-byte identity.\n *\n * @remarks\n * Reads only the GGUF headers upfront and compares every tensor in `chunk`-byte slices and\n * `strip`-row widened strips without loading either full weight file into memory. Untouched tensors\n * with identical format and raw bytes report `exact: true`, `bytes: 0`, `frobenius: 0`,\n * `relative: 0`, and `maximum: 0`. Refuses mismatched tensor sets or dimensions with `BINDING`,\n * unsupported widened tensor formats with `UNSUPPORTED`, invalid chunk/strip sizes with `ARGUMENT`,\n * and aborted signals with `ABORT`.\n *\n * @param options - The baseline and candidate GGUF byte sources, optional slice bounds, and signal\n * @returns Per-tensor and aggregate Frobenius, relative, maximum, and exact-match statistics\n *\n * @example\n * ```ts\n * const diff = await diffWeights({ before: baseSource, after: mergedSource })\n * diff.unchanged + diff.changed === diff.tensors.length // true\n * ```\n */\nexport async function diffWeights(options: WeightDiffOptions): Promise<WeightDiffResult> {\n\tif (!isRecord(options)) {\n\t\tthrow new InferError(\n\t\t\t'The weight diff options must be a plain object carrying before and after.',\n\t\t\t{\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t},\n\t\t)\n\t}\n\tconst { before, after, signal } = options\n\tcheckSignal(signal, 'The weight diff')\n\tif (\n\t\t!isObject(before) ||\n\t\ttypeof Reflect.get(before, 'read') !== 'function' ||\n\t\t!isObject(after) ||\n\t\ttypeof Reflect.get(after, 'read') !== 'function'\n\t) {\n\t\tthrow new InferError(\n\t\t\t'The weight diff before and after inputs must implement ByteSourceInterface.',\n\t\t\t{ code: 'ARGUMENT' },\n\t\t)\n\t}\n\tconst chunkBytes = options.chunk ?? MERGE_CHUNK_BYTES\n\tif (!isSafeInteger(chunkBytes) || chunkBytes < 1) {\n\t\tthrow new InferError(`The weight diff chunk size ${chunkBytes} must be a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { chunk: chunkBytes },\n\t\t})\n\t}\n\tconst stripRows = options.strip ?? MERGE_ROW_STRIP\n\tif (!isSafeInteger(stripRows) || stripRows < 1) {\n\t\tthrow new InferError(`The weight diff strip height ${stripRows} must be a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { strip: stripRows },\n\t\t})\n\t}\n\tconst beforeHeader = await readGGUF(before, signal)\n\tconst afterHeader = await readGGUF(after, signal)\n\tconst afterByName = new Map<string, GGUFTensor>(\n\t\tafterHeader.tensors.map((tensor) => [tensor.name, tensor]),\n\t)\n\tconst beforeNames = new Set(beforeHeader.tensors.map((tensor) => tensor.name))\n\tconst extra = afterHeader.tensors.find((tensor) => !beforeNames.has(tensor.name))\n\tif (extra !== undefined) {\n\t\tthrow new InferError(\n\t\t\t`The candidate GGUF file carries extra tensor ${quoteFaultText(extra.name)} absent from baseline.`,\n\t\t\t{ code: 'BINDING', context: { name: extra.name } },\n\t\t)\n\t}\n\tconst paired: Array<{ readonly left: GGUFTensor; readonly right: GGUFTensor }> =\n\t\tbeforeHeader.tensors.map((left) => {\n\t\t\tconst right = afterByName.get(left.name)\n\t\t\tif (right === undefined) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The candidate GGUF file lacks baseline tensor ${quoteFaultText(left.name)}.`,\n\t\t\t\t\t{ code: 'BINDING', context: { name: left.name } },\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (\n\t\t\t\tleft.dimensions.length !== right.dimensions.length ||\n\t\t\t\tleft.dimensions.some((extent, index) => extent !== right.dimensions[index])\n\t\t\t) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The tensor ${quoteFaultText(left.name)} has dimensions [${left.dimensions.join(', ')}] in baseline and [${right.dimensions.join(', ')}] in candidate.`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'BINDING',\n\t\t\t\t\t\tcontext: { name: left.name, before: left.dimensions, after: right.dimensions },\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn { left, right }\n\t\t})\n\tconst records: Array<{\n\t\treadonly left: GGUFTensor\n\t\treadonly entry: TensorWeightDiff\n\t\treadonly diffSumSq: number\n\t\treadonly baseSumSq: number | undefined\n\t}> = []\n\tfor (const { left, right } of paired) {\n\t\tcheckSignal(signal, 'The weight diff')\n\t\tconst leftBytes = computeTensorBytes(left)\n\t\tconst rightBytes = computeTensorBytes(right)\n\t\tconst leftStart = beforeHeader.offset + left.offset\n\t\tconst rightStart = afterHeader.offset + right.offset\n\t\tconst overlap = Math.min(leftBytes, rightBytes)\n\t\tlet differingBytes = Math.abs(leftBytes - rightBytes)\n\t\tfor (let pos = 0; pos < overlap; pos += chunkBytes) {\n\t\t\tcheckSignal(signal, 'The weight diff')\n\t\t\tconst sliceLength = Math.min(chunkBytes, overlap - pos)\n\t\t\tconst leftSlice = await before.read(leftStart + pos, sliceLength, signal)\n\t\t\tconst rightSlice = await after.read(rightStart + pos, sliceLength, signal)\n\t\t\tfor (let byteIndex = 0; byteIndex < sliceLength; byteIndex += 1) {\n\t\t\t\tif (leftSlice[byteIndex] !== rightSlice[byteIndex]) differingBytes += 1\n\t\t\t}\n\t\t}\n\t\tconst exact = left.format === right.format && differingBytes === 0\n\t\tif (exact) {\n\t\t\trecords.push({\n\t\t\t\tleft,\n\t\t\t\tentry: {\n\t\t\t\t\tname: left.name,\n\t\t\t\t\tdimensions: [...left.dimensions],\n\t\t\t\t\tbefore: left.format,\n\t\t\t\t\tafter: right.format,\n\t\t\t\t\texact: true,\n\t\t\t\t\tbytes: 0,\n\t\t\t\t\tfrobenius: 0,\n\t\t\t\t\trelative: 0,\n\t\t\t\t\tmaximum: 0,\n\t\t\t\t},\n\t\t\t\tdiffSumSq: 0,\n\t\t\t\tbaseSumSq: undefined,\n\t\t\t})\n\t\t\tcontinue\n\t\t}\n\t\tif (!MERGE_SOURCE_FORMATS.includes(left.format)) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The baseline tensor ${quoteFaultText(left.name)} uses unsupported format ${quoteFaultText(left.format)}.`,\n\t\t\t\t{ code: 'UNSUPPORTED', context: { name: left.name, format: left.format } },\n\t\t\t)\n\t\t}\n\t\tif (!MERGE_SOURCE_FORMATS.includes(right.format)) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The candidate tensor ${quoteFaultText(right.name)} uses unsupported format ${quoteFaultText(right.format)}.`,\n\t\t\t\t{ code: 'UNSUPPORTED', context: { name: right.name, format: right.format } },\n\t\t\t)\n\t\t}\n\t\tconst elements = computeElements(left.dimensions)\n\t\tconst leftBlock = GGUF_BLOCKS[left.format]\n\t\tconst rightBlock = GGUF_BLOCKS[right.format]\n\t\tif (elements % leftBlock.elements !== 0 || elements % rightBlock.elements !== 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The tensor ${quoteFaultText(left.name)} element count ${elements} is not aligned to its format blocks.`,\n\t\t\t\t{\n\t\t\t\t\tcode: 'FORMAT',\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\tname: left.name,\n\t\t\t\t\t\telements,\n\t\t\t\t\t\tbefore: leftBlock.elements,\n\t\t\t\t\t\tafter: rightBlock.elements,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\tconst smallBlock = Math.min(leftBlock.elements, rightBlock.elements)\n\t\tconst largeBlock = Math.max(leftBlock.elements, rightBlock.elements)\n\t\tconst unitElements =\n\t\t\tArray.from({ length: smallBlock }, (_, index) => largeBlock * (index + 1)).find(\n\t\t\t\t(candidate) => candidate % smallBlock === 0,\n\t\t\t) ?? largeBlock * smallBlock\n\t\tconst firstExtent = left.dimensions[0] ?? 0\n\t\tconst rowAligned =\n\t\t\tleft.dimensions.length >= 2 && firstExtent > 0 && firstExtent % unitElements === 0\n\t\tconst unitBytes = Math.max(\n\t\t\t(unitElements / leftBlock.elements) * leftBlock.bytes,\n\t\t\t(unitElements / rightBlock.elements) * rightBlock.bytes,\n\t\t)\n\t\tconst stripElements = rowAligned\n\t\t\t? Math.max(\n\t\t\t\t\t1,\n\t\t\t\t\tMath.min(\n\t\t\t\t\t\tstripRows,\n\t\t\t\t\t\tMath.max(\n\t\t\t\t\t\t\t1,\n\t\t\t\t\t\t\tMath.floor(\n\t\t\t\t\t\t\t\tchunkBytes /\n\t\t\t\t\t\t\t\t\tMath.max(\n\t\t\t\t\t\t\t\t\t\t(firstExtent / leftBlock.elements) * leftBlock.bytes,\n\t\t\t\t\t\t\t\t\t\t(firstExtent / rightBlock.elements) * rightBlock.bytes,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t) * firstExtent\n\t\t\t: Math.max(1, Math.min(stripRows, Math.max(1, Math.floor(chunkBytes / unitBytes)))) *\n\t\t\t\tunitElements\n\t\tlet diffSumSq = 0\n\t\tlet baseSumSq = 0\n\t\tlet maxAbs = 0\n\t\tfor (let elemPos = 0; elemPos < elements; elemPos += stripElements) {\n\t\t\tcheckSignal(signal, 'The weight diff')\n\t\t\tconst count = Math.min(stripElements, elements - elemPos)\n\t\t\tconst leftRaw = await before.read(\n\t\t\t\tleftStart + (elemPos / leftBlock.elements) * leftBlock.bytes,\n\t\t\t\t(count / leftBlock.elements) * leftBlock.bytes,\n\t\t\t\tsignal,\n\t\t\t)\n\t\t\tconst rightRaw = await after.read(\n\t\t\t\trightStart + (elemPos / rightBlock.elements) * rightBlock.bytes,\n\t\t\t\t(count / rightBlock.elements) * rightBlock.bytes,\n\t\t\t\tsignal,\n\t\t\t)\n\t\t\tconst leftWide = widenTensor(leftRaw, left.format)\n\t\t\tconst rightWide = widenTensor(rightRaw, right.format)\n\t\t\tfor (let index = 0; index < count; index += 1) {\n\t\t\t\tconst leftVal = leftWide[index] ?? 0\n\t\t\t\tconst rightVal = rightWide[index] ?? 0\n\t\t\t\tconst delta = rightVal - leftVal\n\t\t\t\tconst absDelta = Math.abs(delta)\n\t\t\t\tdiffSumSq += delta * delta\n\t\t\t\tbaseSumSq += leftVal * leftVal\n\t\t\t\tif (absDelta > maxAbs) maxAbs = absDelta\n\t\t\t}\n\t\t}\n\t\tconst frobenius = Math.sqrt(diffSumSq)\n\t\tconst baseNorm = Math.sqrt(baseSumSq)\n\t\tconst relative =\n\t\t\tfrobenius === 0 ? 0 : baseNorm === 0 ? Number.POSITIVE_INFINITY : frobenius / baseNorm\n\t\trecords.push({\n\t\t\tleft,\n\t\t\tentry: {\n\t\t\t\tname: left.name,\n\t\t\t\tdimensions: [...left.dimensions],\n\t\t\t\tbefore: left.format,\n\t\t\t\tafter: right.format,\n\t\t\t\texact: false,\n\t\t\t\tbytes: differingBytes,\n\t\t\t\tfrobenius,\n\t\t\t\trelative,\n\t\t\t\tmaximum: maxAbs,\n\t\t\t},\n\t\t\tdiffSumSq,\n\t\t\tbaseSumSq,\n\t\t})\n\t}\n\tconst totalDiffSumSq = records.reduce((sum, item) => sum + item.diffSumSq, 0)\n\tconst frobenius = Math.sqrt(totalDiffSumSq)\n\tconst exactBaseSums: number[] = []\n\tif (frobenius > 0) {\n\t\tfor (const item of records) {\n\t\t\tif (item.baseSumSq !== undefined || !MERGE_SOURCE_FORMATS.includes(item.left.format)) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst elements = computeElements(item.left.dimensions)\n\t\t\tconst block = GGUF_BLOCKS[item.left.format]\n\t\t\tif (elements % block.elements !== 0) continue\n\t\t\tconst start = beforeHeader.offset + item.left.offset\n\t\t\tconst firstExtent = item.left.dimensions[0] ?? 0\n\t\t\tconst rowAligned =\n\t\t\t\titem.left.dimensions.length >= 2 && firstExtent > 0 && firstExtent % block.elements === 0\n\t\t\tconst stripElements = rowAligned\n\t\t\t\t? Math.max(\n\t\t\t\t\t\t1,\n\t\t\t\t\t\tMath.min(\n\t\t\t\t\t\t\tstripRows,\n\t\t\t\t\t\t\tMath.max(1, Math.floor(chunkBytes / ((firstExtent / block.elements) * block.bytes))),\n\t\t\t\t\t\t),\n\t\t\t\t\t) * firstExtent\n\t\t\t\t: Math.max(1, Math.min(stripRows, Math.max(1, Math.floor(chunkBytes / block.bytes)))) *\n\t\t\t\t\tblock.elements\n\t\t\tlet baseSumSq = 0\n\t\t\tfor (let elemPos = 0; elemPos < elements; elemPos += stripElements) {\n\t\t\t\tcheckSignal(signal, 'The weight diff')\n\t\t\t\tconst count = Math.min(stripElements, elements - elemPos)\n\t\t\t\tconst raw = await before.read(\n\t\t\t\t\tstart + (elemPos / block.elements) * block.bytes,\n\t\t\t\t\t(count / block.elements) * block.bytes,\n\t\t\t\t\tsignal,\n\t\t\t\t)\n\t\t\t\tconst widened = widenTensor(raw, item.left.format)\n\t\t\t\tfor (let index = 0; index < count; index += 1) {\n\t\t\t\t\tconst value = widened[index] ?? 0\n\t\t\t\t\tbaseSumSq += value * value\n\t\t\t\t}\n\t\t\t}\n\t\t\texactBaseSums.push(baseSumSq)\n\t\t}\n\t}\n\tconst totalBaseSumSq =\n\t\trecords.reduce((sum, item) => sum + (item.baseSumSq ?? 0), 0) +\n\t\texactBaseSums.reduce((sum, value) => sum + value, 0)\n\tconst totalBaseNorm = Math.sqrt(totalBaseSumSq)\n\tconst relative =\n\t\tfrobenius === 0 ? 0 : totalBaseNorm === 0 ? Number.POSITIVE_INFINITY : frobenius / totalBaseNorm\n\tconst tensors = records.map((item) => item.entry)\n\tconst maximum = tensors.reduce((peak, entry) => Math.max(peak, entry.maximum), 0)\n\tconst unchanged = tensors.filter((entry) => entry.exact).length\n\treturn {\n\t\ttensors,\n\t\tfrobenius,\n\t\trelative,\n\t\tmaximum,\n\t\tunchanged,\n\t\tchanged: tensors.length - unchanged,\n\t}\n}\n\n/**\n * Combines `N >= 1` weighted `AdapterInterface` instances into one immutable `Adapter` whose\n * weight delta equals the weighted sum of every input adapter's delta.\n *\n * @remarks\n * Validates non-empty entries, finite scalar weights, compatible decoder `family`, compatible\n * `base` digests, and matching `(rows, columns)` shapes per shared target. When every contributor\n * to a target shares the same rank and identical `down` basis matrix (including a single\n * contributor), performs an exact linear merge without increasing rank; otherwise performs exact\n * block-stacked rank concatenation (`down = [A_1; ...; A_m]`, `up = [s_1 B_1, ..., s_m B_m]`) so\n * cross terms remain identically zero. Serializes through `buildAdapterGGUF` to derive the exact\n * SHA-256 `digest` of the returned `Adapter`. Refuses invalid inputs with `ARGUMENT`, incompatible\n * families, bases, or tensor shapes with `BINDING`, and aborted signals with `ABORT`.\n *\n * @param entries - One or more weighted adapters to combine\n * @param options - Optional combined LoRA alpha, base digest binding check, and abort signal\n * @returns The combined immutable `Adapter` instance\n *\n * @example\n * ```ts\n * const combined = await combineAdapters([\n * \t{ adapter: verdictAdapter, weight: 0.5 },\n * \t{ adapter: rewordAdapter, weight: 0.5 },\n * ])\n * combined.scale // 1\n * ```\n */\nexport async function combineAdapters(\n\tentries: readonly AdapterCombinationEntry[],\n\toptions?: AdapterCombinationOptions,\n): Promise<Adapter> {\n\tconst signal = options?.signal\n\tcheckSignal(signal, 'The adapter combine')\n\tif (!isArray(entries) || entries.length === 0) {\n\t\tthrow new InferError('The adapter combine requires at least one adapter entry.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tif (options !== undefined && !isRecord(options)) {\n\t\tthrow new InferError('The adapter combine options must be a plain object.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tconst explicitBase = options?.base\n\tif (\n\t\texplicitBase !== undefined &&\n\t\t(!isString(explicitBase) || !SHA256_PATTERN.test(explicitBase))\n\t) {\n\t\tthrow new InferError(\n\t\t\t`The adapter combine base digest ${quoteFaultText(String(explicitBase))} must be a 64-character lowercase SHA-256 hex string.`,\n\t\t\t{ code: 'ARGUMENT', context: { base: explicitBase } },\n\t\t)\n\t}\n\tconst checkedEntries = entries.map((entry, index) => {\n\t\tif (!isRecord(entry) || !isObject(entry.adapter)) {\n\t\t\tthrow new InferError(`The adapter combine entry at index ${index} must carry an adapter.`, {\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\tcontext: { entry: index },\n\t\t\t})\n\t\t}\n\t\tcheckAdapterOptions(entry.adapter)\n\t\tconst weight = entry.weight ?? 1\n\t\tif (!isFiniteNumber(weight)) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The adapter combine weight at index ${index} is ${weight}; pass a finite number.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { entry: index, weight } },\n\t\t\t)\n\t\t}\n\t\treturn { adapter: entry.adapter, weight }\n\t})\n\tconst [firstEntry] = checkedEntries\n\tif (firstEntry === undefined) {\n\t\tthrow new InferError('The adapter combine requires at least one adapter entry.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tconst family = firstEntry.adapter.family\n\tconst mismatchedFamily = checkedEntries.find((entry) => entry.adapter.family !== family)\n\tif (mismatchedFamily !== undefined) {\n\t\tthrow new InferError(\n\t\t\t`The adapters target incompatible families ${quoteFaultText(family)} and ${quoteFaultText(mismatchedFamily.adapter.family)}.`,\n\t\t\t{ code: 'BINDING', context: { expected: family, actual: mismatchedFamily.adapter.family } },\n\t\t)\n\t}\n\tconst declaredBases = [\n\t\t...new Set(\n\t\t\tcheckedEntries.flatMap((entry) =>\n\t\t\t\tentry.adapter.base === undefined ? [] : [entry.adapter.base],\n\t\t\t),\n\t\t),\n\t]\n\tif (explicitBase !== undefined) {\n\t\tconst wrongBase = declaredBases.find((base) => base !== explicitBase)\n\t\tif (wrongBase !== undefined) {\n\t\t\tthrow new InferError(\n\t\t\t\t`An input adapter binds base ${quoteFaultText(wrongBase)}, differing from expected base ${quoteFaultText(explicitBase)}.`,\n\t\t\t\t{ code: 'BINDING', context: { expected: explicitBase, actual: wrongBase } },\n\t\t\t)\n\t\t}\n\t} else if (declaredBases.length > 1) {\n\t\tthrow new InferError(\n\t\t\t`The input adapters bind conflicting bases ${declaredBases.map(quoteFaultText).join(' and ')}.`,\n\t\t\t{ code: 'BINDING', context: { bases: declaredBases } },\n\t\t)\n\t}\n\tconst resolvedBase = explicitBase ?? declaredBases[0]\n\tconst outAlpha = options?.alpha ?? firstEntry.adapter.alpha\n\tif (!isFiniteNumber(outAlpha) || outAlpha <= 0) {\n\t\tthrow new InferError(\n\t\t\t`The combined adapter alpha is ${outAlpha}; pass a positive finite number.`,\n\t\t\t{ code: 'ARGUMENT', context: { alpha: outAlpha } },\n\t\t)\n\t}\n\tconst grouped = new Map<\n\t\tstring,\n\t\tArray<{ readonly pair: AdapterPair; readonly coefficient: number }>\n\t>()\n\tfor (const entry of checkedEntries) {\n\t\tfor (const pair of entry.adapter.pairs) {\n\t\t\tconst coefficient = entry.weight * entry.adapter.scale * (pair.alpha / pair.rank)\n\t\t\tconst bucket = grouped.get(pair.name)\n\t\t\tif (bucket === undefined) {\n\t\t\t\tgrouped.set(pair.name, [{ pair, coefficient }])\n\t\t\t} else {\n\t\t\t\tbucket.push({ pair, coefficient })\n\t\t\t}\n\t\t}\n\t}\n\tconst orderedKeys = [...grouped.keys()].toSorted((leftKey, rightKey) => {\n\t\tconst leftPair = grouped.get(leftKey)?.[0]?.pair\n\t\tconst rightPair = grouped.get(rightKey)?.[0]?.pair\n\t\tif (leftPair === undefined || rightPair === undefined) return leftKey.localeCompare(rightKey)\n\t\treturn (\n\t\t\tleftPair.layer - rightPair.layer ||\n\t\t\tADAPTER_TARGETS.indexOf(leftPair.target) - ADAPTER_TARGETS.indexOf(rightPair.target)\n\t\t)\n\t})\n\tconst combinedPairs: readonly AdapterPair[] = orderedKeys.map((name) => {\n\t\tconst bucket = grouped.get(name) ?? []\n\t\tconst [head] = bucket\n\t\tif (head === undefined) {\n\t\t\tthrow new InferError(`The combined target ${quoteFaultText(name)} holds no pairs.`, {\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\tcontext: { name },\n\t\t\t})\n\t\t}\n\t\tconst { layer, group, slot, target, columns, rows } = head.pair\n\t\tfor (const item of bucket) {\n\t\t\tif (\n\t\t\t\titem.pair.layer !== layer ||\n\t\t\t\titem.pair.target !== target ||\n\t\t\t\titem.pair.columns !== columns ||\n\t\t\t\titem.pair.rows !== rows\n\t\t\t) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The adapters disagree on shape for ${quoteFaultText(name)}: [${columns}, ${rows}] vs [${item.pair.columns}, ${item.pair.rows}].`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'BINDING',\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\texpected: [columns, rows],\n\t\t\t\t\t\t\tactual: [item.pair.columns, item.pair.rows],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\tconst matchingBasis =\n\t\t\tbucket.length === 1 ||\n\t\t\tbucket.every(\n\t\t\t\t(item) =>\n\t\t\t\t\titem.pair.rank === head.pair.rank &&\n\t\t\t\t\titem.pair.down.every((value, index) => value === head.pair.down[index]),\n\t\t\t)\n\t\tif (matchingBasis) {\n\t\t\tconst rank = head.pair.rank\n\t\t\tconst down = Float32Array.from(head.pair.down)\n\t\t\tconst up = new Float32Array(rows * rank)\n\t\t\tconst scaleFactor = rank / outAlpha\n\t\t\tfor (let index = 0; index < up.length; index += 1) {\n\t\t\t\tlet sum = 0\n\t\t\t\tfor (let itemIndex = 0; itemIndex < bucket.length; itemIndex += 1) {\n\t\t\t\t\tconst item = bucket[itemIndex]\n\t\t\t\t\tif (item === undefined) continue\n\t\t\t\t\tsum += item.coefficient * (item.pair.up[index] ?? 0)\n\t\t\t\t}\n\t\t\t\tconst value = Math.fround(scaleFactor * sum)\n\t\t\t\tif (!Number.isFinite(value)) {\n\t\t\t\t\tthrow new InferError(\n\t\t\t\t\t\t`The combined up projection for ${quoteFaultText(name)} overflowed single precision.`,\n\t\t\t\t\t\t{ code: 'ARGUMENT', context: { name } },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tup[index] = value\n\t\t\t}\n\t\t\treturn { name, layer, group, slot, target, columns, rows, rank, alpha: outAlpha, down, up }\n\t\t}\n\t\tconst totalRank = bucket.reduce((sum, item) => sum + item.pair.rank, 0)\n\t\tif (\n\t\t\t!isSafeInteger(totalRank) ||\n\t\t\t!isSafeInteger(totalRank * columns) ||\n\t\t\t!isSafeInteger(rows * totalRank)\n\t\t) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The combined rank ${totalRank} for ${quoteFaultText(name)} exceeds safe integer limits.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { name, rank: totalRank } },\n\t\t\t)\n\t\t}\n\t\tconst down = new Float32Array(totalRank * columns)\n\t\tconst up = new Float32Array(rows * totalRank)\n\t\tlet rankOffset = 0\n\t\tfor (let itemIndex = 0; itemIndex < bucket.length; itemIndex += 1) {\n\t\t\tconst item = bucket[itemIndex]\n\t\t\tif (item === undefined) continue\n\t\t\tdown.set(item.pair.down, rankOffset * columns)\n\t\t\tconst factor = (totalRank * item.coefficient) / outAlpha\n\t\t\tfor (let row = 0; row < rows; row += 1) {\n\t\t\t\tconst dstRow = row * totalRank + rankOffset\n\t\t\t\tconst srcRow = row * item.pair.rank\n\t\t\t\tfor (let col = 0; col < item.pair.rank; col += 1) {\n\t\t\t\t\tconst value = Math.fround(factor * (item.pair.up[srcRow + col] ?? 0))\n\t\t\t\t\tif (!Number.isFinite(value)) {\n\t\t\t\t\t\tthrow new InferError(\n\t\t\t\t\t\t\t`The combined up projection for ${quoteFaultText(name)} overflowed single precision.`,\n\t\t\t\t\t\t\t{ code: 'ARGUMENT', context: { name } },\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t\tup[dstRow + col] = value\n\t\t\t\t}\n\t\t\t}\n\t\t\trankOffset += item.pair.rank\n\t\t}\n\t\treturn {\n\t\t\tname,\n\t\t\tlayer,\n\t\t\tgroup,\n\t\t\tslot,\n\t\t\ttarget,\n\t\t\tcolumns,\n\t\t\trows,\n\t\t\trank: totalRank,\n\t\t\talpha: outAlpha,\n\t\t\tdown,\n\t\t\tup,\n\t\t}\n\t})\n\tcheckSignal(signal, 'The adapter combine')\n\tconst placeholderOptions: AdapterOptions = {\n\t\tdigest: '0'.repeat(64),\n\t\tfamily,\n\t\talpha: outAlpha,\n\t\t...(resolvedBase === undefined ? {} : { base: resolvedBase }),\n\t\tscale: 1,\n\t\tpairs: combinedPairs,\n\t}\n\tconst ggufBytes = buildAdapterGGUF(placeholderOptions)\n\tconst digest = await digestBytes(ggufBytes)\n\treturn new Adapter({\n\t\tdigest,\n\t\tfamily,\n\t\talpha: outAlpha,\n\t\t...(resolvedBase === undefined ? {} : { base: resolvedBase }),\n\t\tscale: 1,\n\t\tpairs: combinedPairs,\n\t})\n}\n\n/**\n * Permutes one full-rank `SectionEntry` between GGUF layout and Hugging Face safetensors layout\n * for `llama` rotary projections (`attn_q`, `attn_k`) and `qwen35` grouped-value DeltaNet\n * projections (`values !== keys`).\n *\n * @remarks\n * Inverts GGUF adjacent-pair rotary rows through `deinterleaveRotary` when `toGGUF` is `false`\n * (and applies `interleaveRotary` when `toGGUF` is `true`). On `qwen35` architectures with\n * `delta.values !== delta.keys`, permutes value-head blocks across `attn_qkv`, `attn_gate`,\n * `ssm_alpha`, `ssm_beta`, `ssm_conv1d`, `ssm_dt`, `ssm_a`, and `ssm_out`. Returns `entry`\n * unchanged when `architecture` is absent or no layout transform applies.\n *\n * @param entry - The full-rank section tensor entry\n * @param architecture - Optional base decoder architecture carrying head counts\n * @param toGGUF - If `true`, converts Hugging Face order to GGUF order; if `false`, GGUF to Hugging Face\n * @returns The layout-permuted `SectionEntry`\n *\n * @example\n * ```ts\n * permuteSectionEntry(entry, undefined, false) === entry // true\n * ```\n */\nexport function permuteSectionEntry(\n\tentry: SectionEntry,\n\tarchitecture: Architecture | undefined,\n\ttoGGUF: boolean,\n): SectionEntry {\n\tif (architecture === undefined) return entry\n\tif (\n\t\tARCHITECTURE_FAMILIES[architecture.family].interleaved &&\n\t\t(entry.target === 'attn_q' || entry.target === 'attn_k')\n\t) {\n\t\tconst heads = entry.target === 'attn_q' ? architecture.queries : architecture.groups\n\t\tconst expectedRows = heads * architecture.head\n\t\tif (entry.rows !== expectedRows) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The ${entry.target} section entry ${quoteFaultText(entry.name)} has ${entry.rows} rows; expected ${expectedRows}.`,\n\t\t\t\t{\n\t\t\t\t\tcode: 'BINDING',\n\t\t\t\t\tcontext: { name: entry.name, rows: entry.rows, expected: expectedRows },\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\tconst bytes = new Uint8Array(\n\t\t\tentry.values.buffer,\n\t\t\tentry.values.byteOffset,\n\t\t\tentry.values.byteLength,\n\t\t)\n\t\tconst rowBytes = entry.columns * 4\n\t\tconst reordered = toGGUF\n\t\t\t? interleaveRotary(bytes, heads, rowBytes)\n\t\t\t: deinterleaveRotary(bytes, heads, rowBytes)\n\t\treturn { ...entry, values: new Float32Array(reordered.buffer) }\n\t}\n\tconst delta = architecture.delta\n\tif (delta === undefined || delta.values === delta.keys) return entry\n\tconst { keys, values, head } = delta\n\tif (\n\t\t!isSafeInteger(keys) ||\n\t\tkeys < 1 ||\n\t\t!isSafeInteger(values) ||\n\t\tvalues < 1 ||\n\t\tvalues % keys !== 0 ||\n\t\t!isSafeInteger(head) ||\n\t\thead < 1\n\t) {\n\t\tthrow new InferError('The delta architecture head counts are invalid for permutation.', {\n\t\t\tcode: 'FORMAT',\n\t\t\tcontext: { keys, values, head },\n\t\t})\n\t}\n\tif (entry.target === 'attn_qkv' || entry.target === 'ssm_conv1d') {\n\t\tconst prefixRows = 2 * keys * head\n\t\tconst expectedRows = prefixRows + values * head\n\t\tif (entry.rows !== expectedRows) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The ${entry.target} section entry ${quoteFaultText(entry.name)} has ${entry.rows} rows; expected ${expectedRows}.`,\n\t\t\t\t{\n\t\t\t\t\tcode: 'BINDING',\n\t\t\t\t\tcontext: { name: entry.name, rows: entry.rows, expected: expectedRows },\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\tconst prefixFloats = prefixRows * entry.columns\n\t\tconst valueSlice = permuteHeadBlocks(\n\t\t\tentry.values.subarray(prefixFloats),\n\t\t\t1,\n\t\t\tvalues,\n\t\t\tkeys,\n\t\t\thead * entry.columns,\n\t\t\ttoGGUF,\n\t\t)\n\t\tconst out = new Float32Array(entry.values.length)\n\t\tout.set(entry.values.subarray(0, prefixFloats), 0)\n\t\tout.set(valueSlice, prefixFloats)\n\t\treturn { ...entry, values: out }\n\t}\n\tif (entry.target === 'attn_gate') {\n\t\tconst expectedRows = values * head\n\t\tif (entry.rows !== expectedRows) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The attn_gate section entry ${quoteFaultText(entry.name)} has ${entry.rows} rows; expected ${expectedRows}.`,\n\t\t\t\t{\n\t\t\t\t\tcode: 'BINDING',\n\t\t\t\t\tcontext: { name: entry.name, rows: entry.rows, expected: expectedRows },\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\treturn {\n\t\t\t...entry,\n\t\t\tvalues: permuteHeadBlocks(entry.values, 1, values, keys, head * entry.columns, toGGUF),\n\t\t}\n\t}\n\tif (entry.target === 'ssm_alpha' || entry.target === 'ssm_beta') {\n\t\tif (entry.rows !== values) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The ${entry.target} section entry ${quoteFaultText(entry.name)} has ${entry.rows} rows; expected ${values}.`,\n\t\t\t\t{ code: 'BINDING', context: { name: entry.name, rows: entry.rows, expected: values } },\n\t\t\t)\n\t\t}\n\t\treturn {\n\t\t\t...entry,\n\t\t\tvalues: permuteHeadBlocks(entry.values, 1, values, keys, entry.columns, toGGUF),\n\t\t}\n\t}\n\tif (entry.target === 'ssm_dt' || entry.target === 'ssm_a') {\n\t\tif (entry.columns !== values) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The ${entry.target} section entry ${quoteFaultText(entry.name)} has ${entry.columns} columns; expected ${values}.`,\n\t\t\t\t{\n\t\t\t\t\tcode: 'BINDING',\n\t\t\t\t\tcontext: { name: entry.name, columns: entry.columns, expected: values },\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\treturn {\n\t\t\t...entry,\n\t\t\tvalues: permuteHeadBlocks(entry.values, 1, values, keys, 1, toGGUF),\n\t\t}\n\t}\n\tif (entry.target === 'ssm_out') {\n\t\tconst expectedColumns = values * head\n\t\tif (entry.columns !== expectedColumns) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The ssm_out section entry ${quoteFaultText(entry.name)} has ${entry.columns} columns; expected ${expectedColumns}.`,\n\t\t\t\t{\n\t\t\t\t\tcode: 'BINDING',\n\t\t\t\t\tcontext: { name: entry.name, columns: entry.columns, expected: expectedColumns },\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\treturn {\n\t\t\t...entry,\n\t\t\tvalues: permuteHeadBlocks(entry.values, entry.rows, values, keys, head, toGGUF),\n\t\t}\n\t}\n\treturn entry\n}\n\n/**\n * Serializes validated full-rank section patch options or a live `SectionInterface` into a GGUF v3\n * section patch file (`general.type = \"patch\"`, `orkestrel.patch.version = 1`, optional\n * `orkestrel.base`) readable by `readSectionGGUF` and `@orkestrel/infer`'s `createSection`.\n *\n * @remarks\n * Admits `'F32'` (default), `'BF16'`, and `'Q8_0'`. When `format` is `'Q8_0'`, 1D tensors and\n * tensors whose column width is not a multiple of 32 are stored as `'F32'` so normalization gains,\n * biases, and 4-tap convolutions round-trip losslessly alongside `Q8_0`-compressed weight matrices.\n * Entries are ordered canonically by ascending layer and `SECTION_TARGETS` order, with top-level\n * entries trailing.\n *\n * @param options - The validated section options or live section patch\n * @param format - Storage format for full-rank patch tensors (`'F32'`, `'BF16'`, or `'Q8_0'`). Default: `'F32'`\n * @returns The serialized GGUF v3 section patch bytes\n *\n * @example\n * ```ts\n * const bytes = buildSectionGGUF(section, 'BF16')\n * ```\n */\nexport function buildSectionGGUF(\n\toptions: SectionOptions | SectionInterface,\n\tformat: SectionFormat = 'F32',\n): Uint8Array<ArrayBuffer> {\n\tconst normalized: SectionOptions = {\n\t\tdigest: options.digest,\n\t\tfamily: options.family,\n\t\tentries: options.entries,\n\t\t...(options.base === undefined ? {} : { base: options.base }),\n\t}\n\tcheckSectionOptions(normalized)\n\tif (!isSectionFormat(format)) {\n\t\tthrow new InferError(\n\t\t\t`The section patch format ${quoteFaultText(String(format))} must be \"F32\", \"BF16\", or \"Q8_0\".`,\n\t\t\t{ code: 'ARGUMENT', context: { format } },\n\t\t)\n\t}\n\tconst ordered = [...options.entries].toSorted((left, right) => {\n\t\tconst leftLayer = left.layer ?? Number.POSITIVE_INFINITY\n\t\tconst rightLayer = right.layer ?? Number.POSITIVE_INFINITY\n\t\treturn (\n\t\t\tleftLayer - rightLayer ||\n\t\t\tSECTION_TARGETS.indexOf(left.target) - SECTION_TARGETS.indexOf(right.target)\n\t\t)\n\t})\n\tconst metadata = new Map<string, GGUFValue>([\n\t\t[SECTION_KEYS.role, { encoding: 'string', value: SECTION_PATCH_TYPE }],\n\t\t[SECTION_KEYS.version, { encoding: 'uint32', value: SECTION_PATCH_VERSION }],\n\t\t[GGUF_KEYS.architecture, { encoding: 'string', value: options.family }],\n\t\t[GGUF_KEYS.alignment, { encoding: 'uint32', value: GGUF_ALIGNMENT }],\n\t\t...(options.base === undefined\n\t\t\t? []\n\t\t\t: [[SECTION_KEYS.base, { encoding: 'string', value: options.base }] as const]),\n\t])\n\tconst items = ordered.map((entry) => {\n\t\tconst dimensions = entry.rows === 1 ? [entry.columns] : [entry.columns, entry.rows]\n\t\tconst tensorFormat: SectionFormat =\n\t\t\tformat === 'Q8_0' && (entry.rows === 1 || entry.columns % GGUF_BLOCKS.Q8_0.elements !== 0)\n\t\t\t\t? 'F32'\n\t\t\t\t: format\n\t\treturn {\n\t\t\tname: entry.name,\n\t\t\tdimensions,\n\t\t\tformat: tensorFormat,\n\t\t\tbytes: encodeGGUFValues(entry.values, tensorFormat),\n\t\t}\n\t})\n\tconst tensors: GGUFTensor[] = []\n\tlet offset = 0\n\tfor (let index = 0; index < items.length; index += 1) {\n\t\tconst item = items[index]\n\t\tif (item === undefined) continue\n\t\ttensors.push({\n\t\t\tname: item.name,\n\t\t\tdimensions: item.dimensions,\n\t\t\tformat: item.format,\n\t\t\toffset,\n\t\t})\n\t\toffset = alignOffset(offset + item.bytes.byteLength, GGUF_ALIGNMENT)\n\t}\n\tconst data = new Uint8Array(offset)\n\tfor (let index = 0; index < items.length; index += 1) {\n\t\tconst item = items[index]\n\t\tconst tensor = tensors[index]\n\t\tif (item === undefined || tensor === undefined) continue\n\t\tdata.set(item.bytes, tensor.offset)\n\t}\n\treturn buildGGUF(metadata, tensors, data)\n}\n\n/**\n * Reads and validates a GGUF v3 full-rank section patch from a `ByteSourceInterface`, returning an\n * immutable `SectionInterface` and verifying optional architecture and base bindings.\n *\n * @remarks\n * Delegates GGUF v3 decoding (`general.type = \"patch\"`, `orkestrel.patch.version = 1`, `F32`/`BF16`/\n * `Q8_0` widening) to `@orkestrel/infer`'s `readSection`, wraps the result in `new Section(...)`,\n * and verifies `options.architecture` and `options.base` through `checkSectionBinding` (refusing\n * mismatches with `BINDING`). Works identically in Node and Chromium.\n *\n * @param source - The byte source holding the GGUF v3 section patch\n * @param options - Optional architecture binding, base digest binding, and abort signal\n * @returns The immutable `SectionInterface`\n *\n * @example\n * ```ts\n * const patch = await readSectionGGUF(new MemorySource(bytes), { architecture, base })\n * await backbone.section(patch)\n * ```\n */\nexport async function readSectionGGUF(\n\tsource: ByteSourceInterface,\n\toptions: SectionReadOptions = {},\n): Promise<SectionInterface> {\n\tcheckSignal(options.signal, 'The section patch read')\n\tconst parsed = await readSection(source, options.signal)\n\tconst patch = new Section(parsed)\n\tif (options.architecture !== undefined) {\n\t\tcheckSectionBinding(patch, options.architecture, options.base)\n\t} else if (\n\t\toptions.base !== undefined &&\n\t\tpatch.base !== undefined &&\n\t\tpatch.base !== options.base\n\t) {\n\t\tthrow new InferError(\n\t\t\t`The section patch binds to base ${quoteFaultText(patch.base)}, not expected ${quoteFaultText(options.base)}.`,\n\t\t\t{ code: 'BINDING', context: { patch: patch.base, expected: options.base } },\n\t\t)\n\t}\n\treturn patch\n}\n\n/**\n * Computes the learning rate for 1-based optimizer step `step` out of `total` steps under linear\n * warmup followed by `'cosine'` or `'constant'` schedule.\n *\n * @remarks\n * During warmup (`warmup > 0 && step <= warmup`), scales linearly as `rate * (step / warmup)`.\n * After warmup, `'constant'` returns `rate` and `'cosine'` decays along\n * `0.5 * rate * (1 + cos(pi * (step - warmup) / max(1, total - warmup)))`.\n *\n * @param step - The 1-based optimizer step index\n * @param total - The total planned optimizer steps\n * @param rate - The peak non-negative finite learning rate\n * @param warmup - The non-negative integer linear warmup step count\n * @param schedule - The post-warmup schedule (`'cosine'` or `'constant'`)\n * @returns The step's non-negative learning rate\n *\n * @example\n * ```ts\n * computeFinetunerRate(1, 10, 0.001, 2, 'cosine') // 0.0005\n * ```\n */\nexport function computeFinetunerRate(\n\tstep: number,\n\ttotal: number,\n\trate: number,\n\twarmup: number,\n\tschedule: FinetunerSchedule,\n): number {\n\tif (!matchesCount(step, 1) || !matchesCount(total, 1)) {\n\t\tthrow new InferError(\n\t\t\t`The step (${step}) and total (${total}) must be positive safe integers.`,\n\t\t\t{ code: 'ARGUMENT', context: { step, total } },\n\t\t)\n\t}\n\tif (!isFiniteNumber(rate) || rate < 0) {\n\t\tthrow new InferError(`The learning rate ${rate} must be a non-negative finite number.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { rate },\n\t\t})\n\t}\n\tif (!isSafeInteger(warmup) || warmup < 0) {\n\t\tthrow new InferError(`The warmup step count ${warmup} must be a non-negative integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { warmup },\n\t\t})\n\t}\n\tif (!isFinetunerSchedule(schedule)) {\n\t\tthrow new InferError(\n\t\t\t`The learning rate schedule ${quoteFaultText(String(schedule))} must be \"cosine\" or \"constant\".`,\n\t\t\t{ code: 'ARGUMENT', context: { schedule } },\n\t\t)\n\t}\n\tif (warmup > 0 && step <= warmup) {\n\t\treturn rate * (step / warmup)\n\t}\n\tif (schedule === 'constant' || total <= warmup) {\n\t\treturn rate\n\t}\n\tconst span = Math.max(1, total - warmup)\n\tconst progress = Math.min(1, Math.max(0, (step - warmup) / span))\n\treturn rate * 0.5 * (1 + Math.cos(Math.PI * progress))\n}\n\n/**\n * Validates and resolves a `FinetunerOptions` record into checked `FinetunerSettings` with every\n * default applied.\n *\n * @remarks\n * Refuses invalid modes, base digests, optimizer hyperparameters, loop bounds, fold settings,\n * mode/plan mismatches (such as `mode: 'adapter'` carrying `section` settings), or invalid\n * checkpoint intervals and identifiers with the `ARGUMENT` code.\n *\n * @param options - The finetuner configuration to validate\n * @returns The resolved `FinetunerSettings`\n *\n * @example\n * ```ts\n * resolveFinetunerSettings(options).optimizer.rate // 0.0001\n * ```\n */\nexport function resolveFinetunerSettings(options: FinetunerOptions): FinetunerSettings {\n\tif (!isRecord(options)) {\n\t\tthrow new InferError('The finetuner options must be a plain object.', { code: 'ARGUMENT' })\n\t}\n\tconst { mode, architecture, base, optimizer, loop, adapter, section, checkpoint } = options\n\tif (!isCheckpointMode(mode)) {\n\t\tthrow new InferError(\n\t\t\t`The finetuner mode ${quoteFaultText(String(mode))} must be \"adapter\" or \"section\".`,\n\t\t\t{ code: 'ARGUMENT', context: { mode } },\n\t\t)\n\t}\n\tif (!isString(base) || !SHA256_PATTERN.test(base)) {\n\t\tthrow new InferError(\n\t\t\t`The finetuner base digest ${quoteFaultText(String(base))} must be a 64-character lowercase SHA-256 hex digest.`,\n\t\t\t{ code: 'ARGUMENT', context: { base } },\n\t\t)\n\t}\n\tconst rate = optimizer?.rate ?? FINETUNER_RATE\n\tconst decay = optimizer?.decay ?? FINETUNER_DECAY\n\tconst first = optimizer?.first ?? FINETUNER_FIRST\n\tconst second = optimizer?.second ?? FINETUNER_SECOND\n\tconst epsilon = optimizer?.epsilon ?? FINETUNER_EPSILON\n\tconst clip = optimizer?.clip ?? FINETUNER_CLIP\n\tconst warmup = optimizer?.warmup ?? FINETUNER_WARMUP\n\tconst schedule = optimizer?.schedule ?? 'cosine'\n\tif (!isFiniteNumber(rate) || rate < 0) {\n\t\tthrow new InferError(`The optimizer rate ${rate} must be a non-negative finite number.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { rate },\n\t\t})\n\t}\n\tif (!isFiniteNumber(decay) || decay < 0) {\n\t\tthrow new InferError(`The optimizer decay ${decay} must be a non-negative finite number.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { decay },\n\t\t})\n\t}\n\tif (!isFiniteNumber(first) || first < 0 || first >= 1) {\n\t\tthrow new InferError(`The optimizer first moment ${first} must lie in [0, 1).`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { first },\n\t\t})\n\t}\n\tif (!isFiniteNumber(second) || second < 0 || second >= 1) {\n\t\tthrow new InferError(`The optimizer second moment ${second} must lie in [0, 1).`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { second },\n\t\t})\n\t}\n\tif (!isFiniteNumber(epsilon) || epsilon <= 0) {\n\t\tthrow new InferError(`The optimizer epsilon ${epsilon} must be a positive finite number.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { epsilon },\n\t\t})\n\t}\n\tif (!isFiniteNumber(clip) || clip < 0) {\n\t\tthrow new InferError(`The optimizer clip ${clip} must be a non-negative finite number.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { clip },\n\t\t})\n\t}\n\tif (!isSafeInteger(warmup) || warmup < 0) {\n\t\tthrow new InferError(`The optimizer warmup ${warmup} must be a non-negative integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { warmup },\n\t\t})\n\t}\n\tif (!isFinetunerSchedule(schedule)) {\n\t\tthrow new InferError(\n\t\t\t`The optimizer schedule ${quoteFaultText(String(schedule))} must be \"cosine\" or \"constant\".`,\n\t\t\t{ code: 'ARGUMENT', context: { schedule } },\n\t\t)\n\t}\n\tconst epochs = loop?.epochs ?? FINETUNER_EPOCHS\n\tconst batch = loop?.batch ?? FINETUNER_BATCH\n\tconst segment = loop?.segment ?? BACKWARD_SEGMENT\n\tconst limit = loop?.limit ?? FINETUNER_LIMIT\n\tconst steps = loop?.steps\n\tconst seed = loop?.seed ?? FINETUNER_SEED\n\tconst folds = loop?.folds\n\tconst fold = loop?.fold\n\tif (!matchesCount(epochs, 1)) {\n\t\tthrow new InferError(`The loop epochs ${epochs} must be a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { epochs },\n\t\t})\n\t}\n\tif (!matchesCount(batch, 1)) {\n\t\tthrow new InferError(`The loop batch size ${batch} must be a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { batch },\n\t\t})\n\t}\n\tif (!matchesCount(segment, 1)) {\n\t\tthrow new InferError(`The loop segment width ${segment} must be a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { segment },\n\t\t})\n\t}\n\tif (!matchesCount(limit, 2)) {\n\t\tthrow new InferError(`The loop token limit ${limit} must be an integer of at least 2.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { limit },\n\t\t})\n\t}\n\tif (steps !== undefined && !matchesCount(steps, 1)) {\n\t\tthrow new InferError(`The loop steps cap ${steps} must be a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { steps },\n\t\t})\n\t}\n\tif (!isSafeInteger(seed) || seed < 0 || seed > 0xffff_ffff) {\n\t\tthrow new InferError(`The loop seed ${seed} must be an unsigned 32-bit integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { seed },\n\t\t})\n\t}\n\tif (folds !== undefined) {\n\t\tif (!matchesCount(folds, 2)) {\n\t\t\tthrow new InferError(`The loop folds count ${folds} must be an integer of at least 2.`, {\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\tcontext: { folds },\n\t\t\t})\n\t\t}\n\t\tconst resolvedFold = fold ?? 0\n\t\tif (!isSafeInteger(resolvedFold) || resolvedFold < 0 || resolvedFold >= folds) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The loop fold ${resolvedFold} must be an integer from 0 to ${folds - 1}.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { fold: resolvedFold, folds } },\n\t\t\t)\n\t\t}\n\t} else if (fold !== undefined) {\n\t\tthrow new InferError('The loop fold option requires loop.folds to be set.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { fold },\n\t\t})\n\t}\n\tconst plan: TrainPlan = {\n\t\tmode,\n\t\tsegment,\n\t\t...(adapter === undefined ? {} : { adapter: { ...adapter, seed } }),\n\t\t...(section === undefined ? {} : { section }),\n\t}\n\tcheckTrainPlan(plan, architecture)\n\tif (checkpoint !== undefined) {\n\t\tif (!isRecord(checkpoint) || !isObject(checkpoint.store)) {\n\t\t\tthrow new InferError('The checkpoint configuration requires a CheckpointStoreInterface.', {\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t})\n\t\t}\n\t\tcheckCheckpointId(checkpoint.id)\n\t\tif (!matchesCount(checkpoint.every, 1)) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The checkpoint interval ${checkpoint.every} must be a positive integer.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { every: checkpoint.every } },\n\t\t\t)\n\t\t}\n\t\tif (checkpoint.resume !== undefined && !isBoolean(checkpoint.resume)) {\n\t\t\tthrow new InferError('The checkpoint resume flag must be a boolean.', { code: 'ARGUMENT' })\n\t\t}\n\t}\n\treturn {\n\t\tmode,\n\t\tbase,\n\t\toptimizer: { rate, decay, first, second, epsilon, clip, warmup, schedule },\n\t\tloop: {\n\t\t\tepochs,\n\t\t\tbatch,\n\t\t\tsegment,\n\t\t\tlimit,\n\t\t\t...(steps === undefined ? {} : { steps }),\n\t\t\tseed,\n\t\t\t...(folds === undefined ? {} : { folds, fold: fold ?? 0 }),\n\t\t},\n\t\t...(adapter === undefined ? {} : { adapter }),\n\t\t...(section === undefined ? {} : { section }),\n\t\t...(checkpoint === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tcheckpoint: {\n\t\t\t\t\t\tstore: checkpoint.store,\n\t\t\t\t\t\tid: checkpoint.id,\n\t\t\t\t\t\tevery: checkpoint.every,\n\t\t\t\t\t\tresume: checkpoint.resume ?? false,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t}\n}\n\n/**\n * Validates every `FinetuneRow` (including `checkRowProvenance`), renders any `messages` row\n * through `ChatTemplate` or `@orkestrel/template`, and tokenizes `(prompt, completion)` pairs into\n * prompt-masked `TokenSpan` records before step 1.\n *\n * @remarks\n * Refuses empty row lists, malformed rows, hosted-model provenance markers, missing templates when\n * `messages` is used, empty prompt or completion encodings, and spans exceeding `limit` tokens\n * with the `ARGUMENT` code.\n *\n * @param rows - The fine-tuning rows to validate and tokenize\n * @param tokenizer - The tokenizer encoding prompts and completions\n * @param limit - The maximum admitted token length per example\n * @param template - Optional `ChatTemplateInterface`, compiled `TemplateTreeInterface`, or Jinja source\n * @returns Prompt-masked `TokenSpan` records in row order\n *\n * @example\n * ```ts\n * const spans = admitFinetuneRows(rows, backbone.tokenizer, 512)\n * spans[0]?.prompt // number of masked prompt tokens\n * ```\n */\nexport function admitFinetuneRows(\n\trows: readonly FinetuneRow[],\n\ttokenizer: TokenizerInterface,\n\tlimit: number,\n\ttemplate?: ChatTemplateInterface | TemplateTreeInterface | TemplateDocument | string,\n): readonly TokenSpan[] {\n\tif (!isArray(rows) || rows.length === 0) {\n\t\tthrow new InferError('The finetuner received no rows; pass at least one supervised row.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tconst templateDoc: TemplateDocument | undefined =\n\t\ttemplate === undefined\n\t\t\t? undefined\n\t\t\t: isString(template)\n\t\t\t\t? compileTemplate(template)\n\t\t\t\t: isTemplateDocument(template)\n\t\t\t\t\t? template\n\t\t\t\t\t: 'document' in template && isTemplateDocument(template.document)\n\t\t\t\t\t\t? template.document\n\t\t\t\t\t\t: undefined\n\tconst chatTemplate: ChatTemplateInterface | undefined =\n\t\ttemplate !== undefined &&\n\t\t!isString(template) &&\n\t\t'render' in template &&\n\t\t'source' in template &&\n\t\tisFunction(template.render)\n\t\t\t? template\n\t\t\t: undefined\n\treturn rows.map((row, index) => {\n\t\tif (!isFinetuneRow(row)) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The finetune row at index ${index} is malformed: pass either \"prompt\" or \"messages\", a string \"completion\", optional non-empty \"group\"/\"label\", and a local \"provenance\".`,\n\t\t\t\t{ code: 'ARGUMENT', context: { row: index } },\n\t\t\t)\n\t\t}\n\t\tcheckRowProvenance(row.provenance)\n\t\tconst promptText =\n\t\t\trow.prompt !== undefined\n\t\t\t\t? row.prompt\n\t\t\t\t: renderFinetunePrompt(row.messages ?? [], index, chatTemplate, templateDoc)\n\t\tif (\n\t\t\t!matchesTokenBound(tokenizer, promptText, limit) ||\n\t\t\t!matchesTokenBound(tokenizer, row.completion, limit)\n\t\t) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The finetune row at index ${index} exceeds the ${limit}-token UTF-8 bound.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { row: index, limit } },\n\t\t\t)\n\t\t}\n\t\tconst promptTokens = tokenizer.encode(promptText)\n\t\tconst completionTokens = tokenizer.encode(row.completion)\n\t\tif (promptTokens.length === 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The finetune row at index ${index} encoded an empty prompt; prompt masking requires at least 1 prompt token.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { row: index } },\n\t\t\t)\n\t\t}\n\t\tif (completionTokens.length === 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The finetune row at index ${index} encoded an empty completion; loss requires at least 1 completion token.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { row: index } },\n\t\t\t)\n\t\t}\n\t\tconst total = promptTokens.length + completionTokens.length\n\t\tif (total > limit) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The finetune row at index ${index} encodes to ${total} tokens, past the limit of ${limit}.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { row: index, tokens: total, limit } },\n\t\t\t)\n\t\t}\n\t\tconst tokens = new Uint32Array(total)\n\t\ttokens.set(promptTokens, 0)\n\t\ttokens.set(completionTokens, promptTokens.length)\n\t\treturn { tokens, prompt: promptTokens.length }\n\t})\n}\n\n/**\n * Renders one chat-message fine-tuning row into prompt text through either a `ChatTemplateInterface`\n * or a compiled `@orkestrel/template` tree.\n *\n * @param messages - The conversation messages to render\n * @param rowIndex - Zero-based row index reported in error context\n * @param chatTemplate - Optional `ChatTemplateInterface`\n * @param compiledTemplate - Optional compiled `@orkestrel/template` tree\n * @returns The rendered prompt text\n *\n * @example\n * ```ts\n * renderFinetunePrompt([{ id: '1', role: 'user', content: 'hi' }], 0, undefined, tree)\n * ```\n */\nexport function renderFinetunePrompt(\n\tmessages: readonly Message[],\n\trowIndex: number,\n\tchatTemplate: ChatTemplateInterface | undefined,\n\tcompiledTemplate: TemplateDocument | undefined,\n): string {\n\tif (chatTemplate !== undefined) {\n\t\treturn chatTemplate.render(messages, { addGenerationPrompt: true })\n\t}\n\tif (compiledTemplate !== undefined) {\n\t\tconst evaluated = attempt(() =>\n\t\t\tevaluateTemplate(compiledTemplate, {\n\t\t\t\tmessages: buildChatMessages(messages),\n\t\t\t\tadd_generation_prompt: true,\n\t\t\t}),\n\t\t)\n\t\tif (!evaluated.success) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The finetune row at index ${rowIndex} failed template rendering: ${isTemplateError(evaluated.error) ? evaluated.error.message : String(evaluated.error)}`,\n\t\t\t\t{ code: 'ARGUMENT', context: { row: rowIndex }, cause: evaluated.error },\n\t\t\t)\n\t\t}\n\t\treturn evaluated.value\n\t}\n\tthrow new InferError(\n\t\t`The finetune row at index ${rowIndex} carries messages, which require options.template.`,\n\t\t{ code: 'ARGUMENT', context: { row: rowIndex } },\n\t)\n}\n\n/**\n * Computes the deterministic SHA-256 dataset digest binding a sequence of `FinetuneRow` records to\n * a resumable training checkpoint.\n *\n * @param rows - The admitted fine-tuning rows in order\n * @returns The 64-character lowercase hexadecimal SHA-256 digest\n *\n * @example\n * ```ts\n * (await computeFinetuneDatasetDigest(rows)).length // 64\n * ```\n */\nexport async function computeFinetuneDatasetDigest(rows: readonly FinetuneRow[]): Promise<Digest> {\n\tconst canonical = canonicalStringify(\n\t\trows.map((row) => ({\n\t\t\t...(row.prompt === undefined ? {} : { prompt: row.prompt }),\n\t\t\t...(row.messages === undefined ? {} : { messages: row.messages }),\n\t\t\tcompletion: row.completion,\n\t\t\t...(row.group === undefined ? {} : { group: row.group }),\n\t\t\t...(row.label === undefined ? {} : { label: row.label }),\n\t\t\tprovenance: row.provenance,\n\t\t})),\n\t)\n\treturn digestBytes(UTF8_ENCODER.encode(canonical ?? '[]'))\n}\n\n/**\n * Attributes per-block and per-target gradient-norm sensitivity over frozen base weights through a\n * `BackwardInterface` and development `TokenSpan` rows, ranking highest-sensitivity decoder blocks\n * and targets to guide static surgical `mode: 'section'` selection.\n *\n * @remarks\n * Configures the backward engine in static `mode: 'section'`, accumulates exact gradients across\n * every development `TokenSpan`, captures the unclipped mean gradient per target through a\n * zero-rate (`rate: 0, decay: 0, first: 0, second: 0, clip: 0`) step so parameters remain\n * unchanged, snapshots the captured gradients, and ranks both individual targets and per-block\n * aggregates by descending L2 norm. Refuses empty `examples` with `ARGUMENT` and respects `signal`\n * with `ABORT`.\n *\n * @param options - The backward engine, architecture, development `TokenSpan` rows, optional layer/target filters, and signal\n * @returns Ranked per-block and per-target gradient-norm attributions and mean cross-entropy loss\n *\n * @example\n * ```ts\n * const trace = await traceSections({ backward, architecture, examples })\n * const topLayers = trace.blocks.slice(0, 2).map((block) => block.layer)\n * ```\n */\nexport async function traceSections(options: SectionTraceOptions): Promise<SectionTraceResult> {\n\tconst { backward, architecture, examples, layers, targets, norms, segment, signal } = options\n\tcheckSignal(signal, 'The section trace')\n\tif (!isArray(examples) || examples.length === 0) {\n\t\tthrow new InferError('Section tracing requires at least one development TokenSpan example.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tconst plan: TrainPlan = {\n\t\tmode: 'section',\n\t\t...(segment === undefined ? {} : { segment }),\n\t\tsection: {\n\t\t\t...(layers === undefined ? {} : { layers }),\n\t\t\t...(targets === undefined ? {} : { targets }),\n\t\t\t...(norms === undefined ? {} : { norms }),\n\t\t},\n\t}\n\tcheckTrainPlan(plan, architecture)\n\tawait backward.configure(plan)\n\tcheckSignal(signal, 'The section trace')\n\tawait backward.zero()\n\tlet lossWeighted = 0\n\tlet tokens = 0\n\tfor (let index = 0; index < examples.length; index += 1) {\n\t\tcheckSignal(signal, 'The section trace')\n\t\tconst example = examples[index]\n\t\tif (example === undefined) continue\n\t\tconst reading = await backward.accumulate(example, signal)\n\t\tlossWeighted += reading.loss * reading.count\n\t\ttokens += reading.count\n\t}\n\tcheckSignal(signal, 'The section trace')\n\t// Captures exact unclipped mean gradients in Adam's first moment while keeping parameters unchanged.\n\tawait backward.step(\n\t\t{\n\t\t\tstep: 1,\n\t\t\trate: 0,\n\t\t\tdecay: 0,\n\t\t\tfirst: 0,\n\t\t\tsecond: 0,\n\t\t\tepsilon: FINETUNER_EPSILON,\n\t\t\tclip: 0,\n\t\t\tscale: 1 / examples.length,\n\t\t},\n\t\tsignal,\n\t)\n\tconst states = await backward.snapshot(signal)\n\tconst suffixToTarget = new Map<string, SectionTarget>(\n\t\tSECTION_TARGETS.map((target) => [SECTION_TARGET_SUFFIXES[target], target]),\n\t)\n\tconst tracedTargets: SectionTraceTarget[] = []\n\tconst blockBuckets = new Map<number, SectionTraceTarget[]>()\n\tlet totalSq = 0\n\tfor (let stateIndex = 0; stateIndex < states.length; stateIndex += 1) {\n\t\tconst state = states[stateIndex]\n\t\tif (state === undefined) continue\n\t\tconst match = SECTION_TENSOR_PATTERN.exec(state.name)\n\t\tconst rawLayer = match?.[1]\n\t\tconst rawSuffix = match?.[2]\n\t\tconst rawTop = match?.[3]\n\t\tconst target =\n\t\t\trawTop !== undefined\n\t\t\t\t? isSectionTarget(rawTop)\n\t\t\t\t\t? rawTop\n\t\t\t\t\t: undefined\n\t\t\t\t: rawSuffix === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: suffixToTarget.get(rawSuffix)\n\t\tif (target === undefined) continue\n\t\tconst layer = rawLayer === undefined ? undefined : Number(rawLayer)\n\t\tconst grad = state.first\n\t\tconst elements = grad.length\n\t\tlet sumSq = 0\n\t\tlet peak = 0\n\t\tfor (let index = 0; index < elements; index += 1) {\n\t\t\tconst value = grad[index] ?? 0\n\t\t\tsumSq += value * value\n\t\t\tconst magnitude = Math.abs(value)\n\t\t\tif (magnitude > peak) peak = magnitude\n\t\t}\n\t\ttotalSq += sumSq\n\t\tconst norm = Math.sqrt(sumSq)\n\t\tconst rms = elements > 0 ? norm / Math.sqrt(elements) : 0\n\t\tconst entry: SectionTraceTarget = {\n\t\t\tname: state.name,\n\t\t\t...(layer === undefined ? {} : { layer }),\n\t\t\ttarget,\n\t\t\telements,\n\t\t\tnorm,\n\t\t\trms,\n\t\t\tmaximum: peak,\n\t\t}\n\t\ttracedTargets.push(entry)\n\t\tif (layer !== undefined) {\n\t\t\tconst bucket = blockBuckets.get(layer) ?? []\n\t\t\tbucket.push(entry)\n\t\t\tblockBuckets.set(layer, bucket)\n\t\t}\n\t}\n\tconst sortedTargets = tracedTargets.toSorted(\n\t\t(left, right) =>\n\t\t\tright.norm - left.norm ||\n\t\t\t(left.layer ?? Number.POSITIVE_INFINITY) - (right.layer ?? Number.POSITIVE_INFINITY) ||\n\t\t\tSECTION_TARGETS.indexOf(left.target) - SECTION_TARGETS.indexOf(right.target),\n\t)\n\tconst blocks: readonly SectionTraceBlock[] = [...blockBuckets.entries()]\n\t\t.map(([layer, entries]) => {\n\t\t\tconst ordered = entries.toSorted(\n\t\t\t\t(left, right) =>\n\t\t\t\t\tright.norm - left.norm ||\n\t\t\t\t\tSECTION_TARGETS.indexOf(left.target) - SECTION_TARGETS.indexOf(right.target),\n\t\t\t)\n\t\t\tconst blockSq = ordered.reduce((sum, item) => sum + item.norm * item.norm, 0)\n\t\t\tconst elements = ordered.reduce((sum, item) => sum + item.elements, 0)\n\t\t\tconst norm = Math.sqrt(blockSq)\n\t\t\treturn {\n\t\t\t\tlayer,\n\t\t\t\tnorm,\n\t\t\t\trms: elements > 0 ? norm / Math.sqrt(elements) : 0,\n\t\t\t\telements,\n\t\t\t\ttargets: ordered,\n\t\t\t}\n\t\t})\n\t\t.toSorted((left, right) => right.norm - left.norm || left.layer - right.layer)\n\treturn {\n\t\tloss: tokens > 0 ? lossWeighted / tokens : 0,\n\t\ttokens,\n\t\ttotal: Math.sqrt(totalSq),\n\t\tblocks,\n\t\ttargets: sortedTargets,\n\t}\n}\n","import type { JSONRecord } from '@orkestrel/contract'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport type {\n\tArchitecture,\n\tBackwardInterface,\n\tChatTemplateInterface,\n\tDigest,\n\tParameterState,\n\tTokenizerInterface,\n\tTrainPlan,\n} from '@orkestrel/infer'\nimport type { TemplateDocument, TemplateTreeInterface } from '@orkestrel/template'\nimport type {\n\tCheckpoint,\n\tCheckpointTarget,\n\tFinetuneRow,\n\tFinetunerEventMap,\n\tFinetunerInterface,\n\tFinetunerOptions,\n\tFinetunerResult,\n\tFinetunerSettings,\n\tFinetunerStepEvent,\n\tTrainerSettings,\n} from '../types.js'\nimport { isArray, isSafeInteger, isString } from '@orkestrel/contract'\nimport { Emitter } from '@orkestrel/emitter'\nimport {\n\tAdapter,\n\tcheckSignal,\n\tdigestBytes,\n\tInferError,\n\tMemorySource,\n\treadSection,\n\tSection,\n} from '@orkestrel/infer'\nimport {\n\tadmitFinetuneRows,\n\tassignFolds,\n\tbuildAdapterGGUF,\n\tbuildCheckpointGGUF,\n\tbuildSectionGGUF,\n\tcheckFolds,\n\tcomputeFinetuneDatasetDigest,\n\tcomputeFinetunerRate,\n\treadCheckpointGGUF,\n\tresolveFinetunerSettings,\n\tstepRandom,\n} from '../helpers.js'\n\n/**\n * Drives cross-host LoRA adapter fine-tuning and static surgical or LISA rotating full-rank\n * section retraining over an `@orkestrel/infer` `BackwardInterface`.\n *\n * @remarks\n * Validates options at construction through `resolveFinetunerSettings`, enforces local row\n * provenance through `checkRowProvenance` and prompt-masked tokenization through\n * `admitFinetuneRows` before step 1, partitions group-preserving folds through `assignFolds` and\n * `checkFolds`, advances example ordering deterministically through `stepRandom(rng)`, applies\n * linear warmup with cosine or constant schedules, persists GGUF v3 checkpoints every\n * `checkpoint.every` steps, resumes bit-for-bit on matching `base` and `dataset` bindings\n * (`BINDING` on mismatch), emits typed lifecycle events on `emitter`, and honors `AbortSignal`\n * cooperatively with the `ABORT` code.\n *\n * @example\n * ```ts\n * const finetuner = new Finetuner({\n * \tmode: 'adapter',\n * \tbackward,\n * \ttokenizer: backbone.tokenizer,\n * \tarchitecture: backbone.architecture,\n * \tbase: backbone.digest,\n * \trows,\n * \tadapter: { rank: 4, alpha: 8 },\n * })\n * const result = await finetuner.execute()\n * ```\n */\nexport class Finetuner implements FinetunerInterface {\n\treadonly #settings: FinetunerSettings\n\treadonly #backward: BackwardInterface\n\treadonly #tokenizer: TokenizerInterface\n\treadonly #architecture: Architecture\n\treadonly #rows: readonly FinetuneRow[]\n\treadonly #template:\n\t\t| ChatTemplateInterface\n\t\t| TemplateTreeInterface\n\t\t| TemplateDocument\n\t\t| string\n\t\t| undefined\n\treadonly #emitter: Emitter<FinetunerEventMap>\n\t#step = 0\n\t#epoch = 0\n\t#cursor = 0\n\t#rng = 0\n\t#epochRng = 0\n\t#order: number[] = []\n\n\t/**\n\t * Creates a cross-host finetuner over a backward engine, tokenizer, architecture, and rows.\n\t *\n\t * @param options - The training mode, backward engine, tokenizer, architecture, base digest,\n\t * rows, optional template, optimizer/loop/mode/checkpoint settings, and emitter hooks\n\t */\n\tconstructor(options: FinetunerOptions) {\n\t\tthis.#settings = resolveFinetunerSettings(options)\n\t\tthis.#backward = options.backward\n\t\tthis.#tokenizer = options.tokenizer\n\t\tthis.#architecture = options.architecture\n\t\tthis.#rows = [...options.rows]\n\t\tthis.#template = options.template\n\t\tthis.#emitter = new Emitter<FinetunerEventMap>({\n\t\t\t...(options.on === undefined ? {} : { on: options.on }),\n\t\t\t...(options.error === undefined ? {} : { error: options.error }),\n\t\t})\n\t}\n\n\t/** Exposes the typed synchronous lifecycle event emitter. */\n\tget emitter(): EmitterInterface<FinetunerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\t/**\n\t * Executes the configured fine-tuning run, resuming from a checkpoint when configured, and\n\t * returns the exported immutable weights, GGUF v3 bytes, counters, and step history.\n\t *\n\t * @param signal - Cancels the run cooperatively; rejects with the `ABORT` code\n\t * @returns The completed fine-tuning result\n\t */\n\tasync execute(signal?: AbortSignal): Promise<FinetunerResult> {\n\t\tcheckSignal(signal, 'The fine-tuning')\n\t\tconst settings = this.#settings\n\t\tconst spans = admitFinetuneRows(\n\t\t\tthis.#rows,\n\t\t\tthis.#tokenizer,\n\t\t\tsettings.loop.limit,\n\t\t\tthis.#template,\n\t\t)\n\t\tconst [trainIndices, held] = this.#partitionRows()\n\t\tconst dataset = await computeFinetuneDatasetDigest(this.#rows)\n\t\tcheckSignal(signal, 'The fine-tuning')\n\t\tconst pendingResume = await this.#loadResumeCheckpoint(dataset, signal)\n\t\tconst plan: TrainPlan = {\n\t\t\tmode: settings.mode,\n\t\t\tsegment: settings.loop.segment,\n\t\t\t...(settings.adapter === undefined\n\t\t\t\t? {}\n\t\t\t\t: { adapter: { ...settings.adapter, seed: settings.loop.seed } }),\n\t\t\t...(settings.section === undefined ? {} : { section: settings.section }),\n\t\t}\n\t\tawait this.#backward.configure(plan)\n\t\tcheckSignal(signal, 'The fine-tuning')\n\n\t\tthis.#step = 0\n\t\tthis.#epoch = 0\n\t\tthis.#cursor = 0\n\t\tthis.#rng = settings.loop.seed >>> 0\n\t\tthis.#epochRng = this.#rng\n\t\tthis.#order = [...trainIndices]\n\n\t\tconst resumed =\n\t\t\tpendingResume === undefined\n\t\t\t\t? false\n\t\t\t\t: await this.#applyResumeCheckpoint(pendingResume, trainIndices, signal)\n\t\tconst stepsPerEpoch = Math.max(1, Math.ceil(trainIndices.length / settings.loop.batch))\n\t\tconst totalSteps = settings.loop.steps ?? settings.loop.epochs * stepsPerEpoch\n\t\tthis.#emitter.emit('start', {\n\t\t\tmode: settings.mode,\n\t\t\tstep: this.#step,\n\t\t\tepoch: this.#epoch,\n\t\t\tresumed,\n\t\t\ttotal: totalSteps,\n\t\t})\n\n\t\tconst history: FinetunerStepEvent[] = []\n\t\tconst remainingSteps = Math.max(0, totalSteps - this.#step)\n\t\tlet totalLossWeighted = 0\n\t\tlet totalTokens = 0\n\t\tlet epochLossWeighted = 0\n\t\tlet epochTokens = 0\n\t\tfor (let stepOffset = 0; stepOffset < remainingSteps; stepOffset += 1) {\n\t\t\tcheckSignal(signal, 'The fine-tuning')\n\t\t\tconst [batch, epochFinished] = this.#drawBatch(trainIndices, settings.loop.batch)\n\t\t\tawait this.#backward.zero()\n\t\t\tlet batchLossWeighted = 0\n\t\t\tlet batchTokens = 0\n\t\t\tfor (let slot = 0; slot < batch.length; slot += 1) {\n\t\t\t\tcheckSignal(signal, 'The fine-tuning')\n\t\t\t\tconst rowIndex = batch[slot]\n\t\t\t\tconst span = rowIndex === undefined ? undefined : spans[rowIndex]\n\t\t\t\tif (span === undefined) continue\n\t\t\t\tconst reading = await this.#backward.accumulate(span, signal)\n\t\t\t\tbatchLossWeighted += reading.loss * reading.count\n\t\t\t\tbatchTokens += reading.count\n\t\t\t}\n\t\t\tcheckSignal(signal, 'The fine-tuning')\n\t\t\tconst nextStep = this.#step + 1\n\t\t\tconst rate = computeFinetunerRate(\n\t\t\t\tnextStep,\n\t\t\t\ttotalSteps,\n\t\t\t\tsettings.optimizer.rate,\n\t\t\t\tsettings.optimizer.warmup,\n\t\t\t\tsettings.optimizer.schedule,\n\t\t\t)\n\t\t\tconst norm = await this.#backward.step(\n\t\t\t\t{\n\t\t\t\t\tstep: nextStep,\n\t\t\t\t\trate,\n\t\t\t\t\tdecay: settings.optimizer.decay,\n\t\t\t\t\tfirst: settings.optimizer.first,\n\t\t\t\t\tsecond: settings.optimizer.second,\n\t\t\t\t\tepsilon: settings.optimizer.epsilon,\n\t\t\t\t\tclip: settings.optimizer.clip,\n\t\t\t\t\tscale: 1 / batch.length,\n\t\t\t\t},\n\t\t\t\tsignal,\n\t\t\t)\n\t\t\tthis.#step = nextStep\n\t\t\tconst stepLoss = batchTokens > 0 ? batchLossWeighted / batchTokens : 0\n\t\t\ttotalLossWeighted += batchLossWeighted\n\t\t\ttotalTokens += batchTokens\n\t\t\tepochLossWeighted += batchLossWeighted\n\t\t\tepochTokens += batchTokens\n\t\t\tconst event: FinetunerStepEvent = {\n\t\t\t\tstep: this.#step,\n\t\t\t\tepoch: this.#epoch,\n\t\t\t\tcursor: this.#cursor,\n\t\t\t\tloss: stepLoss,\n\t\t\t\ttokens: batchTokens,\n\t\t\t\trate,\n\t\t\t\tnorm,\n\t\t\t}\n\t\t\thistory.push(event)\n\t\t\tthis.#emitter.emit('step', event)\n\t\t\tif (epochFinished) {\n\t\t\t\tthis.#emitter.emit('epoch', {\n\t\t\t\t\tepoch: this.#epoch,\n\t\t\t\t\tstep: this.#step,\n\t\t\t\t\tloss: epochTokens > 0 ? epochLossWeighted / epochTokens : 0,\n\t\t\t\t})\n\t\t\t\tepochLossWeighted = 0\n\t\t\t\tepochTokens = 0\n\t\t\t}\n\t\t\tif (settings.checkpoint !== undefined && this.#step % settings.checkpoint.every === 0) {\n\t\t\t\tawait this.#saveCheckpoint(dataset, signal)\n\t\t\t}\n\t\t}\n\n\t\tcheckSignal(signal, 'The fine-tuning')\n\t\tconst exported = await this.#backward.export(signal)\n\t\tconst loss = totalTokens > 0 ? totalLossWeighted / totalTokens : 0\n\t\tif (settings.mode === 'adapter' && 'pairs' in exported) {\n\t\t\tconst bytes = buildAdapterGGUF(exported)\n\t\t\tconst adapter = new Adapter({ ...exported, digest: await digestBytes(bytes) })\n\t\t\tconst result: FinetunerResult = {\n\t\t\t\tmode: 'adapter',\n\t\t\t\tstep: this.#step,\n\t\t\t\tepoch: this.#epoch,\n\t\t\t\tcursor: this.#cursor,\n\t\t\t\trng: this.#rng,\n\t\t\t\tdataset,\n\t\t\t\tloss,\n\t\t\t\thistory,\n\t\t\t\theld,\n\t\t\t\tadapter,\n\t\t\t\tbytes,\n\t\t\t}\n\t\t\tthis.#emitter.emit('done', result)\n\t\t\treturn result\n\t\t}\n\t\tif (settings.mode === 'section' && 'entries' in exported) {\n\t\t\tconst format = settings.section?.format ?? 'F32'\n\t\t\tconst bytes = buildSectionGGUF(exported, format)\n\t\t\tconst section =\n\t\t\t\tformat === 'F32'\n\t\t\t\t\t? new Section({ ...exported, digest: await digestBytes(bytes) })\n\t\t\t\t\t: new Section(await readSection(new MemorySource(bytes), signal))\n\t\t\tconst result: FinetunerResult = {\n\t\t\t\tmode: 'section',\n\t\t\t\tstep: this.#step,\n\t\t\t\tepoch: this.#epoch,\n\t\t\t\tcursor: this.#cursor,\n\t\t\t\trng: this.#rng,\n\t\t\t\tdataset,\n\t\t\t\tloss,\n\t\t\t\thistory,\n\t\t\t\theld,\n\t\t\t\tsection,\n\t\t\t\tbytes,\n\t\t\t}\n\t\t\tthis.#emitter.emit('done', result)\n\t\t\treturn result\n\t\t}\n\t\tthrow new InferError(\n\t\t\t`The backward engine exported a payload incompatible with mode \"${settings.mode}\".`,\n\t\t\t{ code: 'FORMAT', context: { mode: settings.mode } },\n\t\t)\n\t}\n\n\t// Partitions admitted rows into training and optional held validation indexes preserving groups.\n\t#partitionRows(): readonly [train: readonly number[], held: readonly number[]] {\n\t\tconst { folds, fold, seed } = this.#settings.loop\n\t\tif (folds === undefined) {\n\t\t\treturn [this.#rows.map((_, index) => index), []]\n\t\t}\n\t\tconst uniqueLabels = [...new Set(this.#rows.map((row) => row.label ?? 'default'))]\n\t\tconst labelOrder = new Map(uniqueLabels.map((label, place) => [label, place]))\n\t\tconst strata = this.#rows.map((row) => labelOrder.get(row.label ?? 'default') ?? 0)\n\t\tconst groups = this.#rows.some((row) => row.group !== undefined)\n\t\t\t? this.#rows.map((row) => row.group)\n\t\t\t: undefined\n\t\tconst assignment = assignFolds(strata, folds, seed, groups)\n\t\tconst foldSettings: TrainerSettings = {\n\t\t\tdepth: this.#architecture.layers,\n\t\t\tlabels: uniqueLabels,\n\t\t\ttarget: undefined,\n\t\t\tfolds,\n\t\t\trepeats: 1,\n\t\t\tseed,\n\t\t\tpenalties: [0],\n\t\t}\n\t\tcheckFolds(assignment, strata, foldSettings, groups)\n\t\tconst heldFold = fold ?? 0\n\t\tconst held = assignment.flatMap((assigned, index) => (assigned === heldFold ? [index] : []))\n\t\tconst train = assignment.flatMap((assigned, index) => (assigned === heldFold ? [] : [index]))\n\t\tif (train.length === 0) {\n\t\t\tthrow new InferError(`Holding fold ${heldFold} out of ${folds} leaves no training rows.`, {\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\tcontext: { fold: heldFold, folds },\n\t\t\t})\n\t\t}\n\t\treturn [train, held]\n\t}\n\n\t// Draws the next batch of training row indexes through incremental Fisher-Yates using stepRandom.\n\t#drawBatch(\n\t\ttrainIndices: readonly number[],\n\t\tbatchSize: number,\n\t): readonly [batch: readonly number[], epochFinished: boolean] {\n\t\tconst batch: number[] = []\n\t\tlet completed = 0\n\t\tfor (let slot = 0; slot < batchSize; slot += 1) {\n\t\t\tif (this.#cursor === 0) {\n\t\t\t\tthis.#order = [...trainIndices]\n\t\t\t\tthis.#epochRng = this.#rng\n\t\t\t}\n\t\t\tconst remaining = this.#order.length - this.#cursor\n\t\t\tconst [draw, nextRng] = stepRandom(this.#rng)\n\t\t\tthis.#rng = nextRng\n\t\t\tconst pick = this.#cursor + Math.floor(draw * remaining)\n\t\t\tconst chosen = this.#order[pick] ?? trainIndices[0] ?? 0\n\t\t\tthis.#order[pick] = this.#order[this.#cursor] ?? chosen\n\t\t\tthis.#order[this.#cursor] = chosen\n\t\t\tbatch.push(chosen)\n\t\t\tthis.#cursor += 1\n\t\t\tif (this.#cursor >= this.#order.length) {\n\t\t\t\tthis.#cursor = 0\n\t\t\t\tthis.#epoch += 1\n\t\t\t\tcompleted += 1\n\t\t\t}\n\t\t}\n\t\treturn [batch, completed > 0]\n\t}\n\n\t// Loads and validates any stored resume checkpoint before touching the backward engine.\n\tasync #loadResumeCheckpoint(\n\t\tdataset: Digest,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<Checkpoint | undefined> {\n\t\tconst checkpoint = this.#settings.checkpoint\n\t\tif (checkpoint === undefined || !checkpoint.resume) return undefined\n\t\tconst entry = await checkpoint.store.load(checkpoint.id, signal)\n\t\tif (entry === undefined) return undefined\n\t\tconst loaded = await readCheckpointGGUF(new MemorySource(entry.bytes), {\n\t\t\tbase: this.#settings.base,\n\t\t\tdataset,\n\t\t\t...(signal === undefined ? {} : { signal }),\n\t\t})\n\t\tif (loaded.mode !== this.#settings.mode) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The checkpoint mode is \"${loaded.mode}\", not expected \"${this.#settings.mode}\".`,\n\t\t\t\t{ code: 'BINDING', context: { expected: this.#settings.mode, actual: loaded.mode } },\n\t\t\t)\n\t\t}\n\t\tif (loaded.fold !== this.#settings.loop.fold) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The checkpoint fold is ${String(loaded.fold)}, not expected ${String(this.#settings.loop.fold)}.`,\n\t\t\t\t{ code: 'BINDING', context: { expected: this.#settings.loop.fold, actual: loaded.fold } },\n\t\t\t)\n\t\t}\n\t\treturn loaded\n\t}\n\n\t// Restores validated checkpoint weights, AdamW moments, counters, and permutation state.\n\tasync #applyResumeCheckpoint(\n\t\tloaded: Checkpoint,\n\t\ttrainIndices: readonly number[],\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<boolean> {\n\t\tconst rawInactive = loaded.config['inactive']\n\t\tconst inactive = new Set<string>(isArray(rawInactive) ? rawInactive.filter(isString) : [])\n\t\tconst states: readonly ParameterState[] = loaded.targets.map((target) => {\n\t\t\tconst shape =\n\t\t\t\tthis.#settings.mode === 'section' && target.rows === 1\n\t\t\t\t\t? [target.columns]\n\t\t\t\t\t: [target.rows, target.columns]\n\t\t\tif (inactive.has(target.name)) {\n\t\t\t\treturn {\n\t\t\t\t\tname: target.name,\n\t\t\t\t\tshape,\n\t\t\t\t\tvalues: target.parameters,\n\t\t\t\t\tfirst: new Float32Array(0),\n\t\t\t\t\tsecond: new Float32Array(0),\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tname: target.name,\n\t\t\t\tshape,\n\t\t\t\tvalues: target.parameters,\n\t\t\t\tfirst: target.first,\n\t\t\t\tsecond: target.second,\n\t\t\t}\n\t\t})\n\t\tawait this.#backward.restore(states, signal)\n\t\tthis.#step = loaded.step\n\t\tthis.#epoch = loaded.epoch\n\t\tthis.#cursor = loaded.cursor\n\t\tthis.#rng = loaded.rng\n\t\tconst rawEpochRng = loaded.config['epochRng']\n\t\tthis.#epochRng =\n\t\t\tisSafeInteger(rawEpochRng) && rawEpochRng >= 0 && rawEpochRng <= 0xffff_ffff\n\t\t\t\t? rawEpochRng\n\t\t\t\t: loaded.rng\n\t\tthis.#order = [...trainIndices]\n\t\tif (this.#cursor > 0) {\n\t\t\tlet replay = this.#epochRng\n\t\t\tfor (let pos = 0; pos < this.#cursor && pos < this.#order.length; pos += 1) {\n\t\t\t\tconst remaining = this.#order.length - pos\n\t\t\t\tconst [draw, nextReplay] = stepRandom(replay)\n\t\t\t\treplay = nextReplay\n\t\t\t\tconst pick = pos + Math.floor(draw * remaining)\n\t\t\t\tconst chosen = this.#order[pick] ?? this.#order[pos] ?? 0\n\t\t\t\tthis.#order[pick] = this.#order[pos] ?? chosen\n\t\t\t\tthis.#order[pos] = chosen\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\n\t// Snapshots active and inactive parameter states into a GGUF v3 checkpoint and persists it.\n\tasync #saveCheckpoint(dataset: Digest, signal: AbortSignal | undefined): Promise<void> {\n\t\tconst checkpoint = this.#settings.checkpoint\n\t\tif (checkpoint === undefined) return\n\t\tconst states = await this.#backward.snapshot(signal)\n\t\tconst inactive: string[] = []\n\t\tconst targets: readonly CheckpointTarget[] = states.map((state) => {\n\t\t\tconst rows = state.shape.length === 1 ? 1 : (state.shape[0] ?? 1)\n\t\t\tconst columns = state.shape.length === 1 ? (state.shape[0] ?? 1) : (state.shape[1] ?? 1)\n\t\t\tconst isInactive = state.first.length === 0 && state.second.length === 0\n\t\t\tif (isInactive) inactive.push(state.name)\n\t\t\treturn {\n\t\t\t\tname: state.name,\n\t\t\t\trows,\n\t\t\t\tcolumns,\n\t\t\t\tparameters: state.values,\n\t\t\t\tfirst: isInactive ? new Float32Array(state.values.length) : state.first,\n\t\t\t\tsecond: isInactive ? new Float32Array(state.values.length) : state.second,\n\t\t\t}\n\t\t})\n\t\tconst config: JSONRecord = {\n\t\t\trate: this.#settings.optimizer.rate,\n\t\t\tdecay: this.#settings.optimizer.decay,\n\t\t\tfirst: this.#settings.optimizer.first,\n\t\t\tsecond: this.#settings.optimizer.second,\n\t\t\tepsilon: this.#settings.optimizer.epsilon,\n\t\t\tclip: this.#settings.optimizer.clip,\n\t\t\twarmup: this.#settings.optimizer.warmup,\n\t\t\tschedule: this.#settings.optimizer.schedule,\n\t\t\tbatch: this.#settings.loop.batch,\n\t\t\tepochs: this.#settings.loop.epochs,\n\t\t\tepochRng: this.#epochRng,\n\t\t\t...(inactive.length === 0 ? {} : { inactive }),\n\t\t}\n\t\tconst record: Checkpoint = {\n\t\t\tmode: this.#settings.mode,\n\t\t\tbase: this.#settings.base,\n\t\t\tdataset,\n\t\t\tstep: this.#step,\n\t\t\tepoch: this.#epoch,\n\t\t\tcursor: this.#cursor,\n\t\t\tseed: this.#settings.loop.seed,\n\t\t\trng: this.#rng,\n\t\t\t...(this.#settings.loop.fold === undefined ? {} : { fold: this.#settings.loop.fold }),\n\t\t\tconfig,\n\t\t\ttargets,\n\t\t}\n\t\tconst bytes = buildCheckpointGGUF(record)\n\t\tawait checkpoint.store.save({ id: checkpoint.id, bytes }, signal)\n\t\tthis.#emitter.emit('checkpoint', {\n\t\t\tid: checkpoint.id,\n\t\t\tstep: this.#step,\n\t\t\tepoch: this.#epoch,\n\t\t\tbytes: bytes.byteLength,\n\t\t})\n\t}\n}\n","import type { QueueInterface } from '@orkestrel/queue'\nimport type {\n\tFinetunerInterface,\n\tFinetunerOptions,\n\tTrainQueueJob,\n\tTrainQueueOptions,\n\tTrainQueueResource,\n\tTrainQueueResult,\n} from './types.js'\nimport { checkSignal, joinBytes, InferError } from '@orkestrel/infer'\nimport { createWorker } from '@orkestrel/worker'\nimport { Finetuner } from './finetuners/Finetuner.js'\nimport {\n\tbuildCheckpointGGUF,\n\tcalibrateAdapter,\n\tcheckCheckpointId,\n\tmergeGGUF,\n\tmergeSafetensors,\n\ttraceHead,\n\ttraceSections,\n\twriteByteSink,\n} from './helpers.js'\n\n/**\n * Creates a cross-host `Finetuner` driving LoRA adapter fine-tuning or static surgical / LISA\n * full-rank section retraining over a `BackwardInterface`.\n *\n * @param options - The finetuner configuration\n * @returns The `FinetunerInterface` instance\n *\n * @example\n * ```ts\n * const finetuner = createFinetuner({\n * \tmode: 'adapter',\n * \tbackward,\n * \ttokenizer: backbone.tokenizer,\n * \tarchitecture: backbone.architecture,\n * \tbase: backbone.digest,\n * \trows,\n * \tadapter: { rank: 4, alpha: 8 },\n * })\n * const result = await finetuner.execute()\n * ```\n */\nexport function createFinetuner(options: FinetunerOptions): FinetunerInterface {\n\treturn new Finetuner(options)\n}\n\n/**\n * Creates a resource-backed background training queue over `@orkestrel/worker`'s `createWorker`\n * composing pooled `{ backbone, backward }` resources for fine-tuning, adapter calibration, head\n * and section tracing, checkpoint export, and streaming GGUF or safetensors merges.\n *\n * @remarks\n * Operates strictly at the outer job-queue boundary (never inside inner SIMD or token loops),\n * working identically in Node and offline browsers. Every job honors both the queue attempt\n * `context.signal` and any per-job `signal` through `AbortSignal.any`, and `@orkestrel/worker`\n * releases every leased resource in a `finally` block on completion, error, or cancellation.\n * Calling `destroy()` tears down the queue, then the pool, and finally the emitter behind one\n * idempotent barrier.\n *\n * @param options - The resource pool, concurrency, retry, timeout, store, and emitter hooks\n * @returns A `QueueInterface` accepting `TrainQueueJob` payloads and resolving `TrainQueueResult`\n *\n * @example\n * ```ts\n * const queue = createTrainQueue({\n * \tpool: { create: async () => ({ backbone, backward }) },\n * \tconcurrency: 1,\n * })\n * const out = await queue.enqueue({ job: 'calibrate', options: calibrationOptions })\n * await queue.destroy()\n * ```\n */\nexport function createTrainQueue(\n\toptions: TrainQueueOptions,\n): QueueInterface<TrainQueueJob, TrainQueueResult> {\n\treturn createWorker<TrainQueueJob, TrainQueueResource, TrainQueueResult>({\n\t\tpool: options.pool,\n\t\t...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),\n\t\t...(options.retries === undefined ? {} : { retries: options.retries }),\n\t\t...(options.timeout === undefined ? {} : { timeout: options.timeout }),\n\t\t...(options.store === undefined ? {} : { store: options.store }),\n\t\t...(options.on === undefined ? {} : { on: options.on }),\n\t\t...(options.error === undefined ? {} : { error: options.error }),\n\t\thandler: async (input, resource, context) => {\n\t\t\tconst effective =\n\t\t\t\tinput.signal === undefined\n\t\t\t\t\t? context.signal\n\t\t\t\t\t: AbortSignal.any([context.signal, input.signal])\n\t\t\tcheckSignal(effective, `The ${input.job} job`)\n\t\t\tif (input.job === 'finetune') {\n\t\t\t\tif (resource.backward === undefined) {\n\t\t\t\t\tthrow new InferError(\n\t\t\t\t\t\t'The pooled training resource lacks a backward engine required for a finetune job.',\n\t\t\t\t\t\t{ code: 'ARGUMENT', context: { job: input.job } },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tconst finetuner = new Finetuner({ ...input.options, backward: resource.backward })\n\t\t\t\tconst result = await finetuner.execute(effective)\n\t\t\t\treturn { job: 'finetune', result }\n\t\t\t}\n\t\t\tif (input.job === 'calibrate') {\n\t\t\t\tconst result = await calibrateAdapter({ ...input.options, signal: effective })\n\t\t\t\treturn { job: 'calibrate', result }\n\t\t\t}\n\t\t\tif (input.job === 'trace') {\n\t\t\t\tconst backbone = input.options.backbone ?? resource.backbone\n\t\t\t\tif (backbone === undefined) {\n\t\t\t\t\tthrow new InferError(\n\t\t\t\t\t\t'The pooled training resource lacks a backbone required for a trace job.',\n\t\t\t\t\t\t{ code: 'ARGUMENT', context: { job: input.job } },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tconst result = await traceHead({ ...input.options, backbone, signal: effective })\n\t\t\t\treturn { job: 'trace', result }\n\t\t\t}\n\t\t\tif (input.job === 'sections') {\n\t\t\t\tif (resource.backward === undefined) {\n\t\t\t\t\tthrow new InferError(\n\t\t\t\t\t\t'The pooled training resource lacks a backward engine required for a sections job.',\n\t\t\t\t\t\t{ code: 'ARGUMENT', context: { job: input.job } },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tconst result = await traceSections({\n\t\t\t\t\t...input.options,\n\t\t\t\t\tbackward: resource.backward,\n\t\t\t\t\tsignal: effective,\n\t\t\t\t})\n\t\t\t\treturn { job: 'sections', result }\n\t\t\t}\n\t\t\tif (input.job === 'checkpoint') {\n\t\t\t\tcheckCheckpointId(input.id)\n\t\t\t\tconst bytes = buildCheckpointGGUF(input.checkpoint)\n\t\t\t\tcheckSignal(effective, 'The checkpoint job')\n\t\t\t\tif (input.store !== undefined) {\n\t\t\t\t\tawait input.store.save({ id: input.id, bytes }, effective)\n\t\t\t\t}\n\t\t\t\treturn { job: 'checkpoint', id: input.id, bytes }\n\t\t\t}\n\t\t\tif (input.job === 'mergeGGUF') {\n\t\t\t\tconst stream = mergeGGUF({ ...input.options, signal: effective })\n\t\t\t\tif (input.sink !== undefined) {\n\t\t\t\t\tawait writeByteSink(stream, input.sink, effective)\n\t\t\t\t\treturn { job: 'mergeGGUF', bytes: new Uint8Array(0) }\n\t\t\t\t}\n\t\t\t\tconst chunks: Array<Uint8Array<ArrayBuffer>> = []\n\t\t\t\tfor await (const chunk of stream) {\n\t\t\t\t\tcheckSignal(effective, 'The mergeGGUF job')\n\t\t\t\t\tchunks.push(chunk)\n\t\t\t\t}\n\t\t\t\treturn { job: 'mergeGGUF', bytes: joinBytes(chunks) }\n\t\t\t}\n\t\t\tconst stream = mergeSafetensors({ ...input.options, signal: effective })\n\t\t\tif (input.sink !== undefined) {\n\t\t\t\tawait writeByteSink(stream, input.sink, effective)\n\t\t\t\treturn { job: 'mergeSafetensors', bytes: new Uint8Array(0) }\n\t\t\t}\n\t\t\tconst chunks: Array<Uint8Array<ArrayBuffer>> = []\n\t\t\tfor await (const chunk of stream) {\n\t\t\t\tcheckSignal(effective, 'The mergeSafetensors job')\n\t\t\t\tchunks.push(chunk)\n\t\t\t}\n\t\t\treturn { job: 'mergeSafetensors', bytes: joinBytes(chunks) }\n\t\t},\n\t})\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA4BA,IAAa,gBAAgB;;;;;;;;;;;;;AAc7B,IAAa,qBAAqB;;;;;;;;;AAUlC,IAAa,kBAAkB;;;;;;;;;AAU/B,IAAa,eAAe;;;;;;;;;;;;;AAc5B,IAAa,oBAAuC,OAAO,OAAO;CAAC;CAAM;CAAM;CAAM;CAAM;AAAC,CAAC;;;;;;;;;AAU7F,IAAa,YAAY;;;;;;;;;AAUzB,IAAa,WAAW;;;;;;;;;;;;;AAcxB,IAAa,aAAa,OAAO,OAAO;CAAE,OAAO;CAAK,MAAM;AAAI,CAAC;;;;;;;;;AAUjE,IAAa,cAAc,OAAO,OAAO;CAAE,OAAO;CAAO,MAAM;AAAM,CAAC;;;;;;;;;AAUtE,IAAa,eAAe;;;;;;;;;;;;;;;AAgB5B,IAAa,YAAY,OAAO,OAAO;CACtC,YAAY;CACZ,OAAO;CACP,MAAM;CACN,MAAM;CACN,MAAM;CACN,OAAO;CACP,OAAO;AACR,CAAC;;;;;;;;;;;;;;;AAgBD,IAAa,YAAY;;;;;;;;;;;;;;AAezB,IAAa,YAAY;;;;;;;;;;AAWzB,IAAa,cAAc;;;;;;;;;;;;;;;;;;;;;;;AAwB3B,IAAa,cAA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,KAAK;MAAa,uBAAO,IAAI,WAAW,CAAC;KAAE;IACrD;IACA,MAAM,SAAyC,CAAC;IAChD,WAAW,MAAM,SAAS,QAAQ;KACjC,YAAY,WAAW,mBAAmB;KAC1C,OAAO,KAAK,KAAK;IAClB;IACA,OAAO;KAAE,KAAK;KAAa,OAAO,UAAU,MAAM;IAAE;GACrD;GACA,MAAM,SAAS,iBAAiB;IAAE,GAAG,MAAM;IAAS,QAAQ;GAAU,CAAC;GACvE,IAAI,MAAM,SAAS,KAAA,GAAW;IAC7B,MAAM,cAAc,QAAQ,MAAM,MAAM,SAAS;IACjD,OAAO;KAAE,KAAK;KAAoB,uBAAO,IAAI,WAAW,CAAC;IAAE;GAC5D;GACA,MAAM,SAAyC,CAAC;GAChD,WAAW,MAAM,SAAS,QAAQ;IACjC,YAAY,WAAW,0BAA0B;IACjD,OAAO,KAAK,KAAK;GAClB;GACA,OAAO;IAAE,KAAK;IAAoB,OAAO,UAAU,MAAM;GAAE;EAC5D;CACD,CAAC;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/core/constants.ts","../../../src/core/validators.ts","../../../src/core/fitters/SerialFitter.ts","../../../src/core/fitters/ThreadFitter.ts","../../../src/core/trainers/Trainer.ts","../../../src/core/helpers.ts","../../../src/core/finetuners/Finetuner.ts","../../../src/core/factories.ts"],"sourcesContent":["import type {\n\tAdapterTarget,\n\tArchitectureFamily,\n\tGGUFFormat,\n\tSectionTarget,\n\tThreadProgram,\n} from '@orkestrel/infer'\nimport type {\n\tFinetunerSchedule,\n\tMergeGGUFFormat,\n\tPEFTTargetSpec,\n\tPrecisionFormat,\n\tSectionTargetSpec,\n} from './types.js'\n\n/**\n * Holds the stratified fold count a trainer runs when its options name none.\n *\n * @remarks\n * One fold of the first repeat is the held calibration split, so with 5 folds a label of 17 rows\n * holds 3 or 4 rows out for calibration and fits on the rest. A label needs at least as many rows as\n * folds.\n *\n * @example\n * ```ts\n * TRAINER_FOLDS // 5\n * ```\n */\nexport const TRAINER_FOLDS = 5\n\n/**\n * Holds the fewest stratified folds a trainer runs.\n *\n * @remarks\n * The held fold leaves the others for the cross-validation that chooses the L2 strength, which needs\n * at least two.\n *\n * @example\n * ```ts\n * TRAINER_FOLD_FLOOR // 3\n * ```\n */\nexport const TRAINER_FOLD_FLOOR = 3\n\n/**\n * Holds the fold assignment count a trainer runs when its options name none.\n *\n * @example\n * ```ts\n * TRAINER_REPEATS // 1\n * ```\n */\nexport const TRAINER_REPEATS = 1\n\n/**\n * Holds the seed of the first fold assignment when a trainer's options name none.\n *\n * @example\n * ```ts\n * TRAINER_SEED // 0\n * ```\n */\nexport const TRAINER_SEED = 0\n\n/**\n * Holds the L2 grid a trainer chooses from when its options name none.\n *\n * @remarks\n * Round one's grid. The rare-class and layer probes fixed 0.1 from it; a caller who wants that\n * passes `[0.1]` and skips the choice.\n *\n * @example\n * ```ts\n * TRAINER_PENALTIES.includes(0.1) // true\n * ```\n */\nexport const TRAINER_PENALTIES: readonly number[] = Object.freeze([1e-4, 1e-3, 1e-2, 1e-1, 1])\n\n/**\n * Holds the number of full-batch Adam steps one head fit runs.\n *\n * @example\n * ```ts\n * FIT_STEPS // 300\n * ```\n */\nexport const FIT_STEPS = 300\n\n/**\n * Holds the Adam learning rate of a head fit.\n *\n * @example\n * ```ts\n * FIT_RATE // 0.01\n * ```\n */\nexport const FIT_RATE = 0.01\n\n/**\n * Holds Adam's first moment decay and the gain of each incoming gradient.\n *\n * @remarks\n * The gain is written as its own literal, 0.1, as the probes wrote it, because `1 - 0.9` rounds to\n * another double.\n *\n * @example\n * ```ts\n * ADAM_FIRST.decay // 0.9\n * ```\n */\nexport const ADAM_FIRST = Object.freeze({ decay: 0.9, gain: 0.1 })\n\n/**\n * Holds Adam's second moment decay and the gain of each incoming squared gradient.\n *\n * @example\n * ```ts\n * ADAM_SECOND.decay // 0.999\n * ```\n */\nexport const ADAM_SECOND = Object.freeze({ decay: 0.999, gain: 0.001 })\n\n/**\n * Holds the term Adam adds to each step's denominator.\n *\n * @example\n * ```ts\n * ADAM_EPSILON // 1e-8\n * ```\n */\nexport const ADAM_EPSILON = 1e-8\n\n/**\n * Maps each control slot of a thread fitter's shared protocol to its index in the control buffer.\n *\n * @remarks\n * `generation` counts the batches the calling thread has posted, `count` holds the posted batch's job\n * count, `next` hands out job indexes through `Atomics.add`, `idle` counts the workers that have\n * claimed past the last job, `halt` is 1 after an abort or a fault stops the workers, `fault` holds one\n * more than the index of the first job that threw, or 0, and `ready` counts the workers that started.\n *\n * @example\n * ```ts\n * FIT_SLOTS.next // 2\n * ```\n */\nexport const FIT_SLOTS = Object.freeze({\n\tgeneration: 0,\n\tcount: 1,\n\tnext: 2,\n\tidle: 3,\n\thalt: 4,\n\tfault: 5,\n\tready: 6,\n})\n\n/**\n * Holds the longest time, in milliseconds, a thread fitter blocks in its host's `wait` before it\n * reads the signal.\n *\n * @remarks\n * The fitter blocks the calling thread in slices of this length and yields a turn between them, so a\n * timer or another task can abort the signal. A fit job runs for seconds on a full-size problem, so\n * the fitter bounds no job by time: it stops the workers when the signal aborts between two slices.\n *\n * @example\n * ```ts\n * FIT_SLICE // 25\n * ```\n */\nexport const FIT_SLICE = 25\n\n/**\n * Holds the fewest jobs a thread fitter's shared regions hold at once.\n *\n * @remarks\n * A fitter's regions hold this many jobs or its host's size, whichever is more, and a longer job list\n * runs in batches of that many. A trainer's largest batch under the defaults is 25 jobs: 5 repeats of\n * 5 folds.\n *\n * @example\n * ```ts\n * FIT_BATCH // 64\n * ```\n */\nexport const FIT_BATCH = 64\n\n/**\n * Holds the most UTF-16 code units of a worker fault's text a thread fitter reports, its ending 0\n * included.\n *\n * @example\n * ```ts\n * FIT_MESSAGE // 256\n * ```\n */\nexport const FIT_MESSAGE = 256\n\n/**\n * Holds the program a thread fitter runs on every worker: the fit arithmetic and the job loop.\n *\n * @remarks\n * A worker starts from text, because the package ships one bundle per face. The program is written by\n * hand rather than built from the fit helpers' own text, because a function's text is the text the\n * running build holds: Vite's module runner, which runs the tests, rewrites an imported binding such\n * as `ADAM_FIRST` to a property of a generated import record, and a consumer's minifier renames every\n * binding. The arithmetic follows `computeStandard`, `buildFeatureMatrix`, `computeClassWeights`,\n * `computeProbabilities`, `computeErrors`, `computeGradient`, and `stepAdam` operation for operation,\n * and the tests hold every head it fits byte-equal to `SerialFitter`'s. The program reads the\n * generation, counts itself into the `ready` slot, reports ready, and waits for a batch. For each batch, it\n * claims job indexes through `Atomics.add` until they run out, fits each claimed job whole, writes the\n * job's means, scales, and model into the job's own result slot, then counts itself idle. It checks\n * the `halt` slot before each claim and each Adam step. A job that throws records its index and text\n * once and halts every worker.\n *\n * @example\n * ```ts\n * FIT_PROGRAM.source.startsWith('function serveThread(setup, post) {') // true\n * ```\n */\nexport const FIT_PROGRAM: ThreadProgram = Object.freeze({\n\tsource: `function serveThread(setup, post) {\n\tconst control = new Int32Array(setup.control)\n\tconst features = new Float32Array(setup.features)\n\tconst labels = new Int32Array(setup.labels)\n\tconst members = new Uint8Array(setup.members)\n\tconst penalties = new Float64Array(setup.penalties)\n\tconst results = new Float64Array(setup.results)\n\tconst message = new Uint16Array(setup.message)\n\tlet seen = Atomics.load(control, ${FIT_SLOTS.generation})\n\tAtomics.add(control, ${FIT_SLOTS.ready}, 1)\n\tpost({ ready: true })\n\tfor (;;) {\n\t\tAtomics.wait(control, ${FIT_SLOTS.generation}, seen)\n\t\tseen = Atomics.load(control, ${FIT_SLOTS.generation})\n\t\tconst count = Atomics.load(control, ${FIT_SLOTS.count})\n\t\tfor (;;) {\n\t\t\tif (Atomics.load(control, ${FIT_SLOTS.halt}) !== 0) break\n\t\t\tconst job = Atomics.add(control, ${FIT_SLOTS.next}, 1)\n\t\t\tif (job >= count) break\n\t\t\ttry {\n\t\t\t\tfitJob(\n\t\t\t\t\tsetup,\n\t\t\t\t\tcontrol,\n\t\t\t\t\tfeatures,\n\t\t\t\t\tlabels,\n\t\t\t\t\tmembers.subarray(job * setup.rows, (job + 1) * setup.rows),\n\t\t\t\t\tpenalties[job],\n\t\t\t\t\tresults.subarray(job * setup.stride, (job + 1) * setup.stride),\n\t\t\t\t)\n\t\t\t} catch (error) {\n\t\t\t\tif (Atomics.compareExchange(control, ${FIT_SLOTS.fault}, 0, job + 1) === 0) {\n\t\t\t\t\tconst text = error instanceof Error ? error.message : String(error)\n\t\t\t\t\tconst length = Math.min(text.length, message.length - 1)\n\t\t\t\t\tfor (let unit = 0; unit < length; unit += 1) message[unit] = text.charCodeAt(unit)\n\t\t\t\t\tmessage[length] = 0\n\t\t\t\t}\n\t\t\t\tAtomics.store(control, ${FIT_SLOTS.halt}, 1)\n\t\t\t}\n\t\t}\n\t\tAtomics.add(control, ${FIT_SLOTS.idle}, 1)\n\t\tAtomics.notify(control, ${FIT_SLOTS.idle})\n\t}\n}\n\nfunction fitJob(setup, control, features, labels, member, penalty, result) {\n\tconst columns = setup.columns\n\tconst classes = setup.classes\n\tconst picked = []\n\tfor (let row = 0; row < setup.rows; row += 1) if (member[row] === 1) picked.push(row)\n\tconst count = picked.length\n\tconst mean = new Float64Array(columns)\n\tfor (let column = 0; column < columns; column += 1) {\n\t\tlet sum = 0\n\t\tfor (let place = 0; place < count; place += 1) sum += features[picked[place] * columns + column] / count\n\t\tmean[column] = sum\n\t}\n\tconst variance = new Float64Array(columns)\n\tfor (let column = 0; column < columns; column += 1) {\n\t\tlet sum = 0\n\t\tfor (let place = 0; place < count; place += 1) {\n\t\t\tconst gap = features[picked[place] * columns + column] - mean[column]\n\t\t\tsum += (gap * gap) / count\n\t\t}\n\t\tvariance[column] = sum\n\t}\n\tconst scale = new Float64Array(columns)\n\tfor (let column = 0; column < columns; column += 1) {\n\t\tconst deviation = Math.sqrt(variance[column])\n\t\tscale[column] = deviation > 0 ? deviation : 1\n\t}\n\tconst values = new Float64Array(count * columns)\n\tfor (let place = 0; place < count; place += 1) {\n\t\tfor (let column = 0; column < columns; column += 1) {\n\t\t\tvalues[place * columns + column] = (features[picked[place] * columns + column] - mean[column]) / scale[column]\n\t\t}\n\t}\n\tconst transpose = new Float64Array(count * columns)\n\tfor (let column = 0; column < columns; column += 1) {\n\t\tfor (let place = 0; place < count; place += 1) transpose[column * count + place] = values[place * columns + column]\n\t}\n\tconst matrix = { rows: count, columns, values, transpose }\n\tconst targets = picked.map((row) => labels[row])\n\tconst counts = new Array(classes).fill(0)\n\tfor (const label of targets) counts[label] += 1\n\tconst weights = Float64Array.from(targets, (label) => count / (classes * counts[label]))\n\tconst outputs = classes === 2 ? 1 : classes\n\tconst size = outputs * (columns + 1)\n\tlet state = { model: new Float64Array(size), first: new Float64Array(size), second: new Float64Array(size) }\n\tfor (let step = 1; step <= ${FIT_STEPS}; step += 1) {\n\t\tif (Atomics.load(control, ${FIT_SLOTS.halt}) !== 0) return\n\t\tconst probabilities = computeProbabilities(state.model, matrix, outputs)\n\t\tconst errors = computeErrors(probabilities, targets, weights, outputs)\n\t\tconst gradient = computeGradient(errors, matrix, outputs, state.model, penalty)\n\t\tstate = stepAdam(state, gradient, step, ${FIT_RATE})\n\t}\n\tresult.set(mean, 0)\n\tresult.set(scale, columns)\n\tresult.set(state.model, 2 * columns)\n}\n\nfunction computeLogistic(value) {\n\tif (value >= 0) return 1 / (1 + Math.exp(-value))\n\tconst exponent = Math.exp(value)\n\treturn exponent / (1 + exponent)\n}\n\nfunction computeProbabilities(model, matrix, outputs) {\n\tconst { rows, columns, values } = matrix\n\tconst stride = columns + 1\n\tconst blocked = rows - (rows % 4)\n\tconst logits = new Float64Array(rows * outputs)\n\tfor (let row = 0; row < blocked; row += 4) {\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tconst weight = output * stride\n\t\t\tconst bias = model[weight + columns]\n\t\t\tconst one = row * columns\n\t\t\tconst two = one + columns\n\t\t\tconst three = two + columns\n\t\t\tconst four = three + columns\n\t\t\tlet first = bias\n\t\t\tlet second = bias\n\t\t\tlet third = bias\n\t\t\tlet fourth = bias\n\t\t\tfor (let column = 0; column < columns; column += 1) {\n\t\t\t\tconst coefficient = model[weight + column]\n\t\t\t\tfirst += coefficient * values[one + column]\n\t\t\t\tsecond += coefficient * values[two + column]\n\t\t\t\tthird += coefficient * values[three + column]\n\t\t\t\tfourth += coefficient * values[four + column]\n\t\t\t}\n\t\t\tlogits[row * outputs + output] = first\n\t\t\tlogits[(row + 1) * outputs + output] = second\n\t\t\tlogits[(row + 2) * outputs + output] = third\n\t\t\tlogits[(row + 3) * outputs + output] = fourth\n\t\t}\n\t}\n\tfor (let row = blocked; row < rows; row += 1) {\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tlet sum = model[output * stride + columns]\n\t\t\tfor (let column = 0; column < columns; column += 1) {\n\t\t\t\tsum += model[output * stride + column] * values[row * columns + column]\n\t\t\t}\n\t\t\tlogits[row * outputs + output] = sum\n\t\t}\n\t}\n\tconst probabilities = new Float64Array(rows * outputs)\n\tif (outputs === 1) {\n\t\tfor (let row = 0; row < rows; row += 1) probabilities[row] = computeLogistic(logits[row])\n\t\treturn probabilities\n\t}\n\tfor (let row = 0; row < rows; row += 1) {\n\t\tlet peak = Number.NEGATIVE_INFINITY\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tpeak = Math.max(peak, logits[row * outputs + output])\n\t\t}\n\t\tlet mass = 0\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tmass += Math.exp(logits[row * outputs + output] - peak)\n\t\t}\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tprobabilities[row * outputs + output] = Math.exp(logits[row * outputs + output] - peak) / mass\n\t\t}\n\t}\n\treturn probabilities\n}\n\nfunction computeErrors(probabilities, labels, weights, outputs) {\n\tconst rows = labels.length\n\tconst errors = new Float64Array(outputs * rows)\n\tfor (let output = 0; output < outputs; output += 1) {\n\t\tfor (let row = 0; row < rows; row += 1) {\n\t\t\tconst target = labels[row] === output ? 1 : 0\n\t\t\terrors[output * rows + row] = ((probabilities[row * outputs + output] - target) * weights[row]) / rows\n\t\t}\n\t}\n\treturn errors\n}\n\nfunction computeGradient(errors, matrix, outputs, model, penalty) {\n\tconst { rows, columns, transpose } = matrix\n\tconst stride = columns + 1\n\tconst blocked = columns - (columns % 4)\n\tconst gradient = new Float64Array(outputs * stride)\n\tfor (let column = 0; column < blocked; column += 4) {\n\t\tconst one = column * rows\n\t\tconst two = one + rows\n\t\tconst three = two + rows\n\t\tconst four = three + rows\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tconst error = output * rows\n\t\t\tconst weight = output * stride\n\t\t\tlet first = 0\n\t\t\tlet second = 0\n\t\t\tlet third = 0\n\t\t\tlet fourth = 0\n\t\t\tfor (let row = 0; row < rows; row += 1) {\n\t\t\t\tconst term = errors[error + row]\n\t\t\t\tfirst += term * transpose[one + row]\n\t\t\t\tsecond += term * transpose[two + row]\n\t\t\t\tthird += term * transpose[three + row]\n\t\t\t\tfourth += term * transpose[four + row]\n\t\t\t}\n\t\t\tgradient[weight + column] = first + penalty * model[weight + column]\n\t\t\tgradient[weight + column + 1] = second + penalty * model[weight + column + 1]\n\t\t\tgradient[weight + column + 2] = third + penalty * model[weight + column + 2]\n\t\t\tgradient[weight + column + 3] = fourth + penalty * model[weight + column + 3]\n\t\t}\n\t}\n\tfor (let column = blocked; column < columns; column += 1) {\n\t\tconst base = column * rows\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tconst error = output * rows\n\t\t\tlet sum = 0\n\t\t\tfor (let row = 0; row < rows; row += 1) {\n\t\t\t\tsum += errors[error + row] * transpose[base + row]\n\t\t\t}\n\t\t\tgradient[output * stride + column] = sum + penalty * model[output * stride + column]\n\t\t}\n\t}\n\tfor (let output = 0; output < outputs; output += 1) {\n\t\tconst error = output * rows\n\t\tlet bias = 0\n\t\tfor (let row = 0; row < rows; row += 1) bias += errors[error + row]\n\t\tgradient[output * stride + columns] = bias\n\t}\n\treturn gradient\n}\n\nfunction stepAdam(state, gradient, step, rate) {\n\tconst firstScale = 1 - Math.pow(${ADAM_FIRST.decay}, step)\n\tconst secondScale = 1 - Math.pow(${ADAM_SECOND.decay}, step)\n\tconst first = new Float64Array(gradient.length)\n\tconst second = new Float64Array(gradient.length)\n\tconst model = new Float64Array(state.model.length)\n\tfor (let index = 0; index < first.length; index += 1) {\n\t\tconst value = gradient[index]\n\t\tfirst[index] = ${ADAM_FIRST.decay} * state.first[index] + ${ADAM_FIRST.gain} * value\n\t\tsecond[index] = ${ADAM_SECOND.decay} * state.second[index] + ${ADAM_SECOND.gain} * value * value\n\t}\n\tfor (let index = 0; index < model.length; index += 1) {\n\t\tmodel[index] =\n\t\t\tstate.model[index] -\n\t\t\t(rate * (first[index] / firstScale)) / (Math.sqrt(second[index] / secondScale) + ${ADAM_EPSILON})\n\t}\n\treturn { model, first, second }\n}\n`,\n})\n\n/**\n * Holds the number of Adam steps a calibration fit runs.\n *\n * @example\n * ```ts\n * CALIBRATION_STEPS // 2000\n * ```\n */\nexport const CALIBRATION_STEPS = 2000\n\n/**\n * Holds the Adam learning rate of a calibration fit.\n *\n * @example\n * ```ts\n * CALIBRATION_RATE // 0.01\n * ```\n */\nexport const CALIBRATION_RATE = 0.01\n\n/**\n * Holds the weight of the unit Gaussian prior on the log temperature and on each calibration bias.\n *\n * @remarks\n * The prior counts as one held row, so it moves a calibration fitted on hundreds of rows by little\n * and holds it finite when the held rows separate.\n *\n * @example\n * ```ts\n * CALIBRATION_PRIOR // 1\n * ```\n */\nexport const CALIBRATION_PRIOR = 1\n\n/**\n * Lists the members of a training row, in the order a refusal names them.\n *\n * @example\n * ```ts\n * ROW_KEYS // ['state', 'label']\n * ```\n */\nexport const ROW_KEYS: readonly string[] = Object.freeze(['state', 'label'])\n\n/**\n * Holds the extension of a head file's name.\n *\n * @example\n * ```ts\n * HEAD_FILE_EXTENSION // '.gguf'\n * ```\n */\nexport const HEAD_FILE_EXTENSION = '.gguf'\n\n/**\n * Holds the `general.type` value written into every GGUF v3 training checkpoint.\n *\n * @example\n * ```ts\n * CHECKPOINT_TYPE // 'checkpoint'\n * ```\n */\nexport const CHECKPOINT_TYPE = 'checkpoint'\n\n/**\n * Holds the schema version written to `orkestrel.checkpoint.version`.\n *\n * @example\n * ```ts\n * CHECKPOINT_VERSION // 1\n * ```\n */\nexport const CHECKPOINT_VERSION = 1\n\n/**\n * Lists the admitted training checkpoint modes.\n *\n * @example\n * ```ts\n * CHECKPOINT_MODES // ['adapter', 'section']\n * ```\n */\nexport const CHECKPOINT_MODES: readonly ['adapter', 'section'] = Object.freeze([\n\t'adapter',\n\t'section',\n])\n\n/**\n * Maps each GGUF metadata key of a training checkpoint to its canonical key name.\n *\n * @example\n * ```ts\n * CHECKPOINT_KEYS.version // 'orkestrel.checkpoint.version'\n * ```\n */\nexport const CHECKPOINT_KEYS = Object.freeze({\n\ttype: 'general.type',\n\tversion: 'orkestrel.checkpoint.version',\n\tmode: 'orkestrel.checkpoint.mode',\n\tbase: 'orkestrel.checkpoint.base',\n\tdataset: 'orkestrel.checkpoint.dataset',\n\tstep: 'orkestrel.checkpoint.step',\n\tepoch: 'orkestrel.checkpoint.epoch',\n\tcursor: 'orkestrel.checkpoint.cursor',\n\tseed: 'orkestrel.checkpoint.seed',\n\trng: 'orkestrel.checkpoint.rng',\n\tfold: 'orkestrel.checkpoint.fold',\n\tconfig: 'orkestrel.checkpoint.config',\n\ttargets: 'orkestrel.checkpoint.targets',\n} as const)\n\n/**\n * Maps each tensor role in a target triple to its GGUF tensor name prefix.\n *\n * @example\n * ```ts\n * CHECKPOINT_TENSOR_PREFIXES.first // 'adam.m.'\n * ```\n */\nexport const CHECKPOINT_TENSOR_PREFIXES = Object.freeze({\n\tparameters: 'param.',\n\tfirst: 'adam.m.',\n\tsecond: 'adam.v.',\n} as const)\n\n/**\n * Holds the frozen pattern that every valid checkpoint store identifier matches.\n *\n * @remarks\n * Admits 1 to 128 ASCII letters, digits, underscores, hyphens, and interior single periods, while\n * refusing empty strings, `.`, `..`, path separators, NUL bytes, trailing or repeated periods, and\n * case-insensitive Windows reserved device names (`CON`, `PRN`, `AUX`, `NUL`, `COM1`–`COM9`,\n * `LPT1`–`LPT9`, bare or before `.`).\n *\n * @example\n * ```ts\n * CHECKPOINT_ID_PATTERN.test('run-1.step_10') // true\n * CHECKPOINT_ID_PATTERN.test('../parent') // false\n * CHECKPOINT_ID_PATTERN.test('nul.step1') // false\n * ```\n */\nexport const CHECKPOINT_ID_PATTERN: RegExp = Object.freeze(\n\t/^(?!(?:[Cc][Oo][Nn]|[Pp][Rr][Nn]|[Aa][Uu][Xx]|[Nn][Uu][Ll]|[Cc][Oo][Mm][1-9]|[Ll][Pp][Tt][1-9])(?:\\.|$))[A-Za-z0-9](?:[A-Za-z0-9_-]|\\.(?=[A-Za-z0-9_-])){0,127}$/u,\n)\n\n/**\n * Holds the extension appended to stored checkpoint GGUF files.\n *\n * @example\n * ```ts\n * CHECKPOINT_FILE_EXTENSION // '.gguf'\n * ```\n */\nexport const CHECKPOINT_FILE_EXTENSION = '.gguf'\n\n/**\n * Holds the canonical Hugging Face PEFT layer prefix for Llama-family adapters and the alias prefix\n * admitted on Qwen3.5 PEFT import.\n *\n * @example\n * ```ts\n * PEFT_LAYERS_PREFIX // 'base_model.model.model.layers.'\n * ```\n */\nexport const PEFT_LAYERS_PREFIX = 'base_model.model.model.layers.'\n\n/**\n * Holds the canonical Hugging Face PEFT layer prefix for Qwen3.5 adapters.\n *\n * @example\n * ```ts\n * PEFT_QWEN35_PREFIX // 'base_model.model.model.language_model.layers.'\n * ```\n */\nexport const PEFT_QWEN35_PREFIX = 'base_model.model.model.language_model.layers.'\n\n/**\n * Holds the base Hugging Face safetensors layer prefix for Llama checkpoints and Qwen3.5 aliases.\n *\n * @example\n * ```ts\n * PEFT_BASE_LAYERS_PREFIX // 'model.layers.'\n * ```\n */\nexport const PEFT_BASE_LAYERS_PREFIX = 'model.layers.'\n\n/**\n * Holds the canonical base Hugging Face safetensors layer prefix for Qwen3.5 checkpoints.\n *\n * @example\n * ```ts\n * PEFT_BASE_QWEN35_PREFIX // 'model.language_model.layers.'\n * ```\n */\nexport const PEFT_BASE_QWEN35_PREFIX = 'model.language_model.layers.'\n\n/**\n * Maps each GGUF LoRA target stem to its Hugging Face PEFT module path, leaf stem, and admitted\n * decoder families.\n *\n * @example\n * ```ts\n * PEFT_TARGET_SPECS.attn_qkv.module // 'linear_attn.in_proj_qkv'\n * ```\n */\nexport const PEFT_TARGET_SPECS: Readonly<Record<AdapterTarget, PEFTTargetSpec>> = Object.freeze({\n\tattn_q: Object.freeze({\n\t\tmodule: 'self_attn.q_proj',\n\t\tleaf: 'q_proj',\n\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t}),\n\tattn_k: Object.freeze({\n\t\tmodule: 'self_attn.k_proj',\n\t\tleaf: 'k_proj',\n\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t}),\n\tattn_v: Object.freeze({\n\t\tmodule: 'self_attn.v_proj',\n\t\tleaf: 'v_proj',\n\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t}),\n\tattn_output: Object.freeze({\n\t\tmodule: 'self_attn.o_proj',\n\t\tleaf: 'o_proj',\n\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t}),\n\tattn_qkv: Object.freeze({\n\t\tmodule: 'linear_attn.in_proj_qkv',\n\t\tleaf: 'in_proj_qkv',\n\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t}),\n\tattn_gate: Object.freeze({\n\t\tmodule: 'linear_attn.in_proj_z',\n\t\tleaf: 'in_proj_z',\n\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t}),\n\tssm_beta: Object.freeze({\n\t\tmodule: 'linear_attn.in_proj_b',\n\t\tleaf: 'in_proj_b',\n\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t}),\n\tssm_alpha: Object.freeze({\n\t\tmodule: 'linear_attn.in_proj_a',\n\t\tleaf: 'in_proj_a',\n\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t}),\n\tssm_out: Object.freeze({\n\t\tmodule: 'linear_attn.out_proj',\n\t\tleaf: 'out_proj',\n\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t}),\n\tffn_gate: Object.freeze({\n\t\tmodule: 'mlp.gate_proj',\n\t\tleaf: 'gate_proj',\n\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t}),\n\tffn_up: Object.freeze({\n\t\tmodule: 'mlp.up_proj',\n\t\tleaf: 'up_proj',\n\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t}),\n\tffn_down: Object.freeze({\n\t\tmodule: 'mlp.down_proj',\n\t\tleaf: 'down_proj',\n\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t}),\n})\n\n/**\n * Matches one Hugging Face PEFT LoRA safetensors tensor name under either the canonical Llama\n * prefix or the canonical Qwen3.5 `language_model` prefix.\n *\n * @example\n * ```ts\n * PEFT_TENSOR_PATTERN.test('base_model.model.model.layers.0.self_attn.q_proj.lora_A.weight') // true\n * ```\n */\nexport const PEFT_TENSOR_PATTERN: RegExp = Object.freeze(\n\t/^base_model\\.model\\.model\\.(language_model\\.)?layers\\.(0|[1-9][0-9]*)\\.([a-z0-9_]+\\.[a-z0-9_]+)\\.lora_(A|B)\\.weight$/u,\n)\n\n/**\n * Lists the output tensor formats admitted for targeted merged tensors in `mergeGGUF`.\n *\n * @example\n * ```ts\n * MERGE_GGUF_FORMATS // ['F32', 'BF16', 'Q8_0', 'Q4_K']\n * ```\n */\nexport const MERGE_GGUF_FORMATS: readonly MergeGGUFFormat[] = Object.freeze([\n\t'F32',\n\t'BF16',\n\t'Q8_0',\n\t'Q4_K',\n])\n\n/**\n * Lists the base GGUF tensor formats that `mergeGGUF` widens when a LoRA pair targets the tensor.\n *\n * @example\n * ```ts\n * MERGE_SOURCE_FORMATS.includes('Q8_0') // true\n * ```\n */\nexport const MERGE_SOURCE_FORMATS: readonly GGUFFormat[] = Object.freeze([\n\t'F32',\n\t'F16',\n\t'BF16',\n\t'Q5_0',\n\t'Q8_0',\n\t'Q4_K',\n\t'Q6_K',\n])\n\n/**\n * Holds the default maximum slice size in bytes when streaming untargeted tensors during merge.\n *\n * @example\n * ```ts\n * MERGE_CHUNK_BYTES // 1048576\n * ```\n */\nexport const MERGE_CHUNK_BYTES = 1_048_576\n\n/**\n * Holds the default row strip height processed per slice when merging targeted weight tensors.\n *\n * @example\n * ```ts\n * MERGE_ROW_STRIP // 256\n * ```\n */\nexport const MERGE_ROW_STRIP = 256\n\n/**\n * Lists the default candidate LoRA scales swept by `calibrateAdapter`.\n *\n * @example\n * ```ts\n * ADAPTER_CALIBRATION_SCALES // [0, 0.25, 0.5, 0.75, 1, 1.25, 1.5]\n * ```\n */\nexport const ADAPTER_CALIBRATION_SCALES: readonly number[] = Object.freeze([\n\t0, 0.25, 0.5, 0.75, 1, 1.25, 1.5,\n])\n\n/**\n * Lists the precision and quantization formats admitted by full-vs-compressed shift comparisons.\n *\n * @example\n * ```ts\n * PRECISION_FORMATS // ['BF16', 'Q8_0', 'Q4_K_M']\n * ```\n */\nexport const PRECISION_FORMATS: readonly PrecisionFormat[] = Object.freeze([\n\t'BF16',\n\t'Q8_0',\n\t'Q4_K_M',\n])\n\n/**\n * Holds the default peak learning rate for `Finetuner`.\n *\n * @example\n * ```ts\n * FINETUNER_RATE // 0.0001\n * ```\n */\nexport const FINETUNER_RATE = 1e-4\n\n/**\n * Holds the default decoupled AdamW weight decay for `Finetuner`.\n *\n * @example\n * ```ts\n * FINETUNER_DECAY // 0.01\n * ```\n */\nexport const FINETUNER_DECAY = 0.01\n\n/**\n * Holds the default AdamW first-moment decay (`beta1`) for `Finetuner`.\n *\n * @example\n * ```ts\n * FINETUNER_FIRST // 0.9\n * ```\n */\nexport const FINETUNER_FIRST = 0.9\n\n/**\n * Holds the default AdamW second-moment decay (`beta2`) for `Finetuner`.\n *\n * @example\n * ```ts\n * FINETUNER_SECOND // 0.999\n * ```\n */\nexport const FINETUNER_SECOND = 0.999\n\n/**\n * Holds the default AdamW denominator stability floor for `Finetuner`.\n *\n * @example\n * ```ts\n * FINETUNER_EPSILON // 1e-8\n * ```\n */\nexport const FINETUNER_EPSILON = 1e-8\n\n/**\n * Holds the default global L2 gradient norm clip ceiling for `Finetuner`.\n *\n * @example\n * ```ts\n * FINETUNER_CLIP // 1\n * ```\n */\nexport const FINETUNER_CLIP = 1\n\n/**\n * Holds the default linear warmup step count for `Finetuner`.\n *\n * @example\n * ```ts\n * FINETUNER_WARMUP // 0\n * ```\n */\nexport const FINETUNER_WARMUP = 0\n\n/**\n * Lists the learning-rate decay schedules admitted by `Finetuner`.\n *\n * @example\n * ```ts\n * FINETUNER_SCHEDULES // ['cosine', 'constant']\n * ```\n */\nexport const FINETUNER_SCHEDULES: readonly FinetunerSchedule[] = Object.freeze([\n\t'cosine',\n\t'constant',\n])\n\n/**\n * Holds the default epoch count for `Finetuner`.\n *\n * @example\n * ```ts\n * FINETUNER_EPOCHS // 1\n * ```\n */\nexport const FINETUNER_EPOCHS = 1\n\n/**\n * Holds the default mini-batch example accumulation count for `Finetuner`.\n *\n * @example\n * ```ts\n * FINETUNER_BATCH // 1\n * ```\n */\nexport const FINETUNER_BATCH = 1\n\n/**\n * Holds the default token length limit for `Finetuner` examples.\n *\n * @example\n * ```ts\n * FINETUNER_LIMIT // 2048\n * ```\n */\nexport const FINETUNER_LIMIT = 2048\n\n/**\n * Holds the default deterministic PRNG seed for `Finetuner`.\n *\n * @example\n * ```ts\n * FINETUNER_SEED // 0\n * ```\n */\nexport const FINETUNER_SEED = 0\n\n/**\n * Lists every boundary timing metric name emitted by `Finetuner`, in milliseconds.\n *\n * @example\n * ```ts\n * TRAIN_METRICS.includes('step') // true\n * ```\n */\nexport const TRAIN_METRICS = Object.freeze(['step', 'accumulate', 'update', 'rotation'] as const)\n\n/**\n * Holds the `general.type` value written into every GGUF v3 section patch file.\n *\n * @example\n * ```ts\n * SECTION_PATCH_TYPE // 'patch'\n * ```\n */\nexport const SECTION_PATCH_TYPE = 'patch'\n\n/**\n * Holds the schema version written to `orkestrel.patch.version` in every section patch GGUF file.\n *\n * @example\n * ```ts\n * SECTION_PATCH_VERSION // 1\n * ```\n */\nexport const SECTION_PATCH_VERSION = 1\n\n/**\n * Maps each full-rank `SectionTarget` stem to its Hugging Face safetensors tensor suffix, root\n * placement flag, and admitted decoder families.\n *\n * @example\n * ```ts\n * SECTION_SAFETENSORS_SPECS.ffn_down.suffix // 'mlp.down_proj.weight'\n * ```\n */\nexport const SECTION_SAFETENSORS_SPECS: Readonly<Record<SectionTarget, SectionTargetSpec>> =\n\tObject.freeze({\n\t\tattn_norm: Object.freeze({\n\t\t\tsuffix: 'input_layernorm.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t\t}),\n\t\tattn_q: Object.freeze({\n\t\t\tsuffix: 'self_attn.q_proj.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t\t}),\n\t\tattn_k: Object.freeze({\n\t\t\tsuffix: 'self_attn.k_proj.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t\t}),\n\t\tattn_v: Object.freeze({\n\t\t\tsuffix: 'self_attn.v_proj.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t\t}),\n\t\tattn_q_norm: Object.freeze({\n\t\t\tsuffix: 'self_attn.q_norm.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t\t}),\n\t\tattn_k_norm: Object.freeze({\n\t\t\tsuffix: 'self_attn.k_norm.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t\t}),\n\t\tattn_output: Object.freeze({\n\t\t\tsuffix: 'self_attn.o_proj.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t\t}),\n\t\tattn_qkv: Object.freeze({\n\t\t\tsuffix: 'linear_attn.in_proj_qkv.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t\t}),\n\t\tattn_gate: Object.freeze({\n\t\t\tsuffix: 'linear_attn.in_proj_z.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t\t}),\n\t\tssm_beta: Object.freeze({\n\t\t\tsuffix: 'linear_attn.in_proj_b.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t\t}),\n\t\tssm_alpha: Object.freeze({\n\t\t\tsuffix: 'linear_attn.in_proj_a.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t\t}),\n\t\tssm_conv1d: Object.freeze({\n\t\t\tsuffix: 'linear_attn.conv1d.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t\t}),\n\t\tssm_dt: Object.freeze({\n\t\t\tsuffix: 'linear_attn.dt_bias',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t\t}),\n\t\tssm_a: Object.freeze({\n\t\t\tsuffix: 'linear_attn.A_log',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t\t}),\n\t\tssm_norm: Object.freeze({\n\t\t\tsuffix: 'linear_attn.norm.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t\t}),\n\t\tssm_out: Object.freeze({\n\t\t\tsuffix: 'linear_attn.out_proj.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t\t}),\n\t\tffn_norm: Object.freeze({\n\t\t\tsuffix: 'post_attention_layernorm.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama']),\n\t\t}),\n\t\tpost_attention_norm: Object.freeze({\n\t\t\tsuffix: 'post_attention_layernorm.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['qwen35']),\n\t\t}),\n\t\tffn_gate: Object.freeze({\n\t\t\tsuffix: 'mlp.gate_proj.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t\t}),\n\t\tffn_up: Object.freeze({\n\t\t\tsuffix: 'mlp.up_proj.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t\t}),\n\t\tffn_down: Object.freeze({\n\t\t\tsuffix: 'mlp.down_proj.weight',\n\t\t\ttop: false,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t\t}),\n\t\ttoken_embd: Object.freeze({\n\t\t\tsuffix: 'embed_tokens.weight',\n\t\t\ttop: true,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t\t}),\n\t\toutput_norm: Object.freeze({\n\t\t\tsuffix: 'norm.weight',\n\t\t\ttop: true,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t\t}),\n\t\toutput: Object.freeze({\n\t\t\tsuffix: 'lm_head.weight',\n\t\t\ttop: true,\n\t\t\tfamilies: Object.freeze<readonly ArchitectureFamily[]>(['llama', 'qwen35']),\n\t\t}),\n\t})\n","import type {\n\tByteSinkInterface,\n\tCheckpoint,\n\tCheckpointMode,\n\tCheckpointTarget,\n\tFinetuneRow,\n\tFinetunerSchedule,\n\tMergeGGUFFormat,\n\tPEFTBundle,\n\tPEFTConfig,\n\tPrecisionFormat,\n\tTrainerRow,\n} from './types.js'\nimport {\n\tholds,\n\tisArray,\n\tisBoundedJSONRecord,\n\tisFiniteNumber,\n\tisFloat32Array,\n\tisFunction,\n\tisObject,\n\tisRecord,\n\tisSafeInteger,\n\tisString,\n\tisUint8Array,\n} from '@orkestrel/contract'\nimport { SHA256_PATTERN } from '@orkestrel/infer'\nimport { CHECKPOINT_ID_PATTERN, ROW_KEYS } from './constants.js'\n\n/**\n * Checks whether a value is a training row: a plain record of a string `state`, a string `label`,\n * and an optional non-empty string `group`.\n *\n * @remarks\n * A row is owned data, so a record carrying any other member, an empty `group`, or a non-string\n * `group` is refused. Never throws, whatever the value's accessors do.\n *\n * @param value - The value to inspect\n * @returns True if the value is a training row; false otherwise\n *\n * @example\n * ```ts\n * isTrainerRow({ state: 'user: hi', label: 'chatter' }) // true\n * isTrainerRow({ state: 'user: hi', label: 'chatter', group: 'conv-1' }) // true\n * isTrainerRow({ state: 'user: hi', label: 'chatter', group: '' }) // false\n * ```\n */\nexport function isTrainerRow(value: unknown): value is TrainerRow {\n\treturn holds(() => {\n\t\tif (!isRecord(value)) return false\n\t\tconst keys = Object.keys(value)\n\t\tif (!ROW_KEYS.every((key) => Object.hasOwn(value, key))) return false\n\t\tif (!keys.every((key) => ROW_KEYS.includes(key) || key === 'group')) return false\n\t\tif (!isString(value['state']) || !isString(value['label'])) return false\n\t\tif (Object.hasOwn(value, 'group')) {\n\t\t\treturn isString(value['group']) && value['group'].length > 0\n\t\t}\n\t\treturn true\n\t})\n}\n\n/**\n * Checks whether a value is a valid checkpoint store identifier matching `CHECKPOINT_ID_PATTERN`.\n *\n * @remarks\n * Never throws, whatever the value's accessors or prototype do.\n *\n * @param value - The value to inspect\n * @returns True if the value is a valid checkpoint identifier; false otherwise\n *\n * @example\n * ```ts\n * isCheckpointId('run-1.step_10') // true\n * isCheckpointId('../parent') // false\n * ```\n */\nexport function isCheckpointId(value: unknown): value is string {\n\treturn holds(() => isString(value) && CHECKPOINT_ID_PATTERN.test(value))\n}\n\n/**\n * Checks whether a value is an admitted checkpoint training mode (`'adapter'` or `'section'`).\n *\n * @param value - The value to inspect\n * @returns True if the value is an admitted mode; false otherwise\n *\n * @example\n * ```ts\n * isCheckpointMode('adapter') // true\n * isCheckpointMode('other') // false\n * ```\n */\nexport function isCheckpointMode(value: unknown): value is CheckpointMode {\n\treturn value === 'adapter' || value === 'section'\n}\n\n/**\n * Checks whether a value is a valid checkpoint target with positive dimensions and finite\n * single-precision parameter and Adam moment arrays of matching length.\n *\n * @remarks\n * Never throws, whatever the value's accessors do.\n *\n * @param value - The value to inspect\n * @returns True if the value is a valid checkpoint target; false otherwise\n *\n * @example\n * ```ts\n * isCheckpointTarget({\n * \tname: 'blk.0.attn_q.lora_a',\n * \trows: 1,\n * \tcolumns: 2,\n * \tparameters: Float32Array.of(0.1, 0.2),\n * \tfirst: Float32Array.of(0, 0),\n * \tsecond: Float32Array.of(0, 0),\n * }) // true\n * ```\n */\nexport function isCheckpointTarget(value: unknown): value is CheckpointTarget {\n\treturn holds(() => {\n\t\tif (!isRecord(value)) return false\n\t\tconst allowed: readonly string[] = ['name', 'rows', 'columns', 'parameters', 'first', 'second']\n\t\tconst keys = Object.keys(value)\n\t\tif (!allowed.every((key) => Object.hasOwn(value, key))) return false\n\t\tif (!keys.every((key) => allowed.includes(key))) return false\n\t\tconst { name, rows, columns, parameters, first, second } = value\n\t\tif (!isString(name) || name.length === 0 || name.includes('\\0')) return false\n\t\tif (!isSafeInteger(rows) || rows < 1 || !isSafeInteger(columns) || columns < 1) return false\n\t\tconst total = rows * columns\n\t\tif (!Number.isSafeInteger(total)) return false\n\t\tif (!isFloat32Array(parameters) || !isFloat32Array(first) || !isFloat32Array(second)) {\n\t\t\treturn false\n\t\t}\n\t\tif (parameters.length !== total || first.length !== total || second.length !== total) {\n\t\t\treturn false\n\t\t}\n\t\treturn (\n\t\t\tparameters.every(Number.isFinite) &&\n\t\t\tfirst.every(Number.isFinite) &&\n\t\t\tsecond.every(Number.isFinite)\n\t\t)\n\t})\n}\n\n/**\n * Checks whether a value is a valid resumable training checkpoint record.\n *\n * @remarks\n * Refuses undeclared members, missing required members, malformed digests, negative or fractional\n * counters, out-of-range generator states, non-finite seeds or tensors, duplicate target names, or\n * an explicit `undefined` `fold`. Never throws.\n *\n * @param value - The value to inspect\n * @returns True if the value is a valid checkpoint; false otherwise\n *\n * @example\n * ```ts\n * isCheckpoint({\n * \tmode: 'adapter',\n * \tbase: '0'.repeat(64),\n * \tdataset: '1'.repeat(64),\n * \tstep: 1,\n * \tepoch: 0,\n * \tcursor: 2,\n * \tseed: 7,\n * \trng: 7,\n * \tconfig: { rate: 0.01 },\n * \ttargets: [target],\n * }) // true\n * ```\n */\nexport function isCheckpoint(value: unknown): value is Checkpoint {\n\treturn holds(() => {\n\t\tif (!isRecord(value)) return false\n\t\tconst required: readonly string[] = [\n\t\t\t'mode',\n\t\t\t'base',\n\t\t\t'dataset',\n\t\t\t'step',\n\t\t\t'epoch',\n\t\t\t'cursor',\n\t\t\t'seed',\n\t\t\t'rng',\n\t\t\t'config',\n\t\t\t'targets',\n\t\t]\n\t\tconst keys = Object.keys(value)\n\t\tif (!required.every((key) => Object.hasOwn(value, key))) return false\n\t\tif (!keys.every((key) => key === 'fold' || required.includes(key))) {\n\t\t\treturn false\n\t\t}\n\t\tconst { mode, base, dataset, step, epoch, cursor, seed, rng, config, targets } = value\n\t\tif (!isCheckpointMode(mode)) return false\n\t\tif (!isString(base) || !SHA256_PATTERN.test(base)) return false\n\t\tif (!isString(dataset) || !SHA256_PATTERN.test(dataset)) return false\n\t\tif (!isSafeInteger(step) || step < 0) return false\n\t\tif (!isSafeInteger(epoch) || epoch < 0) return false\n\t\tif (!isSafeInteger(cursor) || cursor < 0) return false\n\t\tif (!isFiniteNumber(seed)) return false\n\t\tif (!isSafeInteger(rng) || rng < 0 || rng > 0xffff_ffff) return false\n\t\tif (Object.hasOwn(value, 'fold')) {\n\t\t\tconst fold = value['fold']\n\t\t\tif (!isSafeInteger(fold) || fold < 0) return false\n\t\t}\n\t\tif (!isBoundedJSONRecord(config)) return false\n\t\tif (!isArray(targets) || targets.length === 0 || !targets.every(isCheckpointTarget))\n\t\t\treturn false\n\t\treturn new Set(targets.map((target) => target.name)).size === targets.length\n\t})\n}\n\n/**\n * Checks whether a value is an admitted `adapter_config.json` wire record for standard LoRA\n * adapters (`peft_type: 'LORA'`, `bias: 'none'`, neither `use_rslora` nor `use_dora` enabled).\n *\n * @remarks\n * Never throws, whatever the value's accessors or prototype do.\n *\n * @param value - The value to inspect\n * @returns True if the value is a supported PEFT LoRA configuration; false otherwise\n *\n * @example\n * ```ts\n * isPEFTConfig({ peft_type: 'LORA', r: 4, lora_alpha: 8, target_modules: ['q_proj'], bias: 'none' }) // true\n * isPEFTConfig({ peft_type: 'LORA', r: 4, lora_alpha: 8, target_modules: ['q_proj'], bias: 'all' }) // false\n * ```\n */\nexport function isPEFTConfig(value: unknown): value is PEFTConfig {\n\treturn holds(() => {\n\t\tif (!isRecord(value)) return false\n\t\tif (value['peft_type'] !== 'LORA') return false\n\t\tconst rank = value['r']\n\t\tif (!isSafeInteger(rank) || rank < 1) return false\n\t\tconst alpha = value['lora_alpha']\n\t\tif (!isFiniteNumber(alpha) || alpha <= 0) return false\n\t\tconst modules = value['target_modules']\n\t\tif (\n\t\t\t!isArray(modules) ||\n\t\t\tmodules.length === 0 ||\n\t\t\t!modules.every((entry) => isString(entry) && entry.length > 0)\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\tif (value['bias'] !== 'none') return false\n\t\tif (Object.hasOwn(value, 'use_rslora') && value['use_rslora'] !== false) return false\n\t\tif (Object.hasOwn(value, 'use_dora') && value['use_dora'] !== false) return false\n\t\tif (Object.hasOwn(value, 'task_type') && !isString(value['task_type'])) return false\n\t\tif (\n\t\t\tObject.hasOwn(value, 'base_model_name_or_path') &&\n\t\t\t!isString(value['base_model_name_or_path'])\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t})\n}\n\n/**\n * Checks whether a value is a `PEFTBundle` carrying a valid `config` and `Uint8Array` `weights`.\n *\n * @remarks\n * Never throws, whatever the value's accessors or prototype do.\n *\n * @param value - The value to inspect\n * @returns True if the value is a PEFT bundle; false otherwise\n *\n * @example\n * ```ts\n * isPEFTBundle({ config, weights: new Uint8Array(8) }) // true\n * ```\n */\nexport function isPEFTBundle(value: unknown): value is PEFTBundle {\n\treturn holds(() => {\n\t\tif (!isRecord(value)) return false\n\t\treturn isPEFTConfig(value['config']) && isUint8Array(value['weights'])\n\t})\n}\n\n/**\n * Checks whether a value is an admitted output tensor format for `mergeGGUF` (`'F32'`, `'BF16'`,\n * `'Q8_0'`, or `'Q4_K'`).\n *\n * @param value - The value to inspect\n * @returns True if the value is an admitted merge GGUF format; false otherwise\n *\n * @example\n * ```ts\n * isMergeGGUFFormat('Q8_0') // true\n * isMergeGGUFFormat('F16') // false\n * ```\n */\nexport function isMergeGGUFFormat(value: unknown): value is MergeGGUFFormat {\n\treturn value === 'F32' || value === 'BF16' || value === 'Q8_0' || value === 'Q4_K'\n}\n\n/**\n * Checks whether a value is an admitted precision format for full-vs-compressed decision shift\n * comparisons (`'BF16'`, `'Q8_0'`, or `'Q4_K_M'`).\n *\n * @param value - The value to inspect\n * @returns True if the value is an admitted precision format; false otherwise\n *\n * @example\n * ```ts\n * isPrecisionFormat('Q4_K_M') // true\n * isPrecisionFormat('F32') // false\n * ```\n */\nexport function isPrecisionFormat(value: unknown): value is PrecisionFormat {\n\treturn value === 'BF16' || value === 'Q8_0' || value === 'Q4_K_M'\n}\n\n/**\n * Checks whether a value implements `ByteSinkInterface` (`write`, `close`, and optional `abort`).\n *\n * @remarks\n * Accepts both plain objects and class instances. Never throws.\n *\n * @param value - The value to inspect\n * @returns True if the value implements `ByteSinkInterface`; false otherwise\n *\n * @example\n * ```ts\n * isByteSink({ write() {}, close() {} }) // true\n * ```\n */\nexport function isByteSink(value: unknown): value is ByteSinkInterface {\n\treturn holds(() => {\n\t\tif (!isObject(value)) return false\n\t\tif (!isFunction(Reflect.get(value, 'write')) || !isFunction(Reflect.get(value, 'close'))) {\n\t\t\treturn false\n\t\t}\n\t\tconst abort: unknown = Reflect.get(value, 'abort')\n\t\treturn abort === undefined || isFunction(abort)\n\t})\n}\n\n/**\n * Checks whether a value is an admitted `Finetuner` learning-rate decay schedule (`'cosine'` or\n * `'constant'`).\n *\n * @param value - The value to inspect\n * @returns True if the value is an admitted schedule; false otherwise\n *\n * @example\n * ```ts\n * isFinetunerSchedule('cosine') // true\n * isFinetunerSchedule('linear') // false\n * ```\n */\nexport function isFinetunerSchedule(value: unknown): value is FinetunerSchedule {\n\treturn value === 'cosine' || value === 'constant'\n}\n\n/**\n * Checks whether a value is a structurally valid `FinetuneRow` carrying either a string `prompt`\n * or a non-empty `messages` array, a string `completion`, optional non-empty `group` and `label`,\n * and a record `provenance`.\n *\n * @remarks\n * Never throws, whatever the value's accessors do. Provenance field content and hosted-model\n * markers are verified separately by `checkRowProvenance`.\n *\n * @param value - The value to inspect\n * @returns True if the value is structurally a `FinetuneRow`; false otherwise\n *\n * @example\n * ```ts\n * isFinetuneRow({ prompt: 'user: hi\\nassistant: ', completion: 'hello', provenance }) // true\n * ```\n */\nexport function isFinetuneRow(value: unknown): value is FinetuneRow {\n\treturn holds(() => {\n\t\tif (!isRecord(value)) return false\n\t\tconst allowed: readonly string[] = [\n\t\t\t'prompt',\n\t\t\t'messages',\n\t\t\t'completion',\n\t\t\t'group',\n\t\t\t'label',\n\t\t\t'provenance',\n\t\t]\n\t\tconst keys = Object.keys(value)\n\t\tif (!keys.every((key) => allowed.includes(key))) return false\n\t\tif (!isString(value['completion'])) return false\n\t\tconst hasPrompt = Object.hasOwn(value, 'prompt') && value['prompt'] !== undefined\n\t\tconst hasMessages = Object.hasOwn(value, 'messages') && value['messages'] !== undefined\n\t\tif (hasPrompt === hasMessages) return false\n\t\tif (hasPrompt && !isString(value['prompt'])) return false\n\t\tif (\n\t\t\thasMessages &&\n\t\t\t(!isArray(value['messages']) ||\n\t\t\t\tvalue['messages'].length === 0 ||\n\t\t\t\t!value['messages'].every(isRecord))\n\t\t) {\n\t\t\treturn false\n\t\t}\n\t\tif (Object.hasOwn(value, 'group') && value['group'] !== undefined) {\n\t\t\tif (!isString(value['group']) || value['group'].length === 0) return false\n\t\t}\n\t\tif (Object.hasOwn(value, 'label') && value['label'] !== undefined) {\n\t\t\tif (!isString(value['label']) || value['label'].length === 0) return false\n\t\t}\n\t\treturn isRecord(value['provenance'])\n\t})\n}\n","import type { HeadWeights } from '@orkestrel/infer'\nimport type { AdamState, FitJob, FitTask, FitterContext, FitterInterface } from '../types.js'\nimport { checkSignal, InferError, yieldTurn } from '@orkestrel/infer'\nimport { FIT_RATE, FIT_STEPS } from '../constants.js'\nimport {\n\tbuildFeatureMatrix,\n\tbuildHeadWeights,\n\tcheckFitJobs,\n\tcheckFitterContext,\n\tcollectRows,\n\tcomputeClassWeights,\n\tcomputeErrors,\n\tcomputeGradient,\n\tcomputeOutputs,\n\tcomputeProbabilities,\n\tcomputeStandard,\n\tstepAdam,\n} from '../helpers.js'\n\n/**\n * Fits one head per job in turn on the calling thread.\n *\n * @remarks\n * The trainer's default fitter. `start` checks the context as `checkFitterContext` states and keeps\n * its own copy of the rows. `fit` checks the jobs as `checkFitJobs` states, then fits each job on its\n * rows, standardized on them, with inverse-frequency class weights, by `FIT_STEPS` full-batch Adam\n * steps at `FIT_RATE` from zero, yielding the thread and checking the signal before each step; on\n * abort it rejects with the `ABORT` code. A second `start` throws with the `ARGUMENT` code, as does a\n * `fit` before `start`; after `destroy`, both throw with the `DESTROYED` code.\n *\n * @example\n * ```ts\n * const fitter = new SerialFitter()\n * await fitter.start({ features, labels: [0, 0, 1, 1], classes: 2 })\n * const [head] = await fitter.fit([{ rows: [0, 1, 2, 3], penalty: 0.1 }])\n * await fitter.destroy()\n * ```\n */\nexport class SerialFitter implements FitterInterface {\n\t#context: FitterContext | undefined\n\t#destroyed = false\n\n\t/**\n\t * Takes the rows every later fit reads.\n\t *\n\t * @param context - The features, the labels, and the label count\n\t * @param signal - Cancels the start; it then rejects with the `ABORT` code\n\t */\n\tasync start(context: FitterContext, signal?: AbortSignal): Promise<void> {\n\t\tif (this.#destroyed) {\n\t\t\tthrow new InferError('The fitter has been destroyed.', { code: 'DESTROYED' })\n\t\t}\n\t\tif (this.#context !== undefined) {\n\t\t\tthrow new InferError('The fitter has already started; destroy it and create another.', {\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t})\n\t\t}\n\t\tcheckFitterContext(context)\n\t\tcheckSignal(signal, 'The fit start')\n\t\tthis.#context = {\n\t\t\tfeatures: context.features.map((feature) => Float32Array.from(feature)),\n\t\t\tlabels: [...context.labels],\n\t\t\tclasses: context.classes,\n\t\t}\n\t}\n\n\t/**\n\t * Fits one head per job and returns the heads in job order.\n\t *\n\t * @param jobs - The fits to run\n\t * @param signal - Cancels the fits; they then reject with the `ABORT` code\n\t * @returns Each job's head weights, in job order\n\t */\n\tasync fit(jobs: readonly FitJob[], signal?: AbortSignal): Promise<readonly HeadWeights[]> {\n\t\tconst context = this.#context\n\t\tif (context === undefined) {\n\t\t\tthrow this.#destroyed\n\t\t\t\t? new InferError('The fitter has been destroyed.', { code: 'DESTROYED' })\n\t\t\t\t: new InferError('The fitter has not started; start it with the rows its jobs read.', {\n\t\t\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\t\t})\n\t\t}\n\t\tcheckFitJobs(jobs, context.labels, context.classes)\n\t\tcheckSignal(signal, 'The fit')\n\t\tconst heads: HeadWeights[] = []\n\t\tfor (const job of jobs) heads.push(await this.#fit(context, job, signal))\n\t\treturn heads\n\t}\n\n\t/** Releases the rows; a second call does nothing. */\n\tasync destroy(): Promise<void> {\n\t\tthis.#destroyed = true\n\t\tthis.#context = undefined\n\t}\n\n\t// Fits one job on its rows, standardized on them, with inverse-frequency class weights.\n\tasync #fit(\n\t\tcontext: FitterContext,\n\t\tjob: FitJob,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<HeadWeights> {\n\t\tconst rows = collectRows(context.features, job.rows)\n\t\tconst labels = collectRows(context.labels, job.rows)\n\t\tconst standard = computeStandard(rows)\n\t\tconst matrix = buildFeatureMatrix(rows, standard)\n\t\tconst outputs = computeOutputs(context.classes)\n\t\tconst size = outputs * (matrix.columns + 1)\n\t\tconst task: FitTask = {\n\t\t\tmatrix,\n\t\t\tlabels,\n\t\t\tweights: computeClassWeights(labels, context.classes),\n\t\t\toutputs,\n\t\t\tpenalty: job.penalty,\n\t\t}\n\t\tconst state: AdamState = {\n\t\t\tmodel: new Float64Array(size),\n\t\t\tfirst: new Float64Array(size),\n\t\t\tsecond: new Float64Array(size),\n\t\t}\n\t\tconst fitted = await this.#descend(task, state, 1, signal)\n\t\treturn buildHeadWeights(fitted.model, standard, context.classes)\n\t}\n\n\t// Takes the Adam steps from `step` to FIT_STEPS, yielding the thread and checking the signal before\n\t// each one.\n\tasync #descend(\n\t\ttask: FitTask,\n\t\tstate: AdamState,\n\t\tstep: number,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<AdamState> {\n\t\tif (step > FIT_STEPS) return state\n\t\tcheckSignal(signal, 'The fit')\n\t\tawait yieldTurn()\n\t\tconst probabilities = computeProbabilities(state.model, task.matrix, task.outputs)\n\t\tconst errors = computeErrors(probabilities, task.labels, task.weights, task.outputs)\n\t\tconst gradient = computeGradient(errors, task.matrix, task.outputs, state.model, task.penalty)\n\t\treturn this.#descend(task, stepAdam(state, gradient, step, FIT_RATE), step + 1, signal)\n\t}\n}\n","import type { HeadWeights, ThreadHostInterface } from '@orkestrel/infer'\nimport type { FitJob, FitSetup, FitterContext, FitterInterface } from '../types.js'\nimport { checkSignal, InferError, yieldTurn } from '@orkestrel/infer'\nimport { FIT_BATCH, FIT_PROGRAM, FIT_SLICE, FIT_SLOTS } from '../constants.js'\nimport { buildFitSetup, checkFitJobs, checkFitterContext, readFitWeights } from '../helpers.js'\n\n/**\n * Fits one head per job across the worker threads of a host, over one shared copy of the rows.\n *\n * @remarks\n * The fitter owns its host: `start` copies the context's features and labels into shared memory once\n * and starts the host's workers on `FIT_PROGRAM`, and `destroy` stops the workers and destroys the\n * host. `fit` writes each batch's jobs into the shared job regions, wakes the workers, and waits in\n * the host's `wait` for slices of `FIT_SLICE` milliseconds, yielding a turn and reading the signal\n * between them. Each worker claims job indexes through `Atomics.add` and fits each claimed job whole,\n * through the same arithmetic as `SerialFitter`, into the job's own result slot, so the heads are read\n * by job index and are byte-identical to `SerialFitter`'s at any worker count and in any completion\n * order. A list longer than the regions hold, `FIT_BATCH` jobs or the host's size if more, runs in\n * batches.\n *\n * Construction refuses a host without `SharedArrayBuffer`, such as a page that is not\n * `crossOriginIsolated`, with the `HOST` code. `start` checks the context as `checkFitterContext`\n * states and rejects as the host's `start` does, the `HOST` and `THREAD` codes included. `fit` checks\n * the jobs as `checkFitJobs` states. On abort, `fit` halts every worker at its next Adam step and\n * rejects with the `ABORT` code; a job that throws on its worker halts every worker and fails the call\n * with the `THREAD` code, naming the job and its text. After either, and after a failed start, `fit`\n * throws with the `THREAD` code, so destroy the fitter. A second `start` throws with the `ARGUMENT`\n * code, as does a `fit` before `start`; after `destroy`, both throw with the `DESTROYED` code. No job\n * is bounded by time: a worker that dies without reporting, such as one the host's memory limit ends,\n * leaves `fit` waiting until the signal aborts.\n *\n * @example\n * ```ts\n * const fitter = new ThreadFitter(createNodeThreadHost({ size: 4 }))\n * await fitter.start({ features, labels: [0, 0, 1, 1], classes: 2 })\n * const [head] = await fitter.fit([{ rows: [0, 1, 2, 3], penalty: 0.1 }])\n * await fitter.destroy()\n * ```\n */\nexport class ThreadFitter implements FitterInterface {\n\treadonly #host: ThreadHostInterface\n\t#setup: FitSetup | undefined\n\t#destroyed = false\n\n\t/**\n\t * Creates a fitter over a thread host it then owns.\n\t *\n\t * @param host - The host whose workers run the jobs\n\t */\n\tconstructor(host: ThreadHostInterface) {\n\t\tif (typeof SharedArrayBuffer !== 'function') {\n\t\t\tthrow new InferError(\n\t\t\t\t'A thread fitter shares its rows with the workers through a SharedArrayBuffer, which this host lacks; on a page, serve the document with Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp, or fit without threads.',\n\t\t\t\t{ code: 'HOST' },\n\t\t\t)\n\t\t}\n\t\tthis.#host = host\n\t}\n\n\t/**\n\t * Copies the rows into shared memory and starts the host's workers on them.\n\t *\n\t * @param context - The features, the labels, and the label count\n\t * @param signal - Cancels the start; it then rejects with the `ABORT` code\n\t */\n\tasync start(context: FitterContext, signal?: AbortSignal): Promise<void> {\n\t\tif (this.#destroyed) {\n\t\t\tthrow new InferError('The fitter has been destroyed.', { code: 'DESTROYED' })\n\t\t}\n\t\tif (this.#setup !== undefined) {\n\t\t\tthrow new InferError('The fitter has already started; destroy it and create another.', {\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t})\n\t\t}\n\t\tcheckFitterContext(context)\n\t\tcheckSignal(signal, 'The fit start')\n\t\tconst setup = buildFitSetup(context, Math.max(FIT_BATCH, this.#host.size))\n\t\tthis.#setup = setup\n\t\tawait this.#host.start(FIT_PROGRAM, setup, signal)\n\t}\n\n\t/**\n\t * Fits one head per job across the workers and returns the heads in job order.\n\t *\n\t * @param jobs - The fits to run\n\t * @param signal - Cancels the fits; they then reject with the `ABORT` code\n\t * @returns Each job's head weights, in job order\n\t */\n\tasync fit(jobs: readonly FitJob[], signal?: AbortSignal): Promise<readonly HeadWeights[]> {\n\t\tconst setup = this.#setup\n\t\tif (setup === undefined) {\n\t\t\tthrow this.#destroyed\n\t\t\t\t? new InferError('The fitter has been destroyed.', { code: 'DESTROYED' })\n\t\t\t\t: new InferError('The fitter has not started; start it with the rows its jobs read.', {\n\t\t\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\t\t})\n\t\t}\n\t\tconst control = new Int32Array(setup.control)\n\t\tif (Atomics.load(control, FIT_SLOTS.ready) < this.#host.size) {\n\t\t\tthrow new InferError(\n\t\t\t\t'Not every worker of the thread fitter is running, because its start failed; destroy it and create another.',\n\t\t\t\t{ code: 'THREAD' },\n\t\t\t)\n\t\t}\n\t\tif (Atomics.load(control, FIT_SLOTS.halt) !== 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t'The thread fitter halted its workers after an abort or a failed job; destroy it and create another.',\n\t\t\t\t{ code: 'THREAD' },\n\t\t\t)\n\t\t}\n\t\tcheckFitJobs(jobs, new Int32Array(setup.labels), setup.classes)\n\t\tcheckSignal(signal, 'The fit')\n\t\tconst firsts = Array.from(\n\t\t\t{ length: Math.ceil(jobs.length / setup.capacity) },\n\t\t\t(_, batch) => batch * setup.capacity,\n\t\t)\n\t\tconst batches: Array<readonly HeadWeights[]> = []\n\t\tfor (const first of firsts) {\n\t\t\tbatches.push(await this.#run(setup, jobs.slice(first, first + setup.capacity), first, signal))\n\t\t}\n\t\treturn batches.flat()\n\t}\n\n\t/** Halts the workers and destroys the host; a second call does nothing. */\n\tasync destroy(): Promise<void> {\n\t\tthis.#destroyed = true\n\t\tconst setup = this.#setup\n\t\tthis.#setup = undefined\n\t\tif (setup !== undefined) Atomics.store(new Int32Array(setup.control), FIT_SLOTS.halt, 1)\n\t\tawait this.#host.destroy()\n\t}\n\n\t// Posts one batch of jobs, waits until every worker has claimed past its last job, and reads each\n\t// job's head from its own result slot.\n\tasync #run(\n\t\tsetup: FitSetup,\n\t\tbatch: readonly FitJob[],\n\t\tfirst: number,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<readonly HeadWeights[]> {\n\t\tconst control = new Int32Array(setup.control)\n\t\tconst chosen = batch.map((job) => new Set(job.rows))\n\t\tnew Uint8Array(setup.members).set(\n\t\t\tUint8Array.from({ length: batch.length * setup.rows }, (_, flat) =>\n\t\t\t\tchosen[Math.floor(flat / setup.rows)]?.has(flat % setup.rows) === true ? 1 : 0,\n\t\t\t),\n\t\t)\n\t\tnew Float64Array(setup.penalties).set(batch.map((job) => job.penalty))\n\t\tAtomics.store(control, FIT_SLOTS.count, batch.length)\n\t\tAtomics.store(control, FIT_SLOTS.next, 0)\n\t\tAtomics.store(control, FIT_SLOTS.idle, 0)\n\t\tAtomics.add(control, FIT_SLOTS.generation, 1)\n\t\tAtomics.notify(control, FIT_SLOTS.generation)\n\t\tawait this.#wait(control, signal)\n\t\tconst fault = Atomics.load(control, FIT_SLOTS.fault)\n\t\tif (fault !== 0) {\n\t\t\tconst units = new Uint16Array(setup.message)\n\t\t\tconst end = units.indexOf(0)\n\t\t\tconst text = String.fromCharCode(...units.subarray(0, end < 0 ? units.length : end))\n\t\t\tthrow new InferError(`Fit job ${first + fault - 1} threw on a worker thread: ${text}`, {\n\t\t\t\tcode: 'THREAD',\n\t\t\t\tcontext: { job: first + fault - 1 },\n\t\t\t})\n\t\t}\n\t\tconst results = new Float64Array(setup.results)\n\t\treturn batch.map((_, job) => readFitWeights(results, job, setup))\n\t}\n\n\t// Blocks in the host's wait in slices until every worker is idle, yielding a turn between slices and\n\t// halting the workers when the signal aborts.\n\tasync #wait(control: Int32Array, signal: AbortSignal | undefined): Promise<void> {\n\t\tfor (;;) {\n\t\t\tconst idle = Atomics.load(control, FIT_SLOTS.idle)\n\t\t\tif (idle >= this.#host.size) return\n\t\t\tthis.#host.wait(control, FIT_SLOTS.idle, idle, FIT_SLICE)\n\t\t\tawait yieldTurn()\n\t\t\tif (signal?.aborted === true) {\n\t\t\t\tAtomics.store(control, FIT_SLOTS.halt, 1)\n\t\t\t\tcheckSignal(signal, 'The fit')\n\t\t\t}\n\t\t}\n\t}\n}\n","import type { JudgeQuestion } from '@orkestrel/agent'\nimport type {\n\tBackboneInterface,\n\tCalibration,\n\tHeadRecord,\n\tThreadHostInterface,\n} from '@orkestrel/infer'\nimport type {\n\tFitterInterface,\n\tFoldOutcome,\n\tFoldSplit,\n\tTrainerInterface,\n\tTrainerOptions,\n\tTrainerResult,\n\tTrainerRow,\n\tTrainerSelection,\n\tTrainerSettings,\n} from '../types.js'\nimport { buildHeadGGUF, checkSignal, computeSignature, InferError } from '@orkestrel/infer'\nimport { SerialFitter } from '../fitters/SerialFitter.js'\nimport { ThreadFitter } from '../fitters/ThreadFitter.js'\nimport {\n\tadmitRows,\n\tassignFolds,\n\tbuildOperatingTable,\n\tbuildSplits,\n\tcheckFolds,\n\tcheckLabels,\n\tcollectRows,\n\tcomputeAccuracy,\n\tcomputeDatasetDigest,\n\tcomputeDistributions,\n\tcomputeHeadLogits,\n\tcomputeLabelAUCs,\n\tencodeStates,\n\textractScores,\n\tfitCalibration,\n\tinferRowLabels,\n\tinferStrata,\n\tpoolOutcomes,\n\tresolveTrainerSettings,\n\tselectPenalty,\n} from '../helpers.js'\n\n/**\n * Fits and calibrates a frozen-feature decision head over an `@orkestrel/infer` backbone's features, and writes\n * the head file `@orkestrel/infer`'s `createHead` loads.\n *\n * @remarks\n * `execute` admits the rows, maps each to a head label, and assigns stratified folds over the rows'\n * own labels before it embeds anything, so a refusal costs no forward. It then embeds every row's\n * state at the depth, mean-pooled, and:\n *\n * - **Chooses the L2 strength.** With more than one penalty, it cross-validates each one over the\n * first repeat's folds other than the held fold, inside the rows the head fits on, and keeps the\n * highest mean label-against-rest AUC, the stronger penalty on a tie.\n * - **Cross-validates.** Each repeat fits one head per fold on the other folds' rows, standardized on\n * them, with inverse-frequency class weights, by `FIT_STEPS` full-batch Adam steps at `FIT_RATE`\n * from zero, and scores the fold's rows through the head's own arithmetic. The AUCs and the\n * accuracy average the repeats.\n * - **Keeps the head the held fold scored.** Fold 0 of the first repeat is the held split, and its\n * fold's head is the head the file carries, so the fit never read a held row.\n * - **Calibrates on the held rows.** It fits a temperature and per-label biases on the held rows'\n * logits alone, as `fitCalibration` states.\n * - **Reports an operating table** per label from the first repeat's out-of-fold logits under the\n * head's calibration; the caller picks the cutoff.\n *\n * Every penalty's inner fits run as one batch of independent jobs, and every repeat's fold fits as\n * another. Without the `threads` option, a `SerialFitter` runs them in turn on the calling thread.\n * With it, the trainer calls `threads` once per `execute`, before the first forward, and runs the\n * batches through a `ThreadFitter` over the host it returns; the result is byte-identical. The\n * trainer owns that host: it destroys it before `execute` settles, on every path. It never holds a\n * host it did not create, so it destroys none.\n *\n * Every refusal rejects with a `InferError`: the `ARGUMENT` code for rows `admitRows`,\n * `inferRowLabels`, `checkLabels`, `checkFolds`, or `encodeStates` refuses; the `HOST` code, before\n * any forward, when `threads` is given on a host without `SharedArrayBuffer`; the codes the host's\n * own `start` rejects with, after the forwards; and the `ABORT` code when the signal aborts, checked\n * before the rows are read, before each forward, before the fits start, and before each optimizer\n * step of a head fit, or between the slices a threaded fit waits in. The constructor throws as\n * `resolveTrainerSettings` states.\n *\n * @example\n * ```ts\n * const trainer = new Trainer({ backbone, depth: 18, question, target: 'correction' })\n * const result = await trainer.execute(rows, signal)\n * const head = await createHead(new MemorySource(result.bytes), { backbone })\n * ```\n */\nexport class Trainer implements TrainerInterface {\n\treadonly #backbone: BackboneInterface\n\treadonly #question: JudgeQuestion\n\treadonly #settings: TrainerSettings\n\treadonly #threads: (() => ThreadHostInterface) | undefined\n\n\t/**\n\t * Creates a trainer over a backbone and a question.\n\t *\n\t * @param options - The backbone, the depth, the question, the cross-validation settings, and the\n\t * thread host factory\n\t */\n\tconstructor(options: TrainerOptions) {\n\t\tthis.#settings = resolveTrainerSettings(options)\n\t\tthis.#backbone = options.backbone\n\t\tthis.#question = options.question\n\t\tthis.#threads = options.threads\n\t}\n\n\t/**\n\t * Embeds the rows, cross-validates, fits, and calibrates a head, and returns its file.\n\t *\n\t * @param rows - The labelled rows\n\t * @param signal - Cancels the run; it then rejects with the `ABORT` code\n\t * @returns The head file and the readings of its fit\n\t */\n\tasync execute(rows: readonly TrainerRow[], signal?: AbortSignal): Promise<TrainerResult> {\n\t\tcheckSignal(signal, 'The training')\n\t\tconst settings = this.#settings\n\t\tconst admitted = admitRows(rows)\n\t\tconst labels = inferRowLabels(admitted, settings)\n\t\tcheckLabels(labels, settings)\n\t\tconst strata = inferStrata(admitted)\n\t\tconst groups = admitted.some((row) => row.group !== undefined)\n\t\t\t? admitted.map((row) => row.group)\n\t\t\t: undefined\n\t\tconst assignments = Array.from({ length: settings.repeats }, (_, repeat) =>\n\t\t\tassignFolds(strata, settings.folds, settings.seed + repeat, groups),\n\t\t)\n\t\tfor (const assignment of assignments) checkFolds(assignment, labels, settings, groups)\n\t\tconst tokens = encodeStates(admitted, this.#backbone.tokenizer, this.#backbone.limit)\n\t\tconst fitter = await this.#createFitter()\n\t\ttry {\n\t\t\tconst features = await this.#extract(tokens, signal)\n\t\t\tawait fitter.start({ features, labels, classes: settings.labels.length }, signal)\n\t\t\treturn await this.#train(admitted, labels, assignments, features, fitter, signal)\n\t\t} finally {\n\t\t\tawait fitter.destroy()\n\t\t}\n\t}\n\n\t// Creates the fitter one execute runs its fits through, destroying the host it created when the\n\t// thread fitter refuses that host.\n\tasync #createFitter(): Promise<FitterInterface> {\n\t\tconst threads = this.#threads\n\t\tif (threads === undefined) return new SerialFitter()\n\t\tconst host = threads()\n\t\ttry {\n\t\t\treturn new ThreadFitter(host)\n\t\t} catch (error) {\n\t\t\tawait host.destroy()\n\t\t\tthrow error\n\t\t}\n\t}\n\n\t// Embeds each row's tokens in turn at the settings' depth.\n\tasync #extract(\n\t\ttokens: ReadonlyArray<readonly number[]>,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<readonly Float32Array[]> {\n\t\tconst features: Float32Array[] = []\n\t\tfor (const state of tokens) {\n\t\t\tfeatures.push(await this.#backbone.embed(state, this.#settings.depth, signal))\n\t\t}\n\t\treturn features\n\t}\n\n\t// Chooses the penalty, cross-validates every repeat, calibrates the held head, and writes its file.\n\tasync #train(\n\t\tadmitted: readonly TrainerRow[],\n\t\tlabels: readonly number[],\n\t\tassignments: ReadonlyArray<readonly number[]>,\n\t\tfeatures: readonly Float32Array[],\n\t\tfitter: FitterInterface,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<TrainerResult> {\n\t\tconst settings = this.#settings\n\t\tconst backbone = this.#backbone\n\t\tconst [primary = []] = assignments\n\t\tconst selection =\n\t\t\tsettings.penalties.length > 1\n\t\t\t\t? await this.#select(fitter, features, labels, primary, signal)\n\t\t\t\t: []\n\t\tconst penalty = selection.length > 0 ? selectPenalty(selection) : (settings.penalties[0] ?? 0)\n\t\tconst splits = assignments.map((assignment) =>\n\t\t\tbuildSplits(assignment, settings.folds, undefined),\n\t\t)\n\t\tconst [fitted = []] = await this.#validate(fitter, features, splits.flat(), [penalty], signal)\n\t\tconst repeats = splits.map((_, repeat) =>\n\t\t\tfitted.slice(repeat * settings.folds, (repeat + 1) * settings.folds),\n\t\t)\n\t\tconst all = admitted.map((_, row) => row)\n\t\tconst classes = settings.labels.length\n\t\tconst identity: Calibration = { temperature: 1, bias: settings.labels.map(() => 0) }\n\t\tconst pooled = splits.map((repeat, index) =>\n\t\t\tpoolOutcomes(\n\t\t\t\trepeat,\n\t\t\t\t(repeats[index] ?? []).map((outcome) => outcome.logits),\n\t\t\t\tall,\n\t\t\t\tclasses,\n\t\t\t),\n\t\t)\n\t\tconst distributions = pooled.map((logits) =>\n\t\t\tcomputeDistributions(logits, classes, identity, backbone.strict),\n\t\t)\n\t\tconst aucs = distributions.map((values) => computeLabelAUCs(values, labels, classes))\n\t\tconst [deployed] = repeats[0] ?? []\n\t\tif (deployed === undefined) {\n\t\t\tthrow new InferError('The first repeat fitted no fold to keep.', { code: 'ARGUMENT' })\n\t\t}\n\t\tconst held = primary.flatMap((fold, row) => (fold === 0 ? [row] : []))\n\t\tconst calibration = fitCalibration(\n\t\t\tcomputeHeadLogits(deployed.weights, collectRows(features, held)),\n\t\t\tcollectRows(labels, held),\n\t\t\tclasses,\n\t\t\tbackbone.strict,\n\t\t)\n\t\tconst operating = computeDistributions(\n\t\t\tpooled[0] ?? new Float64Array(0),\n\t\t\tclasses,\n\t\t\tcalibration,\n\t\t\tbackbone.strict,\n\t\t)\n\t\tconst readings = settings.labels.map((label, position) => ({\n\t\t\tlabel,\n\t\t\trows: labels.filter((value) => value === position).length,\n\t\t\tauc: aucs.reduce((sum, values) => sum + (values[position] ?? 0), 0) / aucs.length,\n\t\t\ttable: buildOperatingTable(\n\t\t\t\textractScores(operating, classes, position),\n\t\t\t\tlabels.map((value) => value === position),\n\t\t\t),\n\t\t}))\n\t\tconst accuracies = distributions.map((values) => computeAccuracy(values, labels, classes))\n\t\tconst record: HeadRecord = {\n\t\t\tbase: backbone.digest,\n\t\t\tdepth: settings.depth,\n\t\t\tpooling: 'mean',\n\t\t\tsignature: await computeSignature(this.#question),\n\t\t\tlabels: [...settings.labels],\n\t\t\tcalibration,\n\t\t\tdataset: await computeDatasetDigest(admitted),\n\t\t\tseed: settings.seed,\n\t\t\tmetrics: {\n\t\t\t\tauc: readings.reduce((sum, reading) => sum + reading.auc, 0) / readings.length,\n\t\t\t\taccuracy: accuracies.reduce((sum, value) => sum + value, 0) / accuracies.length,\n\t\t\t\tpenalty,\n\t\t\t\trows: admitted.length,\n\t\t\t\theld: held.length,\n\t\t\t\tfolds: settings.folds,\n\t\t\t\trepeats: settings.repeats,\n\t\t\t},\n\t\t}\n\t\treturn {\n\t\t\tbytes: buildHeadGGUF(record, deployed.weights),\n\t\t\trecord,\n\t\t\tweights: deployed.weights,\n\t\t\tlabels: readings,\n\t\t\tselection,\n\t\t\theld,\n\t\t}\n\t}\n\n\t// Reads each penalty's mean label AUC over the first repeat's folds but the held one, inside the\n\t// rows the head fits on.\n\tasync #select(\n\t\tfitter: FitterInterface,\n\t\tfeatures: readonly Float32Array[],\n\t\tlabels: readonly number[],\n\t\tassignment: readonly number[],\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<readonly TrainerSelection[]> {\n\t\tconst settings = this.#settings\n\t\tconst classes = settings.labels.length\n\t\tconst splits = buildSplits(assignment, settings.folds, 0)\n\t\tconst fitted = assignment.flatMap((fold, row) => (fold === 0 ? [] : [row]))\n\t\tconst identity: Calibration = { temperature: 1, bias: settings.labels.map(() => 0) }\n\t\tconst groups = await this.#validate(fitter, features, splits, settings.penalties, signal)\n\t\treturn settings.penalties.map((penalty, index) => {\n\t\t\tconst distributions = computeDistributions(\n\t\t\t\tpoolOutcomes(\n\t\t\t\t\tsplits,\n\t\t\t\t\t(groups[index] ?? []).map((outcome) => outcome.logits),\n\t\t\t\t\tfitted,\n\t\t\t\t\tclasses,\n\t\t\t\t),\n\t\t\t\tclasses,\n\t\t\t\tidentity,\n\t\t\t\tthis.#backbone.strict,\n\t\t\t)\n\t\t\tconst aucs = computeLabelAUCs(distributions, collectRows(labels, fitted), classes)\n\t\t\treturn { penalty, auc: aucs.reduce((sum, auc) => sum + auc, 0) / aucs.length }\n\t\t})\n\t}\n\n\t// Fits one head per penalty and split as one batch, penalty by penalty, and scores each split's rows\n\t// through its head; returns each penalty's outcomes in split order.\n\tasync #validate(\n\t\tfitter: FitterInterface,\n\t\tfeatures: readonly Float32Array[],\n\t\tsplits: readonly FoldSplit[],\n\t\tpenalties: readonly number[],\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<ReadonlyArray<readonly FoldOutcome[]>> {\n\t\tconst jobs = penalties.flatMap((penalty) =>\n\t\t\tsplits.map((split) => ({ rows: split.train, penalty })),\n\t\t)\n\t\tconst heads = await fitter.fit(jobs, signal)\n\t\treturn penalties.map((_, group) =>\n\t\t\tsplits.map((split, index) => {\n\t\t\t\tconst weights = heads[group * splits.length + index]\n\t\t\t\tif (weights === undefined) {\n\t\t\t\t\tthrow new InferError(\n\t\t\t\t\t\t`The fitter returned ${heads.length} heads for ${jobs.length} jobs.`,\n\t\t\t\t\t\t{ code: 'ARGUMENT' },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\treturn { weights, logits: computeHeadLogits(weights, collectRows(features, split.test)) }\n\t\t\t}),\n\t\t)\n\t}\n}\n","import type { ConversationSnapshot, JudgeAnswer, Judgment, Message } from '@orkestrel/agent'\nimport type { CSVParseResult, ParseOptions } from '@orkestrel/csv'\nimport type {\n\tAdapterInterface,\n\tAdapterOptions,\n\tAdapterPair,\n\tAdapterTarget,\n\tArchitecture,\n\tArchitectureFamily,\n\tByteSourceInterface,\n\tCalibration,\n\tChatTemplateInterface,\n\tDigest,\n\tGGUFFormat,\n\tGGUFTensor,\n\tGGUFValue,\n\tHeadWeights,\n\tSafetensorsFormat,\n\tSafetensorsTensor,\n\tSectionEntry,\n\tSectionFormat,\n\tSectionInterface,\n\tSectionOptions,\n\tSectionTarget,\n\tTokenizerInterface,\n\tTokenSpan,\n\tTrainPlan,\n} from '@orkestrel/infer'\nimport type {\n\tTemplateDocument,\n\tTemplateFillValues,\n\tTemplateTreeInterface,\n} from '@orkestrel/template'\nimport type {\n\tAdamState,\n\tAdapterCalibrationOptions,\n\tAdapterCalibrationResult,\n\tAdapterCombinationEntry,\n\tAdapterCombinationOptions,\n\tAdapterScaleCandidate,\n\tByteSinkInterface,\n\tChangeCountOptions,\n\tChangeCountResult,\n\tCheckpoint,\n\tCheckpointReadOptions,\n\tCheckpointTarget,\n\tConversationRow,\n\tConversationRowOptions,\n\tFeatureMatrix,\n\tFeatureStandard,\n\tFinetuneRow,\n\tFinetunerOptions,\n\tFinetunerSchedule,\n\tFinetunerSettings,\n\tFitJob,\n\tFitSetup,\n\tFitterContext,\n\tFlipCountOptions,\n\tFlipCountResult,\n\tFoldSplit,\n\tFormatChangeEntry,\n\tFormatChangeOptions,\n\tFormatChangeResult,\n\tHeadTraceOptions,\n\tHeadTraceResult,\n\tHeadTraceToken,\n\tJudgmentRowOptions,\n\tJudgmentRowResult,\n\tMergeGGUFFormat,\n\tMergeGGUFOptions,\n\tMergeSafetensorsOptions,\n\tPEFTBundle,\n\tPEFTConfig,\n\tPEFTConversionOptions,\n\tPrecisionFormat,\n\tRefitHeadOptions,\n\tRefitHeadResult,\n\tRefitHeadTrace,\n\tRowProvenance,\n\tSafetensorsWriteEntry,\n\tSectionReadOptions,\n\tSectionTraceBlock,\n\tSectionTraceOptions,\n\tSectionTraceResult,\n\tSectionTraceTarget,\n\tTensorWeightDiff,\n\tTrainerCSVOptions,\n\tTrainerCut,\n\tTrainerOptions,\n\tTrainerRow,\n\tTrainerSelection,\n\tTrainerSettings,\n\tWeightDiffOptions,\n\tWeightDiffResult,\n} from './types.js'\nimport {\n\tcollectQuestionKeys,\n\tisConversationSnapshot,\n\tisJudgeQuestion,\n\tmatchesJSON,\n\tmeasureAnswer,\n\tscanJudgmentTies,\n} from '@orkestrel/agent'\nimport {\n\tattempt,\n\tcanonicalStringify,\n\tdescribeFaults,\n\tholds,\n\tisArray,\n\tisBoolean,\n\tisBoundedJSONRecord,\n\tisFiniteNumber,\n\tisFloat32Array,\n\tisFunction,\n\tisObject,\n\tisRecord,\n\tisSafeInteger,\n\tisString,\n\tisUint8Array,\n\tparseJSON,\n\tseededRandom,\n} from '@orkestrel/contract'\nimport { isCSVError, parseCSV } from '@orkestrel/csv'\nimport {\n\tAdapter,\n\tADAPTER_KEYS,\n\tADAPTER_TARGET_SPECS,\n\tADAPTER_TARGETS,\n\talignOffset,\n\tARCHITECTURE_FAMILIES,\n\tBACKWARD_SEGMENT,\n\tbuildChatMessages,\n\tbuildGGUF,\n\tcheckAdapterBinding,\n\tcheckAdapterOptions,\n\tcheckHeadWeights,\n\tcheckSectionBinding,\n\tcheckSectionOptions,\n\tcheckSignal,\n\tcheckTrainPlan,\n\tcomputeElements,\n\tcomputeTensorBytes,\n\tdigestBytes,\n\tencodeGGUFBigInts,\n\tencodeGGUFNumbers,\n\tencodeGGUFTensor,\n\texponentiate,\n\tfindTensorOverlap,\n\tGGUF_ALIGNMENT,\n\tGGUF_BLOCKS,\n\tGGUF_KEYS,\n\tGGUF_MAGIC,\n\tGGUF_VERSION,\n\tinterleaveRotary,\n\tisSectionFormat,\n\tisSectionTarget,\n\tjoinBytes,\n\tInferError,\n\tmatchesCount,\n\tmatchesElements,\n\tmatchesTokenBound,\n\tMemorySource,\n\tnarrowHalf,\n\tquoteFaultText,\n\treadAdapter,\n\treadArchitecture,\n\treadGGUF,\n\treadGGUFFile,\n\treadMetadataInteger,\n\treadMetadataNumber,\n\treadMetadataString,\n\treadMetadataStrings,\n\treadNamedTensor,\n\treadSafetensors,\n\treadSafetensorsEntry,\n\treadSection,\n\tresolveAlignment,\n\troundAway,\n\tSAFETENSORS_FORMATS,\n\tSAFETENSORS_HEADER_LIMIT,\n\tSection,\n\tSECTION_KEYS,\n\tSECTION_TARGET_SUFFIXES,\n\tSECTION_TARGETS,\n\tSECTION_TENSOR_PATTERN,\n\tSHA256_PATTERN,\n\tUTF8_ENCODER,\n\twidenHalf,\n\twidenTensor,\n} from '@orkestrel/infer'\nimport { createNDJSONParser } from '@orkestrel/ndjson'\nimport {\n\tcompileTemplate,\n\tevaluateTemplate,\n\tisTemplateDocument,\n\tisTemplateError,\n} from '@orkestrel/template'\nimport {\n\tADAM_EPSILON,\n\tADAM_FIRST,\n\tADAM_SECOND,\n\tADAPTER_CALIBRATION_SCALES,\n\tCALIBRATION_PRIOR,\n\tCALIBRATION_RATE,\n\tCALIBRATION_STEPS,\n\tCHECKPOINT_KEYS,\n\tCHECKPOINT_TENSOR_PREFIXES,\n\tCHECKPOINT_TYPE,\n\tCHECKPOINT_VERSION,\n\tFINETUNER_BATCH,\n\tFINETUNER_CLIP,\n\tFINETUNER_DECAY,\n\tFINETUNER_EPOCHS,\n\tFINETUNER_EPSILON,\n\tFINETUNER_FIRST,\n\tFINETUNER_LIMIT,\n\tFINETUNER_RATE,\n\tFINETUNER_SECOND,\n\tFINETUNER_SEED,\n\tFINETUNER_WARMUP,\n\tFIT_MESSAGE,\n\tFIT_SLOTS,\n\tHEAD_FILE_EXTENSION,\n\tMERGE_CHUNK_BYTES,\n\tMERGE_ROW_STRIP,\n\tMERGE_SOURCE_FORMATS,\n\tPEFT_BASE_LAYERS_PREFIX,\n\tPEFT_BASE_QWEN35_PREFIX,\n\tPEFT_LAYERS_PREFIX,\n\tPEFT_QWEN35_PREFIX,\n\tPEFT_TARGET_SPECS,\n\tPEFT_TENSOR_PATTERN,\n\tPRECISION_FORMATS,\n\tROW_KEYS,\n\tSECTION_PATCH_TYPE,\n\tSECTION_PATCH_VERSION,\n\tSECTION_SAFETENSORS_SPECS,\n\tTRAINER_FOLD_FLOOR,\n\tTRAINER_FOLDS,\n\tTRAINER_PENALTIES,\n\tTRAINER_REPEATS,\n\tTRAINER_SEED,\n} from './constants.js'\nimport { Trainer } from './trainers/Trainer.js'\nimport {\n\tisByteSink,\n\tisCheckpoint,\n\tisCheckpointId,\n\tisCheckpointMode,\n\tisCheckpointTarget,\n\tisFinetuneRow,\n\tisFinetunerSchedule,\n\tisMergeGGUFFormat,\n\tisPrecisionFormat,\n\tisTrainerRow,\n} from './validators.js'\n\n/**\n * Resolves a trainer's options into its settings, applying each default and refusing each value it\n * cannot run.\n *\n * @remarks\n * Thrown with the `ARGUMENT` code when the question fails `isJudgeQuestion`, which admits at least\n * two candidate keys, or offers an empty candidate key, the depth is not an integer from 1 to the backbone's layers, a target\n * accompanies a question that is not a noul, the folds are not an integer of at least\n * `TRAINER_FOLD_FLOOR`, the repeats are not a positive integer, the seed is not a safe integer, the\n * penalties are empty or hold a value that is not finite and non-negative, or `threads` is given and\n * is not a function.\n *\n * @param options - The trainer's options\n * @returns The settings\n *\n * @example\n * ```ts\n * resolveTrainerSettings({ backbone, depth: 18, question: { form: 'noul' } }).labels // ['true', 'false']\n * ```\n */\nexport function resolveTrainerSettings(options: TrainerOptions): TrainerSettings {\n\tconst { backbone, depth, question, target } = options\n\tif (!isJudgeQuestion(question)) {\n\t\tthrow new InferError(\n\t\t\t'The trainer question is not a judge question: pass a choice, a score, or a noul as @orkestrel/agent defines them.',\n\t\t\t{ code: 'ARGUMENT' },\n\t\t)\n\t}\n\tconst labels = collectQuestionKeys(question)\n\tif (labels.some((label) => label.length === 0)) {\n\t\tthrow new InferError(\n\t\t\t'The trainer question offers an empty candidate key; a head names each label by a non-empty key.',\n\t\t\t{ code: 'ARGUMENT', context: { labels: labels.length } },\n\t\t)\n\t}\n\tconst { layers } = backbone.architecture\n\tif (!matchesCount(depth, 1) || depth > layers) {\n\t\tthrow new InferError(\n\t\t\t`The trainer depth is ${depth}; the backbone embeds at an integer depth from 1 to ${layers}.`,\n\t\t\t{ code: 'ARGUMENT', context: { depth, layers } },\n\t\t)\n\t}\n\tif (target !== undefined && question.form !== 'noul') {\n\t\tthrow new InferError(\n\t\t\t`The target ${quoteFaultText(target)} names the rows a noul's \"true\" reads, and the question is a ${question.form}; drop the target and label each row with one of the question's candidate keys.`,\n\t\t\t{ code: 'ARGUMENT', context: { form: question.form } },\n\t\t)\n\t}\n\tconst folds = options.folds ?? TRAINER_FOLDS\n\tif (!matchesCount(folds, TRAINER_FOLD_FLOOR)) {\n\t\tthrow new InferError(\n\t\t\t`The trainer runs ${folds} folds; it runs an integer of at least ${TRAINER_FOLD_FLOOR}, one of which holds the calibration rows.`,\n\t\t\t{ code: 'ARGUMENT', context: { folds } },\n\t\t)\n\t}\n\tconst repeats = options.repeats ?? TRAINER_REPEATS\n\tif (!matchesCount(repeats, 1)) {\n\t\tthrow new InferError(`The trainer runs ${repeats} repeats; it runs a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { repeats },\n\t\t})\n\t}\n\tconst seed = options.seed ?? TRAINER_SEED\n\tif (!Number.isSafeInteger(seed)) {\n\t\tthrow new InferError(`The trainer seed is ${seed}; it is a safe integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { seed },\n\t\t})\n\t}\n\tconst penalties = options.penalties ?? TRAINER_PENALTIES\n\tif (\n\t\tpenalties.length === 0 ||\n\t\t!penalties.every((penalty) => Number.isFinite(penalty) && penalty >= 0)\n\t) {\n\t\tthrow new InferError(\n\t\t\t'The trainer penalties are one or more finite, non-negative L2 strengths.',\n\t\t\t{ code: 'ARGUMENT', context: { penalties: penalties.length } },\n\t\t)\n\t}\n\tif (options.threads !== undefined && typeof options.threads !== 'function') {\n\t\tthrow new InferError(\n\t\t\t'The trainer threads option is a function that creates a thread host, such as () => createNodeThreadHost({ size: 15 }).',\n\t\t\t{ code: 'ARGUMENT' },\n\t\t)\n\t}\n\treturn { depth, labels: [...labels], target, folds, repeats, seed, penalties: [...penalties] }\n}\n\n/**\n * Admits a list of training rows, copying each one.\n *\n * @remarks\n * Thrown with the `ARGUMENT` code when the list is empty or an entry fails `isTrainerRow`; the\n * message names the entry's index and its faults.\n *\n * @param rows - The rows to admit\n * @returns Owned copies of the rows\n *\n * @example\n * ```ts\n * admitRows([{ state: 'user: hi', label: 'chatter' }]).length // 1\n * ```\n */\nexport function admitRows(rows: readonly unknown[]): readonly TrainerRow[] {\n\tif (rows.length === 0) {\n\t\tthrow new InferError('The trainer received no rows; pass at least one row of each label.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\treturn rows.map((row, index) => {\n\t\tif (isTrainerRow(row)) {\n\t\t\treturn row.group === undefined\n\t\t\t\t? { state: row.state, label: row.label }\n\t\t\t\t: { state: row.state, label: row.label, group: row.group }\n\t\t}\n\t\tthrow new InferError(renderRowRefusal(row, `The row at index ${index}`), {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { row: index },\n\t\t})\n\t})\n}\n\n/**\n * Renders the refusal of a value that is not a training row, naming each fault.\n *\n * @remarks\n * Each member name the value carries is JSON-encoded and capped, so a malformed row cannot fake or\n * balloon the message.\n *\n * @param value - The refused value\n * @param subject - The words that open the message and locate the value\n * @returns The refusal message\n *\n * @example\n * ```ts\n * renderRowRefusal({ state: 'user: hi' }, 'Record 3')\n * // 'Record 3 lacks \"label\"; a training row is a JSON object of a string \"state\", a string \"label\", and an optional non-empty string \"group\".'\n * ```\n */\nexport function renderRowRefusal(value: unknown, subject: string): string {\n\tconst shape =\n\t\t'a training row is a JSON object of a string \"state\", a string \"label\", and an optional non-empty string \"group\".'\n\tif (!isRecord(value)) return `${subject} is not a JSON object; ${shape}`\n\tconst keys = Object.keys(value)\n\tconst missing = ROW_KEYS.filter((key) => !keys.includes(key)).map((key) => quoteFaultText(key))\n\tconst unexpected = keys\n\t\t.filter((key) => !ROW_KEYS.includes(key) && key !== 'group')\n\t\t.map((key) => quoteFaultText(key))\n\tconst checked = [...ROW_KEYS, ...(keys.includes('group') ? ['group'] : [])]\n\tconst mistyped = checked\n\t\t.filter((key) => keys.includes(key))\n\t\t.filter((key) => !holds(() => isString(value[key])))\n\t\t.map((key) => quoteFaultText(key))\n\tconst emptyGroup =\n\t\tkeys.includes('group') && holds(() => isString(value['group']) && value['group'].length === 0)\n\tconst extra = unexpected.length > 5 ? ` and ${unexpected.length - 5} more` : ''\n\tconst faults = [\n\t\tmissing.length > 0 ? `lacks ${missing.join(' and ')}` : '',\n\t\tunexpected.length > 0 ? `carries ${unexpected.slice(0, 5).join(', ')}${extra}` : '',\n\t\tmistyped.length > 0 ? `holds ${mistyped.join(' and ')} as a value that is not a string` : '',\n\t\temptyGroup ? 'holds \"group\" as an empty string' : '',\n\t].filter((fault) => fault.length > 0)\n\tconst found = faults.length > 0 ? faults.join(', ') : 'carries a member a row does not declare'\n\treturn `${subject} ${found}; ${shape}`\n}\n\n/**\n * Encodes each row's state with a backbone's tokenizer, refusing a state the backbone cannot embed.\n *\n * @remarks\n * Thrown with the `ARGUMENT` code, naming the row's index, when a state holds more UTF-8 bytes than\n * `limit` tokens can cover (`matchesTokenBound`), which is refused before the state is encoded, or\n * when a state encodes to no token or to more than `limit` tokens.\n *\n * @param rows - The rows\n * @param tokenizer - The backbone's tokenizer\n * @param limit - The most tokens one embedding admits\n * @returns Each row's token ids, in row order\n *\n * @example\n * ```ts\n * encodeStates(rows, backbone.tokenizer, backbone.limit)[0].length // 9\n * ```\n */\nexport function encodeStates(\n\trows: readonly TrainerRow[],\n\ttokenizer: TokenizerInterface,\n\tlimit: number,\n): ReadonlyArray<readonly number[]> {\n\treturn rows.map((row, index) => {\n\t\tif (!matchesTokenBound(tokenizer, row.state, limit)) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The row at index ${index} holds more UTF-8 bytes than ${limit} tokens of at most ${tokenizer.span} bytes can cover; the backbone embeds a state of 1 to ${limit} tokens.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { row: index, limit, span: tokenizer.span } },\n\t\t\t)\n\t\t}\n\t\tconst tokens = tokenizer.encode(row.state)\n\t\tif (tokens.length === 0 || tokens.length > limit) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The row at index ${index} encodes to ${tokens.length} tokens; the backbone embeds a state of 1 to ${limit} tokens.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { row: index, tokens: tokens.length, limit } },\n\t\t\t)\n\t\t}\n\t\treturn tokens\n\t})\n}\n\n/**\n * Infers each row's head label index from its label and the trainer's settings.\n *\n * @remarks\n * Without a target, a row's label is its head label. With one, a row carrying the target reads\n * `true` and every other row reads `false`. Thrown with the `ARGUMENT` code, naming the row's index,\n * when a head label is not one of the question's candidate keys.\n *\n * @param rows - The rows\n * @param settings - The trainer's settings\n * @returns Each row's index into `settings.labels`, in row order\n *\n * @example\n * ```ts\n * inferRowLabels([{ state: 's', label: 'correction' }], { ...settings, target: 'correction' }) // [0]\n * ```\n */\nexport function inferRowLabels(\n\trows: readonly TrainerRow[],\n\tsettings: TrainerSettings,\n): readonly number[] {\n\tconst { labels, target } = settings\n\treturn rows.map((row, index) => {\n\t\tconst label = target === undefined ? row.label : row.label === target ? 'true' : 'false'\n\t\tconst position = labels.indexOf(label)\n\t\tif (position >= 0) return position\n\t\tthrow new InferError(\n\t\t\t`The row at index ${index} carries the label ${quoteFaultText(row.label)}, which the question does not offer; label each row with one of ${labels.map((name) => quoteFaultText(name)).join(', ')}.`,\n\t\t\t{ code: 'ARGUMENT', context: { row: index } },\n\t\t)\n\t})\n}\n\n/**\n * Refuses rows that do not cover a question's labels or that hold a label with fewer rows than\n * folds.\n *\n * @remarks\n * Thrown with the `ARGUMENT` code, naming the label, when no row reads one of the question's labels,\n * or a label's rows number fewer than `settings.folds`, so some fold could not hold one.\n *\n * @param labels - Each row's head label index\n * @param settings - The trainer's settings\n *\n * @example\n * ```ts\n * checkLabels([0, 0, 0, 1, 1], { ...settings, folds: 3 }) // throws: the second label has 2 rows\n * ```\n */\nexport function checkLabels(labels: readonly number[], settings: TrainerSettings): void {\n\tconst counts = settings.labels.map(\n\t\t(_, position) => labels.filter((label) => label === position).length,\n\t)\n\tconst empty = settings.labels.findIndex((_, position) => counts[position] === 0)\n\tif (empty >= 0) {\n\t\tconst label = settings.labels[empty] ?? ''\n\t\tthrow new InferError(\n\t\t\t`No row reads the question's label ${quoteFaultText(label)}${settings.target === undefined || label !== 'true' ? '' : `, which the rows labelled ${quoteFaultText(settings.target)} read`}; the rows cover a question only when each of its labels has rows.`,\n\t\t\t{ code: 'ARGUMENT', context: { label } },\n\t\t)\n\t}\n\tconst short = settings.labels.findIndex((_, position) => (counts[position] ?? 0) < settings.folds)\n\tif (short >= 0) {\n\t\tconst label = settings.labels[short] ?? ''\n\t\tconst rows = counts[short] ?? 0\n\t\tthrow new InferError(\n\t\t\t`The label ${quoteFaultText(label)} has ${rows} rows; ${settings.folds} folds need at least ${settings.folds} rows of each label, so pass more rows of it or run fewer folds.`,\n\t\t\t{ code: 'ARGUMENT', context: { label, rows, folds: settings.folds } },\n\t\t)\n\t}\n}\n\n/**\n * Infers each row's stratum: the position of its label among the labels in the order they first\n * appear.\n *\n * @param rows - The rows\n * @returns Each row's stratum, in row order\n *\n * @example\n * ```ts\n * inferStrata([{ state: 'a', label: 'b' }, { state: 'c', label: 'a' }, { state: 'd', label: 'b' }]) // [0, 1, 0]\n * ```\n */\nexport function inferStrata(rows: readonly TrainerRow[]): readonly number[] {\n\tconst order = new Map(\n\t\t[...new Set(rows.map((row) => row.label))].map((label, place) => [label, place]),\n\t)\n\treturn rows.map((row) => order.get(row.label) ?? 0)\n}\n\n/**\n * Assigns each row a stratified fold under a seed, keeping rows sharing a group in one fold when\n * groups are supplied.\n *\n * @remarks\n * Without `groups`, or when every entry in `groups` is `undefined`, each stratum's rows take one\n * draw each from one `seededRandom(seed)` stream in stratum order and then row order, sort by it,\n * lay end to end, and take fold `p` modulo `folds`, so each stratum splits across folds with counts\n * differing by at most one. When `groups` carries at least one group identifier, rows sharing a\n * group stay in one fold while groups stratify greedily across strata; ungrouped rows act as\n * singleton groups. Thrown with the `ARGUMENT` code when `groups` length differs from `strata`, a\n * defined group is empty, `folds` is not a positive integer, or fewer than `folds` distinct groups\n * exist.\n *\n * @param strata - Each row's stratum, from 0\n * @param folds - The number of folds\n * @param seed - The seed of the draws\n * @param groups - Optional per-row group identifiers kept together in one fold\n * @returns Each row's fold, in row order\n *\n * @example\n * ```ts\n * assignFolds([0, 0, 0, 1, 1], 5, 7) // the stratum-0 rows take folds 0, 1, 2 and the others 3, 4\n * ```\n */\nexport function assignFolds(\n\tstrata: readonly number[],\n\tfolds: number,\n\tseed: number,\n\tgroups?: ReadonlyArray<string | undefined>,\n): readonly number[] {\n\tif (groups !== undefined && groups.length !== strata.length) {\n\t\tthrow new InferError(\n\t\t\t`The fold assignment received ${groups.length} groups for ${strata.length} rows; pass one group entry per row.`,\n\t\t\t{ code: 'ARGUMENT', context: { groups: groups.length, rows: strata.length } },\n\t\t)\n\t}\n\tif (groups !== undefined) {\n\t\tconst blank = groups.findIndex((group) => group !== undefined && group.length === 0)\n\t\tif (blank >= 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The group at index ${blank} is empty; a row group is a non-empty string or undefined.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { row: blank } },\n\t\t\t)\n\t\t}\n\t}\n\tif (groups === undefined || groups.every((group) => group === undefined)) {\n\t\tconst random = seededRandom(seed)\n\t\tconst count = strata.reduce((top, stratum) => Math.max(top, stratum + 1), 0)\n\t\tconst sequence = Array.from({ length: count }, (_, stratum) => stratum).flatMap((stratum) =>\n\t\t\tstrata\n\t\t\t\t.flatMap((value, row) => (value === stratum ? [row] : []))\n\t\t\t\t.map((row) => ({ row, key: random() }))\n\t\t\t\t.toSorted((one, two) => one.key - two.key)\n\t\t\t\t.map((entry) => entry.row),\n\t\t)\n\t\tconst places = new Map(sequence.map((row, place) => [row, place % folds]))\n\t\treturn strata.map((_, row) => places.get(row) ?? 0)\n\t}\n\tif (!matchesCount(folds, 1)) {\n\t\tthrow new InferError(`The fold count is ${folds}; pass a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { folds },\n\t\t})\n\t}\n\tconst grouped = Map.groupBy(\n\t\tstrata.map((_, row) => row),\n\t\t(row) => {\n\t\t\tconst group = groups[row]\n\t\t\treturn group === undefined ? `r:${row}` : `g:${group}`\n\t\t},\n\t)\n\tconst distinct = grouped.size\n\tif (distinct < folds) {\n\t\tthrow new InferError(\n\t\t\t`The rows hold ${distinct} distinct groups; ${folds} folds need at least ${folds} distinct groups.`,\n\t\t\t{ code: 'ARGUMENT', context: { groups: distinct, folds } },\n\t\t)\n\t}\n\tconst stratumCount = strata.reduce((top, stratum) => Math.max(top, stratum + 1), 0)\n\tconst stratumTotals = Array.from(\n\t\t{ length: stratumCount },\n\t\t(_, stratum) => strata.filter((value) => value === stratum).length,\n\t)\n\tconst random = seededRandom(seed)\n\tconst foldOrder = Array.from({ length: folds }, (_, fold) => ({ fold, key: random() }))\n\t\t.toSorted((one, two) => one.key - two.key)\n\t\t.map((entry) => entry.fold)\n\tconst entries = [...grouped.values()]\n\t\t.map((rows) => {\n\t\t\tconst counts = Array.from(\n\t\t\t\t{ length: stratumCount },\n\t\t\t\t(_, stratum) => rows.filter((row) => strata[row] === stratum).length,\n\t\t\t)\n\t\t\tconst rarest = counts.reduce(\n\t\t\t\t(low, count, stratum) =>\n\t\t\t\t\tcount > 0 ? Math.min(low, stratumTotals[stratum] ?? Number.POSITIVE_INFINITY) : low,\n\t\t\t\tNumber.POSITIVE_INFINITY,\n\t\t\t)\n\t\t\treturn { rows, counts, rarest, key: random() }\n\t\t})\n\t\t.toSorted(\n\t\t\t(one, two) =>\n\t\t\t\tone.rarest - two.rarest || two.rows.length - one.rows.length || one.key - two.key,\n\t\t)\n\tconst emptyCounts = Array.from({ length: folds }, () =>\n\t\tArray.from({ length: stratumCount }, () => 0),\n\t)\n\tconst emptyTotals = Array.from({ length: folds }, () => 0)\n\tconst steps: Array<{\n\t\treadonly rows: readonly number[]\n\t\treadonly fold: number\n\t\treadonly counts: ReadonlyArray<readonly number[]>\n\t\treadonly totals: readonly number[]\n\t}> = []\n\tfor (const entry of entries) {\n\t\tconst prior = steps.at(-1)\n\t\tconst currentCounts = prior?.counts ?? emptyCounts\n\t\tconst currentTotals = prior?.totals ?? emptyTotals\n\t\tconst chosen = foldOrder.reduce(\n\t\t\t(best, fold) => {\n\t\t\t\tconst foldCounts = currentCounts[fold] ?? []\n\t\t\t\tconst delta = entry.counts.reduce((sum, add, stratum) => {\n\t\t\t\t\tif (add === 0) return sum\n\t\t\t\t\tconst target = (stratumTotals[stratum] ?? 1) / folds\n\t\t\t\t\tconst before = foldCounts[stratum] ?? 0\n\t\t\t\t\treturn sum + (2 * before * add + add * add) / (target * target)\n\t\t\t\t}, 0)\n\t\t\t\tconst total = currentTotals[fold] ?? 0\n\t\t\t\tif (delta < best.delta || (delta === best.delta && total < best.total)) {\n\t\t\t\t\treturn { fold, delta, total }\n\t\t\t\t}\n\t\t\t\treturn best\n\t\t\t},\n\t\t\t{ fold: foldOrder[0] ?? 0, delta: Number.POSITIVE_INFINITY, total: Number.POSITIVE_INFINITY },\n\t\t).fold\n\t\tconst nextCounts = currentCounts.map((counts, fold) =>\n\t\t\tfold === chosen\n\t\t\t\t? counts.map((count, stratum) => count + (entry.counts[stratum] ?? 0))\n\t\t\t\t: counts,\n\t\t)\n\t\tconst nextTotals = currentTotals.map((total, fold) =>\n\t\t\tfold === chosen ? total + entry.rows.length : total,\n\t\t)\n\t\tsteps.push({ rows: entry.rows, fold: chosen, counts: nextCounts, totals: nextTotals })\n\t}\n\tconst places = new Map(steps.flatMap((step) => step.rows.map((row) => [row, step.fold] as const)))\n\treturn strata.map((_, row) => places.get(row) ?? 0)\n}\n\n/**\n * Refuses a fold assignment that leaves a head label out of some fold or splits a row group across\n * folds.\n *\n * @remarks\n * A label whose rows span several strata or groups can miss a fold even with as many rows as folds.\n * When `groups` is supplied, any defined group appearing in more than one fold is refused. Thrown\n * with the `ARGUMENT` code naming the label and fold, or the leaked group and its folds.\n *\n * @param assignment - Each row's fold\n * @param labels - Each row's head label index\n * @param settings - The trainer's settings\n * @param groups - Optional per-row group identifiers that must not span multiple folds\n *\n * @example\n * ```ts\n * checkFolds([0, 1, 2, 0, 1, 1], [0, 0, 0, 1, 1, 1], { ...settings, folds: 3 }) // throws: label 1 misses fold 2\n * ```\n */\nexport function checkFolds(\n\tassignment: readonly number[],\n\tlabels: readonly number[],\n\tsettings: TrainerSettings,\n\tgroups?: ReadonlyArray<string | undefined>,\n): void {\n\tif (groups !== undefined) {\n\t\tif (groups.length !== assignment.length) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The fold check received ${groups.length} groups for ${assignment.length} rows; pass one group entry per row.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { groups: groups.length, rows: assignment.length } },\n\t\t\t)\n\t\t}\n\t\tconst lastFold = new Map(\n\t\t\tgroups.flatMap((group, row) =>\n\t\t\t\tgroup === undefined ? [] : [[group, assignment[row] ?? -1] as const],\n\t\t\t),\n\t\t)\n\t\tconst leakedRow = groups.findIndex(\n\t\t\t(group, row) => group !== undefined && assignment[row] !== lastFold.get(group),\n\t\t)\n\t\tif (leakedRow >= 0) {\n\t\t\tconst leaked = groups[leakedRow] ?? ''\n\t\t\tconst spanned = [\n\t\t\t\t...new Set(\n\t\t\t\t\tgroups.flatMap((group, row) => (group === leaked ? [assignment[row] ?? -1] : [])),\n\t\t\t\t),\n\t\t\t].toSorted((one, two) => one - two)\n\t\t\tthrow new InferError(\n\t\t\t\t`The group ${quoteFaultText(leaked)} spans folds ${spanned.join(' and ')}; every row of one group must stay in one fold.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { group: leaked, folds: spanned } },\n\t\t\t)\n\t\t}\n\t}\n\tconst gaps = settings.labels.flatMap((label, position) =>\n\t\tArray.from({ length: settings.folds }, (_, fold) => fold)\n\t\t\t.filter(\n\t\t\t\t(fold) => !labels.some((value, row) => value === position && assignment[row] === fold),\n\t\t\t)\n\t\t\t.map((fold) => ({ label, fold })),\n\t)\n\tconst [gap] = gaps\n\tif (gap === undefined) return\n\tthrow new InferError(\n\t\t`The label ${quoteFaultText(gap.label)} has no row in fold ${gap.fold}, because its rows span categories the folds stratify apart; pass more rows of it or run fewer folds.`,\n\t\t{ code: 'ARGUMENT', context: { label: gap.label, fold: gap.fold } },\n\t)\n}\n\n/**\n * Builds the fold splits of an assignment: each fold's rows to score and the other rows to fit.\n *\n * @remarks\n * A `skip` fold takes no part: no split scores it, and no split fits on its rows. The trainer skips\n * the held fold when it chooses the L2 strength inside the rows the head fits on.\n *\n * @param assignment - Each row's fold\n * @param folds - The number of folds\n * @param skip - The fold to leave out, or undefined to keep every fold\n * @returns One split per kept fold, in fold order\n *\n * @example\n * ```ts\n * buildSplits([0, 1, 2, 1], 3, 0) // [{ train: [2], test: [1, 3] }, { train: [1, 3], test: [2] }]\n * ```\n */\nexport function buildSplits(\n\tassignment: readonly number[],\n\tfolds: number,\n\tskip: number | undefined,\n): readonly FoldSplit[] {\n\treturn Array.from({ length: folds }, (_, fold) => fold)\n\t\t.filter((fold) => fold !== skip)\n\t\t.map((fold) => ({\n\t\t\ttrain: assignment.flatMap((value, row) => (value === fold || value === skip ? [] : [row])),\n\t\t\ttest: assignment.flatMap((value, row) => (value === fold ? [row] : [])),\n\t\t}))\n}\n\n/**\n * Collects the entries of a list at the given indexes, in index order.\n *\n * @remarks\n * Thrown with the `ARGUMENT` code when an index names no entry.\n *\n * @param values - The list\n * @param indexes - The indexes to collect\n * @returns The entries\n *\n * @example\n * ```ts\n * collectRows(['a', 'b', 'c'], [2, 0]) // ['c', 'a']\n * ```\n */\nexport function collectRows<T>(values: readonly T[], indexes: readonly number[]): readonly T[] {\n\treturn indexes.map((index) => {\n\t\tconst value = values[index]\n\t\tif (value !== undefined) return value\n\t\tthrow new InferError(`No row sits at index ${index} of ${values.length} rows.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { index, rows: values.length },\n\t\t})\n\t})\n}\n\n/**\n * Computes per-row class weights inverse to each class's frequency, with a mean of 1 over the rows.\n *\n * @remarks\n * A row's weight is `rows / (classes * count of its class)`; with two classes it is the balanced\n * weighting. Thrown with the `ARGUMENT` code when a class has no row.\n *\n * @param labels - Each row's class\n * @param classes - The number of classes\n * @returns Each row's weight\n *\n * @example\n * ```ts\n * computeClassWeights([0, 0, 0, 1], 2) // Float64Array [0.667, 0.667, 0.667, 2]\n * ```\n */\nexport function computeClassWeights(labels: readonly number[], classes: number): Float64Array {\n\tconst counts = Array.from(\n\t\t{ length: classes },\n\t\t(_, label) => labels.filter((value) => value === label).length,\n\t)\n\tconst empty = counts.findIndex((count) => count === 0)\n\tif (empty >= 0) {\n\t\tthrow new InferError(\n\t\t\t`Class ${empty} has no row among ${labels.length}; its inverse-frequency weight is undefined.`,\n\t\t\t{ code: 'ARGUMENT', context: { label: empty } },\n\t\t)\n\t}\n\treturn Float64Array.from(\n\t\tlabels,\n\t\t(label) => labels.length / (classes * (counts[label] ?? Number.NaN)),\n\t)\n}\n\n/**\n * Computes the number of model outputs a head over a label count fits.\n *\n * @remarks\n * A two-label head fits one logistic output, the first label's log-odds, as the probes' binary arm\n * did; any other count fits one softmax output per label.\n *\n * @param classes - The number of labels\n * @returns The number of outputs\n *\n * @example\n * ```ts\n * computeOutputs(2) // 1\n * computeOutputs(7) // 7\n * ```\n */\nexport function computeOutputs(classes: number): number {\n\treturn classes === 2 ? 1 : classes\n}\n\n/**\n * Computes each column's mean and population deviation over feature rows, with a constant column\n * scaled by 1.\n *\n * @remarks\n * Sums each column's terms in row order, dividing each by the row count, as the probes' readout did.\n *\n * @param rows - The feature rows, of one width\n * @returns The standardization\n *\n * @example\n * ```ts\n * computeStandard([Float32Array.of(1, 5), Float32Array.of(3, 5)]) // mean [2, 5], scale [1, 1]\n * ```\n */\nexport function computeStandard(rows: readonly Float32Array[]): FeatureStandard {\n\tconst count = rows.length\n\tconst columns = rows[0]?.length ?? 0\n\tconst mean = new Float64Array(columns)\n\tfor (let column = 0; column < columns; column += 1) {\n\t\tlet sum = 0\n\t\tfor (let row = 0; row < count; row += 1) sum += (rows[row]?.[column] ?? 0) / count\n\t\tmean[column] = sum\n\t}\n\tconst variance = new Float64Array(columns)\n\tfor (let column = 0; column < columns; column += 1) {\n\t\tlet sum = 0\n\t\tfor (let row = 0; row < count; row += 1) {\n\t\t\tconst gap = (rows[row]?.[column] ?? 0) - (mean[column] ?? 0)\n\t\t\tsum += (gap * gap) / count\n\t\t}\n\t\tvariance[column] = sum\n\t}\n\tconst scale = Float64Array.from(variance, (value) => {\n\t\tconst deviation = Math.sqrt(value)\n\t\treturn deviation > 0 ? deviation : 1\n\t})\n\treturn { mean, scale }\n}\n\n/**\n * Builds the standardized matrix of feature rows, row by row and column by column.\n *\n * @param rows - The feature rows\n * @param standard - The standardization to apply\n * @returns The matrix\n *\n * @example\n * ```ts\n * buildFeatureMatrix([Float32Array.of(1), Float32Array.of(3)], { mean: Float64Array.of(2), scale: Float64Array.of(1) }).values\n * // Float64Array [-1, 1]\n * ```\n */\nexport function buildFeatureMatrix(\n\trows: readonly Float32Array[],\n\tstandard: FeatureStandard,\n): FeatureMatrix {\n\tconst count = rows.length\n\tconst columns = standard.mean.length\n\tconst values = new Float64Array(count * columns)\n\tfor (let row = 0; row < count; row += 1) {\n\t\tfor (let column = 0; column < columns; column += 1) {\n\t\t\tvalues[row * columns + column] =\n\t\t\t\t((rows[row]?.[column] ?? 0) - (standard.mean[column] ?? 0)) / (standard.scale[column] ?? 1)\n\t\t}\n\t}\n\tconst transpose = new Float64Array(count * columns)\n\tfor (let column = 0; column < columns; column += 1) {\n\t\tfor (let row = 0; row < count; row += 1) {\n\t\t\ttranspose[column * count + row] = values[row * columns + column] ?? 0\n\t\t}\n\t}\n\treturn { rows: count, columns, values, transpose }\n}\n\n/**\n * Computes the logistic function without overflow on either side.\n *\n * @param value - The log-odds\n * @returns The probability\n *\n * @example\n * ```ts\n * computeLogistic(0) // 0.5\n * ```\n */\nexport function computeLogistic(value: number): number {\n\tif (value >= 0) return 1 / (1 + Math.exp(-value))\n\tconst exponent = Math.exp(value)\n\treturn exponent / (1 + exponent)\n}\n\n/**\n * Computes a model's probabilities over standardized rows.\n *\n * @remarks\n * The model holds, per output, the column weights then the bias. One output is a logistic model, the\n * first label's probability per row; more is a softmax, `outputs` probabilities per row. Each sum\n * starts at the bias and adds the columns in order, as the probes' readout did.\n *\n * @param model - The parameters, `outputs * (columns + 1)` values\n * @param matrix - The standardized rows\n * @param outputs - The number of outputs\n * @returns The probabilities, row by row\n *\n * @example\n * ```ts\n * computeProbabilities(new Float64Array(3), matrix, 1) // 0.5 for every row\n * ```\n */\nexport function computeProbabilities(\n\tmodel: Float64Array,\n\tmatrix: FeatureMatrix,\n\toutputs: number,\n): Float64Array {\n\tconst { rows, columns, values } = matrix\n\tconst stride = columns + 1\n\tconst blocked = rows - (rows % 4)\n\tconst logits = new Float64Array(rows * outputs)\n\t// Four rows share each weight read, and each row keeps its own sum in column order.\n\tfor (let row = 0; row < blocked; row += 4) {\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tconst weight = output * stride\n\t\t\tconst bias = model[weight + columns] ?? 0\n\t\t\tconst one = row * columns\n\t\t\tconst two = one + columns\n\t\t\tconst three = two + columns\n\t\t\tconst four = three + columns\n\t\t\tlet first = bias\n\t\t\tlet second = bias\n\t\t\tlet third = bias\n\t\t\tlet fourth = bias\n\t\t\tfor (let column = 0; column < columns; column += 1) {\n\t\t\t\tconst coefficient = model[weight + column] ?? 0\n\t\t\t\tfirst += coefficient * (values[one + column] ?? 0)\n\t\t\t\tsecond += coefficient * (values[two + column] ?? 0)\n\t\t\t\tthird += coefficient * (values[three + column] ?? 0)\n\t\t\t\tfourth += coefficient * (values[four + column] ?? 0)\n\t\t\t}\n\t\t\tlogits[row * outputs + output] = first\n\t\t\tlogits[(row + 1) * outputs + output] = second\n\t\t\tlogits[(row + 2) * outputs + output] = third\n\t\t\tlogits[(row + 3) * outputs + output] = fourth\n\t\t}\n\t}\n\tfor (let row = blocked; row < rows; row += 1) {\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tlet sum = model[output * stride + columns] ?? 0\n\t\t\tfor (let column = 0; column < columns; column += 1) {\n\t\t\t\tsum += (model[output * stride + column] ?? 0) * (values[row * columns + column] ?? 0)\n\t\t\t}\n\t\t\tlogits[row * outputs + output] = sum\n\t\t}\n\t}\n\tconst probabilities = new Float64Array(rows * outputs)\n\tif (outputs === 1) {\n\t\tfor (let row = 0; row < rows; row += 1) probabilities[row] = computeLogistic(logits[row] ?? 0)\n\t\treturn probabilities\n\t}\n\tfor (let row = 0; row < rows; row += 1) {\n\t\tlet peak = Number.NEGATIVE_INFINITY\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tpeak = Math.max(peak, logits[row * outputs + output] ?? 0)\n\t\t}\n\t\tlet mass = 0\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tmass += Math.exp((logits[row * outputs + output] ?? 0) - peak)\n\t\t}\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tprobabilities[row * outputs + output] =\n\t\t\t\tMath.exp((logits[row * outputs + output] ?? 0) - peak) / mass\n\t\t}\n\t}\n\treturn probabilities\n}\n\n/**\n * Computes each output's weighted error over the rows, output by output.\n *\n * @remarks\n * An error is `(probability - target) * weight / rows`, where the target is 1 when the row's label is\n * the output's label: the gradient of the mean weighted cross-entropy at each output's logit. With one\n * output, its label is label 0.\n *\n * @param probabilities - The probabilities, row by row\n * @param labels - Each row's label index\n * @param weights - Each row's class weight\n * @param outputs - The number of outputs\n * @returns The errors, `outputs` runs of one value per row\n *\n * @example\n * ```ts\n * computeErrors(Float64Array.of(0.5, 0.5), [0, 1], Float64Array.of(1, 1), 1) // Float64Array [-0.25, 0.25]\n * ```\n */\nexport function computeErrors(\n\tprobabilities: Float64Array,\n\tlabels: readonly number[],\n\tweights: Float64Array,\n\toutputs: number,\n): Float64Array {\n\tconst rows = labels.length\n\tconst errors = new Float64Array(outputs * rows)\n\tfor (let output = 0; output < outputs; output += 1) {\n\t\tfor (let row = 0; row < rows; row += 1) {\n\t\t\tconst target = labels[row] === output ? 1 : 0\n\t\t\terrors[output * rows + row] =\n\t\t\t\t(((probabilities[row * outputs + output] ?? 0) - target) * (weights[row] ?? 0)) / rows\n\t\t}\n\t}\n\treturn errors\n}\n\n/**\n * Computes the gradient of the mean weighted cross-entropy plus an L2 penalty on every weight but the\n * biases.\n *\n * @remarks\n * Each column's term sums its errors times the column's values in row order, then adds `penalty`\n * times the weight, as the probes' optimizer did.\n *\n * @param errors - The errors, output by output\n * @param matrix - The standardized rows\n * @param outputs - The number of outputs\n * @param model - The parameters the penalty reads\n * @param penalty - The L2 strength\n * @returns The gradient, laid out as the model\n *\n * @example\n * ```ts\n * computeGradient(computeErrors(probabilities, labels, weights, 1), matrix, 1, model, 0.1)\n * ```\n */\nexport function computeGradient(\n\terrors: Float64Array,\n\tmatrix: FeatureMatrix,\n\toutputs: number,\n\tmodel: Float64Array,\n\tpenalty: number,\n): Float64Array {\n\tconst { rows, columns, transpose } = matrix\n\tconst stride = columns + 1\n\tconst blocked = columns - (columns % 4)\n\tconst gradient = new Float64Array(outputs * stride)\n\t// Keep columns outside outputs so each step streams transpose once while preserving row-order sums.\n\tfor (let column = 0; column < blocked; column += 4) {\n\t\tconst one = column * rows\n\t\tconst two = one + rows\n\t\tconst three = two + rows\n\t\tconst four = three + rows\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tconst error = output * rows\n\t\t\tconst weight = output * stride\n\t\t\tlet first = 0\n\t\t\tlet second = 0\n\t\t\tlet third = 0\n\t\t\tlet fourth = 0\n\t\t\tfor (let row = 0; row < rows; row += 1) {\n\t\t\t\tconst term = errors[error + row] ?? 0\n\t\t\t\tfirst += term * (transpose[one + row] ?? 0)\n\t\t\t\tsecond += term * (transpose[two + row] ?? 0)\n\t\t\t\tthird += term * (transpose[three + row] ?? 0)\n\t\t\t\tfourth += term * (transpose[four + row] ?? 0)\n\t\t\t}\n\t\t\tgradient[weight + column] = first + penalty * (model[weight + column] ?? 0)\n\t\t\tgradient[weight + column + 1] = second + penalty * (model[weight + column + 1] ?? 0)\n\t\t\tgradient[weight + column + 2] = third + penalty * (model[weight + column + 2] ?? 0)\n\t\t\tgradient[weight + column + 3] = fourth + penalty * (model[weight + column + 3] ?? 0)\n\t\t}\n\t}\n\tfor (let column = blocked; column < columns; column += 1) {\n\t\tconst base = column * rows\n\t\tfor (let output = 0; output < outputs; output += 1) {\n\t\t\tconst error = output * rows\n\t\t\tlet sum = 0\n\t\t\tfor (let row = 0; row < rows; row += 1) {\n\t\t\t\tsum += (errors[error + row] ?? 0) * (transpose[base + row] ?? 0)\n\t\t\t}\n\t\t\tgradient[output * stride + column] = sum + penalty * (model[output * stride + column] ?? 0)\n\t\t}\n\t}\n\tfor (let output = 0; output < outputs; output += 1) {\n\t\tconst error = output * rows\n\t\tlet bias = 0\n\t\tfor (let row = 0; row < rows; row += 1) bias += errors[error + row] ?? 0\n\t\tgradient[output * stride + columns] = bias\n\t}\n\treturn gradient\n}\n\n/**\n * Takes one Adam step, returning the next parameters and moment estimates.\n *\n * @param state - The parameters and moments before the step\n * @param gradient - The gradient at the parameters\n * @param step - The step's number, from 1\n * @param rate - The learning rate\n * @returns The state after the step\n *\n * @example\n * ```ts\n * stepAdam(state, gradient, 1, 0.01).model\n * ```\n */\nexport function stepAdam(\n\tstate: AdamState,\n\tgradient: Float64Array,\n\tstep: number,\n\trate: number,\n): AdamState {\n\tconst firstScale = 1 - Math.pow(ADAM_FIRST.decay, step)\n\tconst secondScale = 1 - Math.pow(ADAM_SECOND.decay, step)\n\tconst first = new Float64Array(gradient.length)\n\tconst second = new Float64Array(gradient.length)\n\tconst model = new Float64Array(state.model.length)\n\tfor (let index = 0; index < first.length; index += 1) {\n\t\tconst value = gradient[index] ?? 0\n\t\tfirst[index] = ADAM_FIRST.decay * (state.first[index] ?? 0) + ADAM_FIRST.gain * value\n\t\tsecond[index] =\n\t\t\tADAM_SECOND.decay * (state.second[index] ?? 0) + ADAM_SECOND.gain * value * value\n\t}\n\tfor (let index = 0; index < model.length; index += 1) {\n\t\tmodel[index] =\n\t\t\t(state.model[index] ?? 0) -\n\t\t\t(rate * ((first[index] ?? 0) / firstScale)) /\n\t\t\t\t(Math.sqrt((second[index] ?? 0) / secondScale) + ADAM_EPSILON)\n\t}\n\treturn { model, first, second }\n}\n\n/**\n * Builds a head's weights from a fitted model and its standardization, in single precision.\n *\n * @remarks\n * A softmax model's outputs become the label rows. A logistic model's output becomes the first\n * label's row and bias, and every other label's row and bias are zero, so the head's softmax gives\n * the first label the logistic probability.\n *\n * @param model - The fitted parameters\n * @param standard - The standardization the fit read\n * @param classes - The number of labels\n * @returns The head weights\n *\n * @example\n * ```ts\n * buildHeadWeights(model, standard, 2).matrix.length === 2 * standard.mean.length // true\n * ```\n */\nexport function buildHeadWeights(\n\tmodel: Float64Array,\n\tstandard: FeatureStandard,\n\tclasses: number,\n): HeadWeights {\n\tconst columns = standard.mean.length\n\tconst stride = columns + 1\n\tconst zero = computeOutputs(classes) === 1\n\treturn {\n\t\tmatrix: Float32Array.from({ length: classes * columns }, (_, index) => {\n\t\t\tconst label = Math.floor(index / columns)\n\t\t\treturn zero && label > 0 ? 0 : (model[label * stride + (index % columns)] ?? 0)\n\t\t}),\n\t\tbias: Float32Array.from({ length: classes }, (_, label) =>\n\t\t\tzero && label > 0 ? 0 : (model[label * stride + columns] ?? 0),\n\t\t),\n\t\tmean: Float32Array.from(standard.mean),\n\t\tscale: Float32Array.from(standard.scale),\n\t}\n}\n\n/**\n * Refuses a fitter context whose rows a fit cannot read.\n *\n * @remarks\n * Thrown with the `ARGUMENT` code when `classes` is not an integer of at least 2, the context holds no\n * row, the labels do not number one per row, a feature's width differs from the first one's, or a\n * label is not an integer from 0 to `classes - 1`; the message names the row.\n *\n * @param context - The features, the labels, and the label count\n *\n * @example\n * ```ts\n * checkFitterContext({ features: [Float32Array.of(1)], labels: [0, 1], classes: 2 }) // throws: 1 feature, 2 labels\n * ```\n */\nexport function checkFitterContext(context: FitterContext): void {\n\tconst { features, labels, classes } = context\n\tif (!matchesCount(classes, 2)) {\n\t\tthrow new InferError(\n\t\t\t`The fitter context holds ${classes} classes; a head fits an integer of at least 2 labels.`,\n\t\t\t{ code: 'ARGUMENT', context: { classes } },\n\t\t)\n\t}\n\tif (features.length === 0 || labels.length !== features.length) {\n\t\tthrow new InferError(\n\t\t\t`The fitter context holds ${features.length} features and ${labels.length} labels; pass at least one row and one label per row.`,\n\t\t\t{ code: 'ARGUMENT', context: { features: features.length, labels: labels.length } },\n\t\t)\n\t}\n\tconst width = features[0]?.length ?? 0\n\tconst uneven = features.findIndex((feature) => feature.length !== width)\n\tif (uneven >= 0) {\n\t\tthrow new InferError(\n\t\t\t`The feature at index ${uneven} holds ${features[uneven]?.length ?? 0} values and the first holds ${width}; every feature has one width.`,\n\t\t\t{ code: 'ARGUMENT', context: { row: uneven, width } },\n\t\t)\n\t}\n\tconst stray = labels.findIndex((label) => !matchesCount(label, 0) || label >= classes)\n\tif (stray >= 0) {\n\t\tthrow new InferError(\n\t\t\t`The label at index ${stray} is ${labels[stray] ?? Number.NaN}; each label is an integer from 0 to ${classes - 1}.`,\n\t\t\t{ code: 'ARGUMENT', context: { row: stray } },\n\t\t)\n\t}\n}\n\n/**\n * Refuses a fit job list that a fitter over rows with these labels cannot run.\n *\n * @remarks\n * Thrown with the `ARGUMENT` code, naming the job's index, when a job's penalty is not finite and\n * non-negative, its rows are not strictly ascending indexes of the labelled rows, or its rows hold no\n * row of some label, so that label's class weight is undefined.\n *\n * @param jobs - The jobs\n * @param labels - Each row's head label index\n * @param classes - The number of head labels\n *\n * @example\n * ```ts\n * checkFitJobs([{ rows: [2, 1], penalty: 0.1 }], [0, 1, 0], 2) // throws: the rows are not ascending\n * ```\n */\nexport function checkFitJobs(\n\tjobs: readonly FitJob[],\n\tlabels: ArrayLike<number>,\n\tclasses: number,\n): void {\n\tfor (const [index, job] of jobs.entries()) {\n\t\tconst { rows, penalty } = job\n\t\tif (!Number.isFinite(penalty) || penalty < 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t`Fit job ${index} has the penalty ${penalty}; a penalty is a finite, non-negative L2 strength.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { job: index } },\n\t\t\t)\n\t\t}\n\t\tconst disorder = rows.findIndex(\n\t\t\t(row, place) =>\n\t\t\t\t!matchesCount(row, 0) || row >= labels.length || row <= (rows[place - 1] ?? -1),\n\t\t)\n\t\tif (disorder >= 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t`Fit job ${index} lists ${rows[disorder] ?? Number.NaN} at place ${disorder}; a job lists row indexes from 0 to ${labels.length - 1}, strictly ascending.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { job: index, place: disorder } },\n\t\t\t)\n\t\t}\n\t\tconst missing = Array.from({ length: classes }, (_, label) => label).find(\n\t\t\t(label) => !rows.some((row) => labels[row] === label),\n\t\t)\n\t\tif (missing !== undefined) {\n\t\t\tthrow new InferError(\n\t\t\t\t`Fit job ${index} fits on no row of label ${missing}; a job holds at least one row of every label, so each class weight is defined.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { job: index, label: missing } },\n\t\t\t)\n\t\t}\n\t}\n}\n\n/**\n * Builds the shared memory a thread fitter hands every worker of `FIT_PROGRAM`, with the context's\n * features and labels copied in.\n *\n * @remarks\n * The control buffer holds one 32-bit slot per `FIT_SLOTS` entry, all 0. The job regions hold\n * `capacity` jobs, and the message region `FIT_MESSAGE` code units. A result takes the fit's column\n * means, its column scales, and its `computeOutputs(classes) * (columns + 1)` parameters. Requires\n * `SharedArrayBuffer`, which a page holds only when `crossOriginIsolated`.\n *\n * @param context - The features, the labels, and the label count\n * @param capacity - The most jobs the regions hold at once\n * @returns The setup record\n *\n * @example\n * ```ts\n * buildFitSetup({ features: [Float32Array.of(1, 2)], labels: [0], classes: 2 }, 64).stride // 7\n * ```\n */\nexport function buildFitSetup(context: FitterContext, capacity: number): FitSetup {\n\tconst rows = context.features.length\n\tconst columns = context.features[0]?.length ?? 0\n\tconst { classes } = context\n\tconst stride = 2 * columns + computeOutputs(classes) * (columns + 1)\n\tconst features = new SharedArrayBuffer(rows * columns * Float32Array.BYTES_PER_ELEMENT)\n\tconst values = new Float32Array(features)\n\tfor (const [row, feature] of context.features.entries()) values.set(feature, row * columns)\n\tconst labels = new SharedArrayBuffer(rows * Int32Array.BYTES_PER_ELEMENT)\n\tnew Int32Array(labels).set(context.labels)\n\treturn {\n\t\tcontrol: new SharedArrayBuffer(Object.keys(FIT_SLOTS).length * Int32Array.BYTES_PER_ELEMENT),\n\t\tfeatures,\n\t\tlabels,\n\t\tmembers: new SharedArrayBuffer(capacity * rows),\n\t\tpenalties: new SharedArrayBuffer(capacity * Float64Array.BYTES_PER_ELEMENT),\n\t\tresults: new SharedArrayBuffer(capacity * stride * Float64Array.BYTES_PER_ELEMENT),\n\t\tmessage: new SharedArrayBuffer(FIT_MESSAGE * Uint16Array.BYTES_PER_ELEMENT),\n\t\trows,\n\t\tcolumns,\n\t\tclasses,\n\t\tcapacity,\n\t\tstride,\n\t}\n}\n\n/**\n * Reads one job's head weights from a thread fitter's result region.\n *\n * @remarks\n * The job's slot holds `setup.stride` doubles: the column means, the column scales, then the model.\n * The weights are built as `buildHeadWeights` builds them, so they copy every value out of the\n * region.\n *\n * @param results - The result region, as doubles\n * @param job - The job's index within its batch\n * @param setup - The setup whose shape the region follows\n * @returns The job's head weights\n *\n * @example\n * ```ts\n * readFitWeights(new Float64Array(setup.results), 0, setup).mean.length === setup.columns // true\n * ```\n */\nexport function readFitWeights(results: Float64Array, job: number, setup: FitSetup): HeadWeights {\n\tconst { columns, stride } = setup\n\tconst start = job * stride\n\treturn buildHeadWeights(\n\t\tresults.subarray(start + 2 * columns, start + stride),\n\t\t{\n\t\t\tmean: results.subarray(start, start + columns),\n\t\t\tscale: results.subarray(start + columns, start + 2 * columns),\n\t\t},\n\t\tsetup.classes,\n\t)\n}\n\n/**\n * Computes a head's logits over feature rows, before calibration, as `@orkestrel/infer`'s head computes them.\n *\n * @remarks\n * Each feature element is standardized as `(value - mean) / scale` in double precision, and each\n * label's logit starts at its bias and adds its weights times the standardized elements in order.\n *\n * @param weights - The head's weights\n * @param rows - The feature rows\n * @returns The logits, row by row\n *\n * @example\n * ```ts\n * computeHeadLogits(weights, [feature]).length === weights.bias.length // true\n * ```\n */\nexport function computeHeadLogits(\n\tweights: HeadWeights,\n\trows: readonly Float32Array[],\n): Float64Array {\n\tconst { matrix, bias, mean, scale } = weights\n\tconst classes = bias.length\n\tconst width = mean.length\n\tconst logits = new Float64Array(rows.length * classes)\n\tfor (let row = 0; row < rows.length; row += 1) {\n\t\tconst standard = Array.from(\n\t\t\trows[row] ?? [],\n\t\t\t(value, column) => (value - (mean[column] ?? 0)) / (scale[column] ?? 1),\n\t\t)\n\t\tfor (let label = 0; label < classes; label += 1) {\n\t\t\tlet sum = bias[label] ?? 0\n\t\t\tfor (let column = 0; column < width; column += 1) {\n\t\t\t\tsum += (matrix[label * width + column] ?? 0) * (standard[column] ?? 0)\n\t\t\t}\n\t\t\tlogits[row * classes + label] = sum\n\t\t}\n\t}\n\treturn logits\n}\n\n/**\n * Computes the calibrated distribution of each row's logits, as `@orkestrel/infer`'s head computes it.\n *\n * @remarks\n * Each logit is divided by the temperature and shifted by its label's bias, and the softmax\n * subtracts the row's peak. If `strict` is `true`, it exponentiates through `@orkestrel/infer`'s `exponentiate`;\n * if `false`, through `Math.exp`.\n *\n * @param logits - The logits, row by row\n * @param classes - The number of labels\n * @param calibration - The temperature and per-label bias\n * @param strict - If `true`, the arithmetic exponential; if `false`, the host's\n * @returns The probabilities, row by row\n *\n * @example\n * ```ts\n * computeDistributions(Float64Array.of(0, 0), 2, { temperature: 1, bias: [0, 0] }, false) // [0.5, 0.5]\n * ```\n */\nexport function computeDistributions(\n\tlogits: Float64Array,\n\tclasses: number,\n\tcalibration: Calibration,\n\tstrict: boolean,\n): Float64Array {\n\tconst rows = Math.floor(logits.length / classes)\n\treturn Float64Array.from(\n\t\tArray.from({ length: rows }, (_, row) => {\n\t\t\tconst scaled = Array.from(\n\t\t\t\tlogits.subarray(row * classes, (row + 1) * classes),\n\t\t\t\t(logit, label) => logit / calibration.temperature + (calibration.bias[label] ?? 0),\n\t\t\t)\n\t\t\tconst peak = Math.max(...scaled)\n\t\t\tconst masses = scaled.map((value) =>\n\t\t\t\tstrict ? exponentiate(value - peak) : Math.exp(value - peak),\n\t\t\t)\n\t\t\tconst total = masses.reduce((sum, mass) => sum + mass, 0)\n\t\t\treturn masses.map((mass) => mass / total)\n\t\t}).flat(),\n\t)\n}\n\n/**\n * Pools the folds' per-row values over a list of rows, each read from the split that scored it.\n *\n * @remarks\n * Thrown with the `ARGUMENT` code when a listed row sits in no split's scored rows.\n *\n * @param splits - The splits, each with its scored rows\n * @param outcomes - Each split's values, `width` per scored row, in split order\n * @param rows - The rows to pool, in output order\n * @param width - The number of values per row\n * @returns The pooled values, row by row\n *\n * @example\n * ```ts\n * poolOutcomes([{ train: [1], test: [0] }, { train: [0], test: [1] }], [Float64Array.of(5), Float64Array.of(6)], [0, 1], 1)\n * // Float64Array [5, 6]\n * ```\n */\nexport function poolOutcomes(\n\tsplits: readonly FoldSplit[],\n\toutcomes: readonly Float64Array[],\n\trows: readonly number[],\n\twidth: number,\n): Float64Array {\n\tconst places = new Map(\n\t\tsplits.flatMap((split, index) =>\n\t\t\tsplit.test.map((row, place) => [row, { index, place }] as const),\n\t\t),\n\t)\n\treturn Float64Array.from({ length: rows.length * width }, (_, flat) => {\n\t\tconst row = rows[Math.floor(flat / width)] ?? -1\n\t\tconst entry = places.get(row)\n\t\tif (entry === undefined) {\n\t\t\tthrow new InferError(`Row ${row} sits in no fold's scored rows.`, {\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\tcontext: { row },\n\t\t\t})\n\t\t}\n\t\treturn outcomes[entry.index]?.[entry.place * width + (flat % width)] ?? Number.NaN\n\t})\n}\n\n/**\n * Extracts one column of row-by-row values.\n *\n * @param values - The values, row by row\n * @param width - The number of values per row\n * @param column - The column to extract\n * @returns The column's values, in row order\n *\n * @example\n * ```ts\n * extractScores(Float64Array.of(1, 2, 3, 4), 2, 1) // [2, 4]\n * ```\n */\nexport function extractScores(\n\tvalues: Float64Array,\n\twidth: number,\n\tcolumn: number,\n): readonly number[] {\n\treturn Array.from(\n\t\t{ length: Math.floor(values.length / width) },\n\t\t(_, row) => values[row * width + column] ?? Number.NaN,\n\t)\n}\n\n/**\n * Computes the ROC AUC of scores against positive marks: the chance a positive row outranks a\n * negative one, ties counted half.\n *\n * @remarks\n * Thrown with the `ARGUMENT` code when a score is not finite, the lists differ in length, or the\n * marks hold no positive or no negative row.\n *\n * @param scores - Each row's score\n * @param positive - Whether each row is positive\n * @returns The AUC, from 0 to 1\n *\n * @example\n * ```ts\n * computeAUC([0.1, 0.4, 0.35, 0.8], [false, false, true, true]) // 0.75\n * ```\n */\nexport function computeAUC(scores: readonly number[], positive: readonly boolean[]): number {\n\tif (scores.length !== positive.length || !scores.every((score) => Number.isFinite(score))) {\n\t\tthrow new InferError('An AUC reads one finite score per marked row.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { scores: scores.length, marks: positive.length },\n\t\t})\n\t}\n\tconst order = scores\n\t\t.map((_, row) => row)\n\t\t.toSorted((one, two) => (scores[one] ?? 0) - (scores[two] ?? 0))\n\tconst ends = order.flatMap((row, place) => {\n\t\tconst next = order[place + 1]\n\t\treturn next === undefined || scores[next] !== scores[row] ? [place + 1] : []\n\t})\n\tconst groups = ends.map((end, index) => {\n\t\tconst members = order.slice(ends[index - 1] ?? 0, end)\n\t\tconst positives = members.filter((row) => positive[row] === true).length\n\t\treturn { positives, negatives: members.length - positives }\n\t})\n\tconst positives = groups.reduce((total, group) => total + group.positives, 0)\n\tconst negatives = groups.reduce((total, group) => total + group.negatives, 0)\n\tif (positives === 0 || negatives === 0) {\n\t\tthrow new InferError(\n\t\t\t`An AUC needs positive and negative rows; these marks hold ${positives} and ${negatives}.`,\n\t\t\t{ code: 'ARGUMENT', context: { positives, negatives } },\n\t\t)\n\t}\n\tlet below = 0\n\tlet area = 0\n\tfor (let index = 0; index < groups.length; index += 1) {\n\t\tconst group = groups[index] ?? { positives: 0, negatives: 0 }\n\t\tarea += group.positives * (below + group.negatives / 2)\n\t\tbelow += group.negatives\n\t}\n\treturn area / (positives * negatives)\n}\n\n/**\n * Computes each label's label-against-rest AUC of row-by-row distributions.\n *\n * @param distributions - The probabilities, row by row\n * @param labels - Each row's label index\n * @param classes - The number of labels\n * @returns Each label's AUC, in label order\n *\n * @example\n * ```ts\n * computeLabelAUCs(Float64Array.of(0.9, 0.1, 0.2, 0.8), [0, 1], 2) // [1, 1]\n * ```\n */\nexport function computeLabelAUCs(\n\tdistributions: Float64Array,\n\tlabels: readonly number[],\n\tclasses: number,\n): readonly number[] {\n\treturn Array.from({ length: classes }, (_, label) =>\n\t\tcomputeAUC(\n\t\t\textractScores(distributions, classes, label),\n\t\t\tlabels.map((value) => value === label),\n\t\t),\n\t)\n}\n\n/**\n * Computes the share of rows whose most probable label is their own, the first label on a tie.\n *\n * @param distributions - The probabilities, row by row\n * @param labels - Each row's label index\n * @param classes - The number of labels\n * @returns The accuracy, from 0 to 1\n *\n * @example\n * ```ts\n * computeAccuracy(Float64Array.of(0.9, 0.1, 0.6, 0.4), [0, 1], 2) // 0.5\n * ```\n */\nexport function computeAccuracy(\n\tdistributions: Float64Array,\n\tlabels: readonly number[],\n\tclasses: number,\n): number {\n\tconst right = labels.filter((label, row) => {\n\t\tconst values = Array.from(distributions.subarray(row * classes, (row + 1) * classes))\n\t\tconst choice = values.reduce(\n\t\t\t(best, value, index) => (value > (values[best] ?? Number.NEGATIVE_INFINITY) ? index : best),\n\t\t\t0,\n\t\t)\n\t\treturn choice === label\n\t}).length\n\treturn right / labels.length\n}\n\n/**\n * Selects the L2 strength with the highest AUC, the stronger penalty on a tie.\n *\n * @remarks\n * Thrown with the `ARGUMENT` code when the readings are empty.\n *\n * @param selection - Each strength's reading\n * @returns The chosen strength\n *\n * @example\n * ```ts\n * selectPenalty([{ penalty: 0.01, auc: 0.9 }, { penalty: 0.1, auc: 0.9 }]) // 0.1\n * ```\n */\nexport function selectPenalty(selection: readonly TrainerSelection[]): number {\n\tconst [first, ...rest] = selection\n\tif (first === undefined) {\n\t\tthrow new InferError('A penalty choice reads at least one strength.', { code: 'ARGUMENT' })\n\t}\n\treturn rest.reduce(\n\t\t(best, entry) =>\n\t\t\tentry.auc > best.auc || (entry.auc === best.auc && entry.penalty > best.penalty)\n\t\t\t\t? entry\n\t\t\t\t: best,\n\t\tfirst,\n\t).penalty\n}\n\n/**\n * Builds an operating table: at each distinct score of a positive row, falling, the positive rows\n * and the negative rows that reach it.\n *\n * @remarks\n * Each point catches more positives than the one before, so the table lists every cutoff worth\n * choosing; a caller picks the cutoff its costs favor.\n *\n * @param scores - Each row's score\n * @param positive - Whether each row is positive\n * @returns The table, by falling cutoff\n *\n * @example\n * ```ts\n * buildOperatingTable([0.9, 0.8, 0.7, 0.6, 0.2], [true, false, true, false, false])\n * // [{ cutoff: 0.9, caught: 1, mistaken: 0 }, { cutoff: 0.7, caught: 2, mistaken: 1 }]\n * ```\n */\nexport function buildOperatingTable(\n\tscores: readonly number[],\n\tpositive: readonly boolean[],\n): readonly TrainerCut[] {\n\tconst cutoffs = [...new Set(scores.filter((_, row) => positive[row] === true))].toSorted(\n\t\t(one, two) => two - one,\n\t)\n\treturn cutoffs.map((cutoff) => ({\n\t\tcutoff,\n\t\tcaught: scores.filter((score, row) => score >= cutoff && positive[row] === true).length,\n\t\tmistaken: scores.filter((score, row) => score >= cutoff && positive[row] !== true).length,\n\t}))\n}\n\n/**\n * Computes the gradient of the calibration objective at its parameters.\n *\n * @remarks\n * Parameter 0 is the log temperature, and parameter `k` from 1 is label `k`'s bias; label 0's bias\n * stays 0, because the softmax ignores a shift common to every label. The objective is the mean\n * negative log likelihood of the rows' labels under `softmax(logit / temperature + bias)`, plus\n * `CALIBRATION_PRIOR / (2 * rows)` times the sum of the squared parameters.\n *\n * @param parameters - The log temperature, then each bias after label 0's\n * @param logits - The rows' logits, row by row\n * @param labels - Each row's label index\n * @param classes - The number of labels\n * @param strict - If `true`, uses `@orkestrel/infer`'s arithmetic `exponentiate`; if `false`, uses `Math.exp`\n * @returns The gradient, laid out as the parameters\n *\n * @example\n * ```ts\n * computeCalibrationGradient(new Float64Array(2), Float64Array.of(0, 0), [0], 2) // Float64Array [0, 0.5]\n * ```\n */\nexport function computeCalibrationGradient(\n\tparameters: Float64Array,\n\tlogits: Float64Array,\n\tlabels: readonly number[],\n\tclasses: number,\n\tstrict = false,\n): Float64Array {\n\tconst rows = labels.length\n\tconst logTemperature = parameters[0] ?? 0\n\tconst temperature = strict ? exponentiate(logTemperature) : Math.exp(logTemperature)\n\tconst scaled = Float64Array.from(logits, (logit, index) => {\n\t\tconst label = index % classes\n\t\treturn logit / temperature + (label === 0 ? 0 : (parameters[label] ?? 0))\n\t})\n\tconst residuals = new Float64Array(rows * classes)\n\tfor (let row = 0; row < rows; row += 1) {\n\t\tlet peak = Number.NEGATIVE_INFINITY\n\t\tfor (let label = 0; label < classes; label += 1) {\n\t\t\tpeak = Math.max(peak, scaled[row * classes + label] ?? 0)\n\t\t}\n\t\tlet mass = 0\n\t\tfor (let label = 0; label < classes; label += 1) {\n\t\t\tconst shifted = (scaled[row * classes + label] ?? 0) - peak\n\t\t\tmass += strict ? exponentiate(shifted) : Math.exp(shifted)\n\t\t}\n\t\tfor (let label = 0; label < classes; label += 1) {\n\t\t\tconst shifted = (scaled[row * classes + label] ?? 0) - peak\n\t\t\tconst weight = strict ? exponentiate(shifted) : Math.exp(shifted)\n\t\t\tresiduals[row * classes + label] = weight / mass - (labels[row] === label ? 1 : 0)\n\t\t}\n\t}\n\treturn Float64Array.from({ length: classes }, (_, parameter) => {\n\t\tconst prior = (CALIBRATION_PRIOR * (parameters[parameter] ?? 0)) / rows\n\t\tif (parameter === 0) {\n\t\t\tlet slope = 0\n\t\t\tfor (let index = 0; index < residuals.length; index += 1) {\n\t\t\t\tslope += (residuals[index] ?? 0) * (-(logits[index] ?? 0) / temperature)\n\t\t\t}\n\t\t\treturn slope / rows + prior\n\t\t}\n\t\tlet sum = 0\n\t\tfor (let row = 0; row < rows; row += 1) sum += residuals[row * classes + parameter] ?? 0\n\t\treturn sum / rows + prior\n\t})\n}\n\n/**\n * Fits a temperature and per-label biases to rows' logits and labels.\n *\n * @remarks\n * Runs `CALIBRATION_STEPS` Adam steps at `CALIBRATION_RATE` from a temperature of 1 and zero biases\n * on the objective `computeCalibrationGradient` states. The rows are the held rows a head's fit never\n * read. Label 0's bias is 0. When `strict` is `true`, every exponential runs through\n * `@orkestrel/infer`'s `exponentiate` so calibrated head files stay bit-equal across Node and\n * Chromium.\n *\n * @param logits - The rows' logits, row by row\n * @param labels - Each row's label index\n * @param classes - The number of labels\n * @param strict - If `true`, uses `@orkestrel/infer`'s arithmetic `exponentiate`; if `false`, uses `Math.exp`\n * @returns The calibration\n *\n * @example\n * ```ts\n * fitCalibration(heldLogits, heldLabels, 2).temperature // 1.6\n * ```\n */\nexport function fitCalibration(\n\tlogits: Float64Array,\n\tlabels: readonly number[],\n\tclasses: number,\n\tstrict = false,\n): Calibration {\n\tconst initial: AdamState = {\n\t\tmodel: new Float64Array(classes),\n\t\tfirst: new Float64Array(classes),\n\t\tsecond: new Float64Array(classes),\n\t}\n\tconst fitted = Array.from({ length: CALIBRATION_STEPS }, (_, index) => index + 1).reduce(\n\t\t(state, step) =>\n\t\t\tstepAdam(\n\t\t\t\tstate,\n\t\t\t\tcomputeCalibrationGradient(state.model, logits, labels, classes, strict),\n\t\t\t\tstep,\n\t\t\t\tCALIBRATION_RATE,\n\t\t\t),\n\t\tinitial,\n\t)\n\tconst logTemperature = fitted.model[0] ?? 0\n\treturn {\n\t\ttemperature: strict ? exponentiate(logTemperature) : Math.exp(logTemperature),\n\t\tbias: Array.from({ length: classes }, (_, label) =>\n\t\t\tlabel === 0 ? 0 : (fitted.model[label] ?? 0),\n\t\t),\n\t}\n}\n\n/**\n * Computes the digest of a list of rows: the SHA-256 of one JSON line per row, `[state, label]`\n * when `group` is absent and `[state, label, group]` when present, joined by line feeds.\n *\n * @remarks\n * The order of the rows is part of the digest, because it fixes the folds. Ungrouped datasets encode\n * identically to `[state, label]`. Rejects as `@orkestrel/infer`'s `digestBytes` states.\n *\n * @param rows - The rows\n * @returns The digest\n *\n * @example\n * ```ts\n * await computeDatasetDigest([{ state: 'user: hi', label: 'chatter' }]) // 64 hexadecimal characters\n * ```\n */\nexport async function computeDatasetDigest(rows: readonly TrainerRow[]): Promise<Digest> {\n\treturn digestBytes(\n\t\tUTF8_ENCODER.encode(\n\t\t\trows\n\t\t\t\t.map((row) =>\n\t\t\t\t\trow.group === undefined\n\t\t\t\t\t\t? JSON.stringify([row.state, row.label])\n\t\t\t\t\t\t: JSON.stringify([row.state, row.label, row.group]),\n\t\t\t\t)\n\t\t\t\t.join('\\n'),\n\t\t),\n\t)\n}\n\n/**\n * Computes a head file's name: its SHA-256 digest, which `@orkestrel/infer`'s `HeadInterface.digest` reports,\n * followed by `HEAD_FILE_EXTENSION`.\n *\n * @remarks\n * Rejects as `@orkestrel/infer`'s `digestBytes` states.\n *\n * @param bytes - The head file's bytes\n * @returns The name\n *\n * @example\n * ```ts\n * await computeHeadName(result.bytes) // '3f2a…9c.gguf'\n * ```\n */\nexport async function computeHeadName(bytes: Uint8Array<ArrayBuffer>): Promise<string> {\n\treturn `${await digestBytes(bytes)}${HEAD_FILE_EXTENSION}`\n}\n\n/**\n * Reads training rows from NDJSON text chunks, each line one row.\n *\n * @remarks\n * Feeds every chunk to a strict `@orkestrel/ndjson` parser, which reassembles a line split across\n * chunks, skips blank lines, and reads a last line that has no line feed. A line that is not a JSON\n * object rejects with the parser's `NDJSONError`. A record that fails `isTrainerRow` rejects with\n * the `FORMAT` code naming its place among the records and its faults. The signal is checked before\n * each chunk; on abort it rejects with the `ABORT` code.\n *\n * @param chunks - The text, in chunks\n * @param signal - Cancels the read\n * @returns The rows, in line order\n *\n * @example\n * ```ts\n * await readTrainerRows(['{\"state\":\"user: hi\",\"label\":\"chatter\"}\\n']) // [{ state: 'user: hi', label: 'chatter' }]\n * ```\n */\nexport async function readTrainerRows(\n\tchunks: AsyncIterable<string> | Iterable<string>,\n\tsignal?: AbortSignal,\n): Promise<readonly TrainerRow[]> {\n\tcheckSignal(signal, 'The row read')\n\tconst parser = createNDJSONParser()\n\tconst batches: Array<ReadonlyArray<Record<string, unknown>>> = []\n\tfor await (const chunk of chunks) {\n\t\tcheckSignal(signal, 'The row read')\n\t\tbatches.push(parser.parse(chunk))\n\t}\n\tconst records = [...batches.flat(), ...parser.parse('\\n')]\n\treturn records.map((record, index) => {\n\t\tif (isTrainerRow(record)) {\n\t\t\treturn record.group === undefined\n\t\t\t\t? { state: record.state, label: record.label }\n\t\t\t\t: { state: record.state, label: record.label, group: record.group }\n\t\t}\n\t\tthrow new InferError(renderRowRefusal(record, `Record ${index + 1}`), {\n\t\t\tcode: 'FORMAT',\n\t\t\tcontext: { record: index + 1 },\n\t\t})\n\t})\n}\n\n/**\n * Reads training rows from CSV text through `@orkestrel/csv`, validating every row against\n * `isTrainerRow`.\n *\n * @remarks\n * Parses with `header: true`, `blanks: false`, `ragged: 'error'`, and `strict: true`, admitting\n * `(state, label)` or `(state, label, group)` headers by default, or custom header mappings through\n * `options.columns`. An empty `group` cell omits `group` on that row so mixed grouped and ungrouped\n * CSVs produce valid `TrainerRow` values. Throws `InferError` with code `ARGUMENT` for invalid\n * arguments, column mappings, or delimiters, and code `FORMAT` for malformed CSV syntax, missing\n * required headers, unexpected default columns, or rows failing `isTrainerRow`.\n *\n * @param text - The UTF-8 CSV text (leading BOM optional)\n * @param options - Optional column mapping and field delimiter\n * @returns The validated rows, in source order\n *\n * @example\n * ```ts\n * readTrainerCSV('state,label\\n\"user: hi\",chatter\\n') // [{ state: 'user: hi', label: 'chatter' }]\n * ```\n */\nexport function readTrainerCSV(text: string, options?: TrainerCSVOptions): readonly TrainerRow[] {\n\tif (!isString(text)) {\n\t\tthrow new InferError('The CSV input must be a string.', { code: 'ARGUMENT' })\n\t}\n\tif (options !== undefined && !isRecord(options)) {\n\t\tthrow new InferError('The CSV options must be a plain object.', { code: 'ARGUMENT' })\n\t}\n\tconst columnsOption = options?.columns\n\tif (columnsOption !== undefined) {\n\t\tif (!isRecord(columnsOption)) {\n\t\t\tthrow new InferError('The CSV columns mapping must be a plain object.', { code: 'ARGUMENT' })\n\t\t}\n\t\tconst allowedKeys = ['state', 'label', 'group']\n\t\tconst extraKeys = Object.keys(columnsOption).filter((key) => !allowedKeys.includes(key))\n\t\tif (extraKeys.length > 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The CSV columns mapping carries unsupported keys: ${extraKeys.map(quoteFaultText).join(', ')}.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { keys: extraKeys } },\n\t\t\t)\n\t\t}\n\t\tfor (const key of allowedKeys) {\n\t\t\tif (Object.hasOwn(columnsOption, key)) {\n\t\t\t\tconst mapped = columnsOption[key]\n\t\t\t\tif (!isString(mapped) || mapped.length === 0) {\n\t\t\t\t\tthrow new InferError(`The CSV ${key} column mapping must be a non-empty string.`, {\n\t\t\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\t\t\tcontext: { key },\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tconst stateColumn = isString(columnsOption?.state) ? columnsOption.state : 'state'\n\tconst labelColumn = isString(columnsOption?.label) ? columnsOption.label : 'label'\n\tconst explicitGroup = isString(columnsOption?.group) ? columnsOption.group : undefined\n\tif (\n\t\tstateColumn === labelColumn ||\n\t\t(explicitGroup !== undefined &&\n\t\t\t(explicitGroup === stateColumn || explicitGroup === labelColumn))\n\t) {\n\t\tthrow new InferError('The CSV column mappings for state, label, and group must be distinct.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: {\n\t\t\t\tstate: stateColumn,\n\t\t\t\tlabel: labelColumn,\n\t\t\t\t...(explicitGroup === undefined ? {} : { group: explicitGroup }),\n\t\t\t},\n\t\t})\n\t}\n\tconst delimiter = options?.delimiter\n\tif (delimiter !== undefined && !isString(delimiter)) {\n\t\tthrow new InferError('The CSV delimiter must be a single-character string.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tconst parseOptions: ParseOptions = {\n\t\theader: true,\n\t\tblanks: false,\n\t\tragged: 'error',\n\t\tstrict: true,\n\t\t...(delimiter === undefined ? {} : { delimiter }),\n\t}\n\tconst parsedOutcome = attempt<CSVParseResult>(() => parseCSV(text, parseOptions))\n\tif (!parsedOutcome.success) {\n\t\tconst caught = parsedOutcome.error\n\t\tif (isCSVError(caught)) {\n\t\t\tthrow new InferError(caught.message, {\n\t\t\t\tcode: caught.code === 'INVALID_OPTION' ? 'ARGUMENT' : 'FORMAT',\n\t\t\t\tcause: caught,\n\t\t\t\tcontext: {\n\t\t\t\t\tcode: caught.code,\n\t\t\t\t\t...(caught.line === undefined ? {} : { line: caught.line }),\n\t\t\t\t\t...(caught.column === undefined ? {} : { column: caught.column }),\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t\tthrow caught\n\t}\n\tconst { columns, rows } = parsedOutcome.value.table\n\tif (columns.length === 0 && rows.length === 0) return []\n\tconst requiredColumns =\n\t\texplicitGroup === undefined\n\t\t\t? [stateColumn, labelColumn]\n\t\t\t: [stateColumn, labelColumn, explicitGroup]\n\tconst missingColumns = requiredColumns.filter((column) => !columns.includes(column))\n\tif (missingColumns.length > 0) {\n\t\tthrow new InferError(\n\t\t\t`The CSV header lacks required column ${missingColumns.map(quoteFaultText).join(', ')}.`,\n\t\t\t{ code: 'FORMAT', context: { missing: missingColumns } },\n\t\t)\n\t}\n\tconst groupColumn =\n\t\texplicitGroup ??\n\t\t(stateColumn !== 'group' && labelColumn !== 'group' && columns.includes('group')\n\t\t\t? 'group'\n\t\t\t: undefined)\n\tif (columnsOption === undefined) {\n\t\tconst admitted =\n\t\t\tgroupColumn === undefined\n\t\t\t\t? [stateColumn, labelColumn]\n\t\t\t\t: [stateColumn, labelColumn, groupColumn]\n\t\tconst unexpected = columns.filter((column) => !admitted.includes(column))\n\t\tif (unexpected.length > 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The CSV header carries unsupported column ${unexpected.map(quoteFaultText).join(', ')}.`,\n\t\t\t\t{ code: 'FORMAT', context: { columns: unexpected } },\n\t\t\t)\n\t\t}\n\t}\n\treturn rows.map((record, index) => {\n\t\tconst stateValue = record[stateColumn]\n\t\tconst labelValue = record[labelColumn]\n\t\tconst groupValue = groupColumn === undefined ? undefined : record[groupColumn]\n\t\tconst candidate =\n\t\t\tgroupColumn === undefined || groupValue === ''\n\t\t\t\t? { state: stateValue, label: labelValue }\n\t\t\t\t: { state: stateValue, label: labelValue, group: groupValue }\n\t\tif (isTrainerRow(candidate)) {\n\t\t\treturn candidate.group === undefined\n\t\t\t\t? { state: candidate.state, label: candidate.label }\n\t\t\t\t: { state: candidate.state, label: candidate.label, group: candidate.group }\n\t\t}\n\t\tthrow new InferError(renderRowRefusal(candidate, `Row ${index + 1}`), {\n\t\t\tcode: 'FORMAT',\n\t\t\tcontext: { row: index + 1 },\n\t\t})\n\t})\n}\n\n/**\n * Infers the training label a judge answer reads: the one candidate that holds the greatest\n * probability, as the `measureAnswer` function of `@orkestrel/agent` names its winner.\n *\n * @remarks\n * A choice reads its option name, a score its level index as text, and a noul `'true'` or `'false'`,\n * the candidate keys `collectQuestionKeys` lists. When more than one candidate holds the greatest\n * probability, such as a noul of exactly 0.5, or no candidate holds it, as with a `NaN`, it returns\n * `undefined` rather than the first candidate, because a stored choice keeps the key order its store\n * returned. Thrown as a `JudgeError` with the `PROTOCOL` code, by `measureAnswer`, when a choice or\n * score holds fewer than 2 candidates.\n *\n * @param answer - The answer whose distribution is read\n * @returns The label, or undefined when no single candidate holds the greatest probability\n *\n * @example\n * ```ts\n * inferAnswerLabel({ form: 'choice', probabilities: { refund: 0.7, chatter: 0.2, fact: 0.1 } }) // 'refund'\n * inferAnswerLabel({ form: 'score', probabilities: [0.1, 0.6, 0.3] }) // '1'\n * inferAnswerLabel({ form: 'noul', noul: 0.5 }) // undefined\n * ```\n */\nexport function inferAnswerLabel(answer: JudgeAnswer): string | undefined {\n\tconst candidates =\n\t\tanswer.form === 'noul' ? [answer.noul, 1 - answer.noul] : Object.values(answer.probabilities)\n\tconst peak = Math.max(...candidates)\n\tif (candidates.filter((value) => value === peak).length !== 1) return undefined\n\treturn measureAnswer(answer).winner\n}\n\n/**\n * Collects training rows from recorded judgments of one question, so a head trains on what a\n * conversation's judge recorded and on the corrections recorded beside it.\n *\n * @remarks\n * Keeps each record whose question equals `options.question` as a JSON value, through the\n * `matchesJSON` function of `@orkestrel/agent`, and that `options.filter` keeps. A kept record with\n * an answer becomes the row `{ state, label }`: its rendered `state`, the text the judge read, and\n * the label `inferAnswerLabel` reads. A kept record with no answer is counted in `refusals`, and one whose\n * answer names no single candidate in `ties`; neither becomes a row. Pass a snapshot's\n * `judgments ?? []`, or the `judgments()` list of a conversation's store. Thrown with the `ARGUMENT`\n * code when the question fails `isJudgeQuestion` or the filter is given and is not a function, and,\n * naming the record's index and id, when a kept answer fails `scanJudgmentTies` against the question,\n * such as an answer of another form.\n *\n * @param judgments - The recorded judgments, in the order the rows take\n * @param options - The question and the filter\n * @returns The rows, the refusal count, and the tie count\n *\n * @example\n * ```ts\n * const { rows, refusals } = collectJudgmentRows(conversation.judgments.judgments(), { question: refund })\n * rows[0] // { state: 'user: refund me', label: 'true' }\n * ```\n */\nexport function collectJudgmentRows(\n\tjudgments: readonly Judgment[],\n\toptions: JudgmentRowOptions,\n): JudgmentRowResult {\n\tconst { question, filter } = options\n\tif (!isJudgeQuestion(question)) {\n\t\tthrow new InferError(\n\t\t\t'The judgment question is not a judge question: pass the choice, score, or noul the records answer, as @orkestrel/agent defines them.',\n\t\t\t{ code: 'ARGUMENT' },\n\t\t)\n\t}\n\tif (filter !== undefined && typeof filter !== 'function') {\n\t\tthrow new InferError(\n\t\t\t\"The judgment filter is a function that keeps a record when it returns true, such as (judgment) => judgment.model === 'reviewer'.\",\n\t\t\t{ code: 'ARGUMENT' },\n\t\t)\n\t}\n\tconst kept = judgments.flatMap((judgment, index) =>\n\t\tmatchesJSON(judgment.question, question) && (filter === undefined || filter(judgment) === true)\n\t\t\t? [{ index, id: judgment.id, answer: judgment.answer, state: judgment.state }]\n\t\t\t: [],\n\t)\n\tconst readings = kept.flatMap(({ index, id, answer, state }) => {\n\t\tif (answer === undefined) return []\n\t\tconst faults = scanJudgmentTies(question, answer)\n\t\tif (faults.length > 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The judgment at index ${index}, ${quoteFaultText(id)}, holds an answer that does not fit its ${question.form} question (${describeFaults(faults)}); an answer holds the question's form, a probability in [0, 1] for each candidate, a choice's criteria keys, and a score's levels.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { judgment: index, faults } },\n\t\t\t)\n\t\t}\n\t\treturn [{ state, label: inferAnswerLabel(answer) }]\n\t})\n\tconst rows = readings.flatMap(({ state, label }) =>\n\t\tlabel === undefined ? [] : [{ state, label }],\n\t)\n\treturn { rows, refusals: kept.length - readings.length, ties: readings.length - rows.length }\n}\n\n/**\n * Traces a mean-pooled decision head across every causal prefix of a state, reconstructing each\n * token's normalized vector in double precision and projecting its additive share onto each label's\n * logit.\n *\n * @remarks\n * Tokenizes `state`, checks `1 <= tokens.length <= backbone.limit`, reads all causal prefix\n * embeddings in one `O(L)` forward through `backbone.prefixes(tokens, { depth: record.depth, signal })`\n * when available (falling back to per-prefix `backbone.embed` on custom backbones that omit\n * `prefixes`), reconstructs `u_0 = e_1` and `u_t = (t + 1) * e_{t + 1} - t * e_t` in `Float64`, and\n * projects each token's share\n * `s_{t,k} = (1 / L) * sum_c (matrix[k * D + c] / scale[c]) * (u_t[c] - mean[c])`. For every label\n * `k`, `weights.bias[k] + sum_t s_{t,k}` equals `logits[k]`, and `probabilities` matches\n * `Head.predict(embedding)`. Rejects with the `BINDING` code when `record.base` differs from\n * `backbone.digest`, the `ABORT` code when `signal` aborts, and the `ARGUMENT` code for invalid\n * depth, pooling, weight shapes, calibration, or token count.\n *\n * @param options - The backbone, head record, head weights, state text, and optional abort signal\n * @returns Each token's attribution, the full embedding, the logits, and calibrated probabilities\n *\n * @example\n * ```ts\n * const trace = await traceHead({ backbone, record, weights, state: 'user: refund me' })\n * trace.tokens.length // 15\n * ```\n */\nexport async function traceHead(options: HeadTraceOptions): Promise<HeadTraceResult> {\n\tconst { backbone, record, weights, state, signal } = options\n\tcheckSignal(signal, 'The head trace')\n\tif (record.base !== backbone.digest) {\n\t\tthrow new InferError(\n\t\t\t`The head binds base ${quoteFaultText(record.base)}, not backbone ${quoteFaultText(backbone.digest)}.`,\n\t\t\t{ code: 'BINDING', context: { expected: record.base, actual: backbone.digest } },\n\t\t)\n\t}\n\tif (record.pooling !== 'mean') {\n\t\tthrow new InferError(\n\t\t\t`The head pooling is ${quoteFaultText(record.pooling)}; tracing requires mean pooling.`,\n\t\t\t{ code: 'ARGUMENT', context: { pooling: record.pooling } },\n\t\t)\n\t}\n\tconst { dimension, layers } = backbone.architecture\n\tif (!matchesCount(record.depth, 1) || record.depth > layers) {\n\t\tthrow new InferError(\n\t\t\t`The head depth is ${record.depth}; the backbone embeds at an integer depth from 1 to ${layers}.`,\n\t\t\t{ code: 'ARGUMENT', context: { depth: record.depth, layers } },\n\t\t)\n\t}\n\tconst classes = record.labels.length\n\tif (classes < 2) {\n\t\tthrow new InferError(`The head lists ${classes} labels; a head distributes over at least 2.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { labels: classes },\n\t\t})\n\t}\n\tcheckHeadWeights(weights, classes)\n\tconst { matrix, mean, scale } = weights\n\tif (mean.length !== dimension) {\n\t\tthrow new InferError(\n\t\t\t`The head weights have width ${mean.length}; the backbone embeds width ${dimension}.`,\n\t\t\t{ code: 'ARGUMENT', context: { classes, dimension, width: mean.length } },\n\t\t)\n\t}\n\tif (\n\t\t!Number.isFinite(record.calibration.temperature) ||\n\t\trecord.calibration.temperature <= 0 ||\n\t\trecord.calibration.bias.length !== classes ||\n\t\t!record.calibration.bias.every(Number.isFinite)\n\t) {\n\t\tthrow new InferError(\n\t\t\t`The head calibration requires a positive finite temperature and ${classes} finite label biases.`,\n\t\t\t{ code: 'ARGUMENT', context: { classes } },\n\t\t)\n\t}\n\tif (!matchesTokenBound(backbone.tokenizer, state, backbone.limit)) {\n\t\tthrow new InferError(\n\t\t\t`The state holds more UTF-8 bytes than ${backbone.limit} tokens of at most ${backbone.tokenizer.span} bytes can cover; the backbone embeds a state of 1 to ${backbone.limit} tokens.`,\n\t\t\t{ code: 'ARGUMENT', context: { limit: backbone.limit, span: backbone.tokenizer.span } },\n\t\t)\n\t}\n\tconst tokenIds = backbone.tokenizer.encode(state)\n\tconst length = tokenIds.length\n\tif (length === 0 || length > backbone.limit) {\n\t\tthrow new InferError(\n\t\t\t`The state encodes to ${length} tokens; the backbone embeds a state of 1 to ${backbone.limit} tokens.`,\n\t\t\t{ code: 'ARGUMENT', context: { tokens: length, limit: backbone.limit } },\n\t\t)\n\t}\n\tconst prefixes: Float32Array[] = []\n\tif (typeof backbone.prefixes === 'function') {\n\t\tcheckSignal(signal, 'The head trace')\n\t\tconst packed = await backbone.prefixes(Uint32Array.from(tokenIds), {\n\t\t\tdepth: record.depth,\n\t\t\t...(signal === undefined ? {} : { signal }),\n\t\t})\n\t\tconst expected = length * dimension\n\t\tif (packed.length !== expected) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The backbone prefixes returned ${packed.length} feature values for ${length} tokens; expected ${expected}.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { tokens: length, dimension, actual: packed.length } },\n\t\t\t)\n\t\t}\n\t\tfor (let position = 0; position < length; position += 1) {\n\t\t\tprefixes.push(packed.subarray(position * dimension, (position + 1) * dimension))\n\t\t}\n\t} else {\n\t\tfor (let end = 1; end <= length; end += 1) {\n\t\t\tcheckSignal(signal, 'The head trace')\n\t\t\tconst prefix = await backbone.embed(tokenIds.slice(0, end), record.depth, signal)\n\t\t\tif (prefix.length !== dimension) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The backbone returned ${prefix.length} feature values for prefix length ${end}; expected ${dimension}.`,\n\t\t\t\t\t{ code: 'ARGUMENT', context: { prefix: end, dimension, actual: prefix.length } },\n\t\t\t\t)\n\t\t\t}\n\t\t\tprefixes.push(prefix)\n\t\t}\n\t}\n\tconst tokens: readonly HeadTraceToken[] = tokenIds.map((token, position) => {\n\t\tconst current = prefixes[position] ?? new Float32Array(dimension)\n\t\tconst previous = position > 0 ? prefixes[position - 1] : undefined\n\t\tconst vector = new Float64Array(dimension)\n\t\tfor (let column = 0; column < dimension; column += 1) {\n\t\t\tvector[column] =\n\t\t\t\tposition === 0\n\t\t\t\t\t? (current[column] ?? 0)\n\t\t\t\t\t: (position + 1) * (current[column] ?? 0) - position * (previous?.[column] ?? 0)\n\t\t}\n\t\tconst shares = new Float64Array(classes)\n\t\tfor (let label = 0; label < classes; label += 1) {\n\t\t\tlet sum = 0\n\t\t\tfor (let column = 0; column < dimension; column += 1) {\n\t\t\t\tsum +=\n\t\t\t\t\t((matrix[label * dimension + column] ?? 0) / (scale[column] ?? 1)) *\n\t\t\t\t\t((vector[column] ?? 0) - (mean[column] ?? 0))\n\t\t\t}\n\t\t\tshares[label] = sum / length\n\t\t}\n\t\treturn { token, text: backbone.tokenizer.decode([token]), vector, shares }\n\t})\n\tconst embedding = Float32Array.from(prefixes[length - 1] ?? new Float32Array(dimension))\n\tconst logits = computeHeadLogits(weights, [embedding])\n\tconst probabilities = Array.from(\n\t\tcomputeDistributions(logits, classes, record.calibration, backbone.strict),\n\t)\n\treturn { labels: [...record.labels], tokens, embedding, logits, probabilities }\n}\n\n/**\n * Counts labelled prediction flips between baseline and candidate outputs and computes the 95%\n * one-sided upper bound on the negative flip rate.\n *\n * @remarks\n * Partitions every index into `kept` (right to right), `negative` (right to wrong), `positive`\n * (wrong to right), and `wrong` (wrong to wrong), and records every index where `before` differs\n * from `after` in `changed`. When `negative` is 0, `bound` uses the rule of three\n * (`Math.min(1, 3 / total)`); when `negative` is positive, `bound` uses the 95% one-sided Wilson\n * score upper bound (`z = 1.6448536269514722`). Thrown with the `ARGUMENT` code when `expected` is\n * empty or the three lists differ in length.\n *\n * @typeParam T - The label value type compared with strict equality\n * @param options - The expected labels, baseline predictions, and candidate predictions\n * @returns The partition counts, negative flip rate, 95% upper bound, and exact row indexes\n *\n * @example\n * ```ts\n * countFlips({ expected: ['a', 'b'], before: ['a', 'a'], after: ['a', 'b'] }).positive // 1\n * ```\n */\nexport function countFlips<T = string>(options: FlipCountOptions<T>): FlipCountResult {\n\tconst { expected, before, after } = options\n\tconst total = expected.length\n\tif (total === 0 || before.length !== total || after.length !== total) {\n\t\tthrow new InferError(\n\t\t\t`The flip comparison received ${total} expected, ${before.length} baseline, and ${after.length} candidate entries; pass three non-empty arrays of one length.`,\n\t\t\t{\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\tcontext: { expected: total, before: before.length, after: after.length },\n\t\t\t},\n\t\t)\n\t}\n\tconst kept = expected.flatMap((value, index) =>\n\t\tbefore[index] === value && after[index] === value ? [index] : [],\n\t)\n\tconst negative = expected.flatMap((value, index) =>\n\t\tbefore[index] === value && after[index] !== value ? [index] : [],\n\t)\n\tconst positive = expected.flatMap((value, index) =>\n\t\tbefore[index] !== value && after[index] === value ? [index] : [],\n\t)\n\tconst wrong = expected.flatMap((value, index) =>\n\t\tbefore[index] !== value && after[index] !== value ? [index] : [],\n\t)\n\tconst changed = before.flatMap((value, index) => (value === after[index] ? [] : [index]))\n\tconst rate = negative.length / total\n\tconst z = 1.6448536269514722\n\tconst z2 = z * z\n\tconst bound =\n\t\tnegative.length === 0\n\t\t\t? Math.min(1, 3 / total)\n\t\t\t: Math.min(\n\t\t\t\t\t1,\n\t\t\t\t\t(rate +\n\t\t\t\t\t\tz2 / (2 * total) +\n\t\t\t\t\t\tz * Math.sqrt((rate * (1 - rate)) / total + z2 / (4 * total * total))) /\n\t\t\t\t\t\t(1 + z2 / total),\n\t\t\t\t)\n\treturn {\n\t\ttotal,\n\t\tkept: kept.length,\n\t\tnegative: negative.length,\n\t\tpositive: positive.length,\n\t\twrong: wrong.length,\n\t\tchanged: changed.length,\n\t\trate,\n\t\tbound,\n\t\tindexes: { kept, negative, positive, wrong, changed },\n\t}\n}\n\n/**\n * Counts label-free decision shifts between baseline and candidate outputs and lists each shifted\n * row index, optionally recording the compared precision formats (`'BF16'`, `'Q8_0'`, `'Q4_K_M'`).\n *\n * @remarks\n * Intended for comparing full and compressed model decisions without requiring ground-truth labels.\n * Thrown with the `ARGUMENT` code when `before` is empty, differs in length from `after`, or\n * `formats` carries an unsupported precision format.\n *\n * @typeParam T - The decision value type compared with strict equality\n * @param options - The baseline and candidate predictions and optional precision formats\n * @returns The total, unchanged, and changed counts, the change rate, shifted row indexes, and optional formats\n *\n * @example\n * ```ts\n * countChanges({ before: ['admit', 'refuse'], after: ['admit', 'admit'] }).indexes // [1]\n * ```\n */\nexport function countChanges<T = string>(options: ChangeCountOptions<T>): ChangeCountResult {\n\tconst { before, after, formats } = options\n\tconst total = before.length\n\tif (total === 0 || after.length !== total) {\n\t\tthrow new InferError(\n\t\t\t`The change comparison received ${total} baseline and ${after.length} candidate entries; pass two non-empty arrays of one length.`,\n\t\t\t{ code: 'ARGUMENT', context: { before: total, after: after.length } },\n\t\t)\n\t}\n\tif (formats !== undefined) {\n\t\tif (\n\t\t\t!isRecord(formats) ||\n\t\t\t!isPrecisionFormat(formats.before) ||\n\t\t\t!isPrecisionFormat(formats.after)\n\t\t) {\n\t\t\tthrow new InferError(\n\t\t\t\t'The change comparison formats must name \"BF16\", \"Q8_0\", or \"Q4_K_M\" for both before and after.',\n\t\t\t\t{ code: 'ARGUMENT' },\n\t\t\t)\n\t\t}\n\t}\n\tconst indexes = before.flatMap((value, index) => (value === after[index] ? [] : [index]))\n\tconst changed = indexes.length\n\treturn {\n\t\ttotal,\n\t\tunchanged: total - changed,\n\t\tchanged,\n\t\trate: changed / total,\n\t\tindexes,\n\t\t...(formats === undefined ? {} : { formats: { before: formats.before, after: formats.after } }),\n\t}\n}\n\n/**\n * Compares full-vs-compressed outputs across `'BF16'`, `'Q8_0'`, and `'Q4_K_M'` formats before and\n * optionally after adaptation using `countChanges` and optional `countFlips`.\n *\n * @remarks\n * Validates `reference` (default `'BF16'`) and every supplied format key against\n * `isPrecisionFormat`, verifies matching non-empty row lengths across all supplied arrays, and\n * emits per-format shift and optional flip entries in `PRECISION_FORMATS` order. Thrown with the\n * `ARGUMENT` code when `base` omits the reference format, carries unknown formats, has mismatched\n * lengths, or supplies nothing to compare.\n *\n * @typeParam T - The decision value type compared with strict equality\n * @param options - The reference format, baseline format outputs, optional adapted outputs, and optional expected labels\n * @returns The reference and per-format shift and optional flip reports\n *\n * @example\n * ```ts\n * const report = countFormatChanges({\n * \tbase: { BF16: ['met', 'unmet'], Q8_0: ['met', 'unmet'], Q4_K_M: ['met', 'met'] },\n * })\n * report.formats.map((entry) => entry.format) // ['Q8_0', 'Q4_K_M']\n * ```\n */\nexport function countFormatChanges<T = string>(\n\toptions: FormatChangeOptions<T>,\n): FormatChangeResult {\n\tif (!isRecord(options)) {\n\t\tthrow new InferError('The format change options must be a plain object carrying base.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tconst reference: PrecisionFormat = options.reference ?? 'BF16'\n\tif (!isPrecisionFormat(reference)) {\n\t\tthrow new InferError(\n\t\t\t`The reference format ${quoteFaultText(String(reference))} must be \"BF16\", \"Q8_0\", or \"Q4_K_M\".`,\n\t\t\t{ code: 'ARGUMENT', context: { reference } },\n\t\t)\n\t}\n\tif (!isRecord(options.base)) {\n\t\tthrow new InferError('The format change base outputs must be a plain object keyed by format.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tconst badBaseKey = Object.keys(options.base).find((key) => !isPrecisionFormat(key))\n\tif (badBaseKey !== undefined) {\n\t\tthrow new InferError(\n\t\t\t`The base format key ${quoteFaultText(badBaseKey)} is not one of \"BF16\", \"Q8_0\", or \"Q4_K_M\".`,\n\t\t\t{ code: 'ARGUMENT', context: { format: badBaseKey } },\n\t\t)\n\t}\n\tif (options.adapted !== undefined) {\n\t\tif (!isRecord(options.adapted)) {\n\t\t\tthrow new InferError(\n\t\t\t\t'The format change adapted outputs must be a plain object keyed by format.',\n\t\t\t\t{ code: 'ARGUMENT' },\n\t\t\t)\n\t\t}\n\t\tconst badAdaptedKey = Object.keys(options.adapted).find((key) => !isPrecisionFormat(key))\n\t\tif (badAdaptedKey !== undefined) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The adapted format key ${quoteFaultText(badAdaptedKey)} is not one of \"BF16\", \"Q8_0\", or \"Q4_K_M\".`,\n\t\t\t\t{ code: 'ARGUMENT', context: { format: badAdaptedKey } },\n\t\t\t)\n\t\t}\n\t}\n\tconst refBase = options.base[reference]\n\tif (!isArray(refBase) || refBase.length === 0) {\n\t\tthrow new InferError(\n\t\t\t`The base outputs must include a non-empty array for reference format ${quoteFaultText(reference)}.`,\n\t\t\t{ code: 'ARGUMENT', context: { reference } },\n\t\t)\n\t}\n\tconst total = refBase.length\n\tconst expected = options.expected\n\tif (expected !== undefined && (!isArray(expected) || expected.length !== total)) {\n\t\tthrow new InferError(\n\t\t\t`The expected labels must hold ${total} entries matching reference format ${quoteFaultText(reference)}.`,\n\t\t\t{ code: 'ARGUMENT', context: { expected: isArray(expected) ? expected.length : -1, total } },\n\t\t)\n\t}\n\tconst refAdapted = options.adapted?.[reference]\n\tif (refAdapted !== undefined && (!isArray(refAdapted) || refAdapted.length !== total)) {\n\t\tthrow new InferError(\n\t\t\t`The adapted outputs for ${quoteFaultText(reference)} must hold ${total} entries.`,\n\t\t\t{ code: 'ARGUMENT', context: { format: reference, total } },\n\t\t)\n\t}\n\tfor (const format of PRECISION_FORMATS) {\n\t\tconst baseSeries = options.base[format]\n\t\tif (baseSeries !== undefined && (!isArray(baseSeries) || baseSeries.length !== total)) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The base outputs for ${quoteFaultText(format)} must hold ${total} entries.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { format, total } },\n\t\t\t)\n\t\t}\n\t\tconst adaptedSeries = options.adapted?.[format]\n\t\tif (adaptedSeries !== undefined) {\n\t\t\tif (!isArray(adaptedSeries) || adaptedSeries.length !== total) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The adapted outputs for ${quoteFaultText(format)} must hold ${total} entries.`,\n\t\t\t\t\t{ code: 'ARGUMENT', context: { format, total } },\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (baseSeries === undefined) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The adapted outputs include ${quoteFaultText(format)}, which is absent from base outputs.`,\n\t\t\t\t\t{ code: 'ARGUMENT', context: { format } },\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (format !== reference && refAdapted === undefined) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The adapted outputs include ${quoteFaultText(format)} without reference format ${quoteFaultText(reference)}.`,\n\t\t\t\t\t{ code: 'ARGUMENT', context: { format, reference } },\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\tconst otherFormats = PRECISION_FORMATS.filter(\n\t\t(format) => format !== reference && options.base[format] !== undefined,\n\t)\n\tif (otherFormats.length === 0 && refAdapted === undefined) {\n\t\tthrow new InferError(\n\t\t\t`The format change comparison requires at least one other format beside ${quoteFaultText(reference)} or adapted outputs for ${quoteFaultText(reference)}.`,\n\t\t\t{ code: 'ARGUMENT', context: { reference } },\n\t\t)\n\t}\n\tconst formats: readonly FormatChangeEntry[] = otherFormats.map((format) => {\n\t\tconst baseSeries = options.base[format] ?? []\n\t\tconst base = countChanges({\n\t\t\tbefore: refBase,\n\t\t\tafter: baseSeries,\n\t\t\tformats: { before: reference, after: format },\n\t\t})\n\t\tconst flips =\n\t\t\texpected === undefined\n\t\t\t\t? undefined\n\t\t\t\t: countFlips({ expected, before: refBase, after: baseSeries })\n\t\tconst adaptedSeries = options.adapted?.[format]\n\t\tconst adapted =\n\t\t\tadaptedSeries === undefined || refAdapted === undefined\n\t\t\t\t? undefined\n\t\t\t\t: countChanges({\n\t\t\t\t\t\tbefore: refAdapted,\n\t\t\t\t\t\tafter: adaptedSeries,\n\t\t\t\t\t\tformats: { before: reference, after: format },\n\t\t\t\t\t})\n\t\tconst delta =\n\t\t\tadaptedSeries === undefined\n\t\t\t\t? undefined\n\t\t\t\t: countChanges({\n\t\t\t\t\t\tbefore: baseSeries,\n\t\t\t\t\t\tafter: adaptedSeries,\n\t\t\t\t\t\tformats: { before: format, after: format },\n\t\t\t\t\t})\n\t\tconst gain =\n\t\t\tadaptedSeries === undefined || expected === undefined\n\t\t\t\t? undefined\n\t\t\t\t: countFlips({ expected, before: baseSeries, after: adaptedSeries })\n\t\treturn {\n\t\t\tformat,\n\t\t\tbase,\n\t\t\t...(adapted === undefined ? {} : { adapted }),\n\t\t\t...(delta === undefined ? {} : { delta }),\n\t\t\t...(flips === undefined ? {} : { flips }),\n\t\t\t...(gain === undefined ? {} : { gain }),\n\t\t}\n\t})\n\tconst delta =\n\t\trefAdapted === undefined\n\t\t\t? undefined\n\t\t\t: countChanges({\n\t\t\t\t\tbefore: refBase,\n\t\t\t\t\tafter: refAdapted,\n\t\t\t\t\tformats: { before: reference, after: reference },\n\t\t\t\t})\n\tconst gain =\n\t\trefAdapted === undefined || expected === undefined\n\t\t\t? undefined\n\t\t\t: countFlips({ expected, before: refBase, after: refAdapted })\n\treturn {\n\t\treference,\n\t\ttotal,\n\t\t...(delta === undefined ? {} : { delta }),\n\t\t...(gain === undefined ? {} : { gain }),\n\t\tformats,\n\t}\n}\n\n/**\n * Refuses a provenance record that omits any required field or names a hosted-model service or\n * family marker.\n *\n * @remarks\n * Requires non-empty trimmed strings for `source`, `licence`, `generator`, `date`, and `digest`.\n * Normalizes each field with NFKC, strips format and combining characters, folds Cyrillic and\n * Greek visual confusables to ASCII Latin, normalizes Unicode dashes to `-`, lower-cases the\n * result, and refuses token-bounded hosted-model markers (`anthropic`, `openai`, `google`, `xai`,\n * `claude`, `gpt-`, `gemini`, `grok`, or `chatgpt`) with the `ARGUMENT` code.\n *\n * @param provenance - The provenance record to check\n *\n * @example\n * ```ts\n * checkRowProvenance({\n * \tsource: 'local-reason-berth',\n * \tlicence: 'MIT',\n * \tgenerator: 'orkestrel-reason-local',\n * \tdate: '2026-11-30',\n * \tdigest: '0'.repeat(64),\n * })\n * ```\n */\nexport function checkRowProvenance(provenance: RowProvenance): void {\n\tif (!isRecord(provenance)) {\n\t\tthrow new InferError(\n\t\t\t'The provenance is not a plain object; every row carries source, licence, generator, date, and digest.',\n\t\t\t{ code: 'ARGUMENT' },\n\t\t)\n\t}\n\tconst fields = ['source', 'licence', 'generator', 'date', 'digest'] as const\n\tconst confusables: Readonly<Record<string, string>> = {\n\t\t'\\u0410': 'a',\n\t\t'\\u0430': 'a',\n\t\t'\\u0412': 'b',\n\t\t'\\u0432': 'b',\n\t\t'\\u0421': 'c',\n\t\t'\\u0441': 'c',\n\t\t'\\u0415': 'e',\n\t\t'\\u0435': 'e',\n\t\t'\\u041D': 'h',\n\t\t'\\u043D': 'h',\n\t\t'\\u0406': 'i',\n\t\t'\\u0456': 'i',\n\t\t'\\u0408': 'j',\n\t\t'\\u0458': 'j',\n\t\t'\\u041A': 'k',\n\t\t'\\u043A': 'k',\n\t\t'\\u041C': 'm',\n\t\t'\\u043C': 'm',\n\t\t'\\u041E': 'o',\n\t\t'\\u043E': 'o',\n\t\t'\\u0420': 'p',\n\t\t'\\u0440': 'p',\n\t\t'\\u0405': 's',\n\t\t'\\u0455': 's',\n\t\t'\\u0422': 't',\n\t\t'\\u0442': 't',\n\t\t'\\u0423': 'y',\n\t\t'\\u0443': 'y',\n\t\t'\\u0425': 'x',\n\t\t'\\u0445': 'x',\n\t\t'\\u0391': 'a',\n\t\t'\\u03B1': 'a',\n\t\t'\\u0392': 'b',\n\t\t'\\u0395': 'e',\n\t\t'\\u03B5': 'e',\n\t\t'\\u0397': 'h',\n\t\t'\\u0399': 'i',\n\t\t'\\u03B9': 'i',\n\t\t'\\u039A': 'k',\n\t\t'\\u03BA': 'k',\n\t\t'\\u039C': 'm',\n\t\t'\\u039D': 'n',\n\t\t'\\u03BD': 'v',\n\t\t'\\u039F': 'o',\n\t\t'\\u03BF': 'o',\n\t\t'\\u03A1': 'p',\n\t\t'\\u03C1': 'p',\n\t\t'\\u03A4': 't',\n\t\t'\\u03C4': 't',\n\t\t'\\u03A5': 'y',\n\t\t'\\u03C5': 'u',\n\t\t'\\u03A7': 'x',\n\t\t'\\u03C7': 'x',\n\t}\n\tconst markers: ReadonlyArray<readonly [marker: string, pattern: RegExp]> = [\n\t\t['anthropic', /anthropic/u],\n\t\t['openai', /openai|(?<![a-z0-9])open[\\s\\-_.]+ai(?![a-z])/u],\n\t\t['google', /google/u],\n\t\t['xai', /(?<![a-z0-9])x[\\s\\-_.]*ai(?![a-z0-9])/u],\n\t\t['claude', /claude/u],\n\t\t['chatgpt', /chatgpt|(?<![a-z0-9])chat[\\s\\-_.]+gpt(?![a-z])/u],\n\t\t['gpt-', /gpt-|(?<![a-z0-9])gpt(?:[\\s\\-_.]*(?:\\d|4o)|(?![a-z0-9]))/u],\n\t\t['gemini', /gemini/u],\n\t\t['grok', /grok/u],\n\t]\n\tfor (const field of fields) {\n\t\tconst value = provenance[field]\n\t\tif (!isString(value) || value.trim().length === 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The provenance lacks a non-empty ${quoteFaultText(field)}; every row carries source, licence, generator, date, and digest.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { field } },\n\t\t\t)\n\t\t}\n\t\tconst normalized = Array.from(\n\t\t\tvalue\n\t\t\t\t.normalize('NFKC')\n\t\t\t\t.replace(/\\p{Cf}|\\p{Mn}/gu, '')\n\t\t\t\t.replace(/\\p{Pd}/gu, '-'),\n\t\t\t(character) => confusables[character] ?? character,\n\t\t)\n\t\t\t.join('')\n\t\t\t.toLowerCase()\n\t\tif (normalized.trim().length === 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The provenance lacks a non-empty ${quoteFaultText(field)}; every row carries source, licence, generator, date, and digest.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { field } },\n\t\t\t)\n\t\t}\n\t\tconst matched = markers.find(([, pattern]) => pattern.test(normalized))\n\t\tif (matched !== undefined) {\n\t\t\tconst [marker] = matched\n\t\t\tthrow new InferError(\n\t\t\t\t`The provenance ${field} ${quoteFaultText(value)} carries hosted-model marker ${quoteFaultText(marker)}; no row written or labelled by a hosted model may enter a fit.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { field, marker } },\n\t\t\t)\n\t\t}\n\t}\n}\n\n/**\n * Collects grouped prompt-completion training rows from `@orkestrel/agent` conversation snapshots,\n * checking row provenance first and rendering each turn prefix through `@orkestrel/template`.\n *\n * @remarks\n * Verifies `options.provenance` through `checkRowProvenance` before inspecting snapshots or emitting\n * any row, validates every snapshot with `isConversationSnapshot` and a non-empty `id`, and emits\n * one `{ prompt, completion, group, provenance }` row per non-empty assistant turn that follows at\n * least one preceding message, with `group` set to `snapshot.id`. Template compilation or evaluation\n * failures translate `TemplateError` into `InferError` (`FORMAT` for syntax or subset refusals,\n * `ARGUMENT` for evaluation refusals).\n *\n * @param snapshots - The conversation snapshots to collect from, in order\n * @param options - The template tree or Jinja source, provenance record, and optional context values\n * @returns The rendered prompt-completion rows grouped by conversation id\n *\n * @example\n * ```ts\n * const rows = collectConversationRows([conversation.snapshot()], {\n * \ttemplate: '{% for m in messages %}{{ m.role }}: {{ m.content }}\\n{% endfor %}assistant: ',\n * \tprovenance,\n * })\n * rows[0]?.group === conversation.id // true\n * ```\n */\nexport function collectConversationRows(\n\tsnapshots: readonly ConversationSnapshot[],\n\toptions: ConversationRowOptions,\n): readonly ConversationRow[] {\n\tif (!isRecord(options)) {\n\t\tthrow new InferError(\n\t\t\t'The conversation row options must be a plain object carrying template and provenance.',\n\t\t\t{ code: 'ARGUMENT' },\n\t\t)\n\t}\n\tcheckRowProvenance(options.provenance)\n\tconst provenance: RowProvenance = {\n\t\tsource: options.provenance.source,\n\t\tlicence: options.provenance.licence,\n\t\tgenerator: options.provenance.generator,\n\t\tdate: options.provenance.date,\n\t\tdigest: options.provenance.digest,\n\t}\n\tif (options.context !== undefined && !isRecord(options.context)) {\n\t\tthrow new InferError('The conversation row context option must be a plain object.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tconst source = isString(options.template) ? options.template : undefined\n\tconst compiled = source !== undefined ? attempt(() => compileTemplate(source)) : undefined\n\tif (compiled !== undefined && !compiled.success) {\n\t\tconst code =\n\t\t\tisTemplateError(compiled.error) && compiled.error.code === 'FORMAT' ? 'FORMAT' : 'ARGUMENT'\n\t\tthrow new InferError(\n\t\t\t`The conversation template failed to compile: ${compiled.error instanceof Error ? compiled.error.message : String(compiled.error)}`,\n\t\t\t{ code, cause: compiled.error },\n\t\t)\n\t}\n\tconst tree = source === undefined ? options.template : undefined\n\tif (\n\t\ttree !== undefined &&\n\t\t(!isObject(tree) ||\n\t\t\ttypeof Reflect.get(tree, 'evaluate') !== 'function' ||\n\t\t\t!isTemplateDocument(Reflect.get(tree, 'document')))\n\t) {\n\t\tthrow new InferError(\n\t\t\t'The conversation template must be a Jinja template string or a TemplateTreeInterface.',\n\t\t\t{ code: 'ARGUMENT' },\n\t\t)\n\t}\n\tif (!isArray(snapshots)) {\n\t\tthrow new InferError(\n\t\t\t'The conversation snapshots must be an array of ConversationSnapshot values.',\n\t\t\t{ code: 'ARGUMENT' },\n\t\t)\n\t}\n\tconst checkedSnapshots = snapshots.map((snapshot, index) => {\n\t\tif (!isConversationSnapshot(snapshot) || snapshot.id.length === 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The conversation snapshot at index ${index} is not a valid ConversationSnapshot with a non-empty id.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { snapshot: index } },\n\t\t\t)\n\t\t}\n\t\treturn snapshot\n\t})\n\treturn checkedSnapshots.flatMap((snapshot) =>\n\t\tsnapshot.messages.flatMap((message, turnIndex) => {\n\t\t\tif (message.role !== 'assistant' || message.content.length === 0 || turnIndex === 0) return []\n\t\t\tconst messages = buildChatMessages(snapshot.messages.slice(0, turnIndex))\n\t\t\tconst values: TemplateFillValues = {\n\t\t\t\t...(options.context ?? {}),\n\t\t\t\tmessages,\n\t\t\t\tadd_generation_prompt: true,\n\t\t\t}\n\t\t\tconst rendered = attempt(() =>\n\t\t\t\tcompiled !== undefined\n\t\t\t\t\t? evaluateTemplate(compiled.value, values)\n\t\t\t\t\t: (tree?.evaluate(values) ?? ''),\n\t\t\t)\n\t\t\tif (!rendered.success) {\n\t\t\t\tconst code =\n\t\t\t\t\tisTemplateError(rendered.error) && rendered.error.code === 'FORMAT'\n\t\t\t\t\t\t? 'FORMAT'\n\t\t\t\t\t\t: 'ARGUMENT'\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The conversation template failed on ${quoteFaultText(snapshot.id)} turn ${turnIndex}: ${rendered.error instanceof Error ? rendered.error.message : String(rendered.error)}`,\n\t\t\t\t\t{ code, cause: rendered.error, context: { group: snapshot.id, turn: turnIndex } },\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn [\n\t\t\t\t{ prompt: rendered.value, completion: message.content, group: snapshot.id, provenance },\n\t\t\t]\n\t\t}),\n\t)\n}\n\n/**\n * Checks that a checkpoint identifier satisfies `CHECKPOINT_ID_PATTERN` and refuses malformed,\n * empty, or path-traversing identifiers.\n *\n * @remarks\n * Thrown with the `ARGUMENT` code when `id` fails `isCheckpointId`.\n *\n * @param id - The checkpoint identifier to verify\n *\n * @example\n * ```ts\n * checkCheckpointId('run-1.step_10')\n * ```\n */\nexport function checkCheckpointId(id: string): void {\n\tif (!isCheckpointId(id)) {\n\t\tthrow new InferError(\n\t\t\t`The checkpoint identifier ${quoteFaultText(String(id))} is invalid; use 1 to 128 ASCII letters, digits, hyphens, underscores, or interior periods.`,\n\t\t\t{ code: 'ARGUMENT', context: { id: String(id) } },\n\t\t)\n\t}\n}\n\n/**\n * Builds the bytes of a self-describing GGUF v3 training checkpoint file from its metadata and\n * single-precision parameter and Adam moment triples.\n *\n * @remarks\n * Encodes `general.type = \"checkpoint\"`, `orkestrel.checkpoint.version = 1`, canonicalized JSON\n * `config`, ordered `targets`, and `F32` little-endian tensors `param.<k>`, `adam.m.<k>`, and\n * `adam.v.<k>` aligned to `GGUF_ALIGNMENT`. Omits `orkestrel.checkpoint.fold` completely when\n * `checkpoint.fold` is undefined. Thrown with the `ARGUMENT` code when the checkpoint fails\n * `isCheckpoint`.\n *\n * @param checkpoint - The training checkpoint to serialize\n * @returns The GGUF v3 checkpoint file bytes\n *\n * @example\n * ```ts\n * const bytes = buildCheckpointGGUF(checkpoint)\n * readGGUFHeader(bytes).metadata.get('general.type') // { encoding: 'string', value: 'checkpoint' }\n * ```\n */\nexport function buildCheckpointGGUF(checkpoint: Checkpoint): Uint8Array<ArrayBuffer> {\n\tif (!isCheckpoint(checkpoint)) {\n\t\tthrow new InferError(\n\t\t\t'The checkpoint record is invalid: verify mode, base and dataset digests, non-negative counters, finite seed, uint32 rng, JSON config, and non-empty unique F32 target triples.',\n\t\t\t{ code: 'ARGUMENT' },\n\t\t)\n\t}\n\tconst canonicalConfig = canonicalStringify(checkpoint.config)\n\tif (canonicalConfig === undefined) {\n\t\tthrow new InferError('The checkpoint config cannot serialize to canonical JSON.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tconst integerEntries: ReadonlyArray<readonly [key: string, value: number]> = [\n\t\t[CHECKPOINT_KEYS.step, checkpoint.step],\n\t\t[CHECKPOINT_KEYS.epoch, checkpoint.epoch],\n\t\t[CHECKPOINT_KEYS.cursor, checkpoint.cursor],\n\t\t...(checkpoint.fold === undefined ? [] : ([[CHECKPOINT_KEYS.fold, checkpoint.fold]] as const)),\n\t]\n\tconst metadata = new Map<string, GGUFValue>([\n\t\t[CHECKPOINT_KEYS.type, { encoding: 'string', value: CHECKPOINT_TYPE }],\n\t\t[GGUF_KEYS.alignment, { encoding: 'uint32', value: GGUF_ALIGNMENT }],\n\t\t[CHECKPOINT_KEYS.version, { encoding: 'uint32', value: CHECKPOINT_VERSION }],\n\t\t[CHECKPOINT_KEYS.mode, { encoding: 'string', value: checkpoint.mode }],\n\t\t[CHECKPOINT_KEYS.base, { encoding: 'string', value: checkpoint.base }],\n\t\t[CHECKPOINT_KEYS.dataset, { encoding: 'string', value: checkpoint.dataset }],\n\t\t...integerEntries.map(([key, value]): readonly [string, GGUFValue] => [\n\t\t\tkey,\n\t\t\tvalue <= 0xffff_ffff\n\t\t\t\t? { encoding: 'uint32', value }\n\t\t\t\t: { encoding: 'uint64', value: BigInt(value) },\n\t\t]),\n\t\t[CHECKPOINT_KEYS.seed, { encoding: 'float64', value: checkpoint.seed }],\n\t\t[CHECKPOINT_KEYS.rng, { encoding: 'uint32', value: checkpoint.rng }],\n\t\t[CHECKPOINT_KEYS.config, { encoding: 'string', value: canonicalConfig }],\n\t\t[\n\t\t\tCHECKPOINT_KEYS.targets,\n\t\t\t{\n\t\t\t\tencoding: 'array',\n\t\t\t\telement: 'string',\n\t\t\t\tvalue: checkpoint.targets.map((target) => target.name),\n\t\t\t},\n\t\t],\n\t])\n\tconst parts: ReadonlyArray<\n\t\treadonly [name: string, dimensions: readonly number[], values: Float32Array]\n\t> = checkpoint.targets.flatMap((target) => [\n\t\t[\n\t\t\t`${CHECKPOINT_TENSOR_PREFIXES.parameters}${target.name}`,\n\t\t\t[target.columns, target.rows],\n\t\t\ttarget.parameters,\n\t\t],\n\t\t[\n\t\t\t`${CHECKPOINT_TENSOR_PREFIXES.first}${target.name}`,\n\t\t\t[target.columns, target.rows],\n\t\t\ttarget.first,\n\t\t],\n\t\t[\n\t\t\t`${CHECKPOINT_TENSOR_PREFIXES.second}${target.name}`,\n\t\t\t[target.columns, target.rows],\n\t\t\ttarget.second,\n\t\t],\n\t])\n\tconst ends = parts.map((_, index) =>\n\t\tparts\n\t\t\t.slice(0, index + 1)\n\t\t\t.reduce((total, [, , values]) => alignOffset(total + 4 * values.length, GGUF_ALIGNMENT), 0),\n\t)\n\tconst data = new Uint8Array(ends.at(-1) ?? 0)\n\tconst view = new DataView(data.buffer)\n\tfor (const [index, [, , values]] of parts.entries()) {\n\t\tconst offset = ends[index - 1] ?? 0\n\t\tfor (let element = 0; element < values.length; element += 1) {\n\t\t\tview.setFloat32(offset + 4 * element, values[element] ?? Number.NaN, true)\n\t\t}\n\t}\n\treturn buildGGUF(\n\t\tmetadata,\n\t\tparts.map(([name, dimensions], index) => ({\n\t\t\tname,\n\t\t\tdimensions,\n\t\t\tformat: 'F32',\n\t\t\toffset: ends[index - 1] ?? 0,\n\t\t})),\n\t\tdata,\n\t)\n}\n\n/**\n * Reads and validates a self-describing GGUF v3 training checkpoint from a byte source, verifying\n * optional base and dataset bindings.\n *\n * @remarks\n * Refuses malformed GGUF headers, wrong `general.type` or version, negative or fractional\n * counters, missing or mismatched `param.<k>` / `adam.m.<k>` / `adam.v.<k>` triples, non-`F32`\n * tensor dtypes, shape mismatches across a triple, and non-finite values with the `FORMAT` code.\n * Refuses mismatched expected `base` or `dataset` digests with the `BINDING` code, and an aborted\n * signal with the `ABORT` code.\n *\n * @param source - The byte source holding the GGUF v3 checkpoint\n * @param options - Optional expected bindings and abort signal\n * @returns The decoded and validated checkpoint\n *\n * @example\n * ```ts\n * const checkpoint = await readCheckpointGGUF(new MemorySource(bytes), { base: backbone.digest })\n * checkpoint.mode // 'adapter'\n * ```\n */\nexport async function readCheckpointGGUF(\n\tsource: ByteSourceInterface,\n\toptions: CheckpointReadOptions = {},\n): Promise<Checkpoint> {\n\tcheckSignal(options.signal, 'The checkpoint read')\n\tconst [bytes, , header] = await readGGUFFile(source, 'The checkpoint read', options.signal)\n\tconst { metadata, tensors } = header\n\tconst fileType = readMetadataString(metadata, CHECKPOINT_KEYS.type)\n\tif (fileType !== CHECKPOINT_TYPE) {\n\t\tthrow new InferError(\n\t\t\t`The GGUF general.type is ${quoteFaultText(String(fileType))}; expected ${quoteFaultText(CHECKPOINT_TYPE)}.`,\n\t\t\t{ code: 'FORMAT', context: { type: fileType } },\n\t\t)\n\t}\n\tconst version = readMetadataInteger(metadata, CHECKPOINT_KEYS.version)\n\tif (version !== CHECKPOINT_VERSION) {\n\t\tthrow new InferError(\n\t\t\t`The checkpoint version is ${String(version)}; expected ${CHECKPOINT_VERSION}.`,\n\t\t\t{ code: 'FORMAT', context: { version } },\n\t\t)\n\t}\n\tconst mode = readMetadataString(metadata, CHECKPOINT_KEYS.mode)\n\tif (!isCheckpointMode(mode)) {\n\t\tthrow new InferError(\n\t\t\t`The checkpoint mode is ${quoteFaultText(String(mode))}; expected \"adapter\" or \"section\".`,\n\t\t\t{ code: 'FORMAT', context: { mode } },\n\t\t)\n\t}\n\tconst base = readMetadataString(metadata, CHECKPOINT_KEYS.base)\n\tif (base === undefined || !SHA256_PATTERN.test(base)) {\n\t\tthrow new InferError(\n\t\t\t`The checkpoint base digest ${quoteFaultText(String(base))} is missing or malformed.`,\n\t\t\t{ code: 'FORMAT', context: { key: CHECKPOINT_KEYS.base } },\n\t\t)\n\t}\n\tconst dataset = readMetadataString(metadata, CHECKPOINT_KEYS.dataset)\n\tif (dataset === undefined || !SHA256_PATTERN.test(dataset)) {\n\t\tthrow new InferError(\n\t\t\t`The checkpoint dataset digest ${quoteFaultText(String(dataset))} is missing or malformed.`,\n\t\t\t{ code: 'FORMAT', context: { key: CHECKPOINT_KEYS.dataset } },\n\t\t)\n\t}\n\tconst step = readMetadataInteger(metadata, CHECKPOINT_KEYS.step)\n\tconst epoch = readMetadataInteger(metadata, CHECKPOINT_KEYS.epoch)\n\tconst cursor = readMetadataInteger(metadata, CHECKPOINT_KEYS.cursor)\n\tif (\n\t\tstep === undefined ||\n\t\tstep < 0 ||\n\t\tepoch === undefined ||\n\t\tepoch < 0 ||\n\t\tcursor === undefined ||\n\t\tcursor < 0\n\t) {\n\t\tthrow new InferError(\n\t\t\t'The checkpoint counters step, epoch, and cursor must be non-negative safe integers.',\n\t\t\t{ code: 'FORMAT', context: { step, epoch, cursor } },\n\t\t)\n\t}\n\tconst seed = readMetadataNumber(metadata, CHECKPOINT_KEYS.seed)\n\tif (seed === undefined || !isFiniteNumber(seed)) {\n\t\tthrow new InferError(`The checkpoint seed ${String(seed)} must be a finite number.`, {\n\t\t\tcode: 'FORMAT',\n\t\t\tcontext: { seed },\n\t\t})\n\t}\n\tconst rng = readMetadataInteger(metadata, CHECKPOINT_KEYS.rng)\n\tif (rng === undefined || rng < 0 || rng > 0xffff_ffff) {\n\t\tthrow new InferError(\n\t\t\t`The checkpoint rng state ${String(rng)} must be an unsigned 32-bit integer.`,\n\t\t\t{\n\t\t\t\tcode: 'FORMAT',\n\t\t\t\tcontext: { rng },\n\t\t\t},\n\t\t)\n\t}\n\tconst fold = readMetadataInteger(metadata, CHECKPOINT_KEYS.fold)\n\tif (fold !== undefined && (!isSafeInteger(fold) || fold < 0)) {\n\t\tthrow new InferError(\n\t\t\t`The checkpoint fold ${fold} must be a non-negative integer when present.`,\n\t\t\t{ code: 'FORMAT', context: { fold } },\n\t\t)\n\t}\n\tconst configText = readMetadataString(metadata, CHECKPOINT_KEYS.config)\n\tconst parsedConfig = configText === undefined ? undefined : parseJSON(configText)\n\tconst canonicalConfigText =\n\t\tparsedConfig === undefined ? undefined : canonicalStringify(parsedConfig)\n\tconst config = canonicalConfigText === undefined ? undefined : parseJSON(canonicalConfigText)\n\tif (!isBoundedJSONRecord(config)) {\n\t\tthrow new InferError('The checkpoint config must be a valid JSON object.', {\n\t\t\tcode: 'FORMAT',\n\t\t\tcontext: { key: CHECKPOINT_KEYS.config },\n\t\t})\n\t}\n\tconst targetNames = readMetadataStrings(metadata, CHECKPOINT_KEYS.targets)\n\tif (\n\t\ttargetNames === undefined ||\n\t\ttargetNames.length === 0 ||\n\t\ttargetNames.some((name) => name.length === 0 || name.includes('\\0')) ||\n\t\tnew Set(targetNames).size !== targetNames.length\n\t) {\n\t\tthrow new InferError(\n\t\t\t'The checkpoint targets list must hold one or more unique non-empty target names.',\n\t\t\t{ code: 'FORMAT', context: { key: CHECKPOINT_KEYS.targets } },\n\t\t)\n\t}\n\tconst tensorMap = new Map(tensors.map((tensor) => [tensor.name, tensor] as const))\n\tif (tensorMap.size !== tensors.length || tensors.length !== targetNames.length * 3) {\n\t\tthrow new InferError(\n\t\t\t`The checkpoint holds ${tensors.length} tensors (${tensorMap.size} unique); expected ${targetNames.length * 3} tensors for ${targetNames.length} targets.`,\n\t\t\t{ code: 'FORMAT', context: { tensors: tensors.length, targets: targetNames.length } },\n\t\t)\n\t}\n\tconst targets: readonly CheckpointTarget[] = targetNames.map((name) => {\n\t\tconst tripleNames = [\n\t\t\t`${CHECKPOINT_TENSOR_PREFIXES.parameters}${name}`,\n\t\t\t`${CHECKPOINT_TENSOR_PREFIXES.first}${name}`,\n\t\t\t`${CHECKPOINT_TENSOR_PREFIXES.second}${name}`,\n\t\t] as const\n\t\tconst tripleTensors = tripleNames.map((tensorName) => {\n\t\t\tconst tensor = tensorMap.get(tensorName)\n\t\t\tif (tensor === undefined) {\n\t\t\t\tthrow new InferError(`The checkpoint lacks tensor ${quoteFaultText(tensorName)}.`, {\n\t\t\t\t\tcode: 'FORMAT',\n\t\t\t\t\tcontext: { target: name, tensor: tensorName },\n\t\t\t\t})\n\t\t\t}\n\t\t\tif (tensor.format !== 'F32') {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The checkpoint tensor ${quoteFaultText(tensorName)} has dtype ${tensor.format}; expected F32.`,\n\t\t\t\t\t{ code: 'FORMAT', context: { tensor: tensorName, format: tensor.format } },\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (\n\t\t\t\ttensor.dimensions.length !== 2 ||\n\t\t\t\t!isSafeInteger(tensor.dimensions[0]) ||\n\t\t\t\ttensor.dimensions[0] < 1 ||\n\t\t\t\t!isSafeInteger(tensor.dimensions[1]) ||\n\t\t\t\ttensor.dimensions[1] < 1\n\t\t\t) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The checkpoint tensor ${quoteFaultText(tensorName)} must have positive 2D dimensions.`,\n\t\t\t\t\t{ code: 'FORMAT', context: { tensor: tensorName, dimensions: tensor.dimensions } },\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn tensor\n\t\t})\n\t\tconst [paramTensor, firstTensor, secondTensor] = tripleTensors\n\t\tif (\n\t\t\tparamTensor === undefined ||\n\t\t\tfirstTensor === undefined ||\n\t\t\tsecondTensor === undefined ||\n\t\t\t!matchesElements(paramTensor.dimensions, firstTensor.dimensions) ||\n\t\t\t!matchesElements(paramTensor.dimensions, secondTensor.dimensions)\n\t\t) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The checkpoint target ${quoteFaultText(name)} has mismatched triple tensor dimensions.`,\n\t\t\t\t{ code: 'FORMAT', context: { target: name } },\n\t\t\t)\n\t\t}\n\t\tconst [columns = 0, rows = 0] = paramTensor.dimensions\n\t\tconst [parameters, first, second] = tripleNames.map((tensorName) => {\n\t\t\tconst values = readNamedTensor(bytes, header, tensorName, [columns, rows])\n\t\t\tif (!values.every(Number.isFinite)) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The checkpoint tensor ${quoteFaultText(tensorName)} contains non-finite values.`,\n\t\t\t\t\t{ code: 'FORMAT', context: { tensor: tensorName } },\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn values\n\t\t})\n\t\tif (parameters === undefined || first === undefined || second === undefined) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The checkpoint target ${quoteFaultText(name)} triple could not be read.`,\n\t\t\t\t{\n\t\t\t\t\tcode: 'FORMAT',\n\t\t\t\t\tcontext: { target: name },\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\treturn { name, rows, columns, parameters, first, second }\n\t})\n\tif (options.base !== undefined && base !== options.base) {\n\t\tthrow new InferError(\n\t\t\t`The checkpoint binds base ${quoteFaultText(base)}, not expected ${quoteFaultText(options.base)}.`,\n\t\t\t{ code: 'BINDING', context: { field: 'base', expected: options.base, actual: base } },\n\t\t)\n\t}\n\tif (options.dataset !== undefined && dataset !== options.dataset) {\n\t\tthrow new InferError(\n\t\t\t`The checkpoint binds dataset ${quoteFaultText(dataset)}, not expected ${quoteFaultText(options.dataset)}.`,\n\t\t\t{\n\t\t\t\tcode: 'BINDING',\n\t\t\t\tcontext: { field: 'dataset', expected: options.dataset, actual: dataset },\n\t\t\t},\n\t\t)\n\t}\n\treturn {\n\t\tmode,\n\t\tbase,\n\t\tdataset,\n\t\tstep,\n\t\tepoch,\n\t\tcursor,\n\t\tseed,\n\t\trng,\n\t\t...(fold === undefined ? {} : { fold }),\n\t\tconfig,\n\t\ttargets,\n\t}\n}\n\n/**\n * Advances one single-precision checkpoint target by one Adam optimizer step, returning fresh\n * `Float32Array` parameters and moments.\n *\n * @remarks\n * Uses `ADAM_FIRST`, `ADAM_SECOND`, and `ADAM_EPSILON`, rounding each updated moment and parameter\n * to IEEE 754 single precision with `Math.fround` so resumed steps from a GGUF `F32` checkpoint\n * match uninterrupted runs bit-for-bit. Thrown with the `ARGUMENT` code when target, gradient,\n * step, or rate is invalid.\n *\n * @param target - The target parameters and moments before the step\n * @param gradient - The single-precision gradient matching `target.parameters.length`\n * @param step - The 1-based optimizer step number\n * @param rate - The non-negative finite learning rate\n * @returns The updated checkpoint target\n *\n * @example\n * ```ts\n * const next = stepCheckpointAdam(target, Float32Array.of(0.5, -0.5), 1, 0.01)\n * ```\n */\nexport function stepCheckpointAdam(\n\ttarget: CheckpointTarget,\n\tgradient: Float32Array,\n\tstep: number,\n\trate: number,\n): CheckpointTarget {\n\tif (!isCheckpointTarget(target)) {\n\t\tthrow new InferError('The checkpoint target is invalid.', { code: 'ARGUMENT' })\n\t}\n\tif (\n\t\t!isFloat32Array(gradient) ||\n\t\tgradient.length !== target.parameters.length ||\n\t\t!gradient.every(Number.isFinite)\n\t) {\n\t\tthrow new InferError(\n\t\t\t`The gradient must be a finite Float32Array of length ${target.parameters.length}.`,\n\t\t\t{ code: 'ARGUMENT', context: { expected: target.parameters.length } },\n\t\t)\n\t}\n\tif (!isSafeInteger(step) || step < 1) {\n\t\tthrow new InferError(`The Adam step ${step} must be a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { step },\n\t\t})\n\t}\n\tif (!isFiniteNumber(rate) || rate < 0) {\n\t\tthrow new InferError(`The learning rate ${rate} must be a finite non-negative number.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { rate },\n\t\t})\n\t}\n\tconst length = target.parameters.length\n\tconst firstScale = 1 - Math.pow(ADAM_FIRST.decay, step)\n\tconst secondScale = 1 - Math.pow(ADAM_SECOND.decay, step)\n\tconst parameters = new Float32Array(length)\n\tconst first = new Float32Array(length)\n\tconst second = new Float32Array(length)\n\tfor (let index = 0; index < length; index += 1) {\n\t\tconst value = gradient[index] ?? 0\n\t\tconst m = Math.fround(ADAM_FIRST.decay * (target.first[index] ?? 0) + ADAM_FIRST.gain * value)\n\t\tconst v = Math.fround(\n\t\t\tADAM_SECOND.decay * (target.second[index] ?? 0) + ADAM_SECOND.gain * value * value,\n\t\t)\n\t\tfirst[index] = m\n\t\tsecond[index] = v\n\t\tparameters[index] = Math.fround(\n\t\t\t(target.parameters[index] ?? 0) -\n\t\t\t\t(rate * (m / firstScale)) / (Math.sqrt(v / secondScale) + ADAM_EPSILON),\n\t\t)\n\t}\n\treturn {\n\t\tname: target.name,\n\t\trows: target.rows,\n\t\tcolumns: target.columns,\n\t\tparameters,\n\t\tfirst,\n\t\tsecond,\n\t}\n}\n\n/**\n * Advances an explicit unsigned 32-bit Mulberry32 generator state by one draw, matching\n * `@orkestrel/contract`'s `seededRandom` sequence bit-for-bit.\n *\n * @remarks\n * Thrown with the `ARGUMENT` code when `state` is not an unsigned 32-bit integer.\n *\n * @param state - The current unsigned 32-bit generator state\n * @returns The drawn value in `[0, 1)` and the next unsigned 32-bit state\n *\n * @example\n * ```ts\n * const [value, next] = stepRandom(42)\n * ```\n */\nexport function stepRandom(state: number): readonly [value: number, next: number] {\n\tif (!isSafeInteger(state) || state < 0 || state > 0xffff_ffff) {\n\t\tthrow new InferError(`The generator state ${state} must be an unsigned 32-bit integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { state },\n\t\t})\n\t}\n\tconst next = (state + 0x6d2b79f5) >>> 0\n\tconst mixed = Math.imul(next ^ (next >>> 15), next | 1)\n\tconst final = mixed ^ (mixed + Math.imul(mixed ^ (mixed >>> 7), mixed | 61))\n\treturn [((final ^ (final >>> 14)) >>> 0) / 4294967296, next]\n}\n\n/**\n * Validates an untrusted `adapter_config.json` value and returns an owned `PEFTConfig` record.\n *\n * @remarks\n * Refuses unsupported PEFT options (`peft_type !== 'LORA'`, `use_rslora: true`, `use_dora: true`,\n * and `bias !== 'none'`) with the `UNSUPPORTED` code, and malformed shapes or numeric values with\n * the `FORMAT` code.\n *\n * @param value - The raw configuration record to validate\n * @returns The validated `PEFTConfig`\n *\n * @example\n * ```ts\n * checkPEFTConfig({ peft_type: 'LORA', r: 4, lora_alpha: 8, target_modules: ['q_proj'], bias: 'none' }).r // 4\n * ```\n */\nexport function checkPEFTConfig(value: unknown): PEFTConfig {\n\tif (!isRecord(value)) {\n\t\tthrow new InferError('The PEFT adapter configuration must be a plain object.', {\n\t\t\tcode: 'FORMAT',\n\t\t})\n\t}\n\tconst peftType = value['peft_type']\n\tif (!isString(peftType)) {\n\t\tthrow new InferError('The PEFT adapter configuration requires a string peft_type.', {\n\t\t\tcode: 'FORMAT',\n\t\t\tcontext: { field: 'peft_type' },\n\t\t})\n\t}\n\tif (peftType !== 'LORA') {\n\t\tthrow new InferError(\n\t\t\t`The PEFT adapter declares peft_type ${quoteFaultText(peftType)}; only \"LORA\" is supported.`,\n\t\t\t{ code: 'UNSUPPORTED', context: { field: 'peft_type', value: peftType } },\n\t\t)\n\t}\n\tif (Object.hasOwn(value, 'use_rslora')) {\n\t\tconst rslora = value['use_rslora']\n\t\tif (typeof rslora !== 'boolean') {\n\t\t\tthrow new InferError('The PEFT adapter field use_rslora must be a boolean when present.', {\n\t\t\t\tcode: 'FORMAT',\n\t\t\t\tcontext: { field: 'use_rslora' },\n\t\t\t})\n\t\t}\n\t\tif (rslora) {\n\t\t\tthrow new InferError('Rank-stabilized LoRA (use_rslora: true) is unsupported.', {\n\t\t\t\tcode: 'UNSUPPORTED',\n\t\t\t\tcontext: { field: 'use_rslora', value: true },\n\t\t\t})\n\t\t}\n\t}\n\tif (Object.hasOwn(value, 'use_dora')) {\n\t\tconst dora = value['use_dora']\n\t\tif (typeof dora !== 'boolean') {\n\t\t\tthrow new InferError('The PEFT adapter field use_dora must be a boolean when present.', {\n\t\t\t\tcode: 'FORMAT',\n\t\t\t\tcontext: { field: 'use_dora' },\n\t\t\t})\n\t\t}\n\t\tif (dora) {\n\t\t\tthrow new InferError('Weight-decomposed LoRA (use_dora: true) is unsupported.', {\n\t\t\t\tcode: 'UNSUPPORTED',\n\t\t\t\tcontext: { field: 'use_dora', value: true },\n\t\t\t})\n\t\t}\n\t}\n\tconst bias = value['bias']\n\tif (!isString(bias)) {\n\t\tthrow new InferError('The PEFT adapter configuration requires a string bias.', {\n\t\t\tcode: 'FORMAT',\n\t\t\tcontext: { field: 'bias' },\n\t\t})\n\t}\n\tif (bias !== 'none') {\n\t\tthrow new InferError(\n\t\t\t`The PEFT adapter declares bias ${quoteFaultText(bias)}; only \"none\" is supported.`,\n\t\t\t{ code: 'UNSUPPORTED', context: { field: 'bias', value: bias } },\n\t\t)\n\t}\n\tconst rank = value['r']\n\tif (!isSafeInteger(rank) || rank < 1) {\n\t\tthrow new InferError('The PEFT adapter rank r must be a positive integer.', {\n\t\t\tcode: 'FORMAT',\n\t\t\tcontext: { field: 'r' },\n\t\t})\n\t}\n\tconst alpha = value['lora_alpha']\n\tif (!isFiniteNumber(alpha) || alpha <= 0) {\n\t\tthrow new InferError('The PEFT adapter lora_alpha must be a positive finite number.', {\n\t\t\tcode: 'FORMAT',\n\t\t\tcontext: { field: 'lora_alpha' },\n\t\t})\n\t}\n\tconst modules = value['target_modules']\n\tif (\n\t\t!isArray(modules) ||\n\t\tmodules.length === 0 ||\n\t\t!modules.every((entry): entry is string => isString(entry) && entry.length > 0)\n\t) {\n\t\tthrow new InferError('The PEFT adapter target_modules must be a non-empty list of strings.', {\n\t\t\tcode: 'FORMAT',\n\t\t\tcontext: { field: 'target_modules' },\n\t\t})\n\t}\n\tconst taskType = Object.hasOwn(value, 'task_type') ? value['task_type'] : undefined\n\tif (taskType !== undefined && !isString(taskType)) {\n\t\tthrow new InferError('The PEFT adapter field task_type must be a string when present.', {\n\t\t\tcode: 'FORMAT',\n\t\t\tcontext: { field: 'task_type' },\n\t\t})\n\t}\n\tconst baseModel = Object.hasOwn(value, 'base_model_name_or_path')\n\t\t? value['base_model_name_or_path']\n\t\t: undefined\n\tif (baseModel !== undefined && !isString(baseModel)) {\n\t\tthrow new InferError(\n\t\t\t'The PEFT adapter field base_model_name_or_path must be a string when present.',\n\t\t\t{ code: 'FORMAT', context: { field: 'base_model_name_or_path' } },\n\t\t)\n\t}\n\treturn {\n\t\tpeft_type: 'LORA',\n\t\tr: rank,\n\t\tlora_alpha: alpha,\n\t\ttarget_modules: [...modules],\n\t\tbias: 'none',\n\t\t...(Object.hasOwn(value, 'use_rslora') ? { use_rslora: false } : {}),\n\t\t...(Object.hasOwn(value, 'use_dora') ? { use_dora: false } : {}),\n\t\t...(taskType === undefined ? {} : { task_type: taskType }),\n\t\t...(baseModel === undefined ? {} : { base_model_name_or_path: baseModel }),\n\t}\n}\n\n/**\n * Encodes single-precision float values to little-endian `F32`, IEEE 754 `F16`, or round-to-nearest-even\n * `BF16` bytes.\n *\n * @remarks\n * Uses `@orkestrel/infer`'s `narrowHalf` for `F16` conversion and IEEE 754 round-to-nearest-ties-to-even\n * for `BF16` conversion.\n *\n * @param values - The single-precision values to encode\n * @param format - The target safetensors dtype (`'F32'`, `'F16'`, or `'BF16'`)\n * @returns The encoded little-endian bytes\n *\n * @example\n * ```ts\n * encodeSafetensorsValues(Float32Array.of(1.5), 'BF16').length // 2\n * ```\n */\nexport function encodeSafetensorsValues(\n\tvalues: Float32Array,\n\tformat: SafetensorsFormat,\n): Uint8Array<ArrayBuffer> {\n\tif (format === 'F32') {\n\t\tconst out = new Uint8Array(values.length * 4)\n\t\tconst view = new DataView(out.buffer)\n\t\tfor (let index = 0; index < values.length; index += 1) {\n\t\t\tview.setFloat32(4 * index, values[index] ?? 0, true)\n\t\t}\n\t\treturn out\n\t}\n\tconst words = new Uint32Array(values.buffer, values.byteOffset, values.length)\n\tconst out = new Uint8Array(values.length * 2)\n\tconst view = new DataView(out.buffer)\n\tif (format === 'F16') {\n\t\tfor (let index = 0; index < values.length; index += 1) {\n\t\t\tview.setUint16(2 * index, narrowHalf(words[index] ?? 0), true)\n\t\t}\n\t\treturn out\n\t}\n\tfor (let index = 0; index < values.length; index += 1) {\n\t\tconst bits = words[index] ?? 0\n\t\tconst isNaN = (bits & 0x7f80_0000) === 0x7f80_0000 && (bits & 0x007f_ffff) !== 0\n\t\tconst encoded = isNaN\n\t\t\t? ((bits >>> 16) | 0x0040) & 0xffff\n\t\t\t: ((bits + (0x7fff + ((bits >>> 16) & 1))) >>> 16) & 0xffff\n\t\tview.setUint16(2 * index, encoded, true)\n\t}\n\treturn out\n}\n\n/**\n * Encodes single-precision weights into GGUF `Q8_0` blocks (34 bytes per 32-element block: a\n * little-endian IEEE 754 binary16 scale followed by 32 signed 8-bit quants).\n *\n * @remarks\n * Uses `@orkestrel/infer`'s `narrowHalf`, `widenHalf`, and `roundAway` so blocks match `GGUF_BLOCKS.Q8_0`\n * and decode identically through `widenTensor(bytes, 'Q8_0')` and llama.cpp's `dequantize_row_q8_0`.\n * Throws `InferError` with code `ARGUMENT` when `values.length` is not divisible by 32 or any value\n * is non-finite.\n *\n * @param values - The finite single-precision weights (length divisible by 32)\n * @returns The encoded `Q8_0` bytes\n *\n * @example\n * ```ts\n * encodeQ80Values(new Float32Array(32).fill(1)).length // 34\n * ```\n */\nexport function encodeQ80Values(values: Float32Array): Uint8Array<ArrayBuffer> {\n\tconst { elements, bytes: blockBytes } = GGUF_BLOCKS.Q8_0\n\tif (values.length % elements !== 0) {\n\t\tthrow new InferError(\n\t\t\t`A Q8_0 tensor holds a multiple of ${elements} values; it received ${values.length}.`,\n\t\t\t{ code: 'ARGUMENT', context: { format: 'Q8_0', values: values.length, block: elements } },\n\t\t)\n\t}\n\tconst blocks = values.length / elements\n\tconst out = new Uint8Array(blocks * blockBytes)\n\tconst view = new DataView(out.buffer)\n\tconst scratch = new Float32Array(1)\n\tconst scratchBits = new Uint32Array(scratch.buffer)\n\tfor (let block = 0; block < blocks; block += 1) {\n\t\tconst valueOffset = block * elements\n\t\tlet amax = 0\n\t\tfor (let index = 0; index < elements; index += 1) {\n\t\t\tconst value = values[valueOffset + index] ?? 0\n\t\t\tif (!Number.isFinite(value)) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The Q8_0 value at index ${valueOffset + index} must be finite; it received ${String(value)}.`,\n\t\t\t\t\t{ code: 'ARGUMENT', context: { format: 'Q8_0', index: valueOffset + index } },\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst magnitude = Math.abs(value)\n\t\t\tif (magnitude > amax) amax = magnitude\n\t\t}\n\t\tconst rawScale = Math.fround(amax / 127)\n\t\tscratch[0] = rawScale > 65_504 ? 65_504 : rawScale\n\t\tconst dBits = narrowHalf(scratchBits[0] ?? 0)\n\t\tconst halfScale = widenHalf(dBits)\n\t\tconst inverse = halfScale === 0 ? 0 : Math.fround(1 / halfScale)\n\t\tconst outOffset = block * blockBytes\n\t\tview.setUint16(outOffset, dBits, true)\n\t\tfor (let index = 0; index < elements; index += 1) {\n\t\t\tconst value = values[valueOffset + index] ?? 0\n\t\t\tconst quantized =\n\t\t\t\tinverse === 0 ? 0 : Math.max(-128, Math.min(127, roundAway(Math.fround(value * inverse))))\n\t\t\tview.setInt8(outOffset + 2 + index, quantized)\n\t\t}\n\t}\n\treturn out\n}\n\n/**\n * Encodes single-precision weights into GGUF `Q4_K` superblocks (144 bytes per 256-element block:\n * binary16 superblock scale `d`, binary16 minimum scale `dmin`, 12 packed bytes of 6-bit sub-block\n * scales and minimums, and 128 bytes of 4-bit nibbles).\n *\n * @remarks\n * Uses 1-step least-squares scale and minimum refinement per 32-element sub-block and packs scales\n * and nibbles to match `@orkestrel/infer`'s `decodeQ4K` and llama.cpp's `dequantize_row_q4_K`.\n * Throws `InferError` with code `ARGUMENT` when `values.length` is not divisible by 256 or any value\n * is non-finite.\n *\n * @param values - The finite single-precision weights (length divisible by 256)\n * @returns The encoded `Q4_K` bytes\n *\n * @example\n * ```ts\n * encodeQ4KValues(new Float32Array(256).fill(1)).length // 144\n * ```\n */\nexport function encodeQ4KValues(values: Float32Array): Uint8Array<ArrayBuffer> {\n\tconst { elements, bytes: blockBytes } = GGUF_BLOCKS.Q4_K\n\tif (values.length % elements !== 0) {\n\t\tthrow new InferError(\n\t\t\t`A Q4_K tensor holds a multiple of ${elements} values; it received ${values.length}.`,\n\t\t\t{ code: 'ARGUMENT', context: { format: 'Q4_K', values: values.length, block: elements } },\n\t\t)\n\t}\n\tconst blocks = values.length / elements\n\tconst out = new Uint8Array(blocks * blockBytes)\n\tconst view = new DataView(out.buffer)\n\tconst rawScales = new Float64Array(8)\n\tconst rawMins = new Float64Array(8)\n\tconst quantizedScales = new Uint8Array(8)\n\tconst quantizedMins = new Uint8Array(8)\n\tconst quants = new Uint8Array(elements)\n\tconst scratch = new Float32Array(1)\n\tconst scratchBits = new Uint32Array(scratch.buffer)\n\tfor (let block = 0; block < blocks; block += 1) {\n\t\tconst valueOffset = block * elements\n\t\tlet maxScale = 0\n\t\tlet maxMin = 0\n\t\tfor (let sub = 0; sub < 8; sub += 1) {\n\t\t\tconst subOffset = valueOffset + sub * 32\n\t\t\tlet actualMin = Number.POSITIVE_INFINITY\n\t\t\tlet actualMax = Number.NEGATIVE_INFINITY\n\t\t\tfor (let lane = 0; lane < 32; lane += 1) {\n\t\t\t\tconst value = values[subOffset + lane] ?? 0\n\t\t\t\tif (!Number.isFinite(value)) {\n\t\t\t\t\tthrow new InferError(\n\t\t\t\t\t\t`The Q4_K value at index ${subOffset + lane} must be finite; it received ${String(value)}.`,\n\t\t\t\t\t\t{ code: 'ARGUMENT', context: { format: 'Q4_K', index: subOffset + lane } },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tif (value < actualMin) actualMin = value\n\t\t\t\tif (value > actualMax) actualMax = value\n\t\t\t}\n\t\t\tconst low = actualMin < 0 ? actualMin : 0\n\t\t\tconst span = actualMax - low\n\t\t\tif (span <= 0) {\n\t\t\t\trawScales[sub] = 0\n\t\t\t\trawMins[sub] = -low\n\t\t\t} else {\n\t\t\t\tconst baseScale = span / 15\n\t\t\t\tconst baseMin = -low\n\t\t\t\tlet sumX = 0\n\t\t\t\tlet sumQ = 0\n\t\t\t\tlet sumQ2 = 0\n\t\t\t\tlet sumXQ = 0\n\t\t\t\tfor (let lane = 0; lane < 32; lane += 1) {\n\t\t\t\t\tconst value = values[subOffset + lane] ?? 0\n\t\t\t\t\tconst nibble = Math.max(0, Math.min(15, roundAway((value + baseMin) / baseScale)))\n\t\t\t\t\tsumX += value\n\t\t\t\t\tsumQ += nibble\n\t\t\t\t\tsumQ2 += nibble * nibble\n\t\t\t\t\tsumXQ += value * nibble\n\t\t\t\t}\n\t\t\t\tconst denom = 32 * sumQ2 - sumQ * sumQ\n\t\t\t\tif (denom > 0) {\n\t\t\t\t\tconst candidateScale = (32 * sumXQ - sumX * sumQ) / denom\n\t\t\t\t\tconst candidateMin = (candidateScale * sumQ - sumX) / 32\n\t\t\t\t\tif (candidateScale > 0 && candidateMin >= 0) {\n\t\t\t\t\t\trawScales[sub] = candidateScale\n\t\t\t\t\t\trawMins[sub] = candidateMin\n\t\t\t\t\t} else if (candidateMin < 0 && sumQ2 > 0 && sumXQ > 0) {\n\t\t\t\t\t\trawScales[sub] = sumXQ / sumQ2\n\t\t\t\t\t\trawMins[sub] = 0\n\t\t\t\t\t} else {\n\t\t\t\t\t\trawScales[sub] = baseScale\n\t\t\t\t\t\trawMins[sub] = baseMin\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\trawScales[sub] = baseScale\n\t\t\t\t\trawMins[sub] = baseMin\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst subScale = rawScales[sub] ?? 0\n\t\t\tconst subMin = rawMins[sub] ?? 0\n\t\t\tif (subScale > maxScale) maxScale = subScale\n\t\t\tif (subMin > maxMin) maxMin = subMin\n\t\t}\n\t\tconst dRaw = Math.fround(maxScale / 63)\n\t\tscratch[0] = dRaw > 65_504 ? 65_504 : dRaw\n\t\tconst dBits = narrowHalf(scratchBits[0] ?? 0)\n\t\tconst d = widenHalf(dBits)\n\t\tconst dminRaw = Math.fround(maxMin / 63)\n\t\tscratch[0] = dminRaw > 65_504 ? 65_504 : dminRaw\n\t\tconst dminBits = narrowHalf(scratchBits[0] ?? 0)\n\t\tconst dmin = widenHalf(dminBits)\n\t\tfor (let sub = 0; sub < 8; sub += 1) {\n\t\t\tconst sc = d > 0 ? Math.max(0, Math.min(63, roundAway((rawScales[sub] ?? 0) / d))) : 0\n\t\t\tconst mn = dmin > 0 ? Math.max(0, Math.min(63, roundAway((rawMins[sub] ?? 0) / dmin))) : 0\n\t\t\tquantizedScales[sub] = sc\n\t\t\tquantizedMins[sub] = mn\n\t\t\tconst step = Math.fround(d * sc)\n\t\t\tconst shift = Math.fround(dmin * mn)\n\t\t\tconst subOffset = valueOffset + sub * 32\n\t\t\tfor (let lane = 0; lane < 32; lane += 1) {\n\t\t\t\tconst value = values[subOffset + lane] ?? 0\n\t\t\t\tquants[sub * 32 + lane] =\n\t\t\t\t\tstep > 0 ? Math.max(0, Math.min(15, roundAway((value + shift) / step))) : 0\n\t\t\t}\n\t\t}\n\t\tconst outOffset = block * blockBytes\n\t\tview.setUint16(outOffset, dBits, true)\n\t\tview.setUint16(outOffset + 2, dminBits, true)\n\t\tfor (let group = 0; group < 4; group += 1) {\n\t\t\tconst scLo = quantizedScales[group] ?? 0\n\t\t\tconst scHi = quantizedScales[group + 4] ?? 0\n\t\t\tconst minLo = quantizedMins[group] ?? 0\n\t\t\tconst minHi = quantizedMins[group + 4] ?? 0\n\t\t\tout[outOffset + 4 + group] = (scLo & 63) | ((scHi >>> 4) << 6)\n\t\t\tout[outOffset + 8 + group] = (minLo & 63) | ((minHi >>> 4) << 6)\n\t\t\tout[outOffset + 12 + group] = (scHi & 0xf) | ((minHi & 0xf) << 4)\n\t\t}\n\t\tfor (let run = 0; run < 4; run += 1) {\n\t\t\tfor (let lane = 0; lane < 32; lane += 1) {\n\t\t\t\tconst low = quants[run * 64 + lane] ?? 0\n\t\t\t\tconst high = quants[run * 64 + 32 + lane] ?? 0\n\t\t\t\tout[outOffset + 16 + run * 32 + lane] = (low & 0xf) | ((high & 0xf) << 4)\n\t\t\t}\n\t\t}\n\t}\n\treturn out\n}\n\n/**\n * Encodes a single-precision tensor strip into an admitted `mergeGGUF` output format (`'F32'`,\n * `'BF16'`, `'Q8_0'`, or `'Q4_K'`).\n *\n * @param values - The single-precision values to encode\n * @param format - The target merged GGUF format\n * @returns The encoded little-endian tensor bytes\n *\n * @example\n * ```ts\n * encodeGGUFValues(new Float32Array(32).fill(1), 'Q8_0').length // 34\n * ```\n */\nexport function encodeGGUFValues(\n\tvalues: Float32Array,\n\tformat: MergeGGUFFormat,\n): Uint8Array<ArrayBuffer> {\n\tif (format === 'Q8_0') return encodeQ80Values(values)\n\tif (format === 'Q4_K') return encodeQ4KValues(values)\n\treturn encodeSafetensorsValues(values, format)\n}\n\n/**\n * Permutes `heads` head blocks of `block` floats across `outer` outer slices between Hugging Face\n * grouped order (`[keys, heads / keys]`) and GGUF tiled order (`[heads / keys, keys]`).\n *\n * @remarks\n * If `tiled` is `true`, maps Hugging Face grouped order to GGUF tiled order; if `false`, maps GGUF\n * tiled order back to Hugging Face grouped order. When `heads === keys`, returns a fresh copy with\n * identity order. Thrown with the `ARGUMENT` code when dimensions are invalid or inconsistent.\n *\n * @param values - The flat single-precision tensor slice of length `outer * heads * block`\n * @param outer - The number of outer rows preceding the head axis\n * @param heads - The number of value heads (`delta.values`)\n * @param keys - The number of key heads dividing `heads` (`delta.keys`)\n * @param block - The number of contiguous floats inside each head block\n * @param tiled - If `true`, converts grouped to tiled order; if `false`, converts tiled to grouped order\n * @returns The permuted single-precision array\n *\n * @example\n * ```ts\n * Array.from(permuteHeadBlocks(Float32Array.of(0, 1, 2, 3), 1, 4, 2, 1, true)) // [0, 2, 1, 3]\n * ```\n */\nexport function permuteHeadBlocks(\n\tvalues: Float32Array,\n\touter: number,\n\theads: number,\n\tkeys: number,\n\tblock: number,\n\ttiled: boolean,\n): Float32Array<ArrayBuffer> {\n\tif (\n\t\t!isSafeInteger(outer) ||\n\t\touter < 1 ||\n\t\t!isSafeInteger(heads) ||\n\t\theads < 1 ||\n\t\t!isSafeInteger(keys) ||\n\t\tkeys < 1 ||\n\t\t!isSafeInteger(block) ||\n\t\tblock < 1 ||\n\t\theads % keys !== 0 ||\n\t\tvalues.length !== outer * heads * block\n\t) {\n\t\tthrow new InferError(\n\t\t\t'The head permutation extents are invalid for the supplied tensor slice.',\n\t\t\t{\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\tcontext: { outer, heads, keys, block, length: values.length },\n\t\t\t},\n\t\t)\n\t}\n\tif (heads === keys) return Float32Array.from(values)\n\tconst ratio = heads / keys\n\tconst out = new Float32Array(values.length)\n\tconst sliceStride = heads * block\n\tfor (let row = 0; row < outer; row += 1) {\n\t\tconst rowOffset = row * sliceStride\n\t\tfor (let dstHead = 0; dstHead < heads; dstHead += 1) {\n\t\t\tconst srcHead = tiled\n\t\t\t\t? (dstHead % keys) * ratio + Math.floor(dstHead / keys)\n\t\t\t\t: (dstHead % ratio) * keys + Math.floor(dstHead / ratio)\n\t\t\tconst srcStart = rowOffset + srcHead * block\n\t\t\tconst dstStart = rowOffset + dstHead * block\n\t\t\tfor (let offset = 0; offset < block; offset += 1) {\n\t\t\t\tout[dstStart + offset] = values[srcStart + offset] ?? 0\n\t\t\t}\n\t\t}\n\t}\n\treturn out\n}\n\n/**\n * Permutes one Qwen3.5 Gated DeltaNet `AdapterPair` between Hugging Face grouped value-head order\n * and GGUF tiled value-head order when `architecture.delta.values !== architecture.delta.keys`.\n *\n * @remarks\n * Permutes `up` output rows on the `attn_qkv` value slice, `attn_gate`, `ssm_alpha`, and\n * `ssm_beta`, and permutes `down` input columns on `ssm_out`. Returns `pair` unchanged when\n * `architecture` omits `delta`, when `delta.values === delta.keys`, or when `pair.target` is an\n * attention or feed-forward target. Thrown with the `BINDING` code when a DeltaNet target's extents\n * disagree with `architecture.delta`.\n *\n * @param pair - The LoRA adapter pair\n * @param architecture - Optional base architecture carrying `delta` head counts\n * @param tiled - If `true`, converts Hugging Face grouped order to GGUF tiled order; if `false`, the inverse\n * @returns The permuted pair, or `pair` unchanged when identity applies\n *\n * @example\n * ```ts\n * permuteDeltaPair(pair, undefined, true) === pair // true\n * ```\n */\nexport function permuteDeltaPair(\n\tpair: AdapterPair,\n\tarchitecture: Architecture | undefined,\n\ttiled: boolean,\n): AdapterPair {\n\tconst delta = architecture?.delta\n\tif (delta === undefined || delta.values === delta.keys) return pair\n\tconst { keys, values, head } = delta\n\tif (\n\t\t!isSafeInteger(keys) ||\n\t\tkeys < 1 ||\n\t\t!isSafeInteger(values) ||\n\t\tvalues < 1 ||\n\t\tvalues % keys !== 0 ||\n\t\t!isSafeInteger(head) ||\n\t\thead < 1\n\t) {\n\t\tthrow new InferError('The delta architecture head counts are invalid for permutation.', {\n\t\t\tcode: 'FORMAT',\n\t\t\tcontext: { keys, values, head },\n\t\t})\n\t}\n\tif (pair.target === 'attn_qkv') {\n\t\tconst prefixRows = 2 * keys * head\n\t\tconst expectedRows = prefixRows + values * head\n\t\tif (pair.rows !== expectedRows) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The attn_qkv pair ${quoteFaultText(pair.name)} has ${pair.rows} rows; expected ${expectedRows}.`,\n\t\t\t\t{ code: 'BINDING', context: { name: pair.name, rows: pair.rows, expected: expectedRows } },\n\t\t\t)\n\t\t}\n\t\tconst prefixFloats = prefixRows * pair.rank\n\t\tconst valueSlice = permuteHeadBlocks(\n\t\t\tpair.up.subarray(prefixFloats),\n\t\t\t1,\n\t\t\tvalues,\n\t\t\tkeys,\n\t\t\thead * pair.rank,\n\t\t\ttiled,\n\t\t)\n\t\tconst up = new Float32Array(pair.up.length)\n\t\tup.set(pair.up.subarray(0, prefixFloats), 0)\n\t\tup.set(valueSlice, prefixFloats)\n\t\treturn { ...pair, up }\n\t}\n\tif (pair.target === 'attn_gate') {\n\t\tconst expectedRows = values * head\n\t\tif (pair.rows !== expectedRows) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The attn_gate pair ${quoteFaultText(pair.name)} has ${pair.rows} rows; expected ${expectedRows}.`,\n\t\t\t\t{ code: 'BINDING', context: { name: pair.name, rows: pair.rows, expected: expectedRows } },\n\t\t\t)\n\t\t}\n\t\treturn {\n\t\t\t...pair,\n\t\t\tup: permuteHeadBlocks(pair.up, 1, values, keys, head * pair.rank, tiled),\n\t\t}\n\t}\n\tif (pair.target === 'ssm_alpha' || pair.target === 'ssm_beta') {\n\t\tif (pair.rows !== values) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The ${pair.target} pair ${quoteFaultText(pair.name)} has ${pair.rows} rows; expected ${values}.`,\n\t\t\t\t{ code: 'BINDING', context: { name: pair.name, rows: pair.rows, expected: values } },\n\t\t\t)\n\t\t}\n\t\treturn {\n\t\t\t...pair,\n\t\t\tup: permuteHeadBlocks(pair.up, 1, values, keys, pair.rank, tiled),\n\t\t}\n\t}\n\tif (pair.target === 'ssm_out') {\n\t\tconst expectedColumns = values * head\n\t\tif (pair.columns !== expectedColumns) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The ssm_out pair ${quoteFaultText(pair.name)} has ${pair.columns} columns; expected ${expectedColumns}.`,\n\t\t\t\t{\n\t\t\t\t\tcode: 'BINDING',\n\t\t\t\t\tcontext: { name: pair.name, columns: pair.columns, expected: expectedColumns },\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\treturn {\n\t\t\t...pair,\n\t\t\tdown: permuteHeadBlocks(pair.down, pair.rank, values, keys, head, tiled),\n\t\t}\n\t}\n\treturn pair\n}\n\n/**\n * Reorders rows of a GGUF adjacent-pair rotary projection back into Hugging Face split-half\n * order, inverting `@orkestrel/infer`'s `interleaveRotary`.\n *\n * @remarks\n * Maps GGUF row `2j` and `2j + 1` inside each head of size `head` back to split-half rows `j` and\n * `j + head / 2`. Thrown with the `ARGUMENT` code when `heads`, `row`, or `bytes.length` do not\n * split cleanly into `heads` heads of an even row count.\n *\n * @param bytes - The row-major GGUF projection bytes\n * @param heads - The number of heads the rows split into\n * @param row - The byte length of one row\n * @returns A fresh array of the deinterleaved rows\n *\n * @example\n * ```ts\n * Array.from(deinterleaveRotary(Uint8Array.of(0, 2, 1, 3), 1, 1)) // [0, 1, 2, 3]\n * ```\n */\nexport function deinterleaveRotary(\n\tbytes: Uint8Array,\n\theads: number,\n\trow: number,\n): Uint8Array<ArrayBuffer> {\n\tif (!isSafeInteger(heads) || heads < 1 || !isSafeInteger(row) || row < 1) {\n\t\tthrow new InferError(\n\t\t\t`A rotary projection requires positive integer heads (${heads}) and row byte width (${row}).`,\n\t\t\t{ code: 'ARGUMENT', context: { bytes: bytes.length, heads, row } },\n\t\t)\n\t}\n\tconst rows = bytes.length / row\n\tconst head = rows / heads\n\tif (!Number.isInteger(rows) || !Number.isInteger(head) || head < 2 || head % 2 !== 0) {\n\t\tthrow new InferError(\n\t\t\t`A rotary projection of ${bytes.length} bytes in rows of ${row} does not split into ${heads} heads of an even size.`,\n\t\t\t{ code: 'ARGUMENT', context: { bytes: bytes.length, heads, row } },\n\t\t)\n\t}\n\tconst half = head / 2\n\tconst reordered = new Uint8Array(bytes.length)\n\tfor (let index = 0; index < rows; index += 1) {\n\t\tconst within = index % head\n\t\tconst destination = index - within + (within % 2) * half + Math.floor(within / 2)\n\t\treordered.set(bytes.subarray(index * row, (index + 1) * row), destination * row)\n\t}\n\treturn reordered\n}\n\n/**\n * Permutes `up` output rows of one rotary-interleaved `attn_q` or `attn_k` `AdapterPair` between\n * Hugging Face split-half order and GGUF adjacent-pair order.\n *\n * @remarks\n * Uses `@orkestrel/infer`'s `interleaveRotary` when `interleaved` is `true` (PEFT to GGUF) and\n * `deinterleaveRotary` when `interleaved` is `false` (GGUF to PEFT or safetensors merge), with\n * `architecture.queries` heads on `attn_q` and `architecture.groups` heads on `attn_k`. Returns\n * `pair` unchanged when `architecture` is absent, when the family is non-interleaved (`qwen35`),\n * or when `pair.target` is neither `attn_q` nor `attn_k`. Thrown with the `BINDING` code when\n * `pair.rows` disagrees with `heads * architecture.head`.\n *\n * @param pair - The LoRA adapter pair\n * @param architecture - Optional base architecture carrying rotary head counts\n * @param interleaved - If `true`, converts Hugging Face split-half to GGUF interleaved order; if `false`, the inverse\n * @returns The permuted pair, or `pair` unchanged when no rotary permutation applies\n *\n * @example\n * ```ts\n * permuteRotaryPair(pair, undefined, true) === pair // true\n * ```\n */\nexport function permuteRotaryPair(\n\tpair: AdapterPair,\n\tarchitecture: Architecture | undefined,\n\tinterleaved: boolean,\n): AdapterPair {\n\tif (architecture === undefined || !ARCHITECTURE_FAMILIES[architecture.family].interleaved) {\n\t\treturn pair\n\t}\n\tif (pair.target !== 'attn_q' && pair.target !== 'attn_k') return pair\n\tconst heads = pair.target === 'attn_q' ? architecture.queries : architecture.groups\n\tconst expectedRows = heads * architecture.head\n\tif (pair.rows !== expectedRows) {\n\t\tthrow new InferError(\n\t\t\t`The ${pair.target} pair ${quoteFaultText(pair.name)} has ${pair.rows} rows; expected ${expectedRows}.`,\n\t\t\t{ code: 'BINDING', context: { name: pair.name, rows: pair.rows, expected: expectedRows } },\n\t\t)\n\t}\n\tconst upBytes = new Uint8Array(pair.up.buffer, pair.up.byteOffset, pair.up.byteLength)\n\tconst rowBytes = pair.rank * 4\n\tconst reordered = interleaved\n\t\t? interleaveRotary(upBytes, heads, rowBytes)\n\t\t: deinterleaveRotary(upBytes, heads, rowBytes)\n\treturn { ...pair, up: new Float32Array(reordered.buffer) }\n}\n\n/**\n * Refuses omitting `architecture` when an adapter targets layout-sensitive projections requiring\n * head counts: `llama` rotary projections (`attn_q`, `attn_k`) or `qwen35` DeltaNet projections\n * (`attn_qkv`, `attn_gate`, `ssm_alpha`, `ssm_beta`, `ssm_out`).\n *\n * @remarks\n * Prevents silent row-order corruption when converting between GGUF and Hugging Face PEFT or\n * merging into Hugging Face safetensors. Thrown with the `ARGUMENT` code when `architecture` is\n * absent and any target in `targets` requires head-layout metadata.\n *\n * @param family - The decoder architecture family\n * @param targets - The LoRA targets present in the adapter\n * @param architecture - Optional base architecture supplied by the caller\n *\n * @example\n * ```ts\n * checkAdapterArchitecture('llama', ['ffn_down'], undefined)\n * ```\n */\nexport function checkAdapterArchitecture(\n\tfamily: ArchitectureFamily,\n\ttargets: readonly AdapterTarget[],\n\tarchitecture: Architecture | undefined,\n): void {\n\tif (architecture !== undefined) return\n\tconst requiredTarget =\n\t\tfamily === 'llama'\n\t\t\t? targets.find((target) => target === 'attn_q' || target === 'attn_k')\n\t\t\t: targets.find(\n\t\t\t\t\t(target) =>\n\t\t\t\t\t\ttarget === 'attn_qkv' ||\n\t\t\t\t\t\ttarget === 'attn_gate' ||\n\t\t\t\t\t\ttarget === 'ssm_alpha' ||\n\t\t\t\t\t\ttarget === 'ssm_beta' ||\n\t\t\t\t\t\ttarget === 'ssm_out',\n\t\t\t\t)\n\tif (requiredTarget !== undefined) {\n\t\tthrow new InferError(\n\t\t\t`Converting or merging ${quoteFaultText(family)} target ${quoteFaultText(requiredTarget)} requires the base architecture option to preserve head layout.`,\n\t\t\t{ code: 'ARGUMENT', context: { family, target: requiredTarget } },\n\t\t)\n\t}\n}\n\n/**\n * Adds a scaled LoRA delta `factor * (up[rowStart..rowStart+rowCount) @ down)` into one row strip\n * of a widened base weight matrix, accumulating in double precision and rounding each element with\n * `Math.fround`.\n *\n * @remarks\n * Operates on one strip at a time so streaming merges keep peak memory bounded independent of model\n * size. Thrown with the `ARGUMENT` code when strip extents or `factor` are invalid.\n *\n * @param base - The widened base strip of length `rowCount * pair.columns`\n * @param pair - The LoRA adapter pair in the base matrix's layout\n * @param rowStart - The zero-based first output row in the full base matrix\n * @param rowCount - The number of rows in `base`\n * @param factor - The effective LoRA scale `scale * (pair.alpha / pair.rank)`\n * @returns The merged single-precision strip\n *\n * @example\n * ```ts\n * addLoRAStrip(Float32Array.of(1, 2), pair, 0, 1, 1)\n * ```\n */\nexport function addLoRAStrip(\n\tbase: Float32Array,\n\tpair: AdapterPair,\n\trowStart: number,\n\trowCount: number,\n\tfactor: number,\n): Float32Array<ArrayBuffer> {\n\tconst { columns, rows, rank, down, up } = pair\n\tif (\n\t\t!isSafeInteger(rowStart) ||\n\t\trowStart < 0 ||\n\t\t!isSafeInteger(rowCount) ||\n\t\trowCount < 1 ||\n\t\trowStart + rowCount > rows ||\n\t\tbase.length !== rowCount * columns ||\n\t\t!isFiniteNumber(factor)\n\t) {\n\t\tthrow new InferError('The LoRA merge strip extents or factor are invalid.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { rowStart, rowCount, rows, columns, length: base.length, factor },\n\t\t})\n\t}\n\tconst out = new Float32Array(base.length)\n\tfor (let localRow = 0; localRow < rowCount; localRow += 1) {\n\t\tconst upOffset = (rowStart + localRow) * rank\n\t\tconst rowOffset = localRow * columns\n\t\tfor (let column = 0; column < columns; column += 1) {\n\t\t\tlet dot = 0\n\t\t\tfor (let inner = 0; inner < rank; inner += 1) {\n\t\t\t\tdot += (up[upOffset + inner] ?? 0) * (down[inner * columns + column] ?? 0)\n\t\t\t}\n\t\t\tout[rowOffset + column] = Math.fround((base[rowOffset + column] ?? 0) + factor * dot)\n\t\t}\n\t}\n\treturn out\n}\n\n/**\n * Serializes tensor entries and optional string metadata into one safetensors binary buffer.\n *\n * @remarks\n * Validates unique non-empty tensor names, admitted `SAFETENSORS_FORMATS` dtypes, non-negative\n * integer shapes, exact byte lengths, and the `SAFETENSORS_HEADER_LIMIT` header ceiling. Refuses\n * invalid entries with the `ARGUMENT` code.\n *\n * @param entries - The ordered tensors to serialize\n * @param metadata - Optional `__metadata__` string map stored in the safetensors header\n * @returns The serialized safetensors file bytes\n *\n * @example\n * ```ts\n * buildSafetensors([{ name: 'w', format: 'F32', shape: [1, 2], bytes: new Uint8Array(8) }]).length > 8 // true\n * ```\n */\nexport function buildSafetensors(\n\tentries: readonly SafetensorsWriteEntry[],\n\tmetadata?: Readonly<Record<string, string>>,\n): Uint8Array<ArrayBuffer> {\n\tconst seen = new Set<string>()\n\tconst layout: Array<{\n\t\treadonly name: string\n\t\treadonly format: SafetensorsFormat\n\t\treadonly shape: readonly number[]\n\t\treadonly bytes: Uint8Array\n\t\treadonly start: number\n\t\treadonly end: number\n\t}> = []\n\tlet dataLength = 0\n\tfor (let index = 0; index < entries.length; index += 1) {\n\t\tconst entry = entries[index]\n\t\tif (entry === undefined) continue\n\t\tif (!isString(entry.name) || entry.name.length === 0 || entry.name === '__metadata__') {\n\t\t\tthrow new InferError(\n\t\t\t\t`The safetensors tensor name ${quoteFaultText(entry.name)} is invalid.`,\n\t\t\t\t{\n\t\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\t\tcontext: { name: entry.name },\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\tif (seen.has(entry.name)) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The safetensors tensor name ${quoteFaultText(entry.name)} is duplicated.`,\n\t\t\t\t{\n\t\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\t\tcontext: { name: entry.name },\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\tseen.add(entry.name)\n\t\tif (!SAFETENSORS_FORMATS.some((admitted) => admitted === entry.format)) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The safetensors tensor ${quoteFaultText(entry.name)} declares unsupported format ${quoteFaultText(entry.format)}.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { name: entry.name, format: entry.format } },\n\t\t\t)\n\t\t}\n\t\tif (\n\t\t\t!isArray(entry.shape) ||\n\t\t\t!entry.shape.every((extent) => isSafeInteger(extent) && extent >= 0)\n\t\t) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The safetensors tensor ${quoteFaultText(entry.name)} carries an invalid shape.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { name: entry.name } },\n\t\t\t)\n\t\t}\n\t\tconst elements = entry.shape.reduce((product, extent) => product * extent, 1)\n\t\tconst expectedBytes = elements * GGUF_BLOCKS[entry.format].bytes\n\t\tif (!isSafeInteger(expectedBytes) || entry.bytes.byteLength !== expectedBytes) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The safetensors tensor ${quoteFaultText(entry.name)} carries ${entry.bytes.byteLength} bytes; expected ${expectedBytes}.`,\n\t\t\t\t{\n\t\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\t\tcontext: { name: entry.name, actual: entry.bytes.byteLength, expected: expectedBytes },\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\tconst start = dataLength\n\t\tconst end = start + expectedBytes\n\t\tdataLength = end\n\t\tlayout.push({\n\t\t\tname: entry.name,\n\t\t\tformat: entry.format,\n\t\t\tshape: [...entry.shape],\n\t\t\tbytes: entry.bytes,\n\t\t\tstart,\n\t\t\tend,\n\t\t})\n\t}\n\tconst headerEntries: Array<readonly [string, unknown]> = []\n\tif (metadata !== undefined) {\n\t\tconst metaPairs = Object.entries(metadata)\n\t\tif (!metaPairs.every(([, value]) => isString(value))) {\n\t\t\tthrow new InferError('Safetensors __metadata__ values must be strings.', { code: 'ARGUMENT' })\n\t\t}\n\t\tif (metaPairs.length > 0) {\n\t\t\theaderEntries.push(['__metadata__', Object.fromEntries(metaPairs)])\n\t\t}\n\t}\n\tfor (const item of layout) {\n\t\theaderEntries.push([\n\t\t\titem.name,\n\t\t\t{ dtype: item.format, shape: item.shape, data_offsets: [item.start, item.end] },\n\t\t])\n\t}\n\tconst headerBytes = UTF8_ENCODER.encode(JSON.stringify(Object.fromEntries(headerEntries)))\n\tif (headerBytes.byteLength > SAFETENSORS_HEADER_LIMIT) {\n\t\tthrow new InferError(\n\t\t\t`The safetensors header spans ${headerBytes.byteLength} bytes, past the ${SAFETENSORS_HEADER_LIMIT}-byte limit.`,\n\t\t\t{ code: 'ARGUMENT', context: { length: headerBytes.byteLength } },\n\t\t)\n\t}\n\tconst total = 8 + headerBytes.byteLength + dataLength\n\tconst out = new Uint8Array(total)\n\tnew DataView(out.buffer).setBigUint64(0, BigInt(headerBytes.byteLength), true)\n\tout.set(headerBytes, 8)\n\tconst dataStart = 8 + headerBytes.byteLength\n\tfor (const item of layout) {\n\t\tout.set(item.bytes, dataStart + item.start)\n\t}\n\treturn out\n}\n\n/**\n * Serializes validated LoRA adapter options or an `AdapterInterface` into GGUF v3 adapter bytes\n * readable by `@orkestrel/infer`'s `readAdapter` and `llama-server --lora`.\n *\n * @remarks\n * Writes `general.type = \"adapter\"`, `adapter.type = \"lora\"`, `general.architecture`,\n * `adapter.lora.alpha`, optional `orkestrel.base`, and canonical `F32` `.lora_a` (`[columns, rank]`)\n * and `.lora_b` (`[rank, rows]`) tensors aligned to `GGUF_ALIGNMENT`. Refuses per-pair alpha drift\n * with the `UNSUPPORTED` code.\n *\n * @param options - The validated adapter options or live adapter\n * @returns The serialized GGUF v3 LoRA adapter bytes\n *\n * @example\n * ```ts\n * const bytes = buildAdapterGGUF(adapter)\n * ```\n */\nexport function buildAdapterGGUF(\n\toptions: AdapterOptions | AdapterInterface,\n): Uint8Array<ArrayBuffer> {\n\tcheckAdapterOptions(options)\n\tconst mismatchedAlpha = options.pairs.find((pair) => pair.alpha !== options.alpha)\n\tif (mismatchedAlpha !== undefined) {\n\t\tthrow new InferError(\n\t\t\t`The adapter pair ${quoteFaultText(mismatchedAlpha.name)} carries alpha ${mismatchedAlpha.alpha}, differing from adapter alpha ${options.alpha}.`,\n\t\t\t{\n\t\t\t\tcode: 'UNSUPPORTED',\n\t\t\t\tcontext: {\n\t\t\t\t\tname: mismatchedAlpha.name,\n\t\t\t\t\tpairAlpha: mismatchedAlpha.alpha,\n\t\t\t\t\talpha: options.alpha,\n\t\t\t\t},\n\t\t\t},\n\t\t)\n\t}\n\tconst ordered = [...options.pairs].toSorted(\n\t\t(left, right) =>\n\t\t\tleft.layer - right.layer ||\n\t\t\tADAPTER_TARGETS.indexOf(left.target) - ADAPTER_TARGETS.indexOf(right.target),\n\t)\n\tconst metadata = new Map<string, GGUFValue>([\n\t\t[ADAPTER_KEYS.role, { encoding: 'string', value: 'adapter' }],\n\t\t[ADAPTER_KEYS.format, { encoding: 'string', value: 'lora' }],\n\t\t[GGUF_KEYS.architecture, { encoding: 'string', value: options.family }],\n\t\t[ADAPTER_KEYS.alpha, { encoding: 'float32', value: options.alpha }],\n\t\t...(options.base === undefined\n\t\t\t? []\n\t\t\t: [[ADAPTER_KEYS.base, { encoding: 'string', value: options.base }] as const]),\n\t])\n\tconst items = ordered.flatMap((pair) => [\n\t\t{\n\t\t\tname: `${pair.name}.lora_a`,\n\t\t\tdimensions: [pair.columns, pair.rank],\n\t\t\tbytes: encodeSafetensorsValues(pair.down, 'F32'),\n\t\t},\n\t\t{\n\t\t\tname: `${pair.name}.lora_b`,\n\t\t\tdimensions: [pair.rank, pair.rows],\n\t\t\tbytes: encodeSafetensorsValues(pair.up, 'F32'),\n\t\t},\n\t])\n\tconst tensors: GGUFTensor[] = []\n\tlet offset = 0\n\tfor (let index = 0; index < items.length; index += 1) {\n\t\tconst item = items[index]\n\t\tif (item === undefined) continue\n\t\ttensors.push({\n\t\t\tname: item.name,\n\t\t\tdimensions: item.dimensions,\n\t\t\tformat: 'F32',\n\t\t\toffset,\n\t\t})\n\t\toffset = alignOffset(offset + item.bytes.byteLength, GGUF_ALIGNMENT)\n\t}\n\tconst data = new Uint8Array(offset)\n\tfor (let index = 0; index < items.length; index += 1) {\n\t\tconst item = items[index]\n\t\tconst tensor = tensors[index]\n\t\tif (item === undefined || tensor === undefined) continue\n\t\tdata.set(item.bytes, tensor.offset)\n\t}\n\treturn buildGGUF(metadata, tensors, data)\n}\n\n/**\n * Serializes validated LoRA adapter options or an `AdapterInterface` into a Hugging Face `PEFTBundle`\n * (`adapter_config.json` record and `adapter_model.safetensors` bytes).\n *\n * @remarks\n * Uses `PEFT_LAYERS_PREFIX` for `llama` and `PEFT_QWEN35_PREFIX` for `qwen35`, reverses each\n * 2-element GGUF dimension tuple to safetensors row-major shape (`[rank, columns]` and `[rows, rank]`),\n * deinterleaves `llama` `attn_q` and `attn_k` rotary `up` rows to Hugging Face split-half order,\n * and applies the inverse 4B value-head permutation when `conversion.architecture.delta` has\n * `values !== keys`. Refuses omitting `conversion.architecture` with `ARGUMENT` whenever `llama`\n * targets `attn_q`/`attn_k` or `qwen35` targets DeltaNet projections, refuses mixed ranks or\n * per-pair alpha drift with `UNSUPPORTED`, and refuses family or target mismatches with `BINDING`.\n *\n * @param options - The validated adapter options or live adapter\n * @param conversion - Conversion context carrying `architecture` or `family`\n * @returns The serialized `PEFTBundle`\n *\n * @example\n * ```ts\n * const bundle = buildAdapterPEFT(adapter, { architecture })\n * bundle.config.peft_type // 'LORA'\n * ```\n */\nexport function buildAdapterPEFT(\n\toptions: AdapterOptions | AdapterInterface,\n\tconversion: PEFTConversionOptions = {},\n): PEFTBundle {\n\tcheckAdapterOptions(options)\n\tif (conversion.family !== undefined && conversion.family !== options.family) {\n\t\tthrow new InferError(\n\t\t\t`The conversion family ${quoteFaultText(conversion.family)} disagrees with adapter family ${quoteFaultText(options.family)}.`,\n\t\t\t{ code: 'BINDING', context: { expected: conversion.family, actual: options.family } },\n\t\t)\n\t}\n\tcheckAdapterArchitecture(\n\t\toptions.family,\n\t\toptions.pairs.map((pair) => pair.target),\n\t\tconversion.architecture,\n\t)\n\tif (conversion.architecture !== undefined) {\n\t\tcheckAdapterBinding(new Adapter(options), conversion.architecture)\n\t}\n\tconst [firstPair] = options.pairs\n\tif (firstPair === undefined) {\n\t\tthrow new InferError('The adapter holds no LoRA pairs.', { code: 'ARGUMENT' })\n\t}\n\tconst rank = firstPair.rank\n\tconst mismatchedRank = options.pairs.find((pair) => pair.rank !== rank)\n\tif (mismatchedRank !== undefined) {\n\t\tthrow new InferError(\n\t\t\t`The adapter pair ${quoteFaultText(mismatchedRank.name)} has rank ${mismatchedRank.rank}, differing from PEFT rank ${rank}.`,\n\t\t\t{\n\t\t\t\tcode: 'UNSUPPORTED',\n\t\t\t\tcontext: { name: mismatchedRank.name, rank: mismatchedRank.rank, expected: rank },\n\t\t\t},\n\t\t)\n\t}\n\tconst mismatchedAlpha = options.pairs.find((pair) => pair.alpha !== options.alpha)\n\tif (mismatchedAlpha !== undefined) {\n\t\tthrow new InferError(\n\t\t\t`The adapter pair ${quoteFaultText(mismatchedAlpha.name)} carries alpha ${mismatchedAlpha.alpha}, differing from adapter alpha ${options.alpha}.`,\n\t\t\t{\n\t\t\t\tcode: 'UNSUPPORTED',\n\t\t\t\tcontext: {\n\t\t\t\t\tname: mismatchedAlpha.name,\n\t\t\t\t\tpairAlpha: mismatchedAlpha.alpha,\n\t\t\t\t\talpha: options.alpha,\n\t\t\t\t},\n\t\t\t},\n\t\t)\n\t}\n\tconst ordered = [...options.pairs].toSorted(\n\t\t(left, right) =>\n\t\t\tleft.layer - right.layer ||\n\t\t\tADAPTER_TARGETS.indexOf(left.target) - ADAPTER_TARGETS.indexOf(right.target),\n\t)\n\tconst prefix = options.family === 'qwen35' ? PEFT_QWEN35_PREFIX : PEFT_LAYERS_PREFIX\n\tconst leafOrder: string[] = []\n\tconst entries: SafetensorsWriteEntry[] = []\n\tfor (const rawPair of ordered) {\n\t\tconst spec = PEFT_TARGET_SPECS[rawPair.target]\n\t\tif (!spec.families.includes(options.family)) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The LoRA target ${quoteFaultText(rawPair.target)} is not admitted by family ${quoteFaultText(options.family)}.`,\n\t\t\t\t{ code: 'BINDING', context: { target: rawPair.target, family: options.family } },\n\t\t\t)\n\t\t}\n\t\tconst pair = permuteRotaryPair(\n\t\t\tpermuteDeltaPair(rawPair, conversion.architecture, false),\n\t\t\tconversion.architecture,\n\t\t\tfalse,\n\t\t)\n\t\tif (!leafOrder.includes(spec.leaf)) leafOrder.push(spec.leaf)\n\t\tconst stem = `${prefix}${pair.layer}.${spec.module}`\n\t\tentries.push(\n\t\t\t{\n\t\t\t\tname: `${stem}.lora_A.weight`,\n\t\t\t\tformat: 'F32',\n\t\t\t\tshape: [pair.rank, pair.columns],\n\t\t\t\tbytes: encodeSafetensorsValues(pair.down, 'F32'),\n\t\t\t},\n\t\t\t{\n\t\t\t\tname: `${stem}.lora_B.weight`,\n\t\t\t\tformat: 'F32',\n\t\t\t\tshape: [pair.rows, pair.rank],\n\t\t\t\tbytes: encodeSafetensorsValues(pair.up, 'F32'),\n\t\t\t},\n\t\t)\n\t}\n\tconst config: PEFTConfig = {\n\t\tpeft_type: 'LORA',\n\t\tr: rank,\n\t\tlora_alpha: options.alpha,\n\t\ttarget_modules: leafOrder,\n\t\tbias: 'none',\n\t\tuse_rslora: false,\n\t\tuse_dora: false,\n\t\ttask_type: 'CAUSAL_LM',\n\t}\n\treturn { config, weights: buildSafetensors(entries, { format: 'pt' }) }\n}\n\n/**\n * Reads and validates a Hugging Face `PEFTBundle` into `AdapterOptions` ready for `new Adapter(...)`\n * or `buildAdapterGGUF(...)`.\n *\n * @remarks\n * Admits canonical `PEFT_LAYERS_PREFIX` for `llama` and both `PEFT_QWEN35_PREFIX` and the\n * `PEFT_LAYERS_PREFIX` alias for `qwen35`. Widens `F32`, `F16`, and `BF16` tensors to single\n * precision, interleaves `llama` `attn_q` and `attn_k` rotary `up` rows to GGUF order, applies\n * the 4B value-head permutation when `options.architecture.delta` has `values !== keys`, refuses\n * omitting `options.architecture` with `ARGUMENT` whenever `llama` targets `attn_q`/`attn_k` or\n * `qwen35` targets DeltaNet projections, refuses unsupported PEFT options (`use_rslora`,\n * `use_dora`, `bias !== 'none'`, `peft_type !== 'LORA'`) with `UNSUPPORTED`, and refuses malformed\n * tensors with `FORMAT`.\n *\n * @param bundle - The PEFT configuration and safetensors weights\n * @param options - Conversion family, architecture, base digest, and abort signal\n * @returns The validated `AdapterOptions`\n *\n * @example\n * ```ts\n * const adapterOptions = await readAdapterPEFT(bundle, { architecture })\n * ```\n */\nexport async function readAdapterPEFT(\n\tbundle: PEFTBundle,\n\toptions: PEFTConversionOptions = {},\n): Promise<AdapterOptions> {\n\tcheckSignal(options.signal, 'The PEFT adapter read')\n\tif (!isObject(bundle)) {\n\t\tthrow new InferError('The PEFT bundle must be an object carrying config and weights.', {\n\t\t\tcode: 'FORMAT',\n\t\t})\n\t}\n\tconst config = checkPEFTConfig(Reflect.get(bundle, 'config'))\n\tconst weights: unknown = Reflect.get(bundle, 'weights')\n\tif (!isUint8Array(weights)) {\n\t\tthrow new InferError('The PEFT bundle requires Uint8Array weights.', { code: 'FORMAT' })\n\t}\n\tif (\n\t\toptions.family !== undefined &&\n\t\toptions.architecture !== undefined &&\n\t\toptions.family !== options.architecture.family\n\t) {\n\t\tthrow new InferError(\n\t\t\t`The conversion family ${quoteFaultText(options.family)} disagrees with architecture family ${quoteFaultText(options.architecture.family)}.`,\n\t\t\t{\n\t\t\t\tcode: 'BINDING',\n\t\t\t\tcontext: { family: options.family, architecture: options.architecture.family },\n\t\t\t},\n\t\t)\n\t}\n\tif (options.base !== undefined && !SHA256_PATTERN.test(options.base)) {\n\t\tthrow new InferError(\n\t\t\t`The base digest ${quoteFaultText(options.base)} must be a 64-character lowercase SHA-256 hex string.`,\n\t\t\t{ code: 'ARGUMENT', context: { base: options.base } },\n\t\t)\n\t}\n\tconst [tensors, dataStart] = readSafetensors(weights)\n\tif (tensors.length === 0) {\n\t\tthrow new InferError('The PEFT safetensors file holds no LoRA tensors.', { code: 'FORMAT' })\n\t}\n\tconst moduleToTarget = new Map<string, AdapterTarget>(\n\t\tADAPTER_TARGETS.map((target) => [PEFT_TARGET_SPECS[target].module, target]),\n\t)\n\tconst grouped = new Map<\n\t\tstring,\n\t\t{\n\t\t\treadonly layer: number\n\t\t\treadonly target: AdapterTarget\n\t\t\treadonly a?: SafetensorsTensor\n\t\t\treadonly b?: SafetensorsTensor\n\t\t}\n\t>()\n\tconst languageModelFlags: boolean[] = []\n\tconst qwenOnlyFlags: boolean[] = []\n\tfor (const tensor of tensors) {\n\t\tconst match = PEFT_TENSOR_PATTERN.exec(tensor.name)\n\t\tconst languageModel = match?.[1]\n\t\tconst rawLayer = match?.[2]\n\t\tconst modulePath = match?.[3]\n\t\tconst side = match?.[4]\n\t\tif (\n\t\t\tmatch === null ||\n\t\t\trawLayer === undefined ||\n\t\t\tmodulePath === undefined ||\n\t\t\t(side !== 'A' && side !== 'B')\n\t\t) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The PEFT tensor ${quoteFaultText(tensor.name)} does not name a supported LoRA target pair.`,\n\t\t\t\t{ code: 'FORMAT', context: { name: tensor.name } },\n\t\t\t)\n\t\t}\n\t\tconst target = moduleToTarget.get(modulePath)\n\t\tif (target === undefined) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The PEFT tensor ${quoteFaultText(tensor.name)} names unsupported module ${quoteFaultText(modulePath)}.`,\n\t\t\t\t{ code: 'FORMAT', context: { name: tensor.name, module: modulePath } },\n\t\t\t)\n\t\t}\n\t\tconst layer = Number(rawLayer)\n\t\tif (!isSafeInteger(layer) || layer < 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The PEFT tensor ${quoteFaultText(tensor.name)} names an out-of-range layer index.`,\n\t\t\t\t{ code: 'FORMAT', context: { name: tensor.name, layer: rawLayer } },\n\t\t\t)\n\t\t}\n\t\tconst [dim0, dim1] = tensor.dimensions\n\t\tif (\n\t\t\ttensor.dimensions.length !== 2 ||\n\t\t\tdim0 === undefined ||\n\t\t\tdim1 === undefined ||\n\t\t\t!isSafeInteger(dim0) ||\n\t\t\tdim0 < 1 ||\n\t\t\t!isSafeInteger(dim1) ||\n\t\t\tdim1 < 1\n\t\t) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The PEFT tensor ${quoteFaultText(tensor.name)} has extents [${tensor.dimensions.join(', ')}]; LoRA tensors are 2D with positive extents.`,\n\t\t\t\t{ code: 'FORMAT', context: { name: tensor.name, dimensions: tensor.dimensions } },\n\t\t\t)\n\t\t}\n\t\tif (languageModel !== undefined) languageModelFlags.push(true)\n\t\tif (!PEFT_TARGET_SPECS[target].families.includes('llama')) qwenOnlyFlags.push(true)\n\t\tconst name = `blk.${layer}.${target}.weight`\n\t\tconst prior = grouped.get(name)\n\t\tif ((side === 'A' && prior?.a !== undefined) || (side === 'B' && prior?.b !== undefined)) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The PEFT adapter holds a duplicate lora_${side} tensor for ${quoteFaultText(name)}.`,\n\t\t\t\t{ code: 'FORMAT', context: { name, side } },\n\t\t\t)\n\t\t}\n\t\tgrouped.set(name, {\n\t\t\tlayer,\n\t\t\ttarget,\n\t\t\t...(prior?.a === undefined ? {} : { a: prior.a }),\n\t\t\t...(prior?.b === undefined ? {} : { b: prior.b }),\n\t\t\t...(side === 'A' ? { a: tensor } : { b: tensor }),\n\t\t})\n\t}\n\tconst family: ArchitectureFamily =\n\t\toptions.architecture?.family ??\n\t\toptions.family ??\n\t\t(languageModelFlags.length > 0 || qwenOnlyFlags.length > 0 ? 'qwen35' : 'llama')\n\tif (family === 'llama' && (languageModelFlags.length > 0 || qwenOnlyFlags.length > 0)) {\n\t\tthrow new InferError(\n\t\t\t'The PEFT adapter contains Qwen3.5 prefix or Gated DeltaNet targets incompatible with llama.',\n\t\t\t{ code: 'BINDING', context: { family } },\n\t\t)\n\t}\n\tconst ordered = [...grouped.entries()].toSorted(\n\t\t([, left], [, right]) =>\n\t\t\tleft.layer - right.layer ||\n\t\t\tADAPTER_TARGETS.indexOf(left.target) - ADAPTER_TARGETS.indexOf(right.target),\n\t)\n\tcheckAdapterArchitecture(\n\t\tfamily,\n\t\tordered.map(([, entry]) => entry.target),\n\t\toptions.architecture,\n\t)\n\tconst pairs: AdapterPair[] = []\n\tfor (const [name, entry] of ordered) {\n\t\tif (entry.a === undefined || entry.b === undefined) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The PEFT adapter pair ${quoteFaultText(name)} is incomplete; every LoRA target requires both lora_A and lora_B.`,\n\t\t\t\t{ code: 'FORMAT', context: { name } },\n\t\t\t)\n\t\t}\n\t\tconst [columns, rankA] = entry.a.dimensions\n\t\tconst [rankB, rows] = entry.b.dimensions\n\t\tif (\n\t\t\tcolumns === undefined ||\n\t\t\trankA === undefined ||\n\t\t\trankB === undefined ||\n\t\t\trows === undefined ||\n\t\t\trankA !== rankB ||\n\t\t\trankA !== config.r\n\t\t) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The PEFT adapter pair ${quoteFaultText(name)} has ranks (${String(rankA)}, ${String(rankB)}) disagreeing with config r=${config.r}.`,\n\t\t\t\t{ code: 'FORMAT', context: { name, rankA, rankB, expected: config.r } },\n\t\t\t)\n\t\t}\n\t\tconst down = widenTensor(\n\t\t\tweights.subarray(\n\t\t\t\tdataStart + entry.a.offset,\n\t\t\t\tdataStart + entry.a.offset + computeTensorBytes(entry.a),\n\t\t\t),\n\t\t\tentry.a.format,\n\t\t)\n\t\tconst up = widenTensor(\n\t\t\tweights.subarray(\n\t\t\t\tdataStart + entry.b.offset,\n\t\t\t\tdataStart + entry.b.offset + computeTensorBytes(entry.b),\n\t\t\t),\n\t\t\tentry.b.format,\n\t\t)\n\t\tif (!down.every(Number.isFinite) || !up.every(Number.isFinite)) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The PEFT adapter pair ${quoteFaultText(name)} holds a non-finite weight value.`,\n\t\t\t\t{ code: 'FORMAT', context: { name } },\n\t\t\t)\n\t\t}\n\t\tconst spec = ADAPTER_TARGET_SPECS[entry.target]\n\t\tconst rawPair: AdapterPair = {\n\t\t\tname,\n\t\t\tlayer: entry.layer,\n\t\t\tgroup: spec.group,\n\t\t\tslot: spec.slot,\n\t\t\ttarget: entry.target,\n\t\t\tcolumns,\n\t\t\trows,\n\t\t\trank: rankA,\n\t\t\talpha: config.lora_alpha,\n\t\t\tdown,\n\t\t\tup,\n\t\t}\n\t\tpairs.push(\n\t\t\tpermuteRotaryPair(\n\t\t\t\tpermuteDeltaPair(rawPair, options.architecture, true),\n\t\t\t\toptions.architecture,\n\t\t\t\ttrue,\n\t\t\t),\n\t\t)\n\t}\n\tconst ownedBytes = new Uint8Array(weights)\n\tconst digest = await digestBytes(ownedBytes)\n\tcheckSignal(options.signal, 'The PEFT adapter read')\n\tconst adapterOptions: AdapterOptions = {\n\t\tdigest,\n\t\tfamily,\n\t\talpha: config.lora_alpha,\n\t\t...(options.base === undefined ? {} : { base: options.base }),\n\t\tpairs: Object.freeze(pairs),\n\t}\n\tif (options.architecture !== undefined) {\n\t\tcheckAdapterBinding(new Adapter(adapterOptions), options.architecture)\n\t}\n\treturn adapterOptions\n}\n\n/**\n * Converts a GGUF v3 LoRA adapter into a Hugging Face `PEFTBundle`.\n *\n * @remarks\n * Reads the GGUF adapter through `@orkestrel/infer`'s `readAdapter`, checks optional family and\n * architecture binding, deinterleaves `llama` `attn_q` and `attn_k` rotary `up` rows, applies the\n * inverse 4B value-head permutation when `options.architecture` has `delta.values !== delta.keys`,\n * refuses omitting `options.architecture` with `ARGUMENT` for `llama` `attn_q`/`attn_k` or\n * `qwen35` DeltaNet targets, and serializes `adapter_config.json` and `adapter_model.safetensors`.\n *\n * @param source - The GGUF v3 LoRA adapter byte source or byte array\n * @param options - Conversion family, architecture, and abort signal\n * @returns The converted `PEFTBundle`\n *\n * @example\n * ```ts\n * const bundle = await ggufToPEFT(ggufBytes, { architecture })\n * ```\n */\nexport async function ggufToPEFT(\n\tsource: ByteSourceInterface | Uint8Array,\n\toptions: PEFTConversionOptions = {},\n): Promise<PEFTBundle> {\n\tcheckSignal(options.signal, 'The GGUF-to-PEFT conversion')\n\tconst byteSource: ByteSourceInterface = isUint8Array(source)\n\t\t? new MemorySource(new Uint8Array(source))\n\t\t: source\n\tconst adapterOptions = await readAdapter(byteSource, options.signal)\n\treturn buildAdapterPEFT(adapterOptions, options)\n}\n\n/**\n * Converts a Hugging Face `PEFTBundle` into GGUF v3 LoRA adapter bytes.\n *\n * @remarks\n * Validates `bundle.config` and `bundle.weights` through `readAdapterPEFT`, interleaves `llama`\n * `attn_q` and `attn_k` rotary `up` rows, applies the 4B value-head permutation when\n * `options.architecture` has `delta.values !== delta.keys`, refuses omitting `options.architecture`\n * with `ARGUMENT` for `llama` `attn_q`/`attn_k` or `qwen35` DeltaNet targets, and serializes\n * canonical `F32` GGUF v3 LoRA bytes through `buildAdapterGGUF`.\n *\n * @param bundle - The PEFT configuration and safetensors weights\n * @param options - Conversion family, architecture, base digest, and abort signal\n * @returns The serialized GGUF v3 LoRA adapter bytes\n *\n * @example\n * ```ts\n * const ggufBytes = await peftToGGUF(bundle, { architecture })\n * ```\n */\nexport async function peftToGGUF(\n\tbundle: PEFTBundle,\n\toptions: PEFTConversionOptions = {},\n): Promise<Uint8Array<ArrayBuffer>> {\n\tconst adapterOptions = await readAdapterPEFT(bundle, options)\n\treturn buildAdapterGGUF(adapterOptions)\n}\n\n/**\n * Streams an async chunk iterable into a `ByteSinkInterface`, closing on completion and aborting\n * the sink on error or signal cancellation.\n *\n * @remarks\n * Returns the total number of bytes written. Thrown with the `ARGUMENT` code when `sink` fails\n * `isByteSink`, and with the `ABORT` code when `signal` aborts.\n *\n * @param chunks - The async iterable of byte chunks to write\n * @param sink - The destination byte sink\n * @param signal - Cancels the write between chunks\n * @returns Total bytes written to `sink`\n *\n * @example\n * ```ts\n * const written = await writeByteSink(mergeGGUF({ source, adapter }), sink)\n * ```\n */\nexport async function writeByteSink(\n\tchunks: AsyncIterable<Uint8Array>,\n\tsink: ByteSinkInterface,\n\tsignal?: AbortSignal,\n): Promise<number> {\n\tif (!isByteSink(sink)) {\n\t\tthrow new InferError('The destination must implement ByteSinkInterface.', { code: 'ARGUMENT' })\n\t}\n\tcheckSignal(signal, 'The byte sink write')\n\tconst sizes: number[] = []\n\ttry {\n\t\tfor await (const chunk of chunks) {\n\t\t\tcheckSignal(signal, 'The byte sink write')\n\t\t\tawait sink.write(chunk)\n\t\t\tsizes.push(chunk.byteLength)\n\t\t}\n\t\tcheckSignal(signal, 'The byte sink write')\n\t\tawait sink.close()\n\t} catch (error) {\n\t\tawait attempt(() => sink.abort?.(error))\n\t\tthrow error\n\t}\n\treturn sizes.reduce((sum, length) => sum + length, 0)\n}\n\n/**\n * Reads only the safetensors JSON header from a `ByteSourceInterface` without buffering the tensor\n * payload bytes.\n *\n * @remarks\n * Validates the 8-byte little-endian header length, the `SAFETENSORS_HEADER_LIMIT` ceiling,\n * well-formed UTF-8 JSON, every tensor descriptor through `@orkestrel/infer`'s `readSafetensorsEntry`,\n * and non-overlapping byte ranges through `findTensorOverlap`.\n *\n * @param source - The safetensors byte source\n * @param signal - Cancels the header read; rejects with the `ABORT` code\n * @returns The parsed tensor descriptors, the data section start offset, and optional string metadata\n *\n * @example\n * ```ts\n * const header = await readSafetensorsHeader(source)\n * header.tensors.length // tensor count\n * ```\n */\nexport async function readSafetensorsHeader(\n\tsource: ByteSourceInterface,\n\tsignal?: AbortSignal,\n): Promise<{\n\treadonly tensors: readonly SafetensorsTensor[]\n\treadonly offset: number\n\treadonly metadata?: Readonly<Record<string, string>>\n}> {\n\tcheckSignal(signal, 'The safetensors header read')\n\tif (source.size < 8) {\n\t\tthrow new InferError(\n\t\t\t`The safetensors file holds ${source.size} bytes, fewer than its 8-byte header length.`,\n\t\t\t{ code: 'FORMAT', context: { size: source.size } },\n\t\t)\n\t}\n\tconst prefix = await source.read(0, 8, signal)\n\tconst declared = new DataView(prefix.buffer, prefix.byteOffset, prefix.byteLength).getBigUint64(\n\t\t0,\n\t\ttrue,\n\t)\n\tconst maxLength = Math.min(SAFETENSORS_HEADER_LIMIT, source.size - 8)\n\tif (declared > BigInt(maxLength)) {\n\t\tthrow new InferError(\n\t\t\t`The safetensors header declares ${declared} bytes, past the file or the ${SAFETENSORS_HEADER_LIMIT}-byte limit.`,\n\t\t\t{ code: 'FORMAT', context: { length: String(declared) } },\n\t\t)\n\t}\n\tconst headerLength = Number(declared)\n\tconst headerBytes = await source.read(8, headerLength, signal)\n\tconst decoded = attempt(() => new TextDecoder('utf-8', { fatal: true }).decode(headerBytes))\n\tif (!decoded.success) {\n\t\tthrow new InferError('The safetensors header is not well-formed UTF-8.', { code: 'FORMAT' })\n\t}\n\tconst parsed = parseJSON(decoded.value)\n\tif (!isRecord(parsed)) {\n\t\tthrow new InferError('The safetensors header must be a JSON object.', { code: 'FORMAT' })\n\t}\n\tconst dataStart = 8 + headerLength\n\tconst available = source.size - dataStart\n\tconst rawMetadata = Object.hasOwn(parsed, '__metadata__') ? parsed['__metadata__'] : undefined\n\tif (\n\t\trawMetadata !== undefined &&\n\t\t(!isRecord(rawMetadata) || !Object.values(rawMetadata).every(isString))\n\t) {\n\t\tthrow new InferError('The safetensors __metadata__ member must map strings to strings.', {\n\t\t\tcode: 'FORMAT',\n\t\t})\n\t}\n\tconst metadata =\n\t\trawMetadata === undefined\n\t\t\t? undefined\n\t\t\t: Object.fromEntries(\n\t\t\t\t\tObject.entries(rawMetadata).filter((entry): entry is [string, string] =>\n\t\t\t\t\t\tisString(entry[1]),\n\t\t\t\t\t),\n\t\t\t\t)\n\tconst tensors = Object.entries(parsed)\n\t\t.filter(([name]) => name !== '__metadata__')\n\t\t.map(([name, entry]) => readSafetensorsEntry(name, entry, available))\n\tconst overlap = findTensorOverlap(tensors)\n\tif (overlap !== undefined) {\n\t\tthrow new InferError(\n\t\t\t`The safetensors entry ${quoteFaultText(overlap.name)} overlaps another entry.`,\n\t\t\t{ code: 'FORMAT', context: { name: overlap.name } },\n\t\t)\n\t}\n\treturn {\n\t\ttensors,\n\t\toffset: dataStart,\n\t\t...(metadata === undefined ? {} : { metadata }),\n\t}\n}\n\n/**\n * Streams a LoRA- or section-merged (or combined) safetensors file from a base safetensors\n * `ByteSourceInterface`, an optional `AdapterInterface`, and an optional `SectionInterface`, never\n * holding the base file in memory.\n *\n * @remarks\n * Reads only the base header, validates all adapter and section bindings before yielding any byte,\n * requires `options.architecture` (`ARGUMENT`) whenever `llama` targets `attn_q`/`attn_k` or\n * `qwen35` targets DeltaNet projections, deinterleaves `llama` `attn_q`/`attn_k` rotary rows and\n * permutes 4B DeltaNet value heads into Hugging Face layout, emits the output safetensors header\n * upfront, copies untargeted tensors in `chunk`-byte slices, and replaces full-rank `section`\n * tensors, adds scaled LoRA `adapter` deltas, or both in `strip`-row strips preserving each\n * tensor's base dtype (`F32`, `F16`, or `BF16`). When both `section` and `adapter` target the same\n * weight tensor, `section` replaces the base weight first and `adapter` adds its scaled delta on\n * top. Checks `signal` between slices and strips.\n *\n * @param options - The base byte source, optional adapter and section, architecture, optional base/scale, slice sizes, and signal\n * @returns An async generator yielding merged safetensors file chunks\n *\n * @example\n * ```ts\n * for await (const chunk of mergeSafetensors({ source, adapter, section, architecture })) {\n * \tawait sink.write(chunk)\n * }\n * ```\n */\nexport async function* mergeSafetensors(\n\toptions: MergeSafetensorsOptions,\n): AsyncGenerator<Uint8Array<ArrayBuffer>, void, void> {\n\tconst { source, adapter, section, architecture, base, signal } = options\n\tcheckSignal(signal, 'The safetensors merge')\n\tif (adapter === undefined && section === undefined) {\n\t\tthrow new InferError('The safetensors merge requires at least one of adapter or section.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tif (adapter !== undefined && section !== undefined && adapter.family !== section.family) {\n\t\tthrow new InferError(\n\t\t\t`The adapter targets family ${quoteFaultText(adapter.family)}, while the section targets ${quoteFaultText(section.family)}.`,\n\t\t\t{ code: 'BINDING', context: { adapter: adapter.family, section: section.family } },\n\t\t)\n\t}\n\tconst scale = options.scale ?? adapter?.scale ?? 1\n\tif (!isFiniteNumber(scale)) {\n\t\tthrow new InferError(`The merge scale ${scale} must be a finite number.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { scale },\n\t\t})\n\t}\n\tconst chunkBytes = options.chunk ?? MERGE_CHUNK_BYTES\n\tif (!isSafeInteger(chunkBytes) || chunkBytes < 1) {\n\t\tthrow new InferError(`The merge chunk size ${chunkBytes} must be a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { chunk: chunkBytes },\n\t\t})\n\t}\n\tconst stripRows = options.strip ?? MERGE_ROW_STRIP\n\tif (!isSafeInteger(stripRows) || stripRows < 1) {\n\t\tthrow new InferError(`The merge strip height ${stripRows} must be a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { strip: stripRows },\n\t\t})\n\t}\n\tif (adapter !== undefined) {\n\t\tif (base !== undefined && adapter.base !== undefined && adapter.base !== base) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The adapter binds to base ${quoteFaultText(adapter.base)}; the safetensors base is ${quoteFaultText(base)}.`,\n\t\t\t\t{ code: 'BINDING', context: { base: adapter.base, expected: base } },\n\t\t\t)\n\t\t}\n\t\tcheckAdapterArchitecture(\n\t\t\tadapter.family,\n\t\t\tadapter.pairs.map((pair) => pair.target),\n\t\t\tarchitecture,\n\t\t)\n\t\tif (architecture !== undefined) {\n\t\t\tcheckAdapterBinding(adapter, architecture, base)\n\t\t}\n\t}\n\tif (section !== undefined) {\n\t\tif (base !== undefined && section.base !== undefined && section.base !== base) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The section patch binds to base ${quoteFaultText(section.base)}; the safetensors base is ${quoteFaultText(base)}.`,\n\t\t\t\t{ code: 'BINDING', context: { base: section.base, expected: base } },\n\t\t\t)\n\t\t}\n\t\tif (architecture === undefined) {\n\t\t\tconst sensitive = section.entries.find((entry) =>\n\t\t\t\tsection.family === 'llama'\n\t\t\t\t\t? entry.target === 'attn_q' || entry.target === 'attn_k'\n\t\t\t\t\t: entry.target === 'attn_qkv' ||\n\t\t\t\t\t\tentry.target === 'attn_gate' ||\n\t\t\t\t\t\tentry.target === 'ssm_alpha' ||\n\t\t\t\t\t\tentry.target === 'ssm_beta' ||\n\t\t\t\t\t\tentry.target === 'ssm_conv1d' ||\n\t\t\t\t\t\tentry.target === 'ssm_dt' ||\n\t\t\t\t\t\tentry.target === 'ssm_a' ||\n\t\t\t\t\t\tentry.target === 'ssm_out',\n\t\t\t)\n\t\t\tif (sensitive !== undefined) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`Merging ${quoteFaultText(section.family)} section target ${quoteFaultText(sensitive.target)} into safetensors requires the base architecture option to preserve head layout.`,\n\t\t\t\t\t{ code: 'ARGUMENT', context: { family: section.family, target: sensitive.target } },\n\t\t\t\t)\n\t\t\t}\n\t\t} else {\n\t\t\tcheckSectionBinding(section, architecture, base)\n\t\t}\n\t}\n\tconst header = await readSafetensorsHeader(source, signal)\n\tconst byName = new Map<string, SafetensorsTensor>(\n\t\theader.tensors.map((tensor) => [tensor.name, tensor]),\n\t)\n\tconst targetedAdapters = new Map<string, AdapterPair>()\n\tif (adapter !== undefined) {\n\t\tfor (const rawPair of adapter.pairs) {\n\t\t\tconst spec = PEFT_TARGET_SPECS[rawPair.target]\n\t\t\tif (!spec.families.includes(adapter.family)) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The LoRA target ${quoteFaultText(rawPair.target)} is not admitted by family ${quoteFaultText(adapter.family)}.`,\n\t\t\t\t\t{ code: 'BINDING', context: { target: rawPair.target, family: adapter.family } },\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst canonicalName =\n\t\t\t\tadapter.family === 'qwen35'\n\t\t\t\t\t? `${PEFT_BASE_QWEN35_PREFIX}${rawPair.layer}.${spec.module}.weight`\n\t\t\t\t\t: `${PEFT_BASE_LAYERS_PREFIX}${rawPair.layer}.${spec.module}.weight`\n\t\t\tconst aliasName = `${PEFT_BASE_LAYERS_PREFIX}${rawPair.layer}.${spec.module}.weight`\n\t\t\tconst matched =\n\t\t\t\tbyName.get(canonicalName) ??\n\t\t\t\t(adapter.family === 'qwen35' ? byName.get(aliasName) : undefined)\n\t\t\tif (matched === undefined) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The base safetensors file lacks target tensor ${quoteFaultText(canonicalName)}.`,\n\t\t\t\t\t{ code: 'BINDING', context: { name: canonicalName, pair: rawPair.name } },\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst [columns, rows] = matched.dimensions\n\t\t\tif (matched.dimensions.length !== 2 || columns !== rawPair.columns || rows !== rawPair.rows) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The adapter pair ${quoteFaultText(rawPair.name)} has shape [${rawPair.columns}, ${rawPair.rows}]; the base tensor ${quoteFaultText(matched.name)} has [${matched.dimensions.join(', ')}].`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'BINDING',\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tname: matched.name,\n\t\t\t\t\t\t\tdimensions: [rawPair.columns, rawPair.rows],\n\t\t\t\t\t\t\texpected: matched.dimensions,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\ttargetedAdapters.set(\n\t\t\t\tmatched.name,\n\t\t\t\tpermuteRotaryPair(permuteDeltaPair(rawPair, architecture, false), architecture, false),\n\t\t\t)\n\t\t}\n\t}\n\tconst targetedSections = new Map<string, SectionEntry>()\n\tconst appendedSections: Array<{\n\t\treadonly name: string\n\t\treadonly entry: SectionEntry\n\t\treadonly format: SafetensorsFormat\n\t}> = []\n\tif (section !== undefined) {\n\t\tconst fallbackFormat = header.tensors[0]?.format ?? 'F32'\n\t\tfor (const rawEntry of section.entries) {\n\t\t\tconst spec = SECTION_SAFETENSORS_SPECS[rawEntry.target]\n\t\t\tif (!spec.families.includes(section.family)) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The section target ${quoteFaultText(rawEntry.target)} is not admitted by family ${quoteFaultText(section.family)}.`,\n\t\t\t\t\t{ code: 'BINDING', context: { target: rawEntry.target, family: section.family } },\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst canonicalName = spec.top\n\t\t\t\t? rawEntry.target === 'output'\n\t\t\t\t\t? spec.suffix\n\t\t\t\t\t: section.family === 'qwen35'\n\t\t\t\t\t\t? `model.language_model.${spec.suffix}`\n\t\t\t\t\t\t: `model.${spec.suffix}`\n\t\t\t\t: section.family === 'qwen35'\n\t\t\t\t\t? `${PEFT_BASE_QWEN35_PREFIX}${rawEntry.layer}.${spec.suffix}`\n\t\t\t\t\t: `${PEFT_BASE_LAYERS_PREFIX}${rawEntry.layer}.${spec.suffix}`\n\t\t\tconst aliasName = spec.top\n\t\t\t\t? rawEntry.target === 'output'\n\t\t\t\t\t? spec.suffix\n\t\t\t\t\t: `model.${spec.suffix}`\n\t\t\t\t: `${PEFT_BASE_LAYERS_PREFIX}${rawEntry.layer}.${spec.suffix}`\n\t\t\tconst matched =\n\t\t\t\tbyName.get(canonicalName) ??\n\t\t\t\t(section.family === 'qwen35' ? byName.get(aliasName) : undefined)\n\t\t\tconst permuted = permuteSectionEntry(rawEntry, architecture, false)\n\t\t\tconst transformed =\n\t\t\t\trawEntry.target === 'ssm_a'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t...permuted,\n\t\t\t\t\t\t\tvalues: Float32Array.from(permuted.values, (value) => {\n\t\t\t\t\t\t\t\tif (value >= 0) {\n\t\t\t\t\t\t\t\t\tthrow new InferError(\n\t\t\t\t\t\t\t\t\t\t`The section target ${quoteFaultText(rawEntry.name)} holds non-negative decay ${value}; Hugging Face A_log requires negative ssm_a.`,\n\t\t\t\t\t\t\t\t\t\t{ code: 'FORMAT', context: { name: rawEntry.name, value } },\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\treturn Math.fround(Math.log(-value))\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t}\n\t\t\t\t\t: permuted\n\t\t\tif (matched === undefined) {\n\t\t\t\tif (rawEntry.target === 'output') {\n\t\t\t\t\tconst embed =\n\t\t\t\t\t\tbyName.get('model.language_model.embed_tokens.weight') ??\n\t\t\t\t\t\tbyName.get('model.embed_tokens.weight')\n\t\t\t\t\tif (\n\t\t\t\t\t\tembed !== undefined &&\n\t\t\t\t\t\tembed.dimensions.length === 2 &&\n\t\t\t\t\t\tembed.dimensions[0] === rawEntry.columns &&\n\t\t\t\t\t\tembed.dimensions[1] === rawEntry.rows\n\t\t\t\t\t) {\n\t\t\t\t\t\tappendedSections.push({\n\t\t\t\t\t\t\tname: canonicalName,\n\t\t\t\t\t\t\tentry: transformed,\n\t\t\t\t\t\t\tformat: embed.format ?? fallbackFormat,\n\t\t\t\t\t\t})\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The base safetensors file lacks target tensor ${quoteFaultText(canonicalName)}.`,\n\t\t\t\t\t{ code: 'BINDING', context: { name: canonicalName, entry: rawEntry.name } },\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst shapeMatches =\n\t\t\t\trawEntry.rows === 1\n\t\t\t\t\t? matched.dimensions.length === 1 && matched.dimensions[0] === rawEntry.columns\n\t\t\t\t\t: rawEntry.target === 'ssm_conv1d'\n\t\t\t\t\t\t? (matched.dimensions.length === 2 &&\n\t\t\t\t\t\t\t\tmatched.dimensions[0] === rawEntry.columns &&\n\t\t\t\t\t\t\t\tmatched.dimensions[1] === rawEntry.rows) ||\n\t\t\t\t\t\t\t(matched.dimensions.length === 3 &&\n\t\t\t\t\t\t\t\tmatched.dimensions[0] === rawEntry.columns &&\n\t\t\t\t\t\t\t\tmatched.dimensions[1] === 1 &&\n\t\t\t\t\t\t\t\tmatched.dimensions[2] === rawEntry.rows)\n\t\t\t\t\t\t: matched.dimensions.length === 2 &&\n\t\t\t\t\t\t\tmatched.dimensions[0] === rawEntry.columns &&\n\t\t\t\t\t\t\tmatched.dimensions[1] === rawEntry.rows\n\t\t\tif (!shapeMatches) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The section entry ${quoteFaultText(rawEntry.name)} has shape [${rawEntry.columns}, ${rawEntry.rows}]; the base tensor ${quoteFaultText(matched.name)} has [${matched.dimensions.join(', ')}].`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'BINDING',\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tname: matched.name,\n\t\t\t\t\t\t\tdimensions: [rawEntry.columns, rawEntry.rows],\n\t\t\t\t\t\t\texpected: matched.dimensions,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\ttargetedSections.set(matched.name, transformed)\n\t\t}\n\t}\n\tconst headerEntries: Array<readonly [string, unknown]> = []\n\tif (header.metadata !== undefined && Object.keys(header.metadata).length > 0) {\n\t\theaderEntries.push(['__metadata__', header.metadata])\n\t}\n\tconst plannedSafetensors: ReadonlyArray<{\n\t\treadonly name: string\n\t\treadonly dtype: SafetensorsFormat\n\t\treadonly shape: readonly number[]\n\t\treadonly byteLength: number\n\t}> = [\n\t\t...header.tensors.map((tensor) => ({\n\t\t\tname: tensor.name,\n\t\t\tdtype: tensor.format,\n\t\t\tshape: tensor.dimensions.toReversed(),\n\t\t\tbyteLength: computeTensorBytes(tensor),\n\t\t})),\n\t\t...appendedSections.map((appended) => ({\n\t\t\tname: appended.name,\n\t\t\tdtype: appended.format,\n\t\t\tshape: [appended.entry.rows, appended.entry.columns],\n\t\t\tbyteLength: appended.entry.values.length * GGUF_BLOCKS[appended.format].bytes,\n\t\t})),\n\t]\n\tlet outOffset = 0\n\tfor (let index = 0; index < plannedSafetensors.length; index += 1) {\n\t\tconst item = plannedSafetensors[index]\n\t\tif (item === undefined) continue\n\t\theaderEntries.push([\n\t\t\titem.name,\n\t\t\t{\n\t\t\t\tdtype: item.dtype,\n\t\t\t\tshape: item.shape,\n\t\t\t\tdata_offsets: [outOffset, outOffset + item.byteLength],\n\t\t\t},\n\t\t])\n\t\toutOffset += item.byteLength\n\t}\n\tconst headerBytes = UTF8_ENCODER.encode(JSON.stringify(Object.fromEntries(headerEntries)))\n\tif (headerBytes.byteLength > SAFETENSORS_HEADER_LIMIT) {\n\t\tthrow new InferError(\n\t\t\t`The merged safetensors header spans ${headerBytes.byteLength} bytes, past the ${SAFETENSORS_HEADER_LIMIT}-byte limit.`,\n\t\t\t{ code: 'FORMAT', context: { length: headerBytes.byteLength } },\n\t\t)\n\t}\n\tconst lengthPrefix = new Uint8Array(8)\n\tnew DataView(lengthPrefix.buffer).setBigUint64(0, BigInt(headerBytes.byteLength), true)\n\tyield lengthPrefix\n\tyield headerBytes\n\tfor (const tensor of header.tensors) {\n\t\tcheckSignal(signal, 'The safetensors merge')\n\t\tconst pair = scale === 0 ? undefined : targetedAdapters.get(tensor.name)\n\t\tconst patchEntry = targetedSections.get(tensor.name)\n\t\tconst srcStart = header.offset + tensor.offset\n\t\tconst totalBytes = computeTensorBytes(tensor)\n\t\tif (pair === undefined && patchEntry === undefined) {\n\t\t\tfor (let pos = 0; pos < totalBytes; pos += chunkBytes) {\n\t\t\t\tcheckSignal(signal, 'The safetensors merge')\n\t\t\t\tconst sliceLength = Math.min(chunkBytes, totalBytes - pos)\n\t\t\t\tyield await source.read(srcStart + pos, sliceLength, signal)\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tconst columns = patchEntry?.columns ?? pair?.columns ?? 1\n\t\tconst rows = patchEntry?.rows ?? pair?.rows ?? 1\n\t\tconst factor = pair === undefined ? 0 : scale * (pair.alpha / pair.rank)\n\t\tconst rowBytes = columns * GGUF_BLOCKS[tensor.format].bytes\n\t\tfor (let rowStart = 0; rowStart < rows; rowStart += stripRows) {\n\t\t\tcheckSignal(signal, 'The safetensors merge')\n\t\t\tconst rowCount = Math.min(stripRows, rows - rowStart)\n\t\t\tconst baseStrip =\n\t\t\t\tpatchEntry !== undefined\n\t\t\t\t\t? patchEntry.values.slice(rowStart * columns, (rowStart + rowCount) * columns)\n\t\t\t\t\t: widenTensor(\n\t\t\t\t\t\t\tawait source.read(srcStart + rowStart * rowBytes, rowCount * rowBytes, signal),\n\t\t\t\t\t\t\ttensor.format,\n\t\t\t\t\t\t)\n\t\t\tconst merged =\n\t\t\t\tpair !== undefined ? addLoRAStrip(baseStrip, pair, rowStart, rowCount, factor) : baseStrip\n\t\t\tyield encodeSafetensorsValues(merged, tensor.format)\n\t\t}\n\t}\n\tfor (const appended of appendedSections) {\n\t\tconst { entry, format: outFormat } = appended\n\t\tfor (let rowStart = 0; rowStart < entry.rows; rowStart += stripRows) {\n\t\t\tcheckSignal(signal, 'The safetensors merge')\n\t\t\tconst rowCount = Math.min(stripRows, entry.rows - rowStart)\n\t\t\tconst strip = entry.values.slice(\n\t\t\t\trowStart * entry.columns,\n\t\t\t\t(rowStart + rowCount) * entry.columns,\n\t\t\t)\n\t\t\tyield encodeSafetensorsValues(strip, outFormat)\n\t\t}\n\t}\n}\n\n/**\n * Streams a LoRA- or section-merged (or combined) GGUF v3 file from a base GGUF\n * `ByteSourceInterface`, keeping untargeted quantized tensors unchanged and memory strictly\n * bounded.\n *\n * @remarks\n * Reads only the base GGUF header through `@orkestrel/infer`'s `readGGUF`, validates architecture,\n * adapter binding (`checkAdapterBinding`), and section binding (`checkSectionBinding`) before\n * yielding any byte, copies all metadata verbatim, streams untargeted quantized tensors (`Q8_0`,\n * `Q4_K`, `Q6_K`, `Q5_0`, and float formats) byte-for-byte unchanged in `chunk`-byte slices, and\n * replaces full-rank `section` tensors, adds scaled LoRA `adapter` deltas, or both row-strip by\n * row-strip into `format` (`'F32'` default, `'BF16'`, `'Q8_0'`, or `'Q4_K'`) aligned to the file's\n * GGUF alignment. 1D section tensors (normalization gains, biases, and decay factors) and 4-tap\n * convolutions keep `'F32'` when `format` is quantized so `@orkestrel/infer` and `llama.cpp` load\n * them cleanly. When both `section` and `adapter` target the same tensor, `section` replaces the\n * base weight first and `adapter` adds its scaled delta on top.\n *\n * @param options - The base byte source, optional adapter and section, output format, optional base/scale, slice sizes, and signal\n * @returns An async generator yielding merged GGUF v3 file chunks\n *\n * @example\n * ```ts\n * for await (const chunk of mergeGGUF({ source, adapter, section, format: 'Q8_0' })) {\n * \tawait sink.write(chunk)\n * }\n * ```\n */\nexport async function* mergeGGUF(\n\toptions: MergeGGUFOptions,\n): AsyncGenerator<Uint8Array<ArrayBuffer>, void, void> {\n\tconst { source, adapter, section, base, signal } = options\n\tcheckSignal(signal, 'The GGUF merge')\n\tif (adapter === undefined && section === undefined) {\n\t\tthrow new InferError('The GGUF merge requires at least one of adapter or section.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tif (adapter !== undefined && section !== undefined && adapter.family !== section.family) {\n\t\tthrow new InferError(\n\t\t\t`The adapter targets family ${quoteFaultText(adapter.family)}, while the section targets ${quoteFaultText(section.family)}.`,\n\t\t\t{ code: 'BINDING', context: { adapter: adapter.family, section: section.family } },\n\t\t)\n\t}\n\tconst format: MergeGGUFFormat = options.format ?? 'F32'\n\tif (!isMergeGGUFFormat(format)) {\n\t\tthrow new InferError(\n\t\t\t`The GGUF merge format ${quoteFaultText(String(format))} must be \"F32\", \"BF16\", \"Q8_0\", or \"Q4_K\".`,\n\t\t\t{ code: 'ARGUMENT', context: { format } },\n\t\t)\n\t}\n\tconst scale = options.scale ?? adapter?.scale ?? 1\n\tif (!isFiniteNumber(scale)) {\n\t\tthrow new InferError(`The merge scale ${scale} must be a finite number.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { scale },\n\t\t})\n\t}\n\tconst chunkBytes = options.chunk ?? MERGE_CHUNK_BYTES\n\tif (!isSafeInteger(chunkBytes) || chunkBytes < 1) {\n\t\tthrow new InferError(`The merge chunk size ${chunkBytes} must be a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { chunk: chunkBytes },\n\t\t})\n\t}\n\tconst stripRows = options.strip ?? MERGE_ROW_STRIP\n\tif (!isSafeInteger(stripRows) || stripRows < 1) {\n\t\tthrow new InferError(`The merge strip height ${stripRows} must be a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { strip: stripRows },\n\t\t})\n\t}\n\tconst headerSummary = await readGGUF(source, signal).then((header) => {\n\t\tconst architecture = readArchitecture(header.metadata)\n\t\tif (adapter !== undefined) checkAdapterBinding(adapter, architecture, base)\n\t\tif (section !== undefined) checkSectionBinding(section, architecture, base)\n\t\tconst alignment = resolveAlignment(header.metadata.get(GGUF_KEYS.alignment)) ?? GGUF_ALIGNMENT\n\t\treturn {\n\t\t\talignment,\n\t\t\tmetadataCount: header.metadata.size,\n\t\t\toffset: header.offset,\n\t\t\ttensors: header.tensors,\n\t\t}\n\t})\n\tconst { alignment, metadataCount, offset: srcOffset, tensors: srcTensors } = headerSummary\n\tconst byName = new Map<string, GGUFTensor>(srcTensors.map((tensor) => [tensor.name, tensor]))\n\tconst targetedAdapters = new Map<string, AdapterPair>()\n\tif (adapter !== undefined) {\n\t\tfor (const pair of adapter.pairs) {\n\t\t\tconst baseTensor = byName.get(pair.name)\n\t\t\tif (baseTensor === undefined) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The base GGUF file lacks target tensor ${quoteFaultText(pair.name)}.`,\n\t\t\t\t\t{ code: 'BINDING', context: { name: pair.name } },\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (\n\t\t\t\tbaseTensor.dimensions.length !== 2 ||\n\t\t\t\tbaseTensor.dimensions[0] !== pair.columns ||\n\t\t\t\tbaseTensor.dimensions[1] !== pair.rows\n\t\t\t) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The adapter pair ${quoteFaultText(pair.name)} has shape [${pair.columns}, ${pair.rows}]; the base GGUF tensor has [${baseTensor.dimensions.join(', ')}].`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'BINDING',\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tname: pair.name,\n\t\t\t\t\t\t\tdimensions: [pair.columns, pair.rows],\n\t\t\t\t\t\t\texpected: baseTensor.dimensions,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (!MERGE_SOURCE_FORMATS.includes(baseTensor.format)) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The targeted base GGUF tensor ${quoteFaultText(pair.name)} uses unsupported format ${quoteFaultText(baseTensor.format)}.`,\n\t\t\t\t\t{ code: 'UNSUPPORTED', context: { name: pair.name, format: baseTensor.format } },\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst block = GGUF_BLOCKS[baseTensor.format]\n\t\t\tif (pair.columns % block.elements !== 0) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The targeted base GGUF tensor ${quoteFaultText(pair.name)} has width ${pair.columns}, not divisible by ${block.elements}.`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'FORMAT',\n\t\t\t\t\t\tcontext: { name: pair.name, columns: pair.columns, block: block.elements },\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst outBlock = GGUF_BLOCKS[format]\n\t\t\tif (scale !== 0 && pair.columns % outBlock.elements !== 0) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The merged ${format} tensor ${quoteFaultText(pair.name)} has width ${pair.columns}, not divisible by ${outBlock.elements}.`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'FORMAT',\n\t\t\t\t\t\tcontext: { name: pair.name, columns: pair.columns, format, block: outBlock.elements },\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\ttargetedAdapters.set(pair.name, pair)\n\t\t}\n\t}\n\tconst targetedSections = new Map<string, SectionEntry>()\n\tconst appendedSections: SectionEntry[] = []\n\tif (section !== undefined) {\n\t\tfor (const entry of section.entries) {\n\t\t\tconst baseTensor = byName.get(entry.name)\n\t\t\tif (baseTensor === undefined) {\n\t\t\t\tif (entry.name === 'output.weight') {\n\t\t\t\t\tconst embed = byName.get('token_embd.weight')\n\t\t\t\t\tif (\n\t\t\t\t\t\tembed !== undefined &&\n\t\t\t\t\t\tembed.dimensions.length === 2 &&\n\t\t\t\t\t\tembed.dimensions[0] === entry.columns &&\n\t\t\t\t\t\tembed.dimensions[1] === entry.rows\n\t\t\t\t\t) {\n\t\t\t\t\t\tconst outBlock = GGUF_BLOCKS[format]\n\t\t\t\t\t\tif (entry.columns % outBlock.elements !== 0) {\n\t\t\t\t\t\t\tthrow new InferError(\n\t\t\t\t\t\t\t\t`The merged ${format} tensor ${quoteFaultText(entry.name)} has width ${entry.columns}, not divisible by ${outBlock.elements}.`,\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tcode: 'FORMAT',\n\t\t\t\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\t\t\t\tname: entry.name,\n\t\t\t\t\t\t\t\t\t\tcolumns: entry.columns,\n\t\t\t\t\t\t\t\t\t\tformat,\n\t\t\t\t\t\t\t\t\t\tblock: outBlock.elements,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tappendedSections.push(entry)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The base GGUF file lacks target tensor ${quoteFaultText(entry.name)}.`,\n\t\t\t\t\t{ code: 'BINDING', context: { name: entry.name } },\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst dimsMatch =\n\t\t\t\tentry.rows === 1\n\t\t\t\t\t? baseTensor.dimensions.length === 1 && baseTensor.dimensions[0] === entry.columns\n\t\t\t\t\t: baseTensor.dimensions.length === 2 &&\n\t\t\t\t\t\tbaseTensor.dimensions[0] === entry.columns &&\n\t\t\t\t\t\tbaseTensor.dimensions[1] === entry.rows\n\t\t\tif (!dimsMatch) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The section entry ${quoteFaultText(entry.name)} has shape [${entry.columns}, ${entry.rows}]; the base GGUF tensor has [${baseTensor.dimensions.join(', ')}].`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'BINDING',\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tname: entry.name,\n\t\t\t\t\t\t\tdimensions: [entry.columns, entry.rows],\n\t\t\t\t\t\t\texpected: baseTensor.dimensions,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst keepFloat = entry.rows === 1 || entry.target === 'ssm_conv1d'\n\t\t\tconst outBlock = GGUF_BLOCKS[format]\n\t\t\tif (!keepFloat && entry.columns % outBlock.elements !== 0) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The merged ${format} tensor ${quoteFaultText(entry.name)} has width ${entry.columns}, not divisible by ${outBlock.elements}.`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'FORMAT',\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tname: entry.name,\n\t\t\t\t\t\t\tcolumns: entry.columns,\n\t\t\t\t\t\t\tformat,\n\t\t\t\t\t\t\tblock: outBlock.elements,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\ttargetedSections.set(entry.name, entry)\n\t\t}\n\t}\n\tconst plannedGGUF: ReadonlyArray<{\n\t\treadonly name: string\n\t\treadonly dimensions: readonly number[]\n\t\treadonly format: GGUFFormat\n\t}> = [\n\t\t...srcTensors.map((tensor) => {\n\t\t\tconst hasAdapter = scale !== 0 && targetedAdapters.has(tensor.name)\n\t\t\tconst patchEntry = targetedSections.get(tensor.name)\n\t\t\tconst keepFloat =\n\t\t\t\tpatchEntry !== undefined && (patchEntry.rows === 1 || patchEntry.target === 'ssm_conv1d')\n\t\t\tconst nextFormat: GGUFFormat =\n\t\t\t\thasAdapter || patchEntry !== undefined\n\t\t\t\t\t? keepFloat && (format === 'Q8_0' || format === 'Q4_K' || format === 'BF16')\n\t\t\t\t\t\t? 'F32'\n\t\t\t\t\t\t: format\n\t\t\t\t\t: tensor.format\n\t\t\treturn { name: tensor.name, dimensions: tensor.dimensions, format: nextFormat }\n\t\t}),\n\t\t...appendedSections.map((entry) => ({\n\t\t\tname: entry.name,\n\t\t\tdimensions: [entry.columns, entry.rows],\n\t\t\tformat,\n\t\t})),\n\t]\n\tconst outTensors: GGUFTensor[] = []\n\tlet outOffset = 0\n\tfor (let index = 0; index < plannedGGUF.length; index += 1) {\n\t\tconst spec = plannedGGUF[index]\n\t\tif (spec === undefined) continue\n\t\tconst next: GGUFTensor = {\n\t\t\tname: spec.name,\n\t\t\tdimensions: spec.dimensions,\n\t\t\tformat: spec.format,\n\t\t\toffset: outOffset,\n\t\t}\n\t\toutTensors.push(next)\n\t\toutOffset = alignOffset(outOffset + computeTensorBytes(next), alignment)\n\t}\n\tconst srcTensorSection = joinBytes(srcTensors.map((tensor) => encodeGGUFTensor(tensor)))\n\tconst tailStart = Math.max(24, srcOffset - srcTensorSection.byteLength - alignment)\n\tconst tail = await source.read(tailStart, srcOffset - tailStart, signal)\n\tconst maxCandidate = tail.byteLength - srcTensorSection.byteLength\n\tconst matchedOffset = Array.from({ length: maxCandidate + 1 }, (_, index) => index).find(\n\t\t(candidate) => {\n\t\t\tif (\n\t\t\t\talignOffset(tailStart + candidate + srcTensorSection.byteLength, alignment) !== srcOffset\n\t\t\t) {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tfor (let byteIndex = 0; byteIndex < srcTensorSection.byteLength; byteIndex += 1) {\n\t\t\t\tif (tail[candidate + byteIndex] !== srcTensorSection[byteIndex]) return false\n\t\t\t}\n\t\t\tfor (\n\t\t\t\tlet padIndex = candidate + srcTensorSection.byteLength;\n\t\t\t\tpadIndex < tail.byteLength;\n\t\t\t\tpadIndex += 1\n\t\t\t) {\n\t\t\t\tif (tail[padIndex] !== 0) return false\n\t\t\t}\n\t\t\treturn true\n\t\t},\n\t)\n\tif (matchedOffset === undefined) {\n\t\tthrow new InferError('The base GGUF header tensor table could not be located verbatim.', {\n\t\t\tcode: 'FORMAT',\n\t\t})\n\t}\n\tconst metadataEnd = tailStart + matchedOffset\n\tyield joinBytes([\n\t\tencodeGGUFNumbers('uint32', [GGUF_MAGIC, GGUF_VERSION]),\n\t\tencodeGGUFBigInts('uint64', [BigInt(outTensors.length), BigInt(metadataCount)]),\n\t])\n\tfor (let pos = 24; pos < metadataEnd; pos += chunkBytes) {\n\t\tcheckSignal(signal, 'The GGUF merge')\n\t\tconst sliceLength = Math.min(chunkBytes, metadataEnd - pos)\n\t\tyield await source.read(pos, sliceLength, signal)\n\t}\n\tconst outTensorSection = joinBytes(outTensors.map((tensor) => encodeGGUFTensor(tensor)))\n\tyield outTensorSection\n\tconst headerLength = metadataEnd + outTensorSection.byteLength\n\tconst headerPadded = alignOffset(headerLength, alignment)\n\tif (headerPadded > headerLength) {\n\t\tyield new Uint8Array(headerPadded - headerLength)\n\t}\n\tfor (let index = 0; index < srcTensors.length; index += 1) {\n\t\tcheckSignal(signal, 'The GGUF merge')\n\t\tconst srcTensor = srcTensors[index]\n\t\tconst outTensor = outTensors[index]\n\t\tif (srcTensor === undefined || outTensor === undefined) continue\n\t\tconst srcStart = srcOffset + srcTensor.offset\n\t\tconst pair = scale === 0 ? undefined : targetedAdapters.get(srcTensor.name)\n\t\tconst patchEntry = targetedSections.get(srcTensor.name)\n\t\tconst outBytes = computeTensorBytes(outTensor)\n\t\tif (pair === undefined && patchEntry === undefined) {\n\t\t\tconst srcBytes = computeTensorBytes(srcTensor)\n\t\t\tfor (let pos = 0; pos < srcBytes; pos += chunkBytes) {\n\t\t\t\tcheckSignal(signal, 'The GGUF merge')\n\t\t\t\tconst sliceLength = Math.min(chunkBytes, srcBytes - pos)\n\t\t\t\tyield await source.read(srcStart + pos, sliceLength, signal)\n\t\t\t}\n\t\t} else {\n\t\t\tconst columns = patchEntry?.columns ?? pair?.columns ?? 1\n\t\t\tconst rows = patchEntry?.rows ?? pair?.rows ?? 1\n\t\t\tconst factor = pair === undefined ? 0 : scale * (pair.alpha / pair.rank)\n\t\t\tconst block = GGUF_BLOCKS[srcTensor.format]\n\t\t\tconst rowBytes = (columns / block.elements) * block.bytes\n\t\t\tconst targetFormat: MergeGGUFFormat = isMergeGGUFFormat(outTensor.format)\n\t\t\t\t? outTensor.format\n\t\t\t\t: 'F32'\n\t\t\tfor (let rowStart = 0; rowStart < rows; rowStart += stripRows) {\n\t\t\t\tcheckSignal(signal, 'The GGUF merge')\n\t\t\t\tconst rowCount = Math.min(stripRows, rows - rowStart)\n\t\t\t\tconst baseStrip =\n\t\t\t\t\tpatchEntry !== undefined\n\t\t\t\t\t\t? patchEntry.values.slice(rowStart * columns, (rowStart + rowCount) * columns)\n\t\t\t\t\t\t: widenTensor(\n\t\t\t\t\t\t\t\tawait source.read(srcStart + rowStart * rowBytes, rowCount * rowBytes, signal),\n\t\t\t\t\t\t\t\tsrcTensor.format,\n\t\t\t\t\t\t\t)\n\t\t\t\tconst merged =\n\t\t\t\t\tpair !== undefined ? addLoRAStrip(baseStrip, pair, rowStart, rowCount, factor) : baseStrip\n\t\t\t\tyield encodeGGUFValues(merged, targetFormat)\n\t\t\t}\n\t\t}\n\t\tconst pad = alignOffset(outBytes, alignment) - outBytes\n\t\tif (pad > 0) yield new Uint8Array(pad)\n\t}\n\tfor (let index = 0; index < appendedSections.length; index += 1) {\n\t\tconst entry = appendedSections[index]\n\t\tconst outTensor = outTensors[srcTensors.length + index]\n\t\tif (entry === undefined || outTensor === undefined) continue\n\t\tconst outBytes = computeTensorBytes(outTensor)\n\t\tfor (let rowStart = 0; rowStart < entry.rows; rowStart += stripRows) {\n\t\t\tcheckSignal(signal, 'The GGUF merge')\n\t\t\tconst rowCount = Math.min(stripRows, entry.rows - rowStart)\n\t\t\tconst strip = entry.values.slice(\n\t\t\t\trowStart * entry.columns,\n\t\t\t\t(rowStart + rowCount) * entry.columns,\n\t\t\t)\n\t\t\tyield encodeGGUFValues(strip, format)\n\t\t}\n\t\tconst pad = alignOffset(outBytes, alignment) - outBytes\n\t\tif (pad > 0) yield new Uint8Array(pad)\n\t}\n}\n\n/**\n * Scores labelled development rows with an initial head, traces every misclassified row through\n * `traceHead`, refits a replacement head through `Trainer` over augmented training rows, and reports labelled\n * flips through `countFlips`.\n *\n * @remarks\n * Validates `record` binding (`BINDING`), `record.pooling === 'mean'`, `record.labels` parity with\n * `question`, `weights`, `calibration`, `train`, `development`, and optional `augment` before any\n * backbone forward. Each development row is embedded once, scored before and after refitting, and\n * misclassified rows are traced in row order. When `augment` is omitted, each misclassified\n * development row is appended `weight` times (default `1`), carrying `group: row.group ?? \"refit:<index>\"`\n * whenever `weight > 1` so duplicates remain in one cross-validation fold. Rejects with `ABORT`\n * when `signal` aborts.\n *\n * @param options - The backbone, question, initial head, training rows, development rows, and trainer options\n * @returns The refitted trainer result, misclassified row traces, flip counts, augmented rows, and predictions\n *\n * @example\n * ```ts\n * const refit = await refitTracedHead({\n * \tbackbone,\n * \tquestion,\n * \trecord,\n * \tweights,\n * \ttrain,\n * \tdevelopment,\n * \tfolds: 3,\n * })\n * refit.flips.total === development.length // true\n * ```\n */\nexport async function refitTracedHead(options: RefitHeadOptions): Promise<RefitHeadResult> {\n\tif (!isRecord(options)) {\n\t\tthrow new InferError('The head refit options must be a plain object.', { code: 'ARGUMENT' })\n\t}\n\tconst {\n\t\tbackbone,\n\t\tquestion,\n\t\trecord,\n\t\tweights,\n\t\ttrain,\n\t\tdevelopment,\n\t\taugment,\n\t\ttarget,\n\t\tfolds,\n\t\trepeats,\n\t\tseed,\n\t\tpenalties,\n\t\tthreads,\n\t\tsignal,\n\t} = options\n\tcheckSignal(signal, 'The head refit')\n\tconst weight = options.weight ?? 1\n\tif (!matchesCount(weight, 1)) {\n\t\tthrow new InferError(`The refit augmentation weight is ${weight}; pass a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { weight },\n\t\t})\n\t}\n\tif (record.base !== backbone.digest) {\n\t\tthrow new InferError(\n\t\t\t`The head binds base ${quoteFaultText(record.base)}, not backbone ${quoteFaultText(backbone.digest)}.`,\n\t\t\t{ code: 'BINDING', context: { expected: record.base, actual: backbone.digest } },\n\t\t)\n\t}\n\tif (record.pooling !== 'mean') {\n\t\tthrow new InferError(\n\t\t\t`The head pooling is ${quoteFaultText(record.pooling)}; traced refitting requires mean pooling.`,\n\t\t\t{ code: 'ARGUMENT', context: { pooling: record.pooling } },\n\t\t)\n\t}\n\tconst trainerOptions: TrainerOptions = {\n\t\tbackbone,\n\t\tdepth: record.depth,\n\t\tquestion,\n\t\t...(target === undefined ? {} : { target }),\n\t\t...(folds === undefined ? {} : { folds }),\n\t\t...(repeats === undefined ? {} : { repeats }),\n\t\t...(seed === undefined ? {} : { seed }),\n\t\t...(penalties === undefined ? {} : { penalties }),\n\t\t...(threads === undefined ? {} : { threads }),\n\t}\n\tconst settings = resolveTrainerSettings(trainerOptions)\n\tconst classes = settings.labels.length\n\tif (\n\t\trecord.labels.length !== classes ||\n\t\trecord.labels.some((label, index) => label !== settings.labels[index])\n\t) {\n\t\tthrow new InferError(\n\t\t\t'The head record labels do not match the candidate labels of the question.',\n\t\t\t{ code: 'ARGUMENT', context: { record: record.labels.length, question: classes } },\n\t\t)\n\t}\n\tcheckHeadWeights(weights, classes)\n\tconst { dimension } = backbone.architecture\n\tif (weights.mean.length !== dimension) {\n\t\tthrow new InferError(\n\t\t\t`The head weights have width ${weights.mean.length}; the backbone embeds width ${dimension}.`,\n\t\t\t{ code: 'ARGUMENT', context: { classes, dimension, width: weights.mean.length } },\n\t\t)\n\t}\n\tif (\n\t\t!Number.isFinite(record.calibration.temperature) ||\n\t\trecord.calibration.temperature <= 0 ||\n\t\trecord.calibration.bias.length !== classes ||\n\t\t!record.calibration.bias.every(Number.isFinite)\n\t) {\n\t\tthrow new InferError(\n\t\t\t`The head calibration requires a positive finite temperature and ${classes} finite label biases.`,\n\t\t\t{ code: 'ARGUMENT', context: { classes } },\n\t\t)\n\t}\n\tconst admittedTrain = admitRows(train)\n\tconst admittedDev = admitRows(development)\n\tconst admittedAugment = augment === undefined ? undefined : admitRows(augment)\n\tconst devLabelIndexes = inferRowLabels(admittedDev, settings)\n\tconst expected = devLabelIndexes.map((index) => settings.labels[index] ?? '')\n\tconst devTokens = encodeStates(admittedDev, backbone.tokenizer, backbone.limit)\n\tconst features: Float32Array[] = []\n\tfor (const tokens of devTokens) {\n\t\tcheckSignal(signal, 'The head refit')\n\t\tfeatures.push(await backbone.embed(tokens, record.depth, signal))\n\t}\n\tconst initialDistributions = computeDistributions(\n\t\tcomputeHeadLogits(weights, features),\n\t\tclasses,\n\t\trecord.calibration,\n\t\tbackbone.strict,\n\t)\n\tconst before = admittedDev.map((_, rowIndex) => {\n\t\tconst offset = rowIndex * classes\n\t\tconst scores = Array.from({ length: classes }, (__, labelIndex) => ({\n\t\t\tlabelIndex,\n\t\t\tscore: initialDistributions[offset + labelIndex] ?? Number.NEGATIVE_INFINITY,\n\t\t}))\n\t\tconst winner = scores.reduce((best, entry) => (entry.score > best.score ? entry : best))\n\t\treturn settings.labels[winner.labelIndex] ?? ''\n\t})\n\tconst mistakes = expected.flatMap((label, index) => (before[index] === label ? [] : [index]))\n\tconst traces: RefitHeadTrace[] = []\n\tfor (const index of mistakes) {\n\t\tcheckSignal(signal, 'The head refit')\n\t\tconst row = admittedDev[index]\n\t\tif (row === undefined) continue\n\t\tconst trace = await traceHead({\n\t\t\tbackbone,\n\t\t\trecord,\n\t\t\tweights,\n\t\t\tstate: row.state,\n\t\t\t...(signal === undefined ? {} : { signal }),\n\t\t})\n\t\ttraces.push({\n\t\t\tindex,\n\t\t\trow,\n\t\t\texpected: expected[index] ?? '',\n\t\t\tpredicted: before[index] ?? '',\n\t\t\ttrace,\n\t\t})\n\t}\n\tconst addedRows: readonly TrainerRow[] =\n\t\tadmittedAugment !== undefined\n\t\t\t? admittedAugment\n\t\t\t: mistakes.flatMap((index) => {\n\t\t\t\t\tconst row = admittedDev[index]\n\t\t\t\t\tif (row === undefined) return []\n\t\t\t\t\tif (weight === 1) return [row]\n\t\t\t\t\tconst group = row.group ?? `refit:${index}`\n\t\t\t\t\treturn Array.from({ length: weight }, () => ({\n\t\t\t\t\t\tstate: row.state,\n\t\t\t\t\t\tlabel: row.label,\n\t\t\t\t\t\tgroup,\n\t\t\t\t\t}))\n\t\t\t\t})\n\tconst augmented: readonly TrainerRow[] = [...admittedTrain, ...addedRows]\n\tconst trainer = new Trainer(trainerOptions)\n\tconst result = await trainer.execute(augmented, signal)\n\tconst refittedDistributions = computeDistributions(\n\t\tcomputeHeadLogits(result.weights, features),\n\t\tclasses,\n\t\tresult.record.calibration,\n\t\tbackbone.strict,\n\t)\n\tconst after = admittedDev.map((_, rowIndex) => {\n\t\tconst offset = rowIndex * classes\n\t\tconst scores = Array.from({ length: classes }, (__, labelIndex) => ({\n\t\t\tlabelIndex,\n\t\t\tscore: refittedDistributions[offset + labelIndex] ?? Number.NEGATIVE_INFINITY,\n\t\t}))\n\t\tconst winner = scores.reduce((best, entry) => (entry.score > best.score ? entry : best))\n\t\treturn settings.labels[winner.labelIndex] ?? ''\n\t})\n\tconst flips = countFlips({ expected, before, after })\n\treturn { result, traces, flips, augmented, before, after }\n}\n\n/**\n * Sweeps candidate LoRA scales through zero-copy `adapter.scaled(scale)` views over a held fold\n * verified against group leaks through `checkFolds`, selecting the highest-scoring scale with zero\n * negative flips whenever one exists.\n *\n * @remarks\n * Validates `adapter`, `rows`, `scales`, `folds`, `fold`, `seed`, and optional `assignment` through\n * `checkFolds` before invoking `evaluate` so leaked groups reject immediately with `ARGUMENT` and\n * zero evaluations. When `baseline` is omitted, `adapter.scaled(0)` is evaluated once and reused if\n * `0` also appears in `scales`. Selects the scale maximizing `score` among candidates with\n * `flips.negative === 0` (`safe: true`), breaking ties by higher `flips.positive` then smaller\n * `Math.abs(scale)`. When every candidate causes negative flips (`safe: false`), selects the scale\n * with the fewest negative flips, breaking ties by highest `score` then smaller `Math.abs(scale)`.\n *\n * @param options - The adapter, rows, held-fold evaluator, candidate scales, fold settings, and signal\n * @returns The selected scale, zero-copy scaled adapter view, flip report, safety flag, and all candidates\n *\n * @example\n * ```ts\n * const calibrated = await calibrateAdapter({\n * \tadapter,\n * \trows,\n * \tfolds: 3,\n * \tevaluate: (scaled, held) => ({ predictions: held.map((row) => row.label) }),\n * })\n * calibrated.safe // true\n * ```\n */\nexport async function calibrateAdapter(\n\toptions: AdapterCalibrationOptions,\n): Promise<AdapterCalibrationResult> {\n\tif (!isRecord(options)) {\n\t\tthrow new InferError('The adapter calibration options must be a plain object.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tconst { adapter, rows, evaluate, signal } = options\n\tcheckSignal(signal, 'The adapter calibration')\n\tcheckAdapterOptions(adapter)\n\tif (typeof adapter.scaled !== 'function') {\n\t\tthrow new InferError('The adapter must expose a scaled(scale) zero-copy view method.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tif (typeof evaluate !== 'function') {\n\t\tthrow new InferError('The adapter calibration evaluate option must be a function.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tconst scales = options.scales ?? ADAPTER_CALIBRATION_SCALES\n\tif (\n\t\t!isArray(scales) ||\n\t\tscales.length === 0 ||\n\t\t!scales.every((scale) => isFiniteNumber(scale)) ||\n\t\tnew Set(scales).size !== scales.length\n\t) {\n\t\tthrow new InferError(\n\t\t\t'The adapter calibration scales must be a non-empty array of unique finite numbers.',\n\t\t\t{ code: 'ARGUMENT', context: { scales: isArray(scales) ? scales.length : -1 } },\n\t\t)\n\t}\n\tconst folds = options.folds ?? TRAINER_FOLDS\n\tif (!matchesCount(folds, 2)) {\n\t\tthrow new InferError(\n\t\t\t`The adapter calibration runs ${folds} folds; pass an integer of at least 2.`,\n\t\t\t{ code: 'ARGUMENT', context: { folds } },\n\t\t)\n\t}\n\tconst fold = options.fold ?? 0\n\tif (!isSafeInteger(fold) || fold < 0 || fold >= folds) {\n\t\tthrow new InferError(\n\t\t\t`The held fold index is ${fold}; pass an integer from 0 to ${folds - 1}.`,\n\t\t\t{ code: 'ARGUMENT', context: { fold, folds } },\n\t\t)\n\t}\n\tconst seed = options.seed ?? TRAINER_SEED\n\tif (!Number.isSafeInteger(seed)) {\n\t\tthrow new InferError(`The adapter calibration seed is ${seed}; pass a safe integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { seed },\n\t\t})\n\t}\n\tconst admitted = admitRows(rows)\n\tconst strata = inferStrata(admitted)\n\tconst distinctLabels = [...new Set(admitted.map((row) => row.label))]\n\tconst groups = admitted.some((row) => row.group !== undefined)\n\t\t? admitted.map((row) => row.group)\n\t\t: undefined\n\tconst assignment: readonly number[] =\n\t\toptions.assignment === undefined\n\t\t\t? assignFolds(strata, folds, seed, groups)\n\t\t\t: [...options.assignment]\n\tif (\n\t\tassignment.length !== admitted.length ||\n\t\t!assignment.every((value) => isSafeInteger(value) && value >= 0 && value < folds)\n\t) {\n\t\tthrow new InferError(\n\t\t\t`The fold assignment must hold ${admitted.length} integer fold indexes from 0 to ${folds - 1}.`,\n\t\t\t{\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\tcontext: { assignment: assignment.length, rows: admitted.length, folds },\n\t\t\t},\n\t\t)\n\t}\n\tconst foldSettings: TrainerSettings = {\n\t\tdepth: 1,\n\t\tlabels: distinctLabels,\n\t\ttarget: undefined,\n\t\tfolds,\n\t\trepeats: 1,\n\t\tseed,\n\t\tpenalties: [0],\n\t}\n\tcheckFolds(assignment, strata, foldSettings, groups)\n\tconst held = assignment.flatMap((value, index) => (value === fold ? [index] : []))\n\tconst heldRows = collectRows(admitted, held)\n\tconst expected: readonly string[] =\n\t\toptions.expected === undefined ? heldRows.map((row) => row.label) : [...options.expected]\n\tif (expected.length !== held.length || !expected.every(isString)) {\n\t\tthrow new InferError(\n\t\t\t`The expected held-fold labels must hold ${held.length} strings matching the held fold.`,\n\t\t\t{ code: 'ARGUMENT', context: { expected: expected.length, held: held.length } },\n\t\t)\n\t}\n\tconst baselineProvided = options.baseline\n\tif (\n\t\tbaselineProvided !== undefined &&\n\t\t(!isArray(baselineProvided) ||\n\t\t\tbaselineProvided.length !== held.length ||\n\t\t\t!baselineProvided.every(isString))\n\t) {\n\t\tthrow new InferError(\n\t\t\t`The baseline held-fold predictions must hold ${held.length} strings matching the held fold.`,\n\t\t\t{\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\tcontext: {\n\t\t\t\t\tbaseline: isArray(baselineProvided) ? baselineProvided.length : -1,\n\t\t\t\t\theld: held.length,\n\t\t\t\t},\n\t\t\t},\n\t\t)\n\t}\n\tconst cachedZero =\n\t\tbaselineProvided === undefined\n\t\t\t? await evaluate(adapter.scaled(0), heldRows, held, signal)\n\t\t\t: undefined\n\tif (cachedZero !== undefined) {\n\t\tif (\n\t\t\t!isRecord(cachedZero) ||\n\t\t\t!isArray(cachedZero.predictions) ||\n\t\t\tcachedZero.predictions.length !== held.length ||\n\t\t\t!cachedZero.predictions.every(isString)\n\t\t) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The baseline evaluation at scale 0 must return ${held.length} string predictions.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { scale: 0, held: held.length } },\n\t\t\t)\n\t\t}\n\t\tif (cachedZero.score !== undefined && !isFiniteNumber(cachedZero.score)) {\n\t\t\tthrow new InferError('The baseline evaluation score at scale 0 must be a finite number.', {\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\tcontext: { scale: 0 },\n\t\t\t})\n\t\t}\n\t}\n\tconst baseline: readonly string[] =\n\t\tbaselineProvided === undefined ? [...(cachedZero?.predictions ?? [])] : [...baselineProvided]\n\tconst candidates: AdapterScaleCandidate[] = []\n\tfor (const scale of scales) {\n\t\tcheckSignal(signal, 'The adapter calibration')\n\t\tconst evaluation =\n\t\t\tscale === 0 && cachedZero !== undefined\n\t\t\t\t? cachedZero\n\t\t\t\t: await evaluate(adapter.scaled(scale), heldRows, held, signal)\n\t\tif (\n\t\t\t!isRecord(evaluation) ||\n\t\t\t!isArray(evaluation.predictions) ||\n\t\t\tevaluation.predictions.length !== held.length ||\n\t\t\t!evaluation.predictions.every(isString)\n\t\t) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The evaluation at scale ${scale} must return ${held.length} string predictions.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { scale, held: held.length } },\n\t\t\t)\n\t\t}\n\t\tif (evaluation.score !== undefined && !isFiniteNumber(evaluation.score)) {\n\t\t\tthrow new InferError(`The evaluation score at scale ${scale} must be a finite number.`, {\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\tcontext: { scale },\n\t\t\t})\n\t\t}\n\t\tconst predictions = [...evaluation.predictions]\n\t\tconst flips = countFlips({ expected, before: baseline, after: predictions })\n\t\tconst score = evaluation.score ?? (flips.kept + flips.positive) / flips.total\n\t\tcandidates.push({ scale, score, flips, predictions })\n\t}\n\tconst zeroFlip = candidates.filter((entry) => entry.flips.negative === 0)\n\tconst safe = zeroFlip.length > 0\n\tconst pool = safe ? zeroFlip : candidates\n\tconst chosen = pool.reduce((best, candidate) => {\n\t\tif (!safe && candidate.flips.negative !== best.flips.negative) {\n\t\t\treturn candidate.flips.negative < best.flips.negative ? candidate : best\n\t\t}\n\t\tif (candidate.score !== best.score) {\n\t\t\treturn candidate.score > best.score ? candidate : best\n\t\t}\n\t\tif (candidate.flips.positive !== best.flips.positive) {\n\t\t\treturn candidate.flips.positive > best.flips.positive ? candidate : best\n\t\t}\n\t\tconst bestDistance = Math.abs(best.scale)\n\t\tconst candidateDistance = Math.abs(candidate.scale)\n\t\tif (candidateDistance !== bestDistance) {\n\t\t\treturn candidateDistance < bestDistance ? candidate : best\n\t\t}\n\t\treturn candidate.scale < best.scale ? candidate : best\n\t})\n\treturn {\n\t\tscale: chosen.scale,\n\t\tadapter: adapter.scaled(chosen.scale),\n\t\tscore: chosen.score,\n\t\tflips: chosen.flips,\n\t\tsafe,\n\t\theld,\n\t\tassignment,\n\t\tcandidates,\n\t}\n}\n\n/**\n * Streams a bounded-memory weight comparison between two GGUF `ByteSourceInterface` files,\n * reporting per-tensor Frobenius norm, relative delta, max abs delta, and raw-byte identity.\n *\n * @remarks\n * Reads only the GGUF headers upfront and compares every tensor in `chunk`-byte slices and\n * `strip`-row widened strips without loading either full weight file into memory. Untouched tensors\n * with identical format and raw bytes report `exact: true`, `bytes: 0`, `frobenius: 0`,\n * `relative: 0`, and `maximum: 0`. Refuses mismatched tensor sets or dimensions with `BINDING`,\n * unsupported widened tensor formats with `UNSUPPORTED`, invalid chunk/strip sizes with `ARGUMENT`,\n * and aborted signals with `ABORT`.\n *\n * @param options - The baseline and candidate GGUF byte sources, optional slice bounds, and signal\n * @returns Per-tensor and aggregate Frobenius, relative, maximum, and exact-match statistics\n *\n * @example\n * ```ts\n * const diff = await diffWeights({ before: baseSource, after: mergedSource })\n * diff.unchanged + diff.changed === diff.tensors.length // true\n * ```\n */\nexport async function diffWeights(options: WeightDiffOptions): Promise<WeightDiffResult> {\n\tif (!isRecord(options)) {\n\t\tthrow new InferError(\n\t\t\t'The weight diff options must be a plain object carrying before and after.',\n\t\t\t{\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t},\n\t\t)\n\t}\n\tconst { before, after, signal } = options\n\tcheckSignal(signal, 'The weight diff')\n\tif (\n\t\t!isObject(before) ||\n\t\ttypeof Reflect.get(before, 'read') !== 'function' ||\n\t\t!isObject(after) ||\n\t\ttypeof Reflect.get(after, 'read') !== 'function'\n\t) {\n\t\tthrow new InferError(\n\t\t\t'The weight diff before and after inputs must implement ByteSourceInterface.',\n\t\t\t{ code: 'ARGUMENT' },\n\t\t)\n\t}\n\tconst chunkBytes = options.chunk ?? MERGE_CHUNK_BYTES\n\tif (!isSafeInteger(chunkBytes) || chunkBytes < 1) {\n\t\tthrow new InferError(`The weight diff chunk size ${chunkBytes} must be a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { chunk: chunkBytes },\n\t\t})\n\t}\n\tconst stripRows = options.strip ?? MERGE_ROW_STRIP\n\tif (!isSafeInteger(stripRows) || stripRows < 1) {\n\t\tthrow new InferError(`The weight diff strip height ${stripRows} must be a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { strip: stripRows },\n\t\t})\n\t}\n\tconst beforeHeader = await readGGUF(before, signal)\n\tconst afterHeader = await readGGUF(after, signal)\n\tconst afterByName = new Map<string, GGUFTensor>(\n\t\tafterHeader.tensors.map((tensor) => [tensor.name, tensor]),\n\t)\n\tconst beforeNames = new Set(beforeHeader.tensors.map((tensor) => tensor.name))\n\tconst extra = afterHeader.tensors.find((tensor) => !beforeNames.has(tensor.name))\n\tif (extra !== undefined) {\n\t\tthrow new InferError(\n\t\t\t`The candidate GGUF file carries extra tensor ${quoteFaultText(extra.name)} absent from baseline.`,\n\t\t\t{ code: 'BINDING', context: { name: extra.name } },\n\t\t)\n\t}\n\tconst paired: Array<{ readonly left: GGUFTensor; readonly right: GGUFTensor }> =\n\t\tbeforeHeader.tensors.map((left) => {\n\t\t\tconst right = afterByName.get(left.name)\n\t\t\tif (right === undefined) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The candidate GGUF file lacks baseline tensor ${quoteFaultText(left.name)}.`,\n\t\t\t\t\t{ code: 'BINDING', context: { name: left.name } },\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (\n\t\t\t\tleft.dimensions.length !== right.dimensions.length ||\n\t\t\t\tleft.dimensions.some((extent, index) => extent !== right.dimensions[index])\n\t\t\t) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The tensor ${quoteFaultText(left.name)} has dimensions [${left.dimensions.join(', ')}] in baseline and [${right.dimensions.join(', ')}] in candidate.`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'BINDING',\n\t\t\t\t\t\tcontext: { name: left.name, before: left.dimensions, after: right.dimensions },\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn { left, right }\n\t\t})\n\tconst records: Array<{\n\t\treadonly left: GGUFTensor\n\t\treadonly entry: TensorWeightDiff\n\t\treadonly diffSumSq: number\n\t\treadonly baseSumSq: number | undefined\n\t}> = []\n\tfor (const { left, right } of paired) {\n\t\tcheckSignal(signal, 'The weight diff')\n\t\tconst leftBytes = computeTensorBytes(left)\n\t\tconst rightBytes = computeTensorBytes(right)\n\t\tconst leftStart = beforeHeader.offset + left.offset\n\t\tconst rightStart = afterHeader.offset + right.offset\n\t\tconst overlap = Math.min(leftBytes, rightBytes)\n\t\tlet differingBytes = Math.abs(leftBytes - rightBytes)\n\t\tfor (let pos = 0; pos < overlap; pos += chunkBytes) {\n\t\t\tcheckSignal(signal, 'The weight diff')\n\t\t\tconst sliceLength = Math.min(chunkBytes, overlap - pos)\n\t\t\tconst leftSlice = await before.read(leftStart + pos, sliceLength, signal)\n\t\t\tconst rightSlice = await after.read(rightStart + pos, sliceLength, signal)\n\t\t\tfor (let byteIndex = 0; byteIndex < sliceLength; byteIndex += 1) {\n\t\t\t\tif (leftSlice[byteIndex] !== rightSlice[byteIndex]) differingBytes += 1\n\t\t\t}\n\t\t}\n\t\tconst exact = left.format === right.format && differingBytes === 0\n\t\tif (exact) {\n\t\t\trecords.push({\n\t\t\t\tleft,\n\t\t\t\tentry: {\n\t\t\t\t\tname: left.name,\n\t\t\t\t\tdimensions: [...left.dimensions],\n\t\t\t\t\tbefore: left.format,\n\t\t\t\t\tafter: right.format,\n\t\t\t\t\texact: true,\n\t\t\t\t\tbytes: 0,\n\t\t\t\t\tfrobenius: 0,\n\t\t\t\t\trelative: 0,\n\t\t\t\t\tmaximum: 0,\n\t\t\t\t},\n\t\t\t\tdiffSumSq: 0,\n\t\t\t\tbaseSumSq: undefined,\n\t\t\t})\n\t\t\tcontinue\n\t\t}\n\t\tif (!MERGE_SOURCE_FORMATS.includes(left.format)) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The baseline tensor ${quoteFaultText(left.name)} uses unsupported format ${quoteFaultText(left.format)}.`,\n\t\t\t\t{ code: 'UNSUPPORTED', context: { name: left.name, format: left.format } },\n\t\t\t)\n\t\t}\n\t\tif (!MERGE_SOURCE_FORMATS.includes(right.format)) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The candidate tensor ${quoteFaultText(right.name)} uses unsupported format ${quoteFaultText(right.format)}.`,\n\t\t\t\t{ code: 'UNSUPPORTED', context: { name: right.name, format: right.format } },\n\t\t\t)\n\t\t}\n\t\tconst elements = computeElements(left.dimensions)\n\t\tconst leftBlock = GGUF_BLOCKS[left.format]\n\t\tconst rightBlock = GGUF_BLOCKS[right.format]\n\t\tif (elements % leftBlock.elements !== 0 || elements % rightBlock.elements !== 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The tensor ${quoteFaultText(left.name)} element count ${elements} is not aligned to its format blocks.`,\n\t\t\t\t{\n\t\t\t\t\tcode: 'FORMAT',\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\tname: left.name,\n\t\t\t\t\t\telements,\n\t\t\t\t\t\tbefore: leftBlock.elements,\n\t\t\t\t\t\tafter: rightBlock.elements,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\tconst smallBlock = Math.min(leftBlock.elements, rightBlock.elements)\n\t\tconst largeBlock = Math.max(leftBlock.elements, rightBlock.elements)\n\t\tconst unitElements =\n\t\t\tArray.from({ length: smallBlock }, (_, index) => largeBlock * (index + 1)).find(\n\t\t\t\t(candidate) => candidate % smallBlock === 0,\n\t\t\t) ?? largeBlock * smallBlock\n\t\tconst firstExtent = left.dimensions[0] ?? 0\n\t\tconst rowAligned =\n\t\t\tleft.dimensions.length >= 2 && firstExtent > 0 && firstExtent % unitElements === 0\n\t\tconst unitBytes = Math.max(\n\t\t\t(unitElements / leftBlock.elements) * leftBlock.bytes,\n\t\t\t(unitElements / rightBlock.elements) * rightBlock.bytes,\n\t\t)\n\t\tconst stripElements = rowAligned\n\t\t\t? Math.max(\n\t\t\t\t\t1,\n\t\t\t\t\tMath.min(\n\t\t\t\t\t\tstripRows,\n\t\t\t\t\t\tMath.max(\n\t\t\t\t\t\t\t1,\n\t\t\t\t\t\t\tMath.floor(\n\t\t\t\t\t\t\t\tchunkBytes /\n\t\t\t\t\t\t\t\t\tMath.max(\n\t\t\t\t\t\t\t\t\t\t(firstExtent / leftBlock.elements) * leftBlock.bytes,\n\t\t\t\t\t\t\t\t\t\t(firstExtent / rightBlock.elements) * rightBlock.bytes,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t) * firstExtent\n\t\t\t: Math.max(1, Math.min(stripRows, Math.max(1, Math.floor(chunkBytes / unitBytes)))) *\n\t\t\t\tunitElements\n\t\tlet diffSumSq = 0\n\t\tlet baseSumSq = 0\n\t\tlet maxAbs = 0\n\t\tfor (let elemPos = 0; elemPos < elements; elemPos += stripElements) {\n\t\t\tcheckSignal(signal, 'The weight diff')\n\t\t\tconst count = Math.min(stripElements, elements - elemPos)\n\t\t\tconst leftRaw = await before.read(\n\t\t\t\tleftStart + (elemPos / leftBlock.elements) * leftBlock.bytes,\n\t\t\t\t(count / leftBlock.elements) * leftBlock.bytes,\n\t\t\t\tsignal,\n\t\t\t)\n\t\t\tconst rightRaw = await after.read(\n\t\t\t\trightStart + (elemPos / rightBlock.elements) * rightBlock.bytes,\n\t\t\t\t(count / rightBlock.elements) * rightBlock.bytes,\n\t\t\t\tsignal,\n\t\t\t)\n\t\t\tconst leftWide = widenTensor(leftRaw, left.format)\n\t\t\tconst rightWide = widenTensor(rightRaw, right.format)\n\t\t\tfor (let index = 0; index < count; index += 1) {\n\t\t\t\tconst leftVal = leftWide[index] ?? 0\n\t\t\t\tconst rightVal = rightWide[index] ?? 0\n\t\t\t\tconst delta = rightVal - leftVal\n\t\t\t\tconst absDelta = Math.abs(delta)\n\t\t\t\tdiffSumSq += delta * delta\n\t\t\t\tbaseSumSq += leftVal * leftVal\n\t\t\t\tif (absDelta > maxAbs) maxAbs = absDelta\n\t\t\t}\n\t\t}\n\t\tconst frobenius = Math.sqrt(diffSumSq)\n\t\tconst baseNorm = Math.sqrt(baseSumSq)\n\t\tconst relative =\n\t\t\tfrobenius === 0 ? 0 : baseNorm === 0 ? Number.POSITIVE_INFINITY : frobenius / baseNorm\n\t\trecords.push({\n\t\t\tleft,\n\t\t\tentry: {\n\t\t\t\tname: left.name,\n\t\t\t\tdimensions: [...left.dimensions],\n\t\t\t\tbefore: left.format,\n\t\t\t\tafter: right.format,\n\t\t\t\texact: false,\n\t\t\t\tbytes: differingBytes,\n\t\t\t\tfrobenius,\n\t\t\t\trelative,\n\t\t\t\tmaximum: maxAbs,\n\t\t\t},\n\t\t\tdiffSumSq,\n\t\t\tbaseSumSq,\n\t\t})\n\t}\n\tconst totalDiffSumSq = records.reduce((sum, item) => sum + item.diffSumSq, 0)\n\tconst frobenius = Math.sqrt(totalDiffSumSq)\n\tconst exactBaseSums: number[] = []\n\tif (frobenius > 0) {\n\t\tfor (const item of records) {\n\t\t\tif (item.baseSumSq !== undefined || !MERGE_SOURCE_FORMATS.includes(item.left.format)) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tconst elements = computeElements(item.left.dimensions)\n\t\t\tconst block = GGUF_BLOCKS[item.left.format]\n\t\t\tif (elements % block.elements !== 0) continue\n\t\t\tconst start = beforeHeader.offset + item.left.offset\n\t\t\tconst firstExtent = item.left.dimensions[0] ?? 0\n\t\t\tconst rowAligned =\n\t\t\t\titem.left.dimensions.length >= 2 && firstExtent > 0 && firstExtent % block.elements === 0\n\t\t\tconst stripElements = rowAligned\n\t\t\t\t? Math.max(\n\t\t\t\t\t\t1,\n\t\t\t\t\t\tMath.min(\n\t\t\t\t\t\t\tstripRows,\n\t\t\t\t\t\t\tMath.max(1, Math.floor(chunkBytes / ((firstExtent / block.elements) * block.bytes))),\n\t\t\t\t\t\t),\n\t\t\t\t\t) * firstExtent\n\t\t\t\t: Math.max(1, Math.min(stripRows, Math.max(1, Math.floor(chunkBytes / block.bytes)))) *\n\t\t\t\t\tblock.elements\n\t\t\tlet baseSumSq = 0\n\t\t\tfor (let elemPos = 0; elemPos < elements; elemPos += stripElements) {\n\t\t\t\tcheckSignal(signal, 'The weight diff')\n\t\t\t\tconst count = Math.min(stripElements, elements - elemPos)\n\t\t\t\tconst raw = await before.read(\n\t\t\t\t\tstart + (elemPos / block.elements) * block.bytes,\n\t\t\t\t\t(count / block.elements) * block.bytes,\n\t\t\t\t\tsignal,\n\t\t\t\t)\n\t\t\t\tconst widened = widenTensor(raw, item.left.format)\n\t\t\t\tfor (let index = 0; index < count; index += 1) {\n\t\t\t\t\tconst value = widened[index] ?? 0\n\t\t\t\t\tbaseSumSq += value * value\n\t\t\t\t}\n\t\t\t}\n\t\t\texactBaseSums.push(baseSumSq)\n\t\t}\n\t}\n\tconst totalBaseSumSq =\n\t\trecords.reduce((sum, item) => sum + (item.baseSumSq ?? 0), 0) +\n\t\texactBaseSums.reduce((sum, value) => sum + value, 0)\n\tconst totalBaseNorm = Math.sqrt(totalBaseSumSq)\n\tconst relative =\n\t\tfrobenius === 0 ? 0 : totalBaseNorm === 0 ? Number.POSITIVE_INFINITY : frobenius / totalBaseNorm\n\tconst tensors = records.map((item) => item.entry)\n\tconst maximum = tensors.reduce((peak, entry) => Math.max(peak, entry.maximum), 0)\n\tconst unchanged = tensors.filter((entry) => entry.exact).length\n\treturn {\n\t\ttensors,\n\t\tfrobenius,\n\t\trelative,\n\t\tmaximum,\n\t\tunchanged,\n\t\tchanged: tensors.length - unchanged,\n\t}\n}\n\n/**\n * Combines `N >= 1` weighted `AdapterInterface` instances into one immutable `Adapter` whose\n * weight delta equals the weighted sum of every input adapter's delta.\n *\n * @remarks\n * Validates non-empty entries, finite scalar weights, compatible decoder `family`, compatible\n * `base` digests, and matching `(rows, columns)` shapes per shared target. When every contributor\n * to a target shares the same rank and identical `down` basis matrix (including a single\n * contributor), performs an exact linear merge without increasing rank; otherwise performs exact\n * block-stacked rank concatenation (`down = [A_1; ...; A_m]`, `up = [s_1 B_1, ..., s_m B_m]`) so\n * cross terms remain identically zero. Serializes through `buildAdapterGGUF` to derive the exact\n * SHA-256 `digest` of the returned `Adapter`. Refuses invalid inputs with `ARGUMENT`, incompatible\n * families, bases, or tensor shapes with `BINDING`, and aborted signals with `ABORT`.\n *\n * @param entries - One or more weighted adapters to combine\n * @param options - Optional combined LoRA alpha, base digest binding check, and abort signal\n * @returns The combined immutable `Adapter` instance\n *\n * @example\n * ```ts\n * const combined = await combineAdapters([\n * \t{ adapter: verdictAdapter, weight: 0.5 },\n * \t{ adapter: rewordAdapter, weight: 0.5 },\n * ])\n * combined.scale // 1\n * ```\n */\nexport async function combineAdapters(\n\tentries: readonly AdapterCombinationEntry[],\n\toptions?: AdapterCombinationOptions,\n): Promise<Adapter> {\n\tconst signal = options?.signal\n\tcheckSignal(signal, 'The adapter combine')\n\tif (!isArray(entries) || entries.length === 0) {\n\t\tthrow new InferError('The adapter combine requires at least one adapter entry.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tif (options !== undefined && !isRecord(options)) {\n\t\tthrow new InferError('The adapter combine options must be a plain object.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tconst explicitBase = options?.base\n\tif (\n\t\texplicitBase !== undefined &&\n\t\t(!isString(explicitBase) || !SHA256_PATTERN.test(explicitBase))\n\t) {\n\t\tthrow new InferError(\n\t\t\t`The adapter combine base digest ${quoteFaultText(String(explicitBase))} must be a 64-character lowercase SHA-256 hex string.`,\n\t\t\t{ code: 'ARGUMENT', context: { base: explicitBase } },\n\t\t)\n\t}\n\tconst checkedEntries = entries.map((entry, index) => {\n\t\tif (!isRecord(entry) || !isObject(entry.adapter)) {\n\t\t\tthrow new InferError(`The adapter combine entry at index ${index} must carry an adapter.`, {\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\tcontext: { entry: index },\n\t\t\t})\n\t\t}\n\t\tcheckAdapterOptions(entry.adapter)\n\t\tconst weight = entry.weight ?? 1\n\t\tif (!isFiniteNumber(weight)) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The adapter combine weight at index ${index} is ${weight}; pass a finite number.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { entry: index, weight } },\n\t\t\t)\n\t\t}\n\t\treturn { adapter: entry.adapter, weight }\n\t})\n\tconst [firstEntry] = checkedEntries\n\tif (firstEntry === undefined) {\n\t\tthrow new InferError('The adapter combine requires at least one adapter entry.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tconst family = firstEntry.adapter.family\n\tconst mismatchedFamily = checkedEntries.find((entry) => entry.adapter.family !== family)\n\tif (mismatchedFamily !== undefined) {\n\t\tthrow new InferError(\n\t\t\t`The adapters target incompatible families ${quoteFaultText(family)} and ${quoteFaultText(mismatchedFamily.adapter.family)}.`,\n\t\t\t{ code: 'BINDING', context: { expected: family, actual: mismatchedFamily.adapter.family } },\n\t\t)\n\t}\n\tconst declaredBases = [\n\t\t...new Set(\n\t\t\tcheckedEntries.flatMap((entry) =>\n\t\t\t\tentry.adapter.base === undefined ? [] : [entry.adapter.base],\n\t\t\t),\n\t\t),\n\t]\n\tif (explicitBase !== undefined) {\n\t\tconst wrongBase = declaredBases.find((base) => base !== explicitBase)\n\t\tif (wrongBase !== undefined) {\n\t\t\tthrow new InferError(\n\t\t\t\t`An input adapter binds base ${quoteFaultText(wrongBase)}, differing from expected base ${quoteFaultText(explicitBase)}.`,\n\t\t\t\t{ code: 'BINDING', context: { expected: explicitBase, actual: wrongBase } },\n\t\t\t)\n\t\t}\n\t} else if (declaredBases.length > 1) {\n\t\tthrow new InferError(\n\t\t\t`The input adapters bind conflicting bases ${declaredBases.map(quoteFaultText).join(' and ')}.`,\n\t\t\t{ code: 'BINDING', context: { bases: declaredBases } },\n\t\t)\n\t}\n\tconst resolvedBase = explicitBase ?? declaredBases[0]\n\tconst outAlpha = options?.alpha ?? firstEntry.adapter.alpha\n\tif (!isFiniteNumber(outAlpha) || outAlpha <= 0) {\n\t\tthrow new InferError(\n\t\t\t`The combined adapter alpha is ${outAlpha}; pass a positive finite number.`,\n\t\t\t{ code: 'ARGUMENT', context: { alpha: outAlpha } },\n\t\t)\n\t}\n\tconst grouped = new Map<\n\t\tstring,\n\t\tArray<{ readonly pair: AdapterPair; readonly coefficient: number }>\n\t>()\n\tfor (const entry of checkedEntries) {\n\t\tfor (const pair of entry.adapter.pairs) {\n\t\t\tconst coefficient = entry.weight * entry.adapter.scale * (pair.alpha / pair.rank)\n\t\t\tconst bucket = grouped.get(pair.name)\n\t\t\tif (bucket === undefined) {\n\t\t\t\tgrouped.set(pair.name, [{ pair, coefficient }])\n\t\t\t} else {\n\t\t\t\tbucket.push({ pair, coefficient })\n\t\t\t}\n\t\t}\n\t}\n\tconst orderedKeys = [...grouped.keys()].toSorted((leftKey, rightKey) => {\n\t\tconst leftPair = grouped.get(leftKey)?.[0]?.pair\n\t\tconst rightPair = grouped.get(rightKey)?.[0]?.pair\n\t\tif (leftPair === undefined || rightPair === undefined) return leftKey.localeCompare(rightKey)\n\t\treturn (\n\t\t\tleftPair.layer - rightPair.layer ||\n\t\t\tADAPTER_TARGETS.indexOf(leftPair.target) - ADAPTER_TARGETS.indexOf(rightPair.target)\n\t\t)\n\t})\n\tconst combinedPairs: readonly AdapterPair[] = orderedKeys.map((name) => {\n\t\tconst bucket = grouped.get(name) ?? []\n\t\tconst [head] = bucket\n\t\tif (head === undefined) {\n\t\t\tthrow new InferError(`The combined target ${quoteFaultText(name)} holds no pairs.`, {\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\tcontext: { name },\n\t\t\t})\n\t\t}\n\t\tconst { layer, group, slot, target, columns, rows } = head.pair\n\t\tfor (const item of bucket) {\n\t\t\tif (\n\t\t\t\titem.pair.layer !== layer ||\n\t\t\t\titem.pair.target !== target ||\n\t\t\t\titem.pair.columns !== columns ||\n\t\t\t\titem.pair.rows !== rows\n\t\t\t) {\n\t\t\t\tthrow new InferError(\n\t\t\t\t\t`The adapters disagree on shape for ${quoteFaultText(name)}: [${columns}, ${rows}] vs [${item.pair.columns}, ${item.pair.rows}].`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcode: 'BINDING',\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\texpected: [columns, rows],\n\t\t\t\t\t\t\tactual: [item.pair.columns, item.pair.rows],\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\tconst matchingBasis =\n\t\t\tbucket.length === 1 ||\n\t\t\tbucket.every(\n\t\t\t\t(item) =>\n\t\t\t\t\titem.pair.rank === head.pair.rank &&\n\t\t\t\t\titem.pair.down.every((value, index) => value === head.pair.down[index]),\n\t\t\t)\n\t\tif (matchingBasis) {\n\t\t\tconst rank = head.pair.rank\n\t\t\tconst down = Float32Array.from(head.pair.down)\n\t\t\tconst up = new Float32Array(rows * rank)\n\t\t\tconst scaleFactor = rank / outAlpha\n\t\t\tfor (let index = 0; index < up.length; index += 1) {\n\t\t\t\tlet sum = 0\n\t\t\t\tfor (let itemIndex = 0; itemIndex < bucket.length; itemIndex += 1) {\n\t\t\t\t\tconst item = bucket[itemIndex]\n\t\t\t\t\tif (item === undefined) continue\n\t\t\t\t\tsum += item.coefficient * (item.pair.up[index] ?? 0)\n\t\t\t\t}\n\t\t\t\tconst value = Math.fround(scaleFactor * sum)\n\t\t\t\tif (!Number.isFinite(value)) {\n\t\t\t\t\tthrow new InferError(\n\t\t\t\t\t\t`The combined up projection for ${quoteFaultText(name)} overflowed single precision.`,\n\t\t\t\t\t\t{ code: 'ARGUMENT', context: { name } },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tup[index] = value\n\t\t\t}\n\t\t\treturn { name, layer, group, slot, target, columns, rows, rank, alpha: outAlpha, down, up }\n\t\t}\n\t\tconst totalRank = bucket.reduce((sum, item) => sum + item.pair.rank, 0)\n\t\tif (\n\t\t\t!isSafeInteger(totalRank) ||\n\t\t\t!isSafeInteger(totalRank * columns) ||\n\t\t\t!isSafeInteger(rows * totalRank)\n\t\t) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The combined rank ${totalRank} for ${quoteFaultText(name)} exceeds safe integer limits.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { name, rank: totalRank } },\n\t\t\t)\n\t\t}\n\t\tconst down = new Float32Array(totalRank * columns)\n\t\tconst up = new Float32Array(rows * totalRank)\n\t\tlet rankOffset = 0\n\t\tfor (let itemIndex = 0; itemIndex < bucket.length; itemIndex += 1) {\n\t\t\tconst item = bucket[itemIndex]\n\t\t\tif (item === undefined) continue\n\t\t\tdown.set(item.pair.down, rankOffset * columns)\n\t\t\tconst factor = (totalRank * item.coefficient) / outAlpha\n\t\t\tfor (let row = 0; row < rows; row += 1) {\n\t\t\t\tconst dstRow = row * totalRank + rankOffset\n\t\t\t\tconst srcRow = row * item.pair.rank\n\t\t\t\tfor (let col = 0; col < item.pair.rank; col += 1) {\n\t\t\t\t\tconst value = Math.fround(factor * (item.pair.up[srcRow + col] ?? 0))\n\t\t\t\t\tif (!Number.isFinite(value)) {\n\t\t\t\t\t\tthrow new InferError(\n\t\t\t\t\t\t\t`The combined up projection for ${quoteFaultText(name)} overflowed single precision.`,\n\t\t\t\t\t\t\t{ code: 'ARGUMENT', context: { name } },\n\t\t\t\t\t\t)\n\t\t\t\t\t}\n\t\t\t\t\tup[dstRow + col] = value\n\t\t\t\t}\n\t\t\t}\n\t\t\trankOffset += item.pair.rank\n\t\t}\n\t\treturn {\n\t\t\tname,\n\t\t\tlayer,\n\t\t\tgroup,\n\t\t\tslot,\n\t\t\ttarget,\n\t\t\tcolumns,\n\t\t\trows,\n\t\t\trank: totalRank,\n\t\t\talpha: outAlpha,\n\t\t\tdown,\n\t\t\tup,\n\t\t}\n\t})\n\tcheckSignal(signal, 'The adapter combine')\n\tconst placeholderOptions: AdapterOptions = {\n\t\tdigest: '0'.repeat(64),\n\t\tfamily,\n\t\talpha: outAlpha,\n\t\t...(resolvedBase === undefined ? {} : { base: resolvedBase }),\n\t\tscale: 1,\n\t\tpairs: combinedPairs,\n\t}\n\tconst ggufBytes = buildAdapterGGUF(placeholderOptions)\n\tconst digest = await digestBytes(ggufBytes)\n\treturn new Adapter({\n\t\tdigest,\n\t\tfamily,\n\t\talpha: outAlpha,\n\t\t...(resolvedBase === undefined ? {} : { base: resolvedBase }),\n\t\tscale: 1,\n\t\tpairs: combinedPairs,\n\t})\n}\n\n/**\n * Permutes one full-rank `SectionEntry` between GGUF layout and Hugging Face safetensors layout\n * for `llama` rotary projections (`attn_q`, `attn_k`) and `qwen35` grouped-value DeltaNet\n * projections (`values !== keys`).\n *\n * @remarks\n * Inverts GGUF adjacent-pair rotary rows through `deinterleaveRotary` when `toGGUF` is `false`\n * (and applies `interleaveRotary` when `toGGUF` is `true`). On `qwen35` architectures with\n * `delta.values !== delta.keys`, permutes value-head blocks across `attn_qkv`, `attn_gate`,\n * `ssm_alpha`, `ssm_beta`, `ssm_conv1d`, `ssm_dt`, `ssm_a`, and `ssm_out`. Returns `entry`\n * unchanged when `architecture` is absent or no layout transform applies.\n *\n * @param entry - The full-rank section tensor entry\n * @param architecture - Optional base decoder architecture carrying head counts\n * @param toGGUF - If `true`, converts Hugging Face order to GGUF order; if `false`, GGUF to Hugging Face\n * @returns The layout-permuted `SectionEntry`\n *\n * @example\n * ```ts\n * permuteSectionEntry(entry, undefined, false) === entry // true\n * ```\n */\nexport function permuteSectionEntry(\n\tentry: SectionEntry,\n\tarchitecture: Architecture | undefined,\n\ttoGGUF: boolean,\n): SectionEntry {\n\tif (architecture === undefined) return entry\n\tif (\n\t\tARCHITECTURE_FAMILIES[architecture.family].interleaved &&\n\t\t(entry.target === 'attn_q' || entry.target === 'attn_k')\n\t) {\n\t\tconst heads = entry.target === 'attn_q' ? architecture.queries : architecture.groups\n\t\tconst expectedRows = heads * architecture.head\n\t\tif (entry.rows !== expectedRows) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The ${entry.target} section entry ${quoteFaultText(entry.name)} has ${entry.rows} rows; expected ${expectedRows}.`,\n\t\t\t\t{\n\t\t\t\t\tcode: 'BINDING',\n\t\t\t\t\tcontext: { name: entry.name, rows: entry.rows, expected: expectedRows },\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\tconst bytes = new Uint8Array(\n\t\t\tentry.values.buffer,\n\t\t\tentry.values.byteOffset,\n\t\t\tentry.values.byteLength,\n\t\t)\n\t\tconst rowBytes = entry.columns * 4\n\t\tconst reordered = toGGUF\n\t\t\t? interleaveRotary(bytes, heads, rowBytes)\n\t\t\t: deinterleaveRotary(bytes, heads, rowBytes)\n\t\treturn { ...entry, values: new Float32Array(reordered.buffer) }\n\t}\n\tconst delta = architecture.delta\n\tif (delta === undefined || delta.values === delta.keys) return entry\n\tconst { keys, values, head } = delta\n\tif (\n\t\t!isSafeInteger(keys) ||\n\t\tkeys < 1 ||\n\t\t!isSafeInteger(values) ||\n\t\tvalues < 1 ||\n\t\tvalues % keys !== 0 ||\n\t\t!isSafeInteger(head) ||\n\t\thead < 1\n\t) {\n\t\tthrow new InferError('The delta architecture head counts are invalid for permutation.', {\n\t\t\tcode: 'FORMAT',\n\t\t\tcontext: { keys, values, head },\n\t\t})\n\t}\n\tif (entry.target === 'attn_qkv' || entry.target === 'ssm_conv1d') {\n\t\tconst prefixRows = 2 * keys * head\n\t\tconst expectedRows = prefixRows + values * head\n\t\tif (entry.rows !== expectedRows) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The ${entry.target} section entry ${quoteFaultText(entry.name)} has ${entry.rows} rows; expected ${expectedRows}.`,\n\t\t\t\t{\n\t\t\t\t\tcode: 'BINDING',\n\t\t\t\t\tcontext: { name: entry.name, rows: entry.rows, expected: expectedRows },\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\tconst prefixFloats = prefixRows * entry.columns\n\t\tconst valueSlice = permuteHeadBlocks(\n\t\t\tentry.values.subarray(prefixFloats),\n\t\t\t1,\n\t\t\tvalues,\n\t\t\tkeys,\n\t\t\thead * entry.columns,\n\t\t\ttoGGUF,\n\t\t)\n\t\tconst out = new Float32Array(entry.values.length)\n\t\tout.set(entry.values.subarray(0, prefixFloats), 0)\n\t\tout.set(valueSlice, prefixFloats)\n\t\treturn { ...entry, values: out }\n\t}\n\tif (entry.target === 'attn_gate') {\n\t\tconst expectedRows = values * head\n\t\tif (entry.rows !== expectedRows) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The attn_gate section entry ${quoteFaultText(entry.name)} has ${entry.rows} rows; expected ${expectedRows}.`,\n\t\t\t\t{\n\t\t\t\t\tcode: 'BINDING',\n\t\t\t\t\tcontext: { name: entry.name, rows: entry.rows, expected: expectedRows },\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\treturn {\n\t\t\t...entry,\n\t\t\tvalues: permuteHeadBlocks(entry.values, 1, values, keys, head * entry.columns, toGGUF),\n\t\t}\n\t}\n\tif (entry.target === 'ssm_alpha' || entry.target === 'ssm_beta') {\n\t\tif (entry.rows !== values) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The ${entry.target} section entry ${quoteFaultText(entry.name)} has ${entry.rows} rows; expected ${values}.`,\n\t\t\t\t{ code: 'BINDING', context: { name: entry.name, rows: entry.rows, expected: values } },\n\t\t\t)\n\t\t}\n\t\treturn {\n\t\t\t...entry,\n\t\t\tvalues: permuteHeadBlocks(entry.values, 1, values, keys, entry.columns, toGGUF),\n\t\t}\n\t}\n\tif (entry.target === 'ssm_dt' || entry.target === 'ssm_a') {\n\t\tif (entry.columns !== values) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The ${entry.target} section entry ${quoteFaultText(entry.name)} has ${entry.columns} columns; expected ${values}.`,\n\t\t\t\t{\n\t\t\t\t\tcode: 'BINDING',\n\t\t\t\t\tcontext: { name: entry.name, columns: entry.columns, expected: values },\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\treturn {\n\t\t\t...entry,\n\t\t\tvalues: permuteHeadBlocks(entry.values, 1, values, keys, 1, toGGUF),\n\t\t}\n\t}\n\tif (entry.target === 'ssm_out') {\n\t\tconst expectedColumns = values * head\n\t\tif (entry.columns !== expectedColumns) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The ssm_out section entry ${quoteFaultText(entry.name)} has ${entry.columns} columns; expected ${expectedColumns}.`,\n\t\t\t\t{\n\t\t\t\t\tcode: 'BINDING',\n\t\t\t\t\tcontext: { name: entry.name, columns: entry.columns, expected: expectedColumns },\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t\treturn {\n\t\t\t...entry,\n\t\t\tvalues: permuteHeadBlocks(entry.values, entry.rows, values, keys, head, toGGUF),\n\t\t}\n\t}\n\treturn entry\n}\n\n/**\n * Serializes validated full-rank section patch options or a live `SectionInterface` into a GGUF v3\n * section patch file (`general.type = \"patch\"`, `orkestrel.patch.version = 1`, optional\n * `orkestrel.base`) readable by `readSectionGGUF` and `@orkestrel/infer`'s `createSection`.\n *\n * @remarks\n * Admits `'F32'` (default), `'BF16'`, and `'Q8_0'`. When `format` is `'Q8_0'`, 1D tensors and\n * tensors whose column width is not a multiple of 32 are stored as `'F32'` so normalization gains,\n * biases, and 4-tap convolutions round-trip losslessly alongside `Q8_0`-compressed weight matrices.\n * Entries are ordered canonically by ascending layer and `SECTION_TARGETS` order, with top-level\n * entries trailing.\n *\n * @param options - The validated section options or live section patch\n * @param format - Storage format for full-rank patch tensors (`'F32'`, `'BF16'`, or `'Q8_0'`). Default: `'F32'`\n * @returns The serialized GGUF v3 section patch bytes\n *\n * @example\n * ```ts\n * const bytes = buildSectionGGUF(section, 'BF16')\n * ```\n */\nexport function buildSectionGGUF(\n\toptions: SectionOptions | SectionInterface,\n\tformat: SectionFormat = 'F32',\n): Uint8Array<ArrayBuffer> {\n\tconst normalized: SectionOptions = {\n\t\tdigest: options.digest,\n\t\tfamily: options.family,\n\t\tentries: options.entries,\n\t\t...(options.base === undefined ? {} : { base: options.base }),\n\t}\n\tcheckSectionOptions(normalized)\n\tif (!isSectionFormat(format)) {\n\t\tthrow new InferError(\n\t\t\t`The section patch format ${quoteFaultText(String(format))} must be \"F32\", \"BF16\", or \"Q8_0\".`,\n\t\t\t{ code: 'ARGUMENT', context: { format } },\n\t\t)\n\t}\n\tconst ordered = [...options.entries].toSorted((left, right) => {\n\t\tconst leftLayer = left.layer ?? Number.POSITIVE_INFINITY\n\t\tconst rightLayer = right.layer ?? Number.POSITIVE_INFINITY\n\t\treturn (\n\t\t\tleftLayer - rightLayer ||\n\t\t\tSECTION_TARGETS.indexOf(left.target) - SECTION_TARGETS.indexOf(right.target)\n\t\t)\n\t})\n\tconst metadata = new Map<string, GGUFValue>([\n\t\t[SECTION_KEYS.role, { encoding: 'string', value: SECTION_PATCH_TYPE }],\n\t\t[SECTION_KEYS.version, { encoding: 'uint32', value: SECTION_PATCH_VERSION }],\n\t\t[GGUF_KEYS.architecture, { encoding: 'string', value: options.family }],\n\t\t[GGUF_KEYS.alignment, { encoding: 'uint32', value: GGUF_ALIGNMENT }],\n\t\t...(options.base === undefined\n\t\t\t? []\n\t\t\t: [[SECTION_KEYS.base, { encoding: 'string', value: options.base }] as const]),\n\t])\n\tconst items = ordered.map((entry) => {\n\t\tconst dimensions = entry.rows === 1 ? [entry.columns] : [entry.columns, entry.rows]\n\t\tconst tensorFormat: SectionFormat =\n\t\t\tformat === 'Q8_0' && (entry.rows === 1 || entry.columns % GGUF_BLOCKS.Q8_0.elements !== 0)\n\t\t\t\t? 'F32'\n\t\t\t\t: format\n\t\treturn {\n\t\t\tname: entry.name,\n\t\t\tdimensions,\n\t\t\tformat: tensorFormat,\n\t\t\tbytes: encodeGGUFValues(entry.values, tensorFormat),\n\t\t}\n\t})\n\tconst tensors: GGUFTensor[] = []\n\tlet offset = 0\n\tfor (let index = 0; index < items.length; index += 1) {\n\t\tconst item = items[index]\n\t\tif (item === undefined) continue\n\t\ttensors.push({\n\t\t\tname: item.name,\n\t\t\tdimensions: item.dimensions,\n\t\t\tformat: item.format,\n\t\t\toffset,\n\t\t})\n\t\toffset = alignOffset(offset + item.bytes.byteLength, GGUF_ALIGNMENT)\n\t}\n\tconst data = new Uint8Array(offset)\n\tfor (let index = 0; index < items.length; index += 1) {\n\t\tconst item = items[index]\n\t\tconst tensor = tensors[index]\n\t\tif (item === undefined || tensor === undefined) continue\n\t\tdata.set(item.bytes, tensor.offset)\n\t}\n\treturn buildGGUF(metadata, tensors, data)\n}\n\n/**\n * Reads and validates a GGUF v3 full-rank section patch from a `ByteSourceInterface`, returning an\n * immutable `SectionInterface` and verifying optional architecture and base bindings.\n *\n * @remarks\n * Delegates GGUF v3 decoding (`general.type = \"patch\"`, `orkestrel.patch.version = 1`, `F32`/`BF16`/\n * `Q8_0` widening) to `@orkestrel/infer`'s `readSection`, wraps the result in `new Section(...)`,\n * and verifies `options.architecture` and `options.base` through `checkSectionBinding` (refusing\n * mismatches with `BINDING`). Works identically in Node and Chromium.\n *\n * @param source - The byte source holding the GGUF v3 section patch\n * @param options - Optional architecture binding, base digest binding, and abort signal\n * @returns The immutable `SectionInterface`\n *\n * @example\n * ```ts\n * const patch = await readSectionGGUF(new MemorySource(bytes), { architecture, base })\n * await backbone.section(patch)\n * ```\n */\nexport async function readSectionGGUF(\n\tsource: ByteSourceInterface,\n\toptions: SectionReadOptions = {},\n): Promise<SectionInterface> {\n\tcheckSignal(options.signal, 'The section patch read')\n\tconst parsed = await readSection(source, options.signal)\n\tconst patch = new Section(parsed)\n\tif (options.architecture !== undefined) {\n\t\tcheckSectionBinding(patch, options.architecture, options.base)\n\t} else if (\n\t\toptions.base !== undefined &&\n\t\tpatch.base !== undefined &&\n\t\tpatch.base !== options.base\n\t) {\n\t\tthrow new InferError(\n\t\t\t`The section patch binds to base ${quoteFaultText(patch.base)}, not expected ${quoteFaultText(options.base)}.`,\n\t\t\t{ code: 'BINDING', context: { patch: patch.base, expected: options.base } },\n\t\t)\n\t}\n\treturn patch\n}\n\n/**\n * Computes the learning rate for 1-based optimizer step `step` out of `total` steps under linear\n * warmup followed by `'cosine'` or `'constant'` schedule.\n *\n * @remarks\n * During warmup (`warmup > 0 && step <= warmup`), scales linearly as `rate * (step / warmup)`.\n * After warmup, `'constant'` returns `rate` and `'cosine'` decays along\n * `0.5 * rate * (1 + cos(pi * (step - warmup) / max(1, total - warmup)))`.\n *\n * @param step - The 1-based optimizer step index\n * @param total - The total planned optimizer steps\n * @param rate - The peak non-negative finite learning rate\n * @param warmup - The non-negative integer linear warmup step count\n * @param schedule - The post-warmup schedule (`'cosine'` or `'constant'`)\n * @returns The step's non-negative learning rate\n *\n * @example\n * ```ts\n * computeFinetunerRate(1, 10, 0.001, 2, 'cosine') // 0.0005\n * ```\n */\nexport function computeFinetunerRate(\n\tstep: number,\n\ttotal: number,\n\trate: number,\n\twarmup: number,\n\tschedule: FinetunerSchedule,\n): number {\n\tif (!matchesCount(step, 1) || !matchesCount(total, 1)) {\n\t\tthrow new InferError(\n\t\t\t`The step (${step}) and total (${total}) must be positive safe integers.`,\n\t\t\t{ code: 'ARGUMENT', context: { step, total } },\n\t\t)\n\t}\n\tif (!isFiniteNumber(rate) || rate < 0) {\n\t\tthrow new InferError(`The learning rate ${rate} must be a non-negative finite number.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { rate },\n\t\t})\n\t}\n\tif (!isSafeInteger(warmup) || warmup < 0) {\n\t\tthrow new InferError(`The warmup step count ${warmup} must be a non-negative integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { warmup },\n\t\t})\n\t}\n\tif (!isFinetunerSchedule(schedule)) {\n\t\tthrow new InferError(\n\t\t\t`The learning rate schedule ${quoteFaultText(String(schedule))} must be \"cosine\" or \"constant\".`,\n\t\t\t{ code: 'ARGUMENT', context: { schedule } },\n\t\t)\n\t}\n\tif (warmup > 0 && step <= warmup) {\n\t\treturn rate * (step / warmup)\n\t}\n\tif (schedule === 'constant' || total <= warmup) {\n\t\treturn rate\n\t}\n\tconst span = Math.max(1, total - warmup)\n\tconst progress = Math.min(1, Math.max(0, (step - warmup) / span))\n\treturn rate * 0.5 * (1 + Math.cos(Math.PI * progress))\n}\n\n/**\n * Validates and resolves a `FinetunerOptions` record into checked `FinetunerSettings` with every\n * default applied.\n *\n * @remarks\n * Refuses invalid modes, base digests, optimizer hyperparameters, loop bounds, fold settings,\n * mode/plan mismatches (such as `mode: 'adapter'` carrying `section` settings), or invalid\n * checkpoint intervals and identifiers with the `ARGUMENT` code.\n *\n * @param options - The finetuner configuration to validate\n * @returns The resolved `FinetunerSettings`\n *\n * @example\n * ```ts\n * resolveFinetunerSettings(options).optimizer.rate // 0.0001\n * ```\n */\nexport function resolveFinetunerSettings(options: FinetunerOptions): FinetunerSettings {\n\tif (!isRecord(options)) {\n\t\tthrow new InferError('The finetuner options must be a plain object.', { code: 'ARGUMENT' })\n\t}\n\tconst { mode, architecture, base, optimizer, loop, adapter, section, checkpoint } = options\n\tif (!isCheckpointMode(mode)) {\n\t\tthrow new InferError(\n\t\t\t`The finetuner mode ${quoteFaultText(String(mode))} must be \"adapter\" or \"section\".`,\n\t\t\t{ code: 'ARGUMENT', context: { mode } },\n\t\t)\n\t}\n\tif (!isString(base) || !SHA256_PATTERN.test(base)) {\n\t\tthrow new InferError(\n\t\t\t`The finetuner base digest ${quoteFaultText(String(base))} must be a 64-character lowercase SHA-256 hex digest.`,\n\t\t\t{ code: 'ARGUMENT', context: { base } },\n\t\t)\n\t}\n\tconst rate = optimizer?.rate ?? FINETUNER_RATE\n\tconst decay = optimizer?.decay ?? FINETUNER_DECAY\n\tconst first = optimizer?.first ?? FINETUNER_FIRST\n\tconst second = optimizer?.second ?? FINETUNER_SECOND\n\tconst epsilon = optimizer?.epsilon ?? FINETUNER_EPSILON\n\tconst clip = optimizer?.clip ?? FINETUNER_CLIP\n\tconst warmup = optimizer?.warmup ?? FINETUNER_WARMUP\n\tconst schedule = optimizer?.schedule ?? 'cosine'\n\tif (!isFiniteNumber(rate) || rate < 0) {\n\t\tthrow new InferError(`The optimizer rate ${rate} must be a non-negative finite number.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { rate },\n\t\t})\n\t}\n\tif (!isFiniteNumber(decay) || decay < 0) {\n\t\tthrow new InferError(`The optimizer decay ${decay} must be a non-negative finite number.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { decay },\n\t\t})\n\t}\n\tif (!isFiniteNumber(first) || first < 0 || first >= 1) {\n\t\tthrow new InferError(`The optimizer first moment ${first} must lie in [0, 1).`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { first },\n\t\t})\n\t}\n\tif (!isFiniteNumber(second) || second < 0 || second >= 1) {\n\t\tthrow new InferError(`The optimizer second moment ${second} must lie in [0, 1).`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { second },\n\t\t})\n\t}\n\tif (!isFiniteNumber(epsilon) || epsilon <= 0) {\n\t\tthrow new InferError(`The optimizer epsilon ${epsilon} must be a positive finite number.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { epsilon },\n\t\t})\n\t}\n\tif (!isFiniteNumber(clip) || clip < 0) {\n\t\tthrow new InferError(`The optimizer clip ${clip} must be a non-negative finite number.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { clip },\n\t\t})\n\t}\n\tif (!isSafeInteger(warmup) || warmup < 0) {\n\t\tthrow new InferError(`The optimizer warmup ${warmup} must be a non-negative integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { warmup },\n\t\t})\n\t}\n\tif (!isFinetunerSchedule(schedule)) {\n\t\tthrow new InferError(\n\t\t\t`The optimizer schedule ${quoteFaultText(String(schedule))} must be \"cosine\" or \"constant\".`,\n\t\t\t{ code: 'ARGUMENT', context: { schedule } },\n\t\t)\n\t}\n\tconst epochs = loop?.epochs ?? FINETUNER_EPOCHS\n\tconst batch = loop?.batch ?? FINETUNER_BATCH\n\tconst segment = loop?.segment ?? BACKWARD_SEGMENT\n\tconst limit = loop?.limit ?? FINETUNER_LIMIT\n\tconst steps = loop?.steps\n\tconst seed = loop?.seed ?? FINETUNER_SEED\n\tconst folds = loop?.folds\n\tconst fold = loop?.fold\n\tif (!matchesCount(epochs, 1)) {\n\t\tthrow new InferError(`The loop epochs ${epochs} must be a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { epochs },\n\t\t})\n\t}\n\tif (!matchesCount(batch, 1)) {\n\t\tthrow new InferError(`The loop batch size ${batch} must be a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { batch },\n\t\t})\n\t}\n\tif (!matchesCount(segment, 1)) {\n\t\tthrow new InferError(`The loop segment width ${segment} must be a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { segment },\n\t\t})\n\t}\n\tif (!matchesCount(limit, 2)) {\n\t\tthrow new InferError(`The loop token limit ${limit} must be an integer of at least 2.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { limit },\n\t\t})\n\t}\n\tif (steps !== undefined && !matchesCount(steps, 1)) {\n\t\tthrow new InferError(`The loop steps cap ${steps} must be a positive integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { steps },\n\t\t})\n\t}\n\tif (!isSafeInteger(seed) || seed < 0 || seed > 0xffff_ffff) {\n\t\tthrow new InferError(`The loop seed ${seed} must be an unsigned 32-bit integer.`, {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { seed },\n\t\t})\n\t}\n\tif (folds !== undefined) {\n\t\tif (!matchesCount(folds, 2)) {\n\t\t\tthrow new InferError(`The loop folds count ${folds} must be an integer of at least 2.`, {\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\tcontext: { folds },\n\t\t\t})\n\t\t}\n\t\tconst resolvedFold = fold ?? 0\n\t\tif (!isSafeInteger(resolvedFold) || resolvedFold < 0 || resolvedFold >= folds) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The loop fold ${resolvedFold} must be an integer from 0 to ${folds - 1}.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { fold: resolvedFold, folds } },\n\t\t\t)\n\t\t}\n\t} else if (fold !== undefined) {\n\t\tthrow new InferError('The loop fold option requires loop.folds to be set.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t\tcontext: { fold },\n\t\t})\n\t}\n\tconst plan: TrainPlan = {\n\t\tmode,\n\t\tsegment,\n\t\t...(adapter === undefined ? {} : { adapter: { ...adapter, seed } }),\n\t\t...(section === undefined ? {} : { section }),\n\t}\n\tcheckTrainPlan(plan, architecture)\n\tif (checkpoint !== undefined) {\n\t\tif (!isRecord(checkpoint) || !isObject(checkpoint.store)) {\n\t\t\tthrow new InferError('The checkpoint configuration requires a CheckpointStoreInterface.', {\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t})\n\t\t}\n\t\tcheckCheckpointId(checkpoint.id)\n\t\tif (!matchesCount(checkpoint.every, 1)) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The checkpoint interval ${checkpoint.every} must be a positive integer.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { every: checkpoint.every } },\n\t\t\t)\n\t\t}\n\t\tif (checkpoint.resume !== undefined && !isBoolean(checkpoint.resume)) {\n\t\t\tthrow new InferError('The checkpoint resume flag must be a boolean.', { code: 'ARGUMENT' })\n\t\t}\n\t}\n\treturn {\n\t\tmode,\n\t\tbase,\n\t\toptimizer: { rate, decay, first, second, epsilon, clip, warmup, schedule },\n\t\tloop: {\n\t\t\tepochs,\n\t\t\tbatch,\n\t\t\tsegment,\n\t\t\tlimit,\n\t\t\t...(steps === undefined ? {} : { steps }),\n\t\t\tseed,\n\t\t\t...(folds === undefined ? {} : { folds, fold: fold ?? 0 }),\n\t\t},\n\t\t...(adapter === undefined ? {} : { adapter }),\n\t\t...(section === undefined ? {} : { section }),\n\t\t...(checkpoint === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\tcheckpoint: {\n\t\t\t\t\t\tstore: checkpoint.store,\n\t\t\t\t\t\tid: checkpoint.id,\n\t\t\t\t\t\tevery: checkpoint.every,\n\t\t\t\t\t\tresume: checkpoint.resume ?? false,\n\t\t\t\t\t},\n\t\t\t\t}),\n\t}\n}\n\n/**\n * Validates every `FinetuneRow` (including `checkRowProvenance`), renders any `messages` row\n * through `ChatTemplate` or `@orkestrel/template`, and tokenizes `(prompt, completion)` pairs into\n * prompt-masked `TokenSpan` records before step 1.\n *\n * @remarks\n * Refuses empty row lists, malformed rows, hosted-model provenance markers, missing templates when\n * `messages` is used, empty prompt or completion encodings, and spans exceeding `limit` tokens\n * with the `ARGUMENT` code.\n *\n * @param rows - The fine-tuning rows to validate and tokenize\n * @param tokenizer - The tokenizer encoding prompts and completions\n * @param limit - The maximum admitted token length per example\n * @param template - Optional `ChatTemplateInterface`, compiled `TemplateTreeInterface`, or Jinja source\n * @returns Prompt-masked `TokenSpan` records in row order\n *\n * @example\n * ```ts\n * const spans = admitFinetuneRows(rows, backbone.tokenizer, 512)\n * spans[0]?.prompt // number of masked prompt tokens\n * ```\n */\nexport function admitFinetuneRows(\n\trows: readonly FinetuneRow[],\n\ttokenizer: TokenizerInterface,\n\tlimit: number,\n\ttemplate?: ChatTemplateInterface | TemplateTreeInterface | TemplateDocument | string,\n): readonly TokenSpan[] {\n\tif (!isArray(rows) || rows.length === 0) {\n\t\tthrow new InferError('The finetuner received no rows; pass at least one supervised row.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tconst templateDoc: TemplateDocument | undefined =\n\t\ttemplate === undefined\n\t\t\t? undefined\n\t\t\t: isString(template)\n\t\t\t\t? compileTemplate(template)\n\t\t\t\t: isTemplateDocument(template)\n\t\t\t\t\t? template\n\t\t\t\t\t: 'document' in template && isTemplateDocument(template.document)\n\t\t\t\t\t\t? template.document\n\t\t\t\t\t\t: undefined\n\tconst chatTemplate: ChatTemplateInterface | undefined =\n\t\ttemplate !== undefined &&\n\t\t!isString(template) &&\n\t\t'render' in template &&\n\t\t'source' in template &&\n\t\tisFunction(template.render)\n\t\t\t? template\n\t\t\t: undefined\n\treturn rows.map((row, index) => {\n\t\tif (!isFinetuneRow(row)) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The finetune row at index ${index} is malformed: pass either \"prompt\" or \"messages\", a string \"completion\", optional non-empty \"group\"/\"label\", and a local \"provenance\".`,\n\t\t\t\t{ code: 'ARGUMENT', context: { row: index } },\n\t\t\t)\n\t\t}\n\t\tcheckRowProvenance(row.provenance)\n\t\tconst promptText =\n\t\t\trow.prompt !== undefined\n\t\t\t\t? row.prompt\n\t\t\t\t: renderFinetunePrompt(row.messages ?? [], index, chatTemplate, templateDoc)\n\t\tif (\n\t\t\t!matchesTokenBound(tokenizer, promptText, limit) ||\n\t\t\t!matchesTokenBound(tokenizer, row.completion, limit)\n\t\t) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The finetune row at index ${index} exceeds the ${limit}-token UTF-8 bound.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { row: index, limit } },\n\t\t\t)\n\t\t}\n\t\tconst promptTokens = tokenizer.encode(promptText)\n\t\tconst completionTokens = tokenizer.encode(row.completion)\n\t\tif (promptTokens.length === 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The finetune row at index ${index} encoded an empty prompt; prompt masking requires at least 1 prompt token.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { row: index } },\n\t\t\t)\n\t\t}\n\t\tif (completionTokens.length === 0) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The finetune row at index ${index} encoded an empty completion; loss requires at least 1 completion token.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { row: index } },\n\t\t\t)\n\t\t}\n\t\tconst total = promptTokens.length + completionTokens.length\n\t\tif (total > limit) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The finetune row at index ${index} encodes to ${total} tokens, past the limit of ${limit}.`,\n\t\t\t\t{ code: 'ARGUMENT', context: { row: index, tokens: total, limit } },\n\t\t\t)\n\t\t}\n\t\tconst tokens = new Uint32Array(total)\n\t\ttokens.set(promptTokens, 0)\n\t\ttokens.set(completionTokens, promptTokens.length)\n\t\treturn { tokens, prompt: promptTokens.length }\n\t})\n}\n\n/**\n * Renders one chat-message fine-tuning row into prompt text through either a `ChatTemplateInterface`\n * or a compiled `@orkestrel/template` tree.\n *\n * @param messages - The conversation messages to render\n * @param rowIndex - Zero-based row index reported in error context\n * @param chatTemplate - Optional `ChatTemplateInterface`\n * @param compiledTemplate - Optional compiled `@orkestrel/template` tree\n * @returns The rendered prompt text\n *\n * @example\n * ```ts\n * renderFinetunePrompt([{ id: '1', role: 'user', content: 'hi' }], 0, undefined, tree)\n * ```\n */\nexport function renderFinetunePrompt(\n\tmessages: readonly Message[],\n\trowIndex: number,\n\tchatTemplate: ChatTemplateInterface | undefined,\n\tcompiledTemplate: TemplateDocument | undefined,\n): string {\n\tif (chatTemplate !== undefined) {\n\t\treturn chatTemplate.render(messages, { addGenerationPrompt: true })\n\t}\n\tif (compiledTemplate !== undefined) {\n\t\tconst evaluated = attempt(() =>\n\t\t\tevaluateTemplate(compiledTemplate, {\n\t\t\t\tmessages: buildChatMessages(messages),\n\t\t\t\tadd_generation_prompt: true,\n\t\t\t}),\n\t\t)\n\t\tif (!evaluated.success) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The finetune row at index ${rowIndex} failed template rendering: ${isTemplateError(evaluated.error) ? evaluated.error.message : String(evaluated.error)}`,\n\t\t\t\t{ code: 'ARGUMENT', context: { row: rowIndex }, cause: evaluated.error },\n\t\t\t)\n\t\t}\n\t\treturn evaluated.value\n\t}\n\tthrow new InferError(\n\t\t`The finetune row at index ${rowIndex} carries messages, which require options.template.`,\n\t\t{ code: 'ARGUMENT', context: { row: rowIndex } },\n\t)\n}\n\n/**\n * Computes the deterministic SHA-256 dataset digest binding a sequence of `FinetuneRow` records to\n * a resumable training checkpoint.\n *\n * @param rows - The admitted fine-tuning rows in order\n * @returns The 64-character lowercase hexadecimal SHA-256 digest\n *\n * @example\n * ```ts\n * (await computeFinetuneDatasetDigest(rows)).length // 64\n * ```\n */\nexport async function computeFinetuneDatasetDigest(rows: readonly FinetuneRow[]): Promise<Digest> {\n\tconst canonical = canonicalStringify(\n\t\trows.map((row) => ({\n\t\t\t...(row.prompt === undefined ? {} : { prompt: row.prompt }),\n\t\t\t...(row.messages === undefined ? {} : { messages: row.messages }),\n\t\t\tcompletion: row.completion,\n\t\t\t...(row.group === undefined ? {} : { group: row.group }),\n\t\t\t...(row.label === undefined ? {} : { label: row.label }),\n\t\t\tprovenance: row.provenance,\n\t\t})),\n\t)\n\treturn digestBytes(UTF8_ENCODER.encode(canonical ?? '[]'))\n}\n\n/**\n * Attributes per-block and per-target gradient-norm sensitivity over frozen base weights through a\n * `BackwardInterface` and development `TokenSpan` rows, ranking highest-sensitivity decoder blocks\n * and targets to guide static surgical `mode: 'section'` selection.\n *\n * @remarks\n * Configures the backward engine in static `mode: 'section'`, accumulates exact gradients across\n * every development `TokenSpan`, captures the unclipped mean gradient per target through a\n * zero-rate (`rate: 0, decay: 0, first: 0, second: 0, clip: 0`) step so parameters remain\n * unchanged, snapshots the captured gradients, and ranks both individual targets and per-block\n * aggregates by descending L2 norm. Refuses empty `examples` with `ARGUMENT` and respects `signal`\n * with `ABORT`.\n *\n * @param options - The backward engine, architecture, development `TokenSpan` rows, optional layer/target filters, and signal\n * @returns Ranked per-block and per-target gradient-norm attributions and mean cross-entropy loss\n *\n * @example\n * ```ts\n * const trace = await traceSections({ backward, architecture, examples })\n * const topLayers = trace.blocks.slice(0, 2).map((block) => block.layer)\n * ```\n */\nexport async function traceSections(options: SectionTraceOptions): Promise<SectionTraceResult> {\n\tconst { backward, architecture, examples, layers, targets, norms, segment, signal } = options\n\tcheckSignal(signal, 'The section trace')\n\tif (!isArray(examples) || examples.length === 0) {\n\t\tthrow new InferError('Section tracing requires at least one development TokenSpan example.', {\n\t\t\tcode: 'ARGUMENT',\n\t\t})\n\t}\n\tconst plan: TrainPlan = {\n\t\tmode: 'section',\n\t\t...(segment === undefined ? {} : { segment }),\n\t\tsection: {\n\t\t\t...(layers === undefined ? {} : { layers }),\n\t\t\t...(targets === undefined ? {} : { targets }),\n\t\t\t...(norms === undefined ? {} : { norms }),\n\t\t},\n\t}\n\tcheckTrainPlan(plan, architecture)\n\tawait backward.configure(plan)\n\tcheckSignal(signal, 'The section trace')\n\tawait backward.zero()\n\tlet lossWeighted = 0\n\tlet tokens = 0\n\tfor (let index = 0; index < examples.length; index += 1) {\n\t\tcheckSignal(signal, 'The section trace')\n\t\tconst example = examples[index]\n\t\tif (example === undefined) continue\n\t\tconst reading = await backward.accumulate(example, signal)\n\t\tlossWeighted += reading.loss * reading.count\n\t\ttokens += reading.count\n\t}\n\tcheckSignal(signal, 'The section trace')\n\t// Captures exact unclipped mean gradients in Adam's first moment while keeping parameters unchanged.\n\tawait backward.step(\n\t\t{\n\t\t\tstep: 1,\n\t\t\trate: 0,\n\t\t\tdecay: 0,\n\t\t\tfirst: 0,\n\t\t\tsecond: 0,\n\t\t\tepsilon: FINETUNER_EPSILON,\n\t\t\tclip: 0,\n\t\t\tscale: 1 / examples.length,\n\t\t},\n\t\tsignal,\n\t)\n\tconst states = await backward.snapshot(signal)\n\tconst suffixToTarget = new Map<string, SectionTarget>(\n\t\tSECTION_TARGETS.map((target) => [SECTION_TARGET_SUFFIXES[target], target]),\n\t)\n\tconst tracedTargets: SectionTraceTarget[] = []\n\tconst blockBuckets = new Map<number, SectionTraceTarget[]>()\n\tlet totalSq = 0\n\tfor (let stateIndex = 0; stateIndex < states.length; stateIndex += 1) {\n\t\tconst state = states[stateIndex]\n\t\tif (state === undefined) continue\n\t\tconst match = SECTION_TENSOR_PATTERN.exec(state.name)\n\t\tconst rawLayer = match?.[1]\n\t\tconst rawSuffix = match?.[2]\n\t\tconst rawTop = match?.[3]\n\t\tconst target =\n\t\t\trawTop !== undefined\n\t\t\t\t? isSectionTarget(rawTop)\n\t\t\t\t\t? rawTop\n\t\t\t\t\t: undefined\n\t\t\t\t: rawSuffix === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: suffixToTarget.get(rawSuffix)\n\t\tif (target === undefined) continue\n\t\tconst layer = rawLayer === undefined ? undefined : Number(rawLayer)\n\t\tconst grad = state.first\n\t\tconst elements = grad.length\n\t\tlet sumSq = 0\n\t\tlet peak = 0\n\t\tfor (let index = 0; index < elements; index += 1) {\n\t\t\tconst value = grad[index] ?? 0\n\t\t\tsumSq += value * value\n\t\t\tconst magnitude = Math.abs(value)\n\t\t\tif (magnitude > peak) peak = magnitude\n\t\t}\n\t\ttotalSq += sumSq\n\t\tconst norm = Math.sqrt(sumSq)\n\t\tconst rms = elements > 0 ? norm / Math.sqrt(elements) : 0\n\t\tconst entry: SectionTraceTarget = {\n\t\t\tname: state.name,\n\t\t\t...(layer === undefined ? {} : { layer }),\n\t\t\ttarget,\n\t\t\telements,\n\t\t\tnorm,\n\t\t\trms,\n\t\t\tmaximum: peak,\n\t\t}\n\t\ttracedTargets.push(entry)\n\t\tif (layer !== undefined) {\n\t\t\tconst bucket = blockBuckets.get(layer) ?? []\n\t\t\tbucket.push(entry)\n\t\t\tblockBuckets.set(layer, bucket)\n\t\t}\n\t}\n\tconst sortedTargets = tracedTargets.toSorted(\n\t\t(left, right) =>\n\t\t\tright.norm - left.norm ||\n\t\t\t(left.layer ?? Number.POSITIVE_INFINITY) - (right.layer ?? Number.POSITIVE_INFINITY) ||\n\t\t\tSECTION_TARGETS.indexOf(left.target) - SECTION_TARGETS.indexOf(right.target),\n\t)\n\tconst blocks: readonly SectionTraceBlock[] = [...blockBuckets.entries()]\n\t\t.map(([layer, entries]) => {\n\t\t\tconst ordered = entries.toSorted(\n\t\t\t\t(left, right) =>\n\t\t\t\t\tright.norm - left.norm ||\n\t\t\t\t\tSECTION_TARGETS.indexOf(left.target) - SECTION_TARGETS.indexOf(right.target),\n\t\t\t)\n\t\t\tconst blockSq = ordered.reduce((sum, item) => sum + item.norm * item.norm, 0)\n\t\t\tconst elements = ordered.reduce((sum, item) => sum + item.elements, 0)\n\t\t\tconst norm = Math.sqrt(blockSq)\n\t\t\treturn {\n\t\t\t\tlayer,\n\t\t\t\tnorm,\n\t\t\t\trms: elements > 0 ? norm / Math.sqrt(elements) : 0,\n\t\t\t\telements,\n\t\t\t\ttargets: ordered,\n\t\t\t}\n\t\t})\n\t\t.toSorted((left, right) => right.norm - left.norm || left.layer - right.layer)\n\treturn {\n\t\tloss: tokens > 0 ? lossWeighted / tokens : 0,\n\t\ttokens,\n\t\ttotal: Math.sqrt(totalSq),\n\t\tblocks,\n\t\ttargets: sortedTargets,\n\t}\n}\n","import type { JSONRecord } from '@orkestrel/contract'\nimport type { EmitterInterface } from '@orkestrel/emitter'\nimport type {\n\tArchitecture,\n\tBackwardInterface,\n\tChatTemplateInterface,\n\tDigest,\n\tParameterState,\n\tTokenizerInterface,\n\tTrainPlan,\n} from '@orkestrel/infer'\nimport type { TemplateDocument, TemplateTreeInterface } from '@orkestrel/template'\nimport type {\n\tCheckpoint,\n\tCheckpointTarget,\n\tFinetuneRow,\n\tFinetunerEventMap,\n\tFinetunerInterface,\n\tFinetunerOptions,\n\tFinetunerResult,\n\tFinetunerSettings,\n\tFinetunerStepEvent,\n\tTrainerSettings,\n} from '../types.js'\nimport { isArray, isSafeInteger, isString } from '@orkestrel/contract'\nimport { Emitter } from '@orkestrel/emitter'\nimport {\n\tAdapter,\n\tcheckSignal,\n\tdigestBytes,\n\tInferError,\n\tMemorySource,\n\treadSection,\n\tSection,\n} from '@orkestrel/infer'\nimport {\n\tadmitFinetuneRows,\n\tassignFolds,\n\tbuildAdapterGGUF,\n\tbuildCheckpointGGUF,\n\tbuildSectionGGUF,\n\tcheckFolds,\n\tcomputeFinetuneDatasetDigest,\n\tcomputeFinetunerRate,\n\treadCheckpointGGUF,\n\tresolveFinetunerSettings,\n\tstepRandom,\n} from '../helpers.js'\n\n/**\n * Drives cross-host LoRA adapter fine-tuning and static surgical or LISA rotating full-rank\n * section retraining over an `@orkestrel/infer` `BackwardInterface`.\n *\n * @remarks\n * Validates options at construction through `resolveFinetunerSettings`, enforces local row\n * provenance through `checkRowProvenance` and prompt-masked tokenization through\n * `admitFinetuneRows` before step 1, partitions group-preserving folds through `assignFolds` and\n * `checkFolds`, advances example ordering deterministically through `stepRandom(rng)`, applies\n * linear warmup with cosine or constant schedules, persists GGUF v3 checkpoints every\n * `checkpoint.every` steps, resumes bit-for-bit on matching `base` and `dataset` bindings\n * (`BINDING` on mismatch), emits typed lifecycle events on `emitter`, and honors `AbortSignal`\n * cooperatively with the `ABORT` code.\n *\n * @example\n * ```ts\n * const finetuner = new Finetuner({\n * \tmode: 'adapter',\n * \tbackward,\n * \ttokenizer: backbone.tokenizer,\n * \tarchitecture: backbone.architecture,\n * \tbase: backbone.digest,\n * \trows,\n * \tadapter: { rank: 4, alpha: 8 },\n * })\n * const result = await finetuner.execute()\n * ```\n */\nexport class Finetuner implements FinetunerInterface {\n\treadonly #settings: FinetunerSettings\n\treadonly #backward: BackwardInterface\n\treadonly #tokenizer: TokenizerInterface\n\treadonly #architecture: Architecture\n\treadonly #rows: readonly FinetuneRow[]\n\treadonly #template:\n\t\t| ChatTemplateInterface\n\t\t| TemplateTreeInterface\n\t\t| TemplateDocument\n\t\t| string\n\t\t| undefined\n\treadonly #emitter: Emitter<FinetunerEventMap>\n\t#step = 0\n\t#epoch = 0\n\t#cursor = 0\n\t#rng = 0\n\t#epochRng = 0\n\t#order: number[] = []\n\n\t/**\n\t * Creates a cross-host finetuner over a backward engine, tokenizer, architecture, and rows.\n\t *\n\t * @param options - The training mode, backward engine, tokenizer, architecture, base digest,\n\t * rows, optional template, optimizer/loop/mode/checkpoint settings, and emitter hooks\n\t */\n\tconstructor(options: FinetunerOptions) {\n\t\tthis.#settings = resolveFinetunerSettings(options)\n\t\tthis.#backward = options.backward\n\t\tthis.#tokenizer = options.tokenizer\n\t\tthis.#architecture = options.architecture\n\t\tthis.#rows = [...options.rows]\n\t\tthis.#template = options.template\n\t\tthis.#emitter = new Emitter<FinetunerEventMap>({\n\t\t\t...(options.on === undefined ? {} : { on: options.on }),\n\t\t\t...(options.error === undefined ? {} : { error: options.error }),\n\t\t})\n\t}\n\n\t/** Exposes the typed synchronous lifecycle event emitter. */\n\tget emitter(): EmitterInterface<FinetunerEventMap> {\n\t\treturn this.#emitter\n\t}\n\n\t/**\n\t * Executes the configured fine-tuning run, resuming from a checkpoint when configured, and\n\t * returns the exported immutable weights, GGUF v3 bytes, counters, and step history.\n\t *\n\t * @param signal - Cancels the run cooperatively; rejects with the `ABORT` code\n\t * @returns The completed fine-tuning result\n\t */\n\tasync execute(signal?: AbortSignal): Promise<FinetunerResult> {\n\t\tcheckSignal(signal, 'The fine-tuning')\n\t\tconst settings = this.#settings\n\t\tconst spans = admitFinetuneRows(\n\t\t\tthis.#rows,\n\t\t\tthis.#tokenizer,\n\t\t\tsettings.loop.limit,\n\t\t\tthis.#template,\n\t\t)\n\t\tconst [trainIndices, held] = this.#partitionRows()\n\t\tconst dataset = await computeFinetuneDatasetDigest(this.#rows)\n\t\tcheckSignal(signal, 'The fine-tuning')\n\t\tconst pendingResume = await this.#loadResumeCheckpoint(dataset, signal)\n\t\tconst plan: TrainPlan = {\n\t\t\tmode: settings.mode,\n\t\t\tsegment: settings.loop.segment,\n\t\t\t...(settings.adapter === undefined\n\t\t\t\t? {}\n\t\t\t\t: { adapter: { ...settings.adapter, seed: settings.loop.seed } }),\n\t\t\t...(settings.section === undefined ? {} : { section: settings.section }),\n\t\t}\n\t\tawait this.#backward.configure(plan)\n\t\tcheckSignal(signal, 'The fine-tuning')\n\n\t\tthis.#step = 0\n\t\tthis.#epoch = 0\n\t\tthis.#cursor = 0\n\t\tthis.#rng = settings.loop.seed >>> 0\n\t\tthis.#epochRng = this.#rng\n\t\tthis.#order = [...trainIndices]\n\n\t\tconst resumed =\n\t\t\tpendingResume === undefined\n\t\t\t\t? false\n\t\t\t\t: await this.#applyResumeCheckpoint(pendingResume, trainIndices, signal)\n\t\tconst stepsPerEpoch = Math.max(1, Math.ceil(trainIndices.length / settings.loop.batch))\n\t\tconst totalSteps = settings.loop.steps ?? settings.loop.epochs * stepsPerEpoch\n\t\tthis.#emitter.emit('start', {\n\t\t\tmode: settings.mode,\n\t\t\tstep: this.#step,\n\t\t\tepoch: this.#epoch,\n\t\t\tresumed,\n\t\t\ttotal: totalSteps,\n\t\t})\n\n\t\tconst history: FinetunerStepEvent[] = []\n\t\tconst remainingSteps = Math.max(0, totalSteps - this.#step)\n\t\tlet totalLossWeighted = 0\n\t\tlet totalTokens = 0\n\t\tlet epochLossWeighted = 0\n\t\tlet epochTokens = 0\n\t\tfor (let stepOffset = 0; stepOffset < remainingSteps; stepOffset += 1) {\n\t\t\tcheckSignal(signal, 'The fine-tuning')\n\t\t\tconst metered = this.#emitter.count('metric') > 0\n\t\t\tconst begun = metered ? performance.now() : 0\n\t\t\tconst [batch, epochFinished] = this.#drawBatch(trainIndices, settings.loop.batch)\n\t\t\tawait this.#backward.zero()\n\t\t\tlet batchLossWeighted = 0\n\t\t\tlet batchTokens = 0\n\t\t\tfor (let slot = 0; slot < batch.length; slot += 1) {\n\t\t\t\tcheckSignal(signal, 'The fine-tuning')\n\t\t\t\tconst rowIndex = batch[slot]\n\t\t\t\tconst span = rowIndex === undefined ? undefined : spans[rowIndex]\n\t\t\t\tif (span === undefined) continue\n\t\t\t\tconst accumulating = metered ? performance.now() : 0\n\t\t\t\tconst reading = await this.#backward.accumulate(span, signal)\n\t\t\t\tif (metered) {\n\t\t\t\t\tthis.#emitter.emit('metric', 'accumulate', performance.now() - accumulating)\n\t\t\t\t}\n\t\t\t\tbatchLossWeighted += reading.loss * reading.count\n\t\t\t\tbatchTokens += reading.count\n\t\t\t}\n\t\t\tcheckSignal(signal, 'The fine-tuning')\n\t\t\tconst nextStep = this.#step + 1\n\t\t\tconst rate = computeFinetunerRate(\n\t\t\t\tnextStep,\n\t\t\t\ttotalSteps,\n\t\t\t\tsettings.optimizer.rate,\n\t\t\t\tsettings.optimizer.warmup,\n\t\t\t\tsettings.optimizer.schedule,\n\t\t\t)\n\t\t\tconst updating = metered ? performance.now() : 0\n\t\t\tconst norm = await this.#backward.step(\n\t\t\t\t{\n\t\t\t\t\tstep: nextStep,\n\t\t\t\t\trate,\n\t\t\t\t\tdecay: settings.optimizer.decay,\n\t\t\t\t\tfirst: settings.optimizer.first,\n\t\t\t\t\tsecond: settings.optimizer.second,\n\t\t\t\t\tepsilon: settings.optimizer.epsilon,\n\t\t\t\t\tclip: settings.optimizer.clip,\n\t\t\t\t\tscale: 1 / batch.length,\n\t\t\t\t},\n\t\t\t\tsignal,\n\t\t\t)\n\t\t\tif (metered) {\n\t\t\t\tconst interval = settings.section?.interval\n\t\t\t\tconst rotates =\n\t\t\t\t\tsettings.mode === 'section' && interval !== undefined && nextStep % interval === 0\n\t\t\t\tconst finished = performance.now()\n\t\t\t\tthis.#emitter.emit('metric', rotates ? 'rotation' : 'update', finished - updating)\n\t\t\t\tthis.#emitter.emit('metric', 'step', finished - begun)\n\t\t\t}\n\t\t\tthis.#step = nextStep\n\t\t\tconst stepLoss = batchTokens > 0 ? batchLossWeighted / batchTokens : 0\n\t\t\ttotalLossWeighted += batchLossWeighted\n\t\t\ttotalTokens += batchTokens\n\t\t\tepochLossWeighted += batchLossWeighted\n\t\t\tepochTokens += batchTokens\n\t\t\tconst event: FinetunerStepEvent = {\n\t\t\t\tstep: this.#step,\n\t\t\t\tepoch: this.#epoch,\n\t\t\t\tcursor: this.#cursor,\n\t\t\t\tloss: stepLoss,\n\t\t\t\ttokens: batchTokens,\n\t\t\t\trate,\n\t\t\t\tnorm,\n\t\t\t}\n\t\t\thistory.push(event)\n\t\t\tthis.#emitter.emit('step', event)\n\t\t\tif (epochFinished) {\n\t\t\t\tthis.#emitter.emit('epoch', {\n\t\t\t\t\tepoch: this.#epoch,\n\t\t\t\t\tstep: this.#step,\n\t\t\t\t\tloss: epochTokens > 0 ? epochLossWeighted / epochTokens : 0,\n\t\t\t\t})\n\t\t\t\tepochLossWeighted = 0\n\t\t\t\tepochTokens = 0\n\t\t\t}\n\t\t\tif (settings.checkpoint !== undefined && this.#step % settings.checkpoint.every === 0) {\n\t\t\t\tawait this.#saveCheckpoint(dataset, signal)\n\t\t\t}\n\t\t}\n\n\t\tcheckSignal(signal, 'The fine-tuning')\n\t\tconst exported = await this.#backward.export(signal)\n\t\tconst loss = totalTokens > 0 ? totalLossWeighted / totalTokens : 0\n\t\tif (settings.mode === 'adapter' && 'pairs' in exported) {\n\t\t\tconst bytes = buildAdapterGGUF(exported)\n\t\t\tconst adapter = new Adapter({ ...exported, digest: await digestBytes(bytes) })\n\t\t\tconst result: FinetunerResult = {\n\t\t\t\tmode: 'adapter',\n\t\t\t\tstep: this.#step,\n\t\t\t\tepoch: this.#epoch,\n\t\t\t\tcursor: this.#cursor,\n\t\t\t\trng: this.#rng,\n\t\t\t\tdataset,\n\t\t\t\tloss,\n\t\t\t\thistory,\n\t\t\t\theld,\n\t\t\t\tadapter,\n\t\t\t\tbytes,\n\t\t\t}\n\t\t\tthis.#emitter.emit('done', result)\n\t\t\treturn result\n\t\t}\n\t\tif (settings.mode === 'section' && 'entries' in exported) {\n\t\t\tconst format = settings.section?.format ?? 'F32'\n\t\t\tconst bytes = buildSectionGGUF(exported, format)\n\t\t\tconst section =\n\t\t\t\tformat === 'F32'\n\t\t\t\t\t? new Section({ ...exported, digest: await digestBytes(bytes) })\n\t\t\t\t\t: new Section(await readSection(new MemorySource(bytes), signal))\n\t\t\tconst result: FinetunerResult = {\n\t\t\t\tmode: 'section',\n\t\t\t\tstep: this.#step,\n\t\t\t\tepoch: this.#epoch,\n\t\t\t\tcursor: this.#cursor,\n\t\t\t\trng: this.#rng,\n\t\t\t\tdataset,\n\t\t\t\tloss,\n\t\t\t\thistory,\n\t\t\t\theld,\n\t\t\t\tsection,\n\t\t\t\tbytes,\n\t\t\t}\n\t\t\tthis.#emitter.emit('done', result)\n\t\t\treturn result\n\t\t}\n\t\tthrow new InferError(\n\t\t\t`The backward engine exported a payload incompatible with mode \"${settings.mode}\".`,\n\t\t\t{ code: 'FORMAT', context: { mode: settings.mode } },\n\t\t)\n\t}\n\n\t// Partitions admitted rows into training and optional held validation indexes preserving groups.\n\t#partitionRows(): readonly [train: readonly number[], held: readonly number[]] {\n\t\tconst { folds, fold, seed } = this.#settings.loop\n\t\tif (folds === undefined) {\n\t\t\treturn [this.#rows.map((_, index) => index), []]\n\t\t}\n\t\tconst uniqueLabels = [...new Set(this.#rows.map((row) => row.label ?? 'default'))]\n\t\tconst labelOrder = new Map(uniqueLabels.map((label, place) => [label, place]))\n\t\tconst strata = this.#rows.map((row) => labelOrder.get(row.label ?? 'default') ?? 0)\n\t\tconst groups = this.#rows.some((row) => row.group !== undefined)\n\t\t\t? this.#rows.map((row) => row.group)\n\t\t\t: undefined\n\t\tconst assignment = assignFolds(strata, folds, seed, groups)\n\t\tconst foldSettings: TrainerSettings = {\n\t\t\tdepth: this.#architecture.layers,\n\t\t\tlabels: uniqueLabels,\n\t\t\ttarget: undefined,\n\t\t\tfolds,\n\t\t\trepeats: 1,\n\t\t\tseed,\n\t\t\tpenalties: [0],\n\t\t}\n\t\tcheckFolds(assignment, strata, foldSettings, groups)\n\t\tconst heldFold = fold ?? 0\n\t\tconst held = assignment.flatMap((assigned, index) => (assigned === heldFold ? [index] : []))\n\t\tconst train = assignment.flatMap((assigned, index) => (assigned === heldFold ? [] : [index]))\n\t\tif (train.length === 0) {\n\t\t\tthrow new InferError(`Holding fold ${heldFold} out of ${folds} leaves no training rows.`, {\n\t\t\t\tcode: 'ARGUMENT',\n\t\t\t\tcontext: { fold: heldFold, folds },\n\t\t\t})\n\t\t}\n\t\treturn [train, held]\n\t}\n\n\t// Draws the next batch of training row indexes through incremental Fisher-Yates using stepRandom.\n\t#drawBatch(\n\t\ttrainIndices: readonly number[],\n\t\tbatchSize: number,\n\t): readonly [batch: readonly number[], epochFinished: boolean] {\n\t\tconst batch: number[] = []\n\t\tlet completed = 0\n\t\tfor (let slot = 0; slot < batchSize; slot += 1) {\n\t\t\tif (this.#cursor === 0) {\n\t\t\t\tthis.#order = [...trainIndices]\n\t\t\t\tthis.#epochRng = this.#rng\n\t\t\t}\n\t\t\tconst remaining = this.#order.length - this.#cursor\n\t\t\tconst [draw, nextRng] = stepRandom(this.#rng)\n\t\t\tthis.#rng = nextRng\n\t\t\tconst pick = this.#cursor + Math.floor(draw * remaining)\n\t\t\tconst chosen = this.#order[pick] ?? trainIndices[0] ?? 0\n\t\t\tthis.#order[pick] = this.#order[this.#cursor] ?? chosen\n\t\t\tthis.#order[this.#cursor] = chosen\n\t\t\tbatch.push(chosen)\n\t\t\tthis.#cursor += 1\n\t\t\tif (this.#cursor >= this.#order.length) {\n\t\t\t\tthis.#cursor = 0\n\t\t\t\tthis.#epoch += 1\n\t\t\t\tcompleted += 1\n\t\t\t}\n\t\t}\n\t\treturn [batch, completed > 0]\n\t}\n\n\t// Loads and validates any stored resume checkpoint before touching the backward engine.\n\tasync #loadResumeCheckpoint(\n\t\tdataset: Digest,\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<Checkpoint | undefined> {\n\t\tconst checkpoint = this.#settings.checkpoint\n\t\tif (checkpoint === undefined || !checkpoint.resume) return undefined\n\t\tconst entry = await checkpoint.store.load(checkpoint.id, signal)\n\t\tif (entry === undefined) return undefined\n\t\tconst loaded = await readCheckpointGGUF(new MemorySource(entry.bytes), {\n\t\t\tbase: this.#settings.base,\n\t\t\tdataset,\n\t\t\t...(signal === undefined ? {} : { signal }),\n\t\t})\n\t\tif (loaded.mode !== this.#settings.mode) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The checkpoint mode is \"${loaded.mode}\", not expected \"${this.#settings.mode}\".`,\n\t\t\t\t{ code: 'BINDING', context: { expected: this.#settings.mode, actual: loaded.mode } },\n\t\t\t)\n\t\t}\n\t\tif (loaded.fold !== this.#settings.loop.fold) {\n\t\t\tthrow new InferError(\n\t\t\t\t`The checkpoint fold is ${String(loaded.fold)}, not expected ${String(this.#settings.loop.fold)}.`,\n\t\t\t\t{ code: 'BINDING', context: { expected: this.#settings.loop.fold, actual: loaded.fold } },\n\t\t\t)\n\t\t}\n\t\treturn loaded\n\t}\n\n\t// Restores validated checkpoint weights, AdamW moments, counters, and permutation state.\n\tasync #applyResumeCheckpoint(\n\t\tloaded: Checkpoint,\n\t\ttrainIndices: readonly number[],\n\t\tsignal: AbortSignal | undefined,\n\t): Promise<boolean> {\n\t\tconst rawInactive = loaded.config['inactive']\n\t\tconst inactive = new Set<string>(isArray(rawInactive) ? rawInactive.filter(isString) : [])\n\t\tconst states: readonly ParameterState[] = loaded.targets.map((target) => {\n\t\t\tconst shape =\n\t\t\t\tthis.#settings.mode === 'section' && target.rows === 1\n\t\t\t\t\t? [target.columns]\n\t\t\t\t\t: [target.rows, target.columns]\n\t\t\tif (inactive.has(target.name)) {\n\t\t\t\treturn {\n\t\t\t\t\tname: target.name,\n\t\t\t\t\tshape,\n\t\t\t\t\tvalues: target.parameters,\n\t\t\t\t\tfirst: new Float32Array(0),\n\t\t\t\t\tsecond: new Float32Array(0),\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tname: target.name,\n\t\t\t\tshape,\n\t\t\t\tvalues: target.parameters,\n\t\t\t\tfirst: target.first,\n\t\t\t\tsecond: target.second,\n\t\t\t}\n\t\t})\n\t\tawait this.#backward.restore(states, signal)\n\t\tthis.#step = loaded.step\n\t\tthis.#epoch = loaded.epoch\n\t\tthis.#cursor = loaded.cursor\n\t\tthis.#rng = loaded.rng\n\t\tconst rawEpochRng = loaded.config['epochRng']\n\t\tthis.#epochRng =\n\t\t\tisSafeInteger(rawEpochRng) && rawEpochRng >= 0 && rawEpochRng <= 0xffff_ffff\n\t\t\t\t? rawEpochRng\n\t\t\t\t: loaded.rng\n\t\tthis.#order = [...trainIndices]\n\t\tif (this.#cursor > 0) {\n\t\t\tlet replay = this.#epochRng\n\t\t\tfor (let pos = 0; pos < this.#cursor && pos < this.#order.length; pos += 1) {\n\t\t\t\tconst remaining = this.#order.length - pos\n\t\t\t\tconst [draw, nextReplay] = stepRandom(replay)\n\t\t\t\treplay = nextReplay\n\t\t\t\tconst pick = pos + Math.floor(draw * remaining)\n\t\t\t\tconst chosen = this.#order[pick] ?? this.#order[pos] ?? 0\n\t\t\t\tthis.#order[pick] = this.#order[pos] ?? chosen\n\t\t\t\tthis.#order[pos] = chosen\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\n\t// Snapshots active and inactive parameter states into a GGUF v3 checkpoint and persists it.\n\tasync #saveCheckpoint(dataset: Digest, signal: AbortSignal | undefined): Promise<void> {\n\t\tconst checkpoint = this.#settings.checkpoint\n\t\tif (checkpoint === undefined) return\n\t\tconst states = await this.#backward.snapshot(signal)\n\t\tconst inactive: string[] = []\n\t\tconst targets: readonly CheckpointTarget[] = states.map((state) => {\n\t\t\tconst rows = state.shape.length === 1 ? 1 : (state.shape[0] ?? 1)\n\t\t\tconst columns = state.shape.length === 1 ? (state.shape[0] ?? 1) : (state.shape[1] ?? 1)\n\t\t\tconst isInactive = state.first.length === 0 && state.second.length === 0\n\t\t\tif (isInactive) inactive.push(state.name)\n\t\t\treturn {\n\t\t\t\tname: state.name,\n\t\t\t\trows,\n\t\t\t\tcolumns,\n\t\t\t\tparameters: state.values,\n\t\t\t\tfirst: isInactive ? new Float32Array(state.values.length) : state.first,\n\t\t\t\tsecond: isInactive ? new Float32Array(state.values.length) : state.second,\n\t\t\t}\n\t\t})\n\t\tconst config: JSONRecord = {\n\t\t\trate: this.#settings.optimizer.rate,\n\t\t\tdecay: this.#settings.optimizer.decay,\n\t\t\tfirst: this.#settings.optimizer.first,\n\t\t\tsecond: this.#settings.optimizer.second,\n\t\t\tepsilon: this.#settings.optimizer.epsilon,\n\t\t\tclip: this.#settings.optimizer.clip,\n\t\t\twarmup: this.#settings.optimizer.warmup,\n\t\t\tschedule: this.#settings.optimizer.schedule,\n\t\t\tbatch: this.#settings.loop.batch,\n\t\t\tepochs: this.#settings.loop.epochs,\n\t\t\tepochRng: this.#epochRng,\n\t\t\t...(inactive.length === 0 ? {} : { inactive }),\n\t\t}\n\t\tconst record: Checkpoint = {\n\t\t\tmode: this.#settings.mode,\n\t\t\tbase: this.#settings.base,\n\t\t\tdataset,\n\t\t\tstep: this.#step,\n\t\t\tepoch: this.#epoch,\n\t\t\tcursor: this.#cursor,\n\t\t\tseed: this.#settings.loop.seed,\n\t\t\trng: this.#rng,\n\t\t\t...(this.#settings.loop.fold === undefined ? {} : { fold: this.#settings.loop.fold }),\n\t\t\tconfig,\n\t\t\ttargets,\n\t\t}\n\t\tconst bytes = buildCheckpointGGUF(record)\n\t\tawait checkpoint.store.save({ id: checkpoint.id, bytes }, signal)\n\t\tthis.#emitter.emit('checkpoint', {\n\t\t\tid: checkpoint.id,\n\t\t\tstep: this.#step,\n\t\t\tepoch: this.#epoch,\n\t\t\tbytes: bytes.byteLength,\n\t\t})\n\t}\n}\n","import type { QueueInterface } from '@orkestrel/queue'\nimport type {\n\tFinetunerInterface,\n\tFinetunerOptions,\n\tTrainQueueJob,\n\tTrainQueueOptions,\n\tTrainQueueResource,\n\tTrainQueueResult,\n} from './types.js'\nimport { checkSignal, joinBytes, InferError } from '@orkestrel/infer'\nimport { createWorker } from '@orkestrel/worker'\nimport { Finetuner } from './finetuners/Finetuner.js'\nimport {\n\tbuildCheckpointGGUF,\n\tcalibrateAdapter,\n\tcheckCheckpointId,\n\tmergeGGUF,\n\tmergeSafetensors,\n\ttraceHead,\n\ttraceSections,\n\twriteByteSink,\n} from './helpers.js'\n\n/**\n * Creates a cross-host `Finetuner` driving LoRA adapter fine-tuning or static surgical / LISA\n * full-rank section retraining over a `BackwardInterface`.\n *\n * @param options - The finetuner configuration\n * @returns The `FinetunerInterface` instance\n *\n * @example\n * ```ts\n * const finetuner = createFinetuner({\n * \tmode: 'adapter',\n * \tbackward,\n * \ttokenizer: backbone.tokenizer,\n * \tarchitecture: backbone.architecture,\n * \tbase: backbone.digest,\n * \trows,\n * \tadapter: { rank: 4, alpha: 8 },\n * })\n * const result = await finetuner.execute()\n * ```\n */\nexport function createFinetuner(options: FinetunerOptions): FinetunerInterface {\n\treturn new Finetuner(options)\n}\n\n/**\n * Creates a resource-backed background training queue over `@orkestrel/worker`'s `createWorker`\n * composing pooled `{ backbone, backward }` resources for fine-tuning, adapter calibration, head\n * and section tracing, checkpoint export, and streaming GGUF or safetensors merges.\n *\n * @remarks\n * Operates strictly at the outer job-queue boundary (never inside inner SIMD or token loops),\n * working identically in Node and offline browsers. Every job honors both the queue attempt\n * `context.signal` and any per-job `signal` through `AbortSignal.any`, and `@orkestrel/worker`\n * releases every leased resource in a `finally` block on completion, error, or cancellation.\n * Calling `destroy()` tears down the queue, then the pool, and finally the emitter behind one\n * idempotent barrier.\n *\n * @param options - The resource pool, concurrency, retry, timeout, store, and emitter hooks\n * @returns A `QueueInterface` accepting `TrainQueueJob` payloads and resolving `TrainQueueResult`\n *\n * @example\n * ```ts\n * const queue = createTrainQueue({\n * \tpool: { create: async () => ({ backbone, backward }) },\n * \tconcurrency: 1,\n * })\n * const out = await queue.enqueue({ job: 'calibrate', options: calibrationOptions })\n * await queue.destroy()\n * ```\n */\nexport function createTrainQueue(\n\toptions: TrainQueueOptions,\n): QueueInterface<TrainQueueJob, TrainQueueResult> {\n\treturn createWorker<TrainQueueJob, TrainQueueResource, TrainQueueResult>({\n\t\tpool: options.pool,\n\t\t...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),\n\t\t...(options.retries === undefined ? {} : { retries: options.retries }),\n\t\t...(options.timeout === undefined ? {} : { timeout: options.timeout }),\n\t\t...(options.store === undefined ? {} : { store: options.store }),\n\t\t...(options.on === undefined ? {} : { on: options.on }),\n\t\t...(options.error === undefined ? {} : { error: options.error }),\n\t\thandler: async (input, resource, context) => {\n\t\t\tconst effective =\n\t\t\t\tinput.signal === undefined\n\t\t\t\t\t? context.signal\n\t\t\t\t\t: AbortSignal.any([context.signal, input.signal])\n\t\t\tcheckSignal(effective, `The ${input.job} job`)\n\t\t\tif (input.job === 'finetune') {\n\t\t\t\tif (resource.backward === undefined) {\n\t\t\t\t\tthrow new InferError(\n\t\t\t\t\t\t'The pooled training resource lacks a backward engine required for a finetune job.',\n\t\t\t\t\t\t{ code: 'ARGUMENT', context: { job: input.job } },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tconst finetuner = new Finetuner({ ...input.options, backward: resource.backward })\n\t\t\t\tconst result = await finetuner.execute(effective)\n\t\t\t\treturn { job: 'finetune', result }\n\t\t\t}\n\t\t\tif (input.job === 'calibrate') {\n\t\t\t\tconst result = await calibrateAdapter({ ...input.options, signal: effective })\n\t\t\t\treturn { job: 'calibrate', result }\n\t\t\t}\n\t\t\tif (input.job === 'trace') {\n\t\t\t\tconst backbone = input.options.backbone ?? resource.backbone\n\t\t\t\tif (backbone === undefined) {\n\t\t\t\t\tthrow new InferError(\n\t\t\t\t\t\t'The pooled training resource lacks a backbone required for a trace job.',\n\t\t\t\t\t\t{ code: 'ARGUMENT', context: { job: input.job } },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tconst result = await traceHead({ ...input.options, backbone, signal: effective })\n\t\t\t\treturn { job: 'trace', result }\n\t\t\t}\n\t\t\tif (input.job === 'sections') {\n\t\t\t\tif (resource.backward === undefined) {\n\t\t\t\t\tthrow new InferError(\n\t\t\t\t\t\t'The pooled training resource lacks a backward engine required for a sections job.',\n\t\t\t\t\t\t{ code: 'ARGUMENT', context: { job: input.job } },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\tconst result = await traceSections({\n\t\t\t\t\t...input.options,\n\t\t\t\t\tbackward: resource.backward,\n\t\t\t\t\tsignal: effective,\n\t\t\t\t})\n\t\t\t\treturn { job: 'sections', result }\n\t\t\t}\n\t\t\tif (input.job === 'checkpoint') {\n\t\t\t\tcheckCheckpointId(input.id)\n\t\t\t\tconst bytes = buildCheckpointGGUF(input.checkpoint)\n\t\t\t\tcheckSignal(effective, 'The checkpoint job')\n\t\t\t\tif (input.store !== undefined) {\n\t\t\t\t\tawait input.store.save({ id: input.id, bytes }, effective)\n\t\t\t\t}\n\t\t\t\treturn { job: 'checkpoint', id: input.id, bytes }\n\t\t\t}\n\t\t\tif (input.job === 'mergeGGUF') {\n\t\t\t\tconst stream = mergeGGUF({ ...input.options, signal: effective })\n\t\t\t\tif (input.sink !== undefined) {\n\t\t\t\t\tawait writeByteSink(stream, input.sink, effective)\n\t\t\t\t\treturn { job: 'mergeGGUF', bytes: new Uint8Array(0) }\n\t\t\t\t}\n\t\t\t\tconst chunks: Array<Uint8Array<ArrayBuffer>> = []\n\t\t\t\tfor await (const chunk of stream) {\n\t\t\t\t\tcheckSignal(effective, 'The mergeGGUF job')\n\t\t\t\t\tchunks.push(chunk)\n\t\t\t\t}\n\t\t\t\treturn { job: 'mergeGGUF', bytes: joinBytes(chunks) }\n\t\t\t}\n\t\t\tconst stream = mergeSafetensors({ ...input.options, signal: effective })\n\t\t\tif (input.sink !== undefined) {\n\t\t\t\tawait writeByteSink(stream, input.sink, effective)\n\t\t\t\treturn { job: 'mergeSafetensors', bytes: new Uint8Array(0) }\n\t\t\t}\n\t\t\tconst chunks: Array<Uint8Array<ArrayBuffer>> = []\n\t\t\tfor await (const chunk of stream) {\n\t\t\t\tcheckSignal(effective, 'The mergeSafetensors job')\n\t\t\t\tchunks.push(chunk)\n\t\t\t}\n\t\t\treturn { job: 'mergeSafetensors', bytes: joinBytes(chunks) }\n\t\t},\n\t})\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA4BA,IAAa,gBAAgB;;;;;;;;;;;;;AAc7B,IAAa,qBAAqB;;;;;;;;;AAUlC,IAAa,kBAAkB;;;;;;;;;AAU/B,IAAa,eAAe;;;;;;;;;;;;;AAc5B,IAAa,oBAAuC,OAAO,OAAO;CAAC;CAAM;CAAM;CAAM;CAAM;AAAC,CAAC;;;;;;;;;AAU7F,IAAa,YAAY;;;;;;;;;AAUzB,IAAa,WAAW;;;;;;;;;;;;;AAcxB,IAAa,aAAa,OAAO,OAAO;CAAE,OAAO;CAAK,MAAM;AAAI,CAAC;;;;;;;;;AAUjE,IAAa,cAAc,OAAO,OAAO;CAAE,OAAO;CAAO,MAAM;AAAM,CAAC;;;;;;;;;AAUtE,IAAa,eAAe;;;;;;;;;;;;;;;AAgB5B,IAAa,YAAY,OAAO,OAAO;CACtC,YAAY;CACZ,OAAO;CACP,MAAM;CACN,MAAM;CACN,MAAM;CACN,OAAO;CACP,OAAO;AACR,CAAC;;;;;;;;;;;;;;;AAgBD,IAAa,YAAY;;;;;;;;;;;;;;AAezB,IAAa,YAAY;;;;;;;;;;AAWzB,IAAa,cAAc;;;;;;;;;;;;;;;;;;;;;;;AAwB3B,IAAa,cAA6B,OAAO,OAAO,EACvD,QAAQ;;;;;;;;oCAQ2B,UAAU,WAAW;wBACjC,UAAU,MAAM;;;0BAGd,UAAU,WAAW;iCACd,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