neurarch 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/neurarch.mjs CHANGED
@@ -12,6 +12,8 @@
12
12
  * npx neurarch Qwen/Qwen3-8B --lora-targets # which modules a LoRA can sit on
13
13
  * npx neurarch bert-base-uncased --seq-len 1024 --tokenizer-size 30524 # will this data crash it after it gets the GPU
14
14
  * npx neurarch rightsize jobs.csv # requested vs needed GPU over past jobs
15
+ * npx neurarch layout Qwen/Qwen3-8B --tp 4 --pp 4 --dp 8 --global-batch 512 --seq-len 4096 # is this parallel split legal and balanced
16
+ * npx neurarch serve-check Qwen/Qwen3-8B --gpu l4 --gpus 4 -- vllm serve Qwen/Qwen3-8B -tp 4 --max-model-len 32768 # will this serving launch start and hold what it promises
15
17
  *
16
18
  * The number this exists to print is the second one: parameters derived from
17
19
  * `config.json` alone, next to `safetensors.total` from the published
@@ -20,7 +22,7 @@
20
22
  *
21
23
  * Zero dependencies; the engine is bundled. Set HF_TOKEN for gated repos.
22
24
  */
23
- import { inspectHFModel, keyFor, AGREE_TOLERANCE, priceHFModel, parseHumanSize, PREFLIGHT_GPUS, specFromFlags, renderLoraText, rightsize, renderMarkdown, headline, applyPrices, DEFAULT_CARDS, oomReport, renderOomText, readAttention, attentionPhrase, readSeqLen, DEFAULT_SEQ_LEN, inferHFModel, readInferencePrecision, INFERENCE_PRECISIONS, DEFAULT_GEN_TOKENS, DEFAULT_INFERENCE_BATCH, CHANGE_HEADROOM, storedTwiceSentence, dataFitHFModel } from '../engine.bundle.mjs';
25
+ import { inspectHFModel, keyFor, AGREE_TOLERANCE, priceHFModel, parseHumanSize, PREFLIGHT_GPUS, specFromFlags, renderLoraText, rightsize, renderMarkdown, headline, applyPrices, DEFAULT_CARDS, oomReport, renderOomText, readAttention, attentionPhrase, readSeqLen, DEFAULT_SEQ_LEN, inferHFModel, readInferencePrecision, INFERENCE_PRECISIONS, DEFAULT_GEN_TOKENS, DEFAULT_INFERENCE_BATCH, CHANGE_HEADROOM, storedTwiceSentence, dataFitHFModel, layoutHFModel, readLayout, readHistogram, renderLayoutText, resolveLayoutGpu, serveCheckHFModel, parseServeCommand, readSampler, renderServeText, SERVE_ENGINES } from '../engine.bundle.mjs';
24
26
  /** The channel tag on every link this program prints. `docs/DISTRIBUTION.md`
25
27
  * has asked for one since the first release: without it a visit from a tool
26
28
  * and a visit from a search result are the same row, and "which channel brings
@@ -133,6 +135,187 @@ fragmentation or another process, not enough to say the job is too big.
133
135
  process.exit(r.diagnosis.message ? 0 : 1);
134
136
  }
135
137
 
138
+ // ── layout: is this parallel split legal, balanced, and worth running ────────
139
+ //
140
+ // TP / PP / DP (and CP / EP) for one model, checked before launch: legality,
141
+ // per-stage compute balance (the last stage carries the LM head and the loss),
142
+ // the pipeline bubble, per-stage memory, and, with a histogram, how uneven
143
+ // sequence lengths stall the DP ranks. Every number is derived from the graph;
144
+ // the check is src/utils/parallelLayout.ts through the bundle.
145
+ if (args[0] === 'layout') {
146
+ const rest = args.slice(1);
147
+ const L = {};
148
+ const pos = [];
149
+ const VAL = ['tp', 'pp', 'dp', 'cp', 'ep', 'gpus', 'gpu', 'micro', 'global-batch', 'grad-accum', 'seq-len', 'schedule', 'virtual', 'layers', 'zero', 'seq-hist'];
150
+ for (let i = 0; i < rest.length; i++) {
151
+ const a = rest[i];
152
+ const eq = /^--([a-z-]+)=(.*)$/.exec(a);
153
+ if (eq && VAL.includes(eq[1])) { L[eq[1]] = eq[2]; continue; }
154
+ if (a.startsWith('--') && VAL.includes(a.slice(2))) { L[a.slice(2)] = rest[++i]; continue; }
155
+ if (a === '--json') { L.json = true; continue; }
156
+ if (a === '--fsdp') { L.fsdp = true; continue; }
157
+ if (a === '--recompute' || a === '--activation-checkpointing') { L.recompute = true; continue; }
158
+ if (a === '--embedding-as-layer') { L.embLayer = true; continue; }
159
+ if (a === '--loss-as-layer') { L.lossLayer = true; continue; }
160
+ if (a === '--fused-ce') { L.fusedCe = true; continue; }
161
+ if (a === '-h' || a === '--help') { L.help = true; continue; }
162
+ pos.push(a);
163
+ }
164
+ if (L.help || pos.length !== 1) {
165
+ process.stdout.write(`neurarch layout: is this way of splitting the job across GPUs legal, balanced, and worth running
166
+
167
+ npx neurarch layout <hf-id | graph.json> --tp 4 --pp 4 --dp 8 --micro 1 --global-batch 512 --seq-len 4096
168
+ [--gpu h100] [--gpus 128] [--cp 2] [--ep 8] [--grad-accum 64]
169
+ [--schedule 1f1b|interleaved --virtual 2] [--layers 7,8,8,9]
170
+ [--zero 0|1|2|3 | --fsdp] [--recompute] [--embedding-as-layer] [--loss-as-layer] [--fused-ce]
171
+ [--seq-hist hist.csv] [--json]
172
+
173
+ Checks: world size and TP / EP / CP divisibility (block), per-stage balance
174
+ with a rebalanced --layers, the pipeline bubble, per-stage memory on the card,
175
+ and with --seq-hist (CSV of len,count) how much the slowest DP rank waits on
176
+ uneven sequence lengths. Stage time is predicted, not timed: matmul FLOPs at
177
+ 40% of the card's peak plus memory-bound bytes (norms, elementwise, the fp32
178
+ loss) at 80% of its bandwidth; step time is m x slowest stage + the fill and
179
+ drain, at your microbatch count. --fused-ce says the loss never holds fp32
180
+ logits (Liger, chunked CE). Exits 1 when a check blocks.
181
+ `);
182
+ process.exit(L.help ? 0 : 2);
183
+ }
184
+ const raw = {
185
+ tp: L.tp, pp: L.pp, dp: L.dp, cp: L.cp, ep: L.ep, num_gpus: L.gpus, gpu: L.gpu,
186
+ micro_batch: L.micro ?? 1, global_batch: L['global-batch'], grad_accum: L['grad-accum'],
187
+ seq_len: L['seq-len'] ?? DEFAULT_SEQ_LEN, schedule: L.schedule, virtual_stages: L.virtual,
188
+ layers_per_stage: L.layers, zero_stage: L.zero,
189
+ ...(L.fsdp ? { fsdp: true } : {}), ...(L.recompute ? { activation_checkpointing: true } : {}),
190
+ ...(L.embLayer ? { embedding_on_first: false } : {}), ...(L.lossLayer ? { head_on_last: false } : {}),
191
+ ...(L.fusedCe ? { fused_cross_entropy: true } : {}),
192
+ };
193
+ for (const k of Object.keys(raw)) if (raw[k] == null) delete raw[k];
194
+ const layout = readLayout(raw);
195
+ if (layout.error) {
196
+ const FLAG = { micro_batch: 'micro', num_gpus: 'gpus', virtual_stages: 'virtual', layers_per_stage: 'layers', zero_stage: 'zero' };
197
+ process.stderr.write(`${red('bad flag')}: ${layout.error.replace(/`layout\.([a-z_]+)`/, (_, n) => `--${FLAG[n] ?? n.replace(/_/g, '-')}`)}\n`);
198
+ process.exit(2);
199
+ }
200
+ if (L.gpu != null && !resolveLayoutGpu(L.gpu)) {
201
+ process.stderr.write(`${red('unknown --gpu')} ${L.gpu}: give a card id or an unambiguous prefix (h100, h200, b200, a100-80g, a100-40g, l40s, ...)\n`);
202
+ process.exit(2);
203
+ }
204
+ if (L['seq-hist']) {
205
+ const { readFile } = await import('node:fs/promises');
206
+ let text;
207
+ try { text = await readFile(L['seq-hist'], 'utf8'); } catch (e) {
208
+ process.stderr.write(`${red('cannot read')} --seq-hist ${L['seq-hist']}: ${e.message}\n`);
209
+ process.exit(2);
210
+ }
211
+ const h = readHistogram(text);
212
+ if (h.error) { process.stderr.write(`${red('--seq-hist')} ${h.error}\n`); process.exit(2); }
213
+ layout.seqLenHistogram = h.histogram;
214
+ }
215
+ const r = await layoutHFModel(pos[0], layout);
216
+ if (r.error) { process.stderr.write(`${red('cannot read')} ${pos[0]}: ${r.error}\n`); process.exit(2); }
217
+ const blocked = r.report.findings.some((f) => f.severity === 'block');
218
+ if (L.json) {
219
+ process.stdout.write(JSON.stringify({ model: pos[0], layout, ...r.report }, null, 2) + '\n');
220
+ } else {
221
+ const text = renderLayoutText(r.report, r.name)
222
+ .replace(/^ {2}block (.*)$/gm, (_, t) => ` ${red('block')} ${bold(t)}`)
223
+ .replace(/^ {2}warn {2}(.*)$/gm, (_, t) => ` ${yellow('warn ')} ${t}`)
224
+ .replace(/ NO$/gm, ` ${red('NO')}`);
225
+ process.stdout.write(text);
226
+ }
227
+ process.exit(blocked ? 1 : 0);
228
+ }
229
+
230
+ // ── serve-check: will this vLLM / SGLang / llama.cpp launch start ────────────
231
+ //
232
+ // Reads the launch command (after `--`, or --cmd "<string>"), the model's
233
+ // config.json, tokenizer_config.json, chat_template.jinja and
234
+ // generation_config.json from the Hub, and the card. The check is
235
+ // src/utils/serveConfigCheck.ts through the bundle.
236
+ if (args[0] === 'serve-check') {
237
+ const dd = args.indexOf('--', 1);
238
+ const rest = dd >= 0 ? args.slice(1, dd) : args.slice(1);
239
+ const after = dd >= 0 ? args.slice(dd + 1) : null;
240
+ const S = {};
241
+ const pos = [];
242
+ const VAL = ['engine', 'gpu', 'gpus', 'cmd', 'against', 'sampler'];
243
+ for (let i = 0; i < rest.length; i++) {
244
+ const a = rest[i];
245
+ const eq = /^--([a-z-]+)=(.*)$/.exec(a);
246
+ if (eq && VAL.includes(eq[1])) { S[eq[1]] = eq[2]; continue; }
247
+ if (a.startsWith('--') && VAL.includes(a.slice(2))) { S[a.slice(2)] = rest[++i]; continue; }
248
+ if (a === '--json') { S.json = true; continue; }
249
+ if (a === '-h' || a === '--help') { S.help = true; continue; }
250
+ pos.push(a);
251
+ }
252
+ const cmd = after && after.length ? after : S.cmd;
253
+ if (S.help || !cmd) {
254
+ process.stdout.write(`neurarch serve-check: will this serving launch start, hold what it promises, and serve the model as published
255
+
256
+ npx neurarch serve-check <hf-id | graph.json> [--engine vllm|sglang|llamacpp] --gpu h100 [--gpus 4]
257
+ [--against <old-hf-id>] [--sampler temperature=0.7,top_p=0.8] [--json] -- <launch command>
258
+ npx neurarch serve-check <hf-id> --gpu l4 --cmd "vllm serve Qwen/Qwen3-8B -tp 4 --max-model-len 32768"
259
+
260
+ The launch command is the one you would run: vllm serve ..., python -m
261
+ sglang.launch_server ..., or llama-server -m x.gguf .... The model id is
262
+ optional when the command names a Hugging Face repo (vLLM / SGLang); for
263
+ llama.cpp give the original repo id, since a .gguf file carries no config.json.
264
+
265
+ Checks: TP / PP / DP / EP legality against the heads, KV heads, FFN and expert
266
+ widths and the GPU count; the served length against max_position_embeddings and
267
+ rope_scaling; weights plus KV cache per GPU against the card and the engine's
268
+ memory fraction, and how many full-length sequences fit; dtype and quant method
269
+ against the card's compute capability; the chat template, tool and reasoning
270
+ parsers, and sampler defaults against generation_config.json. --against diffs
271
+ the config of the model being replaced. Everything is derived from files, not
272
+ measured; template checks do not render a conversation. Exits 1 when a check
273
+ blocks.
274
+ `);
275
+ process.exit(S.help ? 0 : 2);
276
+ }
277
+ const parsed = parseServeCommand(cmd, S.engine ? (S.engine === 'llama.cpp' ? 'llamacpp' : S.engine) : undefined);
278
+ if (S.engine && !SERVE_ENGINES.includes(S.engine === 'llama.cpp' ? 'llamacpp' : S.engine)) {
279
+ process.stderr.write(`${red('unknown --engine')} ${S.engine}. One of: ${SERVE_ENGINES.join(', ')}\n`);
280
+ process.exit(2);
281
+ }
282
+ if (!parsed.engine) {
283
+ process.stderr.write(`${red('cannot tell the engine')} from the command; pass --engine vllm|sglang|llamacpp\n`);
284
+ process.exit(2);
285
+ }
286
+ const ref = pos[0] ?? (parsed.engine !== 'llamacpp' && parsed.args.model && /^[\w.-]+\/[\w.-]+$/.test(parsed.args.model) ? parsed.args.model : null);
287
+ if (!ref) {
288
+ process.stderr.write(`${red('no model')}: give the Hugging Face id (or graph.json) before the flags${parsed.engine === 'llamacpp' ? '; a .gguf file carries no config.json, so name the repo it was converted from' : ''}\n`);
289
+ process.exit(2);
290
+ }
291
+ if (S.gpu != null && !resolveLayoutGpu(S.gpu)) {
292
+ process.stderr.write(`${red('unknown --gpu')} ${S.gpu}: give a card id or an unambiguous prefix (h100, h200, b200, a100-80g, a100-40g, l40s, l4, a10g, t4, v100, ...)\n`);
293
+ process.exit(2);
294
+ }
295
+ const gpus = S.gpus != null ? Number(S.gpus) : undefined;
296
+ if (gpus != null && !(Number.isInteger(gpus) && gpus > 0)) { process.stderr.write(`${red('--gpus')} must be a positive integer\n`); process.exit(2); }
297
+ let sampler;
298
+ if (S.sampler) {
299
+ const o = {};
300
+ for (const part of String(S.sampler).split(',')) { const [k, v] = part.split('='); if (k && v != null) o[k.trim()] = v.trim(); }
301
+ sampler = readSampler(o);
302
+ }
303
+ const r = await serveCheckHFModel(ref, { engine: parsed.engine, args: parsed.args, gpu: S.gpu, gpus, sampler, against: S.against });
304
+ if (r.error) { process.stderr.write(`${red('cannot read')} ${ref}: ${r.error}\n`); process.exit(2); }
305
+ const blocked = r.report.findings.some((f) => f.severity === 'block');
306
+ if (S.json) {
307
+ process.stdout.write(JSON.stringify({ model: ref, command: Array.isArray(cmd) ? cmd.join(' ') : cmd, ignoredFlags: parsed.ignored, ...r.report }, null, 2) + '\n');
308
+ } else {
309
+ let text = renderServeText(r.report, r.name)
310
+ .replace(/^ {2}block (.*)$/gm, (_, t) => ` ${red('block')} ${bold(t)}`)
311
+ .replace(/^ {2}warn {2}(.*)$/gm, (_, t) => ` ${yellow('warn ')} ${t}`)
312
+ .replace(/^ {2}info {2}(.*)$/gm, (_, t) => ` ${dim('info ')} ${t}`);
313
+ if (parsed.ignored.length) text += ` ${dim(`flags not read by this check: ${parsed.ignored.join(' ')}`)}\n\n`;
314
+ process.stdout.write(text);
315
+ }
316
+ process.exit(blocked ? 1 : 0);
317
+ }
318
+
136
319
  // ── rightsize: requested vs needed over a team's past jobs ──────────────────
137
320
  //
138
321
  // A subcommand rather than a flag, because its input is a CSV of jobs and not
@@ -215,8 +398,12 @@ if (flags.has('-h') || flags.has('--help') || positional.length === 0) {
215
398
  process.stdout.write(`neurarch: what a GPU job needs before it takes a reservation
216
399
 
217
400
  npx neurarch rightsize <jobs.csv> requested vs needed GPU over your past jobs (--help for the CSV)
401
+ npx neurarch layout <model-id> --tp 4 --pp 4 --dp 8 --global-batch 512 --seq-len 4096
402
+ is this TP/PP/DP split legal, balanced, and worth running (--help)
218
403
  npx neurarch oom <error.txt> --model <id> --batch N
219
404
  why a job ran out of GPU memory, and the least invasive fix
405
+ npx neurarch serve-check <model-id> --gpu l4 --gpus 4 -- vllm serve <model-id> -tp 4 --max-model-len 32768
406
+ will this vLLM / SGLang / llama.cpp launch start and hold what it promises (--help)
220
407
 
221
408
  npx neurarch <model-id> e.g. Qwen/Qwen3-8B, bert-base-uncased
222
409
  npx neurarch <model-id> --json machine-readable
@@ -492,7 +679,9 @@ if (inference) {
492
679
  process.stderr.write(`\n ${red('cannot size')} inference for ${modelId}: no weights read from the config\n`);
493
680
  process.exit(1);
494
681
  }
495
- const fits = ip.fits.map((g) => (g.fits ? green(gpuSlug(g.gpu)) : red(gpuSlug(g.gpu)))).join(' ');
682
+ // The words carry the answer and the colour only repeats it: piped into a
683
+ // file or a CI log (NO_COLOR, no TTY) a bare card name read as "fits" for every card.
684
+ const fits = ip.fits.map((g) => (g.fits ? green(`${gpuSlug(g.gpu)} yes`) : red(`${gpuSlug(g.gpu)} no`))).join(' ');
496
685
  process.stdout.write(`\n ${bold('inference memory')} ${dim(`batch ${ip.batch}, ${ip.promptTokens} prompt + ${ip.genTokens} generated tokens, ${ip.precision} weights`)}\n`);
497
686
  process.stdout.write(` ${dim('weights ')} ${ip.weightsGb.toFixed(1)} GB\n`);
498
687
  process.stdout.write(` ${dim('KV cache ')} ${ip.kvGb.toFixed(1)} GB ${dim(`(${(ip.kvBytesPerToken / 1024).toFixed(0)} KiB per token x ${ip.promptTokens + ip.genTokens} tokens x batch ${ip.batch})`)}\n`);