// Container command lines for deployments, per engine type. Pure: used by the worker to start // containers and by the UI for the live preview. Flags verified against llama.cpp build 11429 // (`llama-server --help`) and vLLM v0.31.0 (`vllm serve --help=all`). import type { DeploymentOptions, RuntimeAccelerator, RuntimeEngine } from "@/lib/db/schema"; /** Where the models folder is mounted inside every runtime container (read-only). */ export const CONTAINER_MODELS_DIR = "/models"; export const ENGINE_PORT: Record = { "llama.cpp": 8080, vllm: 8000 }; export type CommandInput = { engine: RuntimeEngine; options: DeploymentOptions; model: { repoId: string; localPath: string }; /** `accelerator` unset: CPU. */ runtime: { env: Record; extraArgs: string[]; accelerator?: RuntimeAccelerator }; /** Keys from Settings → API keys; used when `options.requireApiKey` is set. */ apiKeys?: string[]; }; /** Stands in for key values in everything Kaname shows or stores. */ export const API_KEY_PLACEHOLDER = ""; export type ContainerCommand = { args: string[]; env: Record; port: number }; const inModels = (localPath: string, file?: string | null) => [CONTAINER_MODELS_DIR, localPath, file].filter(Boolean).join("/").replace(/\/+/g, "/"); const num = (flag: string, v: number | null | undefined) => (v != null && Number.isFinite(v) ? [flag, String(v)] : []); const str = (flag: string, v: string | null | undefined) => (v ? [flag, v] : []); /** `args` without `flag` ("--flag value" or "--flag=value"). */ function withoutFlag(args: string[], flag: string): string[] { const out: string[] = []; for (let i = 0; i < args.length; i++) { if (args[i] === flag) i++; else if (!args[i].startsWith(`${flag}=`)) out.push(args[i]); } return out; } export function buildCommand({ engine, options: o, model, runtime, apiKeys = [] }: CommandInput): ContainerCommand { const port = ENGINE_PORT[engine]; const keys = o.requireApiKey ? apiKeys : []; const gpu = !!runtime.accelerator && runtime.accelerator !== "cpu"; if (engine === "llama.cpp") { // The image's entrypoint is llama-server, so these are its arguments. const args = [ "-m", inModels(model.localPath, o.modelFile), "--host", "0.0.0.0", "--port", String(port), "-a", model.repoId, ...num("-c", o.contextSize), ...num("-t", o.threads), ...num("-tb", o.threads), ...num("-b", o.batchSize), ...num("-ub", o.ubatchSize), ...num("-np", o.parallel), ...str("-ctk", o.cacheTypeK), ...str("-ctv", o.cacheTypeV), ...str("-fa", o.flashAttn), ...num("-cram", o.cacheRamMb), ...(o.mmproj ? ["--mmproj", inModels(model.localPath, o.mmproj)] : []), ...(o.draftFile ? ["-md", inModels(model.localPath, o.draftFile), "--spec-type", o.draftType ?? "draft-simple"] : []), ...(o.webui === false ? ["--no-webui"] : []), // GPU offload (-ngl defaults to "auto", which fits layers into free VRAM). ...(gpu ? str("-ngl", o.gpuLayers && o.gpuLayers !== "auto" ? o.gpuLayers : null) : []), ...(gpu ? str("-sm", o.splitMode) : []), ...(gpu ? str("-ts", o.tensorSplit) : []), ...(gpu && o.cpuMoe ? ["-cmoe"] : []), ...(gpu && !o.cpuMoe ? num("-ncmoe", o.nCpuMoe) : []), "--metrics", ...runtime.extraArgs, ...o.extraArgs, ]; // Via the environment, not the command line; several keys as one comma-separated list. const env = { ...runtime.env, ...(keys.length ? { LLAMA_API_KEY: keys.join(",") } : {}) }; return { args, env, port }; } // vLLM: the image's entrypoint is `vllm serve`; the model is the repo folder. const env = { ...runtime.env }; if (!gpu && o.kvCacheGb != null) env.VLLM_CPU_KVCACHE_SPACE = String(o.kvCacheGb); // VLLM_API_KEY holds a single key; more than one needs --api-key. if (keys.length === 1) env.VLLM_API_KEY = keys[0]; const args = [ inModels(model.localPath, o.modelFile || null), "--host", "0.0.0.0", "--port", String(port), "--served-model-name", model.repoId, ...num("--max-model-len", o.contextSize), ...num("--max-num-seqs", o.maxNumSeqs), ...(gpu ? num("--tensor-parallel-size", o.tensorParallel) : []), ...(gpu ? num("--gpu-memory-utilization", o.gpuMemoryUtilization) : []), ...(keys.length > 1 ? ["--api-key", ...keys] : []), // A deployment's dtype replaces the runtime's default instead of repeating the flag. ...(o.dtype ? withoutFlag(runtime.extraArgs, "--dtype") : runtime.extraArgs), ...str("--dtype", o.dtype), ...o.extraArgs, ]; return { args, env, port }; } /** The command with every key replaced by {@link API_KEY_PLACEHOLDER}. */ export function redactCommand(cmd: ContainerCommand, keys: string[]): ContainerCommand { const hide = (v: string) => keys.filter(Boolean).reduce((acc, k) => acc.split(k).join(API_KEY_PLACEHOLDER), v); return { ...cmd, args: cmd.args.map(hide), env: Object.fromEntries(Object.entries(cmd.env).map(([k, v]) => [k, hide(v)])) }; } /** Shell-style rendering for display ("docker run … image args"). */ export function renderCommand(image: string, cmd: ContainerCommand): string { const q = (s: string) => (/^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`); const env = Object.entries(cmd.env).map(([k, v]) => `-e ${q(`${k}=${v}`)}`); return ["docker run", ...env, `-v :${CONTAINER_MODELS_DIR}:ro`, q(image), ...cmd.args.map(q)].join(" "); } /** Rough memory need: model files plus KV cache and runtime overhead. */ /** llama-server's default --cache-ram (MiB): prompts kept in RAM for reuse. */ export const LLAMA_DEFAULT_CACHE_RAM_MB = 8192; const KV_TYPE_FACTOR: Record = { f32: 2, f16: 1, bf16: 1, q8_0: 0.53, q5_0: 0.34, q5_1: 0.38, q4_0: 0.28, q4_1: 0.31, iq4_nl: 0.28 }; /** llama.cpp KV cache in MiB for a model of `modelMb`: the per-token heuristic below, scaled by the cache type. */ function kvCacheMb(modelMb: number, contextSize: number, o: Pick): number { const perTokenKiB = 96 + 24 * Math.sqrt(modelMb / 1024); const kvFactor = ((KV_TYPE_FACTOR[o.cacheTypeK ?? "f16"] ?? 1) + (KV_TYPE_FACTOR[o.cacheTypeV ?? "f16"] ?? 1)) / 2; return (contextSize * perTokenKiB * kvFactor) / 1024; } /** llama.cpp compute buffers and runtime state on the GPU (measured order of magnitude, not exact). */ const GPU_OVERHEAD_MB = 1024; /** * Rough VRAM need of a GPU deployment in MiB, for NVIDIA and Intel/AMD (/dev/dri) alike; null when it * can't be told without reading the model (only some layers or the MoE experts offloaded). * - vLLM reserves --gpu-memory-utilization (default 0.9) of each GPU's VRAM up front. * - llama.cpp with all layers on the GPU ("auto" fits as many as there is room for): weights + KV * cache + compute buffers. */ export function estimateVramMb( fileBytes: number, contextSize: number, engine: RuntimeEngine, o: Pick, vramTotalMb: number | null, ): number | null { if (engine === "vllm") return vramTotalMb ? Math.ceil(vramTotalMb * (o.gpuMemoryUtilization ?? 0.9)) : null; const layers = o.gpuLayers ?? "auto"; if ((layers !== "auto" && layers !== "all") || o.cpuMoe || (o.nCpuMoe ?? 0) > 0) return null; const model = fileBytes / 2 ** 20; return Math.ceil(model + kvCacheMb(model, contextSize, o) + GPU_OVERHEAD_MB); } /** * Rough RAM need of a deployment in MiB, for the memory limit. Without the GGUF header the KV size * per token is a heuristic: ~110 KiB (f16) for sub-1B models up to ~250 KiB around 70B with GQA. * Measured (llama.cpp b11429, Qwen3-0.6B Q4_K_M, ctx 4096): ~1.2 GiB without the prompt cache. */ export function estimateMemoryMb( fileBytes: number, contextSize: number, engine: RuntimeEngine, o: Pick & { accelerator?: RuntimeAccelerator } = {}, ): number { const model = fileBytes / 2 ** 20; const gpu = !!o.accelerator && o.accelerator !== "cpu"; // vLLM CPU: API server, engine core and worker each load torch (~3 GiB measured with v0.31.0). // On a GPU the weights and KV cache live in VRAM; RAM holds the processes. if (engine === "vllm") return Math.ceil(gpu ? 6144 : model + (o.kvCacheGb ?? 4) * 1024 + 3072); const kv = kvCacheMb(model, contextSize, o); const cache = o.cacheRamMb == null ? LLAMA_DEFAULT_CACHE_RAM_MB : o.cacheRamMb < 0 ? LLAMA_DEFAULT_CACHE_RAM_MB : o.cacheRamMb; // The memory-mapped model counts against the container's limit (page cache), even when offloaded. return Math.ceil(model + (gpu ? 0 : kv) + cache + 768); }