neurarch 0.3.0 → 0.4.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 +85 -0
- package/bin/neurarch.mjs +16 -1
- package/bin/scan.mjs +255 -0
- package/bin/templateCheck.mjs +99 -0
- package/bin/weightsDiff.mjs +35 -0
- package/engine.bundle.mjs +5749 -1054
- package/package.json +1 -1
- package/policy.bundle.mjs +446 -12
package/README.md
CHANGED
|
@@ -16,7 +16,9 @@ npx neurarch layout Qwen/Qwen3-8B --tp 4 --pp 4 --dp 8 --global-batch 512 --seq-
|
|
|
16
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
17
|
npx neurarch Qwen/Qwen3-8B --inference --batch 4 --seq-len 4096 --gen 512 # weights + KV cache for a generation job
|
|
18
18
|
npx neurarch policy show # the repo's .neurarch.yml: severities, budget lines, waivers with owner and expiry
|
|
19
|
+
npx neurarch weights-diff ./base ./edited # which tensors differ, and the shape of each edit
|
|
19
20
|
npx neurarch pin-check . # Hugging Face downloads not pinned to a commit (Bandit B615), --sarif for code scanning
|
|
21
|
+
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
|
|
20
22
|
npx neurarch bert-base-uncased --seq-len 1024 --tokenizer-size 30524 # does the data fit what the config accepts
|
|
21
23
|
```
|
|
22
24
|
|
|
@@ -1091,6 +1093,56 @@ verdicts as `neurarch:` properties: `neurarch:training:peak_gb`,
|
|
|
1091
1093
|
`src/utils/attestation/index.ts`. A fragment to merge into the BOM your SBOM
|
|
1092
1094
|
tool already writes; valid against the official 1.6 schema on its own.
|
|
1093
1095
|
|
|
1096
|
+
## weights-diff: what differs between two local checkpoints
|
|
1097
|
+
|
|
1098
|
+
```
|
|
1099
|
+
npx neurarch weights-diff <a> <b> [--json] [--max-tensors N]
|
|
1100
|
+
```
|
|
1101
|
+
|
|
1102
|
+
`<a>` and `<b>` are `.safetensors` files or directories of them. It hashes every tensor and, for each
|
|
1103
|
+
changed 2-D tensor, reads both sides' values to say how many columns and rows moved, how large the
|
|
1104
|
+
change is against the tensor's norm, and how much of it one rank-1 component explains. Everything is
|
|
1105
|
+
read on your machine. Exit code is 0 when the weights match and 1 when they differ, so it can gate a
|
|
1106
|
+
promotion.
|
|
1107
|
+
|
|
1108
|
+
Each checkpoint also gets a digest that survives re-sharding. Post it as `weights_digest` to the
|
|
1109
|
+
self-hosted `POST /v1/outcome` and the ledger can say when one model name ran as two sets of bytes.
|
|
1110
|
+
|
|
1111
|
+
It reports which values differ. It says nothing about what the difference does to behaviour.
|
|
1112
|
+
|
|
1113
|
+
## scan: a dependency scan for the models your code pulls
|
|
1114
|
+
|
|
1115
|
+
```bash
|
|
1116
|
+
npx neurarch scan [paths...] [--json] [--no-template] [--fix] [--cyclonedx out.cdx.json]
|
|
1117
|
+
```
|
|
1118
|
+
|
|
1119
|
+
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:
|
|
1120
|
+
|
|
1121
|
+
- **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.
|
|
1122
|
+
- **behavior**: upstream changes since your pin to the template, tokenizer, EOS or generation defaults. Not vulnerabilities: what the model receives changed.
|
|
1123
|
+
- **hygiene**: downloads not pinned to a commit.
|
|
1124
|
+
|
|
1125
|
+
Output on a four-line sample (2026-11-17, live Hub and the published feed, trimmed):
|
|
1126
|
+
|
|
1127
|
+
```
|
|
1128
|
+
nomic-ai/nomic-embed-text-v1.5 @ 91d2d6bfdddf
|
|
1129
|
+
high security Its auto_map imports code from nomic-ai/nomic-bert-2048. Loaded with trust_remote_code=True,
|
|
1130
|
+
transformers pins that code only with code_revision=; revision= alone pins
|
|
1131
|
+
nomic-ai/nomic-embed-text-v1.5 and still loads the other repository's main.
|
|
1132
|
+
Qwen/Qwen3-8B @ e8bbd8252970
|
|
1133
|
+
high behavior Qwen3-8B: the chat template changed and renders differently (tool-call-parts) ... (2025-05-19).
|
|
1134
|
+
```
|
|
1135
|
+
|
|
1136
|
+
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.
|
|
1137
|
+
|
|
1138
|
+
Where the model id or commit lives elsewhere, it is still read: module constants (`MODEL_ID = "..."` then `from_pretrained(MODEL_ID, revision=REV)`), 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).
|
|
1139
|
+
|
|
1140
|
+
`--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.
|
|
1141
|
+
|
|
1142
|
+
`--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.
|
|
1143
|
+
|
|
1144
|
+
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.
|
|
1145
|
+
|
|
1094
1146
|
## Which Hugging Face downloads are not pinned to a commit
|
|
1095
1147
|
|
|
1096
1148
|
```
|
|
@@ -1183,3 +1235,36 @@ Set `HF_TOKEN` to read a gated repo. The token is sent only to
|
|
|
1183
1235
|
your own
|
|
1184
1236
|
- [`neurarch-lint`](https://www.npmjs.com/package/neurarch-lint): the same
|
|
1185
1237
|
checks against PyTorch source
|
|
1238
|
+
|
|
1239
|
+
## template-check: the prompt vLLM sends, against the reference
|
|
1240
|
+
|
|
1241
|
+
```
|
|
1242
|
+
npx neurarch template-check <hf-id> [--at <rev>] [--tool-parts] [--json]
|
|
1243
|
+
npx neurarch template-check <hf-id> --from <rev> [--to <rev>] [--tool-parts] [--json]
|
|
1244
|
+
```
|
|
1245
|
+
|
|
1246
|
+
A chat template is code shipped in the model repository, and two things change
|
|
1247
|
+
what it produces without anyone touching your deployment: the engine, and an
|
|
1248
|
+
upstream commit. vLLM's default `--chat-template-content-format auto` hands a
|
|
1249
|
+
template that reads content parts its system, user and assistant messages as a
|
|
1250
|
+
list of text parts; transformers' `apply_chat_template` is usually called with
|
|
1251
|
+
strings. `template-check` renders the template both ways on a system+user turn,
|
|
1252
|
+
a multi-turn chat and a tool call, and prints the first place the prompts
|
|
1253
|
+
diverge. Exit 1 on a difference, so it can gate CI.
|
|
1254
|
+
|
|
1255
|
+
How vLLM hands tool results was measured on vLLM 0.33.0 (2026-11-13, through
|
|
1256
|
+
its own `parse_chat_messages`): a string tool result stays a string. Older
|
|
1257
|
+
stacks passed tool results as parts, which is what broke GLM-5.1's tool calls
|
|
1258
|
+
until its 2026-04-16 template fix; `--tool-parts` renders that case:
|
|
1259
|
+
|
|
1260
|
+
```
|
|
1261
|
+
npx neurarch template-check zai-org/GLM-5.1 --at f5ed80ea7943de93bdb66223a637d7c3af6d8fe4 --tool-parts
|
|
1262
|
+
DIFFERENT prompt: reference (string content) vs vllm (parts content)
|
|
1263
|
+
same system+user
|
|
1264
|
+
same multi-turn
|
|
1265
|
+
different tool-call at char 811
|
|
1266
|
+
```
|
|
1267
|
+
|
|
1268
|
+
On vLLM 0.33.0 itself, `google/gemma-4-31B-it` differs on the system turn (one
|
|
1269
|
+
extra space). Rendered with @huggingface/jinja; `same` holds for these
|
|
1270
|
+
conversations, not every input. SGLang and llama.cpp are not modelled.
|
package/bin/neurarch.mjs
CHANGED
|
@@ -22,7 +22,7 @@
|
|
|
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, resolveServeGpu, parseServeCommand, readSampler, renderServeText, SERVE_ENGINES, readReceiptInput, buildReceipt, renderReceiptText, predictionFromReport } from '../engine.bundle.mjs';
|
|
25
|
+
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
26
|
import { setup as policySetup, finish as policyFinish, policyCommand } from './policy.mjs';
|
|
27
27
|
import { setup as attestSetup, finish as attestFinish, finishPolicyApply } from './attest.mjs';
|
|
28
28
|
/** The channel tag on every link this program prints. `docs/DISTRIBUTION.md`
|
|
@@ -84,7 +84,13 @@ att.argv = [...args];
|
|
|
84
84
|
/** Policy first (it may change the exit code), then the record of what the run concluded. */
|
|
85
85
|
const finish = async (run, code) => attestFinish(att, pol, run, await policyFinish(pol, run, code));
|
|
86
86
|
// pin-check: Hugging Face downloads not pinned to a commit (Bandit B615), see ./pinCheck.mjs.
|
|
87
|
+
// weights-diff: what differs between two local checkpoints, from the bytes, see ./weightsDiff.mjs.
|
|
88
|
+
if (args[0] === 'weights-diff') process.exit((await import('./weightsDiff.mjs')).weightsDiffCommand(args.slice(1), weightsDiff, renderWeightsDiffText));
|
|
87
89
|
if (args[0] === 'pin-check') process.exit(await (await import('./pinCheck.mjs')).pinCheckCommand(args.slice(1), pol, policyFinish));
|
|
90
|
+
// scan: a dependency scan for the models a repository pulls, see ./scan.mjs.
|
|
91
|
+
if (args[0] === 'scan') process.exit(await (await import('./scan.mjs')).scanCommand(args.slice(1), { checkRevision }));
|
|
92
|
+
// template-check: the prompt an engine sends against the reference, or across two revisions, see ./templateCheck.mjs.
|
|
93
|
+
if (args[0] === 'template-check') process.exit(await (await import('./templateCheck.mjs')).templateCheckCommand(args.slice(1), { checkParity, checkRevision, renderConformanceText }));
|
|
88
94
|
|
|
89
95
|
// ── oom: why a job ran out of GPU memory, and the least invasive fix ─────────
|
|
90
96
|
//
|
|
@@ -468,7 +474,10 @@ if (flags.has('-h') || flags.has('--help') || positional.length === 0) {
|
|
|
468
474
|
npx neurarch serve-check <model-id> --gpu l4 --gpus 4 -- vllm serve <model-id> -tp 4 --max-model-len 32768
|
|
469
475
|
will this vLLM / SGLang / llama.cpp launch start and hold what it promises (--help)
|
|
470
476
|
npx neurarch policy --help the repo's .neurarch.yml: severities, budget lines, waivers, baseline, --sarif
|
|
477
|
+
npx neurarch weights-diff <a> <b> Which tensors differ between two local checkpoints, and the shape of each edit
|
|
478
|
+
npx neurarch scan [paths] every model your code pulls: unpinned or changed remote code, pickle weights, upstream changes since your pin
|
|
471
479
|
npx neurarch pin-check [paths] Hugging Face downloads not pinned to a commit (Bandit B615), --sarif
|
|
480
|
+
npx neurarch template-check <id> the prompt vLLM or SGLang sends against the reference; --from <rev> for an upstream change
|
|
472
481
|
|
|
473
482
|
npx neurarch <model-id> e.g. Qwen/Qwen3-8B, bert-base-uncased
|
|
474
483
|
npx neurarch <model-id> --json machine-readable
|
|
@@ -485,6 +494,7 @@ if (flags.has('-h') || flags.has('--help') || positional.length === 0) {
|
|
|
485
494
|
tokens, and which cards hold it (default batch ${DEFAULT_INFERENCE_BATCH}, ${DEFAULT_GEN_TOKENS} generated, bf16)
|
|
486
495
|
npx neurarch <model-id> --lora r=16,targets=q_proj,v_proj --quant int8 --fit a100-40g
|
|
487
496
|
the change record: what may move on this base, and whether the gate approves it
|
|
497
|
+
(memory sized at batch 32 and ${DEFAULT_SEQ_LEN} tokens unless --batch / --seq-len say otherwise)
|
|
488
498
|
npx neurarch <model-id> --lora-targets every Linear a LoRA can target, and PEFT target_modules
|
|
489
499
|
for the attention and all-linear presets with r=8 / r=16 totals
|
|
490
500
|
npx neurarch <model-id> --seq-len 1024 --tokenizer-size 30524 --classes 5 [--image-size 384 --channels 1]
|
|
@@ -874,6 +884,11 @@ if (spec) {
|
|
|
874
884
|
process.stdout.write(` ${dim('allowed to move')} ${desc.join(' · ')}\n`);
|
|
875
885
|
const e = ch.estimates;
|
|
876
886
|
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`);
|
|
887
|
+
// The peak is only true at a workload: say which, and that it was assumed when the caller gave none.
|
|
888
|
+
if (e.trainMemGb != null) {
|
|
889
|
+
const assumed = [batchSize == null ? '--batch' : null, seqLen == null && e.seqLen != null ? '--seq-len' : null].filter(Boolean);
|
|
890
|
+
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`);
|
|
891
|
+
}
|
|
877
892
|
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
893
|
if (e.servingFits != null) process.stdout.write(` ${dim('serving ')} ${e.servingFits ? green('fits') : red('does not fit')}\n`);
|
|
879
894
|
process.stdout.write(` ${dim('gate ')} ${gateOk ? green('approved') : red(`refused (${ch.gate.blockers.length} blocker${ch.gate.blockers.length === 1 ? '' : 's'})`)}\n`);
|
package/bin/scan.mjs
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `neurarch scan [paths...]`: a dependency scan for the models a repository
|
|
3
|
+
* pulls. Finds every Hugging Face download with a literal repo id (pinned or
|
|
4
|
+
* not; the same reader as pin-check), then for each model reads the Hub API at
|
|
5
|
+
* the pinned commit and at main, the recorded history at
|
|
6
|
+
* neurarch.com/changes/index.json, and (pinned, moved) renders the chat
|
|
7
|
+
* template at both commits. Grading is src/utils/policy/modelScan.ts.
|
|
8
|
+
*
|
|
9
|
+
* Network: huggingface.co and www.neurarch.com only. Nothing from the scanned
|
|
10
|
+
* repository is sent anywhere; only public model ids are requested.
|
|
11
|
+
*/
|
|
12
|
+
import { readFileSync, writeFileSync } from 'node:fs';
|
|
13
|
+
import { randomUUID } from 'node:crypto';
|
|
14
|
+
import { relative, resolve, sep, join } from 'node:path';
|
|
15
|
+
import { readdirSync, statSync } from 'node:fs';
|
|
16
|
+
|
|
17
|
+
const tty = process.stdout.isTTY && !process.env.NO_COLOR;
|
|
18
|
+
const c = (code, s) => (tty ? `\x1b[${code}m${s}\x1b[0m` : String(s));
|
|
19
|
+
const posix = (p) => p.split(sep).join('/');
|
|
20
|
+
const SKIP_DIRS = new Set(['.git', '.hg', '.svn', 'node_modules', '.venv', 'venv', 'env', '__pycache__', '.tox', '.nox', 'site-packages', '.ipynb_checkpoints']);
|
|
21
|
+
const FEED = process.env.NEURARCH_CHANGES_URL || 'https://www.neurarch.com/changes/index.json';
|
|
22
|
+
const TRACKED = process.env.NEURARCH_TRACKED_URL || 'https://www.neurarch.com/changes-feeds/advisories/index.json';
|
|
23
|
+
|
|
24
|
+
const HELP = `neurarch scan: a dependency scan for the models your code pulls
|
|
25
|
+
|
|
26
|
+
npx neurarch scan [paths...] [--json] [--no-template] [--fix] [--cyclonedx out.cdx.json]
|
|
27
|
+
|
|
28
|
+
Finds every Hugging Face model your .py, .ipynb, YAML, shell scripts and
|
|
29
|
+
Dockerfiles download (from_pretrained, vllm serve, hf download, base_model:,
|
|
30
|
+
...), pinned or not. For each one it reports, in three lanes:
|
|
31
|
+
|
|
32
|
+
security Python the loader runs from the repo (auto_map) that is unpinned,
|
|
33
|
+
changed since your pin, or lives in another repository that
|
|
34
|
+
revision= does not pin; weights only in pickle formats.
|
|
35
|
+
behavior recorded upstream changes since your pin (template, tokenizer,
|
|
36
|
+
EOS, generation defaults) from neurarch.com/changes, and whether
|
|
37
|
+
the chat template now renders a different prompt.
|
|
38
|
+
hygiene downloads not pinned to a commit.
|
|
39
|
+
|
|
40
|
+
It also reads repo ids and commits held in module constants (MODEL_ID = ...),
|
|
41
|
+
metadata records (MTEB's ModelMeta(name=..., revision=...)) and serving env
|
|
42
|
+
vars in manifests, compose files and Dockerfiles (MODEL_ID, REVISION).
|
|
43
|
+
|
|
44
|
+
--fix hold the code you run today: add code_revision= (pinned to the
|
|
45
|
+
code repository's current commit) where a model imports code from
|
|
46
|
+
another repository, and revision= where a remote-code load is not
|
|
47
|
+
pinned. Edits .py files and shell launch lines in place; review with
|
|
48
|
+
git diff. Calls it cannot edit safely are listed, not guessed.
|
|
49
|
+
--cyclonedx F (alias --bom) write a CycloneDX 1.6 BOM: one component per model (purl at the
|
|
50
|
+
commit), cross-repository code as a dependency, each finding as a
|
|
51
|
+
vulnerability entry mapped to NIST SP 800-218A / AI 600-1.
|
|
52
|
+
|
|
53
|
+
Exit 1 when any finding is high. Reads huggingface.co and www.neurarch.com;
|
|
54
|
+
set HF_TOKEN for gated repos. Only public model ids leave your machine.
|
|
55
|
+
`;
|
|
56
|
+
|
|
57
|
+
function* walk(abs, kindOf) {
|
|
58
|
+
let st;
|
|
59
|
+
try { st = statSync(abs); } catch { return; }
|
|
60
|
+
if (st.isFile()) { if (kindOf(abs) && st.size <= 5 * 1024 * 1024) yield abs; return; }
|
|
61
|
+
if (!st.isDirectory()) return;
|
|
62
|
+
let entries;
|
|
63
|
+
try { entries = readdirSync(abs, { withFileTypes: true }); } catch { return; }
|
|
64
|
+
for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
65
|
+
if (e.isDirectory() && SKIP_DIRS.has(e.name)) continue;
|
|
66
|
+
if (e.isSymbolicLink()) continue;
|
|
67
|
+
yield* walk(join(abs, e.name), kindOf);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const headers = () => (process.env.HF_TOKEN ? { Authorization: `Bearer ${process.env.HF_TOKEN}` } : {});
|
|
72
|
+
async function getJson(url, h = {}) {
|
|
73
|
+
try {
|
|
74
|
+
const r = await fetch(url, { headers: h, signal: AbortSignal.timeout(20_000) });
|
|
75
|
+
return r.ok ? await r.json() : null;
|
|
76
|
+
} catch { return null; }
|
|
77
|
+
}
|
|
78
|
+
const hubInfo = (id, rev) => getJson(`https://huggingface.co/api/models/${id}/revision/${encodeURIComponent(rev)}?blobs=true`, headers());
|
|
79
|
+
|
|
80
|
+
async function rawConfig(id, rev) {
|
|
81
|
+
try {
|
|
82
|
+
const r = await fetch(`https://huggingface.co/${id}/resolve/${encodeURIComponent(rev)}/config.json`, { headers: headers(), signal: AbortSignal.timeout(20_000) });
|
|
83
|
+
return r.ok ? await r.json() : null;
|
|
84
|
+
} catch { return null; }
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async function templateAt(id, rev) {
|
|
88
|
+
const get = async (f) => {
|
|
89
|
+
try {
|
|
90
|
+
const r = await fetch(`https://huggingface.co/${id}/resolve/${encodeURIComponent(rev)}/${f}`, { headers: headers(), signal: AbortSignal.timeout(20_000) });
|
|
91
|
+
return r.ok ? r.text() : null;
|
|
92
|
+
} catch { return null; }
|
|
93
|
+
};
|
|
94
|
+
const [jinja, tokRaw] = await Promise.all([get('chat_template.jinja'), get('tokenizer_config.json')]);
|
|
95
|
+
let tok = null;
|
|
96
|
+
try { tok = tokRaw ? JSON.parse(tokRaw) : null; } catch { tok = null; }
|
|
97
|
+
const t = tok?.chat_template;
|
|
98
|
+
const text = jinja ?? (typeof t === 'string' ? t : Array.isArray(t) ? (t.find((x) => x?.name === 'default') ?? t[0])?.template : null);
|
|
99
|
+
const tx = (v) => (v && typeof v === 'object' ? v.content : typeof v === 'string' ? v : null);
|
|
100
|
+
return text ? { text, specials: { bos_token: tx(tok?.bos_token), eos_token: tx(tok?.eos_token) } } : null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const SEV = { high: '31', medium: '33', low: '2' };
|
|
104
|
+
|
|
105
|
+
export async function scanCommand(args, engine) {
|
|
106
|
+
const L = await import('../policy.bundle.mjs');
|
|
107
|
+
const o = { paths: [], template: true };
|
|
108
|
+
const skip = new Set();
|
|
109
|
+
for (const [i, a] of args.entries()) {
|
|
110
|
+
if (skip.has(i)) continue;
|
|
111
|
+
if (a === '-h' || a === '--help') { process.stdout.write(HELP); return 0; }
|
|
112
|
+
if (a === '--json') o.json = true;
|
|
113
|
+
else if (a === '--no-template') o.template = false;
|
|
114
|
+
else if (a === '--fix') o.fix = true;
|
|
115
|
+
else if (a === '--cyclonedx' || a === '--bom') { o.bom = args[args.indexOf(a) + 1]; if (!o.bom || o.bom.startsWith('-')) { process.stderr.write(`neurarch scan: ${a} needs a file path\n`); return 2; } skip.add(args.indexOf(a) + 1); }
|
|
116
|
+
else if (a.startsWith('-')) { process.stderr.write(`neurarch scan: unknown flag ${a} (--help)\n`); return 2; }
|
|
117
|
+
else o.paths.push(a);
|
|
118
|
+
}
|
|
119
|
+
if (!o.paths.length) o.paths.push('.');
|
|
120
|
+
const root = process.cwd();
|
|
121
|
+
const refs = [];
|
|
122
|
+
let files = 0;
|
|
123
|
+
for (const p of o.paths) {
|
|
124
|
+
const abs = resolve(p);
|
|
125
|
+
try { statSync(abs); } catch { process.stderr.write(`neurarch scan: ${p}: no such file or directory\n`); return 2; }
|
|
126
|
+
for (const f of walk(abs, (x) => L.pinFileKind(posix(x)))) {
|
|
127
|
+
let text;
|
|
128
|
+
try { text = readFileSync(f, 'utf8'); } catch { continue; }
|
|
129
|
+
files++;
|
|
130
|
+
const rel = posix(relative(root, f)) || posix(f);
|
|
131
|
+
for (const h of L.scanModelRefs(rel, text)) if (h.repoType === 'model') refs.push(h);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// One assessment per (model, pin); call sites listed under it.
|
|
136
|
+
const groups = new Map();
|
|
137
|
+
const codeHeads = new Map();
|
|
138
|
+
for (const h of refs) {
|
|
139
|
+
const pin = h.pinned ? h.revision : undefined;
|
|
140
|
+
const k = `${h.repo}@${pin ?? ''}`;
|
|
141
|
+
if (!groups.has(k)) groups.set(k, { id: h.repo, pinned: pin, sites: [], hits: [], codeRevision: true });
|
|
142
|
+
const g = groups.get(k);
|
|
143
|
+
g.sites.push(`${h.path}:${h.line}`);
|
|
144
|
+
g.hits.push(h);
|
|
145
|
+
if (!h.codeRevision) g.codeRevision = false;
|
|
146
|
+
if (h.via !== 'env' || h.trustRemoteCode) g.remoteCodeRuns = undefined;
|
|
147
|
+
else if (g.hits.length === 1) g.remoteCodeRuns = false;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const [feed, advisories] = await Promise.all([getJson(FEED), getJson(TRACKED)]);
|
|
151
|
+
const recorded = feed?.changes ?? null;
|
|
152
|
+
const securityRecorded = (feed?.lanes ?? []).filter((l) => l.lane === 'security');
|
|
153
|
+
const tracked = new Set((advisories?.advisories ?? []).map((a) => a.model));
|
|
154
|
+
for (const ch of recorded ?? []) tracked.add(ch.id);
|
|
155
|
+
|
|
156
|
+
const results = [];
|
|
157
|
+
for (const g of groups.values()) {
|
|
158
|
+
const [atMain, atPin] = await Promise.all([hubInfo(g.id, 'main'), g.pinned ? hubInfo(g.id, g.pinned) : null]);
|
|
159
|
+
let templateVerdict = null;
|
|
160
|
+
const moved = g.pinned && atMain?.sha && !atMain.sha.startsWith(g.pinned);
|
|
161
|
+
if (o.template && moved && engine?.checkRevision) {
|
|
162
|
+
const [a, b] = await Promise.all([templateAt(g.id, g.pinned), templateAt(g.id, atMain.sha)]);
|
|
163
|
+
if (a && b) {
|
|
164
|
+
try { templateVerdict = engine.checkRevision(a.text, b.text, 'vllm', a.specials, b.specials).verdict; } catch { templateVerdict = null; }
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
const [rawConfigMain, rawConfigPin] = await Promise.all([atMain?.sha ? rawConfig(g.id, atMain.sha) : null, g.pinned ? rawConfig(g.id, g.pinned) : null]);
|
|
168
|
+
const code = g.remoteCodeRuns === false ? { declared: false, crossRepo: [] } : L.remoteCodeOf(atMain ?? atPin, g.id);
|
|
169
|
+
const codeRepos = [];
|
|
170
|
+
for (const repo of code.crossRepo) {
|
|
171
|
+
if (!codeHeads.has(repo)) codeHeads.set(repo, hubInfo(repo, 'main').then((x) => x?.sha ?? null));
|
|
172
|
+
codeRepos.push({ id: repo, sha: await codeHeads.get(repo), held: g.codeRevision });
|
|
173
|
+
}
|
|
174
|
+
const findings = atMain || atPin
|
|
175
|
+
? L.assessRef({ id: g.id, pinned: g.pinned, codeRevision: g.codeRevision, atMain, atPin, recorded, tracked: tracked.has(g.id), templateVerdict, rawConfigMain, rawConfigPin, remoteCodeRuns: g.remoteCodeRuns, securityRecorded: g.remoteCodeRuns === false ? [] : securityRecorded })
|
|
176
|
+
: [{ lane: 'hygiene', severity: 'low', kind: 'unreadable', message: 'The Hub did not answer for this id (private, gated without HF_TOKEN, renamed or deleted). A deleted author name can be re-registered by someone else; check who owns it now.' }];
|
|
177
|
+
results.push({ ...g, mainSha: atMain?.sha ?? null, tracked: tracked.has(g.id), remoteCode: code.declared, codeRepos, findings });
|
|
178
|
+
}
|
|
179
|
+
const fixes = o.fix ? applyFixes(results, root, L) : null;
|
|
180
|
+
if (o.bom) {
|
|
181
|
+
let version = '0';
|
|
182
|
+
try { version = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version; } catch { /* keep 0 */ }
|
|
183
|
+
const bom = L.scanBom(results.map((r) => ({ id: r.id, pinned: r.pinned, mainSha: r.mainSha, sites: r.sites, codeRepos: r.codeRepos, findings: r.findings })), { tool: 'neurarch', version, timestamp: new Date().toISOString(), serial: `urn:uuid:${randomUUID()}` });
|
|
184
|
+
writeFileSync(o.bom, JSON.stringify(bom, null, 2) + '\n');
|
|
185
|
+
}
|
|
186
|
+
const code = L.scanExitCode(results.map((r) => r.findings));
|
|
187
|
+
|
|
188
|
+
if (o.json) {
|
|
189
|
+
process.stdout.write(JSON.stringify({ files, feed: recorded ? FEED : null, models: results.map(({ hits, ...r }) => r), ...(fixes ? { fixes } : {}), ...(o.bom ? { bom: o.bom } : {}) }, null, 2) + '\n');
|
|
190
|
+
return code;
|
|
191
|
+
}
|
|
192
|
+
const out = process.stdout;
|
|
193
|
+
const count = (sev) => results.reduce((n, r) => n + r.findings.filter((f) => f.severity === sev && f.kind !== 'pin-current').length, 0);
|
|
194
|
+
out.write(`\n ${c('1', 'neurarch scan')} ${files} file${files === 1 ? '' : 's'} read, ${results.length} model reference${results.length === 1 ? '' : 's'}, ${c(SEV.high, `${count('high')} high`)}, ${c(SEV.medium, `${count('medium')} medium`)}\n`);
|
|
195
|
+
if (!recorded) out.write(` ${c('33', 'recorded history unavailable')} (${FEED}); upstream changes since your pin are not listed\n`);
|
|
196
|
+
for (const r of results) {
|
|
197
|
+
out.write(`\n ${c('1', r.id)}${r.pinned ? ` @ ${r.pinned.slice(0, 12)}` : c('33', ' (not pinned)')}${r.tracked ? '' : c('2', ' no recorded upstream changes at neurarch.com/changes')}\n`);
|
|
198
|
+
out.write(` ${c('2', r.sites.slice(0, 4).join(', ') + (r.sites.length > 4 ? ` +${r.sites.length - 4}` : ''))}\n`);
|
|
199
|
+
for (const f of r.findings) {
|
|
200
|
+
out.write(` ${c(SEV[f.severity], f.severity.padEnd(6))} ${f.lane.padEnd(8)} ${f.message}\n`);
|
|
201
|
+
if (f.fix) out.write(` ${' '.repeat(16)}${c('2', 'fix: ' + f.fix)}\n`);
|
|
202
|
+
if (f.url) out.write(` ${' '.repeat(16)}${c('2', f.url)}\n`);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
if (fixes) {
|
|
206
|
+
out.write(`\n ${c('1', '--fix')} ${fixes.edited.length} call site${fixes.edited.length === 1 ? '' : 's'} edited in ${new Set(fixes.edited.map((e) => e.path)).size} file(s)${fixes.skipped.length ? `, ${fixes.skipped.length} left for you` : ''}\n`);
|
|
207
|
+
for (const e of fixes.edited) out.write(` ${c('32', 'edited')} ${e.path}:${e.line} ${e.what}\n`);
|
|
208
|
+
for (const e of fixes.skipped) out.write(` ${c('33', 'skipped')} ${e.path}:${e.line} ${e.why}\n`);
|
|
209
|
+
if (fixes.edited.length) out.write(` ${c('2', 'Review with git diff. The commits are what each repository has on main today, so nothing you run changes now; it just stops changing underneath you.')}\n`);
|
|
210
|
+
}
|
|
211
|
+
if (o.bom) out.write(`\n ${c('1', '--cyclonedx')} wrote ${o.bom} (CycloneDX 1.6, ${results.length} model${results.length === 1 ? '' : 's'})\n`);
|
|
212
|
+
out.write(`\n ${c('2', 'security = code that runs on load or weights that can execute; behavior = what the model receives changed, not a vulnerability.')}\n\n`);
|
|
213
|
+
return code;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* --fix: for each model that runs remote code, add what holds it to the
|
|
218
|
+
* commits upstream has today. Python call sites and shell launch lines only;
|
|
219
|
+
* records (ModelMeta) and env vars are listed for a person, because which
|
|
220
|
+
* call consumes them is not in the file.
|
|
221
|
+
*/
|
|
222
|
+
function applyFixes(results, root, L) {
|
|
223
|
+
const edited = [];
|
|
224
|
+
const skipped = [];
|
|
225
|
+
const byFile = new Map();
|
|
226
|
+
for (const r of results) {
|
|
227
|
+
if (!r.remoteCode) continue;
|
|
228
|
+
const crossHeld = r.codeRepos.length ? r.codeRepos[0] : null;
|
|
229
|
+
const set = {};
|
|
230
|
+
if (!r.pinned && r.mainSha) set.revision = r.mainSha;
|
|
231
|
+
if (crossHeld && !r.codeRevision && crossHeld.sha) set.codeRevision = crossHeld.sha;
|
|
232
|
+
if (r.codeRepos.length > 1) { for (const h of r.hits) skipped.push({ path: h.path, line: h.line, why: `imports code from ${r.codeRepos.length} repositories; code_revision takes one` }); continue; }
|
|
233
|
+
if (!set.revision && !set.codeRevision) continue;
|
|
234
|
+
for (const h of r.hits) {
|
|
235
|
+
if (h.via === 'record' || h.via === 'env') { skipped.push({ path: h.path, line: h.line, why: `${h.via === 'env' ? 'an env var' : 'a metadata record'}: pass ${set.codeRevision ? `code_revision="${set.codeRevision}"` : `revision="${set.revision}"`} where it is loaded` }); continue; }
|
|
236
|
+
if (!byFile.has(h.path)) byFile.set(h.path, []);
|
|
237
|
+
byFile.get(h.path).push({ h, set });
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
for (const [path, items] of byFile) {
|
|
241
|
+
const abs = resolve(root, path);
|
|
242
|
+
if (/\.ipynb$/i.test(path)) { for (const { h } of items) skipped.push({ path, line: h.line, why: 'a notebook; edit the cell by hand' }); continue; }
|
|
243
|
+
let src;
|
|
244
|
+
try { src = readFileSync(abs, 'utf8'); } catch { continue; }
|
|
245
|
+
// bottom-up so earlier line numbers stay valid
|
|
246
|
+
for (const { h, set } of items.sort((a, b) => b.h.line - a.h.line)) {
|
|
247
|
+
const r = h.syntax === 'python' ? L.fixPythonCall(src, h.line, h.api, set) : h.syntax === 'shell' ? L.fixShellLine(src, h.line, set) : { skipped: 'YAML: add the revision keys by hand' };
|
|
248
|
+
if ('src' in r) { src = r.src; edited.push({ path, line: h.line, what: [set.revision && 'revision=', set.codeRevision && 'code_revision='].filter(Boolean).join(' and ') }); }
|
|
249
|
+
else if (r.skipped !== 'already holds both') skipped.push({ path, line: h.line, why: r.skipped });
|
|
250
|
+
}
|
|
251
|
+
writeFileSync(abs, src);
|
|
252
|
+
}
|
|
253
|
+
edited.sort((a, b) => a.path.localeCompare(b.path) || a.line - b.line);
|
|
254
|
+
return { edited, skipped };
|
|
255
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `neurarch template-check <hf-id>`: does the prompt an engine sends match the
|
|
3
|
+
* lab's reference, and did an upstream template change move it?
|
|
4
|
+
*
|
|
5
|
+
* Reads chat_template.jinja (or tokenizer_config.json's chat_template) at the
|
|
6
|
+
* given revisions from the Hugging Face Hub, then renders a fixed conversation
|
|
7
|
+
* set with src/utils/templateConformance.ts (through engine.bundle.mjs). No
|
|
8
|
+
* weights, no GPU. Exit 1 when a prompt differs, so it can gate CI.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const tty = process.stdout.isTTY && !process.env.NO_COLOR;
|
|
12
|
+
const c = (code, s) => (tty ? `\x1b[${code}m${s}\x1b[0m` : String(s));
|
|
13
|
+
|
|
14
|
+
const HELP = `neurarch template-check: the prompt an engine sends, against the reference
|
|
15
|
+
|
|
16
|
+
npx neurarch template-check <hf-id> [--at <rev>] [--tool-parts] [--json]
|
|
17
|
+
npx neurarch template-check <hf-id> --from <rev> [--to <rev>] [--tool-parts] [--json]
|
|
18
|
+
|
|
19
|
+
With one revision (--at, default main): renders the model's chat template the
|
|
20
|
+
way transformers' apply_chat_template is usually called (content as a string)
|
|
21
|
+
and the way vLLM calls it with --chat-template-content-format auto (system,
|
|
22
|
+
user and assistant content as text parts when the template reads parts; tool
|
|
23
|
+
results as strings, as measured on vLLM 0.33.0), on a system+user turn, a
|
|
24
|
+
multi-turn chat and a tool call. A difference is a prompt vLLM sends that the
|
|
25
|
+
reference does not. --tool-parts also hands tool results as parts, as older
|
|
26
|
+
stacks did and as a client that sends parts gets.
|
|
27
|
+
|
|
28
|
+
With --from: renders the template at both revisions in the engine's form. A
|
|
29
|
+
difference is an upstream change that moves what a deployment sends.
|
|
30
|
+
|
|
31
|
+
Set HF_TOKEN for gated repos. Exits 1 when any prompt differs, 2 on a read error.
|
|
32
|
+
`;
|
|
33
|
+
|
|
34
|
+
function templateFrom(tok) {
|
|
35
|
+
const t = tok?.chat_template;
|
|
36
|
+
if (typeof t === 'string') return t;
|
|
37
|
+
if (Array.isArray(t)) {
|
|
38
|
+
const d = t.find((x) => x && x.name === 'default') ?? t[0];
|
|
39
|
+
return typeof d?.template === 'string' ? d.template : null;
|
|
40
|
+
}
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
const tokenText = (v) => (v && typeof v === 'object' && typeof v.content === 'string' ? v.content : typeof v === 'string' ? v : null);
|
|
44
|
+
|
|
45
|
+
async function readAt(id, rev) {
|
|
46
|
+
const headers = process.env.HF_TOKEN ? { Authorization: `Bearer ${process.env.HF_TOKEN}` } : {};
|
|
47
|
+
const get = async (file) => {
|
|
48
|
+
const r = await fetch(`https://huggingface.co/${id}/resolve/${encodeURIComponent(rev)}/${file}`, { headers, signal: AbortSignal.timeout(20_000) });
|
|
49
|
+
if (r.status === 404) return null;
|
|
50
|
+
if (!r.ok) throw new Error(`${file} at ${rev}: HTTP ${r.status}${r.status === 401 || r.status === 403 ? ' (gated: set HF_TOKEN)' : ''}`);
|
|
51
|
+
return r.text();
|
|
52
|
+
};
|
|
53
|
+
const [jinja, tokRaw] = await Promise.all([get('chat_template.jinja'), get('tokenizer_config.json')]);
|
|
54
|
+
let tok = null;
|
|
55
|
+
try { tok = tokRaw ? JSON.parse(tokRaw) : null; } catch { tok = null; }
|
|
56
|
+
const text = jinja ?? templateFrom(tok);
|
|
57
|
+
if (text == null) throw new Error(`no chat template at ${rev} (neither chat_template.jinja nor tokenizer_config.json carries one)`);
|
|
58
|
+
return { text, specials: { bos_token: tokenText(tok?.bos_token), eos_token: tokenText(tok?.eos_token) } };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export async function templateCheckCommand(argv, lib) {
|
|
62
|
+
const o = { engine: 'vllm', json: false };
|
|
63
|
+
const pos = [];
|
|
64
|
+
for (let i = 0; i < argv.length; i++) {
|
|
65
|
+
const a = argv[i];
|
|
66
|
+
if (a === '-h' || a === '--help') { process.stdout.write(HELP); return 0; }
|
|
67
|
+
if (a === '--json') { o.json = true; continue; }
|
|
68
|
+
if (a === '--tool-parts') { o.toolParts = true; continue; }
|
|
69
|
+
if (['--engine', '--at', '--from', '--to'].includes(a)) { o[a.slice(2)] = argv[++i]; continue; }
|
|
70
|
+
if (a.startsWith('--')) { process.stderr.write(`unknown flag ${a}\n${HELP}`); return 2; }
|
|
71
|
+
pos.push(a);
|
|
72
|
+
}
|
|
73
|
+
const id = pos[0];
|
|
74
|
+
if (!id) { process.stderr.write(HELP); return 2; }
|
|
75
|
+
if (!['vllm', 'sglang'].includes(o.engine)) { process.stderr.write(`--engine must be vllm or sglang\n`); return 2; }
|
|
76
|
+
try {
|
|
77
|
+
let result, labels;
|
|
78
|
+
if (o.from) {
|
|
79
|
+
const to = o.to ?? 'main';
|
|
80
|
+
const [a, b] = await Promise.all([readAt(id, o.from), readAt(id, to)]);
|
|
81
|
+
result = lib.checkRevision(a.text, b.text, o.engine, a.specials, b.specials, { toolParts: !!o.toolParts });
|
|
82
|
+
labels = { left: o.from.slice(0, 12), right: to.slice(0, 12) };
|
|
83
|
+
} else {
|
|
84
|
+
const at = o.at ?? 'main';
|
|
85
|
+
const s = await readAt(id, at);
|
|
86
|
+
result = lib.checkParity(s.text, o.engine, s.specials, { toolParts: !!o.toolParts });
|
|
87
|
+
labels = { left: 'reference', right: o.engine };
|
|
88
|
+
}
|
|
89
|
+
if (o.json) process.stdout.write(JSON.stringify({ model: id, ...result }, null, 2) + '\n');
|
|
90
|
+
else {
|
|
91
|
+
const text = lib.renderConformanceText(result, labels);
|
|
92
|
+
process.stdout.write((result.verdict === 'different' ? c('31', text.split('\n')[0]) + '\n' + text.split('\n').slice(1).join('\n') : text) + '\n');
|
|
93
|
+
}
|
|
94
|
+
return result.verdict === 'different' ? 1 : 0;
|
|
95
|
+
} catch (e) {
|
|
96
|
+
process.stderr.write(`${c('31', 'cannot read the template')}: ${e.message}\n`);
|
|
97
|
+
return 2;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `neurarch weights-diff <a> <b>`: which tensors differ between two local
|
|
3
|
+
* safetensors checkpoints, and the shape of each edit. The reading is
|
|
4
|
+
* scripts/weightsDiff.ts through the engine bundle; this file only parses
|
|
5
|
+
* arguments and prints. Nothing leaves the machine.
|
|
6
|
+
*/
|
|
7
|
+
const USAGE = `usage: npx neurarch weights-diff <a> <b> [--json] [--max-tensors N]
|
|
8
|
+
|
|
9
|
+
<a>, <b> a .safetensors file, or a directory of them
|
|
10
|
+
--max-tensors N read the shape of at most N changed tensors (default 32); the rest are counted
|
|
11
|
+
--json the full result
|
|
12
|
+
|
|
13
|
+
Exit code 0 when the weights match, 1 when they differ, 2 on a usage or read error.
|
|
14
|
+
`;
|
|
15
|
+
|
|
16
|
+
export function weightsDiffCommand(args, weightsDiff, render) {
|
|
17
|
+
const pos = [];
|
|
18
|
+
const opts = {};
|
|
19
|
+
let json = false;
|
|
20
|
+
for (let i = 0; i < args.length; i++) {
|
|
21
|
+
const a = args[i];
|
|
22
|
+
if (a === '--json') json = true;
|
|
23
|
+
else if (a === '--max-tensors') opts.maxTensors = Number(args[++i]);
|
|
24
|
+
else if (a === '-h' || a === '--help') { process.stdout.write(USAGE); return 0; }
|
|
25
|
+
else pos.push(a);
|
|
26
|
+
}
|
|
27
|
+
if (pos.length !== 2 || (opts.maxTensors != null && !(opts.maxTensors >= 0))) { process.stderr.write(USAGE); return 2; }
|
|
28
|
+
let r;
|
|
29
|
+
try { r = weightsDiff(pos[0], pos[1], opts); } catch (e) {
|
|
30
|
+
process.stderr.write(`neurarch weights-diff: ${e instanceof Error ? e.message : e}\n`);
|
|
31
|
+
return 2;
|
|
32
|
+
}
|
|
33
|
+
process.stdout.write(json ? `${JSON.stringify(r, null, 2)}\n` : render(r));
|
|
34
|
+
return r.a.digest === r.b.digest ? 0 : 1;
|
|
35
|
+
}
|