diff --git a/families/muse_glimmer/build_request.py b/families/muse_glimmer/build_request.py index d96dc7597c..e5158114dc 100644 --- a/families/muse_glimmer/build_request.py +++ b/families/muse_glimmer/build_request.py @@ -12,6 +12,8 @@ from tensorrt_model_connect.graph_transform import GraphTransform +from .vision import MEDIA_TASKS + def _validate_id(field: str, value: str) -> None: if not isinstance(value, str) or re.fullmatch(r"[a-z][a-z0-9_]*", value) is None: @@ -20,7 +22,7 @@ def _validate_id(field: str, value: str) -> None: @dataclass(frozen=True) class BuildRequest: - """Family-owned inputs for the admitted Muse-Glimmer NVFP4 text modes.""" + """Family-owned inputs for original and prepared Muse-Glimmer checkpoints.""" model_dir: Path output_path: Path @@ -35,11 +37,12 @@ class BuildRequest: max_batch_size: ClassVar[int] = 1 tensor_parallel_size: ClassVar[int] = 1 context_parallel_size: ClassVar[int] = 1 - quantization: str | None = "nvfp4" + quantization: str | None = None fp32_layers: ClassVar[tuple[int, ...]] = () dynamic_kv_cache: ClassVar[bool] = False execution_variant: str = "autoregressive" companion: Path | None = None + edge_builder_python: Path | None = None verbose: bool = False graph_transform: GraphTransform | None = None @@ -48,8 +51,8 @@ def __post_init__(self) -> None: _validate_id("task", self.task) if self.family != "muse_glimmer": raise ValueError("Muse-Glimmer request family must be muse_glimmer") - if self.task != "text_generation": - raise ValueError("Muse-Glimmer supports only task=text_generation") + if self.task not in ("text_generation", *MEDIA_TASKS): + raise ValueError("Unsupported Muse-Glimmer generation task") if self.precision != "fp16": raise ValueError("Muse-Glimmer supports only precision=fp16") if self.backend != "trt": @@ -57,11 +60,11 @@ def __post_init__(self) -> None: if self.max_sequence_length is not None and self.max_sequence_length < 1: raise ValueError("max_sequence_length must be positive") if self.quantization not in {None, "none", "nvfp4"}: - raise ValueError("Muse-Glimmer supports only quantization=nvfp4") - if self.execution_variant not in {"autoregressive", "dflash"}: - raise ValueError("Muse-Glimmer supports autoregressive or dflash execution") - if (self.execution_variant == "dflash") != (self.companion is not None): - raise ValueError("Muse-Glimmer dflash requires exactly one companion") + raise ValueError("Muse-Glimmer requires source weights or prepared nvfp4 quantization") + if self.execution_variant not in {"autoregressive", "dflash", "dflash_tree"}: + raise ValueError("Muse-Glimmer supports autoregressive, dflash or dflash_tree execution") + if (self.execution_variant != "autoregressive") != (self.companion is not None): + raise ValueError("Muse-Glimmer paired execution requires exactly one companion") if self.graph_transform is not None: raise NotImplementedError("Muse-Glimmer Edge offload does not support graph_transform") diff --git a/families/muse_glimmer/checkpoint.py b/families/muse_glimmer/checkpoint.py index 2201d30883..02f0bab9be 100644 --- a/families/muse_glimmer/checkpoint.py +++ b/families/muse_glimmer/checkpoint.py @@ -24,12 +24,17 @@ def canonical_module(name: str) -> str: class Checkpoint: """Family-local indexed safetensors reader; never calibrates or rewrites weights.""" - def __init__(self, model_dir: Path): + def __init__(self, model_dir: Path, *, source_format: str = "nvfp4"): self.path = Path(model_dir) - descriptor = json.loads((self.path / "hf_quant_config.json").read_text(encoding="utf-8")) - layers = descriptor.get("quantization", {}).get("quantized_layers") - if not isinstance(layers, dict): - raise ValueError("Muse requires an explicit per-module quantization descriptor") + if source_format == "floating": + layers = {} + elif source_format == "nvfp4": + descriptor = json.loads((self.path / "hf_quant_config.json").read_text(encoding="utf-8")) + layers = descriptor.get("quantization", {}).get("quantized_layers") + if not isinstance(layers, dict): + raise ValueError("Muse requires an explicit per-module quantization descriptor") + else: + raise ValueError(f"Unknown Muse source weight format: {source_format}") self.formats = {} for name, policy in layers.items(): name = canonical_module(name) diff --git a/families/muse_glimmer/cli.json b/families/muse_glimmer/cli.json index 9e20141fed..a04a012653 100644 --- a/families/muse_glimmer/cli.json +++ b/families/muse_glimmer/cli.json @@ -3,7 +3,7 @@ "commands": [ { "name": "build", - "help": "Build one Muse-Glimmer NVFP4 TensorRT Edge-LLM bundle", + "help": "Build a Muse-Glimmer TensorRT bundle", "executor": "python", "handler": "cli:build", "arguments": [ @@ -35,7 +35,9 @@ ], "type": "string", "choices": [ - "text_generation" + "text_generation", + "images_text_to_text", + "video_text_to_text" ], "default": "text_generation" }, @@ -75,9 +77,10 @@ ], "type": "string", "choices": [ + "none", "nvfp4" ], - "default": "nvfp4" + "help": "Preserve the source checkpoint format; nvfp4 explicitly requires prepared mixed weights" }, { "name": "verbose", @@ -96,7 +99,8 @@ "type": "string", "choices": [ "autoregressive", - "dflash" + "dflash", + "dflash_tree" ], "default": "autoregressive" }, @@ -107,6 +111,14 @@ ], "type": "string", "help": "Matched Muse assistant or DFlash2 checkpoint" + }, + { + "name": "edge_builder_python", + "flags": [ + "--edge-builder-python" + ], + "type": "path", + "help": "Python interpreter with the ONNX exporter matching the installed Edge SDK" } ] } diff --git a/families/muse_glimmer/cli.py b/families/muse_glimmer/cli.py index f4980c6f4c..4e2eef2c14 100644 --- a/families/muse_glimmer/cli.py +++ b/families/muse_glimmer/cli.py @@ -41,9 +41,10 @@ def build( precision: str = "fp16", backend: str = "trt", max_sequence_length: int | None = None, - quantization: str = "nvfp4", + quantization: str | None = None, execution_variant: str = "autoregressive", companion: str | None = None, + edge_builder_python: Path | None = None, verbose: bool = False, ) -> int: """Resolve a checkpoint and invoke family-owned Edge or native selection.""" @@ -61,6 +62,7 @@ def build( execution_variant=execution_variant, companion=resolve_model(companion, None) if companion is not None else None, verbose=verbose, + edge_builder_python=edge_builder_python, ) build_bundle(request, output) return 0 diff --git a/families/muse_glimmer/edge_llm/README.md b/families/muse_glimmer/edge_llm/README.md index 2b78dec0bb..78ab0c781f 100644 --- a/families/muse_glimmer/edge_llm/README.md +++ b/families/muse_glimmer/edge_llm/README.md @@ -1,11 +1,122 @@ -# Muse-Glimmer with Edge-LLM 0.11 +# Muse-Glimmer with Edge-LLM The `muse_glimmer` family owns complete-network offload, argument mapping, -engine assets, runtime orchestration, and validation. It uses the official -Edge 0.11.0 snapshot `95515c2f87fba8982db5a519f9022277667b3cc9`; no shared-core -model selection is added. +engine assets, runtime orchestration, and validation. Edge 0.11 remains the +default SDK during migration. To select 0.12, configure Model Connect with +`-DTRTMC_ENABLE_EDGELLM=ON -DTRTMC_EDGELLM_RELEASE=0.12.0`. + +## Edge 0.12 + +Muse needs both `-DTRTMC_EDGELLM_ONNX=ON` and +`-DTRTMC_EDGELLM_ALL_KERNELS=ON`. Follow the +[SDK provisioning guide](../../../cmake/edge_llm/README.md) to build on the +target GPU. If CMake finds an external SDK, point `TRTMC_EDGELLM_SOURCE_DIR` +at the populated, pinned Edge checkout: the upstream binary SDK does not +attest which kernel groups it contains. + +A packaged runner uses its own SDK. For a standalone runner, set +`CMAKE_PREFIX_PATH` to the Model Connect SDK installation containing +`share/trtmc/edge-llm.json`. Use an isolated Python environment +with the matching 0.12 exporter (wheel or source installation), Transformers +5.17.0 and the same TensorRT version as the SDK. Pass its absolute interpreter +path to the family; the wheel alone does not provide the native runtime. For example: -## Dependency and execution +```sh +trtmc muse_glimmer build /models/muse-nvfp4 \ + --precision fp16 --quantization nvfp4 --max-sequence-length 1024 \ + --edge-builder-python /opt/edge-exporter/bin/python -o muse.bundle +``` + +The optional 0.12 route uses the released ONNX exporter and C++ builders on the +target device. Its architecture and CUDA/TensorRT versions must match the +installed SDK. The 0.11 SM120 offload restriction does not apply to 0.12. +A builder failure emits a warning and retries the original request with the +family's native TensorRT implementation. Neither a change in precision nor +dropping the draft is a valid fallback. + +The prepared NVFP4 checkpoint is **text-only**. Ordinary decoding and both +documented DFlash pairs have run through the 0.12 Edge backend. This is not +a lossless speculative-decoding or accuracy claim. In particular the released +runner can return different greedy outputs with and without speculation on +the same V1 or V2 paired engine. Thinking mode also affects the output boundary: +with thinking disabled, the chat template supplies the public-channel header +in the prompt, not the generated tokens. Both routes omit checkpoint-declared +special tokens from display text while retaining the actual generated IDs. +The scientific terms and generation budget are the same in both modes. + +For original floating checkpoints, request `--precision fp16 --quantization none`; +the adapter uses original weights. Building a typed image/video task requires the +original processor and visual weights. For example: + +```sh +trtmc muse_glimmer build /models/Muse-Glimmer-30B \ + --task images_text_to_text --precision fp16 --quantization none \ + --max-sequence-length 1024 --edge-builder-python /opt/edge-exporter/bin/python \ + -o muse-media.bundle +``` + +The six documented combinations below built and ran through both Model Connect +routes at batch 1 and TP1. The results are for the tested checkpoints, prompts +and profile, not for every GPU, prompt, or sampling mode. + +| Checkpoint | Decoding | Quality observed | +| --- | --- | --- | +| Original FP16 | Autoregressive | Both routes gave factual answers in both thinking modes, distinguished opposed images and both video orders, and matched token IDs on all six requests. | +| Original FP16 | DFlash V1 and V2, each with its own companion | Both routes passed the same four media checks and both factual text checks for each pair. On each backend and pair, the six greedy outputs matched target-only execution of that same engine token for token. | +| Prepared NVFP4 (text only) | Autoregressive | Both routes returned factual answers in both thinking modes. No media weights are present. | +| Prepared NVFP4 (text only) | DFlash V1 | Native matched its own target in both thinking modes. In the released Edge runner, speculative and target-only outputs differed; with thinking enabled both reached the token cap. The Model Connect Edge run returned a factual answer, so the capped result is specific to the direct control. | +| Prepared NVFP4 (text only) | DFlash V2 | Native matched its own target in both modes. The released Edge runner returned different greedy answers with and without speculation. Model Connect Edge matched the released speculative answers in both modes. | + +The scientific-answer test runs both modes on one bundle. With thinking off, +it checks a direct answer without a generated private turn. With thinking on, +it checks the answer after the generated public-channel delimiter. Terms found +only in reasoning do not count. Separately, both the native and the released FP16 visual encoders exceeded the pointwise +tolerance against the eager reference on identical inputs. Correct media answers +do not establish encoder tensor parity. These quality limitations do not disable +the corresponding build or inference commands. + +### DFlash2 tree decoding + +Use the original FP16 or prepared NVFP4 target with its matched +`incoai/Muse-Glimmer-30B-DFlash2` companion. For example: + +```sh +trtmc muse_glimmer build /models/muse-nvfp4 \ + --precision fp16 --quantization nvfp4 --max-sequence-length 1024 \ + --execution-variant dflash_tree --companion /models/muse-dflash2 \ + --edge-builder-python /opt/edge-exporter/bin/python -o muse-tree.bundle +``` + +The 0.12 Edge builder sets a 32-node verification profile on the target +and keeps the draft's block size at 16. At runtime, the tree retains up to four +children per node. Native TensorRT uses the same conditional selector and +verifies tokens against the target along the accepted path; it does not batch +all nodes into one target call. Both routes reject stochastic generation for an +explicit tree. Use `dflash` for the chain. The chain results above do not +establish tree accuracy. + +On the original FP16 target, the tree built and ran on both routes. Both +passed the thinking-enabled science check and distinguished the two images +and both video orders. With thinking disabled, both gave a factual answer but +did not generate the header that the earlier test expected. Native matched target-only token IDs on all +six requests; Edge matched on five. On the red-then-blue video, the Edge tree +separated the two correct colors with a comma, while target-only used a +newline. The direct Edge runner also produced different text with speculation +enabled and disabled on the same engines for the two science requests; both +settings reached the 512-token cap. These observations do not establish the +cause of the difference. + +For the prepared NVFP4 target, both tree routes built and generated answers +with thinking disabled and enabled. Native returned the same 38 and 171 +token IDs as its own target-only engine, respectively. Both routes missed +the earlier test's generated-header check with thinking disabled; the template +already supplies that header. With thinking +enabled, native passed; the Edge answer said “solid water” rather than either +term accepted by the test (“ice” or “crystal”). The released Edge runner also +produced different text with tree verification enabled versus disabled on the +same engine and prompt. These are accuracy limitations, not command failures. + +## Edge 0.11 dependency and execution Provision the native Edge SDK using Model Connect's optional CMake dependency with the ONNX tools and complete native kernels. Expose its installation @@ -20,7 +131,7 @@ has no SM allowlist: TensorRT must support its packed-format operators and the device must have sufficient memory. Neither route cross-compiles, recalibrates, or replaces the source precision recipe. -## Documented text configurations +## Documented prepared text configurations The base is `RadixArk/Muse-Glimmer-NVFP4`, revision `1416629950afdfb276618fd4810103681dd10f4a`. @@ -46,26 +157,25 @@ trtmc muse_glimmer build /models/muse-nvfp4 \ --companion /models/matched-muse-draft ``` -The recorded profile is TP1/batch1/input512/KV1024, with a full block size 16 +The documented text examples use a profile of TP1/batch1/input512/KV1024, with a full block size 16 verification profile for paired execution. Both base and draft must build; a failed pair is never replaced by an autoregressive bundle. DFlash V1 requires greedy generation. DFlash V2 does not add the V1 greedy-only restriction; local paired qualification uses greedy generation only. Unsupported controls, such as a seed override, remain explicit errors in the Edge route. The native runtime supports its seeded sampler and rejects unsupported controls before execution. -DDTree is not exposed. +The 0.11 Edge offload does not support DDTree. -## Quality and limitations +## Legacy 0.11 quality and limitations The existing owning E2E retains its scientific prompt, low-reasoning system message, 512-token generation budget, and final-answer semantic checks. Muse's -ATEM output must reach `assistant to=user`; a response that stops in the -reasoning channel is not a passing answer. +thinking-enabled ATEM output must reach `assistant to=user`; a response +that stops in the reasoning channel is not a passing answer. -The original `meta-models/Muse-Glimmer-30B` FP16 text/image/video checkpoint -exceeds the available compatible single-device capacity. It and its FP16 -paired modes have no executed qualification or adapter route here. No -unqualified tensor-parallel alternative is implied. The documented NVFP4 +The 0.11 validation did not run the original FP16 checkpoint or its paired +modes: the compatible test device had insufficient memory. This describes +that validation environment, not a general GPU requirement. The documented NVFP4 checkpoint is text-only: its results do not qualify image or video execution. Selection and numerical qualification are separate. Accuracy-only failures @@ -82,7 +192,7 @@ p/q rejection correction for sampled V2 requests, and commits no rejected draft state. This is a correctness-first implementation, not a speculative speedup claim. V1 retains its greedy-only contract. -### Native validation scope +### Legacy native validation scope All three admitted text modes have completed full-checkpoint native build and inference. The existing owning scientific-answer check passes for ordinary @@ -100,3 +210,9 @@ are still required even though the native family has no GPU allowlist. Insufficient device memory is a runtime failure, not permission to silently change precision or remove a companion. Inference failures are returned to the caller and are never silently retried. + +For raw media requests, pass typed image or video parts rather than inserting +special tokens into prompt text. The Edge adapter formats those parts with the +checkpoint's placeholders. If the processor's resize fallback exceeds the +compiled native visual profile, the runtime reports the limit instead of +silently shrinking the image to a single token. diff --git a/families/muse_glimmer/edge_llm/builder.py b/families/muse_glimmer/edge_llm/builder.py index 09314df7da..b3fff054b5 100644 --- a/families/muse_glimmer/edge_llm/builder.py +++ b/families/muse_glimmer/edge_llm/builder.py @@ -1,11 +1,13 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -"""Muse-Glimmer mapping to the pinned Edge 0.11 ONNX builder flow.""" +"""Muse-Glimmer mapping to the pinned Edge ONNX builder flow.""" from __future__ import annotations +from importlib.metadata import PackageNotFoundError, distribution import json +import logging from pathlib import Path import shlex import shutil @@ -19,28 +21,65 @@ ) +from ..vision import media_contract +from ..weight_format import request_weight_format + + EDGE_REVISION = "95515c2f87fba8982db5a519f9022277667b3cc9" +RELEASE_012 = "513dcd18291e587c80928911a480761352f3c2d8" + + def local_target() -> dict: return detect_local_platform() +def _sdk_prefixes(*, warn: bool = False) -> list[Path]: + """Pair a packaged runner with its own SDK; a source installation uses CMake prefixes.""" + prefixes = cmake_prefixes() + try: + installed = Path(distribution("tensorrt-model-connect").locate_file("tensorrt_model_connect")) + except PackageNotFoundError: + return prefixes + if not (installed / "bin/trtmc").is_file(): + return prefixes + relative = Path("share/trtmc/edge-llm.json") + if warn and any((p / relative).is_file() and (p / relative).resolve() != (installed / relative).resolve() + for p in prefixes): + logging.getLogger(__name__).warning( + "Ignoring a standalone Edge SDK: the installed Model Connect runner uses its packaged Muse capability.") + return [installed] + + def package_present() -> bool: - return any((prefix / "share/trtmc/edge-llm.json").is_file() for prefix in cmake_prefixes()) + return any((prefix / "share/trtmc/edge-llm.json").is_file() or + (prefix / "share/trtmc/edge-llm.json").is_symlink() for prefix in _sdk_prefixes(warn=True)) def installed_package(target: dict) -> dict: - """Resolve one complete native Edge 0.11 package from standard CMake prefixes.""" - for prefix in cmake_prefixes(): + """Resolve one complete, matching native Edge package from standard CMake prefixes.""" + for prefix in _sdk_prefixes(): manifest = prefix / "share/trtmc/edge-llm.json" if not manifest.is_file(): continue package = json.loads(manifest.read_text(encoding="utf-8")) - if package.get("schema_version") != 1 or package.get("revision") != EDGE_REVISION: + release = package.get("version") + legacy = ( + release == "0.11.0" + and package.get("schema_version") == 1 + and package.get("revision") == EDGE_REVISION + ) + current = ( + release == "0.12.0" + and package.get("schema_version") == 2 + and "release_revision" in package + and package["release_revision"] in (None, RELEASE_012) + ) + if not (legacy or current): raise ValueError(f"Edge package has an unsupported revision/schema: {manifest}") - if package.get("version") != "0.11.0" or package.get("arch") != target["arch"]: - raise ValueError("Edge package version/architecture differs from executing worker") + if package.get("arch") != target["arch"]: + raise ValueError("Edge package architecture differs from executing worker") if target["sm"] not in package.get("architectures", []): raise ValueError("Edge package was not built for this local GPU") cuda_version = ".".join(str(package.get("cuda_version", "")).split(".")[:2]) @@ -53,7 +92,7 @@ def installed_package(target: dict) -> dict: raise ValueError( "Muse-Glimmer requires the Edge ONNX tools and complete native kernels" ) - for name in ("python", "plugin", "onnx_builder"): + for name in (("python", "plugin", "onnx_builder") if legacy else ("plugin", "onnx_builder")): relative = Path(package[name]) path = (prefix / relative).resolve() if relative.is_absolute() or not path.is_relative_to(prefix.resolve()): @@ -63,64 +102,49 @@ def installed_package(target: dict) -> dict: package[name] = str(path) return package raise FileNotFoundError( - "Edge-LLM 0.11.0 is not installed; enable its CMake dependency or install the " - "0.11.0 wheel alongside a matching native SDK package" + "No compatible native Edge SDK is installed; enable the CMake dependency. " + "A Python wheel does not replace the C++ SDK." ) -def exporter_python(package: dict, target: dict) -> str: - """Prefer a compatible 0.11 wheel in the active environment, else SDK Python.""" - interpreter = sys.executable +def exporter_python(package: dict, target: dict, requested: Path | None = None) -> str: + """Validate the selected wheel or source exporter against the installed SDK.""" + release = package["version"] + current = release == "0.12.0" + interpreter = str(requested) if requested is not None else sys.executable try: if not Path(interpreter).is_absolute() or not Path(interpreter).is_file(): raise ValueError("Edge exporter Python must be an existing absolute path") + module = "tensorrt_edgellm.onnx.cli" if current else "tensorrt_edgellm.scripts.export" probe = subprocess.run( - [ - interpreter, - "-I", - "-c", - "import json, tensorrt, tensorrt_edgellm; " - "import tensorrt_edgellm.scripts.export; " - "print(json.dumps([tensorrt_edgellm.__version__, tensorrt.__version__]))", - ], - check=True, - capture_output=True, - text=True, - timeout=30, + [interpreter, "-I", "-c", "import json, tensorrt, tensorrt_edgellm; " + "from importlib.metadata import version; " + f"import {module}; " + + ("assert version('transformers') == '5.17.0'; " if current else "") + + "print(json.dumps([tensorrt_edgellm.__version__, tensorrt.__version__]))"], + check=True, capture_output=True, text=True, timeout=45, ) - if json.loads(probe.stdout) != ["0.11.0", target["tensorrt_version"]]: - raise ValueError("Edge wheel or TensorRT version differs from the native package") + if json.loads(probe.stdout) != [release, target["tensorrt_version"]]: + raise ValueError("Edge exporter or TensorRT version differs from the native package") except (OSError, ValueError, subprocess.SubprocessError): - return package["python"] + if not current and requested is None: + return package["python"] + raise return interpreter -def checkpoint_weight_format(model_dir: Path, raw: dict) -> str: - """Admit only the documented mixed NVFP4/MXFP8 Muse checkpoint recipe.""" - config = raw.get("quantization_config") - descriptor = model_dir / "hf_quant_config.json" - if ( - not isinstance(config, dict) - or config.get("quant_algo") != "MIXED_PRECISION" - or not descriptor.is_file() - ): - raise ValueError("Muse-Glimmer Edge route requires the documented mixed NVFP4 checkpoint") - document = json.loads(descriptor.read_text(encoding="utf-8")) - layers = document.get("quantization", {}).get("quantized_layers", {}) - algorithms = {value.get("quant_algo") for value in layers.values() if isinstance(value, dict)} - if not {"NVFP4", "MXFP8"} <= algorithms: - raise ValueError("Muse-Glimmer quantization descriptor must contain NVFP4 and MXFP8 layers") - return "nvfp4" - - -def request_weight_format(request, raw: dict) -> str: - source = checkpoint_weight_format(Path(request.model_dir), raw) - requested = source if request.quantization in {None, "none"} else request.quantization.lower() - if requested != source: - raise ValueError( - f"Muse-Glimmer source format {source} does not match requested {requested}" - ) - return source +def export_prefix(request, package: dict, target: dict) -> list[str]: + interpreter = exporter_python(package, target, getattr(request, "edge_builder_python", None)) + module = ("tensorrt_edgellm.onnx.cli" if package["version"] == "0.12.0" + else "tensorrt_edgellm.scripts.export") + return [interpreter, "-I", "-m", module] + + +def release_marker(package: dict) -> dict: + if package["version"] == "0.12.0": + return {"edge_release": "0.12.0", "edge_revision": package["release_revision"], + "builder_flow": "onnx"} + return {"edge_revision": EDGE_REVISION} def _run(command: list[str], log, *, cwd: Path, env: dict | None = None) -> None: @@ -128,18 +152,37 @@ def _run(command: list[str], log, *, cwd: Path, env: dict | None = None) -> None subprocess.run(command, check=True, stdout=log, stderr=subprocess.STDOUT, cwd=cwd, env=env) -def prepare(request, raw: dict, target: dict, staging: Path, log_path: Path) -> tuple[dict, dict]: +def build_visual(onnx: Path, engine: Path, source: Path, package: dict, + vision: dict, limit: int, log, staging: Path, env: dict) -> None: + """Build the released Muse visual encoder next to its matching text engine.""" + if package["version"] != "0.12.0": + raise ValueError("Muse-Glimmer Edge media requires the 0.12 SDK") + executable = Path(package["onnx_builder"]).with_name("visual_build") + _run([str(executable), "--onnxDir", str(onnx / "visual"), "--engineDir", str(engine), + "--minImageTokens", "4", "--maxImageTokens", str(limit), + "--maxImageTokensPerImage", str(vision["max_image_tokens"])], log, cwd=staging, env=env) + visual = engine / "visual" + for name in ("visual.engine", "config.json", "preprocessor_config.json"): + if not (visual / name).is_file() or not (visual / name).stat().st_size: + raise ValueError(f"Muse-Glimmer Edge visual artifact missing: {name}") + # The released Muse runner reads its frame-token budget from this adjacent file. + shutil.copy2(source / "processor_config.json", visual / "processor_config.json") + + +def prepare(request, raw: dict, target: dict, staging: Path, log_path: Path, package=None) -> tuple[dict, dict]: """Export ONNX and build the complete native engine without model reimplementation.""" - if getattr(request, "execution_variant", "autoregressive") == "dflash": + if package is None: + package = installed_package(target) + if getattr(request, "execution_variant", "autoregressive") in {"dflash", "dflash_tree"}: from .paired import prepare as prepare_paired - return prepare_paired(request, raw, target, staging, log_path) - package = installed_package(target) + return prepare_paired(request, raw, target, staging, log_path, package) weight_format = request_weight_format(request, raw) text = raw.get("text_config", raw) capacity = int(text["max_position_embeddings"]) limit = request.max_sequence_length or min(capacity, 1024) - input_limit = min(limit, 512) + vision = media_contract(request, raw, weight_format, limit) + input_limit = limit if vision else min(limit, 512) onnx = staging / "edge_llm/onnx" engine = staging / "edge_llm/engine" checkpoint = staging / "edge_llm/checkpoint" @@ -149,13 +192,10 @@ def prepare(request, raw: dict, target: dict, staging: Path, log_path: Path) -> if source.is_file(): shutil.copy2(source, checkpoint / name) export_command = [ - exporter_python(package, target), - "-I", - "-m", - "tensorrt_edgellm.scripts.export", + *export_prefix(request, package, target), str(Path(request.model_dir)), str(onnx), - "--skip-visual", + *([] if vision else ["--skip-visual"]), "--skip-audio", ] build_command = [ @@ -173,6 +213,10 @@ def prepare(request, raw: dict, target: dict, staging: Path, log_path: Path) -> with log_path.open("a", encoding="utf-8") as log: _run(export_command, log, cwd=staging) _run(build_command, log, cwd=staging, env=environment) + if vision: + build_visual(onnx, engine, Path(request.model_dir), package, vision, limit, log, + staging, environment) + shutil.rmtree(onnx) # The bundle contains engines, not the intermediate export. required = ( "llm.engine", "config.json", @@ -193,7 +237,8 @@ def prepare(request, raw: dict, target: dict, staging: Path, log_path: Path) -> files[path.relative_to(staging).as_posix()] = path return files, { "version": 1, - "edge_revision": EDGE_REVISION, + **release_marker(package), + **({"vision": vision} if vision else {}), "target": target, "precision": "fp16", "weight_format": weight_format, diff --git a/families/muse_glimmer/edge_llm/dispatch.py b/families/muse_glimmer/edge_llm/dispatch.py index f8a5783255..087965dad2 100644 --- a/families/muse_glimmer/edge_llm/dispatch.py +++ b/families/muse_glimmer/edge_llm/dispatch.py @@ -13,10 +13,10 @@ import tempfile import traceback +from ..vision import MEDIA_TASKS from . import builder as edge_llm _LOG = logging.getLogger(__name__) -EDGE_DISPATCH = {("linux", "x86_64", 120, "nvfp4"): edge_llm.prepare} _SHAPE = (52, 6656, 19968, 32, 2, 128, 202048) @@ -38,9 +38,9 @@ def candidate(request, raw: dict) -> bool: raw.get("model_type") == "muse_glimmer" and text.get("model_type") == "muse_glimmer_text" and shape == _SHAPE - and getattr(request, "execution_variant", "autoregressive") in {"autoregressive", "dflash"} + and getattr(request, "execution_variant", "autoregressive") in {"autoregressive", "dflash", "dflash_tree"} and request.backend == "trt" - and request.task == "text_generation" + and request.task in ("text_generation", *MEDIA_TASKS) and request.precision.lower() == "fp16" and request.quantization in {None, "none", "nvfp4"} and request.max_batch_size @@ -87,9 +87,15 @@ def build(request, writer, native) -> None: try: target = edge_llm.local_target() weight_format = edge_llm.request_weight_format(request, raw) - adapter = EDGE_DISPATCH.get((target["os"], target["arch"], target["sm"], weight_format)) - if adapter is not None: - files, marker = adapter(request, raw, target, Path(directory), log_path) + package = edge_llm.installed_package(target) + # Only the legacy offload was qualified on the x86 SM120 stack. + # For 0.12 the matched SDK declares its native GPU architectures. + eligible = package["version"] == "0.12.0" or ( + getattr(request, "execution_variant", "autoregressive") != "dflash_tree" + and request.task == "text_generation" and weight_format == "nvfp4" and (target["arch"], target["sm"]) == ("x86_64", 120) + ) + if eligible: + files, marker = edge_llm.prepare(request, raw, target, Path(directory), log_path, package) except Exception as error: failure = error with log_path.open("a", encoding="utf-8") as log: @@ -105,7 +111,7 @@ def build(request, writer, native) -> None: log_path.unlink(missing_ok=True) raise else: - if adapter is not None: + if eligible: edge_llm.publish(request, writer, files, marker) log_path.unlink() return diff --git a/families/muse_glimmer/edge_llm/paired.py b/families/muse_glimmer/edge_llm/paired.py index 18aab76bba..f3e5d76ebb 100644 --- a/families/muse_glimmer/edge_llm/paired.py +++ b/families/muse_glimmer/edge_llm/paired.py @@ -14,7 +14,7 @@ from . import builder -def companion_version(draft: Path) -> int: +def companion_version(draft: Path, *, tree: bool = False) -> int: """Validate the published assistant geometry without rewriting its weights.""" config = json.loads((draft / "config.json").read_text(encoding="utf-8")) architectures = config.get("architectures") @@ -32,22 +32,27 @@ def companion_version(draft: Path) -> int: or policy.get("target_layer_ids") != [1, 13, 25, 37, 49] or config.get("vocab_size", 202048) != 202048): raise ValueError("Muse-Glimmer requires its documented matched block-16 companion") + if tree and (version != 2 or policy.get("selector_top_k") != 16 or policy.get("selector_rank") != 256): + raise ValueError("Muse-Glimmer DDTree requires the matched rank-256, top-16 V2 selector") if not list(draft.glob("*.safetensors")): raise ValueError("Muse-Glimmer companion requires local safetensors weights") return version -def prepare(request, raw: dict, target: dict, staging: Path, log_path: Path) -> tuple[dict, dict]: +def prepare(request, raw: dict, target: dict, staging: Path, log_path: Path, package: dict) -> tuple[dict, dict]: """Export and build a complete pair; never substitute a base-only bundle.""" source = Path(request.model_dir) draft = Path(request.companion) - version = companion_version(draft) - package = builder.installed_package(target) + tree = request.execution_variant == "dflash_tree" + if tree and package["version"] != "0.12.0": + raise ValueError("Muse-Glimmer DDTree requires the 0.12.0 Edge SDK") + version = companion_version(draft, tree=tree) weight_format = builder.request_weight_format(request, raw) limit = request.max_sequence_length or 1024 if limit < 16: raise ValueError("Muse-Glimmer paired capacity must fit the complete verify block") - input_limit = min(limit, 512) + vision = builder.media_contract(request, raw, weight_format, limit) + input_limit = limit if vision else min(limit, 512) engine = staging / "edge_llm/engine" checkpoint = staging / "edge_llm/checkpoint" checkpoint.mkdir(parents=True) @@ -58,24 +63,28 @@ def prepare(request, raw: dict, target: dict, staging: Path, log_path: Path) -> {"EDGELLM_PLUGIN_PATH": package["plugin"]}, prepend_paths={"LD_LIBRARY_PATH": str(Path(package["plugin"]).parent)}, ) - interpreter = builder.exporter_python(package, target) + exporter = builder.export_prefix(request, package, target) + current = package["version"] == "0.12.0" for role, subdirectory, flag, profile in ( - ("base", "llm", "--specBase", "--maxVerifyTreeSize"), - ("draft", "dflash_draft", "--specDraft", "--maxDraftTreeSize"), + ("base", "llm", "--specBase", "--maxSpecVerifyTokens" if current else "--maxVerifyTreeSize"), + ("draft", "dflash_draft", "--specDraft", "--maxSpecDraftTokens" if current else "--maxDraftTreeSize"), ): onnx = staging / f"{role}-export" commands = [ - [interpreter, "-I", "-m", "tensorrt_edgellm.scripts.export", str(source), - str(onnx), "--skip-visual", "--skip-audio", f"--dflash-{role}", + [*exporter, str(source), + str(onnx), *([] if vision and role == "base" else ["--skip-visual"]), "--skip-audio", f"--dflash-{role}", "--dflash-draft-dir", str(draft)], [package["onnx_builder"], "--onnxDir", str(onnx / subdirectory), "--engineDir", str(engine), "--maxBatchSize", "1", "--maxInputLen", str(input_limit), "--maxKVCacheCapacity", str(limit), - profile, "16", flag], + profile, "32" if tree and role == "base" else "16", flag], ] with log_path.open("a", encoding="utf-8") as log: for command in commands: builder._run(command, log, cwd=staging, env=environment) + if vision and role == "base": + builder.build_visual(onnx, engine, source, package, vision, limit, log, + staging, environment) shutil.rmtree(onnx) # Only this preparation's intermediate files. required = ( "spec_base.engine", "spec_draft.engine", "base_config.json", "draft_config.json", @@ -106,9 +115,11 @@ def prepare(request, raw: dict, target: dict, staging: Path, log_path: Path) -> if path.is_file(): files[path.relative_to(staging).as_posix()] = path return files, { - "version": 1, "edge_revision": builder.EDGE_REVISION, "target": target, - "precision": "fp16", "weight_format": weight_format, "execution_variant": "dflash", + "version": 1, **builder.release_marker(package), "target": target, + "precision": "fp16", "weight_format": weight_format, "execution_variant": request.execution_variant, + **({"dflash_top_k": 4, "dflash_verify": 32} if tree else {}), "dflash_version": version, "dflash_block_size": 16, "max_sequence_length": limit, "max_input_length": input_limit, "max_batch_size": 1, + **({"vision": vision} if vision else {}), "artifacts": list(files), } diff --git a/families/muse_glimmer/native_graph.py b/families/muse_glimmer/native_graph.py index d8e789a4ee..4797645229 100644 --- a/families/muse_glimmer/native_graph.py +++ b/families/muse_glimmer/native_graph.py @@ -158,7 +158,7 @@ def last_row(self, x): layer.set_input(2, one_row) return layer.get_output(0) - def populate(self, target_layer_ids=()): + def populate(self, target_layer_ids=(), *, visual_inputs=False): c = self.config if len(set(target_layer_ids)) != len(target_layer_ids) or any(i < 0 or i >= c.num_hidden_layers for i in target_layer_ids): raise ValueError("Muse draft feature layers must be unique target layer indices") @@ -169,6 +169,11 @@ def populate(self, target_layer_ids=()): embedding = weight_tensor(self.network, embedding, self.keep_alive, trt.float16) x = self.network.add_gather(embedding, token, 0).get_output(0) x = self.norm(x, c.rms_norm_eps) + if visual_inputs: + # The visual projector already normalized its rows independently of text. + visual = self.network.add_input("visual_embeddings", trt.float16, (-1, c.hidden_size)) + is_visual = self.network.add_input("is_visual", trt.int32, (-1, 1)) + x = self.network.add_select(self.cast(is_visual, trt.bool), visual, x).get_output(0) hidden = {} for i in range(c.num_hidden_layers): prefix = f"layers.{i}" @@ -207,7 +212,7 @@ def populate(self, target_layer_ids=()): self.network.mark_output(logits) -def build_target(config, checkpoint, capacity, *, target_layer_ids=(), verbose=False): +def build_target(config, checkpoint, capacity, *, target_layer_ids=(), visual_inputs=False, verbose=False): if type(capacity) is not int or capacity < 1 or capacity > config.max_position_embeddings: raise ValueError("Muse native capacity must fit the checkpoint context") logger = trt.Logger(trt.Logger.VERBOSE if verbose else trt.Logger.WARNING) @@ -215,7 +220,7 @@ def build_target(config, checkpoint, capacity, *, target_layer_ids=(), verbose=F builder.max_threads = min(8, os.cpu_count() or 1) network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED)) graph = Graph(network, checkpoint, config, capacity) - graph.populate(target_layer_ids) + graph.populate(target_layer_ids, visual_inputs=visual_inputs) settings = builder.create_builder_config() settings.builder_optimization_level = 1 # Profile 0 prefills 1..max_rows prompt rows; profile 1 decodes one row. @@ -225,6 +230,9 @@ def build_target(config, checkpoint, capacity, *, target_layer_ids=(), verbose=F for name in ("token_id", "position_id"): profile.set_shape(name, (low,), (opt,), (high,)) profile.set_shape("attention_mask", (low, capacity), (opt, capacity), (high, capacity)) + if visual_inputs: + for name, width in (("is_visual", 1), ("visual_embeddings", config.hidden_size)): + profile.set_shape(name, (low, width), (opt, width), (high, width)) settings.add_optimization_profile(profile) if "NVFP4" in checkpoint.formats.values(): settings.max_aux_streams = 0 diff --git a/families/muse_glimmer/native_model.py b/families/muse_glimmer/native_model.py index ab78dfde16..e7e2fd1186 100644 --- a/families/muse_glimmer/native_model.py +++ b/families/muse_glimmer/native_model.py @@ -18,33 +18,39 @@ def build(request, writer): generation_path = model_dir / "generation_config.json" generation = json.loads(generation_path.read_text(encoding="utf-8")) if generation_path.is_file() else None config = TextConfig.from_dict(raw, generation) - # Source admission is identical to the existing owning Edge route. This - # checker reads the source recipe only; it does not query hardware or run Edge. - from .edge_llm.builder import request_weight_format + from .weight_format import request_weight_format - request_weight_format(request, raw) + source_format = request_weight_format(request, raw) capacity = request.max_sequence_length or 1024 if type(capacity) is not int or not 1 <= capacity <= config.max_position_embeddings: raise ValueError("Muse native capacity must fit the checkpoint context") - if request.execution_variant == "dflash" and capacity < 16: + paired = request.execution_variant in {"dflash", "dflash_tree"} + tree = request.execution_variant == "dflash_tree" + if paired and capacity < 16: raise ValueError("Muse native DFlash capacity must fit the complete block of 16") + from .vision import media_contract + vision = media_contract(request, raw, source_format, capacity) draft_config = None - if request.execution_variant == "dflash": + if paired: from .draft import DraftConfig, load_draft_weights, build_draft_engine, build_selector_engine from .edge_llm.paired import companion_version companion = Path(request.companion) - companion_version(companion) + companion_version(companion, tree=tree) draft_config = DraftConfig.from_dict(json.loads((companion / "config.json").read_text()), config) draft_weights = load_draft_weights(companion, draft_config) for name in ("tokenizer.json", "tokenizer_config.json", "chat_template.jinja"): if not (model_dir / name).is_file(): raise ValueError(f"Muse native bundle requires {name}") - with Checkpoint(model_dir) as checkpoint: + with Checkpoint(model_dir, source_format=source_format) as checkpoint: features = draft_config.feature_layers if draft_config else () - engine = build_target(config, checkpoint, capacity, target_layer_ids=features, verbose=request.verbose) + kwargs = {"visual_inputs": True} if vision else {} + engine = build_target(config, checkpoint, capacity, target_layer_ids=features, verbose=request.verbose, **kwargs) writer.add_bytes("engine.plan", engine) del engine + if vision: + from .visual_graph import build_visual + writer.add_bytes("vision.plan", build_visual(raw, checkpoint, vision["max_patches"], verbose=request.verbose)) if draft_config: head = checkpoint.projection("lm_head", config.vocab_size, config.hidden_size) embedding = checkpoint.projection("embed_tokens", config.vocab_size, config.hidden_size) @@ -55,6 +61,8 @@ def build(request, writer): draft_config, draft_weights, verbose=request.verbose)) writer.add_json("runtime.json", { "version": 1, + **({"vision": vision} if vision else {}), + **({"dflash_top_k": 4, "dflash_verify": 32} if tree else {}), "dflash_version": draft_config.version if draft_config else 0, "dflash_block_size": draft_config.query_rows if draft_config else 0, "feature_width": len(draft_config.feature_layers) * config.hidden_size if draft_config else 0, @@ -64,9 +72,9 @@ def build(request, writer): "selector_top_k": draft_config.selector_top_k if draft_config else 0, "execution_variant": request.execution_variant, "precision": "fp16", - "weight_format": "nvfp4_mxfp8", + "weight_format": "floating" if source_format == "floating" else "nvfp4_mxfp8", "max_cache_length": capacity, - "max_input_length": min(capacity, 512), + "max_input_length": capacity if vision else min(capacity, 512), # One target engine: a multi-row prefill profile and a one-row decode profile. "decoder_engine_layout": "dual_profile", "hidden_size": config.hidden_size, diff --git a/families/muse_glimmer/quantization.py b/families/muse_glimmer/quantization.py index 7aa6311489..128c42ef66 100644 --- a/families/muse_glimmer/quantization.py +++ b/families/muse_glimmer/quantization.py @@ -44,7 +44,7 @@ def weight_tensor(network, projection: Projection, keep_alive, output_dtype): p = projection if p.algorithm == "dense": - w = constant(network, p.weight.astype(np.float32), keep_alive) + w = constant(network, p.weight.astype(np.float32, copy=False), keep_alive) return network.add_cast(w, output_dtype).get_output(0) if p.block_scales is None: raise ValueError("Muse packed projection requires block scales") diff --git a/families/muse_glimmer/runtime/CMakeLists.txt b/families/muse_glimmer/runtime/CMakeLists.txt index 91f61addd5..b4c8e38612 100644 --- a/families/muse_glimmer/runtime/CMakeLists.txt +++ b/families/muse_glimmer/runtime/CMakeLists.txt @@ -3,7 +3,8 @@ find_package(ICU REQUIRED COMPONENTS uc i18n) -add_library(trtmc_model_muse_glimmer SHARED plugin.cpp native_pipeline.cpp tokenizer.cpp sampler.cpp) +add_library(trtmc_model_muse_glimmer SHARED plugin.cpp native_pipeline.cpp tokenizer.cpp sampler.cpp + dflash2_tree.cpp media_request.cpp native_vision.cpp vision_geometry.cpp vision_pixels.cpp) target_include_directories(trtmc_model_muse_glimmer PRIVATE ${PROJECT_SOURCE_DIR} ${PROJECT_SOURCE_DIR}/core/runtime/include diff --git a/families/muse_glimmer/runtime/dflash2_tree.cpp b/families/muse_glimmer/runtime/dflash2_tree.cpp new file mode 100644 index 0000000000..5d5c7e50c7 --- /dev/null +++ b/families/muse_glimmer/runtime/dflash2_tree.cpp @@ -0,0 +1,79 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/muse_glimmer/runtime/dflash2_tree.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc::muse_glimmer { +VerifyTree dflash2_tree(int32_t anchor, const std::vector& ids, const SelectRow& select) { + constexpr int k = 16; + if (ids.size() != 15 * k) + throw std::invalid_argument("DFlash2 DDTree requires fifteen selector rows of width 16"); + // Each child distribution is conditional on its own predecessor, not the + // greedy spine's token. Repeated (row, predecessor) states share scores. + using Children = std::array, 4>; + std::map, Children> cache; + struct Prefix { + int32_t parent, token, depth, slot; + float logp; + bool operator<(const Prefix& rhs) const { + if (logp != rhs.logp) + return logp < rhs.logp; + if (parent != rhs.parent) + return parent > rhs.parent; + return slot > rhs.slot; + } + }; + std::priority_queue frontier; + auto expand = [&](int32_t parent, int32_t token, int32_t depth, float logp) { + if (depth == 15) + return; + auto [it, fresh] = cache.try_emplace({depth, token}); + if (fresh) { + const auto candidates = ids.begin() + depth * k; + const auto scores = select(depth, token); + if (scores.size() != k || !std::all_of(scores.begin(), scores.end(), + [](float x) { return std::isfinite(x); })) + throw std::runtime_error("Non-finite DFlash2 selector tree score"); + std::vector slots(k); + std::iota(slots.begin(), slots.end(), 0); + std::partial_sort(slots.begin(), slots.begin() + 4, slots.end(), [&](int a, int b) { + return scores[a] == scores[b] ? candidates[a] < candidates[b] + : scores[a] > scores[b]; + }); + const float max = scores[slots[0]]; + float mass = 0; + for (float score : scores) + mass += std::exp(score - max); + const float normalizer = std::log(mass); + for (int i = 0; i < 4; ++i) { + const int slot = slots[i]; + it->second[i] = {candidates[slot], (scores[slot] - max) - normalizer}; + } + } + for (int i = 0; i < 4; ++i) { + const auto& child = it->second[i]; + frontier.push({parent, child.first, depth + 1, i, logp + child.second}); + } + }; + VerifyTree tree{{anchor, -1}}; + expand(0, anchor, 0, 0); + while (tree.size() < 32 && !frontier.empty()) { + const auto node = frontier.top(); + frontier.pop(); + tree.push_back({node.token, node.parent}); + if (tree.size() < 32) + expand(static_cast(tree.size()) - 1, node.token, node.depth, node.logp); + } + return tree; +} +} // namespace trtmc::muse_glimmer diff --git a/families/muse_glimmer/runtime/dflash2_tree.h b/families/muse_glimmer/runtime/dflash2_tree.h new file mode 100644 index 0000000000..51a2a397e2 --- /dev/null +++ b/families/muse_glimmer/runtime/dflash2_tree.h @@ -0,0 +1,19 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once +#include +#include +#include + +namespace trtmc::muse_glimmer { +struct TreeNode { + int32_t token; + int32_t parent; +}; +using VerifyTree = std::vector; +// Score the 16 candidates from one proposal row given this branch's predecessor. +using SelectRow = std::function(int32_t row, int32_t predecessor)>; +VerifyTree dflash2_tree(int32_t anchor, const std::vector& ids, const SelectRow& select); +} // namespace trtmc::muse_glimmer diff --git a/families/muse_glimmer/runtime/edge_llm/Adapter.cmake b/families/muse_glimmer/runtime/edge_llm/Adapter.cmake index fdd2bfb1d8..e7729ea747 100644 --- a/families/muse_glimmer/runtime/edge_llm/Adapter.cmake +++ b/families/muse_glimmer/runtime/edge_llm/Adapter.cmake @@ -2,27 +2,32 @@ # SPDX-License-Identifier: Apache-2.0 # Complete-network offload is family-owned and absent from native-only builds. -if(TARGET EdgeLLM::Core) - if(NOT TARGET EdgeLLM::Plugin) - message(FATAL_ERROR "Muse-Glimmer Edge adapter requires the complete EdgeLLM package (Core and Plugin)") - endif() - target_sources(trtmc_model_muse_glimmer PRIVATE - "${CMAKE_CURRENT_LIST_DIR}/adapter.cpp" - "${CMAKE_CURRENT_LIST_DIR}/device_link.cu" - ) - target_compile_definitions(trtmc_model_muse_glimmer PRIVATE TRTMC_HAS_EDGE_LLM=1) - target_link_libraries(trtmc_model_muse_glimmer PRIVATE EdgeLLM::Core) - set_target_properties(trtmc_model_muse_glimmer PROPERTIES - CUDA_ARCHITECTURES "${EdgeLLM_CUDA_ARCHITECTURE}" - CUDA_SEPARABLE_COMPILATION ON - CUDA_RESOLVE_DEVICE_SYMBOLS ON - ) +# Each installation links exactly one SDK. Remove the legacy branch after +# the default SDK changes and all family owners have migrated. +if(TARGET TensorRTEdgeLLM::Core) + set(_muse_glimmer_sdk TensorRTEdgeLLM) + target_compile_definitions(trtmc_model_muse_glimmer PRIVATE TRTMC_MUSE_GLIMMER_EDGE_012=1) +elseif(TARGET EdgeLLM::Core) + set(_muse_glimmer_sdk EdgeLLM) +else() + return() endif() - -if(TARGET EdgeLLM::Core) - add_custom_command(TARGET trtmc_model_muse_glimmer POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different - $ $ - VERBATIM - ) +if(NOT TARGET ${_muse_glimmer_sdk}::Plugin) + message(FATAL_ERROR "Muse-Glimmer Edge adapter requires the complete SDK (Core and Plugin)") endif() +target_sources(trtmc_model_muse_glimmer PRIVATE + "${CMAKE_CURRENT_LIST_DIR}/adapter.cpp" + "${CMAKE_CURRENT_LIST_DIR}/device_link.cu" +) +target_compile_definitions(trtmc_model_muse_glimmer PRIVATE TRTMC_HAS_EDGE_LLM=1) +target_link_libraries(trtmc_model_muse_glimmer PRIVATE ${_muse_glimmer_sdk}::Core) +set_target_properties(trtmc_model_muse_glimmer PROPERTIES + CUDA_ARCHITECTURES "${EdgeLLM_CUDA_ARCHITECTURE}" + CUDA_SEPARABLE_COMPILATION ON + CUDA_RESOLVE_DEVICE_SYMBOLS ON +) +add_custom_command(TARGET trtmc_model_muse_glimmer POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different + $ $/libNvInfer_edgellm_plugin.so + VERBATIM +) diff --git a/families/muse_glimmer/runtime/edge_llm/adapter.cpp b/families/muse_glimmer/runtime/edge_llm/adapter.cpp index e11d6ff7a1..d370879aea 100644 --- a/families/muse_glimmer/runtime/edge_llm/adapter.cpp +++ b/families/muse_glimmer/runtime/edge_llm/adapter.cpp @@ -5,15 +5,26 @@ #include "families/muse_glimmer/runtime/edge_llm/adapter.h" #include "families/muse_glimmer/runtime/edge_llm/request.h" +#include "families/muse_glimmer/runtime/sampler.h" #include #include #include #include #include +#ifdef TRTMC_MUSE_GLIMMER_EDGE_012 +#include "families/muse_glimmer/runtime/edge_llm/media.h" +#include "trtmc/internal/model.h" +#include "trtmc/internal/text.h" + +#include +#include +#include +#else #include #include #include +#endif #include #include #include @@ -83,7 +94,8 @@ class Artifacts { "edge_llm/engine/tokenizer.json", "edge_llm/engine/tokenizer_config.json", "edge_llm/engine/chat_template.jinja", "edge_llm/engine/embedding.safetensors", "edge_llm/checkpoint/config.json"}; - if (marker.at("execution_variant") == "dflash") { + if (marker.at("execution_variant") == "dflash" || + marker.at("execution_variant") == "dflash_tree") { for (const auto* name : {"spec_base.engine", "spec_draft.engine", "base_config.json", "draft_config.json"}) required_files.push_back(std::string("edge_llm/engine/") + name); @@ -105,6 +117,10 @@ class Artifacts { required_files.push_back("edge_llm/engine/llm.engine"); required_files.push_back("edge_llm/engine/config.json"); } + if (marker.contains("vision")) + for (const auto* name : {"visual.engine", "config.json", "preprocessor_config.json", + "processor_config.json"}) + required_files.push_back(std::string("edge_llm/engine/visual/") + name); for (const auto& required : required_files) if (!names.count(required) || bundle.find_section(required)->length == 0) throw std::runtime_error( @@ -165,7 +181,12 @@ std::unique_ptr load_plugin() { std::string(dlerror())); using Initialize = bool (*)(void*, const char*); auto initialize = reinterpret_cast(dlsym(plugin.get(), "initEdgellmPlugins")); +#ifdef TRTMC_MUSE_GLIMMER_EDGE_012 + if (!initialize || + !initialize(static_cast(&trt_edgellm::TrtLogger::instance()), "")) +#else if (!initialize || !initialize(static_cast(&trt_edgellm::gLogger), "")) +#endif throw std::runtime_error("Cannot initialize Muse-Glimmer Edge plugin"); return plugin; } @@ -187,30 +208,42 @@ class Stream { std::unique_ptr make_runtime(const Artifacts& artifacts, const nlohmann::json& marker, cudaStream_t stream) { using Runtime = trt_edgellm::rt::LLMInferenceRuntime; - if (marker.at("execution_variant") == "dflash") { + const auto media_dir = marker.contains("vision") ? artifacts.engine() : std::string{}; + if (marker.at("execution_variant") == "dflash" || + marker.at("execution_variant") == "dflash_tree") { trt_edgellm::rt::SpecDecodeDraftingConfig config{}; +#ifdef TRTMC_MUSE_GLIMMER_EDGE_012 + // The release counts the anchor in the verification window but not in proposals. + const bool tree = marker.at("execution_variant") == "dflash_tree"; + config.draftTopK = tree ? marker.at("dflash_top_k").get() : 1; + if (!tree) + config.proposalTokens = 15; + config.verifyTokens = tree ? marker.at("dflash_verify").get() : 16; +#else config.draftingTopK = 1; config.draftingStep = 1; config.verifySize = 16; config.dflashBlockSize = 16; +#endif return std::make_unique( - artifacts.engine(), "", std::unordered_map{}, config, stream, - trt_edgellm::rt::ContextCacheConfig{}, artifacts.checkpoint()); + artifacts.engine(), media_dir, std::unordered_map{}, config, + stream, trt_edgellm::rt::ContextCacheConfig{}, artifacts.checkpoint()); } - return std::make_unique(artifacts.engine(), "", + return std::make_unique(artifacts.engine(), media_dir, std::unordered_map{}, stream, trt_edgellm::rt::ContextCacheConfig{}, artifacts.checkpoint()); } /// Thin persistent Edge API adapter; serialization prevents concurrent use of Edge request state. -class EdgeTask final : public ITextGeneration { +class EdgeTask : public ITextGeneration { public: EdgeTask(const BundleReader& bundle, const nlohmann::json& marker) : artifacts_(bundle, marker), plugin_(load_plugin()), runtime_(make_runtime(artifacts_, marker, stream_.get())), capacity_(marker.at("max_sequence_length").get()), input_limit_(marker.at("max_input_length").get()), - greedy_only_(marker.value("dflash_version", 0) == 1) {} + v1_(marker.value("dflash_version", 0) == 1), + tree_(marker.at("execution_variant") == "dflash_tree") {} std::int32_t default_max_new_tokens() const override { return std::min(512, capacity_ - 1); } @@ -220,13 +253,35 @@ class EdgeTask final : public ITextGeneration { /// Invoke Edge once; failures propagate without attempting native inference. TextResult generate(const std::string& prompt, const TextGenerationConfig& config) override { auto request = make_request(prompt, config, default_max_new_tokens()); - if (greedy_only_ && request.temperature != 0.0F) + return execute(request, config); + } + + protected: + int capacity() const { return capacity_; } + + TextResult execute(trt_edgellm::rt::LLMGenerationRequest& request, + const TextGenerationConfig& config) { + if (tree_) { + if (!muse_is_greedy(muse_sampling_params_from_config(config, -1))) + throw std::invalid_argument( + "Muse-Glimmer DFlash2 DDTree requires greedy generation"); + // Preserve MC's deterministic result even where the SDK classifies + // the equivalent parameter spelling as a reason to switch to vanilla. + request.temperature = 0.0F; + request.topK = 1; + request.topP = 1.0F; + } else if (v1_ && request.temperature != 0.0F) { throw std::invalid_argument("Muse-Glimmer DFlash V1 requires greedy generation"); + } std::lock_guard lock(mutex_); - const auto counts = runtime_->countPromptTokens(request); - if (counts.size() != 1) - throw std::runtime_error("Muse-Glimmer Edge returned invalid prompt counts"); - validate_capacity(counts.front(), input_limit_, capacity_, request.maxGenerateLength); + if (request.requests.front().imageBuffers.empty()) { + const auto counts = runtime_->countPromptTokens(request); + if (counts.size() != 1) + throw std::runtime_error("Muse-Glimmer Edge returned invalid prompt counts"); + validate_capacity(counts.front(), input_limit_, capacity_, request.maxGenerateLength); + } else if (request.maxGenerateLength <= 0 || request.maxGenerateLength >= capacity_) { + throw std::invalid_argument("Muse-Glimmer Edge media output budget exceeds capacity"); + } trt_edgellm::rt::LLMGenerationResponse response{}; // Complete queued work before response/request storage is destroyed, // including exception paths in a persistent task. @@ -243,6 +298,18 @@ class EdgeTask final : public ITextGeneration { (response.finishReasons.front() != trt_edgellm::rt::FinishReason::kEndId && response.finishReasons.front() != trt_edgellm::rt::FinishReason::kLength)) throw std::runtime_error("Muse-Glimmer Edge generation did not complete successfully"); +#ifdef TRTMC_MUSE_GLIMMER_EDGE_012 + if (!request.requests.front().imageBuffers.empty()) { + // countPromptTokens is text-only. Edge reports its actual expanded media length here. + if (response.inputTokenCounts.size() != 1) + throw std::runtime_error("Muse-Glimmer Edge returned no expanded token count"); + validate_capacity(response.inputTokenCounts.front(), input_limit_, capacity_, + request.maxGenerateLength); + if (response.finishReasons.front() == trt_edgellm::rt::FinishReason::kLength && + response.outputIds.front().size() != static_cast(request.maxGenerateLength)) + throw std::runtime_error("Muse-Glimmer Edge clipped the media output budget"); + } +#endif // This API does not expose per-request stage times; zero means unavailable. return {std::move(response.outputTexts.front()), std::move(response.outputIds.front())}; } @@ -255,28 +322,97 @@ class EdgeTask final : public ITextGeneration { std::unique_ptr runtime_; int capacity_; int input_limit_; - bool greedy_only_; + bool v1_; + bool tree_; std::mutex mutex_; }; +#ifdef TRTMC_MUSE_GLIMMER_EDGE_012 +class EdgeMediaTask final : public EdgeTask, + public internal::IModel, + public internal::ITextContinuation, + public internal::IImagesTextToText, + public internal::IVideoTextToText { + public: + EdgeMediaTask(const BundleReader& b, const nlohmann::json& marker) + : EdgeTask(b, marker), task_(b.info().task), fps_(marker.at("vision").at("fps")) {} + const char* task() const noexcept override { return task_.c_str(); } + std::vector task_bindings() override { + return {internal::bind(*this, media_fields()), + internal::bind(*this, media_fields()), + internal::bind(*this, media_fields())}; + } + TextResult run(const internal::TextContinuationRequest& r, internal::ConfigView v) override { + const auto* text = std::get_if(&r.prefix); + if (!text) + throw std::invalid_argument("Muse-Glimmer text continuation requires UTF-8 text"); + return generate(std::string(*text), media_config(v)); + } + TextResult run(const internal::ImagesTextToTextRequest& r, internal::ConfigView v) override { + return run_media(r, v); + } + TextResult run(const internal::VideoTextToTextRequest& r, internal::ConfigView v) override { + return run_media(r, v); + } + + private: + template + TextResult run_media(const R& input, internal::ConfigView view) { + auto cfg = media_config(view); + auto request = + media_request(media_turns(input, cfg), cfg, default_max_new_tokens(), capacity(), fps_); + return execute(request, cfg); + } + std::string task_; + double fps_; +}; +#endif } // namespace ITask* create(const BundleReader& bundle) { const auto bytes = bundle.read_section("edge_llm.json"); const auto marker = nlohmann::json::parse(bytes.begin(), bytes.end()); const auto variant = marker.at("execution_variant").get(); - const bool paired = + const bool chain = variant == "dflash" && (marker.value("dflash_version", 0) == 1 || marker.value("dflash_version", 0) == 2) && marker.value("dflash_block_size", 0) == 16; - if (marker.at("version") != 1 || marker.at("edge_revision") != kRevision || +#ifdef TRTMC_MUSE_GLIMMER_EDGE_012 + const bool paired = + chain || (variant == "dflash_tree" && marker.value("dflash_version", 0) == 2 && + marker.value("dflash_block_size", 0) == 16 && + marker.value("dflash_top_k", 0) == 4 && marker.value("dflash_verify", 0) == 32); + const auto& revision = marker.at("edge_revision"); + const bool supported_weights = + marker.at("weight_format") == "floating" || marker.at("weight_format") == "nvfp4"; + const bool compatible = marker.at("edge_release") == "0.12.0" && + marker.at("builder_flow") == "onnx" && + (revision.is_null() || revision == kRevision); +#else + const bool paired = chain; + const bool supported_weights = marker.at("weight_format") == "nvfp4"; + const bool compatible = marker.at("edge_revision") == kRevision; +#endif + if (marker.at("version") != 1 || !compatible || marker.at("max_sequence_length").get() <= 1 || marker.at("max_input_length").get() <= 0 || marker.at("max_input_length").get() > marker.at("max_sequence_length").get() || marker.at("max_batch_size") != 1 || marker.at("precision") != "fp16" || - marker.at("weight_format") != "nvfp4" || (variant != "autoregressive" && !paired) || + !supported_weights || (variant != "autoregressive" && !paired) || !marker.at("artifacts").is_array()) throw std::runtime_error("Invalid Muse-Glimmer Edge bundle contract"); validate_target(marker.at("target")); + const auto& task = bundle.info().task; +#ifdef TRTMC_MUSE_GLIMMER_EDGE_012 + if (task == "images_text_to_text" || task == "video_text_to_text") { + if (marker.at("weight_format") != "floating" || !marker.contains("vision") || + !std::isfinite(marker.at("vision").at("fps").get()) || + marker.at("vision").at("fps").get() <= 0) + throw std::runtime_error("Invalid Muse-Glimmer Edge media contract"); + return new EdgeMediaTask(bundle, marker); + } +#endif + if (task != "text_generation" || marker.contains("vision")) + throw std::runtime_error("Unexpected Muse-Glimmer Edge bundle task"); return new EdgeTask(bundle, marker); } diff --git a/families/muse_glimmer/runtime/edge_llm/contract.h b/families/muse_glimmer/runtime/edge_llm/contract.h index a3e3aa8414..7e59b6f3c1 100644 --- a/families/muse_glimmer/runtime/edge_llm/contract.h +++ b/families/muse_glimmer/runtime/edge_llm/contract.h @@ -13,7 +13,11 @@ namespace trtmc::muse_glimmer::edge_llm { +#ifdef TRTMC_MUSE_GLIMMER_EDGE_012 +inline constexpr const char* kRevision = "513dcd18291e587c80928911a480761352f3c2d8"; +#else inline constexpr const char* kRevision = "95515c2f87fba8982db5a519f9022277667b3cc9"; +#endif /// Return whether an artifact is a normalized file below one of the two Edge roots. inline bool safe_artifact_path(const std::string& name) { diff --git a/families/muse_glimmer/runtime/edge_llm/media.h b/families/muse_glimmer/runtime/edge_llm/media.h new file mode 100644 index 0000000000..ff693e4997 --- /dev/null +++ b/families/muse_glimmer/runtime/edge_llm/media.h @@ -0,0 +1,88 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include "families/muse_glimmer/runtime/edge_llm/request.h" +#include "families/muse_glimmer/runtime/media_request.h" +#include "families/muse_glimmer/runtime/vision_pixels.h" + +#include +#include + +namespace trtmc::muse_glimmer::edge_llm { +inline trt_edgellm::rt::imageUtils::ImageData pixels(Span frames, + bool video, double fps, int capacity) { + if (!frames.size() || !frames.data() || frames.size() > 2 * static_cast(capacity)) + throw std::invalid_argument("Invalid Muse Edge visual frame count"); + const auto& first = frames.data()[0]; + // Validate storage and dimensions before allocating an Edge tensor. + auto rgb = visual_rgb(first); + if (frames.size() > static_cast(std::numeric_limits::max()) / rgb.size()) + throw std::invalid_argument("Muse Edge frame stack exceeds tensor capacity"); + using namespace trt_edgellm::rt; + using Dtype = decltype(Tensor{}.getDataType()); + Tensor tensor({static_cast(frames.size()), first.height, first.width, 3}, + DeviceType::kCPU, Dtype::kUINT8); + auto* out = static_cast(tensor.rawPointer()); + for (size_t i = 0; i < frames.size(); ++i) { + if (i != 0) { + const auto& frame = frames.data()[i]; + if (frame.width != first.width || frame.height != first.height) + throw std::invalid_argument("Muse Edge video requires equal frame dimensions"); + rgb = visual_rgb(frame); + } + out = std::copy(rgb.begin(), rgb.end(), out); + } + imageUtils::ImageData data(std::move(tensor)); + data.isVideo = video; + data.fps = fps; + return data; +} + +inline trt_edgellm::rt::LLMGenerationRequest media_request(const MediaTurns& turns, + const TextGenerationConfig& cfg, + int budget, int capacity, double fps) { + if (capacity <= 0) + throw std::invalid_argument("Invalid Muse Edge visual capacity"); + // Reject the whole request before converting even its first borrowed image. + auto remaining_frames = 2 * static_cast(capacity); + for (const auto& turn : turns) { + for (const auto& part : turn.parts) { + const auto* video = std::get_if(&part); + const auto frames = + video ? video->frames.size() + : static_cast(std::holds_alternative(part)); + if (frames > remaining_frames) + throw std::invalid_argument( + "Muse Edge total visual frame count exceeds request capacity"); + remaining_frames -= frames; + } + } + auto request = make_request("", cfg, budget); + auto& row = request.requests.front(); + row.messages.clear(); + for (const auto& turn : turns) { + auto& msg = row.messages.emplace_back(); + msg.role = turn.role; + msg.contentIsArray = true; + for (const auto& part : turn.parts) { + if (const auto* text = std::get_if(&part)) { + msg.contents.push_back({"text", *text}); + } else if (const auto* image = std::get_if(&part)) { + msg.contents.push_back({"image", cfg.use_chat_template ? "" : "<|patch|>"}); + row.imageBuffers.push_back(pixels({image, 1}, false, fps, capacity)); + } else { + const auto& video = std::get(part); + auto data = pixels(video.frames, true, fps, capacity); + for (size_t i = 0; i < video.timestamps_seconds.size(); ++i) + data.timestamps.push_back(video.timestamps_seconds.data()[i]); + msg.contents.push_back({"video", cfg.use_chat_template ? "" : "<|video|>"}); + row.imageBuffers.push_back(std::move(data)); + } + } + } + return request; +} +} // namespace trtmc::muse_glimmer::edge_llm diff --git a/families/muse_glimmer/runtime/edge_llm/request.h b/families/muse_glimmer/runtime/edge_llm/request.h index 015eea7b27..a6a4344a63 100644 --- a/families/muse_glimmer/runtime/edge_llm/request.h +++ b/families/muse_glimmer/runtime/edge_llm/request.h @@ -6,7 +6,11 @@ #include "families/muse_glimmer/runtime/edge_llm/contract.h" +#ifdef TRTMC_MUSE_GLIMMER_EDGE_012 +#include +#else #include +#endif namespace trtmc::muse_glimmer::edge_llm { diff --git a/families/muse_glimmer/runtime/media_request.cpp b/families/muse_glimmer/runtime/media_request.cpp new file mode 100644 index 0000000000..043e71ed43 --- /dev/null +++ b/families/muse_glimmer/runtime/media_request.cpp @@ -0,0 +1,147 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/muse_glimmer/runtime/media_request.h" + +#include +#include +#include +#include + +namespace trtmc::muse_glimmer { +using namespace internal; +Span media_fields() { + static const std::vector fields{ + {"max_new_tokens", ConfigKind::I64, int64_t{128}, "Maximum generated tokens"}, + {"temperature", ConfigKind::F64, 0.0, "Sampling temperature; zero is greedy"}, + {"top_k", ConfigKind::I64, int64_t{1}, "Top-k selection"}, + {"top_p", ConfigKind::F64, 1.0, "Nucleus sampling threshold"}, + {"seed", ConfigKind::I64, int64_t{-1}, "Sampling seed; -1 is unspecified"}, + {"enable_thinking", ConfigKind::Bool, true, + "Allow private reasoning before the public answer"}, + {"use_chat_template", ConfigKind::Bool, true, "Render the Muse conversation template"}, + {"system_prompt", ConfigKind::String, std::string_view{}, "Optional system instruction"}, + }; + return {fields.data(), fields.size()}; +} +TextGenerationConfig media_config(ConfigView supplied) { + const auto fields = media_fields(); + validate_config(fields, supplied); + TextGenerationConfig c; + auto integer = [&](const char* key) { + const auto n = *config_get(supplied, fields, key); + if (n < std::numeric_limits::min() || n > std::numeric_limits::max()) + throw ConfigError(std::string(key) + " exceeds the supported integer range"); + return static_cast(n); + }; + c.max_new_tokens = integer("max_new_tokens"); + c.top_k = integer("top_k"); + c.seed = integer("seed"); + c.temperature = *config_get(supplied, fields, "temperature"); + c.top_p = *config_get(supplied, fields, "top_p"); + c.enable_thinking = *config_get(supplied, fields, "enable_thinking"); + c.use_chat_template = *config_get(supplied, fields, "use_chat_template"); + c.system_prompt = *config_get(supplied, fields, "system_prompt"); + if (c.max_new_tokens < 1 || c.top_k < 0 || c.seed < -1 || !std::isfinite(c.temperature) || + c.temperature < 0 || !std::isfinite(c.top_p) || c.top_p <= 0 || c.top_p > 1) + throw ConfigError("Invalid Muse generation configuration"); + return c; +} + +namespace { +void validate_video(const VideoView& v) { + if (!v.frames.data() || !v.frames.size()) + throw std::invalid_argument("Muse video requires at least one frame"); + if (v.timestamps_seconds.size() && + (!v.timestamps_seconds.data() || v.timestamps_seconds.size() != v.frames.size())) + throw std::invalid_argument("Muse video requires one timestamp per frame"); + for (std::size_t i = 0; i < v.frames.size(); ++i) { + const auto& frame = v.frames.data()[i]; + if (!frame.data || !frame.width || !frame.height || + frame.width != v.frames.data()[0].width || frame.height != v.frames.data()[0].height) + throw std::invalid_argument( + "Muse video frames must have consistent positive dimensions"); + if (v.timestamps_seconds.size()) { + double t = v.timestamps_seconds.data()[i]; + if (!std::isfinite(t) || t < 0 || (i > 0 && t <= v.timestamps_seconds.data()[i - 1])) + throw std::invalid_argument("Muse video timestamps must be finite and increasing"); + } + } +} +template +MediaTurns parse(const Request& r, const TextGenerationConfig& cfg) { + if (r.tools.size() || !r.messages.data() || !r.messages.size()) + throw std::invalid_argument("Muse media requires messages without tool definitions"); + MediaTurns turns; + if (!cfg.system_prompt.empty()) { + if (cfg.system_prompt.find("<|") != std::string::npos) + throw std::invalid_argument( + "Reserved Muse control sequence in configured system prompt"); + turns.push_back({"system", {cfg.system_prompt}}); + } + for (std::size_t i = 0; i < r.messages.size(); ++i) { + const auto& msg = r.messages.data()[i]; + const char* role = nullptr; + switch (msg.role) { + case MessageRole::System: + if (!turns.empty()) + throw std::invalid_argument("Duplicate or misplaced Muse system message"); + role = "system"; + break; + case MessageRole::User: + role = "user"; + break; + case MessageRole::Assistant: + role = "assistant"; + break; + default: + throw std::invalid_argument("Unsupported Muse media message role"); + } + if (!msg.parts.data() || !msg.parts.size()) + throw std::invalid_argument("Empty Muse media turn"); + MediaTurn t{role, {}}; + for (std::size_t j = 0; j < msg.parts.size(); ++j) + std::visit( + [&](const auto& part) { + using T = std::decay_t; + if constexpr (std::is_same_v) { + const std::string text(part.text); + if (text.find("<|") != std::string::npos) + throw std::invalid_argument( + "Reserved Muse control sequence in typed message text"); + t.parts.emplace_back(text); + } else if constexpr (std::is_same_v || + std::is_same_v) { + if (msg.role != MessageRole::User) + throw std::invalid_argument("Muse media must belong to a user turn"); + if constexpr (std::is_same_v) + validate_video(part); + t.parts.emplace_back(part); + } else + throw std::invalid_argument( + "Muse media does not support tool or reasoning content parts"); + }, + msg.parts.data()[j]); + turns.push_back(std::move(t)); + } + if (turns.empty() || turns.back().role != "user") + throw std::invalid_argument("Muse generation requires a final user turn"); + if (!cfg.use_chat_template && turns.size() != 1) + throw std::invalid_argument("Raw Muse media accepts one user turn"); + return turns; +} +} // namespace +MediaTurns media_turns(const ImagesTextToTextRequest& r, const TextGenerationConfig& c) { + return parse(r, c); +} +MediaTurns media_turns(const VideoTextToTextRequest& r, const TextGenerationConfig& c) { + return parse(r, c); +} +double video_timestamp(const VideoView& v, std::size_t frame, double default_fps) { + if (frame >= v.frames.size() || !(default_fps > 0) || !std::isfinite(default_fps)) + throw std::invalid_argument("Invalid Muse video frame time"); + return v.timestamps_seconds.size() ? v.timestamps_seconds.data()[frame] + : static_cast(frame) / default_fps; +} +} // namespace trtmc::muse_glimmer diff --git a/families/muse_glimmer/runtime/media_request.h b/families/muse_glimmer/runtime/media_request.h new file mode 100644 index 0000000000..3d491f5626 --- /dev/null +++ b/families/muse_glimmer/runtime/media_request.h @@ -0,0 +1,26 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include "trtmc/internal/language.h" + +#include +#include +#include + +namespace trtmc::muse_glimmer { +using MediaPart = std::variant; +struct MediaTurn { + std::string role; + std::vector parts; +}; +using MediaTurns = std::vector; + +Span media_fields(); +TextGenerationConfig media_config(internal::ConfigView); +MediaTurns media_turns(const internal::ImagesTextToTextRequest&, const TextGenerationConfig&); +MediaTurns media_turns(const internal::VideoTextToTextRequest&, const TextGenerationConfig&); +double video_timestamp(const internal::VideoView&, std::size_t frame, double default_fps); +} // namespace trtmc::muse_glimmer diff --git a/families/muse_glimmer/runtime/native_pipeline.cpp b/families/muse_glimmer/runtime/native_pipeline.cpp index bcac16e164..1f49533745 100644 --- a/families/muse_glimmer/runtime/native_pipeline.cpp +++ b/families/muse_glimmer/runtime/native_pipeline.cpp @@ -4,8 +4,12 @@ */ #include "families/muse_glimmer/runtime/native_pipeline.h" +#include "families/muse_glimmer/runtime/dflash2_tree.h" +#include "families/muse_glimmer/runtime/native_vision.h" #include "families/muse_glimmer/runtime/sampler.h" #include "families/muse_glimmer/runtime/tokenizer.h" +#include "trtmc/internal/model.h" +#include "trtmc/internal/text.h" #include "trtmc/runtime/trt_backend.h" #include @@ -32,14 +36,18 @@ using Clock = std::chrono::steady_clock; double milliseconds(Clock::time_point start) { return std::chrono::duration(Clock::now() - start).count(); } -class NativePipeline final : public ITextGeneration { +class NativePipeline : public ITextGeneration { public: explicit NativePipeline(const FamilyContext& context) : config_(nlohmann::json::parse(section_text(context.reader, "runtime.json"))), tokenizer_(section_text(context.reader, "tokenizer.json")) { const auto variant = config_.at("execution_variant").get(); - if (config_.at("version") != 1 || (variant != "autoregressive" && variant != "dflash") || - config_.at("precision") != "fp16" || config_.at("weight_format") != "nvfp4_mxfp8") + tree_ = variant == "dflash_tree"; + if (config_.at("version") != 1 || + (variant != "autoregressive" && variant != "dflash" && !tree_) || + config_.at("precision") != "fp16" || + (config_.at("weight_format") != "nvfp4_mxfp8" && + config_.at("weight_format") != "floating")) throw std::invalid_argument("Muse native bundle has an incompatible runtime contract"); capacity_ = config_.at("max_cache_length"); input_limit_ = config_.at("max_input_length"); @@ -73,8 +81,20 @@ class NativePipeline final : public ITextGeneration { name); } bind_prefill_caches(); + if (config_.contains("vision")) { + visual_width_ = config_.at("hidden_size"); + if (!prefill_ || config_.at("vision").at("text_width") != visual_width_ || + !decoder_->has_input("is_visual") || + decoder_->tensor_dtype("is_visual") != DType::kInt32 || + !decoder_->has_input("visual_embeddings") || + decoder_->tensor_dtype("visual_embeddings") != DType::kFloat16) + throw std::invalid_argument("Missing Muse visual inputs on the native decoder"); + auto plan = context.reader.read_section("vision.plan"); + vision_ = std::make_unique( + context.backend.create_module(plan.data(), plan.size(), {}), config_.at("vision")); + } decoder_->set_timing_label("muse_glimmer_native_target"); - if (variant == "dflash") { + if (variant == "dflash" || tree_) { draft_version_ = config_.at("dflash_version"); block_ = config_.at("dflash_block_size"); feature_width_ = config_.at("feature_width"); @@ -82,6 +102,9 @@ class NativePipeline final : public ITextGeneration { draft_window_ = config_.at("draft_window"); rank_ = config_.at("selector_rank"); candidates_ = config_.at("selector_top_k"); + if (tree_ && (draft_version_ != 2 || candidates_ != 16 || rank_ != 256 || + config_.at("dflash_top_k") != 4 || config_.at("dflash_verify") != 32)) + throw std::invalid_argument("Invalid Muse native DFlash2 DDTree profile"); if ((draft_version_ != 1 && draft_version_ != 2) || block_ != 16 || capacity_ < block_ || feature_width_ <= 0 || mask_token_ < 0 || mask_token_ >= vocab_ || @@ -145,17 +168,38 @@ class NativePipeline final : public ITextGeneration { TextResult generate(const std::string& prompt, const TextGenerationConfig& cfg) override { const std::lock_guard guard(mutex_); validate(cfg); + const auto setup = Clock::now(); + const auto text = cfg.use_chat_template ? render_atem(prompt, cfg.system_prompt, bos_text_, + cfg.enable_thinking) + : prompt; + auto input = tokenizer_.encode(text); + if (input.empty()) + input.push_back(bos_); + return decode(input, cfg, setup, nullptr); + } + + TextResult generate_media(const MediaTurns& turns, const TextGenerationConfig& cfg) { + const std::lock_guard guard(mutex_); + validate(cfg); + if (!vision_ || cfg.max_new_tokens > capacity_) + throw std::invalid_argument("Invalid Muse visual bundle or generation budget"); + const auto setup = Clock::now(); + const auto prefix = + vision_->prepare(turns, tokenizer_, bos_text_, cfg, + std::min(input_limit_, capacity_ - cfg.max_new_tokens)); + return decode(prefix.ids, cfg, setup, &prefix); + } + + private: + TextResult decode(const std::vector& input, const TextGenerationConfig& cfg, + Clock::time_point setup, const MediaPrefix* media) { const auto params = muse_sampling_params_from_config(cfg, eos_.front()); + if (tree_ && !muse_is_greedy(params)) + throw std::invalid_argument("Muse-Glimmer DFlash2 DDTree requires greedy generation"); if (draft_version_ == 1 && !muse_is_greedy(params)) throw std::invalid_argument("Muse-Glimmer DFlash V1 requires greedy generation"); if (cfg.eos_token_id < -1 || cfg.eos_token_id >= vocab_ || cfg.seed < -1) throw std::invalid_argument("Muse native EOS override or seed is out of range"); - const auto setup = Clock::now(); - const auto text = - cfg.use_chat_template ? render_atem(prompt, cfg.system_prompt, bos_text_) : prompt; - auto input = tokenizer_.encode(text); - if (input.empty()) - input.push_back(bos_); if (input.size() > static_cast(input_limit_) || input.size() + static_cast(cfg.max_new_tokens) > static_cast(capacity_)) @@ -167,7 +211,7 @@ class NativePipeline final : public ITextGeneration { const double setup_ms = milliseconds(setup); auto start = Clock::now(); std::vector logits(vocab_); - prefill(input, logits); + prefill(input, logits, media); int position = static_cast(input.size()); const double prefill_ms = milliseconds(start); start = Clock::now(); @@ -179,8 +223,29 @@ class NativePipeline final : public ITextGeneration { int rounds = 0, proposed = 0, accepted_count = 0; while (static_cast(output.size()) < cfg.max_new_tokens && !is_eos(output.back(), cfg)) { - const auto proposals = propose(output.back(), position, params, rng); + VerifyTree tree; + const auto proposals = propose(output.back(), position, params, rng, tree); ++rounds; + if (tree_) { + proposed += static_cast(tree.size()) - 1; + int parent = 0; + do { + // Only verified target tokens are ever committed to the KV cache. + step(output.back(), position++, logits); + const int token = sampler->sample(logits.data(), vocab_, params).token_id; + output.push_back(token); + const auto child = + std::find_if(tree.begin() + 1, tree.end(), [&](const TreeNode& n) { + return n.parent == parent && n.token == token; + }); + if (child == tree.end()) + break; + ++accepted_count; + parent = static_cast(child - tree.begin()); + } while (static_cast(output.size()) < cfg.max_new_tokens && + !is_eos(output.back(), cfg)); + continue; + } proposed += static_cast(proposals.size()); bool all_accepted = true; for (const auto& proposal : proposals) { @@ -206,7 +271,8 @@ class NativePipeline final : public ITextGeneration { muse_probabilities(logits.data(), vocab_, params), rng)); } } - std::clog << "[muse_glimmer] native DFlash v" << draft_version_ << " rounds=" << rounds + std::clog << "[muse_glimmer] native DFlash v" << draft_version_ + << (tree_ ? " DDTree" : "") << " rounds=" << rounds << " proposed=" << proposed << " accepted=" << accepted_count << '\n'; } else { for (int i = 0; i < cfg.max_new_tokens; ++i) { @@ -220,7 +286,8 @@ class NativePipeline final : public ITextGeneration { step(sampled.token_id, position++, logits); } } - TextResult result(tokenizer_.decode(output), output, prefill_ms, milliseconds(start)); + // Display text omits declared special pieces, but the public IDs remain lossless. + TextResult result(tokenizer_.decode(output, true), output, prefill_ms, milliseconds(start)); result.setup_ms = setup_ms; return result; } @@ -236,7 +303,8 @@ class NativePipeline final : public ITextGeneration { } std::vector propose(int32_t anchor, int32_t position, - const MuseSamplingParams& params, uint64_t& rng) { + const MuseSamplingParams& params, uint64_t& rng, + VerifyTree& tree) { std::vector tokens(block_, mask_token_), positions(block_); tokens.front() = anchor; const int width = capacity_ + block_; @@ -298,8 +366,7 @@ class NativePipeline final : public ITextGeneration { draft_params.top_p = 1; draft_params.min_p = 0; draft_params.seed = 0; - int32_t previous = anchor; - for (int row = 0; row < rows; ++row) { + auto select_row = [&](int32_t row, int32_t previous) { int32_t* row_ids = ids.data() + row * candidates_; if (std::any_of(row_ids, row_ids + candidates_, [&](int id) { return id < 0 || id >= vocab_; })) @@ -320,6 +387,16 @@ class NativePipeline final : public ITextGeneration { if (std::any_of(scores.begin(), scores.end(), [](float x) { return !std::isfinite(x); })) throw std::runtime_error("Muse native V2 selector produced nonfinite scores"); + return scores; + }; + if (tree_) { + tree = dflash2_tree(anchor, ids, select_row); + return {}; + } + int32_t previous = anchor; + for (int row = 0; row < rows; ++row) { + const auto* row_ids = ids.data() + row * candidates_; + const auto scores = select_row(row, previous); std::vector q(vocab_, 0); if (greedy) { int best = 0; @@ -419,16 +496,17 @@ class NativePipeline final : public ITextGeneration { } } - void prefill(const std::vector& input, std::vector& logits) { + void prefill(const std::vector& input, std::vector& logits, + const MediaPrefix* media) { const int total = static_cast(input.size()); if (!prefill_) { for (int position = 0; position < total; ++position) - run_rows(*decoder_, &input[position], 1, position, logits); + run_rows(*decoder_, &input[position], 1, position, logits, media); return; } for (int start = 0; start < total; start += prefill_rows_) run_rows(*prefill_, &input[start], std::min(prefill_rows_, total - start), start, - logits); + logits, media); } void step(int32_t token, int32_t position, std::vector& logits) { @@ -439,7 +517,7 @@ class NativePipeline final : public ITextGeneration { // commits their K/V (and draft features) to the shared caches, and returns // the logits of the last row. void run_rows(ITrtModule& module, const int32_t* tokens, int rows, int32_t position, - std::vector& logits) { + std::vector& logits, const MediaPrefix* media = nullptr) { if (rows < 1 || position < 0 || position + rows > capacity_ || std::any_of(tokens, tokens + rows, [&](int32_t t) { return t < 0 || t >= vocab_; })) throw std::out_of_range("Muse token or cache position is out of range"); @@ -454,6 +532,28 @@ class NativePipeline final : public ITextGeneration { TensorMap inputs{{"token_id", {const_cast(tokens), {rows}, DType::kInt32}}, {"position_id", {positions.data(), {rows}, DType::kInt32}}, {"attention_mask", {mask.data(), {rows, capacity_}, DType::kFloat32}}}; + std::vector visual_mask; + std::vector visual_values; + if (vision_) { + visual_mask.assign(rows, 0); + visual_values.assign(static_cast(rows) * visual_width_, 0); + if (media) + for (int row = 0; row < rows; ++row) { + const int feature = media->feature_at.at(position + row); + if (feature < 0) + continue; + const auto start = static_cast(feature) * visual_width_; + if (start + visual_width_ > media->features.size()) + throw std::runtime_error("Missing native Muse feature row"); + std::copy_n(media->features.data() + start, visual_width_, + visual_values.data() + + static_cast(row) * visual_width_); + visual_mask[row] = 1; + } + inputs.emplace("is_visual", Tensor{visual_mask.data(), {rows, 1}, DType::kInt32}); + inputs.emplace("visual_embeddings", + Tensor{visual_values.data(), {rows, visual_width_}, DType::kFloat16}); + } module.forward_async(inputs); for (int i = 0; i < layers_; ++i) for (const char* stem : {"k", "v"}) { @@ -485,6 +585,9 @@ class NativePipeline final : public ITextGeneration { Tokenizer tokenizer_; std::unique_ptr decoder_, prefill_, draft_, selector_; int prefill_rows_{1}; + int visual_width_{}; + std::unique_ptr vision_; + bool tree_{false}; int draft_version_{}, block_{}, feature_width_{}, mask_token_{}, draft_window_{}, rank_{}, candidates_{}; std::mutex mutex_; @@ -492,8 +595,48 @@ class NativePipeline final : public ITextGeneration { std::vector eos_; std::string bos_text_; }; +class NativeMediaPipeline final : public NativePipeline, + public internal::IModel, + public internal::ITextContinuation, + public internal::IImagesTextToText, + public internal::IVideoTextToText { + public: + explicit NativeMediaPipeline(const FamilyContext& c) + : NativePipeline(c), task_(c.reader.info().task) {} + const char* task() const noexcept override { return task_.c_str(); } + std::vector task_bindings() override { + return {internal::bind(*this, media_fields()), + internal::bind(*this, media_fields()), + internal::bind(*this, media_fields())}; + } + TextResult run(const internal::TextContinuationRequest& r, internal::ConfigView v) override { + const auto* text = std::get_if(&r.prefix); + if (!text) + throw std::invalid_argument("Muse-Glimmer text continuation requires UTF-8 text"); + return generate(std::string(*text), media_config(v)); + } + TextResult run(const internal::ImagesTextToTextRequest& r, internal::ConfigView view) override { + auto cfg = media_config(view); + return generate_media(media_turns(r, cfg), cfg); + } + TextResult run(const internal::VideoTextToTextRequest& r, internal::ConfigView view) override { + auto cfg = media_config(view); + return generate_media(media_turns(r, cfg), cfg); + } + + private: + std::string task_; +}; } // namespace ITask* create_native(const FamilyContext& context) { + const auto& task = context.reader.info().task; + if (task == "images_text_to_text" || task == "video_text_to_text") { + if (!context.reader.find_section("vision.plan")) + throw std::invalid_argument("Muse media bundle has no visual encoder"); + return new NativeMediaPipeline(context); + } + if (task != "text_generation") + throw std::invalid_argument("Unsupported Muse native task"); return new NativePipeline(context); } } // namespace trtmc::muse_glimmer diff --git a/families/muse_glimmer/runtime/native_vision.cpp b/families/muse_glimmer/runtime/native_vision.cpp new file mode 100644 index 0000000000..80435e8620 --- /dev/null +++ b/families/muse_glimmer/runtime/native_vision.cpp @@ -0,0 +1,164 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/muse_glimmer/runtime/native_vision.h" + +#include "families/muse_glimmer/runtime/vision_geometry.h" +#include "families/muse_glimmer/runtime/vision_pixels.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc::muse_glimmer { +namespace { +struct Group { + internal::ImageView first; + const internal::ImageView* second; + int rows, cols; +}; +using Source = std::variant; +std::vector<__half> half_values(const std::vector& values) { + std::vector<__half> result(values.size()); + std::transform(values.begin(), values.end(), result.begin(), + [](float v) { return __float2half_rn(v); }); + return result; +} +} // namespace +NativeVision::NativeVision(std::unique_ptr module, const nlohmann::json& m) + : module_(std::move(module)), patch_(m.at("patch_size")), side_(m.at("table_side")), + head_dim_(m.at("head_dim")), width_(m.at("text_width")), max_patches_(m.at("max_patches")), + image_limit_(m.at("max_image_tokens")), video_limit_(m.at("max_video_frame_tokens")), + image_id_(m.at("image_token_id")), video_id_(m.at("video_token_id")), + theta_(m.at("rope_theta")), fps_(m.at("fps")) { + if (!module_ || !module_->ok() || patch_ != 14 || side_ <= 0 || head_dim_ <= 0 || width_ <= 0 || + max_patches_ <= 0 || image_limit_ <= 0 || video_limit_ <= 0 || + image_limit_ > max_patches_ / 4 || video_limit_ > max_patches_ / 4 || !(fps_ > 0) || + !std::isfinite(fps_) || !module_->has_output("visual_embeddings") || + module_->tensor_dtype("visual_embeddings") != DType::kFloat16) + throw std::invalid_argument("Invalid Muse native visual engine contract"); +} +MediaPrefix NativeVision::prepare(const MediaTurns& turns, const Tokenizer& tokenizer, + const std::string& bos, const TextGenerationConfig& cfg, + int token_budget) { + if (token_budget < 1) + throw std::invalid_argument("Muse visual prompt has no remaining token capacity"); + std::vector sources; + std::string system, body; + for (const auto& turn : turns) { + std::string contents; + for (const auto& part : turn.parts) { + if (auto* text = std::get_if(&part)) + contents += *text; + else if (auto* image = std::get_if(&part)) { + contents += "<|patch|>"; + sources.emplace_back(*image); + } else { + contents += "<|video|>"; + sources.emplace_back(std::get(part)); + } + } + if (turn.role == "system") + system = contents; + else if (!cfg.use_chat_template) + body += contents; + else + body += "<|start|>" + + (turn.role == "user" ? std::string("user") : std::string("assistant to=user")) + + "<|message|>" + contents + "<|eot|>"; + } + auto input = + tokenizer.encode(cfg.use_chat_template ? render_atem_system(system, bos) + body + + render_atem_generation(cfg.enable_thinking) + : body); + auto special = [&](const char* name) { + auto ids = tokenizer.encode(name); + if (ids.size() != 1) + throw std::invalid_argument("Missing Muse visual control token"); + return ids.front(); + }; + if (special("<|patch|>") != image_id_ || special("<|video|>") != video_id_) + throw std::invalid_argument("Muse visual placeholder IDs do not match tokenizer"); + MediaPrefix out; + std::vector groups; + std::size_t next = 0; + int feature_rows = 0; + auto put = [&](int32_t id, int row = -1) { + if (out.ids.size() >= static_cast(token_budget)) + throw std::invalid_argument("Expanded Muse media exceeds bundle capacity"); + out.ids.push_back(id); + out.feature_at.push_back(row); + }; + auto group = [&](internal::ImageView first, const internal::ImageView* second, int limit) { + if (first.height > INT32_MAX || first.width > INT32_MAX) + throw std::invalid_argument("Muse image dimensions exceed the supported range"); + auto [h, w] = visual_patch_grid(static_cast(first.height), + static_cast(first.width), patch_, limit); + if (h > max_patches_ / w) + throw std::invalid_argument("Muse visual grid exceeds profile"); + for (int t = 0; t < h * w / 4; ++t) + put(image_id_, feature_rows++); + groups.push_back({first, second, h, w}); + }; + for (auto id : input) { + if (id != image_id_ && id != video_id_) { + put(id); + continue; + } + if (next >= sources.size()) + throw std::invalid_argument("Unmatched Muse visual placeholder"); + const auto& source = sources[next++]; + if (id == image_id_) { + const auto& image = std::get(source); + put(special("<|image_start|>")); + group(image, nullptr, image_limit_); + put(special("<|image_end|>")); + } else { + const auto& video = std::get(source); + put(special("<|vid_start|>")); + for (std::size_t i = 0; i < video.frames.size(); i += 2) { + std::ostringstream label; + label.imbue(std::locale::classic()); + label << "Time: " << std::fixed << std::setprecision(1) + << video_timestamp(video, i, fps_) << "s"; + for (auto token : tokenizer.encode(label.str())) + put(token); + group(video.frames[i], i + 1 < video.frames.size() ? &video.frames[i + 1] : nullptr, + video_limit_); + put(special(i + 2 < video.frames.size() ? "<|vid_frame_separator|>" + : "<|vid_end|>")); + } + } + } + if (next != sources.size() || out.ids.empty()) + throw std::invalid_argument("Invalid Muse media prompt"); + out.features.reserve(static_cast(feature_rows) * width_); + for (const auto& v : groups) { + auto g = make_vision_grid(v.rows, v.cols, side_, head_dim_, theta_, max_patches_); + auto pixels = half_values(visual_patches(v.first, v.second, v.rows, v.cols, patch_)); + auto weights = half_values(g.position_weights); + const int n = v.rows * v.cols; + TensorMap args{{"patches", {pixels.data(), {n, 6 * patch_ * patch_}, DType::kFloat16}}, + {"position_indices", {g.position_indices.data(), {n, 4}, DType::kInt32}}, + {"position_weights", {weights.data(), {n, 4}, DType::kFloat16}}, + {"rotary_cos", {g.rotary_cos.data(), {n, 1, head_dim_}, DType::kFloat32}}, + {"rotary_sin", {g.rotary_sin.data(), {n, 1, head_dim_}, DType::kFloat32}}, + {"window_ids", {g.window_ids.data(), {n}, DType::kInt32}}, + {"merge_order", {g.merge_order.data(), {n}, DType::kInt32}}}; + auto result = module_->forward(args); + const auto& features = result.at("visual_embeddings"); + if (!features.data || features.dtype != DType::kFloat16 || + features.shape != std::vector{n / 4, width_}) + throw std::runtime_error("Muse native encoder returned wrong feature type or shape"); + auto* data = static_cast(features.data); + out.features.insert(out.features.end(), data, data + features.numel()); + } + return out; +} +} // namespace trtmc::muse_glimmer diff --git a/families/muse_glimmer/runtime/native_vision.h b/families/muse_glimmer/runtime/native_vision.h new file mode 100644 index 0000000000..e1eeedee0b --- /dev/null +++ b/families/muse_glimmer/runtime/native_vision.h @@ -0,0 +1,31 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once +#include "families/muse_glimmer/runtime/media_request.h" +#include "families/muse_glimmer/runtime/tokenizer.h" +#include "trtmc/runtime/trt_backend.h" + +#include + +namespace trtmc::muse_glimmer { +struct MediaPrefix { + std::vector ids; + std::vector feature_at; + std::vector features; +}; +class NativeVision { + public: + NativeVision(std::unique_ptr module, const nlohmann::json& metadata); + MediaPrefix prepare(const MediaTurns&, const Tokenizer&, const std::string& bos, + const TextGenerationConfig&, int token_budget); + + private: + std::unique_ptr module_; + int patch_, side_, head_dim_, width_, max_patches_, image_limit_, video_limit_, image_id_, + video_id_; + float theta_; + double fps_; +}; +} // namespace trtmc::muse_glimmer diff --git a/families/muse_glimmer/runtime/tokenizer.cpp b/families/muse_glimmer/runtime/tokenizer.cpp index 34cba14b75..766f09b15e 100644 --- a/families/muse_glimmer/runtime/tokenizer.cpp +++ b/families/muse_glimmer/runtime/tokenizer.cpp @@ -17,6 +17,7 @@ #include #include #include +#include namespace trtmc::muse_glimmer { namespace { @@ -70,6 +71,7 @@ void replace_all(std::string& text, const std::string& from, const std::string& } // namespace struct Tokenizer::Impl { + std::unordered_set special_ids; std::unordered_map vocab; std::unordered_map merges; std::vector decoded; @@ -181,6 +183,8 @@ Tokenizer::Tokenizer(const std::string& text) : impl_(std::make_unique()) if (content.empty() || id < 0) throw std::invalid_argument("Muse added token has invalid content or ID"); impl_->added.emplace_back(content, id); + if (item.value("special", false)) + impl_->special_ids.insert(id); if (impl_->decoded.size() <= static_cast(id)) impl_->decoded.resize(static_cast(id) + 1); impl_->decoded[id] = content; @@ -210,17 +214,17 @@ std::vector Tokenizer::encode(const std::string& text) const { } return output; } -std::string Tokenizer::decode(const std::vector& ids) const { +std::string Tokenizer::decode(const std::vector& ids, bool skip_special) const { std::string result; for (const auto id : ids) { if (id < 0 || static_cast(id) >= impl_->decoded.size()) throw std::out_of_range("Muse token ID is outside the vocabulary"); - result += impl_->decoded[id]; + if (!skip_special || !impl_->special_ids.count(id)) + result += impl_->decoded[id]; } return result; } -std::string render_atem(const std::string& prompt, const std::string& system, - const std::string& bos) { +std::string render_atem_system(const std::string& system, const std::string& bos) { auto text = system; if (text.empty()) text = "You are a helpful AI assistant.\nKnowledge cutoff: 2026-01-04.\nCurrent date: " + @@ -236,7 +240,19 @@ std::string render_atem(const std::string& prompt, const std::string& system, if (lower.find("reasoning strength") == std::string::npos) text += "\n\nReasoning strength: high."; return bos + "<|start|>system<|message|>" + text + - "\n\n# Valid recipients: \"self\", \"user\".<|eot|>" + "<|start|>user<|message|>" + - prompt + "<|eot|><|start|>assistant"; + "\n\n# Valid recipients: \"self\", \"user\".<|eot|>"; +} +std::string render_atem_generation(bool enable_thinking) { + std::string rendered = "<|start|>assistant"; + if (!enable_thinking) { + // Start decoding in the public channel, not inside a private reasoning turn. + rendered += " to=self<|message|><|eom|><|start|>assistant to=user<|message|>"; + } + return rendered; +} +std::string render_atem(const std::string& prompt, const std::string& system, + const std::string& bos, bool enable_thinking) { + return render_atem_system(system, bos) + "<|start|>user<|message|>" + prompt + "<|eot|>" + + render_atem_generation(enable_thinking); } } // namespace trtmc::muse_glimmer diff --git a/families/muse_glimmer/runtime/tokenizer.h b/families/muse_glimmer/runtime/tokenizer.h index b897cee5e0..cf7e659378 100644 --- a/families/muse_glimmer/runtime/tokenizer.h +++ b/families/muse_glimmer/runtime/tokenizer.h @@ -14,12 +14,14 @@ class Tokenizer { explicit Tokenizer(const std::string& json); ~Tokenizer(); std::vector encode(const std::string& text) const; - std::string decode(const std::vector& ids) const; + std::string decode(const std::vector& ids, bool skip_special = false) const; private: struct Impl; std::unique_ptr impl_; }; +std::string render_atem_system(const std::string& system, const std::string& bos); +std::string render_atem_generation(bool enable_thinking); std::string render_atem(const std::string& prompt, const std::string& system, - const std::string& bos); + const std::string& bos, bool enable_thinking); } // namespace trtmc::muse_glimmer diff --git a/families/muse_glimmer/runtime/vision_geometry.cpp b/families/muse_glimmer/runtime/vision_geometry.cpp new file mode 100644 index 0000000000..deb3100b54 --- /dev/null +++ b/families/muse_glimmer/runtime/vision_geometry.cpp @@ -0,0 +1,103 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/muse_glimmer/runtime/vision_geometry.h" + +#include +#include +#include +#include + +namespace trtmc::muse_glimmer { +std::pair visual_patch_grid(int height, int width, int patch_size, + int max_merged_tokens) { + if (std::min({height, width, patch_size, max_merged_tokens}) < 1) + throw std::invalid_argument("Invalid Muse visual resize geometry"); + const double factor = 2.0 * patch_size; + double h = height / factor, w = width / factor; + if (h * w > max_merged_tokens) { + const double aspect = w / h; + h = std::sqrt(max_merged_tokens / aspect); + w = h * aspect; + } + double error = std::numeric_limits::infinity(); + std::pair best{2, 2}; + for (const double y : {std::floor(h), std::ceil(h)}) { + for (const double x : {std::floor(w), std::ceil(w)}) { + if (y < 1 || x < 1 || y * x > max_merged_tokens) + continue; + const double candidate = std::abs(y / x - static_cast(height) / width); + if (candidate < error) { + if (std::max(y, x) > std::numeric_limits::max() / 2) + throw std::invalid_argument( + "Muse visual grid exceeds the supported integer range"); + error = candidate; + best = {static_cast(y) * 2, static_cast(x) * 2}; + } + } + } + if (!std::isfinite(error)) { + // Match the processor's rounded fallback. Do not collapse an elongated + // image to one cell or silently clamp a provider grid outside this plan. + const double y = std::max(1.0, std::nearbyint(h)), x = std::max(1.0, std::nearbyint(w)); + if (y * x > max_merged_tokens || std::max(y, x) > std::numeric_limits::max() / 2) + throw std::invalid_argument( + "Muse provider resize exceeds the native visual token profile"); + best = {static_cast(y) * 2, static_cast(x) * 2}; + } + return best; +} + +VisionGrid make_vision_grid(int rows, int cols, int table_side, int head_dim, float rope_theta, + int max_patches) { + if (rows < 2 || cols < 2 || rows % 2 || cols % 2 || table_side < 1 || head_dim < 4 || + head_dim % 4 || !(rope_theta > 0) || !std::isfinite(rope_theta) || max_patches < 4 || + rows > max_patches / cols || table_side > std::numeric_limits::max() / table_side) + throw std::invalid_argument("Invalid Muse visual grid or positional geometry"); + const int count = rows * cols; + const auto n = static_cast(count); + VisionGrid grid; + grid.position_indices.reserve(n * 4); + grid.position_weights.reserve(n * 4); + grid.rotary_cos.reserve(n * head_dim); + grid.rotary_sin.reserve(n * head_dim); + grid.merge_order.reserve(n); + grid.window_ids.reserve(n); + const int window_cols = 1 + (cols - 1) / table_side; + std::vector inv_freq(head_dim / 4); + for (int i = 0; i < head_dim / 4; ++i) + inv_freq[i] = 1.0F / std::pow(rope_theta, static_cast(i) / (head_dim / 4)); + for (int row = 0; row < rows; ++row) { + for (int col = 0; col < cols; ++col) { + // Align-corners-false interpolation into the learned table, with zero padding. + const float y = (row + 0.5F) * (static_cast(table_side) / rows) - 0.5F; + const float x = (col + 0.5F) * (static_cast(table_side) / cols) - 0.5F; + const int y0 = static_cast(std::floor(y)), x0 = static_cast(std::floor(x)); + for (int a = 0; a < 2; ++a) + for (int b = 0; b < 2; ++b) { + const int i = y0 + a, j = x0 + b; + grid.position_indices.push_back(std::clamp(i, 0, table_side - 1) * table_side + + std::clamp(j, 0, table_side - 1)); + const float w = (a ? y - y0 : 1.0F - (y - y0)) * (b ? x - x0 : 1.0F - (x - x0)); + grid.position_weights.push_back( + i >= 0 && i < table_side && j >= 0 && j < table_side ? w : 0.0F); + } + for (int d = 0; d < head_dim; ++d) { + const int phase = d % (head_dim / 2); + const float angle = + (phase < head_dim / 4 ? col + 1 : row + 1) * inv_freq[phase % (head_dim / 4)]; + grid.rotary_cos.push_back(std::cos(angle)); + grid.rotary_sin.push_back(std::sin(angle)); + } + grid.window_ids.push_back((row / table_side) * window_cols + col / table_side); + } + } + for (int y = 0; y < rows; y += 2) + for (int x = 0; x < cols; x += 2) + for (int a = 0; a < 2; ++a) + for (int b = 0; b < 2; ++b) + grid.merge_order.push_back((y + a) * cols + x + b); + return grid; +} +} // namespace trtmc::muse_glimmer diff --git a/families/muse_glimmer/runtime/vision_geometry.h b/families/muse_glimmer/runtime/vision_geometry.h new file mode 100644 index 0000000000..28e577e3a2 --- /dev/null +++ b/families/muse_glimmer/runtime/vision_geometry.h @@ -0,0 +1,25 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include +#include +#include + +namespace trtmc::muse_glimmer { +struct VisionGrid { + std::vector position_indices; + std::vector position_weights; + std::vector rotary_cos; + std::vector rotary_sin; + std::vector window_ids; + std::vector merge_order; +}; + +// Return the patch-grid height and width, not the post-merge token grid. +std::pair visual_patch_grid(int height, int width, int patch_size, int max_merged_tokens); +VisionGrid make_vision_grid(int rows, int cols, int table_side, int head_dim, float rope_theta, + int max_patches); +} // namespace trtmc::muse_glimmer diff --git a/families/muse_glimmer/runtime/vision_pixels.cpp b/families/muse_glimmer/runtime/vision_pixels.cpp new file mode 100644 index 0000000000..63265002f8 --- /dev/null +++ b/families/muse_glimmer/runtime/vision_pixels.cpp @@ -0,0 +1,128 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#include "families/muse_glimmer/runtime/vision_pixels.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc::muse_glimmer { +namespace { +std::size_t checked_product(std::size_t a, std::size_t b) { + if (b && a > std::numeric_limits::max() / b) + throw std::invalid_argument("Muse visual buffer dimensions overflow"); + return a * b; +} +float cubic(float x) { + x = std::abs(x); + if (x < 1) + return ((1.5F * x - 2.5F) * x) * x + 1.0F; + if (x < 2) + return ((-0.5F * x + 2.5F) * x - 4.0F) * x + 2.0F; + return 0; +} +using Taps = std::vector>>; +Taps resize_axis(std::size_t input, int output) { + const double step = static_cast(input) / output, radius = std::max(1.0, step); + Taps taps(output); + for (int o = 0; o < output; ++o) { + const double center = (o + 0.5) * step - 0.5; + const auto lo = static_cast(std::ceil(center - 2 * radius)); + const auto hi = static_cast(std::floor(center + 2 * radius)); + float total = 0; + for (auto i = lo; i <= hi; ++i) { + const float weight = cubic(static_cast((i - center) / radius)); + if (weight == 0) + continue; + const auto j = static_cast(std::clamp(i, 0, input - 1)); + taps[o].emplace_back(j, weight); + total += weight; + } + for (auto& tap : taps[o]) + tap.second /= total; + } + return taps; +} +std::vector resize_rgb(const internal::ImageView& image, int height, int width) { + const auto rgb = visual_rgb(image); + const auto x_weights = resize_axis(image.width, width); + const auto y_weights = resize_axis(image.height, height); + const auto stride = checked_product(width, 3); + std::vector horizontal(checked_product(image.height, stride), 0.0F); + for (std::size_t y = 0; y < image.height; ++y) + for (int x = 0; x < width; ++x) + for (auto [i, weight] : x_weights[x]) + for (int c = 0; c < 3; ++c) + horizontal[y * stride + 3 * x + c] += + weight * rgb[(y * image.width + i) * 3 + c]; + std::vector result(checked_product(height, stride), 0.0F); + for (int y = 0; y < height; ++y) + for (auto [i, weight] : y_weights[y]) + for (std::size_t x = 0; x < stride; ++x) + result[y * stride + x] += weight * horizontal[i * stride + x]; + for (auto& pixel : result) { + const float rgb = std::floor(std::clamp(pixel, 0.0F, 255.0F) + 0.5F); + pixel = rgb * (2.0F / 255.0F) - 1.0F; + } + return result; +} +} // namespace +std::vector visual_rgb(const internal::ImageView& image) { + const bool bytes = image.format == internal::ImageFormat::UInt8; + if ((!bytes && image.format != internal::ImageFormat::Float32) || !image.data || !image.width || + !image.height || (image.channels != 1 && image.channels != 3 && image.channels != 4)) + throw std::invalid_argument("Muse expects a nonempty grayscale, RGB, or RGBA image"); + const auto count = checked_product(checked_product(image.width, image.height), image.channels); + if (image.byte_size != checked_product(count, bytes ? 1 : sizeof(float))) + throw std::invalid_argument("Muse image dimensions and byte size disagree"); + const auto* raw = static_cast(image.data); + auto sample = [&](std::size_t pixel, int channel) { + auto i = pixel * image.channels + (image.channels == 1 ? 0 : channel); + if (bytes) + return static_cast(raw[i]); + float v; + std::memcpy(&v, raw + i * sizeof(float), sizeof(float)); + if (!std::isfinite(v) || v < 0 || v > 1) + throw std::invalid_argument("Muse float image expects finite values in [0,1]"); + return std::floor(v * 255.0F + 0.5F); + }; + std::vector output(checked_product(count / image.channels, 3)); + for (std::size_t i = 0; i < output.size(); ++i) + output[i] = static_cast(sample(i / 3, i % 3)); + return output; +} +std::vector visual_patches(const internal::ImageView& first, + const internal::ImageView* second, int rows, int cols, + int patch_size) { + if (rows < 2 || cols < 2 || rows % 2 || cols % 2 || patch_size <= 0 || + std::max(rows, cols) > std::numeric_limits::max() / patch_size) + throw std::invalid_argument("Invalid Muse temporal patch geometry"); + if (second && (second->width != first.width || second->height != first.height)) + throw std::invalid_argument("Muse video frames have inconsistent geometry"); + const int height = rows * patch_size, width = cols * patch_size; + auto first_pixels = resize_rgb(first, height, width); + auto next = second ? resize_rgb(*second, height, width) : std::vector{}; + const auto& second_pixels = second ? next : first_pixels; + std::vector packed; + packed.reserve(checked_product(2, first_pixels.size())); + for (int y = 0; y < rows; ++y) + for (int x = 0; x < cols; ++x) + for (int t = 0; t < 2; ++t) + for (int c = 0; c < 3; ++c) + for (int dy = 0; dy < patch_size; ++dy) + for (int dx = 0; dx < patch_size; ++dx) { + const auto i = (static_cast(y * patch_size + dy) * width + + x * patch_size + dx) * + 3 + + c; + packed.push_back((t ? second_pixels : first_pixels)[i]); + } + return packed; +} +} // namespace trtmc::muse_glimmer diff --git a/families/muse_glimmer/runtime/vision_pixels.h b/families/muse_glimmer/runtime/vision_pixels.h new file mode 100644 index 0000000000..133205e036 --- /dev/null +++ b/families/muse_glimmer/runtime/vision_pixels.h @@ -0,0 +1,20 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include "trtmc/internal/image.h" + +#include + +namespace trtmc::muse_glimmer { +// Convert validated byte or normalized float HWC input to contiguous RGB bytes. +std::vector visual_rgb(const internal::ImageView& image); + +// Raster-order patches, each laid out as two frames x RGB x patch height x patch width. +// A null second frame duplicates the first for a still image or an odd final video group. +std::vector visual_patches(const internal::ImageView& first, + const internal::ImageView* second, int rows, int cols, + int patch_size); +} // namespace trtmc::muse_glimmer diff --git a/families/muse_glimmer/support.py b/families/muse_glimmer/support.py index e40f9f224d..6e582a7d72 100644 --- a/families/muse_glimmer/support.py +++ b/families/muse_glimmer/support.py @@ -3,13 +3,23 @@ """Family-owned model and task support for Muse-Glimmer.""" -from tensorrt_model_connect.model_support import family_support +from tensorrt_model_connect.model_support import FamilySupport, family_support -describe = family_support( +_text = family_support( model_types=("muse_glimmer", "muse_glimmer_text"), architectures=("MuseGlimmerForConditionalGeneration",), tasks=("text_generation",), default_task="text_generation", default_precision="fp16", ) + + +def describe(metadata): + support = _text(metadata) + if (support is not None and metadata.config.get("vision_config") + and not metadata.config.get("quantization_config") + and "processor_config.json" in metadata.files and "hf_quant_config.json" not in metadata.files): + return FamilySupport(("text_generation", "images_text_to_text", "video_text_to_text"), + "text_generation", "fp16") + return support diff --git a/families/muse_glimmer/tests/manifests/muse-glimmer-nvfp4.json b/families/muse_glimmer/tests/manifests/muse-glimmer-nvfp4.json index c0eecc88a2..7ce687bad7 100644 --- a/families/muse_glimmer/tests/manifests/muse-glimmer-nvfp4.json +++ b/families/muse_glimmer/tests/manifests/muse-glimmer-nvfp4.json @@ -21,7 +21,8 @@ "top_p": 1.0, "use_chat_template": true, "enable_thinking": false, - "expected_terms": [["free energy", "gibbs"], ["ice", "crystal"]] + "expected_terms": [["ice", "crystal"]], + "phase_energy_terms": ["free energy", "gibbs"] } ] } diff --git a/families/muse_glimmer/tests/test_e2e.py b/families/muse_glimmer/tests/test_e2e.py index 7a712d30ad..d73deb6028 100644 --- a/families/muse_glimmer/tests/test_e2e.py +++ b/families/muse_glimmer/tests/test_e2e.py @@ -7,10 +7,12 @@ import json import os +import re import subprocess from pathlib import Path import pytest +from tokenizers import Tokenizer from tensorrt_model_connect import BuildRequest, build from tools.e2e_evidence import evidence_stage, record_evidence @@ -123,25 +125,77 @@ def _run_native(binary: Path, runtime_root: Path, bundle: Path, case: dict) -> d ] completed = subprocess.run(command, check=True, capture_output=True, text=True, timeout=900) record_evidence("commands", {"argv": command}) - record_evidence("native", {"stdout": completed.stdout, "stderr": completed.stderr}) + record_evidence( + "native", + { + "enable_thinking": case["enable_thinking"], + "stdout": completed.stdout, + "stderr": completed.stderr, + }, + ) return json.loads(completed.stdout) -def _assert_correctness(payload: dict, case: dict) -> None: - token_ids = payload["token_ids"] - assert isinstance(token_ids, list) and token_ids - assert all(isinstance(token_id, int) for token_id in token_ids) - assert len(token_ids) <= case["max_new_tokens"] - _assert_answer(str(payload["text"]), case) - - -def _assert_answer(output: str, case: dict) -> None: - marker = "assistant to=user" - assert marker in output, "Muse ATEM output never reached its public user channel" - answer = output.rsplit(marker, 1)[1].casefold() - assert answer.strip() +def _equal_phase_potentials(answer: str) -> bool: + """Recognize an explicit equality between the liquid and solid phases of pure water.""" + liquid = r"(?:the )?liquid(?: water| phase)?" + solid = r"(?:the )?(?:ice|solid(?: water| phase)?)" + pair = rf"(?:{liquid} and {solid}|{solid} and {liquid})" + same = r"(?:equal|identical|the same)" + for clause in re.split(r"[.;!?\n]", answer): + if re.search(r"\b(?:not|never|false)\b|n['’]t\b", clause): + continue + for first, second in ((liquid, solid), (solid, liquid)): + if re.search( + rf"\bchemical potential of {first} (?:equals|is equal to) " + rf"(?:that of|the chemical potential of) {second}\b", + clause, + ): + return True + if re.search( + rf"\b{pair} (?:have|share) {same} chemical potentials?\b", clause + ) or re.search(rf"\bchemical potentials? (?:of|in) {pair} (?:are|is) {same}\b", clause): + return True + return False + + +def _assert_correctness(payload: dict, case: dict, tokenizer: Tokenizer) -> None: + ids = payload["token_ids"] + assert isinstance(ids, list) and ids + assert all(type(token_id) is int for token_id in ids) + assert len(ids) <= case["max_new_tokens"], "generation exceeded the token budget" + assert payload["text"] == tokenizer.decode(ids, skip_special_tokens=True), "incorrect display" + + # ATEM inserts the public turn in the prompt when thinking is disabled. + # When enabled, only a generated, token-delimited public turn ends reasoning. + start, message, eom = ( + tokenizer.token_to_id(s) for s in ("<|start|>", "<|message|>", "<|eom|>") + ) + assert None not in (start, message, eom), "missing checkpoint ATEM delimiter" + public = ids + if case["enable_thinking"]: + starts = [i for i in range(1, len(ids)) if ids[i - 1 : i + 1] == [eom, start]] + assert starts, "no generated public turn" + begin = starts[-1] + 1 + assert message in ids[begin:], "missing message delimiter" + end = ids.index(message, begin) + role = tokenizer.decode(ids[begin:end], skip_special_tokens=False) + assert role == "assistant to=user", "last turn was not addressed to the user" + public = ids[end + 1 :] + + assert public and not set(public).intersection((start, message, eom)), ( + "unexpected turn in public answer" + ) + answer = tokenizer.decode(public, skip_special_tokens=True).strip().casefold() + assert answer and not answer.startswith(("to=self", "assistant to=")), ( + "not a direct public answer" + ) for alternatives in case["expected_terms"]: assert any(term.casefold() in answer for term in alternatives), (alternatives, answer) + if energy_terms := case.get("phase_energy_terms"): + assert any(term.casefold() in answer for term in energy_terms) or _equal_phase_potentials( + answer + ), (energy_terms, answer) @pytest.mark.parametrize("case_name", sorted(_CASES)) @@ -172,7 +226,12 @@ def test_e2e(case_name: str, request, tmp_path: Path) -> None: inspection = json.loads(inspected.stdout) assert inspection["family"] == _FAMILY assert inspection["task"] == manifest["task"] - with evidence_stage("native"): - payload = _run_native(binary, runtime_root, bundle, case) - with evidence_stage("compare"): - _assert_correctness(payload, case) + tokenizer = Tokenizer.from_file(str(model_dir / "tokenizer.json")) + default = case["enable_thinking"] + for thinking in (default, not default): + request_case = {**case, "enable_thinking": thinking} + mode = "thinking" if thinking else "direct" + with evidence_stage(f"native-{mode}"): + payload = _run_native(binary, runtime_root, bundle, request_case) + with evidence_stage(f"compare-{mode}"): + _assert_correctness(payload, request_case, tokenizer) diff --git a/families/muse_glimmer/tests/test_public_answer.py b/families/muse_glimmer/tests/test_public_answer.py new file mode 100644 index 0000000000..3521a79bc5 --- /dev/null +++ b/families/muse_glimmer/tests/test_public_answer.py @@ -0,0 +1,62 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +import pytest +from tokenizers import Tokenizer +from tokenizers.models import WordLevel + +from .test_e2e import _assert_correctness + + +@pytest.fixture +def tokenizer(): + words = [ + "<|start|>", + "<|message|>", + "<|eom|>", + "assistant", + "to=user", + "to=self", + "ice", + "Gibbs", + "The chemical potentials of liquid water and ice are equal.", + "Liquid water and ice have unequal chemical potentials.", + "The chemical potential of ice equals that of liquid water.", + "Ice and liquid water do not have equal chemical potentials.", + "Ice melts; liquid water and vapor have equal chemical potentials.", + ] + tokenizer = Tokenizer(WordLevel(dict(zip(words, range(len(words)))))) + tokenizer.add_special_tokens(words[:3]) + return tokenizer + + +@pytest.mark.parametrize( + ("thinking", "ids", "error"), + [ + (False, [6, 7], None), + (False, [8], None), + (False, [9], "gibbs"), + (True, [2, 0, 3, 4, 1, 10], None), + (False, [11], "gibbs"), + (False, [12], "gibbs"), + (True, [5, 1, 2, 0, 3, 4, 1, 6, 7], None), + (False, [5, 1, 6, 7], "unexpected turn"), + (True, [3, 4, 6, 7], "no generated public turn"), + (True, [5, 1, 6, 7, 2, 0, 3, 4, 1, 7], "ice"), + (True, [2, 0, 3, 5, 1, 6, 7], "not addressed to the user"), + (False, [6, 7] * 8, "token budget"), + ], +) +def test_public_answer(tokenizer, thinking, ids, error): + payload = {"token_ids": ids, "text": tokenizer.decode(ids)} + case = { + "max_new_tokens": 12, + "enable_thinking": thinking, + "expected_terms": [["ice"]], + "phase_energy_terms": ["gibbs"], + } + if error is None: + _assert_correctness(payload, case, tokenizer) + else: + with pytest.raises(AssertionError, match=error): + _assert_correctness(payload, case, tokenizer) diff --git a/families/muse_glimmer/tests/test_support.py b/families/muse_glimmer/tests/test_support.py index 9631829ea5..ad9721fdec 100644 --- a/families/muse_glimmer/tests/test_support.py +++ b/families/muse_glimmer/tests/test_support.py @@ -76,6 +76,7 @@ def request_and_route(tmp_path, monkeypatch): monkeypatch.setattr(dispatch.sys, "platform", "linux") monkeypatch.setattr(builder, "package_present", lambda: True) monkeypatch.setattr(builder, "local_target", lambda: target) + monkeypatch.setattr(builder, "installed_package", lambda _: {"version": "0.11.0"}) return request, target @@ -83,6 +84,24 @@ def test_documented_mixed_checkpoint_is_candidate(request_and_route): request, _ = request_and_route assert dispatch.candidate(request, raw_config()) assert builder.request_weight_format(request, raw_config()) == "nvfp4" + # Same text topology, but original floating weights must not be relabeled + # as NVFP4 or require the prepared checkpoint's quantization sidecar. + source = request.model_dir + (source / "hf_quant_config.json").unlink() + original = raw_config() + original.pop("quantization_config") + original["dtype"] = "bfloat16" + weights = {"model.language_model.embed_tokens.weight": "first.safetensors", + "lm_head.weight": "last.safetensors"} + index = source / "model.safetensors.index.json" + index.write_text(json.dumps({"weight_map": weights})) + assert builder.request_weight_format(replace(request,quantization=None), original) == "floating" + with pytest.raises(ValueError, match="does not match"): + builder.request_weight_format(request, original) + index.write_text(json.dumps({"weight_map": {**weights,"lm_head.weight_scale_inv":"last.safetensors"}})) + with pytest.raises(ValueError, match="undeclared packed"): + builder.request_weight_format(replace(request,quantization=None), original) + @pytest.mark.parametrize( @@ -111,7 +130,7 @@ def test_edge_failure_retries_unchanged_native_once(request_and_route, monkeypat def failed(*args): raise RuntimeError("upstream builder error") - monkeypatch.setitem(dispatch.EDGE_DISPATCH, ("linux", "x86_64", 120, "nvfp4"), failed) + monkeypatch.setattr(builder, "prepare", failed) dispatch.build(request, writer, lambda r, w: calls.append((r, w))) assert calls == [(request, writer)] assert "Retrying native once" in caplog.text @@ -119,9 +138,7 @@ def failed(*args): def test_publication_failure_does_not_retry_native(request_and_route, monkeypatch): request, _ = request_and_route - monkeypatch.setitem( - dispatch.EDGE_DISPATCH, ("linux", "x86_64", 120, "nvfp4"), lambda *args: ({}, {}) - ) + monkeypatch.setattr(builder, "prepare", lambda *args: ({}, {})) monkeypatch.setattr(builder, "publish", lambda *args: (_ for _ in ()).throw(OSError("publish"))) with pytest.raises(OSError, match="publish"): dispatch.build(request, object(), lambda *args: pytest.fail("must not retry")) @@ -135,7 +152,7 @@ def probe(command, **kwargs): return SimpleNamespace(stdout=json.dumps(["0.11.0", "11.1.0.106"])) monkeypatch.setattr(builder.subprocess, "run", probe) - package = {"python": "/sdk/python"} + package = {"python": "/sdk/python", "version": "0.11.0"} assert ( builder.exporter_python(package, {"tensorrt_version": "11.1.0.106"}) == builder.sys.executable @@ -144,8 +161,9 @@ def probe(command, **kwargs): assert builder.exporter_python(package, {"tensorrt_version": "11.0.0.0"}) == package["python"] +@pytest.mark.parametrize("release", ["0.11.0", "0.12.0"]) def test_prepare_maps_to_wheel_exporter_and_native_onnx_builder( - request_and_route, tmp_path, monkeypatch + request_and_route, tmp_path, monkeypatch, release ): request, target = request_and_route prefix = tmp_path / "prefix" @@ -158,14 +176,16 @@ def test_prepare_maps_to_wheel_exporter_and_native_onnx_builder( path.parent.mkdir(parents=True, exist_ok=True) path.write_text("x") package = {name: str(path) for name, path in paths.items()} + package.update(version=release, release_revision=builder.RELEASE_012) + module = "tensorrt_edgellm.onnx.cli" if release == "0.12.0" else "tensorrt_edgellm.scripts.export" monkeypatch.setattr(builder, "installed_package", lambda target: package) - monkeypatch.setattr(builder, "exporter_python", lambda package, target: package["python"]) + monkeypatch.setattr(builder, "exporter_python", lambda package, target, requested: package["python"]) seen = [] def run(command, **kwargs): seen.append((command, kwargs.get("env"))) - if "tensorrt_edgellm.scripts.export" in command: - out = Path(command[command.index("tensorrt_edgellm.scripts.export") + 2]) / "llm" + if module in command: + out = Path(command[command.index(module) + 2]) / "llm" out.mkdir(parents=True) else: out = Path(next(x.split("=", 1)[1] for x in command if x.startswith("--engineDir="))) @@ -186,9 +206,11 @@ def run(command, **kwargs): staging.mkdir() log = tmp_path / "build.log" files, marker = builder.prepare(request, raw_config(), target, staging, log) - assert seen[0][0][2:4] == ["-m", "tensorrt_edgellm.scripts.export"] + assert seen[0][0][2:4] == ["-m", module] assert seen[1][0][0] == package["onnx_builder"] assert seen[1][1]["EDGELLM_PLUGIN_PATH"] == package["plugin"] + if release == "0.12.0": + assert marker["edge_release"] == release and marker["builder_flow"] == "onnx" assert marker["weight_format"] == "nvfp4" assert "edge_llm/engine/llm.engine" in files @@ -208,6 +230,8 @@ def run(command, **kwargs): draft.mkdir() policy = {"block_size": 16, "mask_token_id": 201818, "target_layer_ids": [1, 13, 25, 37, 49]} + if version == 2: + policy.update(selector_top_k=16, selector_rank=256) draft_config = {"architectures": [architecture], "num_hidden_layers": 5, "hidden_size": 6656, "intermediate_size": 19968, "num_attention_heads": 32, "num_key_value_heads": 8, @@ -222,8 +246,8 @@ def run(command, **kwargs): def run_pair(command, **kwargs): paired_commands.append(command) - if "tensorrt_edgellm.scripts.export" in command: - output = Path(command[command.index("tensorrt_edgellm.scripts.export") + 2]) + if module in command: + output = Path(command[command.index(module) + 2]) output.mkdir() assert command[-2:] == ["--dflash-draft-dir", str(draft)] else: @@ -257,6 +281,23 @@ def run_pair(command, **kwargs): assert "edge_llm/engine/spec_base.engine" in pair_files assert "edge_llm/engine/spec_draft.engine" in pair_files assert "edge_llm/engine/llm.engine" not in pair_files + tree_request = replace(paired_request, execution_variant="dflash_tree") + paired_commands.clear() + tree_destination = tmp_path / f"tree-{version}" + tree_destination.mkdir() + if release != "0.12.0" or version != 2: + reason = "0.12.0 Edge SDK" if release != "0.12.0" else "V2 selector" + with pytest.raises(ValueError, match=reason): + builder.prepare(tree_request, raw_config(), target, tree_destination, log) + assert not paired_commands + else: + _, tree_marker = builder.prepare(tree_request, raw_config(), target, tree_destination, log) + assert tree_marker["execution_variant"] == "dflash_tree" + assert (tree_marker["dflash_top_k"], tree_marker["dflash_verify"]) == (4, 32) + assert len(paired_commands) == 4 + base, draft_build = paired_commands[1], paired_commands[3] + assert base[base.index("--maxSpecVerifyTokens") + 1] == "32" + assert draft_build[draft_build.index("--maxSpecDraftTokens") + 1] == "16" if version == 2: assert "edge_llm/engine/dflash2_selector.safetensors" in pair_files include_selector = False @@ -295,7 +336,11 @@ def test_native_bundle_header_has_one_owner(request_and_route, monkeypatch): for name in ("tokenizer.json", "tokenizer_config.json", "chat_template.jinja"): (request.model_dir / name).write_text("fixture") monkeypatch.setattr(builder, "package_present", lambda: False) - monkeypatch.setattr(native_model, "Checkpoint", lambda path: nullcontext(object())) + def reader(path, *, source_format): + assert path == request.model_dir and source_format == "nvfp4" + return nullcontext(object()) + + monkeypatch.setattr(native_model, "Checkpoint", reader) calls = [] def engine(config, weights, capacity, **kwargs): @@ -327,7 +372,8 @@ def unique_keys(pairs): @pytest.mark.parametrize("prefix", ["", "model.", "language_model.", "model.language_model."]) @pytest.mark.parametrize("gate", ["gate_proj", "output_gate_proj"]) -def test_native_checkpoint_uses_canonical_tensor_names(tmp_path, prefix, gate): +@pytest.mark.parametrize("source_format", ["nvfp4", "floating"]) +def test_native_checkpoint_uses_canonical_tensor_names(tmp_path, prefix, gate, source_format): torch = pytest.importorskip("torch") from safetensors.torch import save_file from families.muse_glimmer.checkpoint import Checkpoint @@ -335,11 +381,12 @@ def test_native_checkpoint_uses_canonical_tensor_names(tmp_path, prefix, gate): name = f"{prefix}layers.0.self_attn.{gate}.weight" value = torch.arange(4, dtype=torch.float32).reshape(2, 2) save_file({name: value}, tmp_path / "weights.safetensors") - (tmp_path / "hf_quant_config.json").write_text(json.dumps(quant_config())) + if source_format == "nvfp4": + (tmp_path / "hf_quant_config.json").write_text(json.dumps(quant_config())) weight_map = {name: "weights.safetensors"} index = tmp_path / "model.safetensors.index.json" index.write_text(json.dumps({"weight_map": weight_map})) - with Checkpoint(tmp_path) as checkpoint: + with Checkpoint(tmp_path, source_format=source_format) as checkpoint: for requested in ("layers.0.self_attn.gate_proj.weight", name): assert torch.equal(checkpoint.tensor(requested), value) projection = checkpoint.projection(f"{prefix}layers.0.self_attn.{gate}", 2, 2) @@ -349,4 +396,32 @@ def test_native_checkpoint_uses_canonical_tensor_names(tmp_path, prefix, gate): weight_map[duplicate] = "weights.safetensors" index.write_text(json.dumps({"weight_map": weight_map})) with pytest.raises(ValueError, match="Duplicate canonical Muse tensor"): - Checkpoint(tmp_path) + Checkpoint(tmp_path, source_format=source_format) + +def test_sdk_is_paired_with_active_runner(tmp_path, monkeypatch): + from types import SimpleNamespace + from families.muse_glimmer.edge_llm import builder + + native = tmp_path / "wheel" + runner = native / "bin/trtmc" + runner.parent.mkdir(parents=True) + runner.touch() + standalone = tmp_path / "source" + relative = "share/trtmc/edge-llm.json" + outside = standalone / relative + outside.parent.mkdir(parents=True) + outside.write_text("{}") + monkeypatch.setattr(builder, "cmake_prefixes", lambda: [standalone]) + monkeypatch.setattr(builder, "distribution", lambda _: SimpleNamespace(locate_file=lambda _: native)) + assert not builder.package_present() + assert builder._sdk_prefixes() == [native] + + inside = native / relative + inside.parent.mkdir(parents=True) + inside.symlink_to(native / "missing") + assert builder.package_present() and builder._sdk_prefixes() == [native] + inside.unlink() + inside.write_text("{}") + assert builder.package_present() and builder._sdk_prefixes() == [native] + runner.unlink() + assert builder.package_present() and builder._sdk_prefixes() == [standalone] diff --git a/families/muse_glimmer/vision.py b/families/muse_glimmer/vision.py new file mode 100644 index 0000000000..30004f1995 --- /dev/null +++ b/families/muse_glimmer/vision.py @@ -0,0 +1,47 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Muse-owned media source and dynamic profile contract.""" +import json +from pathlib import Path + +MEDIA_TASKS = ("images_text_to_text", "video_text_to_text") + + +def media_contract(request, raw, weight_format, capacity): + if request.task not in MEDIA_TASKS: + return None + if weight_format != "floating": + raise ValueError("Muse-Glimmer image/video requires the original floating checkpoint") + path = Path(request.model_dir) + processor = json.loads((path / "processor_config.json").read_text(encoding="utf-8")) + image = processor["image_processor"] + video = processor["video_processor"] + v = raw["vision_config"] + if (capacity < 16 or v["patch_size"] != 14 or v["patch_temporal"] != 2 or v["merge_size"] != 2 + or v["pos_emb_height"] != v["pos_emb_width"] or v["num_hidden_layers"] != 50 + or v["hidden_size"] != 1536 or v["num_attention_heads"] != 16 + or raw["text_config"]["hidden_size"] != 6656): + raise ValueError("Unsupported Muse-Glimmer visual geometry or capacity") + for entry in (image, video): + if (entry["image_mean"] != [0.5] * 3 or entry["image_std"] != [0.5] * 3 + or entry["patch_size"] != 14 or entry["merge_size"] != 2 + or entry["temporal_patch_size"] != 2): + raise ValueError("Unsupported Muse-Glimmer pixel processing configuration") + weights = json.loads((path / "model.safetensors.index.json").read_text(encoding="utf-8"))["weight_map"] + required = {"model.vision_adapter.fc1.weight", "model.vision_adapter.fc2.weight", + "model.vision_projection.weight", "model.vision_tower.patch_embedder.patch_embedding.weight"} + required.update(f"model.vision_tower.layers.{i}.attn.q_proj.weight" for i in range(v["num_hidden_layers"])) + if not required.issubset(weights): + raise ValueError("Muse-Glimmer checkpoint does not contain its visual encoder") + # Save half of the sequence budget for the rest of the prompt and answer. + per_image = min(int(image["max_image_tokens"]), capacity // 2) + frame_limit = min(int(video["max_video_frame_tokens"]), per_image) + fps = float(video["fps"]) + if min(per_image, frame_limit) < 4 or not 0 < fps < float("inf"): + raise ValueError("Invalid Muse-Glimmer visual profile or frame rate") + return {"patch_size": 14, "table_side": v["pos_emb_height"], "head_dim": v["hidden_size"] // v["num_attention_heads"], + "text_width": raw["text_config"]["hidden_size"], "max_patches": 4 * per_image, + "max_image_tokens": per_image, "max_video_frame_tokens": frame_limit, + "image_token_id": raw["image_token_id"], "video_token_id": raw["video_token_id"], + "rope_theta": v["rope_parameters"]["rope_theta"], "fps": fps} diff --git a/families/muse_glimmer/visual_graph.py b/families/muse_glimmer/visual_graph.py new file mode 100644 index 0000000000..0ca001c5af --- /dev/null +++ b/families/muse_glimmer/visual_graph.py @@ -0,0 +1,153 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Original Muse-Glimmer visual encoder, one temporal patch group at a time.""" +from __future__ import annotations + +import os + +import numpy as np +import tensorrt as trt + +from .native_graph import Graph +from .quantization import weight_tensor + + +class VisionGraph(Graph): + """Keep patches in raster order. Spatial window membership masks local attention.""" + + def affine_norm(self, x, name, eps): + width = int(x.shape[-1]) + value = self.cast(x, trt.float32) + mean = self.network.add_reduce(value, trt.ReduceOperation.AVG, 2, True).get_output(0) + centered = self.ew(value, mean, trt.ElementWiseOperation.SUB) + normalized = self.norm(centered, eps) + scale = self.const(self.checkpoint.vector(name + ".weight", width)[None, :]) + bias = self.const(self.checkpoint.vector(name + ".bias", width)[None, :]) + return self.cast(self.ew(self.ew(normalized, scale, trt.ElementWiseOperation.PROD), bias, + trt.ElementWiseOperation.SUM), x.dtype) + + def fc(self, x, name, width, *, bias=True): + x = self.project(x, name, width) + if bias: + b = self.const(self.checkpoint.vector(name + ".bias", width)[None, :]) + x = self.ew(x, self.cast(b, x.dtype), trt.ElementWiseOperation.SUM) + return x + + def gelu(self, x): + return self.network.add_activation(x, trt.ActivationType.GELU_ERF).get_output(0) + + def attend(self, x, prefix, heads, cos, sin, mask, scale): + width = int(x.shape[1]) + dim = width // heads + q, k, v = [self.reshape(self.fc(x, prefix + "." + p + "_proj", width), (-1, heads, dim)) + for p in ("q", "k", "v")] + swapped = self.const(np.r_[dim // 2:dim, :dim // 2], np.int32) + sign = self.const(np.repeat([-1, 1], dim // 2).reshape(1, 1, dim)) + def rotate(values): + raw = self.cast(values, trt.float32) + half = self.network.add_gather(raw, swapped, 2).get_output(0) + y = self.ew(self.ew(raw, cos, trt.ElementWiseOperation.PROD), + self.ew(self.ew(half, sign, trt.ElementWiseOperation.PROD), sin, + trt.ElementWiseOperation.PROD), trt.ElementWiseOperation.SUM) + return self.cast(y, trt.float16) + def head_first(values): + layer = self.network.add_shuffle(values) + layer.first_transpose = (1, 0, 2) + return layer.get_output(0) + # FP32 logits/softmax, FP16 projection boundary, no plugin or platform-specific kernel. + q = self.cast(head_first(rotate(q)), trt.float32) + k = self.cast(head_first(rotate(k)), trt.float32) + scores = self.network.add_matrix_multiply(q, trt.MatrixOperation.NONE, k, + trt.MatrixOperation.TRANSPOSE).get_output(0) + scores = self.scale(scores, scale) + if mask is not None: + scores = self.ew(scores, mask, trt.ElementWiseOperation.SUM) + probs = self.network.add_softmax(scores) + probs.axes = 4 + context = self.network.add_matrix_multiply( + probs.get_output(0), trt.MatrixOperation.NONE, self.cast(head_first(v), trt.float32), + trt.MatrixOperation.NONE).get_output(0) + context = self.reshape(self.cast(context, trt.float16), (-1, width), first_transpose=(1, 0, 2)) + return self.fc(context, prefix + ".proj", width) + + def populate_visual(self): + v = self.config["vision_config"] + c = self.config["text_config"] + width, heads, merge = v["hidden_size"], v["num_attention_heads"], v["merge_size"] + if (width % heads or (width // heads) % 4 or merge != 2 or v["hidden_act"] != "gelu" + or self.config["projector_hidden_act"] != "gelu" + or len(v["layer_types"]) != v["num_hidden_layers"]): + raise ValueError("Invalid Muse visual geometry or activation") + dim, lanes = width // heads, merge**2 + features = v["patch_size"]**2 * v["patch_temporal"] * v.get("num_channels", 3) + inputs = { + "patches": (trt.float16, (-1, features)), "position_indices": (trt.int32, (-1, 4)), + "position_weights": (trt.float16, (-1, 4)), "rotary_cos": (trt.float32, (-1, 1, dim)), + "rotary_sin": (trt.float32, (-1, 1, dim)), "window_ids": (trt.int32, (-1,)), + "merge_order": (trt.int32, (-1,)), + } + rows = {k: self.network.add_input(k, *v) for k, v in inputs.items()} + # Send one window ID per patch. Construct the additive mask on-device; + # global-attention layers still receive no mask. + ids = rows["window_ids"] + same_window = self.ew(self.reshape(ids, (1, -1, 1)), self.reshape(ids, (1, 1, -1)), + trt.ElementWiseOperation.EQUAL) + window_mask = self.network.add_select( + same_window, self.const([[[0.0]]]), self.const([[[-np.inf]]]) + ).get_output(0) + tower = "vision_tower" + patch = tower + ".patch_embedder" + x = self.fc(rows["patches"], patch + ".patch_embedding", width, bias=False) + table = self.checkpoint.projection(patch + ".position_embedding_table", + v["pos_emb_height"] * v["pos_emb_width"], width) + table = weight_tensor(self.network, table, self.keep_alive, trt.float16) + pos = self.network.add_gather(table, rows["position_indices"], 0).get_output(0) + weighted = self.ew(pos, self.reshape(rows["position_weights"], (-1, 4, 1)), + trt.ElementWiseOperation.PROD) + pos = self.network.add_reduce(weighted, trt.ReduceOperation.SUM, 2, False).get_output(0) + x = self.affine_norm(self.ew(x, pos, trt.ElementWiseOperation.SUM), tower + ".ln_pre", v["layer_norm_eps"]) + for i, kind in enumerate(v["layer_types"]): + if kind not in {"window_attention", "full_attention"}: + raise ValueError(f"Unknown Muse visual attention type: {kind}") + prefix = f"{tower}.layers.{i}" + y = self.affine_norm(x, prefix + ".norm1", v["layer_norm_eps"]) + y = self.attend(y, prefix + ".attn", heads, rows["rotary_cos"], rows["rotary_sin"], + window_mask if kind == "window_attention" else None, dim**-0.5) + x = self.ew(x, y, trt.ElementWiseOperation.SUM) + y = self.affine_norm(x, prefix + ".norm2", v["layer_norm_eps"]) + y = self.gelu(self.fc(y, prefix + ".mlp.fc1", v["intermediate_size"])) + x = self.ew(x, self.fc(y, prefix + ".mlp.fc2", width), trt.ElementWiseOperation.SUM) + x = self.affine_norm(x, tower + ".ln_post", v["layer_norm_eps"]) + x = self.network.add_gather(x, rows["merge_order"], 0).get_output(0) + x = self.reshape(x, (-1, lanes, width), transpose=(0, 2, 1)) + x = self.reshape(x, (-1, width * lanes)) + for name in ("vision_adapter.fc1", "vision_adapter.fc2"): + x = self.gelu(self.fc(x, name, self.config["projector_hidden_size"], bias=False)) + x = self.fc(x, "vision_projection", c["hidden_size"], bias=False) + x = self.norm(x, c["rms_norm_eps"]) + x.name = "visual_embeddings" + self.network.mark_output(x) + return inputs + + +def build_visual(raw, checkpoint, max_patches, *, verbose=False): + """Build one dynamic per-group encoder; a group's patch grid has even sides.""" + if type(max_patches) is not int or max_patches < 4 or max_patches % 4: + raise ValueError("Muse visual profiles require a positive number of complete 2x2 blocks") + builder = trt.Builder(trt.Logger(trt.Logger.VERBOSE if verbose else trt.Logger.WARNING)) + builder.max_threads = min(8, os.cpu_count() or 1) + network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED)) + graph = VisionGraph(network, checkpoint, raw, max_patches) + inputs = graph.populate_visual() + profile = builder.create_optimization_profile() + for name, (_, axes) in inputs.items(): + profile.set_shape(name, *(tuple(n if a < 0 else a for a in axes) + for n in (4, min(256, max_patches), max_patches))) + settings = builder.create_builder_config() + settings.builder_optimization_level = 1 + settings.add_optimization_profile(profile) + result = builder.build_serialized_network(network, settings) + if result is None: + raise RuntimeError("TensorRT failed to build the Muse visual encoder") + return bytes(result) diff --git a/families/muse_glimmer/weight_format.py b/families/muse_glimmer/weight_format.py new file mode 100644 index 0000000000..894d113eee --- /dev/null +++ b/families/muse_glimmer/weight_format.py @@ -0,0 +1,48 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Family-owned source format admission for native TensorRT and optional Edge builds.""" +from __future__ import annotations + +import json +from pathlib import Path + + +def checkpoint_weight_format(model_dir: Path, raw: dict) -> str: + """Identify the documented floating original or mixed NVFP4/MXFP8 recipe.""" + config = raw.get("quantization_config") + descriptor = model_dir / "hf_quant_config.json" + if config is None and not descriptor.exists(): + if raw.get("model_type") != "muse_glimmer" or raw.get("dtype") not in { + "float16", "bfloat16", "float32" + }: + raise ValueError("Muse floating checkpoint requires an explicit floating source dtype") + index = json.loads((model_dir / "model.safetensors.index.json").read_text(encoding="utf-8")) + keys = index["weight_map"] + if (not isinstance(keys, dict) + or not {"model.language_model.embed_tokens.weight", "lm_head.weight"} <= keys.keys() + or any("weight_scale" in k or k.endswith(".input_scale") for k in keys)): + raise ValueError("Muse floating checkpoint has missing or undeclared packed weights") + return "floating" + if ( + not isinstance(config, dict) + or config.get("quant_algo") != "MIXED_PRECISION" + or not descriptor.is_file() + ): + raise ValueError("Muse-Glimmer requires an explicit floating or documented mixed NVFP4 source") + document = json.loads(descriptor.read_text(encoding="utf-8")) + layers = document.get("quantization", {}).get("quantized_layers", {}) + algorithms = {value.get("quant_algo") for value in layers.values() if isinstance(value, dict)} + if not {"NVFP4", "MXFP8"} <= algorithms: + raise ValueError("Muse-Glimmer quantization descriptor must contain NVFP4 and MXFP8 layers") + return "nvfp4" + + +def request_weight_format(request, raw: dict) -> str: + source = checkpoint_weight_format(Path(request.model_dir), raw) + requested = source if request.quantization in {None, "none"} else request.quantization.lower() + if requested != source: + raise ValueError( + f"Muse-Glimmer source format {source} does not match requested {requested}" + ) + return source diff --git a/website/docs/models-recipes/muse-glimmer-edge-llm.md b/website/docs/models-recipes/muse-glimmer-edge-llm.md index b6c0e418c3..6107b5c653 100644 --- a/website/docs/models-recipes/muse-glimmer-edge-llm.md +++ b/website/docs/models-recipes/muse-glimmer-edge-llm.md @@ -4,32 +4,54 @@ title: Muse-Glimmer with Edge-LLM # Muse-Glimmer with Edge-LLM -The `muse_glimmer` family owns the optional Edge 0.11 text route for -`RadixArk/Muse-Glimmer-NVFP4`. Its original mixed NVFP4/MXFP8 weights are -preserved. Selection, ONNX commands, paired execution, and validation remain -inside the family. - -Use a native SM120 Edge SDK with ONNX tools and complete kernels. A compatible -Python wheel can provide the exporter; the native SDK remains required. -Build on the target device, not by cross-compiling. The family also owns a -native TensorRT Python graph and Model Connect C++ runtime fallback; it does not -inherit the Edge SM allowlist or replace the checkpoint's quantization recipe. -All three admitted native text modes have full-checkpoint build/inference -results, separate from Edge qualification. The existing scientific-answer test -passes for ordinary execution and DFlash V2; V1 remains runnable with a recorded -accuracy issue that also occurs with its identical target engine without the -draft. These are scoped results, not catalog-wide or cross-platform accuracy -claims. - -The owning `trtmc muse_glimmer build` command accepts -`--execution-variant autoregressive` or `--execution-variant dflash`. -The latter requires `--companion` pointing to the matched official assistant -or DFlash2 checkpoint. The draft architecture selects the version, using the -same public block size 16 workflow. No shared CLI extension is required. - -The text-only NVFP4 route does not establish FP16 image/video support. -The original FP16 checkpoint and FP16 pairs remain blocked by available -single-device capacity. The existing final-answer quality checks are unchanged. +The `muse_glimmer` family owns Edge selection, ONNX commands, paired execution +and native TensorRT fallback. Build on the target device. Both paths preserve +the prepared checkpoint's NVFP4/MXFP8 recipe and the requested draft. + +Edge 0.11 is the default and its text offload requires a compatible SM120 SDK. +For 0.12, enable Edge and select `-DTRTMC_EDGELLM_RELEASE=0.12.0`. Also set +`-DTRTMC_EDGELLM_ONNX=ON -DTRTMC_EDGELLM_ALL_KERNELS=ON`: ONNX tools alone +do not satisfy Muse's kernel requirement. Provision the SDK from pinned Edge +source on the target GPU. A packaged runner uses its own SDK; for a standalone +runner, set `CMAKE_PREFIX_PATH` to the corresponding Model Connect SDK installation. +The family option `--edge-builder-python /absolute/path/to/python` +selects a matching wheel or source-installed exporter; it does not replace the +C++ SDK. The 0.12 path uses the installed SDK's GPU architectures. + +For ordinary generation, leave `--execution-variant` at its default. +For a block-16 chain, use `--execution-variant dflash --companion /models/matched-draft`. +For a greedy DFlash2 tree, use `--execution-variant dflash_tree` with the matched +`incoai/Muse-Glimmer-30B-DFlash2` companion. The tree has up to four children +per node and 32 verification nodes including the anchor. Model Connect does +not substitute the chain or ordinary decoding for an explicit tree request. + +All six documented 0.12 combinations built and ran through both Edge and native +TensorRT: the original FP16 and prepared NVFP4 checkpoints, each in ordinary, +DFlash V1 and DFlash V2 chain modes. **They are not all accuracy-qualified.** + +- **Original FP16:** Both routes distinguished opposed image colors and both + video orders in all three modes. On both routes, each draft matched its own + target-only engine on all six greedy text and media requests. The + scientific check scores direct answers when thinking is disabled, because + the template has already opened the public channel. + The DFlash2 tree passed all four media checks and the thinking-enabled + science check on both routes. Native matched target-only IDs on all six + requests; Edge matched on five, with a comma instead of a newline between + the two correct video colors. The earlier test expected a generated + header even with thinking disabled; neither tree route generated one. +- **Prepared NVFP4:** Text only. Both native pairs matched their respective + targets; both released Edge pairs showed a same-engine greedy discrepancy. + The DFlash2 tree also ran on both backends. Its native output matched its own + target with thinking off and on; the Edge tree differed from target-only + execution. The earlier test counted the absent header as a failure with thinking + disabled. Separately, the Edge route missed a required term with thinking + enabled. + A result on this checkpoint does not qualify media execution. + +For native image and video requests, the processor's resized patch grid must +fit the bundle's visual profile. If the processor's rounded fallback exceeds +that profile, native execution reports the limit instead of silently reducing +the image to a single token. See the [family-owned recipe](https://github.com/NVIDIA/TensorRT-Model-Connect/blob/main/families/muse_glimmer/edge_llm/README.md) for commands, dependency requirements, precision/profile boundaries and