neurarch 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +181 -9
- package/bin/gate.mjs +259 -0
- package/bin/neurarch.mjs +31 -6
- package/bin/scan.mjs +444 -0
- package/bin/templateCheck.mjs +102 -0
- package/bin/weightsDiff.mjs +35 -0
- package/engine.bundle.mjs +5777 -1061
- package/package.json +11 -3
- package/policy.bundle.mjs +1405 -54
package/bin/scan.mjs
ADDED
|
@@ -0,0 +1,444 @@
|
|
|
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, openSync, readSync, closeSync } from 'node:fs';
|
|
13
|
+
import { randomUUID } from 'node:crypto';
|
|
14
|
+
import { relative, resolve, sep, join, dirname } 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
|
+
/** The engine's release notes as rows. A path instead of a URL reads a local copy (tests, a network with no way out). */
|
|
24
|
+
const ENGINE_RECORD = process.env.NEURARCH_ENGINE_URL || 'https://www.neurarch.com/engine-changes/vllm.json';
|
|
25
|
+
|
|
26
|
+
const HELP = `neurarch scan: a dependency scan for the models your code pulls
|
|
27
|
+
|
|
28
|
+
npx neurarch scan [paths...] [--json] [--no-template] [--no-adapter] [--no-engine] [--fix] [--cyclonedx out.cdx.json]
|
|
29
|
+
|
|
30
|
+
Finds every Hugging Face model your .py, .ipynb, YAML, shell scripts and
|
|
31
|
+
Dockerfiles download (from_pretrained, vllm serve, hf download, base_model:,
|
|
32
|
+
...), pinned or not. For each one it reports, in three lanes:
|
|
33
|
+
|
|
34
|
+
security Python the loader runs from the repo (auto_map) that is unpinned,
|
|
35
|
+
changed since your pin, or lives in another repository that
|
|
36
|
+
revision= does not pin; weights only in pickle formats.
|
|
37
|
+
behavior what differs between your pin and main, by file hash: weights,
|
|
38
|
+
tokenizer, config (or that only the README moved, so the pin is
|
|
39
|
+
safe to move); recorded upstream changes since your pin from
|
|
40
|
+
neurarch.com/changes; and whether the chat template now renders a
|
|
41
|
+
different prompt.
|
|
42
|
+
hygiene downloads not pinned to a commit.
|
|
43
|
+
|
|
44
|
+
LoRA adapters are read where they are named: PeftModel.from_pretrained, vLLM
|
|
45
|
+
--lora-modules, SGLang --lora-paths, and an exported adapter_config.json. For
|
|
46
|
+
each one the scan reads the tensor names in the adapter's and the base's
|
|
47
|
+
safetensors headers (no weights are downloaded) and reports an adapter whose
|
|
48
|
+
modules do not exist in the base, or that sits a level off (the layout vLLM
|
|
49
|
+
0.32.0 and earlier loaded without an error and never applied). The engine
|
|
50
|
+
version is read from the same file when it is there (an image tag, a pip pin).
|
|
51
|
+
|
|
52
|
+
The engine is a dependency too. When a file states its vLLM version, the scan
|
|
53
|
+
lists what later vLLM release notes record for the model family that file
|
|
54
|
+
serves (adapter loading, tool calling, prompt rendering, quantization) and the
|
|
55
|
+
breaking changes and removals since, each with its pull request. It says what
|
|
56
|
+
the notes say changed, never whether your outputs change. --no-engine skips it.
|
|
57
|
+
|
|
58
|
+
Deployment manifests are read in the spellings their tools use: an
|
|
59
|
+
hf://owner/model[:revision] address (KServe storageUri, KServe
|
|
60
|
+
LLMInferenceService, llm-d modelArtifacts), a flag inside a YAML list or a
|
|
61
|
+
split entrypoint and command (--model_id for the KServe Hugging Face runtime,
|
|
62
|
+
--model-path for SGLang), model_source (Ray Serve) and modelURL (the vLLM
|
|
63
|
+
production stack). The fix is written the way that format takes a commit.
|
|
64
|
+
|
|
65
|
+
It also reads repo ids and commits held in module constants (MODEL_ID = ...),
|
|
66
|
+
pin tables (a dict of repo id to commit, the way hand-pinned repos keep them),
|
|
67
|
+
metadata records (MTEB's ModelMeta(name=..., revision=...)) and serving env
|
|
68
|
+
vars in manifests, compose files and Dockerfiles (MODEL_ID, REVISION); ids
|
|
69
|
+
that reach a load as a default value (a parameter default, an argparse
|
|
70
|
+
default, an instance attribute, an os.getenv fallback), marked as such; and
|
|
71
|
+
LangChain / LlamaIndex HuggingFaceEmbedding(s). An id that travels through a
|
|
72
|
+
registry dict or another file before it is loaded is not followed yet.
|
|
73
|
+
|
|
74
|
+
--fix hold the code you run today: add code_revision= (pinned to the
|
|
75
|
+
code repository's current commit) where a model imports code from
|
|
76
|
+
another repository, and revision= where a remote-code load is not
|
|
77
|
+
pinned. Edits .py files and shell launch lines in place; review with
|
|
78
|
+
git diff. Calls it cannot edit safely are listed, not guessed.
|
|
79
|
+
--cyclonedx F (alias --bom) write a CycloneDX 1.6 BOM: one component per model (purl at the
|
|
80
|
+
commit), cross-repository code as a dependency, each finding as a
|
|
81
|
+
vulnerability entry mapped to NIST SP 800-218A / AI 600-1.
|
|
82
|
+
|
|
83
|
+
Exit 1 when any finding is high. Reads huggingface.co and www.neurarch.com;
|
|
84
|
+
set HF_TOKEN for gated repos. Only public model ids leave your machine.
|
|
85
|
+
`;
|
|
86
|
+
|
|
87
|
+
function* walk(abs, kindOf) {
|
|
88
|
+
let st;
|
|
89
|
+
try { st = statSync(abs); } catch { return; }
|
|
90
|
+
if (st.isFile()) { if (kindOf(abs) && st.size <= 5 * 1024 * 1024) yield abs; return; }
|
|
91
|
+
if (!st.isDirectory()) return;
|
|
92
|
+
let entries;
|
|
93
|
+
try { entries = readdirSync(abs, { withFileTypes: true }); } catch { return; }
|
|
94
|
+
for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
95
|
+
if (e.isDirectory() && SKIP_DIRS.has(e.name)) continue;
|
|
96
|
+
if (e.isSymbolicLink()) continue;
|
|
97
|
+
yield* walk(join(abs, e.name), kindOf);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const headers = () => (process.env.HF_TOKEN ? { Authorization: `Bearer ${process.env.HF_TOKEN}` } : {});
|
|
102
|
+
async function getJson(url, h = {}) {
|
|
103
|
+
try {
|
|
104
|
+
const r = await fetch(url, { headers: h, signal: AbortSignal.timeout(20_000) });
|
|
105
|
+
return r.ok ? await r.json() : null;
|
|
106
|
+
} catch { return null; }
|
|
107
|
+
}
|
|
108
|
+
const hubInfo = (id, rev) => getJson(`https://huggingface.co/api/models/${id}/revision/${encodeURIComponent(rev)}?blobs=true`, headers());
|
|
109
|
+
|
|
110
|
+
async function rawConfig(id, rev) {
|
|
111
|
+
try {
|
|
112
|
+
const r = await fetch(`https://huggingface.co/${id}/resolve/${encodeURIComponent(rev)}/config.json`, { headers: headers(), signal: AbortSignal.timeout(20_000) });
|
|
113
|
+
return r.ok ? await r.json() : null;
|
|
114
|
+
} catch { return null; }
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async function templateAt(id, rev) {
|
|
118
|
+
const get = async (f) => {
|
|
119
|
+
try {
|
|
120
|
+
const r = await fetch(`https://huggingface.co/${id}/resolve/${encodeURIComponent(rev)}/${f}`, { headers: headers(), signal: AbortSignal.timeout(20_000) });
|
|
121
|
+
return r.ok ? r.text() : null;
|
|
122
|
+
} catch { return null; }
|
|
123
|
+
};
|
|
124
|
+
const [jinja, tokRaw] = await Promise.all([get('chat_template.jinja'), get('tokenizer_config.json')]);
|
|
125
|
+
let tok = null;
|
|
126
|
+
try { tok = tokRaw ? JSON.parse(tokRaw) : null; } catch { tok = null; }
|
|
127
|
+
const t = tok?.chat_template;
|
|
128
|
+
const text = jinja ?? (typeof t === 'string' ? t : Array.isArray(t) ? (t.find((x) => x?.name === 'default') ?? t[0])?.template : null);
|
|
129
|
+
const tx = (v) => (v && typeof v === 'object' ? v.content : typeof v === 'string' ? v : null);
|
|
130
|
+
return text ? { text, specials: { bos_token: tx(tok?.bos_token), eos_token: tx(tok?.eos_token) } } : null;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Tensor names from a safetensors header: 8 bytes of length, then JSON. Range requests only; a server that ignores Range is not read. */
|
|
134
|
+
async function remoteTensorNames(id, rev, file) {
|
|
135
|
+
const url = `https://huggingface.co/${id}/resolve/${encodeURIComponent(rev)}/${file.split('/').map(encodeURIComponent).join('/')}`;
|
|
136
|
+
try {
|
|
137
|
+
const r1 = await fetch(url, { headers: { ...headers(), Range: 'bytes=0-7' }, signal: AbortSignal.timeout(20_000) });
|
|
138
|
+
if (r1.status !== 206) { try { await r1.body?.cancel(); } catch { /* nothing to cancel */ } return null; }
|
|
139
|
+
const n = Number(new DataView(await r1.arrayBuffer()).getBigUint64(0, true));
|
|
140
|
+
if (!(n > 1 && n < 100 * 1024 * 1024)) return null;
|
|
141
|
+
const r2 = await fetch(url, { headers: { ...headers(), Range: `bytes=8-${7 + n}` }, signal: AbortSignal.timeout(30_000) });
|
|
142
|
+
if (r2.status !== 206) { try { await r2.body?.cancel(); } catch { /* nothing to cancel */ } return null; }
|
|
143
|
+
return Object.keys(JSON.parse(await r2.text())).filter((k) => k !== '__metadata__');
|
|
144
|
+
} catch { return null; }
|
|
145
|
+
}
|
|
146
|
+
function localTensorNames(abs) {
|
|
147
|
+
let fd;
|
|
148
|
+
try {
|
|
149
|
+
fd = openSync(abs, 'r');
|
|
150
|
+
const head = Buffer.alloc(8);
|
|
151
|
+
if (readSync(fd, head, 0, 8, 0) !== 8) return null;
|
|
152
|
+
const n = Number(head.readBigUInt64LE(0));
|
|
153
|
+
if (!(n > 1 && n < 100 * 1024 * 1024)) return null;
|
|
154
|
+
const body = Buffer.alloc(n);
|
|
155
|
+
if (readSync(fd, body, 0, n, 8) !== n) return null;
|
|
156
|
+
return Object.keys(JSON.parse(body.toString('utf8'))).filter((k) => k !== '__metadata__');
|
|
157
|
+
} catch { return null; } finally { if (fd !== undefined) try { closeSync(fd); } catch { /* already closed */ } }
|
|
158
|
+
}
|
|
159
|
+
const baseNamesCache = new Map();
|
|
160
|
+
/** Every tensor name in a base checkpoint's root safetensors files, from their headers. */
|
|
161
|
+
function baseTensorNames(id, rev) {
|
|
162
|
+
const k = `${id}@${rev}`;
|
|
163
|
+
if (!baseNamesCache.has(k)) baseNamesCache.set(k, (async () => {
|
|
164
|
+
const info = await hubInfo(id, rev);
|
|
165
|
+
const files = (info?.siblings ?? []).map((x) => x.rfilename).filter((f) => f.endsWith('.safetensors') && !f.includes('/') && !/adapter_model|optimizer|training_args/.test(f)).slice(0, 96);
|
|
166
|
+
if (!files.length) return null;
|
|
167
|
+
const out = [];
|
|
168
|
+
for (let i = 0; i < files.length; i += 6) {
|
|
169
|
+
const part = await Promise.all(files.slice(i, i + 6).map((f) => remoteTensorNames(id, info.sha ?? rev, f)));
|
|
170
|
+
if (part.some((x) => x === null)) return null;
|
|
171
|
+
for (const names of part) out.push(...names);
|
|
172
|
+
}
|
|
173
|
+
return out;
|
|
174
|
+
})());
|
|
175
|
+
return baseNamesCache.get(k);
|
|
176
|
+
}
|
|
177
|
+
async function remoteJson(id, rev, file) {
|
|
178
|
+
try {
|
|
179
|
+
const r = await fetch(`https://huggingface.co/${id}/resolve/${encodeURIComponent(rev)}/${file}`, { headers: headers(), signal: AbortSignal.timeout(20_000) });
|
|
180
|
+
return r.ok ? await r.json() : null;
|
|
181
|
+
} catch { return null; }
|
|
182
|
+
}
|
|
183
|
+
const LANE_RANK = { security: 0, behavior: 1, hygiene: 2 };
|
|
184
|
+
const SEV_RANK = { high: 0, medium: 1, low: 2 };
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* For every adapter the scan found, compare its tensor names with its base's.
|
|
188
|
+
* An adapter named by Hub id (PeftModel.from_pretrained, a launch flag) is read
|
|
189
|
+
* from the Hub; an exported adapter directory in the scanned tree is read from
|
|
190
|
+
* disk. Findings land on the adapter's own entry, or on the base's for a local
|
|
191
|
+
* adapter directory.
|
|
192
|
+
*/
|
|
193
|
+
async function adapterPass(results, root, L) {
|
|
194
|
+
const hubId = (s) => typeof s === 'string' && /^[A-Za-z0-9][\w.-]*\/[\w.-]+$/.test(s);
|
|
195
|
+
for (const r of results) {
|
|
196
|
+
const seen = new Set();
|
|
197
|
+
for (const h of r.hits) {
|
|
198
|
+
let adapterNames = null;
|
|
199
|
+
let base;
|
|
200
|
+
let recordedBase;
|
|
201
|
+
let baseCommitRecorded;
|
|
202
|
+
if (h.adapter && r.mainSha) {
|
|
203
|
+
const cfg = await remoteJson(r.id, r.pinned ?? r.mainSha, 'adapter_config.json');
|
|
204
|
+
if (!cfg) continue; // not an adapter repo after all, or unreadable
|
|
205
|
+
recordedBase = hubId(cfg.base_model_name_or_path) ? cfg.base_model_name_or_path : undefined;
|
|
206
|
+
baseCommitRecorded = typeof cfg.revision === 'string' && /^[0-9a-f]{40}$/.test(cfg.revision);
|
|
207
|
+
base = h.servedBase ?? recordedBase;
|
|
208
|
+
adapterNames = await remoteTensorNames(r.id, r.pinned ?? r.mainSha, 'adapter_model.safetensors');
|
|
209
|
+
} else if (h.edge === 'adapter-base') {
|
|
210
|
+
base = r.id;
|
|
211
|
+
adapterNames = localTensorNames(resolve(root, dirname(h.path), 'adapter_model.safetensors'));
|
|
212
|
+
} else continue;
|
|
213
|
+
if (!base) continue;
|
|
214
|
+
const key = `${base}|${h.engine?.name ?? ''}|${h.engine?.version ?? ''}`;
|
|
215
|
+
if (seen.has(key)) continue;
|
|
216
|
+
seen.add(key);
|
|
217
|
+
const baseRev = h.edge === 'adapter-base' ? (r.pinned ?? 'main') : 'main';
|
|
218
|
+
const baseNames = adapterNames ? await baseTensorNames(base, baseRev) : null;
|
|
219
|
+
const layout = adapterNames && baseNames ? L.adapterLayout(adapterNames, baseNames) : null;
|
|
220
|
+
const found = L.assessAdapter({ adapter: h.adapter ? r.id : dirname(h.path), base, layout, engine: h.engine, recordedBase: h.servedBase ? recordedBase : undefined, baseCommitRecorded: h.adapter ? baseCommitRecorded : undefined });
|
|
221
|
+
for (const f of found) if (!r.findings.some((x) => x.kind === f.kind && x.message === f.message)) r.findings.push(f);
|
|
222
|
+
(r.adapterChecks ??= []).push({ base, engine: h.engine ?? null, layout: layout ? { modules: layout.modules, verdict: layout.verdict, wrapper: layout.wrapper ?? null } : null });
|
|
223
|
+
}
|
|
224
|
+
r.findings.sort((a, b) => LANE_RANK[a.lane] - LANE_RANK[b.lane] || SEV_RANK[a.severity] - SEV_RANK[b.severity]);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const SEV = { high: '31', medium: '33', low: '2' };
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* The engine as a dependency: for every model served from a file that states its
|
|
232
|
+
* vLLM version, what later release notes record. The record is fetched once, and
|
|
233
|
+
* only when some file states a version. The breaking changes of a version are
|
|
234
|
+
* told once, under the first model served on it, not under every model.
|
|
235
|
+
*/
|
|
236
|
+
async function enginePass(results, L) {
|
|
237
|
+
const stated = (r) => [...new Set(r.hits.filter((h) => h.engine?.name === 'vllm' && h.engine.version).map((h) => h.engine.version))];
|
|
238
|
+
if (!results.some((r) => stated(r).length)) return null;
|
|
239
|
+
let record = null;
|
|
240
|
+
try { record = /^https?:/.test(ENGINE_RECORD) ? await getJson(ENGINE_RECORD) : JSON.parse(readFileSync(ENGINE_RECORD, 'utf8')); } catch { record = null; }
|
|
241
|
+
if (!record?.releases?.length) return { unavailable: true };
|
|
242
|
+
// One note per engine version, model family and adapter use: a file that serves twenty Qwen
|
|
243
|
+
// models on one image gets it once, under the first, with the count of the others.
|
|
244
|
+
const notes = new Map();
|
|
245
|
+
const toldBreaking = new Set();
|
|
246
|
+
for (const r of results) {
|
|
247
|
+
for (const version of stated(r)) {
|
|
248
|
+
const hit = r.hits.find((h) => h.engine?.version === version);
|
|
249
|
+
// An adapter is judged by the family of the base it is served on.
|
|
250
|
+
const adapter = r.hits.some((h) => h.adapter);
|
|
251
|
+
const since = L.engineChangesSince(record, version, hit?.servedBase ?? r.id, { adapter });
|
|
252
|
+
if (!since) continue;
|
|
253
|
+
const key = `${since.version}|${since.family ?? ''}|${adapter ? 'a' : ''}`;
|
|
254
|
+
const seen = notes.get(key);
|
|
255
|
+
if (seen) { seen.others++; continue; }
|
|
256
|
+
const first = !toldBreaking.has(since.version);
|
|
257
|
+
toldBreaking.add(since.version);
|
|
258
|
+
const found = L.assessEngine(first ? since : { ...since, breaking: [] });
|
|
259
|
+
if (!found.length) continue;
|
|
260
|
+
r.findings.push(...found);
|
|
261
|
+
notes.set(key, { finding: found[0], others: 0 });
|
|
262
|
+
(r.engineChanges ??= []).push({ engine: 'vllm', version: since.version, latest: since.latest, behind: since.behind, family: since.family ?? null, rows: since.rows.slice(0, 8), breaking: first ? since.breaking.slice(0, 8) : [] });
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
for (const n of notes.values()) if (n.others) n.finding.message += ` The same holds for ${n.others} other model${n.others === 1 ? '' : 's'} in this scan served the same way.`;
|
|
266
|
+
return { url: ENGINE_RECORD, asOf: record.asOf, releases: record.releases.length };
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
export async function scanCommand(args, engine) {
|
|
270
|
+
const L = await import('../policy.bundle.mjs');
|
|
271
|
+
const o = { paths: [], template: true, adapter: true, engine: true };
|
|
272
|
+
const skip = new Set();
|
|
273
|
+
for (const [i, a] of args.entries()) {
|
|
274
|
+
if (skip.has(i)) continue;
|
|
275
|
+
if (a === '-h' || a === '--help') { process.stdout.write(HELP); return 0; }
|
|
276
|
+
if (a === '--json') o.json = true;
|
|
277
|
+
else if (a === '--no-template') o.template = false;
|
|
278
|
+
else if (a === '--no-adapter') o.adapter = false;
|
|
279
|
+
else if (a === '--no-engine') o.engine = false;
|
|
280
|
+
else if (a === '--fix') o.fix = true;
|
|
281
|
+
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); }
|
|
282
|
+
else if (a.startsWith('-')) { process.stderr.write(`neurarch scan: unknown flag ${a} (--help)\n`); return 2; }
|
|
283
|
+
else o.paths.push(a);
|
|
284
|
+
}
|
|
285
|
+
if (!o.paths.length) o.paths.push('.');
|
|
286
|
+
const root = process.cwd();
|
|
287
|
+
const refs = [];
|
|
288
|
+
let files = 0;
|
|
289
|
+
for (const p of o.paths) {
|
|
290
|
+
const abs = resolve(p);
|
|
291
|
+
try { statSync(abs); } catch { process.stderr.write(`neurarch scan: ${p}: no such file or directory\n`); return 2; }
|
|
292
|
+
for (const f of walk(abs, (x) => L.refFileKind(posix(x)))) {
|
|
293
|
+
let text;
|
|
294
|
+
try { text = readFileSync(f, 'utf8'); } catch { continue; }
|
|
295
|
+
files++;
|
|
296
|
+
const rel = posix(relative(root, f)) || posix(f);
|
|
297
|
+
const engine = L.engineIn(text);
|
|
298
|
+
for (const h of L.scanModelRefs(rel, text)) if (h.repoType === 'model') refs.push(engine ? { ...h, engine } : h);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// One assessment per (model, pin); call sites listed under it.
|
|
303
|
+
const groups = new Map();
|
|
304
|
+
const codeHeads = new Map();
|
|
305
|
+
for (const h of refs) {
|
|
306
|
+
const pin = h.pinned ? h.revision : undefined;
|
|
307
|
+
const k = `${h.repo}@${pin ?? ''}`;
|
|
308
|
+
if (!groups.has(k)) groups.set(k, { id: h.repo, pinned: pin, sites: [], hits: [], codeRevision: true });
|
|
309
|
+
const g = groups.get(k);
|
|
310
|
+
g.sites.push(`${h.path}:${h.line}`);
|
|
311
|
+
// The id reaches this call only when nothing overrides it (a parameter, argparse or env default).
|
|
312
|
+
if (h.via === 'default') (g.defaultSites ??= []).push(`${h.path}:${h.line}`);
|
|
313
|
+
g.hits.push(h);
|
|
314
|
+
if (!h.codeRevision) g.codeRevision = false;
|
|
315
|
+
}
|
|
316
|
+
// Repository Python runs only with trust_remote_code. When every reference to a model says it is off
|
|
317
|
+
// (a serving image without TRUST_REMOTE_CODE, a from_pretrained call that does not pass it), there is
|
|
318
|
+
// no remote-code finding to make; one reference that passes it, or that cannot say, keeps them.
|
|
319
|
+
for (const g of groups.values()) g.remoteCodeRuns = g.hits.every((h) => h.trustRemoteCode === false) ? false : undefined;
|
|
320
|
+
|
|
321
|
+
const [feed, advisories] = await Promise.all([getJson(FEED), getJson(TRACKED)]);
|
|
322
|
+
const recorded = feed?.changes ?? null;
|
|
323
|
+
const securityRecorded = (feed?.lanes ?? []).filter((l) => l.lane === 'security');
|
|
324
|
+
const tracked = new Set((advisories?.advisories ?? []).map((a) => a.model));
|
|
325
|
+
for (const ch of recorded ?? []) tracked.add(ch.id);
|
|
326
|
+
|
|
327
|
+
const results = [];
|
|
328
|
+
for (const g of groups.values()) {
|
|
329
|
+
const [atMain, atPin] = await Promise.all([hubInfo(g.id, 'main'), g.pinned ? hubInfo(g.id, g.pinned) : null]);
|
|
330
|
+
// A default like name="base" that the Hub does not know is a word, not a model.
|
|
331
|
+
if (!atMain && !atPin && !g.id.includes('/') && g.hits.every((h) => h.via === 'default')) continue;
|
|
332
|
+
let templateVerdict = null;
|
|
333
|
+
const moved = g.pinned && atMain?.sha && !atMain.sha.startsWith(g.pinned);
|
|
334
|
+
if (o.template && moved && engine?.checkRevision) {
|
|
335
|
+
const [a, b] = await Promise.all([templateAt(g.id, g.pinned), templateAt(g.id, atMain.sha)]);
|
|
336
|
+
if (a && b) {
|
|
337
|
+
try { templateVerdict = engine.checkRevision(a.text, b.text, 'vllm', a.specials, b.specials).verdict; } catch { templateVerdict = null; }
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
const [rawConfigMain, rawConfigPin] = await Promise.all([atMain?.sha ? rawConfig(g.id, atMain.sha) : null, g.pinned ? rawConfig(g.id, g.pinned) : null]);
|
|
341
|
+
const code = g.remoteCodeRuns === false ? { declared: false, crossRepo: [] } : L.remoteCodeOf(atMain ?? atPin, g.id);
|
|
342
|
+
const codeRepos = [];
|
|
343
|
+
for (const repo of code.crossRepo) {
|
|
344
|
+
if (!codeHeads.has(repo)) codeHeads.set(repo, hubInfo(repo, 'main').then((x) => x?.sha ?? null));
|
|
345
|
+
codeRepos.push({ id: repo, sha: await codeHeads.get(repo), held: g.codeRevision });
|
|
346
|
+
}
|
|
347
|
+
const findings = atMain || atPin
|
|
348
|
+
? 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 })
|
|
349
|
+
: [{ 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.' }];
|
|
350
|
+
results.push({ ...g, mainSha: atMain?.sha ?? null, tracked: tracked.has(g.id), remoteCode: code.declared, codeRepos, findings });
|
|
351
|
+
}
|
|
352
|
+
if (o.adapter) await adapterPass(results, root, L);
|
|
353
|
+
const engineNote = o.engine ? await enginePass(results, L) : null;
|
|
354
|
+
for (const r of results) {
|
|
355
|
+
// An exported adapter that names its base without a commit: say that, in the file's own terms.
|
|
356
|
+
if (r.hits.every((h) => h.edge === 'adapter-base')) for (const f of r.findings) if (f.kind === 'unpinned') { f.message = `The adapter config at ${r.hits[0].path} names ${r.id} as its base without a commit, so nothing records which revision the adapter was trained against; PEFT attaches it to whatever main has that day.`; f.fix = r.mainSha ? `"revision": "${r.mainSha}" in adapter_config.json, if that is the commit you trained on` : f.fix; }
|
|
357
|
+
// A deployment manifest: say the pin the way that format takes it (an hf:// address, a runtime flag, a chart value).
|
|
358
|
+
if (r.mainSha && r.hits.every((h) => h.pinHint)) for (const f of r.findings) if (f.kind === 'unpinned') f.fix = L.manifestPinFix(r.hits[0].pinHint, r.id, r.mainSha);
|
|
359
|
+
// An adapter handed to the server by id: the launch flag takes no revision.
|
|
360
|
+
if (r.hits.every((h) => h.adapter && h.syntax === 'shell')) for (const f of r.findings) if (f.kind === 'unpinned') f.fix = r.mainSha ? `hf download ${r.id} --revision ${r.mainSha} --local-dir <dir>, then pass the directory to the launch flag (it takes no revision)` : f.fix;
|
|
361
|
+
}
|
|
362
|
+
const fixes = o.fix ? applyFixes(results, root, L) : null;
|
|
363
|
+
if (o.bom) {
|
|
364
|
+
let version = '0';
|
|
365
|
+
try { version = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version; } catch { /* keep 0 */ }
|
|
366
|
+
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()}` });
|
|
367
|
+
writeFileSync(o.bom, JSON.stringify(bom, null, 2) + '\n');
|
|
368
|
+
}
|
|
369
|
+
const code = L.scanExitCode(results.map((r) => r.findings));
|
|
370
|
+
|
|
371
|
+
if (o.json) {
|
|
372
|
+
process.stdout.write(JSON.stringify({ files, feed: recorded ? FEED : null, ...(engineNote ? { engineRecord: engineNote } : {}), models: results.map(({ hits, ...r }) => r), ...(fixes ? { fixes } : {}), ...(o.bom ? { bom: o.bom } : {}) }, null, 2) + '\n');
|
|
373
|
+
return code;
|
|
374
|
+
}
|
|
375
|
+
const out = process.stdout;
|
|
376
|
+
const count = (sev) => results.reduce((n, r) => n + r.findings.filter((f) => f.severity === sev && f.kind !== 'pin-current').length, 0);
|
|
377
|
+
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`);
|
|
378
|
+
if (!recorded) out.write(` ${c('33', 'recorded history unavailable')} (${FEED}); upstream changes since your pin are not listed\n`);
|
|
379
|
+
if (engineNote?.unavailable) out.write(` ${c('33', 'engine release record unavailable')} (${ENGINE_RECORD}); what later vLLM releases changed is not listed\n`);
|
|
380
|
+
for (const r of results) {
|
|
381
|
+
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`);
|
|
382
|
+
out.write(` ${c('2', r.sites.slice(0, 4).join(', ') + (r.sites.length > 4 ? ` +${r.sites.length - 4}` : ''))}\n`);
|
|
383
|
+
for (const a of r.adapterChecks ?? []) out.write(` ${c('2', a.layout ? `adapter on ${a.base}: ${a.layout.modules} target modules, ${a.layout.verdict === 'match' ? 'all present in the base' : a.layout.verdict}${a.engine ? `; served by ${a.engine.name}${a.engine.version ? ' ' + a.engine.version : ''}` : ''}` : `adapter on ${a.base}: tensor names could not be read, so the layout was not checked`)}\n`);
|
|
384
|
+
if (r.defaultSites?.length) out.write(` ${c('2', `the id is a default value at ${r.defaultSites.slice(0, 3).join(', ')}${r.defaultSites.length > 3 ? ` +${r.defaultSites.length - 3}` : ''}: it loads when the caller passes nothing else`)}\n`);
|
|
385
|
+
for (const f of r.findings) {
|
|
386
|
+
out.write(` ${c(SEV[f.severity], f.severity.padEnd(6))} ${f.lane.padEnd(8)} ${f.message}\n`);
|
|
387
|
+
if (f.fix) out.write(` ${' '.repeat(16)}${c('2', 'fix: ' + f.fix)}\n`);
|
|
388
|
+
if (f.url) out.write(` ${' '.repeat(16)}${c('2', f.url)}\n`);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
if (fixes) {
|
|
392
|
+
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`);
|
|
393
|
+
for (const e of fixes.edited) out.write(` ${c('32', 'edited')} ${e.path}:${e.line} ${e.what}\n`);
|
|
394
|
+
for (const e of fixes.skipped) out.write(` ${c('33', 'skipped')} ${e.path}:${e.line} ${e.why}\n`);
|
|
395
|
+
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`);
|
|
396
|
+
}
|
|
397
|
+
if (o.bom) out.write(`\n ${c('1', '--cyclonedx')} wrote ${o.bom} (CycloneDX 1.6, ${results.length} model${results.length === 1 ? '' : 's'})\n`);
|
|
398
|
+
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`);
|
|
399
|
+
return code;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* --fix: for each model that runs remote code, add what holds it to the
|
|
404
|
+
* commits upstream has today. Python call sites and shell launch lines only;
|
|
405
|
+
* records (ModelMeta) and env vars are listed for a person, because which
|
|
406
|
+
* call consumes them is not in the file.
|
|
407
|
+
*/
|
|
408
|
+
function applyFixes(results, root, L) {
|
|
409
|
+
const edited = [];
|
|
410
|
+
const skipped = [];
|
|
411
|
+
const byFile = new Map();
|
|
412
|
+
for (const r of results) {
|
|
413
|
+
if (!r.remoteCode) continue;
|
|
414
|
+
const crossHeld = r.codeRepos.length ? r.codeRepos[0] : null;
|
|
415
|
+
const set = {};
|
|
416
|
+
if (!r.pinned && r.mainSha) set.revision = r.mainSha;
|
|
417
|
+
if (crossHeld && !r.codeRevision && crossHeld.sha) set.codeRevision = crossHeld.sha;
|
|
418
|
+
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; }
|
|
419
|
+
if (!set.revision && !set.codeRevision) continue;
|
|
420
|
+
for (const h of r.hits) {
|
|
421
|
+
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; }
|
|
422
|
+
if (h.via === 'default') { skipped.push({ path: h.path, line: h.line, why: `the id is a default value, and a pin written at this call would apply to whatever id a caller passes: pin where ${r.id} is chosen (${[set.revision && `revision="${set.revision}"`, set.codeRevision && `code_revision="${set.codeRevision}"`].filter(Boolean).join(', ')})` }); continue; }
|
|
423
|
+
if (h.edge === 'adapter-base') { skipped.push({ path: h.path, line: h.line, why: `an adapter config: add ${[set.revision && `"revision": "${set.revision}"`].filter(Boolean).join(', ') || 'the base commit'} by hand if that is the commit it was trained on` }); continue; }
|
|
424
|
+
if (h.wrapper) { skipped.push({ path: h.path, line: h.line, why: `${h.api} takes the pin in model_kwargs: add ${[set.revision && `"revision": "${set.revision}"`, set.codeRevision && `"code_revision": "${set.codeRevision}"`].filter(Boolean).join(', ')}` }); continue; }
|
|
425
|
+
if (!byFile.has(h.path)) byFile.set(h.path, []);
|
|
426
|
+
byFile.get(h.path).push({ h, set });
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
for (const [path, items] of byFile) {
|
|
430
|
+
const abs = resolve(root, path);
|
|
431
|
+
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; }
|
|
432
|
+
let src;
|
|
433
|
+
try { src = readFileSync(abs, 'utf8'); } catch { continue; }
|
|
434
|
+
// bottom-up so earlier line numbers stay valid
|
|
435
|
+
for (const { h, set } of items.sort((a, b) => b.h.line - a.h.line)) {
|
|
436
|
+
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' };
|
|
437
|
+
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 ') }); }
|
|
438
|
+
else if (r.skipped !== 'already holds both') skipped.push({ path, line: h.line, why: r.skipped });
|
|
439
|
+
}
|
|
440
|
+
writeFileSync(abs, src);
|
|
441
|
+
}
|
|
442
|
+
edited.sort((a, b) => a.path.localeCompare(b.path) || a.line - b.line);
|
|
443
|
+
return { edited, skipped };
|
|
444
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
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
|
+
import { createHash } from 'node:crypto';
|
|
11
|
+
|
|
12
|
+
const tty = process.stdout.isTTY && !process.env.NO_COLOR;
|
|
13
|
+
const c = (code, s) => (tty ? `\x1b[${code}m${s}\x1b[0m` : String(s));
|
|
14
|
+
|
|
15
|
+
const HELP = `neurarch template-check: the prompt an engine sends, against the reference
|
|
16
|
+
|
|
17
|
+
npx neurarch template-check <hf-id> [--at <rev>] [--tool-parts] [--json]
|
|
18
|
+
npx neurarch template-check <hf-id> --from <rev> [--to <rev>] [--tool-parts] [--json]
|
|
19
|
+
|
|
20
|
+
With one revision (--at, default main): renders the model's chat template the
|
|
21
|
+
way transformers' apply_chat_template is usually called (content as a string)
|
|
22
|
+
and the way vLLM calls it with --chat-template-content-format auto (system,
|
|
23
|
+
user and assistant content as text parts when the template reads parts; tool
|
|
24
|
+
results as strings, as measured on vLLM 0.33.0), on a system+user turn, a
|
|
25
|
+
multi-turn chat and a tool call. A difference is a prompt vLLM sends that the
|
|
26
|
+
reference does not. --tool-parts also hands tool results as parts, as older
|
|
27
|
+
stacks did and as a client that sends parts gets.
|
|
28
|
+
|
|
29
|
+
With --from: renders the template at both revisions in the engine's form. A
|
|
30
|
+
difference is an upstream change that moves what a deployment sends.
|
|
31
|
+
|
|
32
|
+
Set HF_TOKEN for gated repos. Exits 1 when any prompt differs, 2 on a read error.
|
|
33
|
+
`;
|
|
34
|
+
|
|
35
|
+
function templateFrom(tok) {
|
|
36
|
+
const t = tok?.chat_template;
|
|
37
|
+
if (typeof t === 'string') return t;
|
|
38
|
+
if (Array.isArray(t)) {
|
|
39
|
+
const d = t.find((x) => x && x.name === 'default') ?? t[0];
|
|
40
|
+
return typeof d?.template === 'string' ? d.template : null;
|
|
41
|
+
}
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
const tokenText = (v) => (v && typeof v === 'object' && typeof v.content === 'string' ? v.content : typeof v === 'string' ? v : null);
|
|
45
|
+
|
|
46
|
+
async function readAt(id, rev) {
|
|
47
|
+
const headers = process.env.HF_TOKEN ? { Authorization: `Bearer ${process.env.HF_TOKEN}` } : {};
|
|
48
|
+
const get = async (file) => {
|
|
49
|
+
const r = await fetch(`https://huggingface.co/${id}/resolve/${encodeURIComponent(rev)}/${file}`, { headers, signal: AbortSignal.timeout(20_000) });
|
|
50
|
+
if (r.status === 404) return null;
|
|
51
|
+
if (!r.ok) throw new Error(`${file} at ${rev}: HTTP ${r.status}${r.status === 401 || r.status === 403 ? ' (gated: set HF_TOKEN)' : ''}`);
|
|
52
|
+
return r.text();
|
|
53
|
+
};
|
|
54
|
+
const [jinja, tokRaw] = await Promise.all([get('chat_template.jinja'), get('tokenizer_config.json')]);
|
|
55
|
+
let tok = null;
|
|
56
|
+
try { tok = tokRaw ? JSON.parse(tokRaw) : null; } catch { tok = null; }
|
|
57
|
+
const text = jinja ?? templateFrom(tok);
|
|
58
|
+
if (text == null) throw new Error(`no chat template at ${rev} (neither chat_template.jinja nor tokenizer_config.json carries one)`);
|
|
59
|
+
return { text, specials: { bos_token: tokenText(tok?.bos_token), eos_token: tokenText(tok?.eos_token) } };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export async function templateCheckCommand(argv, lib) {
|
|
63
|
+
const o = { engine: 'vllm', json: false };
|
|
64
|
+
const pos = [];
|
|
65
|
+
for (let i = 0; i < argv.length; i++) {
|
|
66
|
+
const a = argv[i];
|
|
67
|
+
if (a === '-h' || a === '--help') { process.stdout.write(HELP); return 0; }
|
|
68
|
+
if (a === '--json') { o.json = true; continue; }
|
|
69
|
+
if (a === '--tool-parts') { o.toolParts = true; continue; }
|
|
70
|
+
if (['--engine', '--at', '--from', '--to'].includes(a)) { o[a.slice(2)] = argv[++i]; continue; }
|
|
71
|
+
if (a.startsWith('--')) { process.stderr.write(`unknown flag ${a}\n${HELP}`); return 2; }
|
|
72
|
+
pos.push(a);
|
|
73
|
+
}
|
|
74
|
+
const id = pos[0];
|
|
75
|
+
if (!id) { process.stderr.write(HELP); return 2; }
|
|
76
|
+
if (!['vllm', 'sglang'].includes(o.engine)) { process.stderr.write(`--engine must be vllm or sglang\n`); return 2; }
|
|
77
|
+
try {
|
|
78
|
+
let result, labels, identity = {};
|
|
79
|
+
if (o.from) {
|
|
80
|
+
const to = o.to ?? 'main';
|
|
81
|
+
const [a, b] = await Promise.all([readAt(id, o.from), readAt(id, to)]);
|
|
82
|
+
result = lib.checkRevision(a.text, b.text, o.engine, a.specials, b.specials, { toolParts: !!o.toolParts });
|
|
83
|
+
labels = { left: o.from.slice(0, 12), right: to.slice(0, 12) };
|
|
84
|
+
} else {
|
|
85
|
+
const at = o.at ?? 'main';
|
|
86
|
+
const s = await readAt(id, at);
|
|
87
|
+
result = lib.checkParity(s.text, o.engine, s.specials, { toolParts: !!o.toolParts });
|
|
88
|
+
labels = { left: 'reference', right: o.engine };
|
|
89
|
+
// Which template this verdict is about: the revision asked for and the bytes that were read there.
|
|
90
|
+
identity = { at, templateSha256: createHash('sha256').update(s.text).digest('hex') };
|
|
91
|
+
}
|
|
92
|
+
if (o.json) process.stdout.write(JSON.stringify({ model: id, ...identity, ...result }, null, 2) + '\n');
|
|
93
|
+
else {
|
|
94
|
+
const text = lib.renderConformanceText(result, labels);
|
|
95
|
+
process.stdout.write((result.verdict === 'different' ? c('31', text.split('\n')[0]) + '\n' + text.split('\n').slice(1).join('\n') : text) + '\n');
|
|
96
|
+
}
|
|
97
|
+
return result.verdict === 'different' ? 1 : 0;
|
|
98
|
+
} catch (e) {
|
|
99
|
+
process.stderr.write(`${c('31', 'cannot read the template')}: ${e.message}\n`);
|
|
100
|
+
return 2;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
@@ -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
|
+
}
|