Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions ASSET_LICENSES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down Expand Up @@ -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
Expand Down
93 changes: 93 additions & 0 deletions families/minicpmv4_6/NOTICE
Original file line number Diff line number Diff line change
@@ -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.
90 changes: 90 additions & 0 deletions families/minicpmv4_6/README.md
Original file line number Diff line number Diff line change
@@ -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 `<image_id>`, `<image>` and `<slice>` 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=<build>/trtmc TRTMC_RUNTIME_ROOT=<build> TRTMC_NATIVE_BUILD_DIR=<build> \
python -m pytest families/minicpmv4_6/tests --e2e-model minicpmv4_6 -vv
```
4 changes: 4 additions & 0 deletions families/minicpmv4_6/__init__.py
Original file line number Diff line number Diff line change
@@ -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."""
97 changes: 97 additions & 0 deletions families/minicpmv4_6/checkpoint_mapper.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading