neurarch 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,22 +1,64 @@
1
1
  # neurarch
2
2
 
3
- The pre-check for an open-weight model change, before it takes a GPU or
4
- traffic. From a Hugging Face `config.json` (or a traced graph), without running
5
- the model: what a training job needs (the peak memory at its batch, the smallest
6
- card that holds it, what one run costs), whether a parallel layout is legal and
7
- balanced (`layout`), whether a serving launch will start and hold what it
8
- promises (`serve-check`), and whether the data fits what the config accepts.
9
- No account, no download, no GPU.
3
+ The release gate for the open-weight models you run yourself. Before a new
4
+ base, launch config or chat template goes live, it checks that what you will
5
+ serve is what you tested: the exact weights and code (`scan`), a prompt that
6
+ renders the same (`template-check`), a model that fits the GPU (`serve-check`,
7
+ `layout`, and the sizing check). It reads published files and your flags and
8
+ runs nothing. No account, no weights downloaded, no GPU.
9
+
10
+ Before a change goes live:
11
+
12
+ ```
13
+ npx neurarch scan . # every model your code pulls, pinned or not, and what changed since your pin
14
+ npx neurarch template-check zai-org/GLM-5.1 --engine vllm # does vLLM send the prompt the reference sends; --from <sha> for an upstream change
15
+ npx neurarch serve-check Qwen/Qwen3-8B --gpu l4 --gpus 4 -- vllm serve Qwen/Qwen3-8B -tp 4 --max-model-len 32768 # will this serving launch start
16
+ npx neurarch pin-check . # Hugging Face downloads not pinned to a commit (Bandit B615), --sarif for code scanning
17
+ ```
18
+
19
+ `scan` exits 1 on a high finding, `template-check` when a prompt differs and
20
+ `serve-check` when a check blocks, so a CI step stops on them.
21
+
22
+ **One decision: `neurarch gate`.** The three commands above as one verdict, one
23
+ exit code and one record (in the repository, not yet in the release on npm):
24
+
25
+ ```
26
+ npx neurarch gate . --gpu l4 --gpus 4 --record gate.json
27
+ ```
28
+
29
+ It runs `scan` on the paths, `serve-check` on every launch line those files
30
+ contain (on the card you name, or the card a SkyPilot task asks for) and
31
+ `template-check` on every model a launch serves. `refuse` (exit 1) is a high
32
+ scan finding or a launch that will not start; `review` (exit 0, or 1 with
33
+ `--strict`) is something to read; `admit` is nothing above low. `--record`
34
+ writes what was checked as JSON
35
+ ([schema](https://www.neurarch.com/schema/gate-record-v1.json)): each model
36
+ with the commit it is pinned to or resolved to, each launch with its card and
37
+ the engine release its defaults came from, each prompt comparison, every
38
+ finding, and what was not checked and why. A manifest that hands the model to a
39
+ runtime as arguments has no launch line: it is scanned, and the record says its
40
+ launch was not checked.
41
+
42
+ `--ledger gate-ledger.jsonl` appends one line per run (the verdict, each model's
43
+ commit, each launch's engine release and card, each prompt's template hash, the
44
+ commit and CI run it ran on); `--ledger https://your-verifier` posts the same
45
+ line to a self-hosted verifier (`POST /v1/gate`), where `GET /v1/ledger` reads
46
+ it next to the cluster's admission decisions
47
+ ([line format](https://www.neurarch.com/schema/admission-ledger-v1.json)).
48
+
49
+ Sizing and diagnosis, from a Hugging Face `config.json` (or a traced graph):
50
+ what a training job needs (the peak memory at its batch, the smallest card that
51
+ holds it, what one run costs), whether a parallel layout is legal and balanced,
52
+ and whether the data fits what the config accepts.
10
53
 
11
54
  ```
12
55
  npx neurarch rightsize jobs.csv # each past job's request next to what it needed
13
56
  npx neurarch Qwen/Qwen3-8B --batch 8 # the training peak for one model
14
57
  npx neurarch oom error.txt --model Qwen/Qwen3-8B --batch 8 # why it ran out of memory, and the least invasive fix
15
58
  npx neurarch layout Qwen/Qwen3-8B --tp 4 --pp 4 --dp 8 --global-batch 512 --seq-len 4096 # is this parallel split legal and balanced
16
- npx neurarch serve-check Qwen/Qwen3-8B --gpu l4 --gpus 4 -- vllm serve Qwen/Qwen3-8B -tp 4 --max-model-len 32768 # will this serving launch start
17
59
  npx neurarch Qwen/Qwen3-8B --inference --batch 4 --seq-len 4096 --gen 512 # weights + KV cache for a generation job
18
60
  npx neurarch policy show # the repo's .neurarch.yml: severities, budget lines, waivers with owner and expiry
19
- npx neurarch pin-check . # Hugging Face downloads not pinned to a commit (Bandit B615), --sarif for code scanning
61
+ npx neurarch weights-diff ./base ./edited # which tensors differ, and the shape of each edit
20
62
  npx neurarch bert-base-uncased --seq-len 1024 --tokenizer-size 30524 # does the data fit what the config accepts
21
63
  ```
22
64
 
@@ -543,6 +585,17 @@ What it checks (exit 1 on any `block`):
543
585
  recommended sampling changed, and the memory numbers recomputed for both
544
586
  under the same flags.
545
587
 
588
+ **vLLM 0.34.0 and later.** That release sizes the KV cache differently: the
589
+ cache is committed after CUDA graph capture and warmup from the memory actually
590
+ free, and `gpu_memory_utilization` defaults to 1.0 (vllm-project/vllm#56492);
591
+ the default block size is 64 (#63231). `serve-check --vllm-version 0.34.0` uses
592
+ block size 64 and still estimates the KV budget the earlier way, at 0.92, and
593
+ says so in the report: upstream measured 4 to 10% more KV tokens than that
594
+ default, and 1 to 4% fewer at an explicit utilization. A request that misses the
595
+ estimate by less than 10% at the default is a warning there, not a refusal.
596
+ Nothing has been fitted to a 0.34 log yet. This is in the repository and not
597
+ yet in the release on npm.
598
+
546
599
  Qwen3-8B on four L4s, with a length past the model and a batch the cache cannot hold:
547
600
 
548
601
  ```
@@ -1091,6 +1144,92 @@ verdicts as `neurarch:` properties: `neurarch:training:peak_gb`,
1091
1144
  `src/utils/attestation/index.ts`. A fragment to merge into the BOM your SBOM
1092
1145
  tool already writes; valid against the official 1.6 schema on its own.
1093
1146
 
1147
+ ## weights-diff: what differs between two local checkpoints
1148
+
1149
+ ```
1150
+ npx neurarch weights-diff <a> <b> [--json] [--max-tensors N]
1151
+ ```
1152
+
1153
+ `<a>` and `<b>` are `.safetensors` files or directories of them. It hashes every tensor and, for each
1154
+ changed 2-D tensor, reads both sides' values to say how many columns and rows moved, how large the
1155
+ change is against the tensor's norm, and how much of it one rank-1 component explains. Everything is
1156
+ read on your machine. Exit code is 0 when the weights match and 1 when they differ, so it can gate a
1157
+ promotion.
1158
+
1159
+ Each checkpoint also gets a digest that survives re-sharding. Post it as `weights_digest` to the
1160
+ self-hosted `POST /v1/outcome` and the ledger can say when one model name ran as two sets of bytes.
1161
+
1162
+ It reports which values differ. It says nothing about what the difference does to behaviour.
1163
+
1164
+ ## scan: a dependency scan for the models your code pulls
1165
+
1166
+ ```bash
1167
+ npx neurarch scan [paths...] [--json] [--no-template] [--fix] [--cyclonedx out.cdx.json]
1168
+ ```
1169
+
1170
+ Reads the same files `pin-check` reads and keeps every model download, pinned or not. For each model it reads the Hub API at your pinned commit and at `main`, the recorded change history at [neurarch.com/changes](https://www.neurarch.com/changes/), and, when the pin has moved, renders the chat template at both commits. Findings come in three lanes, and the lanes are never mixed:
1171
+
1172
+ - **security**: Python the loader runs from the repository (`auto_map` with `trust_remote_code`) that is unpinned, changed since your pin, or lives in another repository; weights available only in pickle formats.
1173
+ - **behavior**: upstream changes since your pin to the template, tokenizer, EOS or generation defaults. Not vulnerabilities: what the model receives changed.
1174
+ - **hygiene**: downloads not pinned to a commit.
1175
+
1176
+ Output on a four-line sample (2026-11-17, live Hub and the published feed, trimmed):
1177
+
1178
+ ```
1179
+ nomic-ai/nomic-embed-text-v1.5 @ 91d2d6bfdddf
1180
+ high security Its auto_map imports code from nomic-ai/nomic-bert-2048. Loaded with trust_remote_code=True,
1181
+ transformers pins that code only with code_revision=; revision= alone pins
1182
+ nomic-ai/nomic-embed-text-v1.5 and still loads the other repository's main.
1183
+ Qwen/Qwen3-8B @ e8bbd8252970
1184
+ high behavior Qwen3-8B: the chat template changed and renders differently (tool-call-parts) ... (2025-05-19).
1185
+ ```
1186
+
1187
+ The cross-repository rule is transformers' own code: `dynamic_module_utils.get_class_from_dynamic_module` fills `code_revision` from `revision` only when the code sits in the same repository ([v4.57.1, lines 595 to 602](https://github.com/huggingface/transformers/blob/v4.57.1/src/transformers/dynamic_module_utils.py#L595-L602)). On 2026-11-17, 150 of the 608 models we track ran code from their repository; 17 of the 150 tracked models that run code from their repository load it from another one.
1188
+
1189
+ For a pinned model whose `main` has moved, the scan compares the two revisions file by file, by content hash, and says which kind of file differs: weights (`weights-changed`, high), tokenizer or config (`files-changed`), the licence text (`licence-file-changed`), or nothing but the README (`pin-behind-docs-only`: moving the pin loads the same weights, tokenizer, config and code). A safetensors copy added next to an existing weight file is not counted as a change. On NeMo-Retriever at `ebc87c9` (2026-11-20), 12 of the 28 pins were behind `main`: 8 were README-only, and 4 had changed code, config, chat template or licence text.
1190
+
1191
+ **LoRA adapters.** An adapter is read where it is named: `PeftModel.from_pretrained(base, "org/adapter")`, vLLM `--lora-modules name=org/adapter`, SGLang `--lora-paths`, and an exported `adapter_config.json` in the tree. For each one the scan reads the tensor names in the adapter's and the base's safetensors headers (range requests; no weights are downloaded, nothing is run) and compares the adapter's target modules with the modules the base checkpoint has:
1192
+
1193
+ - `adapter-noop-wrapper`: the adapter's modules are named without the `language_model` level the base keeps them under. vLLM loaded such an adapter without an error and applied none of it through 0.32.0, and applies it from 0.33.0 ([vllm#34186](https://github.com/vllm-project/vllm/issues/34186), fixed by #62224). High when the file pins a vLLM version before 0.33.0 (an image tag or a pip pin in the same file), medium when the version is not in the file.
1194
+ - `adapter-no-match`: none of the adapter's target modules exists in the base.
1195
+ - `adapter-base-differs`: the launch line serves the adapter on a different id than its `adapter_config.json` names.
1196
+ - `adapter-base-unpinned` (low): the adapter's config names its base without a commit.
1197
+
1198
+ Measured on 2026-11-20 against the 600 most-downloaded Hub adapters: of the 379 that could be read, 20 carry the `language_model` signature, 16 of them on Qwen3.5 bases. The scan flags all 20 and none of 50 controls. None was run on vLLM here; the claim about engine behavior is the engine's own issue tracker's. `--no-adapter` skips the check.
1199
+
1200
+ **Deployment manifests.** A model named only in a manifest is read in the
1201
+ spelling its tool uses: an `hf://owner/model[:revision]` address (KServe
1202
+ `storageUri`, KServe `LLMInferenceService`, llm-d `modelArtifacts`), a flag
1203
+ inside a YAML list or a split `entrypoint:` and `command:` (`--model_id` for the
1204
+ KServe Hugging Face runtime, `--model-path` for SGLang), `model_source` (Ray
1205
+ Serve) and `modelURL` (the vLLM production stack's values). The fix is written
1206
+ the way that format takes a commit (`hf://owner/model:<sha>`,
1207
+ `--model_revision=<sha>`, an entry in `vllmConfig.extraArgs`). Measured on
1208
+ 2026-11-25 on 214 public manifests from GitHub code search: 154 name a Hub
1209
+ model on a line that is not commented out, and the scan read a model from 28 of
1210
+ them before these readers and from all 154 after. The yardstick is a regular
1211
+ expression, not a hand count; the other 60 files keep the model in a template
1212
+ value, an OCI image or a volume, or name none. This is in the repository and
1213
+ not yet in the release on npm.
1214
+
1215
+ **The engine is a dependency too.** When a file states its vLLM version (an
1216
+ image tag, a `vllm==` pin), `scan` lists what later vLLM release notes record
1217
+ for the model family that file serves (tool calling, prompt rendering, adapter
1218
+ loading, quantization) and the breaking changes and removals since, each with
1219
+ its pull request. The rows come from
1220
+ <https://www.neurarch.com/engine-changes/vllm.json>, built from vLLM's own
1221
+ release notes (31 releases in 2026). It says what the notes say changed, never
1222
+ whether your outputs change, and it never blocks. `--no-engine` skips it; this
1223
+ is in the repository and not yet in the release on npm.
1224
+
1225
+ Where the model id or commit lives elsewhere, it is still read: module constants (`MODEL_ID = "..."` then `from_pretrained(MODEL_ID, revision=REV)`), pin tables (a dict that maps repo ids to commits, such as the `HF_MODEL_REVISIONS` table in NVIDIA's NeMo-Retriever, where the scan read 3 models before and 31 after, 28 of them pinned), metadata records with a Hub id and a commit (MTEB's `ModelMeta(name=..., revision=...)`), and serving env vars in Kubernetes manifests, compose files and Dockerfiles (`MODEL_ID`, `REVISION`, as TGI and TEI read them). An env-only reference gets no remote-code finding unless the file sets `TRUST_REMOTE_CODE`, because those images run their own implementation, not the repository's Python. A `config.json` that names a Hub repository as its attention implementation (`_attn_implementation_internal`) is a security finding: transformers before 5.3.0 downloads and runs that repository's code (CVE-2026-4372). An id that reaches the load as a default value is read too and marked as one in the output: a parameter default (`def __init__(self, model_name="org/model")`), an argparse default read as `args.model_name`, an instance attribute, an `os.getenv("MODEL", "org/model")` fallback. `--fix` lists these instead of editing them, because a pin written at that call would apply to whatever id a caller passes. LangChain and LlamaIndex `HuggingFaceEmbedding(s)` are read, with the pin LangChain keeps in `model_kwargs`. Measured on 353 public files that name a model importing code from another repository (sampled 2026-11-17): the model is reported in 241, up from 204 before these were read. The rest pass the id through a registry dict, a list, or another file before the load; that is not followed yet. A Python load that does not pass `trust_remote_code` gets no remote-code finding, the same as a serving image without `TRUST_REMOTE_CODE`: `AutoTokenizer.from_pretrained("Alibaba-NLP/gte-large-en-v1.5")` runs none of that repository's Python, and was reported as high before 0.4.1.
1226
+
1227
+ `--fix` holds the code you run today. Where a model imports code from another repository it adds `code_revision=` at that repository's current commit (for sentence-transformers, inside `model_kwargs` and `config_kwargs`, merged into a literal dict if one is there), and where a remote-code load is not pinned it adds `revision=` at the model's current commit. Nothing you run changes on the day; it stops changing underneath you. Python calls and `vllm serve` lines are edited in place; a `**kwargs` call, a dict built elsewhere, a notebook, a metadata record or an env var is listed with the exact value to add, never guessed. Review with `git diff`; in CI, hand the working tree to a pull-request action.
1228
+
1229
+ `--cyclonedx out.cdx.json` writes a CycloneDX 1.6 BOM (validated against the 1.6 JSON schema): one `machine-learning-model` component per model with a `pkg:huggingface/<id>@<commit>` purl, each cross-repository code repository as a dependency, and each finding as a vulnerability entry carrying its lane and the recommendation it is evidence for: NIST SP 800-218A PW.4.4 (verify acquired AI models, including configuration parameters, and scan them before use), PS.3.1 / PS.3.2 (inventory and provenance), and NIST AI 600-1 GV-1.6-003 (record versions of underlying models). These are recommendations; the BOM says so, and is evidence toward them, not a certification.
1230
+
1231
+ Exit 1 when any finding is high. Network: huggingface.co and www.neurarch.com; only public model ids are requested, nothing from the scanned repository is sent. Set `HF_TOKEN` for gated repos.
1232
+
1094
1233
  ## Which Hugging Face downloads are not pinned to a commit
1095
1234
 
1096
1235
  ```
@@ -1183,3 +1322,36 @@ Set `HF_TOKEN` to read a gated repo. The token is sent only to
1183
1322
  your own
1184
1323
  - [`neurarch-lint`](https://www.npmjs.com/package/neurarch-lint): the same
1185
1324
  checks against PyTorch source
1325
+
1326
+ ## template-check: the prompt vLLM sends, against the reference
1327
+
1328
+ ```
1329
+ npx neurarch template-check <hf-id> [--at <rev>] [--tool-parts] [--json]
1330
+ npx neurarch template-check <hf-id> --from <rev> [--to <rev>] [--tool-parts] [--json]
1331
+ ```
1332
+
1333
+ A chat template is code shipped in the model repository, and two things change
1334
+ what it produces without anyone touching your deployment: the engine, and an
1335
+ upstream commit. vLLM's default `--chat-template-content-format auto` hands a
1336
+ template that reads content parts its system, user and assistant messages as a
1337
+ list of text parts; transformers' `apply_chat_template` is usually called with
1338
+ strings. `template-check` renders the template both ways on a system+user turn,
1339
+ a multi-turn chat and a tool call, and prints the first place the prompts
1340
+ diverge. Exit 1 on a difference, so it can gate CI.
1341
+
1342
+ How vLLM hands tool results was measured on vLLM 0.33.0 (2026-11-13, through
1343
+ its own `parse_chat_messages`): a string tool result stays a string. Older
1344
+ stacks passed tool results as parts, which is what broke GLM-5.1's tool calls
1345
+ until its 2026-04-16 template fix; `--tool-parts` renders that case:
1346
+
1347
+ ```
1348
+ npx neurarch template-check zai-org/GLM-5.1 --at f5ed80ea7943de93bdb66223a637d7c3af6d8fe4 --tool-parts
1349
+ DIFFERENT prompt: reference (string content) vs vllm (parts content)
1350
+ same system+user
1351
+ same multi-turn
1352
+ different tool-call at char 811
1353
+ ```
1354
+
1355
+ On vLLM 0.33.0 itself, `google/gemma-4-31B-it` differs on the system turn (one
1356
+ extra space). Rendered with @huggingface/jinja; `same` holds for these
1357
+ conversations, not every input. SGLang and llama.cpp are not modelled.
package/bin/gate.mjs ADDED
@@ -0,0 +1,259 @@
1
+ /**
2
+ * neurarch gate: one decision before a change goes live.
3
+ *
4
+ * Runs the three checks the CLI already has, over one repository, and adds
5
+ * them up:
6
+ *
7
+ * 1. the exact weights and code `scan` on the paths
8
+ * 2. a model that fits the GPU `serve-check` on every launch line the
9
+ * scanned files contain, on the card given
10
+ * (or the one a SkyPilot task names)
11
+ * 3. a prompt that renders the same `template-check` on every model a launch serves
12
+ *
13
+ * One verdict (admit, review, refuse), one exit code, and with --record one
14
+ * file that says what was checked, at which commits and on which engine
15
+ * release, and what was not checked. Each check runs as the command a person
16
+ * would run, in a child process, so the gate cannot disagree with them.
17
+ *
18
+ * Network: what the three commands use (huggingface.co, www.neurarch.com).
19
+ */
20
+ import { execFile, execFileSync } from 'node:child_process';
21
+ import { appendFileSync, readFileSync, writeFileSync } from 'node:fs';
22
+ import { resolve } from 'node:path';
23
+ import { fileURLToPath } from 'node:url';
24
+
25
+ const SELF = fileURLToPath(new URL('./neurarch.mjs', import.meta.url));
26
+ const MAX_PROMPTS = 12;
27
+
28
+ const HELP = `neurarch gate: is what goes live what you tested, in one decision
29
+
30
+ npx neurarch gate [paths...] [--gpu <card>] [--gpus N] [--record gate.json] [--ledger <file | url>]
31
+ [--strict] [--json] [--vllm-version V] [--no-serve] [--no-template]
32
+
33
+ Runs, over the paths (default: the current directory):
34
+
35
+ 1. scan every model the code and manifests pull, pinned or not,
36
+ and what changed since the pin
37
+ 2. serve-check every launch line in those files (vllm serve, python -m
38
+ sglang.launch_server, ...) on the card you name with
39
+ --gpu, or the card a SkyPilot task asks for, which
40
+ wins over --gpu for that file
41
+ 3. template-check every model a launch serves: the prompt the engine sends
42
+ against the reference
43
+
44
+ and adds them up:
45
+
46
+ refuse a high scan finding, or a launch that will not start. Exit 1.
47
+ review nothing blocks, and there is something to read: a medium finding,
48
+ a launch warning, a prompt that renders differently. Exit 0, or 1
49
+ with --strict.
50
+ admit nothing above low, and everything was read. Exit 0.
51
+
52
+ A model the Hub does not answer for, or a launch whose config cannot be read,
53
+ is never admitted: the verdict is review at best, and --strict fails on it.
54
+
55
+ --record F writes what was checked as JSON: each model with the commit it is
56
+ pinned to or resolves to today, each launch with its card and the engine
57
+ release its defaults came from, each prompt comparison, every finding, and a
58
+ list of what was not checked and why. A manifest that hands the model to a
59
+ runtime as arguments (a KServe args list, a chart value) has no launch line:
60
+ it is scanned, and the record says its launch was not checked.
61
+
62
+ --ledger F appends one line per run to a file (JSON lines): the verdict, each
63
+ model with its commit, each launch's engine release and card, each prompt's
64
+ template hash, the commit and CI run the gate ran on, and how many checks could
65
+ not be read. --ledger https://verifier.internal posts the same line to your
66
+ self-hosted verifier (POST /v1/gate), where GET /v1/ledger reads it next to the
67
+ admission webhook's decisions (NEURARCH_SELFHOST_TOKEN is sent as the bearer
68
+ token when set). A ledger write that fails is said out loud and
69
+ never changes the verdict. Line format:
70
+ https://www.neurarch.com/schema/admission-ledger-v1.json
71
+
72
+ Without --gpu, and with no card in the file, step 2 is skipped and the record
73
+ says so. Nothing is run on a GPU and no weights are downloaded.
74
+ `;
75
+
76
+ const run = (argv) => new Promise((done) => {
77
+ execFile(process.execPath, [SELF, ...argv], { maxBuffer: 256 * 1024 * 1024, env: { ...process.env, NO_COLOR: '1' } }, (err, stdout, stderr) => {
78
+ done({ code: err ? (typeof err.code === 'number' ? err.code : 2) : 0, stdout, stderr });
79
+ });
80
+ });
81
+ const json = (s) => { try { return JSON.parse(s); } catch { return null; } };
82
+
83
+ /** The commands of a file: shell lines with continuations joined, and inline arrays (`command: ["vllm", "serve", ...]`, with `args:` on the next line). */
84
+ function commandsOf(text, L) {
85
+ const out = [];
86
+ const lines = text.replace(/\\\r?\n/g, ' ').split(/\r?\n/);
87
+ for (let i = 0; i < lines.length; i++) {
88
+ const line = lines[i];
89
+ if (/^\s*#/.test(line)) continue;
90
+ const arr = (s) => { const m = /\[(.*)\]\s*$/.exec(s ?? ''); if (!m) return null; const a = json(`[${m[1]}]`); return Array.isArray(a) && a.every((x) => typeof x === 'string') ? a : null; };
91
+ const a = arr(line);
92
+ if (a) {
93
+ const next = /^\s*-?\s*args\s*:/.test(lines[i + 1] ?? '') ? arr(lines[i + 1]) : null;
94
+ out.push(next ? [...a, ...next] : a);
95
+ continue;
96
+ }
97
+ out.push(...L.shellCommands(line));
98
+ }
99
+ return out;
100
+ }
101
+
102
+ export async function gateCommand(args) {
103
+ const o = { paths: [], serve: true, template: true };
104
+ for (let i = 0; i < args.length; i++) {
105
+ const a = args[i];
106
+ const val = (name) => { const eq = a.startsWith(`${name}=`) ? a.slice(name.length + 1) : undefined; return eq ?? (a === name ? args[++i] : undefined); };
107
+ if (a === '-h' || a === '--help') { process.stdout.write(HELP); return 0; }
108
+ if (a === '--json') o.json = true;
109
+ else if (a === '--strict') o.strict = true;
110
+ else if (a === '--no-serve') o.serve = false;
111
+ else if (a === '--no-template') o.template = false;
112
+ else if (a === '--gpu' || a.startsWith('--gpu=')) o.gpu = val('--gpu');
113
+ else if (a === '--gpus' || a.startsWith('--gpus=')) o.gpus = Number(val('--gpus'));
114
+ else if (a === '--record' || a.startsWith('--record=')) o.record = val('--record');
115
+ else if (a === '--ledger' || a.startsWith('--ledger=')) o.ledger = val('--ledger');
116
+ else if (a === '--vllm-version' || a.startsWith('--vllm-version=')) o.vllmVersion = val('--vllm-version');
117
+ else if (a.startsWith('-')) { process.stderr.write(`neurarch gate: unknown flag ${a} (--help)\n`); return 2; }
118
+ else o.paths.push(a);
119
+ }
120
+ if (!o.paths.length) o.paths.push('.');
121
+ if (o.gpus != null && !(o.gpus >= 1)) { process.stderr.write('neurarch gate: --gpus must be a positive number\n'); return 2; }
122
+ if ((args.includes('--record') || args.some((x) => x.startsWith('--record='))) && !o.record) { process.stderr.write('neurarch gate: --record needs a file path\n'); return 2; }
123
+ const L = await import('../policy.bundle.mjs');
124
+ const notChecked = [];
125
+
126
+ // 1. The exact weights and code.
127
+ const scanned = await run(['scan', ...o.paths, '--json', ...(o.template ? [] : ['--no-template'])]);
128
+ const scan = json(scanned.stdout);
129
+ if (!scan) { process.stderr.write(scanned.stderr || 'neurarch gate: the scan produced no result\n'); return 2; }
130
+ const models = scan.models ?? [];
131
+ const count = (sev) => models.reduce((n, m) => n + (m.findings ?? []).filter((f) => f.severity === sev && f.kind !== 'pin-current').length, 0);
132
+ if (!scan.feed) notChecked.push('Recorded upstream changes since each pin: the change record could not be read.');
133
+ // A model the Hub did not answer for was not checked, whatever severity the scan gives the line.
134
+ const unreadModels = models.filter((m) => (m.findings ?? []).some((f) => f.kind === 'unreadable'));
135
+ if (unreadModels.length) notChecked.push(`${unreadModels.length} model${unreadModels.length === 1 ? '' : 's'} the Hub did not answer for (private, gated without HF_TOKEN, renamed, deleted, or the Hub was unreachable or rate-limiting): ${unreadModels.slice(0, 4).map((m) => m.id).join(', ')}${unreadModels.length > 4 ? ', ...' : ''}. Nothing about ${unreadModels.length === 1 ? 'it' : 'them'} was checked.`);
136
+ let unreadLaunches = 0;
137
+ if (scan.engineRecord?.unavailable) notChecked.push('What later engine releases changed: the engine release record could not be read.');
138
+
139
+ // 2. A model that fits the GPU: every launch line in the files the scan read a model from.
140
+ const files = [...new Set(models.flatMap((m) => (m.sites ?? []).map((s) => s.replace(/:\d+$/, ''))))];
141
+ const launches = [];
142
+ let manifestsWithoutLaunch = 0;
143
+ for (const file of files) {
144
+ let text;
145
+ try { text = readFileSync(resolve(file), 'utf8'); } catch { continue; }
146
+ const found = L.launchesIn(commandsOf(text, L));
147
+ if (!found.length) { if (/\.ya?ml$/i.test(file)) manifestsWithoutLaunch++; continue; }
148
+ const acc = L.acceleratorsIn(text);
149
+ const engineHere = L.engineIn(text);
150
+ for (const launch of found) launches.push({ file, ...launch, // What the file asks for is more specific than the default given on the command line.
151
+ card: (acc.card ?? o.gpu ?? null)?.toLowerCase() ?? null, gpus: acc.count ?? o.gpus ?? null, engineVersion: (launch.engine === 'vllm' ? o.vllmVersion : undefined) ?? (engineHere?.name === launch.engine ? engineHere.version : undefined) ?? null });
152
+ }
153
+ if (manifestsWithoutLaunch) notChecked.push(`Whether the launch starts and fits, for ${manifestsWithoutLaunch} manifest${manifestsWithoutLaunch === 1 ? '' : 's'} that hand${manifestsWithoutLaunch === 1 ? 's' : ''} the model to a runtime as arguments or chart values: there is no launch line to check.`);
154
+ const checkedLaunches = [];
155
+ if (!o.serve) notChecked.push('Whether any launch starts and fits: --no-serve.');
156
+ else {
157
+ const noCard = launches.filter((l) => !l.card);
158
+ if (noCard.length) notChecked.push(`Whether ${noCard.length} launch${noCard.length === 1 ? '' : 'es'} start${noCard.length === 1 ? 's' : ''} and fit${noCard.length === 1 ? 's' : ''}: no card was given. Pass --gpu <card> (and --gpus N).`);
159
+ for (const l of launches.filter((x) => x.card)) {
160
+ const r = await run(['serve-check', '--gpu', l.card, ...(l.gpus ? ['--gpus', String(l.gpus)] : []), ...(l.engineVersion ? [l.engine === 'vllm' ? '--vllm-version' : '--sglang-version', l.engineVersion] : []), '--json', '--cmd', l.command]);
161
+ const rep = json(r.stdout);
162
+ if (!rep) { unreadLaunches++; notChecked.push(`Whether \`${l.command.slice(0, 80)}\` (${l.file}) starts and fits: serve-check could not read it (${(r.stderr || '').trim().split('\n')[0].slice(0, 140) || 'no result'}).`); continue; }
163
+ checkedLaunches.push({ file: l.file, command: l.command, engine: l.engine, engineVersion: rep.resolved?.engineVersion ?? l.engineVersion, engineVersionAssumed: !!rep.resolved?.engineVersionAssumed, card: l.card, gpus: l.gpus, modelId: l.modelId, findings: (rep.findings ?? []).filter((f) => f.severity !== 'info').map((f) => ({ severity: f.severity, rule: f.rule, title: f.title })) });
164
+ }
165
+ }
166
+
167
+ // 3. A prompt that renders the same: every model a launch serves.
168
+ const prompts = [];
169
+ if (!o.template) notChecked.push('Whether each engine sends the prompt the reference sends: --no-template.');
170
+ else {
171
+ const served = [...new Map(launches.filter((l) => l.modelId).map((l) => [`${l.modelId}|${l.engine}`, l])).values()];
172
+ if (served.length > MAX_PROMPTS) notChecked.push(`The prompt of ${served.length - MAX_PROMPTS} more served model${served.length - MAX_PROMPTS === 1 ? '' : 's'}: the gate renders the first ${MAX_PROMPTS}; run template-check on the rest.`);
173
+ for (const l of served.slice(0, MAX_PROMPTS)) {
174
+ // The template the launch will load: at the commit it pins, or at main when it pins none.
175
+ const pin = models.find((m) => m.id === l.modelId)?.pinned;
176
+ const r = await run(['template-check', l.modelId, '--engine', l.engine, ...(pin ? ['--at', pin] : []), '--json']);
177
+ const rep = json(r.stdout);
178
+ if (rep?.verdict) prompts.push({ id: l.modelId, engine: l.engine, verdict: rep.verdict, ...(rep.at ? { at: rep.at } : {}), ...(rep.templateSha256 ? { templateSha256: rep.templateSha256 } : {}) });
179
+ else notChecked.push(`The prompt of ${l.modelId}: its chat template could not be read (gated without HF_TOKEN, or the repository has none).`);
180
+ }
181
+ }
182
+
183
+ const counts = {
184
+ scan: { high: count('high'), medium: count('medium'), low: count('low') },
185
+ serve: { block: checkedLaunches.reduce((n, l) => n + l.findings.filter((f) => f.severity === 'block').length, 0), warn: checkedLaunches.reduce((n, l) => n + l.findings.filter((f) => f.severity === 'warn').length, 0) },
186
+ promptDiffers: prompts.filter((p) => p.verdict === 'different').length,
187
+ unread: unreadModels.length + unreadLaunches,
188
+ };
189
+ let version = '0';
190
+ try { version = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version; } catch { /* keep 0 */ }
191
+ const record = L.buildGateRecord({
192
+ version, strict: o.strict, at: new Date().toISOString(), paths: o.paths, counts,
193
+ models: models.map((m) => ({ id: m.id, pinned: m.pinned ?? null, resolvedTo: m.mainSha ?? null, ...(m.adapterChecks?.[0]?.base ? { adapterOf: m.adapterChecks[0].base } : {}), sites: m.sites ?? [], findings: (m.findings ?? []).filter((f) => f.kind !== 'pin-current').map((f) => ({ lane: f.lane, severity: f.severity, kind: f.kind, message: f.message })) })),
194
+ launches: checkedLaunches.map(({ modelId, ...l }) => ({ ...l, ...(modelId ? { model: modelId } : {}) })),
195
+ prompts, notChecked,
196
+ });
197
+ if (o.record) writeFileSync(o.record, JSON.stringify(record, null, 2) + '\n');
198
+ // The ledger line: one per run, appended to a file or posted to the organisation's own verifier.
199
+ // Like the verifier's own ledger, a failed write never changes the verdict; unlike a silent
200
+ // failure, it is said on stderr and in the output, because a missing line is a hole in the record.
201
+ let ledgerNote = '';
202
+ if (o.ledger) {
203
+ const subject = L.gateSubjectFromEnv(process.env);
204
+ if (!subject.commit) {
205
+ const git = (...a) => { try { return execFileSync('git', a, { stdio: ['ignore', 'pipe', 'ignore'], encoding: 'utf8' }).trim() || null; } catch { return null; } };
206
+ subject.commit = git('rev-parse', 'HEAD');
207
+ subject.ref = git('rev-parse', '--abbrev-ref', 'HEAD');
208
+ }
209
+ const row = L.gateLedgerRow(record, subject);
210
+ try {
211
+ if (/^https?:\/\//i.test(o.ledger)) {
212
+ const url = /\/v1\/gate\/?$/.test(new URL(o.ledger).pathname) ? o.ledger : `${o.ledger.replace(/\/+$/, '')}/v1/gate`;
213
+ const res = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json', ...(process.env.NEURARCH_SELFHOST_TOKEN ? { authorization: `Bearer ${process.env.NEURARCH_SELFHOST_TOKEN}` } : {}) }, body: JSON.stringify(row), signal: AbortSignal.timeout(15_000) });
214
+ if (!res.ok) throw new Error(`HTTP ${res.status} ${(await res.text().catch(() => '')).slice(0, 200)}`);
215
+ ledgerNote = `Ledger: posted to ${url}`;
216
+ } else {
217
+ appendFileSync(o.ledger, JSON.stringify(row) + '\n');
218
+ ledgerNote = `Ledger: appended to ${o.ledger}`;
219
+ }
220
+ } catch (e) {
221
+ ledgerNote = `Ledger: NOT written (${e instanceof Error ? e.message : String(e)})`;
222
+ process.stderr.write(`neurarch gate: the ledger line was not written to ${o.ledger}: ${e instanceof Error ? e.message : String(e)}. The verdict is unchanged.\n`);
223
+ }
224
+ }
225
+ if (o.json) { process.stdout.write(JSON.stringify(record, null, 2) + '\n'); return record.exit; }
226
+
227
+ const tty = process.stdout.isTTY && !process.env.NO_COLOR;
228
+ const c = (code, s) => (tty ? `\u001b[${code}m${s}\u001b[0m` : String(s));
229
+ const tone = { refuse: '31', review: '33', admit: '32' }[record.verdict];
230
+ const out = process.stdout;
231
+ out.write(`\n ${c('1', 'neurarch gate')} ${c(`1;${tone}`, record.verdict.toUpperCase())} ${scan.files} file${scan.files === 1 ? '' : 's'}, ${models.length} model${models.length === 1 ? '' : 's'}, ${launches.length} launch${launches.length === 1 ? '' : 'es'}\n`);
232
+
233
+ out.write(`\n ${c('1', '1 · The exact weights and code')} ${counts.scan.high} high, ${counts.scan.medium} medium, ${counts.scan.low} low\n`);
234
+ for (const m of record.models) {
235
+ const shown = m.findings.filter((f) => f.severity === 'high' || f.severity === 'medium');
236
+ if (!shown.length) continue;
237
+ out.write(` ${m.id}${m.pinned ? ` @ ${m.pinned.slice(0, 12)}` : ' (not pinned)'} ${c('2', m.sites.slice(0, 2).join(', '))}\n`);
238
+ for (const f of shown) out.write(` ${c(f.severity === 'high' ? '31' : '33', f.severity.padEnd(6))} ${f.message.length > 220 ? `${f.message.slice(0, 217)}...` : f.message}\n`);
239
+ }
240
+
241
+ out.write(`\n ${c('1', '2 · A model that fits the GPU')} ${checkedLaunches.length} of ${launches.length} launch${launches.length === 1 ? '' : 'es'} checked, ${counts.serve.block} blocker${counts.serve.block === 1 ? '' : 's'}, ${counts.serve.warn} warning${counts.serve.warn === 1 ? '' : 's'}\n`);
242
+ for (const l of record.launches) {
243
+ out.write(` ${l.file} ${c('2', `${l.gpus ?? 1} x ${l.card}${l.engineVersion ? `, ${l.engineVersion}${l.engineVersionAssumed ? ' (assumed: the file states none)' : ''}` : ''}`)}\n ${c('2', l.command.length > 150 ? `${l.command.slice(0, 147)}...` : l.command)}\n`);
244
+ for (const f of l.findings) out.write(` ${c(f.severity === 'block' ? '31' : '33', f.severity.padEnd(6))} ${f.title}\n`);
245
+ if (!l.findings.length) out.write(` ${c('32', 'clear')}\n`);
246
+ }
247
+
248
+ out.write(`\n ${c('1', '3 · A prompt that renders the same')} ${prompts.length} model${prompts.length === 1 ? '' : 's'} rendered, ${counts.promptDiffers} differ${counts.promptDiffers === 1 ? 's' : ''}\n`);
249
+ for (const p of prompts) out.write(` ${p.id} ${c(p.verdict === 'different' ? '33' : '32', p.verdict)} ${c('2', `(reference against ${p.engine})`)}\n`);
250
+
251
+ if (notChecked.length) {
252
+ out.write(`\n ${c('1', 'Not checked')}\n`);
253
+ for (const n of notChecked) out.write(` ${n}\n`);
254
+ }
255
+ out.write(`\n ${c(`1;${tone}`, record.verdict.toUpperCase())}${record.because.length ? `: ${record.because.join(', ')}` : ': nothing above low'}. Exit ${record.exit}.${o.record ? ` Record: ${o.record}` : ''}\n`);
256
+ if (ledgerNote) out.write(` ${ledgerNote}\n`);
257
+ out.write(` ${c('2', 'Each part is the command it names; run scan, serve-check or template-check for the full detail.')}\n\n`);
258
+ return record.exit;
259
+ }
package/bin/neurarch.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * neurarch: what a GPU job needs before it takes a reservation.
3
+ * neurarch: the release gate for the models you run yourself, and the sizing
4
+ * checks underneath it (what a GPU job needs before it takes a reservation).
4
5
  *
5
6
  * npx neurarch Qwen/Qwen3-8B # layer table + derived vs published
6
7
  * npx neurarch openai/clip-vit-base-patch32 --json
@@ -22,7 +23,7 @@
22
23
  *
23
24
  * Zero dependencies; the engine is bundled. Set HF_TOKEN for gated repos.
24
25
  */
25
- import { inspectHFModel, keyFor, AGREE_TOLERANCE, priceHFModel, parseHumanSize, PREFLIGHT_GPUS, specFromFlags, renderLoraText, rightsize, renderMarkdown, headline, applyPrices, DEFAULT_CARDS, oomReport, renderOomText, readAttention, attentionPhrase, readSeqLen, DEFAULT_SEQ_LEN, inferHFModel, readInferencePrecision, INFERENCE_PRECISIONS, DEFAULT_GEN_TOKENS, DEFAULT_INFERENCE_BATCH, CHANGE_HEADROOM, storedTwiceSentence, dataFitHFModel, layoutHFModel, readLayout, readHistogram, renderLayoutText, resolveLayoutGpu, serveCheckHFModel, resolveServeGpu, parseServeCommand, readSampler, renderServeText, SERVE_ENGINES, readReceiptInput, buildReceipt, renderReceiptText, predictionFromReport } from '../engine.bundle.mjs';
26
+ import { checkParity, checkRevision, renderConformanceText, weightsDiff, renderWeightsDiffText, inspectHFModel, keyFor, AGREE_TOLERANCE, priceHFModel, parseHumanSize, PREFLIGHT_GPUS, specFromFlags, renderLoraText, rightsize, renderMarkdown, headline, applyPrices, DEFAULT_CARDS, oomReport, renderOomText, readAttention, attentionPhrase, readSeqLen, DEFAULT_SEQ_LEN, inferHFModel, readInferencePrecision, INFERENCE_PRECISIONS, DEFAULT_GEN_TOKENS, DEFAULT_INFERENCE_BATCH, CHANGE_HEADROOM, storedTwiceSentence, dataFitHFModel, layoutHFModel, readLayout, readHistogram, renderLayoutText, resolveLayoutGpu, serveCheckHFModel, resolveServeGpu, parseServeCommand, readSampler, renderServeText, SERVE_ENGINES, readReceiptInput, buildReceipt, renderReceiptText, predictionFromReport } from '../engine.bundle.mjs';
26
27
  import { setup as policySetup, finish as policyFinish, policyCommand } from './policy.mjs';
27
28
  import { setup as attestSetup, finish as attestFinish, finishPolicyApply } from './attest.mjs';
28
29
  /** The channel tag on every link this program prints. `docs/DISTRIBUTION.md`
@@ -75,6 +76,12 @@ function gpuFromFlag(arg) {
75
76
  }
76
77
 
77
78
  const args = process.argv.slice(2);
79
+ // scan: a dependency scan for the models a repository pulls, see ./scan.mjs. Dispatched before
80
+ // attestSetup, which takes `--cyclonedx F` out of argv for the pre-check commands: scan has its own
81
+ // `--cyclonedx` (the model BOM), and in 0.4.0 the global parser swallowed it and no file was written.
82
+ if (args[0] === 'scan') process.exit(await (await import('./scan.mjs')).scanCommand(args.slice(1), { checkRevision }));
83
+ // gate: scan, serve-check and template-check as one decision with one record, see ./gate.mjs. It runs each as a child process.
84
+ if (args[0] === 'gate') process.exit(await (await import('./gate.mjs')).gateCommand(args.slice(1)));
78
85
  // `--attest` / `--cyclonedx`: the run as an in-toto record and an ML-BOM fragment, see ./attest.mjs.
79
86
  const att = attestSetup(args);
80
87
  // `.neurarch.yml`, waivers, baselines, SARIF: see ./policy.mjs. Inert when the repo has none of them.
@@ -84,7 +91,11 @@ att.argv = [...args];
84
91
  /** Policy first (it may change the exit code), then the record of what the run concluded. */
85
92
  const finish = async (run, code) => attestFinish(att, pol, run, await policyFinish(pol, run, code));
86
93
  // pin-check: Hugging Face downloads not pinned to a commit (Bandit B615), see ./pinCheck.mjs.
94
+ // weights-diff: what differs between two local checkpoints, from the bytes, see ./weightsDiff.mjs.
95
+ if (args[0] === 'weights-diff') process.exit((await import('./weightsDiff.mjs')).weightsDiffCommand(args.slice(1), weightsDiff, renderWeightsDiffText));
87
96
  if (args[0] === 'pin-check') process.exit(await (await import('./pinCheck.mjs')).pinCheckCommand(args.slice(1), pol, policyFinish));
97
+ // template-check: the prompt an engine sends against the reference, or across two revisions, see ./templateCheck.mjs.
98
+ if (args[0] === 'template-check') process.exit(await (await import('./templateCheck.mjs')).templateCheckCommand(args.slice(1), { checkParity, checkRevision, renderConformanceText }));
88
99
 
89
100
  // ── oom: why a job ran out of GPU memory, and the least invasive fix ─────────
90
101
  //
@@ -458,17 +469,25 @@ for (let i = 0; i < args.length; i++) {
458
469
  }
459
470
 
460
471
  if (flags.has('-h') || flags.has('--help') || positional.length === 0) {
461
- process.stdout.write(`neurarch: what a GPU job needs before it takes a reservation
472
+ process.stdout.write(`neurarch: the release gate for the models you run yourself
462
473
 
474
+ Before a change goes live
475
+ npx neurarch gate [paths] --gpu l4 --gpus 4 --record gate.json
476
+ the three checks below as one verdict, one exit code and one record (--help)
477
+ npx neurarch scan [paths] every model your code pulls: unpinned or changed remote code, pickle weights, upstream changes since your pin
478
+ npx neurarch template-check <id> the prompt vLLM or SGLang sends against the reference; --from <rev> for an upstream change
479
+ npx neurarch serve-check <model-id> --gpu l4 --gpus 4 -- vllm serve <model-id> -tp 4 --max-model-len 32768
480
+ will this vLLM / SGLang / llama.cpp launch start and hold what it promises (--help)
481
+ npx neurarch pin-check [paths] Hugging Face downloads not pinned to a commit (Bandit B615), --sarif
482
+
483
+ Sizing and diagnosis
463
484
  npx neurarch rightsize <jobs.csv> requested vs needed GPU over your past jobs (--help for the CSV)
464
485
  npx neurarch layout <model-id> --tp 4 --pp 4 --dp 8 --global-batch 512 --seq-len 4096
465
486
  is this TP/PP/DP split legal, balanced, and worth running (--help)
466
487
  npx neurarch oom <error.txt> --model <id> --batch N
467
488
  why a job ran out of GPU memory, and the least invasive fix
468
- npx neurarch serve-check <model-id> --gpu l4 --gpus 4 -- vllm serve <model-id> -tp 4 --max-model-len 32768
469
- will this vLLM / SGLang / llama.cpp launch start and hold what it promises (--help)
470
489
  npx neurarch policy --help the repo's .neurarch.yml: severities, budget lines, waivers, baseline, --sarif
471
- npx neurarch pin-check [paths] Hugging Face downloads not pinned to a commit (Bandit B615), --sarif
490
+ npx neurarch weights-diff <a> <b> Which tensors differ between two local checkpoints, and the shape of each edit
472
491
 
473
492
  npx neurarch <model-id> e.g. Qwen/Qwen3-8B, bert-base-uncased
474
493
  npx neurarch <model-id> --json machine-readable
@@ -485,6 +504,7 @@ if (flags.has('-h') || flags.has('--help') || positional.length === 0) {
485
504
  tokens, and which cards hold it (default batch ${DEFAULT_INFERENCE_BATCH}, ${DEFAULT_GEN_TOKENS} generated, bf16)
486
505
  npx neurarch <model-id> --lora r=16,targets=q_proj,v_proj --quant int8 --fit a100-40g
487
506
  the change record: what may move on this base, and whether the gate approves it
507
+ (memory sized at batch 32 and ${DEFAULT_SEQ_LEN} tokens unless --batch / --seq-len say otherwise)
488
508
  npx neurarch <model-id> --lora-targets every Linear a LoRA can target, and PEFT target_modules
489
509
  for the attention and all-linear presets with r=8 / r=16 totals
490
510
  npx neurarch <model-id> --seq-len 1024 --tokenizer-size 30524 --classes 5 [--image-size 384 --channels 1]
@@ -874,6 +894,11 @@ if (spec) {
874
894
  process.stdout.write(` ${dim('allowed to move')} ${desc.join(' · ')}\n`);
875
895
  const e = ch.estimates;
876
896
  if (e.trainMemGb != null) process.stdout.write(` ${dim('train memory ')} ${(e.trainMemGb * CHANGE_HEADROOM).toFixed(1)} GB ${dim(ch.spec.adapter ? `(peak ${e.trainMemGb.toFixed(1)} GB, ${humanParams(e.trainableParams)} trainable, ${CHANGE_HEADROOM}x headroom)` : `(peak ${e.trainMemGb.toFixed(1)} GB, full weights, ${CHANGE_HEADROOM}x headroom)`)}\n`);
897
+ // The peak is only true at a workload: say which, and that it was assumed when the caller gave none.
898
+ if (e.trainMemGb != null) {
899
+ const assumed = [batchSize == null ? '--batch' : null, seqLen == null && e.seqLen != null ? '--seq-len' : null].filter(Boolean);
900
+ process.stdout.write(` ${dim('sized at ')} batch ${e.batchSize}${e.seqLen != null ? `, ${e.seqLen} tokens per sample` : ''}${assumed.length ? dim(` (assumed; ${assumed.join(', ')} to change)`) : ''}\n`);
901
+ }
877
902
  if (e.weightBytes != null) process.stdout.write(` ${dim('weights ')} ${(e.weightBytes / 1e9).toFixed(2)} GB ${dim(`at ${ch.spec.quant ? ch.spec.quant.precision : 'fp16'}`)}\n`);
878
903
  if (e.servingFits != null) process.stdout.write(` ${dim('serving ')} ${e.servingFits ? green('fits') : red('does not fit')}\n`);
879
904
  process.stdout.write(` ${dim('gate ')} ${gateOk ? green('approved') : red(`refused (${ch.gate.blockers.length} blocker${ch.gate.blockers.length === 1 ? '' : 's'})`)}\n`);