neurarch 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE +507 -0
- package/README.md +577 -152
- package/attest.bundle.mjs +343 -0
- package/bin/attest.mjs +188 -0
- package/bin/neurarch.mjs +94 -22
- package/bin/pinCheck.mjs +138 -0
- package/bin/policy.mjs +320 -0
- package/engine.bundle.mjs +3553 -131
- package/examples/.neurarch.yml +44 -0
- package/examples/github-attest.yml +69 -0
- package/examples/github-precheck.yml +40 -0
- package/package.json +5 -2
- package/policy.bundle.mjs +7958 -0
package/bin/neurarch.mjs
CHANGED
|
@@ -22,7 +22,9 @@
|
|
|
22
22
|
*
|
|
23
23
|
* Zero dependencies; the engine is bundled. Set HF_TOKEN for gated repos.
|
|
24
24
|
*/
|
|
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, parseServeCommand, readSampler, renderServeText, SERVE_ENGINES } 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';
|
|
26
28
|
/** The channel tag on every link this program prints. `docs/DISTRIBUTION.md`
|
|
27
29
|
* has asked for one since the first release: without it a visit from a tool
|
|
28
30
|
* and a visit from a search result are the same row, and "which channel brings
|
|
@@ -73,6 +75,16 @@ function gpuFromFlag(arg) {
|
|
|
73
75
|
}
|
|
74
76
|
|
|
75
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));
|
|
76
88
|
|
|
77
89
|
// ── oom: why a job ran out of GPU memory, and the least invasive fix ─────────
|
|
78
90
|
//
|
|
@@ -173,10 +185,11 @@ if (args[0] === 'layout') {
|
|
|
173
185
|
Checks: world size and TP / EP / CP divisibility (block), per-stage balance
|
|
174
186
|
with a rebalanced --layers, the pipeline bubble, per-stage memory on the card,
|
|
175
187
|
and with --seq-hist (CSV of len,count) how much the slowest DP rank waits on
|
|
176
|
-
uneven sequence lengths. Stage time is predicted, not timed: matmul
|
|
177
|
-
40% of the card's peak
|
|
178
|
-
|
|
179
|
-
|
|
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
|
|
180
193
|
logits (Liger, chunked CE). Exits 1 when a check blocks.
|
|
181
194
|
`);
|
|
182
195
|
process.exit(L.help ? 0 : 2);
|
|
@@ -224,7 +237,7 @@ logits (Liger, chunked CE). Exits 1 when a check blocks.
|
|
|
224
237
|
.replace(/ NO$/gm, ` ${red('NO')}`);
|
|
225
238
|
process.stdout.write(text);
|
|
226
239
|
}
|
|
227
|
-
process.exit(blocked ? 1 : 0);
|
|
240
|
+
process.exit(await finish({ command: 'layout', model: pos[0], layout: r.report, layoutSpec: layout, gpu: L.gpu, json: L.json }, blocked ? 1 : 0));
|
|
228
241
|
}
|
|
229
242
|
|
|
230
243
|
// ── serve-check: will this vLLM / SGLang / llama.cpp launch start ────────────
|
|
@@ -239,7 +252,7 @@ if (args[0] === 'serve-check') {
|
|
|
239
252
|
const after = dd >= 0 ? args.slice(dd + 1) : null;
|
|
240
253
|
const S = {};
|
|
241
254
|
const pos = [];
|
|
242
|
-
const VAL = ['engine', 'gpu', 'gpus', 'cmd', 'against', 'sampler'];
|
|
255
|
+
const VAL = ['engine', 'gpu', 'gpus', 'cmd', 'against', 'sampler', 'vllm-version', 'sglang-version', 'receipt', 'gpu-mem', 'gpu-mem-used'];
|
|
243
256
|
for (let i = 0; i < rest.length; i++) {
|
|
244
257
|
const a = rest[i];
|
|
245
258
|
const eq = /^--([a-z-]+)=(.*)$/.exec(a);
|
|
@@ -254,7 +267,9 @@ if (args[0] === 'serve-check') {
|
|
|
254
267
|
process.stdout.write(`neurarch serve-check: will this serving launch start, hold what it promises, and serve the model as published
|
|
255
268
|
|
|
256
269
|
npx neurarch serve-check <hf-id | graph.json> [--engine vllm|sglang|llamacpp] --gpu h100 [--gpus 4]
|
|
257
|
-
[--
|
|
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>
|
|
258
273
|
npx neurarch serve-check <hf-id> --gpu l4 --cmd "vllm serve Qwen/Qwen3-8B -tp 4 --max-model-len 32768"
|
|
259
274
|
|
|
260
275
|
The launch command is the one you would run: vllm serve ..., python -m
|
|
@@ -264,13 +279,35 @@ llama.cpp give the original repo id, since a .gguf file carries no config.json.
|
|
|
264
279
|
|
|
265
280
|
Checks: TP / PP / DP / EP legality against the heads, KV heads, FFN and expert
|
|
266
281
|
widths and the GPU count; the served length against max_position_embeddings and
|
|
267
|
-
rope_scaling;
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
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.
|
|
274
311
|
`);
|
|
275
312
|
process.exit(S.help ? 0 : 2);
|
|
276
313
|
}
|
|
@@ -288,8 +325,12 @@ blocks.
|
|
|
288
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`);
|
|
289
326
|
process.exit(2);
|
|
290
327
|
}
|
|
291
|
-
|
|
292
|
-
|
|
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`);
|
|
293
334
|
process.exit(2);
|
|
294
335
|
}
|
|
295
336
|
const gpus = S.gpus != null ? Number(S.gpus) : undefined;
|
|
@@ -300,20 +341,42 @@ blocks.
|
|
|
300
341
|
for (const part of String(S.sampler).split(',')) { const [k, v] = part.split('='); if (k && v != null) o[k.trim()] = v.trim(); }
|
|
301
342
|
sampler = readSampler(o);
|
|
302
343
|
}
|
|
303
|
-
|
|
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 });
|
|
304
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
|
+
}
|
|
305
367
|
const blocked = r.report.findings.some((f) => f.severity === 'block');
|
|
306
368
|
if (S.json) {
|
|
307
|
-
process.stdout.write(JSON.stringify({ model: ref, command: Array.isArray(cmd) ? cmd.join(' ') : cmd, ignoredFlags: parsed.ignored, ...r.report }, null, 2) + '\n');
|
|
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');
|
|
308
370
|
} else {
|
|
309
371
|
let text = renderServeText(r.report, r.name)
|
|
310
372
|
.replace(/^ {2}block (.*)$/gm, (_, t) => ` ${red('block')} ${bold(t)}`)
|
|
311
373
|
.replace(/^ {2}warn {2}(.*)$/gm, (_, t) => ` ${yellow('warn ')} ${t}`)
|
|
312
374
|
.replace(/^ {2}info {2}(.*)$/gm, (_, t) => ` ${dim('info ')} ${t}`);
|
|
313
375
|
if (parsed.ignored.length) text += ` ${dim(`flags not read by this check: ${parsed.ignored.join(' ')}`)}\n\n`;
|
|
376
|
+
if (receipt) text += renderReceiptText(receipt);
|
|
314
377
|
process.stdout.write(text);
|
|
315
378
|
}
|
|
316
|
-
process.exit(blocked ? 1 : 0);
|
|
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));
|
|
317
380
|
}
|
|
318
381
|
|
|
319
382
|
// ── rightsize: requested vs needed over a team's past jobs ──────────────────
|
|
@@ -404,6 +467,8 @@ if (flags.has('-h') || flags.has('--help') || positional.length === 0) {
|
|
|
404
467
|
why a job ran out of GPU memory, and the least invasive fix
|
|
405
468
|
npx neurarch serve-check <model-id> --gpu l4 --gpus 4 -- vllm serve <model-id> -tp 4 --max-model-len 32768
|
|
406
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
|
|
407
472
|
|
|
408
473
|
npx neurarch <model-id> e.g. Qwen/Qwen3-8B, bert-base-uncased
|
|
409
474
|
npx neurarch <model-id> --json machine-readable
|
|
@@ -573,7 +638,8 @@ if (flags.has('--json')) {
|
|
|
573
638
|
}
|
|
574
639
|
: { ok: false, modelId, reason: result.reason };
|
|
575
640
|
process.stdout.write(JSON.stringify(payload, null, 2) + '\n');
|
|
576
|
-
|
|
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));
|
|
577
643
|
}
|
|
578
644
|
|
|
579
645
|
if (!result.ok && !sizingOnly) {
|
|
@@ -585,6 +651,8 @@ const hub = result.hub;
|
|
|
585
651
|
const facts = result.ok ? result.facts : result.sizing;
|
|
586
652
|
/** Blocking findings; the exit code reads it. Empty when only sizing ran. */
|
|
587
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 };
|
|
588
656
|
|
|
589
657
|
process.stdout.write(`\n${bold(hub.modelId)} ${dim(`${hub.modelType}${hub.pipelineTag ? ` · ${hub.pipelineTag}` : ''}`)}\n\n`);
|
|
590
658
|
|
|
@@ -656,6 +724,7 @@ if (sizingOnly) {
|
|
|
656
724
|
// does not get far enough for its peak to matter.
|
|
657
725
|
if (dataAsked) {
|
|
658
726
|
const fit = dataFitHFModel(facts, dataSpec);
|
|
727
|
+
policyRun.dataFit = fit;
|
|
659
728
|
const blocks = fit.findings.filter((f) => f.severity === 'block');
|
|
660
729
|
process.stdout.write(`\n ${bold('data fit')} ${dim(`checked: ${fit.checked.join(', ') || 'nothing'}`)}\n`);
|
|
661
730
|
if (!fit.findings.length && fit.checked.length) process.stdout.write(` ${green('fits')} ${dim('every stated field is within what the config accepts')}\n`);
|
|
@@ -675,6 +744,7 @@ if (dataAsked) {
|
|
|
675
744
|
// and the lines below say what that leaves out.
|
|
676
745
|
if (inference) {
|
|
677
746
|
const ip = inferHFModel(facts, inferOpts);
|
|
747
|
+
policyRun.inference = ip;
|
|
678
748
|
if (!ip) {
|
|
679
749
|
process.stderr.write(`\n ${red('cannot size')} inference for ${modelId}: no weights read from the config\n`);
|
|
680
750
|
process.exit(1);
|
|
@@ -726,6 +796,7 @@ if (trainingSizing) {
|
|
|
726
796
|
}
|
|
727
797
|
const { plan } = priceHFModel(facts, samples != null ? { samples, source: String(opts.data) } : undefined, runFrom(run), undefined, attention, seqLen);
|
|
728
798
|
const cost = plan.cost;
|
|
799
|
+
policyRun.cost = cost;
|
|
729
800
|
if (samples != null) {
|
|
730
801
|
const hrs = cost.estTrainSec != null ? cost.estTrainSec / 3600 : null;
|
|
731
802
|
const money = cost.estCostUsd == null ? 'n/a'
|
|
@@ -791,6 +862,7 @@ if (spec) {
|
|
|
791
862
|
const run = gpuFromFlag(opts.gpu);
|
|
792
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);
|
|
793
864
|
const ch = plan.change;
|
|
865
|
+
policyRun.change = ch;
|
|
794
866
|
if (ch) {
|
|
795
867
|
const gateOk = ch.gate.ok;
|
|
796
868
|
process.stdout.write(`\n ${bold('change record')} ${dim(`spec ${ch.specId} on ${ch.baseFingerprint}`)}\n`);
|
|
@@ -841,4 +913,4 @@ process.stdout.write('\n');
|
|
|
841
913
|
if (publishedPage) process.stdout.write(` ${dim(`page ${publishedPage}`)}\n`);
|
|
842
914
|
process.stdout.write(` ${dim(`compare https://neurarch.com/compare?a=${encodeURIComponent(modelId)}&b=&utm_source=${SOURCE}`)}\n`);
|
|
843
915
|
process.stdout.write(` ${dim('check POST https://www.neurarch.com/api/v1/check')}\n\n`);
|
|
844
|
-
process.exit(blockers.length ? 1 : 0);
|
|
916
|
+
process.exit(await finish(policyRun, blockers.length ? 1 : 0));
|
package/bin/pinCheck.mjs
ADDED
|
@@ -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
|
+
}
|