Repository navigation
feat(vit_mae): add masked ViT-MAE image features #2866
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
willg-nv
wants to merge
6
commits into
NVIDIA:main
Choose a base branch
from
willg-nv:bringup/models-2-355-vit-mae-base
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,109
−0
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
873cc1c
feat(vit_mae): add native masked image token features
willg-nv 7ad4eac
fix(vit_mae): validate processor rescaling
willg-nv fb01eda
Merge upstream main and reconcile review fixes
willg-nv a04b163
fix(vit_mae): validate processor metadata and bound resize scratch
willg-nv 4cbb74a
fix(vit-mae): validate normalization across the pixel range
willg-nv 4b02a83
fix(vit-mae): require bilinear bundle resampling
willg-nv File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
|
|
||
| """ViT-MAE visible image patch features with reproducible masking.""" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,217 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| """ViT-MAE encoder with the checkpoint mask ratio and explicit visible-patch indices.""" | ||
|
|
||
| import json | ||
| from pathlib import Path | ||
|
|
||
| import numpy as np | ||
| from safetensors import safe_open | ||
| import tensorrt as trt | ||
|
|
||
|
|
||
| def geometry(config): | ||
| if config.get("model_type") != "vit_mae": | ||
| raise ValueError("vit_mae requires model_type=vit_mae") | ||
| for key in ("hidden_size", "num_attention_heads", "num_hidden_layers", "intermediate_size", "image_size", "patch_size", "num_channels"): | ||
| if type(config.get(key)) is not int or config[key] <= 0: | ||
| raise ValueError(f"vit_mae requires positive integer {key}") | ||
| if config["hidden_size"] % config["num_attention_heads"] or config["image_size"] % config["patch_size"]: | ||
| raise ValueError("vit_mae head and patch geometry must divide their respective dimensions") | ||
| if config.get("hidden_act", "gelu") != "gelu" or config["num_channels"] != 3: | ||
| raise NotImplementedError("vit_mae requires RGB patches and exact GELU") | ||
| patches = (config["image_size"] // config["patch_size"]) ** 2 | ||
| ratio = config.get("mask_ratio", 0.75) | ||
| if not isinstance(ratio, (float, int)) or not 0 <= ratio < 1 or int(patches * (1 - ratio)) <= 0: | ||
| raise ValueError("vit_mae requires a mask ratio retaining at least one patch") | ||
| return patches, int(patches * (1 - ratio)) | ||
|
|
||
|
|
||
| def required_shapes(config): | ||
| patches, _ = geometry(config) | ||
| width, inner, patch = config["hidden_size"], config["intermediate_size"], config["patch_size"] | ||
| required = {"vit.embeddings.cls_token": (1, 1, width), | ||
| "vit.embeddings.position_embeddings": (1, patches + 1, width), | ||
| "vit.embeddings.patch_embeddings.projection.weight": (width, 3, patch, patch), | ||
| "vit.embeddings.patch_embeddings.projection.bias": (width,), | ||
| "vit.layernorm.weight": (width,), "vit.layernorm.bias": (width,)} | ||
| for layer in range(config["num_hidden_layers"]): | ||
| prefix = f"vit.encoder.layer.{layer}." | ||
| for norm in ("layernorm_before", "layernorm_after"): | ||
| required[prefix + norm + ".weight"] = (width,) | ||
| required[prefix + norm + ".bias"] = (width,) | ||
| for projection in ("attention.attention.query", "attention.attention.key", "attention.attention.value", "attention.output.dense"): | ||
| required[prefix + projection + ".weight"] = (width, width) | ||
| if projection == "attention.output.dense" or config.get("qkv_bias", True): | ||
| required[prefix + projection + ".bias"] = (width,) | ||
| for name, shape in (("intermediate.dense.weight", (inner, width)), ("intermediate.dense.bias", (inner,)), | ||
| ("output.dense.weight", (width, inner)), ("output.dense.bias", (width,))): | ||
| required[prefix + name] = shape | ||
| return required | ||
|
|
||
|
|
||
| def load_weights(root, config): | ||
| required, weights = required_shapes(config), {} | ||
| with safe_open(str(root / "model.safetensors"), framework="numpy") as source: | ||
| keys = set(source.keys()) | ||
| for key, shape in required.items(): | ||
| if key not in keys or tuple(source.get_slice(key).get_shape()) != shape: | ||
| raise ValueError(f"vit_mae missing or invalid checkpoint tensor: {key}, expected {shape}") | ||
| weights[key] = source.get_tensor(key).astype(np.float32) | ||
| return weights | ||
|
|
||
|
|
||
| class Graph: | ||
| def __init__(self, network, config, weights, capacity): | ||
| self.n, self.c, self.w, self.capacity = network, config, weights, capacity | ||
| self.patches, self.kept = geometry(config) | ||
| self.heads, self.dim = config["num_attention_heads"], config["hidden_size"] // config["num_attention_heads"] | ||
| self.constants = [] | ||
|
|
||
| def constant(self, value, dtype=np.float32): | ||
| value = np.ascontiguousarray(value, dtype=dtype) | ||
| self.constants.append(value) | ||
| return self.n.add_constant(value.shape, trt.Weights(value)).get_output(0) | ||
|
|
||
| def binary(self, x, y, operation=trt.ElementWiseOperation.SUM): | ||
| return self.n.add_elementwise(x, y, operation).get_output(0) | ||
|
|
||
| def reshape(self, x, shape, transpose=None): | ||
| layer = self.n.add_shuffle(x) | ||
| layer.reshape_dims = shape | ||
| if transpose is not None: | ||
| layer.second_transpose = transpose | ||
| return layer.get_output(0) | ||
|
|
||
| def linear(self, x, name): | ||
| x = self.n.add_matrix_multiply(x, trt.MatrixOperation.NONE, | ||
| self.constant(self.w[name + ".weight"].T), trt.MatrixOperation.NONE).get_output(0) | ||
| if name + ".bias" in self.w: | ||
| x = self.binary(x, self.constant(self.w[name + ".bias"].reshape(1, -1))) | ||
| return x | ||
|
|
||
| def norm(self, x, name): | ||
| layer = self.n.add_normalization(x, self.constant(self.w[name + ".weight"].reshape(1, -1)), | ||
| self.constant(self.w[name + ".bias"].reshape(1, -1)), 1 << 1) | ||
| layer.epsilon = self.c["layer_norm_eps"] | ||
| return layer.get_output(0) | ||
|
|
||
| def build(self): | ||
| width, size, patch = self.c["hidden_size"], self.c["image_size"], self.c["patch_size"] | ||
| length = self.kept + 1 | ||
| pixels = self.n.add_input("pixel_values", trt.float32, (1, 3, size, size)) | ||
| visible = self.n.add_input("visible_indices", trt.int32, (self.kept,)) | ||
| prefix = "vit.embeddings.patch_embeddings.projection" | ||
| convolution = self.n.add_convolution_nd(pixels, width, (patch, patch), | ||
| trt.Weights(self.w[prefix + ".weight"]), trt.Weights(self.w[prefix + ".bias"])) | ||
| convolution.stride_nd = (patch, patch) | ||
| x = self.reshape(convolution.get_output(0), (width, self.patches), (1, 0)) | ||
| x = self.binary(x, self.constant(self.w["vit.embeddings.position_embeddings"][0, 1:])) | ||
| x = self.n.add_gather(x, visible, 0).get_output(0) | ||
| cls = self.w["vit.embeddings.cls_token"].reshape(1, width) + self.w["vit.embeddings.position_embeddings"][0, :1] | ||
| tokens = self.n.add_concatenation([self.constant(cls), x]) | ||
| tokens.axis = 0 | ||
| x = tokens.get_output(0) | ||
| for layer in range(self.c["num_hidden_layers"]): | ||
| prefix = f"vit.encoder.layer.{layer}" | ||
| normalized = self.norm(x, prefix + ".layernorm_before") | ||
| query, key, value = [self.reshape(self.linear(normalized, prefix + ".attention.attention." + name), | ||
| (length, self.heads, self.dim), (1, 0, 2)) for name in ("query", "key", "value")] | ||
| scores = self.n.add_matrix_multiply(query, trt.MatrixOperation.NONE, key, trt.MatrixOperation.TRANSPOSE).get_output(0) | ||
| scores = self.binary(scores, self.constant([[[self.dim ** -0.5]]]), trt.ElementWiseOperation.PROD) | ||
| probabilities = self.n.add_softmax(scores) | ||
| probabilities.axes = 1 << 2 | ||
| context = self.n.add_matrix_multiply(probabilities.get_output(0), trt.MatrixOperation.NONE, value, | ||
| trt.MatrixOperation.NONE).get_output(0) | ||
| merged = self.n.add_shuffle(context) | ||
| merged.first_transpose = (1, 0, 2) | ||
| merged.reshape_dims = (length, width) | ||
| x = self.binary(self.linear(merged.get_output(0), prefix + ".attention.output.dense"), x) | ||
| intermediate = self.linear(self.norm(x, prefix + ".layernorm_after"), prefix + ".intermediate.dense") | ||
| intermediate = self.n.add_activation(intermediate, trt.ActivationType.GELU_ERF).get_output(0) | ||
| x = self.binary(self.linear(intermediate, prefix + ".output.dense"), x) | ||
| x = self.norm(x, "vit.layernorm") | ||
| x.name = "last_hidden_state" | ||
| self.n.mark_output(x) | ||
|
|
||
|
|
||
| def compile_engine(config, weights, verbose=False): | ||
| 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)) | ||
| options = builder.create_builder_config() | ||
| options.builder_optimization_level = 3 | ||
| options.clear_flag(trt.BuilderFlag.TF32) | ||
| graph = Graph(network, config, weights, geometry(config)[1] + 1) | ||
| graph.build() | ||
| plan = builder.build_serialized_network(network, options) | ||
| if plan is None: | ||
| raise RuntimeError("vit_mae TensorRT encoder build failed") | ||
| return bytes(plan) | ||
|
|
||
|
|
||
| def _normalization(processor, name): | ||
| raw = processor.get(name) | ||
| if raw is None: | ||
| raw = 0.5 | ||
| values = [raw] * 3 if type(raw) in (int, float) else raw | ||
| fp32_max = float(np.finfo(np.float32).max) | ||
| if ( | ||
| not isinstance(values, list) or len(values) != 3 | ||
| or any(type(value) not in (int, float) or not abs(value) <= fp32_max for value in values) | ||
| ): | ||
| raise ValueError(f"vit_mae processor {name} requires three finite float32 channels") | ||
| with np.errstate(under="ignore"): | ||
| channels = np.asarray(values, dtype=np.float32) | ||
| if name == "image_std" and (channels == 0).any(): | ||
| raise ValueError("vit_mae processor image_std must be nonzero in float32") | ||
| return channels.tolist() | ||
|
|
||
|
|
||
| def build(request, writer): | ||
| if request.dynamic_kv_cache: | ||
| raise NotImplementedError("vit_mae does not support dynamic_kv_cache") | ||
| if request.task != "image_to_token_features" or request.precision != "fp32" or request.backend != "trt": | ||
| raise ValueError("vit_mae requires image_to_token_features, precision=fp32, backend=trt") | ||
| for field, value, default in ( | ||
| ("max_batch_size", request.max_batch_size, 1), ("tensor_parallel_size", request.tensor_parallel_size, 1), | ||
| ("context_parallel_size", request.context_parallel_size, 1), ("max_sequence_length", request.max_sequence_length, None), | ||
| ("image_height", request.image_height, None), ("image_width", request.image_width, None), | ||
| ("video_num_frames", request.video_num_frames, None), ("mtp_seq_len", request.mtp_seq_len, None), | ||
| ("fp32_layers", request.fp32_layers, ()), | ||
| ): | ||
| if value != default: | ||
| raise NotImplementedError(f"vit_mae does not support {field}") | ||
| if request.quantization not in (None, "none"): | ||
| raise NotImplementedError("vit_mae does not support quantization") | ||
| root = Path(request.model_dir) | ||
| config = json.loads((root / "config.json").read_text()) | ||
| patches, kept = geometry(config) | ||
| processor = json.loads((root / "preprocessor_config.json").read_text()) | ||
| if not processor.get("do_resize", True) or not processor.get("do_normalize", True) or processor.get("resample", 2) != 2: | ||
| raise NotImplementedError("vit_mae requires its bilinear resize and channel normalization") | ||
| if processor.get("do_rescale", True) is not True or processor.get("rescale_factor", 1 / 255) != 1 / 255: | ||
| raise NotImplementedError("vit_mae requires rescaling pixels by 1/255") | ||
| size = processor.get("size") | ||
| if size is None: | ||
| size = 224 | ||
| if type(size) is int: | ||
| size = {"height": size, "width": size} | ||
| if not isinstance(size, dict) or any( | ||
| type(size.get(axis)) is not int or size[axis] != config["image_size"] | ||
| for axis in ("height", "width") | ||
| ): | ||
| raise ValueError("vit_mae processor size disagrees with checkpoint patches") | ||
| mean = _normalization(processor, "image_mean") | ||
| std = _normalization(processor, "image_std") | ||
| pixels = np.array([[0], [1]], dtype=np.float32) | ||
| with np.errstate(over="ignore"): | ||
| endpoints = (pixels - np.asarray(mean, dtype=np.float32)) / np.asarray(std, dtype=np.float32) | ||
| if not np.isfinite(endpoints).all(): | ||
| raise ValueError("vit_mae normalization must cover the pixel range in float32") | ||
| writer.set_header(family="vit_mae", task=request.task, backend=request.backend) | ||
| writer.add_bytes("model.plan", compile_engine(config, load_weights(root, config), request.verbose)) | ||
| writer.add_json("runtime.json", {"schema_version": 1, "image_size": config["image_size"], | ||
| "patch_size": config["patch_size"], "patches": patches, "kept": kept, "hidden_size": config["hidden_size"], | ||
| "image_mean": mean, "image_std": std, "resample": 2}) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| transformers>=5.3.0 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| add_library(trtmc_model_vit_mae SHARED pipeline.cpp plugin.cpp image_preprocess.cpp) | ||
| target_include_directories(trtmc_model_vit_mae PRIVATE | ||
| ${PROJECT_SOURCE_DIR} ${PROJECT_SOURCE_DIR}/core/runtime/include) | ||
| target_include_directories(trtmc_model_vit_mae SYSTEM PRIVATE ${TRTMC_CUDA_INCLUDE_DIR}) | ||
| target_link_libraries(trtmc_model_vit_mae PRIVATE | ||
| trtmc_core nlohmann_json::nlohmann_json ${TRTMC_CUDART_LIBRARY}) | ||
| target_compile_options(trtmc_model_vit_mae PRIVATE -Wall -Wextra -Wpedantic) | ||
| set_target_properties(trtmc_model_vit_mae PROPERTIES | ||
| LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}" | ||
| BUILD_RPATH "\$ORIGIN" INSTALL_RPATH "\$ORIGIN") | ||
| install(TARGETS trtmc_model_vit_mae LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) | ||
|
|
||
| if(TRTMC_BUILD_TESTS) | ||
| add_executable(vit_mae_e2e ${PROJECT_SOURCE_DIR}/families/vit_mae/tests/cpp/e2e_consumer.cpp image_preprocess.cpp) | ||
| target_include_directories(vit_mae_e2e PRIVATE ${PROJECT_SOURCE_DIR}) | ||
| target_link_libraries(vit_mae_e2e PRIVATE trtmc_c trtmc_core nlohmann_json::nlohmann_json) | ||
| set_target_properties(vit_mae_e2e PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") | ||
| endif() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.