neurarch 0.1.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/neurarch.mjs CHANGED
@@ -12,6 +12,8 @@
12
12
  * npx neurarch Qwen/Qwen3-8B --lora-targets # which modules a LoRA can sit on
13
13
  * npx neurarch bert-base-uncased --seq-len 1024 --tokenizer-size 30524 # will this data crash it after it gets the GPU
14
14
  * npx neurarch rightsize jobs.csv # requested vs needed GPU over past jobs
15
+ * 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 and hold what it promises
15
17
  *
16
18
  * The number this exists to print is the second one: parameters derived from
17
19
  * `config.json` alone, next to `safetensors.total` from the published
@@ -20,7 +22,9 @@
20
22
  *
21
23
  * Zero dependencies; the engine is bundled. Set HF_TOKEN for gated repos.
22
24
  */
23
- 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 } from '../engine.bundle.mjs';
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 { setup as policySetup, finish as policyFinish, policyCommand } from './policy.mjs';
27
+ import { setup as attestSetup, finish as attestFinish, finishPolicyApply } from './attest.mjs';
24
28
  /** The channel tag on every link this program prints. `docs/DISTRIBUTION.md`
25
29
  * has asked for one since the first release: without it a visit from a tool
26
30
  * and a visit from a search result are the same row, and "which channel brings
@@ -71,6 +75,16 @@ function gpuFromFlag(arg) {
71
75
  }
72
76
 
73
77
  const args = process.argv.slice(2);
78
+ // `--attest` / `--cyclonedx`: the run as an in-toto record and an ML-BOM fragment, see ./attest.mjs.
79
+ const att = attestSetup(args);
80
+ // `.neurarch.yml`, waivers, baselines, SARIF: see ./policy.mjs. Inert when the repo has none of them.
81
+ if (args[0] === 'policy') process.exit(await policyCommand(args.slice(1), att.active ? { onApply: (input, ev, st) => { att.argv = [...args]; return finishPolicyApply(att, st, input, ev); } } : undefined));
82
+ const pol = await policySetup(args);
83
+ att.argv = [...args];
84
+ /** Policy first (it may change the exit code), then the record of what the run concluded. */
85
+ const finish = async (run, code) => attestFinish(att, pol, run, await policyFinish(pol, run, code));
86
+ // pin-check: Hugging Face downloads not pinned to a commit (Bandit B615), see ./pinCheck.mjs.
87
+ if (args[0] === 'pin-check') process.exit(await (await import('./pinCheck.mjs')).pinCheckCommand(args.slice(1), pol, policyFinish));
74
88
 
75
89
  // ── oom: why a job ran out of GPU memory, and the least invasive fix ─────────
76
90
  //
@@ -133,6 +147,238 @@ fragmentation or another process, not enough to say the job is too big.
133
147
  process.exit(r.diagnosis.message ? 0 : 1);
134
148
  }
135
149
 
150
+ // ── layout: is this parallel split legal, balanced, and worth running ────────
151
+ //
152
+ // TP / PP / DP (and CP / EP) for one model, checked before launch: legality,
153
+ // per-stage compute balance (the last stage carries the LM head and the loss),
154
+ // the pipeline bubble, per-stage memory, and, with a histogram, how uneven
155
+ // sequence lengths stall the DP ranks. Every number is derived from the graph;
156
+ // the check is src/utils/parallelLayout.ts through the bundle.
157
+ if (args[0] === 'layout') {
158
+ const rest = args.slice(1);
159
+ const L = {};
160
+ const pos = [];
161
+ const VAL = ['tp', 'pp', 'dp', 'cp', 'ep', 'gpus', 'gpu', 'micro', 'global-batch', 'grad-accum', 'seq-len', 'schedule', 'virtual', 'layers', 'zero', 'seq-hist'];
162
+ for (let i = 0; i < rest.length; i++) {
163
+ const a = rest[i];
164
+ const eq = /^--([a-z-]+)=(.*)$/.exec(a);
165
+ if (eq && VAL.includes(eq[1])) { L[eq[1]] = eq[2]; continue; }
166
+ if (a.startsWith('--') && VAL.includes(a.slice(2))) { L[a.slice(2)] = rest[++i]; continue; }
167
+ if (a === '--json') { L.json = true; continue; }
168
+ if (a === '--fsdp') { L.fsdp = true; continue; }
169
+ if (a === '--recompute' || a === '--activation-checkpointing') { L.recompute = true; continue; }
170
+ if (a === '--embedding-as-layer') { L.embLayer = true; continue; }
171
+ if (a === '--loss-as-layer') { L.lossLayer = true; continue; }
172
+ if (a === '--fused-ce') { L.fusedCe = true; continue; }
173
+ if (a === '-h' || a === '--help') { L.help = true; continue; }
174
+ pos.push(a);
175
+ }
176
+ if (L.help || pos.length !== 1) {
177
+ process.stdout.write(`neurarch layout: is this way of splitting the job across GPUs legal, balanced, and worth running
178
+
179
+ npx neurarch layout <hf-id | graph.json> --tp 4 --pp 4 --dp 8 --micro 1 --global-batch 512 --seq-len 4096
180
+ [--gpu h100] [--gpus 128] [--cp 2] [--ep 8] [--grad-accum 64]
181
+ [--schedule 1f1b|interleaved --virtual 2] [--layers 7,8,8,9]
182
+ [--zero 0|1|2|3 | --fsdp] [--recompute] [--embedding-as-layer] [--loss-as-layer] [--fused-ce]
183
+ [--seq-hist hist.csv] [--json]
184
+
185
+ Checks: world size and TP / EP / CP divisibility (block), per-stage balance
186
+ with a rebalanced --layers, the pipeline bubble, per-stage memory on the card,
187
+ and with --seq-hist (CSV of len,count) how much the slowest DP rank waits on
188
+ uneven sequence lengths. Stage time is predicted, not timed: each matmul at up
189
+ to 40% of the card's peak, less when short (a curve fitted to measured kernels
190
+ on H100, L4, A100, V100, T4), plus memory-bound bytes (norms, elementwise, the
191
+ fp32 loss) at 80% of its bandwidth; step time simulates the 1F1B or
192
+ interleaved schedule at your microbatch count. --fused-ce says the loss never holds fp32
193
+ logits (Liger, chunked CE). Exits 1 when a check blocks.
194
+ `);
195
+ process.exit(L.help ? 0 : 2);
196
+ }
197
+ const raw = {
198
+ tp: L.tp, pp: L.pp, dp: L.dp, cp: L.cp, ep: L.ep, num_gpus: L.gpus, gpu: L.gpu,
199
+ micro_batch: L.micro ?? 1, global_batch: L['global-batch'], grad_accum: L['grad-accum'],
200
+ seq_len: L['seq-len'] ?? DEFAULT_SEQ_LEN, schedule: L.schedule, virtual_stages: L.virtual,
201
+ layers_per_stage: L.layers, zero_stage: L.zero,
202
+ ...(L.fsdp ? { fsdp: true } : {}), ...(L.recompute ? { activation_checkpointing: true } : {}),
203
+ ...(L.embLayer ? { embedding_on_first: false } : {}), ...(L.lossLayer ? { head_on_last: false } : {}),
204
+ ...(L.fusedCe ? { fused_cross_entropy: true } : {}),
205
+ };
206
+ for (const k of Object.keys(raw)) if (raw[k] == null) delete raw[k];
207
+ const layout = readLayout(raw);
208
+ if (layout.error) {
209
+ const FLAG = { micro_batch: 'micro', num_gpus: 'gpus', virtual_stages: 'virtual', layers_per_stage: 'layers', zero_stage: 'zero' };
210
+ process.stderr.write(`${red('bad flag')}: ${layout.error.replace(/`layout\.([a-z_]+)`/, (_, n) => `--${FLAG[n] ?? n.replace(/_/g, '-')}`)}\n`);
211
+ process.exit(2);
212
+ }
213
+ if (L.gpu != null && !resolveLayoutGpu(L.gpu)) {
214
+ process.stderr.write(`${red('unknown --gpu')} ${L.gpu}: give a card id or an unambiguous prefix (h100, h200, b200, a100-80g, a100-40g, l40s, ...)\n`);
215
+ process.exit(2);
216
+ }
217
+ if (L['seq-hist']) {
218
+ const { readFile } = await import('node:fs/promises');
219
+ let text;
220
+ try { text = await readFile(L['seq-hist'], 'utf8'); } catch (e) {
221
+ process.stderr.write(`${red('cannot read')} --seq-hist ${L['seq-hist']}: ${e.message}\n`);
222
+ process.exit(2);
223
+ }
224
+ const h = readHistogram(text);
225
+ if (h.error) { process.stderr.write(`${red('--seq-hist')} ${h.error}\n`); process.exit(2); }
226
+ layout.seqLenHistogram = h.histogram;
227
+ }
228
+ const r = await layoutHFModel(pos[0], layout);
229
+ if (r.error) { process.stderr.write(`${red('cannot read')} ${pos[0]}: ${r.error}\n`); process.exit(2); }
230
+ const blocked = r.report.findings.some((f) => f.severity === 'block');
231
+ if (L.json) {
232
+ process.stdout.write(JSON.stringify({ model: pos[0], layout, ...r.report }, null, 2) + '\n');
233
+ } else {
234
+ const text = renderLayoutText(r.report, r.name)
235
+ .replace(/^ {2}block (.*)$/gm, (_, t) => ` ${red('block')} ${bold(t)}`)
236
+ .replace(/^ {2}warn {2}(.*)$/gm, (_, t) => ` ${yellow('warn ')} ${t}`)
237
+ .replace(/ NO$/gm, ` ${red('NO')}`);
238
+ process.stdout.write(text);
239
+ }
240
+ process.exit(await finish({ command: 'layout', model: pos[0], layout: r.report, layoutSpec: layout, gpu: L.gpu, json: L.json }, blocked ? 1 : 0));
241
+ }
242
+
243
+ // ── serve-check: will this vLLM / SGLang / llama.cpp launch start ────────────
244
+ //
245
+ // Reads the launch command (after `--`, or --cmd "<string>"), the model's
246
+ // config.json, tokenizer_config.json, chat_template.jinja and
247
+ // generation_config.json from the Hub, and the card. The check is
248
+ // src/utils/serveConfigCheck.ts through the bundle.
249
+ if (args[0] === 'serve-check') {
250
+ const dd = args.indexOf('--', 1);
251
+ const rest = dd >= 0 ? args.slice(1, dd) : args.slice(1);
252
+ const after = dd >= 0 ? args.slice(dd + 1) : null;
253
+ const S = {};
254
+ const pos = [];
255
+ const VAL = ['engine', 'gpu', 'gpus', 'cmd', 'against', 'sampler', 'vllm-version', 'sglang-version', 'receipt', 'gpu-mem', 'gpu-mem-used'];
256
+ for (let i = 0; i < rest.length; i++) {
257
+ const a = rest[i];
258
+ const eq = /^--([a-z-]+)=(.*)$/.exec(a);
259
+ if (eq && VAL.includes(eq[1])) { S[eq[1]] = eq[2]; continue; }
260
+ if (a.startsWith('--') && VAL.includes(a.slice(2))) { S[a.slice(2)] = rest[++i]; continue; }
261
+ if (a === '--json') { S.json = true; continue; }
262
+ if (a === '-h' || a === '--help') { S.help = true; continue; }
263
+ pos.push(a);
264
+ }
265
+ const cmd = after && after.length ? after : S.cmd;
266
+ if (S.help || !cmd) {
267
+ process.stdout.write(`neurarch serve-check: will this serving launch start, hold what it promises, and serve the model as published
268
+
269
+ npx neurarch serve-check <hf-id | graph.json> [--engine vllm|sglang|llamacpp] --gpu h100 [--gpus 4]
270
+ [--vllm-version 0.19.1 | --sglang-version 0.5.22] [--against <old-hf-id>]
271
+ [--gpu-mem <GiB>] [--gpu-mem-used <GiB>]
272
+ [--sampler temperature=0.7,top_p=0.8] [--receipt <startup plan | dir | vLLM log>] [--json] -- <launch command>
273
+ npx neurarch serve-check <hf-id> --gpu l4 --cmd "vllm serve Qwen/Qwen3-8B -tp 4 --max-model-len 32768"
274
+
275
+ The launch command is the one you would run: vllm serve ..., python -m
276
+ sglang.launch_server ..., or llama-server -m x.gguf .... The model id is
277
+ optional when the command names a Hugging Face repo (vLLM / SGLang); for
278
+ llama.cpp give the original repo id, since a .gguf file carries no config.json.
279
+
280
+ Checks: TP / PP / DP / EP legality against the heads, KV heads, FFN and expert
281
+ widths and the GPU count; the served length against max_position_embeddings and
282
+ rope_scaling; memory per GPU with the engine's own arithmetic (vLLM's KV cache
283
+ blocks per attention type and the reserve it takes first, SGLang's
284
+ mem_fraction_static formula, llama.cpp's cells and the GGUF header), predicting
285
+ the "GPU KV cache size" and "Maximum concurrency" lines; the quant method
286
+ against each engine release's own minimum compute capability; the vLLM recipe
287
+ for the model (parsers, trust-remote-code, min version); the chat template and
288
+ sampler defaults against generation_config.json. Defaults that changed between
289
+ releases (gpu_memory_utilization 0.9 -> 0.92 and CUDA graphs counted, both in
290
+ vLLM 0.20.0) follow --vllm-version, or the newest release the tables were read
291
+ from, and the report says which. --against diffs the config of the model being
292
+ replaced. Everything is predicted from files, not measured; template checks do
293
+ not render a conversation. Exits 1 when a check blocks.
294
+
295
+ Cards: the app's table plus a40, gh200-96g, gh200-144g, rtx-pro-6000 and
296
+ ascend-910b (memory only; no CUDA checks). --gpu-mem <GiB> sets the card's total
297
+ as torch reports it (the figure vLLM multiplies by --gpu-memory-utilization),
298
+ on top of --gpu or alone for a card not in the table. --gpu-mem-used <GiB> is
299
+ memory other processes already hold on each GPU. vLLM's --kv-cache-memory-bytes
300
+ is read from the launch command. When the repo publishes
301
+ model.safetensors.index.json, the weights derived from config.json are compared
302
+ with its total_size; past 10% apart the published size is used and the report
303
+ says so.
304
+
305
+ --receipt prints what vLLM measured next to the prediction: a startup plan
306
+ (VLLM_ENABLE_STARTUP_PLAN=1 writes {VLLM_CACHE_ROOT}/startup_plan/startup_plan_<fp>.json,
307
+ vLLM >= 0.26; give a file or the directory, ranks are read together) or a startup
308
+ log. A plan vLLM itself would ignore (wrong schema, a fingerprint that does not
309
+ match its name, a non-positive size, a baseline above this card's memory) is
310
+ named and not quoted. A log's vLLM version is used when --vllm-version is not given.
311
+ `);
312
+ process.exit(S.help ? 0 : 2);
313
+ }
314
+ const parsed = parseServeCommand(cmd, S.engine ? (S.engine === 'llama.cpp' ? 'llamacpp' : S.engine) : undefined);
315
+ if (S.engine && !SERVE_ENGINES.includes(S.engine === 'llama.cpp' ? 'llamacpp' : S.engine)) {
316
+ process.stderr.write(`${red('unknown --engine')} ${S.engine}. One of: ${SERVE_ENGINES.join(', ')}\n`);
317
+ process.exit(2);
318
+ }
319
+ if (!parsed.engine) {
320
+ process.stderr.write(`${red('cannot tell the engine')} from the command; pass --engine vllm|sglang|llamacpp\n`);
321
+ process.exit(2);
322
+ }
323
+ const ref = pos[0] ?? (parsed.engine !== 'llamacpp' && parsed.args.model && /^[\w.-]+\/[\w.-]+$/.test(parsed.args.model) ? parsed.args.model : null);
324
+ if (!ref) {
325
+ process.stderr.write(`${red('no model')}: give the Hugging Face id (or graph.json) before the flags${parsed.engine === 'llamacpp' ? '; a .gguf file carries no config.json, so name the repo it was converted from' : ''}\n`);
326
+ process.exit(2);
327
+ }
328
+ const gpuMem = S['gpu-mem'] != null ? Number(S['gpu-mem']) : undefined;
329
+ const gpuMemUsed = S['gpu-mem-used'] != null ? Number(S['gpu-mem-used']) : undefined;
330
+ if (gpuMem != null && !(gpuMem > 0)) { process.stderr.write(`${red('--gpu-mem')} must be a positive number of GiB\n`); process.exit(2); }
331
+ if (gpuMemUsed != null && !(gpuMemUsed >= 0)) { process.stderr.write(`${red('--gpu-mem-used')} must be a number of GiB, 0 or more\n`); process.exit(2); }
332
+ if (S.gpu != null && !resolveServeGpu(S.gpu)) {
333
+ process.stderr.write(`${red('unknown --gpu')} ${S.gpu}: give a card id or an unambiguous prefix (h100, h200, b200, a100-80g, a100-40g, a40, gh200-96g, gh200-144g, rtx-pro-6000, ascend-910b, l40s, l4, ...), or --gpu-mem <GiB> for any other card\n`);
334
+ process.exit(2);
335
+ }
336
+ const gpus = S.gpus != null ? Number(S.gpus) : undefined;
337
+ if (gpus != null && !(Number.isInteger(gpus) && gpus > 0)) { process.stderr.write(`${red('--gpus')} must be a positive integer\n`); process.exit(2); }
338
+ let sampler;
339
+ if (S.sampler) {
340
+ const o = {};
341
+ for (const part of String(S.sampler).split(',')) { const [k, v] = part.split('='); if (k && v != null) o[k.trim()] = v.trim(); }
342
+ sampler = readSampler(o);
343
+ }
344
+ let receiptInputs = null;
345
+ if (S.receipt) {
346
+ const fs = await import('node:fs');
347
+ const path = await import('node:path');
348
+ if (parsed.engine !== 'vllm') { process.stderr.write(`${red('--receipt')} reads vLLM startup plans and logs; this launch is ${parsed.engine}\n`); process.exit(2); }
349
+ let files;
350
+ try {
351
+ files = fs.statSync(S.receipt).isDirectory()
352
+ ? fs.readdirSync(S.receipt).filter((f) => /^startup_plan_.*\.json$/.test(f)).sort().map((f) => path.join(S.receipt, f))
353
+ : [S.receipt];
354
+ } catch (e) { process.stderr.write(`${red('cannot read --receipt')} ${S.receipt}: ${e.message}\n`); process.exit(2); }
355
+ if (!files.length) { process.stderr.write(`${red('--receipt')} ${S.receipt}: no startup_plan_*.json in the directory\n`); process.exit(2); }
356
+ receiptInputs = files.map((f) => readReceiptInput(fs.readFileSync(f, 'utf8'), f));
357
+ }
358
+ const logVersion = receiptInputs?.find((x) => x.kind === 'startup-log' && x.vllmVersion)?.vllmVersion;
359
+ const engineVersion = parsed.engine === 'vllm' ? (S['vllm-version'] ?? logVersion?.replace(/^(\d+\.\d+\.\d+).*$/, '$1')) : parsed.engine === 'sglang' ? S['sglang-version'] : undefined;
360
+ const r = await serveCheckHFModel(ref, { engine: parsed.engine, args: parsed.args, gpu: S.gpu, gpus, sampler, against: S.against, engineVersion, gpuMemGiB: gpuMem, gpuMemUsedGiB: gpuMemUsed });
361
+ if (r.error) { process.stderr.write(`${red('cannot read')} ${ref}: ${r.error}\n`); process.exit(2); }
362
+ let receipt = null;
363
+ if (receiptInputs) {
364
+ const pred = predictionFromReport(r.report);
365
+ receipt = pred ? buildReceipt(receiptInputs, pred) : { source: S.receipt, rows: [], notes: ['no prediction to compare against: the memory check needs --gpu and a config with layer geometry'], compared: false };
366
+ }
367
+ const blocked = r.report.findings.some((f) => f.severity === 'block');
368
+ if (S.json) {
369
+ process.stdout.write(JSON.stringify({ model: ref, command: Array.isArray(cmd) ? cmd.join(' ') : cmd, ignoredFlags: parsed.ignored, ...r.report, ...(receipt ? { receipt } : {}) }, null, 2) + '\n');
370
+ } else {
371
+ let text = renderServeText(r.report, r.name)
372
+ .replace(/^ {2}block (.*)$/gm, (_, t) => ` ${red('block')} ${bold(t)}`)
373
+ .replace(/^ {2}warn {2}(.*)$/gm, (_, t) => ` ${yellow('warn ')} ${t}`)
374
+ .replace(/^ {2}info {2}(.*)$/gm, (_, t) => ` ${dim('info ')} ${t}`);
375
+ if (parsed.ignored.length) text += ` ${dim(`flags not read by this check: ${parsed.ignored.join(' ')}`)}\n\n`;
376
+ if (receipt) text += renderReceiptText(receipt);
377
+ process.stdout.write(text);
378
+ }
379
+ process.exit(await finish({ command: 'serve-check', model: ref, serve: r.report, engine: parsed.engine, gpu: S.gpu, json: S.json }, blocked ? 1 : 0));
380
+ }
381
+
136
382
  // ── rightsize: requested vs needed over a team's past jobs ──────────────────
137
383
  //
138
384
  // A subcommand rather than a flag, because its input is a CSV of jobs and not
@@ -215,8 +461,14 @@ if (flags.has('-h') || flags.has('--help') || positional.length === 0) {
215
461
  process.stdout.write(`neurarch: what a GPU job needs before it takes a reservation
216
462
 
217
463
  npx neurarch rightsize <jobs.csv> requested vs needed GPU over your past jobs (--help for the CSV)
464
+ npx neurarch layout <model-id> --tp 4 --pp 4 --dp 8 --global-batch 512 --seq-len 4096
465
+ is this TP/PP/DP split legal, balanced, and worth running (--help)
218
466
  npx neurarch oom <error.txt> --model <id> --batch N
219
467
  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
+ 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
220
472
 
221
473
  npx neurarch <model-id> e.g. Qwen/Qwen3-8B, bert-base-uncased
222
474
  npx neurarch <model-id> --json machine-readable
@@ -386,7 +638,8 @@ if (flags.has('--json')) {
386
638
  }
387
639
  : { ok: false, modelId, reason: result.reason };
388
640
  process.stdout.write(JSON.stringify(payload, null, 2) + '\n');
389
- process.exit(payload.ok && !(payload.dataFit?.findings ?? []).some((f) => f.severity === 'block') ? 0 : 1);
641
+ const code = payload.ok && !(payload.dataFit?.findings ?? []).some((f) => f.severity === 'block') ? 0 : 1;
642
+ process.exit(!payload.ok ? code : await finish({ command: 'check', model: modelId, json: true, lint: payload.findings, dataFit: payload.dataFit, cost: payload.cost, inference: payload.inference, change: payload.change, params: payload.derivedParams, gpu: opts.gpu, dataGiven: opts.data != null }, code));
390
643
  }
391
644
 
392
645
  if (!result.ok && !sizingOnly) {
@@ -398,6 +651,8 @@ const hub = result.hub;
398
651
  const facts = result.ok ? result.facts : result.sizing;
399
652
  /** Blocking findings; the exit code reads it. Empty when only sizing ran. */
400
653
  const blockers = result.ok ? facts.findings.filter((f) => f.severity === 'block') : [];
654
+ /** What the policy layer reads at exit; each block below adds its report. */
655
+ const policyRun = { command: 'check', model: modelId, gpu: opts.gpu, dataGiven: opts.data != null, lint: result.ok ? facts.findings : undefined, params: result.ok ? facts.derivedParams : undefined };
401
656
 
402
657
  process.stdout.write(`\n${bold(hub.modelId)} ${dim(`${hub.modelType}${hub.pipelineTag ? ` · ${hub.pipelineTag}` : ''}`)}\n\n`);
403
658
 
@@ -469,6 +724,7 @@ if (sizingOnly) {
469
724
  // does not get far enough for its peak to matter.
470
725
  if (dataAsked) {
471
726
  const fit = dataFitHFModel(facts, dataSpec);
727
+ policyRun.dataFit = fit;
472
728
  const blocks = fit.findings.filter((f) => f.severity === 'block');
473
729
  process.stdout.write(`\n ${bold('data fit')} ${dim(`checked: ${fit.checked.join(', ') || 'nothing'}`)}\n`);
474
730
  if (!fit.findings.length && fit.checked.length) process.stdout.write(` ${green('fits')} ${dim('every stated field is within what the config accepts')}\n`);
@@ -488,11 +744,14 @@ if (dataAsked) {
488
744
  // and the lines below say what that leaves out.
489
745
  if (inference) {
490
746
  const ip = inferHFModel(facts, inferOpts);
747
+ policyRun.inference = ip;
491
748
  if (!ip) {
492
749
  process.stderr.write(`\n ${red('cannot size')} inference for ${modelId}: no weights read from the config\n`);
493
750
  process.exit(1);
494
751
  }
495
- const fits = ip.fits.map((g) => (g.fits ? green(gpuSlug(g.gpu)) : red(gpuSlug(g.gpu)))).join(' ');
752
+ // The words carry the answer and the colour only repeats it: piped into a
753
+ // file or a CI log (NO_COLOR, no TTY) a bare card name read as "fits" for every card.
754
+ const fits = ip.fits.map((g) => (g.fits ? green(`${gpuSlug(g.gpu)} yes`) : red(`${gpuSlug(g.gpu)} no`))).join(' ');
496
755
  process.stdout.write(`\n ${bold('inference memory')} ${dim(`batch ${ip.batch}, ${ip.promptTokens} prompt + ${ip.genTokens} generated tokens, ${ip.precision} weights`)}\n`);
497
756
  process.stdout.write(` ${dim('weights ')} ${ip.weightsGb.toFixed(1)} GB\n`);
498
757
  process.stdout.write(` ${dim('KV cache ')} ${ip.kvGb.toFixed(1)} GB ${dim(`(${(ip.kvBytesPerToken / 1024).toFixed(0)} KiB per token x ${ip.promptTokens + ip.genTokens} tokens x batch ${ip.batch})`)}\n`);
@@ -537,6 +796,7 @@ if (trainingSizing) {
537
796
  }
538
797
  const { plan } = priceHFModel(facts, samples != null ? { samples, source: String(opts.data) } : undefined, runFrom(run), undefined, attention, seqLen);
539
798
  const cost = plan.cost;
799
+ policyRun.cost = cost;
540
800
  if (samples != null) {
541
801
  const hrs = cost.estTrainSec != null ? cost.estTrainSec / 3600 : null;
542
802
  const money = cost.estCostUsd == null ? 'n/a'
@@ -602,6 +862,7 @@ if (spec) {
602
862
  const run = gpuFromFlag(opts.gpu);
603
863
  const { plan } = priceHFModel(facts, { samples: samples && samples > 0 ? samples : 50_000, source: opts.data != null ? String(opts.data) : 'assumed' }, runFrom(run), spec, attention, seqLen);
604
864
  const ch = plan.change;
865
+ policyRun.change = ch;
605
866
  if (ch) {
606
867
  const gateOk = ch.gate.ok;
607
868
  process.stdout.write(`\n ${bold('change record')} ${dim(`spec ${ch.specId} on ${ch.baseFingerprint}`)}\n`);
@@ -652,4 +913,4 @@ process.stdout.write('\n');
652
913
  if (publishedPage) process.stdout.write(` ${dim(`page ${publishedPage}`)}\n`);
653
914
  process.stdout.write(` ${dim(`compare https://neurarch.com/compare?a=${encodeURIComponent(modelId)}&b=&utm_source=${SOURCE}`)}\n`);
654
915
  process.stdout.write(` ${dim('check POST https://www.neurarch.com/api/v1/check')}\n\n`);
655
- process.exit(blockers.length ? 1 : 0);
916
+ process.exit(await finish(policyRun, blockers.length ? 1 : 0));
@@ -0,0 +1,138 @@
1
+ /**
2
+ * `neurarch pin-check [paths...]`: Hugging Face downloads not pinned to a
3
+ * commit, in .py, .ipynb, YAML, shell scripts and Dockerfiles. Aligned with
4
+ * Bandit B615. The scanning is src/utils/policy/pinCheck.ts (through
5
+ * policy.bundle.mjs); this file walks the tree, optionally asks the Hub for
6
+ * the current commit (`--resolve`, off by default: no network unless asked),
7
+ * prints, and hands the findings to the policy layer for `.neurarch.yml`
8
+ * severities, waivers, the baseline and `--sarif`.
9
+ */
10
+ import { readFileSync, readdirSync, statSync } from 'node:fs';
11
+ import { join, relative, resolve, sep } from 'node:path';
12
+
13
+ const SKIP_DIRS = new Set(['.git', '.hg', '.svn', 'node_modules', '.venv', 'venv', 'env', '__pycache__', '.tox', '.nox', '.mypy_cache', '.pytest_cache', '.ruff_cache', 'site-packages', '.ipynb_checkpoints']);
14
+ const MAX_BYTES = 5 * 1024 * 1024;
15
+
16
+ const tty = process.stdout.isTTY && !process.env.NO_COLOR;
17
+ const c = (code, s) => (tty ? `\x1b[${code}m${s}\x1b[0m` : String(s));
18
+ const posix = (p) => p.split(sep).join('/');
19
+
20
+ function* walk(abs, kindOf) {
21
+ let st;
22
+ try { st = statSync(abs); } catch { return; }
23
+ if (st.isFile()) { if (kindOf(abs) && st.size <= MAX_BYTES) yield abs; return; }
24
+ if (!st.isDirectory()) return;
25
+ let entries;
26
+ try { entries = readdirSync(abs, { withFileTypes: true }); } catch { return; }
27
+ for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
28
+ if (e.isDirectory() && SKIP_DIRS.has(e.name)) continue;
29
+ if (e.isSymbolicLink()) continue;
30
+ yield* walk(join(abs, e.name), kindOf);
31
+ }
32
+ }
33
+
34
+ /** The commit `main` points at now, or null. Only called with --resolve. */
35
+ async function headSha(repoType, id) {
36
+ const url = `https://huggingface.co/api/${repoType === 'dataset' ? 'datasets' : 'models'}/${id}/revision/main`;
37
+ const headers = process.env.HF_TOKEN ? { Authorization: `Bearer ${process.env.HF_TOKEN}` } : {};
38
+ try {
39
+ const r = await fetch(url, { headers, signal: AbortSignal.timeout(10_000) });
40
+ if (!r.ok) return null;
41
+ const j = await r.json();
42
+ return typeof j.sha === 'string' && /^[0-9a-f]{40}$/.test(j.sha) ? j.sha : null;
43
+ } catch { return null; }
44
+ }
45
+
46
+ const HELP = `neurarch pin-check: Hugging Face downloads that are not pinned to a commit
47
+
48
+ npx neurarch pin-check [paths...] [--resolve] [--json] [--sarif out.sarif] [--policy .neurarch.yml]
49
+
50
+ Reads .py, .ipynb, YAML, shell scripts and Dockerfiles (default: the current
51
+ directory) for from_pretrained / load_dataset / hf_hub_download /
52
+ snapshot_download / pipeline(model=...), vllm serve, the vLLM and SGLang server
53
+ modules, huggingface-cli / hf download, and YAML model keys (base_model,
54
+ model_name_or_path, ...) with no revision, or with a branch or tag as the
55
+ revision. Aligned with Bandit B615; # nosec and # nosec B615 are honoured.
56
+
57
+ pin/hf-unpinned NX-PIN-001 warn a repo id and no revision
58
+ pin/hf-floating-revision NX-PIN-002 warn revision is main, a tag or a PR ref
59
+ pin/hf-unpinned-dynamic NX-PIN-003 info the repo id is a variable and there is no revision
60
+
61
+ --resolve asks the Hub API for the commit main points at now and puts that sha
62
+ in the fix (network; HF_TOKEN is sent for gated repos). Off by default.
63
+
64
+ Severity per rule in .neurarch.yml, e.g. rules: { pin/hf-unpinned: block }
65
+ Once pinned, extend https://www.neurarch.com/changes-feeds/renovate/preset.json
66
+ in renovate.json and Renovate opens a PR when a tracked model moves.
67
+ `;
68
+
69
+ export async function pinCheckCommand(args, pol, policyFinish) {
70
+ const L = await import('../policy.bundle.mjs');
71
+ const o = { paths: [] };
72
+ for (const a of args) {
73
+ if (a === '-h' || a === '--help') { process.stdout.write(HELP); return 0; }
74
+ if (a === '--json') o.json = true;
75
+ else if (a === '--resolve') o.resolve = true;
76
+ else if (a.startsWith('-')) { process.stderr.write(`neurarch pin-check: unknown flag ${a} (--help)\n`); return 2; }
77
+ else o.paths.push(a);
78
+ }
79
+ if (!o.paths.length) o.paths.push('.');
80
+ const root = pol?.root ?? process.cwd();
81
+ const kindOf = (p) => L.pinFileKind(posix(p));
82
+
83
+ const hits = [];
84
+ const sources = [];
85
+ let files = 0;
86
+ for (const p of o.paths) {
87
+ const abs = resolve(p);
88
+ try { statSync(abs); } catch { process.stderr.write(`neurarch pin-check: ${p}: no such file or directory\n`); return 2; }
89
+ for (const f of walk(abs, kindOf)) {
90
+ let text;
91
+ try { text = readFileSync(f, 'utf8'); } catch { continue; }
92
+ files++;
93
+ const rel = posix(relative(root, f)) || posix(f);
94
+ const found = L.scanPins(rel, text);
95
+ hits.push(...found);
96
+ sources.push({ path: rel, text });
97
+ }
98
+ }
99
+
100
+ const shas = {};
101
+ let resolvedOn;
102
+ if (o.resolve) {
103
+ resolvedOn = new Date().toISOString().slice(0, 10);
104
+ const ids = [...new Set(hits.filter((h) => h.repo).map((h) => `${h.repoType}:${h.repo}`))];
105
+ await Promise.all(ids.map(async (k) => {
106
+ const [type, ...rest] = k.split(':');
107
+ const sha = await headSha(type, rest.join(':'));
108
+ if (sha) shas[k] = sha;
109
+ }));
110
+ }
111
+ const findings = L.fromPinCheck(hits, { shas, resolvedOn });
112
+ const code = findings.some((f) => f.severity === 'block') ? 1 : 0;
113
+
114
+ const out = o.json ? process.stderr : process.stdout;
115
+ if (o.json) {
116
+ process.stdout.write(JSON.stringify({ files, hits, findings, resolved: o.resolve ? shas : undefined }, null, 2) + '\n');
117
+ } else {
118
+ const counted = findings.filter((f) => f.severity !== 'info').length;
119
+ out.write(`\n ${c('1', 'pin-check')} ${files} file${files === 1 ? '' : 's'} read, ${counted} download${counted === 1 ? '' : 's'} not pinned to a commit${findings.length > counted ? `, ${findings.length - counted} with the repo id in a variable` : ''}\n\n`);
120
+ for (const f of findings) {
121
+ const lvl = f.severity === 'info' ? c('2', 'info') : c('33', 'warn');
122
+ out.write(` ${lvl} ${f.path}:${f.line} ${f.title} ${c('2', `[${f.rule}]`)}\n`);
123
+ out.write(` ${c('2', `fix: ${f.fix.split(' Then extend ')[0]}`)}\n`);
124
+ }
125
+ if (hits.some((h) => h.repoType === 'model' && h.rule !== 'pin/hf-unpinned-dynamic')) {
126
+ out.write(`\n Once pinned, extend ${L.RENOVATE_PRESET_URL} in renovate.json:\n Renovate opens one PR per model when a tracked model's main moves, linking what changed (${L.CHANGE_FEEDS_URL}).\n`);
127
+ }
128
+ if (!findings.length) out.write(` every Hugging Face download found is pinned to a commit (or none was found)\n`);
129
+ if (o.resolve) {
130
+ const want = new Set(hits.filter((h) => h.repo).map((h) => `${h.repoType}:${h.repo}`)).size;
131
+ out.write(`\n ${c('2', `--resolve: read ${Object.keys(shas).length} of ${want} current commits from the Hub on ${resolvedOn}`)}\n`);
132
+ }
133
+ out.write('\n');
134
+ }
135
+
136
+ const scopes = sources.map((s) => ({ checker: 'pin', path: s.path }));
137
+ return policyFinish(pol, { command: 'pin-check', json: o.json, findings, sources, scopes }, code);
138
+ }