From 62db437747b7c31ef08a1e70b4a632ecbb24c043 Mon Sep 17 00:00:00 2001 From: Qikai Li Date: Fri, 13 Nov 2026 09:05:42 +0000 Subject: [PATCH] feat(minicpmv4_6): add the images-and-text to text family for MiniCPM-V-4.6 Add a family for openbmb/MiniCPM-V-4.6 (MiniCPMV4_6ForConditionalGeneration): a SigLIP-style vision tower with a windowed 2 x 2 token merger inside the encoder and an MLP projector, feeding a Qwen3.5 hybrid decoder (Gated DeltaNet and gated attention layers). The bundle holds a one-token decoder, a chunked prefill engine whose rows take a token embedding or a vision feature row, and a per-slice vision engine, in FP16 (default) or FP32. The runtime implements images_text_to_text, and text_continuation for text-only prompts, and reproduces the checkpoint's processor on the host: image slicing, antialiased bicubic resampling, the image placeholder markup and the chat template. Signed-off-by: Qikai Li --- ASSET_LICENSES.md | 4 + families/minicpmv4_6/NOTICE | 93 ++ families/minicpmv4_6/README.md | 90 ++ families/minicpmv4_6/__init__.py | 4 + families/minicpmv4_6/checkpoint_mapper.py | 97 ++ families/minicpmv4_6/config.py | 288 +++++ families/minicpmv4_6/deltanet_rows.py | 321 +++++ families/minicpmv4_6/graph_blocks.py | 82 ++ families/minicpmv4_6/graph_ops.py | 564 +++++++++ families/minicpmv4_6/model.py | 99 ++ families/minicpmv4_6/prompt.py | 348 +++++ families/minicpmv4_6/requirements.txt | 7 + families/minicpmv4_6/rope.py | 33 + families/minicpmv4_6/runtime/CMakeLists.txt | 88 ++ .../minicpmv4_6/runtime/bpe_tokenizer.cpp | 657 ++++++++++ families/minicpmv4_6/runtime/decoder.cpp | 164 +++ families/minicpmv4_6/runtime/decoder.h | 57 + families/minicpmv4_6/runtime/engine_io.cpp | 196 +++ families/minicpmv4_6/runtime/engine_io.h | 31 + families/minicpmv4_6/runtime/image.cpp | 488 +++++++ families/minicpmv4_6/runtime/image.h | 81 ++ families/minicpmv4_6/runtime/metadata.cpp | 115 ++ families/minicpmv4_6/runtime/metadata.h | 40 + families/minicpmv4_6/runtime/plugin.cpp | 426 +++++++ families/minicpmv4_6/runtime/prompt.cpp | 156 +++ families/minicpmv4_6/runtime/prompt.h | 30 + families/minicpmv4_6/runtime/sampler.cpp | 97 ++ families/minicpmv4_6/runtime/sampler.h | 39 + families/minicpmv4_6/runtime/state.cpp | 180 +++ families/minicpmv4_6/runtime/state.h | 71 ++ families/minicpmv4_6/runtime/tokenizer.h | 48 + .../minicpmv4_6/runtime/vision_encoder.cpp | 60 + families/minicpmv4_6/runtime/vision_encoder.h | 32 + families/minicpmv4_6/support.py | 14 + families/minicpmv4_6/tests/__init__.py | 4 + .../tests/cpp/test_minicpmv4_6_host.cpp | 907 +++++++++++++ families/minicpmv4_6/tests/data/README.md | 13 + .../minicpmv4_6/tests/data/orc_test_img.jpeg | Bin 0 -> 109232 bytes families/minicpmv4_6/tests/data/test_img.jpeg | Bin 0 -> 55258 bytes .../tests/manifests/minicpm-v-4.6-fp32.json | 30 + .../tests/manifests/minicpm-v-4.6.json | 50 + families/minicpmv4_6/tests/sdk_consumer.c | 160 +++ families/minicpmv4_6/tests/sdk_consumer.cpp | 67 + .../minicpmv4_6/tests/test_builder_config.py | 296 +++++ .../tests/test_checkpoint_mapper.py | 111 ++ families/minicpmv4_6/tests/test_e2e.py | 456 +++++++ .../minicpmv4_6/tests/test_e2e_contract.py | 367 ++++++ .../minicpmv4_6/tests/test_graph_numerics.py | 81 ++ .../minicpmv4_6/tests/test_rope_tables.py | 29 + families/minicpmv4_6/tests/test_support.py | 36 + families/minicpmv4_6/text_model.py | 1125 +++++++++++++++++ families/minicpmv4_6/vision.py | 236 ++++ 52 files changed, 9068 insertions(+) create mode 100644 families/minicpmv4_6/NOTICE create mode 100644 families/minicpmv4_6/README.md create mode 100644 families/minicpmv4_6/__init__.py create mode 100644 families/minicpmv4_6/checkpoint_mapper.py create mode 100644 families/minicpmv4_6/config.py create mode 100644 families/minicpmv4_6/deltanet_rows.py create mode 100644 families/minicpmv4_6/graph_blocks.py create mode 100644 families/minicpmv4_6/graph_ops.py create mode 100644 families/minicpmv4_6/model.py create mode 100644 families/minicpmv4_6/prompt.py create mode 100644 families/minicpmv4_6/requirements.txt create mode 100644 families/minicpmv4_6/rope.py create mode 100644 families/minicpmv4_6/runtime/CMakeLists.txt create mode 100644 families/minicpmv4_6/runtime/bpe_tokenizer.cpp create mode 100644 families/minicpmv4_6/runtime/decoder.cpp create mode 100644 families/minicpmv4_6/runtime/decoder.h create mode 100644 families/minicpmv4_6/runtime/engine_io.cpp create mode 100644 families/minicpmv4_6/runtime/engine_io.h create mode 100644 families/minicpmv4_6/runtime/image.cpp create mode 100644 families/minicpmv4_6/runtime/image.h create mode 100644 families/minicpmv4_6/runtime/metadata.cpp create mode 100644 families/minicpmv4_6/runtime/metadata.h create mode 100644 families/minicpmv4_6/runtime/plugin.cpp create mode 100644 families/minicpmv4_6/runtime/prompt.cpp create mode 100644 families/minicpmv4_6/runtime/prompt.h create mode 100644 families/minicpmv4_6/runtime/sampler.cpp create mode 100644 families/minicpmv4_6/runtime/sampler.h create mode 100644 families/minicpmv4_6/runtime/state.cpp create mode 100644 families/minicpmv4_6/runtime/state.h create mode 100644 families/minicpmv4_6/runtime/tokenizer.h create mode 100644 families/minicpmv4_6/runtime/vision_encoder.cpp create mode 100644 families/minicpmv4_6/runtime/vision_encoder.h create mode 100644 families/minicpmv4_6/support.py create mode 100644 families/minicpmv4_6/tests/__init__.py create mode 100644 families/minicpmv4_6/tests/cpp/test_minicpmv4_6_host.cpp create mode 100644 families/minicpmv4_6/tests/data/README.md create mode 100644 families/minicpmv4_6/tests/data/orc_test_img.jpeg create mode 100644 families/minicpmv4_6/tests/data/test_img.jpeg create mode 100644 families/minicpmv4_6/tests/manifests/minicpm-v-4.6-fp32.json create mode 100644 families/minicpmv4_6/tests/manifests/minicpm-v-4.6.json create mode 100644 families/minicpmv4_6/tests/sdk_consumer.c create mode 100644 families/minicpmv4_6/tests/sdk_consumer.cpp create mode 100644 families/minicpmv4_6/tests/test_builder_config.py create mode 100644 families/minicpmv4_6/tests/test_checkpoint_mapper.py create mode 100644 families/minicpmv4_6/tests/test_e2e.py create mode 100644 families/minicpmv4_6/tests/test_e2e_contract.py create mode 100644 families/minicpmv4_6/tests/test_graph_numerics.py create mode 100644 families/minicpmv4_6/tests/test_rope_tables.py create mode 100644 families/minicpmv4_6/tests/test_support.py create mode 100644 families/minicpmv4_6/text_model.py create mode 100644 families/minicpmv4_6/vision.py 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 0000000000000000000000000000000000000000..b8da05838c308eaff87eedfa959f577445a38eb8 GIT binary patch literal 109232 zcmd?QXIN9;)-M{Q2~q?E>8LcNO79>Rsz|S)h;$-EdZU%2IZ~)&&TCA0L^uR5yCt|f_s2#Gz5e+ z1eaX^4gi3F_-eNQn(+T~5L~;OBMIqsGV&W&55R8%t`QItULzv>*Q~Fe4!pV#Afh3r zy(^+jLZ@p@de7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l5(}-9cAjcW=`>$G@{}pG8mV=mhMeZG7%^>@0{67E!L&op` literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..095c03620f4efba781e30520da7f1462b08a6a30 GIT binary patch literal 55258 zcmb4KQ*b6gm;GWpnb_vUwry)-^NS|7ZTpLDYbLgxOl&)uVCS#h+I`;JUHx*qZr|#D z=+oz({#yOo0ieoC%18phzyJWSe+}@p0T2T~LO}edLqb48K|(@7!^1%TGbA{8Sa=j9 zR8$ls6l63E985HHY;P>27w0lH3%RC0KmZ^!2Xl({}==$I20H(3;-7HpIZSH z01gHL4gn1T1^sV;hK2wGhX6pLp_4+fh(KeIsTezB1}4Igvx*jCsWuGE-N2dvDcFLN zc5lClsbQPC1Q#_@vWu(#n&(JP`4*~shqhuHHFk=)=~2^SpDIZ9l~PIy&a=RI|w`B{VL~%ix=I+#30E zi>Lk^0e4SfOS6Z<7XTIH_*315dK*AIT}{?*!t7o+eX$e;l%E65)%lHwk?-@oD&vPq zUhk5i=(Z(#2x5rRk{t_w&=)EiPW~)}+2O+D5Y1XSHB_AbfeI%s?Defm+A@#vaHX`` zWKTtKF!5UT?!W-E5L(55*E{BC9+@u^wBgJYD&;-{jK+2=#}Y-KN7xT9r}jWNYMAZ9 z<1G5~Xm)2~TyBqnN37&u#l#uJxpwozZPN&n0S^w%8oRB5P8!l@GF5;7B>7cwkp9Nj zoOD)TkN~Jd;M4@Zh(i(`M&7RE z4VYPudys0n7moGBoKAB25lTLuO5%}IIpL91Cqr(V3^{|#$?EM!GGC)swYvCtf5#U=2>%oYW$^Fu(q z4-qn1D9SsFZV;i0JXgSwXMpy;vA0e7e>+|-Wtvfuja2kdw$W|L6ZfgqSJ7l;%AO!u z)MqG8gq#iJ=AJS|$!)ZDmPX8o&jlBE0z&&*2Q+@34#{vOJb& zt4|*UUux#Vj=TH#R1Fh$TME(n3=NiZ&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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)