Skip to content

Commit 1e6f61f

Browse files
justinchubyCopilot
andauthored
Add NVIDIA Nemotron Parse 2.0 support (#473)
## Summary Add end-to-end support for `nvidia/NVIDIA-Nemotron-Parse-2.0` (`model_type: nemotron_parse`) as a two-model image-to-text package. ### Architecture - C-RADIOv2-H vision backbone: linear patch projection emitted as Conv, cropped CPE positions, eight register/teacher tokens, 32 ViT-H blocks, and three flattened teacher summaries. - Nemotron feature neck: 1280→1024 projection, horizontal 1×4 convolutional compression, summary-token projection, and LayerNorms. - Position-free scaled-embedding mBART decoder: 10 pre-norm self/cross-attention layers, causal self KV cache, exact GELU FFN, tied LM head. - Standardized package keys: `vision_encoder` and `decoder`. - Vision graph accepts the official processor's float32 pixels and casts internally for f16/bf16 weights. - Config/registry/task wiring, Conv2d asymmetric kernels, CLI/runtime guard, real document fixture, L1-L5 tests, and committed real-image goldens. ## Validation GPU: **NVIDIA RTX A1000, 8188 MiB, driver 573.44**. CUDA runs explicitly requested `CUDAExecutionProvider`; sessions reported `['CUDAExecutionProvider', 'CPUExecutionProvider']` (CPU is retained for ORT shape operations). | Gate | Exact result | |---|---| | L1 graph | `4 passed, 1350 deselected in 8.74s` | | Weight alignment | `1 passed, 226 deselected in 8.80s` | | L2 YAML schema | `237 passed in 1.94s` | | L3 synthetic fp32 parity | `1 passed, 203 deselected in 7.43s` at `rtol=atol=1e-3` (ONNX vision output fed to ONNX decoder) | | Real-image BF16 HF/ONNX CUDA parity | `1 passed, 122 deselected in 71.49s` (74.683s wall); encoder cosine >0.99, logits cosine >0.995, identical argmax | | L4 + deterministic L5 CUDA | `2 passed, 377 deselected in 103.13s` (106.441s wall); real nonzero image, exact L4 top-1 and exact 24-token L5 golden | | Regression suite | `3638 passed, 57 skipped in 47.45s` | | Lint | initialized `lintrunner`; `lintrunner -a`: `ok No lint issues` | | Automated review | final code-review agent: no significant issues | ### CUDA CLI and dtype matrix All three exports used `mobius build --model nvidia/NVIDIA-Nemotron-Parse-2.0 --trust-remote-code --dtype <dtype> --ep cuda` and produced `vision_encoder/model.onnx` plus `decoder/model.onnx`. - **bf16:** export 52.083s; saved package 1,806,874,350 bytes; float32 processor input; vision load+run 5.631s, decoder load+prefill 1.664s; golden top-1 `50251` matched. - **f16:** export 51.423s; full CUDA load+prefill 8.032s; golden top-1 `50251` matched. - **f32:** export 51.346s; saved package 3,613,010,525 bytes; full CUDA load+prefill 24.155s; golden top-1 `50251` matched. ### Olive Olive 0.13.0 `OnnxBnb4Quantization` NF4 quantized the final f16 decoder successfully in 29.320s (237,677,671-byte model). CUDA generation produced 24 non-degenerate OCR tokens in 7.112s: `# MOBIUS OCR VALIDATION ... Nemotron Parse 2.` ## Checklist - [x] Microsoft/MIT headers, model docstrings, Multimodal metadata, public component imports, no explicit protobuf APIs - [x] Registry/export/task/config extraction and representative tiny config - [x] Identity weight alignment - [x] L1 graph construction and L2 schema/config - [x] L3 synthetic and real-weight parity - [x] Real-image BF16 CUDA L4 golden - [x] Deterministic greedy 24-token CUDA L5 golden - [x] fp32/fp16/bf16 CUDA CLI exports and exact real-image top-1 match - [x] CUDA CLI artifact reload/runtime - [x] Olive NF4 quantization and non-degenerate CUDA generation - [x] Initialized `lintrunner -a` clean - [x] Final automated code review clean ## Narrow waivers / limitations - **ORT GenAI:** waived. Installed ORT GenAI 0.15.2 has no generic image-to-text vision-encoder-decoder pipeline/schema for this two-model package (it is not the supported VLM decoder+embedding+vision contract). Emitting a `genai_config.json` would create an unloadable artifact, so export explicitly raises `NotImplementedError`; the guard test passed (`1 passed, 76 deselected in 7.08s`). Direct ONNX CUDA runtime is fully validated above. - **Foundry Local:** waived. Foundry Local 0.10.2 consumes ORT GenAI packages and therefore cannot load this package without the unsupported GenAI configuration above. The installed CLI was checked; fabricating registration metadata would not make the image-to-text pipeline executable. - **Cross-attention projection cache:** the shared `EncoderDecoderAttention` contract currently recomputes encoder K/V projections per decode token. Adding a lazy cross-cache requires a broader split-prefill/decode redesign; this is a performance limitation, not a correctness gap, and the exact 24-token CUDA L5 run passes. ## Baseline note Before validation, `.pytest_cache/v/cache/lastfailed` contained only `tests/synthetic_parity_test.py::test_synthetic_parity[granitemoehybrid]`. That cached unrelated baseline was not treated as a Nemotron failure; targeted Nemotron parity and the full non-integration regression suite pass as reported above. ### Post-push CI baseline status The repository-wide GitHub matrix and L3 jobs currently fail only the untouched `bamba_0`/`bamba_1` synthetic cases on every Python/OS matrix entry (`max_abs_diff=0.001375` / `0.001662`, argmax matches, cosine ≥0.999996). Nemotron's affected-model L1 job passes, and its targeted local L1-L5 results are above. The benchmark-base job separately failed while finalizing an artifact with GitHub `403 Forbidden`; benchmark head passed. These unrelated failures are not masked or changed in this PR. --------- Signed-off-by: Justin Chu <[email protected]> Signed-off-by: justinchuby <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent a2e0ab7 commit 1e6f61f

26 files changed

Lines changed: 1629 additions & 20 deletions

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ multi-component export for pipelines.
2929
|---|---|
3030
| **Text Generation** | Llama 2/3/4, Mistral, Qwen 2/2.5/3/3.5/3.6, Phi-3/3.5, Gemma 1/2/3/4, Granite, GPT-2, OPT, OLMo, SmolLM3, and many more |
3131
| **Mixture of Experts** | PhiMoE, GPTOSS, Mixtral, OLMoE, DeepSeek-V2/V3, Qwen2-MoE, Qwen3-MoE, Qwen3-Next, GLM-4-MoE, Arctic, DBRX, Jamba |
32-
| **Multimodal** | Gemma 3/4, Phi-4MM (vision + audio + LoRA), LLaVA, InternVL2, Qwen2.5-VL, Qwen3-VL, Qwen3.5/3.6-VL, Pixtral |
32+
| **Multimodal** | Gemma 3/4, Phi-4MM (vision + audio + LoRA), Nemotron Parse, LLaVA, InternVL2, Qwen2.5-VL, Qwen3-VL, Qwen3.5/3.6-VL, Pixtral |
3333
| **Encoder-only** | BERT, RoBERTa, ALBERT, DeBERTa, DistilBERT, ELECTRA, XLNet |
3434
| **Encoder-Decoder** | BART, T5/mT5, Marian, M2M-100, Pegasus, BigBird-Pegasus |
3535
| **Speech-to-Text** | Whisper, FastConformer-RNNT, FunASR, Qwen3-ASR, SenseVoice |

‎scripts/generate_golden.py‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -539,6 +539,86 @@ def _generate_vision_language(case: TestCase, json_path: Path, device: str) -> N
539539
)
540540

541541

542+
def _generate_image_to_text(case: TestCase, json_path: Path, device: str) -> None:
543+
"""Generate Nemotron Parse-style image-to-text reference data."""
544+
import torch
545+
from PIL import Image
546+
from transformers import AutoModel, AutoProcessor
547+
548+
from mobius._testing.golden import save_generation_json, save_golden_ref
549+
550+
dtype_map = {
551+
"float32": torch.float32,
552+
"float16": torch.float16,
553+
"bfloat16": torch.bfloat16,
554+
}
555+
model = AutoModel.from_pretrained(
556+
case.model_id,
557+
revision=case.revision,
558+
torch_dtype=dtype_map[case.dtype],
559+
trust_remote_code=case.trust_remote_code,
560+
).to(device)
561+
model.eval()
562+
processor = AutoProcessor.from_pretrained(
563+
case.model_id,
564+
revision=case.revision,
565+
trust_remote_code=case.trust_remote_code,
566+
)
567+
images = [
568+
Image.open(Path("testdata") / image_path).convert("RGB") for image_path in case.images
569+
]
570+
processed = processor(
571+
images=images,
572+
text=case.decoder_prompt,
573+
return_tensors="pt",
574+
add_special_tokens=False,
575+
).to(device)
576+
decoder_input_ids = processed["input_ids"]
577+
578+
with torch.no_grad():
579+
outputs = model(
580+
pixel_values=processed["pixel_values"],
581+
decoder_input_ids=decoder_input_ids,
582+
)
583+
last_logits = outputs.logits[0, -1].float().cpu().numpy()
584+
golden = _extract_logits_golden(last_logits)
585+
input_ids = decoder_input_ids.cpu().numpy()
586+
587+
generated_ids = None
588+
if "L5" in case.level:
589+
with torch.no_grad():
590+
generated = model.generate(
591+
pixel_values=processed["pixel_values"],
592+
decoder_input_ids=decoder_input_ids,
593+
max_new_tokens=case.generation_params.get("max_new_tokens", 20),
594+
do_sample=False,
595+
)
596+
generated_ids = generated[0, input_ids.shape[1] :].cpu().numpy()
597+
598+
save_golden_ref(
599+
json_path,
600+
top1_id=golden["top1_id"],
601+
top2_id=golden["top2_id"],
602+
top10_ids=golden["top10_ids"],
603+
top10_logits=golden["top10_logits"],
604+
logits_summary=golden["logits_summary"],
605+
input_ids=input_ids,
606+
)
607+
608+
if generated_ids is not None:
609+
gen_path = json_path.with_name(json_path.stem + "_generation.json")
610+
save_generation_json(
611+
gen_path,
612+
model_id=case.model_id,
613+
prompt=case.decoder_prompt,
614+
generated_tokens=generated_ids.tolist(),
615+
generated_text=processor.decode(
616+
generated_ids.tolist(),
617+
skip_special_tokens=False,
618+
),
619+
)
620+
621+
542622
def _generate_speech_to_text(case: TestCase, json_path: Path, device: str) -> None:
543623
"""Generate golden data for a speech-to-text (Whisper) model."""
544624
import librosa
@@ -1674,6 +1754,7 @@ def _hook(_module, _args, kwargs, output):
16741754
"feature-extraction": _generate_encoder,
16751755
"seq2seq": _generate_seq2seq,
16761756
"image-text-to-text": _generate_vision_language,
1757+
"image-to-text": _generate_image_to_text,
16771758
"image-classification": _generate_image_classification,
16781759
"speech-to-text": _generate_speech_to_text,
16791760
"speech-language": _generate_speech_language,

‎src/mobius/_configs/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
MuseGlimmerConfig,
4949
NanoChatConfig,
5050
NemotronHConfig,
51+
NemotronParseConfig,
5152
Qwen35MtpConfig,
5253
Sam2Config,
5354
SegformerConfig,
@@ -115,6 +116,7 @@
115116
"MMSConfig",
116117
"MuseGlimmerConfig",
117118
"NanoChatConfig",
119+
"NemotronParseConfig",
118120
"NemotronHConfig",
119121
"QuantizationConfig",
120122
"Qwen35MtpConfig",

‎src/mobius/_configs/_base.py‎

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1282,6 +1282,101 @@ class VisionLanguageConfig(CausalLMConfig):
12821282
"""
12831283

12841284

1285+
@dataclasses.dataclass
1286+
class NemotronParseConfig(ArchitectureConfig):
1287+
"""Configuration for NVIDIA Nemotron Parse image-to-text models."""
1288+
1289+
image_height: int = 2048
1290+
image_width: int = 1664
1291+
vision_max_grid_size: int = 128
1292+
num_summary_tokens: int = 3
1293+
decoder_start_token_id: int = 2
1294+
scale_embedding: bool = True
1295+
add_final_layer_norm: bool = True
1296+
1297+
@classmethod
1298+
def from_transformers(cls, config, parent_config=None) -> NemotronParseConfig:
1299+
del parent_config
1300+
import types
1301+
1302+
def _namespace(value):
1303+
if isinstance(value, dict):
1304+
return types.SimpleNamespace(
1305+
**{key: _namespace(item) for key, item in value.items()}
1306+
)
1307+
if isinstance(value, list):
1308+
return [_namespace(item) for item in value]
1309+
return value
1310+
1311+
decoder = _namespace(getattr(config, "decoder", None))
1312+
if decoder is None:
1313+
raise ValueError("Nemotron Parse config is missing its decoder sub-config")
1314+
base = ArchitectureConfig.from_transformers(decoder, parent_config=config)
1315+
fields = _shallow_fields(base)
1316+
num_attention_heads = int(
1317+
getattr(decoder, "decoder_attention_heads", None)
1318+
or getattr(decoder, "num_attention_heads", fields["num_attention_heads"])
1319+
)
1320+
hidden_size = int(fields["hidden_size"])
1321+
if hidden_size % num_attention_heads:
1322+
raise ValueError(
1323+
"Nemotron Parse decoder hidden size must be divisible by its attention heads"
1324+
)
1325+
fields.update(
1326+
num_attention_heads=num_attention_heads,
1327+
num_key_value_heads=num_attention_heads,
1328+
head_dim=hidden_size // num_attention_heads,
1329+
)
1330+
1331+
raw_image_size = getattr(config, "image_size", (2048, 1664))
1332+
if isinstance(raw_image_size, int):
1333+
image_height = image_width = raw_image_size
1334+
else:
1335+
image_height, image_width = (int(raw_image_size[0]), int(raw_image_size[1]))
1336+
1337+
encoder = _namespace(getattr(config, "encoder", None))
1338+
patch_size = int(getattr(encoder, "patch_size", 16))
1339+
max_resolution = int(
1340+
getattr(encoder, "max_resolution", max(image_height, image_width))
1341+
)
1342+
fields.update(
1343+
model_type="nemotron_parse",
1344+
bos_token_id=getattr(config, "bos_token_id", fields.get("bos_token_id")),
1345+
eos_token_id=getattr(config, "eos_token_id", fields.get("eos_token_id")),
1346+
pad_token_id=getattr(config, "pad_token_id", fields["pad_token_id"]),
1347+
tie_word_embeddings=getattr(config, "tie_word_embeddings", True),
1348+
max_position_embeddings=(
1349+
getattr(config, "max_sequence_length", None)
1350+
or fields["max_position_embeddings"]
1351+
),
1352+
vision=VisionConfig(
1353+
hidden_size=1280,
1354+
intermediate_size=5120,
1355+
num_hidden_layers=32,
1356+
num_attention_heads=16,
1357+
image_size=max_resolution,
1358+
patch_size=patch_size,
1359+
norm_eps=1e-6,
1360+
model_type="radio_v2.5-h",
1361+
in_channels=3,
1362+
),
1363+
)
1364+
resolved_dtype = _resolve_dtype(config)
1365+
if resolved_dtype is not None:
1366+
fields["dtype"] = resolved_dtype
1367+
1368+
return cls(
1369+
**fields,
1370+
image_height=image_height,
1371+
image_width=image_width,
1372+
vision_max_grid_size=max_resolution // patch_size,
1373+
num_summary_tokens=3,
1374+
decoder_start_token_id=int(getattr(config, "decoder_start_token_id", 2)),
1375+
scale_embedding=bool(getattr(decoder, "scale_embedding", True)),
1376+
add_final_layer_norm=bool(getattr(decoder, "add_final_layer_norm", True)),
1377+
)
1378+
1379+
12851380
# ---------------------------------------------------------------------------
12861381
# Model-family subclasses — add model-specific fields
12871382
# ---------------------------------------------------------------------------

‎src/mobius/_configs/_base_test.py‎

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,45 @@
11
# Copyright (c) Microsoft Corporation.
22
# Licensed under the MIT License.
33

4-
"""Unit tests for :class:`ArchitectureConfig.from_transformers`."""
4+
"""Unit tests for architecture-specific configuration extraction."""
55

66
from __future__ import annotations
77

8-
from mobius._configs._base import ArchitectureConfig
8+
import types
9+
10+
from mobius._configs import ArchitectureConfig, NemotronParseConfig
11+
12+
13+
def test_nemotron_parse_maps_raw_mbart_decoder_attention_heads():
14+
"""The Hub's non-trusted config exposes MBART's decoder-specific aliases."""
15+
config = types.SimpleNamespace(
16+
model_type="nemotron_parse",
17+
decoder={
18+
"model_type": "nemotron_parse_text",
19+
"d_model": 1024,
20+
"decoder_attention_heads": 16,
21+
"decoder_ffn_dim": 4096,
22+
"decoder_layers": 10,
23+
"num_hidden_layers": 12,
24+
"vocab_size": 72256,
25+
"pad_token_id": 1,
26+
},
27+
encoder={"patch_size": 16, "max_resolution": 2048},
28+
image_size=[2048, 1664],
29+
max_sequence_length=9000,
30+
bos_token_id=0,
31+
eos_token_id=2,
32+
pad_token_id=1,
33+
tie_word_embeddings=True,
34+
decoder_start_token_id=2,
35+
)
36+
37+
extracted = NemotronParseConfig.from_transformers(config)
38+
39+
assert extracted.num_attention_heads == 16
40+
assert extracted.num_key_value_heads == 16
41+
assert extracted.head_dim == 64
42+
assert extracted.num_decoder_layers == 10
943

1044

1145
class _FakeHFConfig:

‎src/mobius/_registry.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
Lfm2Config,
3232
MMSConfig,
3333
MuseGlimmerConfig,
34+
NemotronParseConfig,
3435
WhisperConfig,
3536
)
3637
from mobius.models import (
@@ -77,6 +78,7 @@
7778
MoECausalLMModel,
7879
NanoChatCausalLMModel,
7980
NemotronCausalLMModel,
81+
NemotronParseForConditionalGeneration,
8082
OLMo2CausalLMModel,
8183
OLMoCausalLMModel,
8284
Phi3CausalLMModel,
@@ -576,6 +578,11 @@ def _detect_fallback_registration(hf_config) -> ModelRegistration | None:
576578
"bamba": ModelRegistration(BambaCausalLMModel),
577579
"jamba": ModelRegistration(JambaCausalLMModel),
578580
"nemotron_h": ModelRegistration(NemotronHCausalLMModel),
581+
"nemotron_parse": ModelRegistration(
582+
NemotronParseForConditionalGeneration,
583+
task="vision-encoder-decoder",
584+
config_class=NemotronParseConfig,
585+
),
579586
# --- Hybrid linear-attention ---
580587
"longcat_flash": ModelRegistration(LongcatFlashCausalLMModel),
581588
# --- Multimodal ---
@@ -892,6 +899,7 @@ def _create_default_registry() -> ModelRegistry:
892899
"csm": "sesame/csm-1b",
893900
"evolla": "westlake-repl/Evolla-10B-hf",
894901
"nemotron_h": "nvidia/NVIDIA-Nemotron-3-Nano-4B-BF16",
902+
"nemotron_parse": "nvidia/NVIDIA-Nemotron-Parse-2.0",
895903
"open-llama": "openlm-research/open_llama_3b",
896904
"persimmon": "adept/persimmon-8b-base",
897905
"shieldgemma2": "google/shieldgemma-2b",

‎src/mobius/components/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@
6161
"PostNormDecoderLayer",
6262
"QuantizedEmbedding",
6363
"QuantizedLinear",
64+
"RadioVisionModel",
6465
"RMSNorm",
6566
"RmsNorm2d",
6667
"ScaleFreeRMSNorm",
@@ -265,6 +266,7 @@
265266
from mobius.components._qwen25_vl_vision import (
266267
Qwen25VLVisionRotaryEmbedding as Qwen25VLVisionRotaryEmbedding,
267268
)
269+
from mobius.components._radio_vision import RadioVisionModel
268270
from mobius.components._rms_norm import (
269271
GatedRMSNorm,
270272
OffsetRMSNorm,

0 commit comments

Comments
 (0)