-
Notifications
You must be signed in to change notification settings - Fork 3k
Expand file tree
/
Copy pathvllm.ts
More file actions
2318 lines (2194 loc) · 82.9 KB
/
Copy pathvllm.ts
File metadata and controls
2318 lines (2194 loc) · 82.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// vLLM container actions invoked from onboard.ts. Detection of "should we
// offer vLLM at all" lives in onboard.ts; this module owns picking the
// right profile per platform and running the install.
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { isDeepStrictEqual } from "node:util";
import {
dockerCapture,
dockerForceRm,
dockerImageInspectFormat,
dockerPullWithProgressWatchdog,
dockerRunDetached,
dockerSpawn,
dockerStop,
} from "../adapters/docker";
import { createBearerAuthConfig } from "../adapters/http/auth-config";
import { buildValidatedCurlCommandArgs } from "../adapters/http/curl-args";
import { runCurlProbe } from "../adapters/http/probe";
import { CLI_NAME } from "../cli/branding";
import { warnLine } from "../cli/terminal-style";
import { markPhaseActivity } from "../core/phase-activity";
import { VLLM_PORT } from "../core/vllm-port";
import { shellQuote } from "../core/shell-quote";
import { isAffirmativeAnswer } from "../onboard/prompt-helpers";
import { runCapture } from "../runner";
import { isSafeModelId } from "../validation";
import {
acquireHuggingFaceModel,
hfDownloadAuthentication,
} from "./model-acquisition/hugging-face";
import { getGpuIndicesByName } from "./nim";
import {
buildLocalDualStationDockerEnv,
buildLocalManagedVllmDockerEnv,
buildRemoteVllmDockerEnv,
buildVllmDockerEnv,
captureNvidiaSmi,
ensureDualStationVllmApiKey,
loadDualStationVllmApiKey,
type MaterializedHostLocalVllmSelection,
persistHostLocalVllmRuntimeReceipt,
recoverHostLocalManagedVllmEndpoint,
recoverInstalledManagedClusterVllmEndpoint,
resolveHostLocalVllmSelection,
resolveManagedVllmBridgeHost,
resolveNvidiaSmiCommand,
resolveVllmInstallModel,
runtimeAuthFingerprint,
tryInstallManagedClusterManagedVllm,
validateManagedVllmBridgeHost,
} from "./serving/vllm-managed-support";
import {
assertGatedModelAccess,
buildVllmServeCommand,
defaultVllmModelForPlatform,
defaultVllmRuntimeForPlatform,
STATION_PAIR_OPTIONAL_ORCHESTRATION,
parseVllmExtraServeArgs,
VLLM_EXTRA_ARGS_ENV,
VLLM_MODELS,
vllmModelForOrchestration,
vllmModelUsesOrchestration,
vllmPlatformSpecificity,
type VllmModelDef,
type VllmPlatform,
type VllmRuntimeOverride,
type VllmRuntimeVariant,
} from "./vllm-models";
import {
type DualStationVllmPlan,
NEMOCLAW_DGX_STATION_PEER_ENV,
probeDualStationVllmCapability,
} from "./vllm-station-cluster";
import type { ManagedInferenceReadinessSource } from "./serving/types";
import {
areDualStationManagedVllmContainersRunning,
cleanupDualStationManagedVllm,
commitDualStationLegacyMigration,
DUAL_STATION_VLLM_CLUSTER_LABEL,
DUAL_STATION_VLLM_ENDPOINT_LABEL,
DUAL_STATION_VLLM_ROLE_LABEL,
getDualStationManagedVllmBaseUrl,
preflightDualStationGpuRuntime,
preflightDualStationManagedVllm,
rollbackDualStationLegacyMigration,
startDualStationManagedVllm,
withDualStationManagedVllmLifecycle,
} from "./vllm-station-cluster-lifecycle";
import { stageDualStationModelSnapshot } from "./vllm-station-model-staging";
import {
persistDualStationVllmRuntimeReceipt,
recoverInstalledDualStationVllmRuntime,
} from "./vllm-station-runtime-receipt";
import {
findUnwritableModelCachePath,
formatStorageBytes,
formatStorageDecimalBytes,
imageStorageRequirementBytes,
managedVllmStorageEstimateBytes,
measureDirectorySizeBytes,
probeDockerStorage,
probeHostStorage,
type StorageCapacity,
type StorageProbeResult,
} from "./vllm-storage";
// Per-platform install recipe. Add new platforms by appending an entry to
// the profile table at the bottom of this file. The menu key in onboard.ts
// stays "install-vllm" regardless of platform.
export interface VllmProfile {
name: string; // human label, e.g. "DGX Spark"
// Platform key matched against `VllmModelDef.platforms` when the picker
// filters the registry. Decoupled from `name` so future user-facing label
// tweaks don't change which models are offered.
platform: VllmPlatform;
/** Qualified host architecture for this platform profile. */
architecture?: NodeJS.Architecture;
image: string; // platform-specific image pinned by digest
// Compressed size of that exact platform manifest. The storage preflight
// adds unpacking and pull-staging headroom.
imageDownloadSizeBytes: number;
// Pre-calculated unpacked layer size for this exact digest when available.
imageUnpackedSizeBytes?: number;
// Default model when NEMOCLAW_VLLM_MODEL is unset. Per-platform default
// because Spark/Station can host larger recipes, but generic discrete-GPU
// Linux falls back to the small Nemotron-Nano-4B that fits on consumer
// cards.
defaultModel: VllmModelDef;
containerName: string;
// docker run flags excluding the image and the entrypoint command. The
// caller appends -p / --name / etc. that are not platform-specific.
dockerRunFlags: string[];
// Optional dynamic flag builder. When present, its return value replaces
// dockerRunFlags at install time. Used by Station to pick the GB300 GPU
// out of a mixed-GPU host instead of using `--gpus all`.
buildDockerRunFlags?: () => string[];
// Maximum wall-clock safety budget for image pulls. The Docker adapter uses
// a shorter progress watchdog for stalls, so slow-but-moving pulls can keep
// going until this last-ditch cap.
pullTimeoutSec: number;
// Wall-clock budget for the load phase (after pull, before ready).
loadTimeoutSec: number;
// Optional pinned model snapshot size. Model-specific runtime overrides use
// this to guard the host Hugging Face cache before a cold download.
modelDownloadSizeBytes?: number;
/** GPU floor selected by a compatibility-qualified model runtime. */
minComputeCapability?: number;
/** Minimum GPU or unified-memory capacity selected by the runtime recipe. */
minGpuMemoryBytes?: number;
servingCatalog?: {
catalogDigest: string;
presetId: string;
presetDigest: string;
recipeId: string;
recipeDigest: string;
};
}
const VLLM_WRITABLE_ALLOWANCE_BYTES = 816_000_000;
// Compatibility export for image-boundary checks. Runtime image identity and
// size are owned by catalog recipes, including optional orchestration images.
export const VLLM_IMAGES = {
catalog: Object.fromEntries(
VLLM_MODELS.flatMap((model) =>
(model.runtimeVariants ?? []).flatMap((runtime, index) => [
[
`${model.envValue}-${String(index)}`,
{ ref: runtime.image, downloadSizeBytes: runtime.imageDownloadSizeBytes },
],
...(runtime.stationPair
? [
[
`${model.envValue}-${String(index)}-station-pair`,
{
ref: runtime.stationPair.image,
downloadSizeBytes: runtime.stationPair.imageDownloadSizeBytes,
},
],
]
: []),
]),
),
),
} as const;
const HF_TOKEN_SETTINGS_URL = "https://huggingface.co/settings/tokens";
const VLLM_LAUNCH_HEARTBEAT_MS = 30_000;
const VLLM_MAX_STARTUP_RESTARTS = 3;
const HF_CACHE_CONTAINER_DIR = "/root/.cache/huggingface";
const HF_CACHE_COMPONENT_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
export const NEMOCLAW_VLLM_CONTAINER_NAME = "nemoclaw-vllm";
export const NEMOCLAW_VLLM_MANAGED_LABEL = "com.nvidia.nemoclaw.managed-vllm";
export const NEMOCLAW_VLLM_HOST_LOCAL_AUTH_LABEL = "com.nvidia.nemoclaw.managed-vllm-auth";
const DOCKER_CONTAINER_ID_PATTERN = /^[a-f0-9]{12,64}$/;
function hostHfCacheDir(): string {
return path.join(os.homedir(), ".cache", "huggingface");
}
function hfCacheMount(): string {
return `${hostHfCacheDir()}:${HF_CACHE_CONTAINER_DIR}`;
}
function hfModelCacheKey(model: VllmModelDef): string | null {
const modelParts = model.id.split("/");
if (modelParts.some((part) => !HF_CACHE_COMPONENT_PATTERN.test(part))) return null;
return `models--${modelParts.join("--")}`;
}
export function hfModelSnapshotDir(model: VllmModelDef): string | null {
const revision = model.revision;
const modelCacheKey = hfModelCacheKey(model);
if (!revision || !modelCacheKey || !HF_CACHE_COMPONENT_PATTERN.test(revision)) {
return null;
}
return path.join(hostHfCacheDir(), "hub", modelCacheKey, "snapshots", revision);
}
function hfModelCacheDir(model: VllmModelDef): string | null {
const modelParts = model.id.split("/");
if (modelParts.some((part) => !HF_CACHE_COMPONENT_PATTERN.test(part))) {
return null;
}
return path.join(hostHfCacheDir(), "hub", `models--${modelParts.join("--")}`);
}
function hostUserIdentity(): string | null {
if (typeof process.getuid !== "function" || typeof process.getgid !== "function") return null;
return `${String(process.getuid())}:${String(process.getgid())}`;
}
function vllmDockerRunFlags(gpuFlag = "all"): string[] {
return [
"--gpus",
gpuFlag,
"--ipc=host",
"-v",
hfCacheMount(),
"-e",
`HF_HOME=${HF_CACHE_CONTAINER_DIR}`,
];
}
function printHfDownloadAuthentication(nonInteractive: boolean): void {
const authentication = hfDownloadAuthentication();
if (authentication.authenticated) {
console.log(` Hugging Face download: authenticated with ${authentication.source}.`);
console.log(
" The token value is not displayed and is passed only to the temporary downloader.",
);
return;
}
if (nonInteractive) {
console.log(" Hugging Face download: continuing anonymously for this public model.");
console.log(" For large downloads, a read token reduces anonymous HTTP 429 rate limiting.");
console.log(` Create one at ${HF_TOKEN_SETTINGS_URL}.`);
console.log(" Before restarting onboarding, run: export HF_TOKEN=<read-token>");
return;
}
console.log(" Hugging Face authentication is optional for this public model but recommended");
console.log(
" for this large download. Anonymous downloads may be rate-limited with HTTP 429.",
);
console.log(` Create a read token at ${HF_TOKEN_SETTINGS_URL}.`);
console.log(" Before restarting onboarding, run: export HF_TOKEN=<read-token>");
console.log(" The token is passed only to the temporary model downloader.");
}
function printHfRateLimitRecovery(): void {
process.stderr.write(" Hugging Face rate limiting was detected.\n");
process.stderr.write(` Create a read token at ${HF_TOKEN_SETTINGS_URL}.\n`);
process.stderr.write(" In your shell, run: export HF_TOKEN=<read-token>\n");
process.stderr.write(` Then run: ${CLI_NAME} onboard --resume\n`);
process.stderr.write(
" Existing files in ~/.cache/huggingface are reused when the download resumes.\n",
);
}
const sparkDefaultRuntime = defaultVllmRuntimeForPlatform("spark", "arm64");
const SPARK_PROFILE: VllmProfile = {
name: "DGX Spark",
platform: "spark",
architecture: "arm64",
image: sparkDefaultRuntime.image,
imageDownloadSizeBytes: sparkDefaultRuntime.imageDownloadSizeBytes,
imageUnpackedSizeBytes: sparkDefaultRuntime.imageUnpackedSizeBytes,
defaultModel: defaultVllmModelForPlatform("spark", "arm64"),
containerName: NEMOCLAW_VLLM_CONTAINER_NAME,
dockerRunFlags: vllmDockerRunFlags(),
pullTimeoutSec: 12 * 60 * 60,
loadTimeoutSec: 1800,
};
const n1xDefaultRuntime = defaultVllmRuntimeForPlatform("n1x", "arm64");
const N1X_PROFILE: VllmProfile = {
name: "N1x",
platform: "n1x",
architecture: "arm64",
image: n1xDefaultRuntime.image,
imageDownloadSizeBytes: n1xDefaultRuntime.imageDownloadSizeBytes,
imageUnpackedSizeBytes: n1xDefaultRuntime.imageUnpackedSizeBytes,
defaultModel: defaultVllmModelForPlatform("n1x", "arm64"),
containerName: NEMOCLAW_VLLM_CONTAINER_NAME,
dockerRunFlags: SPARK_PROFILE.dockerRunFlags,
pullTimeoutSec: SPARK_PROFILE.pullTimeoutSec,
loadTimeoutSec: SPARK_PROFILE.loadTimeoutSec,
};
// DGX Station.
const stationDefaultRuntime = defaultVllmRuntimeForPlatform("station", "arm64");
const STATION_PROFILE: VllmProfile = {
name: "DGX Station",
platform: "station",
architecture: "arm64",
image: stationDefaultRuntime.image,
imageDownloadSizeBytes: stationDefaultRuntime.imageDownloadSizeBytes,
imageUnpackedSizeBytes: stationDefaultRuntime.imageUnpackedSizeBytes,
defaultModel: defaultVllmModelForPlatform("station", "arm64"),
containerName: NEMOCLAW_VLLM_CONTAINER_NAME,
dockerRunFlags: SPARK_PROFILE.dockerRunFlags,
buildDockerRunFlags: () => {
const indices = getGpuIndicesByName(/GB300/i);
if (indices.length === 0) {
throw new Error(
"DGX Station managed vLLM requires an NVIDIA GB300 GPU, but none was detected",
);
}
// Docker parses --gpus as CSV, so multi-device values must retain
// double quotes inside the argv token to keep the comma in one field.
const gpuFlag = indices.length === 1 ? `device=${indices[0]}` : `"device=${indices.join(",")}"`;
return vllmDockerRunFlags(gpuFlag);
},
pullTimeoutSec: SPARK_PROFILE.pullTimeoutSec,
loadTimeoutSec: SPARK_PROFILE.loadTimeoutSec,
};
// Generic discrete-GPU Linux. Uses a small nemotron model that fits on
// most GPUs.
const genericLinuxRuntime =
process.arch === "arm64" || process.arch === "x64"
? defaultVllmRuntimeForPlatform("linux", process.arch)
: null;
const GENERIC_LINUX_PROFILE: VllmProfile | null = genericLinuxRuntime
? {
name: "Linux + NVIDIA GPU",
platform: "linux",
architecture: process.arch,
image: genericLinuxRuntime.image,
imageDownloadSizeBytes: genericLinuxRuntime.imageDownloadSizeBytes,
imageUnpackedSizeBytes: genericLinuxRuntime.imageUnpackedSizeBytes,
defaultModel: defaultVllmModelForPlatform("linux", process.arch),
containerName: NEMOCLAW_VLLM_CONTAINER_NAME,
dockerRunFlags: SPARK_PROFILE.dockerRunFlags,
pullTimeoutSec: SPARK_PROFILE.pullTimeoutSec,
loadTimeoutSec: SPARK_PROFILE.loadTimeoutSec,
}
: null;
export function detectVllmProfile(
gpu:
| {
spark?: boolean;
type?: string;
platform?: "spark" | "station" | "n1x" | "linux";
}
| null
| undefined,
): VllmProfile | null {
if (gpu?.platform === "spark") return SPARK_PROFILE;
if (gpu?.platform === "station") return STATION_PROFILE;
if (gpu?.platform === "n1x") return N1X_PROFILE;
if (gpu?.spark) return SPARK_PROFILE;
if (gpu?.type === "nvidia") return GENERIC_LINUX_PROFILE;
return null;
}
function emit(line: string): void {
process.stdout.write(` ==> ${line}\n`);
}
function formatElapsed(ms: number): string {
const totalSeconds = Math.max(0, Math.floor(ms / 1000));
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
if (minutes === 0) return `${String(seconds)}s`;
return `${String(minutes)}m ${String(seconds)}s`;
}
function dockerPrereqsOk(): { ok: boolean; reason?: string } {
if (!runCapture(["sh", "-c", "command -v docker"], { ignoreError: true }).trim()) {
return { ok: false, reason: "docker not found on PATH" };
}
if (!resolveNvidiaSmiCommand({ runCaptureImpl: runCapture })) {
return { ok: false, reason: "nvidia-smi not found — vLLM requires NVIDIA drivers" };
}
if (!runCapture(["sh", "-c", "command -v curl"], { ignoreError: true }).trim()) {
return { ok: false, reason: "curl not found on PATH — vLLM readiness checks require curl" };
}
return { ok: true };
}
export function readGpuComputeCapabilities(): number[] {
const out = captureNvidiaSmi(["--query-gpu=compute_cap", "--format=csv,noheader,nounits"], {
runCaptureImpl: runCapture,
});
if (!out) return [];
const capabilities: number[] = [];
for (const line of out.split("\n")) {
const trimmed = line.trim();
if (!trimmed) continue;
const match = /^(\d+)\.(\d+)$/.exec(trimmed);
if (!match) continue;
capabilities.push(Number(match[1]) * 10 + Number(match[2]));
}
return capabilities;
}
export function formatComputeCapability(capability: number): string {
return `${String(Math.floor(capability / 10))}.${String(capability % 10)}`;
}
export function computeCapabilityPreflight(
model: VllmModelDef,
capabilities: number[] = readGpuComputeCapabilities(),
runtimeMinimum: number | undefined = model.minComputeCapability,
): { ok: true } | { ok: false; reason: string } {
const required = runtimeMinimum;
if (required === undefined) return { ok: true };
if (capabilities.length === 0) return { ok: true };
const lowest = Math.min(...capabilities);
if (lowest >= required) return { ok: true };
return {
ok: false,
reason:
`${model.label} requires GPU compute capability ${formatComputeCapability(required)} or newer, ` +
`but this host reports ${formatComputeCapability(lowest)}. ` +
"Serve this model on a newer GPU, or select a compatible model with NEMOCLAW_VLLM_MODEL.",
};
}
export async function pullImage(
profile: VllmProfile,
dockerEnv: Record<string, string> = buildVllmDockerEnv(),
): Promise<{ ok: boolean; reason?: string }> {
try {
assertVllmRegistryDigestRef(profile.image);
} catch (err) {
return { ok: false, reason: (err as Error).message };
}
emit(`Pulling vLLM image: ${profile.image}`);
// Docker can be quiet while finalizing large layers on every supported vLLM
// profile, so all profiles intentionally share the 15-minute stall default.
// The profile-specific maximum still bounds the complete pull operation.
const result = await dockerPullWithProgressWatchdog(profile.image, {
env: dockerEnv,
maxTimeoutMs: profile.pullTimeoutSec * 1000,
logLine: emit,
});
if (result.status !== 0) {
if (result.timeoutKind === "stall") {
return { ok: false, reason: "docker pull stalled with no progress" };
}
if (result.timeoutKind === "max") {
return {
ok: false,
reason: `docker pull exceeded ${String(profile.pullTimeoutSec)}s safety budget`,
};
}
return { ok: false, reason: `docker pull failed (exit ${String(result.status)})` };
}
return { ok: true };
}
// Preserve the vLLM downloadModel API while acquireHuggingFaceModel runs `hf download`.
export function downloadModel(
profile: VllmProfile,
model: VllmModelDef,
dockerEnv: Record<string, string> = buildVllmDockerEnv(),
target: { hostCacheDir?: string; userIdentity?: string } = {},
): Promise<{ ok: boolean; reason?: string }> {
return acquireHuggingFaceModel(
{
dockerEnv,
downloaderImage: profile.image,
hostCacheDir: target.hostCacheDir ?? hostHfCacheDir(),
repository: model.id,
revision: model.revision,
spawnDocker: dockerSpawn,
userIdentity: target.userIdentity ?? hostUserIdentity(),
},
{ logLine: emit, onRateLimit: printHfRateLimitRecovery },
);
}
function validateDockerArg(value: string, label: string): string {
if (value.length === 0) {
throw new Error(`${label} must not be empty`);
}
if (value.includes("\0")) {
throw new Error(`${label} must not contain NUL bytes`);
}
return value;
}
function validateDockerArgs(args: readonly string[], label: string): string[] {
return args.map((arg, index) => validateDockerArg(String(arg), `${label}[${String(index)}]`));
}
// Build the `docker run` argv for the long-lived vLLM inference container.
// Exported for testing. `--init` forwards signals and reaps child processes so
// Docker can stop and restart the long-lived server cleanly. `--restart
// unless-stopped` brings it back after a host reboot or Docker daemon restart
// (#4886); without a restart policy the container stays down after a reboot and
// `nemoclaw inference get` fails until onboarding recreates it.
export function buildVllmRunArgs(
profile: VllmProfile,
model: VllmModelDef,
runFlags: readonly string[],
env: NodeJS.ProcessEnv = process.env,
managedBridgeHost?: string,
): string[] {
assertVllmRegistryDigestRef(profile.image);
const image = validateDockerArg(profile.image, "vLLM image");
const containerName = validateDockerArg(profile.containerName, "vLLM container name");
const safeRunFlags = validateDockerArgs(runFlags, "vLLM docker run flags");
const managedApiKey = model.managedBearerAuth ? String(env.VLLM_API_KEY ?? "") : "";
if (model.managedBearerAuth && !/^[a-f0-9]{64}$/.test(managedApiKey)) {
throw new Error("Managed host-local vLLM requires a valid host-global API key");
}
const managedPublishHost = model.managedBearerAuth
? validateManagedVllmBridgeHost(managedBridgeHost ?? "")
: null;
return [
"--pull=never",
"--init",
"--restart",
"unless-stopped",
...safeRunFlags,
"--label",
`${NEMOCLAW_VLLM_MANAGED_LABEL}=true`,
...(profile.servingCatalog
? [
"--label",
`com.nvidia.nemoclaw.serving-catalog-digest=${profile.servingCatalog.catalogDigest}`,
"--label",
`com.nvidia.nemoclaw.serving-preset=${profile.servingCatalog.presetId}`,
"--label",
`com.nvidia.nemoclaw.serving-preset-digest=${profile.servingCatalog.presetDigest}`,
"--label",
`com.nvidia.nemoclaw.serving-recipe=${profile.servingCatalog.recipeId}`,
"--label",
`com.nvidia.nemoclaw.serving-recipe-digest=${profile.servingCatalog.recipeDigest}`,
]
: []),
...(model.managedBearerAuth
? [
"--label",
`${NEMOCLAW_VLLM_HOST_LOCAL_AUTH_LABEL}=${runtimeAuthFingerprint(managedApiKey)}`,
"--env",
"VLLM_API_KEY",
]
: []),
"-p",
`${model.managedBearerAuth ? "127.0.0.1:" : ""}${String(VLLM_PORT)}:8000`,
...(model.managedBearerAuth ? ["-p", `${managedPublishHost}:${String(VLLM_PORT)}:8000`] : []),
"--name",
containerName,
"--entrypoint",
"/bin/bash",
image,
"-lc",
buildVllmServeCommand(model, env),
];
}
function selectedVllmRuntime(
profile: VllmProfile,
model: VllmModelDef,
architecture: NodeJS.Architecture = profile.architecture ?? process.arch,
): VllmRuntimeOverride | VllmRuntimeVariant | undefined {
const matchingVariants = (model.runtimeVariants ?? [])
.filter(
(candidate) =>
vllmPlatformSpecificity(candidate.platforms, profile.platform) >= 0 &&
(!candidate.architectures || candidate.architectures.includes(architecture)),
)
.sort(
(left, right) =>
vllmPlatformSpecificity(left.platforms, profile.platform) -
vllmPlatformSpecificity(right.platforms, profile.platform) ||
left.priority - right.priority ||
(left.catalogPresetId ?? "").localeCompare(right.catalogPresetId ?? ""),
);
const runtime = matchingVariants.at(-1) ?? model.runtime;
if (model.requireRuntimeVariant && !runtime) {
throw new Error(
`${model.label} has no managed vLLM runtime for ${profile.name} on ${architecture}.`,
);
}
return runtime;
}
function replaceCatalogGpuRequest(
profile: VllmProfile,
runtime: VllmRuntimeOverride,
extraRunArgs: string[],
): string[] {
if (runtime.dockerRunArgsMode !== "replace" || !profile.buildDockerRunFlags) {
return extraRunArgs;
}
if (!runtime.catalogPresetId) return extraRunArgs;
const platformFlags = profile.buildDockerRunFlags();
const platformGpuIndex = platformFlags.indexOf("--gpus");
const recipeGpuIndex = extraRunArgs.indexOf("--gpus");
if (
platformGpuIndex < 0 ||
platformGpuIndex === platformFlags.length - 1 ||
recipeGpuIndex < 0 ||
recipeGpuIndex === extraRunArgs.length - 1
) {
throw new Error(`${profile.name} did not produce one declarative GPU request.`);
}
const replaced = [...extraRunArgs];
replaced[recipeGpuIndex + 1] = platformFlags[platformGpuIndex + 1]!;
return replaced;
}
function applyVllmRuntimeProfile(
profile: VllmProfile,
model: VllmModelDef,
runtime: VllmRuntimeOverride | VllmRuntimeVariant | undefined,
): VllmProfile {
let resolved = profile;
if (runtime) {
const extraRunArgs = replaceCatalogGpuRequest(profile, runtime, [
...(runtime.dockerRunArgs ?? []),
]);
resolved = {
...profile,
image: runtime.image,
imageDownloadSizeBytes: runtime.imageDownloadSizeBytes,
imageUnpackedSizeBytes:
runtime.imageUnpackedSizeBytes ??
(runtime.image === profile.image ? profile.imageUnpackedSizeBytes : undefined),
modelDownloadSizeBytes: runtime.modelDownloadSizeBytes ?? profile.modelDownloadSizeBytes,
loadTimeoutSec: runtime.loadTimeoutSec ?? profile.loadTimeoutSec,
dockerRunFlags:
runtime.dockerRunArgsMode === "replace"
? extraRunArgs
: [...profile.dockerRunFlags, ...extraRunArgs],
buildDockerRunFlags:
runtime.dockerRunArgsMode === "replace"
? undefined
: profile.buildDockerRunFlags
? () => [...profile.buildDockerRunFlags!(), ...extraRunArgs]
: undefined,
pullTimeoutSec: runtime.pullTimeoutSec ?? profile.pullTimeoutSec,
minComputeCapability: runtime.minComputeCapability ?? model.minComputeCapability,
minGpuMemoryBytes: runtime.minGpuMemoryBytes,
servingCatalog: runtime.servingCatalog ?? profile.servingCatalog,
};
}
assertVllmRegistryDigestRef(resolved.image);
return resolved;
}
export function resolveVllmRuntimeProfile(
profile: VllmProfile,
model: VllmModelDef,
architecture: NodeJS.Architecture = profile.architecture ?? process.arch,
): VllmProfile {
return applyVllmRuntimeProfile(profile, model, selectedVllmRuntime(profile, model, architecture));
}
export function resolveVllmModelRuntime(
profile: VllmProfile,
model: VllmModelDef,
architecture: NodeJS.Architecture = profile.architecture ?? process.arch,
): { profile: VllmProfile; model: VllmModelDef } {
const runtime = selectedVllmRuntime(profile, model, architecture);
const resolvedProfile = applyVllmRuntimeProfile(profile, model, runtime);
if (!runtime || !("modelArgs" in runtime)) return { profile: resolvedProfile, model };
return {
profile: resolvedProfile,
model: {
...model,
maxModelLen: runtime.maxModelLen,
revision: runtime.revision,
servedModelId: runtime.servedModelId,
modelArgs: runtime.modelArgs,
serveEnv: runtime.serveEnv,
installFastSafetensors: runtime.installFastSafetensors,
fixedServeCommand: runtime.fixedServeCommand,
managedBearerAuth: runtime.managedBearerAuth,
trustRemoteCode: runtime.trustRemoteCode,
runtime,
},
};
}
const SHA256_IMAGE_DIGEST_PATTERN = /^sha256:[0-9a-f]{64}$/;
const IMAGE_REPOSITORY_COMPONENT_PATTERN = /^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;
/**
* Managed vLLM is a product install path, so every effective runtime must be
* downloadable by immutable registry digest. A bare Docker image/config ID
* only identifies bytes already present in one daemon and is never a valid
* product dependency.
*/
export function assertVllmRegistryDigestRef(image: string): void {
const separator = image.lastIndexOf("@");
const repository = separator > 0 ? image.slice(0, separator) : "";
const digest = separator > 0 ? image.slice(separator + 1) : "";
const components = repository.split("/");
const firstComponent = components[0] ?? "";
const portSeparator = firstComponent.lastIndexOf(":");
const registryOrNamespace =
portSeparator > 0 && /^\d+$/.test(firstComponent.slice(portSeparator + 1))
? firstComponent.slice(0, portSeparator)
: firstComponent;
const hasInvalidPort = firstComponent.includes(":") && registryOrNamespace === firstComponent;
const validRepository =
separator === image.indexOf("@") &&
components.length >= 2 &&
!hasInvalidPort &&
IMAGE_REPOSITORY_COMPONENT_PATTERN.test(registryOrNamespace) &&
components.slice(1).every((component) => IMAGE_REPOSITORY_COMPONENT_PATTERN.test(component));
if (!validRepository || !SHA256_IMAGE_DIGEST_PATTERN.test(digest)) {
throw new Error(
"vLLM image must be a pullable immutable registry reference in " +
`repository@sha256:<64 lowercase hex> form; got '${image}'. ` +
"Local image IDs and mutable tags are not supported.",
);
}
}
type VllmContainerOwnership =
| { kind: "absent" }
| { kind: "dual-managed"; containerId: string; running: boolean }
| { kind: "foreign" }
| { kind: "managed"; containerId: string; running: boolean }
| { kind: "unknown" };
function inspectVllmContainerOwnershipInDockerEnv(
containerName: string,
env: Record<string, string>,
): VllmContainerOwnership {
const format = [
"{{.ID}}",
"{{.Names}}",
"{{.State}}",
`{{.Label "${NEMOCLAW_VLLM_MANAGED_LABEL}"}}`,
`{{.Label "${DUAL_STATION_VLLM_ROLE_LABEL}"}}`,
`{{.Label "${DUAL_STATION_VLLM_ENDPOINT_LABEL}"}}`,
`{{.Label "${DUAL_STATION_VLLM_CLUSTER_LABEL}"}}`,
].join("|");
try {
const output = dockerCapture(
[
"container",
"ls",
"--all",
"--no-trunc",
"--filter",
`name=^/${containerName}$`,
"--format",
format,
],
{ env, timeout: 10_000 },
).trim();
if (!output) return { kind: "absent" };
const rows = output.split(/\r?\n/);
if (rows.length !== 1) return { kind: "unknown" };
const fields = rows[0].split("|");
if (fields.length !== 7) return { kind: "unknown" };
const [containerId, observedName, state, managedLabel, dualRole, dualEndpoint, dualCluster] =
fields;
if (observedName !== containerName || !DOCKER_CONTAINER_ID_PATTERN.test(containerId)) {
return { kind: "unknown" };
}
if (managedLabel !== "true") return { kind: "foreign" };
const hasAnyDualLabel = Boolean(dualRole || dualEndpoint || dualCluster);
if (hasAnyDualLabel) {
const exactDualHead =
dualRole === "head" &&
/^http:\/\/192\.168\.|^http:\/\/10\.|^http:\/\/172\.(?:1[6-9]|2[0-9]|3[01])\./.test(
dualEndpoint,
) &&
/^[a-f0-9]{64}$/.test(dualCluster);
return exactDualHead
? { kind: "dual-managed", containerId, running: state === "running" }
: { kind: "unknown" };
}
return { kind: "managed", containerId, running: state === "running" };
} catch {
return { kind: "unknown" };
}
}
function inspectVllmContainerOwnership(containerName: string): VllmContainerOwnership {
// A managed dual-Station head always lives on the physical host's default
// daemon. Inspect it before following ambient single-host Docker routing so
// DOCKER_HOST, DOCKER_CONTEXT, or Docker's persisted currentContext cannot
// hide the pair from running-state detection or replacement guards.
const canonicalOwnership = inspectVllmContainerOwnershipInDockerEnv(
containerName,
buildLocalDualStationDockerEnv(),
);
if (canonicalOwnership.kind === "dual-managed" || canonicalOwnership.kind === "unknown") {
return canonicalOwnership;
}
return inspectVllmContainerOwnershipInDockerEnv(containerName, buildVllmDockerEnv());
}
function vllmContainerReplacementTarget(
containerName: string,
dockerEnv?: Record<string, string>,
expectedContainerId?: string,
): { ok: true; containerId?: string } | { ok: false; reason: string } {
const ownership = dockerEnv
? inspectVllmContainerOwnershipInDockerEnv(containerName, dockerEnv)
: inspectVllmContainerOwnership(containerName);
if (ownership.kind === "foreign") {
return {
ok: false,
reason: `Container "${containerName}" already exists without the NemoClaw ownership label. NemoClaw will not remove it. Remove or rename that container, then retry managed vLLM installation.`,
};
}
if (ownership.kind === "unknown") {
return {
ok: false,
reason: `Could not verify ownership of Docker container "${containerName}". NemoClaw will not remove it. Check Docker access and retry.`,
};
}
if (ownership.kind === "dual-managed") {
return {
ok: false,
reason:
`Container "${containerName}" is the head of a managed dual-Station deployment. ` +
`Refusing single-host replacement because it would orphan the peer worker. Restore ${NEMOCLAW_DGX_STATION_PEER_ENV} and select Nemotron Ultra to manage the pair.`,
};
}
if (
expectedContainerId &&
(ownership.kind !== "managed" || ownership.containerId !== expectedContainerId)
) {
return {
ok: false,
reason: `Managed vLLM container "${containerName}" changed after recovery. NemoClaw will not remove it. Retry onboarding.`,
};
}
return ownership.kind === "managed"
? { ok: true, containerId: ownership.containerId }
: { ok: true };
}
export function isNemoClawManagedVllmRunning(): boolean {
try {
if (recoverInstalledManagedClusterVllmEndpoint()) return true;
} catch {
return false;
}
const ownership = inspectVllmContainerOwnership(NEMOCLAW_VLLM_CONTAINER_NAME);
return (ownership.kind === "managed" || ownership.kind === "dual-managed") && ownership.running;
}
export type PersistConfiguredManagedVllmRuntimeResult =
| { ok: true; persisted: boolean }
| { ok: false; reason: string };
/**
* Confirm an installer-owned receipt or adopt an already-running Station pair
* after onboarding has authenticated and validated its endpoint.
*/
export async function persistConfiguredManagedVllmRuntimeReceipt(): Promise<PersistConfiguredManagedVllmRuntimeResult> {
try {
if (recoverInstalledManagedClusterVllmEndpoint()) return { ok: true, persisted: true };
} catch (error) {
return { ok: false, reason: `managed vLLM recovery failed: ${(error as Error).message}` };
}
try {
if (recoverHostLocalManagedVllmEndpoint()) return { ok: true, persisted: true };
} catch (error) {
return {
ok: false,
reason: `managed host-local vLLM recovery failed: ${(error as Error).message}`,
};
}
const configuredPeer = String(process.env[NEMOCLAW_DGX_STATION_PEER_ENV] ?? "").trim();
let configuredPlan: DualStationVllmPlan | null = null;
if (configuredPeer) {
const capability = probeDualStationVllmCapability();
if (capability.kind !== "ready") {
const reason =
capability.kind === "unavailable"
? capability.reason
: "the configured dual-Station peer disappeared";
return { ok: false, reason };
}
configuredPlan = capability.plan;
}
try {
return await withDualStationManagedVllmLifecycle(async () => {
let plan: DualStationVllmPlan;
let receiptAlreadyPersisted = false;
if (configuredPlan) {
plan = configuredPlan;
} else {
const recovered = recoverInstalledDualStationVllmRuntime();
if (recovered.kind === "not-installed") {
return {
ok: false,
reason: "the managed dual-Station peer configuration is missing",
};
}
if (recovered.kind === "unsafe") {
return {
ok: false,
reason: `the managed dual-Station cleanup receipt is unsafe: ${recovered.reason}`,
};
}
plan = recovered.plan;
receiptAlreadyPersisted = true;
}
const preflight = preflightDualStationManagedVllm(plan);
if (!preflight.ok) return { ok: false, reason: preflight.reason };
if (!areDualStationManagedVllmContainersRunning(plan)) {
return {
ok: false,
reason: "the managed dual-Station containers changed before cleanup ownership validation",
};
}
if (receiptAlreadyPersisted) return { ok: true, persisted: true };
try {
persistDualStationVllmRuntimeReceipt(plan);
} catch (error) {
return { ok: false, reason: (error as Error).message };
}
return { ok: true, persisted: true };
});
} catch (error) {
return {
ok: false,
reason: `dual-Station lifecycle lock failed: ${(error as Error).message}`,
};
}
}
function startContainer(
profile: VllmProfile,
model: VllmModelDef,
dockerEnv: Record<string, string> = buildVllmDockerEnv(),
resolveBridgeHost: (dockerEnv: Record<string, string>) => string = (env) =>
resolveManagedVllmBridgeHost(dockerCapture, env),
expectedReplacementContainerId?: string,
): { ok: true; containerId: string } | { ok: false; reason: string } {
emit(`Starting vLLM container (${profile.containerName})`);
// The explicit download completed before this long-lived container starts,
// so do not retain the host Hugging Face token in the serving process.
let runArgs: string[];
try {
const resolvedFlags = profile.buildDockerRunFlags
? profile.buildDockerRunFlags()
: profile.dockerRunFlags;
const commandEnv: NodeJS.ProcessEnv = {
...dockerEnv,
...(process.env[VLLM_EXTRA_ARGS_ENV] === undefined
? {}
: { [VLLM_EXTRA_ARGS_ENV]: process.env[VLLM_EXTRA_ARGS_ENV] }),
};
runArgs = buildVllmRunArgs(
profile,
model,
resolvedFlags,
commandEnv,
model.managedBearerAuth ? resolveBridgeHost(dockerEnv) : undefined,
);
} catch (err) {
return { ok: false, reason: (err as Error).message };
}
// Re-check immediately before teardown. Removing the inspected container ID
// avoids deleting an unrelated same-name container if the name changes hands.
const replacement = vllmContainerReplacementTarget(
profile.containerName,
model.managedBearerAuth ? dockerEnv : undefined,