nvidia-oliver-holworthy commited on
Commit
e9fb531
·
unverified ·
1 Parent(s): 382fc3a

Add golden regression tests and Docker test environment

Browse files

25-test pytest suite covering image preprocessing, encoder output, decoder
forward pass, generation, and processor behaviour. golden_outputs.json
captures reference values from transformers 4.51.3. Dockerfile and
docker-compose.yaml provide a reproducible environment for running tests
against multiple transformers versions.

Signed-off-by: Oliver Holworthy <nvidia-oliver-holworthy@users.noreply.huggingface.co>

Files changed (6) hide show
  1. Dockerfile +39 -0
  2. docker-compose.yaml +33 -0
  3. golden_outputs.json +134 -0
  4. pyproject.toml +33 -0
  5. test_golden.py +538 -0
  6. uv.lock +0 -0
Dockerfile ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM nvcr.io/nvidia/pytorch:26.03-py3
2
+
3
+ # ---------------------------------------------------------------------------
4
+ # Install uv
5
+ # ---------------------------------------------------------------------------
6
+ COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
7
+
8
+ WORKDIR /workspace
9
+
10
+ # ---------------------------------------------------------------------------
11
+ # Virtual environment
12
+ #
13
+ # --system-site-packages makes the venv inherit every package already
14
+ # installed in the NVIDIA base image, including torch, torchvision, and the
15
+ # matching CUDA libraries. uv will not reinstall those packages (they are
16
+ # declared in [tool.uv] exclude-dependencies), so the base-image builds are
17
+ # left untouched.
18
+ # ---------------------------------------------------------------------------
19
+ RUN uv venv /opt/venv --system-site-packages
20
+ ENV VIRTUAL_ENV=/opt/venv
21
+ ENV PATH="/opt/venv/bin:$PATH"
22
+
23
+ # ---------------------------------------------------------------------------
24
+ # Layer 1 — install dependencies (not the project itself)
25
+ #
26
+ # Only pyproject.toml is present at this point, so Docker re-runs this step
27
+ # only when the dependency list changes, not when source files change.
28
+ # ---------------------------------------------------------------------------
29
+ COPY pyproject.toml .
30
+ RUN uv sync --no-install-project
31
+
32
+ # ---------------------------------------------------------------------------
33
+ # Layer 2 — copy source and finish
34
+ #
35
+ # With package = false in pyproject.toml there is nothing extra to install;
36
+ # the second sync is a fast no-op that confirms the environment is complete.
37
+ # ---------------------------------------------------------------------------
38
+ COPY . .
39
+ RUN uv sync
docker-compose.yaml ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ services:
2
+ nemotron-parse:
3
+ build: .
4
+ image: nemotron-parse:latest
5
+ working_dir: /workspace
6
+
7
+ deploy:
8
+ resources:
9
+ reservations:
10
+ devices:
11
+ - driver: nvidia
12
+ count: all
13
+ capabilities: [gpu]
14
+
15
+ volumes:
16
+ # Project source — live-edits on the host are reflected immediately.
17
+ - .:/workspace
18
+ # Shadow the host .venv (wrong Python version) so uv uses /opt/venv inside
19
+ # the container rather than the host-side virtual environment.
20
+ - /workspace/.venv
21
+ # HuggingFace model cache — persists the RADIO encoder weights across
22
+ # container restarts so they are not re-downloaded on every run.
23
+ - hf-cache:/root/.cache/huggingface
24
+
25
+ environment:
26
+ HF_HOME: /root/.cache/huggingface
27
+
28
+ # Keep the container alive for interactive use (exec, attach, etc.).
29
+ stdin_open: true
30
+ tty: true
31
+
32
+ volumes:
33
+ hf-cache:
golden_outputs.json ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "transformers_version": "4.51.3",
4
+ "torch_version": "2.11.0a0+a6c236b9fd.nv26.03.46836102",
5
+ "device": "cuda:0",
6
+ "dtype": "torch.bfloat16",
7
+ "model_path": "/workspace"
8
+ },
9
+ "image_processing": {
10
+ "shape": [
11
+ 1,
12
+ 3,
13
+ 2048,
14
+ 1664
15
+ ],
16
+ "mean": 0.06537187099456787,
17
+ "std": 0.2386379987001419,
18
+ "first_20_values": [
19
+ 0.0,
20
+ 0.0,
21
+ 0.0,
22
+ 0.0,
23
+ 0.0,
24
+ 0.0,
25
+ 0.0,
26
+ 0.0,
27
+ 0.0,
28
+ 0.0,
29
+ 0.0,
30
+ 0.0,
31
+ 0.0,
32
+ 0.0,
33
+ 0.0,
34
+ 0.0,
35
+ 0.0,
36
+ 0.0,
37
+ 0.0,
38
+ 0.0
39
+ ]
40
+ },
41
+ "encoder_output": {
42
+ "shape": [
43
+ 1,
44
+ 3329,
45
+ 1024
46
+ ],
47
+ "mean": -0.0001354874111711979,
48
+ "std": 0.9438313841819763,
49
+ "token0_first16": [
50
+ -0.1884765625,
51
+ 0.81640625,
52
+ -0.37890625,
53
+ -0.46875,
54
+ 0.5078125,
55
+ -0.89453125,
56
+ 0.71484375,
57
+ -0.11865234375,
58
+ -0.484375,
59
+ -0.169921875,
60
+ 0.173828125,
61
+ 0.6640625,
62
+ 1.5625,
63
+ -0.283203125,
64
+ -0.9921875,
65
+ 0.10009765625
66
+ ]
67
+ },
68
+ "forward_pass": {
69
+ "logits_shape": [
70
+ 1,
71
+ 1,
72
+ 52352
73
+ ],
74
+ "top_k_indices": [
75
+ 0,
76
+ 38394,
77
+ 159,
78
+ 1972,
79
+ 31501,
80
+ 5007,
81
+ 25230,
82
+ 49726,
83
+ 12301,
84
+ 40617
85
+ ],
86
+ "top_k_values": [
87
+ 56.0,
88
+ 38.0,
89
+ 38.0,
90
+ 37.75,
91
+ 37.75,
92
+ 37.75,
93
+ 37.75,
94
+ 37.75,
95
+ 37.5,
96
+ 37.5
97
+ ]
98
+ },
99
+ "generation": {
100
+ "max_new_tokens": 50,
101
+ "token_ids": [
102
+ 2,
103
+ 0,
104
+ 50004,
105
+ 50008,
106
+ 50001,
107
+ 50010,
108
+ 50412,
109
+ 51799,
110
+ 82,
111
+ 2722,
112
+ 113,
113
+ 18121,
114
+ 579,
115
+ 115,
116
+ 113,
117
+ 19321,
118
+ 89,
119
+ 115,
120
+ 221,
121
+ 82,
122
+ 493,
123
+ 113,
124
+ 18121,
125
+ 579,
126
+ 115,
127
+ 50633,
128
+ 51850,
129
+ 52327,
130
+ 2
131
+ ],
132
+ "decoded_text": "</s><s><predict_bbox><predict_classes><output_markdown><predict_no_text_in_pic><x_0.3916><y_0.5969>\\begin{tabular}{ccccc}\n\\end{tabular}<x_0.6074><y_0.6367><class_Table></s>"
133
+ }
134
+ }
pyproject.toml ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "nemotron-parse"
3
+ version = "1.2.0"
4
+ description = "NVIDIA Nemotron-Parse document parsing model"
5
+ requires-python = ">=3.10"
6
+ dependencies = [
7
+ "transformers==4.51.3",
8
+ "accelerate==1.12.0",
9
+ "albumentations==2.0.8",
10
+ "timm==1.0.22",
11
+ "einops",
12
+ "Pillow",
13
+ "numpy",
14
+ "opencv-python-headless",
15
+ "beautifulsoup4",
16
+ "open-clip-torch>=3.3.0",
17
+ "pytest>=9.0.3",
18
+ ]
19
+
20
+ [project.optional-dependencies]
21
+ # vLLM serving (install separately in the serving container).
22
+ vllm = ["openai"]
23
+ # Development / testing.
24
+ dev = ["pytest"]
25
+
26
+ [tool.uv]
27
+ # This repo is a model directory loaded via trust_remote_code, not an
28
+ # installable Python package, so uv should only manage dependencies.
29
+ package = false
30
+
31
+ # torch and torchvision ship pre-compiled with CUDA support inside the
32
+ # NVIDIA base image (nvcr.io/nvidia/pytorch:*). uv must not overwrite them.
33
+ exclude-dependencies = ["torch", "torchvision"]
test_golden.py ADDED
@@ -0,0 +1,538 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Golden reference tests for NVIDIA-Nemotron-Parse-v1.2.
3
+
4
+ Captures reference outputs from the pinned dependency set, then verifies the
5
+ same outputs after dependency changes.
6
+
7
+ WORKFLOW
8
+ --------
9
+ Step 1 — capture (run once against pinned deps, e.g. transformers==4.51.3):
10
+
11
+ python test_golden.py --capture [--model-path /path/to/model]
12
+
13
+ This writes golden_outputs.json next to this file.
14
+
15
+ Step 2 — verify (run against new deps):
16
+
17
+ pytest test_golden.py -v
18
+
19
+ All tests skip automatically if golden_outputs.json is missing.
20
+
21
+ TEST LAYERS
22
+ -----------
23
+ 1. Image preprocessing — pixel value stats + first-N raw values (no GPU needed)
24
+ 2. Encoder output — hidden state shape, mean, std, and a fixed-position slice
25
+ 3. Decoder forward pass — top-k logit indices and values at a fixed decoder step
26
+ 4. Generation — exact token ID sequence for 50 greedy-decoded tokens
27
+ """
28
+
29
+ import json
30
+ import os
31
+ import sys
32
+ import pytest
33
+ import numpy as np
34
+ import torch
35
+ from pathlib import Path
36
+
37
+ # ---------------------------------------------------------------------------
38
+ # Paths / constants
39
+ # ---------------------------------------------------------------------------
40
+ MODEL_PATH = str(Path(__file__).parent)
41
+ GOLDEN_FILE = Path(__file__).parent / "golden_outputs.json"
42
+
43
+ TASK_PROMPT = "</s><s><predict_bbox><predict_classes><output_markdown><predict_no_text_in_pic>"
44
+ MAX_NEW_TOKENS_GOLDEN = 50 # short enough to be fast, long enough to be meaningful
45
+ TOP_K = 10 # number of top logit predictions to capture
46
+
47
+
48
+ # ---------------------------------------------------------------------------
49
+ # Deterministic test image (no external files required)
50
+ # ---------------------------------------------------------------------------
51
+ def make_test_image():
52
+ """Return a fully deterministic PIL image that loosely resembles a document."""
53
+ from PIL import Image, ImageDraw
54
+
55
+ img = Image.new("RGB", (400, 600), color=(255, 255, 255))
56
+ draw = ImageDraw.Draw(img)
57
+
58
+ # Title bar
59
+ draw.rectangle([20, 20, 380, 80], fill=(210, 210, 210))
60
+
61
+ # Body text area with ruled lines
62
+ draw.rectangle([20, 100, 380, 480], fill=(245, 245, 245))
63
+ for y in range(120, 470, 18):
64
+ draw.line([(40, y), (360, y)], fill=(170, 170, 170), width=1)
65
+
66
+ # Table-like grid at the bottom
67
+ draw.rectangle([20, 500, 380, 580], fill=(200, 220, 200))
68
+ for x in range(80, 380, 80):
69
+ draw.line([(x, 500), (x, 580)], fill=(100, 140, 100), width=1)
70
+ for y in range(520, 580, 20):
71
+ draw.line([(20, y), (380, y)], fill=(100, 140, 100), width=1)
72
+
73
+ return img
74
+
75
+
76
+ # ---------------------------------------------------------------------------
77
+ # Golden file helpers
78
+ # ---------------------------------------------------------------------------
79
+ def load_golden():
80
+ if GOLDEN_FILE.exists():
81
+ with open(GOLDEN_FILE) as f:
82
+ return json.load(f)
83
+ return None
84
+
85
+
86
+ def save_golden(data: dict):
87
+ with open(GOLDEN_FILE, "w") as f:
88
+ json.dump(data, f, indent=2)
89
+
90
+
91
+ # ---------------------------------------------------------------------------
92
+ # Pytest fixtures (session-scoped so the model is loaded only once)
93
+ # ---------------------------------------------------------------------------
94
+ @pytest.fixture(scope="session")
95
+ def env():
96
+ """Load model, processor, and tokenizer once for the whole test session."""
97
+ import torch
98
+ from transformers import AutoModel, AutoProcessor, AutoTokenizer
99
+
100
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
101
+ dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32
102
+
103
+ print(f"\nLoading model from {MODEL_PATH} on {device} ({dtype})…")
104
+ model = AutoModel.from_pretrained(
105
+ MODEL_PATH,
106
+ trust_remote_code=True,
107
+ torch_dtype=dtype,
108
+ ).to(device).eval()
109
+
110
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, trust_remote_code=True)
111
+ processor = AutoProcessor.from_pretrained(MODEL_PATH, trust_remote_code=True)
112
+
113
+ return dict(model=model, tokenizer=tokenizer, processor=processor,
114
+ device=device, dtype=dtype)
115
+
116
+
117
+ @pytest.fixture(scope="session")
118
+ def processed_inputs(env):
119
+ """Preprocess the test image once for the whole session."""
120
+ import torch
121
+
122
+ image = make_test_image()
123
+ inputs = env["processor"](
124
+ images=[image],
125
+ text=TASK_PROMPT,
126
+ return_tensors="pt",
127
+ add_special_tokens=False,
128
+ ).to(env["device"])
129
+
130
+ return inputs, image
131
+
132
+
133
+ @pytest.fixture(scope="session")
134
+ def golden():
135
+ """Load golden data; tests that need it skip if the file is absent."""
136
+ data = load_golden()
137
+ if data is None:
138
+ pytest.skip("golden_outputs.json not found — run: python test_golden.py --capture")
139
+ return data
140
+
141
+
142
+ # ---------------------------------------------------------------------------
143
+ # Layer 1: Image preprocessing
144
+ # (Does not require a model or GPU — fast sanity check on the processor.)
145
+ # ---------------------------------------------------------------------------
146
+ class TestImageProcessing:
147
+ def test_pixel_values_shape(self, processed_inputs):
148
+ inputs, _ = processed_inputs
149
+ pv = inputs["pixel_values"]
150
+ # Model expects 2048×1664 images
151
+ assert list(pv.shape) == [1, 3, 2048, 1664], f"Unexpected shape: {pv.shape}"
152
+
153
+ def test_pixel_values_dtype(self, processed_inputs):
154
+ inputs, _ = processed_inputs
155
+ # T.ToTensor() always produces float32; the model casts internally
156
+ assert inputs["pixel_values"].dtype == torch.float32
157
+
158
+ def test_pixel_value_range(self, processed_inputs):
159
+ """Values should be in [0, 1] after ToTensor (before RADIO normalisation)."""
160
+ pv = processed_inputs[0]["pixel_values"].float()
161
+ assert pv.min() >= 0.0, f"Pixel values below 0: {pv.min()}"
162
+ assert pv.max() <= 1.0, f"Pixel values above 1: {pv.max()}"
163
+
164
+ def test_pixel_values_stats_match_golden(self, processed_inputs, golden):
165
+ pv = processed_inputs[0]["pixel_values"].float()
166
+ g = golden["image_processing"]
167
+
168
+ assert abs(pv.mean().item() - g["mean"]) < 1e-4, \
169
+ f"mean changed: {pv.mean().item():.6f} vs golden {g['mean']:.6f}"
170
+ assert abs(pv.std().item() - g["std"]) < 1e-4, \
171
+ f"std changed: {pv.std().item():.6f} vs golden {g['std']:.6f}"
172
+
173
+ def test_pixel_values_first_values_match_golden(self, processed_inputs, golden):
174
+ """Exact match on the first 20 float values (catches transform-order bugs)."""
175
+ pv = processed_inputs[0]["pixel_values"].float()
176
+ actual = pv.flatten()[:20].tolist()
177
+ expected = golden["image_processing"]["first_20_values"]
178
+
179
+ for i, (a, e) in enumerate(zip(actual, expected)):
180
+ assert abs(a - e) < 1e-5, f"pixel[{i}] changed: {a} vs {e}"
181
+
182
+
183
+ # ---------------------------------------------------------------------------
184
+ # Layer 2: Encoder output
185
+ # ---------------------------------------------------------------------------
186
+ class TestEncoderOutput:
187
+ @pytest.fixture(scope="class")
188
+ def encoder_out(self, env, processed_inputs):
189
+ import torch
190
+ with torch.no_grad():
191
+ out = env["model"].encoder(processed_inputs[0]["pixel_values"])
192
+ return out
193
+
194
+ def test_encoder_output_shape(self, encoder_out):
195
+ # RadioWithNeck outputs (batch, 321, 1024): 320 patch tokens + 1 summary token
196
+ hs = encoder_out.last_hidden_state
197
+ assert hs.shape[0] == 1
198
+ assert hs.shape[2] == 1024, f"Unexpected hidden dim: {hs.shape[2]}"
199
+
200
+ def test_encoder_output_stats_match_golden(self, encoder_out, golden):
201
+ hs = encoder_out.last_hidden_state.float()
202
+ g = golden["encoder_output"]
203
+
204
+ assert abs(hs.mean().item() - g["mean"]) < 0.05, \
205
+ f"encoder mean changed: {hs.mean().item():.4f} vs {g['mean']:.4f}"
206
+ assert abs(hs.std().item() - g["std"]) < 0.05, \
207
+ f"encoder std changed: {hs.std().item():.4f} vs {g['std']:.4f}"
208
+
209
+ def test_encoder_output_slice_match_golden(self, encoder_out, golden):
210
+ """Fixed-position slice: token 0, first 16 hidden dims."""
211
+ hs = encoder_out.last_hidden_state.float()
212
+ actual = hs[0, 0, :16].tolist()
213
+ expected = golden["encoder_output"]["token0_first16"]
214
+
215
+ for i, (a, e) in enumerate(zip(actual, expected)):
216
+ assert abs(a - e) < 0.1, \
217
+ f"encoder hidden[0,0,{i}] changed: {a:.4f} vs {e:.4f}"
218
+
219
+
220
+ # ---------------------------------------------------------------------------
221
+ # Layer 3: Decoder forward pass (logits)
222
+ # ---------------------------------------------------------------------------
223
+ class TestForwardPass:
224
+ @pytest.fixture(scope="class")
225
+ def forward_out(self, env, processed_inputs):
226
+ import torch
227
+ # Minimal decoder input: just the decoder_start_token (EOS = 2 for mBART)
228
+ dec_ids = torch.tensor([[2]], device=env["device"])
229
+ with torch.no_grad():
230
+ out = env["model"](
231
+ pixel_values=processed_inputs[0]["pixel_values"],
232
+ decoder_input_ids=dec_ids,
233
+ return_dict=True,
234
+ )
235
+ return out
236
+
237
+ def test_logits_shape(self, forward_out, env):
238
+ logits = forward_out.logits
239
+ assert logits.shape[0] == 1
240
+ assert logits.shape[1] == 1 # one decoder step
241
+ assert logits.shape[2] == 52352, f"Unexpected vocab size: {logits.shape[2]}"
242
+
243
+ def test_top_k_indices_match_golden(self, forward_out, golden):
244
+ """The TOP_K predicted token IDs should be identical (order matters)."""
245
+ import torch
246
+ logits = forward_out.logits[0, -1, :].float()
247
+ top_k = torch.topk(logits, k=TOP_K)
248
+
249
+ actual = top_k.indices.tolist()
250
+ expected = golden["forward_pass"]["top_k_indices"]
251
+
252
+ assert actual == expected, \
253
+ f"Top-{TOP_K} predicted tokens changed.\n actual: {actual}\n expected: {expected}"
254
+
255
+ def test_top_k_values_match_golden(self, forward_out, golden):
256
+ """Logit magnitudes may drift slightly due to bf16; use a loose tolerance."""
257
+ import torch
258
+ logits = forward_out.logits[0, -1, :].float()
259
+ top_k = torch.topk(logits, k=TOP_K)
260
+
261
+ for i, (a, e) in enumerate(zip(top_k.values.tolist(),
262
+ golden["forward_pass"]["top_k_values"])):
263
+ assert abs(a - e) < 1.0, \
264
+ f"top-{i+1} logit value changed: {a:.3f} vs {e:.3f}"
265
+
266
+
267
+ # ---------------------------------------------------------------------------
268
+ # Layer 4: Generation (greedy, deterministic)
269
+ # ---------------------------------------------------------------------------
270
+ class TestGeneration:
271
+ @pytest.fixture(scope="class")
272
+ def gen_out(self, env, processed_inputs):
273
+ import torch
274
+ with torch.no_grad():
275
+ out = env["model"].generate(
276
+ **processed_inputs[0],
277
+ max_new_tokens=MAX_NEW_TOKENS_GOLDEN,
278
+ do_sample=False,
279
+ num_beams=1,
280
+ )
281
+ return out
282
+
283
+ def test_generated_token_ids_match_golden(self, gen_out, golden):
284
+ """Exact token-ID match — the most sensitive regression signal."""
285
+ actual = gen_out[0].cpu().tolist()
286
+ expected = golden["generation"]["token_ids"]
287
+
288
+ assert actual == expected, (
289
+ f"Generated token sequence differs from golden.\n"
290
+ f" first divergence at index "
291
+ f"{next((i for i,(a,e) in enumerate(zip(actual,expected)) if a!=e), '?')}\n"
292
+ f" actual: {actual}\n"
293
+ f" expected: {expected}"
294
+ )
295
+
296
+ def test_decoded_text_matches_golden(self, gen_out, env, golden):
297
+ text = env["tokenizer"].decode(gen_out[0], skip_special_tokens=False)
298
+ assert text == golden["generation"]["decoded_text"], \
299
+ f"Decoded text differs:\n actual: {text!r}\n expected: {golden['generation']['decoded_text']!r}"
300
+
301
+
302
+ # ---------------------------------------------------------------------------
303
+ # Layer 5: Processor (no model or GPU needed — pure preprocessing & text utils)
304
+ # ---------------------------------------------------------------------------
305
+ @pytest.fixture(scope="session")
306
+ def proc():
307
+ """Load processor + tokenizer only (no model weights, no GPU required)."""
308
+ from transformers import AutoProcessor, AutoTokenizer
309
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, trust_remote_code=True)
310
+ processor = AutoProcessor.from_pretrained(MODEL_PATH, trust_remote_code=True)
311
+ return dict(processor=processor, tokenizer=tokenizer)
312
+
313
+
314
+ class TestProcessor:
315
+ # ------------------------------------------------------------------
316
+ # post_process_generation
317
+ # ------------------------------------------------------------------
318
+ def test_post_process_generation_returns_string_for_string_input(self, proc, golden):
319
+ """String input → string output."""
320
+ decoded = golden["generation"]["decoded_text"]
321
+ result = proc["processor"].post_process_generation(decoded)
322
+ assert isinstance(result, str)
323
+
324
+ def test_post_process_generation_removes_bos_eos(self, proc, golden):
325
+ """<s> and </s> tokens must be stripped from the output."""
326
+ decoded = golden["generation"]["decoded_text"]
327
+ result = proc["processor"].post_process_generation(decoded)
328
+ assert "<s>" not in result
329
+ assert "</s>" not in result
330
+
331
+ def test_post_process_generation_matches_manual_clean(self, proc, golden):
332
+ """Exact match against the expected cleaned string."""
333
+ decoded = golden["generation"]["decoded_text"]
334
+ expected = decoded.replace("<s>", "").replace("</s>", "").strip()
335
+ result = proc["processor"].post_process_generation(decoded)
336
+ assert result == expected
337
+
338
+ def test_post_process_generation_list_returns_list(self, proc, golden):
339
+ """Multi-element list input → list output of the same length."""
340
+ decoded = golden["generation"]["decoded_text"]
341
+ result = proc["processor"].post_process_generation([decoded, decoded])
342
+ assert isinstance(result, list)
343
+ assert len(result) == 2
344
+ assert result[0] == result[1]
345
+
346
+ def test_post_process_generation_single_element_list_returns_string(self, proc, golden):
347
+ """Single-element list input → scalar string (not a list)."""
348
+ decoded = golden["generation"]["decoded_text"]
349
+ result = proc["processor"].post_process_generation([decoded])
350
+ assert isinstance(result, str)
351
+
352
+ # ------------------------------------------------------------------
353
+ # decode / batch_decode via the processor
354
+ # ------------------------------------------------------------------
355
+ def test_decode_via_processor_matches_tokenizer(self, proc, golden):
356
+ """processor.decode() must give the same result as tokenizer.decode()."""
357
+ token_ids = golden["generation"]["token_ids"]
358
+ via_proc = proc["processor"].decode(token_ids, skip_special_tokens=False)
359
+ via_tok = proc["tokenizer"].decode(token_ids, skip_special_tokens=False)
360
+ assert via_proc == via_tok
361
+
362
+ def test_batch_decode_via_processor(self, proc, golden):
363
+ """processor.batch_decode() on repeated token lists matches golden decoded text."""
364
+ token_ids = golden["generation"]["token_ids"]
365
+ results = proc["processor"].batch_decode(
366
+ [token_ids, token_ids], skip_special_tokens=False
367
+ )
368
+ assert isinstance(results, list)
369
+ assert len(results) == 2
370
+ assert results[0] == results[1] == golden["generation"]["decoded_text"]
371
+
372
+ # ------------------------------------------------------------------
373
+ # Image processing edge cases
374
+ # ------------------------------------------------------------------
375
+ def test_large_image_resized_to_target(self, proc):
376
+ """Image larger than 2048×1664 is downscaled to exactly [1, 3, 2048, 1664]."""
377
+ from PIL import Image
378
+ large = Image.new("RGB", (4000, 5000), color=(128, 64, 32))
379
+ out = proc["processor"](images=[large], return_tensors="pt")
380
+ assert list(out["pixel_values"].shape) == [1, 3, 2048, 1664]
381
+
382
+ def test_grayscale_image_converted_to_rgb(self, proc):
383
+ """Grayscale (mode 'L') image is converted to RGB and produces 3 output channels."""
384
+ from PIL import Image
385
+ gray = Image.new("L", (400, 600), color=128)
386
+ out = proc["processor"](images=[gray], return_tensors="pt")
387
+ assert list(out["pixel_values"].shape) == [1, 3, 2048, 1664]
388
+
389
+ def test_multi_image_batch_first_dim(self, proc):
390
+ """A batch of N images produces pixel_values with first dimension N."""
391
+ from PIL import Image
392
+ imgs = [
393
+ Image.new("RGB", (400, 600), color=(i * 30, i * 20, i * 10))
394
+ for i in range(3)
395
+ ]
396
+ out = proc["processor"](images=imgs, return_tensors="pt")
397
+ assert list(out["pixel_values"].shape) == [3, 3, 2048, 1664]
398
+
399
+ def test_image_only_input_has_no_input_ids(self, proc):
400
+ """Passing images without text returns pixel_values and no input_ids key."""
401
+ from PIL import Image
402
+ img = Image.new("RGB", (400, 600))
403
+ out = proc["processor"](images=[img], return_tensors="pt")
404
+ assert "pixel_values" in out
405
+ assert "input_ids" not in out
406
+
407
+ def test_text_only_input_has_no_pixel_values(self, proc):
408
+ """Passing text without images returns input_ids and no pixel_values key."""
409
+ out = proc["processor"](text="hello world", return_tensors="pt")
410
+ assert "input_ids" in out
411
+ assert "pixel_values" not in out
412
+
413
+
414
+ # ---------------------------------------------------------------------------
415
+ # Capture helper (run as script: python test_golden.py --capture)
416
+ # ---------------------------------------------------------------------------
417
+ def capture(model_path: str = MODEL_PATH):
418
+ """
419
+ Run a full inference pass and write golden_outputs.json.
420
+ Intended to be run once against the pinned dependency set.
421
+ """
422
+ import torch
423
+ import transformers
424
+ from transformers import AutoModel, AutoProcessor, AutoTokenizer
425
+
426
+ device = "cuda:0" if torch.cuda.is_available() else "cpu"
427
+ dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32
428
+
429
+ print(f"Capturing golden outputs")
430
+ print(f" transformers : {transformers.__version__}")
431
+ print(f" torch : {torch.__version__}")
432
+ print(f" device : {device} dtype={dtype}")
433
+ print(f" model_path : {model_path}")
434
+
435
+ model = AutoModel.from_pretrained(
436
+ model_path, trust_remote_code=True, torch_dtype=dtype
437
+ ).to(device).eval()
438
+ tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
439
+ processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
440
+
441
+ image = make_test_image()
442
+ inputs = processor(
443
+ images=[image],
444
+ text=TASK_PROMPT,
445
+ return_tensors="pt",
446
+ add_special_tokens=False,
447
+ ).to(device)
448
+
449
+ # ---------- image processing ----------
450
+ pv = inputs["pixel_values"].float()
451
+ image_data = {
452
+ "shape": list(pv.shape),
453
+ "mean": pv.mean().item(),
454
+ "std": pv.std().item(),
455
+ "first_20_values": pv.flatten()[:20].tolist(),
456
+ }
457
+ print(f"\n[image] shape={image_data['shape']} mean={image_data['mean']:.4f} std={image_data['std']:.4f}")
458
+
459
+ # ---------- encoder output ----------
460
+ with torch.no_grad():
461
+ enc_out = model.encoder(inputs["pixel_values"])
462
+ hs = enc_out.last_hidden_state.float()
463
+ encoder_data = {
464
+ "shape": list(hs.shape),
465
+ "mean": hs.mean().item(),
466
+ "std": hs.std().item(),
467
+ "token0_first16": hs[0, 0, :16].tolist(),
468
+ }
469
+ print(f"[encoder] shape={encoder_data['shape']} mean={encoder_data['mean']:.4f} std={encoder_data['std']:.4f}")
470
+
471
+ # ---------- forward pass (logits) ----------
472
+ dec_ids = torch.tensor([[2]], device=device) # decoder_start_token_id
473
+ with torch.no_grad():
474
+ fwd_out = model(
475
+ pixel_values=inputs["pixel_values"],
476
+ decoder_input_ids=dec_ids,
477
+ return_dict=True,
478
+ )
479
+ logits = fwd_out.logits[0, -1, :].float()
480
+ top_k = torch.topk(logits, k=TOP_K)
481
+ forward_data = {
482
+ "logits_shape": list(fwd_out.logits.shape),
483
+ "top_k_indices": top_k.indices.tolist(),
484
+ "top_k_values": top_k.values.tolist(),
485
+ }
486
+ top_tokens = [tokenizer.decode([i]) for i in top_k.indices.tolist()]
487
+ print(f"[forward] top-{TOP_K} tokens: {top_tokens}")
488
+
489
+ # ---------- generation ----------
490
+ with torch.no_grad():
491
+ gen_out = model.generate(
492
+ **inputs,
493
+ max_new_tokens=MAX_NEW_TOKENS_GOLDEN,
494
+ do_sample=False,
495
+ num_beams=1,
496
+ )
497
+ token_ids = gen_out[0].cpu().tolist()
498
+ decoded_text = tokenizer.decode(gen_out[0], skip_special_tokens=False)
499
+ generation_data = {
500
+ "max_new_tokens": MAX_NEW_TOKENS_GOLDEN,
501
+ "token_ids": token_ids,
502
+ "decoded_text": decoded_text,
503
+ }
504
+ print(f"[generation] {len(token_ids)} tokens: {decoded_text!r}")
505
+
506
+ # ---------- save ----------
507
+ golden = {
508
+ "metadata": {
509
+ "transformers_version": transformers.__version__,
510
+ "torch_version": torch.__version__,
511
+ "device": str(device),
512
+ "dtype": str(dtype),
513
+ "model_path": model_path,
514
+ },
515
+ "image_processing": image_data,
516
+ "encoder_output": encoder_data,
517
+ "forward_pass": forward_data,
518
+ "generation": generation_data,
519
+ }
520
+ save_golden(golden)
521
+ print(f"\nGolden outputs written to {GOLDEN_FILE}")
522
+ return golden
523
+
524
+
525
+ if __name__ == "__main__":
526
+ import argparse
527
+
528
+ parser = argparse.ArgumentParser(description="Golden reference capture/verify for Nemotron-Parse")
529
+ parser.add_argument("--capture", action="store_true", help="Capture golden outputs")
530
+ parser.add_argument("--model-path", default=MODEL_PATH, help="Path to model directory")
531
+ args = parser.parse_args()
532
+
533
+ if args.capture:
534
+ capture(model_path=args.model_path)
535
+ else:
536
+ parser.print_help()
537
+ print("\nTo run tests: pytest test_golden.py -v")
538
+ print("To capture: python test_golden.py --capture")
uv.lock ADDED
The diff for this file is too large to render. See raw diff