diff --git a/ASSET_LICENSES.md b/ASSET_LICENSES.md index 1cf7523817..174ea882c8 100644 --- a/ASSET_LICENSES.md +++ b/ASSET_LICENSES.md @@ -37,6 +37,7 @@ inclusion and redistribution in this repository under the Apache License 2.0: - `families/internvl/tests/data/test_img.jpeg` - `families/lance/tests/data/test_img.jpeg` - `families/locateanything/tests/data/test_img.jpeg` +- `families/minicpmv4_6/tests/data/test_img.jpeg` - `families/moge/tests/data/test_img.jpeg` - `families/molmo2/tests/data/test_img.jpeg` - `families/oneformer/tests/data/test_img.jpeg` @@ -95,6 +96,9 @@ distributed under the Apache License 2.0 with the rest of the project: single-line GLM-OCR E2E cases - `families/lighton_ocr/tests/data/invoice.png` — synthetic invoice with invented data rendered by the family-owned `generate_fixture.py` +- `families/minicpmv4_6/tests/data/orc_test_img.jpeg` — byte-identical copy of + `families/deepseek_ocr/tests/data/orc_test_img.jpeg`, the input of the text-reading + E2E cases - `families/phi4_multimodal/tests/data/dynamic-hd/synthetic-*.png` (7 images) — synthetic test patterns written by the checked-in `families/phi4_multimodal/tests/data/dynamic-hd/generate.py` for Dynamic-HD diff --git a/families/minicpmv4_6/NOTICE b/families/minicpmv4_6/NOTICE new file mode 100644 index 0000000000..fe0b50ceaf --- /dev/null +++ b/families/minicpmv4_6/NOTICE @@ -0,0 +1,93 @@ +MiniCPM-V 4.6 image slicing in runtime/image.cpp (find_best_resize, +get_refine_size, get_sliced_grid, the slice order and the image placeholder +layout) follows MiniCPMV4_6ImageProcessor and MiniCPMV4_6Processor of Hugging +Face Transformers 5.22.2 (src/transformers/models/minicpmv4_6/): +https://github.com/huggingface/transformers +These files carry this header: + +Copyright 2026 OpenBMB and the HuggingFace Inc. team. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not +use these files except in compliance with the License. You may obtain a copy +of the License at http://www.apache.org/licenses/LICENSE-2.0 (also in this +repository's LICENSE file). Unless required by applicable law or agreed to in +writing, software distributed under the License is distributed on an "AS IS" +BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +The antialiased uint8 bicubic resampling in runtime/image.cpp (resize_rgb8 and +its int16 fixed-point weights) is adapted from PyTorch, +aten/src/ATen/native/cpu/UpSampleKernel.cpp: +https://github.com/pytorch/pytorch/blob/main/aten/src/ATen/native/cpu/UpSampleKernel.cpp +Licensed under the BSD 3-Clause License: + +Copyright (c) 2016- Facebook, Inc (Adam Paszke) +Copyright (c) 2014- Facebook, Inc (Soumith Chintala) +Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert) +Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu) +Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu) +Copyright (c) 2011-2013 NYU (Clement Farabet) +Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston) +Copyright (c) 2006 Idiap Research Institute (Samy Bengio) +Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz) + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +3. Neither the names of Facebook, Deepmind Technologies, NYU, NEC Laboratories America + and IDIAP Research Institute nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +PyTorch derives that code from Pillow-SIMD's Resample.c: +https://github.com/uploadcare/pillow-simd/blob/simd/master/src/libImaging/Resample.c + +The Python Imaging Library (PIL) is + + Copyright (c) 1997-2011 by Secret Labs AB + Copyright (c) 1995-2011 by Fredrik Lundh and contributors + +Pillow is the friendly PIL fork. It is + + Copyright (c) 2010 by Jeffrey 'Alex' Clark and contributors + +Like PIL, Pillow is licensed under the open source MIT-CMU License: + +By obtaining, using, and/or copying this software and/or its associated +documentation, you agree that you have read, understood, and will comply +with the following terms and conditions: + +Permission to use, copy, modify and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appears in all copies, and that +both that copyright notice and this permission notice appear in supporting +documentation, and that the name of Secret Labs AB or the author not be +used in advertising or publicity pertaining to distribution of the software +without specific, written prior permission. + +SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS +SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR ANY SPECIAL, +INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE +OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. diff --git a/families/minicpmv4_6/README.md b/families/minicpmv4_6/README.md new file mode 100644 index 0000000000..ccfc21846f --- /dev/null +++ b/families/minicpmv4_6/README.md @@ -0,0 +1,90 @@ +# MiniCPM-V 4.6 + +This family builds [`openbmb/MiniCPM-V-4.6`](https://huggingface.co/openbmb/MiniCPM-V-4.6) +(`MiniCPMV4_6ForConditionalGeneration`, 1.3 B parameters, BF16 checkpoint) for +`images_text_to_text`. The model pairs a SigLIP-style vision tower, whose +encoder merges every 2 x 2 window of patches into one token after layer +`insert_layer_id`, and an MLP projector with a Qwen3.5 hybrid decoder (Gated +DeltaNet and gated full-attention layers). + +## Bundle + +| Section | Content | +|---|---| +| `engine.plan` | one-token decoder: the KV cache of the attention layers and the FP32 DeltaNet convolution and recurrent state in, present tensors and logits out | +| `prefill.plan` | chunked prefill of 1 to 64 prompt rows per launch; a row takes its token embedding or a vision feature row | +| `vision.plan` | one image slice per launch (16 to 4096 patches): vision tower, windowed merger and projector | +| `runtime.json`, `vision.json` | decoder geometry and stop ids; image-processor settings, markup token ids and the chat-template recipes | +| `tokenizer.json`, `tokenizer_config.json`, `chat_template.jinja`, `preprocessor_config.json` | copied from the checkpoint | + +Build with `--precision fp16` (the default) or `--precision fp32`. The DeltaNet +recurrence and its state stay FP32 at both precisions, and FP32 math never uses +TF32. `max_sequence_length` (default 4096) bounds the prompt, including the +image tokens, plus the generated tokens. + +## Tasks + +`images_text_to_text` takes system, user and assistant messages with ordered +text and image parts (several images per request are supported). The runtime +reproduces the checkpoint's processor: each image becomes a source thumbnail +plus up to `max_slice_nums` (9) slices of about 448 x 448 pixels, every slice +is resized with antialiased bicubic resampling, encoded separately and +represented by ``, `` and `` markup around its image +tokens (16x token compression, 64 tokens for a 448 x 448 slice). The chat +template is applied as the checkpoint defines it, with thinking disabled +unless `enable_thinking` is set. + +The loaded bundle also offers `text_continuation` for text-only prompts (the +CLI selects it when no image is given); `use_chat_template` formats the prefix +as one user message. + +Config fields of both tasks: + +| Field | Default | Meaning | +|---|---|---| +| `max_new_tokens` | 128 | generated token budget | +| `temperature` | 1.0 | sampling temperature; 0 is greedy | +| `top_k` | 1 | 1 is greedy, 0 keeps the whole vocabulary | +| `top_p` | 1.0 | nucleus sampling mass | +| `seed` | -1 | sampling seed; -1 uses a fixed default | +| `enable_thinking` | false | chat-template thinking mode | +| `use_chat_template` | false | `text_continuation` only | + +```bash +trtmc build openbmb/MiniCPM-V-4.6 -o minicpm-v-4.6.bundle +trtmc run minicpm-v-4.6.bundle --image car.jpg --prompt "What color is the car? Answer in one word." +``` + +## Not supported + +- `video_text_to_text` and video inputs. +- The processor's `downsample_mode="4x"` (finer images with four times the + image tokens); the bundle implements the default 16x compression. +- Tool definitions, tool calls and reasoning parts in requests. +- Images whose source thumbnail or slices exceed 4096 patches (aspect ratios + beyond about 1000:1, for example 14 x 20000 pixels). +- A `max_slice_nums` above 4096 (the checkpoint sets 9). +- Images that are not RGB (grayscale or RGBA buffers), batches larger than one, + quantized builds and tensor parallelism. + +## Validation + +`tests/test_e2e.py` builds each manifest's bundle once from the pinned +checkpoint, resolved offline from the local Hugging Face cache as CI resolves it +(download it first, as below), runs the native CLI and compares the generated tokens with the +Transformers reference (`requirements.txt`) run in FP32 on the same decoded +pixels: the FP32 bundle must reproduce the reference's greedy tokens exactly; +for the FP16 bundle the reference re-scores the native tokens and each must be +its argmax or within the calibrated logit tolerance. The case marked `sdk` +also runs the public C and C++ SDK consumers (`tests/sdk_consumer.c`, +`tests/sdk_consumer.cpp`) and requires the CLI's tokens. +`tests/cpp/test_minicpmv4_6_host.cpp` checks image slicing, resampling and +grid indices, placeholder text, conversation formatting and tokenization on the +host, including `tokenizers`' Unicode tables: version 9.0 for NFC and 16.0 for +the character classes of the split pattern. + +```bash +hf download openbmb/MiniCPM-V-4.6 --revision 97328f3c2d70c4645b6a35594807eb6932068635 +HF_HUB_OFFLINE=1 TRTMC_BINARY=/trtmc TRTMC_RUNTIME_ROOT= TRTMC_NATIVE_BUILD_DIR= \ + python -m pytest families/minicpmv4_6/tests --e2e-model minicpmv4_6 -vv +``` diff --git a/families/minicpmv4_6/__init__.py b/families/minicpmv4_6/__init__.py new file mode 100644 index 0000000000..4ed145f750 --- /dev/null +++ b/families/minicpmv4_6/__init__.py @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""MiniCPM-V 4.6 images-and-text to text family.""" diff --git a/families/minicpmv4_6/checkpoint_mapper.py b/families/minicpmv4_6/checkpoint_mapper.py new file mode 100644 index 0000000000..61aa53fb4c --- /dev/null +++ b/families/minicpmv4_6/checkpoint_mapper.py @@ -0,0 +1,97 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Read the checkpoint's safetensors tensors as FP32 NumPy arrays.""" + +from __future__ import annotations + +from pathlib import Path + +import numpy as np + +# Register NumPy bfloat16 support required by safetensors. +import ml_dtypes # noqa: F401 + +from safetensors import safe_open + +from .config import load_json + + +class WeightDict(dict): + """Graph weight name -> FP32 array; projections are stored ``[in, out]``.""" + + +class _ReaderCollection(list): + """Checkpoint readers with one exact tensor-to-reader index.""" + + def __init__(self, readers: list, *, tensor_map: dict[str, object] | None = None): + super().__init__(readers) + if tensor_map is None: + tensor_map = {name: reader for reader in readers for name in reader.keys()} + self.tensor_map = tensor_map + + +def _open_safetensors(model_dir: Path) -> _ReaderCollection: + """Open ``model.safetensors`` or the shards named by its index.""" + single = model_dir / "model.safetensors" + if single.is_file(): + return _ReaderCollection([safe_open(str(single), framework="numpy")]) + index_path = model_dir / "model.safetensors.index.json" + if index_path.is_file(): + index = load_json(index_path) + weight_map = index.get("weight_map") if isinstance(index, dict) else None + if (not isinstance(weight_map, dict) or not weight_map + or not all(isinstance(name, str) and isinstance(shard, str) and shard + for name, shard in weight_map.items())): + raise ValueError("model.safetensors.index.json needs a weight_map of tensor names to shard files") + readers = {shard: safe_open(str(model_dir / shard), framework="numpy") + for shard in sorted({str(value) for value in weight_map.values()})} + return _ReaderCollection( + list(readers.values()), + tensor_map={str(name): readers[str(shard)] for name, shard in weight_map.items()}, + ) + raise FileNotFoundError(f"No safetensors checkpoint in {model_dir}") + + +def _has_tensor(readers: _ReaderCollection, name: str) -> bool: + return name in readers.tensor_map + + +_FLOAT_DTYPES = frozenset({"BF16", "F16", "F32"}) + + +def _load_tensor(readers: _ReaderCollection, name: str, shape: tuple[int, ...]) -> np.ndarray: + """One weight as FP32; its dtype and shape are checked from the header before it is read.""" + reader = readers.tensor_map.get(name) + if reader is None: + raise KeyError(f"Tensor not found: {name}") + header = reader.get_slice(name) + if header.get_dtype() not in _FLOAT_DTYPES: + raise ValueError(f"{name}: dtype {header.get_dtype()} is not a BF16, FP16 or FP32 weight") + if tuple(header.get_shape()) != tuple(shape): + raise ValueError(f"{name}: expected {tuple(shape)}, got {tuple(header.get_shape())}") + value = np.asarray(reader.get_tensor(name), dtype=np.float32) + if not np.isfinite(value).all(): + raise ValueError(f"{name} holds NaN or infinite values") + return value + + +def decay_rates(a_log: np.ndarray, name: str) -> np.ndarray: + """The DeltaNet decay rates ``-exp(A_log)`` in FP32, as the reference computes them; they must stay finite.""" + with np.errstate(over="ignore"): + rates = -np.exp(np.asarray(a_log, dtype=np.float32)) + if not np.isfinite(rates).all(): + raise ValueError(f"MiniCPM-V 4.6 {name} overflows exp() in FP32") + return rates + + +def narrowed(values, dtype, what: str = "weights") -> np.ndarray: + """``values`` as a contiguous array of an engine constant's dtype; a finite value may not leave its range. + + BF16 and FP32 checkpoint values above 65504 would become infinite FP16 constants. + """ + with np.errstate(over="ignore", invalid="ignore"): + array = np.ascontiguousarray(values, dtype=dtype) + if np.issubdtype(array.dtype, np.floating) and not np.isfinite(array).all(): + raise ValueError(f"MiniCPM-V 4.6 {what} of shape {array.shape} leave the {array.dtype.name} range") + return array diff --git a/families/minicpmv4_6/config.py b/families/minicpmv4_6/config.py new file mode 100644 index 0000000000..e4fcb57ebc --- /dev/null +++ b/families/minicpmv4_6/config.py @@ -0,0 +1,288 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Strict MiniCPM-V 4.6 checkpoint configuration (``config.json``). + +Only the geometry this family implements is accepted; any other value is an +error instead of a silently different graph. +""" + +from __future__ import annotations + +import json +import math +import struct +from dataclasses import dataclass +from pathlib import Path + +_INT32_MAX = 2**31 - 1 +DEFAULT_CAPACITY = 4096 + + +def load_json(path: Path) -> object: + """Parse a checkpoint JSON file; a repeated key or a NaN / Infinity literal is an error.""" + def unique(pairs: list[tuple[str, object]]) -> dict: + # One pass: tokenizer.json holds objects with hundreds of thousands of keys. + result: dict = {} + for key, value in pairs: + if key in result: + raise ValueError(f"MiniCPM-V 4.6 {path.name} repeats the key {key!r}") + result[key] = value + return result + + def constant(name: str) -> None: + raise ValueError(f"MiniCPM-V 4.6 {path.name} contains {name}, which is not a JSON number") + + return json.loads(Path(path).read_text(encoding="utf-8"), object_pairs_hook=unique, parse_constant=constant) + + +def stored_value(value: float, fmt: str) -> float: + """``value`` as a ``struct`` float format stores it ('f' FP32, 'e' FP16); infinity when it overflows.""" + try: + return struct.unpack(f"<{fmt}", struct.pack(f"<{fmt}", value))[0] + except OverflowError: + return math.inf + + +def positive_when_stored(value: float, fmt: str) -> bool: + stored = stored_value(value, fmt) + return math.isfinite(stored) and stored > 0 + + +def same_value(value: object, expected: object) -> bool: + """Equality that also requires the JSON type at every level: True is not 1, and 3.0 is not 3.""" + if isinstance(expected, dict): + return (isinstance(value, dict) and value.keys() == expected.keys() + and all(same_value(value[key], want) for key, want in expected.items())) + if isinstance(expected, list): + return (isinstance(value, list) and len(value) == len(expected) + and all(same_value(item, want) for item, want in zip(value, expected))) + return type(value) is type(expected) and value == expected + + +def _integer(raw: dict, key: str) -> int: + value = raw.get(key) + if type(value) is not int or not 0 < value <= _INT32_MAX: + raise ValueError(f"MiniCPM-V 4.6 config field {key!r} must be a positive 32-bit integer") + return value + + +def _token_id(raw: dict, key: str, vocab_size: int) -> int: + value = raw.get(key) + if type(value) is not int or not 0 <= value < vocab_size: + raise ValueError(f"MiniCPM-V 4.6 config field {key!r} must be a token id below {vocab_size}") + return value + + +def _number(raw: dict, key: str) -> float: + value = raw.get(key) + if (type(value) not in (int, float) or not math.isfinite(value) or value <= 0 + or not positive_when_stored(value, "f")): + raise ValueError(f"MiniCPM-V 4.6 config field {key!r} must be a positive number that FP32 represents") + return float(value) + + +def _require(raw: dict, key: str, expected, default=None) -> None: + if not same_value(raw.get(key, default), expected): + raise ValueError(f"MiniCPM-V 4.6 requires {key}={expected!r}, got {raw.get(key, default)!r}") + + +def parse_layer_types(raw_types: list[str]) -> list[str]: + """Normalize decoder layer types to 'deltanet' (linear attention) or 'attention'.""" + mapping = { + "linear_attention": "deltanet", + "full_attention": "attention", + } + result = [] + for value in raw_types: + if value not in mapping: + raise ValueError(f"MiniCPM-V 4.6 does not support decoder layer type {value!r}") + result.append(mapping[value]) + return result + + +@dataclass(frozen=True) +class TextConfig: + """The ``qwen3_5_text`` decoder of the checkpoint.""" + + hidden_size: int + intermediate_size: int + vocab_size: int + layer_types: tuple[str, ...] + num_attention_heads: int + num_key_value_heads: int + head_dim: int + linear_num_key_heads: int + linear_num_value_heads: int + linear_key_head_dim: int + linear_value_head_dim: int + linear_conv_kernel_dim: int + rms_norm_eps: float + rope_theta: float + rotary_dim: int + max_position_embeddings: int + + @classmethod + def from_dict(cls, raw: dict) -> TextConfig: + if not isinstance(raw, dict): + raise ValueError("MiniCPM-V 4.6 config.json requires a text_config object") + _require(raw, "model_type", "qwen3_5_text") + _require(raw, "hidden_act", "silu") + _require(raw, "attention_bias", False) + _require(raw, "attn_output_gate", True) + _require(raw, "mamba_ssm_dtype", "float32") + _require(raw, "tie_word_embeddings", True) + _require(raw, "mlp_only_layers", []) + rope = raw.get("rope_parameters") + if not isinstance(rope, dict) or rope.get("rope_type") != "default" or "mrope_section" in rope: + raise ValueError("MiniCPM-V 4.6 requires default one-dimensional rotary parameters") + raw_types = raw.get("layer_types") + if not isinstance(raw_types, list) or not all(isinstance(kind, str) for kind in raw_types): + raise ValueError("MiniCPM-V 4.6 layer_types must be a JSON array of layer type names") + layer_types = tuple(parse_layer_types(raw_types)) + num_layers = _integer(raw, "num_hidden_layers") + if len(layer_types) != num_layers or "deltanet" not in layer_types or "attention" not in layer_types: + raise ValueError("MiniCPM-V 4.6 layer_types must list every decoder layer of both kinds") + head_dim = _integer(raw, "head_dim") + partial = rope.get("partial_rotary_factor", raw.get("partial_rotary_factor")) + if type(partial) not in (int, float) or not 0 < partial <= 1: + raise ValueError("MiniCPM-V 4.6 partial_rotary_factor must be in (0, 1]") + rotary_dim = int(head_dim * partial) + if rotary_dim < 2 or rotary_dim % 2 or rotary_dim != head_dim * partial: + raise ValueError("MiniCPM-V 4.6 rotary dimensions must be an even number of head dimensions") + config = cls( + hidden_size=_integer(raw, "hidden_size"), + intermediate_size=_integer(raw, "intermediate_size"), + vocab_size=_integer(raw, "vocab_size"), + layer_types=layer_types, + num_attention_heads=_integer(raw, "num_attention_heads"), + num_key_value_heads=_integer(raw, "num_key_value_heads"), + head_dim=head_dim, + linear_num_key_heads=_integer(raw, "linear_num_key_heads"), + linear_num_value_heads=_integer(raw, "linear_num_value_heads"), + linear_key_head_dim=_integer(raw, "linear_key_head_dim"), + linear_value_head_dim=_integer(raw, "linear_value_head_dim"), + linear_conv_kernel_dim=_integer(raw, "linear_conv_kernel_dim"), + rms_norm_eps=_number(raw, "rms_norm_eps"), + rope_theta=_number(rope, "rope_theta"), + rotary_dim=rotary_dim, + max_position_embeddings=_integer(raw, "max_position_embeddings"), + ) + if (config.num_attention_heads % config.num_key_value_heads + or config.linear_num_value_heads % config.linear_num_key_heads + or config.linear_key_head_dim != config.linear_value_head_dim): + raise ValueError("MiniCPM-V 4.6 decoder head geometry is not supported") + return config + + +@dataclass(frozen=True) +class VisionConfig: + """The SigLIP-style vision tower with its windowed merger after ``insert_layer_id``.""" + + hidden_size: int + intermediate_size: int + num_hidden_layers: int + num_attention_heads: int + patch_size: int + positions_per_side: int + layer_norm_eps: float + insert_layer_id: int + + @property + def head_dim(self) -> int: + return self.hidden_size // self.num_attention_heads + + @property + def patch_width(self) -> int: + return 3 * self.patch_size * self.patch_size + + @classmethod + def from_dict(cls, raw: dict, insert_layer_id: object) -> VisionConfig: + if not isinstance(raw, dict): + raise ValueError("MiniCPM-V 4.6 config.json requires a vision_config object") + _require(raw, "model_type", "minicpmv4_6_vision") + _require(raw, "hidden_act", "gelu_pytorch_tanh") + _require(raw, "num_channels", 3) + _require(raw, "window_kernel_size", [2, 2], default=[2, 2]) + image_size = _integer(raw, "image_size") + patch_size = _integer(raw, "patch_size") + if image_size % patch_size: + raise ValueError("MiniCPM-V 4.6 vision image_size must be a multiple of patch_size") + # The position embedding grid must have at least two rows (the runtime's bucketing needs them). + if image_size // patch_size < 2: + raise ValueError("MiniCPM-V 4.6 vision image_size must span at least two patches") + config = cls( + hidden_size=_integer(raw, "hidden_size"), + intermediate_size=_integer(raw, "intermediate_size"), + num_hidden_layers=_integer(raw, "num_hidden_layers"), + num_attention_heads=_integer(raw, "num_attention_heads"), + patch_size=patch_size, + positions_per_side=image_size // patch_size, + layer_norm_eps=_number(raw, "layer_norm_eps"), + insert_layer_id=insert_layer_id if type(insert_layer_id) is int else -1, + ) + if config.hidden_size % config.num_attention_heads: + raise ValueError("MiniCPM-V 4.6 vision hidden size must split evenly over heads") + if not 0 <= config.insert_layer_id < config.num_hidden_layers - 1: + raise ValueError("MiniCPM-V 4.6 requires the windowed merger inside the vision encoder") + return config + + +@dataclass(frozen=True) +class CheckpointConfig: + """Top-level ``MiniCPMV4_6ForConditionalGeneration`` configuration.""" + + text: TextConfig + vision: VisionConfig + image_token_id: int + video_token_id: int + eos_token_id: int + + @classmethod + def from_dir(cls, model_dir: Path) -> CheckpointConfig: + raw = load_json(Path(model_dir) / "config.json") + if not isinstance(raw, dict): + raise ValueError("MiniCPM-V 4.6 config.json must contain one JSON object") + _require(raw, "model_type", "minicpmv4_6") + _require(raw, "architectures", ["MiniCPMV4_6ForConditionalGeneration"]) + _require(raw, "tie_word_embeddings", True) + _require(raw, "drop_vision_last_layer", False, default=False) + _require(raw, "merge_kernel_size", [2, 2], default=[2, 2]) + _require(raw, "merger_times", 1, default=1) + _require(raw, "downsample_mode", "16x", default="16x") + text = TextConfig.from_dict(raw.get("text_config")) + vision = VisionConfig.from_dict(raw.get("vision_config"), raw.get("insert_layer_id")) + return cls( + text=text, + vision=vision, + image_token_id=_token_id(raw, "image_token_id", text.vocab_size), + video_token_id=_token_id(raw, "video_token_id", text.vocab_size), + eos_token_id=_token_id(raw, "eos_token_id", text.vocab_size), + ) + + +def generation_ids(model_dir: Path, config: CheckpointConfig) -> list[int]: + path = model_dir / "generation_config.json" + if not path.is_file(): + return [config.eos_token_id] + generation = load_json(path) + value = generation.get("eos_token_id", config.eos_token_id) if isinstance(generation, dict) else None + ids = [value] if type(value) is int else value + if (not isinstance(ids, list) or not ids or len(set(ids)) != len(ids) + or any(type(i) is not int or not 0 <= i < config.text.vocab_size for i in ids)): + raise ValueError("MiniCPM-V 4.6 generation_config.json eos_token_id must be distinct token ids") + return ids + + +def capacity_rows(requested, max_positions: int) -> int: + """KV cache rows: the request's max_sequence_length, or the default when it is None.""" + if requested is None: + requested = min(DEFAULT_CAPACITY, max_positions) + elif type(requested) is not int: + raise ValueError("minicpmv4_6 max_sequence_length must be an integer") + elif requested > max_positions: + raise ValueError("minicpmv4_6 max_sequence_length exceeds the checkpoint's context capacity") + # The default as well: the runtime needs a prompt row and a generated row. + if requested < 2: + raise ValueError("minicpmv4_6 max_sequence_length must hold a prompt and one generated token") + return requested diff --git a/families/minicpmv4_6/deltanet_rows.py b/families/minicpmv4_6/deltanet_rows.py new file mode 100644 index 0000000000..047c0e4272 --- /dev/null +++ b/families/minicpmv4_6/deltanet_rows.py @@ -0,0 +1,321 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Gated DeltaNet mixer over ``S`` rows in one launch (chunked delta rule). + +The single-token decoder applies, per head and token ``t``:: + + S_t = exp(g_t) S_{t-1} + k_t u_t^T, u_t = beta_t (v_t - exp(g_t) S_{t-1}^T k_t) + o_t = S_t^T q_t + +For a chunk of ``S`` tokens with cumulative decay ``gamma_t = sum_{i<=t} g_i`` +and ``Gamma_t = exp(gamma_t)`` this is equivalent to:: + + (I + A) U = beta V - diag(beta Gamma) K S_0, + A_ij = beta_i exp(gamma_i - gamma_j) k_i.k_j for j < i, else 0 + O = diag(Gamma) Q S_0 + (exp(gamma_t - gamma_i) q_t.k_i)_{i<=t} U + S_S = exp(gamma_S) S_0 + (K * exp(gamma_S - gamma))^T U + +``I + A`` is unit lower triangular. It is inverted by 2x2 block inversion on +a fixed ``SOLVE_ROWS`` padding (the padded rows are identity), batched over +the blocks of each level. This stays accurate where a single Neumann product +over 32 or more rows does not (nearly identical keys with beta close to one). +""" + +from __future__ import annotations + +import math + +import numpy as np +import tensorrt as trt + +# Static size of the padded triangular solve; it bounds the prefill rows. +SOLVE_ROWS = 64 +# Diagonal blocks of this size are inverted with a Neumann product. +_SOLVE_LEAF = 8 + + +def _const(network, values: np.ndarray) -> trt.ITensor: + values = np.ascontiguousarray(values) + return network.add_constant(values.shape, trt.Weights(values)).get_output(0) + + +def _i64(network, values) -> trt.ITensor: + return _const(network, np.asarray(values, dtype=np.int64)) + + +def _ew(network, a, b, op) -> trt.ITensor: + return network.add_elementwise(a, b, op).get_output(0) + + +def _mm(network, a, b, transpose_a=False, transpose_b=False) -> trt.ITensor: + op_a = trt.MatrixOperation.TRANSPOSE if transpose_a else trt.MatrixOperation.NONE + op_b = trt.MatrixOperation.TRANSPOSE if transpose_b else trt.MatrixOperation.NONE + return network.add_matrix_multiply(a, op_a, b, op_b).get_output(0) + + +def _shuffle(network, tensor, reshape=None, transpose=None) -> trt.ITensor: + layer = network.add_shuffle(tensor) + if transpose is not None: + layer.first_transpose = transpose + if reshape is not None: + layer.reshape_dims = reshape + return layer.get_output(0) + + +def row_count(network, tensor: trt.ITensor) -> trt.ITensor: + """Length of axis 0 as an int64 ``[1]`` shape tensor.""" + shape = network.add_shape(tensor).get_output(0) + return network.add_slice(shape, (0,), (1,), (1,)).get_output(0) + + +def _dims(network, parts) -> trt.ITensor: + tensors = [p if isinstance(p, trt.ITensor) else _i64(network, [p]) for p in parts] + joined = network.add_concatenation(tensors) + joined.axis = 0 + return joined.get_output(0) + + +def dynamic_slice(network, tensor, start, size) -> trt.ITensor: + """Slice with static or shape-tensor start and size entries.""" + rank = len(start) + layer = network.add_slice(tensor, (0,) * rank, (1,) * rank, (1,) * rank) + if any(isinstance(s, trt.ITensor) for s in start): + layer.set_input(1, _dims(network, start)) + else: + layer.start = tuple(start) + layer.set_input(2, _dims(network, size)) + return layer.get_output(0) + + +def _block_rows(network, matrix, heads: int, blocks: int, size: int, pairs: np.ndarray): + """Blocks ``(r, c)`` of ``[heads, blocks*size, blocks*size]`` with ``pairs[r, c] = 1``, summed over c. + + Returns ``[heads, blocks, size, size]``: row block ``r`` holds the selected block of that row. + """ + split = _shuffle(network, matrix, reshape=(heads, blocks, size, blocks, size)) + mask = _const(network, pairs.astype(np.float32).reshape(1, blocks, 1, blocks, 1)) + selected = _ew(network, split, mask, trt.ElementWiseOperation.PROD) + return network.add_reduce( + selected, trt.ReduceOperation.SUM, 1 << 3, keep_dims=False + ).get_output(0) + + +def _pair_half(network, tensor, heads: int, pairs: int, size: int, index: int) -> trt.ITensor: + """``[heads, 2*pairs, size, size]`` -> block ``index`` (0 or 1) of each pair.""" + grouped = _shuffle(network, tensor, reshape=(heads, pairs, 2, size, size)) + half = network.add_slice( + grouped, (0, 0, index, 0, 0), (heads, pairs, 1, size, size), (1, 1, 1, 1, 1) + ).get_output(0) + return _shuffle(network, half, reshape=(heads, pairs, size, size)) + + +def _inverse_unit_lower(network, lower: trt.ITensor, heads: int, size: int) -> trt.ITensor: + """Inverse of a static ``[heads, size, size]`` unit lower-triangular matrix. + + All ``_SOLVE_LEAF`` diagonal blocks are inverted at once with a Neumann + product, then each level merges pairs of blocks with + ``[[T11, 0], [-T22 L21 T11, T22]]``, batched over the pairs, so the + graph has a handful of matmuls per level rather than per block. + """ + sum_op = trt.ElementWiseOperation.SUM + leaf = min(_SOLVE_LEAF, size) + if size % leaf or (size // leaf) & (size // leaf - 1): + raise ValueError("the triangular solve size must be a power-of-two multiple of the leaf") + blocks = size // leaf + diagonal = _block_rows(network, lower, heads, blocks, leaf, np.eye(blocks)) + identity = _const(network, np.eye(leaf, dtype=np.float32)[None, None]) + # (I - N)^-1 = (I + N)(I + N^2)(I + N^4)... with N = I - D nilpotent. + nilpotent = _ew(network, identity, diagonal, trt.ElementWiseOperation.SUB) + inverse = _ew(network, identity, nilpotent, sum_op) + power = nilpotent + for _ in range(max(0, math.ceil(math.log2(leaf)) - 1)): + power = _mm(network, power, power) + inverse = _mm(network, inverse, _ew(network, identity, power, sum_op)) + width = leaf + while blocks > 1: + pairs = blocks // 2 + below = np.zeros((blocks, blocks)) + below[np.arange(1, blocks, 2), np.arange(0, blocks, 2)] = 1.0 + lower_left = _pair_half( + network, + _block_rows(network, lower, heads, blocks, width, below), + heads, + pairs, + width, + 1, + ) + upper = _pair_half(network, inverse, heads, pairs, width, 0) + bottom_right = _pair_half(network, inverse, heads, pairs, width, 1) + corner = network.add_unary( + _mm(network, _mm(network, bottom_right, lower_left), upper), trt.UnaryOperation.NEG + ).get_output(0) + zeros = _const(network, np.zeros((heads, pairs, width, width), dtype=np.float32)) + top = network.add_concatenation([upper, zeros]) + top.axis = 3 + bottom = network.add_concatenation([corner, bottom_right]) + bottom.axis = 3 + merged = network.add_concatenation([top.get_output(0), bottom.get_output(0)]) + merged.axis = 2 + inverse = merged.get_output(0) + blocks, width = pairs, width * 2 + return _shuffle(network, inverse, reshape=(heads, size, size)) + + +def add_chunked_delta_rule( + network: trt.INetworkDefinition, + *, + q: trt.ITensor, + k: trt.ITensor, + v: trt.ITensor, + g: trt.ITensor, + beta: trt.ITensor, + state: trt.ITensor, + num_heads: int, + head_dim: int, +) -> tuple[trt.ITensor, trt.ITensor]: + """Gated delta rule over one chunk, all tensors FP32. + + ``q``/``k``/``v`` are head-major ``[H, S, D]`` (``q`` already scaled), + ``g``/``beta`` are ``[H, S]`` and ``state`` is ``[H, D_k, D_v]``. + Returns ``(outputs [H, S, D_v], final state [H, D_k, D_v])``. + """ + sum_op, prod_op = trt.ElementWiseOperation.SUM, trt.ElementWiseOperation.PROD + rows = row_count(network, _shuffle(network, g, transpose=(1, 0))) + + axis = network.add_constant((), np.array(1, dtype=np.int32)).get_output(0) + # Pairwise decays come from FP32 cumulative sums within the chunk, as the reference's chunked rule + # (transformers' torch_chunk_gated_delta_rule, 64-row chunks) forms them. + gamma = network.add_cumulative(g, axis, trt.CumulativeOperation.SUM, False, False).get_output(0) + gamma_rows = _shuffle(network, gamma, reshape=(0, 0, 1)) # [H, S, 1] + gamma_cols = _shuffle(network, gamma, reshape=(0, 1, -1)) # [H, 1, S] + # exp(gamma_i - gamma_j) for j <= i; the exponent is clamped at zero so the + # masked upper triangle cannot overflow before it is multiplied by zero. + diff = _ew(network, gamma_rows, gamma_cols, trt.ElementWiseOperation.SUB) + diff = _ew( + network, + diff, + _const(network, np.zeros((1, 1, 1), np.float32)), + trt.ElementWiseOperation.MIN, + ) + decay = network.add_unary(diff, trt.UnaryOperation.EXP).get_output(0) + + def mask(offset: int) -> trt.ITensor: + full = np.tril(np.ones((SOLVE_ROWS, SOLVE_ROWS), np.float32), offset)[None] + return dynamic_slice(network, _const(network, full), (0, 0, 0), (1, rows, rows)) + + decay_strict = _ew(network, decay, mask(-1), prod_op) + decay_inclusive = _ew(network, decay, mask(0), prod_op) + + beta_rows = _shuffle(network, beta, reshape=(0, 0, 1)) # [H, S, 1] + a_matrix = _ew( + network, + _ew(network, beta_rows, decay_strict, prod_op), + _mm(network, k, k, transpose_b=True), + prod_op, + ) + padded = network.add_slice(a_matrix, (0, 0, 0), (num_heads, SOLVE_ROWS, SOLVE_ROWS), (1, 1, 1)) + padded.mode = trt.SampleMode.FILL + padded.set_input(4, network.add_constant((), np.array(0.0, dtype=np.float32)).get_output(0)) + lower = _ew( + network, + _const(network, np.eye(SOLVE_ROWS, dtype=np.float32)[None]), + padded.get_output(0), + sum_op, + ) + inverse = dynamic_slice( + network, + _inverse_unit_lower(network, lower, num_heads, SOLVE_ROWS), + (0, 0, 0), + (num_heads, rows, rows), + ) + + gamma_exp = network.add_unary(gamma_rows, trt.UnaryOperation.EXP).get_output(0) # [H, S, 1] + history = _mm(network, k, state) # [H, S, D_v]: S_0^T k_i + rhs = _ew( + network, + _ew(network, beta_rows, v, prod_op), + _ew(network, _ew(network, beta_rows, gamma_exp, prod_op), history, prod_op), + trt.ElementWiseOperation.SUB, + ) + updates = _mm(network, inverse, rhs) # U: [H, S, D_v] + + scores = _ew(network, decay_inclusive, _mm(network, q, k, transpose_b=True), prod_op) + outputs = _ew( + network, + _ew(network, gamma_exp, _mm(network, q, state), prod_op), + _mm(network, scores, updates), + sum_op, + ) + + # gamma_S is the last cumulative sum, not a separate reduction: summed in + # another order it can exceed gamma_i by many ulps at large |g|, and + # exp(gamma_S - gamma_i) would then overflow. A float running sum of + # non-positive terms never increases, and the clamp keeps the exponent at + # most zero regardless. + last = _ew(network, rows, _i64(network, [1]), trt.ElementWiseOperation.SUB) + total = dynamic_slice(network, gamma, (_i64(network, [0]), last), (num_heads, 1)) # [H, 1] + tail = network.add_unary( + _ew( + network, + _ew( + network, + _shuffle(network, total, reshape=(0, 0, 1)), + gamma_rows, + trt.ElementWiseOperation.SUB, + ), + _const(network, np.zeros((1, 1, 1), np.float32)), + trt.ElementWiseOperation.MIN, + ), + trt.UnaryOperation.EXP, + ).get_output(0) # exp(gamma_S - gamma_i): [H, S, 1] + carried = _ew( + network, + network.add_unary( + _shuffle(network, total, reshape=(0, 1, 1)), trt.UnaryOperation.EXP + ).get_output(0), + state, + prod_op, + ) + final_state = _ew( + network, + carried, + _mm(network, _ew(network, k, tail, prod_op), updates, transpose_a=True), + sum_op, + ) + return outputs, final_state + + +def add_short_conv_rows( + network: trt.INetworkDefinition, + *, + columns: trt.ITensor, + conv_state: trt.ITensor, + weight: trt.ITensor, + channels: int, + kernel: int, +) -> tuple[trt.ITensor, trt.ITensor]: + """Causal depthwise conv over ``columns`` ``[C, S]`` with a ``[C, kernel]`` history. + + The history holds the last ``kernel`` inputs (newest last). Output column + ``t`` is ``sum_j weight[:, j] * window[:, t + j]`` over + ``window = [history[:, 1:], columns]``; the new history is the last + ``kernel`` columns of the window. Returns ``(outputs [C, S], history)``. + """ + rows = row_count(network, _shuffle(network, columns, transpose=(1, 0))) + if kernel > 1: + past = network.add_slice(conv_state, (0, 1), (channels, kernel - 1), (1, 1)).get_output(0) + window = network.add_concatenation([past, columns]) + window.axis = 1 + window = window.get_output(0) + else: + window = columns + total = None + for tap in range(kernel): + tap_weight = network.add_slice(weight, (0, tap), (channels, 1), (1, 1)).get_output(0) + shifted = dynamic_slice(network, window, (0, tap), (channels, rows)) + term = _ew(network, shifted, tap_weight, trt.ElementWiseOperation.PROD) + total = term if total is None else _ew(network, total, term, trt.ElementWiseOperation.SUM) + last = _ew(network, rows, _i64(network, [1]), trt.ElementWiseOperation.SUB) + history = dynamic_slice(network, window, (_i64(network, [0]), last), (channels, kernel)) + return total, history diff --git a/families/minicpmv4_6/graph_blocks.py b/families/minicpmv4_6/graph_blocks.py new file mode 100644 index 0000000000..1d190458fd --- /dev/null +++ b/families/minicpmv4_6/graph_blocks.py @@ -0,0 +1,82 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Composable architectural building blocks for TRT engine construction. + +Layer 2 in the three-layer builder stack: + + graph_ops.py Layer 1: Atomic TRT operations (tensor-in/tensor-out) + | + graph_blocks.py Layer 2: Composable blocks (weight-aware) <- THIS FILE + | + builders / plugins Layer 3: Full engine assembly + +Each block composes multiple graph_ops into a reusable sub-structure +(full attention block, SwiGLU MLP, GELU MLP, norm dispatch). Functions +accept a ``weights`` dict + ``prefix`` string to resolve weight names. + +Blocks do NOT apply residual connections. Callers compose the residual +pattern, which is what varies across architectures (sequential vs parallel +residual, DeepStack injection, MoE routing, etc.). +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import numpy as np +import tensorrt as trt + +from . import graph_ops + +if TYPE_CHECKING: + from .checkpoint_mapper import WeightDict + + +# --------------------------------------------------------------------------- +# Precision boundary helpers (used by standard_decoder_builder, not inside +# blocks themselves). +# --------------------------------------------------------------------------- + + +def make_matmul_fn(network, dtype): + """Create the projection matmul callable with a constant right-hand side.""" + + def matmul(lhs, lhs_w, rhs_w, rhs_weights, weight_name): + del weight_name + return graph_ops.add_matmul_rhs_constant( + network, lhs, lhs_w, rhs_w, rhs_weights, dtype=dtype + ) + + return matmul + + +_make_matmul_fn = make_matmul_fn + + +def add_swiglu_mlp( + network: trt.INetworkDefinition, + inp: trt.ITensor, + *, + weights: WeightDict, + prefix: str, + hidden_size: int, + mlp_size: int, + dtype: np.dtype = np.float32, + layer_prefix: str = "", +) -> trt.ITensor: + """Gate/up/down SwiGLU MLP. Returns output tensor.""" + matmul = _make_matmul_fn(network, dtype) + _lp = layer_prefix or prefix + + gate = matmul(inp, hidden_size, mlp_size, weights[f"{prefix}.w_gate"], f"{_lp}.w_gate") + up = matmul(inp, hidden_size, mlp_size, weights[f"{prefix}.w_up"], f"{_lp}.w_up") + + sigmoid = network.add_activation(gate, trt.ActivationType.SIGMOID) + swish = network.add_elementwise(gate, sigmoid.get_output(0), trt.ElementWiseOperation.PROD) + gated = network.add_elementwise(swish.get_output(0), up, trt.ElementWiseOperation.PROD) + + mlp_out = matmul( + gated.get_output(0), mlp_size, hidden_size, weights[f"{prefix}.w_down"], f"{_lp}.w_down" + ) + return mlp_out diff --git a/families/minicpmv4_6/graph_ops.py b/families/minicpmv4_6/graph_ops.py new file mode 100644 index 0000000000..b14a1454f1 --- /dev/null +++ b/families/minicpmv4_6/graph_ops.py @@ -0,0 +1,564 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Family-owned TensorRT graph operations for Python engine builds. + +Tensor names and shapes must stay compatible with the C++ bundle runtime. +""" + +from __future__ import annotations + +import numpy as np +import tensorrt as trt + +from .checkpoint_mapper import narrowed + + +def _cast_back_to_trt_dtype( + network: trt.INetworkDefinition, + tensor: trt.ITensor, + target_dtype: trt.DataType, +) -> trt.ITensor: + """Cast a tensor back to the original TRT runtime dtype after FP32 compute.""" + if tensor.dtype == target_dtype: + return tensor + return network.add_cast(tensor, target_dtype).get_output(0) + + +def layer_tensor_name(stem: str, layer: int) -> str: + return f"{stem}_{layer}" + + +def add_constant( + network: trt.INetworkDefinition, + shape: tuple[int, ...], + values: np.ndarray, + dtype: np.dtype = np.float32, +) -> trt.ITensor: + """Add a constant tensor in the given *dtype* (default float32); its values must fit the dtype.""" + weights = trt.Weights(narrowed(values, dtype)) + layer = network.add_constant(shape, weights) + return layer.get_output(0) + + +def add_matmul_rhs_constant( + network: trt.INetworkDefinition, + lhs: trt.ITensor, + lhs_width: int, + rhs_width: int, + rhs_weights: np.ndarray, + dtype: np.dtype = np.float32, +) -> trt.ITensor: + """Matrix multiply: lhs @ rhs_constant. rhs is [lhs_width, rhs_width].""" + rank = len(tuple(lhs.shape)) + rhs_shape = (lhs_width, rhs_width) if rank <= 2 else (1,) * (rank - 2) + (lhs_width, rhs_width) + rhs = add_constant( + network, + rhs_shape, + np.asarray(rhs_weights).reshape(rhs_shape), + dtype=dtype, + ) + rhs = _cast_back_to_trt_dtype(network, rhs, lhs.dtype) + mm = network.add_matrix_multiply( + lhs, + trt.MatrixOperation.NONE, + rhs, + trt.MatrixOperation.NONE, + ) + return _cast_back_to_trt_dtype(network, mm.get_output(0), lhs.dtype) + + +def add_bias_sum( + network: trt.INetworkDefinition, + inp: trt.ITensor, + width: int, + bias: np.ndarray, + dtype: np.dtype = np.float32, +) -> trt.ITensor: + """Element-wise add a bias broadcast over all non-feature axes.""" + rank = len(tuple(inp.shape)) + bias_shape = (width,) if rank <= 1 else (1,) * (rank - 1) + (width,) + bias_t = add_constant(network, bias_shape, np.asarray(bias).reshape(bias_shape), dtype=dtype) + bias_t = _cast_back_to_trt_dtype(network, bias_t, inp.dtype) + s = network.add_elementwise(inp, bias_t, trt.ElementWiseOperation.SUM) + return _cast_back_to_trt_dtype(network, s.get_output(0), inp.dtype) + + +def add_rms_norm( + network: trt.INetworkDefinition, + inp: trt.ITensor, + hidden_size: int, + gamma: np.ndarray, + eps_tensor: trt.ITensor, + dtype: np.dtype = np.float32, +) -> trt.ITensor: + """RMSNorm: gamma * (x / sqrt(mean(x^2) + eps)). + + FP32 precision boundary: when dtype != float32, casts to FP32 before + norm computation for numerical stability, then casts back. + + TRT's native normalization API implements mean-centered LayerNorm, not + RMSNorm, so this remains a manual shared implementation. + """ + need_cast = dtype != np.float32 + output_dtype = inp.dtype + if need_cast: + inp = network.add_cast(inp, trt.float32).get_output(0) + eps_tensor = network.add_cast(eps_tensor, trt.float32).get_output(0) + sq = network.add_elementwise(inp, inp, trt.ElementWiseOperation.PROD) + mean = network.add_reduce(sq.get_output(0), trt.ReduceOperation.AVG, 1 << 1, keep_dims=True) + denom_in = network.add_elementwise(mean.get_output(0), eps_tensor, trt.ElementWiseOperation.SUM) + sqrt_l = network.add_unary(denom_in.get_output(0), trt.UnaryOperation.SQRT) + recip = network.add_unary(sqrt_l.get_output(0), trt.UnaryOperation.RECIP) + normalized = network.add_elementwise(inp, recip.get_output(0), trt.ElementWiseOperation.PROD) + gamma_t = add_constant(network, (1, hidden_size), gamma, dtype=np.float32) + scaled = network.add_elementwise( + normalized.get_output(0), gamma_t, trt.ElementWiseOperation.PROD + ) + result = scaled.get_output(0) + if need_cast: + result = _cast_back_to_trt_dtype(network, result, output_dtype) + return result + + +def add_rms_norm_per_head( + network: trt.INetworkDefinition, + inp: trt.ITensor, + num_heads: int, + head_dim: int, + gamma: np.ndarray, + eps_tensor: trt.ITensor, + dtype: np.dtype = np.float32, + sequence_length: int | None = 1, +) -> trt.ITensor: + """Per-head RMSNorm for [Sq, num_heads * head_dim] tensors. + + FP32 precision boundary: when dtype != float32, casts to FP32 before + norm computation for numerical stability, then casts back. + ``sequence_length=None`` means runtime-dynamic Sq. + ``gamma`` may be [num_heads * head_dim] or [head_dim] broadcast to heads. + """ + need_cast = dtype != np.float32 + output_dtype = inp.dtype + seq_dim = -1 if sequence_length is None else sequence_length + reshape_in = network.add_shuffle(inp) + reshape_in.reshape_dims = (seq_dim, num_heads, head_dim) + + reshaped = reshape_in.get_output(0) + if need_cast: + reshaped = network.add_cast(reshaped, trt.float32).get_output(0) + eps_tensor = network.add_cast(eps_tensor, trt.float32).get_output(0) + eps_3d = network.add_shuffle(eps_tensor) + eps_3d.reshape_dims = (1, 1, 1) + sq = network.add_elementwise(reshaped, reshaped, trt.ElementWiseOperation.PROD) + mean = network.add_reduce(sq.get_output(0), trt.ReduceOperation.AVG, 1 << 2, keep_dims=True) + denom_in = network.add_elementwise( + mean.get_output(0), eps_3d.get_output(0), trt.ElementWiseOperation.SUM + ) + sqrt_l = network.add_unary(denom_in.get_output(0), trt.UnaryOperation.SQRT) + recip = network.add_unary(sqrt_l.get_output(0), trt.UnaryOperation.RECIP) + normalized = network.add_elementwise( + reshaped, recip.get_output(0), trt.ElementWiseOperation.PROD + ) + gamma_arr = np.asarray(gamma, dtype=np.float32) + if gamma_arr.size == head_dim: + gamma_t = add_constant( + network, (1, 1, head_dim), gamma_arr.reshape(1, 1, head_dim), dtype=np.float32 + ) + else: + gamma_t = add_constant( + network, + (1, num_heads, head_dim), + gamma_arr.reshape(num_heads, head_dim), + dtype=np.float32, + ) + scaled = network.add_elementwise( + normalized.get_output(0), gamma_t, trt.ElementWiseOperation.PROD + ) + + result = scaled.get_output(0) + if need_cast: + result = _cast_back_to_trt_dtype(network, result, output_dtype) + reshape_out = network.add_shuffle(result) + reshape_out.reshape_dims = (seq_dim, num_heads * head_dim) + return reshape_out.get_output(0) + + +def add_l2_norm( + network: trt.INetworkDefinition, + inp: trt.ITensor, + reduce_axis: int, + eps: float = 1e-12, + dtype: np.dtype = np.float32, +) -> trt.ITensor: + """L2 normalize as the reference's ``l2norm``: x / sqrt(sum(x^2) + eps) along reduce_axis. + + Used for DeltaNet Q/K normalization (Gated DeltaNet architecture). + + FP32 precision boundary: when dtype != float32, casts to FP32 before + norm computation for numerical stability, then casts back. + """ + need_cast = dtype != np.float32 + output_dtype = inp.dtype + if need_cast: + inp = network.add_cast(inp, trt.float32).get_output(0) + sq = network.add_elementwise(inp, inp, trt.ElementWiseOperation.PROD) + sum_sq = network.add_reduce( + sq.get_output(0), trt.ReduceOperation.SUM, 1 << reduce_axis, keep_dims=True + ) + eps_const = add_constant( + network, (1,) * (reduce_axis + 1), np.array([eps], dtype=np.float32), dtype=np.float32 + ) + shifted = network.add_elementwise(sum_sq.get_output(0), eps_const, trt.ElementWiseOperation.SUM) + norm = network.add_unary(shifted.get_output(0), trt.UnaryOperation.SQRT) + recip = network.add_unary(norm.get_output(0), trt.UnaryOperation.RECIP) + normalized = network.add_elementwise(inp, recip.get_output(0), trt.ElementWiseOperation.PROD) + result = normalized.get_output(0) + if need_cast: + result = _cast_back_to_trt_dtype(network, result, output_dtype) + return result + + +def add_softplus(network: trt.INetworkDefinition, inp: trt.ITensor) -> trt.ITensor: + """FP32 softplus without overflow: max(x, 0) + log(1 + exp(-|x|)). + + The direct log(1 + exp(x)) reaches infinity for x above about 88 in FP32. + """ + if inp.dtype != trt.float32: + raise ValueError("softplus expects an FP32 tensor") + rank = len(inp.shape) + one = add_constant(network, (1,) * rank, np.array([1.0], dtype=np.float32), dtype=np.float32) + magnitude = network.add_unary(inp, trt.UnaryOperation.ABS).get_output(0) + negative = network.add_unary(magnitude, trt.UnaryOperation.NEG).get_output(0) + tail = network.add_unary( + network.add_elementwise( + network.add_unary(negative, trt.UnaryOperation.EXP).get_output(0), one, + trt.ElementWiseOperation.SUM, + ).get_output(0), + trt.UnaryOperation.LOG, + ).get_output(0) + positive = network.add_activation(inp, trt.ActivationType.RELU).get_output(0) + return network.add_elementwise(positive, tail, trt.ElementWiseOperation.SUM).get_output(0) + + +def add_rms_norm_last_axis(network: trt.INetworkDefinition, inp: trt.ITensor, eps: float) -> trt.ITensor: + """FP32 x / sqrt(mean(x^2) + eps) over the last axis (no weight).""" + if inp.dtype != trt.float32: + raise ValueError("the RMS normalization expects an FP32 tensor") + rank = len(inp.shape) + eps_const = add_constant(network, (1,) * rank, np.array([eps], dtype=np.float32), dtype=np.float32) + sq = network.add_elementwise(inp, inp, trt.ElementWiseOperation.PROD) + mean = network.add_reduce(sq.get_output(0), trt.ReduceOperation.AVG, 1 << (rank - 1), keep_dims=True) + shifted = network.add_elementwise(mean.get_output(0), eps_const, trt.ElementWiseOperation.SUM) + recip = network.add_unary( + network.add_unary(shifted.get_output(0), trt.UnaryOperation.SQRT).get_output(0), + trt.UnaryOperation.RECIP, + ) + return network.add_elementwise(inp, recip.get_output(0), trt.ElementWiseOperation.PROD).get_output(0) + + +def add_activation( + network: trt.INetworkDefinition, + inp: trt.ITensor, + activation_type: str, + dtype: np.dtype = np.float32, +) -> trt.ITensor: + """SiLU, the activation of the DeltaNet convolution, gate and MLP.""" + del dtype + if activation_type != "silu": + raise ValueError(f"Unsupported activation: {activation_type}") + sigmoid = network.add_activation(inp, trt.ActivationType.SIGMOID) + swish = network.add_elementwise(inp, sigmoid.get_output(0), trt.ElementWiseOperation.PROD) + return swish.get_output(0) + + +# --------------------------------------------------------------------------- +# TRT 10 native attention APIs (TRT 10.x) +# +# Two primitives replace manual primitive chains: +# add_apply_rope_native → IRotaryEmbeddingLayer +# add_attention_core → IAttention (replaces score+softmax+V) +# --------------------------------------------------------------------------- + + +def validate_native_rope_dim( + rotary_embedding_dim: int, + *, + field_name: str = "rotary_embedding_dim", +) -> int: + """Validate the dimension contract required by TRT native RoPE.""" + rotary_embedding_dim = int(rotary_embedding_dim) + if rotary_embedding_dim < 2 or rotary_embedding_dim % 2 != 0: + raise ValueError( + f"TRT native RoPE requires {field_name} to be an even value >= 2; " + f"got {rotary_embedding_dim}" + ) + return rotary_embedding_dim + + +def reshape_rows_to_heads_4d( + network: trt.INetworkDefinition, + x: trt.ITensor, + num_heads: int, + head_dim: int, + sequence_length: int | None = None, + tag: str | None = None, +) -> trt.ITensor: + """Reshape [S, H * D] rows into [1, H, S, D]. + + The transpose is required for S > 1 because each input row contains all + heads for one token. ``sequence_length=None`` means runtime-dynamic S. + """ + seq_dim = -1 if sequence_length is None else sequence_length + r1 = network.add_shuffle(x) + if tag: + r1.name = tag + "_s_h_d" + r1.reshape_dims = (seq_dim, num_heads, head_dim) + r1.second_transpose = trt.Permutation([1, 0, 2]) + + r2 = network.add_shuffle(r1.get_output(0)) + if tag: + r2.name = tag + "_1_h_s_d" + r2.reshape_dims = (1, num_heads, seq_dim, head_dim) + return r2.get_output(0) + + +def reshape_heads_4d_to_rows( + network: trt.INetworkDefinition, + x_4d: trt.ITensor, + attention_size: int, + sequence_length: int | None = None, + tag: str | None = None, +) -> trt.ITensor: + """Reshape [1, H, S, D] back to [S, H * D].""" + seq_dim = -1 if sequence_length is None else sequence_length + out = network.add_shuffle(x_4d) + if tag: + out.name = tag + "_s_h_d" + out.first_transpose = trt.Permutation([0, 2, 1, 3]) + out.reshape_dims = (seq_dim, attention_size) + return out.get_output(0) + + +def add_2d_mask_to_4d( + network: trt.INetworkDefinition, + mask_2d: trt.ITensor, +) -> trt.ITensor: + """Reshape additive attention mask [Sq, K] to [1, 1, Sq, K].""" + mask_shape = network.add_shape(mask_2d).get_output(0) + ones = add_constant(network, (2,), np.array([1, 1], dtype=np.int64), dtype=np.int64) + target = network.add_concatenation([ones, mask_shape]) + target.axis = 0 + mask_4d = network.add_shuffle(mask_2d) + mask_4d.set_input(1, target.get_output(0)) + return mask_4d.get_output(0) + + +def add_apply_rope_native( + network: trt.INetworkDefinition, + inp: trt.ITensor, + num_heads: int, + head_dim: int, + cos_cache_2d: trt.ITensor, + sin_cache_2d: trt.ITensor, + position_id: trt.ITensor, + rotary_embedding_dim: int, + interleaved: bool = False, + sequence_length: int | None = 1, +) -> trt.ITensor: + """Apply RoPE via TRT native IRotaryEmbeddingLayer. + + Handles both single-token decoder steps and dynamic-Sq prefill/decode + graphs without a manual rotate-half matmul chain. + + Shape contract (IRotaryEmbeddingLayer with position_ids): + input: [1, num_heads, Sq, head_dim] (reshaped internally) + cos_cache_2d: [max_S, rotary_embedding_dim // 2] (2-D constant) + sin_cache_2d: [max_S, rotary_embedding_dim // 2] (2-D constant) + position_id: [Sq] int32, reshaped to [1, Sq] internally + interleaved: False → rotate-half (LLaMA/Qwen) + True → adjacent-pair (CodeGen/GPT-J) + + Args: + inp: [Sq, num_heads * head_dim]. + num_heads: Number of attention heads. + head_dim: Per-head dimension. + cos_cache_2d: Pre-built 2-D cos table constant. + sin_cache_2d: Pre-built 2-D sin table constant. + position_id: Runtime position indices, shape [Sq] int32. + rotary_embedding_dim: Number of head dims that participate in RoPE. + interleaved: Frequency layout (see above). + sequence_length: Static Sq, or None for runtime-dynamic Sq. + + Returns: + [Sq, num_heads * head_dim] with RoPE applied. + """ + rotary_embedding_dim = validate_native_rope_dim(rotary_embedding_dim) + attention_size = num_heads * head_dim + + inp_4d = reshape_rows_to_heads_4d(network, inp, num_heads, head_dim, sequence_length) + + # Reshape position_id [Sq] -> [1, Sq] (batch=1). + seq_dim = -1 if sequence_length is None else sequence_length + pos_2d = network.add_shuffle(position_id) + pos_2d.reshape_dims = (1, seq_dim) + + rope = network.add_rotary_embedding( + inp_4d, + cos_cache_2d, + sin_cache_2d, + interleaved, + rotary_embedding_dim, + ) + rope.set_input(3, pos_2d.get_output(0)) + + return reshape_heads_4d_to_rows(network, rope.get_output(0), attention_size, sequence_length) + + +def add_attention_core( + network: trt.INetworkDefinition, + q_4d: trt.ITensor, + k_4d: trt.ITensor, + v_4d: trt.ITensor, + causal: bool = False, + mask: trt.ITensor | None = None, + scale: float | None = None, + fp32_accumulation: bool = False, +) -> trt.ITensor: + """Scaled dot-product attention via TRT native IAttention layer. + + Replaces the manual Q@K^T → scale → softmax → @V chain. TRT 10 fuses + this into a single kernel when available; ``decomposable=True`` permits + TensorRT to lower the same operation into primitives. + + NOTE: TRT IAttention computes raw BMM1 = Q @ K^T without any built-in + 1/sqrt(D) scaling. We pre-scale Q by 1/sqrt(D) so that the fused kernel + computes the standard scaled dot-product attention formula. + + Args: + q_4d: Query [B, H, q_seq, D]. + k_4d: Key [B, H, kv_seq, D]. + v_4d: Value [B, H, kv_seq, D]. + causal: Apply causal (autoregressive) mask. Mutually exclusive + with ``mask``. + mask: Optional additive float mask [B, H, q_seq, kv_seq] added + to scaled logits before softmax. Cannot be used with + causal=True. + scale: Optional Q pre-scale factor. Defaults to 1/sqrt(D). + fp32_accumulation: + Cast Q/K/V to FP32 before IAttention, then cast the context + back to the original Q dtype. TRT may still select a + Half-input fused MHA tactic after optimizing the casts, while + keeping the IAttention accumulation/output boundary in FP32. + + Returns: + Context tensor [B, H, q_seq, D]. + """ + output_dtype = q_4d.dtype + if fp32_accumulation and output_dtype != trt.float32: + q_4d = network.add_cast(q_4d, trt.float32).get_output(0) + k_4d = network.add_cast(k_4d, trt.float32).get_output(0) + v_4d = network.add_cast(v_4d, trt.float32).get_output(0) + if mask is not None and mask.dtype != trt.float32: + mask = network.add_cast(mask, trt.float32).get_output(0) + + # Pre-scale Q: TRT IAttention does not apply score scaling itself. + # Match the scale constant's dtype to Q's dtype: in strongly-typed networks + # a FP32 constant mixed with a FP16/BF16 Q causes add_elementwise to emit + # a type-mismatch error and produce a tensor with corrupted dimensions, + # which makes add_attention return None. + if scale is None: + head_dim = q_4d.shape[-1] + scale = float(1.0 / np.sqrt(head_dim)) if head_dim > 0 else 1.0 + # Use FP16 weights directly for FP16; BF16 has no numpy native type so + # create as FP32 and cast; FP32 falls through to the default. + scale_np_dtype = np.float16 if q_4d.dtype == trt.float16 else np.float32 + scale_t = add_constant(network, (1, 1, 1, 1), np.array([[[[scale]]]]), dtype=scale_np_dtype) + if q_4d.dtype == trt.bfloat16: + scale_t = network.add_cast(scale_t, trt.bfloat16).get_output(0) + q_scaled = network.add_elementwise(q_4d, scale_t, trt.ElementWiseOperation.PROD) + + attn = network.add_attention( + q_scaled.get_output(0), + k_4d, + v_4d, + trt.AttentionNormalizationOp.SOFTMAX, + causal, + ) + # Allow TRT to decompose into primitive ops when no fused kernel is + # available (e.g. unsupported head-dim or dtype). This guarantees + # correctness on any configuration at the cost of potential performance. + attn.decomposable = True + if mask is not None and not causal: + attn.mask = mask + return _cast_back_to_trt_dtype(network, attn.get_output(0), output_dtype) + + +def add_attention_from_rows( + network: trt.INetworkDefinition, + q: trt.ITensor, + k: trt.ITensor, + v: trt.ITensor, + *, + num_heads: int, + head_dim: int, + num_kv_heads: int | None = None, + q_seq: int | None, + kv_seq: int | None, + causal: bool = False, + mask: trt.ITensor | None = None, + scale: float | None = None, + fp32_accumulation: bool = False, + tag: str | None = None, +) -> trt.ITensor: + """Native IAttention for row-major [S, H * D] Q/K/V tensors. + + ``num_kv_heads`` can be smaller than ``num_heads`` for GQA/MQA. TRT + native IAttention supports this directly, so callers should not expand K/V + heads unless the model semantics require per-query-head K/V values. + """ + attention_size = num_heads * head_dim + kv_heads = num_heads if num_kv_heads is None else num_kv_heads + q_4d = reshape_rows_to_heads_4d( + network, + q, + num_heads, + head_dim, + sequence_length=q_seq, + tag=None if tag is None else tag + ".q", + ) + k_4d = reshape_rows_to_heads_4d( + network, + k, + kv_heads, + head_dim, + sequence_length=kv_seq, + tag=None if tag is None else tag + ".k", + ) + v_4d = reshape_rows_to_heads_4d( + network, + v, + kv_heads, + head_dim, + sequence_length=kv_seq, + tag=None if tag is None else tag + ".v", + ) + if scale is None: + scale = float(1.0 / np.sqrt(head_dim)) if head_dim > 0 else 1.0 + ctx_4d = add_attention_core( + network, + q_4d, + k_4d, + v_4d, + causal=causal, + mask=mask, + scale=scale, + fp32_accumulation=fp32_accumulation, + ) + return reshape_heads_4d_to_rows( + network, + ctx_4d, + attention_size, + sequence_length=q_seq, + tag=None if tag is None else tag + ".ctx", + ) diff --git a/families/minicpmv4_6/model.py b/families/minicpmv4_6/model.py new file mode 100644 index 0000000000..9ad139dcb3 --- /dev/null +++ b/families/minicpmv4_6/model.py @@ -0,0 +1,99 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""MiniCPM-V 4.6 bundle builder. + +``MiniCPMV4_6ForConditionalGeneration`` pairs a SigLIP-style vision tower +(with a windowed token merger inside the encoder and an MLP projector) with a +Qwen3.5 hybrid decoder (Gated DeltaNet + gated attention). The bundle holds: + +``engine.plan`` one-token decoder (``text_model``) +``prefill.plan`` chunked prefill that accepts vision feature rows (``text_model``) +``vision.plan`` per-slice vision tower, merger and projector (``vision``) +``runtime.json`` decoder geometry and generation ids +``vision.json`` image-processor settings, markup token ids and prompt recipes +``tokenizer.json``, ``chat_template.jinja`` and the processor configuration. +""" + +from __future__ import annotations + +import gc +from pathlib import Path + +from .checkpoint_mapper import _open_safetensors +from .config import CheckpointConfig, capacity_rows, generation_ids, positive_when_stored +from .prompt import image_metadata +from .rope import rope_positions, rope_tables +from .text_model import PREFILL_MAX_ROWS, build_text_engine, load_text_weights, text_runtime_config +from .vision import MAX_PATCHES, build_vision_engine, load_vision_weights + +_PRECISIONS = ("fp16", "fp32") +_BUNDLE_FILES = ("tokenizer.json", "tokenizer_config.json", "chat_template.jinja", "preprocessor_config.json") + + +def build(request, writer) -> None: + """Build one MiniCPM-V 4.6 bundle; every request option is consumed or rejected.""" + if request.task != "images_text_to_text": + raise ValueError("minicpmv4_6 supports only the images_text_to_text task") + if request.backend != "trt": + raise ValueError("minicpmv4_6 supports only the trt backend") + if request.precision not in _PRECISIONS: + raise ValueError(f"minicpmv4_6 precision must be one of {', '.join(_PRECISIONS)}") + if type(request.tensor_parallel_size) is not int or request.tensor_parallel_size != 1: + raise ValueError("minicpmv4_6 runs on one GPU; tensor_parallel_size must be 1") + if type(request.context_parallel_size) is not int or request.context_parallel_size != 1: + raise ValueError("minicpmv4_6 does not support context parallelism") + if type(request.max_batch_size) is not int or request.max_batch_size != 1: + raise ValueError("minicpmv4_6 serves one request at a time; max_batch_size must be 1") + if type(request.verbose) is not bool: + raise ValueError("minicpmv4_6 verbose must be a boolean") + if request.quantization is not None: + raise ValueError("minicpmv4_6 does not support quantization") + if request.fp32_layers: + raise ValueError("minicpmv4_6 does not support per-layer FP32 overrides") + if request.dynamic_kv_cache: + raise NotImplementedError("minicpmv4_6 does not support dynamic_kv_cache") + if request.mtp_seq_len is not None: + raise ValueError("minicpmv4_6 has no multi-token prediction head") + if request.image_height is not None or request.image_width is not None: + raise ValueError("minicpmv4_6 sizes every image slice at runtime; image dimensions are not build options") + if request.video_num_frames is not None: + raise ValueError("minicpmv4_6 does not support video input") + + model_dir = Path(request.model_dir) + config = CheckpointConfig.from_dir(model_dir) + capacity = capacity_rows(request.max_sequence_length, config.text.max_position_embeddings) + precision = request.precision + # The decoder's RMSNorm epsilon is a constant of the work dtype. + if not positive_when_stored(config.text.rms_norm_eps, "e" if precision == "fp16" else "f"): + raise ValueError(f"minicpmv4_6 rms_norm_eps {config.text.rms_norm_eps} vanishes in {precision}") + rope_tables(config.text, rope_positions(capacity)) # finite angles for every cached position + metadata = image_metadata(model_dir, config, capacity, precision, MAX_PATCHES) + verbose = request.verbose + + writer.set_header(family="minicpmv4_6", task=request.task, backend=request.backend) + readers = _open_safetensors(model_dir) + text_weights = load_text_weights(readers, config.text) + writer.add_bytes("engine.plan", build_text_engine( + config.text, text_weights, capacity, precision=precision, verbose=verbose)) + writer.add_bytes("prefill.plan", build_text_engine( + config.text, text_weights, capacity, precision=precision, prefill_rows=PREFILL_MAX_ROWS, + verbose=verbose)) + del text_weights + gc.collect() + vision_weights = load_vision_weights(readers, config.vision, config.text.hidden_size) + writer.add_bytes("vision.plan", build_vision_engine(config.vision, vision_weights, precision=precision, + verbose=verbose)) + del vision_weights + writer.add_json("vision.json", metadata) + writer.add_json("runtime.json", { + **text_runtime_config(config.text), + "precision": precision, + "max_cache_length": capacity, + "eos_token_id": generation_ids(model_dir, config), + }) + for name in _BUNDLE_FILES: + path = model_dir / name + if not path.is_file(): + raise FileNotFoundError(f"MiniCPM-V 4.6 checkpoint is missing {name}") + writer.add_bytes(name, path.read_bytes()) diff --git a/families/minicpmv4_6/prompt.py b/families/minicpmv4_6/prompt.py new file mode 100644 index 0000000000..2a0dddc1d5 --- /dev/null +++ b/families/minicpmv4_6/prompt.py @@ -0,0 +1,348 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Provider chat-template recipes and image-prompt metadata for the native runtime. + +The runtime formats conversations with a small recipe (fixed prefixes and +suffixes per role) instead of a template engine. The recipe is extracted from +the checkpoint's own chat template with sentinel messages and then checked +against the template on a set of conversations; a template whose formatting +the recipe cannot reproduce is rejected at build time. +""" + +from __future__ import annotations + +import math +from pathlib import Path + +from .config import load_json, same_value, stored_value + +# MiniCPMV4_6ImageProcessor options. The native runtime honors these values only; the checkpoint may restate them. +_PROCESSOR_FIXED = { + "image_processor_type": "MiniCPMV4_6ImageProcessor", + "processor_class": "MiniCPMV4_6Processor", + "do_resize": True, "do_rescale": True, "do_normalize": True, "do_convert_rgb": True, + "rescale_factor": 1 / 255, "resample": 3, "slice_mode": True, "use_image_id": True, "downsample_mode": "16x", +} +# Options the runtime reads from vision.json (patch_size must also match config.json). +_PROCESSOR_SETTINGS = ("patch_size", "max_slice_nums", "scale_resolution", "image_mean", "image_std") +_FP16_MAX = 65504.0 +# The runtime plans slice grids in time linear in max_slice_nums and accepts at most this value +# (runtime/image.h, kMaxSliceNums). +MAX_SLICE_NUMS = 4096 + +IMAGE_PLACEHOLDER = "<|image_pad|>" +# Image-slice markup tokens of the processor, by role. +MARKUP_TOKENS = { + "image_pad": "<|image_pad|>", + "video_pad": "<|video_pad|>", + "image_start": "", + "image_end": "", + "slice_start": "", + "slice_end": "", + "image_id_start": "", + "image_id_end": "", +} + + +def _split(text: str, marker: str) -> list[str]: + if text.count(marker) != 1: + raise ValueError("MiniCPM-V 4.6 chat template does not preserve content markers") + return text.split(marker) + + +def _without_prefix(text: str, prefix: str) -> str: + if not text.startswith(prefix): + raise ValueError("MiniCPM-V 4.6 chat template has context-dependent formatting") + return text[len(prefix):] + + +def _without_suffix(text: str, suffix: str) -> str: + if not text.endswith(suffix): + raise ValueError("MiniCPM-V 4.6 chat template has context-dependent formatting") + return text[:-len(suffix)] if suffix else text + + +def render_recipe(recipe: dict, messages: list[dict], *, generation: bool = True) -> str: + """Builder-side oracle of the runtime's message formatter (text content only).""" + last_user = -1 + for index, message in enumerate(messages): + content = message["content"].strip() + if message["role"] == "user" and not ( + content.startswith("") and content.endswith("") + ): + last_user = index + if last_user < 0: + raise ValueError("MiniCPM-V 4.6 requires a user query") + system = messages[0]["content"].strip() if messages[0]["role"] == "system" else None + if system is None: + output = recipe["default_prefix"] + elif system: + output = recipe["system"]["prefix"] + system + recipe["system"]["suffix"] + else: + output = recipe["empty_system_prefix"] + for index, message in enumerate(messages): + role, content = message["role"], message["content"].strip() + if role == "system": + if index: + raise ValueError("System message must be first") + continue + if role not in {"user", "assistant"}: + raise ValueError("MiniCPM-V 4.6 accepts system, user and assistant roles") + if role == "user": + output += recipe["user"]["prefix"] + content + recipe["user"]["suffix"] + continue + reasoning = message.get("reasoning_content", "").strip() + if recipe["parse_assistant_thinking"] and "reasoning_content" not in message and "" in content: + reasoning = content.split("")[0].rstrip("\n").split("")[-1].lstrip("\n").strip() + content = content.split("")[-1].lstrip("\n") + form = recipe["assistant_recent" if index > last_user else "assistant_history"] + output += form["prefix"] + if form["include_reasoning"]: + output += reasoning + form["reasoning_suffix"] + output += content + form["suffix"] + return output + (recipe["generation"] if generation else "") + + +def provider_recipes(tokenizer) -> dict: + """Extract the no-tool message forms of the checkpoint template, for both thinking modes.""" + a, b, c, reasoning = (f"MINICPMV46_NATIVE_SENTINEL_{index}_END" for index in range(4)) + + def message(role, content, **kwargs): + return {"role": role, "content": content, **kwargs} + + result = {} + for thinking in (False, True): + def render(messages, generation=False): + return tokenizer.apply_chat_template( + messages, tokenize=False, add_generation_prompt=generation, enable_thinking=thinking + ) + + single = render([message("user", a)]) + full_prefix, user_suffix = _split(single, a) + doubled = render([message("user", a), message("user", b)]) + middle = _split(_split(doubled, a)[1], b)[0] + user_prefix = _without_prefix(middle, user_suffix) + default = _without_suffix(full_prefix, user_prefix) + system = _without_suffix(render([message("system", c), message("user", a)]), user_prefix + a + user_suffix) + system_prefix, system_suffix = _split(system, c) + recipe = { + "default_prefix": default, + "user": {"prefix": user_prefix, "suffix": user_suffix}, + "system": {"prefix": system_prefix, "suffix": system_suffix}, + "empty_system_prefix": _without_suffix( + render([message("system", ""), message("user", a)]), user_prefix + a + user_suffix + ), + "generation": _without_prefix(render([message("user", a)], True), single), + } + for historical in (False, True): + messages = [message("user", a), message("assistant", b, reasoning_content=reasoning)] + if historical: + messages.append(message("user", c)) + assistant = _without_prefix(render(messages), single) + if historical: + assistant = _without_suffix(assistant, user_prefix + c + user_suffix) + prefix, suffix = _split(assistant, b) + includes = reasoning in prefix + start, between = _split(prefix, reasoning) if includes else (prefix, "") + recipe["assistant_history" if historical else "assistant_recent"] = { + "prefix": start, "include_reasoning": includes, "reasoning_suffix": between, "suffix": suffix, + } + probe = [message("user", a), message("assistant", f"{reasoning}{b}")] + recipe["parse_assistant_thinking"] = False + actual = render(probe) + if render_recipe(recipe, probe, generation=False) != actual: + recipe["parse_assistant_thinking"] = True + if render_recipe(recipe, probe, generation=False) != actual: + raise ValueError("Unsupported MiniCPM-V 4.6 assistant reasoning formatting") + cases = [ + [message("user", " \nHello, 世界! ")], + [message("system", ""), message("user", "")], + [message("system", " Follow instructions. "), message("user", a)], + [message("user", a), message("assistant", b)], + [message("user", a), message("assistant", b), message("user", c)], + probe, + probe + [message("user", c)], + [message("user", a), message("assistant", b, reasoning_content=reasoning), message("user", c)], + [message("user", a), message("assistant", b, reasoning_content=reasoning)], + [message("user", a), message("user", "value"), message("assistant", b)], + ] + for messages in cases: + for generation in (False, True): + if render_recipe(recipe, messages, generation=generation) != render(messages, generation): + raise ValueError("MiniCPM-V 4.6 prompt recipe does not match the checkpoint template") + # Structured image parts render as one placeholder each, joined to the text by newlines. + structured = [ + message("user", [{"type": "image"}, {"type": "text", "text": "Describe this."}]), + message("assistant", b), + message("user", [{"type": "image"}, {"type": "image"}, {"type": "text", "text": " Compare. "}]), + ] + expanded = [ + message("user", f"{IMAGE_PLACEHOLDER}\nDescribe this."), + message("assistant", b), + message("user", f"{IMAGE_PLACEHOLDER}\n{IMAGE_PLACEHOLDER}\n Compare. "), + ] + if render(structured, True) != render_recipe(recipe, expanded): + raise ValueError("MiniCPM-V 4.6 image placeholders differ from the checkpoint template") + result[str(thinking).lower()] = recipe + return result + + +def normalization_values(values: object, key: str) -> list[float]: + if (not isinstance(values, list) or len(values) != 3 + or any(type(v) not in (int, float) or not math.isfinite(v) for v in values)): + raise ValueError(f"MiniCPM-V 4.6 preprocessor_config.json {key} must hold three finite numbers") + return [float(v) for v in values] + + +def check_normalization(mean: list[float], stddev: list[float]) -> None: + """The runtime normalizes 0..255 pixels as (pixel - mean * 255) / (std * 255) in FP32; the + results of both ends must be finite and fit FP16, the vision engine's narrowest work type.""" + def f32(value: float) -> float: + return stored_value(value, "f") + + for m, s in zip(mean, stddev): + offset, scale = f32(f32(m) * 255.0), f32(f32(s) * 255.0) + if not (math.isfinite(offset) and math.isfinite(scale) and scale > 0): + raise ValueError("MiniCPM-V 4.6 image normalization overflows FP32") + for pixel in (0.0, 255.0): + value = f32(f32(pixel - offset) / scale) + if not math.isfinite(value) or abs(value) > _FP16_MAX: + raise ValueError("MiniCPM-V 4.6 image normalization produces values outside the FP16 range") + + +def processor_settings(model_dir: Path, patch_size: int, max_patches: int) -> dict: + """The image-processor settings the runtime implements, from ``preprocessor_config.json``.""" + processor = load_json(model_dir / "preprocessor_config.json") + if not isinstance(processor, dict): + raise ValueError("MiniCPM-V 4.6 preprocessor_config.json must contain one JSON object") + unknown = sorted(set(processor) - set(_PROCESSOR_FIXED) - set(_PROCESSOR_SETTINGS)) + if unknown: + raise ValueError(f"MiniCPM-V 4.6 native runtime does not implement image processor options {unknown}") + for key, value in _PROCESSOR_FIXED.items(): + if key in processor and not same_value(processor[key], value): + raise ValueError(f"MiniCPM-V 4.6 native runtime implements {key}={value!r}, " + f"preprocessor_config.json sets {processor[key]!r}") + for key in _PROCESSOR_SETTINGS: + if key not in processor: + raise ValueError(f"MiniCPM-V 4.6 preprocessor_config.json must set {key}") + if not same_value(processor["patch_size"], patch_size): + raise ValueError(f"MiniCPM-V 4.6 preprocessor_config.json requires patch_size={patch_size}") + for key in ("max_slice_nums", "scale_resolution"): + if type(processor[key]) is not int or not 0 < processor[key] <= 2**31 - 1: + raise ValueError(f"MiniCPM-V 4.6 preprocessor_config.json {key} must be a positive 32-bit integer") + if processor["max_slice_nums"] > MAX_SLICE_NUMS: + raise ValueError(f"MiniCPM-V 4.6 native runtime supports max_slice_nums up to {MAX_SLICE_NUMS}") + if processor["scale_resolution"] < 4 * patch_size: + raise ValueError("MiniCPM-V 4.6 scale_resolution must hold at least one 4 x 4 block of patches") + if (processor["scale_resolution"] // patch_size) ** 2 > max_patches: + raise ValueError(f"MiniCPM-V 4.6 scale_resolution exceeds the vision engine's {max_patches} patches") + mean, stddev = (normalization_values(processor[key], key) for key in ("image_mean", "image_std")) + check_normalization(mean, stddev) + return {"scale_resolution": processor["scale_resolution"], "max_slice_nums": processor["max_slice_nums"], + "mean": mean, "stddev": stddev} + + +def check_vocabulary(vocabulary: dict[str, int], total: int, rows: int) -> None: + """Every token id must address a row of the embedding table (checked before any engine build).""" + ids = list(vocabulary.values()) + if (not ids or type(total) is not int or total > rows or len(set(ids)) != len(ids) + or any(type(i) is not int or not 0 <= i < rows for i in ids)): + raise ValueError(f"MiniCPM-V 4.6 tokenizer ids must be distinct rows of the {rows}-row embedding table") + + +# The tokenizer.json layout the native tokenizer loads (runtime/bpe_tokenizer.cpp, validate_schema and parse_*). +_SPLIT_PATTERN = (r"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+|\p{N}" + r"| ?[^\s\p{L}\p{M}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+") +_BYTE_LEVEL = {"type": "ByteLevel", "add_prefix_space": False, "trim_offsets": False, "use_regex": False} +_TOKENIZER_LAYOUT = { + "version": "1.0", "truncation": None, "padding": None, "normalizer": {"type": "NFC"}, + "pre_tokenizer": {"type": "Sequence", "pretokenizers": [ + {"type": "Split", "pattern": {"Regex": _SPLIT_PATTERN}, "behavior": "Isolated", "invert": False}, + _BYTE_LEVEL]}, + "post_processor": _BYTE_LEVEL, "decoder": _BYTE_LEVEL, +} +_BPE_MODEL = {"type": "BPE", "dropout": None, "unk_token": None, "continuing_subword_prefix": "", + "end_of_word_suffix": "", "fuse_unk": False, "byte_fallback": False, "ignore_merges": False} +_ADDED_FLAGS = ("single_word", "lstrip", "rstrip", "normalized") + + +def _byte_alphabet() -> list[str]: + """GPT-2's byte-level characters: one per byte value.""" + direct = set(range(33, 127)) | set(range(161, 173)) | set(range(174, 256)) + characters, displaced = [], 0 + for byte in range(256): + characters.append(chr(byte) if byte in direct else chr(256 + displaced)) + displaced += byte not in direct + return characters + + +def check_tokenizer_layout(root: object) -> None: + """The parsed ``tokenizer.json`` must be the byte-level BPE the native tokenizer loads (before any engine build).""" + def require(condition: bool, what: str) -> None: + if not condition: + raise ValueError(f"MiniCPM-V 4.6 native tokenizer cannot load this tokenizer.json: {what}") + + require(isinstance(root, dict) and set(root) == {*_TOKENIZER_LAYOUT, "added_tokens", "model"}, + "unexpected top-level fields") + for key, expected in _TOKENIZER_LAYOUT.items(): + require(same_value(root[key], expected), f"{key} differs from the supported layout") + model = root["model"] + require(isinstance(model, dict) and set(model) == {*_BPE_MODEL, "vocab", "merges"} + and all(same_value(model[key], value) for key, value in _BPE_MODEL.items()), "not the byte-level BPE model") + vocab, merges = model["vocab"], model["merges"] + require(isinstance(vocab, dict) and vocab and all(type(i) is int for i in vocab.values()) + and sorted(vocab.values()) == list(range(len(vocab))), "vocabulary ids are not 0 .. n-1") + require(all(character in vocab for character in _byte_alphabet()), "a byte-level token is missing") + added = root["added_tokens"] + require(isinstance(added, list) and added, "no added tokens") + contents = set() + for index, token in enumerate(added): + require(isinstance(token, dict) and set(token) == {"id", "content", "special", *_ADDED_FLAGS} + and same_value(token["id"], len(vocab) + index) and isinstance(token["content"], str) + and token["content"] and token["content"] not in vocab and token["content"] not in contents + and all(token[flag] is False for flag in _ADDED_FLAGS) and type(token["special"]) is bool, + f"added token {index} is not a verbatim token numbered after the vocabulary") + contents.add(token["content"]) + require(isinstance(merges, list), "merges are not a list") + seen = set() + for merge in merges: + require(isinstance(merge, list) and len(merge) == 2 and all(isinstance(part, str) for part in merge) + and merge[0] in vocab and merge[1] in vocab and merge[0] + merge[1] in vocab + and tuple(merge) not in seen, f"merge {merge!r} is not a new pair of vocabulary tokens") + seen.add(tuple(merge)) + + +def image_metadata(model_dir: Path, config, capacity: int, precision: str, max_patches: int) -> dict: + """Validated image-processor settings, markup token ids and prompt recipes (``vision.json``).""" + from transformers import AutoTokenizer + + processor = processor_settings(model_dir, config.vision.patch_size, max_patches) + check_tokenizer_layout(load_json(model_dir / "tokenizer.json")) + + tokenizer = AutoTokenizer.from_pretrained(str(model_dir), local_files_only=True, trust_remote_code=False) + check_vocabulary(tokenizer.get_vocab(), len(tokenizer), config.text.vocab_size) + token_ids = {} + for name, text in MARKUP_TOKENS.items(): + encoded = tokenizer.encode(text, add_special_tokens=False) + if len(encoded) != 1: + raise ValueError(f"MiniCPM-V 4.6 tokenizer does not keep {text} as one token") + token_ids[name] = encoded[0] + if token_ids["image_pad"] != config.image_token_id or token_ids["video_pad"] != config.video_token_id: + raise ValueError("MiniCPM-V 4.6 tokenizer and config.json disagree on media token ids") + del token_ids["video_pad"] + return { + "schema_version": 1, + "precision": precision, + "capacity": capacity, + "hidden_size": config.text.hidden_size, + "patch_size": config.vision.patch_size, + "positions_per_side": config.vision.positions_per_side, + "max_patches": max_patches, + "scale_resolution": processor["scale_resolution"], + "max_slice_nums": processor["max_slice_nums"], + "mean": processor["mean"], + "stddev": processor["stddev"], + "token_ids": token_ids, + "prompts": provider_recipes(tokenizer), + } diff --git a/families/minicpmv4_6/requirements.txt b/families/minicpmv4_6/requirements.txt new file mode 100644 index 0000000000..507b9e65f1 --- /dev/null +++ b/families/minicpmv4_6/requirements.txt @@ -0,0 +1,7 @@ +# Transformers reference for the E2E oracle and build-time chat-template rendering; +# MiniCPM-V 4.6 needs transformers >= 5.7.0. The pins keep packages the repository +# constrains inside those constraints when this file is resolved on its own. +transformers==5.22.2 +tokenizers==0.23.3 +huggingface-hub==1.33.0 +numpy<2.5 diff --git a/families/minicpmv4_6/rope.py b/families/minicpmv4_6/rope.py new file mode 100644 index 0000000000..0d3fc01f01 --- /dev/null +++ b/families/minicpmv4_6/rope.py @@ -0,0 +1,33 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""RoPE tables of the decoder (NumPy only, so the builder checks them before any engine).""" + +from __future__ import annotations + +import numpy as np + + +def rope_positions(max_cache_length: int) -> int: + """Rows of the RoPE tables: the cache plus the current token.""" + return max_cache_length + 1 + + +def rope_tables(config, positions: int) -> tuple[np.ndarray, np.ndarray]: + """Half-dimension cos/sin tables of ``config.rotary_dim`` and ``config.rope_theta``, in the reference's FP32. + + The reference computes ``inv_freq = 1 / theta ** (arange(0, dim, 2) / dim)`` + and ``angle = position * inv_freq`` in FP32 before taking cos and sin, so + the tables round the same intermediates. + """ + dim = config.rotary_dim + exponents = np.arange(0, dim, 2, dtype=np.float32) / np.float32(dim) + with np.errstate(over="ignore", divide="ignore", invalid="ignore"): + inv_freq = (np.float32(1.0) / np.power(np.float32(config.rope_theta), exponents)).astype(np.float32) + angles = np.arange(positions, dtype=np.float32)[:, None] * inv_freq[None, :] + angles = angles.astype(np.float32) + # A small rope_theta makes the frequencies, and then the angles of late positions, overflow FP32. + if not (np.isfinite(inv_freq).all() and np.isfinite(angles).all()): + raise ValueError(f"MiniCPM-V 4.6 rope_theta {config.rope_theta} overflows the FP32 RoPE angles " + f"of {positions} positions") + return np.cos(angles.astype(np.float64)).astype(np.float32), np.sin(angles.astype(np.float64)).astype(np.float32) diff --git a/families/minicpmv4_6/runtime/CMakeLists.txt b/families/minicpmv4_6/runtime/CMakeLists.txt new file mode 100644 index 0000000000..6b2405cd45 --- /dev/null +++ b/families/minicpmv4_6/runtime/CMakeLists.txt @@ -0,0 +1,88 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# The tokenizer pins ICU's Unicode tables from Unicode 15.0 (ICU 72) on (bpe_tokenizer.cpp). +find_package(ICU 72 REQUIRED COMPONENTS uc i18n) + +add_library(trtmc_model_minicpmv4_6 SHARED + bpe_tokenizer.cpp + decoder.cpp + engine_io.cpp + image.cpp + metadata.cpp + plugin.cpp + prompt.cpp + sampler.cpp + state.cpp + vision_encoder.cpp +) + +target_include_directories(trtmc_model_minicpmv4_6 + PRIVATE + ${PROJECT_SOURCE_DIR} + ${PROJECT_SOURCE_DIR}/core/runtime/include +) +target_include_directories(trtmc_model_minicpmv4_6 SYSTEM PRIVATE + ${TRTMC_CUDA_INCLUDE_DIR} +) +target_link_libraries(trtmc_model_minicpmv4_6 PRIVATE + trtmc_core + ICU::uc + ICU::i18n + nlohmann_json::nlohmann_json + ${TRTMC_CUDART_LIBRARY} +) +target_compile_options(trtmc_model_minicpmv4_6 PRIVATE -Wall -Wextra -Wpedantic) +set_target_properties(trtmc_model_minicpmv4_6 PROPERTIES + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" + BUILD_RPATH "\$ORIGIN" + INSTALL_RPATH "\$ORIGIN" +) +install(TARGETS trtmc_model_minicpmv4_6 + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} +) +# The library carries code adapted from Apache-2.0, BSD-3-Clause and MIT-CMU sources; ship their notices with it. +install(FILES ${PROJECT_SOURCE_DIR}/families/minicpmv4_6/NOTICE + DESTINATION ${CMAKE_INSTALL_DATADIR}/trtmc/families/minicpmv4_6 +) + +if(TRTMC_BUILD_TESTS) + # Host-only checks: image slicing and resampling, tokenizer, prompt formatting, metadata, + # sampling and the engine I/O contracts (against a fake module). + add_executable(test_minicpmv4_6_host + ${PROJECT_SOURCE_DIR}/families/minicpmv4_6/tests/cpp/test_minicpmv4_6_host.cpp + bpe_tokenizer.cpp + engine_io.cpp + image.cpp + metadata.cpp + prompt.cpp + sampler.cpp + ) + target_include_directories(test_minicpmv4_6_host PRIVATE + ${PROJECT_SOURCE_DIR} + ${PROJECT_SOURCE_DIR}/core/runtime/include + ) + target_include_directories(test_minicpmv4_6_host SYSTEM PRIVATE + ${TRTMC_CUDA_INCLUDE_DIR} + ) + target_link_libraries(test_minicpmv4_6_host PRIVATE + ICU::uc + ICU::i18n + nlohmann_json::nlohmann_json + ) + target_compile_options(test_minicpmv4_6_host PRIVATE -Wall -Wextra -Wpedantic) + add_test(NAME test_minicpmv4_6_host COMMAND test_minicpmv4_6_host) + + # Public SDK consumers run by the family E2E from the native build directory. + foreach(kind IN ITEMS c cpp) + add_executable(test_minicpmv4_6_sdk_${kind} + ${PROJECT_SOURCE_DIR}/families/minicpmv4_6/tests/sdk_consumer.${kind} + ) + target_link_libraries(test_minicpmv4_6_sdk_${kind} PRIVATE trtmc_c) + target_compile_options(test_minicpmv4_6_sdk_${kind} PRIVATE -Wall -Wextra -Wpedantic) + set_target_properties(test_minicpmv4_6_sdk_${kind} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" + ) + endforeach() + target_link_libraries(test_minicpmv4_6_sdk_cpp PRIVATE nlohmann_json::nlohmann_json) +endif() diff --git a/families/minicpmv4_6/runtime/bpe_tokenizer.cpp b/families/minicpmv4_6/runtime/bpe_tokenizer.cpp new file mode 100644 index 0000000000..ec0d0620bc --- /dev/null +++ b/families/minicpmv4_6/runtime/bpe_tokenizer.cpp @@ -0,0 +1,657 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/minicpmv4_6/runtime/metadata.h" +#include "families/minicpmv4_6/runtime/tokenizer.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc::minicpmv4_6 { +namespace { + +constexpr std::string_view kPretokenizerPattern = + R"regex((?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+|\p{N}| ?[^\s\p{L}\p{M}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+)regex"; + +[[noreturn]] void schema_error(const std::string& detail) { + throw std::runtime_error("MiniCPM-V 4.6 tokenizer.json " + detail); +} + +void require_schema(bool condition, const std::string& detail) { + if (!condition) + schema_error(detail); +} + +// A token id from JSON: an integer (not a boolean or a fraction) in [0, limit), +// checked before it is narrowed. +std::int32_t token_id(const nlohmann::json& value, std::int64_t limit, const char* what) { + require_schema(value.is_number_integer(), std::string("contains a non-integer ") + what); + const bool in_range = value.is_number_unsigned() + ? value.get() < static_cast(limit) + : value.get() >= 0 && value.get() < limit; + require_schema(in_range, std::string("contains an out-of-range ") + what); + return static_cast(value.get()); +} + +std::string codepoint_to_utf8(char32_t codepoint) { + std::string result; + if (codepoint <= 0x7F) { + result.push_back(static_cast(codepoint)); + } else if (codepoint <= 0x7FF) { + result.push_back(static_cast(0xC0 | ((codepoint >> 6) & 0x1F))); + result.push_back(static_cast(0x80 | (codepoint & 0x3F))); + } else { + result.push_back(static_cast(0xE0 | ((codepoint >> 12) & 0x0F))); + result.push_back(static_cast(0x80 | ((codepoint >> 6) & 0x3F))); + result.push_back(static_cast(0x80 | (codepoint & 0x3F))); + } + return result; +} + +char32_t next_codepoint(std::string_view text, std::size_t& position) { + const auto first = static_cast(text[position++]); + if (first < 0x80) + return first; + + int continuation_count = 0; + char32_t codepoint = 0; + if ((first & 0xE0) == 0xC0) { + continuation_count = 1; + codepoint = first & 0x1F; + } else if ((first & 0xF0) == 0xE0) { + continuation_count = 2; + codepoint = first & 0x0F; + } else if ((first & 0xF8) == 0xF0) { + continuation_count = 3; + codepoint = first & 0x07; + } else { + schema_error("contains an invalid byte-level vocabulary token"); + } + + if (position + static_cast(continuation_count) > text.size()) + schema_error("contains a truncated byte-level vocabulary token"); + for (int index = 0; index < continuation_count; ++index) { + const auto next = static_cast(text[position++]); + if ((next & 0xC0) != 0x80) + schema_error("contains an invalid byte-level vocabulary token"); + codepoint = (codepoint << 6) | (next & 0x3F); + } + return codepoint; +} + +struct ByteEncoderTables { + std::array byte_to_token; + std::unordered_map token_to_byte; + + ByteEncoderTables() { + std::array direct{}; + for (int byte = 33; byte <= 126; ++byte) + direct[static_cast(byte)] = true; + for (int byte = 161; byte <= 172; ++byte) + direct[static_cast(byte)] = true; + for (int byte = 174; byte <= 255; ++byte) + direct[static_cast(byte)] = true; + + int displaced = 0; + for (int byte = 0; byte < 256; ++byte) { + const char32_t codepoint = direct[static_cast(byte)] + ? static_cast(byte) + : static_cast(256 + displaced++); + byte_to_token[static_cast(byte)] = codepoint_to_utf8(codepoint); + token_to_byte.emplace(codepoint, static_cast(byte)); + } + } +}; + +const ByteEncoderTables& byte_tables() { + static const ByteEncoderTables tables; + return tables; +} + +std::string lossy_utf8(std::string_view bytes) { + constexpr std::string_view replacement = "\xEF\xBF\xBD"; + const auto continuation = [](unsigned char byte) { return (byte & 0xC0U) == 0x80U; }; + std::string result; + result.reserve(bytes.size()); + + std::size_t position = 0; + while (position < bytes.size()) { + const auto first = static_cast(bytes[position]); + if (first < 0x80U) { + result.push_back(bytes[position++]); + continue; + } + + std::size_t length = 0; + if (first >= 0xC2U && first <= 0xDFU) { + length = 2; + } else if (first >= 0xE0U && first <= 0xEFU) { + length = 3; + } else if (first >= 0xF0U && first <= 0xF4U) { + length = 4; + } else { + result += replacement; + ++position; + continue; + } + + if (position + 1 >= bytes.size()) { + result += replacement; + break; + } + const auto second = static_cast(bytes[position + 1]); + const bool second_valid = continuation(second) && !(first == 0xE0U && second < 0xA0U) && + !(first == 0xEDU && second >= 0xA0U) && + !(first == 0xF0U && second < 0x90U) && + !(first == 0xF4U && second >= 0x90U); + if (!second_valid) { + result += replacement; + ++position; + continue; + } + + if (length >= 3) { + if (position + 2 >= bytes.size()) { + result += replacement; + break; + } + if (!continuation(static_cast(bytes[position + 2]))) { + result += replacement; + position += 2; + continue; + } + } + if (length == 4) { + if (position + 3 >= bytes.size()) { + result += replacement; + break; + } + if (!continuation(static_cast(bytes[position + 3]))) { + result += replacement; + position += 3; + continue; + } + } + + result.append(bytes.substr(position, length)); + position += length; + } + return result; +} + +// tokenizers normalizes with the Unicode 9.0 tables of its NFC crate and matches the Split pattern +// with Oniguruma's Unicode 16.0 tables; ICU's own tables (Unicode 15.1 in ICU 74) are pinned to +// both. NFC only touches code points that Unicode 9.0 assigns: a later code point is a starter +// without a decomposition in those tables, so it stays and normalization does not cross it. The +// letter, mark and number classes are ICU's up to Unicode 16.0 plus the code points that +// Unicode 16.0 assigns to them after Unicode 15.0; \s is White_Space in both. +static_assert(U_ICU_VERSION_MAJOR_NUM >= 72, + "the Unicode 16.0 additions below start from ICU 72's Unicode 15.0 tables"); +constexpr std::string_view kLetters16 = + R"(\x{1C89}-\x{1C8A}\x{A7CB}-\x{A7CD}\x{A7DA}-\x{A7DC}\x{105C0}-\x{105F3}\x{10D4A}-\x{10D65})" + R"(\x{10D6F}-\x{10D85}\x{10EC2}-\x{10EC4}\x{11380}-\x{11389}\x{1138B}\x{1138E})" + R"(\x{11390}-\x{113B5}\x{113B7}\x{113D1}\x{113D3}\x{11BC0}-\x{11BE0}\x{13460}-\x{143FA})" + R"(\x{16100}-\x{1611D}\x{16D40}-\x{16D6C}\x{18CFF}\x{1E5D0}-\x{1E5ED}\x{1E5F0})" + R"(\x{2EBF0}-\x{2EE5D})"; +constexpr std::string_view kMarks16 = + R"(\x{897}\x{10D69}-\x{10D6D}\x{10EFC}\x{113B8}-\x{113C0}\x{113C2}\x{113C5}\x{113C7}-\x{113CA})" + R"(\x{113CC}-\x{113D0}\x{113D2}\x{113E1}-\x{113E2}\x{11F5A}\x{1611E}-\x{1612F})" + R"(\x{1E5EE}-\x{1E5EF})"; +constexpr std::string_view kNumbers16 = + R"(\x{10D40}-\x{10D49}\x{116D0}-\x{116E3}\x{11BF0}-\x{11BF9}\x{16130}-\x{16139})" + R"(\x{16D70}-\x{16D79}\x{1CCF0}-\x{1CCF9}\x{1E5F1}-\x{1E5FA})"; + +struct Unicode9Nfc { + icu::UnicodeSet assigned; + icu::FilteredNormalizer2 normalizer; + Unicode9Nfc(const icu::Normalizer2& nfc, UErrorCode& status) + : assigned(icu::UnicodeString(u"[:age=9.0:]"), status), normalizer(nfc, assigned) { + assigned.freeze(); + } +}; + +const icu::Normalizer2& unicode9_nfc() { + static const auto value = [] { + UErrorCode status = U_ZERO_ERROR; + const auto* nfc = icu::Normalizer2::getNFCInstance(status); + if (U_FAILURE(status)) + schema_error("cannot initialize NFC normalization"); + auto pinned = std::make_unique(*nfc, status); + if (U_FAILURE(status)) + schema_error("cannot build the Unicode 9.0 character set"); + return pinned; + }(); + return value->normalizer; +} + +// kPretokenizerPattern with \p{L}, \p{M} and \p{N} replaced by their Unicode 16.0 classes. +std::string unicode16_split_pattern() { + std::string pattern(kPretokenizerPattern); + for (const auto& [property, additions] : + {std::pair{std::string_view("L"), kLetters16}, std::pair{std::string_view("M"), kMarks16}, + std::pair{std::string_view("N"), kNumbers16}}) { + const std::string name = "\\p{" + std::string(property) + "}"; + const std::string pinned = "[[" + name + "&&\\p{Age=16.0}]" + std::string(additions) + "]"; + for (auto at = pattern.find(name); at != std::string::npos; + at = pattern.find(name, at + pinned.size())) + pattern.replace(at, name.size(), pinned); + } + return pattern; +} + +// Calls `piece` with each pre-tokenized piece of the normalized text, in order, until it returns +// false. +template +void for_each_piece(std::string_view text, Callback&& piece) { + UErrorCode status = U_ZERO_ERROR; + icu::UnicodeString normalized; + unicode9_nfc().normalize( + icu::UnicodeString::fromUTF8(icu::StringPiece(text.data(), text.size())), normalized, + status); + if (U_FAILURE(status)) + schema_error("cannot normalize prompt text"); + + static const auto pattern = [] { + UErrorCode code = U_ZERO_ERROR; + std::unique_ptr value(icu::RegexPattern::compile( + icu::UnicodeString::fromUTF8(unicode16_split_pattern()), 0, code)); + if (U_FAILURE(code)) + schema_error("cannot compile the pinned Unicode Split pattern"); + return value; + }(); + std::unique_ptr matcher(pattern->matcher(normalized, status)); + while (U_SUCCESS(status) && matcher->find(status)) { + std::string value; + matcher->group(status).toUTF8String(value); + if (U_FAILURE(status) || !piece(value)) + break; + } + if (U_FAILURE(status)) + schema_error("cannot split prompt text"); +} + +std::vector split_text(std::string_view text) { + std::vector result; + for_each_piece(text, [&](const std::string& piece) { + result.push_back(piece); + return true; + }); + return result; +} + +struct PairHash { + std::size_t operator()(const std::pair& pair) const { + const std::size_t first = std::hash{}(pair.first); + const std::size_t second = std::hash{}(pair.second); + return first ^ (second + 0x9e3779b9U + (first << 6U) + (first >> 2U)); + } +}; + +class BpeTokenizer final : public Tokenizer { + public: + static std::unique_ptr create(const char* data, std::size_t size) { + if (data == nullptr || size == 0) + schema_error("is empty"); + auto tokenizer = std::unique_ptr(new BpeTokenizer()); + tokenizer->parse(data, size); + return tokenizer; + } + + std::optional> encode(std::string_view text, + std::size_t limit) const override { + if (code_points(text) > max_code_points(limit)) + return std::nullopt; + std::vector result; + for (const auto& segment : split_added_tokens(text)) { + if (segment.added_id >= 0) + result.push_back(segment.added_id); + else + encode_text(segment.text, limit, result); + if (result.size() > limit) + return std::nullopt; + } + return result; + } + + std::size_t max_code_points(std::size_t tokens) const override { + constexpr std::size_t kLongestComposition = 4; + const std::size_t per_token = kLongestComposition * longest_token_; + if (tokens > std::numeric_limits::max() / per_token) + return std::numeric_limits::max(); + return tokens * per_token; + } + + std::string decode(const std::vector& ids) const override { + std::string bytes; + const auto& reverse = byte_tables().token_to_byte; + for (const std::int32_t id : ids) { + if (id < 0 || id >= static_cast(vocabulary_.size())) + throw std::invalid_argument("MiniCPM-V 4.6 token ID is outside the vocabulary"); + if (special_ids_.count(id) != 0) + continue; + // ByteLevel decoding maps each character of a token back to its byte; a token + // with a character outside the byte alphabet (an added token) keeps its own + // UTF-8 bytes whole, as Hugging Face tokenizers do. + const auto& token = vocabulary_[static_cast(id)]; + std::string mapped; + bool byte_level = true; + for (std::size_t position = 0; position < token.size() && byte_level;) { + const auto found = reverse.find(next_codepoint(token, position)); + byte_level = found != reverse.end(); + if (byte_level) + mapped.push_back(static_cast(found->second)); + } + bytes += byte_level ? mapped : token; + } + // Hugging Face tokenizers decode byte-level output with Rust's + // String::from_utf8_lossy; match its replacement grouping. + return lossy_utf8(bytes); + } + + std::int32_t id_for_token(std::string_view token) const override { + const auto found = token_to_id_.find(std::string(token)); + return found == token_to_id_.end() ? -1 : found->second; + } + + std::int32_t vocabulary_size() const override { + return static_cast(vocabulary_.size()); + } + + private: + struct Segment { + std::string text; + std::int32_t added_id{-1}; + }; + + BpeTokenizer() = default; + + static void validate_byte_level(const nlohmann::json& value, const char* what) { + require_schema(value.is_object() && value.size() == 4 && value.at("type") == "ByteLevel" && + value.at("add_prefix_space") == false && + value.at("trim_offsets") == false && value.at("use_regex") == false, + std::string("must use the pinned ByteLevel ") + what); + } + + static void validate_schema(const nlohmann::json& root) { + require_schema(root.is_object() && root.size() == 9, "has an unexpected top-level shape"); + require_schema(root.at("version") == "1.0" && root.at("truncation").is_null() && + root.at("padding").is_null(), + "uses unsupported version, truncation, or padding"); + const auto& normalizer = root.at("normalizer"); + require_schema(normalizer.is_object() && normalizer.size() == 1 && + normalizer.at("type") == "NFC", + "must use the NFC normalizer"); + const auto& pre = root.at("pre_tokenizer"); + require_schema(pre.is_object() && pre.size() == 2 && pre.at("type") == "Sequence", + "must use a Sequence pre-tokenizer"); + const auto& stages = pre.at("pretokenizers"); + require_schema(stages.is_array() && stages.size() == 2, + "must contain exactly the Split and ByteLevel stages"); + const auto& split = stages.at(0); + require_schema(split.is_object() && split.size() == 4 && split.at("type") == "Split" && + split.at("behavior") == "Isolated" && split.at("invert") == false && + split.at("pattern").is_object() && split.at("pattern").size() == 1 && + split.at("pattern").at("Regex") == kPretokenizerPattern, + "does not match the pinned Unicode Split pattern"); + validate_byte_level(stages.at(1), "pre-tokenizer"); + validate_byte_level(root.at("post_processor"), "post-processor"); + validate_byte_level(root.at("decoder"), "decoder"); + const auto& model = root.at("model"); + require_schema(model.is_object() && model.size() == 10 && model.at("type") == "BPE" && + model.at("dropout").is_null() && model.at("unk_token").is_null() && + model.at("continuing_subword_prefix") == "" && + model.at("end_of_word_suffix") == "" && model.at("fuse_unk") == false && + model.at("byte_fallback") == false && model.at("ignore_merges") == false, + "must use a byte-level BPE model"); + require_schema(model.at("vocab").is_object() && !model.at("vocab").empty() && + model.at("merges").is_array(), + "has no BPE vocabulary or merges"); + } + + void parse(const char* data, std::size_t size) { + nlohmann::json root; + try { + root = parse_json_unique(data, size, "tokenizer.json"); + validate_schema(root); + parse_vocabulary(root.at("model").at("vocab")); + parse_added_tokens(root.at("added_tokens")); + parse_merges(root.at("model").at("merges")); + for (const auto& token : vocabulary_) + longest_token_ = std::max(longest_token_, code_points(token)); + } catch (const nlohmann::json::exception& error) { + schema_error(std::string("is invalid: ") + error.what()); + } + } + + void parse_vocabulary(const nlohmann::json& values) { + require_schema(values.size() < + static_cast(std::numeric_limits::max()), + "has too many vocabulary entries"); + base_size_ = static_cast(values.size()); + vocabulary_.resize(static_cast(base_size_)); + token_to_id_.reserve(values.size()); + std::vector seen(values.size()); + for (const auto& [token, value] : values.items()) { + const auto id = token_id(value, base_size_, "vocabulary ID"); + require_schema(!seen[static_cast(id)], + "contains a duplicate vocabulary ID"); + seen[static_cast(id)] = true; + vocabulary_[static_cast(id)] = token; + token_to_id_.emplace(token, id); + } + for (const auto& token : byte_tables().byte_to_token) + require_schema(token_to_id_.count(token) == 1, + "base vocabulary is missing a byte-level token"); + } + + void parse_added_tokens(const nlohmann::json& values) { + require_schema(values.is_array() && !values.empty(), "has no added tokens"); + for (std::size_t index = 0; index < values.size(); ++index) { + const auto& value = values.at(index); + require_schema(value.is_object() && value.size() == 7, + "contains an invalid added-token entry"); + const auto id = token_id(value.at("id"), std::numeric_limits::max(), + "added-token ID"); + const auto content = value.at("content").get(); + // Added tokens follow the dense base vocabulary and are matched verbatim. + require_schema(id == base_size_ + static_cast(index) && + !content.empty() && value.at("single_word") == false && + value.at("lstrip") == false && value.at("rstrip") == false && + value.at("normalized") == false, + "contains an unsupported added-token contract"); + vocabulary_.push_back(content); + require_schema(token_to_id_.emplace(content, id).second, + "contains duplicate added-token content"); + if (value.at("special").get()) + special_ids_.insert(id); + added_tokens_.emplace_back(content, id); + } + std::stable_sort(added_tokens_.begin(), added_tokens_.end(), + [](const auto& left, const auto& right) { + return left.first.size() > right.first.size(); + }); + } + + void parse_merges(const nlohmann::json& values) { + merge_rank_.reserve(values.size()); + for (std::size_t index = 0; index < values.size(); ++index) { + const auto& value = values.at(index); + require_schema(value.is_array() && value.size() == 2 && value.at(0).is_string() && + value.at(1).is_string(), + "contains an invalid BPE merge"); + auto pair = + std::make_pair(value.at(0).get(), value.at(1).get()); + // Both operands and their concatenation are base-vocabulary tokens. + for (const auto* token : {&pair.first, &pair.second}) { + const auto found = token_to_id_.find(*token); + require_schema(found != token_to_id_.end() && found->second < base_size_, + "contains a BPE merge of a token outside the base vocabulary"); + } + const auto merged = token_to_id_.find(pair.first + pair.second); + require_schema(merged != token_to_id_.end() && merged->second < base_size_, + "contains a BPE merge whose result is outside the base vocabulary"); + require_schema(merge_rank_.emplace(std::move(pair), static_cast(index)).second, + "contains a duplicate BPE merge"); + } + } + + // Leftmost-longest match of the verbatim added tokens, as Hugging Face tokenizers do. + std::vector split_added_tokens(std::string_view text) const { + std::vector result; + std::size_t position = 0; + while (position < text.size()) { + const auto found = + std::find_if(added_tokens_.begin(), added_tokens_.end(), [&](const auto& token) { + return token.first.size() <= text.size() - position && + text.compare(position, token.first.size(), token.first) == 0; + }); + if (found != added_tokens_.end()) { + result.push_back({found->first, found->second}); + position += found->first.size(); + continue; + } + if (result.empty() || result.back().added_id >= 0) + result.push_back({}); + result.back().text.push_back(text[position++]); + } + return result; + } + + static std::vector byte_encode(std::string_view text) { + std::vector result; + result.reserve(text.size()); + for (const unsigned char byte : text) + result.push_back(byte_tables().byte_to_token[byte]); + return result; + } + + // Hugging Face tokenizers' BPE: apply the lowest-rank merge at its leftmost position, one + // occurrence at a time, and re-evaluate the pairs it forms with its neighbors after each + // merge (a queue entry whose pair has changed since it was queued is skipped). + std::vector apply_merges(std::vector symbols) const { + const std::size_t count = symbols.size(); + if (count < 2) + return symbols; + constexpr std::size_t kNone = std::numeric_limits::max(); + std::vector previous(count), next(count); + std::vector alive(count, true); + for (std::size_t i = 0; i < count; ++i) { + previous[i] = i == 0 ? kNone : i - 1; + next[i] = i + 1 < count ? i + 1 : kNone; + } + struct Entry { + int rank; + std::size_t position; + std::string merged; + }; + const auto later = [](const Entry& left, const Entry& right) { + return left.rank != right.rank ? left.rank > right.rank + : left.position > right.position; + }; + std::priority_queue, decltype(later)> queue(later); + const auto push = [&](std::size_t left) { + if (left == kNone || next[left] == kNone) + return; + const auto found = merge_rank_.find({symbols[left], symbols[next[left]]}); + if (found != merge_rank_.end()) + queue.push({found->second, left, symbols[left] + symbols[next[left]]}); + }; + for (std::size_t i = 0; i + 1 < count; ++i) + push(i); + while (!queue.empty()) { + const Entry top = queue.top(); + queue.pop(); + if (!alive[top.position] || next[top.position] == kNone) + continue; + const std::size_t right = next[top.position]; + if (merge_rank_.count({symbols[top.position], symbols[right]}) == 0 || + symbols[top.position] + symbols[right] != top.merged) + continue; + symbols[top.position] = top.merged; + alive[right] = false; + next[top.position] = next[right]; + if (next[right] != kNone) + previous[next[right]] = top.position; + push(previous[top.position]); + push(top.position); + } + std::vector result; + for (std::size_t i = 0; i < count; ++i) + if (alive[i]) + result.push_back(std::move(symbols[i])); + return result; + } + + // Appends the ids of the text, piece by piece, until `result` holds more than `limit` ids. + void encode_text(std::string_view text, std::size_t limit, + std::vector& result) const { + for_each_piece(text, [&](const std::string& word) { + for (const auto& token : apply_merges(byte_encode(word))) { + const auto found = token_to_id_.find(token); + if (found == token_to_id_.end()) + schema_error("cannot encode a byte-level BPE token"); + result.push_back(found->second); + } + return result.size() <= limit; + }); + } + + std::int32_t base_size_{0}; + std::size_t longest_token_{1}; // code points of the longest vocabulary or added token + std::vector vocabulary_; + std::unordered_map token_to_id_; + std::unordered_map, int, PairHash> merge_rank_; + std::unordered_set special_ids_; + std::vector> added_tokens_; +}; + +} // namespace + +std::string utf8_lossy(std::string_view bytes) { + return lossy_utf8(bytes); +} + +std::size_t code_points(std::string_view text) { + const auto* bytes = reinterpret_cast(text.data()); + const auto length = static_cast(text.size()); + std::size_t count = 0; + for (std::int64_t position = 0; position < length; ++count) { + UChar32 value = 0; + // Advances past one code point, or past the maximal ill-formed subpart that ICU's UTF-8 + // conversion replaces with one U+FFFD. + U8_NEXT(bytes, position, length, value); + static_cast(value); + } + return count; +} + +std::vector pre_tokenize(std::string_view text) { + return split_text(text); +} + +std::unique_ptr create_tokenizer(const char* tokenizer_json, std::size_t size) { + return BpeTokenizer::create(tokenizer_json, size); +} + +} // namespace trtmc::minicpmv4_6 diff --git a/families/minicpmv4_6/runtime/decoder.cpp b/families/minicpmv4_6/runtime/decoder.cpp new file mode 100644 index 0000000000..337d3ffb6b --- /dev/null +++ b/families/minicpmv4_6/runtime/decoder.cpp @@ -0,0 +1,164 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/minicpmv4_6/runtime/decoder.h" + +#include "families/minicpmv4_6/runtime/engine_io.h" + +#include +#include +#include +#include +#include +#include + +namespace trtmc::minicpmv4_6 { +namespace { + +double elapsed_ms(std::chrono::steady_clock::time_point start) { + return std::chrono::duration(std::chrono::steady_clock::now() - start) + .count(); +} + +// Argument order is unspecified: never dereference a module that failed to load. +cudaStream_t stream_of(const ITrtModule* module) { + return module ? module->stream() : nullptr; +} + +// Validate both engines before the decoder state allocates its buffers. +const DecoderGeometry& checked_engines(const DecoderGeometry& geometry, const ITrtModule* decoder, + const ITrtModule* prefill, std::int32_t vocab_size, + std::int32_t hidden_size) { + if (decoder == nullptr || !decoder->ok() || prefill == nullptr || !prefill->ok()) + throw std::runtime_error("MiniCPM-V 4.6 decoder engines failed to load"); + if (prefill->stream() != decoder->stream()) + throw std::runtime_error("MiniCPM-V 4.6 prefill and decoder engines must share a stream"); + validate_decoder_engine(*decoder, geometry, false, vocab_size, hidden_size); + validate_decoder_engine(*prefill, geometry, true, vocab_size, hidden_size); + prefill_rows(*prefill, geometry, hidden_size); + return geometry; +} + +} // namespace + +Decoder::Decoder(std::unique_ptr decoder, std::unique_ptr prefill, + const DecoderGeometry& geometry, std::int32_t vocab_size, std::int32_t hidden_size) + : decoder_(std::move(decoder)), prefill_(std::move(prefill)), + state_(checked_engines(geometry, decoder_.get(), prefill_.get(), vocab_size, hidden_size), + stream_of(decoder_.get())), + vocab_size_(vocab_size), hidden_size_(hidden_size), + prefill_rows_(prefill_rows(*prefill_, geometry, hidden_size)), dtype_(geometry.cache_dtype) {} + +void Decoder::copy_logits(const ITrtModule& module, std::vector& logits) { + const void* device = module.device_ptr("logits"); + if (device == nullptr) + throw std::runtime_error("MiniCPM-V 4.6 engine has no logits output"); + logits.resize(static_cast(vocab_size_)); + const auto status = + cudaMemcpy(logits.data(), device, logits.size() * sizeof(float), cudaMemcpyDeviceToHost); + if (status != cudaSuccess) + throw std::runtime_error(std::string("MiniCPM-V 4.6 logits copy failed: ") + + cudaGetErrorString(status)); +} + +void Decoder::prefill(const PromptRows& prompt, std::vector& logits) { + const auto row_bytes = static_cast(hidden_size_) * dtype_size(dtype_); + const auto total = static_cast(prompt.token_ids.size()); + state_.bind_prefill(*prefill_); + try { + for (std::int32_t start = 0; start < total; start += prefill_rows_) { + const std::int32_t rows = std::min(prefill_rows_, total - start); + chunk_features_.assign(static_cast(rows) * row_bytes, 0); + chunk_selector_.assign(static_cast(rows), 0); + for (std::int32_t i = 0; i < rows; ++i) { + const auto feature = prompt.feature_rows[static_cast(start + i)]; + if (feature < 0) + continue; + chunk_selector_[static_cast(i)] = 1; + std::memcpy(chunk_features_.data() + static_cast(i) * row_bytes, + prompt.features.data() + static_cast(feature) * row_bytes, + row_bytes); + } + TensorMap inputs; + inputs["token_id"] = Tensor{ + const_cast(prompt.token_ids.data() + start), {rows}, DType::kInt32}; + inputs["visual_embedding"] = + Tensor{chunk_features_.data(), {rows, hidden_size_}, dtype_}; + inputs["use_visual_embedding"] = + Tensor{chunk_selector_.data(), {rows, 1}, DType::kInt32}; + state_.prepare(inputs, rows); + prefill_->forward_async(inputs); + state_.commit_prefill(*prefill_, rows); + } + prefill_->sync(); + } catch (...) { + // Queued launches may still read request buffers: drain before unwinding. + try { + prefill_->sync(); + } catch (...) { + } + throw; + } + copy_logits(*prefill_, logits); +} + +void Decoder::step(std::int32_t token, std::vector& logits) { + TensorMap inputs; + inputs["token_id"] = Tensor{&token, {1}, DType::kInt32}; + state_.prepare(inputs, 1); + decoder_->forward_async(inputs); + decoder_->sync(); + copy_logits(*decoder_, logits); + state_.commit_decoder(); +} + +Generation Decoder::generate(const PromptRows& prompt, std::int32_t max_new_tokens, + const std::vector& eos_ids, Sampler& sampler) { + const auto count = prompt.token_ids.size(); + const auto row_bytes = static_cast(hidden_size_) * dtype_size(dtype_); + if (count == 0 || prompt.feature_rows.size() != count || prompt.features.size() % row_bytes) + throw std::invalid_argument("MiniCPM-V 4.6 prompt rows are inconsistent"); + if (max_new_tokens <= 0) + throw std::invalid_argument("MiniCPM-V 4.6 max_new_tokens must be positive"); + if (static_cast(count) + max_new_tokens > state_.capacity()) + throw std::invalid_argument("MiniCPM-V 4.6 prompt of " + std::to_string(count) + + " tokens plus " + std::to_string(max_new_tokens) + + " new tokens exceeds the bundle's " + + std::to_string(state_.capacity()) + "-token capacity"); + const auto feature_count = static_cast(prompt.features.size() / row_bytes); + for (std::size_t i = 0; i < count; ++i) + if (prompt.token_ids[i] < 0 || prompt.token_ids[i] >= vocab_size_ || + prompt.feature_rows[i] < -1 || prompt.feature_rows[i] >= feature_count) + throw std::invalid_argument("MiniCPM-V 4.6 prompt has an invalid token or feature row"); + + Generation result; + std::vector logits; + state_.reset(); + auto start = std::chrono::steady_clock::now(); + prefill(prompt, logits); + result.prefill_ms = elapsed_ms(start); + start = std::chrono::steady_clock::now(); + state_.bind_decoder(*decoder_); + try { + for (std::int32_t index = 0; index < max_new_tokens; ++index) { + const std::int32_t token = sampler.sample(logits); + result.token_ids.push_back(token); + if (std::find(eos_ids.begin(), eos_ids.end(), token) != eos_ids.end() || + index + 1 == max_new_tokens) + break; + step(token, logits); + } + } catch (...) { + try { + decoder_->sync(); + } catch (...) { + } + throw; + } + result.decode_ms = elapsed_ms(start); + return result; +} + +} // namespace trtmc::minicpmv4_6 diff --git a/families/minicpmv4_6/runtime/decoder.h b/families/minicpmv4_6/runtime/decoder.h new file mode 100644 index 0000000000..578d303b62 --- /dev/null +++ b/families/minicpmv4_6/runtime/decoder.h @@ -0,0 +1,57 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include "families/minicpmv4_6/runtime/sampler.h" +#include "families/minicpmv4_6/runtime/state.h" +#include "trtmc/runtime/trt_module.h" + +#include +#include +#include + +namespace trtmc::minicpmv4_6 { + +// Prompt rows: a token id per row and, for vision rows, the index of the +// feature row (in `features`, [rows, hidden] at the decoder precision) that +// replaces the token embedding; -1 for text rows. +struct PromptRows { + std::vector token_ids; + std::vector feature_rows; + std::vector features; +}; + +struct Generation { + std::vector token_ids; // generated tokens only + double prefill_ms{0.0}, decode_ms{0.0}; +}; + +// The hybrid decoder: chunked prefill (prefill.plan) then one-token decoding +// (engine.plan) on one CUDA stream. +class Decoder { + public: + Decoder(std::unique_ptr decoder, std::unique_ptr prefill, + const DecoderGeometry& geometry, std::int32_t vocab_size, std::int32_t hidden_size); + + Generation generate(const PromptRows& prompt, std::int32_t max_new_tokens, + const std::vector& eos_ids, Sampler& sampler); + std::int32_t capacity() const { return state_.capacity(); } + DType precision() const { return dtype_; } + + private: + void prefill(const PromptRows& prompt, std::vector& logits); + void step(std::int32_t token, std::vector& logits); + void copy_logits(const ITrtModule& module, std::vector& logits); + + std::unique_ptr decoder_, prefill_; + DecoderState state_; + std::int32_t vocab_size_{0}, hidden_size_{0}, prefill_rows_{0}; + DType dtype_{DType::kFloat16}; + std::vector chunk_features_; + std::vector chunk_selector_; +}; + +} // namespace trtmc::minicpmv4_6 diff --git a/families/minicpmv4_6/runtime/engine_io.cpp b/families/minicpmv4_6/runtime/engine_io.cpp new file mode 100644 index 0000000000..2f859ae629 --- /dev/null +++ b/families/minicpmv4_6/runtime/engine_io.cpp @@ -0,0 +1,196 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/minicpmv4_6/runtime/engine_io.h" + +#include +#include +#include +#include + +namespace trtmc::minicpmv4_6 { +namespace { + +struct Expected { + std::string name; + DType dtype; + std::vector shape; +}; + +std::string indexed(const char* stem, std::int32_t index) { + return std::string(stem) + "_" + std::to_string(index); +} + +// Each tensor's dtype, rank and static dimensions. The module reports a tensor at its current +// shape (a dynamic input at its profile's opt shape until a launch sets another, an output at the +// shape that follows), so a dimension expected as -1 is not compared: such an input must be +// dynamic, and its profile is checked separately (prefill_rows, validate_vision_engine). +void check_side(const ITrtModule& module, const std::vector& expected, bool input, + const char* engine) { + const auto actual = input ? module.input_info() : module.output_info(); + if (actual.size() != expected.size()) + throw std::runtime_error(std::string("MiniCPM-V 4.6 ") + engine + " engine has " + + std::to_string(actual.size()) + + (input ? " inputs, expected " : " outputs, expected ") + + std::to_string(expected.size())); + for (const auto& tensor : expected) { + bool matches = input ? module.has_input(tensor.name) : module.has_output(tensor.name); + matches = matches && module.tensor_dtype(tensor.name) == tensor.dtype; + const auto shape = matches ? module.tensor_shape(tensor.name) : std::vector{}; + matches = matches && shape.size() == tensor.shape.size(); + bool dynamic = false; + for (std::size_t i = 0; matches && i < shape.size(); ++i) { + dynamic = dynamic || tensor.shape[i] < 0; + matches = tensor.shape[i] < 0 || shape[i] == tensor.shape[i]; + } + if (matches && input) + matches = module.input_is_dynamic(tensor.name) == dynamic; + if (!matches) + throw std::runtime_error(std::string("MiniCPM-V 4.6 ") + engine + " engine tensor " + + tensor.name + " disagrees with the bundle metadata"); + } +} + +void check_positive(std::int64_t value, const char* what) { + if (value <= 0) + throw std::invalid_argument(std::string("MiniCPM-V 4.6 ") + what + " must be positive"); +} + +} // namespace + +void validate_decoder_engine(const ITrtModule& module, const DecoderGeometry& geometry, + bool prefill, std::int32_t vocab_size, std::int32_t hidden_size) { + for (const auto value : {geometry.attention_layers, geometry.deltanet_layers, geometry.kv_width, + geometry.conv_width, geometry.conv_kernel, geometry.deltanet_heads, + geometry.deltanet_head_dim, vocab_size, hidden_size}) + check_positive(value, "decoder geometry"); + if (geometry.capacity <= 1) + throw std::invalid_argument("MiniCPM-V 4.6 decoder capacity must exceed one row"); + const char* engine = prefill ? "prefill" : "decoder"; + const int64_t rows = prefill ? -1 : 1; + const DType cache = geometry.cache_dtype; + const std::vector conv{geometry.conv_width, geometry.conv_kernel}; + const std::vector ssm{geometry.deltanet_heads, geometry.deltanet_head_dim, + geometry.deltanet_head_dim}; + const std::vector kv_cache{geometry.capacity, geometry.kv_width}; + const std::vector kv_rows{rows, geometry.kv_width}; + + std::vector inputs{ + {"token_id", DType::kInt32, {rows}}, + {"position_id", DType::kInt32, {rows}}, + {"attention_mask", + DType::kFloat32, + {rows, prefill ? int64_t{-1} : int64_t{geometry.capacity} + 1}}, + }; + if (prefill) { + inputs.push_back({"visual_embedding", cache, {-1, hidden_size}}); + inputs.push_back({"use_visual_embedding", DType::kInt32, {-1, 1}}); + } + std::vector outputs{{"logits", DType::kFloat32, {1, vocab_size}}}; + for (std::int32_t i = 0; i < geometry.deltanet_layers; ++i) { + inputs.push_back({indexed("conv_state", i), DType::kFloat32, conv}); + inputs.push_back({indexed("ssm_state", i), DType::kFloat32, ssm}); + outputs.push_back({indexed("present_conv", i), DType::kFloat32, conv}); + outputs.push_back({indexed("present_ssm", i), DType::kFloat32, ssm}); + } + for (std::int32_t i = 0; i < geometry.attention_layers; ++i) { + inputs.push_back({indexed("cache_k", i), cache, kv_cache}); + inputs.push_back({indexed("cache_v", i), cache, kv_cache}); + outputs.push_back({indexed("present_k", i), cache, kv_rows}); + outputs.push_back({indexed("present_v", i), cache, kv_rows}); + } + check_side(module, inputs, true, engine); + check_side(module, outputs, false, engine); +} + +void validate_vision_engine(const ITrtModule& module, DType feature_dtype, std::int32_t patch_width, + std::int32_t hidden_size, std::int32_t max_patches) { + check_positive(patch_width, "patch width"); + check_positive(hidden_size, "hidden size"); + if (max_patches < 16 || max_patches % 16) + throw std::invalid_argument("MiniCPM-V 4.6 vision patch capacity must be a multiple of 16"); + check_side(module, + {{"patches", DType::kFloat32, {-1, patch_width}}, + {"position_ids", DType::kInt32, {-1}}, + {"window_index", DType::kInt32, {-1}}, + {"merge_index", DType::kInt32, {-1}}}, + true, "vision"); + check_side(module, {{"visual_features", feature_dtype, {-1, hidden_size}}}, false, "vision"); + // A slice has 16 (one 4 x 4 block) to max_patches patches and a quarter as many merged rows; + // the profile must admit both ends. + const auto profile = module.profile_idx(); + const struct { + const char* name; + std::vector smallest, largest; + } inputs[] = { + {"patches", {16, patch_width}, {max_patches, patch_width}}, + {"position_ids", {16}, {max_patches}}, + {"window_index", {16}, {max_patches}}, + {"merge_index", {4}, {max_patches / 4}}, + }; + for (const auto& input : inputs) { + const auto minimum = + module.input_profile_shape(input.name, profile, ProfileShapeSelector::kMin); + bool admitted = minimum.size() == input.smallest.size() && + module.input_profile_shape(input.name, profile, + ProfileShapeSelector::kMax) == input.largest; + for (std::size_t i = 0; admitted && i < minimum.size(); ++i) + admitted = minimum[i] <= input.smallest[i]; + if (!admitted) + throw std::runtime_error(std::string("MiniCPM-V 4.6 vision engine profile of ") + + input.name + " does not admit slices of 16 to " + + std::to_string(max_patches) + " patches"); + } +} + +std::int32_t prefill_rows(const ITrtModule& prefill, const DecoderGeometry& geometry, + std::int32_t hidden_size) { + const std::int64_t capacity = geometry.capacity; + const auto profile = prefill.profile_idx(); + const auto rows = prefill.input_profile_shape("token_id", profile, ProfileShapeSelector::kMax); + if (rows.size() != 1 || rows[0] < 1 || rows[0] > capacity || + prefill.input_profile_shape("token_id", profile, ProfileShapeSelector::kMin) != + std::vector{1}) + throw std::runtime_error("MiniCPM-V 4.6 prefill engine has an invalid row profile"); + // A chunk of r rows binds these shapes (DecoderState::prepare, Decoder::prefill); the profile + // must admit them for every r from one to the most rows. + const int64_t most = rows[0]; + const struct { + const char* name; + std::vector one, all; + } chunks[] = { + {"position_id", {1}, {most}}, + {"attention_mask", {1, capacity + 1}, {most, capacity + most}}, + {"visual_embedding", {1, hidden_size}, {most, hidden_size}}, + {"use_visual_embedding", {1, 1}, {most, 1}}, + }; + for (const auto& chunk : chunks) { + const auto minimum = + prefill.input_profile_shape(chunk.name, profile, ProfileShapeSelector::kMin); + const auto maximum = + prefill.input_profile_shape(chunk.name, profile, ProfileShapeSelector::kMax); + bool admitted = minimum.size() == chunk.one.size() && maximum.size() == chunk.all.size(); + for (std::size_t i = 0; admitted && i < chunk.one.size(); ++i) + admitted = minimum[i] <= chunk.one[i] && maximum[i] >= chunk.all[i]; + if (!admitted) + throw std::runtime_error(std::string("MiniCPM-V 4.6 prefill engine profile of ") + + chunk.name + " does not admit chunks of 1 to " + + std::to_string(most) + " rows"); + } + // The module sizes each output for the profile's largest inputs and reports that shape at load; + // commit_prefill copies up to `most` rows of present K/V from these buffers. + for (std::int32_t i = 0; i < geometry.attention_layers; ++i) + for (const char* stem : {"present_k", "present_v"}) { + const auto name = indexed(stem, i); + const auto shape = prefill.tensor_shape(name); + if (shape.size() != 2 || shape[0] < most || shape[1] != geometry.kv_width) + throw std::runtime_error("MiniCPM-V 4.6 prefill engine output " + name + + " does not hold a chunk of " + std::to_string(most) + + " rows"); + } + return static_cast(most); +} + +} // namespace trtmc::minicpmv4_6 diff --git a/families/minicpmv4_6/runtime/engine_io.h b/families/minicpmv4_6/runtime/engine_io.h new file mode 100644 index 0000000000..df018bfe6e --- /dev/null +++ b/families/minicpmv4_6/runtime/engine_io.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/minicpmv4_6/runtime/state.h" +#include "trtmc/runtime/trt_module.h" + +#include + +namespace trtmc::minicpmv4_6 { + +// The exact tensor contract of a decoder engine (one-token decoder, or the +// chunked prefill when `prefill`): every input and output by name, dtype and +// shape, and no other tensor. Checked at load, before any buffer is bound. +void validate_decoder_engine(const ITrtModule& module, const DecoderGeometry& geometry, + bool prefill, std::int32_t vocab_size, std::int32_t hidden_size); + +// The most rows of one prefill chunk: the token profile starts at one row and ends within the +// capacity, the profiles of the other chunk inputs admit every chunk from one row to that many, and +// the present K/V outputs hold that many rows. +std::int32_t prefill_rows(const ITrtModule& prefill, const DecoderGeometry& geometry, + std::int32_t hidden_size); + +// The per-slice vision engine: patches, grid indices and the projected features. +void validate_vision_engine(const ITrtModule& module, DType feature_dtype, std::int32_t patch_width, + std::int32_t hidden_size, std::int32_t max_patches); + +} // namespace trtmc::minicpmv4_6 diff --git a/families/minicpmv4_6/runtime/image.cpp b/families/minicpmv4_6/runtime/image.cpp new file mode 100644 index 0000000000..80217f2b95 --- /dev/null +++ b/families/minicpmv4_6/runtime/image.cpp @@ -0,0 +1,488 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +// Image slicing and resampling adapted from the MiniCPM-V 4.6 image processor +// of Hugging Face Transformers 5.22.2 (src/transformers/models/minicpmv4_6/ +// image_processing_minicpmv4_6.py) and from the PyTorch antialiased uint8 +// resampling it calls (aten/src/ATen/native/cpu/UpSampleKernel.cpp); see NOTICE. + +#include "families/minicpmv4_6/runtime/image.h" + +#include +#include +#include +#include +#include + +namespace trtmc::minicpmv4_6 { +namespace { + +// Python round(): ties to even. +std::int64_t round_half_even(double value) { + const double floor = std::floor(value); + const double fraction = value - floor; + auto result = static_cast(floor); + if (fraction > 0.5 || (fraction == 0.5 && (result & 1) != 0)) + ++result; + return result; +} + +// max(round(length / divisor) * divisor, divisor) +std::int64_t ensure_divide(double length, std::int64_t divisor) { + return std::max(round_half_even(length / static_cast(divisor)) * divisor, + divisor); +} + +// find_best_resize(): area-preserving resize to scale_resolution, then the +// 16x mode's divisibility (patch x 4 pixels). +std::pair best_resize(double height, double width, + std::int32_t scale_resolution, + std::int32_t patch_size, bool allow_upscale) { + const double limit = static_cast(scale_resolution) * scale_resolution; + if (height * width > limit || allow_upscale) { + const double aspect_ratio = width / height; + height = static_cast( + static_cast(scale_resolution / std::sqrt(aspect_ratio))); + width = static_cast(static_cast(height * aspect_ratio)); + } + const std::int64_t divisor = static_cast(patch_size) * 4; + return {ensure_divide(height, divisor), ensure_divide(width, divisor)}; +} + +// get_sliced_grid(): {rows, cols}, or {0, 0} for an image that is not sliced. +std::pair sliced_grid(std::int32_t height, std::int32_t width, + std::int32_t max_slice_nums, + std::int32_t scale_resolution) { + const double log_ratio = std::log(static_cast(width) / height); + const double ratio = static_cast(width) * height / + (static_cast(scale_resolution) * scale_resolution); + // validate() bounds max_slice_nums, and with it this search; int64 keeps multiple + 1 in range. + const auto multiple = + static_cast(std::min(std::ceil(ratio), max_slice_nums)); + if (multiple <= 1) + return {0, 0}; + std::pair best{1, 1}; + double min_error = std::numeric_limits::infinity(); + for (const std::int64_t slices : {multiple - 1, multiple, multiple + 1}) { + if (slices == 1 || slices > max_slice_nums) + continue; + for (std::int64_t rows = 1; rows <= slices; ++rows) { + if (slices % rows != 0) + continue; + const std::int64_t cols = slices / rows; + const double error = std::fabs( + log_ratio - std::log(static_cast(cols) / static_cast(rows))); + if (error < min_error) { + best = {rows, cols}; + min_error = error; + } else if (error == min_error && rows > best.first) { + best = {rows, cols}; + } + } + } + // Both factors divide a slice count that does not exceed max_slice_nums. + return {static_cast(best.first), static_cast(best.second)}; +} + +std::int32_t checked_int(std::int64_t value, const char* what) { + if (value <= 0 || value > std::numeric_limits::max()) + throw std::invalid_argument(std::string("MiniCPM-V 4.6 image ") + what + + " is out of range"); + return static_cast(value); +} + +// Keys cubic convolution with a = -0.5. +double keys_cubic(double x) { + constexpr double a = -0.5; + x = std::fabs(x); + if (x < 1.0) + return ((a + 2) * x - (a + 3)) * x * x + 1; + if (x < 2.0) + return ((a * x - 5 * a) * x + 8 * a) * x - 4 * a; + return 0.0; +} + +struct Taps { + std::vector first, count; + std::vector weights; // [output, width] + std::int64_t width{0}; + unsigned precision{0}; +}; + +Taps antialias_taps(std::int64_t input_size, std::int64_t output_size) { + const double scale = static_cast(input_size) / static_cast(output_size); + const double support = scale >= 1.0 ? 2.0 * scale : 2.0; + Taps taps; + taps.width = static_cast(std::ceil(support)) * 2 + 1; + taps.first.resize(static_cast(output_size)); + taps.count.resize(static_cast(output_size)); + std::vector real(static_cast(output_size * taps.width), 0.0); + double max_weight = 0.0; + const double invscale = scale >= 1.0 ? 1.0 / scale : 1.0; + for (std::int64_t i = 0; i < output_size; ++i) { + const double center = scale * (static_cast(i) + 0.5); + const std::int64_t first = + std::max(static_cast(center - support + 0.5), std::int64_t{0}); + std::int64_t count = + std::min(static_cast(center + support + 0.5), input_size) - first; + count = std::clamp(count, std::int64_t{0}, taps.width); + double* row = real.data() + i * taps.width; + double total = 0.0; + for (std::int64_t j = 0; j < count; ++j) { + row[j] = keys_cubic((static_cast(j + first) - center + 0.5) * invscale); + total += row[j]; + } + if (total != 0.0) { + for (std::int64_t j = 0; j < count; ++j) { + row[j] /= total; + max_weight = std::max(max_weight, row[j]); + } + } + taps.first[static_cast(i)] = first; + taps.count[static_cast(i)] = count; + } + for (taps.precision = 0; taps.precision < 22; ++taps.precision) { + const int next = static_cast(0.5 + max_weight * (1 << (taps.precision + 1))); + if (next >= (1 << 15)) + break; + } + taps.weights.resize(real.size()); + for (std::size_t k = 0; k < real.size(); ++k) { + const double value = real[k] * (1 << taps.precision); + taps.weights[k] = static_cast(value < 0 ? static_cast(-0.5 + value) + : static_cast(0.5 + value)); + } + return taps; +} + +std::uint8_t clamp_pixel(int value, unsigned precision) { + return static_cast(std::clamp(value >> precision, 0, 255)); +} + +// The number of channel values of a nonempty RGB8 or RGB float view whose storage matches its +// int32 dimensions. The slice plan is computed from the dimensions, so they are checked first. +std::uint64_t checked_values(const internal::ImageView& image) { + if (image.data == nullptr || image.height == 0 || image.width == 0 || image.channels != 3 || + (image.format != internal::ImageFormat::UInt8 && + image.format != internal::ImageFormat::Float32)) + throw std::invalid_argument("MiniCPM-V 4.6 requires nonempty RGB8 or RGB float images"); + constexpr auto kMaxSide = static_cast(std::numeric_limits::max()); + if (image.height > kMaxSide || image.width > kMaxSide) + throw std::invalid_argument("MiniCPM-V 4.6 image dimensions are too large"); + // Both sides are below 2^31, so the count stays below 2^64. + const std::uint64_t count = static_cast(image.height) * image.width * 3; + const std::size_t element = image.format == internal::ImageFormat::UInt8 ? 1 : sizeof(float); + if (count > std::numeric_limits::max() / element || + image.byte_size != count * element) + throw std::invalid_argument("MiniCPM-V 4.6 RGB storage does not match image dimensions"); + return count; +} + +std::vector rgb8(const internal::ImageView& image) { + const std::uint64_t count = checked_values(image); + std::vector pixels(static_cast(count)); + if (image.format == internal::ImageFormat::UInt8) { + std::memcpy(pixels.data(), image.data, pixels.size()); + return pixels; + } + const auto* source = static_cast(image.data); + for (std::size_t i = 0; i < pixels.size(); ++i) { + float value; + std::memcpy(&value, source + i * sizeof(float), sizeof(float)); + if (!std::isfinite(value) || value < 0.0F || value > 1.0F) + throw std::invalid_argument("MiniCPM-V 4.6 RGB float pixels must be finite in [0, 1]"); + pixels[i] = static_cast(std::lround(value * 255.0F)); + } + return pixels; +} + +// Normalized patches of one RGB8 crop, channel-major inside each patch as the +// reference packs them for its patch convolution. +std::vector patchify(const ImageSettings& settings, const std::vector& pixels, + std::int32_t image_width, std::int32_t top, std::int32_t left, + std::int32_t height, std::int32_t width) { + const std::int32_t p = settings.patch_size; + const std::int32_t rows = height / p, cols = width / p; + const std::size_t patch_width = static_cast(3) * p * p; + // The reference fuses rescale (1 / 255) into mean and std in FP32. + const float scale = static_cast(1.0 / (1.0 / 255.0)); + std::array mean{}, stddev{}; + for (int c = 0; c < 3; ++c) { + mean[c] = settings.mean[c] * scale; + stddev[c] = settings.stddev[c] * scale; + } + std::vector result(static_cast(rows) * cols * patch_width); + std::size_t out = 0; + for (std::int32_t py = 0; py < rows; ++py) + for (std::int32_t px = 0; px < cols; ++px) + for (int c = 0; c < 3; ++c) + for (std::int32_t y = 0; y < p; ++y) + for (std::int32_t x = 0; x < p; ++x) { + const std::size_t source = + (static_cast(top + py * p + y) * image_width + + (left + px * p + x)) * + 3 + + c; + result[out++] = (static_cast(pixels[source]) - mean[c]) / stddev[c]; + } + return result; +} + +VisionSlice make_slice(const ImageSettings& settings, const std::vector& pixels, + std::int32_t image_width, std::int32_t top, std::int32_t left, + std::int32_t height, std::int32_t width) { + VisionSlice slice; + slice.height = height / settings.patch_size; + slice.width = width / settings.patch_size; + if (height % settings.patch_size || width % settings.patch_size || slice.height % 4 || + slice.width % 4) + throw std::logic_error("MiniCPM-V 4.6 slice is not a whole number of 4 x 4 patch blocks"); + if (static_cast(slice.height) * slice.width > settings.max_patches) + throw std::invalid_argument( + "MiniCPM-V 4.6 image slice exceeds the vision engine's patch capacity; use a less " + "elongated image"); + slice.patches = patchify(settings, pixels, image_width, top, left, height, width); + slice.position_ids = + bucket_position_ids(slice.height, slice.width, settings.positions_per_side); + slice.window_index = block_order(slice.height, slice.width); + slice.merge_index = block_order(slice.height / 2, slice.width / 2); + return slice; +} + +} // namespace + +void ImageSettings::validate() const { + if (patch_size <= 0 || positions_per_side <= 1 || + scale_resolution < std::int64_t{4} * patch_size || max_slice_nums <= 0 || + max_slice_nums > kMaxSliceNums || max_patches < 16) + throw std::invalid_argument("Invalid MiniCPM-V 4.6 image settings"); + // A slice at the nominal resolution must fit the vision engine. + const std::int64_t side = scale_resolution / patch_size; + if (side * side > max_patches) + throw std::invalid_argument( + "MiniCPM-V 4.6 scale_resolution exceeds the vision engine's patch capacity"); + // patchify() normalizes 0..255 pixels as (pixel - mean * 255) / (std * 255) in FP32; both + // ends must stay finite and inside FP16, the narrowest type of the vision engine. + constexpr float kFp16Max = 65504.0F; + for (int c = 0; c < 3; ++c) { + const float offset = mean[c] * 255.0F, scale = stddev[c] * 255.0F; + if (!std::isfinite(mean[c]) || !std::isfinite(stddev[c]) || !std::isfinite(offset) || + !std::isfinite(scale) || !(scale > 0.0F)) + throw std::invalid_argument("Invalid MiniCPM-V 4.6 image normalization"); + for (const float pixel : {0.0F, 255.0F}) { + const float value = (pixel - offset) / scale; + if (!std::isfinite(value) || std::fabs(value) > kFp16Max) + throw std::invalid_argument( + "MiniCPM-V 4.6 image normalization leaves the FP16 range"); + } + } +} + +SlicePlan plan_slices(const ImageSettings& settings, std::int32_t height, std::int32_t width) { + settings.validate(); + if (height <= 0 || width <= 0) + throw std::invalid_argument("MiniCPM-V 4.6 image dimensions must be positive"); + SlicePlan plan; + const auto grid = + sliced_grid(height, width, settings.max_slice_nums, settings.scale_resolution); + const bool sliced = grid.first > 0; + const auto source = best_resize(height, width, settings.scale_resolution, settings.patch_size, + /*allow_upscale=*/!sliced); + plan.source_height = checked_int(source.first, "height"); + plan.source_width = checked_int(source.second, "width"); + if (!sliced) + return plan; + plan.rows = grid.first; + plan.cols = grid.second; + // get_refine_size(): the grid divides the image before the per-slice resize. + const std::int64_t refine_width = ensure_divide(width, plan.cols); + const std::int64_t refine_height = ensure_divide(height, plan.rows); + const auto cell = best_resize(static_cast(refine_height) / plan.rows, + static_cast(refine_width) / plan.cols, + settings.scale_resolution, settings.patch_size, + /*allow_upscale=*/true); + plan.refine_height = checked_int(cell.first * plan.rows, "slice height"); + plan.refine_width = checked_int(cell.second * plan.cols, "slice width"); + return plan; +} + +std::vector resize_rgb8(const std::uint8_t* pixels, std::int32_t height, + std::int32_t width, std::int32_t out_height, + std::int32_t out_width) { + if (height <= 0 || width <= 0 || out_height <= 0 || out_width <= 0) + throw std::invalid_argument("MiniCPM-V 4.6 resize dimensions must be positive"); + std::vector current(pixels, + pixels + static_cast(height) * width * 3); + std::int32_t current_width = width; + if (out_width != width) { + const auto taps = antialias_taps(width, out_width); + std::vector next(static_cast(height) * out_width * 3); + for (std::int32_t y = 0; y < height; ++y) + for (std::int32_t x = 0; x < out_width; ++x) { + const auto first = taps.first[static_cast(x)]; + const auto count = taps.count[static_cast(x)]; + const std::int16_t* weights = taps.weights.data() + x * taps.width; + for (int c = 0; c < 3; ++c) { + int sum = 1 << (taps.precision - 1); + for (std::int64_t j = 0; j < count; ++j) + sum += current[(static_cast(y) * width + first + j) * 3 + c] * + weights[j]; + next[(static_cast(y) * out_width + x) * 3 + c] = + clamp_pixel(sum, taps.precision); + } + } + current = std::move(next); + current_width = out_width; + } + if (out_height != height) { + const auto taps = antialias_taps(height, out_height); + std::vector next(static_cast(out_height) * current_width * 3); + for (std::int32_t y = 0; y < out_height; ++y) { + const auto first = taps.first[static_cast(y)]; + const auto count = taps.count[static_cast(y)]; + const std::int16_t* weights = taps.weights.data() + y * taps.width; + for (std::int32_t x = 0; x < current_width; ++x) + for (int c = 0; c < 3; ++c) { + int sum = 1 << (taps.precision - 1); + for (std::int64_t j = 0; j < count; ++j) + sum += current[((first + j) * current_width + x) * 3 + c] * weights[j]; + next[(static_cast(y) * current_width + x) * 3 + c] = + clamp_pixel(sum, taps.precision); + } + } + current = std::move(next); + } + return current; +} + +std::vector bucket_position_ids(std::int32_t height, std::int32_t width, + std::int32_t side) { + if (height <= 0 || width <= 0 || side <= 1) + throw std::invalid_argument("MiniCPM-V 4.6 position grid must be positive"); + // torch.arange(1 / side, 1.0, 1 / side) on the GPU: the size is computed in + // double, each element as an FP32 fused multiply-add start + step * i. + const double step = 1.0 / side; + const auto count = static_cast(std::ceil((1.0 - step) / step)); + const float start = static_cast(step); + std::vector boundaries(static_cast(count)); + for (std::int64_t i = 0; i < count; ++i) + boundaries[static_cast(i)] = std::fmaf(start, static_cast(i), start); + // arange(n) / n on the GPU multiplies by the FP32 reciprocal; bucketize(right=True) + // returns the number of boundaries not greater than the coordinate. + auto buckets = [&](std::int32_t n) { + const float reciprocal = 1.0F / static_cast(n); + std::vector result(static_cast(n)); + for (std::int32_t k = 0; k < n; ++k) { + const float coordinate = static_cast(k) * reciprocal; + result[static_cast(k)] = static_cast( + std::upper_bound(boundaries.begin(), boundaries.end(), coordinate) - + boundaries.begin()); + } + return result; + }; + const auto rows = buckets(height), cols = buckets(width); + std::vector ids(static_cast(height) * width); + for (std::int32_t y = 0; y < height; ++y) + for (std::int32_t x = 0; x < width; ++x) + ids[static_cast(y) * width + x] = + rows[static_cast(y)] * side + cols[static_cast(x)]; + return ids; +} + +std::vector block_order(std::int32_t height, std::int32_t width) { + if (height <= 0 || width <= 0 || height % 2 || width % 2) + throw std::invalid_argument("MiniCPM-V 4.6 block grid must be even and positive"); + std::vector order; + order.reserve(static_cast(height) * width); + for (std::int32_t by = 0; by < height; by += 2) + for (std::int32_t bx = 0; bx < width; bx += 2) + for (std::int32_t dy = 0; dy < 2; ++dy) + for (std::int32_t dx = 0; dx < 2; ++dx) + order.push_back((by + dy) * width + bx + dx); + return order; +} + +SlicePlan plan_image(const ImageSettings& settings, const internal::ImageView& image) { + checked_values(image); + return plan_slices(settings, static_cast(image.height), + static_cast(image.width)); +} + +std::int64_t planned_rows(const ImageSettings& settings, const SlicePlan& plan) { + // One vision row per 4 x 4 block of patches (VisionSlice::tokens()). + const auto rows = [&](std::int64_t height, std::int64_t width) { + return (height / settings.patch_size) * (width / settings.patch_size) / 16; + }; + std::int64_t total = rows(plan.source_height, plan.source_width); + if (plan.rows > 0) + total += static_cast(plan.rows) * plan.cols * + rows(plan.refine_height / plan.rows, plan.refine_width / plan.cols); + return total; +} + +PreparedImage prepare_image(const ImageSettings& settings, const internal::ImageView& image) { + const auto height = static_cast(image.height); + const auto width = static_cast(image.width); + const auto plan = plan_image(settings, image); + // Check every planned slice before any resize allocates it. + const auto check_patches = [&](std::int64_t slice_height, std::int64_t slice_width) { + if ((slice_height / settings.patch_size) * (slice_width / settings.patch_size) > + settings.max_patches) + throw std::invalid_argument( + "MiniCPM-V 4.6 image slice exceeds the vision engine's patch capacity; use a less " + "elongated image"); + }; + check_patches(plan.source_height, plan.source_width); + if (plan.rows > 0) + check_patches(plan.refine_height / plan.rows, plan.refine_width / plan.cols); + // Only an image whose slices fit is copied and converted. + const auto pixels = rgb8(image); + PreparedImage result; + result.rows = plan.rows; + result.cols = plan.cols; + const auto source = + resize_rgb8(pixels.data(), height, width, plan.source_height, plan.source_width); + result.slices.push_back(make_slice(settings, source, plan.source_width, 0, 0, + plan.source_height, plan.source_width)); + if (plan.rows == 0) + return result; + const auto refined = + resize_rgb8(pixels.data(), height, width, plan.refine_height, plan.refine_width); + const std::int32_t slice_height = plan.refine_height / plan.rows; + const std::int32_t slice_width = plan.refine_width / plan.cols; + for (std::int32_t row = 0; row < plan.rows; ++row) + for (std::int32_t col = 0; col < plan.cols; ++col) + result.slices.push_back(make_slice(settings, refined, plan.refine_width, + row * slice_height, col * slice_width, slice_height, + slice_width)); + return result; +} + +std::string image_placeholder(const PreparedImage& image, std::int32_t image_index) { + if (image.slices.empty() || + image.slices.size() != 1 + static_cast(image.rows) * image.cols) + throw std::logic_error("MiniCPM-V 4.6 prepared image has an inconsistent slice grid"); + auto pads = [](std::int32_t count) { + std::string text; + text.reserve(static_cast(count) * 13); + for (std::int32_t i = 0; i < count; ++i) + text += "<|image_pad|>"; + return text; + }; + std::string text = "" + std::to_string(image_index) + "" + + pads(image.slices.front().tokens()) + ""; + for (std::int32_t row = 0; row < image.rows; ++row) { + if (row > 0) + text += "\n"; + for (std::int32_t col = 0; col < image.cols; ++col) + text += + "" + + pads(image.slices[1 + static_cast(row) * image.cols + col].tokens()) + + ""; + } + return text; +} + +} // namespace trtmc::minicpmv4_6 diff --git a/families/minicpmv4_6/runtime/image.h b/families/minicpmv4_6/runtime/image.h new file mode 100644 index 0000000000..4be16f20d2 --- /dev/null +++ b/families/minicpmv4_6/runtime/image.h @@ -0,0 +1,81 @@ +/* + * 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 +#include +#include +#include + +namespace trtmc::minicpmv4_6 { + +// The largest max_slice_nums the runtime accepts (the builder applies the same bound). Slice grids +// are planned before any pixel work, in time linear in this bound; 4096 slices of the nominal +// 448-pixel size (64 rows each) already fill the decoder's 262144 positions. +inline constexpr std::int32_t kMaxSliceNums = 4096; + +// Image-processor settings recorded in the bundle (vision.json). +struct ImageSettings { + std::int32_t patch_size{14}; + std::int32_t positions_per_side{70}; + std::int32_t scale_resolution{448}; + std::int32_t max_slice_nums{9}; + std::int32_t max_patches{4096}; + std::array mean{0.5F, 0.5F, 0.5F}; + std::array stddev{0.5F, 0.5F, 0.5F}; + void validate() const; +}; + +// Source thumbnail size and optional slice grid of one image (pixels). +struct SlicePlan { + std::int32_t source_height{0}, source_width{0}; + std::int32_t rows{0}, cols{0}; // 0 x 0 when the image is not sliced + std::int32_t refine_height{0}, refine_width{0}; +}; + +// One vision-engine launch: a patch grid with its pixel patches and grid indices. +struct VisionSlice { + std::int32_t height{0}, width{0}; // patch grid, both multiples of four + std::vector patches; // [h * w, 3 * patch * patch], channel-major per patch + std::vector position_ids; // [h * w] learned-position rows + std::vector window_index; // [h * w] patches in 2 x 2 window order + std::vector merge_index; // [h * w / 4] merged tokens in projector block order + std::int32_t tokens() const { return height * width / 16; } +}; + +struct PreparedImage { + std::vector slices; // source thumbnail first, then the grid slices row-major + std::int32_t rows{0}, cols{0}; +}; + +// Reference slicing arithmetic (16x token compression). +SlicePlan plan_slices(const ImageSettings& settings, std::int32_t height, std::int32_t width); + +// The slice plan of an image view (its dimensions checked), and the vision rows the plan produces. +SlicePlan plan_image(const ImageSettings& settings, const internal::ImageView& image); +std::int64_t planned_rows(const ImageSettings& settings, const SlicePlan& plan); + +// Separable antialiased Keys bicubic (a = -0.5) on RGB8 HWC data with int16 +// fixed-point weights, horizontal pass first and rounding to RGB8 after each +// pass, as the reference resamples uint8 images. +std::vector resize_rgb8(const std::uint8_t* pixels, std::int32_t height, + std::int32_t width, std::int32_t out_height, + std::int32_t out_width); + +// Learned-position rows of a patch grid (reference bucketing, GPU arithmetic). +std::vector bucket_position_ids(std::int32_t height, std::int32_t width, + std::int32_t side); +// Indices of a grid in 2 x 2 block order: blocks row-major, (dy, dx) inside. +std::vector block_order(std::int32_t height, std::int32_t width); + +PreparedImage prepare_image(const ImageSettings& settings, const internal::ImageView& image); + +// Provider placeholder text of one image (local index `image_index` in the request). +std::string image_placeholder(const PreparedImage& image, std::int32_t image_index); + +} // namespace trtmc::minicpmv4_6 diff --git a/families/minicpmv4_6/runtime/metadata.cpp b/families/minicpmv4_6/runtime/metadata.cpp new file mode 100644 index 0000000000..0206cea1da --- /dev/null +++ b/families/minicpmv4_6/runtime/metadata.cpp @@ -0,0 +1,115 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/minicpmv4_6/runtime/metadata.h" + +#include +#include +#include +#include +#include +#include + +namespace trtmc::minicpmv4_6 { +namespace { + +using Json = nlohmann::json; + +[[noreturn]] void fail(const std::string& what, const char* rule) { + throw std::runtime_error("MiniCPM-V 4.6 metadata " + what + " " + rule); +} + +const Json& field(const Json& object, const char* name) { + if (!object.is_object() || !object.contains(name) || object.at(name).is_null()) + fail(name, "is missing"); + return object.at(name); +} + +std::int32_t int32_value(const Json& value, const std::string& what, std::int64_t minimum) { + constexpr auto kMax = std::numeric_limits::max(); + if (!value.is_number_integer()) + fail(what, "must be an integer"); + if (value.is_number_unsigned()) { + const auto number = value.get(); + if (number > static_cast(kMax) || + static_cast(number) < minimum) + fail(what, "is out of range"); + return static_cast(number); + } + const auto number = value.get(); + if (number < minimum || number > kMax) + fail(what, "is out of range"); + return static_cast(number); +} + +} // namespace + +std::int32_t json_int32(const Json& object, const char* name, std::int32_t minimum) { + return int32_value(field(object, name), name, minimum); +} + +std::array json_float3(const Json& object, const char* name) { + const auto& value = field(object, name); + if (!value.is_array() || value.size() != 3) + fail(name, "must hold exactly three numbers"); + std::array result{}; + for (std::size_t i = 0; i < 3; ++i) { + if (!value[i].is_number()) + fail(name, "must hold exactly three numbers"); + const auto number = value[i].get(); + if (!std::isfinite(number) || std::fabs(number) > std::numeric_limits::max()) + fail(name, "must hold finite FP32 values"); + result[i] = static_cast(number); + } + return result; +} + +std::vector json_token_ids(const Json& object, const char* name, + std::int32_t vocab_size) { + const auto& value = field(object, name); + if (!value.is_array() || value.empty()) + fail(name, "must be a nonempty list of token ids"); + std::vector ids; + std::unordered_set seen; + for (const auto& item : value) { + const auto id = int32_value(item, name, 0); + if (id >= vocab_size) + fail(name, "addresses a token outside the vocabulary"); + if (!seen.insert(id).second) + fail(name, "repeats a token id"); + ids.push_back(id); + } + return ids; +} + +std::int32_t checked_product(std::int32_t a, std::int32_t b, const char* what) { + const auto product = static_cast(a) * b; + if (a <= 0 || b <= 0 || product > std::numeric_limits::max()) + fail(what, "is out of range"); + return static_cast(product); +} + +Json parse_json_unique(const char* data, std::size_t size, const std::string& what) { + std::vector> keys; + const Json::parser_callback_t unique = [&](int, Json::parse_event_t event, Json& parsed) { + if (event == Json::parse_event_t::object_start) { + keys.emplace_back(); + } else if (event == Json::parse_event_t::object_end) { + keys.pop_back(); + } else if (event == Json::parse_event_t::key && + !keys.back().insert(parsed.get()).second) { + throw std::runtime_error("MiniCPM-V 4.6 " + what + " repeats the key " + parsed.dump()); + } + return true; + }; + return Json::parse(data, data + size, unique); +} + +void check_vocabulary(std::int32_t tokenizer_size, std::int32_t embedding_rows) { + if (tokenizer_size <= 0 || tokenizer_size > embedding_rows) + throw std::runtime_error("MiniCPM-V 4.6 tokenizer ids exceed the decoder's embedding rows"); +} + +} // namespace trtmc::minicpmv4_6 diff --git a/families/minicpmv4_6/runtime/metadata.h b/families/minicpmv4_6/runtime/metadata.h new file mode 100644 index 0000000000..d3a5b21d88 --- /dev/null +++ b/families/minicpmv4_6/runtime/metadata.h @@ -0,0 +1,40 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace trtmc::minicpmv4_6 { + +// Strict readers of the bundle's JSON metadata. Each requires the JSON type +// (a boolean is not a number, a fraction is not an integer) and checks the +// range before narrowing; a missing key or an explicit null is an error. + +// An integer field in [minimum, INT32_MAX]. +std::int32_t json_int32(const nlohmann::json& object, const char* name, std::int32_t minimum); + +// Exactly three finite numbers that FP32 represents. +std::array json_float3(const nlohmann::json& object, const char* name); + +// A nonempty list of distinct token ids in [0, vocab_size). +std::vector json_token_ids(const nlohmann::json& object, const char* name, + std::int32_t vocab_size); + +// a * b, or an error when the product leaves int32. +std::int32_t checked_product(std::int32_t a, std::int32_t b, const char* what); + +// Parse JSON text; an object that repeats a key is an error (nlohmann would keep the last value). +nlohmann::json parse_json_unique(const char* data, std::size_t size, const std::string& what); + +// The tokenizer's ids must address rows of the embedding table; a padded table may have more rows. +void check_vocabulary(std::int32_t tokenizer_size, std::int32_t embedding_rows); + +} // namespace trtmc::minicpmv4_6 diff --git a/families/minicpmv4_6/runtime/plugin.cpp b/families/minicpmv4_6/runtime/plugin.cpp new file mode 100644 index 0000000000..7ca8d317d2 --- /dev/null +++ b/families/minicpmv4_6/runtime/plugin.cpp @@ -0,0 +1,426 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/minicpmv4_6/runtime/decoder.h" +#include "families/minicpmv4_6/runtime/image.h" +#include "families/minicpmv4_6/runtime/metadata.h" +#include "families/minicpmv4_6/runtime/prompt.h" +#include "families/minicpmv4_6/runtime/tokenizer.h" +#include "families/minicpmv4_6/runtime/vision_encoder.h" +#include "trtmc/internal/language.h" +#include "trtmc/internal/model.h" +#include "trtmc/internal/text.h" +#include "trtmc/runtime/family_factory.h" +#include "trtmc/runtime/trt_backend.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc::minicpmv4_6 { +namespace { + +namespace api = trtmc::internal; +using Json = nlohmann::json; + +constexpr const char* kImagePad = "<|image_pad|>"; +constexpr const char* kVideoPad = "<|video_pad|>"; + +std::vector section(const BundleReader& bundle, std::string_view name) { + const auto* info = bundle.find_section(name); + if (info == nullptr || info->length == 0) + throw std::runtime_error("MiniCPM-V 4.6 bundle section is missing or empty: " + + std::string(name)); + return bundle.read_section(name); +} + +Json json_section(const BundleReader& bundle, std::string_view name) { + const auto data = section(bundle, name); + auto value = parse_json_unique(data.data(), data.size(), std::string(name)); + if (!value.is_object()) + throw std::runtime_error("MiniCPM-V 4.6 " + std::string(name) + " must be a JSON object"); + return value; +} + +std::unique_ptr load_engine(IBackend& backend, const BundleReader& bundle, + std::string_view name, const ModuleCreateOptions& options) { + const auto plan = section(bundle, name); + auto module = backend.create_module(plan.data(), plan.size(), options); + if (!module || !module->ok()) + throw std::runtime_error("MiniCPM-V 4.6 failed to load " + std::string(name)); + module->set_timing_label("minicpmv4_6 " + std::string(name)); + return module; +} + +// Generation options of both Tasks; text continuation adds use_chat_template. +const std::vector& common_fields() { + static const std::vector fields{ + {"max_new_tokens", api::ConfigKind::I64, std::int64_t{128}, "Generated token budget"}, + {"temperature", api::ConfigKind::F64, 1.0, "Sampling temperature; 0 is greedy"}, + {"top_k", api::ConfigKind::I64, std::int64_t{1}, + "Top-k sampling; 1 is greedy, 0 keeps all"}, + {"top_p", api::ConfigKind::F64, 1.0, "Nucleus sampling probability mass"}, + {"seed", api::ConfigKind::I64, std::int64_t{-1}, "Sampling seed; -1 uses a fixed default"}, + {"enable_thinking", api::ConfigKind::Bool, false, "Chat template thinking mode"}, + }; + return fields; +} + +const std::vector& text_fields() { + static const std::vector fields = [] { + auto copy = common_fields(); + copy.push_back({"use_chat_template", api::ConfigKind::Bool, false, + "Format the prefix as one user message with the chat template"}); + return copy; + }(); + return fields; +} + +Span span(const std::vector& fields) { + return {fields.data(), fields.size()}; +} + +struct Options { + std::int32_t max_new_tokens{128}; + SamplingOptions sampling; + bool enable_thinking{false}; + bool use_chat_template{false}; +}; + +Options read_options(api::ConfigView supplied, const std::vector& fields) { + const auto schema = span(fields); + api::validate_config(schema, supplied); + Options options; + const auto max_new = *api::config_get(supplied, schema, "max_new_tokens"); + if (max_new <= 0 || max_new > std::numeric_limits::max()) + throw std::invalid_argument("MiniCPM-V 4.6 max_new_tokens must be a positive int32"); + options.max_new_tokens = static_cast(max_new); + options.sampling = sampling_options(*api::config_get(supplied, schema, "temperature"), + *api::config_get(supplied, schema, "top_k"), + *api::config_get(supplied, schema, "top_p"), + *api::config_get(supplied, schema, "seed")); + options.enable_thinking = *api::config_get(supplied, schema, "enable_thinking"); + if (api::find_config_field(schema, "use_chat_template")) + options.use_chat_template = *api::config_get(supplied, schema, "use_chat_template"); + return options; +} + +double since_ms(std::chrono::steady_clock::time_point start) { + return std::chrono::duration(std::chrono::steady_clock::now() - start) + .count(); +} + +class Model final : public internal::IModel, + public internal::IImagesTextToText, + public internal::ITextContinuation { + public: + explicit Model(const FamilyContext& context) { + const auto& bundle = context.reader; + if (bundle.info().task != api::IImagesTextToText::kTask) + throw std::runtime_error("MiniCPM-V 4.6 bundles have the images_text_to_text task"); + const auto runtime = json_section(bundle, "runtime.json"); + vision_ = json_section(bundle, "vision.json"); + if (json_int32(vision_, "schema_version", 1) != 1) + throw std::runtime_error("Unsupported MiniCPM-V 4.6 vision.json schema"); + const auto precision = runtime.at("precision").get(); + if ((precision != "fp16" && precision != "fp32") || vision_.at("precision") != precision) + throw std::runtime_error("MiniCPM-V 4.6 bundle precision metadata disagrees"); + const DType dtype = precision == "fp16" ? DType::kFloat16 : DType::kFloat32; + + DecoderGeometry geometry; + geometry.attention_layers = json_int32(runtime, "num_attention_layers", 1); + geometry.deltanet_layers = json_int32(runtime, "num_mamba_layers", 1); + geometry.kv_width = + checked_product(json_int32(runtime, "num_key_value_heads", 1), + json_int32(runtime, "head_dim", 1), "num_key_value_heads x head_dim"); + geometry.conv_width = json_int32(runtime, "conv_dim", 1); + geometry.conv_kernel = json_int32(runtime, "mamba_d_conv", 1); + geometry.deltanet_heads = json_int32(runtime, "mamba_nheads", 1); + geometry.deltanet_head_dim = json_int32(runtime, "mamba_head_dim", 1); + geometry.capacity = json_int32(runtime, "max_cache_length", 2); + geometry.cache_dtype = dtype; + const auto hidden = json_int32(runtime, "hidden_size", 1); + const auto vocab = json_int32(runtime, "vocab_size", 1); + if (json_int32(vision_, "capacity", 1) != geometry.capacity || + json_int32(vision_, "hidden_size", 1) != hidden) + throw std::runtime_error("MiniCPM-V 4.6 vision.json disagrees with runtime.json"); + eos_ids_ = json_token_ids(runtime, "eos_token_id", vocab); + + settings_.patch_size = json_int32(vision_, "patch_size", 1); + settings_.positions_per_side = json_int32(vision_, "positions_per_side", 1); + settings_.scale_resolution = json_int32(vision_, "scale_resolution", 1); + settings_.max_slice_nums = json_int32(vision_, "max_slice_nums", 1); + settings_.max_patches = json_int32(vision_, "max_patches", 1); + settings_.mean = json_float3(vision_, "mean"); + settings_.stddev = json_float3(vision_, "stddev"); + settings_.validate(); + for (const char* mode : {"false", "true"}) + validate_recipe(vision_.at("prompts").at(mode)); + + const auto tokenizer_json = section(bundle, "tokenizer.json"); + tokenizer_ = create_tokenizer(tokenizer_json.data(), tokenizer_json.size()); + check_vocabulary(tokenizer_->vocabulary_size(), vocab); + const auto& ids = vision_.at("token_ids"); + if (!ids.is_object() || ids.size() != 7) + throw std::runtime_error( + "MiniCPM-V 4.6 vision.json token_ids must name the seven markup tokens"); + for (const auto& [name, text] : + std::vector>{{"image_pad", kImagePad}, + {"image_start", ""}, + {"image_end", ""}, + {"slice_start", ""}, + {"slice_end", ""}, + {"image_id_start", ""}, + {"image_id_end", ""}}) + if (const auto id = json_int32(ids, name, 0); + id >= vocab || tokenizer_->id_for_token(text) != id) + throw std::runtime_error("MiniCPM-V 4.6 tokenizer disagrees with vision.json"); + image_pad_ = json_int32(ids, "image_pad", 0); + + auto decoder = load_engine(context.backend, bundle, "engine.plan", {}); + ModuleCreateOptions shared; + shared.stream = decoder->stream(); + auto prefill = load_engine(context.backend, bundle, "prefill.plan", shared); + decoder_ = std::make_unique(std::move(decoder), std::move(prefill), geometry, + vocab, hidden); + vision_encoder_ = std::make_unique( + load_engine(context.backend, bundle, "vision.plan", {}), hidden, dtype, + checked_product(3, checked_product(settings_.patch_size, settings_.patch_size, "patch"), + "patch width"), + settings_.max_patches); + } + + const char* task() const noexcept override { return api::IImagesTextToText::kTask.data(); } + + std::vector task_bindings() override { + return {api::bind(*this, span(common_fields())), + api::bind(*this, span(text_fields()))}; + } + + TextResult run(const api::ImagesTextToTextRequest& request, api::ConfigView config) override { + const auto options = read_options(config, common_fields()); + if (!request.tools.empty()) + throw std::invalid_argument("MiniCPM-V 4.6 does not map tool definitions"); + if (request.messages.empty()) + throw std::invalid_argument("MiniCPM-V 4.6 requires at least one message"); + std::lock_guard lock(mutex_); + const auto start = std::chrono::steady_clock::now(); + std::vector messages; + std::vector images; + const std::int64_t budget = prompt_budget(options); + // Every message renders at least its start marker, and the prompt's text may not exceed + // what the budget's ids can stand for: both are checked before anything is copied. + if (request.messages.size() > static_cast(budget)) + prompt_too_long(); + const std::size_t max_points = + tokenizer_->max_code_points(static_cast(budget)); + std::size_t points = 0; + std::int64_t image_rows = 0; + for (const auto& message : request.messages) { + PromptMessage item; + item.role = role(message.role); + if (message.parts.empty()) + throw std::invalid_argument("MiniCPM-V 4.6 messages must have content"); + bool first = true; + for (const auto& part : message.parts) { + // The provider template joins content parts with newlines and + // renders each image as one placeholder. + if (!first) { + if (++points > max_points) + prompt_too_long(); + item.content += "\n"; + } + first = false; + std::visit( + [&](const auto& value) { + using T = std::decay_t; + if constexpr (std::is_same_v) { + points += code_points(value.text); + if (points > max_points) + prompt_too_long(); + item.content += checked_text(value.text); + } else if constexpr (std::is_same_v) { + if (item.role == Role::System) + throw std::invalid_argument( + "MiniCPM-V 4.6 system messages cannot contain images"); + // Count the image's rows from its slice plan before any slice + // is allocated; stop once the images alone exceed the cache. + image_rows += planned_rows(settings_, plan_image(settings_, value)); + if (image_rows > budget) + throw std::invalid_argument( + "MiniCPM-V 4.6 images need more rows than the bundle's " + + std::to_string(decoder_->capacity()) + + "-token capacity leaves after max_new_tokens"); + images.push_back(prepare_image(settings_, value)); + item.content += kImagePad; + } else { + throw std::invalid_argument( + "MiniCPM-V 4.6 maps text and image parts only"); + } + }, + part); + } + messages.push_back(std::move(item)); + } + auto text = format_conversation(recipe(options), messages); + text = expand_images(text, images); + PromptRows prompt; + // The token budget holds before any vision engine launch. + auto ids = tokenizer_->encode(text, static_cast(budget)); + if (!ids) + prompt_too_long(); + prompt.token_ids = std::move(*ids); + prompt.feature_rows.assign(prompt.token_ids.size(), -1); + std::int32_t rows = 0; + for (const auto& image : images) + for (const auto& slice : image.slices) { + const auto features = vision_encoder_->encode(slice); + prompt.features.insert(prompt.features.end(), features.begin(), features.end()); + rows += slice.tokens(); + } + std::int32_t next = 0; + for (std::size_t i = 0; i < prompt.token_ids.size(); ++i) + if (prompt.token_ids[i] == image_pad_) + prompt.feature_rows[i] = next++; + if (next != rows) + throw std::invalid_argument( + "MiniCPM-V 4.6 image placeholder tokens do not match the image features"); + const double setup_ms = since_ms(start); + auto result = generate(prompt, options); + result.setup_ms = setup_ms; + return result; + } + + TextResult run(const api::TextContinuationRequest& request, api::ConfigView config) override { + const auto options = read_options(config, text_fields()); + std::lock_guard lock(mutex_); + const auto budget = static_cast(prompt_budget(options)); + PromptRows prompt; + if (const auto* text = std::get_if(&request.prefix)) { + if (code_points(*text) > tokenizer_->max_code_points(budget)) + prompt_too_long(); + std::string formatted(*text); + if (options.use_chat_template) + formatted = + format_conversation(recipe(options), {{Role::User, checked_text(*text)}}); + auto ids = tokenizer_->encode(formatted, budget); + if (!ids) + prompt_too_long(); + prompt.token_ids = std::move(*ids); + } else { + const auto& tokens = std::get>(request.prefix); + if (options.use_chat_template) + throw std::invalid_argument( + "MiniCPM-V 4.6 applies the chat template to text prefixes only"); + if (tokens.size() > budget) + prompt_too_long(); + prompt.token_ids.assign(tokens.begin(), tokens.end()); + } + prompt.feature_rows.assign(prompt.token_ids.size(), -1); + return generate(prompt, options); + } + + private: + // Prompt rows left after max_new_tokens; a prompt needs at least one. + std::int64_t prompt_budget(const Options& options) const { + const std::int64_t budget = + static_cast(decoder_->capacity()) - options.max_new_tokens; + if (budget < 1) + throw std::invalid_argument("MiniCPM-V 4.6 max_new_tokens leaves no room for a prompt " + "in the bundle's " + + std::to_string(decoder_->capacity()) + "-token capacity"); + return budget; + } + + [[noreturn]] void prompt_too_long() const { + throw std::invalid_argument( + "MiniCPM-V 4.6 prompt plus max_new_tokens exceeds the bundle's " + + std::to_string(decoder_->capacity()) + "-token capacity"); + } + + static Role role(api::MessageRole value) { + switch (value) { + case api::MessageRole::System: + return Role::System; + case api::MessageRole::User: + return Role::User; + case api::MessageRole::Assistant: + return Role::Assistant; + default: + throw std::invalid_argument( + "MiniCPM-V 4.6 accepts system, user and assistant messages"); + } + } + + // Placeholder spellings in text would be expanded as images by the provider processor. + static std::string checked_text(std::string_view text) { + std::string value(text); + if (value.find(kImagePad) != std::string::npos || + value.find(kVideoPad) != std::string::npos) + throw std::invalid_argument( + "MiniCPM-V 4.6 text parts cannot contain media placeholders"); + return value; + } + + const Json& recipe(const Options& options) const { + return vision_.at("prompts").at(options.enable_thinking ? "true" : "false"); + } + + // Replace each rendered image placeholder, in order, by the image's slice markup. + static std::string expand_images(const std::string& text, + const std::vector& images) { + std::string result; + std::size_t position = 0, index = 0; + const std::string marker = kImagePad; + for (std::size_t found = text.find(marker); found != std::string::npos; + found = text.find(marker, position)) { + if (index == images.size()) + throw std::logic_error( + "MiniCPM-V 4.6 rendered more image placeholders than images"); + result.append(text, position, found - position); + result += image_placeholder(images[index], static_cast(index)); + ++index; + position = found + marker.size(); + } + if (index != images.size()) + throw std::logic_error("MiniCPM-V 4.6 rendered fewer image placeholders than images"); + result.append(text, position, std::string::npos); + return result; + } + + TextResult generate(const PromptRows& prompt, const Options& options) { + Sampler sampler(options.sampling); + const auto generation = + decoder_->generate(prompt, options.max_new_tokens, eos_ids_, sampler); + TextResult result(tokenizer_->decode(generation.token_ids), generation.token_ids, + generation.prefill_ms, generation.decode_ms); + return result; + } + + Json vision_; + ImageSettings settings_; + std::vector eos_ids_; + std::int32_t image_pad_{-1}; + std::unique_ptr tokenizer_; + std::unique_ptr decoder_; + std::unique_ptr vision_encoder_; + std::mutex mutex_; +}; + +} // namespace +} // namespace trtmc::minicpmv4_6 + +extern "C" trtmc::ITask* trtmc_create_family(const trtmc::FamilyContext& context) { + if (context.kv_cache_size_bytes != 0) + throw std::invalid_argument("minicpmv4_6 does not support --kv-cache-size"); + return new trtmc::minicpmv4_6::Model(context); +} diff --git a/families/minicpmv4_6/runtime/prompt.cpp b/families/minicpmv4_6/runtime/prompt.cpp new file mode 100644 index 0000000000..828762af37 --- /dev/null +++ b/families/minicpmv4_6/runtime/prompt.cpp @@ -0,0 +1,156 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/minicpmv4_6/runtime/prompt.h" + +#include +#include + +namespace trtmc::minicpmv4_6 { +namespace { + +std::string value(const nlohmann::json& object, const char* name) { + return object.at(name).get(); +} + +bool starts_with(const std::string& text, const std::string& prefix) { + return text.compare(0, prefix.size(), prefix) == 0; +} + +bool ends_with(const std::string& text, const std::string& suffix) { + return text.size() >= suffix.size() && + text.compare(text.size() - suffix.size(), suffix.size(), suffix) == 0; +} + +} // namespace + +std::string strip(const std::string& text) { + // Unicode White_Space plus the ASCII information separators, as Python's str.isspace(). + static const std::vector spaces{" ", + "\t", + "\n", + "\r", + "\v", + "\f", + "\x1c", + "\x1d", + "\x1e", + "\x1f", + "\xc2\x85", + "\xc2\xa0", + "\xe1\x9a\x80", + "\xe2\x80\x80", + "\xe2\x80\x81", + "\xe2\x80\x82", + "\xe2\x80\x83", + "\xe2\x80\x84", + "\xe2\x80\x85", + "\xe2\x80\x86", + "\xe2\x80\x87", + "\xe2\x80\x88", + "\xe2\x80\x89", + "\xe2\x80\x8a", + "\xe2\x80\xa8", + "\xe2\x80\xa9", + "\xe2\x80\xaf", + "\xe2\x81\x9f", + "\xe3\x80\x80"}; + std::size_t begin = 0, end = text.size(); + for (bool found = true; found && begin < end;) { + found = false; + for (const auto& space : spaces) + if (space.size() <= end - begin && text.compare(begin, space.size(), space) == 0) { + begin += space.size(); + found = true; + break; + } + } + for (bool found = true; found && begin < end;) { + found = false; + for (const auto& space : spaces) + if (space.size() <= end - begin && + text.compare(end - space.size(), space.size(), space) == 0) { + end -= space.size(); + found = true; + break; + } + } + return text.substr(begin, end - begin); +} + +void validate_recipe(const nlohmann::json& recipe) { + for (const char* field : {"default_prefix", "empty_system_prefix", "generation"}) + (void)value(recipe, field); + (void)recipe.at("parse_assistant_thinking").get(); + for (const char* kind : {"user", "system", "assistant_recent", "assistant_history"}) { + (void)value(recipe.at(kind), "prefix"); + (void)value(recipe.at(kind), "suffix"); + if (std::string(kind).rfind("assistant", 0) == 0) { + (void)recipe.at(kind).at("include_reasoning").get(); + (void)value(recipe.at(kind), "reasoning_suffix"); + } + } +} + +std::string format_conversation(const nlohmann::json& recipe, + const std::vector& messages) { + if (messages.empty()) + throw std::invalid_argument("MiniCPM-V 4.6 requires at least one message"); + std::vector content; + std::int64_t last_user = -1; + for (std::size_t i = 0; i < messages.size(); ++i) { + content.push_back(strip(messages[i].content)); + const auto& text = content.back(); + const bool tool_response = + starts_with(text, "") && ends_with(text, ""); + if (messages[i].role == Role::User && !tool_response) + last_user = static_cast(i); + } + if (last_user < 0) + throw std::invalid_argument("MiniCPM-V 4.6 requires a user query"); + std::string output; + if (messages[0].role != Role::System) + output = value(recipe, "default_prefix"); + else if (content[0].empty()) + output = value(recipe, "empty_system_prefix"); + else + output = value(recipe.at("system"), "prefix") + content[0] + + value(recipe.at("system"), "suffix"); + for (std::size_t i = 0; i < messages.size(); ++i) { + if (messages[i].role == Role::System) { + if (i != 0) + throw std::invalid_argument("MiniCPM-V 4.6 system message must be first"); + continue; + } + if (messages[i].role == Role::User) { + output += value(recipe.at("user"), "prefix") + content[i] + + value(recipe.at("user"), "suffix"); + continue; + } + std::string body = content[i], reasoning; + const auto close = body.find(""); + if (recipe.at("parse_assistant_thinking").get() && close != std::string::npos) { + reasoning = body.substr(0, close); + while (!reasoning.empty() && reasoning.back() == '\n') + reasoning.pop_back(); + const auto open = reasoning.rfind(""); + if (open != std::string::npos) + reasoning.erase(0, open + 7); + reasoning = strip(reasoning); + body.erase(0, body.rfind("") + 8); + const auto first = body.find_first_not_of('\n'); + body.erase(0, first == std::string::npos ? body.size() : first); + } + const auto& form = recipe.at( + static_cast(i) > last_user ? "assistant_recent" : "assistant_history"); + output += value(form, "prefix"); + if (form.at("include_reasoning").get()) + output += reasoning + value(form, "reasoning_suffix"); + output += body + value(form, "suffix"); + } + return output + value(recipe, "generation"); +} + +} // namespace trtmc::minicpmv4_6 diff --git a/families/minicpmv4_6/runtime/prompt.h b/families/minicpmv4_6/runtime/prompt.h new file mode 100644 index 0000000000..3bb480a1c5 --- /dev/null +++ b/families/minicpmv4_6/runtime/prompt.h @@ -0,0 +1,30 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include +#include +#include + +namespace trtmc::minicpmv4_6 { + +enum class Role { System, User, Assistant }; + +struct PromptMessage { + Role role{Role::User}; + std::string content; +}; + +// Python str.strip() whitespace (the template's trim filter). +std::string strip(const std::string& text); + +// Render a conversation with a provider recipe extracted at build time +// (vision.json "prompts"), including the generation prompt. +std::string format_conversation(const nlohmann::json& recipe, + const std::vector& messages); +void validate_recipe(const nlohmann::json& recipe); + +} // namespace trtmc::minicpmv4_6 diff --git a/families/minicpmv4_6/runtime/sampler.cpp b/families/minicpmv4_6/runtime/sampler.cpp new file mode 100644 index 0000000000..cb42a32be5 --- /dev/null +++ b/families/minicpmv4_6/runtime/sampler.cpp @@ -0,0 +1,97 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/minicpmv4_6/runtime/sampler.h" + +#include +#include +#include +#include +#include + +namespace trtmc::minicpmv4_6 { + +SamplingOptions sampling_options(double temperature, std::int64_t top_k, double top_p, + std::int64_t seed) { + constexpr double kFloatMax = std::numeric_limits::max(); + if (!std::isfinite(temperature) || temperature < 0.0 || temperature > kFloatMax || + (temperature > 0.0 && static_cast(temperature) == 0.0F)) + throw std::invalid_argument("MiniCPM-V 4.6 temperature must be 0 or a positive FP32 value"); + if (!std::isfinite(top_p) || !(top_p > 0.0) || top_p > 1.0 || static_cast(top_p) == 0.0F) + throw std::invalid_argument("MiniCPM-V 4.6 top_p must be in (0, 1]"); + if (top_k < 0 || top_k > std::numeric_limits::max()) + throw std::invalid_argument("MiniCPM-V 4.6 top_k must be a non-negative int32"); + if (seed < -1) + throw std::invalid_argument("MiniCPM-V 4.6 seed must be -1 or non-negative"); + SamplingOptions options; + options.temperature = static_cast(temperature); + options.top_k = static_cast(top_k); + options.top_p = static_cast(top_p); + options.seed = seed; + return options; +} + +Sampler::Sampler(const SamplingOptions& options) : options_(options) { + if (!std::isfinite(options.temperature) || options.temperature < 0.0F || + !std::isfinite(options.top_p) || options.top_p <= 0.0F || options.top_p > 1.0F || + options.top_k < 0 || options.seed < -1) + throw std::invalid_argument("MiniCPM-V 4.6 sampling requires temperature >= 0, top_k >= 0, " + "top_p in (0, 1] and seed >= -1"); + // top_k == 0 keeps the whole vocabulary; top_k == 1 is greedy. + greedy_ = options.temperature == 0.0F || options.top_k == 1; + const auto seed = options.seed >= 0 ? static_cast(options.seed) : 42ULL; + state_ = seed == 0 ? 1 : seed; +} + +std::int32_t Sampler::sample(const std::vector& logits) { + if (logits.empty()) + throw std::invalid_argument("MiniCPM-V 4.6 sampler received no logits"); + // NaN breaks both the argmax and the sort's ordering; infinity breaks the probabilities. + if (std::any_of(logits.begin(), logits.end(), + [](float value) { return !std::isfinite(value); })) + throw std::runtime_error("MiniCPM-V 4.6 decoder produced nonfinite logits"); + if (greedy_) + return static_cast(std::max_element(logits.begin(), logits.end()) - + logits.begin()); + const auto vocab = static_cast(logits.size()); + const std::int32_t k = options_.top_k == 0 ? vocab : std::min(options_.top_k, vocab); + std::vector order(static_cast(vocab)); + std::iota(order.begin(), order.end(), 0); + std::partial_sort(order.begin(), order.begin() + k, order.end(), + [&](std::int32_t a, std::int32_t b) { return logits[a] > logits[b]; }); + std::vector probabilities(static_cast(k)); + const double top = logits[static_cast(order[0])]; + double total = 0.0; + for (std::int32_t i = 0; i < k; ++i) { + probabilities[i] = std::exp((logits[static_cast(order[i])] - top) / + static_cast(options_.temperature)); + total += probabilities[i]; + } + std::int32_t keep = k; + if (options_.top_p < 1.0F) { + double cumulative = 0.0; + for (keep = 0; keep < k;) { + cumulative += probabilities[keep++] / total; + if (cumulative >= options_.top_p) + break; + } + } + double kept = 0.0; + for (std::int32_t i = 0; i < keep; ++i) + kept += probabilities[i]; + state_ ^= state_ << 13; + state_ ^= state_ >> 7; + state_ ^= state_ << 17; + const double draw = static_cast(state_ & 0xFFFFFFFFULL) / 4294967296.0 * kept; + double cumulative = 0.0; + for (std::int32_t i = 0; i < keep; ++i) { + cumulative += probabilities[i]; + if (draw < cumulative) + return order[i]; + } + return order[keep - 1]; +} + +} // namespace trtmc::minicpmv4_6 diff --git a/families/minicpmv4_6/runtime/sampler.h b/families/minicpmv4_6/runtime/sampler.h new file mode 100644 index 0000000000..3f33f18ed5 --- /dev/null +++ b/families/minicpmv4_6/runtime/sampler.h @@ -0,0 +1,39 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include +#include + +namespace trtmc::minicpmv4_6 { + +struct SamplingOptions { + float temperature{1.0F}; + std::int32_t top_k{1}; + float top_p{1.0F}; + std::int64_t seed{-1}; // -1: a fixed default seed +}; + +// Sampling options from a request's values, checked before they are narrowed to FP32: a +// negative or nonfinite value, a positive temperature or top_p that FP32 rounds to zero, and a +// top_p above one are rejected. +SamplingOptions sampling_options(double temperature, std::int64_t top_k, double top_p, + std::int64_t seed); + +// Greedy argmax when top_k <= 1 (the default) or the temperature is zero; +// otherwise temperature, top-k and top-p filtering with a seeded xorshift draw. +class Sampler { + public: + explicit Sampler(const SamplingOptions& options); + std::int32_t sample(const std::vector& logits); + + private: + SamplingOptions options_; + bool greedy_{true}; + std::uint64_t state_{1}; +}; + +} // namespace trtmc::minicpmv4_6 diff --git a/families/minicpmv4_6/runtime/state.cpp b/families/minicpmv4_6/runtime/state.cpp new file mode 100644 index 0000000000..1e26d1d4c9 --- /dev/null +++ b/families/minicpmv4_6/runtime/state.cpp @@ -0,0 +1,180 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/minicpmv4_6/runtime/state.h" + +#include "trtmc/runtime/trt_module.h" + +#include +#include +#include + +namespace trtmc::minicpmv4_6 { +namespace { + +// Additive score of masked attention entries (model-local constant). +constexpr float kMaskedScore = -1.0e4F; + +std::string indexed(const char* stem, std::int32_t index) { + return std::string(stem) + "_" + std::to_string(index); +} + +void check(cudaError_t status, const char* what) { + if (status != cudaSuccess) + throw std::runtime_error(std::string("MiniCPM-V 4.6 ") + what + ": " + + cudaGetErrorString(status)); +} + +} // namespace + +DecoderState::DecoderState(const DecoderGeometry& geometry, cudaStream_t stream) + : geometry_(geometry), stream_(stream) { + if (geometry.attention_layers <= 0 || geometry.deltanet_layers <= 0 || geometry.kv_width <= 0 || + geometry.conv_width <= 0 || geometry.conv_kernel <= 0 || geometry.deltanet_heads <= 0 || + geometry.deltanet_head_dim <= 0 || geometry.capacity <= 1) + throw std::invalid_argument("Invalid MiniCPM-V 4.6 decoder state geometry"); + for (std::int32_t i = 0; i < geometry.attention_layers; ++i) { + cache_k_.push_back(DeviceTensor::zeros({geometry.capacity, geometry.kv_width}, + geometry.cache_dtype, stream)); + cache_v_.push_back(DeviceTensor::zeros({geometry.capacity, geometry.kv_width}, + geometry.cache_dtype, stream)); + present_k_.emplace_back(std::vector{1, geometry.kv_width}, geometry.cache_dtype, + stream); + present_v_.emplace_back(std::vector{1, geometry.kv_width}, geometry.cache_dtype, + stream); + } + const std::vector conv_shape{geometry.conv_width, geometry.conv_kernel}; + const std::vector ssm_shape{geometry.deltanet_heads, geometry.deltanet_head_dim, + geometry.deltanet_head_dim}; + for (std::int32_t i = 0; i < geometry.deltanet_layers; ++i) { + conv_.emplace_back(conv_shape, DType::kFloat32, stream); + present_conv_.emplace_back(conv_shape, DType::kFloat32, stream); + ssm_.emplace_back(ssm_shape, DType::kFloat32, stream); + present_ssm_.emplace_back(ssm_shape, DType::kFloat32, stream); + } + for (const auto* group : {&cache_k_, &cache_v_, &present_k_, &present_v_, &conv_, + &present_conv_, &ssm_, &present_ssm_}) + for (const auto& tensor : *group) + if (!tensor.ok()) + throw std::runtime_error("MiniCPM-V 4.6 failed to allocate decoder state"); + reset(); +} + +void DecoderState::reset() { + // Masks hide stale KV rows; the recurrent state must start from zero. + position_ = 0; + for (auto* group : {&conv_, &ssm_}) + for (auto& tensor : *group) + check(cudaMemsetAsync(tensor.data(), 0, tensor.nbytes(), stream_), + "recurrent state reset failed"); +} + +void DecoderState::bind_caches(ITrtModule& module) { + const std::vector cache_shape{geometry_.capacity, geometry_.kv_width}; + for (std::int32_t i = 0; i < geometry_.attention_layers; ++i) { + for (const char* stem : {"cache_k", "cache_v"}) { + const auto name = indexed(stem, i); + if (module.tensor_shape(name) != cache_shape || + module.tensor_dtype(name) != geometry_.cache_dtype) + throw std::runtime_error( + "MiniCPM-V 4.6 engine disagrees with the KV-cache contract"); + } + module.bind_external(indexed("cache_k", i), cache_k_[static_cast(i)].data()); + module.bind_external(indexed("cache_v", i), cache_v_[static_cast(i)].data()); + } +} + +void DecoderState::bind_recurrent(ITrtModule& module) { + for (std::int32_t i = 0; i < geometry_.deltanet_layers; ++i) { + const auto layer = static_cast(i); + module.bind_external(indexed("conv_state", i), conv_[layer].data()); + module.bind_external(indexed("present_conv", i), present_conv_[layer].data()); + module.bind_external(indexed("ssm_state", i), ssm_[layer].data()); + module.bind_external(indexed("present_ssm", i), present_ssm_[layer].data()); + } +} + +void DecoderState::bind_decoder(ITrtModule& module) { + bind_caches(module); + for (std::int32_t i = 0; i < geometry_.attention_layers; ++i) { + module.bind_external(indexed("present_k", i), + present_k_[static_cast(i)].data()); + module.bind_external(indexed("present_v", i), + present_v_[static_cast(i)].data()); + } + bind_recurrent(module); +} + +void DecoderState::bind_prefill(ITrtModule& module) { + bind_caches(module); + bind_recurrent(module); +} + +void DecoderState::prepare(TensorMap& inputs, std::int32_t rows) { + if (rows <= 0 || position_ + rows > geometry_.capacity) + throw std::invalid_argument("MiniCPM-V 4.6 request exceeds the KV-cache capacity"); + positions_.resize(static_cast(rows)); + for (std::int32_t i = 0; i < rows; ++i) + positions_[static_cast(i)] = position_ + i; + inputs["position_id"] = Tensor{positions_.data(), {rows}, DType::kInt32}; + // Columns [0, capacity) address the cache (valid below position_), then the + // new rows causally. + const std::int32_t width = geometry_.capacity + rows; + mask_.assign(static_cast(rows) * width, kMaskedScore); + for (std::int32_t i = 0; i < rows; ++i) { + float* row = mask_.data() + static_cast(i) * width; + std::fill(row, row + position_, 0.0F); + std::fill(row + geometry_.capacity, row + geometry_.capacity + i + 1, 0.0F); + } + inputs["attention_mask"] = Tensor{mask_.data(), {rows, width}, DType::kFloat32}; +} + +void DecoderState::commit_recurrent() { + for (std::size_t i = 0; i < conv_.size(); ++i) { + if (!conv_[i].copy_from(present_conv_[i]) || !ssm_[i].copy_from(present_ssm_[i])) + throw std::runtime_error("MiniCPM-V 4.6 recurrent state copy failed"); + } +} + +void DecoderState::commit_decoder() { + const auto row_bytes = + static_cast(geometry_.kv_width) * dtype_size(geometry_.cache_dtype); + const auto offset = static_cast(position_) * row_bytes; + for (std::size_t i = 0; i < cache_k_.size(); ++i) { + check(cudaMemcpyAsync(static_cast(cache_k_[i].data()) + offset, + present_k_[i].data(), row_bytes, cudaMemcpyDeviceToDevice, stream_), + "KV append failed"); + check(cudaMemcpyAsync(static_cast(cache_v_[i].data()) + offset, + present_v_[i].data(), row_bytes, cudaMemcpyDeviceToDevice, stream_), + "KV append failed"); + } + commit_recurrent(); + ++position_; +} + +void DecoderState::commit_prefill(const ITrtModule& module, std::int32_t rows) { + const auto row_bytes = + static_cast(geometry_.kv_width) * dtype_size(geometry_.cache_dtype); + const auto offset = static_cast(position_) * row_bytes; + for (std::int32_t i = 0; i < geometry_.attention_layers; ++i) { + const void* keys = module.device_ptr(indexed("present_k", i)); + const void* values = module.device_ptr(indexed("present_v", i)); + if (keys == nullptr || values == nullptr) + throw std::runtime_error("MiniCPM-V 4.6 prefill engine has no present K/V output"); + const auto layer = static_cast(i); + check(cudaMemcpyAsync(static_cast(cache_k_[layer].data()) + offset, keys, + static_cast(rows) * row_bytes, cudaMemcpyDeviceToDevice, + stream_), + "KV append failed"); + check(cudaMemcpyAsync(static_cast(cache_v_[layer].data()) + offset, values, + static_cast(rows) * row_bytes, cudaMemcpyDeviceToDevice, + stream_), + "KV append failed"); + } + commit_recurrent(); + position_ += rows; +} + +} // namespace trtmc::minicpmv4_6 diff --git a/families/minicpmv4_6/runtime/state.h b/families/minicpmv4_6/runtime/state.h new file mode 100644 index 0000000000..caa6292369 --- /dev/null +++ b/families/minicpmv4_6/runtime/state.h @@ -0,0 +1,71 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include "trtmc/runtime/device_tensor.h" +#include "trtmc/runtime/tensor.h" + +#include +#include +#include + +namespace trtmc { +class ITrtModule; +} + +namespace trtmc::minicpmv4_6 { + +// Decoder geometry from runtime.json. +struct DecoderGeometry { + std::int32_t attention_layers{0}; + std::int32_t deltanet_layers{0}; + std::int32_t kv_width{0}; // KV heads x head dimension + std::int32_t conv_width{0}; // DeltaNet convolution channels + std::int32_t conv_kernel{0}; + std::int32_t deltanet_heads{0}; + std::int32_t deltanet_head_dim{0}; + std::int32_t capacity{0}; // KV cache rows + DType cache_dtype{DType::kFloat16}; +}; + +// Per-request state of the hybrid decoder: the attention KV cache (rows +// [0, position) valid) and the FP32 DeltaNet convolution and recurrent states. +// Engines read the state through bound inputs and write present tensors; the +// state commits those after every launch on the engines' stream. +class DecoderState { + public: + DecoderState(const DecoderGeometry& geometry, cudaStream_t stream); + + void reset(); + std::int32_t position() const { return position_; } + std::int32_t capacity() const { return geometry_.capacity; } + + // One-token decoder: caches, one-row present K/V and the recurrent state. + void bind_decoder(ITrtModule& module); + // Prefill engine: caches and recurrent state; its present K/V rows are read + // from the engine after each launch. + void bind_prefill(ITrtModule& module); + + // position_id and the additive attention mask for `rows` new tokens. + void prepare(TensorMap& inputs, std::int32_t rows); + void commit_decoder(); + void commit_prefill(const ITrtModule& module, std::int32_t rows); + + private: + void bind_caches(ITrtModule& module); + void bind_recurrent(ITrtModule& module); + void commit_recurrent(); + + DecoderGeometry geometry_; + cudaStream_t stream_{nullptr}; + std::vector cache_k_, cache_v_, present_k_, present_v_; + std::vector conv_, present_conv_, ssm_, present_ssm_; + std::vector mask_; + std::vector positions_; + std::int32_t position_{0}; +}; + +} // namespace trtmc::minicpmv4_6 diff --git a/families/minicpmv4_6/runtime/tokenizer.h b/families/minicpmv4_6/runtime/tokenizer.h new file mode 100644 index 0000000000..eadca41a04 --- /dev/null +++ b/families/minicpmv4_6/runtime/tokenizer.h @@ -0,0 +1,48 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace trtmc::minicpmv4_6 { + +// Byte-level BPE of the checkpoint's tokenizer.json: added tokens split first, +// NFC normalization and the declared Unicode Split pattern on the remaining +// text, with the Unicode versions of tokenizers' tables (9.0 for NFC, 16.0 for +// the pattern's classes), then BPE merges. Decoding skips special added tokens. +class Tokenizer { + public: + virtual ~Tokenizer() = default; + // The ids of the text, or nothing when it needs more than `limit` ids. The text is read only as + // far as that takes: one with more code points than max_code_points(limit) is refused unread, + // and encoding stops at the first id beyond `limit`. + virtual std::optional> encode(std::string_view text, + std::size_t limit) const = 0; + // The most code points that `tokens` ids can stand for: NFC composes at most four code points + // into one (the longest canonical decomposition), and an id covers at most as many code points + // as its longest token has. + virtual std::size_t max_code_points(std::size_t tokens) const = 0; + virtual std::string decode(const std::vector& ids) const = 0; + virtual std::int32_t id_for_token(std::string_view token) const = 0; + virtual std::int32_t vocabulary_size() const = 0; +}; + +std::unique_ptr create_tokenizer(const char* tokenizer_json, std::size_t size); + +// The number of code points of UTF-8 text as ICU decodes it (an ill-formed sequence is one U+FFFD). +std::size_t code_points(std::string_view text); + +// Exposed for focused tests. +std::vector pre_tokenize(std::string_view text); +std::string utf8_lossy(std::string_view bytes); + +} // namespace trtmc::minicpmv4_6 diff --git a/families/minicpmv4_6/runtime/vision_encoder.cpp b/families/minicpmv4_6/runtime/vision_encoder.cpp new file mode 100644 index 0000000000..55ed8ce3d8 --- /dev/null +++ b/families/minicpmv4_6/runtime/vision_encoder.cpp @@ -0,0 +1,60 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "families/minicpmv4_6/runtime/vision_encoder.h" + +#include "families/minicpmv4_6/runtime/engine_io.h" + +#include +#include + +namespace trtmc::minicpmv4_6 { + +VisionEncoder::VisionEncoder(std::unique_ptr module, std::int32_t hidden_size, + DType dtype, std::int32_t patch_width, std::int32_t max_patches) + : module_(std::move(module)), hidden_size_(hidden_size), dtype_(dtype), + patch_width_(patch_width) { + if (!module_ || !module_->ok()) + throw std::runtime_error("Invalid MiniCPM-V 4.6 vision engine"); + validate_vision_engine(*module_, dtype_, patch_width_, hidden_size_, max_patches); +} + +std::vector VisionEncoder::encode(const VisionSlice& slice) { + const auto patches = static_cast(slice.height) * slice.width; + if (patches <= 0 || slice.patches.size() != static_cast(patches) * patch_width_ || + slice.position_ids.size() != static_cast(patches) || + slice.window_index.size() != static_cast(patches) || + slice.merge_index.size() * 4 != static_cast(patches)) + throw std::invalid_argument("MiniCPM-V 4.6 vision slice inputs are inconsistent"); + TensorMap inputs{ + {"patches", + {const_cast(slice.patches.data()), {patches, patch_width_}, DType::kFloat32}}, + {"position_ids", + {const_cast(slice.position_ids.data()), {patches}, DType::kInt32}}, + {"window_index", + {const_cast(slice.window_index.data()), {patches}, DType::kInt32}}, + {"merge_index", + {const_cast(slice.merge_index.data()), {patches / 4}, DType::kInt32}}, + }; + TensorMap outputs; + try { + outputs = module_->forward(inputs); + } catch (...) { + try { + module_->sync(); + } catch (...) { + } + throw; + } + const auto& features = outputs.at("visual_features"); + if (features.dtype != dtype_ || + features.shape != std::vector{slice.tokens(), hidden_size_}) + throw std::runtime_error("MiniCPM-V 4.6 vision output has invalid geometry or dtype"); + std::vector result(features.nbytes()); + std::memcpy(result.data(), features.data, result.size()); + return result; +} + +} // namespace trtmc::minicpmv4_6 diff --git a/families/minicpmv4_6/runtime/vision_encoder.h b/families/minicpmv4_6/runtime/vision_encoder.h new file mode 100644 index 0000000000..037e8e6058 --- /dev/null +++ b/families/minicpmv4_6/runtime/vision_encoder.h @@ -0,0 +1,32 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include "families/minicpmv4_6/runtime/image.h" +#include "trtmc/runtime/trt_module.h" + +#include +#include +#include + +namespace trtmc::minicpmv4_6 { + +// Runs vision.plan once per slice; returns [slice tokens, hidden] feature rows +// at the decoder precision. +class VisionEncoder { + public: + VisionEncoder(std::unique_ptr module, std::int32_t hidden_size, DType dtype, + std::int32_t patch_width, std::int32_t max_patches); + std::vector encode(const VisionSlice& slice); + + private: + std::unique_ptr module_; + std::int32_t hidden_size_{0}; + DType dtype_{DType::kFloat16}; + std::int32_t patch_width_{0}; +}; + +} // namespace trtmc::minicpmv4_6 diff --git a/families/minicpmv4_6/support.py b/families/minicpmv4_6/support.py new file mode 100644 index 0000000000..77e0638dbe --- /dev/null +++ b/families/minicpmv4_6/support.py @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Exact checkpoint identity and task support of the MiniCPM-V 4.6 family.""" + +from tensorrt_model_connect.model_support import family_support + +describe = family_support( + model_types=("minicpmv4_6",), + architectures=("MiniCPMV4_6ForConditionalGeneration",), + tasks=("images_text_to_text",), + default_task="images_text_to_text", + default_precision="fp16", +) diff --git a/families/minicpmv4_6/tests/__init__.py b/families/minicpmv4_6/tests/__init__.py new file mode 100644 index 0000000000..a2ad1f63bf --- /dev/null +++ b/families/minicpmv4_6/tests/__init__.py @@ -0,0 +1,4 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Family-owned tests.""" diff --git a/families/minicpmv4_6/tests/cpp/test_minicpmv4_6_host.cpp b/families/minicpmv4_6/tests/cpp/test_minicpmv4_6_host.cpp new file mode 100644 index 0000000000..265bc9b82a --- /dev/null +++ b/families/minicpmv4_6/tests/cpp/test_minicpmv4_6_host.cpp @@ -0,0 +1,907 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +// Host-only checks of the MiniCPM-V 4.6 runtime: image slicing, resampling and +// grid indices, placeholder text, conversation formatting, pre-tokenization and +// BPE merges, metadata parsing, sampling, and the engine I/O contracts. +// Golden values were produced with the Transformers 5.22.2 processor, the +// PyTorch operations the reference model runs, and Hugging Face tokenizers 0.23.3. + +#include "families/minicpmv4_6/runtime/engine_io.h" +#include "families/minicpmv4_6/runtime/image.h" +#include "families/minicpmv4_6/runtime/metadata.h" +#include "families/minicpmv4_6/runtime/prompt.h" +#include "families/minicpmv4_6/runtime/sampler.h" +#include "families/minicpmv4_6/runtime/tokenizer.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace trtmc::minicpmv4_6; + +int failures = 0; + +void check(bool condition, const std::string& label) { + if (!condition) { + std::cerr << "FAIL: " << label << '\n'; + ++failures; + } +} + +template +bool rejects(Callable&& callable) { + try { + callable(); + } catch (const std::invalid_argument&) { + return true; + } + return false; +} + +template +bool fails(Callable&& callable) { + try { + callable(); + } catch (const std::runtime_error&) { + return true; + } catch (const std::invalid_argument&) { + return true; + } + return false; +} + +// Deterministic RGB8 test pattern (the generator of the resize goldens). +std::vector pattern(std::int32_t height, std::int32_t width) { + std::vector values; + for (std::int32_t y = 0; y < height; ++y) + for (std::int32_t x = 0; x < width; ++x) + for (std::int32_t c = 0; c < 3; ++c) + values.push_back( + static_cast((y * 37 + x * 101 + c * 59 + (y * x) % 23) % 256)); + return values; +} + +struct PlanCase { + std::int32_t height, width, source_height, source_width, rows, cols, refine_height, + refine_width; +}; + +void slice_plans() { + // {image height, image width} -> source size, grid, refined size (pixels). + const std::vector cases{ + {382, 640, 336, 560, 1, 2, 504, 784}, {468, 931, 336, 616, 1, 2, 448, 896}, + {448, 448, 448, 448, 0, 0, 0, 0}, {10, 10, 448, 448, 0, 0, 0, 0}, + {1000, 1000, 448, 448, 2, 2, 896, 896}, {300, 4000, 112, 1624, 1, 7, 336, 4312}, + {4000, 300, 1624, 112, 7, 1, 4312, 336}, {2000, 3000, 392, 560, 2, 4, 1008, 1568}, + {449, 449, 448, 448, 2, 1, 672, 616}, {100, 3000, 56, 2408, 1, 3, 168, 4200}, + }; + const ImageSettings settings; + for (const auto& c : cases) { + const auto plan = plan_slices(settings, c.height, c.width); + const auto label = "plan " + std::to_string(c.height) + "x" + std::to_string(c.width); + check(plan.source_height == c.source_height && plan.source_width == c.source_width, + label + " source"); + check(plan.rows == c.rows && plan.cols == c.cols, label + " grid"); + check(plan.refine_height == c.refine_height && plan.refine_width == c.refine_width, + label + " refine"); + } + check(rejects([&] { plan_slices(settings, 0, 10); }), "plan rejects an empty image"); +} + +void grid_indices() { + check(block_order(2, 4) == std::vector{0, 1, 4, 5, 2, 3, 6, 7}, + "block order 2x4"); + check(block_order(4, 2) == std::vector{0, 1, 2, 3, 4, 5, 6, 7}, + "block order 4x2"); + check(rejects([] { block_order(3, 4); }), "block order rejects odd grids"); + const auto ids = bucket_position_ids(4, 8, 70); + check(ids.size() == 32, "position ids size"); + check(ids.front() == 0, "position ids origin"); + bool inside = true; + for (const auto id : ids) + inside = inside && id >= 0 && id < 70 * 70; + check(inside, "position ids address the 70 x 70 table"); + + // get_vision_nearest_position_ids evaluated on the GPU, as the reference model does; its + // CPU evaluation buckets these sizes differently. + const std::vector>> buckets{ + {25, {0, 2, 5, 8, 11, 13, 16, 19, 22, 25, 27, 30, 33, + 36, 39, 41, 44, 47, 50, 53, 55, 58, 61, 64, 67}}, + {49, {0, 1, 2, 4, 5, 7, 8, 9, 11, 12, 14, 15, 17, 18, 19, 21, 22, + 24, 25, 27, 28, 30, 31, 32, 34, 35, 37, 38, 39, 41, 42, 44, 45, 47, + 48, 49, 51, 52, 54, 55, 57, 58, 60, 61, 62, 64, 65, 67, 68}}, + {50, {0, 1, 2, 4, 5, 6, 8, 9, 11, 12, 13, 15, 16, 18, 19, 20, 22, + 23, 25, 26, 27, 29, 30, 32, 33, 35, 36, 37, 39, 40, 41, 43, 44, 46, + 47, 49, 50, 51, 53, 54, 55, 57, 58, 60, 61, 63, 64, 65, 67, 68}}, + {55, {0, 1, 2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 15, 16, 17, 19, 20, 21, 22, + 24, 25, 26, 27, 29, 30, 31, 33, 34, 35, 36, 38, 39, 40, 41, 43, 44, 45, 47, + 48, 49, 50, 52, 53, 54, 55, 57, 58, 59, 61, 62, 63, 64, 66, 67, 68}}, + {82, {0, 0, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10, 11, 11, 12, 13, 14, 15, 16, 17, + 17, 18, 19, 20, 21, 22, 23, 23, 24, 25, 26, 27, 28, 29, 29, 30, 31, 32, 33, 34, 34, + 35, 36, 37, 38, 39, 40, 40, 41, 42, 43, 44, 45, 46, 46, 47, 48, 49, 50, 51, 52, 52, + 53, 54, 55, 56, 57, 58, 58, 59, 60, 61, 62, 63, 64, 64, 65, 66, 67, 68, 69}}, + }; + for (const auto& [width, expected] : buckets) + check(bucket_position_ids(1, width, 70) == expected, + "position buckets of width " + std::to_string(width)); +} + +void resampling() { + // A uniform image stays uniform through both antialiased passes. + const std::vector gray(37 * 53 * 3, 117); + const auto smaller = resize_rgb8(gray.data(), 37, 53, 14, 28); + bool uniform = smaller.size() == static_cast(14 * 28 * 3); + for (const auto value : smaller) + uniform = uniform && value == 117; + check(uniform, "uniform image resamples to itself"); + const auto same = resize_rgb8(gray.data(), 37, 53, 37, 53); + check(same == gray, "same-size resize is the identity"); + + // torchvision resize(uint8, BICUBIC, antialias=True), as the reference processor calls it. + struct ResizeCase { + std::int32_t height, width, out_height, out_width; + std::vector expected; + }; + const std::vector cases{ + {5, 7, 3, 4, {64, 119, 125, 161, 77, 120, 136, 168, 86, 135, 130, 181, + 119, 152, 121, 112, 136, 131, 140, 125, 147, 131, 160, 142, + 179, 123, 108, 146, 107, 141, 94, 121, 118, 192, 110, 106}}, + {5, 7, 9, 11, {0, 49, 107, 34, 106, 175, 108, 152, 231, 190, 33, 97, 151, 20, 88, + 44, 103, 162, 96, 186, 55, 184, 173, 16, 255, 54, 98, 170, 99, 171, + 78, 156, 216, 7, 61, 125, 45, 118, 144, 121, 164, 154, 210, 45, 86, + 170, 32, 108, 57, 116, 175, 116, 205, 68, 174, 194, 29, 190, 68, 111, + 141, 113, 191, 98, 170, 237, 26, 85, 160, 69, 141, 91, 145, 188, 16, + 237, 69, 68, 197, 57, 145, 82, 141, 200, 153, 233, 94, 159, 222, 55, + 54, 95, 138, 91, 140, 219, 137, 198, 255, 46, 104, 184, 96, 169, 94, + 159, 224, 1, 156, 95, 80, 128, 83, 175, 105, 164, 237, 194, 166, 123, + 185, 143, 81, 42, 111, 165, 97, 179, 173, 164, 237, 159, 67, 126, 203, + 125, 184, 123, 172, 231, 39, 54, 113, 107, 43, 112, 190, 127, 186, 245, + 211, 81, 140, 200, 43, 109, 82, 126, 194, 129, 202, 111, 187, 246, 31, + 88, 157, 242, 146, 136, 154, 192, 109, 60, 64, 96, 138, 61, 152, 158, + 149, 226, 121, 126, 99, 106, 100, 57, 147, 97, 153, 236, 161, 142, 136, + 213, 116, 41, 108, 186, 223, 167, 100, 153, 215, 12, 83, 98, 90, 170, + 98, 169, 135, 172, 211, 23, 59, 118, 86, 21, 98, 169, 113, 183, 223, + 190, 93, 149, 233, 6, 79, 132, 210, 70, 191, 126, 80, 239, 39, 114, + 123, 127, 199, 123, 132, 160, 197, 71, 51, 87, 83, 126, 49, 136, 153, + 140, 211, 88, 208, 112, 90, 245, 21, 102, 144, 221, 0, 203, 142, 39, + 251, 60, 130, 135, 149, 214, 135, 109, 176, 210, 0, 72, 106, 62, 149, + 70, 156, 143, 154, 225, 12, 216, 126, 56, 251, 36, 114}}, + {6, 4, 6, 9, {0, 49, 108, 10, 72, 131, 55, 131, 190, 107, 157, 216, 168, 83, 142, + 203, 8, 67, 148, 34, 93, 66, 93, 152, 32, 116, 175, 27, 86, 170, + 47, 109, 136, 92, 169, 54, 145, 195, 0, 206, 121, 36, 242, 47, 97, + 188, 73, 150, 106, 133, 195, 72, 156, 215, 64, 123, 206, 87, 146, 173, + 147, 206, 92, 174, 233, 38, 101, 160, 75, 27, 86, 136, 54, 113, 189, + 114, 173, 234, 137, 196, 255, 101, 184, 243, 125, 152, 211, 185, 70, 129, + 213, 17, 77, 139, 54, 129, 65, 116, 181, 93, 170, 129, 154, 215, 47, + 177, 236, 15, 138, 221, 0, 162, 189, 21, 222, 108, 67, 251, 56, 121, + 178, 109, 184, 104, 161, 221, 133, 109, 168, 193, 28, 87, 217, 0, 55, + 199, 255, 37, 167, 226, 61, 86, 145, 122, 35, 94, 151, 72, 147, 78, + 135, 200, 5, 190, 149, 34, 236, 68, 95, 255, 36, 119}}, + {13, 3, 4, 3, {46, 110, 167, 158, 172, 73, 143, 53, 123, 158, 173, 86, + 148, 82, 132, 118, 172, 115, 74, 89, 146, 133, 182, 116, + 107, 95, 97, 137, 201, 112, 106, 92, 106, 94, 158, 224}}, + }; + for (const auto& c : cases) + check(resize_rgb8(pattern(c.height, c.width).data(), c.height, c.width, c.out_height, + c.out_width) == c.expected, + "resize " + std::to_string(c.height) + "x" + std::to_string(c.width) + " -> " + + std::to_string(c.out_height) + "x" + std::to_string(c.out_width)); +} + +void placeholders() { + PreparedImage image; + image.rows = 1; + image.cols = 2; + VisionSlice source, slice; + source.height = 4; + source.width = 8; // 2 tokens + slice.height = slice.width = 4; // 1 token + image.slices = {source, slice, slice}; + check(image_placeholder(image, 3) == + "3<|image_pad|><|image_pad|>" + "<|image_pad|><|image_pad|>", + "placeholder of a 1 x 2 grid"); + image.rows = 2; + image.cols = 1; + check(image_placeholder(image, 0) == + "0<|image_pad|><|image_pad|>" + "<|image_pad|>\n<|image_pad|>", + "placeholder rows are newline separated"); +} + +void conversations() { + const auto recipe = nlohmann::json::parse(R"({ + "default_prefix": "", "empty_system_prefix": "\n\n", "generation": "\n", + "parse_assistant_thinking": true, + "user": {"prefix": "\n", "suffix": "\n"}, + "system": {"prefix": "\n", "suffix": "\n"}, + "assistant_recent": {"prefix": "\n\n", "include_reasoning": true, + "reasoning_suffix": "\n\n\n", "suffix": "\n"}, + "assistant_history": {"prefix": "\n", "include_reasoning": false, + "reasoning_suffix": "", "suffix": "\n"}})"); + validate_recipe(recipe); + check(format_conversation(recipe, {{Role::User, " \n Hi \xe3\x80\x80"}}) == + "\nHi\n\n", + "user message is stripped like Python"); + check(format_conversation(recipe, {{Role::System, " Be brief. "}, + {Role::User, "Q1"}, + {Role::Assistant, "r\n\nA1"}, + {Role::User, "Q2"}}) == + "\nBe brief.\n\nQ1\n\nA1\n\nQ2\n\n", + "history assistant drops its reasoning"); + check(rejects([&] { format_conversation(recipe, {{Role::Assistant, "A"}}); }), + "a conversation needs a user query"); + check(strip("\xc2\xa0 x \t") == "x", "strip removes Unicode white space"); +} + +void pre_tokenization() { + check(pre_tokenize("Hello world") == std::vector{"Hello", " world"}, + "words keep their leading space"); + check(pre_tokenize("2026") == std::vector{"2", "0", "2", "6"}, + "digits split one by one"); + check(pre_tokenize("it's") == std::vector{"it", "'s"}, "contractions split"); + // Pieces from tokenizers 0.23.3 on the same texts. Its NFC uses Unicode 9.0 tables, where + // U+1DF6 (Unicode 10.0) is a starter: it stays before U+0316 and blocks e + U+0301, which + // current NFC reorders and composes. + check(pre_tokenize("x\xE1\xB7\xB6\xCC\x96") == + std::vector{"x\xE1\xB7\xB6\xCC\x96"}, + "a mark unknown to Unicode 9.0 is not reordered"); + check(pre_tokenize("e\xE1\xB7\xB6\xCC\x81") == + std::vector{"e\xE1\xB7\xB6\xCC\x81"}, + "a mark unknown to Unicode 9.0 blocks composition"); + check(pre_tokenize("e\xCC\x81") == std::vector{"\xC3\xA9"}, "NFC composes"); + // Its pattern classes are Unicode 16.0's: GARAY DIGIT ONE (U+10D41) is a number and CYRILLIC + // CAPITAL LETTER TJE (U+1C89) a letter, while U+10940 (assigned in Unicode 17.0) is neither. + check(pre_tokenize("a\xF0\x90\xB5\x81" + "b") == std::vector{"a", "\xF0\x90\xB5\x81", "b"}, + "a Unicode 16.0 digit splits alone"); + check(pre_tokenize("a\xE1\xB2\x89" + "b") == std::vector{"a\xE1\xB2\x89" + "b"}, + "a Unicode 16.0 letter joins the word"); + // Unicode 15.0 (ICU 72 and newer): KAWI LETTER A (U+11F04) and KAWI DIGIT ONE (U+11F51). + check(pre_tokenize("a\xF0\x91\xBC\x84" + "b") == std::vector{"a\xF0\x91\xBC\x84" + "b"}, + "a Unicode 15.0 letter joins the word"); + check(pre_tokenize("a\xF0\x91\xBD\x91" + "b") == std::vector{"a", "\xF0\x91\xBD\x91", "b"}, + "a Unicode 15.0 digit splits alone"); + check(pre_tokenize("a\xF0\x90\xA5\x80" + "b") == std::vector{"a", "\xF0\x90\xA5\x80" + "b"}, + "a code point unassigned in Unicode 16.0 is not a letter"); + // \s is White_Space in both regex engines, VT and NEL included. + check(pre_tokenize("x\x0B\x0By") == std::vector{"x", "\x0B", "\x0By"}, + "vertical tabs are white space"); + check(pre_tokenize("x\xC2\x85\xC2\x85y") == + std::vector{"x", "\xC2\x85", "\xC2\x85y"}, + "next-line characters are white space"); + check(utf8_lossy(std::string("a\xff", 2)) == "a\xef\xbf\xbd", "invalid UTF-8 is replaced"); +} + +// A module that only answers introspection queries, for the engine I/O contracts. Like the TensorRT +// module it reports every tensor at a current, concrete shape: a dynamic dimension (-1 in `shape`, +// the engine's declared shape) at its profile maximum, or 1 without a profile. +class FakeModule final : public trtmc::ITrtModule { + public: + struct Entry { + trtmc::DType dtype; + std::vector shape; + bool input; + std::vector minimum, maximum; + std::vector current() const { + auto result = shape; + for (std::size_t i = 0; i < result.size(); ++i) + if (result[i] < 0) + result[i] = maximum.size() == shape.size() ? maximum[i] : 1; + return result; + } + }; + std::map tensors; + + void add(const std::string& name, trtmc::DType dtype, std::vector shape, bool input, + std::vector minimum = {}, std::vector maximum = {}) { + tensors[name] = {dtype, std::move(shape), input, std::move(minimum), std::move(maximum)}; + } + + trtmc::TensorMap forward(const trtmc::TensorMap&) override { throw std::logic_error("fake"); } + trtmc::DeviceTensorMap forward_device(const trtmc::DeviceTensorMap&) override { + throw std::logic_error("fake"); + } + void forward_device_async(const trtmc::DeviceTensorMap&) override {} + void forward_async(const trtmc::TensorMap&) override {} + void sync() override {} + cudaStream_t stream() const override { return nullptr; } + void enable_cuda_graph() override {} + bool cuda_graph_active() const override { return false; } + bool cuda_graph_captured() const override { return false; } + int32_t profile_idx() const override { return 0; } + std::vector input_info() const override { return info(true); } + std::vector output_info() const override { return info(false); } + bool has_input(const std::string& name) const override { + const auto found = tensors.find(name); + return found != tensors.end() && found->second.input; + } + bool has_output(const std::string& name) const override { + const auto found = tensors.find(name); + return found != tensors.end() && !found->second.input; + } + trtmc::DType tensor_dtype(const std::string& name) const override { + return tensors.at(name).dtype; + } + std::vector tensor_shape(const std::string& name) const override { + return tensors.at(name).current(); + } + std::vector input_profile_shape(const std::string& name, int32_t, + trtmc::ProfileShapeSelector selector) const override { + const auto& entry = tensors.at(name); + return selector == trtmc::ProfileShapeSelector::kMin ? entry.minimum : entry.maximum; + } + int32_t optimization_profile_count() const override { return 1; } + void* device_ptr(const std::string&) const override { return nullptr; } + void bind_external(const std::string&, void*) override {} + void bind_external(const std::string&, void*, const std::vector&) override {} + int32_t input_rank(const std::string& name) const override { + return static_cast(tensors.at(name).shape.size()); + } + bool input_is_dynamic(const std::string& name) const override { + const auto& entry = tensors.at(name); + return entry.input && + std::any_of(entry.shape.begin(), entry.shape.end(), [](int64_t d) { return d < 0; }); + } + void reset_execution_context() override {} + void set_timing_label(std::string) override {} + bool ok() const override { return true; } + void keep_alive(std::shared_ptr) override {} + + private: + std::vector info(bool input) const { + std::vector result; + for (const auto& [name, entry] : tensors) + if (entry.input == input) + result.push_back({name, entry.current(), entry.dtype, input}); + return result; + } +}; + +DecoderGeometry small_geometry() { + DecoderGeometry geometry; + geometry.attention_layers = 1; + geometry.deltanet_layers = 2; + geometry.kv_width = 8; + geometry.conv_width = 6; + geometry.conv_kernel = 4; + geometry.deltanet_heads = 2; + geometry.deltanet_head_dim = 3; + geometry.capacity = 16; + geometry.cache_dtype = trtmc::DType::kFloat16; + return geometry; +} + +// The tensors the builder declares for the decoder (rows = 1) or the prefill (rows = -1). +FakeModule decoder_engine(const DecoderGeometry& g, bool prefill, int64_t vocab, int64_t hidden) { + using trtmc::DType; + FakeModule module; + const int64_t rows = prefill ? -1 : 1; + // The prefill profile admits chunks of 1 to 8 rows, as the builder declares it. + const int64_t most = prefill ? 8 : 1; + module.add("token_id", DType::kInt32, {rows}, true, {1}, {most}); + module.add("position_id", DType::kInt32, {rows}, true, {1}, {most}); + module.add("attention_mask", DType::kFloat32, {rows, prefill ? -1 : g.capacity + 1}, true, + {1, g.capacity + 1}, {most, g.capacity + most}); + if (prefill) { + module.add("visual_embedding", g.cache_dtype, {-1, hidden}, true, {1, hidden}, + {most, hidden}); + module.add("use_visual_embedding", DType::kInt32, {-1, 1}, true, {1, 1}, {most, 1}); + } + module.add("logits", DType::kFloat32, {1, vocab}, false); + for (int i = 0; i < g.deltanet_layers; ++i) { + const auto n = std::to_string(i); + for (const char* stem : {"conv_state_", "present_conv_"}) + module.add(stem + n, DType::kFloat32, {g.conv_width, g.conv_kernel}, stem[0] == 'c'); + for (const char* stem : {"ssm_state_", "present_ssm_"}) + module.add(stem + n, DType::kFloat32, + {g.deltanet_heads, g.deltanet_head_dim, g.deltanet_head_dim}, + stem[0] == 's'); + } + for (int i = 0; i < g.attention_layers; ++i) { + const auto n = std::to_string(i); + module.add("cache_k_" + n, g.cache_dtype, {g.capacity, g.kv_width}, true); + module.add("cache_v_" + n, g.cache_dtype, {g.capacity, g.kv_width}, true); + // Outputs are sized for the profile's largest chunk, as the TensorRT module allocates them. + module.add("present_k_" + n, g.cache_dtype, {rows, g.kv_width}, false, {}, + {most, g.kv_width}); + module.add("present_v_" + n, g.cache_dtype, {rows, g.kv_width}, false, {}, + {most, g.kv_width}); + } + return module; +} + +void engine_contracts() { + using trtmc::DType; + const auto geometry = small_geometry(); + for (const bool prefill : {false, true}) { + const std::string kind = prefill ? "prefill" : "decoder"; + auto engine = decoder_engine(geometry, prefill, 32, 4); + validate_decoder_engine(engine, geometry, prefill, 32, 4); + auto wrong_ssm = engine; + wrong_ssm.tensors["ssm_state_1"].shape = {2, 3, 2}; + check(fails([&] { validate_decoder_engine(wrong_ssm, geometry, prefill, 32, 4); }), + kind + ": a recurrent state of another shape is rejected"); + auto wrong_present = engine; + wrong_present.tensors["present_conv_0"].dtype = DType::kFloat16; + check(fails([&] { validate_decoder_engine(wrong_present, geometry, prefill, 32, 4); }), + kind + ": a present state of another dtype is rejected"); + auto wrong_logits = engine; + wrong_logits.tensors["logits"].shape = {1, 16}; + check(fails([&] { validate_decoder_engine(wrong_logits, geometry, prefill, 32, 4); }), + kind + ": logits narrower than the vocabulary are rejected"); + auto missing = engine; + missing.tensors.erase("present_v_0"); + check(fails([&] { validate_decoder_engine(missing, geometry, prefill, 32, 4); }), + kind + ": a missing present output is rejected"); + auto extra = engine; + extra.add("unexpected", DType::kInt32, {1}, true); + check(fails([&] { validate_decoder_engine(extra, geometry, prefill, 32, 4); }), + kind + ": an input the runtime does not bind is rejected"); + } + auto prefill = decoder_engine(geometry, true, 32, 4); + prefill.tensors["visual_embedding"].shape = {-1, 8}; + check(fails([&] { validate_decoder_engine(prefill, geometry, true, 32, 4); }), + "a vision row of another width is rejected"); + // Row inputs must be dynamic in the prefill engine and static in the decoder. + auto fixed_rows = decoder_engine(geometry, true, 32, 4); + fixed_rows.tensors["token_id"].shape = {8}; + check(fails([&] { validate_decoder_engine(fixed_rows, geometry, true, 32, 4); }), + "a prefill engine with a fixed row count is rejected"); + auto dynamic_rows = decoder_engine(geometry, false, 32, 4); + dynamic_rows.tensors["position_id"].shape = {-1}; + dynamic_rows.tensors["position_id"].maximum = {1}; + check(fails([&] { validate_decoder_engine(dynamic_rows, geometry, false, 32, 4); }), + "a decoder engine with a dynamic row count is rejected"); + + // Every chunk input's profile must admit chunks of 1 to 8 rows. + const auto chunked = decoder_engine(geometry, true, 32, 4); + check(prefill_rows(chunked, geometry, 4) == 8, "the prefill chunk has 8 rows"); + const std::vector>> narrow_maxima{ + {"token_id", {17}}, + {"position_id", {4}}, + {"attention_mask", {8, 23}}, + {"visual_embedding", {4, 4}}, + {"use_visual_embedding", {4, 1}}}; + for (const auto& [name, maximum] : narrow_maxima) { + auto engine = chunked; + engine.tensors[name].maximum = maximum; + check(fails([&] { prefill_rows(engine, geometry, 4); }), + "a prefill profile whose " + name + " maximum is too small is rejected"); + } + // A present K/V output smaller than the largest chunk would be read past its end. + for (const char* name : {"present_k_0", "present_v_0"}) { + auto engine = chunked; + engine.tensors[name].shape = {1, geometry.kv_width}; + check(fails([&] { prefill_rows(engine, geometry, 4); }), + std::string("a prefill engine whose ") + name + " holds one row is rejected"); + } + auto late_start = chunked; + late_start.tensors["attention_mask"].minimum = {2, geometry.capacity + 2}; + check(fails([&] { prefill_rows(late_start, geometry, 4); }), + "a prefill profile that does not admit one-row chunks is rejected"); + + FakeModule vision; + vision.add("patches", DType::kFloat32, {-1, 12}, true, {16, 12}, {64, 12}); + vision.add("position_ids", DType::kInt32, {-1}, true, {16}, {64}); + vision.add("window_index", DType::kInt32, {-1}, true, {16}, {64}); + vision.add("merge_index", DType::kInt32, {-1}, true, {4}, {16}); + vision.add("visual_features", DType::kFloat16, {-1, 4}, false); + validate_vision_engine(vision, DType::kFloat16, 12, 4, 64); + auto bad_index = vision; + bad_index.tensors["window_index"].dtype = DType::kFloat32; + check(fails([&] { validate_vision_engine(bad_index, DType::kFloat16, 12, 4, 64); }), + "a grid index of another dtype is rejected"); + auto bad_profile = vision; + bad_profile.tensors["merge_index"].maximum = {64}; + check(fails([&] { validate_vision_engine(bad_profile, DType::kFloat16, 12, 4, 64); }), + "a merge-index profile that does not match the patch capacity is rejected"); + auto bad_features = vision; + bad_features.tensors["visual_features"].shape = {-1, 8}; + check(fails([&] { validate_vision_engine(bad_features, DType::kFloat16, 12, 4, 64); }), + "features of another width are rejected"); + // The smallest slice is one 4 x 4 block: 16 patches and 4 merged rows. + const std::vector>> late_minima{ + {"patches", {32, 12}}, + {"position_ids", {32}}, + {"window_index", {32}}, + {"merge_index", {8}}}; + for (const auto& [name, minimum] : late_minima) { + auto engine = vision; + engine.tensors[name].minimum = minimum; + check(fails([&] { validate_vision_engine(engine, DType::kFloat16, 12, 4, 64); }), + "a vision profile whose " + name + " excludes the smallest slice is rejected"); + } +} + +void metadata_parsing() { + const auto object = nlohmann::json::parse(R"({ + "int": 7, "fraction": 7.5, "flag": true, "huge": 8589934592, "negative": -3, "nothing": null, + "float3": [0.5, 1, 0.25], "two": [0.5, 0.5], "four": [1, 2, 3, 4], "bool3": [0.5, true, 0.5], + "big3": [1e39, 0.5, 0.5], "ids": [3, 5], "repeated": [3, 3], "outside": [3, 99], + "fraction_ids": [3.0], "empty": []})"); + check(json_int32(object, "int", 1) == 7, "an integer field is read"); + for (const char* name : {"fraction", "flag", "huge", "negative", "nothing", "missing"}) + check(fails([&] { json_int32(object, name, 0); }), + std::string("integer field '") + name + "' is rejected"); + check(json_float3(object, "float3") == std::array{0.5F, 1.0F, 0.25F}, + "three numbers are read"); + for (const char* name : {"two", "four", "bool3", "big3", "int"}) + check(fails([&] { json_float3(object, name); }), + std::string("float triple '") + name + "' is rejected"); + check(json_token_ids(object, "ids", 10) == std::vector{3, 5}, "token ids read"); + for (const char* name : {"repeated", "outside", "fraction_ids", "empty", "int"}) + check(fails([&] { json_token_ids(object, name, 10); }), + std::string("token id list '") + name + "' is rejected"); + check(checked_product(4, 256, "kv") == 1024, "a small product is kept"); + check(fails([&] { checked_product(65536, 65536, "kv"); }), "an int32 overflow is rejected"); + + const auto parse = [](const std::string& text) { + return parse_json_unique(text.data(), text.size(), "test.json"); + }; + check(parse(R"({"a": {"b": 1}, "c": {"b": 2}})")["c"]["b"] == 2, + "the same key in sibling objects is accepted"); + check(fails([&] { parse(R"({"a": 1, "a": 2})"); }), "a repeated top-level key is rejected"); + check(fails([&] { parse(R"({"x": [{"b": 1, "b": 2}]})"); }), + "a repeated nested key is rejected"); + check_vocabulary(248094, 248094); + check_vocabulary(248094, 248320); + check(fails([&] { check_vocabulary(248321, 248320); }), + "token ids beyond the embedding rows are rejected"); +} + +void sampling() { + SamplingOptions options; + Sampler greedy(options); + check(greedy.sample({0.5F, 2.0F, 1.0F}) == 1, "greedy picks the argmax"); + const float nan = std::numeric_limits::quiet_NaN(); + const float inf = std::numeric_limits::infinity(); + check(fails([&] { greedy.sample({0.5F, nan, 1.0F}); }), "NaN logits are rejected"); + check(fails([&] { greedy.sample({0.5F, inf, 1.0F}); }), "infinite logits are rejected"); + options.top_k = 0; + options.seed = 7; + Sampler drawing(options); + check(fails([&] { drawing.sample({nan, 0.0F}); }), "NaN logits are rejected when sampling"); + options.seed = -2; + check(rejects([&] { Sampler invalid(options); }), "a seed below -1 is rejected"); + + // Request values are checked before FP32 narrows them. + const auto valid = sampling_options(0.7, 40, 0.9, 7); + check(valid.temperature == 0.7F && valid.top_k == 40 && valid.top_p == 0.9F && valid.seed == 7, + "valid sampling values are kept"); + check(sampling_options(0.0, 1, 1.0, -1).temperature == 0.0F, "a zero temperature is greedy"); + const double nan_double = std::numeric_limits::quiet_NaN(); + for (const double temperature : {-1e-50, 1e-50, 1e39, nan_double}) + check(rejects([&] { sampling_options(temperature, 1, 1.0, -1); }), + "temperature " + std::to_string(temperature) + " is rejected"); + for (const double top_p : {1.00000001, 0.0, 1e-50, -0.5, nan_double}) + check(rejects([&] { sampling_options(1.0, 1, top_p, -1); }), + "top_p " + std::to_string(top_p) + " is rejected"); + for (const std::int64_t top_k : {std::int64_t{-1}, std::int64_t{1} << 31}) + check(rejects([&] { sampling_options(1.0, top_k, 1.0, -1); }), + "an invalid top_k is rejected"); + check(rejects([&] { sampling_options(1.0, 1, 1.0, -2); }), "a seed below -1 is rejected"); +} + +void planned_image_rows() { + // The rows counted from the slice plan before any allocation equal the prepared slices' rows. + ImageSettings settings; + for (const auto& [height, width] : std::vector>{ + {382, 640}, {468, 931}, {448, 448}, {10, 10}, {1000, 1000}, {300, 1200}}) { + const auto pixels = pattern(height, width); + trtmc::internal::ImageView image{}; + image.data = pixels.data(); + image.byte_size = pixels.size(); + image.height = static_cast(height); + image.width = static_cast(width); + image.channels = 3; + image.format = trtmc::internal::ImageFormat::UInt8; + std::int64_t prepared = 0; + for (const auto& slice : prepare_image(settings, image).slices) + prepared += slice.tokens(); + check(planned_rows(settings, plan_image(settings, image)) == prepared, + "planned rows of " + std::to_string(height) + "x" + std::to_string(width) + + " equal the prepared slices"); + } +} + +std::string message_of(const std::function& callable) { + try { + callable(); + } catch (const std::exception& error) { + return error.what(); + } + return ""; +} + +void planning_before_pixels() { + // A tiny engine capacity: one 4 x 4 block of patches per slice. + ImageSettings settings; + settings.scale_resolution = 56; + settings.max_patches = 16; + settings.validate(); + const std::int32_t height = 10, width = 200; + const auto plan = plan_slices(settings, height, width); + check(static_cast(plan.source_height / 14) * (plan.source_width / 14) > 16, + "the elongated test image plans a slice beyond the capacity"); + // The float pixels hold a NaN: the slice plan must reject the image before they are read. + std::vector pixels(static_cast(height) * width * 3, 0.5F); + pixels[7] = std::numeric_limits::quiet_NaN(); + trtmc::internal::ImageView image{}; + image.data = pixels.data(); + image.byte_size = pixels.size() * sizeof(float); + image.height = height; + image.width = width; + image.channels = 3; + image.format = trtmc::internal::ImageFormat::Float32; + check(message_of([&] { prepare_image(settings, image); }).find("patch capacity") != + std::string::npos, + "the slice plan is checked before the pixels are converted"); +} + +void slice_bounds() { + ImageSettings settings; + settings.max_slice_nums = kMaxSliceNums; + settings.validate(); + for (const std::int32_t count : {kMaxSliceNums + 1, std::numeric_limits::max()}) { + auto large = settings; + large.max_slice_nums = count; + check(rejects([&] { large.validate(); }), + "max_slice_nums " + std::to_string(count) + " is rejected"); + } + // The largest accepted slice count on the largest square image. + const std::int32_t side = std::numeric_limits::max(); + const auto plan = plan_slices(settings, side, side); + check(plan.rows == 64 && plan.cols == 64, "the largest image plans a 64 x 64 grid"); + // Dimensions that the storage does not hold are rejected before the slice plan. + const std::vector pixel{1, 2, 3}; + trtmc::internal::ImageView image{}; + image.data = pixel.data(); + image.byte_size = pixel.size(); + image.height = static_cast(side); + image.width = static_cast(side); + image.channels = 3; + image.format = trtmc::internal::ImageFormat::UInt8; + check(message_of([&] { plan_image(settings, image); }).find("storage") != std::string::npos, + "the slice plan checks the image storage first"); +} + +void normalization_bounds() { + ImageSettings settings; + settings.validate(); + auto tiny = settings; + tiny.stddev[1] = 1e-40F; + check(rejects([&] { tiny.validate(); }), "a vanishing std is rejected"); + auto large = settings; + large.mean[0] = 1e38F; + check(rejects([&] { large.validate(); }), "a mean that overflows FP32 at 255x is rejected"); + auto narrow = settings; + narrow.stddev[2] = 1e-6F; + check(rejects([&] { narrow.validate(); }), "normalized pixels beyond FP16 are rejected"); + auto patch = settings; + patch.patch_size = std::numeric_limits::max(); + check(rejects([&] { patch.validate(); }), "a patch size whose 4x overflows int32 is rejected"); + auto resolution = settings; + resolution.scale_resolution = 1000000; + check(rejects([&] { resolution.validate(); }), + "a nominal slice beyond the vision engine's patches is rejected"); +} + +// GPT-2 byte-level alphabet: one vocabulary token per byte, in byte order. +std::vector byte_alphabet() { + std::vector direct; + for (int b = 33; b <= 126; ++b) + direct.push_back(b); + for (int b = 161; b <= 172; ++b) + direct.push_back(b); + for (int b = 174; b <= 255; ++b) + direct.push_back(b); + std::vector tokens(256); + int displaced = 0; + for (int b = 0; b < 256; ++b) { + const bool kept = std::find(direct.begin(), direct.end(), b) != direct.end(); + const auto codepoint = static_cast(kept ? b : 256 + displaced++); + std::string utf8; + if (codepoint < 0x80) { + utf8.push_back(static_cast(codepoint)); + } else { + utf8.push_back(static_cast(0xC0 | (codepoint >> 6))); + utf8.push_back(static_cast(0x80 | (codepoint & 0x3F))); + } + tokens[static_cast(b)] = utf8; + } + return tokens; +} + +// A minimal tokenizer.json of the pinned schema: bytes, "xy" (256), "xyx" (257), one added token. +nlohmann::json small_tokenizer() { + nlohmann::json vocab = nlohmann::json::object(); + const auto bytes = byte_alphabet(); + for (std::size_t i = 0; i < bytes.size(); ++i) + vocab[bytes[i]] = i; + vocab["xy"] = 256; + vocab["xyx"] = 257; + nlohmann::json byte_level = nlohmann::json::object(); + byte_level["type"] = "ByteLevel"; + byte_level["add_prefix_space"] = false; + byte_level["trim_offsets"] = false; + byte_level["use_regex"] = false; + nlohmann::json split = nlohmann::json::object(); + split["type"] = "Split"; + split["pattern"]["Regex"] = + R"((?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+|\p{N}| ?[^\s\p{L}\p{M}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+)"; + split["behavior"] = "Isolated"; + split["invert"] = false; + nlohmann::json added = nlohmann::json::object(); + added["id"] = 258; + added["content"] = "<|end|>"; + for (const char* flag : {"single_word", "lstrip", "rstrip", "normalized"}) + added[flag] = false; + added["special"] = true; + nlohmann::json model = nlohmann::json::object(); + model["type"] = "BPE"; + model["dropout"] = nullptr; + model["unk_token"] = nullptr; + model["continuing_subword_prefix"] = ""; + model["end_of_word_suffix"] = ""; + model["fuse_unk"] = false; + model["byte_fallback"] = false; + model["ignore_merges"] = false; + model["vocab"] = vocab; + model["merges"] = nlohmann::json::array(); + model["merges"].push_back(nlohmann::json::array({"xy", "x"})); + model["merges"].push_back(nlohmann::json::array({"x", "y"})); + nlohmann::json root = nlohmann::json::object(); + root["version"] = "1.0"; + root["truncation"] = nullptr; + root["padding"] = nullptr; + root["added_tokens"] = nlohmann::json::array({added}); + root["normalizer"]["type"] = "NFC"; + root["pre_tokenizer"]["type"] = "Sequence"; + root["pre_tokenizer"]["pretokenizers"] = nlohmann::json::array({split, byte_level}); + root["post_processor"] = byte_level; + root["decoder"] = byte_level; + root["model"] = model; + return root; +} + +std::unique_ptr load(const nlohmann::json& json) { + const auto text = json.dump(); + return create_tokenizer(text.data(), text.size()); +} + +// The ids of a text that fits a generous limit. +std::vector ids(const Tokenizer& tokenizer, std::string_view text) { + const auto result = tokenizer.encode(text, 1000); + check(result.has_value(), "the text fits 1000 ids"); + return result.value_or(std::vector{}); +} + +void bpe_merges() { + // Hugging Face tokenizers merge one occurrence at a time and re-rank after each + // merge: in "xyxy" the first "xy" joins the next "x" (rank 0) before the second + // "xy" (rank 1) can form. Expected ids from tokenizers 0.23.3 on the same file. + const auto tokenizer = load(small_tokenizer()); + check(ids(*tokenizer, "xyxy") == std::vector{257, 121}, + "xyxy merges as tokenizers does"); + check(ids(*tokenizer, "xyxyxy") == std::vector{257, 121, 256}, + "xyxyxy merges as tokenizers does"); + check(ids(*tokenizer, "x xyxy") == std::vector{120, 32, 257, 121}, + "a spaced word merges as tokenizers does"); + check(ids(*tokenizer, "yxyx<|end|>") == std::vector{121, 257, 258}, + "added tokens split the text"); + + // A non-special added token with a character outside the byte alphabet decodes as its own + // UTF-8 text (tokenizers 0.23.3 on the same file: "你é", not "你\uFFFD"). + auto with_text_token = small_tokenizer(); + nlohmann::json text_token = with_text_token["added_tokens"][0]; + text_token["id"] = 259; + text_token["content"] = "\xE4\xBD\xA0\xC3\xA9"; + text_token["special"] = false; + with_text_token["added_tokens"].push_back(text_token); + const auto text_tokenizer = load(with_text_token); + check(text_tokenizer->decode({259}) == "\xE4\xBD\xA0\xC3\xA9", + "an added text token decodes whole"); + check(text_tokenizer->decode({257, 259, 121}) == "xyx\xE4\xBD\xA0\xC3\xA9y", + "byte-level tokens around an added text token decode as tokenizers does"); + check(text_tokenizer->decode({195, 259}) == "\xEF\xBF\xBD\xE4\xBD\xA0\xC3\xA9", + "a dangling lead byte before an added text token is replaced"); + check(ids(*text_tokenizer, "a\xE4\xBD\xA0\xC3\xA9" + "b") == std::vector{97, 259, 98}, + "an added text token is matched whole"); + + auto unknown_result = small_tokenizer(); + unknown_result["model"]["merges"].push_back(nlohmann::json::array({"y", "y"})); + check(fails([&] { load(unknown_result); }), "a merge whose result is not a token is rejected"); + auto added_operand = small_tokenizer(); + added_operand["model"]["vocab"]["xy<|end|>"] = 258; + added_operand["added_tokens"][0]["id"] = 259; + added_operand["model"]["merges"].push_back(nlohmann::json::array({"xy", "<|end|>"})); + check(fails([&] { load(added_operand); }), + "a merge of a token outside the base vocabulary is rejected"); + auto repeated = small_tokenizer().dump(); + // The same valid value twice: nlohmann alone would keep one and accept the file. + repeated.replace(repeated.find("\"dropout\":null"), 14, "\"dropout\":null,\"dropout\":null"); + check(fails([&] { create_tokenizer(repeated.data(), repeated.size()); }), + "a tokenizer.json that repeats a key is rejected"); + auto wrapped_id = small_tokenizer(); + wrapped_id["model"]["vocab"]["xyx"] = 4294967296LL + 257; + check(fails([&] { load(wrapped_id); }), "a vocabulary id that wraps to a valid id is rejected"); + auto fractional_added = small_tokenizer(); + fractional_added["added_tokens"][0]["id"] = 258.0; + check(fails([&] { load(fractional_added); }), "a fractional added-token id is rejected"); +} + +void bounded_encoding() { + const auto tokenizer = load(small_tokenizer()); + // The longest entry is the added token "<|end|>": 7 code points, 28 per id. + check(tokenizer->max_code_points(10) == 280, "ten ids stand for at most 280 code points"); + check(tokenizer->encode("xyxy", 2) == std::vector{257, 121}, + "a text that needs exactly the limit fits"); + check(!tokenizer->encode("xyxy", 1), "a text that needs one id more than the limit does not"); + check(!tokenizer->encode(std::string(281, 'x'), 10), + "a text longer than the limit can stand for is refused"); + check(!tokenizer->encode(std::string(std::size_t{1} << 26, 'x'), 4096), + "a 64 MiB text is refused against a 4096-id limit"); + // Code points as ICU decodes UTF-8: each maximal ill-formed subpart is one U+FFFD. + check(code_points("a\x80\x80" + "b") == 4, + "stray continuation bytes count one each"); + check(code_points("\xE4\xBD") == 1, "a truncated sequence counts once"); + check(code_points("\xE4\xBD\xA0\xC3\xA9") == 2, "well-formed text counts its code points"); +} + +} // namespace + +int main() { + try { + slice_plans(); + grid_indices(); + resampling(); + placeholders(); + conversations(); + pre_tokenization(); + engine_contracts(); + metadata_parsing(); + sampling(); + normalization_bounds(); + slice_bounds(); + planning_before_pixels(); + planned_image_rows(); + bpe_merges(); + bounded_encoding(); + } catch (const std::exception& error) { + std::cerr << "FAIL: unexpected exception: " << error.what() << '\n'; + return 1; + } + if (failures != 0) { + std::cerr << failures << " check(s) failed\n"; + return 1; + } + std::cout << "test_minicpmv4_6_host passed\n"; + return 0; +} diff --git a/families/minicpmv4_6/tests/data/README.md b/families/minicpmv4_6/tests/data/README.md new file mode 100644 index 0000000000..7a44b13c25 --- /dev/null +++ b/families/minicpmv4_6/tests/data/README.md @@ -0,0 +1,13 @@ +# MiniCPM-V 4.6 image fixtures + +- `test_img.jpeg` is a byte-identical copy of the repository's shared vehicle + test photograph (see `ASSET_LICENSES.md`); it exercises a sliced image (a + source thumbnail plus a 1 x 2 slice grid) and image-conditioned color + recognition. +- `orc_test_img.jpeg` is a byte-identical copy of the project-created OCR + screenshot (see `ASSET_LICENSES.md`); it exercises a wider slice grid and + text reading. + +The E2E decodes each fixture once with Pillow and writes it as lossless PNG, so +the native CLI, the SDK consumers and the Transformers reference read identical +RGB values regardless of their JPEG decoders. diff --git a/families/minicpmv4_6/tests/data/orc_test_img.jpeg b/families/minicpmv4_6/tests/data/orc_test_img.jpeg new file mode 100644 index 0000000000..b8da05838c Binary files /dev/null and b/families/minicpmv4_6/tests/data/orc_test_img.jpeg differ diff --git a/families/minicpmv4_6/tests/data/test_img.jpeg b/families/minicpmv4_6/tests/data/test_img.jpeg new file mode 100644 index 0000000000..095c03620f Binary files /dev/null and b/families/minicpmv4_6/tests/data/test_img.jpeg differ diff --git a/families/minicpmv4_6/tests/manifests/minicpm-v-4.6-fp32.json b/families/minicpmv4_6/tests/manifests/minicpm-v-4.6-fp32.json new file mode 100644 index 0000000000..ada69bacd5 --- /dev/null +++ b/families/minicpmv4_6/tests/manifests/minicpm-v-4.6-fp32.json @@ -0,0 +1,30 @@ +{ + "name": "minicpm-v-4.6-fp32", + "hf_id": "openbmb/MiniCPM-V-4.6", + "hf_revision": "97328f3c2d70c4645b6a35594807eb6932068635", + "bundle": "minicpm-v-4.6-fp32.bundle", + "family": "minicpmv4_6", + "task": "images_text_to_text", + "precision": "fp32", + "max_sequence_length": 2048, + "tensor_parallel_size": 1, + "testcases": [ + { + "name": "minicpm-v-4.6-fp32-car-color", + "premerge": true, + "images": ["families/minicpmv4_6/tests/data/test_img.jpeg"], + "prompt": "What color is the car? Answer in one word.", + "max_new_tokens": 8, + "oracle": "token_exact", + "expected_answer": "white" + }, + { + "name": "minicpm-v-4.6-fp32-ocr-first-line", + "images": ["families/minicpmv4_6/tests/data/orc_test_img.jpeg"], + "prompt": "What is the first line of text in the image? Reply with the text only.", + "max_new_tokens": 32, + "oracle": "token_exact", + "expected_mentions": ["DeepSeek-OCR-2"] + } + ] +} diff --git a/families/minicpmv4_6/tests/manifests/minicpm-v-4.6.json b/families/minicpmv4_6/tests/manifests/minicpm-v-4.6.json new file mode 100644 index 0000000000..2502daf8e4 --- /dev/null +++ b/families/minicpmv4_6/tests/manifests/minicpm-v-4.6.json @@ -0,0 +1,50 @@ +{ + "name": "minicpm-v-4.6", + "hf_id": "openbmb/MiniCPM-V-4.6", + "hf_revision": "97328f3c2d70c4645b6a35594807eb6932068635", + "bundle": "minicpm-v-4.6.bundle", + "family": "minicpmv4_6", + "task": "images_text_to_text", + "precision": "fp16", + "max_sequence_length": 4096, + "tensor_parallel_size": 1, + "testcases": [ + { + "name": "minicpm-v-4.6-car-color", + "premerge": true, + "images": ["families/minicpmv4_6/tests/data/test_img.jpeg"], + "prompt": "What color is the car? Answer in one word.", + "max_new_tokens": 8, + "oracle": "teacher_forced", + "expected_answer": "white", + "sdk": true + }, + { + "name": "minicpm-v-4.6-ocr-first-line", + "premerge": true, + "images": ["families/minicpmv4_6/tests/data/orc_test_img.jpeg"], + "prompt": "What is the first line of text in the image? Reply with the text only.", + "max_new_tokens": 32, + "oracle": "teacher_forced", + "expected_mentions": ["DeepSeek-OCR-2"] + }, + { + "name": "minicpm-v-4.6-two-images", + "images": [ + "families/minicpmv4_6/tests/data/test_img.jpeg", + "families/minicpmv4_6/tests/data/orc_test_img.jpeg" + ], + "prompt": "Describe the first image and then the second image, one short sentence each.", + "max_new_tokens": 64, + "oracle": "teacher_forced", + "expected_mentions": ["white", "DeepSeek-OCR-2"] + }, + { + "name": "minicpm-v-4.6-text-only", + "prompt": "What is the capital of France? Answer in one word.", + "max_new_tokens": 8, + "oracle": "teacher_forced", + "expected_answer": "Paris" + } + ] +} diff --git a/families/minicpmv4_6/tests/sdk_consumer.c b/families/minicpmv4_6/tests/sdk_consumer.c new file mode 100644 index 0000000000..281d075328 --- /dev/null +++ b/families/minicpmv4_6/tests/sdk_consumer.c @@ -0,0 +1,160 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +/* Public C SDK consumer for the family-owned end-to-end test. + * + * BUNDLE RUNTIME_ROOT RGB_F32 HEIGHT WIDTH PROMPT MAX_NEW_TOKENS + * + * Runs images_text_to_text on one user message (image, then text) and prints + * {"text": ..., "token_ids": [...]} as JSON. + */ +#include +#include +#include +#include +#include +#include +#include + +static trtmc_string_view text(const char* value) { + const trtmc_string_view result = {value, (uint64_t)strlen(value)}; + return result; +} +static uint32_t dimension(const char* value) { + char* end = NULL; + const unsigned long parsed = strtoul(value, &end, 10); + return (!end || *end || parsed == 0 || parsed > 65535UL) ? 0U : (uint32_t)parsed; +} +static void json_string(trtmc_string_view value) { + uint64_t i; + putchar('"'); + for (i = 0; i < value.size; ++i) { + const unsigned char byte = (unsigned char)value.data[i]; + if (byte == '"' || byte == '\\') { + putchar('\\'); + putchar(byte); + } else if (byte < 32) { + printf("\\u%04x", (unsigned)byte); + } else { + putchar(byte); + } + } + putchar('"'); +} + +int main(int argc, char** argv) { + const trtmc_core_api_v1* core = NULL; + const trtmc_api_header* header = NULL; + const trtmc_images_text_to_text_api_v1* task = NULL; + trtmc_model* model = NULL; + trtmc_result* result = NULL; + trtmc_error* error = NULL; + trtmc_load_options_v1 options = {0}; + trtmc_images_text_part_v1 parts[2]; + trtmc_images_text_message_v1 message; + trtmc_images_text_to_text_request_v1 request = {0}; + trtmc_config_entry_v1 entry; + trtmc_config_view_v1 config; + trtmc_text_result_view_v1 view = {0}; + float* pixels = NULL; + FILE* file = NULL; + uint32_t height, width; + size_t count; + long long limit; + uint64_t i; + int status = 1; + + if (argc != 8) { + fprintf(stderr, + "Usage: %s BUNDLE RUNTIME_ROOT RGB_F32 HEIGHT WIDTH PROMPT MAX_NEW_TOKENS\n", + argv[0]); + return 2; + } + height = dimension(argv[4]); + width = dimension(argv[5]); + limit = strtoll(argv[7], NULL, 10); + if (!height || !width || limit <= 0) { + fprintf(stderr, "invalid image dimensions or token limit\n"); + return 2; + } + count = (size_t)height * width * 3; + pixels = (float*)malloc(count * sizeof(float)); + file = fopen(argv[3], "rb"); + if (!pixels || !file || fread(pixels, sizeof(float), count, file) != count || + fgetc(file) != EOF || ferror(file)) { + fprintf(stderr, "input must contain exactly HEIGHT x WIDTH x 3 float32 RGB values\n"); + goto cleanup; + } + fclose(file); + file = NULL; + + if (trtmc_get_api(1, 0, &core) != TRTMC_OK || !core) { + fprintf(stderr, "unable to obtain the v1 C API\n"); + goto cleanup; + } + options.struct_size = sizeof(options); + options.runtime_root = text(argv[2]); + if (core->model_load(text(argv[1]), &options, &model, &error) != TRTMC_OK) + goto cleanup; + if (core->model_get_task_api(model, text(TRTMC_TASK_IMAGES_TEXT_TO_TEXT), 1, 0, &header, + &error) != TRTMC_OK) + goto cleanup; + if (!header || header->byte_size < sizeof(*task)) { + fprintf(stderr, "incomplete images_text_to_text C table\n"); + goto cleanup; + } + task = (const trtmc_images_text_to_text_api_v1*)header; + + parts[0].kind = TRTMC_MEDIA_IMAGE; + parts[0].content.image = (trtmc_image_input_v1){pixels, count * sizeof(float), height, width, + 3, TRTMC_IMAGE_FLOAT32}; + parts[1].kind = TRTMC_MEDIA_TEXT; + parts[1].content.text = text(argv[6]); + message.role = TRTMC_ROLE_USER; + message.parts = parts; + message.part_count = 2; + request.messages = &message; + request.message_count = 1; + entry.name = text("max_new_tokens"); + entry.value.kind = TRTMC_CONFIG_I64; + entry.value.as.i64 = limit; + config.entries = &entry; + config.count = 1; + if (task->run(model, &request, &config, &result, &error) != TRTMC_OK) + goto cleanup; + /* The result must stay readable after its input and model are gone. */ + free(pixels); + pixels = NULL; + core->model_release(model); + model = NULL; + if (task->result_view(result, &view, &error) != TRTMC_OK) + goto cleanup; + if (!view.token_ids.size || view.token_ids.size > (uint64_t)limit) { + fprintf(stderr, "images_text_to_text must return 1..MAX_NEW_TOKENS generated tokens\n"); + goto cleanup; + } + printf("{\"text\":"); + json_string(view.text); + printf(",\"token_ids\":["); + for (i = 0; i < view.token_ids.size; ++i) + printf(i ? ",%" PRId32 : "%" PRId32, view.token_ids.data[i]); + puts("]}"); + status = 0; + +cleanup: + if (error) { + const trtmc_string_view message_text = core->error_message(error); + fprintf(stderr, "%.*s\n", (int)message_text.size, message_text.data); + core->error_release(error); + } + if (result) + core->result_release(result); + if (model) + core->model_release(model); + if (file) + fclose(file); + free(pixels); + return status; +} diff --git a/families/minicpmv4_6/tests/sdk_consumer.cpp b/families/minicpmv4_6/tests/sdk_consumer.cpp new file mode 100644 index 0000000000..e9aa28d78e --- /dev/null +++ b/families/minicpmv4_6/tests/sdk_consumer.cpp @@ -0,0 +1,67 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +/* Public C++ SDK consumer for the family-owned end-to-end test. + * + * BUNDLE RUNTIME_ROOT RGB_F32 HEIGHT WIDTH PROMPT MAX_NEW_TOKENS + * + * Runs images_text_to_text on one user message (image, then text) and prints + * {"text": ..., "token_ids": [...]} as JSON. + */ +#include +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char** argv) { + if (argc != 8) { + std::cerr << "Usage: " << argv[0] + << " BUNDLE RUNTIME_ROOT RGB_F32 HEIGHT WIDTH PROMPT MAX_NEW_TOKENS\n"; + return 2; + } + try { + const auto height = std::stoul(argv[4]); + const auto width = std::stoul(argv[5]); + const auto limit = std::stoll(argv[7]); + if (!height || !width || height > 65535 || width > 65535 || limit <= 0) + throw std::invalid_argument("invalid image dimensions or token limit"); + std::vector pixels(height * width * 3); + std::ifstream input(argv[3], std::ios::binary | std::ios::ate); + if (!input || static_cast(input.tellg()) != pixels.size() * sizeof(float)) + throw std::invalid_argument("input must contain HEIGHT x WIDTH x 3 float32 RGB values"); + input.seekg(0); + input.read(reinterpret_cast(pixels.data()), + static_cast(pixels.size() * sizeof(float))); + if (!input) + throw std::runtime_error("incomplete RGB input"); + trtmc::LoadOptions options; + options.runtime_root = argv[2]; + auto model = trtmc::Model::load(argv[1], options); + const auto task = model.task(); + std::vector parts; + parts.emplace_back(trtmc::ImageInput{{pixels.data(), pixels.size()}, + static_cast(height), + static_cast(width)}); + parts.emplace_back(trtmc::TextPart{argv[6]}); + const auto result = task.run(trtmc::ImagesTextToTextRequest::from_parts(std::move(parts)), + {{"max_new_tokens", static_cast(limit)}}); + const auto ids = result.token_ids(); + if (ids.empty() || ids.size() > static_cast(limit)) + throw std::runtime_error( + "images_text_to_text must return 1..MAX_NEW_TOKENS generated tokens"); + std::cout << nlohmann::json( + {{"text", std::string(result.text())}, + {"token_ids", std::vector(ids.begin(), ids.end())}}) + .dump() + << '\n'; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/families/minicpmv4_6/tests/test_builder_config.py b/families/minicpmv4_6/tests/test_builder_config.py new file mode 100644 index 0000000000..285a93768f --- /dev/null +++ b/families/minicpmv4_6/tests/test_builder_config.py @@ -0,0 +1,296 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""CPU checks of the builder's checkpoint-configuration rules (no TensorRT, no checkpoint).""" + +from __future__ import annotations + +import json +import math +import time +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from families.minicpmv4_6 import config as cfg +from families.minicpmv4_6 import prompt + +_PROCESSOR = { + "image_processor_type": "MiniCPMV4_6ImageProcessor", + "processor_class": "MiniCPMV4_6Processor", + "max_slice_nums": 9, + "scale_resolution": 448, + "patch_size": 14, + "use_image_id": True, + "slice_mode": True, + "image_mean": [0.5, 0.5, 0.5], + "image_std": [0.5, 0.5, 0.5], +} + + +_VISION = { + "model_type": "minicpmv4_6_vision", "hidden_act": "gelu_pytorch_tanh", "num_channels": 3, "image_size": 980, + "patch_size": 14, "hidden_size": 1152, "intermediate_size": 4304, "num_hidden_layers": 27, + "num_attention_heads": 16, "layer_norm_eps": 1e-06, +} + + +def _write(tmp_path, name, value): + path = tmp_path / name + path.write_text(value if isinstance(value, str) else json.dumps(value), encoding="utf-8") + return path + + +@pytest.mark.parametrize(("value", "expected"), [ + (True, 1), (1, True), (0, False), (3.0, 3), ([2.0, 2], [2, 2]), ([2, 2, 2], [2, 2]), (None, "16x"), +]) +def test_a_required_value_must_also_have_the_json_type(value, expected): + with pytest.raises(ValueError, match="requires"): + cfg._require({"key": value}, "key", expected) + + +def test_a_required_value_may_be_restated_exactly_or_left_out(): + cfg._require({"key": [2, 2]}, "key", [2, 2]) + cfg._require({}, "key", "16x", default="16x") + + +@pytest.mark.parametrize("value", [math.nan, math.inf, 1e-50, 1e39, 0, -1e-6, True, "1e-6", None]) +def test_a_config_number_must_be_positive_and_fit_fp32(value): + with pytest.raises(ValueError, match="FP32"): + cfg._number({"eps": value}, "eps") + + +def test_a_config_number_is_accepted_as_a_float(): + assert cfg._number({"eps": 1e-6}, "eps") == 1e-6 + assert cfg._number({"theta": 10000000}, "theta") == 1e7 + + +def test_a_special_token_id_may_be_zero(): + assert cfg._token_id({"id": 0}, "id", 10) == 0 + assert cfg._token_id({"id": 9}, "id", 10) == 9 + + +@pytest.mark.parametrize("value", [-1, 10, 1.0, True, None]) +def test_a_special_token_id_must_address_the_vocabulary(value): + with pytest.raises(ValueError, match="token id"): + cfg._token_id({"id": value}, "id", 10) + + +@pytest.mark.parametrize("value", [2**31, 1.0, True, 0, None]) +def test_a_config_integer_must_be_a_positive_int32(value): + with pytest.raises(ValueError, match="32-bit"): + cfg._integer({"size": value}, "size") + + +@pytest.mark.parametrize("text", ['{"a": 1, "a": 2}', '{"a": NaN}', '{"a": Infinity}', '{"a": -Infinity}']) +def test_checkpoint_json_rejects_repeated_keys_and_non_numbers(tmp_path, text): + with pytest.raises(ValueError): + cfg.load_json(_write(tmp_path, "config.json", text)) + + +def test_an_fp16_epsilon_must_not_vanish(): + assert cfg.positive_when_stored(1e-6, "e") + assert not cfg.positive_when_stored(1e-8, "e") + assert cfg.positive_when_stored(1e-8, "f") + assert not cfg.positive_when_stored(1e39, "f") + + +@pytest.mark.parametrize("requested", [0, 1, True, 4096.0, 262145]) +def test_an_invalid_capacity_is_rejected_not_replaced_by_the_default(requested): + # 0 and other falsy values are not "unset"; only None is. + with pytest.raises(ValueError, match="max_sequence_length"): + cfg.capacity_rows(requested, 262144) + + +def test_a_defaulted_capacity_must_hold_two_rows(): + # A checkpoint of one position would default to a one-row cache, which the runtime refuses. + with pytest.raises(ValueError, match="max_sequence_length"): + cfg.capacity_rows(None, 1) + + +def test_the_capacity_defaults_only_when_unset(): + assert cfg.capacity_rows(None, 262144) == cfg.DEFAULT_CAPACITY + assert cfg.capacity_rows(None, 1024) == 1024 + assert cfg.capacity_rows(2, 262144) == 2 + + +def _checkpoint(vocab_size=248320, eos_token_id=248044): + return SimpleNamespace(text=SimpleNamespace(vocab_size=vocab_size), eos_token_id=eos_token_id) + + +@pytest.mark.parametrize("generation", [ + {"eos_token_id": [248046, 248046]}, {"eos_token_id": None}, {"eos_token_id": [248320]}, + {"eos_token_id": [1.0]}, {"eos_token_id": True}, {"eos_token_id": []}, [248046], +]) +def test_generation_end_ids_must_be_distinct_token_ids(tmp_path, generation): + _write(tmp_path, "generation_config.json", generation) + with pytest.raises(ValueError, match="eos_token_id"): + cfg.generation_ids(tmp_path, _checkpoint()) + + +def test_generation_end_ids_default_to_the_config(tmp_path): + assert cfg.generation_ids(tmp_path, _checkpoint()) == [248044] + _write(tmp_path, "generation_config.json", {"eos_token_id": 248046}) + assert cfg.generation_ids(tmp_path, _checkpoint()) == [248046] + _write(tmp_path, "generation_config.json", {"eos_token_id": [248046, 248044]}) + assert cfg.generation_ids(tmp_path, _checkpoint()) == [248046, 248044] + + +def test_the_checkpoint_processor_settings_are_accepted(tmp_path): + _write(tmp_path, "preprocessor_config.json", {**_PROCESSOR, "do_resize": True, "rescale_factor": 1 / 255, + "resample": 3, "downsample_mode": "16x"}) + assert prompt.processor_settings(tmp_path, 14, 4096) == { + "scale_resolution": 448, "max_slice_nums": 9, "mean": [0.5] * 3, "stddev": [0.5] * 3} + + +@pytest.mark.parametrize("change", [ + {"do_rescale": False}, {"do_normalize": False}, {"do_resize": False}, {"do_convert_rgb": False}, + {"rescale_factor": 0.5}, {"resample": 2}, {"resample": 3.0}, {"slice_mode": 1}, {"use_image_id": False}, + {"downsample_mode": "4x"}, {"crop_size": 448}, {"patch_size": 16}, {"max_slice_nums": 0}, + {"max_slice_nums": prompt.MAX_SLICE_NUMS + 1}, {"max_slice_nums": 2**31 - 1}, + {"scale_resolution": 28}, {"scale_resolution": 448.0}, {"scale_resolution": 1000000}, + {"image_mean": [0.5, 0.5]}, + {"image_std": [0.5, 0.5, 0.0]}, {"image_std": [0.5, 0.5, True]}, {"image_std": [1e-40, 0.5, 0.5]}, + {"image_mean": [1e38, 0.5, 0.5]}, {"image_std": [0.5, 0.5, -0.5]}, +]) +def test_a_processor_option_the_runtime_cannot_honor_is_rejected(tmp_path, change): + _write(tmp_path, "preprocessor_config.json", {**_PROCESSOR, **change}) + with pytest.raises(ValueError, match="MiniCPM-V 4.6"): + prompt.processor_settings(tmp_path, 14, 4096) + + +def test_the_largest_supported_slice_count_is_accepted(tmp_path): + _write(tmp_path, "preprocessor_config.json", {**_PROCESSOR, "max_slice_nums": prompt.MAX_SLICE_NUMS}) + assert prompt.processor_settings(tmp_path, 14, 4096)["max_slice_nums"] == 4096 + + +def test_a_missing_processor_setting_is_rejected(tmp_path): + _write(tmp_path, "preprocessor_config.json", {k: v for k, v in _PROCESSOR.items() if k != "image_std"}) + with pytest.raises(ValueError, match="must set image_std"): + prompt.processor_settings(tmp_path, 14, 4096) + + +@pytest.mark.parametrize(("vocabulary", "total"), [ + ({"a": 0, "b": 248320}, 2), ({"a": 0, "b": 1}, 248321), ({"a": 0, "b": 0}, 2), ({}, 0), ({"a": -1}, 1), +]) +def test_token_ids_must_address_embedding_rows(vocabulary, total): + with pytest.raises(ValueError, match="embedding table"): + prompt.check_vocabulary(vocabulary, total, 248320) + + +def test_a_vocabulary_within_the_embedding_table_is_accepted(): + prompt.check_vocabulary({"a": 0, "b": 248319}, 248077, 248320) + + +def test_the_checkpoint_vision_config_is_accepted(): + assert cfg.VisionConfig.from_dict(dict(_VISION), 6).positions_per_side == 70 + + +def test_a_position_grid_of_one_row_is_rejected(): + # The runtime buckets patch positions over at least two rows of the position grid. + with pytest.raises(ValueError, match="at least two patches"): + cfg.VisionConfig.from_dict({**_VISION, "image_size": 14}, 6) + + +def test_same_value_compares_json_types_inside_objects(): + assert cfg.same_value({"a": [True, "x"]}, {"a": [True, "x"]}) + assert not cfg.same_value({"a": 1}, {"a": True}) + assert not cfg.same_value({"a": True, "b": None}, {"a": True}) + + +def _tokenizer(): + """The smallest tokenizer.json of the layout the native tokenizer loads (as the host test's).""" + vocab = {character: index for index, character in enumerate(prompt._byte_alphabet())} + vocab.update({"xy": 256, "xyx": 257}) + byte_level = {"type": "ByteLevel", "add_prefix_space": False, "trim_offsets": False, "use_regex": False} + split = {"type": "Split", "pattern": {"Regex": prompt._SPLIT_PATTERN}, "behavior": "Isolated", "invert": False} + return { + "version": "1.0", "truncation": None, "padding": None, + "added_tokens": [{"id": 258, "content": "<|end|>", "single_word": False, "lstrip": False, "rstrip": False, + "normalized": False, "special": True}], + "normalizer": {"type": "NFC"}, + "pre_tokenizer": {"type": "Sequence", "pretokenizers": [split, dict(byte_level)]}, + "post_processor": dict(byte_level), "decoder": dict(byte_level), + "model": {"type": "BPE", "dropout": None, "unk_token": None, "continuing_subword_prefix": "", + "end_of_word_suffix": "", "fuse_unk": False, "byte_fallback": False, "ignore_merges": False, + "vocab": vocab, "merges": [["xy", "x"], ["x", "y"]]}, + } + + +def test_the_supported_tokenizer_layout_is_accepted(): + prompt.check_tokenizer_layout(_tokenizer()) + + +def _set(root, path, value): + for key in path[:-1]: + root = root[key] + root[path[-1]] = value + + +@pytest.mark.parametrize(("path", "value"), [ + (("pre_tokenizer", "pretokenizers", 1, "use_regex"), True), + (("pre_tokenizer", "pretokenizers", 0, "pattern", "Regex"), r"\s+|\S+"), + (("normalizer", "type"), "NFKC"), + (("decoder", "trim_offsets"), True), + (("post_processor", "add_prefix_space"), 0), + (("truncation",), {"max_length": 8}), + (("model", "byte_fallback"), True), + (("model", "dropout"), 0.1), + (("model", "vocab", "xyx"), 300), + (("model", "vocab", "xyx"), 257.0), + (("model", "merges", 0), "xy x"), + (("model", "merges", 1), ["x", "x"]), + (("added_tokens", 0, "id"), 259), + (("added_tokens", 0, "normalized"), True), + (("added_tokens", 0, "special"), 1), + (("added_tokens", 0, "content"), "xy"), + (("extra",), 1), +]) +def test_a_tokenizer_layout_the_runtime_cannot_load_is_rejected(path, value): + root = _tokenizer() + _set(root, path, value) + with pytest.raises(ValueError, match="native tokenizer cannot load"): + prompt.check_tokenizer_layout(root) + + +def test_a_vocabulary_without_every_byte_token_or_with_a_repeated_merge_is_rejected(): + missing = _tokenizer() + del missing["model"]["vocab"]["x"] + with pytest.raises(ValueError, match="native tokenizer cannot load"): + prompt.check_tokenizer_layout(missing) + repeated = _tokenizer() + repeated["model"]["merges"].append(["x", "y"]) + with pytest.raises(ValueError, match="native tokenizer cannot load"): + prompt.check_tokenizer_layout(repeated) + + +def test_the_builder_and_the_runtime_pin_the_same_split_pattern(): + source = (Path(prompt.__file__).parent / "runtime" / "bpe_tokenizer.cpp").read_text(encoding="utf-8") + pinned = source.split('kPretokenizerPattern =\n R"regex(', 1)[1].split(')regex"', 1)[0] + assert pinned == prompt._SPLIT_PATTERN + + +def test_checkpoint_json_with_many_keys_loads_in_linear_time(tmp_path): + # tokenizer.json's vocabulary has about 248,000 keys; a quadratic duplicate check would take hours on it. + path = _write(tmp_path, "tokenizer.json", {"vocab": {f"t{index}": index for index in range(60000)}}) + start = time.perf_counter() + assert len(cfg.load_json(path)["vocab"]) == 60000 + assert time.perf_counter() - start < 2.0 + + +_TEXT = { + "model_type": "qwen3_5_text", "hidden_act": "silu", "attention_bias": False, "attn_output_gate": True, + "mamba_ssm_dtype": "float32", "tie_word_embeddings": True, "mlp_only_layers": [], + "rope_parameters": {"rope_type": "default", "rope_theta": 10000000, "partial_rotary_factor": 0.25}, + "layer_types": ["linear_attention", "full_attention"], "num_hidden_layers": 2, +} + + +@pytest.mark.parametrize("layer_types", [ + {"linear_attention": 1, "full_attention": 2}, "linear_attention", [["linear_attention"], "full_attention"], + None, +]) +def test_layer_types_must_be_a_json_array_of_names(layer_types): + with pytest.raises(ValueError, match="layer_types"): + cfg.TextConfig.from_dict({**_TEXT, "layer_types": layer_types}) diff --git a/families/minicpmv4_6/tests/test_checkpoint_mapper.py b/families/minicpmv4_6/tests/test_checkpoint_mapper.py new file mode 100644 index 0000000000..3856108395 --- /dev/null +++ b/families/minicpmv4_6/tests/test_checkpoint_mapper.py @@ -0,0 +1,111 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Checkpoint weights are checked against the header and for finite values before graph construction.""" + +import pytest + +np = pytest.importorskip("numpy") +ml_dtypes = pytest.importorskip("ml_dtypes") +safetensors_numpy = pytest.importorskip("safetensors.numpy") + +from families.minicpmv4_6.checkpoint_mapper import ( # noqa: E402 + _load_tensor, + _open_safetensors, + decay_rates, + narrowed, +) + + +def _readers(tmp_path, **tensors): + safetensors_numpy.save_file(tensors, str(tmp_path / "model.safetensors")) + return _open_safetensors(tmp_path) + + +@pytest.mark.parametrize("dtype", [ml_dtypes.bfloat16, np.float16, np.float32]) +def test_a_floating_point_weight_is_read_as_fp32(tmp_path, dtype): + readers = _readers(tmp_path, w=np.arange(6, dtype=np.float32).reshape(2, 3).astype(dtype)) + value = _load_tensor(readers, "w", (2, 3)) + assert value.dtype == np.float32 + assert value.tolist() == [[0.0, 1.0, 2.0], [3.0, 4.0, 5.0]] + + +@pytest.mark.parametrize("dtype", [np.int32, np.int8, np.uint8, np.float64]) +def test_a_weight_of_another_dtype_is_rejected(tmp_path, dtype): + readers = _readers(tmp_path, w=np.ones((2, 3), dtype=dtype)) + with pytest.raises(ValueError, match="BF16, FP16 or FP32"): + _load_tensor(readers, "w", (2, 3)) + + +@pytest.mark.parametrize("shape", [(3, 2), (6,), (2, 3, 1)]) +def test_a_weight_of_another_shape_is_rejected(tmp_path, shape): + readers = _readers(tmp_path, w=np.ones((2, 3), dtype=np.float32)) + with pytest.raises(ValueError, match="expected"): + _load_tensor(readers, "w", shape) + + +@pytest.mark.parametrize("bad", [np.nan, np.inf, -np.inf]) +def test_a_nonfinite_weight_is_rejected(tmp_path, bad): + value = np.ones((2, 3), dtype=np.float32) + value[1, 2] = bad + readers = _readers(tmp_path, w=value.astype(ml_dtypes.bfloat16)) + with pytest.raises(ValueError, match="NaN or infinite"): + _load_tensor(readers, "w", (2, 3)) + + +def test_a_missing_weight_is_reported_by_name(tmp_path): + readers = _readers(tmp_path, w=np.ones((2, 3), dtype=np.float32)) + with pytest.raises(KeyError, match="other"): + _load_tensor(readers, "other", (2, 3)) + + +def _shard(tmp_path, index_text): + safetensors_numpy.save_file({"w": np.ones((2, 3), dtype=np.float32)}, str(tmp_path / "shard-1.safetensors")) + (tmp_path / "model.safetensors.index.json").write_text(index_text, encoding="utf-8") + return tmp_path + + +def test_a_sharded_checkpoint_maps_each_tensor_to_its_shard(tmp_path): + readers = _open_safetensors(_shard(tmp_path, '{"weight_map": {"w": "shard-1.safetensors"}}')) + assert _load_tensor(readers, "w", (2, 3)).shape == (2, 3) + + +@pytest.mark.parametrize("text", [ + '{"weight_map": {"w": "shard-1.safetensors", "w": "shard-1.safetensors"}}', + '{"weight_map": {"w": 1}}', + '{"weight_map": {"w": ""}}', + '{"weight_map": {"w": "shard-1.safetensors"}, "weight_map": {"w": "shard-1.safetensors"}}', +]) +def test_a_shard_index_must_map_names_to_files_once(tmp_path, text): + with pytest.raises(ValueError): + _open_safetensors(_shard(tmp_path, text)) + + +def test_decay_rates_are_minus_exp_of_a_log_in_fp32(): + rates = decay_rates(np.array([-2.0, 0.0, 88.0], dtype=ml_dtypes.bfloat16), "A_log") + assert rates.dtype == np.float32 + np.testing.assert_allclose(rates, -np.exp(np.array([-2.0, 0.0, 88.0], dtype=np.float64)), rtol=1e-6) + + +@pytest.mark.parametrize("a_log", [89.0, 100.0]) +def test_an_a_log_whose_exponential_overflows_fp32_is_rejected(a_log): + # exp(89) is above FP32's maximum: the decay becomes -inf and the recurrence NaN. + with pytest.raises(ValueError, match="overflows exp"): + decay_rates(np.array([0.0, a_log], dtype=np.float32), "model.layers.0.linear_attn.A_log") + + +def test_weights_within_fp16_become_fp16_constants(): + value = narrowed(np.array([[-65504.0, 1.5], [0.0, 65504.0]], dtype=np.float32), np.float16) + assert value.dtype == np.float16 and value.flags["C_CONTIGUOUS"] + assert value.tolist() == [[-65504.0, 1.5], [0.0, 65504.0]] + + +@pytest.mark.parametrize("big", [65536.0, -1e5, 3e38]) +def test_a_finite_weight_beyond_fp16_is_rejected_not_made_infinite(big): + with pytest.raises(ValueError, match="leave the float16 range"): + narrowed(np.array([1.0, big], dtype=np.float32), np.float16, "w_q") + + +def test_fp32_and_integer_constants_keep_their_values(): + assert narrowed(np.array([3e38], dtype=np.float64), np.float32).tolist() == [np.float32(3e38)] + assert narrowed(np.array([1, 2], dtype=np.int64), np.int64).tolist() == [1, 2] diff --git a/families/minicpmv4_6/tests/test_e2e.py b/families/minicpmv4_6/tests/test_e2e.py new file mode 100644 index 0000000000..a454265cec --- /dev/null +++ b/families/minicpmv4_6/tests/test_e2e.py @@ -0,0 +1,456 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Family-owned checkpoint-to-native-runtime proof for MiniCPM-V 4.6. + +Every case builds (once per manifest) a bundle from the pinned checkpoint, +runs the native CLI and compares the generated tokens with the Transformers +reference, run in FP32 on the same decoded pixels: + +``token_exact`` the native greedy tokens equal the reference's. +``teacher_forced`` the reference re-scores the native tokens; each must be the + reference's argmax or within ``logit_tolerance`` (default + ``_LOGIT_TOLERANCE``) of it. + +Image fixtures are decoded once with Pillow and written as lossless PNG, so the +native loader and the reference read identical RGB values. Image cases marked +``sdk`` also run the public C and C++ SDK consumers on the same input and +require their tokens to equal the CLI's. + +Each case also checks the content of both outputs: a short ``expected_answer`` +is the whole text (case and white space aside), and each of the +``expected_mentions`` of a longer output appears as a whole word. + +The real E2E runs with ``TRTMC_E2E=1`` or an explicit selection +(``--e2e-model``, ``--e2e-testcase``, ``--e2e-models-file``); a selection that +names this family but matches none of its cases is a usage error, and a +testcase-only selection fails unless some collected E2E case owns it. +""" + +from __future__ import annotations + +from tools.e2e_evidence import evidence_enabled, evidence_stage, record_evidence + +import gc +import json +import math +import os +import re +import subprocess +from pathlib import Path + +import pytest + +from tensorrt_model_connect import BuildRequest, build + +_TEST_DIR = Path(__file__).resolve().parent +_REPO = _TEST_DIR.parents[2] +_FAMILY = _TEST_DIR.parent.name +_ORACLES = {"token_exact", "teacher_forced"} +# The single parameter of a testcase-only selection that names none of this family's cases. +_SELECTION_CHECK = "selection-check" +# FP16 bundle tokens may trail the FP32 reference argmax by at most this many logits. +# Calibration, every output scored by the FP32 reference (TF32 off) on the E2E inputs +# plus a 160-token transcription: +# healthy - the reference's own FP16 and BF16 runs (10 runs, 470 tokens): at most +# 0.215 (FP16) and 0.0555 (BF16); the FP16 bundle (4 cases, 75 tokens): +# at most 0.0555; +# defective - 12 known-wrong answers (3 per input on 4 inputs: one word changed or +# another answer): each has a token at least 10.6 below the argmax. +_LOGIT_TOLERANCE = 0.25 + + +def _load_cases() -> dict[str, tuple[dict, dict]]: + cases: dict[str, tuple[dict, dict]] = {} + for path in sorted((_TEST_DIR / "manifests").glob("*.json")): + manifest = json.loads(path.read_text(encoding="utf-8")) + assert manifest["family"] == _FAMILY, path + assert manifest["task"] == "images_text_to_text", path + assert manifest["precision"] in {"fp16", "fp32"}, path + assert isinstance(manifest["max_sequence_length"], int), path + assert manifest["tensor_parallel_size"] == 1, path + for case in manifest["testcases"]: + assert case["name"] not in cases and case["name"] != _SELECTION_CHECK, case["name"] + assert case["oracle"] in _ORACLES, case["name"] + # One content check per case: a whole short answer, or whole-word mentions. + assert ("expected_answer" in case) != ("expected_mentions" in case), case["name"] + texts = [case["expected_answer"]] if "expected_answer" in case else case["expected_mentions"] + assert texts and all(isinstance(text, str) and text.strip() for text in texts), case["name"] + cases[case["name"]] = (manifest, case) + assert cases, f"{_FAMILY} has no E2E cases" + return cases + + +_CASES = _load_cases() + + +def _csv_values(values) -> set[str]: + return {item.strip() for value in values or [] for item in str(value).split(",") if item.strip()} + + +def _filters(config) -> tuple[set[str], set[str]]: + models = _csv_values(config.getoption("--e2e-model")) + models_file = config.getoption("--e2e-models-file") + if models_file: + path = Path(models_file) + if not path.is_file(): + raise pytest.UsageError(f"E2E models file does not exist: {path}") + models |= { + line.strip() + for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() and not line.lstrip().startswith("#") + } + return models, _csv_values(config.getoption("--e2e-testcase")) + + +def _selected_cases(config) -> tuple[list[str], bool]: + """The cases to run, and whether the real E2E runs at all. + + ``--e2e-model`` (this family, a manifest or a case name) and + ``--e2e-testcase`` (case names) narrow each other. A model selection that + names this family, one of its manifests or one of its cases but matches + none of its cases is an error; a model selection of other families leaves + this file empty, whatever ``--e2e-testcase`` names. + """ + models, testcases = _filters(config) + if not models and not testcases: + return sorted(_CASES), os.environ.get("TRTMC_E2E") == "1" + selected = [ + name + for name, (manifest, _) in sorted(_CASES.items()) + if (not models or {_FAMILY, manifest["name"], name} & models) + and (not testcases or name in testcases) + ] + own = {_FAMILY, *(manifest["name"] for manifest, _ in _CASES.values()), *_CASES} + if not selected and models & own: + raise pytest.UsageError( + f"the E2E selection names {_FAMILY} but matches none of its cases " + f"(--e2e-model {sorted(models)}, --e2e-testcase {sorted(testcases)}); " + f"its cases: {', '.join(sorted(_CASES))}" + ) + if not selected and testcases and not models: + # Only the whole session knows whether another family owns these cases (test_e2e checks). + return [_SELECTION_CHECK], True + return selected, True + + +def _foreign_testcases(request) -> None: + """Skip when another collected family's E2E owns the selected testcases; fail when none does.""" + _, testcases = _filters(request.config) + owned = set() + for item in request.session.items: + params = getattr(getattr(item, "callspec", None), "params", {}) + name = getattr(item, "originalname", "") + if name.startswith("test_") and name.endswith("e2e") and "case_name" in params: + owned.add(params["case_name"]) + owned.discard(_SELECTION_CHECK) + if testcases & owned: + pytest.skip(f"--e2e-testcase {sorted(testcases & owned)} belongs to another family") + pytest.fail(f"--e2e-testcase {sorted(testcases)} matches none of the session's E2E cases") + + +def pytest_generate_tests(metafunc) -> None: + if "case_name" not in metafunc.fixturenames: + return + names, enabled = _selected_cases(metafunc.config) + parameters = names if enabled else [ + pytest.param(name, marks=pytest.mark.skip( + reason="real family E2E requires TRTMC_E2E=1 or an explicit E2E selection")) + for name in names + ] + metafunc.parametrize("case_name", parameters, ids=names) + + +def _environment(): + binary = Path(os.environ.get("TRTMC_BINARY", "")) + runtime_root = Path(os.environ.get("TRTMC_RUNTIME_ROOT", "")) + assert binary.is_file() and os.access(binary, os.X_OK), "selected E2E requires TRTMC_BINARY" + assert runtime_root.is_dir(), "selected E2E requires TRTMC_RUNTIME_ROOT" + assert (runtime_root / "libtrtmc_backend_trt.so").is_file(), runtime_root + assert (runtime_root / f"libtrtmc_model_{_FAMILY}.so").is_file(), runtime_root + import torch + + assert torch.cuda.is_available(), "selected E2E requires CUDA" + return binary, runtime_root, torch + + +def _checkpoint(manifest: dict) -> Path: + """The pinned snapshot, resolved as ``trtmc build --revision `` resolves it in CI: offline.""" + from tensorrt_model_connect.model_support import resolve_model + + assert os.environ.get("HF_HUB_OFFLINE") == "1", "selected E2E resolves the checkpoint offline, as CI does" + try: + path = resolve_model(manifest["hf_id"], manifest["hf_revision"]) + except Exception as error: + raise AssertionError( + f"selected {_FAMILY} E2E requires the exact cached checkpoint " + f"{manifest['hf_id']} at {manifest['hf_revision']}" + ) from error + assert path.name == manifest["hf_revision"] and (path / "config.json").is_file(), path + return path + + +def _unique_keys(pairs: list[tuple[str, object]]) -> dict: + keys = [key for key, _ in pairs] + assert len(set(keys)) == len(keys), f"duplicate keys: {keys}" + return dict(pairs) + + +def _thresholds(case_name: str) -> dict: + """The case's optional threshold sidecar; ``logit_tolerance`` is its only key.""" + path = _TEST_DIR / "thresholds" / f"{case_name}.json" + if not path.is_file(): + return {} + payload = json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=_unique_keys) + assert set(payload) == {"threshold_overrides"}, path + thresholds = payload["threshold_overrides"] + assert isinstance(thresholds, dict) and thresholds, path + assert set(thresholds) <= {"logit_tolerance"}, (path, sorted(thresholds)) + return thresholds + + +def _tolerance(thresholds: dict) -> float: + value = thresholds.get("logit_tolerance", _LOGIT_TOLERANCE) + assert type(value) in (int, float) and math.isfinite(value) and value >= 0, value + return float(value) + + +_BUNDLES: dict[str, Path] = {} + + +def _bundle(manifest: dict, model_dir: Path, directory: Path) -> Path: + """Build each manifest's bundle once per session; its cases share it.""" + if manifest["name"] in _BUNDLES: + return _BUNDLES[manifest["name"]] + bundle = directory / manifest["bundle"] + with evidence_stage("build"): + build(BuildRequest( + model_dir=model_dir, + output_path=bundle, + family=_FAMILY, + task=manifest["task"], + precision=manifest["precision"], + max_sequence_length=manifest["max_sequence_length"], + tensor_parallel_size=manifest["tensor_parallel_size"], + )) + assert bundle.is_file() and bundle.stat().st_size > 0, bundle + _BUNDLES[manifest["name"]] = bundle + return bundle + + +def _images(case: dict, directory: Path) -> list[Path]: + """Decode each fixture with Pillow once and store it as lossless PNG.""" + from PIL import Image + + paths = [] + for index, source in enumerate(case.get("images", [])): + target = directory / f"input-{index}.png" + with Image.open(_REPO / source) as image: + image.convert("RGB").save(target) + paths.append(target) + return paths + + +def _run(command: list[str], tmp_path: Path, label: str) -> dict: + completed = subprocess.run(command, check=False, capture_output=True, text=True, timeout=900) + record_evidence(f"{label}_command", { + "argv": command, + "returncode": completed.returncode, + "stdout": completed.stdout, + "stderr": completed.stderr, + }) + (tmp_path / f"{label}.stdout.log").write_text(completed.stdout, encoding="utf-8") + (tmp_path / f"{label}.stderr.log").write_text(completed.stderr, encoding="utf-8") + completed.check_returncode() + return json.loads(completed.stdout.strip().splitlines()[-1]) + + +def _run_cli(binary: Path, runtime_root: Path, bundle: Path, case: dict, images: list[Path], + tmp_path: Path) -> dict: + command = [str(binary), "run", str(bundle), "--runtime-root", str(runtime_root), + "--prompt", case["prompt"], "--max-new-tokens", str(case["max_new_tokens"])] + if len(images) == 1: + command += ["--image", str(images[0])] + elif images: + command += ["--images", json.dumps([str(path) for path in images])] + else: + command += ["--use-chat-template", "true"] + return _run(command, tmp_path, "cli") + + +def _run_sdk_consumers(runtime_root: Path, bundle: Path, case: dict, image: Path, + tmp_path: Path) -> list[dict]: + import numpy as np + from PIL import Image + + native_build = Path(os.environ.get("TRTMC_NATIVE_BUILD_DIR", runtime_root)) + with Image.open(image) as decoded: + pixels = np.asarray(decoded.convert("RGB"), dtype=np.float32) / np.float32(255) + raw = tmp_path / "sdk-input.rgb.f32" + raw.write_bytes(np.ascontiguousarray(pixels, dtype=" dict: + """FP32 Transformers reference: greedy tokens and the scores of the native tokens.""" + from transformers import AutoModelForImageTextToText, AutoProcessor + + torch.backends.cuda.matmul.allow_tf32 = False + torch.backends.cudnn.allow_tf32 = False + assert torch.get_float32_matmul_precision() == "highest" + processor = AutoProcessor.from_pretrained(model_dir, local_files_only=True) + model = AutoModelForImageTextToText.from_pretrained( + model_dir, local_files_only=True, dtype=torch.float32).eval().to("cuda") + try: + inputs = _reference_inputs(processor, case, images).to("cuda") + prompt_length = inputs["input_ids"].shape[1] + with torch.inference_mode(): + generated = model.generate(**inputs, max_new_tokens=int(case["max_new_tokens"]), do_sample=False) + reference_ids = generated[0, prompt_length:].tolist() + # Re-score the native continuation: logits[i] predicts native token i. + forced = torch.tensor([native_ids], dtype=inputs["input_ids"].dtype, device="cuda") + scored = dict(inputs) + scored["input_ids"] = torch.cat([inputs["input_ids"], forced], dim=1) + scored["attention_mask"] = torch.ones_like(scored["input_ids"]) + logits = model(**scored).logits[0, prompt_length - 1: prompt_length - 1 + len(native_ids)].float() + native = logits.gather(1, forced[0].unsqueeze(1)).squeeze(1) + best = logits.max(dim=1) + gaps = (best.values - native).tolist() + eos = model.generation_config.eos_token_id + return { + "prompt_tokens": prompt_length, + "reference_ids": reference_ids, + "reference_text": processor.tokenizer.decode(reference_ids, skip_special_tokens=True), + "teacher_forced_argmax_ids": best.indices.tolist(), + "native_logit_gaps": gaps, + "native_ids_decoded": processor.tokenizer.decode(native_ids, skip_special_tokens=True), + "eos_token_ids": [eos] if isinstance(eos, int) else list(eos or []), + } + finally: + del model + gc.collect() + torch.cuda.empty_cache() + + +def _record_teacher_forced(native_ids: list[int], reference: dict, worst: float, tolerance: float, + tmp_path: Path) -> None: + """Record the teacher-forced comparison so that the report can verify it.""" + if not evidence_enabled(): + return + native_file = tmp_path / "teacher-forced-native.json" + reference_file = tmp_path / "teacher-forced-reference.json" + native_file.write_text(json.dumps({"token_ids": native_ids}) + "\n", encoding="utf-8") + reference_file.write_text(json.dumps({ + "argmax_ids": reference["teacher_forced_argmax_ids"], + "native_logit_gaps": reference["native_logit_gaps"], + }, allow_nan=False) + "\n", encoding="utf-8") + record_evidence("reference_comparison", { + "label": "Native tokens re-scored by the FP32 Transformers reference (teacher forcing)", + "scope": "independent_reference", + "enforced": True, + "native": native_file, + "reference": reference_file, + "checks": [{ + "name": "max_logit_gap", + "label": "Largest logit gap of a native token below the reference argmax", + "scope": "independent_reference", + "actual": worst, + "operator": "<=", + "expected": tolerance, + "passed": worst <= tolerance, + }], + }) + + +def _assert_oracle(case: dict, thresholds: dict[str, float], payload: dict, reference: dict, + tmp_path: Path) -> None: + native_ids = payload["token_ids"] + budget = int(case["max_new_tokens"]) + assert native_ids and len(native_ids) <= budget + eos_ids = set(reference["eos_token_ids"]) + assert eos_ids, "the reference declares no end-of-sequence token" + # Generation ends at its first end-of-sequence token, or when the budget is spent. + assert not eos_ids & set(native_ids[:-1]), f"native output continues after an end token: {native_ids}" + assert native_ids[-1] in eos_ids or len(native_ids) == budget, f"native output stopped early: {native_ids}" + # The runtime's text is the reference tokenizer's decoding of the same ids, whole. + native_text = str(payload["text"]) + assert native_text == reference["native_ids_decoded"], (native_text, reference["native_ids_decoded"]) + if case["oracle"] == "token_exact": + assert not thresholds, "token_exact cases take no threshold" + assert native_ids == reference["reference_ids"], (native_ids, reference["reference_ids"]) + else: + tolerance = _tolerance(thresholds) + record_evidence("thresholds", {"logit_tolerance": tolerance}) + gaps = reference["native_logit_gaps"] + assert len(gaps) == len(native_ids) == len(reference["teacher_forced_argmax_ids"]) + assert all(math.isfinite(gap) for gap in gaps), gaps + worst = max(gaps) + _record_teacher_forced(native_ids, reference, worst, tolerance, tmp_path) + assert worst <= tolerance, f"native token {gaps.index(worst)} trails the reference argmax by {worst}" + # Content of both runs: a short answer is the whole text; a longer output names each mention. + for label, text in (("native", native_text), ("reference", reference["reference_text"])): + if "expected_answer" in case: + assert _normalized(text) == _normalized(case["expected_answer"]), (label, text) + for mention in case.get("expected_mentions", []): + assert _mentions(text, mention), (label, text, mention) + + +def _normalized(text: str) -> str: + return " ".join(text.split()).casefold() + + +def _mentions(text: str, mention: str) -> bool: + """The mention appears as a whole word: not inside a longer word or hyphenated name; any case.""" + return re.search(rf"(? None: + if case_name == _SELECTION_CHECK: + _foreign_testcases(request) + manifest, case = _CASES[case_name] + record_evidence("inputs", {"manifest": manifest, "case": case, "prompt": case["prompt"]}) + binary, runtime_root, torch = _environment() + model_dir = _checkpoint(manifest) + record_evidence("checkpoint", {"hf_id": manifest["hf_id"], "hf_revision": manifest["hf_revision"]}) + bundle = _bundle(manifest, model_dir, tmp_path_factory.mktemp(manifest["name"])) + images = _images(case, tmp_path) + if images: + record_evidence("inputs", {"images": images}) + + with evidence_stage("native"): + payload = _run_cli(binary, runtime_root, bundle, case, images, tmp_path) + record_evidence("native", payload) + if case.get("sdk", False): + assert len(images) == 1, "SDK consumer cases use exactly one image" + with evidence_stage("native"): + for output in _run_sdk_consumers(runtime_root, bundle, case, images[0], tmp_path): + assert output["token_ids"] == payload["token_ids"] + assert output["text"] == payload["text"] + + with evidence_stage("reference"): + reference = _reference(model_dir, case, images, payload["token_ids"], torch) + record_evidence("reference", reference) + with evidence_stage("compare"): + _assert_oracle(case, _thresholds(case_name), payload, reference, tmp_path) diff --git a/families/minicpmv4_6/tests/test_e2e_contract.py b/families/minicpmv4_6/tests/test_e2e_contract.py new file mode 100644 index 0000000000..972935f8ba --- /dev/null +++ b/families/minicpmv4_6/tests/test_e2e_contract.py @@ -0,0 +1,367 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""CPU checks of the E2E's own rules: case selection and the recorded comparison.""" + +from __future__ import annotations + +import json +import math + +import pytest + +from tools import e2e_evidence + +from . import test_e2e as e2e + +_FP16 = sorted(name for name, (manifest, _) in e2e._CASES.items() if manifest["precision"] == "fp16") +_FP32 = sorted(name for name, (manifest, _) in e2e._CASES.items() if manifest["precision"] == "fp32") +_FP32_MANIFEST = next(manifest["name"] for manifest, _ in e2e._CASES.values() if manifest["precision"] == "fp32") + + +class _Config: + def __init__(self, **options): + self.options = options + + def getoption(self, name): + return self.options.get(name) + + +class _Metafunc: + fixturenames = ("tmp_path", "tmp_path_factory", "case_name") + + def __init__(self, **options): + self.config = _Config(**options) + self.parametrized = [] + + def parametrize(self, name, values, ids): + self.parametrized.append((name, values, ids)) + + +def _generate(**options): + metafunc = _Metafunc(**options) + e2e.pytest_generate_tests(metafunc) + (name, values, ids), = metafunc.parametrized + assert name == "case_name" + return values, ids + + +def test_the_manifests_hold_both_precisions(): + assert _FP16 and _FP32 and set(_FP16) | set(_FP32) == set(e2e._CASES) + + +@pytest.mark.parametrize("options", [ + {"--e2e-model": [e2e._FAMILY], "--e2e-testcase": ["minicpm-v-4.6-car-colour"]}, + {"--e2e-model": [_FP32_MANIFEST], "--e2e-testcase": [_FP16[0]]}, + {"--e2e-testcase": [f"{_FP16[0]}x"], "--e2e-model": [f"{e2e._FAMILY},other"]}, +]) +def test_a_selection_naming_the_family_that_matches_no_case_is_an_error(options): + # Pytest would skip an empty parametrization silently, and the run would pass + # without testing anything. + with pytest.raises(pytest.UsageError, match="matches none of its cases"): + _generate(**options) + + +def test_a_testcase_narrows_the_family_selection(): + values, ids = _generate(**{"--e2e-model": [e2e._FAMILY], "--e2e-testcase": [_FP16[0]]}) + assert values == ids == [_FP16[0]] + + +def test_a_manifest_name_selects_its_cases_only(): + values, _ = _generate(**{"--e2e-model": [_FP32_MANIFEST]}) + assert values == _FP32 + + +def test_the_family_name_selects_every_case(): + values, _ = _generate(**{"--e2e-model": [f" {e2e._FAMILY} ,"]}) + assert values == sorted(e2e._CASES) + + +def test_a_models_file_selects_like_the_option(tmp_path): + listing = tmp_path / "models.txt" + listing.write_text(f"# comment\n\n {_FP32_MANIFEST}\n", encoding="utf-8") + values, _ = _generate(**{"--e2e-models-file": str(listing)}) + assert values == _FP32 + with pytest.raises(pytest.UsageError, match="does not exist"): + _generate(**{"--e2e-models-file": str(tmp_path / "missing.txt")}) + + +@pytest.mark.parametrize("options", [ + {"--e2e-model": ["another_family"]}, + {"--e2e-model": ["another_family"], "--e2e-testcase": ["another-family-case"]}, + # The model filter selects another family; this family's case name does not select it back. + {"--e2e-model": ["another_family"], "--e2e-testcase": [_FP16[0]]}, +]) +def test_a_selection_of_other_families_leaves_this_file_empty(options): + assert _generate(**options) == ([], []) + + +def test_a_testcase_only_selection_of_no_own_case_runs_the_session_check(): + check = e2e._SELECTION_CHECK + assert _generate(**{"--e2e-testcase": ["another-family-case"]}) == ([check], [check]) + + +class _Item: + def __init__(self, originalname, case_name=None): + self.originalname = originalname + if case_name is not None: + self.callspec = type("CallSpec", (), {"params": {"case_name": case_name}})() + + +class _Request: + def __init__(self, testcases, items): + self.config = _Config(**{"--e2e-testcase": testcases}) + self.session = type("Session", (), {"items": items})() + + +def test_a_testcase_another_collected_family_owns_skips_here(): + request = _Request(["other-case"], [_Item("test_e2e", e2e._SELECTION_CHECK), _Item("test_family_e2e", "other-case")]) + with pytest.raises(pytest.skip.Exception, match="another family"): + e2e._foreign_testcases(request) + + +@pytest.mark.parametrize("items", [ + [_Item("test_e2e", "selection-check")], + [_Item("test_e2e", "selection-check"), _Item("test_e2e", "another-case")], + [_Item("test_e2e", "selection-check"), _Item("test_contract", "typo-case"), _Item("test_e2e")], +]) +def test_a_testcase_no_collected_e2e_owns_fails(items): + # Neither this family's check, nor another case, nor a non-E2E test or one without cases owns it. + with pytest.raises(pytest.fail.Exception, match="matches none of the session's E2E cases"): + e2e._foreign_testcases(_Request(["typo-case"], items)) + + +@pytest.mark.parametrize("case", [ + {"oracle": "token_exact"}, + {"oracle": "token_exact", "expected_answer": "white", "expected_mentions": ["white"]}, + {"oracle": "token_exact", "expected_answer": " "}, + {"oracle": "token_exact", "expected_mentions": []}, + {"oracle": "token_exact", "expected_answers": ["white"]}, +]) +def test_each_case_has_exactly_one_content_check(tmp_path, monkeypatch, case): + manifest = {"name": "m", "family": e2e._FAMILY, "task": "images_text_to_text", "precision": "fp16", + "max_sequence_length": 64, "tensor_parallel_size": 1, "testcases": [{"name": "c", **case}]} + (tmp_path / "manifests").mkdir() + (tmp_path / "manifests" / "m.json").write_text(json.dumps(manifest), encoding="utf-8") + monkeypatch.setattr(e2e, "_TEST_DIR", tmp_path) + with pytest.raises(AssertionError): + e2e._load_cases() + + +def test_without_a_selection_the_cases_run_only_with_trtmc_e2e(monkeypatch): + monkeypatch.delenv("TRTMC_E2E", raising=False) + values, ids = _generate() + assert ids == sorted(e2e._CASES) + assert all(value.marks and value.marks[0].name == "skip" for value in values) + monkeypatch.setenv("TRTMC_E2E", "1") + assert _generate() == (sorted(e2e._CASES), sorted(e2e._CASES)) + + +def _recorder(tmp_path): + tmp_path.mkdir(parents=True, exist_ok=True) + return e2e_evidence.Evidence( + tmp_path / "evidence", family=e2e._FAMILY, case="contract-check", + source_revision="a" * 40, roots=(tmp_path,), + ) + + +_EOS = 248046 + + +def _oracle(recorder, tmp_path, gaps, argmax_ids, thresholds=None, oracle="teacher_forced", + token_ids=(5603, _EOS), budget=8, text="white", decoded=None, reference_text=None, content=None): + case = {"oracle": oracle, "max_new_tokens": budget, **(content or {"expected_answer": "white"})} + payload = {"text": text, "token_ids": list(token_ids)} + reference = {"reference_ids": list(token_ids), "native_logit_gaps": gaps, + "teacher_forced_argmax_ids": argmax_ids, "eos_token_ids": [_EOS], + "native_ids_decoded": text if decoded is None else decoded, + "reference_text": text if reference_text is None else reference_text} + token = e2e_evidence._ACTIVE.set(recorder) + try: + e2e._assert_oracle(case, thresholds or {}, payload, reference, tmp_path) + finally: + e2e_evidence._ACTIVE.reset(token) + return recorder.data + + +def _check(data): + record = data["reference_comparison"] + assert record["scope"] == "independent_reference" and record["enforced"] is True + native, reference = record["native"], record["reference"] + assert native["artifact"] != reference["artifact"] + assert native["size_bytes"] > 0 and reference["size_bytes"] > 0 + check, = record["checks"] + return check + + +def test_a_teacher_forced_pass_records_a_complete_comparison(tmp_path): + check = _check(_oracle(_recorder(tmp_path), tmp_path, [0.0, 0.0556], [5603, 248045])) + assert (check["name"], check["scope"], check["operator"]) == ( + "max_logit_gap", "independent_reference", "<=") + assert (check["actual"], check["expected"], check["passed"]) == (0.0556, e2e._LOGIT_TOLERANCE, True) + + +def test_a_teacher_forced_failure_is_recorded_before_the_assertion(tmp_path): + recorder = _recorder(tmp_path) + with pytest.raises(AssertionError, match="trails the reference argmax"): + _oracle(recorder, tmp_path, [0.0, 0.358], [5603, 248045]) + check = _check(recorder.data) + assert (check["actual"], check["passed"]) == (0.358, False) + + +def test_a_token_exact_case_records_no_library_comparison(tmp_path): + # The badge comes from the asserted token equality; a comparison record would replace it. + data = _oracle(_recorder(tmp_path), tmp_path, [0.0, 0.0], [5603, 248046], oracle="token_exact") + assert "reference_comparison" not in data + + +@pytest.mark.parametrize("gaps", [[0.0, math.nan], [math.inf, 0.0]]) +def test_nonfinite_gaps_are_rejected_before_the_comparison(tmp_path, gaps): + recorder = _recorder(tmp_path) + with pytest.raises(AssertionError): + _oracle(recorder, tmp_path, gaps, [5603, 248045]) + assert "reference_comparison" not in recorder.data + + +@pytest.mark.parametrize("argmax_ids", [[5603], [5603, 248045, 1]]) +def test_mismatched_lengths_are_rejected(tmp_path, argmax_ids): + with pytest.raises(AssertionError): + _oracle(_recorder(tmp_path), tmp_path, [0.0, 0.0], argmax_ids) + + +@pytest.mark.parametrize("value", [-0.1, math.nan, math.inf, True, "0.3", None]) +def test_a_logit_tolerance_must_be_a_finite_nonnegative_number(tmp_path, value): + with pytest.raises(AssertionError): + _oracle(_recorder(tmp_path), tmp_path, [0.0, 0.0], [5603, 248046], {"logit_tolerance": value}) + + +def test_a_token_exact_case_rejects_a_threshold(tmp_path): + with pytest.raises(AssertionError, match="take no threshold"): + _oracle(_recorder(tmp_path), tmp_path, [0.0, 0.0], [5603, 248046], {"logit_tolerance": 0.3}, + oracle="token_exact") + + +@pytest.mark.parametrize("text", [ + '{"threshold_overrides": {"logit_tolerance": 0.3, "logit_tolerance": 0.5}}', + '{"threshold_overrides": {"max_ned": 0.1}}', + '{"threshold_overrides": {}}', + '{"threshold_overrides": {"logit_tolerance": 0.3}, "note": "x"}', +]) +def test_a_threshold_sidecar_takes_only_its_known_key_once(tmp_path, monkeypatch, text): + (tmp_path / "thresholds").mkdir() + (tmp_path / "thresholds" / "case.json").write_text(text, encoding="utf-8") + monkeypatch.setattr(e2e, "_TEST_DIR", tmp_path) + with pytest.raises(AssertionError): + e2e._thresholds("case") + + +def test_a_threshold_sidecar_is_optional(tmp_path, monkeypatch): + monkeypatch.setattr(e2e, "_TEST_DIR", tmp_path) + assert e2e._thresholds("case") == {} + (tmp_path / "thresholds").mkdir() + (tmp_path / "thresholds" / "case.json").write_text( + '{"threshold_overrides": {"logit_tolerance": 0.3}}', encoding="utf-8") + assert e2e._tolerance(e2e._thresholds("case")) == 0.3 + + +@pytest.mark.parametrize("oracle", ["teacher_forced", "token_exact"]) +def test_an_output_that_stops_early_without_an_end_token_fails(tmp_path, oracle): + # One correct token of an eight-token budget, without the end token, is a truncated answer. + with pytest.raises(AssertionError, match="stopped early"): + _oracle(_recorder(tmp_path), tmp_path, [0.0], [5603], oracle=oracle, token_ids=[5603]) + + +@pytest.mark.parametrize("oracle", ["teacher_forced", "token_exact"]) +def test_an_output_that_continues_after_an_end_token_fails(tmp_path, oracle): + with pytest.raises(AssertionError, match="continues after an end token"): + _oracle(_recorder(tmp_path), tmp_path, [0.0, 0.0], [_EOS, 5603], oracle=oracle, + token_ids=[_EOS, 5603]) + + +def test_an_output_that_spends_the_budget_needs_no_end_token(tmp_path): + check = _check(_oracle(_recorder(tmp_path), tmp_path, [0.0, 0.1], [5603, 5604], token_ids=[5603, 5605], + budget=2)) + assert check["passed"] is True + + +@pytest.mark.parametrize("oracle", ["teacher_forced", "token_exact"]) +@pytest.mark.parametrize("text", ["whitE", "white ", "white\ufffd", ""]) +def test_native_text_must_equal_the_reference_decoding_of_its_ids(tmp_path, oracle, text): + # Matching ids and an answer substring are not enough: the detokenized text must be whole. + with pytest.raises(AssertionError): + _oracle(_recorder(tmp_path), tmp_path, [0.0, 0.0], [5603, _EOS], oracle=oracle, text=text, + decoded="white") + + +@pytest.mark.parametrize("text", ["White", " white\n", "WHITE"]) +def test_a_short_answer_may_differ_in_case_and_white_space_only(tmp_path, text): + _oracle(_recorder(tmp_path), tmp_path, [0.0, 0.0], [5603, _EOS], oracle="token_exact", text=text) + + +@pytest.mark.parametrize(("text", "reference_text"), [ + ("whiteX", "whiteX"), ("white car", "white car"), ("White.", "White."), ("white", "black"), ("black", "white"), +]) +def test_a_short_answer_is_the_whole_text_of_both_runs(tmp_path, text, reference_text): + with pytest.raises(AssertionError): + _oracle(_recorder(tmp_path), tmp_path, [0.0, 0.0], [5603, _EOS], oracle="token_exact", text=text, + reference_text=reference_text) + + +_OCR = {"expected_mentions": ["DeepSeek-OCR-2"]} + + +def test_a_mention_may_stand_anywhere_as_a_whole_word(tmp_path): + text = '""DeepSeek-OCR-2 family plugin.' + _oracle(_recorder(tmp_path), tmp_path, [0.0, 0.0], [5603, _EOS], oracle="token_exact", text=text, + content=_OCR) + + +@pytest.mark.parametrize(("text", "reference_text"), [ + ("DeepSeek-OCR-2X plugin", "DeepSeek-OCR-2X plugin"), + ("DeepSeek-OCR-23 plugin", "DeepSeek-OCR-23 plugin"), + ("the DeepSeek-OCR-2 plugin", "the OCR plugin"), + ("the OCR plugin", "the DeepSeek-OCR-2 plugin"), +]) +def test_a_mention_inside_a_longer_name_or_missing_from_either_run_fails(tmp_path, text, reference_text): + with pytest.raises(AssertionError): + _oracle(_recorder(tmp_path), tmp_path, [0.0, 0.0], [5603, _EOS], oracle="token_exact", text=text, + reference_text=reference_text, content=_OCR) + + +_MANIFEST = {"hf_id": "openbmb/MiniCPM-V-4.6", "hf_revision": "97328f3c2d70c4645b6a35594807eb6932068635"} + + +def _snapshot(tmp_path, name): + path = tmp_path / name + path.mkdir() + (path / "config.json").write_text("{}", encoding="utf-8") + return path + + +def test_the_checkpoint_resolves_through_the_cli_path(tmp_path, monkeypatch): + from tensorrt_model_connect import model_support + + calls = [] + snapshot = _snapshot(tmp_path, _MANIFEST["hf_revision"]) + monkeypatch.setenv("HF_HUB_OFFLINE", "1") + monkeypatch.setattr(model_support, "resolve_model", lambda *args: calls.append(args) or snapshot) + assert e2e._checkpoint(_MANIFEST) == snapshot + assert calls == [(_MANIFEST["hf_id"], _MANIFEST["hf_revision"])] + + +def test_the_checkpoint_must_be_the_pinned_snapshot(tmp_path, monkeypatch): + from tensorrt_model_connect import model_support + + monkeypatch.setenv("HF_HUB_OFFLINE", "1") + monkeypatch.setattr(model_support, "resolve_model", lambda *args: _snapshot(tmp_path, "main")) + with pytest.raises(AssertionError): + e2e._checkpoint(_MANIFEST) + + +def test_the_checkpoint_is_resolved_offline_only(monkeypatch): + from tensorrt_model_connect import model_support + + monkeypatch.delenv("HF_HUB_OFFLINE", raising=False) + monkeypatch.setattr(model_support, "resolve_model", lambda *args: pytest.fail("resolved online")) + with pytest.raises(AssertionError, match="offline"): + e2e._checkpoint(_MANIFEST) diff --git a/families/minicpmv4_6/tests/test_graph_numerics.py b/families/minicpmv4_6/tests/test_graph_numerics.py new file mode 100644 index 0000000000..62bddd4024 --- /dev/null +++ b/families/minicpmv4_6/tests/test_graph_numerics.py @@ -0,0 +1,81 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Decoder graph helpers must agree with the reference formulas, including at their extremes.""" + +import pytest + +trt = pytest.importorskip("tensorrt") +torch = pytest.importorskip("torch") + +from families.minicpmv4_6 import graph_ops # noqa: E402 +from families.minicpmv4_6.text_model import _normalized_heads # noqa: E402 + +pytestmark = [ + pytest.mark.gpu, + pytest.mark.trt, + pytest.mark.skipif(not torch.cuda.is_available(), reason="requires a CUDA GPU"), +] + + +def _run(build, value, input_dtype=None): + """Build an engine around ``build(network, x)`` and run it on ``value``; the output is FP32.""" + logger = trt.Logger(trt.Logger.WARNING) + builder = trt.Builder(logger) + network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED)) + config = builder.create_builder_config() + config.builder_optimization_level = 1 + config.clear_flag(trt.BuilderFlag.TF32) + trt_dtype = trt.float16 if input_dtype == torch.float16 else trt.float32 + output = build(network, network.add_input("x", trt_dtype, tuple(value.shape))) + assert output.dtype == trt.float32, output.dtype + output.name = "y" + network.mark_output(output) + plan = builder.build_serialized_network(network, config) + assert plan is not None + engine = trt.Runtime(logger).deserialize_cuda_engine(plan) + context = engine.create_execution_context() + source = value.to(input_dtype or torch.float32).contiguous().cuda() + tensors = {"x": source, "y": torch.empty(tuple(value.shape), device="cuda")} + for name, tensor in tensors.items(): + assert context.set_tensor_address(name, tensor.data_ptr()) + assert context.execute_async_v3(torch.cuda.current_stream().cuda_stream) + torch.cuda.synchronize() + return tensors["y"].cpu() + + +def test_the_qk_l2_norm_adds_eps_under_the_root_as_the_reference(): + # The reference's l2norm is x * rsqrt(sum(x^2) + eps); dividing by max(norm, eps) + # instead turns these short vectors into unit vectors. + torch.manual_seed(2046) + value = torch.randn(4, 128) * torch.tensor([[1.0], [1e-2], [1e-3], [1e-4]]) + actual = _run(lambda network, x: graph_ops.add_l2_norm(network, x, reduce_axis=1, eps=1e-6), value) + expected = value * torch.rsqrt((value * value).sum(dim=-1, keepdim=True) + 1e-6) + torch.testing.assert_close(actual, expected, atol=1e-6, rtol=1e-5) + + +def test_softplus_stays_finite_and_matches_torch(): + # log(1 + exp(x)) overflows FP32 above x = 88; the decay then turns into NaN. + value = torch.tensor([[-100.0, -30.0, -5.0, -1e-3, 0.0, 1e-3, 5.0, 20.0, 30.0, 88.0, 90.0, 100.0, 1e4]]) + actual = _run(graph_ops.add_softplus, value) + assert torch.isfinite(actual).all(), actual + torch.testing.assert_close(actual, torch.nn.functional.softplus(value), atol=1e-6, rtol=1e-6) + + +def test_the_head_rms_norm_uses_the_given_eps(): + torch.manual_seed(7) + value = torch.randn(3, 4, 8) * 0.1 + actual = _run(lambda network, x: graph_ops.add_rms_norm_last_axis(network, x, 0.5), value) + expected = value * torch.rsqrt((value * value).mean(dim=-1, keepdim=True) + 0.5) + torch.testing.assert_close(actual, expected, atol=1e-6, rtol=1e-5) + + +def test_normalized_fp16_heads_stay_fp32_for_the_recurrence(): + # The reference feeds its l2norm output to the FP32 recurrence without rounding it to FP16; + # an FP16 round trip would leave errors of about 1e-3 here. + torch.manual_seed(11) + value = torch.randn(2, 4, 128).half() + actual = _run(lambda network, x: _normalized_heads(network, x, 2), value, input_dtype=torch.float16) + reference = value.float() + expected = reference * torch.rsqrt((reference * reference).sum(dim=-1, keepdim=True) + 1e-6) + torch.testing.assert_close(actual, expected, atol=1e-6, rtol=1e-5) diff --git a/families/minicpmv4_6/tests/test_rope_tables.py b/families/minicpmv4_6/tests/test_rope_tables.py new file mode 100644 index 0000000000..4960cf5a7f --- /dev/null +++ b/families/minicpmv4_6/tests/test_rope_tables.py @@ -0,0 +1,29 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""The decoder's RoPE tables are finite for every cached position, or the build stops before any engine.""" + +from types import SimpleNamespace + +import pytest + +np = pytest.importorskip("numpy") + +from families.minicpmv4_6.rope import rope_positions, rope_tables # noqa: E402 + + +def _text(theta): + return SimpleNamespace(rotary_dim=64, rope_theta=theta) + + +def test_the_checkpoint_theta_gives_finite_tables(): + cos, sin = rope_tables(_text(1e7), rope_positions(4096)) + assert cos.shape == sin.shape == (4097, 32) + assert np.isfinite(cos).all() and np.isfinite(sin).all() + + +@pytest.mark.parametrize("theta", [1e-38, 1e-40]) +def test_a_theta_whose_fp32_frequencies_or_angles_overflow_is_rejected(theta): + # 1e-38: the angles of late positions overflow; 1e-40: already the frequencies do. + with pytest.raises(ValueError, match="overflows the FP32 RoPE angles"): + rope_tables(_text(theta), rope_positions(4096)) diff --git a/families/minicpmv4_6/tests/test_support.py b/families/minicpmv4_6/tests/test_support.py new file mode 100644 index 0000000000..05985825b1 --- /dev/null +++ b/families/minicpmv4_6/tests/test_support.py @@ -0,0 +1,36 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""Dependency-free checkpoint identity and task policy for MiniCPM-V 4.6.""" + +from families.minicpmv4_6.support import describe +from tensorrt_model_connect.model_support import ModelMetadata + + +def test_checkpoint_identity_selects_images_text_to_text(): + support = describe(ModelMetadata( + config={"model_type": "minicpmv4_6", "architectures": ["MiniCPMV4_6ForConditionalGeneration"]}, + model_index={})) + assert support is not None + assert support.tasks == ("images_text_to_text",) + assert support.default_task == "images_text_to_text" + assert support.default_precision == "fp16" + + +def test_architecture_alone_resolves(): + support = describe(ModelMetadata( + config={"architectures": ["MiniCPMV4_6ForConditionalGeneration"]}, model_index={})) + assert support is not None + assert support.default_task == "images_text_to_text" + + +def test_neighbouring_generations_and_towers_are_not_claimed(): + # Other MiniCPM-V generations differ in tower, merger or decoder; the + # Qwen3.5 decoder and the vision tower alone are not this model either. + for model_type in ("minicpmv4_7", "minicpmv", "minicpm_ocr", "minicpmo", "minicpm", + "minicpmv4_6_vision", "qwen3_5", "qwen3_5_text"): + assert describe(ModelMetadata(config={"model_type": model_type}, model_index={})) is None + + +def test_missing_identity_is_not_claimed(): + assert describe(ModelMetadata(config={}, model_index={})) is None diff --git a/families/minicpmv4_6/text_model.py b/families/minicpmv4_6/text_model.py new file mode 100644 index 0000000000..0821cddb3a --- /dev/null +++ b/families/minicpmv4_6/text_model.py @@ -0,0 +1,1125 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""MiniCPM-V 4.6 language model: the Qwen3.5 hybrid decoder as TensorRT graphs. + +The text tower is a ``qwen3_5_text`` decoder: Gated DeltaNet layers +(``linear_attention``) interleaved with gated full self-attention layers, a +SwiGLU MLP in every layer, (1 + weight) RMSNorm and tied input/output +embeddings. Positions are one-dimensional: the checkpoint's provider passes +plain sequence positions, so every rotary axis carries the same index. + +Two engines share the weights and the runtime state contract: + +``decoder`` one token per launch. +``prefill`` 1..``PREFILL_MAX_ROWS`` prompt rows per launch. Each row takes + either its token embedding or one supplied vision feature row + (``visual_embedding`` selected by ``use_visual_embedding``), so a + prompt that interleaves text and image tokens is prefilled in + chunks without a host copy of the embedding table. + +Both engines read and write the DeltaNet convolution and recurrent state and +the attention KV cache under the same tensor names; the recurrence and its +state stay in FP32 at every precision, as in the reference implementation. +""" + +from __future__ import annotations + +import numpy as np +import tensorrt as trt + +from . import deltanet_rows +from . import graph_blocks +from . import graph_ops +from .checkpoint_mapper import WeightDict, _has_tensor, _load_tensor, decay_rates +from .config import TextConfig +from .rope import rope_positions, rope_tables + +# Prefill rows per launch; the chunked delta rule pads its solve to this size. +PREFILL_MAX_ROWS = deltanet_rows.SOLVE_ROWS +PREFILL_OPT_ROWS = 32 + + +def _projection(network, x, in_features, out_features, weights, key, *, dtype): + """Projection matmul with a constant ``[in, out]`` right-hand side.""" + return graph_ops.add_matmul_rhs_constant( + network, x, in_features, out_features, weights[key], dtype=dtype + ) + + +def _normalized_heads(network: trt.INetworkDefinition, tensor: trt.ITensor, reduce_axis: int) -> trt.ITensor: + """L2-normalized Q or K heads in FP32: the reference's l2norm output enters its FP32 recurrence unrounded.""" + if tensor.dtype != trt.float32: + tensor = network.add_cast(tensor, trt.float32).get_output(0) + return graph_ops.add_l2_norm(network, tensor, reduce_axis, eps=1e-6, dtype=np.float32) + + +def _prepare_runtime_inputs( + network, + work_trt_dtype, + attention_mask, + conv_state_inputs, + ssm_state_inputs, + cache_k_inputs, + cache_v_inputs, +): + """Cast storage tensors while preserving DeltaNet recurrence in FP32.""" + if work_trt_dtype == trt.float32: + return ( + attention_mask, + conv_state_inputs, + ssm_state_inputs, + cache_k_inputs, + cache_v_inputs, + ) + + def cast_all(tensors): + return [network.add_cast(tensor, work_trt_dtype).get_output(0) for tensor in tensors] + + return ( + network.add_cast(attention_mask, work_trt_dtype).get_output(0), + cast_all(conv_state_inputs), + # The reference keeps the DeltaNet recurrent state in FP32. Never round + # this persistent input before the per-token recurrence. + ssm_state_inputs, + cast_all(cache_k_inputs), + cast_all(cache_v_inputs), + ) + + +def _transposed(readers, key: str, rows: int, columns: int) -> np.ndarray: + """Read one ``[out, in]`` checkpoint projection as an FP32 ``[in, out]`` array.""" + return np.ascontiguousarray(_load_tensor(readers, key, (rows, columns)).T) + + +def _vector(readers, key: str, size: int) -> np.ndarray: + return np.ascontiguousarray(_load_tensor(readers, key, (size,)), dtype=np.float32) + + +def load_text_weights(readers, config: TextConfig) -> WeightDict: + """Map the ``model.language_model.*`` tensors to the decoder graph weights.""" + hidden = config.hidden_size + vocab = config.vocab_size + attn_size = config.num_attention_heads * config.head_dim + kv_size = config.num_key_value_heads * config.head_dim + d_inner = config.linear_num_value_heads * config.linear_value_head_dim + qk_dim = config.linear_num_key_heads * config.linear_key_head_dim + conv_dim = 2 * qk_dim + d_inner + root = "model.language_model" + + weights = WeightDict() + embedding = _load_tensor(readers, f"{root}.embed_tokens.weight", (vocab, hidden)) + weights["embedding"] = np.ascontiguousarray(embedding, dtype=np.float32) + # The checkpoint ties the LM head to the input embedding. + if _has_tensor(readers, "lm_head.weight"): + raise ValueError("MiniCPM-V 4.6 ties lm_head to the input embedding; found a separate lm_head") + weights["w_lm_head"] = np.ascontiguousarray(embedding.T, dtype=np.float32) + + for index, layer_type in enumerate(config.layer_types): + prefix = f"layer.{index}" + source = f"{root}.layers.{index}" + # Qwen3.5 RMSNorm scales by (1 + weight). + weights[f"{prefix}.input_norm"] = 1.0 + _vector(readers, f"{source}.input_layernorm.weight", hidden) + weights[f"{prefix}.post_attn_norm"] = 1.0 + _vector( + readers, f"{source}.post_attention_layernorm.weight", hidden + ) + if layer_type == "deltanet": + linear = f"{source}.linear_attn" + heads = config.linear_num_value_heads + head_dim = config.linear_value_head_dim + weights[f"{prefix}.deltanet_in_proj_qkv"] = _transposed( + readers, f"{linear}.in_proj_qkv.weight", conv_dim, hidden + ) + weights[f"{prefix}.deltanet_z_proj"] = _transposed(readers, f"{linear}.in_proj_z.weight", d_inner, hidden) + weights[f"{prefix}.deltanet_a_proj"] = _transposed(readers, f"{linear}.in_proj_a.weight", heads, hidden) + weights[f"{prefix}.deltanet_b_proj"] = _transposed(readers, f"{linear}.in_proj_b.weight", heads, hidden) + # Decay uses -exp(A_log); the reference evaluates it in FP32. + weights[f"{prefix}.A"] = decay_rates(_vector(readers, f"{linear}.A_log", heads), f"{linear}.A_log") + weights[f"{prefix}.dt_bias"] = _vector(readers, f"{linear}.dt_bias", heads) + conv = _load_tensor(readers, f"{linear}.conv1d.weight", (conv_dim, 1, config.linear_conv_kernel_dim)) + weights[f"{prefix}.conv1d_weight"] = np.ascontiguousarray( + conv.reshape(conv_dim, config.linear_conv_kernel_dim), dtype=np.float32 + ) + if _has_tensor(readers, f"{linear}.conv1d.bias"): + raise ValueError("MiniCPM-V 4.6 DeltaNet convolutions have no bias") + weights[f"{prefix}.conv1d_bias"] = np.zeros(conv_dim, dtype=np.float32) + # Gated RMSNorm weight is per head dimension; the graph applies it per head. + weights[f"{prefix}.deltanet_norm"] = np.tile(_vector(readers, f"{linear}.norm.weight", head_dim), heads) + weights[f"{prefix}.deltanet_out_proj"] = _transposed( + readers, f"{linear}.out_proj.weight", hidden, d_inner + ) + else: + attention = f"{source}.self_attn" + heads = config.num_attention_heads + head_dim = config.head_dim + # q_proj interleaves query and gate per head: [head][query | gate]. + query_gate = _transposed(readers, f"{attention}.q_proj.weight", 2 * attn_size, hidden) + rows = np.arange(2 * attn_size).reshape(heads, 2 * head_dim) + weights[f"{prefix}.w_q"] = np.ascontiguousarray(query_gate[:, rows[:, :head_dim].reshape(-1)]) + weights[f"{prefix}.w_gate_attn"] = np.ascontiguousarray(query_gate[:, rows[:, head_dim:].reshape(-1)]) + weights[f"{prefix}.w_k"] = _transposed(readers, f"{attention}.k_proj.weight", kv_size, hidden) + weights[f"{prefix}.w_v"] = _transposed(readers, f"{attention}.v_proj.weight", kv_size, hidden) + weights[f"{prefix}.w_o"] = _transposed(readers, f"{attention}.o_proj.weight", hidden, attn_size) + weights[f"{prefix}.q_norm"] = np.tile( + 1.0 + _vector(readers, f"{attention}.q_norm.weight", head_dim), heads + ) + weights[f"{prefix}.k_norm"] = np.tile( + 1.0 + _vector(readers, f"{attention}.k_norm.weight", head_dim), config.num_key_value_heads + ) + mlp = f"{source}.mlp" + weights[f"{prefix}.w_gate"] = _transposed(readers, f"{mlp}.gate_proj.weight", config.intermediate_size, hidden) + weights[f"{prefix}.w_up"] = _transposed(readers, f"{mlp}.up_proj.weight", config.intermediate_size, hidden) + weights[f"{prefix}.w_down"] = _transposed(readers, f"{mlp}.down_proj.weight", hidden, config.intermediate_size) + + weights["final_norm"] = 1.0 + _vector(readers, f"{root}.norm.weight", hidden) + return weights + + +def text_runtime_config(config: TextConfig) -> dict: + """Decoder geometry shared with the native runtime (``runtime.json``).""" + return { + "vocab_size": config.vocab_size, + "hidden_size": config.hidden_size, + "num_hidden_layers": len(config.layer_types), + "num_attention_heads": config.num_attention_heads, + "num_key_value_heads": config.num_key_value_heads, + "head_dim": config.head_dim, + "layer_types": list(config.layer_types), + "num_mamba_layers": config.layer_types.count("deltanet"), + "num_attention_layers": config.layer_types.count("attention"), + "d_inner": config.linear_num_value_heads * config.linear_value_head_dim, + "mamba_d_state": config.linear_value_head_dim, + "mamba_d_conv": config.linear_conv_kernel_dim, + "mamba_nheads": config.linear_num_value_heads, + "mamba_head_dim": config.linear_value_head_dim, + "conv_dim": 2 * config.linear_num_key_heads * config.linear_key_head_dim + + config.linear_num_value_heads * config.linear_value_head_dim, + } + + +def build_text_engine( + config: TextConfig, + weights: WeightDict, + max_cache_length: int, + *, + precision: str, + prefill_rows: int | None = None, + verbose: bool = False, +) -> bytes: + """Build the one-token decoder, or the prefill engine when ``prefill_rows`` is set. + + The prefill engine runs ``S`` rows with one profile ``1..prefill_rows``: + DeltaNet as one chunked delta rule and attention over the cache plus the + chunk's causal prefix. Its logits come from the last row; present K/V + cover all rows and the recurrent outputs hold the state after the last row. + """ + if prefill_rows is not None and not 1 <= prefill_rows <= PREFILL_MAX_ROWS: + raise ValueError(f"MiniCPM-V 4.6 prefill rows must be in 1..{PREFILL_MAX_ROWS}") + if precision == "fp16": + work_np_dtype, work_trt_dtype = np.float16, trt.float16 + elif precision == "fp32": + work_np_dtype, work_trt_dtype = np.float32, trt.float32 + else: + raise ValueError(f"Unsupported MiniCPM-V 4.6 precision {precision!r}; expected fp32 or fp16") + + hidden = config.hidden_size + vocab = config.vocab_size + layer_types = config.layer_types + num_heads = config.num_attention_heads + num_kv_heads = config.num_key_value_heads + head_dim = config.head_dim + attn_size = num_heads * head_dim + kv_attention_size = num_kv_heads * head_dim + d_inner = config.linear_num_value_heads * config.linear_value_head_dim + deltanet_num_heads = config.linear_num_value_heads + deltanet_num_kv_heads = config.linear_num_key_heads + deltanet_head_dim = config.linear_value_head_dim + d_conv = config.linear_conv_kernel_dim + conv_dim = 2 * deltanet_num_kv_heads * config.linear_key_head_dim + d_inner + mlp_size = config.intermediate_size + num_mamba = layer_types.count("deltanet") + num_attn = layer_types.count("attention") + attention_window = rope_positions(max_cache_length) + + logger = trt.Logger(trt.Logger.VERBOSE if verbose else trt.Logger.WARNING) + builder = trt.Builder(logger) + network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED)) + trt_config = builder.create_builder_config() + trt_config.builder_optimization_level = 1 + # FP32 math stays FP32 (the recurrence, norms, FP32 builds), as in the reference. + trt_config.clear_flag(trt.BuilderFlag.TF32) + + # --- Inputs --- + rows = None if prefill_rows else 1 + row_dim = -1 if prefill_rows else 1 + token_id = network.add_input("token_id", trt.int32, (row_dim,)) + position_id = network.add_input("position_id", trt.int32, (row_dim,)) + attention_mask = network.add_input( + "attention_mask", trt.float32, (row_dim, -1 if prefill_rows else attention_window) + ) + visual = selector = None + if prefill_rows: + visual = network.add_input("visual_embedding", work_trt_dtype, (-1, hidden)) + selector = network.add_input("use_visual_embedding", trt.int32, (-1, 1)) + max_rows = min(prefill_rows, max_cache_length) + opt_rows = min(PREFILL_OPT_ROWS, max_rows) + profile = builder.create_optimization_profile() + for name in ("token_id", "position_id"): + profile.set_shape(name, (1,), (opt_rows,), (max_rows,)) + profile.set_shape("visual_embedding", (1, hidden), (opt_rows, hidden), (max_rows, hidden)) + profile.set_shape("use_visual_embedding", (1, 1), (opt_rows, 1), (max_rows, 1)) + profile.set_shape( + "attention_mask", + (1, max_cache_length + 1), + (opt_rows, max_cache_length + opt_rows), + (max_rows, max_cache_length + max_rows), + ) + trt_config.add_optimization_profile(profile) + + # DeltaNet state inputs (conv + ssm per DeltaNet layer) + conv_state_inputs = [] + ssm_state_inputs = [] + for index in range(num_mamba): + conv_state_inputs.append(network.add_input( + graph_ops.layer_tensor_name("conv_state", index), trt.float32, (conv_dim, d_conv) + )) + ssm_state_inputs.append(network.add_input( + graph_ops.layer_tensor_name("ssm_state", index), + trt.float32, + (deltanet_num_heads, deltanet_head_dim, deltanet_head_dim), + )) + + # Attention KV cache inputs, stored at the compute precision. + cache_k_inputs = [] + cache_v_inputs = [] + for index in range(num_attn): + cache_k_inputs.append(network.add_input( + graph_ops.layer_tensor_name("cache_k", index), work_trt_dtype, (max_cache_length, kv_attention_size) + )) + cache_v_inputs.append(network.add_input( + graph_ops.layer_tensor_name("cache_v", index), work_trt_dtype, (max_cache_length, kv_attention_size) + )) + + ( + attention_mask, + conv_state_inputs, + ssm_state_inputs, + cache_k_inputs, + cache_v_inputs, + ) = _prepare_runtime_inputs( + network, + work_trt_dtype, + attention_mask, + conv_state_inputs, + ssm_state_inputs, + cache_k_inputs, + cache_v_inputs, + ) + + # --- Shared constants --- + embedding_table = graph_ops.add_constant(network, (vocab, hidden), weights["embedding"], dtype=work_np_dtype) + eps_tensor = graph_ops.add_constant( + network, (1, 1), np.array([config.rms_norm_eps], dtype=work_np_dtype), dtype=work_np_dtype + ) + cos_half, sin_half = rope_tables(config, attention_window) + cos_half_tensor = graph_ops.add_constant(network, cos_half.shape, cos_half, dtype=work_np_dtype) + sin_half_tensor = graph_ops.add_constant(network, sin_half.shape, sin_half, dtype=work_np_dtype) + + # --- Embedding --- + hidden_state = network.add_gather(embedding_table, token_id, 0).get_output(0) + if prefill_rows: + use_visual = network.add_cast(selector, trt.bool).get_output(0) + hidden_state = network.add_select(use_visual, visual, hidden_state).get_output(0) + + # --- Layer stack --- + present_conv_outputs = [] + present_ssm_outputs = [] + present_k_outputs = [] + present_v_outputs = [] + mamba_counter = 0 + attn_counter = 0 + for layer_index, layer_type in enumerate(layer_types): + prefix = f"layer.{layer_index}" + if layer_type == "deltanet": + result = _add_deltanet_layer( + network=network, + hidden=hidden_state, + conv_state_in=conv_state_inputs[mamba_counter], + # The reference casts the DeltaNet recurrence and its persistent + # state to FP32 even when the projections run in FP16. + ssm_state_in=ssm_state_inputs[mamba_counter], + eps_tensor=eps_tensor, + weights=weights, + prefix=prefix, + hidden_size=hidden, + d_inner=d_inner, + d_conv=d_conv, + conv_dim=conv_dim, + num_heads=deltanet_num_heads, + num_kv_heads=deltanet_num_kv_heads, + head_dim=deltanet_head_dim, + mlp_size=mlp_size, + norm_eps=config.rms_norm_eps, + dtype=work_np_dtype, + sequence_length=rows, + ) + hidden_state = result["hidden"] + present_conv_outputs.append(result["present_conv"]) + present_ssm_outputs.append(result["present_ssm"]) + mamba_counter += 1 + else: + result = _add_full_attention_layer( + network=network, + hidden=hidden_state, + cache_k=cache_k_inputs[attn_counter], + cache_v=cache_v_inputs[attn_counter], + attention_mask=attention_mask, + position_id=position_id, + cos_half_tensor=cos_half_tensor, + sin_half_tensor=sin_half_tensor, + eps_tensor=eps_tensor, + weights=weights, + prefix=prefix, + hidden_size=hidden, + attn_size=attn_size, + kv_attention_size=kv_attention_size, + num_heads=num_heads, + num_kv_heads=num_kv_heads, + head_dim=head_dim, + rotary_embedding_dim=config.rotary_dim, + max_cache_length=max_cache_length, + mlp_size=mlp_size, + dtype=work_np_dtype, + sequence_length=rows, + ) + hidden_state = result["hidden"] + present_k_outputs.append(result["present_k"]) + present_v_outputs.append(result["present_v"]) + attn_counter += 1 + + if prefill_rows: + # Only the last row can affect the next token. + last = network.add_elementwise( + deltanet_rows.row_count(network, hidden_state), + graph_ops.add_constant(network, (1,), np.array([1], dtype=np.int64), dtype=np.int64), + trt.ElementWiseOperation.SUB, + ).get_output(0) + hidden_state = deltanet_rows.dynamic_slice(network, hidden_state, (last, 0), (1, hidden)) + + # --- Final norm and tied LM head --- + hidden_state = graph_ops.add_rms_norm( + network, hidden_state, hidden, weights["final_norm"], eps_tensor, dtype=work_np_dtype + ) + logits = graph_ops.add_matmul_rhs_constant( + network, hidden_state, hidden, vocab, weights["w_lm_head"], dtype=work_np_dtype + ) + if logits.dtype != trt.float32: + logits = network.add_cast(logits, trt.float32).get_output(0) + logits.name = "logits" + network.mark_output(logits) + + # --- Present state outputs --- + for index in range(num_mamba): + conv = present_conv_outputs[index] + ssm = present_ssm_outputs[index] + if conv.dtype != trt.float32: + conv = network.add_cast(conv, trt.float32).get_output(0) + if ssm.dtype != trt.float32: + ssm = network.add_cast(ssm, trt.float32).get_output(0) + conv.name = graph_ops.layer_tensor_name("present_conv", index) + ssm.name = graph_ops.layer_tensor_name("present_ssm", index) + network.mark_output(conv) + network.mark_output(ssm) + for index in range(num_attn): + key = present_k_outputs[index] + value = present_v_outputs[index] + if key.dtype != work_trt_dtype: + key = network.add_cast(key, work_trt_dtype).get_output(0) + if value.dtype != work_trt_dtype: + value = network.add_cast(value, work_trt_dtype).get_output(0) + key.name = graph_ops.layer_tensor_name("present_k", index) + value.name = graph_ops.layer_tensor_name("present_v", index) + network.mark_output(key) + network.mark_output(value) + + plan = builder.build_serialized_network(network, trt_config) + if plan is None: + raise RuntimeError("MiniCPM-V 4.6 text engine build failed") + return bytes(plan) + + +def _add_deltanet_layer( + *, + network: trt.INetworkDefinition, + hidden: trt.ITensor, + conv_state_in: trt.ITensor, + ssm_state_in: trt.ITensor, + eps_tensor: trt.ITensor, + weights: WeightDict, + prefix: str, + hidden_size: int, + d_inner: int, + d_conv: int, + conv_dim: int, + num_heads: int, + num_kv_heads: int, + head_dim: int, + mlp_size: int, + norm_eps: float, + dtype: np.dtype = np.float32, + sequence_length: int | None = 1, +) -> dict[str, trt.ITensor]: + """Add one Gated DeltaNet layer over one row, or ``S`` rows when ``sequence_length`` is None. + + DeltaNet uses delta-rule linear attention with: + - Conv1d on QKV projection output + - L2-normalized Q,K with Compact GQA/MQA K/V + - Per-head decay (A_log + softplus(a + dt_bias)) + - Per-head beta (write strength via sigmoid) + - Delta rule state update: S' = decay*S + outer(k, (v - S@k)*beta) + - Gated output: norm(S'@q) * silu(z) * norm_weight + + Returns: {hidden, present_conv, present_ssm} + """ + # ===== 1. RMSNorm ===== + normed = graph_ops.add_rms_norm( + network, hidden, hidden_size, weights[f"{prefix}.input_norm"], eps_tensor, dtype=dtype + ) + + # ===== 2. Input projections ===== + # QKV combined: [1, hidden] -> [1, conv_dim] + qkv = _projection( + network, normed, hidden_size, conv_dim, weights, f"{prefix}.deltanet_in_proj_qkv", dtype=dtype + ) + + # Gate (z): [1, hidden] -> [1, d_inner] + z = _projection( + network, normed, hidden_size, d_inner, weights, f"{prefix}.deltanet_z_proj", dtype=dtype + ) + + # Decay projection (a): [1, hidden] -> [1, num_heads] + a_raw = _projection( + network, normed, hidden_size, num_heads, weights, f"{prefix}.deltanet_a_proj", dtype=dtype + ) + + # Beta projection (b): [1, hidden] -> [1, num_heads] + b_raw = _projection( + network, normed, hidden_size, num_heads, weights, f"{prefix}.deltanet_b_proj", dtype=dtype + ) + + mixer = _add_deltanet_mixer_rows if sequence_length is None else _add_deltanet_mixer_step + mixer_output, present_conv, present_ssm = mixer( + network, + qkv=qkv, + a_raw=a_raw, + b_raw=b_raw, + conv_state_in=conv_state_in, + ssm_state_in=ssm_state_in, + weights=weights, + prefix=prefix, + d_inner=d_inner, + d_conv=d_conv, + conv_dim=conv_dim, + num_heads=num_heads, + num_kv_heads=num_kv_heads, + head_dim=head_dim, + dtype=dtype, + ) + + # ===== 10. Gated RMSNorm per-head: weight * norm(output) * silu(z) ===== + # The reference recurrent kernel returns the attention output in the model + # storage dtype before Qwen3_5RMSNormGated casts it back to FP32. + recurrent_output = mixer_output + rows = 1 if sequence_length is not None else -1 + head_shape = (num_heads, head_dim) if sequence_length is not None else (-1, num_heads, head_dim) + if recurrent_output.dtype != hidden.dtype: + recurrent_output = network.add_cast(recurrent_output, hidden.dtype).get_output(0) + + # HF norm operates per head_v_dim: reshape to [num_heads, head_dim], norm, reshape back + deltanet_norm_w = weights[f"{prefix}.deltanet_norm"] + + # Reshape output and z to [num_heads, head_dim] for per-head norm + output_heads = network.add_shuffle(recurrent_output) + output_heads.reshape_dims = head_shape + norm_input = output_heads.get_output(0) + norm_output_dtype = norm_input.dtype + if dtype != np.float32: + norm_input = network.add_cast(norm_input, trt.float32).get_output(0) + + # Per-head RMSNorm with the configured epsilon, as Qwen3_5RMSNormGated + normalized = graph_ops.add_rms_norm_last_axis(network, norm_input, norm_eps) + + # Reshape back and apply weight + norm_flat = network.add_shuffle(normalized) + norm_flat.reshape_dims = (rows, d_inner) + gamma_t = graph_ops.add_constant(network, (1, d_inner), deltanet_norm_w, dtype=np.float32) + normed_output = network.add_elementwise( + norm_flat.get_output(0), gamma_t, trt.ElementWiseOperation.PROD + ) + normed_output_tensor = normed_output.get_output(0) + if normed_output_tensor.dtype != norm_output_dtype: + normed_output_tensor = network.add_cast(normed_output_tensor, norm_output_dtype).get_output( + 0 + ) + + # Gate: multiply by silu(z) + z_activated = graph_ops.add_activation(network, z, "silu", dtype=dtype) + gated = network.add_elementwise( + normed_output_tensor, z_activated, trt.ElementWiseOperation.PROD + ) + + # ===== 11. Output projection + residual ===== + out = _projection( + network, gated.get_output(0), d_inner, hidden_size, weights, f"{prefix}.deltanet_out_proj", dtype=dtype + ) + + residual = network.add_elementwise(hidden, out, trt.ElementWiseOperation.SUM) + hidden_after_attn = residual.get_output(0) + + # ===== 12. Post-attention norm + SwiGLU MLP + residual ===== + post_normed = graph_ops.add_rms_norm( + network, + hidden_after_attn, + hidden_size, + weights[f"{prefix}.post_attn_norm"], + eps_tensor, + dtype=dtype, + ) + + mlp_out = graph_blocks.add_swiglu_mlp( + network, + post_normed, + weights=weights, + prefix=prefix, + hidden_size=hidden_size, + mlp_size=mlp_size, + dtype=dtype, + ) + + mlp_residual = network.add_elementwise(hidden_after_attn, mlp_out, trt.ElementWiseOperation.SUM) + + return { + "hidden": mlp_residual.get_output(0), + "present_conv": present_conv, + "present_ssm": present_ssm, + } + + +def _add_deltanet_mixer_step( + network: trt.INetworkDefinition, + *, + qkv: trt.ITensor, + a_raw: trt.ITensor, + b_raw: trt.ITensor, + conv_state_in: trt.ITensor, + ssm_state_in: trt.ITensor, + weights: WeightDict, + prefix: str, + d_inner: int, + d_conv: int, + conv_dim: int, + num_heads: int, + num_kv_heads: int, + head_dim: int, + dtype: np.dtype, +) -> tuple[trt.ITensor, trt.ITensor, trt.ITensor]: + """Conv step and delta-rule update for one token: ``(output [1, d_inner], conv, ssm)``.""" + qk_dim = num_kv_heads * head_dim # Q and K dimension before Compact GQA/MQA K/V + + # ===== 3. Conv1d step on QKV ===== + # conv_state_in: [conv_dim, d_conv] + # qkv: [1, conv_dim] -> [conv_dim, 1] + qkv_col = network.add_shuffle(qkv) + qkv_col.reshape_dims = (conv_dim, 1) + + if d_conv > 1: + slice_layer = network.add_slice( + conv_state_in, start=(0, 1), shape=(conv_dim, d_conv - 1), stride=(1, 1) + ) + new_conv_state = network.add_concatenation( + [slice_layer.get_output(0), qkv_col.get_output(0)] + ) + new_conv_state.axis = 1 + present_conv = new_conv_state.get_output(0) + else: + present_conv = qkv_col.get_output(0) + + conv_w = graph_ops.add_constant( + network, (conv_dim, d_conv), weights[f"{prefix}.conv1d_weight"], dtype=dtype + ) + conv_prod = network.add_elementwise(present_conv, conv_w, trt.ElementWiseOperation.PROD) + conv_sum = network.add_reduce( + conv_prod.get_output(0), trt.ReduceOperation.SUM, 1 << 1, keep_dims=True + ) + conv_flat = network.add_shuffle(conv_sum.get_output(0)) + conv_flat.reshape_dims = (1, conv_dim) + conv_out = graph_ops.add_bias_sum( + network, conv_flat.get_output(0), conv_dim, weights[f"{prefix}.conv1d_bias"], dtype=dtype + ) + qkv_activated = graph_ops.add_activation(network, conv_out, "silu", dtype=dtype) + + # ===== 4. Split Q, K, V from activated output ===== + offset = 0 + q_slice = network.add_slice(qkv_activated, start=(0, offset), shape=(1, qk_dim), stride=(1, 1)) + q_raw_t = q_slice.get_output(0) + offset += qk_dim + + k_slice = network.add_slice(qkv_activated, start=(0, offset), shape=(1, qk_dim), stride=(1, 1)) + k_raw_t = k_slice.get_output(0) + offset += qk_dim + + v_slice = network.add_slice(qkv_activated, start=(0, offset), shape=(1, d_inner), stride=(1, 1)) + v_raw = v_slice.get_output(0) + + # ===== 5. L2-normalize Q and K ===== + # Reshape to [num_kv_heads, head_dim], normalize per-head, reshape back + q_heads_in = network.add_shuffle(q_raw_t) + q_heads_in.reshape_dims = (num_kv_heads, head_dim) + q_normed = _normalized_heads(network, q_heads_in.get_output(0), 1) + + k_heads_in = network.add_shuffle(k_raw_t) + k_heads_in.reshape_dims = (num_kv_heads, head_dim) + k_normed = _normalized_heads(network, k_heads_in.get_output(0), 1) + + # ===== 6. keep compact Q,K from num_kv_heads -> num_heads ===== + heads_per_group = num_heads // num_kv_heads + + if heads_per_group > 1: + # Q: [num_kv_heads, head_dim] -> [num_kv_heads, 1, head_dim] -> + # tile -> [num_kv_heads, heads_per_group, head_dim] -> + # [num_heads, head_dim] + q_3d = network.add_shuffle(q_normed) + q_3d.reshape_dims = (num_kv_heads, 1, head_dim) + tile_ones = graph_ops.add_constant( + network, + (1, heads_per_group, 1), + np.ones((1, heads_per_group, 1), dtype=np.float32), + dtype=np.float32, + ) + q_tiled = network.add_elementwise( + q_3d.get_output(0), tile_ones, trt.ElementWiseOperation.PROD + ) + q_expanded_s = network.add_shuffle(q_tiled.get_output(0)) + q_expanded_s.reshape_dims = (num_heads, head_dim) + q_expanded = q_expanded_s.get_output(0) + + k_3d = network.add_shuffle(k_normed) + k_3d.reshape_dims = (num_kv_heads, 1, head_dim) + k_tiled = network.add_elementwise( + k_3d.get_output(0), tile_ones, trt.ElementWiseOperation.PROD + ) + k_t_s = network.add_shuffle(k_tiled.get_output(0)) + k_t_s.reshape_dims = (num_heads, head_dim) + k_t = k_t_s.get_output(0) + else: + q_expanded = q_normed + k_t = k_normed + + # V: [1, d_inner] -> [num_heads, head_dim] + v_heads = network.add_shuffle(v_raw) + v_heads.reshape_dims = (num_heads, head_dim) + v_t = v_heads.get_output(0) + + # ===== 7. Compute decay: -exp(A_log) * softplus(a + dt_bias) per head ===== + # Transformers performs the decay and recurrent rule in FP32 even when + # the model projections use FP16. Keeping these tensors in the model + # storage dtype quantizes the persistent state again on every token. + recurrent_dtype = trt.float32 + + def recurrent_cast(tensor: trt.ITensor) -> trt.ITensor: + if tensor.dtype == recurrent_dtype: + return tensor + return network.add_cast(tensor, recurrent_dtype).get_output(0) + + # A: [num_heads] (precomputed as -exp(A_log)) + A_const = graph_ops.add_constant( + network, (1, num_heads), weights[f"{prefix}.A"], dtype=np.float32 + ) + + # dt_bias: [num_heads] + dt_bias_const = graph_ops.add_constant( + network, (1, num_heads), weights[f"{prefix}.dt_bias"], dtype=np.float32 + ) + a_biased = network.add_elementwise( + recurrent_cast(a_raw), dt_bias_const, trt.ElementWiseOperation.SUM + ) + + # softplus(a + dt_bias), without overflow for large arguments + a_softplus = graph_ops.add_softplus(network, a_biased.get_output(0)) + + # decay = A * softplus(...) per head: [1, num_heads] + decay_flat = network.add_elementwise(A_const, a_softplus, trt.ElementWiseOperation.PROD) + # exp(decay) for the state update: [1, num_heads] -> [num_heads, 1, 1] + decay_reshaped = network.add_shuffle(decay_flat.get_output(0)) + decay_reshaped.reshape_dims = (num_heads, 1, 1) + decay_exp = network.add_unary(decay_reshaped.get_output(0), trt.UnaryOperation.EXP) + + # ===== 8. Compute beta: sigmoid(b) per head ===== + # b_raw: [1, num_heads] + beta = network.add_activation(b_raw, trt.ActivationType.SIGMOID) + # [1, num_heads] -> [num_heads, 1] + beta_reshaped = network.add_shuffle(recurrent_cast(beta.get_output(0))) + beta_reshaped.reshape_dims = (num_heads, 1) + + # ===== 9. Delta rule state update ===== + # HF state layout: [H, K_dim, V_dim] + # ssm_state_in: [num_heads, head_dim, head_dim] (K on axis -2, V on axis -1) + # k: [num_heads, head_dim], q: [num_heads, head_dim], v: [num_heads, head_dim] + + # 9a. Decay state first: state = state * exp(g) + decayed_state = network.add_elementwise( + decay_exp.get_output(0), recurrent_cast(ssm_state_in), trt.ElementWiseOperation.PROD + ) + + # 9b. kv_mem = state^T @ k: read old value for this key + # [H, V, K] @ [H, K, 1] = [H, V, 1] (transpose state to swap K/V axes) + k_recurrent = recurrent_cast(k_t) + v_recurrent = recurrent_cast(v_t) + q_recurrent = recurrent_cast(q_expanded) + + k_col = network.add_shuffle(k_recurrent) + k_col.reshape_dims = (num_heads, head_dim, 1) + kv_old_3d = network.add_matrix_multiply( + decayed_state.get_output(0), + trt.MatrixOperation.TRANSPOSE, + k_col.get_output(0), + trt.MatrixOperation.NONE, + ) + kv_old = network.add_shuffle(kv_old_3d.get_output(0)) + kv_old.reshape_dims = (num_heads, head_dim) + + # 9c. delta = (v - kv_mem) * beta + v_minus_old = network.add_elementwise( + v_recurrent, kv_old.get_output(0), trt.ElementWiseOperation.SUB + ) + v_delta = network.add_elementwise( + v_minus_old.get_output(0), beta_reshaped.get_output(0), trt.ElementWiseOperation.PROD + ) + + # 9d. state_new = decayed_state + outer(k, delta) + # outer: k[:, :, None] * delta[:, None, :] = [H, K, 1] @ [H, 1, V] = [H, K, V] + k_col2 = network.add_shuffle(k_recurrent) + k_col2.reshape_dims = (num_heads, head_dim, 1) + v_delta_row = network.add_shuffle(v_delta.get_output(0)) + v_delta_row.reshape_dims = (num_heads, 1, head_dim) + outer_prod = network.add_matrix_multiply( + k_col2.get_output(0), + trt.MatrixOperation.NONE, + v_delta_row.get_output(0), + trt.MatrixOperation.NONE, + ) + + new_state = network.add_elementwise( + decayed_state.get_output(0), outer_prod.get_output(0), trt.ElementWiseOperation.SUM + ) + present_ssm = new_state.get_output(0) + + # 9e. output = state_new^T @ (q * scale) + # HF applies: query *= 1/sqrt(k_dim) + q_scale = graph_ops.add_constant( + network, (1, 1), np.array([1.0 / np.sqrt(head_dim)], dtype=np.float32), dtype=np.float32 + ) + q_scaled = network.add_elementwise(q_recurrent, q_scale, trt.ElementWiseOperation.PROD) + # [H, V, K] @ [H, K, 1] = [H, V, 1] + q_col = network.add_shuffle(q_scaled.get_output(0)) + q_col.reshape_dims = (num_heads, head_dim, 1) + output_3d = network.add_matrix_multiply( + present_ssm, trt.MatrixOperation.TRANSPOSE, q_col.get_output(0), trt.MatrixOperation.NONE + ) + output_flat = network.add_shuffle(output_3d.get_output(0)) + output_flat.reshape_dims = (1, d_inner) + + + return output_flat.get_output(0), present_conv, present_ssm + + +def _add_deltanet_mixer_rows( + network: trt.INetworkDefinition, + *, + qkv: trt.ITensor, + a_raw: trt.ITensor, + b_raw: trt.ITensor, + conv_state_in: trt.ITensor, + ssm_state_in: trt.ITensor, + weights: WeightDict, + prefix: str, + d_inner: int, + d_conv: int, + conv_dim: int, + num_heads: int, + num_kv_heads: int, + head_dim: int, + dtype: np.dtype, +) -> tuple[trt.ITensor, trt.ITensor, trt.ITensor]: + """Conv and delta rule over ``S`` rows in one launch: ``(output [S, d_inner], conv, ssm)``. + + Same arithmetic as :func:`_add_deltanet_mixer_step` applied token by token; + the recurrence runs as one chunk (see :mod:`.deltanet_rows`). + """ + qk_dim = num_kv_heads * head_dim + + def shuffle(tensor, reshape=None, transpose=None): + layer = network.add_shuffle(tensor) + if transpose is not None: + layer.first_transpose = transpose + if reshape is not None: + layer.reshape_dims = reshape + return layer.get_output(0) + + def fp32(tensor): + return tensor if tensor.dtype == trt.float32 else network.add_cast(tensor, trt.float32).get_output(0) + + conv_w = graph_ops.add_constant( + network, (conv_dim, d_conv), weights[f"{prefix}.conv1d_weight"], dtype=dtype + ) + conv_columns, present_conv = deltanet_rows.add_short_conv_rows( + network, + columns=shuffle(qkv, transpose=(1, 0)), + conv_state=conv_state_in, + weight=conv_w, + channels=conv_dim, + kernel=d_conv, + ) + conv_out = graph_ops.add_bias_sum( + network, shuffle(conv_columns, transpose=(1, 0)), conv_dim, + weights[f"{prefix}.conv1d_bias"], dtype=dtype, + ) + activated = graph_ops.add_activation(network, conv_out, "silu", dtype=dtype) + rows = deltanet_rows.row_count(network, activated) + + def columns(offset, width): + return deltanet_rows.dynamic_slice(network, activated, (0, offset), (rows, width)) + + q_normed = _normalized_heads(network, shuffle(columns(0, qk_dim), reshape=(-1, num_kv_heads, head_dim)), 2) + k_normed = _normalized_heads(network, shuffle(columns(qk_dim, qk_dim), reshape=(-1, num_kv_heads, head_dim)), 2) + heads_per_group = num_heads // num_kv_heads + + def expand_heads(tensor): + # [S, kv_heads, D] -> [S, heads, D], head = kv_head * heads_per_group + g. + if heads_per_group == 1: + return tensor + tile = graph_ops.add_constant( + network, (1, 1, heads_per_group, 1), + np.ones((1, 1, heads_per_group, 1), dtype=np.float32), dtype=np.float32, + ) + tiled = network.add_elementwise( + shuffle(tensor, reshape=(-1, num_kv_heads, 1, head_dim)), tile, + trt.ElementWiseOperation.PROD, + ).get_output(0) + return shuffle(tiled, reshape=(-1, num_heads, head_dim)) + + def head_major(tensor): + return shuffle(fp32(tensor), transpose=(1, 0, 2)) # [H, S, D] + + q_scale = graph_ops.add_constant( + network, (1, 1, 1), np.array([[[1.0 / np.sqrt(head_dim)]]], dtype=np.float32), + dtype=np.float32, + ) + q_heads = network.add_elementwise( + head_major(expand_heads(q_normed)), q_scale, trt.ElementWiseOperation.PROD + ).get_output(0) + k_heads = head_major(expand_heads(k_normed)) + v_heads = head_major(shuffle(columns(2 * qk_dim, d_inner), reshape=(-1, num_heads, head_dim))) + + # Decay g = A * softplus(a + dt_bias) and beta = sigmoid(b), FP32, [H, S]. + a_const = graph_ops.add_constant(network, (1, num_heads), weights[f"{prefix}.A"], dtype=np.float32) + dt_bias = graph_ops.add_constant( + network, (1, num_heads), weights[f"{prefix}.dt_bias"], dtype=np.float32 + ) + biased = network.add_elementwise(fp32(a_raw), dt_bias, trt.ElementWiseOperation.SUM).get_output(0) + softplus = graph_ops.add_softplus(network, biased) + decay = network.add_elementwise(a_const, softplus, trt.ElementWiseOperation.PROD).get_output(0) + beta = fp32(network.add_activation(b_raw, trt.ActivationType.SIGMOID).get_output(0)) + + outputs, present_ssm = deltanet_rows.add_chunked_delta_rule( + network, + q=q_heads, + k=k_heads, + v=v_heads, + g=shuffle(decay, transpose=(1, 0)), + beta=shuffle(beta, transpose=(1, 0)), + state=fp32(ssm_state_in), + num_heads=num_heads, + head_dim=head_dim, + ) + return shuffle(outputs, transpose=(1, 0, 2), reshape=(-1, d_inner)), present_conv, present_ssm + + + +def _add_full_attention_layer( + *, + network: trt.INetworkDefinition, + hidden: trt.ITensor, + cache_k: trt.ITensor, + cache_v: trt.ITensor, + attention_mask: trt.ITensor, + position_id: trt.ITensor, + cos_half_tensor: trt.ITensor, + sin_half_tensor: trt.ITensor, + eps_tensor: trt.ITensor, + weights: WeightDict, + prefix: str, + hidden_size: int, + attn_size: int, + kv_attention_size: int, + num_heads: int, + num_kv_heads: int, + head_dim: int, + rotary_embedding_dim: int, + max_cache_length: int, + mlp_size: int, + dtype: np.dtype = np.float32, + sequence_length: int | None = 1, +) -> dict[str, trt.ITensor]: + """Add one full self-attention layer with output gating. + + Qwen3.5 full attention has: + - QK-norm with (1+weight) centering + - Partial RoPE (25% of dims) + - Output gating: context * sigmoid(gate) BEFORE o_proj + - SwiGLU MLP after attention + + ``sequence_length`` is the query row count, or None for ``S`` runtime rows + attending over the cache plus their own causal prefix. + + Returns: {hidden, present_k, present_v} + """ + rows = -1 if sequence_length is None else sequence_length + kv_rows = None if sequence_length is None else max_cache_length + sequence_length + + # Pre-attention norm + normed = graph_ops.add_rms_norm( + network, hidden, hidden_size, weights[f"{prefix}.input_norm"], eps_tensor, dtype=dtype + ) + + # QKV projections + q = _projection( + network, normed, hidden_size, attn_size, weights, f"{prefix}.w_q", dtype=dtype + ) + k = _projection( + network, normed, hidden_size, kv_attention_size, weights, f"{prefix}.w_k", dtype=dtype + ) + v = _projection( + network, normed, hidden_size, kv_attention_size, weights, f"{prefix}.w_v", dtype=dtype + ) + + # Per-head QK norm + q_norm = weights.get(f"{prefix}.q_norm") + if q_norm is not None: + q = graph_ops.add_rms_norm_per_head( + network, q, num_heads, head_dim, q_norm, eps_tensor, dtype=dtype, + sequence_length=sequence_length, + ) + k_norm = weights.get(f"{prefix}.k_norm") + if k_norm is not None: + k = graph_ops.add_rms_norm_per_head( + network, k, num_kv_heads, head_dim, k_norm, eps_tensor, dtype=dtype, + sequence_length=sequence_length, + ) + + # Native RoPE + q = graph_ops.add_apply_rope_native( + network, + q, + num_heads, + head_dim, + cos_half_tensor, + sin_half_tensor, + position_id, + rotary_embedding_dim, + sequence_length=sequence_length, + ) + k = graph_ops.add_apply_rope_native( + network, + k, + num_kv_heads, + head_dim, + cos_half_tensor, + sin_half_tensor, + position_id, + rotary_embedding_dim, + sequence_length=sequence_length, + ) + + present_k, present_v = k, v + + # Reshape K, V for concatenation + k_reshape = network.add_shuffle(k) + k_reshape.reshape_dims = (rows, kv_attention_size) + v_reshape = network.add_shuffle(v) + v_reshape.reshape_dims = (rows, kv_attention_size) + + # Concatenate with cache + all_k = network.add_concatenation([cache_k, k_reshape.get_output(0)]) + all_k.axis = 0 + all_v = network.add_concatenation([cache_v, v_reshape.get_output(0)]) + all_v.axis = 0 + + mask_4d = graph_ops.add_2d_mask_to_4d(network, attention_mask) + context_flat = graph_ops.add_attention_from_rows( + network, + q, + all_k.get_output(0), + all_v.get_output(0), + num_heads=num_heads, + head_dim=head_dim, + num_kv_heads=num_kv_heads, + q_seq=sequence_length, + kv_seq=kv_rows, + mask=mask_4d, + ) + + # Gate: applied BEFORE o_proj (HF order) + gate_attn_w = weights.get(f"{prefix}.w_gate_attn") + attn_out = context_flat + if gate_attn_w is not None: + gate = _projection( + network, + normed, + hidden_size, + attn_size, + weights, + f"{prefix}.w_gate_attn", + dtype=dtype, + ) + gate_sigmoid = network.add_activation(gate, trt.ActivationType.SIGMOID) + gated = network.add_elementwise( + attn_out, gate_sigmoid.get_output(0), trt.ElementWiseOperation.PROD + ) + attn_out = gated.get_output(0) + + # Output projection (AFTER gate) + attn_out = _projection( + network, attn_out, attn_size, hidden_size, weights, f"{prefix}.w_o", dtype=dtype + ) + + residual = network.add_elementwise(hidden, attn_out, trt.ElementWiseOperation.SUM) + hidden_after_attn = residual.get_output(0) + + # Post-attention norm + SwiGLU MLP + residual + post_normed = graph_ops.add_rms_norm( + network, + hidden_after_attn, + hidden_size, + weights[f"{prefix}.post_attn_norm"], + eps_tensor, + dtype=dtype, + ) + + mlp_out = graph_blocks.add_swiglu_mlp( + network, + post_normed, + weights=weights, + prefix=prefix, + hidden_size=hidden_size, + mlp_size=mlp_size, + dtype=dtype, + ) + + mlp_residual = network.add_elementwise(hidden_after_attn, mlp_out, trt.ElementWiseOperation.SUM) + + return { + "hidden": mlp_residual.get_output(0), + "present_k": present_k, + "present_v": present_v, + } diff --git a/families/minicpmv4_6/vision.py b/families/minicpmv4_6/vision.py new file mode 100644 index 0000000000..27f28b662a --- /dev/null +++ b/families/minicpmv4_6/vision.py @@ -0,0 +1,236 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""MiniCPM-V 4.6 vision tower, windowed merger and projector as one TensorRT engine. + +One launch encodes one image slice of ``N`` patches (a ``h x w`` patch grid, +both multiples of four). Attention never crosses slices in the reference, so +the runtime encodes the source image and every slice separately and +concatenates the features in provider order. + +Dataflow (16x token compression, the checkpoint's default): + +1. patch embedding (a 14 x 14 stride-14 convolution, written as a matmul over + flattened patches) plus a learned position row per patch; +2. encoder layers ``0..insert_layer_id`` over all ``N`` patches; +3. the windowed merger: attention inside every 2 x 2 window, then one MLP per + window that maps the four concatenated patches to one token (plus their + mean), giving ``N / 4`` tokens in window order; +4. the remaining encoder layers and the post layer norm over ``N / 4`` tokens; +5. the projector: every 2 x 2 block of merged tokens through LayerNorm, an + exact-GELU MLP and a projection to the language model width (``N / 16``). + +The runtime supplies the integer inputs that depend only on the grid shape: +``position_ids`` (bucketed learned-position rows), ``window_index`` (patches in +window order) and ``merge_index`` (merged tokens in projector block order). +""" + +from __future__ import annotations + +import numpy as np +import tensorrt as trt + +from .checkpoint_mapper import _load_tensor, narrowed +from .config import VisionConfig + +# Patches per slice: 4 x 4 is the smallest grid of the 16x mode; the largest +# bounds attention memory for very elongated images. +MIN_PATCHES = 16 +OPT_PATCHES = 1024 +MAX_PATCHES = 4096 +PROJECTOR_EPS = 1e-6 + + +def load_vision_weights(readers, config: VisionConfig, text_hidden: int) -> dict[str, np.ndarray]: + """Read the vision tower, windowed merger and projector as FP32 arrays.""" + weights: dict[str, np.ndarray] = {} + h = config.hidden_size + window = 4 * h + + def dense(name: str, shape: tuple[int, ...]) -> np.ndarray: + return np.ascontiguousarray(_load_tensor(readers, name, shape), dtype=np.float32) + + def linear(source: str, target: str, out_width: int, in_width: int) -> None: + weights[target + ".weight"] = np.ascontiguousarray(dense(source + ".weight", (out_width, in_width)).T) + weights[target + ".bias"] = dense(source + ".bias", (out_width,)) + + def norm(source: str, target: str, width: int) -> None: + weights[target + ".weight"] = dense(source + ".weight", (width,)) + weights[target + ".bias"] = dense(source + ".bias", (width,)) + + tower = "model.vision_tower" + patch = dense(f"{tower}.embeddings.patch_embedding.weight", (h, 3, config.patch_size, config.patch_size)) + weights["patch.weight"] = np.ascontiguousarray(patch.reshape(h, config.patch_width).T) + weights["patch.bias"] = dense(f"{tower}.embeddings.patch_embedding.bias", (h,)) + weights["position"] = dense( + f"{tower}.embeddings.position_embedding.weight", (config.positions_per_side ** 2, h) + ) + for index in range(config.num_hidden_layers): + source = f"{tower}.encoder.layers.{index}" + target = f"layer.{index}" + norm(f"{source}.layer_norm1", f"{target}.norm1", h) + norm(f"{source}.layer_norm2", f"{target}.norm2", h) + for projection in ("q_proj", "k_proj", "v_proj", "out_proj"): + linear(f"{source}.self_attn.{projection}", f"{target}.{projection}", h, h) + linear(f"{source}.mlp.fc1", f"{target}.fc1", config.intermediate_size, h) + linear(f"{source}.mlp.fc2", f"{target}.fc2", h, config.intermediate_size) + merger = f"{tower}.vit_merger" + norm(f"{merger}.layer_norm1", "window.norm1", h) + for projection in ("q_proj", "k_proj", "v_proj", "out_proj"): + linear(f"{merger}.self_attn.{projection}", f"window.{projection}", h, h) + norm(f"{merger}.pre_norm", "window.pre_norm", window) + linear(f"{merger}.linear_1", "window.linear_1", 4 * config.intermediate_size, window) + linear(f"{merger}.linear_2", "window.linear_2", h, 4 * config.intermediate_size) + norm(f"{tower}.post_layernorm", "post_norm", h) + projector = "model.merger.mlp.0" + norm(f"{projector}.pre_norm", "projector.pre_norm", window) + linear(f"{projector}.linear_1", "projector.linear_1", window, window) + linear(f"{projector}.linear_2", "projector.linear_2", text_hidden, window) + return weights + + +def build_vision_engine(config: VisionConfig, weights: dict[str, np.ndarray], *, precision: str, + verbose: bool = False) -> bytes: + """Build the per-slice vision engine; all learned math stays in TensorRT.""" + if precision == "fp16": + work, np_work = trt.float16, np.float16 + elif precision == "fp32": + work, np_work = trt.float32, np.float32 + else: + raise ValueError(f"Unsupported MiniCPM-V 4.6 vision precision {precision!r}") + h = config.hidden_size + heads = config.num_attention_heads + head_dim = config.head_dim + text_hidden = weights["projector.linear_2.bias"].shape[0] + + logger = trt.Logger(trt.Logger.VERBOSE if verbose else trt.Logger.WARNING) + builder = trt.Builder(logger) + network = builder.create_network(1 << int(trt.NetworkDefinitionCreationFlag.STRONGLY_TYPED)) + build_config = builder.create_builder_config() + build_config.builder_optimization_level = 3 + # FP32 math stays FP32 (attention scores, FP32 builds), as in the reference. + build_config.clear_flag(trt.BuilderFlag.TF32) + + patches = network.add_input("patches", trt.float32, (-1, config.patch_width)) + position_ids = network.add_input("position_ids", trt.int32, (-1,)) + window_index = network.add_input("window_index", trt.int32, (-1,)) + merge_index = network.add_input("merge_index", trt.int32, (-1,)) + profile = builder.create_optimization_profile() + profile.set_shape("patches", (MIN_PATCHES, config.patch_width), (OPT_PATCHES, config.patch_width), + (MAX_PATCHES, config.patch_width)) + for name in ("position_ids", "window_index"): + profile.set_shape(name, (MIN_PATCHES,), (OPT_PATCHES,), (MAX_PATCHES,)) + profile.set_shape("merge_index", (MIN_PATCHES // 4,), (OPT_PATCHES // 4,), (MAX_PATCHES // 4,)) + build_config.add_optimization_profile(profile) + + def cast(x, dtype): + return x if x.dtype == dtype else network.add_cast(x, dtype).get_output(0) + + def constant(values, dtype): + array = narrowed(values, dtype, "vision weights") + return network.add_constant(array.shape, trt.Weights(array)).get_output(0) + + def reshape(x, shape): + layer = network.add_shuffle(x) + layer.reshape_dims = shape + return layer.get_output(0) + + def transpose(x, order): + layer = network.add_shuffle(x) + layer.first_transpose = trt.Permutation(order) + return layer.get_output(0) + + def binary(a, b, operation): + return network.add_elementwise(a, b, operation).get_output(0) + + def linear(x, name): + weight = weights[name + ".weight"] + rank = len(tuple(x.shape)) + rhs = constant(weight.reshape((1,) * (rank - 2) + weight.shape), np_work) + y = network.add_matrix_multiply(x, trt.MatrixOperation.NONE, rhs, trt.MatrixOperation.NONE).get_output(0) + bias = weights[name + ".bias"] + return binary(y, constant(bias.reshape((1,) * (rank - 1) + bias.shape), np_work), + trt.ElementWiseOperation.SUM) + + def layer_norm(x, name, eps): + # The reference normalizes in FP32 and rounds the result to the model dtype. + width = weights[name + ".weight"].shape[0] + rank = len(tuple(x.shape)) + shape = (1,) * (rank - 1) + (width,) + layer = network.add_normalization_v2( + cast(x, trt.float32), constant(weights[name + ".weight"].reshape(shape), np.float32), + constant(weights[name + ".bias"].reshape(shape), np.float32), 1 << (rank - 1)) + layer.epsilon = eps + return cast(layer.get_output(0), work) + + def gelu(x, approximate): + kind = trt.ActivationType.GELU_TANH if approximate else trt.ActivationType.GELU_ERF + return cast(network.add_activation(cast(x, trt.float32), kind).get_output(0), work) + + def attention(x, prefix, groups, group_size): + """Multi-head attention inside ``groups`` independent sets of ``group_size`` rows.""" + query = reshape(linear(x, prefix + ".q_proj"), (groups, group_size, heads, head_dim)) + key = reshape(linear(x, prefix + ".k_proj"), (groups, group_size, heads, head_dim)) + value = reshape(linear(x, prefix + ".v_proj"), (groups, group_size, heads, head_dim)) + query, key, value = (transpose(t, (0, 2, 1, 3)) for t in (query, key, value)) + scores = network.add_matrix_multiply(cast(query, trt.float32), trt.MatrixOperation.NONE, + cast(key, trt.float32), trt.MatrixOperation.TRANSPOSE).get_output(0) + scores = binary(scores, constant(np.full((1, 1, 1, 1), head_dim ** -0.5, np.float32), np.float32), + trt.ElementWiseOperation.PROD) + softmax = network.add_softmax(scores) + softmax.axes = 1 << 3 + probabilities = cast(softmax.get_output(0), work) + context = network.add_matrix_multiply(probabilities, trt.MatrixOperation.NONE, + value, trt.MatrixOperation.NONE).get_output(0) + context = reshape(transpose(context, (0, 2, 1, 3)), (-1, h)) + return linear(context, prefix + ".out_proj") + + def encoder_layer(x, index): + prefix = f"layer.{index}" + residual = x + x = attention(layer_norm(x, prefix + ".norm1", config.layer_norm_eps), prefix, 1, -1) + x = binary(residual, x, trt.ElementWiseOperation.SUM) + residual = x + x = layer_norm(x, prefix + ".norm2", config.layer_norm_eps) + x = linear(gelu(linear(x, prefix + ".fc1"), True), prefix + ".fc2") + return binary(residual, x, trt.ElementWiseOperation.SUM) + + # 1. Patch embedding and learned positions (pixel values rounded to the model dtype first). + hidden = linear(cast(patches, work), "patch") + positions = network.add_gather(constant(weights["position"], np_work), position_ids, 0).get_output(0) + hidden = binary(hidden, positions, trt.ElementWiseOperation.SUM) + + # 2. Full-resolution encoder layers. + for index in range(config.insert_layer_id + 1): + hidden = encoder_layer(hidden, index) + + # 3. Windowed merger: attention inside each 2 x 2 window, then one token per window. + normalized = network.add_gather(layer_norm(hidden, "window.norm1", config.layer_norm_eps), + window_index, 0).get_output(0) + residual = network.add_gather(hidden, window_index, 0).get_output(0) + hidden = binary(residual, attention(normalized, "window", -1, 4), trt.ElementWiseOperation.SUM) + windows = reshape(hidden, (-1, 4, h)) + window_mean = reshape(cast(network.add_reduce(cast(windows, trt.float32), trt.ReduceOperation.AVG, + 1 << 1, keep_dims=True).get_output(0), work), (-1, h)) + flat = reshape(windows, (-1, 4 * h)) + merged = linear(gelu(linear(layer_norm(flat, "window.pre_norm", config.layer_norm_eps), "window.linear_1"), + True), "window.linear_2") + hidden = binary(merged, window_mean, trt.ElementWiseOperation.SUM) + + # 4. Remaining encoder layers over the merged tokens and the post layer norm. + for index in range(config.insert_layer_id + 1, config.num_hidden_layers): + hidden = encoder_layer(hidden, index) + hidden = layer_norm(hidden, "post_norm", config.layer_norm_eps) + + # 5. Projector: 2 x 2 blocks of merged tokens to the language model width. + blocks = reshape(network.add_gather(hidden, merge_index, 0).get_output(0), (-1, 4 * h)) + projected = linear(gelu(linear(layer_norm(blocks, "projector.pre_norm", PROJECTOR_EPS), + "projector.linear_1"), False), "projector.linear_2") + projected = reshape(projected, (-1, text_hidden)) + projected.name = "visual_features" + network.mark_output(projected) + + plan = builder.build_serialized_network(network, build_config) + if plan is None: + raise RuntimeError("MiniCPM-V 4.6 vision engine build failed") + return bytes(plan)