Skip to content

armgit / ODS

Public Imported from GitHub
0

ODS V3 Pre-Release: Public testing and refinement ahead of the official V3 launch. Turn your PC, Mac, or Linux box into a private AI server.

feat(models): add vLLM catalog entries, selection and verified download (#8289)

Mike Bradley68c1c9c5ba0f
diff --git a/ods/config/model-library.json b/ods/config/model-library.json
index 777ff8948..aa3358627 100644
--- a/ods/config/model-library.json
+++ b/ods/config/model-library.json
@@ -2826,6 +2826,142 @@
"tokens_per_sec_estimate": 15,
"llm_model_name": "qwen3.5-122b-a10b",
"llama_server_image": null
+ },
+ {
+ "id": "qwen3.8-flash-next-nvfp4-vllm",
+ "name": "Qwen 3.8 Flash Next NVFP4 (vLLM)",
+ "family": "qwen",
+ "runtime": "vllm",
+ "hf_repo": "nvidia/Qwen3.8-Flash-Next-NVFP4",
+ "revision": "fc694b54fb0174e0913e6adf86691ef85a4ead47",
+ "source_url": "https://huggingface.co/nvidia/Qwen3.8-Flash-Next-NVFP4",
+ "license": "other",
+ "license_name": "nvidia-open-model-license",
+ "size_bytes": 132734506847,
+ "size_mb": 132735,
+ "served_model_name": "Qwen3.8-Flash-Next-NVFP4",
+ "llm_model_name": "qwen3.8-flash-next-nvfp4",
+ "context_length": 131072,
+ "max_context_length": 262144,
+ "min_gpu_mib": 158720,
+ "compute_capability": ["10.0", "10.3"],
+ "reasoning": "medium",
+ "tool_call_parser": "qwen3_coder",
+ "reasoning_parser": "qwen3",
+ "vllm_args": ["--quantization", "modelopt", "--max-model-len", "131072", "--max-num-seqs", "32", "--max-num-batched-tokens", "8192", "--enable-prefix-caching", "--enable-auto-tool-choice", "--tool-call-parser", "qwen3_coder", "--reasoning-parser", "qwen3", "--trust-remote-code", "--engram-config.cpu_offload=false", "--speculative-config.method=mtp", "--speculative-config.num_speculative_tokens=3"],
+ "selection": {
+ "discrete": 0,
+ "unified": 0,
+ "cpu": 0,
+ "vllm": 90
+ },
+ "quantization": "NVFP4",
+ "specialty": "Reasoning and coding",
+ "description": "NVIDIA's NVFP4 build of Qwen 3.8 Flash Next for the vLLM engine (not llama.cpp): a mixture-of-experts model with 125B parameters, 6B active, plus n-gram embeddings and an MTP head. It reads text, images and video. It needs one NVIDIA datacenter Blackwell GPU (compute capability 10.x, such as a B200, B300 or GB300) with at least 155 GiB of memory, and 133 GB of disk. Served at 128K context with medium thinking and MTP speculative decoding. On a DGX Station GB300 it wrote about 510 tokens/s on one coding stream and read prompts at about 31,000 tokens/s.",
+ "files": [
+ {"path": ".gitattributes", "size": 1635, "git_blob_sha1": "a09db2ea4d1bd1fc1c09f6fca45e8e4054953535"},
+ {"path": "README.md", "size": 12109, "git_blob_sha1": "f3edfc5b8f2cae8ae751162626d4c5aa3ed071a6"},
+ {"path": "chat_template.jinja", "size": 8952, "git_blob_sha1": "c0c686f9c38d70d179fb7b5f5aa7530bc913dda3"},
+ {"path": "config.json", "size": 30820, "git_blob_sha1": "d9df7636dc5b8bdab82655aba8ce0ebe25b22342"},
+ {"path": "generation_config.json", "size": 202, "git_blob_sha1": "023756cfadf88e5bf69eefeee3e172f38c448d64"},
+ {"path": "hf_quant_config.json", "size": 23001, "git_blob_sha1": "89bb1a48d2358f4b9ab7959bd4357a6d6d04020e"},
+ {"path": "merges.txt", "size": 3353259, "git_blob_sha1": "a494e019ca1502219fd0128658b979e5f05ae8e8"},
+ {"path": "model-00001-of-00010.safetensors", "size": 3115991696, "sha256": "63fde954be6f08b49b876f4f70a0ad0bcfee71aff7b1faa33779b6b32feca2a2"},
+ {"path": "model-00002-of-00010.safetensors", "size": 10005510304, "sha256": "4dafaef62a908e49e0d92c7c2a3fa99f4d9651fdeeb0ca09f09a9b40095af4e0"},
+ {"path": "model-00003-of-00010.safetensors", "size": 10005364728, "sha256": "3218ddc129258e91a721a8e81329ca8f00588332ec721bd8d2cf7d20e324bf47"},
+ {"path": "model-00004-of-00010.safetensors", "size": 10006060112, "sha256": "55e2bdf6a3a1f6e65270787f65c63b2a2a56b308b54eb1fb318dfabc9b48b141"},
+ {"path": "model-00005-of-00010.safetensors", "size": 10005362392, "sha256": "d3c169d3694bfba846455d01e48f047d770f78d071c5a4d22f129389411d686e"},
+ {"path": "model-00006-of-00010.safetensors", "size": 10005375328, "sha256": "38f65a9d11090428e139cc60d0587e8e5433ea2ce79820883c583d7cfcc53130"},
+ {"path": "model-00007-of-00010.safetensors", "size": 10005956544, "sha256": "8cf3fa05c04cb2e060963b69bb01f7a7b9f43c58435fbe380836a0457a19cd3e"},
+ {"path": "model-00008-of-00010.safetensors", "size": 10005375200, "sha256": "53d1f80746aa0cc0a7c2f4836587002a8a4dd72c827432cd2e43abae3c3899e4"},
+ {"path": "model-00009-of-00010.safetensors", "size": 5679113808, "sha256": "eaff6a87ece6fbfd6ad0fbaa0a5cf9ff542f8076acba38e62410b1ed55e12cc3"},
+ {"path": "model-00010-of-00010.safetensors", "size": 128587536, "sha256": "0d49b0cf7c15bf9b5bd1e17403b36727315860a8f2a2e0f5a53655547084f640"},
+ {"path": "model-fp8-mtp-ple.safetensors", "size": 53717551730, "sha256": "3525520c8602d850003eb1960aec0b64291dae33b83f8b65dd639a451df78823"},
+ {"path": "model.safetensors.index.json", "size": 31275518, "sha256": "660414e8300728ba80062e6a3c81cb76a65e2ab136ac9e9ceb450ba0c51c3c0d"},
+ {"path": "preprocessor_config.json", "size": 390, "git_blob_sha1": "2ea84a437d448ff71b08df68fdd949d5cc4ebb64"},
+ {"path": "processor_config.json", "size": 1191, "git_blob_sha1": "33818c7f9e991ad735fd240209f4fa73e6c28c50"},
+ {"path": "tokenizer.json", "size": 12809320, "sha256": "0997f410c57a1f4e53b09e4be8f4a172d90edd9564368fb0847030937229b9f3"},
+ {"path": "tokenizer_config.json", "size": 17928, "git_blob_sha1": "5de744b3fca2129d7186979ae47c06be33903243"},
+ {"path": "video_preprocessor_config.json", "size": 385, "git_blob_sha1": "3ba673a5ad7d4d13f54155ecd38b2a94a6dac8fe"},
+ {"path": "vocab.json", "size": 6722759, "git_blob_sha1": "0aa0ce0658d60ac4a5d609f4eadb0e8e43514176"}
+ ]
+ },
+ {
+ "id": "glm-5.3-flash-nvfp4-vllm",
+ "name": "GLM 5.3 Flash NVFP4 (vLLM)",
+ "family": "glm",
+ "runtime": "vllm",
+ "hf_repo": "nvidia/GLM-5.3-Flash-NVFP4",
+ "revision": "da920bb0b9f4a06727223a349e55468e38352348",
+ "source_url": "https://huggingface.co/nvidia/GLM-5.3-Flash-NVFP4",
+ "license": "mit",
+ "size_bytes": 204476278199,
+ "size_mb": 204476,
+ "served_model_name": "GLM-5.3-Flash-NVFP4",
+ "llm_model_name": "glm-5.3-flash-nvfp4",
+ "context_length": 131072,
+ "max_context_length": 1048576,
+ "min_gpu_mib": 244736,
+ "compute_capability": ["10.0", "10.3"],
+ "reasoning": "medium",
+ "tool_call_parser": "glm47",
+ "reasoning_parser": "glm47",
+ "vllm_args": ["--max-model-len", "131072", "--kv-cache-dtype", "fp8", "--max-num-seqs", "32", "--max-num-batched-tokens", "8192", "--enable-prefix-caching", "--enable-auto-tool-choice", "--tool-call-parser", "glm47", "--reasoning-parser", "glm47", "--trust-remote-code", "--speculative-config.method=mtp", "--speculative-config.num_speculative_tokens=5"],
+ "selection": {
+ "discrete": 0,
+ "unified": 0,
+ "cpu": 0,
+ "vllm": 100
+ },
+ "quantization": "NVFP4",
+ "specialty": "Quality",
+ "description": "NVIDIA's NVFP4 build of GLM-5.3 Flash for the vLLM engine (not llama.cpp): a mixture-of-experts model with 320B parameters, 18B active. It reads text, images and video. It needs one NVIDIA datacenter Blackwell GPU (compute capability 10.x) with at least 239 GiB of memory, such as a GB300, and 204 GB of disk. Served at 128K context with an FP8 KV cache, medium thinking and MTP speculative decoding. On a DGX Station GB300 it wrote about 390 tokens/s on one coding stream and read prompts at about 24,000 tokens/s.",
+ "files": [
+ {"path": ".gitattributes", "size": 1635, "git_blob_sha1": "a09db2ea4d1bd1fc1c09f6fca45e8e4054953535"},
+ {"path": ".quant_summary.txt", "size": 616642, "git_blob_sha1": "388d3ad297bef5d95516a0400716d27af6e0eec7"},
+ {"path": "README.md", "size": 10235, "git_blob_sha1": "08fa91a54c57d22b41740736017c83a1477d5d00"},
+ {"path": "chat_template.jinja", "size": 10644, "git_blob_sha1": "fb94d40d72a2eefa0c7140cb66d941656be16969"},
+ {"path": "config.json", "size": 16770, "git_blob_sha1": "c76d04db0f678a8f7e8b1b6a27a97b6050b7b340"},
+ {"path": "generation_config.json", "size": 215, "git_blob_sha1": "46d04e68002526d394949f63d65f93ac4ac8abeb"},
+ {"path": "hf_quant_config.json", "size": 8076, "git_blob_sha1": "cbc53ce3eec597abe641fbeaac4aa50fd01e4fd6"},
+ {"path": "model-00001-of-00033.safetensors", "size": 8945680672, "sha256": "5c7ee3e2a0bd7452b7ccea70bd18f7221676a709a3d4c050d1457fa7d7359125"},
+ {"path": "model-00002-of-00033.safetensors", "size": 8945659984, "sha256": "7afab1480693d8a37faba2f092b0626b121f6fce9241478ad95cf857145ddc41"},
+ {"path": "model-00003-of-00033.safetensors", "size": 8945740832, "sha256": "f184e8b75db437579fa571d4693d6fba7a2806e531d3b8e05d13b1dbc0a90142"},
+ {"path": "model-00004-of-00033.safetensors", "size": 5985863344, "sha256": "dd08e62f3f86dad5ac784e68eb956fa20a18bab72d81337d3058af281ce18c93"},
+ {"path": "model-00005-of-00033.safetensors", "size": 5985909512, "sha256": "bc763b5eec6911a7750b6e37d7f499d6226535792be5c7e7a169d1abb09875d6"},
+ {"path": "model-00006-of-00033.safetensors", "size": 5915365198, "sha256": "c7d9597fad87af3b54dbcf994be2b65cd99fc458e392e34f22eeac4af502e4fc"},
+ {"path": "model-00007-of-00033.safetensors", "size": 5915359020, "sha256": "3d0f68feb7fe4cee3bd87a464c845843594e0039124941c2a89e7c1ce9da9e2b"},
+ {"path": "model-00008-of-00033.safetensors", "size": 5915364798, "sha256": "5c4d7657a3d6fe137b9de14a917d84e511fc9b206fe76bd943d1e53deedba857"},
+ {"path": "model-00009-of-00033.safetensors", "size": 5915358812, "sha256": "4770820b433f6ca50c7d30f0b2eaa9df6fd7c095769f51ee46aa519c37e5f7d3"},
+ {"path": "model-00010-of-00033.safetensors", "size": 5915358494, "sha256": "be92de14713dc46c0b0c8c87f1c02395b2eeb6059087c69d0a39d01dee34edd8"},
+ {"path": "model-00011-of-00033.safetensors", "size": 5915358332, "sha256": "a3294966995e1a81525c6a9efdeb6a27c599a4d04b4e3a5342331298a527d0be"},
+ {"path": "model-00012-of-00033.safetensors", "size": 5915083008, "sha256": "4d6f4b1a555377bfa773981a4c0d84a86ee782501613a18a3e86caefbace7f66"},
+ {"path": "model-00013-of-00033.safetensors", "size": 5915639642, "sha256": "d1d5c86fa3566eb099f99677550f44191c77faa935491d6d2c5a7c337797eaf9"},
+ {"path": "model-00014-of-00033.safetensors", "size": 5915084432, "sha256": "fd6c81655a572a2462dea772bed6fd5114017f12185a619ce693f6b476be5524"},
+ {"path": "model-00015-of-00033.safetensors", "size": 5915642946, "sha256": "6ff8daa650fcfacd509e15be48f4c986ff7dae081a874fcb4c1ee67d3a66487a"},
+ {"path": "model-00016-of-00033.safetensors", "size": 5915084544, "sha256": "286c1a635749f6364c5b4bbab0c7a9eb0916f9421b17f6ade618a5478b25be58"},
+ {"path": "model-00017-of-00033.safetensors", "size": 5915653746, "sha256": "7be78c2466c0c5d4472c1405ff8631b1da1f0dc059e878d3f6f75bf670514b27"},
+ {"path": "model-00018-of-00033.safetensors", "size": 5915084536, "sha256": "b5755440acc16e3a935ab60106a99bc9db6cc03d033786e7502e2010a27ff6aa"},
+ {"path": "model-00019-of-00033.safetensors", "size": 5915653908, "sha256": "2385071e3600654014011755c97a46e1abe1d2aa988e6fdb7aa2bd4c751b9419"},
+ {"path": "model-00020-of-00033.safetensors", "size": 5915368968, "sha256": "8597c39572caa35b1a5e4896ed7c83eb12350ca862dce875071ec2e2d70fec98"},
+ {"path": "model-00021-of-00033.safetensors", "size": 5915366420, "sha256": "cf2923ceb37fd1dcb2772f16aa6d459e472dea3d36275f5c5580781646f27f60"},
+ {"path": "model-00022-of-00033.safetensors", "size": 5915362564, "sha256": "8f27fac338e9960367a58f0a6ba3681148d52bf38d563d183cac5ab7092b16a6"},
+ {"path": "model-00023-of-00033.safetensors", "size": 5915370484, "sha256": "04bbd26640bdf145da1c412aa4c01ef2d0103b2d7e8a2846f207175be461be5d"},
+ {"path": "model-00024-of-00033.safetensors", "size": 5915084584, "sha256": "2dc1b2fdf6ba9816545ce9036c9561cd293f71c887d3d3d1590e86900548fb75"},
+ {"path": "model-00025-of-00033.safetensors", "size": 5915652952, "sha256": "12a327e0f52b18e7feae2936ebacf33f7a5eff11c96038a06d2547f5653f0838"},
+ {"path": "model-00026-of-00033.safetensors", "size": 5915084552, "sha256": "0eb6db2777bebcf9ea34e9b639a8497ffb0d7c520e00a4e0a0b6331cfb18ac2d"},
+ {"path": "model-00027-of-00033.safetensors", "size": 5915652344, "sha256": "e220abe4abb6a4798b1d16fdb7d4f6121b6c6e3e8f8d9f71243ba957a7f9542d"},
+ {"path": "model-00028-of-00033.safetensors", "size": 5915364684, "sha256": "04b44953c3a5019c4da79260b9abf39bc6fa2b9414f4ede20fea400325aaab3d"},
+ {"path": "model-00029-of-00033.safetensors", "size": 5915373524, "sha256": "a705d67e2580270744f26135fc46fd062ea59df6260b45cd628bc2b8a74f6ab2"},
+ {"path": "model-00030-of-00033.safetensors", "size": 5915364844, "sha256": "60c0e12a793693702303e7d0ebf16e7619fbbc7a45fe2e9e6d038459053f8e1f"},
+ {"path": "model-00031-of-00033.safetensors", "size": 5915373956, "sha256": "5d3a07314659b264b56d84385e89abb5a0199ce944a7cb33eab556832d100075"},
+ {"path": "model-00032-of-00033.safetensors", "size": 5915364628, "sha256": "5126cddeb35041953ad0375d926081f7d78b0b279460fa8d1afcdfbe36bca3d1"},
+ {"path": "model-00033-of-00033.safetensors", "size": 5915373132, "sha256": "c6fa7921452627ad9d7913875d78496c60082f71b05f943b5dddb3318f0771c2"},
+ {"path": "model.safetensors.index.json", "size": 16291474, "sha256": "26765b2601fd246ef361cfb9f5e10f9fb291a59e05ad0a109062f3a4747c7fd1"},
+ {"path": "processor_config.json", "size": 909, "git_blob_sha1": "3ec2a058b2cdec556eca0f621e8c5164eec213c2"},
+ {"path": "tokenizer.json", "size": 20217442, "sha256": "19e773648cb4e65de8660ea6365e10acca112d42a854923df93db4a6f333a82d"},
+ {"path": "tokenizer_config.json", "size": 761, "git_blob_sha1": "e375fa0a4e16660ce0e2026e39374d35dad4c079"}
+ ]
}
]
}
diff --git a/ods/docs/MODEL-TERMS-INVENTORY.md b/ods/docs/MODEL-TERMS-INVENTORY.md
index 048dc1f32..bfc03049a 100644
--- a/ods/docs/MODEL-TERMS-INVENTORY.md
+++ b/ods/docs/MODEL-TERMS-INVENTORY.md
@@ -8,6 +8,11 @@ to pinned unsloth revisions after ggml-org deleted their Q4_K_M files upstream.
The same day, every other direct catalog URL that requested `main` was pinned
to the revision listed here after its LFS sha256 at that revision matched the
catalog `gguf_sha256`; the terms metadata in those rows is unchanged.
+The `qwen3.8-flash-next-nvfp4-vllm` and `glm-5.3-flash-nvfp4-vllm` rows were
+added on 2026-10-27 with their catalog entries, for 60 records. They are vLLM
+snapshots, not GGUFs: the catalog pins the whole repository revision and every
+file's digest. The Qwen model card names the NVIDIA Open Model License for the
+checkpoint and the Qwen Community License 1.0 for the base model.
This is a documentation inventory of upstream repository metadata, not a license
grant, legal-compatibility decision, or completed per-artifact clearance. A
@@ -15,9 +20,9 @@ quantizer's model-card tag can be incomplete or wrong and does not override the
original model license. Each source link identifies the revision requested by
the catalog; mutable refs need a separate immutable artifact receipt.
-Two catalog entries have a top-level `license`, none has a top-level
-`license_url`, and one additional entry has nested `source_evidence` license
-information. This page does not change that runtime schema or enforce acceptance.
+Four catalog entries have a top-level `license` (one of them also a
+`license_name`), none has a top-level `license_url`, and one additional entry
+has nested `source_evidence` license information. This page does not change that runtime schema or enforce acceptance.
The separate Hugging Face browser does display upstream license metadata; that
does not close the curated catalog's provenance and acceptance gaps.
@@ -86,6 +91,8 @@ A missing or `other` tag requires review, not an assumption of Apache-2.0.
| `qwen3-coder-next-q4` | [unsloth/Qwen3-Coder-Next-GGUF @ ce09c67b53bc](https://huggingface.co/api/models/unsloth/Qwen3-Coder-Next-GGUF/revision/ce09c67b53bc8739eef83fe67b2f5d293c270632) (requested `ce09c67b53bc`) | apache-2.0 | ["Qwen/Qwen3-Coder-Next"] |
| `llama4-scout-q4` | No direct GGUF source | No direct Hugging Face GGUF source in this record | Not declared |
| `qwen3.5-122b-a10b-q4` | No direct GGUF source | No direct Hugging Face GGUF source in this record | Not declared |
+| `qwen3.8-flash-next-nvfp4-vllm` | [nvidia/Qwen3.8-Flash-Next-NVFP4 @ fc694b54fb01](https://huggingface.co/api/models/nvidia/Qwen3.8-Flash-Next-NVFP4/revision/fc694b54fb0174e0913e6adf86691ef85a4ead47) (requested `fc694b54fb01`; vLLM snapshot) | other (`nvidia-open-model-license`) | ["Qwen/Qwen3.8-Flash-Next"] |
+| `glm-5.3-flash-nvfp4-vllm` | [nvidia/GLM-5.3-Flash-NVFP4 @ da920bb0b9f4](https://huggingface.co/api/models/nvidia/GLM-5.3-Flash-NVFP4/revision/da920bb0b9f4a06727223a349e55468e38352348) (requested `da920bb0b9f4`; vLLM snapshot) | mit | ["zai-org/GLM-5.3-Flash"] |
## Maintenance
diff --git a/ods/extensions/services/dashboard-api/model_memory.py b/ods/extensions/services/dashboard-api/model_memory.py
index 39980c3cd..dfe1bf45e 100644
--- a/ods/extensions/services/dashboard-api/model_memory.py
+++ b/ods/extensions/services/dashboard-api/model_memory.py
@@ -21,6 +21,15 @@ There are two estimate paths:
yet) keeps the historical estimate exactly: file size + KV (from metadata or
a parameter-count heuristic), floored by ``vram_required_gb``.
+Entries served by vLLM (``"runtime": "vllm"``, see model_vllm.py) take
+neither path: llama.cpp's KV, recurrent-state and checkpoint maths do not
+apply to them. Their weights are the sum of the ``files`` manifest, and the
+device need is weights / :data:`VLLM_GPU_MEMORY_UTILIZATION`, the GPU size at
+which the share vLLM preallocates just holds the weights (method ``vllm``).
+vLLM fits its KV cache and activations into whatever that share leaves, so
+this is a floor for callers that ask; the catalog's ``min_gpu_mib`` (weights
+plus about 25%) is what the installer admits a GPU on.
+
The GPU-residency work reuses :func:`estimate_model_memory`,
:class:`MemoryEstimate` and :func:`fit_margin_gib`; do not re-derive KV there.
"""
@@ -41,8 +50,16 @@ MEMORY_METADATA_KEYS = (
"size_bytes", "max_context_length",
"sliding_window", "sliding_window_layer_count", "sliding_window_head_count_kv",
"sliding_window_key_length", "sliding_window_value_length",
+ "runtime", "files", "vllm_args",
)
+# A catalog entry with this ``runtime`` is served by vLLM (model_vllm.py).
+VLLM_RUNTIME = "vllm"
+# The share of its GPU vLLM preallocates (--gpu-memory-utilization; .env
+# VLLM_GPU_MEMORY_UTILIZATION defaults to it) for weights, activations and
+# its KV cache.
+VLLM_GPU_MEMORY_UTILIZATION = 0.90
+
MIB = 1024.0 ** 2
GIB = 1024.0 ** 3
@@ -342,7 +359,10 @@ def estimate_model_memory(
:func:`sliding_window_cells`). Context checkpoints, kept in host RAM,
copy each sequence's recurrent and sliding-window state.
``weight_size_mb`` (the file on disk, MiB) overrides catalog sizes.
+ A vLLM entry gets :func:`vllm_memory_estimate` instead.
"""
+ if model.get("runtime") == VLLM_RUNTIME:
+ return vllm_memory_estimate(model, context_length=context_length, weight_size_mb=weight_size_mb)
context = _context(model, context_length)
cache_k = str(cache_type_k or "f16").strip().lower()
cache_v = str(cache_type_v or "f16").strip().lower()
@@ -412,11 +432,73 @@ def estimate_model_memory(
)
+def _vllm_weights_bytes(model: dict[str, Any], weight_size_mb: int | float | None) -> float:
+ explicit = _positive_number(weight_size_mb)
+ if explicit:
+ return explicit * MIB
+ files = model.get("files")
+ if not isinstance(files, list):
+ return 0.0
+ return sum(_positive_number(item.get("size")) for item in files if isinstance(item, dict))
+
+
+def _vllm_kv_cache_dtype(model: dict[str, Any]) -> str:
+ """vLLM's ``--kv-cache-dtype`` from the entry's ``vllm_args`` (default ``auto``)."""
+ args = model.get("vllm_args")
+ args = [str(arg) for arg in args] if isinstance(args, list) else []
+ for index, arg in enumerate(args):
+ if arg == "--kv-cache-dtype" and index + 1 < len(args):
+ return args[index + 1]
+ if arg.startswith("--kv-cache-dtype="):
+ return arg.split("=", 1)[1]
+ return "auto"
+
+
+def vllm_memory_estimate(
+ model: dict[str, Any],
+ *,
+ context_length: int | None = None,
+ weight_size_mb: int | float | None = None,
+) -> MemoryEstimate:
+ """The documented estimate for a vLLM entry (see the module docstring).
+
+ Weights are the ``files`` manifest total (or ``weight_size_mb``, a measured
+ size on disk). ``device_gib`` is weights / VLLM_GPU_MEMORY_UTILIZATION; KV
+ cache, recurrent state, overhead and host checkpoints are 0 because vLLM
+ keeps them inside its preallocated share. The context does not change it.
+ """
+ weights = _vllm_weights_bytes(model, weight_size_mb) / GIB
+ device = round(weights / VLLM_GPU_MEMORY_UTILIZATION, 2)
+ cache = _vllm_kv_cache_dtype(model)
+ return MemoryEstimate(
+ context_length=_context(model, context_length),
+ cache_type_k=cache,
+ cache_type_v=cache,
+ layers=None,
+ kv_layers=None,
+ kv_bytes_per_token=None,
+ weights_gib=round(weights, 3),
+ kv_gib=0.0,
+ recurrent_state_gib=0.0,
+ compute_overhead_gib=0.0,
+ host_checkpoint_gib=0.0,
+ device_gib=device,
+ total_gib=device,
+ method="vllm",
+ )
+
+
def estimated_context_kv_gb(
model: dict[str, Any],
context_length: int | None = None,
) -> float:
- """Estimate standard llama.cpp f16 KV pressure at the selected context."""
+ """Estimate standard llama.cpp f16 KV pressure at the selected context.
+
+ A vLLM entry adds none: its KV cache lives inside the share of the GPU
+ vLLM preallocates (see :func:`vllm_memory_estimate`).
+ """
+ if model.get("runtime") == VLLM_RUNTIME:
+ return 0.0
context = _context(model, context_length)
per_token = kv_bytes_per_token(model)
if per_token is not None:
diff --git a/ods/extensions/services/dashboard-api/model_vllm.py b/ods/extensions/services/dashboard-api/model_vllm.py
new file mode 100644
index 000000000..5067b3ac8
--- /dev/null
+++ b/ods/extensions/services/dashboard-api/model_vllm.py
@@ -0,0 +1,311 @@
+"""vLLM catalog entries: schema, model folder and GPU fit.
+
+Entries in config/model-library.json with ``"runtime": "vllm"`` are served by
+the vLLM engine (``.env`` ``LLM_BACKEND=vllm``), not llama.cpp. They carry no
+``gguf_*`` fields; each one pins a whole Hugging Face snapshot instead:
+
+* ``hf_repo`` and ``revision`` (the full 40-hex commit);
+* ``files``: every file at that commit, ``{path, size, sha256}`` for an LFS
+ file and ``{path, size, git_blob_sha1}`` for a small file git stores itself
+ (the blob id Hugging Face reports: sha1 of ``"blob <size>\\0"`` + content);
+* ``served_model_name`` (the id vLLM serves, ``.env`` ``VLLM_SERVED_MODEL``),
+ ``context_length`` (equal to ``--max-model-len``) and ``vllm_args``;
+* ``min_gpu_mib`` and ``compute_capability``: the one GPU vLLM runs on needs
+ at least this much memory (nvidia-smi ``memory.total``) and one of these
+ compute capabilities;
+* ``reasoning`` (the thinking default), plus ``tool_call_parser`` and
+ ``reasoning_parser``, which name the same parsers as ``vllm_args``;
+* ``selection``: 0 for every llama.cpp memory class, so no llama.cpp install
+ ever picks the entry, and a ``vllm`` priority for ``--llm-runtime vllm``.
+
+JSON-valued vLLM options go in ``vllm_args`` as vLLM's dotted flags, so each
+argument stays a plain token: ``--speculative-config.method=mtp
+--speculative-config.num_speculative_tokens=3`` parses to the same config as
+``--speculative-config '{"method":"mtp","num_speculative_tokens":3}'``.
+
+scripts/select-model.py (``--llm-runtime vllm``), scripts/download-hf-manifest.py
+and the catalog tests share these rules. Standard library only and no sibling
+imports, so a caller can load this file by path, as bin/ods-host-agent.py loads
+model_memory.py.
+"""
+
+from __future__ import annotations
+
+import re
+import shlex
+from typing import Any, Iterable, NamedTuple
+
+
+VLLM_RUNTIME = "vllm"
+REASONING_LEVELS = ("off", "low", "medium", "high")
+LLAMA_MEMORY_CLASSES = ("discrete", "unified", "cpu")
+# The vllm-server compose service passes these itself:
+# --model /model --served-model-name ${VLLM_SERVED_MODEL} ${VLLM_ARGS}.
+COMPOSE_FLAGS = frozenset({"--model", "--served-model-name", "--host", "--port"})
+# A file downloads under <name><PARTIAL_SUFFIX> until it is verified.
+PARTIAL_SUFFIX = ".partial"
+GPU_QUERY = "nvidia-smi --query-gpu=uuid,compute_cap,memory.total --format=csv,noheader,nounits"
+
+_HF_REPO = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*/[A-Za-z0-9][A-Za-z0-9._-]*")
+_HEX40 = re.compile(r"[0-9a-f]{40}")
+_HEX64 = re.compile(r"[0-9a-f]{64}")
+_COMPUTE_CAPABILITY = re.compile(r"[0-9]+\.[0-9]+")
+_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*")
+# vllm_args travel through .env VLLM_ARGS and compose's shell-like command
+# splitting, so they hold no whitespace, quotes or shell syntax.
+_ARG = re.compile(r"[A-Za-z0-9_.:/=,+-]+")
+_GPU_UUID = re.compile(r"[A-Za-z0-9][A-Za-z0-9-]*")
+_GPU_MEMORY = re.compile(r"([0-9]+)(?:\s*MiB)?")
+_FILE_KEYS = ({"path", "size", "sha256"}, {"path", "size", "git_blob_sha1"})
+_SELECTION_KEYS = frozenset(LLAMA_MEMORY_CLASSES) | {VLLM_RUNTIME}
+_LLAMA_KEYS = frozenset({"llama_server_image", "runtime_profiles", "mmproj_file", "mmproj_url", "mmproj_sha256"})
+
+
+class Gpu(NamedTuple):
+ """One NVIDIA GPU as nvidia-smi reports it."""
+
+ uuid: str
+ compute_capability: str
+ memory_mib: int
+
+
+class Candidate(NamedTuple):
+ """One vLLM entry planned onto the GPU it would own."""
+
+ model: dict
+ gpu: Gpu
+ priority: int
+ meets_min_context: bool
+
+
+def is_vllm_entry(model: Any) -> bool:
+ return isinstance(model, dict) and model.get("runtime") == VLLM_RUNTIME
+
+
+def model_dir_name(model: dict[str, Any]) -> str:
+ """The folder under data/models/ (``.env`` VLLM_MODEL_DIR): ``owner--name@<revision[:8]>``."""
+ return f"{model['hf_repo'].replace('/', '--')}@{model['revision'][:8]}"
+
+
+def manifest_bytes(model: dict[str, Any]) -> int:
+ return sum(int(item["size"]) for item in model["files"])
+
+
+def flag_value(args: list[str], flag: str) -> str | None:
+ """The value after ``flag`` (or in ``flag=value``), "" without one, None when absent."""
+ for index, arg in enumerate(args):
+ if arg == flag:
+ return args[index + 1] if index + 1 < len(args) else ""
+ if arg.startswith(flag + "="):
+ return arg.split("=", 1)[1]
+ return None
+
+
+def vllm_args_text(model: dict[str, Any]) -> str:
+ """``vllm_args`` as one string for ``.env`` VLLM_ARGS; compose splits it again."""
+ return shlex.join(model["vllm_args"])
+
+
+def selection_priority(model: dict[str, Any]) -> int:
+ """The ``selection.vllm`` priority; 0 (or none) means never auto-selected."""
+ selection = model.get("selection")
+ value = selection.get(VLLM_RUNTIME, 0) if isinstance(selection, dict) else 0
+ return value if isinstance(value, int) and not isinstance(value, bool) else 0
+
+
+def path_problem(path: Any) -> str | None:
+ """Why ``path`` is unsafe to create under the model folder, or None."""
+ if not isinstance(path, str) or not path:
+ return "is empty"
+ if "\\" in path or "\x00" in path or ":" in path or path.startswith("/"):
+ return "must be a relative POSIX path"
+ if any(part in {"", ".", ".."} for part in path.split("/")):
+ return "may not contain empty, '.' or '..' parts"
+ if path.endswith(PARTIAL_SUFFIX):
+ return f"may not end in {PARTIAL_SUFFIX}, the download's temporary suffix"
+ return None
+
+
+def _whole(value: Any, minimum: int = 0) -> bool:
+ return isinstance(value, int) and not isinstance(value, bool) and value >= minimum
+
+
+def _file_problems(files: Any) -> list[str]:
+ if not isinstance(files, list) or not files:
+ return ["files must list every file of the pinned revision"]
+ problems: list[str] = []
+ seen: set[str] = set()
+ for index, item in enumerate(files):
+ where = f"files[{index}]"
+ if not isinstance(item, dict) or set(item) not in _FILE_KEYS:
+ problems.append(f"{where} must be {{path, size, sha256}} or {{path, size, git_blob_sha1}}")
+ continue
+ unsafe = path_problem(item["path"])
+ if unsafe:
+ problems.append(f"{where} path {item['path']!r} {unsafe}")
+ elif item["path"] in seen:
+ problems.append(f"{where} repeats {item['path']}")
+ else:
+ seen.add(item["path"])
+ if not _whole(item["size"]):
+ problems.append(f"{where} size must be a whole number of bytes")
+ lfs = "sha256" in item
+ digest = item["sha256"] if lfs else item["git_blob_sha1"]
+ if not isinstance(digest, str) or not (_HEX64 if lfs else _HEX40).fullmatch(digest):
+ problems.append(f"{where} {'sha256' if lfs else 'git_blob_sha1'} must be lowercase hex")
+ return problems
+
+
+def _args_problems(model: dict[str, Any]) -> list[str]:
+ args = model.get("vllm_args")
+ if not isinstance(args, list) or not args or not all(
+ isinstance(arg, str) and _ARG.fullmatch(arg) for arg in args
+ ):
+ return ["vllm_args must be a list of plain strings (letters, digits and _.:/=,+-)"]
+ problems = []
+ owned = sorted({arg.split("=", 1)[0] for arg in args} & COMPOSE_FLAGS)
+ if owned:
+ problems.append(f"vllm_args may not set {', '.join(owned)}: the vllm-server service sets them")
+ for flag, key in (("--max-model-len", "context_length"), ("--tool-call-parser", "tool_call_parser"),
+ ("--reasoning-parser", "reasoning_parser")):
+ if flag_value(args, flag) != str(model.get(key)):
+ problems.append(f"vllm_args {flag} must equal the entry's {key} ({model.get(key)})")
+ if "--enable-auto-tool-choice" not in args:
+ problems.append("vllm_args needs --enable-auto-tool-choice so the tool-call parser runs")
+ return problems
+
+
+def _selection_problems(selection: Any) -> list[str]:
+ if not isinstance(selection, dict) or not set(selection) <= _SELECTION_KEYS:
+ return [f"selection may hold only {', '.join(sorted(_SELECTION_KEYS))}"]
+ problems = [
+ f"selection.{memory_class} must be 0: a llama.cpp install never picks a vLLM entry"
+ for memory_class in LLAMA_MEMORY_CLASSES
+ if selection.get(memory_class) != 0 or isinstance(selection.get(memory_class), bool)
+ ]
+ if not _whole(selection.get(VLLM_RUNTIME)):
+ problems.append("selection.vllm must be a whole number (0 never auto-selects)")
+ return problems
+
+
+def _identity_problems(model: dict[str, Any]) -> list[str]:
+ problems = []
+ for key in ("id", "llm_model_name", "served_model_name"):
+ if not isinstance(model.get(key), str) or not _NAME.fullmatch(model[key]):
+ problems.append(f"{key} must be letters, digits and ._-")
+ if not isinstance(model.get("name"), str) or not model["name"].strip():
+ problems.append("name must be set")
+ llama = sorted(key for key in model if key.startswith("gguf") or key in _LLAMA_KEYS)
+ if llama:
+ problems.append(f"llama.cpp fields do not apply to a vLLM entry: {', '.join(llama)}")
+ if not isinstance(model.get("hf_repo"), str) or not _HF_REPO.fullmatch(model["hf_repo"]):
+ problems.append("hf_repo must be <owner>/<name>")
+ if not isinstance(model.get("revision"), str) or not _HEX40.fullmatch(model["revision"]):
+ problems.append("revision must be the full 40-hex commit")
+ return problems
+
+
+def _serving_problems(model: dict[str, Any]) -> list[str]:
+ problems = []
+ if not _whole(model.get("context_length"), 1):
+ problems.append("context_length must be a positive whole number")
+ elif "max_context_length" in model and not _whole(model["max_context_length"], model["context_length"]):
+ problems.append("max_context_length (config.json max_position_embeddings) must be at least context_length")
+ if not _whole(model.get("min_gpu_mib"), 1):
+ problems.append("min_gpu_mib must be a positive whole number of MiB")
+ capabilities = model.get("compute_capability")
+ if (not isinstance(capabilities, list) or not capabilities
+ or len(set(map(str, capabilities))) != len(capabilities)
+ or not all(isinstance(item, str) and _COMPUTE_CAPABILITY.fullmatch(item) for item in capabilities)):
+ problems.append('compute_capability must list distinct "major.minor" strings')
+ if model.get("reasoning") not in REASONING_LEVELS:
+ problems.append(f"reasoning must be one of {', '.join(REASONING_LEVELS)}")
+ for key in ("tool_call_parser", "reasoning_parser"):
+ if not isinstance(model.get(key), str) or not _ARG.fullmatch(model[key]):
+ problems.append(f"{key} must name a vLLM parser")
+ return problems
+
+
+def _size_problems(model: dict[str, Any]) -> list[str]:
+ total = manifest_bytes(model)
+ problems = []
+ if "size_bytes" in model and model["size_bytes"] != total:
+ problems.append(f"size_bytes must be the manifest total, {total}")
+ if "size_mb" in model and model["size_mb"] != round(total / 1_000_000):
+ problems.append(f"size_mb must be the manifest total in MB, {round(total / 1_000_000)}")
+ return problems
+
+
+def entry_problems(model: Any) -> list[str]:
+ """Every way ``model`` breaks the vLLM entry schema (see the module doc)."""
+ if not is_vllm_entry(model):
+ return ["runtime is not vllm"]
+ files = _file_problems(model.get("files"))
+ problems = [
+ *_identity_problems(model),
+ *files,
+ *_serving_problems(model),
+ *_args_problems(model),
+ *_selection_problems(model.get("selection")),
+ *([] if files else _size_problems(model)),
+ ]
+ return [f"{model.get('id') or '<no id>'}: {problem}" for problem in problems]
+
+
+def require_valid(model: dict[str, Any]) -> dict[str, Any]:
+ problems = entry_problems(model)
+ if problems:
+ raise ValueError("invalid vLLM catalog entry: " + "; ".join(problems))
+ return model
+
+
+def parse_gpu(text: str) -> Gpu:
+ """One row of :data:`GPU_QUERY` output: ``UUID, COMPUTE_CAP, MEMORY_MIB``."""
+ parts = [part.strip() for part in str(text).split(",")]
+ if len(parts) == 3:
+ uuid, capability, memory = parts
+ size = _GPU_MEMORY.fullmatch(memory)
+ if _GPU_UUID.fullmatch(uuid) and _COMPUTE_CAPABILITY.fullmatch(capability) and size:
+ return Gpu(uuid, capability, int(size.group(1)))
+ raise ValueError(f"{text!r} is not UUID,COMPUTE_CAP,MEMORY_MIB ({GPU_QUERY})")
+
+
+def gpu_fits(model: dict[str, Any], gpu: Gpu) -> bool:
+ return gpu.compute_capability in model["compute_capability"] and gpu.memory_mib >= model["min_gpu_mib"]
+
+
+def best_gpu(model: dict[str, Any], gpus: Iterable[Gpu]) -> Gpu | None:
+ """The largest GPU ``model`` fits on (the first listed on a tie), or None."""
+ fitting = [gpu for gpu in gpus if gpu_fits(model, gpu)]
+ return max(fitting, key=lambda gpu: gpu.memory_mib) if fitting else None
+
+
+def requirement_text(model: dict[str, Any]) -> str:
+ capabilities = " or ".join(model["compute_capability"])
+ return f"one GPU with compute capability {capabilities} and at least {model['min_gpu_mib']} MiB"
+
+
+def rank_entries(catalog: Iterable[dict[str, Any]], gpus: Iterable[Gpu], *,
+ min_context: int = 0, require_min_context: bool = False,
+ installable_only: bool = False) -> list[Candidate]:
+ """Every curated vLLM entry that fits one of ``gpus``, best first.
+
+ Order: meets ``min_context``, then the ``selection.vllm`` priority, then
+ the larger snapshot. A malformed entry raises ValueError.
+ """
+ gpus = list(gpus)
+ pool = []
+ for model in catalog:
+ if not is_vllm_entry(model) or str(model.get("source") or "").strip().lower() not in {"", "curated"}:
+ continue
+ require_valid(model)
+ if installable_only and model.get("install_recommendation", True) is False:
+ continue
+ priority = selection_priority(model)
+ gpu = best_gpu(model, gpus)
+ meets = not min_context or model["context_length"] >= min_context
+ if priority <= 0 or gpu is None or (require_min_context and not meets):
+ continue
+ pool.append(Candidate(model, gpu, priority, meets))
+ pool.sort(key=lambda item: (item.meets_min_context, item.priority, manifest_bytes(item.model)), reverse=True)
+ return pool
diff --git a/ods/extensions/services/dashboard-api/tests/test_model_memory.py b/ods/extensions/services/dashboard-api/tests/test_model_memory.py
index a6934fc28..9af1db61f 100644
--- a/ods/extensions/services/dashboard-api/tests/test_model_memory.py
+++ b/ods/extensions/services/dashboard-api/tests/test_model_memory.py
@@ -544,3 +544,78 @@ class TestArchitectureEstimator:
assert sliding_window_kv_bytes_per_cell(ARCH["qwen3.5-9b"]) == 0
assert sliding_window_cells(ARCH["qwen3.5-9b"], 65536) == 0
assert estimate_model_memory(ARCH["qwen3.5-9b"], context_length=65536).swa_kv_gib == 0
+
+
+# ---------------------------------------------------------------------------
+# vLLM entries ("runtime": "vllm"): weights = manifest total, device need =
+# weights / VLLM_GPU_MEMORY_UTILIZATION, no llama.cpp KV or checkpoint maths.
+# ---------------------------------------------------------------------------
+
+from model_memory import VLLM_GPU_MEMORY_UTILIZATION, memory_metadata # noqa: E402
+
+VLLM_ENTRY = {
+ "id": "test-vllm", "runtime": "vllm", "context_length": 131072,
+ "files": [
+ {"path": "config.json", "size": 30 * 1024 ** 2, "git_blob_sha1": "0" * 40},
+ {"path": "model-00001-of-00002.safetensors", "size": 60 * 1024 ** 3, "sha256": "0" * 64},
+ {"path": "model-00002-of-00002.safetensors", "size": 30 * 1024 ** 3, "sha256": "0" * 64},
+ ],
+ "vllm_args": ["--max-model-len", "131072", "--kv-cache-dtype", "fp8"],
+ # llama.cpp metadata a vLLM entry would never carry; it must be ignored.
+ "block_count": 48, "attention_head_count_kv": 4, "attention_key_length": 128,
+ "attention_value_length": 128, "recurrent_state_bytes": 0, "vram_required_gb": 500,
+}
+
+
+class TestVllmEstimate:
+
+ def test_device_need_is_the_weights_over_the_utilisation_share(self):
+ estimate = estimate_model_memory(VLLM_ENTRY)
+ weights = 90 + 30 / 1024
+ assert VLLM_GPU_MEMORY_UTILIZATION == 0.90
+ assert estimate.method == "vllm"
+ assert estimate.weights_gib == round(weights, 3)
+ assert estimate.device_gib == estimate.total_gib == round(weights / 0.90, 2) == 100.03
+ assert (estimate.kv_gib, estimate.recurrent_state_gib, estimate.compute_overhead_gib,
+ estimate.host_checkpoint_gib, estimate.swa_kv_gib) == (0, 0, 0, 0, 0)
+ assert (estimate.cache_type_k, estimate.cache_type_v) == ("fp8", "fp8")
+ assert estimate.kv_bytes_per_token is None
+
+ def test_context_and_llama_cache_settings_do_not_change_it(self):
+ base = estimate_model_memory(VLLM_ENTRY).device_gib
+ for context in (8192, 65536, 262144):
+ assert estimate_model_memory(VLLM_ENTRY, context_length=context, cache_type_k="q4_0",
+ cache_type_v="q4_0", parallel=4, ctx_checkpoints=32).device_gib == base
+ assert estimated_context_kv_gb(VLLM_ENTRY, 262144) == 0.0
+ profile = {"env": {"LLAMA_ARG_CACHE_TYPE_K": "q8_0", "LLAMA_PARALLEL": "2"}}
+ assert required_model_memory_gb(VLLM_ENTRY, runtime_profile=profile) == base
+ assert required_model_memory_gb(VLLM_ENTRY, include_host_state=True) == base
+
+ def test_measured_weights_override_the_manifest(self):
+ assert estimate_model_memory(VLLM_ENTRY, weight_size_mb=92160).device_gib == 100.0
+
+ def test_kv_cache_dtype_defaults_to_auto(self):
+ entry = {**VLLM_ENTRY, "vllm_args": ["--max-model-len", "131072"]}
+ assert estimate_model_memory(entry).cache_type_k == "auto"
+ entry = {**VLLM_ENTRY, "vllm_args": ["--kv-cache-dtype=fp8_e4m3"]}
+ assert estimate_model_memory(entry).cache_type_v == "fp8_e4m3"
+
+ def test_normalized_records_keep_what_the_estimate_reads(self):
+ kept = memory_metadata(VLLM_ENTRY)
+ assert {key: kept[key] for key in ("runtime", "files", "vllm_args")} == {
+ key: VLLM_ENTRY[key] for key in ("runtime", "files", "vllm_args")
+ }
+ assert estimate_model_memory(kept).device_gib == estimate_model_memory(VLLM_ENTRY).device_gib
+
+ def test_catalog_vllm_entries_get_a_sane_number_below_their_gpu_minimum(self):
+ entries = [raw for raw in _catalog_entries() if raw.get("runtime") == "vllm"]
+ assert len(entries) == 2
+ select_model = _load_select_model()
+ for raw in entries:
+ weights = sum(item["size"] for item in raw["files"]) / 1024 ** 3
+ estimate = estimate_model_memory(raw)
+ assert estimate.method == "vllm"
+ assert estimate.weights_gib == round(weights, 3)
+ assert estimate.device_gib == round(weights / 0.90, 2)
+ assert estimate.device_gib * 1024 < raw["min_gpu_mib"]
+ assert select_model.selector_required_memory_gb(raw) == estimate.device_gib
diff --git a/ods/scripts/download-hf-manifest.py b/ods/scripts/download-hf-manifest.py
new file mode 100644
index 000000000..41c03524b
--- /dev/null
+++ b/ods/scripts/download-hf-manifest.py
@@ -0,0 +1,329 @@
+#!/usr/bin/env python3
+"""Download a vLLM catalog model's pinned Hugging Face files and verify each one.
+
+A config/model-library.json entry with ``"runtime": "vllm"`` pins a Hugging
+Face repo at a full commit and lists every file there with its size and its
+sha256 (LFS files) or git blob sha1 (small files); see
+extensions/services/dashboard-api/model_vllm.py. This helper fetches that
+manifest into ``<models-dir>/<owner>--<name>@<revision[:8]>/``, the folder
+``.env`` VLLM_MODEL_DIR names, with the Python standard library only:
+
+* each file downloads to ``<name>.partial`` and is renamed into place only
+ after its size and digest match, so a file under its final name is always a
+ verified one; a ``.partial`` file an interruption left behind resumes with an
+ HTTP Range request on the next run;
+* files already in place are verified again and replaced when they differ;
+* it refuses to start when the volume has less free space than the bytes
+ still to download plus the margin model downloads keep (5% of the volume,
+ at least 2 GiB, as bin/ods-host-agent.py _download_disk_margin);
+* progress lines go to stdout, failures to stderr.
+
+It never retries: an interrupted download keeps its bytes, so run it again to
+resume. Exit codes: 0 every file verified; 1 download or catalog error; 3 a
+file did not match the catalog (its download was deleted); 4 not enough free
+disk.
+
+Usage:
+ download-hf-manifest.py --catalog config/model-library.json \\
+ --model-id qwen3.8-flash-next-nvfp4-vllm --models-dir data/models
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import os
+import re
+import shutil
+import socket
+import sys
+import urllib.error
+import urllib.request
+from http.client import HTTPException
+from pathlib import Path
+from typing import Any
+from urllib.parse import quote
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "extensions/services/dashboard-api"))
+from model_vllm import ( # noqa: E402
+ PARTIAL_SUFFIX,
+ is_vllm_entry,
+ manifest_bytes,
+ model_dir_name,
+ require_valid,
+)
+
+
+DEFAULT_BASE_URL = "https://huggingface.co"
+CHUNK_BYTES = 8 * 1024 * 1024
+TIMEOUT_SECONDS = 60
+USER_AGENT = "ods-download-hf-manifest/1"
+MARGIN_MIN_BYTES = 2 * 1024 ** 3
+MARGIN_FRACTION = 0.05
+GB = 1000 ** 3
+EXIT_FAILED = 1
+EXIT_MISMATCH = 3
+EXIT_NO_SPACE = 4
+HELP_URL = os.environ.get("ODS_HELP_DISCORD_URL") or "https://discord.gg/4ntNp9MAwC"
+_CONTENT_RANGE = re.compile(r"bytes ([0-9]+)-([0-9]+)/([0-9]+|\*)")
+
+
+class Mismatch(Exception):
+ """A complete file whose size or digest differs from the catalog."""
+
+
+class NoSpace(Exception):
+ """The volume cannot hold the rest of the download plus the margin."""
+
+
+class DownloadStopped(Exception):
+ """The server ended a file early or answered unexpectedly; bytes so far stay."""
+
+
+class HubRefused(Exception):
+ """Hugging Face answered a file request with an HTTP error status."""
+
+
+class Progress:
+ """A stdout line each time the whole download passes another percent."""
+
+ def __init__(self, total: int):
+ self.total = max(total, 1)
+ self.completed = 0
+ self.current = 0
+ self.shown = -1
+
+ def advance(self, count: int) -> None:
+ self.current += count
+ self._show()
+
+ def restart_file(self) -> None:
+ self.current = 0
+
+ def finish_file(self) -> None:
+ self.completed += self.current
+ self.current = 0
+ self._show()
+
+ def _show(self) -> None:
+ done = self.completed + self.current
+ percent = done * 100 // self.total
+ if percent > self.shown:
+ self.shown = percent
+ print(f"progress: {percent}% {done / GB:.1f} of {self.total / GB:.1f} GB", flush=True)
+
+
+def find_entry(catalog: Path, model_id: str) -> dict[str, Any]:
+ """The one catalog entry whose id or llm_model_name is ``model_id``; it must be vLLM."""
+ models = json.loads(catalog.read_text(encoding="utf-8")).get("models", [])
+ matches = [model for model in models if isinstance(model, dict)
+ and model_id in {model.get("id"), model.get("llm_model_name")}]
+ if len(matches) != 1:
+ raise LookupError(f"{model_id!r} names {len(matches)} catalog models, not one")
+ if not is_vllm_entry(matches[0]):
+ raise LookupError(f"{model_id} is a llama.cpp model; this helper downloads vLLM models only")
+ return require_valid(matches[0])
+
+
+def file_url(base_url: str, model: dict[str, Any], path: str) -> str:
+ return f"{base_url.rstrip('/')}/{model['hf_repo']}/resolve/{model['revision']}/{quote(path, safe='/')}"
+
+
+def new_digest(item: dict[str, Any]) -> Any:
+ """sha256 of the content for an LFS file; git's blob sha1 for a small one."""
+ if "sha256" in item:
+ return hashlib.sha256()
+ digest = hashlib.sha1()
+ digest.update(b"blob %d\0" % item["size"])
+ return digest
+
+
+def expected_digest(item: dict[str, Any]) -> str:
+ return item["sha256"] if "sha256" in item else item["git_blob_sha1"]
+
+
+def hash_into(digest: Any, path: Path, progress: Progress) -> None:
+ with path.open("rb") as handle:
+ for chunk in iter(lambda: handle.read(CHUNK_BYTES), b""):
+ digest.update(chunk)
+ progress.advance(len(chunk))
+
+
+def verified_in_place(final: Path, item: dict[str, Any], progress: Progress) -> bool:
+ """True when ``final`` already holds exactly the catalog file."""
+ if not final.is_file() or final.stat().st_size != item["size"]:
+ return False
+ digest = new_digest(item)
+ hash_into(digest, final, progress)
+ if digest.hexdigest() == expected_digest(item):
+ return True
+ progress.restart_file()
+ return False
+
+
+def _check_content_range(response: Any, offset: int, size: int) -> None:
+ match = _CONTENT_RANGE.fullmatch(str(response.headers.get("Content-Range") or ""))
+ if not match or int(match.group(1)) != offset or match.group(3) not in {str(size), "*"}:
+ raise DownloadStopped(
+ f"the server resumed at {response.headers.get('Content-Range')!r}, not at byte {offset} of {size}"
+ )
+
+
+def fetch(url: str, partial: Path, offset: int, item: dict[str, Any], digest: Any,
+ progress: Progress) -> Any:
+ """Append bytes ``offset``.. of ``url`` to ``partial``; return the running digest."""
+ headers = {"User-Agent": USER_AGENT}
+ if offset:
+ headers["Range"] = f"bytes={offset}-"
+ try:
+ response = urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=TIMEOUT_SECONDS)
+ except urllib.error.HTTPError as exc:
+ # Report the resolve URL, not the signed CDN URL a redirect led to.
+ raise HubRefused(f"Hugging Face answered HTTP {exc.code} for {url}") from exc
+ with response:
+ if offset and response.status == 206:
+ _check_content_range(response, offset, item["size"])
+ elif response.status == 200:
+ if offset:
+ # The server ignored the Range header: start the file again.
+ offset, digest = 0, new_digest(item)
+ progress.restart_file()
+ else:
+ raise DownloadStopped(f"unexpected HTTP {response.status} for {item['path']}")
+ remaining = item["size"] - offset
+ with partial.open("ab" if offset else "wb") as handle:
+ while remaining > 0:
+ chunk = response.read(min(CHUNK_BYTES, remaining))
+ if not chunk:
+ break
+ handle.write(chunk)
+ digest.update(chunk)
+ progress.advance(len(chunk))
+ remaining -= len(chunk)
+ handle.flush()
+ os.fsync(handle.fileno())
+ if remaining > 0:
+ raise DownloadStopped(f"the server ended {item['path']} {remaining} bytes early")
+ return digest
+
+
+def download(url: str, partial: Path, item: dict[str, Any], progress: Progress) -> None:
+ """Complete ``partial`` (resuming what is there) and verify it, or delete it."""
+ offset = partial.stat().st_size if partial.is_file() else 0
+ if offset > item["size"]:
+ partial.unlink()
+ offset = 0
+ digest = new_digest(item)
+ if offset:
+ hash_into(digest, partial, progress)
+ if offset < item["size"] or not partial.exists():
+ digest = fetch(url, partial, offset, item, digest, progress)
+ actual = digest.hexdigest()
+ if partial.stat().st_size != item["size"] or actual != expected_digest(item):
+ partial.unlink()
+ kind = "sha256" if "sha256" in item else "git blob sha1"
+ raise Mismatch(
+ f"{item['path']} does not match the catalog ({kind} {actual}, expected "
+ f"{expected_digest(item)}), so its download was deleted. Run this again to fetch it again."
+ )
+
+
+def bytes_to_download(target: Path, files: list[dict[str, Any]]) -> int:
+ """Bytes still to fetch; a file in place at the right size counts as done."""
+ needed = 0
+ for item in files:
+ final = target / item["path"]
+ if final.is_file() and final.stat().st_size == item["size"]:
+ continue
+ partial = final.with_name(final.name + PARTIAL_SUFFIX)
+ have = partial.stat().st_size if partial.is_file() else 0
+ needed += item["size"] - have if have <= item["size"] else item["size"]
+ return needed
+
+
+def check_space(target: Path, files: list[dict[str, Any]]) -> None:
+ needed = bytes_to_download(target, files)
+ if not needed:
+ return
+ usage = shutil.disk_usage(target)
+ margin = max(MARGIN_MIN_BYTES, int(usage.total * MARGIN_FRACTION))
+ if usage.free < needed + margin:
+ raise NoSpace(
+ f"{target} has {usage.free / GB:.1f} GB free, but this model needs {needed / GB:.1f} GB more "
+ f"plus a {margin / GB:.1f} GB safety margin. Free up space or choose a smaller model, "
+ f"then run this again."
+ )
+
+
+def _safe_destination(final: Path) -> Path:
+ partial = final.with_name(final.name + PARTIAL_SUFFIX)
+ for path in (final, partial):
+ if path.is_symlink():
+ raise DownloadStopped(f"refusing to write through the symbolic link {path}")
+ return partial
+
+
+def fetch_manifest(model: dict[str, Any], models_dir: Path, base_url: str) -> Path:
+ """Download and verify every manifest file; return the model folder."""
+ target = models_dir / model_dir_name(model)
+ target.mkdir(parents=True, exist_ok=True)
+ files = model["files"]
+ check_space(target, files)
+ print(f"plan: {model['hf_repo']}@{model['revision'][:8]}, {len(files)} files, "
+ f"{manifest_bytes(model) / GB:.1f} GB, into {target}", flush=True)
+ progress = Progress(manifest_bytes(model))
+ for index, item in enumerate(files, 1):
+ final = target / item["path"]
+ final.parent.mkdir(parents=True, exist_ok=True)
+ partial = _safe_destination(final)
+ if verified_in_place(final, item, progress):
+ progress.finish_file()
+ print(f"verified [{index}/{len(files)}] {item['path']} (already downloaded)", flush=True)
+ continue
+ if final.exists():
+ print(f"replacing {item['path']}: it does not match the catalog", flush=True)
+ final.unlink()
+ download(file_url(base_url, model, item["path"]), partial, item, progress)
+ os.replace(partial, final)
+ progress.finish_file()
+ print(f"verified [{index}/{len(files)}] {item['path']}", flush=True)
+ print(f"done: {len(files)} files verified in {target}", flush=True)
+ return target
+
+
+def _fail(message: str, code: int) -> int:
+ print(f"error: {message}\nNeed help? Ask on the ODS Discord: {HELP_URL}", file=sys.stderr)
+ return code
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--catalog", required=True, type=Path)
+ parser.add_argument("--model-id", required=True,
+ help="id or llm_model_name of a runtime: vllm catalog entry (select-model.py's LLM_MODEL)")
+ parser.add_argument("--models-dir", required=True, type=Path,
+ help="data/models; files land in <models-dir>/<VLLM_MODEL_DIR>/")
+ parser.add_argument("--base-url", default=DEFAULT_BASE_URL,
+ help="Hugging Face endpoint (tests point it at a local server)")
+ args = parser.parse_args(argv)
+ try:
+ model = find_entry(args.catalog, args.model_id)
+ except (OSError, ValueError, LookupError) as exc:
+ return _fail(f"cannot download {args.model_id} from {args.catalog}: {exc}", EXIT_FAILED)
+ try:
+ fetch_manifest(model, args.models_dir, args.base_url)
+ except NoSpace as exc:
+ return _fail(str(exc), EXIT_NO_SPACE)
+ except Mismatch as exc:
+ return _fail(str(exc), EXIT_MISMATCH)
+ except HubRefused as exc:
+ return _fail(f"{exc}. Files verified so far are kept.", EXIT_FAILED)
+ except (DownloadStopped, urllib.error.URLError, HTTPException, ConnectionError, TimeoutError,
+ socket.timeout) as exc:
+ return _fail(f"the download stopped: {exc}. Its bytes are kept: run this again to resume.", EXIT_FAILED)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/ods/scripts/select-model.py b/ods/scripts/select-model.py
index aa537c8de..ae795c7b8 100644
--- a/ods/scripts/select-model.py
+++ b/ods/scripts/select-model.py
@@ -5,6 +5,11 @@ This script is intentionally offline and deterministic. It only uses the
installer's detected hardware envelope plus the versioned model catalog; it
does not download GGUF metadata and it never treats catalog tok/s estimates as
measured performance.
+
+By default it picks a llama.cpp (GGUF) model and never looks at the catalog's
+vLLM entries (``"runtime": "vllm"``). ``--llm-runtime vllm`` picks only among
+those, for one GPU named by ``--gpu``, and fails rather than fall back to a
+GGUF model when none fits.
"""
from __future__ import annotations
@@ -17,7 +22,9 @@ from typing import Any
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "extensions/services/dashboard-api"))
from model_memory import ( # noqa: E402
+ VLLM_GPU_MEMORY_UTILIZATION,
context_fitting_model as context_fitting_model,
+ estimate_model_memory,
estimated_context_kv_gb as estimated_context_kv_gb,
estimated_param_billions as estimated_param_billions,
memory_metadata,
@@ -42,6 +49,18 @@ from model_selection import ( # noqa: E402
)
from model_selection import pixel_agent_ready as _pixel_agent_ready # noqa: E402
from model_selection import usable_memory_gb as _usable_memory_gb # noqa: E402
+from model_vllm import ( # noqa: E402
+ GPU_QUERY,
+ Candidate as VllmCandidate,
+ Gpu,
+ is_vllm_entry,
+ manifest_bytes,
+ model_dir_name,
+ parse_gpu,
+ rank_entries,
+ requirement_text,
+ vllm_args_text,
+)
VRAM_FIT_TOLERANCE_GB = 0.25
@@ -56,6 +75,8 @@ SPARK_AARCH64_MODEL_ID = "qwen3.6-35b-a3b-ud-q4"
# about why the substitution fired.
UNIFIED_MEMORY_POLICY = "unified-memory-coder-next-a3b-v1"
UNIFIED_MEMORY_MODEL_ID = SPARK_AARCH64_MODEL_ID
+VLLM_POLICY = "vllm-gpu-fit-v1"
+VLLM_SOURCE = "catalog_vllm_pre_download"
EXIT_NO_FIT = 2
EXIT_CHECK_FIT_FAILED = 3
@@ -142,13 +163,14 @@ def curated_source_allowed(model: dict[str, Any]) -> bool:
def load_catalog(path: Path) -> list[dict[str, Any]]:
+ """The curated llama.cpp (GGUF) models; vLLM entries are left to _vllm_main."""
with path.open("r", encoding="utf-8") as fh:
data = json.load(fh)
return [
model for model in (
normalize_model(raw)
for raw in data.get("models", [])
- if curated_source_allowed(raw)
+ if curated_source_allowed(raw) and not is_vllm_entry(raw)
)
if model is not None
]
@@ -445,7 +467,134 @@ def _check_fit_main(args: argparse.Namespace, catalog: list[dict[str, Any]],
return 0 if result["fits"] else EXIT_CHECK_FIT_FAILED
-def main() -> int:
+def _vllm_reason(candidate: VllmCandidate, min_context: int) -> str:
+ model, gpu = candidate.model, candidate.gpu
+ weights_gib = estimate_model_memory(model).weights_gib
+ room_gib = gpu.memory_mib * VLLM_GPU_MEMORY_UTILIZATION / 1024.0 - weights_gib
+ reason = (
+ f"Curated vLLM fit ({VLLM_POLICY}): {model['name']} is the highest-priority vLLM "
+ f"catalog model for GPU {gpu.uuid} (compute capability {gpu.compute_capability}, "
+ f"{gpu.memory_mib} MiB), which meets its {model['min_gpu_mib']} MiB minimum. Its "
+ f"{weights_gib:.1f} GiB of weights leave about {room_gib:.1f} GiB of vLLM's "
+ f"{VLLM_GPU_MEMORY_UTILIZATION:.2f} share of that GPU for KV cache and activations at "
+ f"{model['context_length'] // 1024}K context. Throughput requires a local benchmark "
+ f"after first launch."
+ )
+ if min_context and not candidate.meets_min_context:
+ reason += (
+ f" No vLLM catalog model serves the {min_context} context floor here; "
+ f"this one serves {model['context_length']}."
+ )
+ return reason
+
+
+def _vllm_no_fit(pool: list[dict[str, Any]], gpus: list[Gpu], args: argparse.Namespace) -> str:
+ if not pool:
+ if args.agent_ready_only:
+ return "no vLLM catalog model has an explicit verified Pixel capability verdict"
+ return "the catalog has no vLLM models"
+ if not gpus:
+ return f"--llm-runtime vllm needs the host's NVIDIA GPUs: pass each one as --gpu ({GPU_QUERY})"
+ seen = ", ".join(
+ f"{gpu.uuid} (compute capability {gpu.compute_capability}, {gpu.memory_mib} MiB)" for gpu in gpus
+ )
+ floor = f" at the {args.min_context} context floor" if args.require_min_context and args.min_context else ""
+ needs = "; ".join(f"{model['id']} needs {requirement_text(model)}" for model in pool)
+ return f"no vLLM catalog model fits this host{floor}. GPUs: {seen}. {needs}"
+
+
+def _vllm_payload(ranked: list[VllmCandidate], reason: str, min_context: int, host_arch: str) -> dict[str, Any]:
+ selected = ranked[0]
+ model, gpu = selected.model, selected.gpu
+ return {
+ "policy": VLLM_POLICY,
+ "source": VLLM_SOURCE,
+ "confidence": "high",
+ "runtime": "vllm",
+ "host_arch": normalize_host_arch(host_arch),
+ "gpu": gpu._asdict(),
+ "memory_capacity_gb": round(gpu.memory_mib / 1024.0, 1),
+ "memory_label": "GPU memory",
+ "memory_class": "discrete",
+ "min_context": min_context,
+ "meets_min_context": selected.meets_min_context,
+ "selected": {
+ **{key: value for key, value in model.items() if key != "files"},
+ "file_count": len(model["files"]),
+ "model_dir": model_dir_name(model),
+ "estimate": estimate_model_memory(model).as_dict(),
+ },
+ "reason": reason,
+ "alternatives": [
+ {"id": item.model["id"], "name": item.model["name"],
+ "context_length": item.model["context_length"], "min_gpu_mib": item.model["min_gpu_mib"],
+ "gpu": item.gpu.uuid, "model_dir": model_dir_name(item.model)}
+ for item in ranked[:3]
+ ],
+ }
+
+
+def _vllm_env(ranked: list[VllmCandidate], reason: str) -> dict[str, Any]:
+ """The installer contract for a vLLM pick (VLLM_* are .env keys as named)."""
+ model, gpu = ranked[0].model, ranked[0].gpu
+ return {
+ "LLM_MODEL": model["llm_model_name"],
+ # A vLLM pick has no GGUF: clear the tier map's so nothing downloads one.
+ "GGUF_FILE": "",
+ "GGUF_URL": "",
+ "GGUF_SHA256": "",
+ "MAX_CONTEXT": model["context_length"],
+ "LLM_MODEL_SIZE_MB": int(round(manifest_bytes(model) / 1_000_000)),
+ "MODEL_RECOMMENDATION_SOURCE": VLLM_SOURCE,
+ "MODEL_RECOMMENDATION_POLICY": VLLM_POLICY,
+ "MODEL_RECOMMENDATION_CONFIDENCE": "high",
+ "MODEL_RECOMMENDATION_REASON": reason,
+ "MODEL_RECOMMENDED_ALTERNATIVES": ";".join(
+ f"{item.model['id']}:{item.model['context_length']}:{item.model['min_gpu_mib'] / 1024.0:g}"
+ for item in ranked[:3]
+ ),
+ "PIXEL_AGENT_MODEL_READY": "true" if pixel_agent_ready(model) else "false",
+ "VLLM_MODEL_DIR": model_dir_name(model),
+ "VLLM_SERVED_MODEL": model["served_model_name"],
+ "VLLM_ARGS": vllm_args_text(model),
+ "VLLM_GPU_UUID": gpu.uuid,
+ }
+
+
+def _vllm_main(args: argparse.Namespace) -> int:
+ """``--llm-runtime vllm``: pick the best vLLM entry for one GPU, never a GGUF."""
+ if args.check_fit:
+ print("error: --check-fit checks llama.cpp models; a vLLM entry serves only "
+ "the context its --max-model-len fixes", file=sys.stderr)
+ return 1
+ try:
+ gpus = [parse_gpu(text) for text in args.gpu]
+ except ValueError as exc:
+ print(f"error: --gpu {exc}", file=sys.stderr)
+ return EXIT_NO_FIT
+ if normalize_backend(args.backend) != "nvidia":
+ print(f"error: vLLM models need NVIDIA GPUs; the detected backend is {args.backend}", file=sys.stderr)
+ return EXIT_NO_FIT
+ with args.catalog.open("r", encoding="utf-8") as fh:
+ pool = [model for model in json.load(fh).get("models", []) if is_vllm_entry(model)]
+ if args.agent_ready_only:
+ pool = [model for model in pool if pixel_agent_ready(model)]
+ min_context = max(int(args.min_context or 0), 0)
+ ranked = rank_entries(pool, gpus, min_context=min_context, require_min_context=args.require_min_context,
+ installable_only=args.installable_only)
+ if not ranked:
+ print(f"error: {_vllm_no_fit(pool, gpus, args)}", file=sys.stderr)
+ return EXIT_NO_FIT
+ reason = _vllm_reason(ranked[0], min_context)
+ if not args.env:
+ print(json.dumps(_vllm_payload(ranked, reason, min_context, args.host_arch), indent=2))
+ return 0
+ for key, value in _vllm_env(ranked, reason).items():
+ print(f"{key}={shell_value(value)}")
+ return 0
+
+
+def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--catalog", required=True, type=Path)
parser.add_argument("--backend", default="unknown")
@@ -484,8 +633,22 @@ def main() -> int:
parser.add_argument("--model-id", default="")
parser.add_argument("--context", type=int, default=0)
parser.add_argument("--runtime-profile", default="")
+ parser.add_argument(
+ "--llm-runtime", choices=("llama-server", "vllm"), default="llama-server",
+ help="The model server (.env LLM_BACKEND). llama-server (default) picks a GGUF "
+ "and never a vLLM entry; vllm picks only vLLM entries, for one --gpu, and "
+ "exits 2 when none fits. With vllm the fit comes from --gpu alone: --vram-mb, "
+ "--ram-gb, --memory-type, --tier, --profile and --max-size-mb are not read.",
+ )
+ parser.add_argument(
+ "--gpu", action="append", default=[], metavar="UUID,COMPUTE_CAP,MEMORY_MIB",
+ help=f"One NVIDIA GPU, a row of `{GPU_QUERY}`; repeat per GPU. "
+ "Read only with --llm-runtime vllm.",
+ )
parser.add_argument("--env", action="store_true", help="print shell assignments")
- args = parser.parse_args()
+ args = parser.parse_args(argv)
+ if args.llm_runtime == "vllm":
+ return _vllm_main(args)
catalog = load_catalog(args.catalog)
if not catalog:
diff --git a/ods/tests/ci-suite.txt b/ods/tests/ci-suite.txt
index 2a86cc4bb..f4a9e000f 100644
--- a/ods/tests/ci-suite.txt
+++ b/ods/tests/ci-suite.txt
@@ -143,6 +143,8 @@ tests/test-migrate-lemonade-install.py
tests/test-model-integrity.sh
tests/test-model-library-coverage.py
tests/test-model-library-verdicts.py
+tests/test-model-library-vllm.py
+tests/test_select_model_vllm.py
tests/test-native-llm-phase02.sh
tests/test-network-security.sh
tests/test-network-timeouts.sh
@@ -276,6 +278,7 @@ tests/test_extension_audit_library.py
tests/test_generate_llama_architectures.py
tests/test_healthcheck_redirect_policy.py
tests/test_hf_download_helper.py
+tests/test_hf_manifest_download.py
tests/test_macos_launchd_stop_live.py
tests/test_macos_recover_local_model.py
tests/test_macos_snapshot_definition.py
diff --git a/ods/tests/test-hermes-context-floor.sh b/ods/tests/test-hermes-context-floor.sh
index 29e0decc1..6d0a664d9 100644
--- a/ods/tests/test-hermes-context-floor.sh
+++ b/ods/tests/test-hermes-context-floor.sh
@@ -87,6 +87,7 @@ cp config/model-library.json "$fixture_dir/config/"
cp installers/lib/model-selector.sh "$fixture_dir/installers/lib/"
cp extensions/services/dashboard-api/model_memory.py \
extensions/services/dashboard-api/model_selection.py \
+ extensions/services/dashboard-api/model_vllm.py \
"$fixture_dir/extensions/services/dashboard-api/"
cp lib/python-cmd.sh "$fixture_dir/lib/"
diff --git a/ods/tests/test-model-library-architecture.py b/ods/tests/test-model-library-architecture.py
index a357d858c..40db1e17a 100644
--- a/ods/tests/test-model-library-architecture.py
+++ b/ods/tests/test-model-library-architecture.py
@@ -172,6 +172,12 @@ def test_selection_priorities_cover_every_memory_class():
assert {"discrete", "unified", "cpu"} <= set(selection), model["id"]
for memory_class in ("discrete", "unified", "cpu"):
assert isinstance(selection[memory_class], int) and selection[memory_class] >= 0, model["id"]
+ if model.get("runtime") == "vllm":
+ # vLLM entries never enter a llama.cpp pick; only --llm-runtime
+ # vllm reads their "vllm" priority (tests/test-model-library-vllm.py).
+ assert set(selection) == {"discrete", "unified", "cpu", "vllm"}, model["id"]
+ assert not any(selection[c] for c in ("discrete", "unified", "cpu")), model["id"]
+ continue
assert set(selection) <= {"discrete", "unified", "cpu", "min_capacity_gib"}, model["id"]
if model["id"] not in GEMMA_EXEMPT and any(selection[c] for c in ("discrete", "unified", "cpu")):
assert _installable(model), model["id"]
diff --git a/ods/tests/test-model-library-coverage.py b/ods/tests/test-model-library-coverage.py
index 72243e500..ec4237e33 100644
--- a/ods/tests/test-model-library-coverage.py
+++ b/ods/tests/test-model-library-coverage.py
@@ -77,7 +77,10 @@ def test_low_vram_catalog_has_six_agent_viable_downloadable_models():
low_vram = [
model
for model in models
- if int(model.get("vram_required_gb") or 0) <= 8
+ # vLLM entries need a datacenter GPU (min_gpu_mib) and download a
+ # snapshot, not a GGUF; they are never low-VRAM downloads.
+ if model.get("runtime") != "vllm"
+ and int(model.get("vram_required_gb") or 0) <= 8
and int(model.get("context_length") or 0) >= HERMES_CONTEXT_FLOOR
and _agent_viable_for_release(model)
]
diff --git a/ods/tests/test-model-library-pinned-urls.py b/ods/tests/test-model-library-pinned-urls.py
index 028ee0834..f21119913 100644
--- a/ods/tests/test-model-library-pinned-urls.py
+++ b/ods/tests/test-model-library-pinned-urls.py
@@ -8,6 +8,11 @@ both catalog downloads failed with HTTP 404 until they were repointed.
Pinning a 40-hex commit keeps ``gguf_url``, ``gguf_sha256`` and ``size_bytes``
describing one exact file.
+vLLM entries (``"runtime": "vllm"``) have no download URL: they pin the
+whole snapshot by ``hf_repo`` and a 40-hex ``revision`` and give every file a
+sha256 (LFS) or git blob sha1 (small files). They are checked here for that
+pin; tests/test-model-library-vllm.py checks the rest of their schema.
+
Network-free: this checks the catalog's shape, not Hugging Face. Verify a new
pin against the Hub's LFS metadata (``lfs.oid`` / ``lfs.size``) before adding it.
"""
@@ -27,6 +32,8 @@ PINNED_URL = re.compile(
r"(?P<repo>[^/\s]+/[^/\s]+)/resolve/(?P<revision>[0-9a-f]{40})/(?P<path>[^\s]+\.gguf)$"
)
SHA256 = re.compile(r"^[0-9a-f]{64}$")
+COMMIT = re.compile(r"^[0-9a-f]{40}$")
+HF_REPO = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*/[A-Za-z0-9][A-Za-z0-9._-]*$")
def _artifacts(model: dict) -> list[dict]:
@@ -43,10 +50,35 @@ def _artifacts(model: dict) -> list[dict]:
}]
-def _models() -> list[dict]:
+def _catalog_models() -> list[dict]:
return json.loads(CATALOG.read_text(encoding="utf-8"))["models"]
+def _models() -> list[dict]:
+ """The llama.cpp (GGUF) entries; vLLM entries pin a snapshot instead."""
+ return [model for model in _catalog_models() if model.get("runtime") != "vllm"]
+
+
+def test_every_vllm_snapshot_pins_a_commit_and_every_file_digest() -> None:
+ offenders = []
+ vllm = [model for model in _catalog_models() if model.get("runtime") == "vllm"]
+ for model in vllm:
+ if not HF_REPO.match(str(model.get("hf_repo") or "")) or not COMMIT.match(str(model.get("revision") or "")):
+ offenders.append(f"{model['id']}: hf_repo {model.get('hf_repo')!r} @ {model.get('revision')!r}")
+ for item in model.get("files") or [{}]:
+ digest_ok = (
+ SHA256.match(str(item.get("sha256") or "")) if "sha256" in item
+ else COMMIT.match(str(item.get("git_blob_sha1") or ""))
+ )
+ if not digest_ok or not isinstance(item.get("size"), int):
+ offenders.append(f"{model['id']}: {item.get('path') or '<missing path>'}")
+ assert vllm, "the catalog's vLLM entries went missing"
+ assert not offenders, (
+ "vLLM entries must pin <owner>/<repo> at a 40-hex commit and give every file a size and "
+ "a sha256 or git_blob_sha1:\n " + "\n ".join(offenders)
+ )
+
+
def test_every_download_url_pins_a_commit() -> None:
offenders = []
for model in _models():
@@ -115,6 +147,7 @@ def main() -> int:
test_every_download_declares_a_sha256()
test_split_parts_share_one_revision()
test_declared_source_matches_download_url()
+ test_every_vllm_snapshot_pins_a_commit_and_every_file_digest()
print("[PASS] Every catalog download pins a Hugging Face commit and declares a sha256")
return 0
diff --git a/ods/tests/test-model-library-vllm.py b/ods/tests/test-model-library-vllm.py
new file mode 100644
index 000000000..bb6ad8866
--- /dev/null
+++ b/ods/tests/test-model-library-vllm.py
@@ -0,0 +1,211 @@
+#!/usr/bin/env python3
+"""vLLM entries in config/model-library.json follow model_vllm.py's schema.
+
+A ``"runtime": "vllm"`` entry pins a Hugging Face snapshot (repo, full
+commit, every file with its size and sha256 or git blob sha1) and the vLLM
+arguments, GPU minimum and compute capabilities the installer needs. These
+checks keep the shipped entries well formed and their numbers consistent:
+
+* the schema itself (model_vllm.entry_problems), and that it catches the
+ mistakes it is meant to catch;
+* ``min_gpu_mib`` covers the weights plus 25% (the authoring rule) and so
+ also model_memory's device need, weights / 0.90;
+* every shard a safetensors set names is in the manifest;
+* the two first entries keep the revisions and licences reviewed for them.
+
+Network-free: verify a new manifest against the Hub's
+``/api/models/<repo>/revision/<sha>?blobs=true`` before adding it.
+"""
+
+from __future__ import annotations
+
+import copy
+import json
+import re
+import sys
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[1]
+CATALOG = ROOT / "config" / "model-library.json"
+sys.path.insert(0, str(ROOT / "extensions" / "services" / "dashboard-api"))
+
+from model_memory import estimate_model_memory # noqa: E402
+from model_vllm import entry_problems, manifest_bytes, model_dir_name # noqa: E402
+
+MIB = 1024 ** 2
+SHARD = re.compile(r"(?P<stem>.+)-(?P<index>[0-9]{5})-of-(?P<count>[0-9]{5})\.safetensors")
+REVIEWED = {
+ "qwen3.8-flash-next-nvfp4-vllm": {
+ "hf_repo": "nvidia/Qwen3.8-Flash-Next-NVFP4",
+ "revision": "fc694b54fb0174e0913e6adf86691ef85a4ead47",
+ "license": "other", "license_name": "nvidia-open-model-license",
+ "size_bytes": 132734506847, "files": 25,
+ },
+ "glm-5.3-flash-nvfp4-vllm": {
+ "hf_repo": "nvidia/GLM-5.3-Flash-NVFP4",
+ "revision": "da920bb0b9f4a06727223a349e55468e38352348",
+ "license": "mit", "license_name": None,
+ "size_bytes": 204476278199, "files": 44,
+ },
+}
+
+
+def _models() -> list[dict]:
+ return json.loads(CATALOG.read_text(encoding="utf-8"))["models"]
+
+
+def _vllm_models() -> list[dict]:
+ return [model for model in _models() if model.get("runtime") == "vllm"]
+
+
+def _ids(models):
+ return [model["id"] for model in models]
+
+
+def test_reviewed_entries_are_in_the_catalog():
+ by_id = {model["id"]: model for model in _vllm_models()}
+ assert set(REVIEWED) <= set(by_id)
+ for model_id, expected in REVIEWED.items():
+ model = by_id[model_id]
+ assert model["hf_repo"] == expected["hf_repo"], model_id
+ assert model["revision"] == expected["revision"], model_id
+ assert model["license"] == expected["license"], model_id
+ assert model.get("license_name") == expected["license_name"], model_id
+ assert model["size_bytes"] == expected["size_bytes"], model_id
+ assert len(model["files"]) == expected["files"], model_id
+ assert model["compute_capability"] == ["10.0", "10.3"], model_id
+ assert model["reasoning"] == "medium", model_id
+
+
[email protected]("model", _vllm_models(), ids=_ids(_vllm_models()))
+def test_entries_follow_the_schema(model):
+ assert entry_problems(model) == []
+
+
[email protected]("model", _vllm_models(), ids=_ids(_vllm_models()))
+def test_min_gpu_memory_covers_the_weights_plus_a_quarter(model):
+ weights_mib = manifest_bytes(model) / MIB
+ assert model["min_gpu_mib"] >= weights_mib * 1.25, model["id"]
+ # Rounded up to a whole GiB, not padded further.
+ assert model["min_gpu_mib"] % 1024 == 0 and model["min_gpu_mib"] - weights_mib * 1.25 < 1024, model["id"]
+ device_gib = estimate_model_memory(model).device_gib
+ assert device_gib * 1024 <= model["min_gpu_mib"], (model["id"], device_gib)
+
+
[email protected]("model", _vllm_models(), ids=_ids(_vllm_models()))
+def test_every_safetensors_shard_is_in_the_manifest(model):
+ paths = {item["path"] for item in model["files"]}
+ shards: dict[tuple[str, str], set[int]] = {}
+ for path in paths:
+ match = SHARD.fullmatch(path)
+ if match:
+ shards.setdefault((match["stem"], match["count"]), set()).add(int(match["index"]))
+ assert shards, model["id"]
+ for (stem, count), indexes in shards.items():
+ assert indexes == set(range(1, int(count) + 1)), (model["id"], stem)
+ assert {"config.json", "model.safetensors.index.json", "tokenizer_config.json"} <= paths, model["id"]
+
+
+def test_folders_served_names_and_model_names_are_unique():
+ models = _vllm_models()
+ every_name = [model.get("llm_model_name") for model in _models()]
+ for key in (model_dir_name, lambda model: model["served_model_name"], lambda model: model["id"]):
+ values = [key(model) for model in models]
+ assert len(values) == len(set(values))
+ for model in models:
+ assert every_name.count(model["llm_model_name"]) == 1, model["id"]
+
+
+def _valid() -> dict:
+ return copy.deepcopy(next(model for model in _vllm_models() if model["id"] == "glm-5.3-flash-nvfp4-vllm"))
+
+
+def _mutate(path: str, value):
+ model = _valid()
+ target = model
+ *parents, last = path.split(".")
+ for key in parents:
+ target = target[int(key)] if isinstance(target, list) else target[key]
+ if value is KeyError:
+ del target[last]
+ elif isinstance(target, list):
+ target[int(last)] = value
+ else:
+ target[last] = value
+ return model
+
+
[email protected]("path,value,expected", [
+ ("gguf_file", "model.gguf", "llama.cpp fields do not apply"),
+ ("revision", "da920bb0", "revision must be the full 40-hex commit"),
+ ("hf_repo", "GLM-5.3-Flash-NVFP4", "hf_repo must be <owner>/<name>"),
+ ("files.0.path", "../escape", "may not contain empty, '.' or '..' parts"),
+ ("files.0.path", "/etc/passwd", "must be a relative POSIX path"),
+ ("files.0.path", "README.md", "repeats README.md"),
+ ("files.8.sha256", "ABC", "sha256 must be lowercase hex"),
+ ("files.0.size", -1, "size must be a whole number of bytes"),
+ ("files.0", {"path": "a.json", "size": 1}, "must be {path, size, sha256}"),
+ ("size_bytes", 1, "size_bytes must be the manifest total"),
+ ("context_length", 65536, "--max-model-len must equal the entry's context_length"),
+ ("max_context_length", 65536, "max_context_length (config.json max_position_embeddings) must be at least"),
+ ("tool_call_parser", "hermes", "--tool-call-parser must equal the entry's tool_call_parser"),
+ ("vllm_args", ["--model", "/x"], "vllm_args may not set --model"),
+ ("vllm_args", ["--speculative-config", '{"method": "mtp"}'], "vllm_args must be a list of plain strings"),
+ ("min_gpu_mib", 0, "min_gpu_mib must be a positive whole number"),
+ ("compute_capability", ["10"], 'compute_capability must list distinct "major.minor" strings'),
+ ("reasoning", "on", "reasoning must be one of off, low, medium, high"),
+ ("selection.discrete", 50, "selection.discrete must be 0"),
+ ("selection.vllm", KeyError, "selection.vllm must be a whole number"),
+ ("served_model_name", "GLM 5.3", "served_model_name must be letters, digits and ._-"),
+])
+def test_the_schema_catches_broken_entries(path, value, expected):
+ problems = entry_problems(_mutate(path, value))
+ assert any(expected in problem for problem in problems), problems
+
+
+def _dotted_config(args: list[str], flag: str) -> dict:
+ """The config vLLM builds from ``flag.key=value`` tokens: JSON values, else the text."""
+ config = {}
+ for arg in args:
+ if arg.startswith(flag + "."):
+ key, value = arg[len(flag) + 1:].split("=", 1)
+ try:
+ config[key] = json.loads(value)
+ except json.JSONDecodeError:
+ config[key] = value
+ return config
+
+
+# Measured on the DGX Station GB300 (vLLM v0.32.0, 10-27): MTP drafts lifted one-stream
+# writing from about 200 to 313 tokens/s on Qwen and from 145 to 210 on GLM, and Qwen's
+# n-gram embedding table on the GPU (not offloaded to the CPU) is part of that best setup.
+MEASURED_FLAGS = {
+ "qwen3.8-flash-next-nvfp4-vllm": {
+ "--speculative-config": {"method": "mtp", "num_speculative_tokens": 3},
+ "--engram-config": {"cpu_offload": False},
+ },
+ "glm-5.3-flash-nvfp4-vllm": {
+ "--speculative-config": {"method": "mtp", "num_speculative_tokens": 5},
+ "--engram-config": {},
+ },
+}
+
+
[email protected]("model_id", sorted(MEASURED_FLAGS))
+def test_the_entries_keep_the_flags_measured_on_a_dgx_station(model_id):
+ model = {item["id"]: item for item in _vllm_models()}[model_id]
+ for flag, expected in MEASURED_FLAGS[model_id].items():
+ assert _dotted_config(model["vllm_args"], flag) == expected, (model_id, flag)
+
+
+def test_the_broken_entry_cases_edit_what_they_name():
+ # "repeats README.md" needs README.md after files[0]; "sha256 must be
+ # lowercase hex" needs files[8] to be an LFS file.
+ assert "README.md" in {item["path"] for item in _valid()["files"][1:]}
+ assert "sha256" in _valid()["files"][8]
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/ods/tests/test_hf_manifest_download.py b/ods/tests/test_hf_manifest_download.py
new file mode 100644
index 000000000..5cf8b0205
--- /dev/null
+++ b/ods/tests/test_hf_manifest_download.py
@@ -0,0 +1,340 @@
+"""scripts/download-hf-manifest.py against a local stand-in for Hugging Face.
+
+No network: a ThreadingHTTPServer on 127.0.0.1 serves /<repo>/resolve/<rev>/<path>
+with Range support and can redirect, drop a connection mid-file, ignore Range
+or serve wrong bytes, so resume, verification and the disk check all run here.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import importlib.util
+import json
+import re
+import shutil
+import threading
+from collections import namedtuple
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+
+import pytest
+
+
+ROOT = Path(__file__).resolve().parents[1]
+HELPER = ROOT / "scripts" / "download-hf-manifest.py"
+REPO = "nvidia/Test-Model-NVFP4"
+REVISION = "0123456789abcdef0123456789abcdef01234567"
+MODEL_DIR = "nvidia--Test-Model-NVFP4@01234567"
+WEIGHTS = bytes(range(256)) * 1200 + b"tail"
+FILES = {
+ "config.json": b'{"architectures": ["TestForCausalLM"]}\n',
+ "model-00001-of-00001.safetensors": WEIGHTS,
+ "nested/tokenizer.json": b'{"version": "1.0"}' * 50,
+}
+LFS = {"model-00001-of-00001.safetensors", "nested/tokenizer.json"}
+Usage = namedtuple("Usage", "total used free")
+
+
[email protected](autouse=True)
+def roomy_volume(monkeypatch):
+ """The disk check must not depend on the machine running the tests."""
+ monkeypatch.setattr(shutil, "disk_usage", lambda path: Usage(10 * 1000 ** 4, 0, 9 * 1000 ** 4))
+
+
+def _helper():
+ spec = importlib.util.spec_from_file_location("ods_download_hf_manifest", HELPER)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def git_blob_sha1(content: bytes) -> str:
+ return hashlib.sha1(b"blob %d\0" % len(content) + content).hexdigest()
+
+
+def manifest(files: dict[str, bytes]) -> list[dict]:
+ return [
+ {"path": path, "size": len(content), "sha256": hashlib.sha256(content).hexdigest()}
+ if path in LFS else
+ {"path": path, "size": len(content), "git_blob_sha1": git_blob_sha1(content)}
+ for path, content in files.items()
+ ]
+
+
+def write_catalog(path: Path, files: dict[str, bytes], **overrides) -> Path:
+ entry = {
+ "id": "test-model-nvfp4-vllm", "name": "Test Model NVFP4 (vLLM)", "runtime": "vllm",
+ "hf_repo": REPO, "revision": REVISION, "files": manifest(files),
+ "served_model_name": "Test-Model-NVFP4", "llm_model_name": "test-model-nvfp4",
+ "context_length": 8192, "min_gpu_mib": 1024, "compute_capability": ["10.0"],
+ "reasoning": "off", "tool_call_parser": "hermes", "reasoning_parser": "qwen3",
+ "vllm_args": ["--max-model-len", "8192", "--enable-auto-tool-choice",
+ "--tool-call-parser", "hermes", "--reasoning-parser", "qwen3"],
+ "selection": {"discrete": 0, "unified": 0, "cpu": 0, "vllm": 1},
+ **overrides,
+ }
+ gguf = {"id": "tiny-q4", "name": "Tiny", "gguf_file": "tiny.gguf", "gguf_url": "https://example.invalid/t.gguf"}
+ path.write_text(json.dumps({"version": 2, "models": [gguf, entry]}), encoding="utf-8")
+ return path
+
+
+class FakeHub:
+ """Serves FILES; switches make it misbehave the way a real download can."""
+
+ def __init__(self, files: dict[str, bytes]):
+ self.files = dict(files)
+ self.requests: list[tuple[str, str | None]] = []
+ self.drop_after: dict[str, int] = {}
+ self.ignore_range: set[str] = set()
+ self.redirect: set[str] = set()
+ self.status: dict[str, int] = {}
+ hub = self
+
+ class Handler(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def log_message(self, *args):
+ pass
+
+ def do_GET(self):
+ hub.handle(self)
+
+ self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ self.url = f"http://127.0.0.1:{self.server.server_address[1]}"
+ threading.Thread(target=self.server.serve_forever, daemon=True).start()
+
+ def handle(self, request: BaseHTTPRequestHandler) -> None:
+ self.requests.append((request.path, request.headers.get("Range")))
+ prefix = f"/{REPO}/resolve/{REVISION}/"
+ if request.path.startswith(prefix):
+ path = request.path[len(prefix):]
+ if path in self.redirect:
+ request.send_response(302)
+ request.send_header("Location", f"/cdn/{path}?signature=abc")
+ request.send_header("Content-Length", "0")
+ request.end_headers()
+ return
+ elif request.path.startswith("/cdn/"):
+ path = request.path[len("/cdn/"):].split("?", 1)[0]
+ else:
+ path = ""
+ if path in self.status or path not in self.files:
+ request.send_response(self.status.get(path, 404))
+ request.send_header("Content-Length", "0")
+ request.end_headers()
+ return
+ self.send_file(request, path)
+
+ def send_file(self, request: BaseHTTPRequestHandler, path: str) -> None:
+ body = self.files[path]
+ start = 0
+ match = re.fullmatch(r"bytes=([0-9]+)-", request.headers.get("Range") or "")
+ if match and path not in self.ignore_range:
+ start = int(match.group(1))
+ request.send_response(206)
+ request.send_header("Content-Range", f"bytes {start}-{len(body) - 1}/{len(body)}")
+ else:
+ request.send_response(200)
+ request.send_header("Content-Length", str(len(body) - start))
+ request.end_headers()
+ cut = self.drop_after.pop(path, None)
+ if cut is not None:
+ request.wfile.write(body[start:start + cut])
+ request.wfile.flush()
+ request.close_connection = True
+ return
+ request.wfile.write(body[start:])
+
+ def close(self) -> None:
+ self.server.shutdown()
+ self.server.server_close()
+
+ def gets(self, path: str) -> list[str | None]:
+ return [rng for url, rng in self.requests if url.split("?", 1)[0].endswith("/" + path)]
+
+
+def hub():
+ server = FakeHub(FILES)
+ yield server
+ server.close()
+
+
+def run(tmp_path: Path, hub: FakeHub, catalog: Path | None = None, model_id: str = "test-model-nvfp4-vllm"):
+ catalog = catalog or write_catalog(tmp_path / "model-library.json", FILES)
+ return _helper().main([
+ "--catalog", str(catalog), "--model-id", model_id,
+ "--models-dir", str(tmp_path / "models"), "--base-url", hub.url,
+ ])
+
+
+def model_files(tmp_path: Path) -> dict[str, bytes]:
+ root = tmp_path / "models" / MODEL_DIR
+ return {
+ path.relative_to(root).as_posix(): path.read_bytes()
+ for path in sorted(root.rglob("*")) if path.is_file()
+ }
+
+
+def test_git_blob_sha1_matches_git():
+ helper = _helper()
+ for content, expected in ((b"hello\n", "ce013625030ba8dba906f756967f9e9ca394464a"),
+ (b"", "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391")):
+ digest = helper.new_digest({"path": "x", "size": len(content), "git_blob_sha1": expected})
+ digest.update(content)
+ assert digest.hexdigest() == expected
+
+
+def test_downloads_and_verifies_every_file(tmp_path, hub, capsys):
+ hub.redirect.add("model-00001-of-00001.safetensors")
+
+ assert run(tmp_path, hub) == 0
+
+ assert model_files(tmp_path) == FILES
+ out = capsys.readouterr().out
+ assert "progress: 100%" in out
+ assert f"done: 3 files verified in {tmp_path / 'models' / MODEL_DIR}" in out
+ # The redirect target (a CDN in real life) served the weights.
+ assert any(url.startswith("/cdn/model-00001") for url, _ in hub.requests)
+
+
+def test_interrupted_file_resumes_with_a_range_request(tmp_path, hub, capsys):
+ hub.drop_after["model-00001-of-00001.safetensors"] = 100_000
+ hub.redirect.add("model-00001-of-00001.safetensors")
+
+ assert run(tmp_path, hub) == 1
+ root = tmp_path / "models" / MODEL_DIR
+ partial = root / "model-00001-of-00001.safetensors.partial"
+ assert partial.stat().st_size == 100_000
+ assert not (root / "model-00001-of-00001.safetensors").exists()
+ assert "run this again to resume" in capsys.readouterr().err
+
+ assert run(tmp_path, hub) == 0
+ assert model_files(tmp_path) == FILES
+ # The Range header survived the redirect to the CDN.
+ assert hub.gets("model-00001-of-00001.safetensors")[-1] == "bytes=100000-"
+ # Files verified on the first run were not fetched again.
+ assert len(hub.gets("config.json")) == 1
+
+
+def test_server_that_ignores_range_restarts_the_file(tmp_path, hub):
+ root = tmp_path / "models" / MODEL_DIR
+ root.mkdir(parents=True)
+ (root / "model-00001-of-00001.safetensors.partial").write_bytes(WEIGHTS[:5000])
+ hub.ignore_range.add("model-00001-of-00001.safetensors")
+
+ assert run(tmp_path, hub) == 0
+
+ assert model_files(tmp_path) == FILES
+ assert hub.gets("model-00001-of-00001.safetensors") == ["bytes=5000-"]
+
+
+def test_wrong_bytes_are_deleted_and_never_take_the_final_name(tmp_path, hub, capsys):
+ hub.files["config.json"] = b'{"architectures": ["EvilForCausalLM"]}\n'[: len(FILES["config.json"])]
+ assert len(hub.files["config.json"]) == len(FILES["config.json"])
+
+ assert run(tmp_path, hub) == 3
+
+ root = tmp_path / "models" / MODEL_DIR
+ assert not (root / "config.json").exists()
+ assert not (root / "config.json.partial").exists()
+ assert "config.json does not match the catalog (git blob sha1" in capsys.readouterr().err
+
+
+def test_verified_files_in_place_are_not_downloaded_again(tmp_path, hub):
+ assert run(tmp_path, hub) == 0
+ hub.requests.clear()
+
+ assert run(tmp_path, hub) == 0
+
+ assert hub.requests == []
+ assert model_files(tmp_path) == FILES
+
+
+def test_a_changed_file_in_place_is_replaced(tmp_path, hub, capsys):
+ assert run(tmp_path, hub) == 0
+ damaged = tmp_path / "models" / MODEL_DIR / "nested" / "tokenizer.json"
+ damaged.write_bytes(b"x" * len(FILES["nested/tokenizer.json"]))
+ capsys.readouterr()
+
+ assert run(tmp_path, hub) == 0
+
+ assert model_files(tmp_path) == FILES
+ assert "replacing nested/tokenizer.json: it does not match the catalog" in capsys.readouterr().out
+
+
+def test_refuses_to_start_without_room_for_the_rest_plus_a_margin(tmp_path, hub, monkeypatch, capsys):
+ monkeypatch.setattr(shutil, "disk_usage", lambda path: Usage(100 * 1024 ** 3, 0, 2 * 1024 ** 3))
+ catalog = write_catalog(tmp_path / "model-library.json", FILES)
+
+ assert run(tmp_path, hub, catalog, model_id="test-model-nvfp4") == 4
+
+ assert hub.requests == []
+ err = capsys.readouterr().err
+ # 5% of a 100 GiB volume (more than the 2 GiB floor) stays free.
+ assert "has 2.1 GB free, but this model needs 0.0 GB more plus a 5.4 GB safety margin" in err
+ assert "discord.gg" in err
+
+
+def test_a_resumed_download_only_needs_room_for_the_rest(tmp_path):
+ helper = _helper()
+ root = tmp_path / "models" / MODEL_DIR
+ root.mkdir(parents=True)
+ (root / "model-00001-of-00001.safetensors.partial").write_bytes(WEIGHTS[:300_000])
+ (root / "config.json").write_bytes(FILES["config.json"])
+
+ assert helper.bytes_to_download(root, manifest(FILES)) == (
+ len(WEIGHTS) - 300_000 + len(FILES["nested/tokenizer.json"])
+ )
+
+
+def test_a_complete_model_needs_no_free_space(tmp_path, hub, monkeypatch):
+ assert run(tmp_path, hub) == 0
+ monkeypatch.setattr(shutil, "disk_usage", lambda path: Usage(100 * 1024 ** 3, 0, 0))
+
+ assert run(tmp_path, hub) == 0
+
+
+def test_http_errors_name_the_file_not_the_redirect(tmp_path, hub, capsys):
+ hub.status["nested/tokenizer.json"] = 403
+
+ assert run(tmp_path, hub) == 1
+
+ err = capsys.readouterr().err
+ assert f"HTTP 403 for {hub.url}/{REPO}/resolve/{REVISION}/nested/tokenizer.json" in err
+
+
[email protected]("path", ["../escape.json", "/etc/passwd", "a//b.json", "a\\b.json", "x.partial"])
+def test_unsafe_manifest_paths_are_refused_before_any_download(tmp_path, hub, path, capsys):
+ files = {**FILES, path: b"{}"}
+ catalog = write_catalog(tmp_path / "model-library.json", files)
+
+ assert run(tmp_path, hub, catalog) == 1
+
+ assert hub.requests == []
+ assert not (tmp_path / "models").exists()
+ assert "invalid vLLM catalog entry" in capsys.readouterr().err
+
+
+def test_only_vllm_catalog_entries_download(tmp_path, hub, capsys):
+ assert run(tmp_path, hub, model_id="tiny-q4") == 1
+ assert "is a llama.cpp model" in capsys.readouterr().err
+ assert run(tmp_path, hub, model_id="missing") == 1
+
+
+def test_real_catalog_entries_resolve_to_their_model_folders():
+ helper = _helper()
+ catalog = ROOT / "config" / "model-library.json"
+ for model_id, folder in (
+ ("qwen3.8-flash-next-nvfp4-vllm", "nvidia--Qwen3.8-Flash-Next-NVFP4@fc694b54"),
+ ("glm-5.3-flash-nvfp4-vllm", "nvidia--GLM-5.3-Flash-NVFP4@da920bb0"),
+ ):
+ entry = helper.find_entry(catalog, model_id)
+ assert helper.model_dir_name(entry) == folder
+ assert helper.file_url(helper.DEFAULT_BASE_URL, entry, "config.json") == (
+ f"https://huggingface.co/{entry['hf_repo']}/resolve/{entry['revision']}/config.json"
+ )
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))
diff --git a/ods/tests/test_model_library_native_context.py b/ods/tests/test_model_library_native_context.py
index c714d47d9..a7a7c25e6 100644
--- a/ods/tests/test_model_library_native_context.py
+++ b/ods/tests/test_model_library_native_context.py
@@ -8,7 +8,10 @@ agent's context proof cannot pass and activation rolls back (tower2
``NATIVE_CONTEXT`` pins ``<arch>.context_length`` read from each catalog
artifact's GGUF header (the first shard for split models) on 2026-09-25.
-Record the header value when adding or re-pinning an artifact.
+Record the header value when adding or re-pinning an artifact. A vLLM entry
+(``"runtime": "vllm"``) has no GGUF: record ``max_position_embeddings`` from
+the config.json at its pinned revision, which vLLM's ``--max-model-len`` may
+not exceed either.
"""
from __future__ import annotations
@@ -81,6 +84,9 @@ NATIVE_CONTEXT = {
"qwen3-coder-next-q4": 262144,
"llama4-scout-q4": 10485760,
"qwen3.5-122b-a10b-q4": 262144,
+ # vLLM entries: config.json text_config.max_position_embeddings (2026-10-27).
+ "qwen3.8-flash-next-nvfp4-vllm": 262144,
+ "glm-5.3-flash-nvfp4-vllm": 1048576,
}
diff --git a/ods/tests/test_select_model_vllm.py b/ods/tests/test_select_model_vllm.py
new file mode 100644
index 000000000..d309386c9
--- /dev/null
+++ b/ods/tests/test_select_model_vllm.py
@@ -0,0 +1,293 @@
+"""scripts/select-model.py --llm-runtime vllm, and proof that GGUF picks are unchanged.
+
+vLLM catalog entries (``"runtime": "vllm"``) are eligible only when the
+selector is told the runtime is vllm and a GPU named by --gpu has one of the
+entry's compute capabilities and at least its min_gpu_mib. Without
+--llm-runtime vllm the selector's output over every installer envelope
+(tests/fixtures/model-selection-envelopes.json) is byte-identical to the
+output for the same catalog without its vLLM entries.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import functools
+import importlib.util
+import io
+import json
+import re
+import shlex
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+
+ROOT = Path(__file__).resolve().parents[1]
+CATALOG = ROOT / "config" / "model-library.json"
+SELECTOR = ROOT / "scripts" / "select-model.py"
+ENVELOPES = ROOT / "tests" / "fixtures" / "model-selection-envelopes.json"
+TIER_MAP = ROOT / "installers" / "lib" / "tier-map.sh"
+SIMULATOR = ROOT / "scripts" / "simulate-model-selection.py"
+
+# nvidia-smi --query-gpu=uuid,compute_cap,memory.total --format=csv,noheader,nounits rows.
+# GB300 and RTX PRO 6000 memory: the DGX Station Workstation06 (2026-10-27).
+GB300 = "GPU-test-gb300, 10.3, 256703"
+RTX_PRO_6000 = "GPU-test-rtx-pro-6000, 12.0, 97887"
+B200 = "GPU-test-b200, 10.0, 183359"
+H200 = "GPU-test-h200, 9.0, 143771"
+# The installer's selector arguments on the DGX Station, plus the vLLM runtime.
+VLLM = ("--backend", "nvidia", "--memory-type", "discrete", "--vram-mb", "354590", "--ram-gb", "494",
+ "--profile", "qwen", "--tier", "NV_ULTRA", "--max-size-mb", "0", "--host-arch", "arm64",
+ "--installable-only", "--min-context", "65536", "--llm-runtime", "vllm")
+VLLM_ENV_KEYS = {
+ "LLM_MODEL", "GGUF_FILE", "GGUF_URL", "GGUF_SHA256", "MAX_CONTEXT", "LLM_MODEL_SIZE_MB",
+ "MODEL_RECOMMENDATION_SOURCE", "MODEL_RECOMMENDATION_POLICY", "MODEL_RECOMMENDATION_CONFIDENCE",
+ "MODEL_RECOMMENDATION_REASON", "MODEL_RECOMMENDED_ALTERNATIVES", "PIXEL_AGENT_MODEL_READY",
+ "VLLM_MODEL_DIR", "VLLM_SERVED_MODEL", "VLLM_ARGS", "VLLM_GPU_UUID",
+}
+
+
+def _load(name: str, path: Path):
+ spec = importlib.util.spec_from_file_location(name, path)
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
[email protected]_cache(maxsize=1)
+def _selector():
+ return _load("ods_select_model_vllm_test", SELECTOR)
+
+
+def select(*args: str, catalog: Path = CATALOG) -> tuple[int, str, str]:
+ out, err = io.StringIO(), io.StringIO()
+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
+ status = _selector().main(["--catalog", str(catalog), *args])
+ return status, out.getvalue(), err.getvalue()
+
+
+def env_values(stdout: str) -> dict[str, str]:
+ """Decode --env lines the way lib/safe-env.sh load_env_from_output does."""
+ values = {}
+ for line in stdout.splitlines():
+ match = re.fullmatch(r'([A-Za-z_][A-Za-z0-9_]*)="(.*)"', line)
+ assert match, line
+ values[match.group(1)] = (
+ match.group(2).replace('\\"', '"').replace("\\$", "$").replace("\\`", "`").replace("\\\\", "\\")
+ )
+ return values
+
+
+def _catalog() -> dict:
+ return json.loads(CATALOG.read_text(encoding="utf-8"))
+
+
+def _vllm_entries() -> list[dict]:
+ return [model for model in _catalog()["models"] if model.get("runtime") == "vllm"]
+
+
+def _best_fitting(capability: str, memory_mib: int) -> tuple[dict, list[dict]]:
+ fitting = [model for model in _vllm_entries()
+ if capability in model["compute_capability"] and model["min_gpu_mib"] <= memory_mib]
+ assert fitting
+ return max(fitting, key=lambda model: model["selection"]["vllm"]), fitting
+
+
+def _gpu_args(*rows: str) -> list[str]:
+ return [arg for row in rows for arg in ("--gpu", row)]
+
+
+def test_dgx_station_gets_the_top_priority_vllm_model_on_its_gb300():
+ status, out, err = select(*VLLM, *_gpu_args(RTX_PRO_6000, GB300), "--env")
+
+ assert status == 0, err
+ env = env_values(out)
+ best, fitting = _best_fitting("10.3", 256703)
+ assert set(env) == VLLM_ENV_KEYS
+ assert env["LLM_MODEL"] == best["llm_model_name"]
+ assert env["VLLM_GPU_UUID"] == "GPU-test-gb300"
+ assert env["VLLM_MODEL_DIR"] == f"{best['hf_repo'].replace('/', '--')}@{best['revision'][:8]}"
+ assert env["VLLM_SERVED_MODEL"] == best["served_model_name"]
+ assert shlex.split(env["VLLM_ARGS"]) == best["vllm_args"]
+ assert env["MAX_CONTEXT"] == str(best["context_length"]) == "131072"
+ assert env["LLM_MODEL_SIZE_MB"] == str(best["size_mb"])
+ assert env["GGUF_FILE"] == env["GGUF_URL"] == env["GGUF_SHA256"] == ""
+ assert env["PIXEL_AGENT_MODEL_READY"] == "false"
+ assert env["MODEL_RECOMMENDATION_POLICY"] == "vllm-gpu-fit-v1"
+ assert env["MODEL_RECOMMENDATION_SOURCE"] == "catalog_vllm_pre_download"
+ assert "GPU-test-gb300 (compute capability 10.3, 256703 MiB)" in env["MODEL_RECOMMENDATION_REASON"]
+ alternatives = [item.split(":")[0] for item in env["MODEL_RECOMMENDED_ALTERNATIVES"].split(";")]
+ assert alternatives[0] == best["id"] and set(alternatives) == {model["id"] for model in fitting}
+
+
+def test_both_entries_fit_the_gb300_and_neither_the_rtx_pro_6000():
+ _, fitting = _best_fitting("10.3", 256703)
+ assert {model["id"] for model in fitting} == {"qwen3.8-flash-next-nvfp4-vllm", "glm-5.3-flash-nvfp4-vllm"}
+ status, out, _ = select(*VLLM, *_gpu_args(RTX_PRO_6000), "--env")
+ assert (status, out) == (2, "")
+
+
+def test_a_b200_gets_only_what_fits_its_memory():
+ status, out, err = select(*VLLM, *_gpu_args(B200), "--env")
+
+ assert status == 0, err
+ env = env_values(out)
+ best, fitting = _best_fitting("10.0", 183359)
+ assert env["LLM_MODEL"] == best["llm_model_name"]
+ assert "glm-5.3-flash-nvfp4-vllm" not in {model["id"] for model in fitting}
+ assert "glm-5.3-flash-nvfp4-vllm" not in env["MODEL_RECOMMENDED_ALTERNATIVES"]
+
+
[email protected]("rows,expected", [
+ ((RTX_PRO_6000,), "needs one GPU with compute capability 10.0 or 10.3 and at least"),
+ ((H200,), "GPU-test-h200 (compute capability 9.0, 143771 MiB)"),
+ ((), "pass each one as --gpu"),
+ (("GPU-test-gb10, 12.1, [N/A]",), "is not UUID,COMPUTE_CAP,MEMORY_MIB"),
+])
+def test_no_fitting_gpu_fails_instead_of_falling_back(rows, expected):
+ status, out, err = select(*VLLM, *_gpu_args(*rows), "--env")
+
+ assert status == 2
+ assert out == ""
+ assert err.startswith("error: ") and expected in err
+
+
+def test_the_exit_status_reaches_the_installer():
+ result = subprocess.run(
+ [sys.executable, str(SELECTOR), "--catalog", str(CATALOG), *VLLM, *_gpu_args(RTX_PRO_6000), "--env"],
+ capture_output=True, text=True, check=False,
+ )
+ assert (result.returncode, result.stdout) == (2, "")
+ assert "no vLLM catalog model fits this host" in result.stderr
+
+
+def test_vllm_needs_an_nvidia_backend():
+ status, out, err = select("--backend", "amd", "--llm-runtime", "vllm", *_gpu_args(GB300), "--env")
+ assert (status, out) == (2, "")
+ assert "need NVIDIA GPUs" in err
+
+
+def test_check_fit_is_refused_for_vllm():
+ status, out, err = select(*VLLM, *_gpu_args(GB300), "--check-fit",
+ "--model-id", "glm-5.3-flash-nvfp4-vllm", "--context", "65536")
+ assert (status, out) == (1, "")
+ assert "--check-fit checks llama.cpp models" in err
+
+
+def test_context_floor_is_a_preference_unless_required():
+ status, out, err = select(*VLLM, *_gpu_args(GB300), "--min-context", "262144", "--env")
+ assert status == 0, err
+ assert "No vLLM catalog model serves the 262144 context floor" in env_values(out)["MODEL_RECOMMENDATION_REASON"]
+
+ status, out, err = select(*VLLM, *_gpu_args(GB300), "--min-context", "262144", "--require-min-context", "--env")
+ assert (status, out) == (2, "")
+ assert "at the 262144 context floor" in err
+
+
+def test_the_largest_fitting_gpu_is_the_one_vllm_owns():
+ status, out, err = select(*VLLM, *_gpu_args(GB300, "GPU-test-b300, 10.3, 275040", GB300), "--env")
+ assert status == 0, err
+ assert env_values(out)["VLLM_GPU_UUID"] == "GPU-test-b300"
+
+
+def test_json_payload_names_the_gpu_folder_and_estimate():
+ status, out, err = select(*VLLM, *_gpu_args(GB300))
+
+ assert status == 0, err
+ payload = json.loads(out)
+ best, _ = _best_fitting("10.3", 256703)
+ assert payload["runtime"] == "vllm"
+ assert payload["gpu"] == {"uuid": "GPU-test-gb300", "compute_capability": "10.3", "memory_mib": 256703}
+ assert payload["selected"]["id"] == best["id"]
+ assert payload["selected"]["file_count"] == len(best["files"])
+ assert "files" not in payload["selected"]
+ assert payload["selected"]["estimate"]["method"] == "vllm"
+
+
+def _write_catalog(tmp_path: Path, catalog: dict) -> Path:
+ path = tmp_path / "model-library.json"
+ path.write_text(json.dumps(catalog), encoding="utf-8")
+ return path
+
+
+def test_selection_priority_decides_between_fitting_entries(tmp_path):
+ catalog = _catalog()
+ for model in catalog["models"]:
+ if model.get("runtime") == "vllm":
+ model["selection"]["vllm"] = 100 if model["id"].startswith("glm") else 90
+ path = _write_catalog(tmp_path, catalog)
+
+ status, out, err = select(*VLLM, *_gpu_args(GB300), "--env", catalog=path)
+ assert status == 0, err
+ assert env_values(out)["LLM_MODEL"] == "glm-5.3-flash-nvfp4"
+ status, out, err = select(*VLLM, *_gpu_args(B200), "--env", catalog=path)
+ assert env_values(out)["LLM_MODEL"] == "qwen3.8-flash-next-nvfp4"
+
+ for model in catalog["models"]:
+ if model.get("runtime") == "vllm":
+ model["selection"]["vllm"] = 0
+ path = _write_catalog(tmp_path, catalog)
+ assert select(*VLLM, *_gpu_args(GB300), "--env", catalog=path)[:2] == (2, "")
+
+
+def test_install_recommendation_false_keeps_an_entry_out_of_installer_picks(tmp_path):
+ catalog = _catalog()
+ for model in catalog["models"]:
+ if model.get("runtime") == "vllm":
+ model["install_recommendation"] = False
+ path = _write_catalog(tmp_path, catalog)
+ assert select(*VLLM, *_gpu_args(GB300), "--env", catalog=path)[:2] == (2, "")
+
+
+def test_llama_server_selection_never_returns_a_vllm_entry_on_a_gb300_sized_gpu():
+ status, out, err = select("--backend", "nvidia", "--memory-type", "discrete", "--vram-mb", "256703",
+ "--ram-gb", "494", "--tier", "NV_ULTRA", "--host-arch", "arm64",
+ "--installable-only", "--min-context", "65536", *_gpu_args(GB300), "--env")
+ assert status == 0, err
+ env = env_values(out)
+ assert env["GGUF_FILE"].endswith(".gguf")
+ assert not any(key.startswith("VLLM_") for key in env)
+ assert env["LLM_MODEL"] not in {model["llm_model_name"] for model in _vllm_entries()}
+
+
+def _envelope_args(envelope: dict, simulator) -> list[str]:
+ """The arguments scripts/simulate-model-selection.py passes, as the installers do."""
+ ceiling = envelope.get("ceiling")
+ ceiling = (simulator.tier_map_size_mb(TIER_MAP, str(envelope["tier"]), str(envelope["host_arch"]))
+ if ceiling == "tier-map" else int(ceiling or 0))
+ return [
+ "--backend", envelope["backend"], "--memory-type", envelope["memory_type"],
+ "--vram-mb", str(envelope["vram_mb"]), "--ram-gb", str(envelope["ram_gb"]),
+ "--profile", "qwen", "--tier", str(envelope["tier"]), "--max-size-mb", str(ceiling),
+ "--host-arch", envelope["host_arch"], "--installable-only", "--min-context", "65536",
+ ]
+
+
+def test_gguf_selection_is_byte_identical_with_or_without_vllm_entries(tmp_path):
+ catalog = _catalog()
+ assert len(_vllm_entries()) == 2
+ without = _write_catalog(tmp_path, {
+ **catalog, "models": [model for model in catalog["models"] if model.get("runtime") != "vllm"],
+ })
+ simulator = _load("ods_simulate_model_selection_vllm_test", SIMULATOR)
+ envelopes = json.loads(ENVELOPES.read_text(encoding="utf-8"))["envelopes"]
+ compared = picked = 0
+ for envelope in envelopes:
+ args = _envelope_args(envelope, simulator)
+ for extra in ([], ["--env"], ["--agent-ready-only", "--env"]):
+ today = select(*args, *extra, catalog=without)
+ case = (envelope["id"], extra)
+ assert select(*args, *extra) == today, case
+ assert select(*args, *extra, "--llm-runtime", "llama-server", *_gpu_args(GB300)) == today, case
+ compared += 1
+ picked += today[0] == 0 and bool(today[1])
+ assert compared == 3 * len(envelopes) == 195
+ # Not vacuous: every envelope picks a model (the Pixel-verdict route some).
+ assert picked >= 2 * len(envelopes)
+
+
+if __name__ == "__main__":
+ raise SystemExit(pytest.main([__file__, "-q"]))