neurarch 0.4.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 +98 -11
- package/bin/gate.mjs +259 -0
- package/bin/neurarch.mjs +19 -9
- package/bin/scan.mjs +202 -13
- package/bin/templateCheck.mjs +5 -2
- package/engine.bundle.mjs +28 -7
- package/package.json +11 -3
- package/policy.bundle.mjs +962 -45
package/bin/scan.mjs
CHANGED
|
@@ -9,9 +9,9 @@
|
|
|
9
9
|
* Network: huggingface.co and www.neurarch.com only. Nothing from the scanned
|
|
10
10
|
* repository is sent anywhere; only public model ids are requested.
|
|
11
11
|
*/
|
|
12
|
-
import { readFileSync, writeFileSync } from 'node:fs';
|
|
12
|
+
import { readFileSync, writeFileSync, openSync, readSync, closeSync } from 'node:fs';
|
|
13
13
|
import { randomUUID } from 'node:crypto';
|
|
14
|
-
import { relative, resolve, sep, join } from 'node:path';
|
|
14
|
+
import { relative, resolve, sep, join, dirname } from 'node:path';
|
|
15
15
|
import { readdirSync, statSync } from 'node:fs';
|
|
16
16
|
|
|
17
17
|
const tty = process.stdout.isTTY && !process.env.NO_COLOR;
|
|
@@ -20,10 +20,12 @@ const posix = (p) => p.split(sep).join('/');
|
|
|
20
20
|
const SKIP_DIRS = new Set(['.git', '.hg', '.svn', 'node_modules', '.venv', 'venv', 'env', '__pycache__', '.tox', '.nox', 'site-packages', '.ipynb_checkpoints']);
|
|
21
21
|
const FEED = process.env.NEURARCH_CHANGES_URL || 'https://www.neurarch.com/changes/index.json';
|
|
22
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';
|
|
23
25
|
|
|
24
26
|
const HELP = `neurarch scan: a dependency scan for the models your code pulls
|
|
25
27
|
|
|
26
|
-
npx neurarch scan [paths...] [--json] [--no-template] [--fix] [--cyclonedx out.cdx.json]
|
|
28
|
+
npx neurarch scan [paths...] [--json] [--no-template] [--no-adapter] [--no-engine] [--fix] [--cyclonedx out.cdx.json]
|
|
27
29
|
|
|
28
30
|
Finds every Hugging Face model your .py, .ipynb, YAML, shell scripts and
|
|
29
31
|
Dockerfiles download (from_pretrained, vllm serve, hf download, base_model:,
|
|
@@ -32,14 +34,42 @@ Dockerfiles download (from_pretrained, vllm serve, hf download, base_model:,
|
|
|
32
34
|
security Python the loader runs from the repo (auto_map) that is unpinned,
|
|
33
35
|
changed since your pin, or lives in another repository that
|
|
34
36
|
revision= does not pin; weights only in pickle formats.
|
|
35
|
-
behavior
|
|
36
|
-
|
|
37
|
-
|
|
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.
|
|
38
42
|
hygiene downloads not pinned to a commit.
|
|
39
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
|
+
|
|
40
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),
|
|
41
67
|
metadata records (MTEB's ModelMeta(name=..., revision=...)) and serving env
|
|
42
|
-
vars in manifests, compose files and Dockerfiles (MODEL_ID, REVISION)
|
|
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.
|
|
43
73
|
|
|
44
74
|
--fix hold the code you run today: add code_revision= (pinned to the
|
|
45
75
|
code repository's current commit) where a model imports code from
|
|
@@ -100,17 +130,153 @@ async function templateAt(id, rev) {
|
|
|
100
130
|
return text ? { text, specials: { bos_token: tx(tok?.bos_token), eos_token: tx(tok?.eos_token) } } : null;
|
|
101
131
|
}
|
|
102
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
|
+
|
|
103
228
|
const SEV = { high: '31', medium: '33', low: '2' };
|
|
104
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
|
+
|
|
105
269
|
export async function scanCommand(args, engine) {
|
|
106
270
|
const L = await import('../policy.bundle.mjs');
|
|
107
|
-
const o = { paths: [], template: true };
|
|
271
|
+
const o = { paths: [], template: true, adapter: true, engine: true };
|
|
108
272
|
const skip = new Set();
|
|
109
273
|
for (const [i, a] of args.entries()) {
|
|
110
274
|
if (skip.has(i)) continue;
|
|
111
275
|
if (a === '-h' || a === '--help') { process.stdout.write(HELP); return 0; }
|
|
112
276
|
if (a === '--json') o.json = true;
|
|
113
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;
|
|
114
280
|
else if (a === '--fix') o.fix = true;
|
|
115
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); }
|
|
116
282
|
else if (a.startsWith('-')) { process.stderr.write(`neurarch scan: unknown flag ${a} (--help)\n`); return 2; }
|
|
@@ -123,12 +289,13 @@ export async function scanCommand(args, engine) {
|
|
|
123
289
|
for (const p of o.paths) {
|
|
124
290
|
const abs = resolve(p);
|
|
125
291
|
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.
|
|
292
|
+
for (const f of walk(abs, (x) => L.refFileKind(posix(x)))) {
|
|
127
293
|
let text;
|
|
128
294
|
try { text = readFileSync(f, 'utf8'); } catch { continue; }
|
|
129
295
|
files++;
|
|
130
296
|
const rel = posix(relative(root, f)) || posix(f);
|
|
131
|
-
|
|
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);
|
|
132
299
|
}
|
|
133
300
|
}
|
|
134
301
|
|
|
@@ -141,11 +308,15 @@ export async function scanCommand(args, engine) {
|
|
|
141
308
|
if (!groups.has(k)) groups.set(k, { id: h.repo, pinned: pin, sites: [], hits: [], codeRevision: true });
|
|
142
309
|
const g = groups.get(k);
|
|
143
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}`);
|
|
144
313
|
g.hits.push(h);
|
|
145
314
|
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
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;
|
|
149
320
|
|
|
150
321
|
const [feed, advisories] = await Promise.all([getJson(FEED), getJson(TRACKED)]);
|
|
151
322
|
const recorded = feed?.changes ?? null;
|
|
@@ -156,6 +327,8 @@ export async function scanCommand(args, engine) {
|
|
|
156
327
|
const results = [];
|
|
157
328
|
for (const g of groups.values()) {
|
|
158
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;
|
|
159
332
|
let templateVerdict = null;
|
|
160
333
|
const moved = g.pinned && atMain?.sha && !atMain.sha.startsWith(g.pinned);
|
|
161
334
|
if (o.template && moved && engine?.checkRevision) {
|
|
@@ -176,6 +349,16 @@ export async function scanCommand(args, engine) {
|
|
|
176
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.' }];
|
|
177
350
|
results.push({ ...g, mainSha: atMain?.sha ?? null, tracked: tracked.has(g.id), remoteCode: code.declared, codeRepos, findings });
|
|
178
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
|
+
}
|
|
179
362
|
const fixes = o.fix ? applyFixes(results, root, L) : null;
|
|
180
363
|
if (o.bom) {
|
|
181
364
|
let version = '0';
|
|
@@ -186,16 +369,19 @@ export async function scanCommand(args, engine) {
|
|
|
186
369
|
const code = L.scanExitCode(results.map((r) => r.findings));
|
|
187
370
|
|
|
188
371
|
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');
|
|
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');
|
|
190
373
|
return code;
|
|
191
374
|
}
|
|
192
375
|
const out = process.stdout;
|
|
193
376
|
const count = (sev) => results.reduce((n, r) => n + r.findings.filter((f) => f.severity === sev && f.kind !== 'pin-current').length, 0);
|
|
194
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`);
|
|
195
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`);
|
|
196
380
|
for (const r of results) {
|
|
197
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`);
|
|
198
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`);
|
|
199
385
|
for (const f of r.findings) {
|
|
200
386
|
out.write(` ${c(SEV[f.severity], f.severity.padEnd(6))} ${f.lane.padEnd(8)} ${f.message}\n`);
|
|
201
387
|
if (f.fix) out.write(` ${' '.repeat(16)}${c('2', 'fix: ' + f.fix)}\n`);
|
|
@@ -233,6 +419,9 @@ function applyFixes(results, root, L) {
|
|
|
233
419
|
if (!set.revision && !set.codeRevision) continue;
|
|
234
420
|
for (const h of r.hits) {
|
|
235
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; }
|
|
236
425
|
if (!byFile.has(h.path)) byFile.set(h.path, []);
|
|
237
426
|
byFile.get(h.path).push({ h, set });
|
|
238
427
|
}
|
package/bin/templateCheck.mjs
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
* set with src/utils/templateConformance.ts (through engine.bundle.mjs). No
|
|
8
8
|
* weights, no GPU. Exit 1 when a prompt differs, so it can gate CI.
|
|
9
9
|
*/
|
|
10
|
+
import { createHash } from 'node:crypto';
|
|
10
11
|
|
|
11
12
|
const tty = process.stdout.isTTY && !process.env.NO_COLOR;
|
|
12
13
|
const c = (code, s) => (tty ? `\x1b[${code}m${s}\x1b[0m` : String(s));
|
|
@@ -74,7 +75,7 @@ export async function templateCheckCommand(argv, lib) {
|
|
|
74
75
|
if (!id) { process.stderr.write(HELP); return 2; }
|
|
75
76
|
if (!['vllm', 'sglang'].includes(o.engine)) { process.stderr.write(`--engine must be vllm or sglang\n`); return 2; }
|
|
76
77
|
try {
|
|
77
|
-
let result, labels;
|
|
78
|
+
let result, labels, identity = {};
|
|
78
79
|
if (o.from) {
|
|
79
80
|
const to = o.to ?? 'main';
|
|
80
81
|
const [a, b] = await Promise.all([readAt(id, o.from), readAt(id, to)]);
|
|
@@ -85,8 +86,10 @@ export async function templateCheckCommand(argv, lib) {
|
|
|
85
86
|
const s = await readAt(id, at);
|
|
86
87
|
result = lib.checkParity(s.text, o.engine, s.specials, { toolParts: !!o.toolParts });
|
|
87
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') };
|
|
88
91
|
}
|
|
89
|
-
if (o.json) process.stdout.write(JSON.stringify({ model: id, ...result }, null, 2) + '\n');
|
|
92
|
+
if (o.json) process.stdout.write(JSON.stringify({ model: id, ...identity, ...result }, null, 2) + '\n');
|
|
90
93
|
else {
|
|
91
94
|
const text = lib.renderConformanceText(result, labels);
|
|
92
95
|
process.stdout.write((result.verdict === 'different' ? c('31', text.split('\n')[0]) + '\n' + text.split('\n').slice(1).join('\n') : text) + '\n');
|
package/engine.bundle.mjs
CHANGED
|
@@ -44168,7 +44168,7 @@ init_toastStore();
|
|
|
44168
44168
|
// scripts/siteMeta.ts
|
|
44169
44169
|
var SITE = "https://www.neurarch.com";
|
|
44170
44170
|
var OG_IMAGE = `${SITE}/og-image.png`;
|
|
44171
|
-
var OG_IMAGE_ALT = "Neurarch: the
|
|
44171
|
+
var OG_IMAGE_ALT = "Neurarch: the release gate for the models you run yourself. Before a change goes live it checks the exact weights and code, what runs on load, a model that fits the GPU, and a prompt that renders the same.";
|
|
44172
44172
|
var OG_IMAGE_META = `<meta property="og:image" content="${OG_IMAGE}" />
|
|
44173
44173
|
<meta property="og:image:width" content="1200" />
|
|
44174
44174
|
<meta property="og:image:height" content="630" />
|
|
@@ -51285,7 +51285,9 @@ var BOOL_FLAGS = /* @__PURE__ */ new Set([
|
|
|
51285
51285
|
"--embedding",
|
|
51286
51286
|
"--embeddings",
|
|
51287
51287
|
"--async-scheduling",
|
|
51288
|
-
"--skip-mm-profiling"
|
|
51288
|
+
"--skip-mm-profiling",
|
|
51289
|
+
"--enable-extensible-kv-cache",
|
|
51290
|
+
"--no-enable-extensible-kv-cache"
|
|
51289
51291
|
]);
|
|
51290
51292
|
function parseServeCommand(cmd, engineHint) {
|
|
51291
51293
|
const tokens = Array.isArray(cmd) ? cmd : tokenizeCommand(cmd);
|
|
@@ -51682,7 +51684,9 @@ function vllmVersionDefaults(version, card, pp) {
|
|
|
51682
51684
|
maxNumSeqs: big || huge ? 1024 : 256,
|
|
51683
51685
|
inFlightBatches: v26 ? pp > 1 ? pp : 2 : 1,
|
|
51684
51686
|
printsTokensAs: vAtLeast(version, [0, 21, 0]) ? "concurrency" : "blocks",
|
|
51685
|
-
linearRecurrentAlign: vAtLeast(version, [0, 15, 0])
|
|
51687
|
+
linearRecurrentAlign: vAtLeast(version, [0, 15, 0]),
|
|
51688
|
+
extensibleKv: vAtLeast(version, [0, 34, 0]),
|
|
51689
|
+
defaultBlockSize: vAtLeast(version, [0, 34, 0]) ? 64 : null
|
|
51686
51690
|
};
|
|
51687
51691
|
}
|
|
51688
51692
|
function textConfigOf(c) {
|
|
@@ -52257,10 +52261,12 @@ function engineMemory(x) {
|
|
|
52257
52261
|
const reserve = vllmNonKvReserve(x.config, { weightsGib, tp: x.tp, pp: x.pp, maxNumSeqs: mns, maxNumBatchedTokens: mnbt, cudaGraphsCounted: D.cudaGraphsCounted, enforceEager: !!args.enforceEager, actBytes: x.actBytes, nvlink: card.nvlinkGBs > 0, encoder, cudaGraph });
|
|
52258
52262
|
const reserveGib = reserve.reduce((s, r) => s + r.gib, 0);
|
|
52259
52263
|
const kvBudget = kvFixed ?? requested - reserveGib;
|
|
52264
|
+
const sizedAfterWarmup = D.extensibleKv && kvFixed == null && !(args.flags ?? []).includes("--no-enable-extensible-kv-cache");
|
|
52265
|
+
const likelyMore = sizedAfterWarmup && args.gpuMemoryUtilization == null;
|
|
52260
52266
|
const capOf = (len) => vllmKvCapacity(stage, {
|
|
52261
52267
|
budgetBytes: Math.max(0, kvBudget) * GiB,
|
|
52262
52268
|
maxModelLen: len,
|
|
52263
|
-
blockSize: args.blockSize,
|
|
52269
|
+
blockSize: args.blockSize ?? D.defaultBlockSize ?? void 0,
|
|
52264
52270
|
inFlightTokens: D.inFlightBatches * mnbt,
|
|
52265
52271
|
printsTokensAs: D.printsTokensAs,
|
|
52266
52272
|
encoderTokens: mnbt,
|
|
@@ -52287,6 +52293,17 @@ function engineMemory(x) {
|
|
|
52287
52293
|
...encoder ? encoder.notes : x.config.audio_config || x.config.vision_config && !args.skipMmProfiling && args.limitMmPerPrompt?.image !== 0 ? ["the multimodal encoder's profiling run for this architecture (vLLM profiles the vision / audio tower too; sized here for gemma-3 and Qwen2/2.5/3-VL images only, so on this model the activation here is low)"] : []
|
|
52288
52294
|
]
|
|
52289
52295
|
};
|
|
52296
|
+
if (sizedAfterWarmup) {
|
|
52297
|
+
findings.push({
|
|
52298
|
+
rule: "kv-sized-after-warmup",
|
|
52299
|
+
area: "memory",
|
|
52300
|
+
severity: "info",
|
|
52301
|
+
title: `${x.versionLabel ?? "vLLM 0.34.0 and later"} sizes the KV cache after warmup from measured memory; the figures here are the earlier estimate`,
|
|
52302
|
+
detail: likelyMore ? `From 0.34.0 the extensible KV cache is on by default: the cache is committed after CUDA graph capture and warmup from the memory actually free, less a measured reserve and a margin, and gpu_memory_utilization defaults to 1.0. This estimate still holds back 8% of the card (${gib(total.gib)} x ${util}). Upstream measured 4 to 10% more KV tokens than that on eight models on GB200, so expect the engine's own log to show more than the number here. Nothing in this check has been fitted to a 0.34 log.` : `From 0.34.0 the extensible KV cache is on by default: the cache is committed after CUDA graph capture and warmup from the memory actually free, less a measured reserve and a margin. With an explicit --gpu-memory-utilization, upstream measured 1 to 4% fewer KV tokens than the earlier sizing gave, because the new path subtracts the CUDA graph and warmup memory it measured. Nothing in this check has been fitted to a 0.34 log.`,
|
|
52303
|
+
fix: "",
|
|
52304
|
+
source: "https://github.com/vllm-project/vllm/pull/56492"
|
|
52305
|
+
});
|
|
52306
|
+
}
|
|
52290
52307
|
if (used > 0) {
|
|
52291
52308
|
checked.push("memory-in-use");
|
|
52292
52309
|
if (total.gib - used < requested) {
|
|
@@ -52317,10 +52334,11 @@ function engineMemory(x) {
|
|
|
52317
52334
|
}
|
|
52318
52335
|
if (kvBudget <= 0) {
|
|
52319
52336
|
const weightsOnly = weightsGib >= requested;
|
|
52337
|
+
const insideSlack = likelyMore && !weightsOnly && total.gib - reserveGib > 0;
|
|
52320
52338
|
findings.push({
|
|
52321
52339
|
rule: weightsOnly ? "weights-over-budget" : "no-kv-memory",
|
|
52322
52340
|
area: "memory",
|
|
52323
|
-
severity: "block",
|
|
52341
|
+
severity: insideSlack ? "warn" : "block",
|
|
52324
52342
|
title: weightsOnly ? `Weights alone are ${gib(weightsGib)} per GPU${x.shareWord}, over the ${gib(requested)} budget` : `Weights plus vLLM's own reserve leave no memory for the KV cache`,
|
|
52325
52343
|
detail: `Budget = ${budgetWord}. Out of it: ${reserveWord}. vLLM refuses at startup ("No available memory for the cache blocks. Try increasing \`gpu_memory_utilization\`").`,
|
|
52326
52344
|
fix: "Raise TP (or PP), quantize the weights, raise --gpu-memory-utilization, or use a larger card.",
|
|
@@ -52334,10 +52352,11 @@ function engineMemory(x) {
|
|
|
52334
52352
|
if (c && c.maxConcurrency >= 1) lo = mid;
|
|
52335
52353
|
else hi = mid - 1;
|
|
52336
52354
|
}
|
|
52355
|
+
const insideBand = likelyMore && perSeqBytes / GiB <= kvBudget * 1.1;
|
|
52337
52356
|
findings.push({
|
|
52338
52357
|
rule: "kv-under-one-sequence",
|
|
52339
52358
|
area: "memory",
|
|
52340
|
-
severity: "block",
|
|
52359
|
+
severity: insideBand ? "warn" : "block",
|
|
52341
52360
|
title: `One ${servedLen}-token request needs ${gib(perSeqBytes / GiB)} of KV per GPU; vLLM would have ${gib(kvBudget)}`,
|
|
52342
52361
|
detail: `Budget = ${budgetWord}; out of it ${reserveWord}. vLLM refuses at startup ("To serve at least one request with the model's max seq len (${servedLen}), (${(perSeqBytes / GiB).toFixed(2)} GiB KV cache is needed, which is larger than the available KV cache memory (${kvBudget.toFixed(2)} GiB). Based on the available memory, the estimated maximum model length is ${lo}.").`,
|
|
52343
52362
|
fix: `Serve at most ~${lo} tokens, raise --gpu-memory-utilization, use an fp8 KV cache (--kv-cache-dtype fp8), or raise TP.`,
|
|
@@ -52626,7 +52645,9 @@ function checkServeConfig(input) {
|
|
|
52626
52645
|
if (!lc && !givenVersion) defaultsAssumed.push(`${versionLabel} (no --${engine}-version given; the newest release the tables were read from)`);
|
|
52627
52646
|
const vllmDefaults = engine === "vllm" && card && ver ? vllmVersionDefaults(ver, card, pp) : null;
|
|
52628
52647
|
if (vllmDefaults) {
|
|
52629
|
-
|
|
52648
|
+
const sizedLater = vllmDefaults.extensibleKv && args.kvCacheMemoryBytes == null && !(args.flags ?? []).includes("--no-enable-extensible-kv-cache");
|
|
52649
|
+
if (args.gpuMemoryUtilization == null) defaultsAssumed.push(sizedLater ? `gpu_memory_utilization ${vllmDefaults.gpuMemoryUtilization}, the sizing before 0.34.0 (vLLM >= 0.34.0 defaults to 1.0 and sizes the KV cache after warmup; expect more than this estimate)` : `gpu_memory_utilization ${vllmDefaults.gpuMemoryUtilization} (vLLM ${vllmDefaults.gpuMemoryUtilization === 0.92 ? ">= 0.20.0" : "< 0.20.0"} default)`);
|
|
52650
|
+
if (args.blockSize == null && vllmDefaults.defaultBlockSize != null) defaultsAssumed.push(`block size ${vllmDefaults.defaultBlockSize} (vLLM >= 0.34.0 default; 16 before)`);
|
|
52630
52651
|
defaultsAssumed.push(`CUDA graph memory ${vllmDefaults.cudaGraphsCounted ? args.enforceEager ? "none (--enforce-eager)" : "taken from the KV budget (vLLM >= 0.20.0)" : "not taken from the KV budget (vLLM < 0.20.0)"}`);
|
|
52631
52652
|
if (args.maxNumBatchedTokens == null) defaultsAssumed.push(`max_num_batched_tokens ${vllmDefaults.maxNumBatchedTokens} (vllm serve default on ${card.label})`);
|
|
52632
52653
|
if (args.maxNumSeqs == null) defaultsAssumed.push(`max_num_seqs ${vllmDefaults.maxNumSeqs} (vllm serve default on ${card.label})`);
|
package/package.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "neurarch",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "The
|
|
3
|
+
"version": "0.5.0",
|
|
4
|
+
"description": "The release gate for the open-weight models you run yourself. Before a new base, launch config or chat template goes live, it checks that what you will serve is what you tested: every model your code pulls and what changed since your pin (`neurarch scan`), the prompt your engine sends against the reference (`neurarch template-check`), and whether a serving launch starts and fits the cards (`neurarch serve-check`). Also sizes a training job (peak memory, the smallest card, what a run costs) and checks a parallel layout (`neurarch layout`). Reads published files and your flags; runs nothing.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "SEE LICENSE IN LICENSE",
|
|
7
7
|
"author": "neurarch-ai",
|
|
8
|
-
"homepage": "https://neurarch.com
|
|
8
|
+
"homepage": "https://www.neurarch.com",
|
|
9
9
|
"repository": {
|
|
10
10
|
"type": "git",
|
|
11
11
|
"url": "git+https://github.com/neurarch-ai/neurarch.git"
|
|
@@ -29,16 +29,24 @@
|
|
|
29
29
|
"keywords": [
|
|
30
30
|
"architecture",
|
|
31
31
|
"capacity-planning",
|
|
32
|
+
"chat-template",
|
|
33
|
+
"cyclonedx",
|
|
32
34
|
"gpu",
|
|
33
35
|
"huggingface",
|
|
36
|
+
"llm",
|
|
34
37
|
"memory",
|
|
35
38
|
"ml",
|
|
39
|
+
"model-pinning",
|
|
36
40
|
"oom",
|
|
37
41
|
"parallelism",
|
|
38
42
|
"parameters",
|
|
39
43
|
"pytorch",
|
|
44
|
+
"release-gate",
|
|
40
45
|
"rightsizing",
|
|
46
|
+
"sbom",
|
|
41
47
|
"serving",
|
|
48
|
+
"sglang",
|
|
49
|
+
"supply-chain",
|
|
42
50
|
"training",
|
|
43
51
|
"transformers",
|
|
44
52
|
"vllm"
|