Image-Text-to-Text
Transformers
Safetensors
nvidia
VLM
conversational
richtext amalad commited on
Commit
1025db9
·
0 Parent(s):

Duplicate from nvidia/NVIDIA-Nemotron-Nano-12B-v2-VL-BF16

Browse files

Co-authored-by: Amala Sanjay Deshmukh <amalad@users.noreply.huggingface.co>

This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +36 -0
  2. README.md +554 -0
  3. bias.md +13 -0
  4. chat_template.jinja +180 -0
  5. config.json +321 -0
  6. configuration.py +65 -0
  7. configuration_nemotron_h.py +243 -0
  8. configuration_radio.py +152 -0
  9. evs.py +86 -0
  10. explainability.md +15 -0
  11. generation_config.json +11 -0
  12. image_processing.py +161 -0
  13. images/demo.mp4 +3 -0
  14. images/demo_frames/frame_0000.jpg +3 -0
  15. images/demo_frames/frame_0001.jpg +3 -0
  16. images/demo_frames/frame_0002.jpg +3 -0
  17. images/demo_frames/frame_0003.jpg +3 -0
  18. images/demo_frames/frame_0004.jpg +3 -0
  19. images/demo_frames/frame_0005.jpg +3 -0
  20. images/demo_frames/frame_0006.jpg +3 -0
  21. images/demo_frames/frame_0007.jpg +3 -0
  22. images/demo_frames/frame_0008.jpg +3 -0
  23. images/demo_frames/frame_0009.jpg +3 -0
  24. images/demo_frames/frame_0010.jpg +3 -0
  25. images/demo_frames/frame_0011.jpg +3 -0
  26. images/demo_frames/frame_0012.jpg +3 -0
  27. images/demo_frames/frame_0013.jpg +3 -0
  28. images/demo_frames/frame_0014.jpg +3 -0
  29. images/demo_frames/metadata.json +42 -0
  30. images/example1a.jpeg +0 -0
  31. images/example1b.jpeg +0 -0
  32. images/table.png +3 -0
  33. images/tech.png +3 -0
  34. model-00001-of-00007.safetensors +3 -0
  35. model-00002-of-00007.safetensors +3 -0
  36. model-00003-of-00007.safetensors +3 -0
  37. model-00004-of-00007.safetensors +3 -0
  38. model-00005-of-00007.safetensors +3 -0
  39. model-00006-of-00007.safetensors +3 -0
  40. model-00007-of-00007.safetensors +3 -0
  41. model.safetensors.index.json +768 -0
  42. modeling.py +300 -0
  43. modeling_nemotron_h.py +1632 -0
  44. preprocessor_config.json +15 -0
  45. privacy.md +13 -0
  46. processing.py +274 -0
  47. processing_utils.py +96 -0
  48. quick_test_image.py +241 -0
  49. quick_test_video.py +208 -0
  50. safety.md +10 -0
.gitattributes ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,554 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: other
3
+ license_name: nvidia-open-model-license
4
+ license_link: >-
5
+ https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-license/
6
+ pipeline_tag: image-text-to-text
7
+ library_name: transformers
8
+ tags:
9
+ - nvidia
10
+ - VLM
11
+ ---
12
+
13
+ # Model Overview
14
+
15
+
16
+ ### Description:
17
+ NVIDIA Nemotron Nano v2 12B VL model enables multi-image reasoning and video understanding, along with strong document intelligence, visual Q&A and summarization capabilities.
18
+ <br>
19
+
20
+ This model is ready for commercial use. <br>
21
+
22
+ ### License/Terms of Use
23
+
24
+ Governing Terms: Use of this model is governed by the [ NVIDIA Open Model License Agreement](https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-license/)
25
+
26
+ ### Deployment Geography:
27
+ Global <br>
28
+
29
+ ### Use Case: <br>
30
+ Nemotron Nano 12B V2 VL is a model for multi-modal document intelligence. It would be used by individuals or businesses that need to process documents such as invoices, receipts, and manuals. The model is capable of handling multiple images of documents, up to four images at a resolution of 1k x 2k each, along with a long text prompt. The expected use is for tasks like summarization and Visual Question Answering (VQA). The model is also expected to have a significant advantage in throughput. <br>
31
+
32
+ ### Release Date: <br>
33
+ - Build.Nvidia.com [October 28th, 2025] via [nvidia/NVIDIA-Nemotron-Nano-VL-12B-V2](https://build.nvidia.com/nvidia/nvidia-nemotron-nano-vl-12b-v2)
34
+ - Hugging Face [October 28th, 2025] via [nvidia/NVIDIA-Nemotron-Nano-VL-12B-V2-BF16](https://huggingface.co/nvidia/Nemotron-Nano-12B-v2-VL-BF16)
35
+ - Hugging Face [October 28th, 2025] via [nvidia/NVIDIA-Nemotron-Nano-VL-12B-V2-FP8](https://huggingface.co/nvidia/NVIDIA-Nemotron-Nano-12B-v2-VL-FP8)
36
+ - Hugging Face [October 28th, 2025] via [nvidia/NVIDIA-Nemotron-Nano-VL-12B-V2-NVFP4](https://huggingface.co/nvidia/NVIDIA-Nemotron-Nano-12B-v2-VL-NVFP4-QAD)
37
+
38
+
39
+
40
+ # Model Architecture:
41
+ **Architecture Type:**
42
+ Transformer <br>
43
+ **Network Architecture:**
44
+ Vision Encoder: CRadioV2-H
45
+ Language Encoder: NVIDIA-Nemotron-Nano-12B-v2
46
+ <br>
47
+
48
+ ** Number of model parameters: 12.6B<br>
49
+
50
+
51
+ ## Computational Load (For NVIDIA Models Only)
52
+ **Cumulative Compute:** 2.2e+22 <br>
53
+ **Estimated Energy and Emissions for Model Training:**
54
+ Energy Consumption: 7,827.46 kWh <br>
55
+ Carbon Emissions: 3.21 tCO2e <br>
56
+
57
+
58
+ ## Input: <br>
59
+ **Input Type(s):** Image, Video, Text
60
+ **Input Format:** Image (png,jpg), Video (MP4, MKV, FLV, 3GP), Text (String) <br>
61
+ **Input Parameters:** Image (2D),Video(3D), Text (1D) <br>
62
+ **Other Properties Related to Input:**
63
+ - Input Images Supported: 4
64
+ - Language Supported: English only <br>
65
+ - Input + Output Token: 128K
66
+ - Minimum Resolution: 32 × 32 pixels
67
+ - Maximum Resolution: Determined by a 12-tile layout constraint, with each tile being 512 × 512 pixels. This supports aspect ratios such as:
68
+ - 4 × 3 layout: up to 2048 × 1536 pixels
69
+ - 3 × 4 layout: up to 1536 × 2048 pixels
70
+ - 2 × 6 layout: up to 1024 × 3072 pixels
71
+ - 6 × 2 layout: up to 3072 × 1024 pixels
72
+ - Other configurations allowed, provided total tiles ≤ 12
73
+ - Channel Count: 3 channels (RGB)
74
+ - Alpha Channel: Not supported (no transparency) <br>
75
+ - Frames: 2 FPS with min of 8 frame and max of 128 frames
76
+
77
+
78
+
79
+ ## Output: <br>
80
+ **Output Type(s):** Text <br>
81
+ **Output Format:** String <br>
82
+ Output Parameters: 1D <br>
83
+ **Other Properties Related to Output:** Input + Output Token: 128K <br>
84
+
85
+ Our AI models are designed and/or optimized to run on NVIDIA GPU-accelerated systems. By leveraging NVIDIA’s hardware (e.g. GPU cores) and software frameworks (e.g., CUDA libraries), the model achieves faster training and inference times compared to CPU-only solutions. <br>
86
+
87
+
88
+ ## Software Integration:
89
+ **Runtime Engine(s):**
90
+ * [vLLM] <br>
91
+ * [TRT-LLM] <br>
92
+ * [SGLang] <br>
93
+
94
+ **Supported Hardware Microarchitecture Compatibility:** <br>
95
+ * NVIDIA L40S <br>*
96
+ * NVIDIA A100 <br>
97
+ * NVIDIA B200 <br>
98
+ * NVIDIA H100/H200 <br>
99
+ * NVIDIA RTX PRO 6000 Server Edition<br>
100
+ * NVIDIA GB200 <br>
101
+
102
+ **Preferred/Supported Operating System(s):**
103
+ * [Linux] <br>
104
+
105
+ The integration of foundation and fine-tuned models into AI systems requires additional testing using use-case-specific data to ensure safe and effective deployment. Following the V-model methodology, iterative testing and validation at both unit and system levels are essential to mitigate risks, meet technical and functional requirements, and ensure compliance with safety and ethical standards before deployment. <br>
106
+
107
+
108
+ ## Model Version(s):
109
+ v1.0
110
+
111
+ ## Quick Start
112
+
113
+ ### Install Dependencies
114
+ ```
115
+ pip install causal_conv1d "transformers>4.53,<4.54" torch timm "mamba-ssm==2.2.5" accelerate open_clip_torch numpy pillow
116
+ ```
117
+
118
+ ### Usage
119
+
120
+ #### Single Image Inference
121
+ ```python
122
+ import torch
123
+ from PIL import Image
124
+ from transformers import AutoModelForCausalLM, AutoProcessor, AutoTokenizer
125
+
126
+ # Load model and processor
127
+ model_path = "nvidia/NVIDIA-Nemotron-Nano-12B-v2-VL-BF16" # Or use a local path
128
+ device = "cuda:0"
129
+
130
+ model = AutoModelForCausalLM.from_pretrained(
131
+ model_path,
132
+ trust_remote_code=True,
133
+ device_map=device,
134
+ torch_dtype=torch.bfloat16
135
+ ).eval()
136
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
137
+ processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
138
+
139
+ # Load image
140
+ image = Image.open("path/to/your/image.jpg")
141
+
142
+ # Prepare messages
143
+ messages = [
144
+ {"role": "system", "content": "/no_think"},
145
+ {
146
+ "role": "user",
147
+ "content": [
148
+ {"type": "image", "image": ""},
149
+ {"type": "text", "text": "Describe the image."},
150
+ ],
151
+ }
152
+ ]
153
+
154
+ # Generate prompt and process inputs
155
+ prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
156
+ inputs = processor(text=[prompt], images=[image], return_tensors="pt").to(device)
157
+
158
+ # Generate output
159
+ generated_ids = model.generate(
160
+ pixel_values=inputs.pixel_values,
161
+ input_ids=inputs.input_ids,
162
+ attention_mask=inputs.attention_mask,
163
+ max_new_tokens=1024,
164
+ do_sample=False,
165
+ eos_token_id=tokenizer.eos_token_id,
166
+ )
167
+
168
+ # Decode output
169
+ output_text = processor.batch_decode(
170
+ generated_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False
171
+ )[0]
172
+ print(output_text)
173
+ ```
174
+
175
+ #### Multi-Image Inference
176
+ ```python
177
+ import torch
178
+ from PIL import Image
179
+ from transformers import AutoModelForCausalLM, AutoProcessor, AutoTokenizer
180
+
181
+ # Load model and processor
182
+ model_path = "nvidia/NVIDIA-Nemotron-Nano-12B-v2-VL-BF16" # Or use a local path
183
+ device = "cuda:0"
184
+
185
+ model = AutoModelForCausalLM.from_pretrained(
186
+ model_path,
187
+ trust_remote_code=True,
188
+ device_map=device,
189
+ torch_dtype=torch.bfloat16
190
+ ).eval()
191
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
192
+ processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
193
+
194
+ # Load multiple images
195
+ images = [
196
+ Image.open("path/to/image1.jpg"),
197
+ Image.open("path/to/image2.jpg"),
198
+ ]
199
+
200
+ # Prepare messages with multiple images
201
+ messages = [
202
+ {"role": "system", "content": "/no_think"},
203
+ {
204
+ "role": "user",
205
+ "content": [
206
+ {"type": "image", "image": "/path/to/image1"},
207
+ {"type": "image", "image": "/path/to/image2"},
208
+ {"type": "text", "text": "\nDescribe the two images in detail."},
209
+ ],
210
+ }
211
+ ]
212
+
213
+ # Generate prompt and process inputs
214
+ prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
215
+ inputs = processor(text=[prompt], images=images, return_tensors="pt").to(device)
216
+
217
+ # Generate output
218
+ generated_ids = model.generate(
219
+ pixel_values=inputs.pixel_values,
220
+ input_ids=inputs.input_ids,
221
+ attention_mask=inputs.attention_mask,
222
+ max_new_tokens=1024,
223
+ do_sample=False,
224
+ eos_token_id=tokenizer.eos_token_id,
225
+ )
226
+
227
+ # Decode output
228
+ output_text = processor.batch_decode(
229
+ generated_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False
230
+ )[0]
231
+ print(output_text)
232
+ ```
233
+
234
+ #### Video Inference (from Pre-extracted Frames)
235
+
236
+ **Note:** Video decoding is not included. You must first extract frames from your video using ffmpeg or similar tools.
237
+
238
+ **Step 1: Extract frames from video**
239
+ ```bash
240
+ # Extract 1 frame per second
241
+ ffmpeg -i video.mp4 -vf fps=1 frames/frame_%04d.jpg
242
+
243
+ # Or extract a specific number of frames uniformly
244
+ ffmpeg -i video.mp4 -vf "select=not(mod(n\,30))" -vsync vfr frames/frame_%04d.jpg
245
+ ```
246
+
247
+ **Step 2: Run inference on frames**
248
+ ```python
249
+ import torch
250
+ from transformers import AutoModelForCausalLM, AutoProcessor, AutoTokenizer
251
+
252
+ import video_io # Helper module for loading frames
253
+
254
+ # Load model and processor
255
+ model_path = "nvidia/NVIDIA-Nemotron-Nano-12B-v2-VL-BF16" # Or use a local path
256
+ device = "cuda:0"
257
+
258
+ model = AutoModelForCausalLM.from_pretrained(
259
+ model_path,
260
+ trust_remote_code=True,
261
+ device_map=device,
262
+ torch_dtype=torch.bfloat16
263
+ ).eval()
264
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
265
+ processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
266
+
267
+ # Load frames from directory
268
+ frames_dir = "path/to/frames_directory"
269
+ video_fps = 1 # FPS used when extracting frames (for temporal understanding)
270
+
271
+ frames = video_io.load_frames_from_directory(frames_dir)
272
+ image_urls, metadata = video_io.frames_to_data_urls_with_metadata(frames, video_fps)
273
+
274
+ print(f"Loaded {len(frames)} frames, metadata: {metadata}")
275
+
276
+ # Prepare messages
277
+ messages = [
278
+ {"role": "system", "content": "/no_think"},
279
+ {
280
+ "role": "user",
281
+ "content": [
282
+ {"type": "video", "video": ""},
283
+ {"type": "text", "text": "\nDescribe what you see."},
284
+ ],
285
+ }
286
+ ]
287
+
288
+ # Generate prompt and process inputs
289
+ prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
290
+
291
+ # Process with FPS metadata for better temporal understanding
292
+ if metadata:
293
+ inputs = processor(
294
+ text=[prompt],
295
+ videos=frames,
296
+ videos_kwargs={'video_metadata': metadata},
297
+ return_tensors="pt",
298
+ )
299
+ else:
300
+ inputs = processor(
301
+ text=[prompt],
302
+ videos=frames,
303
+ return_tensors="pt",
304
+ )
305
+ inputs = inputs.to(device)
306
+
307
+ # Set video pruning rate for efficient inference
308
+ model.video_pruning_rate = 0.75
309
+
310
+ # Generate output
311
+ generated_ids = model.generate(
312
+ pixel_values_videos=inputs.pixel_values_videos,
313
+ input_ids=inputs.input_ids,
314
+ attention_mask=inputs.attention_mask,
315
+ max_new_tokens=128,
316
+ )
317
+
318
+ # Decode output
319
+ output_text = processor.batch_decode(
320
+ generated_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False
321
+ )[0]
322
+ print(output_text)
323
+ ```
324
+
325
+ #### Inference with vLLM
326
+
327
+ Make sure to use the main branch of vLLM. Run the following install command:
328
+
329
+ ```bash
330
+ !VLLM_USE_PRECOMPILED=1 pip install git+https://github.com/vllm-project/vllm.git@main
331
+ ```
332
+
333
+ Commands to serve the model:
334
+
335
+ **BF16**
336
+ ```bash
337
+ vllm serve nvidia/NVIDIA-Nemotron-Nano-12B-v2-VL-BF16 --trust-remote-code --dtype bfloat16 --video-pruning-rate 0
338
+ ```
339
+
340
+ **FP8**
341
+ ```bash
342
+ vllm serve nvidia/NVIDIA-Nemotron-Nano-12B-v2-VL-FP8 --trust-remote-code --quantization modelopt --video-pruning-rate 0
343
+ ```
344
+
345
+ **FP4**
346
+ ```bash
347
+ vllm serve nvidia/NVIDIA-Nemotron-Nano-12B-v2-VL-NVFP4-QAD --trust-remote-code --quantization modelopt_fp4 --video-pruning-rate 0
348
+ ```
349
+
350
+ #### Inference with SGLang
351
+ Support is verified in **main**:
352
+
353
+ ```bash
354
+ pip install "git+https://github.com/sgl-project/sglang.git@main#subdirectory=python"
355
+ ```
356
+
357
+ **BF16**
358
+ ```bash
359
+ sglang serve --trust-remote-code --model-path nvidia/Nemotron-Nano-12B-v2-VL-BF16 --max-mamba-cache-size 256 # Adjust '--max-mamba-cache-size' as needed, to fit in memory
360
+ ```
361
+
362
+ **FP8**
363
+ ```bash
364
+ sglang serve --trust-remote-code --model-path nvidia/NVIDIA-Nemotron-Nano-12B-v2-VL-FP8
365
+ ```
366
+
367
+ **FP4**
368
+ ```bash
369
+ sglang serve --trust-remote-code --model-path nvidia/NVIDIA-Nemotron-Nano-12B-v2-VL-NVFP4-QAD --quantization modelopt_fp4
370
+ ```
371
+
372
+
373
+ ## Training, Testing, and Evaluation Datasets:
374
+
375
+ ### Training Datasets:
376
+
377
+ **Data Modalities** <br>
378
+ ** Total Size: 39'486'703 samples <br>
379
+ ** Total Number of Datasets: 270 <br>
380
+ ** Text-only datasets: 33 <br>
381
+ ** Text-and-image datasets: 176 <br>
382
+ ** Video-and-text datasets: 61 <br>
383
+ ** Total size: 27.7 TB <br>
384
+
385
+ ** Data modalities: Text, Image, Video <br>
386
+ ** Data Collection Method by dataset: Hybrid: Automated, Human, Synthetic <br>
387
+ ** Labeling Method by dataset: Hybrid: Automated, Human, Synthetic <br>
388
+
389
+ ** Dataset partition: Training [100%], Testing [0%], Validation [0%] <br>
390
+ ** Time period for training data collection: 2023-2025 <br>
391
+ ** Time period for testing data collection: N/A <br>
392
+ ** Time period for validation data collection: N/A <br>
393
+
394
+ The post-training datasets consist of a mix of internal and public datasets designed for training vision language models across various tasks. It includes:
395
+
396
+ * Public datasets sourced from publicly available images and annotations, supporting tasks like classification, captioning, visual question answering, conversation modeling, document analysis and text/image reasoning.
397
+ * Internal text and image datasets built with public commercial images and internal labels, adapted for the same tasks as listed above.
398
+ * Synthetic image datasets generated programmatically for specific tasks like tabular data understanding and optical character recognition (OCR), for English, Chinese as well as other languages.
399
+ * Video datasets supporting video question answering and reasoning tasks from publicly available video sources, with either publicly available or internally generated annotations.
400
+ * Specialized datasets for safety alignment, function calling, and domain-specific tasks (e.g., science diagrams, financial question answering).
401
+ * NVIDIA-Sourced Synthetic Datasets for text reasoning.
402
+ * Private datasets for safety alignment or VQA on invoices.
403
+ * Crawled or scraped captioning, VQA, and video datasets.
404
+ * Some datasets were improved with Qwen2.5-72B-Instruct annotations
405
+
406
+ For around ~30% of our total training corpus and several of the domains listed above, we used commercially permissive models to perform:
407
+ * Language translation
408
+ * Re-labeling of annotations for text, image and video datasets
409
+ * Synthetic data generation
410
+ * Generating chain-of-thought (CoT) traces
411
+
412
+ Additional processing for several datasets included rule-based QA generation (e.g., with templates), expanding short answers into longer responses, as well as proper reformatting. More details can be found [here](https://arxiv.org/abs/2501.14818).
413
+
414
+
415
+ ** Image based datasets were all scanned against known CSAM to make sure no such content was included in training.<br>
416
+
417
+ # Public Datasets <br>
418
+ | Type | Data Type | Total Samples | Total Size (GB) |
419
+ |------|-----------|---------------|------------------|
420
+ | Function call | text | 8,000 | 0.02 |
421
+ | Image Captioning | image, text | 1,422,102 | 1,051.04 |
422
+ | Image Reasoning | image, text | 1,888,217 | 286.95 |
423
+ | OCR | image, text | 9,830,570 | 5,317.60 |
424
+ | Referring Expression Grounding | image, text | 14,694 | 2.39 |
425
+ | Safety | image, text | 34,187 | 9.21 |
426
+ | Safety | text | 57,223 | 0.52 |
427
+ | Safety | video, text | 12,988 | 11.78 |
428
+ | Text Instruction Tuning | text | 245,056 | 1.13 |
429
+ | Text Reasoning | text | 225,408 | 4.55 |
430
+ | VQA | image, text | 8,174,136 | 2,207.52 |
431
+ | VQA | video, text | 40,000 | 46.05 |
432
+ | Video Captioning | video, text | 3,289 | 6.31 |
433
+ | Video Reasoning | video, text | 42,620 | 49.10 |
434
+ | VideoQA | video, text | 1,371,923 | 17,641.79 |
435
+ | Visual Instruction Tuning | image, text | 1,173,877 | 167.79 |
436
+ | **TOTAL** | | **24,544,290** | **26,803.75** |
437
+
438
+
439
+ # Private Datasets <br>
440
+ | Type | Modalities | Total Samples | Total Size (GB) |
441
+ |------|------------|---------------|------------------|
442
+ | Image Reasoning | image, text | 17,729 | 15.41 |
443
+ | Text Reasoning | text | 445,958 | 9.01 |
444
+ | **TOTAL** | | **463,687** | **24.42** |
445
+
446
+
447
+ # Data Crawling and Scraping <br>
448
+ | Type | Modalities | Total Samples | Total Size (GB) |
449
+ |------|------------|---------------|------------------|
450
+ | Image Captioning | image, text | 39,870 | 10.24 |
451
+ | VQA | image, text | 40,348 | 3.94 |
452
+ | VideoQA | video, text | 288,728 | 393.30 |
453
+ | **TOTAL** | | **368,946** | **407.48** |
454
+
455
+
456
+ # User-Sourced Data (Collected by Provider including Prompts) <br>
457
+ <br>
458
+
459
+ # Self-Sourced Synthetic Data <br>
460
+ | Type | Data Type | Total Samples | Total Size (GB) |
461
+ |------|-----------|---------------|------------------|
462
+ | Code | text | 1,165,591 | 54.15 |
463
+ | OCR | image, text | 216,332 | 83.53 |
464
+ | Text Reasoning | text | 12,727,857 | 295.80 |
465
+ | **TOTAL** | | **14,109,780** | **433.48** |
466
+
467
+
468
+
469
+
470
+ **Properties**<br>
471
+ * Additionally, the dataset collection (for training and evaluation) consists of a mix of internal and public datasets designed for training and evaluation across various tasks. It includes:
472
+ * Internal datasets built with public commercial images and internal labels, supporting tasks like conversation modeling and document analysis.
473
+ * Public datasets sourced from publicly available images and annotations, adapted for tasks such as image captioning and visual question answering.
474
+ * Synthetic datasets generated programmatically for specific tasks like tabular data understanding.
475
+ * Specialized datasets for safety alignment, function calling, and domain-specific tasks (e.g., science diagrams, financial question answering).
476
+
477
+ ### Evaluation Datasets:
478
+ The following external benchmarks are used for evaluating the model: <br>
479
+
480
+ | Dataset |
481
+ |---------|
482
+ | [RDTableBench](https://github.com/Filimoa/rd-tablebench?tab=readme-ov-file ) |
483
+ | NVIDIA internal test set for OCR |
484
+ | [MMMU Val with ChatGPT as judge](https://mmmu-benchmark.github.io/) |
485
+ | [AI2D Test](https://prior.allenai.org/projects/diagram-understanding ) |
486
+ | [ChartQA Test](https://github.com/vis-nlp/ChartQA) |
487
+ | [InfoVQA Val](https://www.docvqa.org/datasets/infographicvqa) |
488
+ | [OCRBench](https://github.com/Yuliang-Liu/MultimodalOCR) |
489
+ | [OCRBenchV2](https://github.com/Yuliang-Liu/MultimodalOCR) English |
490
+ | [DocVQA Val](https://www.docvqa.org/datasets) |
491
+ | [SlideQA Val](https://github.com/nttmdlab-nlp/SlideVQA) |
492
+ | [Video MME](https://github.com/MME-Benchmarks/Video-MME) |
493
+
494
+
495
+
496
+ Data Collection Method by dataset: <br>
497
+ * Hybrid: Human, Automated <br>
498
+
499
+ Labeling Method by dataset: <br>
500
+ * Hybrid: Human, Automated <br>
501
+
502
+ **Properties (Quantity, Dataset Descriptions, Sensor(s)):** N/A <br>
503
+
504
+ **Dataset License(s):** N/A <br>
505
+
506
+ Evaluation benchmarks scores: <br>
507
+
508
+ | Benchmarks | Score |
509
+ |--------------------|-------|
510
+ | MMMU* | 68 |
511
+ | MathVista* | 76.9 |
512
+ | AI2D | 87.11 |
513
+ | OCRBenchv2 | 62.0 |
514
+ | OCRBench | 85.6 |
515
+ | OCR-Reasoning | 36.4 |
516
+ | ChartQA | 89.72 |
517
+ | DocVQA | 94.39 |
518
+ | Video-MME w/o sub | 65.9 |
519
+ | Vision Average | 74.0 |
520
+
521
+
522
+ # Inference: <br>
523
+ **Acceleration Engine:** vLLM <br>
524
+ **Acceleration Engine:** TRT-LLM <br>
525
+ **Acceleration Engine:** SGLang <br>
526
+
527
+ **Test Hardware:** <br>
528
+ * NVIDIA L40S <br>
529
+ * NVIDIA A100 <br>
530
+ * NVIDIA B200 <br>
531
+ * NVIDIA H100/H200 <br>
532
+ * NVIDIA RTX PRO 6000 Server Edition<br>
533
+ * NVIDIA GB200 <br>
534
+
535
+ ## Ethical Considerations:
536
+ NVIDIA believes Trustworthy AI is a shared responsibility and we have established policies and practices to enable development for a wide array of AI applications. When downloaded or used in accordance with our terms of service, developers should work with their internal model team to ensure this model meets requirements for the relevant industry and use case and addresses unforeseen product misuse. <br>
537
+
538
+ For more detailed information on ethical considerations for this model, please see the Model Card++ [Bias](bias.md), [Explainability](explainability.md), [Safety & Security](safety.md), and [Privacy](privacy.md) Subcards.
539
+
540
+ Please report security vulnerabilities or NVIDIA AI Concerns [here](https://www.nvidia.com/en-us/support/submit-security-vulnerability/).
541
+
542
+
543
+ # Citation:
544
+ ```
545
+ @misc{nvidia2025nvidianemotronnanov2,
546
+ title={NVIDIA Nemotron Nano V2 VL},
547
+ author={NVIDIA},
548
+ year={2025},
549
+ eprint={2511.03929},
550
+ archivePrefix={arXiv},
551
+ primaryClass={cs.LG},
552
+ url={https://arxiv.org/abs/2511.03929},
553
+ }
554
+ ```
bias.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ | Field | Response |
2
+ |:---|:---|
3
+ | Participation considerations from adversely impacted groups [protected classes](https://www.senate.ca.gov/content/protected-classes) in model design and testing: | None |
4
+ | Bias Metric (If Measured): | [BBQ Accuracy Scores in Ambiguous Contexts](https://github.com/nyu-mll/BBQ/) |
5
+ | Which characteristic (feature) show(s) the greatest difference in performance?: | The model shows high variance across many characteristics when used at a high temperature, with the greatest measurable difference seen in categories such as Gender Identity and Race x Gender. |
6
+ | Which feature(s) have the worst performance overall? | Age (ambiguous) has both the lowest category accuracy listed (0.75) and a notably negative bias score (–0.56), indicating it is the worst-performing feature overall in this evaluation. |
7
+ | Measures taken to mitigate against unwanted bias: | None |
8
+ | If using internal data, description of methods implemented in data acquisition or processing, if any, to address the prevalence of identifiable biases in the training, testing, and validation data: | The training datasets contain a large amount of synthetic data generated by LLMs. We manually curated prompts. |
9
+ | Tools used to assess statistical imbalances and highlight patterns that may introduce bias into AI models: | Bias Benchmark for Question Answering (BBQ) |
10
+ | Tools used to assess statistical imbalances and highlight patterns that may introduce bias into AI models: | The datasets, which include video datasets (e.g., YouCook2, VCG Human Dataset) and image captioning datasets, do not collectively or exhaustively represent all demographic groups (and proportionally therein).
11
+ For instance, these datasets do not contain explicit mentions of demographic classes such as age, gender, or ethnicity in over 80% of samples. In the subset where analysis was performed, certain datasets contain skews in the representation of participants—for example, perceived gender of "female" participants may be significant compared to "male" participants for certain datasets. Separately, individuals aged "40 to 49 years" and “20 to 29 years” are the most frequent among ethnic identifiers. Toxicity analysis was additionally performed on several datasets to identify potential not-safe-for-work samples and risks.
12
+ To mitigate these imbalances, we recommend considering evaluation techniques such as bias audits, fine-tuning with demographically balanced datasets, and mitigation strategies like counterfactual data augmentation to align with the desired model behavior. This evaluation was conducted on a data subset ranging from 200 to 3,000 samples per dataset; as such, certain limitations may exist in the reliability of the embeddings. A baseline of 200 samples was used across all datasets, with larger subsets of up to 3,000 samples utilized for certain in-depth analyses.
13
+ |
chat_template.jinja ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- set ns = namespace(enable_thinking=false, has_sys_prompt=false, non_tool_system_content='', has_video=false, explicit_think_requested=false) -%}
2
+ {%- set msg = namespace(content='') -%}
3
+ {%- for message in messages -%}
4
+ {%- if message['role'] == 'system' -%}
5
+ {%- set ns.has_sys_prompt = true -%}
6
+ {# Extract system content without tool flags #}
7
+ {%- if message['content'] is string -%}
8
+ {%- set ns.non_tool_system_content = message['content'].replace('</think>', '<_end_think>').replace('/think', '').replace('/no_think', '').replace('<_end_think>', '</think>').strip() -%}
9
+ {%- else -%}
10
+ {%- set ns.non_tool_system_content = '' -%}
11
+ {%- for content in message['content'] -%}
12
+ {%- if content['type'] == 'text' -%}
13
+ {%- set ns.non_tool_system_content = ns.non_tool_system_content + content['text'].replace('</think>', '<_end_think>').replace('/think', '').replace('/no_think', '').replace('<_end_think>', '</think>') -%}
14
+ {%- endif -%}
15
+ {%- endfor -%}
16
+ {%- set ns.non_tool_system_content = ns.non_tool_system_content.strip() -%}
17
+ {%- endif -%}
18
+ {%- endif -%}
19
+ {# Check for video content in all messages #}
20
+ {%- if message['content'] is not string -%}
21
+ {%- for content in message['content'] -%}
22
+ {%- if content['type'] == 'video' or content['type'] == 'video_url' -%}
23
+ {%- set ns.has_video = true -%}
24
+ {%- endif -%}
25
+ {%- endfor -%}
26
+ {%- endif -%}
27
+ {%- if message['content'] is string -%}
28
+ {%- if message['role'] == 'user' or message['role'] == 'system' -%}
29
+ {%- if '/think' in message['content'].replace('</think>', '') -%}
30
+ {%- set ns.enable_thinking = true -%}
31
+ {%- set ns.explicit_think_requested = true -%}
32
+ {%- elif '/no_think' in message['content'] -%}
33
+ {%- set ns.enable_thinking = false -%}
34
+ {%- endif -%}
35
+ {%- endif -%}
36
+ {%- else -%}
37
+ {%- for content in message['content'] -%}
38
+ {%- if content['type'] == 'text' -%}
39
+ {%- if message['role'] == 'user' or message['role'] == 'system' -%}
40
+ {%- if '/think' in content['text'].replace('</think>', '') -%}
41
+ {%- set ns.enable_thinking = true -%}
42
+ {%- set ns.explicit_think_requested = true -%}
43
+ {%- elif '/no_think' in content['text'] -%}
44
+ {%- set ns.enable_thinking = false -%}
45
+ {%- endif -%}
46
+ {%- endif -%}
47
+ {%- endif -%}
48
+ {%- endfor -%}
49
+ {%- endif -%}
50
+ {%- endfor -%}
51
+
52
+ {# Error out if video is present and reasoning is explicitly requested #}
53
+ {%- if ns.has_video and ns.explicit_think_requested -%}
54
+ {{ raise_exception('Video inputs are not supported with reasoning mode. Please remove /think flag or remove video content.') }}
55
+ {%- endif -%}
56
+
57
+ {# Automatically disable reasoning if video is present (without explicit /think request) #}
58
+ {%- if ns.has_video and not ns.explicit_think_requested -%}
59
+ {%- set ns.enable_thinking = false -%}
60
+ {%- endif -%}
61
+
62
+ {{- bos_token -}}
63
+ {%- if messages[0]['role'] != 'system' -%}
64
+ {{- '<SPECIAL_10>System\n' -}}
65
+ {%- else -%}
66
+ {{- '<SPECIAL_10>System\n' + ns.non_tool_system_content }}
67
+ {%- endif -%}
68
+
69
+ {%- if tools -%}
70
+ {%- if ns.non_tool_system_content != '' -%}
71
+ {{- '\n\n' -}}
72
+ {%- endif -%}
73
+ {{- 'You can use the following tools to assist the user if required:\n' -}}
74
+ {{- '<AVAILABLE_TOOLS>[' -}}
75
+ {%- for tool in tools -%}
76
+ {{- (tool.function if tool.function is defined else tool) | tojson -}}
77
+ {{- ', ' if not loop.last else '' -}}
78
+ {%- endfor -%}
79
+ {{- ']</AVAILABLE_TOOLS>\n\n' -}}
80
+
81
+ {{- 'If you decide to call any tool(s), use the following format:\n' -}}
82
+ {{- '<TOOLCALL>[{"name": "tool_name1", "arguments": "tool_args1"}, ' -}}
83
+ {{- '{"name": "tool_name2", "arguments": "tool_args2"}]</TOOLCALL>\n\n' -}}
84
+
85
+ {{- 'The user will execute tool-calls and return responses from tool(s) in this format:\n' -}}
86
+ {{- '<TOOL_RESPONSE>[{"response": "tool_response1"}, ' -}}
87
+ {{- '{"response": "tool_response2"}]</TOOL_RESPONSE>\n\n' -}}
88
+
89
+ {{- 'Based on the tool responses, you can call additional tools if needed, ' -}}
90
+ {{- 'correct tool calls if any errors are found, or just respond to the user.' -}}
91
+ {%- endif -%}
92
+ {{- '\n' -}}
93
+
94
+ {%- set messages = messages[1:] if messages[0]['role'] == 'system' else messages -%}
95
+
96
+ {# Prevent no user or assistant message #}
97
+ {%- if messages|length == 0 -%}
98
+ {%- set messages = [{'role': 'user', 'content': ''}] -%}
99
+ {%- endif -%}
100
+
101
+ {%- for message in messages %}
102
+ {%- if message['content'] is string -%}
103
+ {%- set msg.content = message['content'].replace('</think>', '<_end_think>').replace('/think', '').replace('/no_think', '').replace('<_end_think>', '</think>').strip() -%}
104
+ {%- else -%}
105
+ {%- set msg.content = '' -%}
106
+ {%- set mm_content = '' -%}
107
+ {%- set counters = namespace(images=0, videos=0) -%}
108
+
109
+ {%- for content in message['content'] -%}
110
+ {%- if content['type'] == 'image' -%}
111
+ {%- set counters.images = counters.images + 1 -%}
112
+ {%- elif content['type'] == 'video' -%}
113
+ {%- set counters.videos = counters.videos + 1 -%}
114
+ {%- elif content['type'] == 'text' -%}
115
+ {%- set msg.content = msg.content + content['text'] -%}
116
+ {%- endif -%}
117
+ {%- endfor -%}
118
+ {%- if '<image>' in msg.content -%}
119
+ {%- set counters.images = 0 -%}
120
+ {%- endif -%}
121
+ {%- if '<video>' in msg.content -%}
122
+ {%- set counters.videos = 0 -%}
123
+ {%- endif -%}
124
+ {%- if counters.images > 1 -%}
125
+ {%- set image_tags = namespace(tags=[]) -%}
126
+ {%- for i in range(counters.images) -%}
127
+ {%- set image_tags.tags = image_tags.tags + ['<image ' + (i + 1)|string + '><image>'] -%}
128
+ {%- endfor -%}
129
+ {%- set mm_content = ' '.join(image_tags.tags) + '\n' -%}
130
+ {%- elif counters.images == 1 -%}
131
+ {%- set mm_content = '<image>\n' -%}
132
+ {%- endif -%}
133
+ {%- set mm_content = mm_content + '<video>\n' * counters.videos -%}
134
+ {%- set msg.content = mm_content + msg.content.lstrip('\n') -%}
135
+ {%- endif -%}
136
+
137
+ {%- if message['role'] == 'user' %}
138
+ {{- '<SPECIAL_11>User\n' + msg.content.replace('</think>', '<_end_think>').replace('/think', '').replace('/no_think', '').replace('<_end_think>', '</think>').strip() + '\n' }}
139
+ {%- elif message['role'] == 'tool' %}
140
+ {%- if loop.first or (messages[loop.index0 - 1].role != 'tool') -%}
141
+ {{- '<SPECIAL_11>User\n' + '<TOOL_RESPONSE>[' }}
142
+ {%- endif -%}
143
+ {{- msg.content -}}
144
+ {{- ', ' if not loop.last and (messages[loop.index0 + 1].role == 'tool') else '' -}}
145
+ {%- if loop.last or (messages[loop.index0 + 1].role != 'tool') -%}
146
+ {{- ']</TOOL_RESPONSE>\n' -}}
147
+ {%- endif -%}
148
+ {%- elif message['role'] == 'assistant' %}
149
+ {%- if '</think>' in msg.content %}
150
+ {%- set msg.content = msg.content.split('</think>')[1].strip() %}
151
+ {%- endif %}
152
+ {{- '<SPECIAL_11>Assistant\n' + msg.content.strip() }}
153
+ {%- if message.tool_calls -%}
154
+ {%- if msg.content.strip() != '' -%}
155
+ {{- '\n\n' -}}
156
+ {%- endif -%}
157
+ {{- '<TOOLCALL>[' -}}
158
+ {%- for call in message.tool_calls -%}
159
+ {%- set fn = call.function if call.function is defined else call -%}
160
+ {{- '{"name": "' + fn.name + '", "arguments": ' -}}
161
+ {%- if fn.arguments is string -%}
162
+ {{- fn.arguments -}}
163
+ {%- else -%}
164
+ {{- fn.arguments | tojson -}}
165
+ {%- endif -%}
166
+ {{- '}' + (', ' if not loop.last else '') -}}
167
+ {%- endfor -%}
168
+ {{- ']</TOOLCALL>' -}}
169
+ {%- endif -%}
170
+ {{- '\n<SPECIAL_12>\n' -}}
171
+ {%- endif %}
172
+ {%- endfor -%}
173
+ {%- if add_generation_prompt %}
174
+ {{- '<SPECIAL_11>Assistant\n' }}
175
+ {%- if ns.enable_thinking is defined and ns.enable_thinking is false %}
176
+ {{- '<think></think>' }}
177
+ {%- else %}
178
+ {{- '<think>\n' }}
179
+ {%- endif %}
180
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "NemotronH_Nano_VL_V2"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration.NemotronH_Nano_VL_V2_Config",
7
+ "AutoModel": "modeling.NemotronH_Nano_VL_V2",
8
+ "AutoModelForCausalLM": "modeling.NemotronH_Nano_VL_V2"
9
+ },
10
+ "max_sequence_length": 131072,
11
+ "downsample_ratio": 0.5,
12
+ "force_image_size": 512,
13
+ "patch_size": 16,
14
+ "use_thumbnail": true,
15
+ "eos_token_id": 12,
16
+ "model_type": "NemotronH_Nano_VL_V2",
17
+ "ps_version": "v2",
18
+ "template": "n5h_5p5_nanov2",
19
+ "torch_dtype": "bfloat16",
20
+ "image_tag_type": "internvl",
21
+ "img_context_token_id": 131072,
22
+ "video_context_token_id": 131081,
23
+ "img_context_token": "<image>",
24
+ "video_context_token": "<video>",
25
+ "img_start_token": "<img>",
26
+ "img_end_token": "</img>",
27
+
28
+ "vit_hidden_size": 1280,
29
+ "projector_hidden_size": 20480,
30
+ "norm_mean":[0.48145466, 0.4578275, 0.40821073],
31
+ "norm_std": [0.26862954, 0.26130258, 0.27577711],
32
+
33
+ "video_pruning_rate": 0.7,
34
+
35
+ "llm_config": {
36
+ "architectures": [
37
+ "NemotronHForCausalLM"
38
+ ],
39
+ "attention_bias": false,
40
+ "attention_dropout": 0.0,
41
+ "attention_head_dim": 128,
42
+ "auto_map": {
43
+ "AutoConfig": "nvidia/NVIDIA-Nemotron-Nano-12B-v2-Base--configuration_nemotron_h.NemotronHConfig",
44
+ "AutoModelForCausalLM": "nvidia/NVIDIA-Nemotron-Nano-12B-v2-Base--modeling_nemotron_h.NemotronHForCausalLM"
45
+ },
46
+ "bos_token_id": 1,
47
+ "chunk_size": 128,
48
+ "conv_kernel": 4,
49
+ "eos_token_id": 12,
50
+ "expand": 2,
51
+ "hidden_dropout": 0.0,
52
+ "hidden_size": 5120,
53
+ "hybrid_override_pattern": "M-M-M-M*-M-M-M-M*-M-M-M-M*-M-M-M-M*-M-M-M-M*-M-M-M-M*-M-M-M-M-",
54
+ "initializer_range": 0.02,
55
+ "intermediate_size": 20480,
56
+ "layer_norm_epsilon": 1e-05,
57
+ "mamba_head_dim": 80,
58
+ "mamba_hidden_act": "silu",
59
+ "mamba_num_heads": 128,
60
+ "mamba_proj_bias": false,
61
+ "max_position_embeddings": 131072,
62
+ "mlp_bias": false,
63
+ "mlp_hidden_act": "relu2",
64
+ "model_type": "nemotron_h",
65
+ "n_groups": 8,
66
+ "num_attention_heads": 40,
67
+ "num_hidden_layers": 62,
68
+ "num_key_value_heads": 8,
69
+ "num_logits_to_keep": 1,
70
+ "pad_token_id": 0,
71
+ "rescale_prenorm_residual": true,
72
+ "residual_in_fp32": false,
73
+ "rms_norm_eps": 1e-05,
74
+ "sliding_window": null,
75
+ "ssm_state_size": 128,
76
+ "tie_word_embeddings": false,
77
+ "time_step_floor": 0.0001,
78
+ "time_step_limit": [
79
+ 0.0,
80
+ Infinity
81
+ ],
82
+ "time_step_max": 0.1,
83
+ "time_step_min": 0.001,
84
+ "time_step_rank": 256,
85
+ "torch_dtype": "bfloat16",
86
+ "transformers_version": "4.51.3",
87
+ "use_bias": false,
88
+ "use_cache": true,
89
+ "use_conv_bias": true,
90
+ "use_mamba_kernels": true,
91
+ "vocab_size": 132096
92
+ },
93
+
94
+ "vision_config": {
95
+ "auto_map": {
96
+ "AutoConfig": "nvidia/C-RADIOv2-H--hf_model.RADIOConfig",
97
+ "AutoModel": "nvidia/C-RADIOv2-H--hf_model.RADIOModel"
98
+ },
99
+ "adaptor_configs": {},
100
+ "adaptor_names": null,
101
+ "architectures": [
102
+ "RADIOModel"
103
+ ],
104
+ "args": {
105
+ "aa": null,
106
+ "amp": true,
107
+ "amp_dtype": "bfloat16",
108
+ "amp_impl": "native",
109
+ "aug_repeats": 0,
110
+ "aug_splits": 0,
111
+ "bn_eps": null,
112
+ "bn_momentum": null,
113
+ "cache_dir": null,
114
+ "channels_last": false,
115
+ "checkpoint_hist": 10,
116
+ "chk_keep_forever": 100,
117
+ "class_map": "",
118
+ "clip_grad": null,
119
+ "clip_mode": "norm",
120
+ "cls_token_per_teacher": true,
121
+ "coco_annotations_file": "/datasets/coco2017-adlsa/annotations/captions_val2017.json",
122
+ "coco_image_dir": "/datasets/coco2017-adlsa/val2017",
123
+ "color_jitter": 0.4,
124
+ "cooldown_epochs": 0,
125
+ "cpe_max_size": 2048,
126
+ "crd_loss": false,
127
+ "crd_loss_weight": 0.8,
128
+ "crop_pct": null,
129
+ "cutmix": 0.0,
130
+ "cutmix_minmax": null,
131
+ "dataset_download": false,
132
+ "debug_full_knn": false,
133
+ "decay_epochs": 90,
134
+ "decay_milestones": [
135
+ 90,
136
+ 180,
137
+ 270
138
+ ],
139
+ "decay_rate": 0.1,
140
+ "depchain": true,
141
+ "dist_bn": "reduce",
142
+ "dist_norm_weight": 0.0,
143
+ "distributed": true,
144
+ "drop": 0.0,
145
+ "drop_block": null,
146
+ "drop_connect": null,
147
+ "drop_path": null,
148
+ "dtype": "bfloat16",
149
+ "epoch_repeats": 0.0,
150
+ "eval": false,
151
+ "eval_metric": "knn_top1",
152
+ "eval_teacher": false,
153
+ "eval_teacher_only": false,
154
+ "eval_throughput": false,
155
+ "fast_norm": false,
156
+ "fd_loss_fn": "MSE",
157
+ "feature_normalization": "SHIP_NORM",
158
+ "feature_summarizer": "cls_token",
159
+ "feature_upscale_factor": null,
160
+ "force_new_wandb_id": false,
161
+ "force_spectral_reparam": true,
162
+ "freeze_bn": false,
163
+ "fsdp": false,
164
+ "fuser": "",
165
+ "gp": null,
166
+ "grad_accum_steps": 1,
167
+ "grad_checkpointing": false,
168
+ "head_init_bias": null,
169
+ "head_init_scale": null,
170
+ "head_warmup": 5,
171
+ "head_weight_decay": 0.001,
172
+ "hflip": 0.5,
173
+ "img_size": null,
174
+ "in_chans": null,
175
+ "initial_checkpoint": null,
176
+ "input_size": null,
177
+ "interpolation": "",
178
+ "layer_decay": null,
179
+ "local_rank": 0,
180
+ "log_interval": 50,
181
+ "log_mlflow": false,
182
+ "log_wandb": true,
183
+ "loss_auto_balance": false,
184
+ "lr_base": 0.1,
185
+ "lr_base_scale": "",
186
+ "lr_base_size": 256,
187
+ "lr_cycle_decay": 0.5,
188
+ "lr_cycle_limit": 1,
189
+ "lr_cycle_mul": 1.0,
190
+ "lr_k_decay": 1.0,
191
+ "lr_noise": null,
192
+ "lr_noise_pct": 0.67,
193
+ "lr_noise_std": 1.0,
194
+ "mean": null,
195
+ "mesa": false,
196
+ "min_lr": 0,
197
+ "mixup": 0.0,
198
+ "mixup_mode": "batch",
199
+ "mixup_off_epoch": 0,
200
+ "mixup_prob": 1.0,
201
+ "mixup_switch_prob": 0.5,
202
+ "mlp_hidden_size": 1520,
203
+ "mlp_num_inner": 3,
204
+ "mlp_version": "v2",
205
+ "model": "vit_huge_patch16_224",
206
+ "model_kwargs": {},
207
+ "model_norm": false,
208
+ "momentum": 0.9,
209
+ "no_aug": false,
210
+ "no_ddp_bb": true,
211
+ "no_prefetcher": false,
212
+ "no_resume_opt": false,
213
+ "num_classes": null,
214
+ "opt_betas": null,
215
+ "opt_eps": null,
216
+ "patience_epochs": 10,
217
+ "pin_mem": false,
218
+ "prefetcher": true,
219
+ "pretrained": false,
220
+ "rank": 0,
221
+ "ratio": [
222
+ 0.75,
223
+ 1.3333333333333333
224
+ ],
225
+ "recount": 1,
226
+ "recovery_interval": 0,
227
+ "register_multiple": 16,
228
+ "remode": "pixel",
229
+ "reprob": 0.0,
230
+ "reset_loss_state": false,
231
+ "resplit": false,
232
+ "save_images": false,
233
+ "scale": [
234
+ 0.5,
235
+ 1.0
236
+ ],
237
+ "sched": "cosine",
238
+ "seed": 42,
239
+ "smoothing": 0.1,
240
+ "spectral_heads": false,
241
+ "spectral_reparam": false,
242
+ "split_bn": false,
243
+ "start_epoch": null,
244
+ "std": null,
245
+ "stream_teachers": true,
246
+ "sync_bn": false,
247
+ "synchronize_step": false,
248
+ "teachers": [
249
+ {
250
+ "fd_normalize": false,
251
+ "feature_distillation": true,
252
+ "input_size": 378,
253
+ "model": "ViT-H-14-378-quickgelu",
254
+ "name": "clip",
255
+ "pretrained": "dfn5b",
256
+ "type": "open_clip",
257
+ "use_summary": true
258
+ },
259
+ {
260
+ "fd_normalize": false,
261
+ "feature_distillation": true,
262
+ "input_size": 378,
263
+ "model": "ViT-SO400M-14-SigLIP-384",
264
+ "name": "siglip",
265
+ "pretrained": "webli",
266
+ "type": "open_clip",
267
+ "use_summary": true
268
+ },
269
+ {
270
+ "fd_normalize": false,
271
+ "feature_distillation": true,
272
+ "input_size": 378,
273
+ "model": "dinov2_vitg14_reg",
274
+ "name": "dino_v2",
275
+ "type": "dino_v2",
276
+ "use_summary": true
277
+ },
278
+ {
279
+ "fd_normalize": false,
280
+ "feature_distillation": true,
281
+ "input_size": 1024,
282
+ "model": "vit-h",
283
+ "name": "sam",
284
+ "type": "sam",
285
+ "use_summary": false
286
+ }
287
+ ],
288
+ "torchcompile": null,
289
+ "torchscript": false,
290
+ "train_interpolation": "random",
291
+ "train_split": "train",
292
+ "tta": 0,
293
+ "use_coco": false,
294
+ "use_multi_epochs_loader": false,
295
+ "val_ema_only": false,
296
+ "val_split": "val",
297
+ "vflip": 0.0,
298
+ "vitdet_version": 1,
299
+ "wandb_entity": "",
300
+ "wandb_job_type": "",
301
+ "wandb_name": "",
302
+ "wandb_project": "",
303
+ "warmup_lr": 1e-05,
304
+ "warmup_prefix": false,
305
+ "worker_seeding": "all",
306
+ "workers": 8,
307
+ "world_size": 256
308
+ },
309
+ "feature_normalizer_config": null,
310
+ "inter_feature_normalizer_config": null,
311
+ "max_resolution": 2048,
312
+ "patch_size": 16,
313
+ "preferred_resolution": [
314
+ 768,
315
+ 768
316
+ ],
317
+ "torch_dtype": "bfloat16",
318
+ "version": "radio_v2.5-h",
319
+ "vitdet_window_size": null
320
+ }
321
+ }
configuration.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from transformers.configuration_utils import PretrainedConfig
15
+ from transformers.utils import logging
16
+ from .configuration_nemotron_h import NemotronHConfig
17
+ from .configuration_radio import RADIOConfig
18
+
19
+ logger = logging.get_logger(__name__)
20
+
21
+ class NemotronH_Nano_VL_V2_Config(PretrainedConfig):
22
+ model_type = 'NemotronH_Nano_VL_V2'
23
+ is_composition = True
24
+
25
+ def __init__(
26
+ self,
27
+ vision_config=None,
28
+ llm_config=None,
29
+ force_image_size=None,
30
+ downsample_ratio=0.5,
31
+ template=None,
32
+ ps_version='v1',
33
+ image_tag_type="internvl",
34
+ projector_hidden_size=4096,
35
+ vit_hidden_size=1280,
36
+ attn_implementation="flash_attention_2",
37
+ video_pruning_rate: float = 0.0,
38
+ **kwargs
39
+ ):
40
+ super().__init__(**kwargs)
41
+
42
+ if vision_config is not None:
43
+ self.vision_config = RADIOConfig(**vision_config)
44
+ else:
45
+ self.vision_config = RADIOConfig()
46
+
47
+ # Handle both cases: when loading from JSON (llm_config is dict) and when called internally by transformers (llm_config is None)
48
+ if llm_config is not None:
49
+ self.llm_config = NemotronHConfig(**llm_config)
50
+ else:
51
+ self.llm_config = NemotronHConfig()
52
+
53
+ # Assign configuration values
54
+ self.force_image_size = force_image_size
55
+ self.downsample_ratio = downsample_ratio
56
+ self.template = template # TODO move out of here and into the tokenizer
57
+ self.ps_version = ps_version # Pixel shuffle version
58
+ self.image_tag_type = image_tag_type # TODO: into the tokenizer too?
59
+ self.projector_hidden_size = projector_hidden_size
60
+ self.vit_hidden_size = vit_hidden_size
61
+ self.video_pruning_rate = video_pruning_rate
62
+
63
+ self._attn_implementation = attn_implementation
64
+ self.vision_config.use_flash_attn = self._attn_implementation is not None and "flash_attention" in self._attn_implementation
65
+ self.llm_config._attn_implementation = self._attn_implementation
configuration_nemotron_h.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """NemotronH model configuration"""
15
+
16
+ import re
17
+
18
+ from transformers.configuration_utils import PretrainedConfig
19
+ from transformers.utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class NemotronHConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`NemotronHModel`]. It is used to instantiate a
28
+ NemotronH model according to the specified arguments, defining the model architecture. Instantiating a configuration
29
+ with the defaults will yield a similar configuration to that of the NemotronH-v0.1 model.
30
+
31
+ [todo](todo)
32
+
33
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
34
+ documentation from [`PretrainedConfig`] for more information.
35
+
36
+
37
+ Args:
38
+ vocab_size (`int`, *optional*, defaults to 131072):
39
+ Vocabulary size of the NemotronH model. Defines the number of different tokens that can be represented by the
40
+ `inputs_ids` passed when calling [`NemotronHModel`]
41
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
42
+ Whether the model's input and output word embeddings should be tied. Note that this is only relevant if the
43
+ model has a output word embedding layer.
44
+ hidden_size (`int`, *optional*, defaults to 4096):
45
+ Dimension of the hidden representations.
46
+ intermediate_size (`int`, *optional*, defaults to 21504):
47
+ Dimension of the MLP representations.
48
+ num_hidden_layers (`int`, *optional*, defaults to 52):
49
+ Number of hidden layers in the Transformer encoder.
50
+ hybrid_override_pattern (`str`, *optional*, defaults to `"M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M-"`):
51
+ The pattern of the hybrid model. The pattern is a string of characters where each character represents M: Mamba2, *: Attention, -: MLP
52
+ num_attention_heads (`int`, *optional*, defaults to 32):
53
+ Number of attention heads for each attention layer in the Transformer encoder.
54
+ attention_head_dim (`int`, *optional*, defaults to 128):
55
+ Dimension of each attention head.
56
+ num_key_value_heads (`int`, *optional*, defaults to 8):
57
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
58
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
59
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used.
60
+ mlp_hidden_act (`str`, *optional*, defaults to "relu2"):
61
+ The non-linear activation function in the MLP layers.
62
+ attention_bias (`bool`, *optional*, defaults to `False`):
63
+ Whether to use bias in attention layers.
64
+ mlp_bias (`bool`, *optional*, defaults to `False`):
65
+ Whether to use bias in MLP layers.
66
+ use_bias (`bool`, *optional*, defaults to `False`):
67
+ Whether to use bias in the model.
68
+ initializer_range (`float`, *optional*, defaults to 0.02):
69
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
70
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-5):
71
+ The epsilon used by the layer normalization layers.
72
+ residual_in_fp32 (`bool`, *optional*, defaults to `False`):
73
+ Whether or not residuals should be in `float32`. If set to `False` residuals will keep the same `dtype` as the rest of the model.
74
+ use_cache (`bool`, *optional*, defaults to `True`):
75
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
76
+ relevant if `config.is_decoder=True`.
77
+ num_logits_to_keep (`int` or `None`, *optional*, defaults to 1):
78
+ Number of prompt logits to calculate during generation. If `None`, all logits will be calculated. If an
79
+ integer value, only last `num_logits_to_keep` logits will be calculated.
80
+ pad_token_id (`int`, *optional*, defaults to 0):
81
+ The id of the padding token.
82
+ bos_token_id (`int`, *optional*, defaults to 1):
83
+ The id of the "beginning-of-sequence" token.
84
+ eos_token_id (`int`, *optional*, defaults to 2):
85
+ The id of the "end-of-sequence" token.
86
+ sliding_window (`int`, *optional*, defaults to None):
87
+ Sliding window attention window size.
88
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
89
+ The maximum sequence length that this model might ever be used with.
90
+ attention_dropout (`float`, *optional*, defaults to 0.0):
91
+ The dropout ratio for the attention probabilities.
92
+ hidden_dropout (`float`, *optional*, defaults to 0.0):
93
+ The dropout ratio for the hidden states.
94
+ use_mamba_kernels (`bool`, *optional*, defaults to `True`):
95
+ Flag indicating whether or not to use the fast mamba kernels. These are available only if `mamba-ssm` and
96
+ `causal-conv1d` are installed, and the mamba modules are running on a CUDA device.
97
+ ssm_state_size (`int`, *optional*, defaults to 128):
98
+ The dimension of the mamba state space latents.
99
+ mamba_num_heads (`int`, *optional*, defaults to 128):
100
+ Number of heads in Mamba layers.
101
+ mamba_n_groups (`int`, *optional*, defaults to 8):
102
+ Number of groups in Mamba layers.
103
+ mamba_head_dim (`int`, *optional*, defaults to 64):
104
+ Dimension of each Mamba head.
105
+ mamba_d_conv (`int`, *optional*, defaults to 4):
106
+ The size of the mamba convolution kernel.
107
+ mamba_expand (`int`, *optional*, defaults to 2):
108
+ Expanding factor used to determine the mamba intermediate size.
109
+ mamba_hidden_act (`str`, *optional*, defaults to "silu"):
110
+ The non-linear activation function in the Mamba layers.
111
+ mamba_dt_min (`float`, *optional*, defaults to 0.001):
112
+ Minimum value for the time step in Mamba.
113
+ mamba_dt_max (`float`, *optional*, defaults to 0.1):
114
+ Maximum value for the time step in Mamba.
115
+ mamba_dt_limit (`tuple`, *optional*, defaults to (0.0, float("inf"))):
116
+ Limits for the time step in Mamba.
117
+ mamba_dt_init_floor (`float`, *optional*, defaults to 1e-4):
118
+ Floor value for time step initialization in Mamba.
119
+ mamba_conv_bias (`bool`, *optional*, defaults to `True`):
120
+ Whether to use bias in the convolution layer of the mamba mixer block.
121
+ mamba_proj_bias (`bool`, *optional*, defaults to `False`):
122
+ Whether to use bias in the input and output projections of the mamba mixer block.
123
+ mamba_chunk_size (`int`, *optional*, defaults to 256):
124
+ Size of chunks for Mamba processing.
125
+ rescale_prenorm_residual (`bool`, *optional*, defaults to `True`):
126
+ Whether to rescale the pre-normalization residual connections.
127
+ """
128
+
129
+ model_type = "nemotron_h"
130
+ keys_to_ignore_at_inference = ["past_key_values"]
131
+
132
+ def __init__(
133
+ self,
134
+ vocab_size=131072,
135
+ tie_word_embeddings=False,
136
+ hidden_size=4096,
137
+ intermediate_size=21504,
138
+ num_hidden_layers=52,
139
+ hybrid_override_pattern="M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M-",
140
+ num_attention_heads=32,
141
+ #attention_head_dim=128,
142
+ head_dim=128,
143
+ num_key_value_heads=8, # nemo: num_query_groups
144
+ mlp_hidden_act="relu2",
145
+ attention_bias=False,
146
+ mlp_bias=False,
147
+ use_bias=False,
148
+ initializer_range=0.02, # nemo: init_method_std
149
+ layer_norm_epsilon=1e-5, # nemo: layernorm_epsilon
150
+ residual_in_fp32=False, # Megatron Core default value
151
+ use_cache=True,
152
+ num_logits_to_keep=1,
153
+ pad_token_id=0,
154
+ bos_token_id=1,
155
+ eos_token_id=2,
156
+ sliding_window=None,
157
+ max_position_embeddings=4096,
158
+ attention_dropout=0.0,
159
+ hidden_dropout=0.0, # * ADDED
160
+ use_mamba_kernels=True,
161
+ ssm_state_size=128, # mamba_state_size
162
+ mamba_num_heads=128,
163
+ mamba_n_groups=8, # nemo: mamba_ssm_ngroups = num_heads
164
+ mamba_head_dim=64,
165
+ mamba_d_conv=4,
166
+ mamba_expand=2,
167
+ mamba_hidden_act="silu",
168
+ mamba_dt_min=0.001,
169
+ mamba_dt_max=0.1,
170
+ mamba_dt_limit=(0.0, float("inf")),
171
+ mamba_dt_init_floor=1e-4,
172
+ mamba_conv_bias=True,
173
+ mamba_proj_bias=False,
174
+ mamba_chunk_size=256,
175
+ rescale_prenorm_residual=True,
176
+ **kwargs,
177
+ ):
178
+ self.vocab_size = vocab_size
179
+ self.tie_word_embeddings = tie_word_embeddings
180
+ self.hidden_size = hidden_size
181
+ self.intermediate_size = intermediate_size
182
+ self.num_hidden_layers = num_hidden_layers
183
+ self.hybrid_override_pattern = hybrid_override_pattern
184
+ self.num_attention_heads = num_attention_heads
185
+ #self.attention_head_dim = attention_head_dim
186
+ self.head_dim = head_dim
187
+ self.sliding_window = sliding_window
188
+ self.max_position_embeddings = max_position_embeddings
189
+ self.attention_dropout = attention_dropout
190
+ self.hidden_dropout = hidden_dropout
191
+
192
+ # Validate hybrid_override_pattern
193
+ # M: Mamba2, *: Attention, -: MLP
194
+ assert len(self.hybrid_override_pattern) == self.num_hidden_layers, "hybrid_override_pattern must have the same length as num_hidden_layers"
195
+ assert re.match(r"^[*-M]+$", self.hybrid_override_pattern), "hybrid_override_pattern must only contain characters 'M', '*', or '-'"
196
+
197
+ # for backward compatibility
198
+ if num_key_value_heads is None:
199
+ num_key_value_heads = num_attention_heads
200
+
201
+ self.num_key_value_heads = num_key_value_heads
202
+ self.mlp_hidden_act = mlp_hidden_act
203
+ self.attention_bias = attention_bias
204
+ self.mlp_bias = mlp_bias
205
+ self.use_bias = use_bias
206
+ self.initializer_range = initializer_range
207
+ self.layer_norm_epsilon = layer_norm_epsilon
208
+ self.residual_in_fp32 = residual_in_fp32
209
+
210
+ self.use_cache = use_cache
211
+ self.num_logits_to_keep = num_logits_to_keep
212
+
213
+ self.use_mamba_kernels = use_mamba_kernels
214
+ self.n_groups = mamba_n_groups
215
+ self.mamba_head_dim = mamba_head_dim
216
+ self.ssm_state_size = ssm_state_size
217
+ self.mamba_num_heads = mamba_num_heads
218
+ self.conv_kernel = mamba_d_conv
219
+ self.expand = mamba_expand
220
+ self.mamba_hidden_act = mamba_hidden_act
221
+ self.time_step_min = mamba_dt_min
222
+ self.time_step_max = mamba_dt_max
223
+ self.time_step_limit = mamba_dt_limit
224
+ self.time_step_floor = mamba_dt_init_floor
225
+ self.use_conv_bias = mamba_conv_bias
226
+ self.mamba_proj_bias = mamba_proj_bias
227
+ self.chunk_size = mamba_chunk_size
228
+ self.rescale_prenorm_residual = rescale_prenorm_residual
229
+
230
+ super().__init__(
231
+ pad_token_id=pad_token_id,
232
+ bos_token_id=bos_token_id,
233
+ eos_token_id=eos_token_id,
234
+ tie_word_embeddings=tie_word_embeddings,
235
+ **kwargs,
236
+ )
237
+
238
+ @property
239
+ def layers_block_type(self):
240
+ return [
241
+ "mamba" if self.hybrid_override_pattern[i] == "M" else
242
+ "attention" if self.hybrid_override_pattern[i] == "*" else "mlp"
243
+ for i in range(self.num_hidden_layers)]
configuration_radio.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # NVIDIA CORPORATION and its licensors retain all intellectual property
4
+ # and proprietary rights in and to this software, related documentation
5
+ # and any modifications thereto. Any use, reproduction, disclosure or
6
+ # distribution of this software and related documentation without an express
7
+ # license agreement from NVIDIA CORPORATION is strictly prohibited.
8
+
9
+ from dataclasses import dataclass
10
+ from typing import Optional, NamedTuple, Union, List, Dict
11
+
12
+ from transformers import PretrainedConfig
13
+
14
+
15
+ class Resolution(NamedTuple):
16
+ height: int
17
+ width: int
18
+
19
+
20
+ @dataclass
21
+ class RadioResource:
22
+ url: str
23
+ patch_size: int
24
+ max_resolution: int
25
+ preferred_resolution: Resolution
26
+ vitdet_num_windowed: Optional[int] = None
27
+ vitdet_num_global: Optional[int] = None
28
+
29
+
30
+ RESOURCE_MAP = {
31
+ # RADIOv2.5
32
+ "radio_v2.5-b": RadioResource(
33
+ "https://huggingface.co/nvidia/RADIO/resolve/main/radio-v2.5-b_half.pth.tar?download=true",
34
+ patch_size=16,
35
+ max_resolution=2048,
36
+ preferred_resolution=(768, 768),
37
+ vitdet_num_global=4,
38
+ ),
39
+ "radio_v2.5-l": RadioResource(
40
+ "https://huggingface.co/nvidia/RADIO/resolve/main/radio-v2.5-l_half.pth.tar?download=true",
41
+ patch_size=16,
42
+ max_resolution=2048,
43
+ preferred_resolution=(768, 768),
44
+ vitdet_num_global=4,
45
+ ),
46
+ "radio_v2.5-h": RadioResource(
47
+ "https://huggingface.co/nvidia/RADIO/resolve/main/radio_v2.5-h.pth.tar?download=true",
48
+ patch_size=16,
49
+ max_resolution=2048,
50
+ preferred_resolution=(768, 768),
51
+ vitdet_num_global=4,
52
+ ),
53
+ "radio_v2.5-h-norm": RadioResource(
54
+ "https://huggingface.co/nvidia/RADIO/resolve/main/radio_v2.5-h-norm.pth.tar?download=true",
55
+ patch_size=16,
56
+ max_resolution=2048,
57
+ preferred_resolution=(768, 768),
58
+ vitdet_num_global=4,
59
+ ),
60
+ "radio_v2.5-g": RadioResource(
61
+ "https://huggingface.co/nvidia/RADIO/resolve/main/radio_v2.5-g.pth.tar?download=true",
62
+ patch_size=14,
63
+ max_resolution=1792,
64
+ preferred_resolution=(896, 896),
65
+ vitdet_num_global=8,
66
+ ),
67
+ # RADIO
68
+ "radio_v2.1": RadioResource(
69
+ "https://huggingface.co/nvidia/RADIO/resolve/main/radio_v2.1_bf16.pth.tar?download=true",
70
+ patch_size=16,
71
+ max_resolution=2048,
72
+ preferred_resolution=Resolution(432, 432),
73
+ vitdet_num_windowed=5,
74
+ ),
75
+ "radio_v2": RadioResource(
76
+ "https://huggingface.co/nvidia/RADIO/resolve/main/radio_v2.pth.tar?download=true",
77
+ patch_size=16,
78
+ max_resolution=2048,
79
+ preferred_resolution=Resolution(432, 432),
80
+ vitdet_num_windowed=5,
81
+ ),
82
+ "radio_v1": RadioResource(
83
+ "https://huggingface.co/nvidia/RADIO/resolve/main/radio_v1.pth.tar?download=true",
84
+ patch_size=14,
85
+ max_resolution=1050,
86
+ preferred_resolution=Resolution(378, 378),
87
+ ),
88
+ # E-RADIO
89
+ "e-radio_v2": RadioResource(
90
+ "https://huggingface.co/nvidia/RADIO/resolve/main/eradio_v2.pth.tar?download=true",
91
+ patch_size=16,
92
+ max_resolution=2048,
93
+ preferred_resolution=Resolution(512, 512),
94
+ ),
95
+ # C-RADIO
96
+ "c-radio_v2.5-g": RadioResource(
97
+ "https://huggingface.co/nvidia/C-RADIOv2-g/resolve/main/c-radio_v2-g_half.pth.tar",
98
+ patch_size=16,
99
+ max_resolution=2048,
100
+ preferred_resolution=(768, 768),
101
+ vitdet_num_global=8,
102
+ ),
103
+ "c-radio_v3-l": RadioResource(
104
+ # NOTE: Currently, this model cannot be loaded via TorchHub. Instead, use the transformers API at https://huggingface.co/nvidia/C-RADIOv3-L
105
+ # and accept the license terms.
106
+ "https://huggingface.co/nvidia/C-RADIOv3-L/resolve/main/c-radio-v3_l_half.pth.tar?download=true",
107
+ patch_size=16,
108
+ max_resolution=2048,
109
+ preferred_resolution=Resolution(512, 512),
110
+ ),
111
+ }
112
+
113
+ DEFAULT_VERSION = "radio_v2.5-h"
114
+
115
+
116
+ class RADIOConfig(PretrainedConfig):
117
+ """Pretrained Hugging Face configuration for RADIO models."""
118
+
119
+ def __init__(
120
+ self,
121
+ args: Optional[dict] = None,
122
+ version: Optional[str] = DEFAULT_VERSION,
123
+ patch_size: Optional[int] = None,
124
+ max_resolution: Optional[int] = None,
125
+ preferred_resolution: Optional[Resolution] = None,
126
+ adaptor_names: Union[str, List[str]] = None,
127
+ adaptor_configs: Dict[str, Dict[str, int]] = None,
128
+ vitdet_window_size: Optional[int] = None,
129
+ feature_normalizer_config: Optional[dict] = None,
130
+ inter_feature_normalizer_config: Optional[dict] = None,
131
+ **kwargs,
132
+ ):
133
+ self.args = args
134
+ for field in ["dtype", "amp_dtype"]:
135
+ if self.args is not None and field in self.args:
136
+ # Convert to a string in order to make it serializable.
137
+ # For example for torch.float32 we will store "float32",
138
+ # for "bfloat16" we will store "bfloat16".
139
+ self.args[field] = str(args[field]).split(".")[-1]
140
+ self.version = version
141
+ resource = RESOURCE_MAP[version]
142
+ self.patch_size = patch_size or resource.patch_size
143
+ self.max_resolution = max_resolution or resource.max_resolution
144
+ self.preferred_resolution = (
145
+ preferred_resolution or resource.preferred_resolution
146
+ )
147
+ self.adaptor_names = adaptor_names
148
+ self.adaptor_configs = adaptor_configs
149
+ self.vitdet_window_size = vitdet_window_size
150
+ self.feature_normalizer_config = feature_normalizer_config
151
+ self.inter_feature_normalizer_config = inter_feature_normalizer_config
152
+ super().__init__(**kwargs)
evs.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import torch
15
+ from typing import Tuple
16
+
17
+ class EfficientVideoSampling:
18
+ @staticmethod
19
+ def compute_retention_mask(
20
+ *,
21
+ video_embeds: torch.FloatTensor,
22
+ thw: torch.LongTensor,
23
+ spatial_merge_size: int,
24
+ q: float,
25
+ ):
26
+ """
27
+ Computes the retention mask for video embeddings based on the grid dimensions.
28
+
29
+ Args:
30
+ video_embeds (`torch.FloatTensor` of shape `(T * H * W, hidden_size)`):
31
+ The video embeddings to compute the retention mask for.
32
+ thw (`torch.LongTensor` of shape `(3)`):
33
+ The temporal, height and width of feature shape of each video in LLM.
34
+ spatial_merge_size (`int`): The spatial merge size of the video embeddings.
35
+ If embeddings will be downsampled *later*, this should be the downsampling factor.
36
+ q: (`float`): Pruning rate factor, indicating number of tokens to prune (remove)
37
+
38
+ Returns:
39
+ `torch.Tensor`: The retention mask for the video embeddings (T * H * W).
40
+ 1 for tokens to keep, 0 for tokens to prune.
41
+ """
42
+ T, H, W = thw
43
+
44
+ # video_embeds = einops.rearrange(
45
+ # video_embeds,
46
+ # "(T H W) C -> T H W C",
47
+ # T=T,
48
+ # H=H // spatial_merge_size,
49
+ # W=W // spatial_merge_size,
50
+ # )
51
+ # Use reshape instead of einops to avoid graph breaks
52
+ video_embeds = video_embeds.reshape(
53
+ T, H // spatial_merge_size, W // spatial_merge_size, video_embeds.size(-1)
54
+ )
55
+
56
+ # Core EVS
57
+ similarity = torch.nn.functional.cosine_similarity(
58
+ video_embeds[1:, ...], video_embeds[:-1, ...], dim=-1
59
+ )
60
+ dissimilarity = 1 - similarity
61
+
62
+ # Always ensure we include all tokens from the first frame
63
+ dissimilarity = torch.cat(
64
+ [255 * torch.ones_like(video_embeds[:1, :, :, 0]), dissimilarity], dim=0
65
+ )
66
+ dissimilarity_flat = dissimilarity.view(-1)
67
+
68
+ min_num_tokens = (H // spatial_merge_size) * (W // spatial_merge_size) # a single frame
69
+ evs_num_tokens = int(T * min_num_tokens * (1 - q))
70
+ num_tokens_to_keep = max(min_num_tokens, evs_num_tokens)
71
+
72
+ order = torch.argsort(dissimilarity_flat,
73
+ dim=-1,
74
+ descending=True,
75
+ stable=True)
76
+ topk_indices = order[:num_tokens_to_keep]
77
+
78
+ retention_mask = torch.zeros_like(dissimilarity_flat, dtype=torch.bool)
79
+ retention_mask[topk_indices] = True
80
+ retention_mask = retention_mask.reshape(dissimilarity.size())
81
+
82
+ # print(
83
+ # f"Computed retention mask of shape {retention_mask.shape=} with sparsity {retention_mask.float().mean().item():.4f} for {q=}",
84
+ # )
85
+ mask = retention_mask.view(-1) # "T H W -> (T H W)"
86
+ return mask
explainability.md ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Field | Response
2
+ :------------------------------------------------------------------------------------------------------|:---------------------------------------------------------------------------------
3
+ Intended Task/Domain: | Visual Question Answering
4
+ Model Type: | Transformer
5
+ Intended Users: | Individuals and businesses that need to process documents such as invoices, receipts, and manuals. Also, users who are building multi-modal agents and RAG systems.
6
+ Output: | Text
7
+ Tools used to evaluate datasets to identify synthetic data and ensure data authenticity. | We used a Gemma-3 4B-based filtering model fine-tuned on [Nemotron Content Safety Dataset v2](https://huggingface.co/datasets/nvidia/Aegis-AI-Content-Safety-Dataset-2.0) to ensure the quality of synthetic data.
8
+ Describe how the model works: | Vision Encoder and a Nemotron 5.5H -12B Language Encoder. It processes multiple input modalities, including text, multiple images, and video. It fuses these inputs and uses its large language model backbone with a 128K context length to perform visual Q&A, summarization, and data extraction.
9
+ Name the adversely impacted groups this has been tested to deliver comparable outcomes regardless of: | Not Applicable
10
+ Technical Limitations & Mitigation: | The model has a limited maximum resolution determined by a 12-tile layout constraint, where each tile is 512x512 pixels. It also supports a limited number of input images (up to 4) and has a maximum context length of 128K tokens for combined input and output.
11
+ Verified to have met prescribed NVIDIA quality standards: | Yes
12
+ Performance Metrics: | Accuracy (Visual Question Answering), Latency, Throughput
13
+ Potential Known Risks: | The Model may produce output that is biased, toxic, or incorrect responses. Therefore, the model may amplify those biases and return toxic responses especially when prompted with toxic prompts. The Model may also generate answers that may be inaccurate, omit key information, or include irrelevant or redundant text, producing socially unacceptable or undesirable text, even if the prompt itself does not include anything explicitly offensive.While we have taken safety and security into account and are continuously improving, outputs may still contain political content, misleading information, or unwanted bias beyond our control.
14
+ Licensing: | Governing Terms: Use of this model is governed by the [ NVIDIA Open Model License Agreement](https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-license/)
15
+
generation_config.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": [
5
+ 2,
6
+ 11,
7
+ 12
8
+ ],
9
+ "pad_token_id": 0,
10
+ "transformers_version": "4.51.3"
11
+ }
image_processing.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import List, Optional, Union, Any, Dict
15
+
16
+ from PIL import Image
17
+ import torch
18
+ from transformers.image_processing_base import BatchFeature
19
+ from transformers.image_processing_utils_fast import BaseImageProcessorFast, divide_to_patches
20
+ from transformers.image_utils import (make_list_of_images, get_image_size,
21
+ get_image_type, ImageInput, ImageType, ChannelDimension)
22
+ from transformers.utils import TensorType
23
+ import torchvision.transforms as T
24
+
25
+
26
+
27
+ class NemotronNanoVLV2ImageProcessor(BaseImageProcessorFast):
28
+ model_input_names = ["pixel_values"]
29
+
30
+ def __init__(self, image_size=512, max_num_tiles=12, use_thumbnail=True, norm_mean=None, norm_std=None, do_rescale=True, patch_size=16, downsample_ratio=0.5, **kwargs):
31
+ super().__init__(**kwargs)
32
+ self.image_size = image_size
33
+ self.max_num_tiles = max_num_tiles
34
+ self.use_thumbnail = use_thumbnail
35
+ self.norm_mean = norm_mean
36
+ self.norm_std = norm_std
37
+ self.do_rescale = do_rescale
38
+ self.num_image_token = int((image_size // patch_size) ** 2 * (downsample_ratio ** 2))
39
+
40
+ def _process_image(
41
+ self,
42
+ image: ImageInput,
43
+ **kwargs,
44
+ ) -> torch.Tensor:
45
+ image_type = get_image_type(image)
46
+ if image_type == ImageType.PIL:
47
+ if image.mode != 'RGB':
48
+ image = image.convert('RGB')
49
+ image = T.ToTensor()(image)
50
+ return image
51
+
52
+ def _preprocess(
53
+ self,
54
+ images: List[torch.Tensor],
55
+ image_size: int = None,
56
+ max_num_tiles: int = None,
57
+ use_thumbnail: bool = None,
58
+ do_rescale: bool = None,
59
+ return_tensors: Optional[Union[str, TensorType]] = None,
60
+ **kwargs,
61
+ ) -> List[torch.Tensor]:
62
+ image_size = image_size if image_size is not None else self.image_size
63
+ max_num_tiles = max_num_tiles if max_num_tiles is not None else self.max_num_tiles
64
+ use_thumbnail = use_thumbnail if use_thumbnail is not None else self.use_thumbnail
65
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
66
+
67
+ images = make_list_of_images(images)
68
+
69
+ all_patches = []
70
+ num_patches = []
71
+ for image in images:
72
+ patches = dynamic_preprocess(image, image_size, max_num_tiles, use_thumbnail)
73
+ all_patches.extend(patches)
74
+ num_patches.append(len(patches))
75
+
76
+ pixel_values = torch.stack(all_patches, dim=0)
77
+ norm_mean = torch.Tensor(self.norm_mean).view(1, 3, 1, 1)
78
+ norm_std = torch.Tensor(self.norm_std).view(1, 3, 1, 1)
79
+ pixel_values = (pixel_values - norm_mean) / norm_std
80
+ return BatchFeature(data={"pixel_values": pixel_values, "num_patches": num_patches}, tensor_type=return_tensors)
81
+
82
+
83
+ def get_internvl_target_ratios(
84
+ min_num: int,
85
+ max_num: int,
86
+ ) -> list[tuple[int, int]]:
87
+ target_ratios = {(i, j)
88
+ for n in range(min_num, max_num + 1)
89
+ for i in range(1, n + 1)
90
+ for j in range(1, n + 1) if min_num <= i * j <= max_num}
91
+ return sorted(target_ratios, key=lambda x: x[0] * x[1])
92
+
93
+
94
+ # From https://github.com/OpenGVLab/InternVL/blob/c62fa4f7c850165d7386bdc48ac6bc5a6fab0864/internvl_chat/internvl/train/dataset.py#L685
95
+ # Copyright (c) 2023 OpenGVLab.
96
+ def find_closest_aspect_ratio(
97
+ aspect_ratio: float,
98
+ target_ratios: list[tuple[int, int]],
99
+ width: int,
100
+ height: int,
101
+ image_size: int,
102
+ ) -> tuple[int, int]:
103
+ best_ratio_diff = float("inf")
104
+ best_ratio = (1, 1)
105
+ area = width * height
106
+ for ratio in target_ratios:
107
+ target_aspect_ratio = ratio[0] / ratio[1]
108
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
109
+ if ratio_diff < best_ratio_diff:
110
+ best_ratio_diff = ratio_diff
111
+ best_ratio = ratio
112
+ elif ratio_diff == best_ratio_diff:
113
+ if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
114
+ best_ratio = ratio
115
+ return best_ratio
116
+
117
+
118
+ def calculate_targets(
119
+ orig_width: int,
120
+ orig_height: int,
121
+ target_ratios: list[tuple[int, int]],
122
+ image_size: int,
123
+ ) -> tuple[int, int, int]:
124
+ aspect_ratio = orig_width / orig_height
125
+
126
+ # find the closest aspect ratio to the target
127
+ target_aspect_ratio = find_closest_aspect_ratio(
128
+ aspect_ratio,
129
+ target_ratios,
130
+ width=orig_width,
131
+ height=orig_height,
132
+ image_size=image_size,
133
+ )
134
+
135
+ # calculate the target width and height
136
+ target_width = image_size * target_aspect_ratio[0]
137
+ target_height = image_size * target_aspect_ratio[1]
138
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
139
+
140
+ return blocks, target_width, target_height
141
+
142
+
143
+ def dynamic_preprocess(image, image_size=512, max_num_tiles=12, use_thumbnail=True):
144
+ orig_height, orig_width = get_image_size(image, channel_dim=ChannelDimension.FIRST)
145
+ target_ratios = get_internvl_target_ratios(1, max_num_tiles)
146
+
147
+ blocks, target_width, target_height = calculate_targets(
148
+ orig_width,
149
+ orig_height,
150
+ target_ratios,
151
+ image_size
152
+ )
153
+ # resize the image
154
+ resized_img = T.Resize((target_height, target_width), interpolation=T.InterpolationMode.BICUBIC)(image)
155
+ patches = divide_to_patches(resized_img, image_size)
156
+ assert len(patches) == blocks
157
+ if use_thumbnail and len(patches) != 1:
158
+ thumbnail_img = T.Resize((image_size, image_size), interpolation=T.InterpolationMode.BICUBIC)(image)
159
+ patches.append(thumbnail_img)
160
+
161
+ return patches
images/demo.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e77cbba796091e59490b57e9ef814a9f295a0f7669d42b99537685e1958e974d
3
+ size 7333182
images/demo_frames/frame_0000.jpg ADDED

Git LFS Details

  • SHA256: 0c664ba20597a961daf435f4ce30c93febbba02eb964e2e595525eaca256483d
  • Pointer size: 131 Bytes
  • Size of remote file: 532 kB
images/demo_frames/frame_0001.jpg ADDED

Git LFS Details

  • SHA256: f961cda1f4ad1e44fb75cc8951eaeef628e75a05c602a71e815ffd3bf8a26d22
  • Pointer size: 131 Bytes
  • Size of remote file: 526 kB
images/demo_frames/frame_0002.jpg ADDED

Git LFS Details

  • SHA256: 8609912cbe164a3baadd0c3e7150afd8b9d68988b9f8d115948e44d2d14a996b
  • Pointer size: 131 Bytes
  • Size of remote file: 523 kB
images/demo_frames/frame_0003.jpg ADDED

Git LFS Details

  • SHA256: e5d7b553d7366562884ae77ea16c65b92d6796b7b3b76d3fd568d4e74c4a03da
  • Pointer size: 131 Bytes
  • Size of remote file: 511 kB
images/demo_frames/frame_0004.jpg ADDED

Git LFS Details

  • SHA256: 151ee1231201c8b6dc3c0cb56c0c7b84d6b1e16fb874059becbe5335df03682b
  • Pointer size: 131 Bytes
  • Size of remote file: 495 kB
images/demo_frames/frame_0005.jpg ADDED

Git LFS Details

  • SHA256: 959f473ea000c8bc87952e6c390d050ea8c7f865c44531e6bfa1f29833fadbd8
  • Pointer size: 131 Bytes
  • Size of remote file: 435 kB
images/demo_frames/frame_0006.jpg ADDED

Git LFS Details

  • SHA256: a608b7cfe92096baceab221be7c7d608ec6057c9f4c182bc7dac28dc18fac706
  • Pointer size: 131 Bytes
  • Size of remote file: 466 kB
images/demo_frames/frame_0007.jpg ADDED

Git LFS Details

  • SHA256: dff13f52befedf7d2749a64ec40e14bb47c8997af7a153e4e6dc0fbfb075ced7
  • Pointer size: 131 Bytes
  • Size of remote file: 452 kB
images/demo_frames/frame_0008.jpg ADDED

Git LFS Details

  • SHA256: 06f01f307849ffaf7b33fe0a2a2ad9174c5c36599f13978a656ef6a4505b134d
  • Pointer size: 131 Bytes
  • Size of remote file: 446 kB
images/demo_frames/frame_0009.jpg ADDED

Git LFS Details

  • SHA256: 2b8a4689a908a2d04e33e13037bbb2dcf4994df5236f66804d6e4e597423c223
  • Pointer size: 131 Bytes
  • Size of remote file: 443 kB
images/demo_frames/frame_0010.jpg ADDED

Git LFS Details

  • SHA256: aad1ffb23eaf1dc3afe1eddf024f0573ce7636e726fd4ae4d0d8cf95a07dc59c
  • Pointer size: 131 Bytes
  • Size of remote file: 399 kB
images/demo_frames/frame_0011.jpg ADDED

Git LFS Details

  • SHA256: 48d68cc5255a1c538f0f5606475a9a56da3e45adec02b054bef4853b0c134958
  • Pointer size: 131 Bytes
  • Size of remote file: 400 kB
images/demo_frames/frame_0012.jpg ADDED

Git LFS Details

  • SHA256: 6857551a744ed3e83f31f6b9e24465a7d3c65d7a9d1f9255d6d8ea70736106d4
  • Pointer size: 131 Bytes
  • Size of remote file: 375 kB
images/demo_frames/frame_0013.jpg ADDED

Git LFS Details

  • SHA256: ec3d3ac4b0e30d2f0956fdd5c96de10e54a7d766a8fad3910d4c3df7c2eca71a
  • Pointer size: 131 Bytes
  • Size of remote file: 362 kB
images/demo_frames/frame_0014.jpg ADDED

Git LFS Details

  • SHA256: 651bdd06eb684ff83f44cd6b30d129b2d1861ef4a21f91b572f27768b4342ed9
  • Pointer size: 131 Bytes
  • Size of remote file: 425 kB
images/demo_frames/metadata.json ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "num_frames": 15,
3
+ "fps": 1.0,
4
+ "duration": 15.666666666666666,
5
+ "original_video_fps": 30.0,
6
+ "original_total_frames": 471,
7
+ "original_duration": 15.7,
8
+ "frame_indices": [
9
+ 0,
10
+ 34,
11
+ 67,
12
+ 101,
13
+ 134,
14
+ 168,
15
+ 201,
16
+ 235,
17
+ 269,
18
+ 302,
19
+ 336,
20
+ 369,
21
+ 403,
22
+ 436,
23
+ 470
24
+ ],
25
+ "timestamps": [
26
+ 0.0,
27
+ 1.1333333333333333,
28
+ 2.2333333333333334,
29
+ 3.3666666666666667,
30
+ 4.466666666666667,
31
+ 5.6,
32
+ 6.7,
33
+ 7.833333333333333,
34
+ 8.966666666666667,
35
+ 10.066666666666666,
36
+ 11.2,
37
+ 12.3,
38
+ 13.433333333333334,
39
+ 14.533333333333333,
40
+ 15.666666666666666
41
+ ]
42
+ }
images/example1a.jpeg ADDED
images/example1b.jpeg ADDED
images/table.png ADDED

Git LFS Details

  • SHA256: 001461d8dd271602ce849013c9a226113279e0ae6156a27a12332bace6225e33
  • Pointer size: 131 Bytes
  • Size of remote file: 131 kB
images/tech.png ADDED

Git LFS Details

  • SHA256: 4ae75f51f941a0d05b9c7c9a5025f962930e3e7526a68a627602c47846278109
  • Pointer size: 131 Bytes
  • Size of remote file: 222 kB
model-00001-of-00007.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ac6d735e46b9ae89bd75f462c4a8080e3325692924ba5e2289e5a6b04c89819a
3
+ size 3831944248
model-00002-of-00007.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1c9bfacf484b2c7178e1aecc0086aef67de88b33692526049875a42dd0ff5352
3
+ size 3908097776
model-00003-of-00007.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a31e6b86866116c028d99b4b3e1fb82e01fd3fdb0a3530955eed4268f6d63131
3
+ size 3908097808
model-00004-of-00007.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a45fe2b6f4af25a32738f013009b72f7d2a7e749ea16258829cb98ad179a9440
3
+ size 3824190384
model-00005-of-00007.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fc5898c8e1a872928ccd162f5ea80c1471c3d1e959f1f0ec86022347d70bab9c
3
+ size 3908097808
model-00006-of-00007.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:40dfa0068329788adf9d17a42e20dc10f91d117a1dcfd7eaf8b5d298dc8c3c0d
3
+ size 3908097808
model-00007-of-00007.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:28c456af5e605d472277f69ec68c298ae39442f72f825f06cb1c2df5043a1ba0
3
+ size 3075291960
model.safetensors.index.json ADDED
@@ -0,0 +1,768 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 26363720728
4
+ },
5
+ "weight_map": {
6
+ "vision_model.radio_model.model.patch_generator.embedder.weight": "model-00001-of-00007.safetensors",
7
+ "vision_model.radio_model.model.patch_generator.cls_token.token": "model-00001-of-00007.safetensors",
8
+ "vision_model.radio_model.model.patch_generator.pos_embed": "model-00001-of-00007.safetensors",
9
+ "vision_model.radio_model.input_conditioner.norm_mean": "model-00001-of-00007.safetensors",
10
+ "vision_model.radio_model.input_conditioner.norm_std": "model-00001-of-00007.safetensors",
11
+ "vision_model.radio_model.model.blocks.0.norm1.weight": "model-00001-of-00007.safetensors",
12
+ "vision_model.radio_model.model.blocks.0.norm2.weight": "model-00001-of-00007.safetensors",
13
+ "vision_model.radio_model.model.blocks.0.norm1.bias": "model-00001-of-00007.safetensors",
14
+ "vision_model.radio_model.model.blocks.0.norm2.bias": "model-00001-of-00007.safetensors",
15
+ "vision_model.radio_model.model.blocks.0.mlp.fc1.weight": "model-00001-of-00007.safetensors",
16
+ "vision_model.radio_model.model.blocks.0.mlp.fc1.bias": "model-00001-of-00007.safetensors",
17
+ "vision_model.radio_model.model.blocks.0.attn.qkv.weight": "model-00001-of-00007.safetensors",
18
+ "vision_model.radio_model.model.blocks.0.attn.qkv.bias": "model-00001-of-00007.safetensors",
19
+ "vision_model.radio_model.model.blocks.0.attn.proj.weight": "model-00001-of-00007.safetensors",
20
+ "vision_model.radio_model.model.blocks.0.mlp.fc2.weight": "model-00001-of-00007.safetensors",
21
+ "vision_model.radio_model.model.blocks.0.mlp.fc2.bias": "model-00001-of-00007.safetensors",
22
+ "vision_model.radio_model.model.blocks.0.attn.proj.bias": "model-00001-of-00007.safetensors",
23
+ "vision_model.radio_model.model.blocks.1.norm1.weight": "model-00001-of-00007.safetensors",
24
+ "vision_model.radio_model.model.blocks.1.norm2.weight": "model-00001-of-00007.safetensors",
25
+ "vision_model.radio_model.model.blocks.1.norm1.bias": "model-00001-of-00007.safetensors",
26
+ "vision_model.radio_model.model.blocks.1.norm2.bias": "model-00001-of-00007.safetensors",
27
+ "vision_model.radio_model.model.blocks.1.mlp.fc1.weight": "model-00001-of-00007.safetensors",
28
+ "vision_model.radio_model.model.blocks.1.mlp.fc1.bias": "model-00001-of-00007.safetensors",
29
+ "vision_model.radio_model.model.blocks.1.attn.qkv.weight": "model-00001-of-00007.safetensors",
30
+ "vision_model.radio_model.model.blocks.1.attn.qkv.bias": "model-00001-of-00007.safetensors",
31
+ "vision_model.radio_model.model.blocks.1.attn.proj.weight": "model-00001-of-00007.safetensors",
32
+ "vision_model.radio_model.model.blocks.1.mlp.fc2.weight": "model-00001-of-00007.safetensors",
33
+ "vision_model.radio_model.model.blocks.1.mlp.fc2.bias": "model-00001-of-00007.safetensors",
34
+ "vision_model.radio_model.model.blocks.1.attn.proj.bias": "model-00001-of-00007.safetensors",
35
+ "vision_model.radio_model.model.blocks.2.norm1.weight": "model-00001-of-00007.safetensors",
36
+ "vision_model.radio_model.model.blocks.2.norm2.weight": "model-00001-of-00007.safetensors",
37
+ "vision_model.radio_model.model.blocks.2.norm1.bias": "model-00001-of-00007.safetensors",
38
+ "vision_model.radio_model.model.blocks.2.norm2.bias": "model-00001-of-00007.safetensors",
39
+ "vision_model.radio_model.model.blocks.2.mlp.fc1.weight": "model-00001-of-00007.safetensors",
40
+ "vision_model.radio_model.model.blocks.2.mlp.fc1.bias": "model-00001-of-00007.safetensors",
41
+ "vision_model.radio_model.model.blocks.2.attn.qkv.weight": "model-00001-of-00007.safetensors",
42
+ "vision_model.radio_model.model.blocks.2.attn.qkv.bias": "model-00001-of-00007.safetensors",
43
+ "vision_model.radio_model.model.blocks.2.attn.proj.weight": "model-00001-of-00007.safetensors",
44
+ "vision_model.radio_model.model.blocks.2.mlp.fc2.weight": "model-00001-of-00007.safetensors",
45
+ "vision_model.radio_model.model.blocks.2.mlp.fc2.bias": "model-00001-of-00007.safetensors",
46
+ "vision_model.radio_model.model.blocks.2.attn.proj.bias": "model-00001-of-00007.safetensors",
47
+ "vision_model.radio_model.model.blocks.3.norm1.weight": "model-00001-of-00007.safetensors",
48
+ "vision_model.radio_model.model.blocks.3.norm2.weight": "model-00001-of-00007.safetensors",
49
+ "vision_model.radio_model.model.blocks.3.norm1.bias": "model-00001-of-00007.safetensors",
50
+ "vision_model.radio_model.model.blocks.3.norm2.bias": "model-00001-of-00007.safetensors",
51
+ "vision_model.radio_model.model.blocks.3.mlp.fc1.weight": "model-00001-of-00007.safetensors",
52
+ "vision_model.radio_model.model.blocks.3.mlp.fc1.bias": "model-00001-of-00007.safetensors",
53
+ "vision_model.radio_model.model.blocks.3.attn.qkv.weight": "model-00001-of-00007.safetensors",
54
+ "vision_model.radio_model.model.blocks.3.attn.qkv.bias": "model-00001-of-00007.safetensors",
55
+ "vision_model.radio_model.model.blocks.3.attn.proj.weight": "model-00001-of-00007.safetensors",
56
+ "vision_model.radio_model.model.blocks.3.mlp.fc2.weight": "model-00001-of-00007.safetensors",
57
+ "vision_model.radio_model.model.blocks.3.mlp.fc2.bias": "model-00001-of-00007.safetensors",
58
+ "vision_model.radio_model.model.blocks.3.attn.proj.bias": "model-00001-of-00007.safetensors",
59
+ "vision_model.radio_model.model.blocks.4.norm1.weight": "model-00001-of-00007.safetensors",
60
+ "vision_model.radio_model.model.blocks.4.norm2.weight": "model-00001-of-00007.safetensors",
61
+ "vision_model.radio_model.model.blocks.4.norm1.bias": "model-00001-of-00007.safetensors",
62
+ "vision_model.radio_model.model.blocks.4.norm2.bias": "model-00001-of-00007.safetensors",
63
+ "vision_model.radio_model.model.blocks.4.mlp.fc1.weight": "model-00001-of-00007.safetensors",
64
+ "vision_model.radio_model.model.blocks.4.mlp.fc1.bias": "model-00001-of-00007.safetensors",
65
+ "vision_model.radio_model.model.blocks.4.attn.qkv.weight": "model-00001-of-00007.safetensors",
66
+ "vision_model.radio_model.model.blocks.4.attn.qkv.bias": "model-00001-of-00007.safetensors",
67
+ "vision_model.radio_model.model.blocks.4.attn.proj.weight": "model-00001-of-00007.safetensors",
68
+ "vision_model.radio_model.model.blocks.4.mlp.fc2.weight": "model-00001-of-00007.safetensors",
69
+ "vision_model.radio_model.model.blocks.4.mlp.fc2.bias": "model-00001-of-00007.safetensors",
70
+ "vision_model.radio_model.model.blocks.4.attn.proj.bias": "model-00001-of-00007.safetensors",
71
+ "vision_model.radio_model.model.blocks.5.norm1.weight": "model-00001-of-00007.safetensors",
72
+ "vision_model.radio_model.model.blocks.5.norm2.weight": "model-00001-of-00007.safetensors",
73
+ "vision_model.radio_model.model.blocks.5.norm1.bias": "model-00001-of-00007.safetensors",
74
+ "vision_model.radio_model.model.blocks.5.norm2.bias": "model-00001-of-00007.safetensors",
75
+ "vision_model.radio_model.model.blocks.5.mlp.fc1.weight": "model-00001-of-00007.safetensors",
76
+ "vision_model.radio_model.model.blocks.5.mlp.fc1.bias": "model-00001-of-00007.safetensors",
77
+ "vision_model.radio_model.model.blocks.5.attn.qkv.weight": "model-00001-of-00007.safetensors",
78
+ "vision_model.radio_model.model.blocks.5.attn.qkv.bias": "model-00001-of-00007.safetensors",
79
+ "vision_model.radio_model.model.blocks.5.attn.proj.weight": "model-00001-of-00007.safetensors",
80
+ "vision_model.radio_model.model.blocks.5.mlp.fc2.weight": "model-00001-of-00007.safetensors",
81
+ "vision_model.radio_model.model.blocks.5.mlp.fc2.bias": "model-00001-of-00007.safetensors",
82
+ "vision_model.radio_model.model.blocks.5.attn.proj.bias": "model-00001-of-00007.safetensors",
83
+ "vision_model.radio_model.model.blocks.6.norm1.weight": "model-00001-of-00007.safetensors",
84
+ "vision_model.radio_model.model.blocks.6.norm2.weight": "model-00001-of-00007.safetensors",
85
+ "vision_model.radio_model.model.blocks.6.norm1.bias": "model-00001-of-00007.safetensors",
86
+ "vision_model.radio_model.model.blocks.6.norm2.bias": "model-00001-of-00007.safetensors",
87
+ "vision_model.radio_model.model.blocks.6.mlp.fc1.weight": "model-00001-of-00007.safetensors",
88
+ "vision_model.radio_model.model.blocks.6.mlp.fc1.bias": "model-00001-of-00007.safetensors",
89
+ "vision_model.radio_model.model.blocks.6.attn.qkv.weight": "model-00001-of-00007.safetensors",
90
+ "vision_model.radio_model.model.blocks.6.attn.qkv.bias": "model-00001-of-00007.safetensors",
91
+ "vision_model.radio_model.model.blocks.6.attn.proj.weight": "model-00001-of-00007.safetensors",
92
+ "vision_model.radio_model.model.blocks.6.mlp.fc2.weight": "model-00001-of-00007.safetensors",
93
+ "vision_model.radio_model.model.blocks.6.mlp.fc2.bias": "model-00001-of-00007.safetensors",
94
+ "vision_model.radio_model.model.blocks.6.attn.proj.bias": "model-00001-of-00007.safetensors",
95
+ "vision_model.radio_model.model.blocks.7.norm1.weight": "model-00001-of-00007.safetensors",
96
+ "vision_model.radio_model.model.blocks.7.norm2.weight": "model-00001-of-00007.safetensors",
97
+ "vision_model.radio_model.model.blocks.7.norm1.bias": "model-00001-of-00007.safetensors",
98
+ "vision_model.radio_model.model.blocks.7.norm2.bias": "model-00001-of-00007.safetensors",
99
+ "vision_model.radio_model.model.blocks.7.mlp.fc1.weight": "model-00001-of-00007.safetensors",
100
+ "vision_model.radio_model.model.blocks.7.mlp.fc1.bias": "model-00001-of-00007.safetensors",
101
+ "vision_model.radio_model.model.blocks.7.attn.qkv.weight": "model-00001-of-00007.safetensors",
102
+ "vision_model.radio_model.model.blocks.7.attn.qkv.bias": "model-00001-of-00007.safetensors",
103
+ "vision_model.radio_model.model.blocks.7.attn.proj.weight": "model-00001-of-00007.safetensors",
104
+ "vision_model.radio_model.model.blocks.7.mlp.fc2.weight": "model-00001-of-00007.safetensors",
105
+ "vision_model.radio_model.model.blocks.7.mlp.fc2.bias": "model-00001-of-00007.safetensors",
106
+ "vision_model.radio_model.model.blocks.7.attn.proj.bias": "model-00001-of-00007.safetensors",
107
+ "vision_model.radio_model.model.blocks.8.norm1.weight": "model-00001-of-00007.safetensors",
108
+ "vision_model.radio_model.model.blocks.8.norm2.weight": "model-00001-of-00007.safetensors",
109
+ "vision_model.radio_model.model.blocks.8.norm1.bias": "model-00001-of-00007.safetensors",
110
+ "vision_model.radio_model.model.blocks.8.norm2.bias": "model-00001-of-00007.safetensors",
111
+ "vision_model.radio_model.model.blocks.8.mlp.fc1.weight": "model-00001-of-00007.safetensors",
112
+ "vision_model.radio_model.model.blocks.8.mlp.fc1.bias": "model-00001-of-00007.safetensors",
113
+ "vision_model.radio_model.model.blocks.8.attn.qkv.weight": "model-00001-of-00007.safetensors",
114
+ "vision_model.radio_model.model.blocks.8.attn.qkv.bias": "model-00001-of-00007.safetensors",
115
+ "vision_model.radio_model.model.blocks.8.attn.proj.weight": "model-00001-of-00007.safetensors",
116
+ "vision_model.radio_model.model.blocks.8.mlp.fc2.weight": "model-00001-of-00007.safetensors",
117
+ "vision_model.radio_model.model.blocks.8.mlp.fc2.bias": "model-00001-of-00007.safetensors",
118
+ "vision_model.radio_model.model.blocks.8.attn.proj.bias": "model-00001-of-00007.safetensors",
119
+ "vision_model.radio_model.model.blocks.9.norm1.weight": "model-00001-of-00007.safetensors",
120
+ "vision_model.radio_model.model.blocks.9.norm2.weight": "model-00001-of-00007.safetensors",
121
+ "vision_model.radio_model.model.blocks.9.norm1.bias": "model-00001-of-00007.safetensors",
122
+ "vision_model.radio_model.model.blocks.9.norm2.bias": "model-00001-of-00007.safetensors",
123
+ "vision_model.radio_model.model.blocks.9.mlp.fc1.weight": "model-00001-of-00007.safetensors",
124
+ "vision_model.radio_model.model.blocks.9.mlp.fc1.bias": "model-00001-of-00007.safetensors",
125
+ "vision_model.radio_model.model.blocks.9.attn.qkv.weight": "model-00001-of-00007.safetensors",
126
+ "vision_model.radio_model.model.blocks.9.attn.qkv.bias": "model-00001-of-00007.safetensors",
127
+ "vision_model.radio_model.model.blocks.9.attn.proj.weight": "model-00001-of-00007.safetensors",
128
+ "vision_model.radio_model.model.blocks.9.mlp.fc2.weight": "model-00001-of-00007.safetensors",
129
+ "vision_model.radio_model.model.blocks.9.mlp.fc2.bias": "model-00001-of-00007.safetensors",
130
+ "vision_model.radio_model.model.blocks.9.attn.proj.bias": "model-00001-of-00007.safetensors",
131
+ "vision_model.radio_model.model.blocks.10.norm1.weight": "model-00001-of-00007.safetensors",
132
+ "vision_model.radio_model.model.blocks.10.norm2.weight": "model-00001-of-00007.safetensors",
133
+ "vision_model.radio_model.model.blocks.10.norm1.bias": "model-00001-of-00007.safetensors",
134
+ "vision_model.radio_model.model.blocks.10.norm2.bias": "model-00001-of-00007.safetensors",
135
+ "vision_model.radio_model.model.blocks.10.mlp.fc1.weight": "model-00001-of-00007.safetensors",
136
+ "vision_model.radio_model.model.blocks.10.mlp.fc1.bias": "model-00001-of-00007.safetensors",
137
+ "vision_model.radio_model.model.blocks.10.attn.qkv.weight": "model-00001-of-00007.safetensors",
138
+ "vision_model.radio_model.model.blocks.10.attn.qkv.bias": "model-00001-of-00007.safetensors",
139
+ "vision_model.radio_model.model.blocks.10.attn.proj.weight": "model-00001-of-00007.safetensors",
140
+ "vision_model.radio_model.model.blocks.10.mlp.fc2.weight": "model-00001-of-00007.safetensors",
141
+ "vision_model.radio_model.model.blocks.10.mlp.fc2.bias": "model-00001-of-00007.safetensors",
142
+ "vision_model.radio_model.model.blocks.10.attn.proj.bias": "model-00001-of-00007.safetensors",
143
+ "vision_model.radio_model.model.blocks.11.norm1.weight": "model-00001-of-00007.safetensors",
144
+ "vision_model.radio_model.model.blocks.11.norm2.weight": "model-00001-of-00007.safetensors",
145
+ "vision_model.radio_model.model.blocks.11.norm1.bias": "model-00001-of-00007.safetensors",
146
+ "vision_model.radio_model.model.blocks.11.norm2.bias": "model-00001-of-00007.safetensors",
147
+ "vision_model.radio_model.model.blocks.11.mlp.fc1.weight": "model-00001-of-00007.safetensors",
148
+ "vision_model.radio_model.model.blocks.11.mlp.fc1.bias": "model-00001-of-00007.safetensors",
149
+ "vision_model.radio_model.model.blocks.11.attn.qkv.weight": "model-00001-of-00007.safetensors",
150
+ "vision_model.radio_model.model.blocks.11.attn.qkv.bias": "model-00001-of-00007.safetensors",
151
+ "vision_model.radio_model.model.blocks.11.attn.proj.weight": "model-00001-of-00007.safetensors",
152
+ "vision_model.radio_model.model.blocks.11.mlp.fc2.weight": "model-00001-of-00007.safetensors",
153
+ "vision_model.radio_model.model.blocks.11.mlp.fc2.bias": "model-00001-of-00007.safetensors",
154
+ "vision_model.radio_model.model.blocks.11.attn.proj.bias": "model-00001-of-00007.safetensors",
155
+ "vision_model.radio_model.model.blocks.12.norm1.weight": "model-00001-of-00007.safetensors",
156
+ "vision_model.radio_model.model.blocks.12.norm2.weight": "model-00001-of-00007.safetensors",
157
+ "vision_model.radio_model.model.blocks.12.norm1.bias": "model-00001-of-00007.safetensors",
158
+ "vision_model.radio_model.model.blocks.12.norm2.bias": "model-00001-of-00007.safetensors",
159
+ "vision_model.radio_model.model.blocks.12.mlp.fc1.weight": "model-00001-of-00007.safetensors",
160
+ "vision_model.radio_model.model.blocks.12.mlp.fc1.bias": "model-00001-of-00007.safetensors",
161
+ "vision_model.radio_model.model.blocks.12.attn.qkv.weight": "model-00001-of-00007.safetensors",
162
+ "vision_model.radio_model.model.blocks.12.attn.qkv.bias": "model-00001-of-00007.safetensors",
163
+ "vision_model.radio_model.model.blocks.12.attn.proj.weight": "model-00001-of-00007.safetensors",
164
+ "vision_model.radio_model.model.blocks.12.mlp.fc2.weight": "model-00001-of-00007.safetensors",
165
+ "vision_model.radio_model.model.blocks.12.mlp.fc2.bias": "model-00001-of-00007.safetensors",
166
+ "vision_model.radio_model.model.blocks.12.attn.proj.bias": "model-00001-of-00007.safetensors",
167
+ "vision_model.radio_model.model.blocks.13.norm1.weight": "model-00001-of-00007.safetensors",
168
+ "vision_model.radio_model.model.blocks.13.norm2.weight": "model-00001-of-00007.safetensors",
169
+ "vision_model.radio_model.model.blocks.13.norm1.bias": "model-00001-of-00007.safetensors",
170
+ "vision_model.radio_model.model.blocks.13.norm2.bias": "model-00001-of-00007.safetensors",
171
+ "vision_model.radio_model.model.blocks.13.mlp.fc1.weight": "model-00001-of-00007.safetensors",
172
+ "vision_model.radio_model.model.blocks.13.mlp.fc1.bias": "model-00001-of-00007.safetensors",
173
+ "vision_model.radio_model.model.blocks.13.attn.qkv.weight": "model-00001-of-00007.safetensors",
174
+ "vision_model.radio_model.model.blocks.13.attn.qkv.bias": "model-00001-of-00007.safetensors",
175
+ "vision_model.radio_model.model.blocks.13.attn.proj.weight": "model-00001-of-00007.safetensors",
176
+ "vision_model.radio_model.model.blocks.13.mlp.fc2.weight": "model-00001-of-00007.safetensors",
177
+ "vision_model.radio_model.model.blocks.13.mlp.fc2.bias": "model-00001-of-00007.safetensors",
178
+ "vision_model.radio_model.model.blocks.13.attn.proj.bias": "model-00001-of-00007.safetensors",
179
+ "vision_model.radio_model.model.blocks.14.norm1.weight": "model-00001-of-00007.safetensors",
180
+ "vision_model.radio_model.model.blocks.14.norm2.weight": "model-00001-of-00007.safetensors",
181
+ "vision_model.radio_model.model.blocks.14.norm1.bias": "model-00001-of-00007.safetensors",
182
+ "vision_model.radio_model.model.blocks.14.norm2.bias": "model-00001-of-00007.safetensors",
183
+ "vision_model.radio_model.model.blocks.14.mlp.fc1.weight": "model-00001-of-00007.safetensors",
184
+ "vision_model.radio_model.model.blocks.14.mlp.fc1.bias": "model-00001-of-00007.safetensors",
185
+ "vision_model.radio_model.model.blocks.14.attn.qkv.weight": "model-00001-of-00007.safetensors",
186
+ "vision_model.radio_model.model.blocks.14.attn.qkv.bias": "model-00001-of-00007.safetensors",
187
+ "vision_model.radio_model.model.blocks.14.attn.proj.weight": "model-00001-of-00007.safetensors",
188
+ "vision_model.radio_model.model.blocks.14.mlp.fc2.weight": "model-00001-of-00007.safetensors",
189
+ "vision_model.radio_model.model.blocks.14.mlp.fc2.bias": "model-00001-of-00007.safetensors",
190
+ "vision_model.radio_model.model.blocks.14.attn.proj.bias": "model-00001-of-00007.safetensors",
191
+ "vision_model.radio_model.model.blocks.15.norm1.weight": "model-00001-of-00007.safetensors",
192
+ "vision_model.radio_model.model.blocks.15.norm2.weight": "model-00001-of-00007.safetensors",
193
+ "vision_model.radio_model.model.blocks.15.norm1.bias": "model-00001-of-00007.safetensors",
194
+ "vision_model.radio_model.model.blocks.15.norm2.bias": "model-00001-of-00007.safetensors",
195
+ "vision_model.radio_model.model.blocks.15.mlp.fc1.weight": "model-00001-of-00007.safetensors",
196
+ "vision_model.radio_model.model.blocks.15.mlp.fc1.bias": "model-00001-of-00007.safetensors",
197
+ "vision_model.radio_model.model.blocks.15.attn.qkv.weight": "model-00001-of-00007.safetensors",
198
+ "vision_model.radio_model.model.blocks.15.attn.qkv.bias": "model-00001-of-00007.safetensors",
199
+ "vision_model.radio_model.model.blocks.15.attn.proj.weight": "model-00001-of-00007.safetensors",
200
+ "vision_model.radio_model.model.blocks.15.mlp.fc2.weight": "model-00001-of-00007.safetensors",
201
+ "vision_model.radio_model.model.blocks.15.mlp.fc2.bias": "model-00001-of-00007.safetensors",
202
+ "vision_model.radio_model.model.blocks.15.attn.proj.bias": "model-00001-of-00007.safetensors",
203
+ "vision_model.radio_model.model.blocks.16.norm1.weight": "model-00001-of-00007.safetensors",
204
+ "vision_model.radio_model.model.blocks.16.norm2.weight": "model-00001-of-00007.safetensors",
205
+ "vision_model.radio_model.model.blocks.16.norm1.bias": "model-00001-of-00007.safetensors",
206
+ "vision_model.radio_model.model.blocks.16.norm2.bias": "model-00001-of-00007.safetensors",
207
+ "vision_model.radio_model.model.blocks.16.mlp.fc1.weight": "model-00001-of-00007.safetensors",
208
+ "vision_model.radio_model.model.blocks.16.mlp.fc1.bias": "model-00001-of-00007.safetensors",
209
+ "vision_model.radio_model.model.blocks.16.attn.qkv.weight": "model-00001-of-00007.safetensors",
210
+ "vision_model.radio_model.model.blocks.16.attn.qkv.bias": "model-00001-of-00007.safetensors",
211
+ "vision_model.radio_model.model.blocks.16.attn.proj.weight": "model-00001-of-00007.safetensors",
212
+ "vision_model.radio_model.model.blocks.16.mlp.fc2.weight": "model-00001-of-00007.safetensors",
213
+ "vision_model.radio_model.model.blocks.16.mlp.fc2.bias": "model-00001-of-00007.safetensors",
214
+ "vision_model.radio_model.model.blocks.16.attn.proj.bias": "model-00001-of-00007.safetensors",
215
+ "vision_model.radio_model.model.blocks.17.norm1.weight": "model-00001-of-00007.safetensors",
216
+ "vision_model.radio_model.model.blocks.17.norm2.weight": "model-00001-of-00007.safetensors",
217
+ "vision_model.radio_model.model.blocks.17.norm1.bias": "model-00001-of-00007.safetensors",
218
+ "vision_model.radio_model.model.blocks.17.norm2.bias": "model-00001-of-00007.safetensors",
219
+ "vision_model.radio_model.model.blocks.17.mlp.fc1.weight": "model-00001-of-00007.safetensors",
220
+ "vision_model.radio_model.model.blocks.17.mlp.fc1.bias": "model-00001-of-00007.safetensors",
221
+ "vision_model.radio_model.model.blocks.17.attn.qkv.weight": "model-00001-of-00007.safetensors",
222
+ "vision_model.radio_model.model.blocks.17.attn.qkv.bias": "model-00001-of-00007.safetensors",
223
+ "vision_model.radio_model.model.blocks.17.attn.proj.weight": "model-00001-of-00007.safetensors",
224
+ "vision_model.radio_model.model.blocks.17.mlp.fc2.weight": "model-00001-of-00007.safetensors",
225
+ "vision_model.radio_model.model.blocks.17.mlp.fc2.bias": "model-00001-of-00007.safetensors",
226
+ "vision_model.radio_model.model.blocks.17.attn.proj.bias": "model-00001-of-00007.safetensors",
227
+ "vision_model.radio_model.model.blocks.18.norm1.weight": "model-00001-of-00007.safetensors",
228
+ "vision_model.radio_model.model.blocks.18.norm2.weight": "model-00001-of-00007.safetensors",
229
+ "vision_model.radio_model.model.blocks.18.norm1.bias": "model-00001-of-00007.safetensors",
230
+ "vision_model.radio_model.model.blocks.18.norm2.bias": "model-00001-of-00007.safetensors",
231
+ "vision_model.radio_model.model.blocks.18.mlp.fc1.weight": "model-00001-of-00007.safetensors",
232
+ "vision_model.radio_model.model.blocks.18.mlp.fc1.bias": "model-00001-of-00007.safetensors",
233
+ "vision_model.radio_model.model.blocks.18.attn.qkv.weight": "model-00001-of-00007.safetensors",
234
+ "vision_model.radio_model.model.blocks.18.attn.qkv.bias": "model-00001-of-00007.safetensors",
235
+ "vision_model.radio_model.model.blocks.18.attn.proj.weight": "model-00001-of-00007.safetensors",
236
+ "vision_model.radio_model.model.blocks.18.mlp.fc2.weight": "model-00001-of-00007.safetensors",
237
+ "vision_model.radio_model.model.blocks.18.mlp.fc2.bias": "model-00001-of-00007.safetensors",
238
+ "vision_model.radio_model.model.blocks.18.attn.proj.bias": "model-00001-of-00007.safetensors",
239
+ "vision_model.radio_model.model.blocks.19.norm1.weight": "model-00001-of-00007.safetensors",
240
+ "vision_model.radio_model.model.blocks.19.norm2.weight": "model-00001-of-00007.safetensors",
241
+ "vision_model.radio_model.model.blocks.19.norm1.bias": "model-00001-of-00007.safetensors",
242
+ "vision_model.radio_model.model.blocks.19.norm2.bias": "model-00001-of-00007.safetensors",
243
+ "vision_model.radio_model.model.blocks.19.mlp.fc1.weight": "model-00001-of-00007.safetensors",
244
+ "vision_model.radio_model.model.blocks.19.mlp.fc1.bias": "model-00001-of-00007.safetensors",
245
+ "vision_model.radio_model.model.blocks.19.attn.qkv.weight": "model-00001-of-00007.safetensors",
246
+ "vision_model.radio_model.model.blocks.19.attn.qkv.bias": "model-00001-of-00007.safetensors",
247
+ "vision_model.radio_model.model.blocks.19.attn.proj.weight": "model-00001-of-00007.safetensors",
248
+ "vision_model.radio_model.model.blocks.19.mlp.fc2.weight": "model-00001-of-00007.safetensors",
249
+ "vision_model.radio_model.model.blocks.19.mlp.fc2.bias": "model-00001-of-00007.safetensors",
250
+ "vision_model.radio_model.model.blocks.19.attn.proj.bias": "model-00001-of-00007.safetensors",
251
+ "vision_model.radio_model.model.blocks.20.norm1.weight": "model-00001-of-00007.safetensors",
252
+ "vision_model.radio_model.model.blocks.20.norm2.weight": "model-00001-of-00007.safetensors",
253
+ "vision_model.radio_model.model.blocks.20.norm1.bias": "model-00001-of-00007.safetensors",
254
+ "vision_model.radio_model.model.blocks.20.norm2.bias": "model-00001-of-00007.safetensors",
255
+ "vision_model.radio_model.model.blocks.20.mlp.fc1.weight": "model-00001-of-00007.safetensors",
256
+ "vision_model.radio_model.model.blocks.20.mlp.fc1.bias": "model-00001-of-00007.safetensors",
257
+ "vision_model.radio_model.model.blocks.20.attn.qkv.weight": "model-00001-of-00007.safetensors",
258
+ "vision_model.radio_model.model.blocks.20.attn.qkv.bias": "model-00001-of-00007.safetensors",
259
+ "vision_model.radio_model.model.blocks.20.attn.proj.weight": "model-00001-of-00007.safetensors",
260
+ "vision_model.radio_model.model.blocks.20.mlp.fc2.weight": "model-00001-of-00007.safetensors",
261
+ "vision_model.radio_model.model.blocks.20.mlp.fc2.bias": "model-00001-of-00007.safetensors",
262
+ "vision_model.radio_model.model.blocks.20.attn.proj.bias": "model-00001-of-00007.safetensors",
263
+ "vision_model.radio_model.model.blocks.21.norm1.weight": "model-00001-of-00007.safetensors",
264
+ "vision_model.radio_model.model.blocks.21.norm2.weight": "model-00001-of-00007.safetensors",
265
+ "vision_model.radio_model.model.blocks.21.norm1.bias": "model-00001-of-00007.safetensors",
266
+ "vision_model.radio_model.model.blocks.21.norm2.bias": "model-00001-of-00007.safetensors",
267
+ "vision_model.radio_model.model.blocks.21.mlp.fc1.weight": "model-00001-of-00007.safetensors",
268
+ "vision_model.radio_model.model.blocks.21.mlp.fc1.bias": "model-00001-of-00007.safetensors",
269
+ "vision_model.radio_model.model.blocks.21.attn.qkv.weight": "model-00001-of-00007.safetensors",
270
+ "vision_model.radio_model.model.blocks.21.attn.qkv.bias": "model-00001-of-00007.safetensors",
271
+ "vision_model.radio_model.model.blocks.21.attn.proj.weight": "model-00001-of-00007.safetensors",
272
+ "vision_model.radio_model.model.blocks.21.mlp.fc2.weight": "model-00001-of-00007.safetensors",
273
+ "vision_model.radio_model.model.blocks.21.mlp.fc2.bias": "model-00001-of-00007.safetensors",
274
+ "vision_model.radio_model.model.blocks.21.attn.proj.bias": "model-00001-of-00007.safetensors",
275
+ "vision_model.radio_model.model.blocks.22.norm1.weight": "model-00001-of-00007.safetensors",
276
+ "vision_model.radio_model.model.blocks.22.norm2.weight": "model-00001-of-00007.safetensors",
277
+ "vision_model.radio_model.model.blocks.22.norm1.bias": "model-00001-of-00007.safetensors",
278
+ "vision_model.radio_model.model.blocks.22.norm2.bias": "model-00001-of-00007.safetensors",
279
+ "vision_model.radio_model.model.blocks.22.mlp.fc1.weight": "model-00001-of-00007.safetensors",
280
+ "vision_model.radio_model.model.blocks.22.mlp.fc1.bias": "model-00001-of-00007.safetensors",
281
+ "vision_model.radio_model.model.blocks.22.attn.qkv.weight": "model-00001-of-00007.safetensors",
282
+ "vision_model.radio_model.model.blocks.22.attn.qkv.bias": "model-00001-of-00007.safetensors",
283
+ "vision_model.radio_model.model.blocks.22.attn.proj.weight": "model-00001-of-00007.safetensors",
284
+ "vision_model.radio_model.model.blocks.22.mlp.fc2.weight": "model-00001-of-00007.safetensors",
285
+ "vision_model.radio_model.model.blocks.22.mlp.fc2.bias": "model-00001-of-00007.safetensors",
286
+ "vision_model.radio_model.model.blocks.22.attn.proj.bias": "model-00001-of-00007.safetensors",
287
+ "vision_model.radio_model.model.blocks.23.norm1.weight": "model-00001-of-00007.safetensors",
288
+ "vision_model.radio_model.model.blocks.23.norm2.weight": "model-00001-of-00007.safetensors",
289
+ "vision_model.radio_model.model.blocks.23.norm1.bias": "model-00001-of-00007.safetensors",
290
+ "vision_model.radio_model.model.blocks.23.norm2.bias": "model-00001-of-00007.safetensors",
291
+ "vision_model.radio_model.model.blocks.23.mlp.fc1.weight": "model-00001-of-00007.safetensors",
292
+ "vision_model.radio_model.model.blocks.23.mlp.fc1.bias": "model-00001-of-00007.safetensors",
293
+ "vision_model.radio_model.model.blocks.23.attn.qkv.weight": "model-00001-of-00007.safetensors",
294
+ "vision_model.radio_model.model.blocks.23.attn.qkv.bias": "model-00001-of-00007.safetensors",
295
+ "vision_model.radio_model.model.blocks.23.attn.proj.weight": "model-00001-of-00007.safetensors",
296
+ "vision_model.radio_model.model.blocks.23.mlp.fc2.weight": "model-00001-of-00007.safetensors",
297
+ "vision_model.radio_model.model.blocks.23.mlp.fc2.bias": "model-00001-of-00007.safetensors",
298
+ "vision_model.radio_model.model.blocks.23.attn.proj.bias": "model-00001-of-00007.safetensors",
299
+ "vision_model.radio_model.model.blocks.24.norm1.weight": "model-00001-of-00007.safetensors",
300
+ "vision_model.radio_model.model.blocks.24.norm2.weight": "model-00001-of-00007.safetensors",
301
+ "vision_model.radio_model.model.blocks.24.norm1.bias": "model-00001-of-00007.safetensors",
302
+ "vision_model.radio_model.model.blocks.24.norm2.bias": "model-00001-of-00007.safetensors",
303
+ "vision_model.radio_model.model.blocks.24.mlp.fc1.weight": "model-00001-of-00007.safetensors",
304
+ "vision_model.radio_model.model.blocks.24.mlp.fc1.bias": "model-00001-of-00007.safetensors",
305
+ "vision_model.radio_model.model.blocks.24.attn.qkv.weight": "model-00001-of-00007.safetensors",
306
+ "vision_model.radio_model.model.blocks.24.attn.qkv.bias": "model-00001-of-00007.safetensors",
307
+ "vision_model.radio_model.model.blocks.24.attn.proj.weight": "model-00001-of-00007.safetensors",
308
+ "vision_model.radio_model.model.blocks.24.mlp.fc2.weight": "model-00001-of-00007.safetensors",
309
+ "vision_model.radio_model.model.blocks.24.mlp.fc2.bias": "model-00001-of-00007.safetensors",
310
+ "vision_model.radio_model.model.blocks.24.attn.proj.bias": "model-00001-of-00007.safetensors",
311
+ "vision_model.radio_model.model.blocks.25.norm1.weight": "model-00001-of-00007.safetensors",
312
+ "vision_model.radio_model.model.blocks.25.norm2.weight": "model-00001-of-00007.safetensors",
313
+ "vision_model.radio_model.model.blocks.25.norm1.bias": "model-00001-of-00007.safetensors",
314
+ "vision_model.radio_model.model.blocks.25.norm2.bias": "model-00001-of-00007.safetensors",
315
+ "vision_model.radio_model.model.blocks.25.mlp.fc1.weight": "model-00001-of-00007.safetensors",
316
+ "vision_model.radio_model.model.blocks.25.mlp.fc1.bias": "model-00001-of-00007.safetensors",
317
+ "vision_model.radio_model.model.blocks.25.attn.qkv.weight": "model-00001-of-00007.safetensors",
318
+ "vision_model.radio_model.model.blocks.25.attn.qkv.bias": "model-00001-of-00007.safetensors",
319
+ "vision_model.radio_model.model.blocks.25.attn.proj.weight": "model-00001-of-00007.safetensors",
320
+ "vision_model.radio_model.model.blocks.25.mlp.fc2.weight": "model-00001-of-00007.safetensors",
321
+ "vision_model.radio_model.model.blocks.25.mlp.fc2.bias": "model-00001-of-00007.safetensors",
322
+ "vision_model.radio_model.model.blocks.25.attn.proj.bias": "model-00001-of-00007.safetensors",
323
+ "vision_model.radio_model.model.blocks.26.norm1.weight": "model-00001-of-00007.safetensors",
324
+ "vision_model.radio_model.model.blocks.26.norm2.weight": "model-00001-of-00007.safetensors",
325
+ "vision_model.radio_model.model.blocks.26.norm1.bias": "model-00001-of-00007.safetensors",
326
+ "vision_model.radio_model.model.blocks.26.norm2.bias": "model-00001-of-00007.safetensors",
327
+ "vision_model.radio_model.model.blocks.26.mlp.fc1.weight": "model-00001-of-00007.safetensors",
328
+ "vision_model.radio_model.model.blocks.26.mlp.fc1.bias": "model-00001-of-00007.safetensors",
329
+ "vision_model.radio_model.model.blocks.26.attn.qkv.weight": "model-00001-of-00007.safetensors",
330
+ "vision_model.radio_model.model.blocks.26.attn.qkv.bias": "model-00001-of-00007.safetensors",
331
+ "vision_model.radio_model.model.blocks.26.attn.proj.weight": "model-00001-of-00007.safetensors",
332
+ "vision_model.radio_model.model.blocks.26.mlp.fc2.weight": "model-00001-of-00007.safetensors",
333
+ "vision_model.radio_model.model.blocks.26.mlp.fc2.bias": "model-00001-of-00007.safetensors",
334
+ "vision_model.radio_model.model.blocks.26.attn.proj.bias": "model-00001-of-00007.safetensors",
335
+ "vision_model.radio_model.model.blocks.27.norm1.weight": "model-00001-of-00007.safetensors",
336
+ "vision_model.radio_model.model.blocks.27.norm2.weight": "model-00001-of-00007.safetensors",
337
+ "vision_model.radio_model.model.blocks.27.norm1.bias": "model-00001-of-00007.safetensors",
338
+ "vision_model.radio_model.model.blocks.27.norm2.bias": "model-00001-of-00007.safetensors",
339
+ "vision_model.radio_model.model.blocks.27.mlp.fc1.weight": "model-00001-of-00007.safetensors",
340
+ "vision_model.radio_model.model.blocks.27.mlp.fc1.bias": "model-00001-of-00007.safetensors",
341
+ "vision_model.radio_model.model.blocks.27.attn.qkv.weight": "model-00001-of-00007.safetensors",
342
+ "vision_model.radio_model.model.blocks.27.attn.qkv.bias": "model-00001-of-00007.safetensors",
343
+ "vision_model.radio_model.model.blocks.27.attn.proj.weight": "model-00001-of-00007.safetensors",
344
+ "vision_model.radio_model.model.blocks.27.mlp.fc2.weight": "model-00001-of-00007.safetensors",
345
+ "vision_model.radio_model.model.blocks.27.mlp.fc2.bias": "model-00001-of-00007.safetensors",
346
+ "vision_model.radio_model.model.blocks.27.attn.proj.bias": "model-00001-of-00007.safetensors",
347
+ "vision_model.radio_model.model.blocks.28.norm1.weight": "model-00001-of-00007.safetensors",
348
+ "vision_model.radio_model.model.blocks.28.norm2.weight": "model-00001-of-00007.safetensors",
349
+ "vision_model.radio_model.model.blocks.28.norm1.bias": "model-00001-of-00007.safetensors",
350
+ "vision_model.radio_model.model.blocks.28.norm2.bias": "model-00001-of-00007.safetensors",
351
+ "vision_model.radio_model.model.blocks.28.mlp.fc1.weight": "model-00001-of-00007.safetensors",
352
+ "vision_model.radio_model.model.blocks.28.mlp.fc1.bias": "model-00001-of-00007.safetensors",
353
+ "vision_model.radio_model.model.blocks.28.attn.qkv.weight": "model-00001-of-00007.safetensors",
354
+ "vision_model.radio_model.model.blocks.28.attn.qkv.bias": "model-00001-of-00007.safetensors",
355
+ "vision_model.radio_model.model.blocks.28.attn.proj.weight": "model-00001-of-00007.safetensors",
356
+ "vision_model.radio_model.model.blocks.28.mlp.fc2.weight": "model-00001-of-00007.safetensors",
357
+ "vision_model.radio_model.model.blocks.28.mlp.fc2.bias": "model-00001-of-00007.safetensors",
358
+ "vision_model.radio_model.model.blocks.28.attn.proj.bias": "model-00001-of-00007.safetensors",
359
+ "vision_model.radio_model.model.blocks.29.norm1.weight": "model-00001-of-00007.safetensors",
360
+ "vision_model.radio_model.model.blocks.29.norm2.weight": "model-00001-of-00007.safetensors",
361
+ "vision_model.radio_model.model.blocks.29.norm1.bias": "model-00001-of-00007.safetensors",
362
+ "vision_model.radio_model.model.blocks.29.norm2.bias": "model-00001-of-00007.safetensors",
363
+ "vision_model.radio_model.model.blocks.29.mlp.fc1.weight": "model-00001-of-00007.safetensors",
364
+ "vision_model.radio_model.model.blocks.29.mlp.fc1.bias": "model-00001-of-00007.safetensors",
365
+ "vision_model.radio_model.model.blocks.29.attn.qkv.weight": "model-00001-of-00007.safetensors",
366
+ "vision_model.radio_model.model.blocks.29.attn.qkv.bias": "model-00001-of-00007.safetensors",
367
+ "vision_model.radio_model.model.blocks.29.attn.proj.weight": "model-00001-of-00007.safetensors",
368
+ "vision_model.radio_model.model.blocks.29.mlp.fc2.weight": "model-00001-of-00007.safetensors",
369
+ "vision_model.radio_model.model.blocks.29.mlp.fc2.bias": "model-00001-of-00007.safetensors",
370
+ "vision_model.radio_model.model.blocks.29.attn.proj.bias": "model-00001-of-00007.safetensors",
371
+ "vision_model.radio_model.model.blocks.30.norm1.weight": "model-00001-of-00007.safetensors",
372
+ "vision_model.radio_model.model.blocks.30.norm2.weight": "model-00001-of-00007.safetensors",
373
+ "vision_model.radio_model.model.blocks.30.norm1.bias": "model-00001-of-00007.safetensors",
374
+ "vision_model.radio_model.model.blocks.30.norm2.bias": "model-00001-of-00007.safetensors",
375
+ "vision_model.radio_model.model.blocks.30.mlp.fc1.weight": "model-00001-of-00007.safetensors",
376
+ "vision_model.radio_model.model.blocks.30.mlp.fc1.bias": "model-00001-of-00007.safetensors",
377
+ "vision_model.radio_model.model.blocks.30.attn.qkv.weight": "model-00001-of-00007.safetensors",
378
+ "vision_model.radio_model.model.blocks.30.attn.qkv.bias": "model-00001-of-00007.safetensors",
379
+ "vision_model.radio_model.model.blocks.30.attn.proj.weight": "model-00001-of-00007.safetensors",
380
+ "vision_model.radio_model.model.blocks.30.mlp.fc2.weight": "model-00001-of-00007.safetensors",
381
+ "vision_model.radio_model.model.blocks.30.mlp.fc2.bias": "model-00001-of-00007.safetensors",
382
+ "vision_model.radio_model.model.blocks.30.attn.proj.bias": "model-00001-of-00007.safetensors",
383
+ "vision_model.radio_model.model.blocks.31.norm1.weight": "model-00001-of-00007.safetensors",
384
+ "vision_model.radio_model.model.blocks.31.norm2.weight": "model-00001-of-00007.safetensors",
385
+ "vision_model.radio_model.model.blocks.31.norm1.bias": "model-00001-of-00007.safetensors",
386
+ "vision_model.radio_model.model.blocks.31.norm2.bias": "model-00001-of-00007.safetensors",
387
+ "vision_model.radio_model.model.blocks.31.mlp.fc1.weight": "model-00001-of-00007.safetensors",
388
+ "vision_model.radio_model.model.blocks.31.mlp.fc1.bias": "model-00001-of-00007.safetensors",
389
+ "vision_model.radio_model.model.blocks.31.attn.qkv.weight": "model-00001-of-00007.safetensors",
390
+ "vision_model.radio_model.model.blocks.31.attn.qkv.bias": "model-00001-of-00007.safetensors",
391
+ "vision_model.radio_model.model.blocks.31.attn.proj.weight": "model-00001-of-00007.safetensors",
392
+ "vision_model.radio_model.model.blocks.31.mlp.fc2.weight": "model-00001-of-00007.safetensors",
393
+ "vision_model.radio_model.model.blocks.31.mlp.fc2.bias": "model-00001-of-00007.safetensors",
394
+ "vision_model.radio_model.model.blocks.31.attn.proj.bias": "model-00001-of-00007.safetensors",
395
+ "mlp1.0.weight": "model-00001-of-00007.safetensors",
396
+ "mlp1.1.weight": "model-00001-of-00007.safetensors",
397
+ "mlp1.3.weight": "model-00001-of-00007.safetensors",
398
+ "language_model.backbone.embeddings.weight": "model-00001-of-00007.safetensors",
399
+ "language_model.backbone.layers.0.norm.weight": "model-00001-of-00007.safetensors",
400
+ "language_model.backbone.layers.0.mixer.norm.weight": "model-00001-of-00007.safetensors",
401
+ "language_model.backbone.layers.0.mixer.D": "model-00001-of-00007.safetensors",
402
+ "language_model.backbone.layers.0.mixer.dt_bias": "model-00001-of-00007.safetensors",
403
+ "language_model.backbone.layers.0.mixer.A_log": "model-00001-of-00007.safetensors",
404
+ "language_model.backbone.layers.0.mixer.in_proj.weight": "model-00001-of-00007.safetensors",
405
+ "language_model.backbone.layers.0.mixer.conv1d.weight": "model-00001-of-00007.safetensors",
406
+ "language_model.backbone.layers.0.mixer.conv1d.bias": "model-00001-of-00007.safetensors",
407
+ "language_model.backbone.layers.0.mixer.out_proj.weight": "model-00001-of-00007.safetensors",
408
+ "language_model.backbone.layers.1.norm.weight": "model-00001-of-00007.safetensors",
409
+ "language_model.backbone.layers.1.mixer.up_proj.weight": "model-00001-of-00007.safetensors",
410
+ "language_model.backbone.layers.1.mixer.down_proj.weight": "model-00001-of-00007.safetensors",
411
+ "language_model.backbone.layers.2.norm.weight": "model-00001-of-00007.safetensors",
412
+ "language_model.backbone.layers.2.mixer.norm.weight": "model-00001-of-00007.safetensors",
413
+ "language_model.backbone.layers.2.mixer.D": "model-00001-of-00007.safetensors",
414
+ "language_model.backbone.layers.2.mixer.dt_bias": "model-00001-of-00007.safetensors",
415
+ "language_model.backbone.layers.2.mixer.A_log": "model-00001-of-00007.safetensors",
416
+ "language_model.backbone.layers.2.mixer.in_proj.weight": "model-00002-of-00007.safetensors",
417
+ "language_model.backbone.layers.2.mixer.conv1d.weight": "model-00002-of-00007.safetensors",
418
+ "language_model.backbone.layers.2.mixer.conv1d.bias": "model-00002-of-00007.safetensors",
419
+ "language_model.backbone.layers.2.mixer.out_proj.weight": "model-00002-of-00007.safetensors",
420
+ "language_model.backbone.layers.3.norm.weight": "model-00002-of-00007.safetensors",
421
+ "language_model.backbone.layers.3.mixer.up_proj.weight": "model-00002-of-00007.safetensors",
422
+ "language_model.backbone.layers.3.mixer.down_proj.weight": "model-00002-of-00007.safetensors",
423
+ "language_model.backbone.layers.4.norm.weight": "model-00002-of-00007.safetensors",
424
+ "language_model.backbone.layers.4.mixer.norm.weight": "model-00002-of-00007.safetensors",
425
+ "language_model.backbone.layers.4.mixer.D": "model-00002-of-00007.safetensors",
426
+ "language_model.backbone.layers.4.mixer.dt_bias": "model-00002-of-00007.safetensors",
427
+ "language_model.backbone.layers.4.mixer.A_log": "model-00002-of-00007.safetensors",
428
+ "language_model.backbone.layers.4.mixer.in_proj.weight": "model-00002-of-00007.safetensors",
429
+ "language_model.backbone.layers.4.mixer.conv1d.weight": "model-00002-of-00007.safetensors",
430
+ "language_model.backbone.layers.4.mixer.conv1d.bias": "model-00002-of-00007.safetensors",
431
+ "language_model.backbone.layers.4.mixer.out_proj.weight": "model-00002-of-00007.safetensors",
432
+ "language_model.backbone.layers.5.norm.weight": "model-00002-of-00007.safetensors",
433
+ "language_model.backbone.layers.5.mixer.up_proj.weight": "model-00002-of-00007.safetensors",
434
+ "language_model.backbone.layers.5.mixer.down_proj.weight": "model-00002-of-00007.safetensors",
435
+ "language_model.backbone.layers.6.norm.weight": "model-00002-of-00007.safetensors",
436
+ "language_model.backbone.layers.6.mixer.norm.weight": "model-00002-of-00007.safetensors",
437
+ "language_model.backbone.layers.6.mixer.D": "model-00002-of-00007.safetensors",
438
+ "language_model.backbone.layers.6.mixer.dt_bias": "model-00002-of-00007.safetensors",
439
+ "language_model.backbone.layers.6.mixer.A_log": "model-00002-of-00007.safetensors",
440
+ "language_model.backbone.layers.6.mixer.in_proj.weight": "model-00002-of-00007.safetensors",
441
+ "language_model.backbone.layers.6.mixer.conv1d.weight": "model-00002-of-00007.safetensors",
442
+ "language_model.backbone.layers.6.mixer.conv1d.bias": "model-00002-of-00007.safetensors",
443
+ "language_model.backbone.layers.6.mixer.out_proj.weight": "model-00002-of-00007.safetensors",
444
+ "language_model.backbone.layers.7.norm.weight": "model-00002-of-00007.safetensors",
445
+ "language_model.backbone.layers.7.mixer.q_proj.weight": "model-00002-of-00007.safetensors",
446
+ "language_model.backbone.layers.7.mixer.k_proj.weight": "model-00002-of-00007.safetensors",
447
+ "language_model.backbone.layers.7.mixer.v_proj.weight": "model-00002-of-00007.safetensors",
448
+ "language_model.backbone.layers.7.mixer.o_proj.weight": "model-00002-of-00007.safetensors",
449
+ "language_model.backbone.layers.8.norm.weight": "model-00002-of-00007.safetensors",
450
+ "language_model.backbone.layers.8.mixer.up_proj.weight": "model-00002-of-00007.safetensors",
451
+ "language_model.backbone.layers.8.mixer.down_proj.weight": "model-00002-of-00007.safetensors",
452
+ "language_model.backbone.layers.9.norm.weight": "model-00002-of-00007.safetensors",
453
+ "language_model.backbone.layers.9.mixer.norm.weight": "model-00002-of-00007.safetensors",
454
+ "language_model.backbone.layers.9.mixer.D": "model-00002-of-00007.safetensors",
455
+ "language_model.backbone.layers.9.mixer.dt_bias": "model-00002-of-00007.safetensors",
456
+ "language_model.backbone.layers.9.mixer.A_log": "model-00002-of-00007.safetensors",
457
+ "language_model.backbone.layers.9.mixer.in_proj.weight": "model-00002-of-00007.safetensors",
458
+ "language_model.backbone.layers.9.mixer.conv1d.weight": "model-00002-of-00007.safetensors",
459
+ "language_model.backbone.layers.9.mixer.conv1d.bias": "model-00002-of-00007.safetensors",
460
+ "language_model.backbone.layers.9.mixer.out_proj.weight": "model-00002-of-00007.safetensors",
461
+ "language_model.backbone.layers.10.norm.weight": "model-00002-of-00007.safetensors",
462
+ "language_model.backbone.layers.10.mixer.up_proj.weight": "model-00002-of-00007.safetensors",
463
+ "language_model.backbone.layers.10.mixer.down_proj.weight": "model-00002-of-00007.safetensors",
464
+ "language_model.backbone.layers.11.norm.weight": "model-00002-of-00007.safetensors",
465
+ "language_model.backbone.layers.11.mixer.norm.weight": "model-00002-of-00007.safetensors",
466
+ "language_model.backbone.layers.11.mixer.D": "model-00002-of-00007.safetensors",
467
+ "language_model.backbone.layers.11.mixer.dt_bias": "model-00002-of-00007.safetensors",
468
+ "language_model.backbone.layers.11.mixer.A_log": "model-00002-of-00007.safetensors",
469
+ "language_model.backbone.layers.11.mixer.in_proj.weight": "model-00002-of-00007.safetensors",
470
+ "language_model.backbone.layers.11.mixer.conv1d.weight": "model-00002-of-00007.safetensors",
471
+ "language_model.backbone.layers.11.mixer.conv1d.bias": "model-00002-of-00007.safetensors",
472
+ "language_model.backbone.layers.11.mixer.out_proj.weight": "model-00002-of-00007.safetensors",
473
+ "language_model.backbone.layers.12.norm.weight": "model-00002-of-00007.safetensors",
474
+ "language_model.backbone.layers.12.mixer.up_proj.weight": "model-00002-of-00007.safetensors",
475
+ "language_model.backbone.layers.12.mixer.down_proj.weight": "model-00002-of-00007.safetensors",
476
+ "language_model.backbone.layers.13.norm.weight": "model-00002-of-00007.safetensors",
477
+ "language_model.backbone.layers.13.mixer.norm.weight": "model-00002-of-00007.safetensors",
478
+ "language_model.backbone.layers.13.mixer.D": "model-00002-of-00007.safetensors",
479
+ "language_model.backbone.layers.13.mixer.dt_bias": "model-00002-of-00007.safetensors",
480
+ "language_model.backbone.layers.13.mixer.A_log": "model-00002-of-00007.safetensors",
481
+ "language_model.backbone.layers.13.mixer.in_proj.weight": "model-00003-of-00007.safetensors",
482
+ "language_model.backbone.layers.13.mixer.conv1d.weight": "model-00003-of-00007.safetensors",
483
+ "language_model.backbone.layers.13.mixer.conv1d.bias": "model-00003-of-00007.safetensors",
484
+ "language_model.backbone.layers.13.mixer.out_proj.weight": "model-00003-of-00007.safetensors",
485
+ "language_model.backbone.layers.14.norm.weight": "model-00003-of-00007.safetensors",
486
+ "language_model.backbone.layers.14.mixer.up_proj.weight": "model-00003-of-00007.safetensors",
487
+ "language_model.backbone.layers.14.mixer.down_proj.weight": "model-00003-of-00007.safetensors",
488
+ "language_model.backbone.layers.15.norm.weight": "model-00003-of-00007.safetensors",
489
+ "language_model.backbone.layers.15.mixer.norm.weight": "model-00003-of-00007.safetensors",
490
+ "language_model.backbone.layers.15.mixer.D": "model-00003-of-00007.safetensors",
491
+ "language_model.backbone.layers.15.mixer.dt_bias": "model-00003-of-00007.safetensors",
492
+ "language_model.backbone.layers.15.mixer.A_log": "model-00003-of-00007.safetensors",
493
+ "language_model.backbone.layers.15.mixer.in_proj.weight": "model-00003-of-00007.safetensors",
494
+ "language_model.backbone.layers.15.mixer.conv1d.weight": "model-00003-of-00007.safetensors",
495
+ "language_model.backbone.layers.15.mixer.conv1d.bias": "model-00003-of-00007.safetensors",
496
+ "language_model.backbone.layers.15.mixer.out_proj.weight": "model-00003-of-00007.safetensors",
497
+ "language_model.backbone.layers.16.norm.weight": "model-00003-of-00007.safetensors",
498
+ "language_model.backbone.layers.16.mixer.q_proj.weight": "model-00003-of-00007.safetensors",
499
+ "language_model.backbone.layers.16.mixer.k_proj.weight": "model-00003-of-00007.safetensors",
500
+ "language_model.backbone.layers.16.mixer.v_proj.weight": "model-00003-of-00007.safetensors",
501
+ "language_model.backbone.layers.16.mixer.o_proj.weight": "model-00003-of-00007.safetensors",
502
+ "language_model.backbone.layers.17.norm.weight": "model-00003-of-00007.safetensors",
503
+ "language_model.backbone.layers.17.mixer.up_proj.weight": "model-00003-of-00007.safetensors",
504
+ "language_model.backbone.layers.17.mixer.down_proj.weight": "model-00003-of-00007.safetensors",
505
+ "language_model.backbone.layers.18.norm.weight": "model-00003-of-00007.safetensors",
506
+ "language_model.backbone.layers.18.mixer.norm.weight": "model-00003-of-00007.safetensors",
507
+ "language_model.backbone.layers.18.mixer.D": "model-00003-of-00007.safetensors",
508
+ "language_model.backbone.layers.18.mixer.dt_bias": "model-00003-of-00007.safetensors",
509
+ "language_model.backbone.layers.18.mixer.A_log": "model-00003-of-00007.safetensors",
510
+ "language_model.backbone.layers.18.mixer.in_proj.weight": "model-00003-of-00007.safetensors",
511
+ "language_model.backbone.layers.18.mixer.conv1d.weight": "model-00003-of-00007.safetensors",
512
+ "language_model.backbone.layers.18.mixer.conv1d.bias": "model-00003-of-00007.safetensors",
513
+ "language_model.backbone.layers.18.mixer.out_proj.weight": "model-00003-of-00007.safetensors",
514
+ "language_model.backbone.layers.19.norm.weight": "model-00003-of-00007.safetensors",
515
+ "language_model.backbone.layers.19.mixer.up_proj.weight": "model-00003-of-00007.safetensors",
516
+ "language_model.backbone.layers.19.mixer.down_proj.weight": "model-00003-of-00007.safetensors",
517
+ "language_model.backbone.layers.20.norm.weight": "model-00003-of-00007.safetensors",
518
+ "language_model.backbone.layers.20.mixer.norm.weight": "model-00003-of-00007.safetensors",
519
+ "language_model.backbone.layers.20.mixer.D": "model-00003-of-00007.safetensors",
520
+ "language_model.backbone.layers.20.mixer.dt_bias": "model-00003-of-00007.safetensors",
521
+ "language_model.backbone.layers.20.mixer.A_log": "model-00003-of-00007.safetensors",
522
+ "language_model.backbone.layers.20.mixer.in_proj.weight": "model-00003-of-00007.safetensors",
523
+ "language_model.backbone.layers.20.mixer.conv1d.weight": "model-00003-of-00007.safetensors",
524
+ "language_model.backbone.layers.20.mixer.conv1d.bias": "model-00003-of-00007.safetensors",
525
+ "language_model.backbone.layers.20.mixer.out_proj.weight": "model-00003-of-00007.safetensors",
526
+ "language_model.backbone.layers.21.norm.weight": "model-00003-of-00007.safetensors",
527
+ "language_model.backbone.layers.21.mixer.up_proj.weight": "model-00003-of-00007.safetensors",
528
+ "language_model.backbone.layers.21.mixer.down_proj.weight": "model-00003-of-00007.safetensors",
529
+ "language_model.backbone.layers.22.norm.weight": "model-00003-of-00007.safetensors",
530
+ "language_model.backbone.layers.22.mixer.norm.weight": "model-00003-of-00007.safetensors",
531
+ "language_model.backbone.layers.22.mixer.D": "model-00003-of-00007.safetensors",
532
+ "language_model.backbone.layers.22.mixer.dt_bias": "model-00003-of-00007.safetensors",
533
+ "language_model.backbone.layers.22.mixer.A_log": "model-00003-of-00007.safetensors",
534
+ "language_model.backbone.layers.22.mixer.in_proj.weight": "model-00003-of-00007.safetensors",
535
+ "language_model.backbone.layers.22.mixer.conv1d.weight": "model-00003-of-00007.safetensors",
536
+ "language_model.backbone.layers.22.mixer.conv1d.bias": "model-00003-of-00007.safetensors",
537
+ "language_model.backbone.layers.22.mixer.out_proj.weight": "model-00003-of-00007.safetensors",
538
+ "language_model.backbone.layers.23.norm.weight": "model-00003-of-00007.safetensors",
539
+ "language_model.backbone.layers.23.mixer.up_proj.weight": "model-00003-of-00007.safetensors",
540
+ "language_model.backbone.layers.23.mixer.down_proj.weight": "model-00003-of-00007.safetensors",
541
+ "language_model.backbone.layers.24.norm.weight": "model-00003-of-00007.safetensors",
542
+ "language_model.backbone.layers.24.mixer.norm.weight": "model-00003-of-00007.safetensors",
543
+ "language_model.backbone.layers.24.mixer.D": "model-00003-of-00007.safetensors",
544
+ "language_model.backbone.layers.24.mixer.dt_bias": "model-00003-of-00007.safetensors",
545
+ "language_model.backbone.layers.24.mixer.A_log": "model-00003-of-00007.safetensors",
546
+ "language_model.backbone.layers.24.mixer.in_proj.weight": "model-00004-of-00007.safetensors",
547
+ "language_model.backbone.layers.24.mixer.conv1d.weight": "model-00004-of-00007.safetensors",
548
+ "language_model.backbone.layers.24.mixer.conv1d.bias": "model-00004-of-00007.safetensors",
549
+ "language_model.backbone.layers.24.mixer.out_proj.weight": "model-00004-of-00007.safetensors",
550
+ "language_model.backbone.layers.25.norm.weight": "model-00004-of-00007.safetensors",
551
+ "language_model.backbone.layers.25.mixer.q_proj.weight": "model-00004-of-00007.safetensors",
552
+ "language_model.backbone.layers.25.mixer.k_proj.weight": "model-00004-of-00007.safetensors",
553
+ "language_model.backbone.layers.25.mixer.v_proj.weight": "model-00004-of-00007.safetensors",
554
+ "language_model.backbone.layers.25.mixer.o_proj.weight": "model-00004-of-00007.safetensors",
555
+ "language_model.backbone.layers.26.norm.weight": "model-00004-of-00007.safetensors",
556
+ "language_model.backbone.layers.26.mixer.up_proj.weight": "model-00004-of-00007.safetensors",
557
+ "language_model.backbone.layers.26.mixer.down_proj.weight": "model-00004-of-00007.safetensors",
558
+ "language_model.backbone.layers.27.norm.weight": "model-00004-of-00007.safetensors",
559
+ "language_model.backbone.layers.27.mixer.norm.weight": "model-00004-of-00007.safetensors",
560
+ "language_model.backbone.layers.27.mixer.D": "model-00004-of-00007.safetensors",
561
+ "language_model.backbone.layers.27.mixer.dt_bias": "model-00004-of-00007.safetensors",
562
+ "language_model.backbone.layers.27.mixer.A_log": "model-00004-of-00007.safetensors",
563
+ "language_model.backbone.layers.27.mixer.in_proj.weight": "model-00004-of-00007.safetensors",
564
+ "language_model.backbone.layers.27.mixer.conv1d.weight": "model-00004-of-00007.safetensors",
565
+ "language_model.backbone.layers.27.mixer.conv1d.bias": "model-00004-of-00007.safetensors",
566
+ "language_model.backbone.layers.27.mixer.out_proj.weight": "model-00004-of-00007.safetensors",
567
+ "language_model.backbone.layers.28.norm.weight": "model-00004-of-00007.safetensors",
568
+ "language_model.backbone.layers.28.mixer.up_proj.weight": "model-00004-of-00007.safetensors",
569
+ "language_model.backbone.layers.28.mixer.down_proj.weight": "model-00004-of-00007.safetensors",
570
+ "language_model.backbone.layers.29.norm.weight": "model-00004-of-00007.safetensors",
571
+ "language_model.backbone.layers.29.mixer.norm.weight": "model-00004-of-00007.safetensors",
572
+ "language_model.backbone.layers.29.mixer.D": "model-00004-of-00007.safetensors",
573
+ "language_model.backbone.layers.29.mixer.dt_bias": "model-00004-of-00007.safetensors",
574
+ "language_model.backbone.layers.29.mixer.A_log": "model-00004-of-00007.safetensors",
575
+ "language_model.backbone.layers.29.mixer.in_proj.weight": "model-00004-of-00007.safetensors",
576
+ "language_model.backbone.layers.29.mixer.conv1d.weight": "model-00004-of-00007.safetensors",
577
+ "language_model.backbone.layers.29.mixer.conv1d.bias": "model-00004-of-00007.safetensors",
578
+ "language_model.backbone.layers.29.mixer.out_proj.weight": "model-00004-of-00007.safetensors",
579
+ "language_model.backbone.layers.30.norm.weight": "model-00004-of-00007.safetensors",
580
+ "language_model.backbone.layers.30.mixer.up_proj.weight": "model-00004-of-00007.safetensors",
581
+ "language_model.backbone.layers.30.mixer.down_proj.weight": "model-00004-of-00007.safetensors",
582
+ "language_model.backbone.layers.31.norm.weight": "model-00004-of-00007.safetensors",
583
+ "language_model.backbone.layers.31.mixer.norm.weight": "model-00004-of-00007.safetensors",
584
+ "language_model.backbone.layers.31.mixer.D": "model-00004-of-00007.safetensors",
585
+ "language_model.backbone.layers.31.mixer.dt_bias": "model-00004-of-00007.safetensors",
586
+ "language_model.backbone.layers.31.mixer.A_log": "model-00004-of-00007.safetensors",
587
+ "language_model.backbone.layers.31.mixer.in_proj.weight": "model-00004-of-00007.safetensors",
588
+ "language_model.backbone.layers.31.mixer.conv1d.weight": "model-00004-of-00007.safetensors",
589
+ "language_model.backbone.layers.31.mixer.conv1d.bias": "model-00004-of-00007.safetensors",
590
+ "language_model.backbone.layers.31.mixer.out_proj.weight": "model-00004-of-00007.safetensors",
591
+ "language_model.backbone.layers.32.norm.weight": "model-00004-of-00007.safetensors",
592
+ "language_model.backbone.layers.32.mixer.up_proj.weight": "model-00004-of-00007.safetensors",
593
+ "language_model.backbone.layers.32.mixer.down_proj.weight": "model-00004-of-00007.safetensors",
594
+ "language_model.backbone.layers.33.norm.weight": "model-00004-of-00007.safetensors",
595
+ "language_model.backbone.layers.33.mixer.norm.weight": "model-00004-of-00007.safetensors",
596
+ "language_model.backbone.layers.33.mixer.D": "model-00004-of-00007.safetensors",
597
+ "language_model.backbone.layers.33.mixer.dt_bias": "model-00004-of-00007.safetensors",
598
+ "language_model.backbone.layers.33.mixer.A_log": "model-00004-of-00007.safetensors",
599
+ "language_model.backbone.layers.33.mixer.in_proj.weight": "model-00004-of-00007.safetensors",
600
+ "language_model.backbone.layers.33.mixer.conv1d.weight": "model-00004-of-00007.safetensors",
601
+ "language_model.backbone.layers.33.mixer.conv1d.bias": "model-00004-of-00007.safetensors",
602
+ "language_model.backbone.layers.33.mixer.out_proj.weight": "model-00004-of-00007.safetensors",
603
+ "language_model.backbone.layers.34.norm.weight": "model-00004-of-00007.safetensors",
604
+ "language_model.backbone.layers.34.mixer.q_proj.weight": "model-00004-of-00007.safetensors",
605
+ "language_model.backbone.layers.34.mixer.k_proj.weight": "model-00004-of-00007.safetensors",
606
+ "language_model.backbone.layers.34.mixer.v_proj.weight": "model-00004-of-00007.safetensors",
607
+ "language_model.backbone.layers.34.mixer.o_proj.weight": "model-00004-of-00007.safetensors",
608
+ "language_model.backbone.layers.35.norm.weight": "model-00004-of-00007.safetensors",
609
+ "language_model.backbone.layers.35.mixer.up_proj.weight": "model-00004-of-00007.safetensors",
610
+ "language_model.backbone.layers.35.mixer.down_proj.weight": "model-00005-of-00007.safetensors",
611
+ "language_model.backbone.layers.36.norm.weight": "model-00005-of-00007.safetensors",
612
+ "language_model.backbone.layers.36.mixer.norm.weight": "model-00005-of-00007.safetensors",
613
+ "language_model.backbone.layers.36.mixer.D": "model-00005-of-00007.safetensors",
614
+ "language_model.backbone.layers.36.mixer.dt_bias": "model-00005-of-00007.safetensors",
615
+ "language_model.backbone.layers.36.mixer.A_log": "model-00005-of-00007.safetensors",
616
+ "language_model.backbone.layers.36.mixer.in_proj.weight": "model-00005-of-00007.safetensors",
617
+ "language_model.backbone.layers.36.mixer.conv1d.weight": "model-00005-of-00007.safetensors",
618
+ "language_model.backbone.layers.36.mixer.conv1d.bias": "model-00005-of-00007.safetensors",
619
+ "language_model.backbone.layers.36.mixer.out_proj.weight": "model-00005-of-00007.safetensors",
620
+ "language_model.backbone.layers.37.norm.weight": "model-00005-of-00007.safetensors",
621
+ "language_model.backbone.layers.37.mixer.up_proj.weight": "model-00005-of-00007.safetensors",
622
+ "language_model.backbone.layers.37.mixer.down_proj.weight": "model-00005-of-00007.safetensors",
623
+ "language_model.backbone.layers.38.norm.weight": "model-00005-of-00007.safetensors",
624
+ "language_model.backbone.layers.38.mixer.norm.weight": "model-00005-of-00007.safetensors",
625
+ "language_model.backbone.layers.38.mixer.D": "model-00005-of-00007.safetensors",
626
+ "language_model.backbone.layers.38.mixer.dt_bias": "model-00005-of-00007.safetensors",
627
+ "language_model.backbone.layers.38.mixer.A_log": "model-00005-of-00007.safetensors",
628
+ "language_model.backbone.layers.38.mixer.in_proj.weight": "model-00005-of-00007.safetensors",
629
+ "language_model.backbone.layers.38.mixer.conv1d.weight": "model-00005-of-00007.safetensors",
630
+ "language_model.backbone.layers.38.mixer.conv1d.bias": "model-00005-of-00007.safetensors",
631
+ "language_model.backbone.layers.38.mixer.out_proj.weight": "model-00005-of-00007.safetensors",
632
+ "language_model.backbone.layers.39.norm.weight": "model-00005-of-00007.safetensors",
633
+ "language_model.backbone.layers.39.mixer.up_proj.weight": "model-00005-of-00007.safetensors",
634
+ "language_model.backbone.layers.39.mixer.down_proj.weight": "model-00005-of-00007.safetensors",
635
+ "language_model.backbone.layers.40.norm.weight": "model-00005-of-00007.safetensors",
636
+ "language_model.backbone.layers.40.mixer.norm.weight": "model-00005-of-00007.safetensors",
637
+ "language_model.backbone.layers.40.mixer.D": "model-00005-of-00007.safetensors",
638
+ "language_model.backbone.layers.40.mixer.dt_bias": "model-00005-of-00007.safetensors",
639
+ "language_model.backbone.layers.40.mixer.A_log": "model-00005-of-00007.safetensors",
640
+ "language_model.backbone.layers.40.mixer.in_proj.weight": "model-00005-of-00007.safetensors",
641
+ "language_model.backbone.layers.40.mixer.conv1d.weight": "model-00005-of-00007.safetensors",
642
+ "language_model.backbone.layers.40.mixer.conv1d.bias": "model-00005-of-00007.safetensors",
643
+ "language_model.backbone.layers.40.mixer.out_proj.weight": "model-00005-of-00007.safetensors",
644
+ "language_model.backbone.layers.41.norm.weight": "model-00005-of-00007.safetensors",
645
+ "language_model.backbone.layers.41.mixer.up_proj.weight": "model-00005-of-00007.safetensors",
646
+ "language_model.backbone.layers.41.mixer.down_proj.weight": "model-00005-of-00007.safetensors",
647
+ "language_model.backbone.layers.42.norm.weight": "model-00005-of-00007.safetensors",
648
+ "language_model.backbone.layers.42.mixer.norm.weight": "model-00005-of-00007.safetensors",
649
+ "language_model.backbone.layers.42.mixer.D": "model-00005-of-00007.safetensors",
650
+ "language_model.backbone.layers.42.mixer.dt_bias": "model-00005-of-00007.safetensors",
651
+ "language_model.backbone.layers.42.mixer.A_log": "model-00005-of-00007.safetensors",
652
+ "language_model.backbone.layers.42.mixer.in_proj.weight": "model-00005-of-00007.safetensors",
653
+ "language_model.backbone.layers.42.mixer.conv1d.weight": "model-00005-of-00007.safetensors",
654
+ "language_model.backbone.layers.42.mixer.conv1d.bias": "model-00005-of-00007.safetensors",
655
+ "language_model.backbone.layers.42.mixer.out_proj.weight": "model-00005-of-00007.safetensors",
656
+ "language_model.backbone.layers.43.norm.weight": "model-00005-of-00007.safetensors",
657
+ "language_model.backbone.layers.43.mixer.q_proj.weight": "model-00005-of-00007.safetensors",
658
+ "language_model.backbone.layers.43.mixer.k_proj.weight": "model-00005-of-00007.safetensors",
659
+ "language_model.backbone.layers.43.mixer.v_proj.weight": "model-00005-of-00007.safetensors",
660
+ "language_model.backbone.layers.43.mixer.o_proj.weight": "model-00005-of-00007.safetensors",
661
+ "language_model.backbone.layers.44.norm.weight": "model-00005-of-00007.safetensors",
662
+ "language_model.backbone.layers.44.mixer.up_proj.weight": "model-00005-of-00007.safetensors",
663
+ "language_model.backbone.layers.44.mixer.down_proj.weight": "model-00005-of-00007.safetensors",
664
+ "language_model.backbone.layers.45.norm.weight": "model-00005-of-00007.safetensors",
665
+ "language_model.backbone.layers.45.mixer.norm.weight": "model-00005-of-00007.safetensors",
666
+ "language_model.backbone.layers.45.mixer.D": "model-00005-of-00007.safetensors",
667
+ "language_model.backbone.layers.45.mixer.dt_bias": "model-00005-of-00007.safetensors",
668
+ "language_model.backbone.layers.45.mixer.A_log": "model-00005-of-00007.safetensors",
669
+ "language_model.backbone.layers.45.mixer.in_proj.weight": "model-00005-of-00007.safetensors",
670
+ "language_model.backbone.layers.45.mixer.conv1d.weight": "model-00005-of-00007.safetensors",
671
+ "language_model.backbone.layers.45.mixer.conv1d.bias": "model-00005-of-00007.safetensors",
672
+ "language_model.backbone.layers.45.mixer.out_proj.weight": "model-00005-of-00007.safetensors",
673
+ "language_model.backbone.layers.46.norm.weight": "model-00005-of-00007.safetensors",
674
+ "language_model.backbone.layers.46.mixer.up_proj.weight": "model-00005-of-00007.safetensors",
675
+ "language_model.backbone.layers.46.mixer.down_proj.weight": "model-00006-of-00007.safetensors",
676
+ "language_model.backbone.layers.47.norm.weight": "model-00006-of-00007.safetensors",
677
+ "language_model.backbone.layers.47.mixer.norm.weight": "model-00006-of-00007.safetensors",
678
+ "language_model.backbone.layers.47.mixer.D": "model-00006-of-00007.safetensors",
679
+ "language_model.backbone.layers.47.mixer.dt_bias": "model-00006-of-00007.safetensors",
680
+ "language_model.backbone.layers.47.mixer.A_log": "model-00006-of-00007.safetensors",
681
+ "language_model.backbone.layers.47.mixer.in_proj.weight": "model-00006-of-00007.safetensors",
682
+ "language_model.backbone.layers.47.mixer.conv1d.weight": "model-00006-of-00007.safetensors",
683
+ "language_model.backbone.layers.47.mixer.conv1d.bias": "model-00006-of-00007.safetensors",
684
+ "language_model.backbone.layers.47.mixer.out_proj.weight": "model-00006-of-00007.safetensors",
685
+ "language_model.backbone.layers.48.norm.weight": "model-00006-of-00007.safetensors",
686
+ "language_model.backbone.layers.48.mixer.up_proj.weight": "model-00006-of-00007.safetensors",
687
+ "language_model.backbone.layers.48.mixer.down_proj.weight": "model-00006-of-00007.safetensors",
688
+ "language_model.backbone.layers.49.norm.weight": "model-00006-of-00007.safetensors",
689
+ "language_model.backbone.layers.49.mixer.norm.weight": "model-00006-of-00007.safetensors",
690
+ "language_model.backbone.layers.49.mixer.D": "model-00006-of-00007.safetensors",
691
+ "language_model.backbone.layers.49.mixer.dt_bias": "model-00006-of-00007.safetensors",
692
+ "language_model.backbone.layers.49.mixer.A_log": "model-00006-of-00007.safetensors",
693
+ "language_model.backbone.layers.49.mixer.in_proj.weight": "model-00006-of-00007.safetensors",
694
+ "language_model.backbone.layers.49.mixer.conv1d.weight": "model-00006-of-00007.safetensors",
695
+ "language_model.backbone.layers.49.mixer.conv1d.bias": "model-00006-of-00007.safetensors",
696
+ "language_model.backbone.layers.49.mixer.out_proj.weight": "model-00006-of-00007.safetensors",
697
+ "language_model.backbone.layers.50.norm.weight": "model-00006-of-00007.safetensors",
698
+ "language_model.backbone.layers.50.mixer.up_proj.weight": "model-00006-of-00007.safetensors",
699
+ "language_model.backbone.layers.50.mixer.down_proj.weight": "model-00006-of-00007.safetensors",
700
+ "language_model.backbone.layers.51.norm.weight": "model-00006-of-00007.safetensors",
701
+ "language_model.backbone.layers.51.mixer.norm.weight": "model-00006-of-00007.safetensors",
702
+ "language_model.backbone.layers.51.mixer.D": "model-00006-of-00007.safetensors",
703
+ "language_model.backbone.layers.51.mixer.dt_bias": "model-00006-of-00007.safetensors",
704
+ "language_model.backbone.layers.51.mixer.A_log": "model-00006-of-00007.safetensors",
705
+ "language_model.backbone.layers.51.mixer.in_proj.weight": "model-00006-of-00007.safetensors",
706
+ "language_model.backbone.layers.51.mixer.conv1d.weight": "model-00006-of-00007.safetensors",
707
+ "language_model.backbone.layers.51.mixer.conv1d.bias": "model-00006-of-00007.safetensors",
708
+ "language_model.backbone.layers.51.mixer.out_proj.weight": "model-00006-of-00007.safetensors",
709
+ "language_model.backbone.layers.52.norm.weight": "model-00006-of-00007.safetensors",
710
+ "language_model.backbone.layers.52.mixer.q_proj.weight": "model-00006-of-00007.safetensors",
711
+ "language_model.backbone.layers.52.mixer.k_proj.weight": "model-00006-of-00007.safetensors",
712
+ "language_model.backbone.layers.52.mixer.v_proj.weight": "model-00006-of-00007.safetensors",
713
+ "language_model.backbone.layers.52.mixer.o_proj.weight": "model-00006-of-00007.safetensors",
714
+ "language_model.backbone.layers.53.norm.weight": "model-00006-of-00007.safetensors",
715
+ "language_model.backbone.layers.53.mixer.up_proj.weight": "model-00006-of-00007.safetensors",
716
+ "language_model.backbone.layers.53.mixer.down_proj.weight": "model-00006-of-00007.safetensors",
717
+ "language_model.backbone.layers.54.norm.weight": "model-00006-of-00007.safetensors",
718
+ "language_model.backbone.layers.54.mixer.norm.weight": "model-00006-of-00007.safetensors",
719
+ "language_model.backbone.layers.54.mixer.D": "model-00006-of-00007.safetensors",
720
+ "language_model.backbone.layers.54.mixer.dt_bias": "model-00006-of-00007.safetensors",
721
+ "language_model.backbone.layers.54.mixer.A_log": "model-00006-of-00007.safetensors",
722
+ "language_model.backbone.layers.54.mixer.in_proj.weight": "model-00006-of-00007.safetensors",
723
+ "language_model.backbone.layers.54.mixer.conv1d.weight": "model-00006-of-00007.safetensors",
724
+ "language_model.backbone.layers.54.mixer.conv1d.bias": "model-00006-of-00007.safetensors",
725
+ "language_model.backbone.layers.54.mixer.out_proj.weight": "model-00006-of-00007.safetensors",
726
+ "language_model.backbone.layers.55.norm.weight": "model-00006-of-00007.safetensors",
727
+ "language_model.backbone.layers.55.mixer.up_proj.weight": "model-00006-of-00007.safetensors",
728
+ "language_model.backbone.layers.55.mixer.down_proj.weight": "model-00006-of-00007.safetensors",
729
+ "language_model.backbone.layers.56.norm.weight": "model-00006-of-00007.safetensors",
730
+ "language_model.backbone.layers.56.mixer.norm.weight": "model-00006-of-00007.safetensors",
731
+ "language_model.backbone.layers.56.mixer.D": "model-00006-of-00007.safetensors",
732
+ "language_model.backbone.layers.56.mixer.dt_bias": "model-00006-of-00007.safetensors",
733
+ "language_model.backbone.layers.56.mixer.A_log": "model-00006-of-00007.safetensors",
734
+ "language_model.backbone.layers.56.mixer.in_proj.weight": "model-00006-of-00007.safetensors",
735
+ "language_model.backbone.layers.56.mixer.conv1d.weight": "model-00006-of-00007.safetensors",
736
+ "language_model.backbone.layers.56.mixer.conv1d.bias": "model-00006-of-00007.safetensors",
737
+ "language_model.backbone.layers.56.mixer.out_proj.weight": "model-00006-of-00007.safetensors",
738
+ "language_model.backbone.layers.57.norm.weight": "model-00006-of-00007.safetensors",
739
+ "language_model.backbone.layers.57.mixer.up_proj.weight": "model-00006-of-00007.safetensors",
740
+ "language_model.backbone.layers.57.mixer.down_proj.weight": "model-00007-of-00007.safetensors",
741
+ "language_model.backbone.layers.58.norm.weight": "model-00007-of-00007.safetensors",
742
+ "language_model.backbone.layers.58.mixer.norm.weight": "model-00007-of-00007.safetensors",
743
+ "language_model.backbone.layers.58.mixer.D": "model-00007-of-00007.safetensors",
744
+ "language_model.backbone.layers.58.mixer.dt_bias": "model-00007-of-00007.safetensors",
745
+ "language_model.backbone.layers.58.mixer.A_log": "model-00007-of-00007.safetensors",
746
+ "language_model.backbone.layers.58.mixer.in_proj.weight": "model-00007-of-00007.safetensors",
747
+ "language_model.backbone.layers.58.mixer.conv1d.weight": "model-00007-of-00007.safetensors",
748
+ "language_model.backbone.layers.58.mixer.conv1d.bias": "model-00007-of-00007.safetensors",
749
+ "language_model.backbone.layers.58.mixer.out_proj.weight": "model-00007-of-00007.safetensors",
750
+ "language_model.backbone.layers.59.norm.weight": "model-00007-of-00007.safetensors",
751
+ "language_model.backbone.layers.59.mixer.up_proj.weight": "model-00007-of-00007.safetensors",
752
+ "language_model.backbone.layers.59.mixer.down_proj.weight": "model-00007-of-00007.safetensors",
753
+ "language_model.backbone.layers.60.norm.weight": "model-00007-of-00007.safetensors",
754
+ "language_model.backbone.layers.60.mixer.norm.weight": "model-00007-of-00007.safetensors",
755
+ "language_model.backbone.layers.60.mixer.D": "model-00007-of-00007.safetensors",
756
+ "language_model.backbone.layers.60.mixer.dt_bias": "model-00007-of-00007.safetensors",
757
+ "language_model.backbone.layers.60.mixer.A_log": "model-00007-of-00007.safetensors",
758
+ "language_model.backbone.layers.60.mixer.in_proj.weight": "model-00007-of-00007.safetensors",
759
+ "language_model.backbone.layers.60.mixer.conv1d.weight": "model-00007-of-00007.safetensors",
760
+ "language_model.backbone.layers.60.mixer.conv1d.bias": "model-00007-of-00007.safetensors",
761
+ "language_model.backbone.layers.60.mixer.out_proj.weight": "model-00007-of-00007.safetensors",
762
+ "language_model.backbone.layers.61.norm.weight": "model-00007-of-00007.safetensors",
763
+ "language_model.backbone.layers.61.mixer.up_proj.weight": "model-00007-of-00007.safetensors",
764
+ "language_model.backbone.layers.61.mixer.down_proj.weight": "model-00007-of-00007.safetensors",
765
+ "language_model.backbone.norm_f.weight": "model-00007-of-00007.safetensors",
766
+ "language_model.lm_head.weight": "model-00007-of-00007.safetensors"
767
+ }
768
+ }
modeling.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import os
15
+ import warnings
16
+ from typing import List, Optional, Tuple, Union
17
+
18
+ import torch
19
+ import transformers
20
+ from torch import nn
21
+ from torch.nn import CrossEntropyLoss
22
+ from transformers import AutoModel, AutoModelForCausalLM, GenerationConfig
23
+ from transformers.modeling_outputs import CausalLMOutputWithPast
24
+ from transformers.modeling_utils import PreTrainedModel
25
+ from transformers.utils import logging
26
+
27
+ from .configuration import NemotronH_Nano_VL_V2_Config
28
+ from .modeling_nemotron_h import NemotronHForCausalLM
29
+ from .evs import EfficientVideoSampling
30
+
31
+ logger = logging.get_logger(__name__)
32
+
33
+
34
+ """
35
+ The following code is adapted from the
36
+ https://huggingface.co/OpenGVLab/InternVL2-Llama3-76B/blob/main/modeling_internvl_chat.py repository
37
+
38
+ The chat function is adapted to handle NVLM 1-D tile-tagging design for dynamic high-resolution images.
39
+ """
40
+
41
+
42
+ class SquaredReLU(nn.Module):
43
+ def forward(self, x):
44
+ return torch.pow(torch.nn.functional.relu(x), 2)
45
+
46
+
47
+ class RMSNorm(nn.Module):
48
+ def __init__(self, hidden_size, eps=1e-5):
49
+ super().__init__()
50
+ self.weight = nn.Parameter(torch.ones(hidden_size))
51
+ self.eps = eps
52
+
53
+ def forward(self, hidden_states):
54
+ input_dtype = hidden_states.dtype
55
+ hidden_states = hidden_states.to(torch.float32)
56
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
57
+ hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
58
+ return (self.weight.to(torch.float32) * hidden_states).to(input_dtype)
59
+
60
+
61
+ def version_cmp(v1, v2, op='eq'):
62
+ import operator
63
+
64
+ from packaging import version
65
+ op_func = getattr(operator, op)
66
+ return op_func(version.parse(v1), version.parse(v2))
67
+
68
+
69
+ class NemotronH_Nano_VL_V2(PreTrainedModel):
70
+ config_class = NemotronH_Nano_VL_V2_Config
71
+ main_input_name = 'pixel_values'
72
+ _supports_flash_attn_2 = True
73
+ _no_split_modules = ['NemotronHBlock']
74
+
75
+ def __init__(self, config: NemotronH_Nano_VL_V2_Config):
76
+ super().__init__(config)
77
+
78
+ assert version_cmp(transformers.__version__, '4.36.2', 'ge')
79
+ image_size = config.force_image_size
80
+ patch_size = config.patch_size
81
+ self.patch_size = patch_size
82
+ self.template = config.template
83
+ self.num_image_token = int((image_size // patch_size) ** 2 * (config.downsample_ratio ** 2))
84
+ self.downsample_ratio = config.downsample_ratio
85
+ self.ps_version = config.ps_version
86
+ self.image_tag_type = config.image_tag_type
87
+ self.img_context_token_id = config.img_context_token_id
88
+ self.video_context_token_id = config.video_context_token_id
89
+
90
+ logger.info(f'num_image_token: {self.num_image_token}')
91
+ logger.info(f'ps_version: {self.ps_version}')
92
+
93
+ self.language_model = AutoModelForCausalLM.from_config(config.llm_config, trust_remote_code=True)
94
+ self.vision_model = AutoModel.from_config(config.vision_config, trust_remote_code=True)
95
+ self.vision_model.model._initialize_weights = self.vision_model.model._init_weights # WAR for transformers issue 38358
96
+ self.vision_model.radio_model.make_preprocessor_external()
97
+ self.vision_model = self.vision_model.to(self.language_model.config.torch_dtype)
98
+
99
+ self.drop_vision_class_token = True
100
+
101
+ # Construct the vision projection.
102
+ # Default
103
+ vit_hidden_size = config.vit_hidden_size
104
+ vision_projection_hidden_size = config.projector_hidden_size
105
+ llm_hidden_size = config.llm_config.hidden_size
106
+
107
+ self.video_pruning_rate = config.video_pruning_rate
108
+
109
+ self.mlp1 = nn.Sequential(
110
+ RMSNorm(vit_hidden_size * int(1 / self.downsample_ratio) ** 2, eps=1e-5),
111
+ nn.Linear(vit_hidden_size * int(1 / self.downsample_ratio) ** 2, vision_projection_hidden_size, bias=False),
112
+ SquaredReLU(),
113
+ nn.Linear(vision_projection_hidden_size, llm_hidden_size, bias=False)
114
+ )
115
+ self.mlp1 = self.mlp1.to(self.language_model.config.torch_dtype)
116
+
117
+ def forward(
118
+ self,
119
+ pixel_values: torch.FloatTensor,
120
+ input_ids: torch.LongTensor = None,
121
+ attention_mask: Optional[torch.Tensor] = None,
122
+ position_ids: Optional[torch.LongTensor] = None,
123
+ image_flags: Optional[torch.LongTensor] = None,
124
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
125
+ labels: Optional[torch.LongTensor] = None,
126
+ inputs_embeds = None,
127
+ use_cache: Optional[bool] = None,
128
+ output_attentions: Optional[bool] = None,
129
+ output_hidden_states: Optional[bool] = None,
130
+ return_dict: Optional[bool] = None,
131
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
132
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
133
+
134
+ if inputs_embeds is None:
135
+ inputs_embeds = self.language_model.get_input_embeddings()(input_ids)
136
+
137
+ image_flags = image_flags.squeeze(-1)
138
+
139
+ B, N, C = inputs_embeds.shape
140
+ inputs_embeds = inputs_embeds.reshape(B * N, C)
141
+
142
+ input_ids = input_ids.reshape(B * N)
143
+ selected = (input_ids == self.img_context_token_id)
144
+
145
+ vit_batch_size = pixel_values.shape[0]
146
+ vit_embeds = self.extract_feature(pixel_values)
147
+
148
+ del pixel_values
149
+
150
+ if torch.distributed.get_rank() == 0:
151
+ print(f'dynamic ViT batch size: {vit_batch_size}, images per sample: {vit_batch_size / B}, dynamic token length: {N}')
152
+
153
+ vit_embeds = vit_embeds[image_flags == 1]
154
+ try:
155
+ inputs_embeds[selected] = inputs_embeds[selected] * 0.0 + vit_embeds.reshape(-1, C)
156
+ except Exception as e:
157
+ vit_embeds = vit_embeds.reshape(-1, C)
158
+ print(f'warning: {e}, inputs_embeds[selected].shape={inputs_embeds[selected].shape}, '
159
+ f'vit_embeds.shape={vit_embeds.shape}')
160
+ n_token = selected.sum()
161
+ inputs_embeds[selected] = inputs_embeds[selected] * 0.0 + vit_embeds[:n_token]
162
+
163
+ del vit_embeds
164
+
165
+ inputs_embeds = inputs_embeds.reshape(B, N, C)
166
+
167
+ outputs = self.language_model(
168
+ inputs_embeds=inputs_embeds,
169
+ attention_mask=attention_mask,
170
+ position_ids=position_ids,
171
+ past_key_values=past_key_values,
172
+ use_cache=use_cache,
173
+ output_attentions=output_attentions,
174
+ output_hidden_states=output_hidden_states,
175
+ return_dict=return_dict,
176
+ )
177
+ logits = outputs.logits
178
+
179
+ loss = None
180
+ if labels is not None:
181
+ # Shift so that tokens < n predict n
182
+ shift_logits = logits[..., :-1, :].contiguous()
183
+ shift_labels = labels[..., 1:].contiguous()
184
+ # Flatten the tokens
185
+ loss_fct = CrossEntropyLoss()
186
+ shift_logits = shift_logits.view(-1, self.language_model.config.vocab_size)
187
+ shift_labels = shift_labels.view(-1)
188
+ # Enable model parallelism
189
+ shift_labels = shift_labels.to(shift_logits.device)
190
+ loss = loss_fct(shift_logits, shift_labels)
191
+
192
+ if not return_dict:
193
+ output = (logits,) + outputs[1:]
194
+ return (loss,) + output if loss is not None else output
195
+
196
+ return CausalLMOutputWithPast(
197
+ loss=loss,
198
+ logits=logits,
199
+ past_key_values=outputs.past_key_values,
200
+ hidden_states=outputs.hidden_states,
201
+ attentions=outputs.attentions,
202
+ )
203
+
204
+ def pixel_shuffle(self, x, scale_factor=0.5):
205
+ n, w, h, c = x.size()
206
+ # N, W, H, C --> N, W, H * scale, C // scale
207
+ x = x.view(n, w, int(h * scale_factor), int(c / scale_factor))
208
+ # N, W, H * scale, C // scale --> N, H * scale, W, C // scale
209
+ x = x.permute(0, 2, 1, 3).contiguous()
210
+ # N, H * scale, W, C // scale --> N, H * scale, W * scale, C // (scale ** 2)
211
+ x = x.view(n, int(h * scale_factor), int(w * scale_factor),
212
+ int(c / (scale_factor * scale_factor)))
213
+ if self.ps_version == 'v1':
214
+ warnings.warn("In ps_version 'v1', the height and width have not been swapped back, "
215
+ 'which results in a transposed image.')
216
+ else:
217
+ x = x.permute(0, 2, 1, 3).contiguous()
218
+ return x
219
+
220
+ def extract_feature(self, pixel_values):
221
+ vit_embeds = self.vision_model(pixel_values).features
222
+ vit_embeds = vit_embeds.to(dtype=torch.bfloat16)
223
+ h = w = int(vit_embeds.shape[1] ** 0.5)
224
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], h, w, -1)
225
+ vit_embeds = self.pixel_shuffle(vit_embeds, scale_factor=self.downsample_ratio)
226
+ vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], -1, vit_embeds.shape[-1])
227
+ vit_embeds = self.mlp1(vit_embeds)
228
+ return vit_embeds
229
+
230
+ @torch.no_grad()
231
+ def generate(
232
+ self,
233
+ pixel_values: Optional[torch.FloatTensor] = None,
234
+ pixel_values_videos: Optional[torch.FloatTensor] = None,
235
+ input_ids: Optional[torch.FloatTensor] = None,
236
+ attention_mask: Optional[torch.LongTensor] = None,
237
+ generation_config: Optional[GenerationConfig] = None,
238
+ output_hidden_states: Optional[bool] = None,
239
+ return_dict: Optional[bool] = None,
240
+ **generate_kwargs,
241
+ ) -> torch.LongTensor:
242
+ assert self.img_context_token_id is not None
243
+ if pixel_values is not None or pixel_values_videos is not None:
244
+ image_vit_embeds, video_vit_embeds = None, None
245
+ if pixel_values is not None:
246
+ pixel_values = pixel_values.to(dtype=self.vision_model.config.torch_dtype)
247
+ image_vit_embeds = self.extract_feature(pixel_values)
248
+ if pixel_values_videos is not None:
249
+ pixel_values_videos = pixel_values_videos.to(dtype=self.vision_model.config.torch_dtype)
250
+ video_vit_embeds = self.extract_feature(pixel_values_videos)
251
+ inputs_embeds = self.language_model.get_input_embeddings()(input_ids)
252
+ B, N, C = inputs_embeds.shape
253
+ inputs_embeds = inputs_embeds.reshape(B * N, C)
254
+ input_ids_copy = input_ids.reshape(B * N)
255
+ if image_vit_embeds is not None:
256
+ image_mask = (input_ids_copy == self.img_context_token_id)
257
+ assert image_mask.sum() != 0
258
+ inputs_embeds[image_mask] = image_vit_embeds.reshape(-1, C).to(inputs_embeds.device, inputs_embeds.dtype)
259
+ if video_vit_embeds is not None:
260
+ if B > 1:
261
+ raise NotImplementedError("Video is not supported for batch size > 1")
262
+ video_mask = (input_ids_copy == self.video_context_token_id)
263
+ assert video_mask.sum() != 0
264
+ inputs_embeds[video_mask] = video_vit_embeds.reshape(-1, C).to(inputs_embeds.device, inputs_embeds.dtype)
265
+ if video_vit_embeds is not None and self.video_pruning_rate > 0: # EVS
266
+ h = w = int(video_vit_embeds.shape[1] ** 0.5) # assumption here (and everywhere else) is that shape is square
267
+ evs_mask = EfficientVideoSampling.compute_retention_mask(
268
+ video_embeds=video_vit_embeds,
269
+ thw=(video_vit_embeds.shape[0], h, w),
270
+ spatial_merge_size=1, # we already work on vision embeddings, so no downsampling to follow
271
+ q=self.video_pruning_rate,
272
+ )
273
+ print(f"pruning rate: {self.video_pruning_rate}, EVS mask: {evs_mask.sum().item()} tokens retained out of {evs_mask.numel()} total video tokens ({evs_mask.sum().item() / evs_mask.numel() * 100:.2f}%)")
274
+
275
+ retention_mask = torch.ones_like(input_ids_copy, dtype=torch.bool)
276
+ retention_mask[video_mask] = evs_mask.view(-1)
277
+ inputs_embeds = inputs_embeds[retention_mask].unsqueeze(0) # adding batch=1
278
+ if attention_mask is not None:
279
+ attention_mask = attention_mask[:, retention_mask].contiguous()
280
+ if input_ids is not None:
281
+ input_ids = input_ids[:, retention_mask].contiguous()
282
+ else:
283
+ inputs_embeds = inputs_embeds.reshape(B, N, C)
284
+ else:
285
+ inputs_embeds = self.language_model.get_input_embeddings()(input_ids)
286
+ # print(f"DEBUG: input_ids shape: {input_ids.shape}")
287
+ # print(f"DEBUG: input text: {self._tokenizer.decode(input_ids[0])}")
288
+ outputs = self.language_model.generate(
289
+ input_ids=input_ids,
290
+ inputs_embeds=inputs_embeds,
291
+ attention_mask=attention_mask,
292
+ generation_config=generation_config,
293
+ output_hidden_states=output_hidden_states,
294
+ use_cache=True,
295
+ # return_dict_in_generate=True,
296
+ # output_scores=True,
297
+ **generate_kwargs,
298
+ )
299
+
300
+ return outputs
modeling_nemotron_h.py ADDED
@@ -0,0 +1,1632 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import math
15
+ from dataclasses import dataclass
16
+ from typing import Any, Dict, Optional, Tuple, Union
17
+
18
+ import torch
19
+ import torch.utils.checkpoint
20
+ from torch import nn
21
+ from torch.nn import CrossEntropyLoss
22
+
23
+ from transformers.activations import ACT2FN
24
+ from transformers.cache_utils import DynamicCache # we need __iter__ and __len__ of pkv
25
+ from transformers.generation import GenerationMixin
26
+ from transformers.modeling_attn_mask_utils import (
27
+ AttentionMaskConverter,
28
+ )
29
+ from transformers.modeling_utils import PreTrainedModel
30
+ from transformers.utils import (
31
+ ModelOutput,
32
+ add_code_sample_docstrings,
33
+ add_start_docstrings,
34
+ add_start_docstrings_to_model_forward,
35
+ logging,
36
+ )
37
+ from transformers.utils.import_utils import (
38
+ is_causal_conv1d_available,
39
+ is_flash_attn_2_available,
40
+ is_flash_attn_greater_or_equal_2_10,
41
+ is_mamba_2_ssm_available,
42
+ )
43
+ from .configuration_nemotron_h import NemotronHConfig
44
+
45
+
46
+ logger = logging.get_logger(__name__)
47
+
48
+
49
+ # Copied from transformers.models.mamba.modeling_mamba2.modeling_mamba2.py with MAMBA2->NEMOTRONH,Mamba2->NemotronH
50
+ # For Mamba2 components Mamba2->NemotronHMamba2
51
+ if is_mamba_2_ssm_available():
52
+ from mamba_ssm.ops.triton.selective_state_update import selective_state_update
53
+ from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined
54
+ else:
55
+ mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined, selective_state_update = None, None, None
56
+
57
+ try:
58
+ #from mamba_ssm.ops.triton.layernorm_gated import RMSNorm as RMSNormGated
59
+ from mamba_ssm.ops.triton.layernorm_gated import rmsnorm_fn
60
+ except ImportError:
61
+ raise ImportError("mamba-ssm is required by the Mamba model but cannot be imported")
62
+
63
+ if is_causal_conv1d_available():
64
+ from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
65
+ else:
66
+ causal_conv1d_update, causal_conv1d_fn = None, None
67
+
68
+ if is_flash_attn_2_available():
69
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
70
+
71
+ is_fast_path_available = all(
72
+ (
73
+ selective_state_update,
74
+ mamba_chunk_scan_combined,
75
+ mamba_split_conv1d_scan_combined,
76
+ causal_conv1d_fn,
77
+ causal_conv1d_update,
78
+ )
79
+ )
80
+
81
+
82
+ _CHECKPOINT_FOR_DOC = "nvidia/Nemotron-H-56B-Base-8K"
83
+ _CONFIG_FOR_DOC = "NemotronHConfig"
84
+
85
+
86
+ # Helper methods for segment sum computation
87
+
88
+
89
+ def pad_tensor_by_size(input_tensor: torch.Tensor, pad_size: int):
90
+ """
91
+ Padding x tensor with `pad_size` on the seq_len dim (dim=1)
92
+
93
+ Assumes that we only have tensors of either size 4 or 3
94
+ """
95
+ pad_shape = (0, 0, 0, 0, 0, pad_size, 0, 0) if len(input_tensor.shape) == 4 else (0, 0, 0, pad_size, 0, 0)
96
+
97
+ return torch.nn.functional.pad(input_tensor, pad_shape, mode="constant", value=0)
98
+
99
+
100
+ def reshape_into_chunks(input_tensor, pad_size, chunk_size):
101
+ """
102
+ Padding input_tensor with `pad_size` on the seq_len dim (dim=1) and
103
+ simultaneously splitting it into chunk sequences.
104
+
105
+ Assumes that we only have tensors of either size 4 or 3
106
+ """
107
+ # [bsz, seq_len, ...] -> [bsz, seq_len multiple of chunk_size, ...]
108
+ input_tensor = pad_tensor_by_size(input_tensor, pad_size)
109
+
110
+ if len(input_tensor.shape) == 3:
111
+ # [bsz, seq_len multiple of chunk_size, num_heads] -> [bsz, -1, chunk_size, num_heads]
112
+ return input_tensor.reshape(input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2])
113
+ else:
114
+ # [bsz, seq_len multiple of chunk_size, num_heads, head_dim or state_size] -> [bsz, -1, chunk_size, num_heads, head_dim or state_size]
115
+ return input_tensor.reshape(
116
+ input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2], input_tensor.shape[3]
117
+ )
118
+
119
+
120
+ def segment_sum(input_tensor):
121
+ """
122
+ More stable segment sum calculation. Uses cumulative sums and masking instead of direct subtractions.
123
+ """
124
+ chunk_size = input_tensor.size(-1)
125
+ # 1. expand input tensor to have an additional dimension and repeat along that dimension
126
+ # [..., chunk_size] -> [..., chunk_size, chunk_size]
127
+ input_tensor = input_tensor[..., None].expand(*input_tensor.size(), chunk_size)
128
+ # 2. create a lower triangular mask with the diagonal set to 0 to 0 out elements above diag
129
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=-1)
130
+ input_tensor = input_tensor.masked_fill(~mask, 0)
131
+ # 3. compute actual cumsum
132
+ tensor_segsum = torch.cumsum(input_tensor, dim=-2)
133
+
134
+ # 4. apply mask to keep only the lower triangular part of the cumulative sum result (incl diagonal this time)
135
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=0)
136
+ tensor_segsum = tensor_segsum.masked_fill(~mask, -torch.inf)
137
+ return tensor_segsum
138
+
139
+
140
+ def apply_mask_to_padding_states(hidden_states, attention_mask):
141
+ """
142
+ Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66
143
+ """
144
+ if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
145
+ dtype = hidden_states.dtype
146
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
147
+
148
+ return hidden_states
149
+
150
+ # Copied from https://github.com/huggingface/transformers/blob/main/src/transformers/models/jamba/modeling_jamba.py
151
+ class HybridMambaAttentionDynamicCache(DynamicCache):
152
+ """
153
+ A dynamic cache that can handle both the attention cache (which has a seq_len dimension) and the mamba cache
154
+ (which has a constant shape regardless of seq_len).
155
+
156
+ This cache has two sets of lists of tensors: `key_cache` and `value_cache` for attention cache and `conv_states`
157
+ and `ssm_states` for mamba cache. Each of these lists has `num_layers` tensors. The expected shape for each tensor
158
+ For attention layers, `key_cache` and `value_cache` have a shape of `(batch_size, num_heads, seq_len, head_dim)`,
159
+ while `conv_states` and `ssm_states` have a shape of `(batch_size, 0)` (empty tensors).
160
+ For mamba layers, `key_cache` and `value_cache` have a shape of `(batch_size, 0)` (empty tensors),
161
+ while `conv_states` represents the convolution state and has a shape of `(batch_size, d_inner, d_conv)`,
162
+ and `ssm_states` represents the ssm state and has a shape of `(batch_size, d_inner, d_state)`.
163
+ """
164
+
165
+ def __init__(self, config, batch_size, dtype=torch.float16, device=None):
166
+ super().__init__()
167
+ self.dtype = dtype
168
+ self.hybrid_override_pattern = config.hybrid_override_pattern
169
+ self.has_previous_state = False # only used by mamba
170
+ #intermediate_size = config.expand * config.hidden_size
171
+ intermediate_size = config.mamba_num_heads * config.mamba_head_dim
172
+ ssm_state_size = config.ssm_state_size
173
+ conv_kernel_size = config.conv_kernel
174
+ self.conv_states = []
175
+ self.ssm_states = []
176
+ self.transformer_layers = []
177
+ for i in range(config.num_hidden_layers):
178
+ if self.hybrid_override_pattern[i] == "M":
179
+ # Mamba layer
180
+ self.conv_states += [
181
+ torch.zeros(batch_size, intermediate_size, conv_kernel_size, device=device, dtype=dtype)
182
+ ]
183
+ self.ssm_states += [
184
+ torch.zeros(batch_size, intermediate_size, ssm_state_size, device=device, dtype=torch.float32)
185
+ ]
186
+ else:
187
+ # Attention or MLP layer
188
+ self.conv_states += [torch.tensor([[]] * batch_size, device=device)]
189
+ self.ssm_states += [torch.tensor([[]] * batch_size, device=device)]
190
+ self.transformer_layers.append(i)
191
+
192
+ self.key_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
193
+ self.value_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
194
+
195
+ def update(
196
+ self,
197
+ key_states: torch.Tensor,
198
+ value_states: torch.Tensor,
199
+ layer_idx: int,
200
+ cache_kwargs: Optional[Dict[str, Any]] = None,
201
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
202
+ # Update the cache
203
+ if self.key_cache[layer_idx].shape[-1] == 0:
204
+ self.key_cache[layer_idx] = key_states
205
+ self.value_cache[layer_idx] = value_states
206
+ else:
207
+ self.key_cache[layer_idx] = torch.cat([self.key_cache[layer_idx], key_states], dim=2)
208
+ self.value_cache[layer_idx] = torch.cat([self.value_cache[layer_idx], value_states], dim=2)
209
+
210
+ return self.key_cache[layer_idx], self.value_cache[layer_idx]
211
+
212
+ def reorder_cache(self, beam_idx: torch.LongTensor):
213
+ """Reorders the cache for beam search, given the selected beam indices."""
214
+ for layer_idx in range(len(self.key_cache)):
215
+ device = self.key_cache[layer_idx].device
216
+ self.key_cache[layer_idx] = self.key_cache[layer_idx].index_select(0, beam_idx.to(device))
217
+ device = self.value_cache[layer_idx].device
218
+ self.value_cache[layer_idx] = self.value_cache[layer_idx].index_select(0, beam_idx.to(device))
219
+
220
+ device = self.conv_states[layer_idx].device
221
+ self.conv_states[layer_idx] = self.conv_states[layer_idx].index_select(0, beam_idx.to(device))
222
+ device = self.ssm_states[layer_idx].device
223
+ self.ssm_states[layer_idx] = self.ssm_states[layer_idx].index_select(0, beam_idx.to(device))
224
+
225
+ def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
226
+ """Returns the sequence length of the cached states. A layer index can be optionally passed."""
227
+ # take any layer that contains cache and not empty tensor
228
+ layer_idx = self.transformer_layers[0] if layer_idx not in self.transformer_layers else layer_idx
229
+ if len(self.key_cache) <= layer_idx:
230
+ return 0
231
+ return self.key_cache[layer_idx].shape[-2]
232
+
233
+ def to_legacy_cache(self) -> Tuple[Tuple[torch.Tensor], Tuple[torch.Tensor]]:
234
+ raise NotImplementedError("HybridMambaAttentionDynamicCache does not have a legacy cache equivalent.")
235
+
236
+ @classmethod
237
+ def from_legacy_cache(cls, past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None) -> "DynamicCache":
238
+ raise NotImplementedError("HybridMambaAttentionDynamicCache does not have a legacy cache equivalent.")
239
+
240
+ # Copied from modeling_mamba2.py
241
+ def update_conv_state(
242
+ self, layer_idx: int, new_conv_state: torch.Tensor, cache_init: bool = False
243
+ ) -> torch.Tensor:
244
+ if cache_init:
245
+ self.conv_states[layer_idx] = new_conv_state.to(self.conv_states.device)
246
+ else:
247
+ self.conv_states[layer_idx] = self.conv_states[layer_idx].roll(shifts=-1, dims=-1)
248
+ self.conv_states[layer_idx][:, :, -1] = new_conv_state[:, 0, :].to(self.conv_states.device)
249
+ return self.conv_states[layer_idx]
250
+
251
+ def update_ssm_state(self, layer_idx: int, new_ssm_state: torch.Tensor):
252
+ self.ssm_states[layer_idx] = new_ssm_state.to(self.ssm_states.device)
253
+ return self.ssm_states[layer_idx]
254
+
255
+ def reset(self):
256
+ self.conv_states.zero_()
257
+ self.ssm_states.zero_()
258
+
259
+ class MambaRMSNormGated(torch.nn.Module):
260
+ def __init__(self, hidden_size, group_size, eps=1e-5):
261
+ super().__init__()
262
+ self.weight = nn.Parameter(torch.ones(hidden_size))
263
+ self.variance_epsilon = eps
264
+ self.group_size = group_size
265
+
266
+ # jan28b version
267
+ def forward(self, hidden_states, gate=None):
268
+ return rmsnorm_fn(x=hidden_states,
269
+ weight=self.weight,
270
+ bias=None, # No bias
271
+ z=gate,
272
+ eps=self.variance_epsilon,
273
+ group_size=self.group_size,
274
+ norm_before_gate=False
275
+ )
276
+
277
+ class NemotronHMamba2Mixer(nn.Module):
278
+ """
279
+ Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
280
+ A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
281
+ ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
282
+ and is why Mamba is called **selective** state spaces)
283
+ """
284
+
285
+ def __init__(self, config: NemotronHConfig, layer_idx: int):
286
+ super().__init__()
287
+ self.num_heads = config.mamba_num_heads
288
+ self.hidden_size = config.hidden_size
289
+ self.ssm_state_size = config.ssm_state_size
290
+ self.conv_kernel_size = config.conv_kernel
291
+ self.intermediate_size = config.mamba_num_heads * config.mamba_head_dim
292
+ self.layer_idx = layer_idx
293
+ self.use_conv_bias = config.use_conv_bias
294
+ self.activation = config.mamba_hidden_act
295
+ self.act = ACT2FN[config.mamba_hidden_act]
296
+
297
+ self.layer_norm_epsilon = config.layer_norm_epsilon
298
+
299
+ self.n_groups = config.n_groups
300
+ self.head_dim = config.mamba_head_dim
301
+ self.chunk_size = config.chunk_size
302
+
303
+ self.time_step_limit = config.time_step_limit
304
+ self.time_step_min = config.time_step_min
305
+ self.time_step_max = config.time_step_max
306
+
307
+ self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size
308
+ self.conv1d = nn.Conv1d(
309
+ in_channels=self.conv_dim,
310
+ out_channels=self.conv_dim,
311
+ bias=config.use_conv_bias,
312
+ kernel_size=config.conv_kernel,
313
+ groups=self.conv_dim,
314
+ padding=config.conv_kernel - 1,
315
+ )
316
+
317
+ # projection of the input hidden states
318
+ projection_size = self.intermediate_size + self.conv_dim + self.num_heads
319
+ self.in_proj = nn.Linear(
320
+ self.hidden_size,
321
+ projection_size,
322
+ bias=config.use_bias,
323
+ )
324
+ # selective projection used to make dt, B and C input dependant
325
+
326
+ # time step projection (discretization)
327
+ # instantiate once and copy inv_dt in init_weights of PretrainedModel
328
+ self.dt_bias = nn.Parameter(torch.ones(self.num_heads))
329
+
330
+ # S4D real initialization. These are not discretized!
331
+ # The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
332
+ A = torch.arange(1, self.num_heads + 1)
333
+ self.A_log = nn.Parameter(torch.log(A))
334
+ self.A_log._no_weight_decay = True
335
+ self.norm = MambaRMSNormGated(self.intermediate_size, eps=self.layer_norm_epsilon, group_size=self.intermediate_size // self.n_groups)
336
+ self.D = nn.Parameter(torch.ones(self.num_heads))
337
+ self.D._no_weight_decay = True
338
+
339
+ self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.use_bias)
340
+ self.use_bias = config.use_bias
341
+
342
+ if not is_fast_path_available:
343
+ logger.warning_once(
344
+ "The fast path is not available because on of `(selective_state_update, causal_conv1d_fn, causal_conv1d_update)`"
345
+ " is None. Falling back to the naive implementation. To install follow https://github.com/state-spaces/mamba/#installation and"
346
+ " https://github.com/Dao-AILab/causal-conv1d"
347
+ )
348
+
349
+ def cuda_kernels_forward(
350
+ self,
351
+ hidden_states: torch.Tensor,
352
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
353
+ cache_position: Optional[torch.LongTensor] = None,
354
+ attention_mask: Optional[torch.Tensor] = None,
355
+ ):
356
+ # 1. Gated MLP's linear projection
357
+ hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
358
+ projected_states = self.in_proj(hidden_states)
359
+
360
+ # Set up dimensions for reshapes later
361
+ batch_size, seq_len, _ = hidden_states.shape
362
+ groups_time_state_size = self.n_groups * self.ssm_state_size
363
+ d_mlp = (
364
+ projected_states.shape[-1]
365
+ - 2 * self.intermediate_size
366
+ - 2 * self.n_groups * self.ssm_state_size
367
+ - self.num_heads
368
+ ) // 2
369
+
370
+ # Single step calculations via cache
371
+ if cache_params is not None and cache_position is not None and cache_position[0] > 0:
372
+ _, _, gate, hidden_states_B_C, dt = projected_states.squeeze(1).split(
373
+ [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
374
+ )
375
+
376
+ # 2. Convolution sequence transformation
377
+ hidden_states_B_C = causal_conv1d_update(
378
+ hidden_states_B_C,
379
+ cache_params.conv_states[self.layer_idx],
380
+ self.conv1d.weight.squeeze(1),
381
+ self.conv1d.bias,
382
+ self.activation,
383
+ )
384
+
385
+ hidden_states, B, C = torch.split(
386
+ hidden_states_B_C,
387
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
388
+ dim=-1,
389
+ )
390
+
391
+ # 3. SSM transformation
392
+ A = -torch.exp(self.A_log.float()) # (nheads,)
393
+ A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
394
+ dt = dt[:, :, None].expand(-1, -1, self.head_dim)
395
+ dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
396
+ D = self.D[:, None, ...].expand(-1, self.head_dim)
397
+ B = B.view(batch_size, self.n_groups, B.shape[1] // self.n_groups)
398
+ C = C.view(batch_size, self.n_groups, C.shape[1] // self.n_groups)
399
+ hidden_states_reshaped = hidden_states.view(batch_size, self.num_heads, self.head_dim)
400
+ hidden_states = selective_state_update(
401
+ cache_params.ssm_states[self.layer_idx],
402
+ hidden_states_reshaped,
403
+ dt,
404
+ A,
405
+ B,
406
+ C,
407
+ D,
408
+ z=None,
409
+ dt_bias=dt_bias,
410
+ dt_softplus=True,
411
+ )
412
+ hidden_states = hidden_states.view(batch_size, self.num_heads * self.head_dim)
413
+ hidden_states = self.norm(hidden_states, gate)
414
+
415
+ # 4. Final linear projection
416
+ out = self.out_proj(hidden_states)[:, None, ...]
417
+
418
+ # Fused calculations or step by step if no initialized cache is found
419
+ else:
420
+ A = -torch.exp(self.A_log.float()) # (num_heads) or (intermediate_size, state_size)
421
+ dt_limit_kwargs = {} if self.time_step_limit == (0.0, float("inf")) else {"dt_limit": self.time_step_limit}
422
+
423
+ # 2-4. Fused kernel for conv1d, SSM, and the final projection
424
+ if self.training and cache_params is None:
425
+ out = mamba_split_conv1d_scan_combined(
426
+ projected_states,
427
+ self.conv1d.weight.squeeze(1),
428
+ self.conv1d.bias,
429
+ self.dt_bias,
430
+ A,
431
+ D=self.D,
432
+ chunk_size=self.chunk_size,
433
+ seq_idx=None, # was seq_idx
434
+ activation=self.activation,
435
+ rmsnorm_weight=self.norm.weight,
436
+ rmsnorm_eps=self.norm.variance_epsilon,
437
+ outproj_weight=self.out_proj.weight,
438
+ outproj_bias=self.out_proj.bias,
439
+ headdim=self.head_dim,
440
+ ngroups=self.n_groups,
441
+ norm_before_gate=False,
442
+ return_final_states=False,
443
+ **dt_limit_kwargs,
444
+ )
445
+
446
+ else:
447
+ _, _, gate, hidden_states_B_C, dt = projected_states.split(
448
+ [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
449
+ )
450
+
451
+ # 2. Convolution sequence transformation
452
+ # Init cache
453
+ if cache_params is not None:
454
+ hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2)
455
+ conv_states = nn.functional.pad(
456
+ hidden_states_B_C_transposed,
457
+ (cache_params.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0),
458
+ )
459
+ cache_params.update_conv_state(
460
+ layer_idx=self.layer_idx, new_conv_state=conv_states, cache_init=True
461
+ )
462
+
463
+ if self.activation not in ["silu", "swish"]:
464
+ hidden_states_B_C = self.act(
465
+ self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2)
466
+ )
467
+ else:
468
+ hidden_states_B_C = causal_conv1d_fn(
469
+ x=hidden_states_B_C.transpose(1, 2),
470
+ weight=self.conv1d.weight.squeeze(1),
471
+ bias=self.conv1d.bias,
472
+ activation=self.activation,
473
+ ).transpose(1, 2)
474
+ hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
475
+ hidden_states, B, C = torch.split(
476
+ hidden_states_B_C,
477
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
478
+ dim=-1,
479
+ )
480
+
481
+ # 3. SSM transformation
482
+ scan_output, ssm_state = mamba_chunk_scan_combined(
483
+ hidden_states.view(batch_size, seq_len, -1, self.head_dim),
484
+ dt,
485
+ A,
486
+ B.view(batch_size, seq_len, self.n_groups, -1),
487
+ C.view(batch_size, seq_len, self.n_groups, -1),
488
+ chunk_size=self.chunk_size,
489
+ D=self.D,
490
+ z=None,
491
+ seq_idx=None,
492
+ return_final_states=True,
493
+ dt_bias=self.dt_bias,
494
+ dt_softplus=True,
495
+ **dt_limit_kwargs,
496
+ )
497
+
498
+ # Init cache
499
+ if ssm_state is not None and cache_params is not None:
500
+ cache_params.update_ssm_state(layer_idx=self.layer_idx, new_ssm_state=ssm_state)
501
+
502
+ scan_output = scan_output.view(batch_size, seq_len, -1)
503
+
504
+ # Multiply "gate" branch and apply extra normalization layer
505
+ scan_output = self.norm(scan_output, gate)
506
+
507
+ # 4. Final linear projection
508
+ out = self.out_proj(scan_output)
509
+ return out
510
+
511
+ # fmt: off
512
+ def torch_forward(self, input_states, cache_params: Optional[HybridMambaAttentionDynamicCache]=None, cache_position:Optional[torch.LongTensor]=None, attention_mask: Optional[torch.Tensor]=None):
513
+ batch_size, seq_len, _ = input_states.shape
514
+ dtype = input_states.dtype
515
+
516
+ # 1. Gated MLP's linear projection
517
+ input_states = apply_mask_to_padding_states(input_states, attention_mask)
518
+ projected_states = self.in_proj(input_states)
519
+ d_mlp = (projected_states.shape[-1] - 2 * self.intermediate_size - 2 * self.n_groups * self.ssm_state_size-self.num_heads) // 2
520
+ _, _, gate, hidden_states_B_C, dt = projected_states.split(
521
+ [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
522
+ )
523
+
524
+ # 2. Convolution sequence transformation
525
+ if cache_params is not None and cache_position is not None and cache_position[0] > 0:
526
+ cache_params.update_conv_state(layer_idx=self.layer_idx, new_conv_state=hidden_states_B_C, cache_init=False)
527
+
528
+ # We need to guarantee that anything regarding the cache is on the same device
529
+ conv_states = cache_params.conv_states[self.layer_idx].to(device=self.conv1d.weight.device)
530
+
531
+ hidden_states_B_C = torch.sum(
532
+ conv_states * self.conv1d.weight.squeeze(1), dim=-1
533
+ )
534
+ if self.use_conv_bias:
535
+ hidden_states_B_C = hidden_states_B_C + self.conv1d.bias
536
+ hidden_states_B_C = self.act(hidden_states_B_C)
537
+ else:
538
+ # Init cache
539
+ if cache_params is not None:
540
+ hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2)
541
+ conv_states = nn.functional.pad(
542
+ hidden_states_B_C_transposed, (cache_params.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0)
543
+ )
544
+ cache_params.update_conv_state(layer_idx=self.layer_idx, new_conv_state=conv_states, cache_init=True)
545
+
546
+ hidden_states_B_C = self.act(self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2))
547
+
548
+ hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
549
+ hidden_states, B, C = torch.split(
550
+ hidden_states_B_C,
551
+ [self.intermediate_size, self.n_groups * self.ssm_state_size, self.n_groups * self.ssm_state_size],
552
+ dim=-1
553
+ )
554
+
555
+ # 3. SSM transformation
556
+ A = -torch.exp(self.A_log.float()) # [num_heads]
557
+ if cache_params is not None and cache_position is not None and cache_position[0] > 0:
558
+ # We need to guarantee that anything regarding the cache is on the same device
559
+ cache_device = cache_params.ssm_states.device
560
+
561
+ # Note: there is no need to pad parameter matrices here, as there is just one new token
562
+ # for batched generation
563
+ dt = dt[:, 0, :][:, None, ...]
564
+ dt = dt.transpose(1, 2).expand(batch_size, dt.shape[-1], self.head_dim)
565
+ # [num_heads] -> [num_heads, head_dim]
566
+ dt_bias = self.dt_bias[..., None].expand(self.dt_bias.shape[0], self.head_dim)
567
+
568
+ dt = torch.nn.functional.softplus(dt + dt_bias.to(dt.dtype))
569
+ dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
570
+ A = A[..., None, None].expand(self.num_heads, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
571
+ # [bsz, num_heads, head_dim, state_size]
572
+ dA = (torch.exp(dt[..., None] * A)).to(device=cache_device)
573
+
574
+ # Discretize B
575
+ # [bsz, n_groups * state_size] -> [bsz, n_groups, 1, state_size] ->
576
+ # -> [bsz, n_groups, group to head repetition factor, state_size] -> [bsz, num_heads, state_size]
577
+ B = B.reshape(batch_size, self.n_groups, -1)[..., None, :]
578
+ B = B.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, B.shape[-1]).contiguous()
579
+ B = B.reshape(batch_size, -1, B.shape[-1])
580
+ # [bsz, num_heads, head_dim, state_size]
581
+ dB = dt[..., None] * B[..., None, :]
582
+
583
+ # Discretize x into dB
584
+ # [bsz, intermediate_size] -> [bsz, num_heads, head_dim]
585
+ hidden_states = hidden_states.reshape(batch_size, -1, self.head_dim)
586
+ dBx = (dB * hidden_states[..., None]).to(device=cache_device)
587
+
588
+ # State calculation
589
+ cache_params.update_ssm_state(
590
+ layer_idx=self.layer_idx,
591
+ new_ssm_state=cache_params.ssm_states[self.layer_idx] * dA + dBx
592
+ )
593
+
594
+ # Subsequent output
595
+ # [bsz, n_groups * state_size] -> [bsz, num_heads, state_size]
596
+ C = C.reshape(batch_size, self.n_groups, -1)[..., None, :]
597
+ C = C.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, C.shape[-1]).contiguous()
598
+ C = C.reshape(batch_size, -1, C.shape[-1])
599
+ # [bsz, num_heads, head_dim]
600
+
601
+ ssm_states = cache_params.ssm_states[self.layer_idx].to(device=C.device, dtype=C.dtype) # Shape: [b, h, d, n]
602
+ # Reshape ssm_states to merge the first two dimensions
603
+ ssm_states_reshaped = ssm_states.view(batch_size * self.num_heads, self.head_dim, self.ssm_state_size) # Shape: [b*h, d, n]
604
+ C_reshaped = C.view(batch_size * self.num_heads, self.ssm_state_size, 1) # Shape: [b*h, n, 1]
605
+ y = torch.bmm(ssm_states_reshaped, C_reshaped)
606
+ y = y.view(batch_size, self.num_heads, self.head_dim)
607
+
608
+ # D skip connection
609
+ # [num_heads] -> [num_heads, head_dim]
610
+ D = self.D[..., None].expand(self.D.shape[0], self.head_dim)
611
+ y = (y + hidden_states * D).to(y.dtype)
612
+
613
+ # [bsz, num_heads, head_dim] -> [bsz, 1, intermediate_size]
614
+ y = y.reshape(batch_size, -1)[:, None, ...]
615
+ else:
616
+ # begin ssd naive implementation without einsums
617
+ dt = nn.functional.softplus(dt + self.dt_bias)
618
+ dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
619
+ hidden_states = hidden_states.reshape(batch_size, seq_len, -1, self.head_dim).float()
620
+ B = B.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
621
+ C = C.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
622
+ B = B.repeat(1, 1, self.num_heads // self.n_groups, 1)
623
+ C = C.repeat(1, 1, self.num_heads // self.n_groups, 1)
624
+ pad_size = (self.chunk_size - seq_len % self.chunk_size) % self.chunk_size
625
+
626
+ D_residual = self.D[..., None] * pad_tensor_by_size(hidden_states, pad_size)
627
+
628
+ # Discretize x and A
629
+ hidden_states = hidden_states * dt[..., None]
630
+ A = A.to(hidden_states.dtype) * dt
631
+
632
+ # Rearrange into blocks/chunks
633
+ hidden_states, A, B, C = [reshape_into_chunks(t, pad_size, self.chunk_size) for t in (hidden_states, A, B, C)]
634
+
635
+ # [bsz, -1, chunk_size, num_heads] -> [bsz, num_heads, -1, chunk_size]
636
+ A = A.permute(0, 3, 1, 2)
637
+ A_cumsum = torch.cumsum(A, dim=-1)
638
+
639
+ # 1. Compute the output for each intra-chunk (diagonal blocks)
640
+ # This is the analog of a causal mask
641
+ L = torch.exp(segment_sum(A))
642
+
643
+ # Contraction of C and B to get G (attention-weights like)
644
+ G_intermediate = C[:, :, :, None, :, :] * B[:, :, None, :, :, :] # shape: (b, c, l, s, h, n)
645
+ G = G_intermediate.sum(dim=-1) # shape: (b, c, l, s, h)
646
+
647
+ # Compute M, equivalent to applying attention mask to weights
648
+ M_intermediate = G[..., None] * L.permute(0, 2, 3, 4, 1)[..., None]
649
+ M = M_intermediate.sum(dim=-1)
650
+
651
+ # Compute Y_diag (apply to values)
652
+ Y_diag = (M[..., None] * hidden_states[:, :, None]).sum(dim=3)
653
+
654
+ # 2. Compute the state for each intra-chunk
655
+ # (right term of low-rank factorization of off-diagonal blocks; B terms)
656
+ decay_states = torch.exp((A_cumsum[:, :, :, -1:] - A_cumsum))
657
+ B_decay = B * decay_states.permute(0, -2, -1, 1)[..., None]
658
+ states = (B_decay[..., None, :] * hidden_states[..., None]).sum(dim=2)
659
+
660
+ # 3. Compute the inter-chunk SSM recurrence; produces correct SSM states at chunk boundaries
661
+ # (middle term of factorization of off-diag blocks; A terms)
662
+ if cache_params is not None and cache_position is not None and cache_position[0] > 0:
663
+ previous_states = cache_params.ssm_states[self.layer_idx][:, None, ...].to(device=states.device)
664
+ else:
665
+ previous_states = torch.zeros_like(states[:, :1])
666
+ states = torch.cat([previous_states, states], dim=1)
667
+ decay_chunk = torch.exp(segment_sum(nn.functional.pad(A_cumsum[:, :, :, -1], (1, 0))))
668
+ decay_chunk = decay_chunk.transpose(1, 3)
669
+ new_states = (decay_chunk[..., None, None] * states[:, :, None, ...]).sum(dim=1)
670
+ states, ssm_state = new_states[:, :-1], new_states[:, -1]
671
+
672
+ # 4. Compute state -> output conversion per chunk
673
+ # (left term of low-rank factorization of off-diagonal blocks; C terms)
674
+ state_decay_out = torch.exp(A_cumsum)
675
+ C_times_states = (C[..., None, :] * states[:, :, None, ...])
676
+ state_decay_out_permuted = state_decay_out.permute(0, 2, 3, 1)
677
+ Y_off = (C_times_states.sum(-1) * state_decay_out_permuted[..., None])
678
+
679
+ # Add output of intra-chunk and inter-chunk terms (diagonal and off-diagonal blocks)
680
+ y = Y_diag + Y_off
681
+ # [bsz, -1, self.chunk_size, num_heads, head_dim] -> [bsz, (padded) seq_len, num_heads, head_dim]
682
+ y = y.reshape(batch_size, -1, self.num_heads, self.head_dim)
683
+
684
+ y = y + D_residual
685
+ # Cutting off padded chunks
686
+ if pad_size > 0:
687
+ y = y[:, :seq_len, :, :]
688
+ y = y.reshape(batch_size, seq_len, -1)
689
+
690
+ # Init cache
691
+ if ssm_state is not None and cache_params is not None:
692
+ cache_params.update_ssm_state(layer_idx=self.layer_idx, new_ssm_state=ssm_state)
693
+
694
+ scan_output = self.norm(y, gate)
695
+
696
+ # end ssd naive
697
+
698
+ # 4. Final linear projection
699
+ contextualized_states = self.out_proj(scan_output.to(dtype)) # [batch, seq_len, hidden_size]
700
+ return contextualized_states
701
+ # fmt: on
702
+
703
+ def forward(
704
+ self,
705
+ hidden_states,
706
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
707
+ cache_position: Optional[torch.LongTensor] = None,
708
+ attention_mask: Optional[torch.Tensor] = None,
709
+ ):
710
+ if is_fast_path_available and "cuda" in self.in_proj.weight.device.type:
711
+ return self.cuda_kernels_forward(hidden_states, cache_params, cache_position, attention_mask)
712
+ dtype = hidden_states.dtype
713
+ if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
714
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
715
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
716
+
717
+ return self.torch_forward(hidden_states, cache_params, cache_position, attention_mask)
718
+
719
+
720
+ class NemotronHRMSNorm(nn.Module):
721
+ def __init__(self, hidden_size, eps=1e-6):
722
+ """
723
+ NemotronHRMSNorm is equivalent to T5LayerNorm and LlamaRMSNorm
724
+ """
725
+ super().__init__()
726
+ self.weight = nn.Parameter(torch.ones(hidden_size))
727
+ self.variance_epsilon = eps
728
+
729
+ def forward(self, hidden_states):
730
+ input_dtype = hidden_states.dtype
731
+ hidden_states = hidden_states.to(torch.float32)
732
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
733
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
734
+ # Weights are in float32
735
+ return (self.weight.to(torch.float32) * hidden_states).to(input_dtype)
736
+
737
+ class NemotronHBlock(nn.Module):
738
+ def __init__(self, config, layer_idx):
739
+ super().__init__()
740
+ self.config = config
741
+ self.layer_idx = layer_idx
742
+ self.residual_in_fp32 = config.residual_in_fp32
743
+ self.norm = NemotronHRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
744
+
745
+ # M: Mamba2, *: Attention, -: MLP
746
+ self.block_type = config.layers_block_type[layer_idx]
747
+ if self.block_type == "mamba":
748
+ self.mixer = NemotronHMamba2Mixer(config, layer_idx=layer_idx)
749
+ elif self.block_type == "attention":
750
+ self.mixer = NEMOTRONH_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
751
+ elif self.block_type == "mlp":
752
+ self.mixer = NemotronHMLP(config, layer_idx=layer_idx)
753
+ else:
754
+ raise ValueError(f"Invalid layer pattern {config.hybrid_override_pattern[layer_idx]}")
755
+
756
+ def forward(
757
+ self,
758
+ hidden_states,
759
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
760
+ cache_position: Optional[torch.LongTensor] = None,
761
+ attention_mask: Optional[torch.Tensor] = None,
762
+ ):
763
+ with torch.cuda.stream(torch.cuda.default_stream(hidden_states.device)):
764
+ # * Use torch.cuda.stream() to avoid NaN issues when using multiple GPUs
765
+ residual = hidden_states
766
+ hidden_states = self.norm(hidden_states.to(dtype=self.norm.weight.dtype))
767
+ if self.residual_in_fp32:
768
+ residual = residual.to(torch.float32)
769
+
770
+ if self.block_type == "mamba":
771
+ hidden_states = self.mixer(
772
+ hidden_states, cache_params=cache_params, cache_position=cache_position
773
+ )
774
+ elif self.block_type == "attention":
775
+ hidden_states = self.mixer(
776
+ hidden_states, cache_position=cache_position
777
+ )
778
+ hidden_states = hidden_states[0]
779
+ elif self.block_type == "mlp":
780
+ hidden_states = self.mixer(
781
+ hidden_states
782
+ )
783
+ else:
784
+ raise ValueError(f"Invalid block_type: {self.block_type}")
785
+
786
+ hidden_states = residual + hidden_states
787
+ return hidden_states
788
+
789
+
790
+ # Copied from transformers.models.nemotron.modeling_nemotron Nemotron->NemotronH
791
+ class NemotronHMLP(nn.Module):
792
+ def __init__(self, config, layer_idx: Optional[int] = None):
793
+ super().__init__()
794
+ self.config = config
795
+ self.layer_idx = layer_idx
796
+ if layer_idx is None:
797
+ logger.warning_once(
798
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
799
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
800
+ "when creating this class."
801
+ )
802
+ self.hidden_size = config.hidden_size
803
+ #intermediate_size = config.expand * config.hidden_size
804
+ self.intermediate_size = config.intermediate_size
805
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
806
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
807
+ self.act_fn = ACT2FN[config.mlp_hidden_act]
808
+
809
+ def forward(self, x):
810
+ return self.down_proj(self.act_fn(self.up_proj(x)))
811
+
812
+
813
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
814
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
815
+ """
816
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
817
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
818
+ """
819
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
820
+ if n_rep == 1:
821
+ return hidden_states
822
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
823
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
824
+
825
+
826
+ class NemotronHAttention(nn.Module):
827
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
828
+
829
+ def __init__(self, config: NemotronHConfig, layer_idx: Optional[int] = None):
830
+ super().__init__()
831
+ self.config = config
832
+ self.layer_idx = layer_idx
833
+ if layer_idx is None:
834
+ logger.warning_once(
835
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
836
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
837
+ "when creating this class."
838
+ )
839
+
840
+ self.attention_dropout = config.attention_dropout
841
+ self.hidden_size = config.hidden_size
842
+ self.num_heads = config.num_attention_heads
843
+ if config.head_dim is not None:
844
+ self.head_dim = config.head_dim
845
+ else:
846
+ self.head_dim = config.hidden_size // config.num_attention_heads
847
+ self.num_key_value_heads = config.num_key_value_heads
848
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
849
+ self.max_position_embeddings = config.max_position_embeddings
850
+ self.is_causal = True
851
+
852
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
853
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
854
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
855
+ self.o_proj = nn.Linear(self.head_dim * self.num_heads, self.hidden_size, bias=config.attention_bias)
856
+
857
+ def forward(
858
+ self,
859
+ hidden_states: torch.Tensor,
860
+ # position_embeddings: Tuple[torch.Tensor, torch.Tensor], #TODO
861
+ attention_mask: Optional[torch.Tensor] = None,
862
+ position_ids: Optional[torch.LongTensor] = None,
863
+ past_key_value: Optional[HybridMambaAttentionDynamicCache] = None,
864
+ output_attentions: bool = False,
865
+ use_cache: bool = False,
866
+ cache_position: Optional[torch.LongTensor] = None,
867
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
868
+ bsz, q_len, _ = hidden_states.size()
869
+
870
+ query_states = self.q_proj(hidden_states)
871
+ key_states = self.k_proj(hidden_states)
872
+ value_states = self.v_proj(hidden_states)
873
+
874
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
875
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
876
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
877
+
878
+ if past_key_value is not None:
879
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx)
880
+
881
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
882
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
883
+
884
+ causal_mask = attention_mask
885
+ if attention_mask is not None: # no matter the length, we just slice it
886
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
887
+
888
+ if query_states.device.type == "cuda" and attention_mask is not None:
889
+ query_states = query_states.contiguous()
890
+ key_states = key_states.contiguous()
891
+ value_states = value_states.contiguous()
892
+
893
+ is_causal = True if causal_mask is None and q_len > 1 else False
894
+
895
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
896
+ query_states,
897
+ key_states,
898
+ value_states,
899
+ attn_mask=causal_mask,
900
+ dropout_p=self.attention_dropout if self.training else 0.0,
901
+ is_causal=is_causal,
902
+ )
903
+ attn_output = attn_output.transpose(1, 2).contiguous()
904
+ #attn_output = attn_output.view(bsz, q_len, self.hidden_size)
905
+ attn_output = attn_output.view(bsz, q_len, self.num_heads * self.head_dim)
906
+
907
+ attn_output = self.o_proj(attn_output)
908
+
909
+ return attn_output, None, past_key_value
910
+
911
+
912
+ # Adapted from transformers.models.mistral.modeling_mistral.MistralFlashAttention2 with Mistral->Jamba
913
+ #class JambaFlashAttention2(JambaAttention):
914
+ class NemotronHFlashAttention2(NemotronHAttention):
915
+ """
916
+ Jamba flash attention module. This module inherits from `JambaAttention` as the weights of the module stays
917
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
918
+ flash attention and deal with padding tokens in case the input contains any of them.
919
+ """
920
+ def __init__(self, *args, **kwargs):
921
+ super().__init__(*args, **kwargs)
922
+
923
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
924
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
925
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
926
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
927
+
928
+ def forward(
929
+ self,
930
+ hidden_states: torch.Tensor,
931
+ attention_mask: Optional[torch.Tensor] = None,
932
+ position_ids: Optional[torch.LongTensor] = None,
933
+ past_key_value: Optional[HybridMambaAttentionDynamicCache] = None,
934
+ output_attentions: bool = False,
935
+ use_cache: bool = False,
936
+ cache_position: Optional[torch.LongTensor] = None,
937
+ **kwargs,
938
+ ):
939
+ bsz, q_len, _ = hidden_states.size()
940
+
941
+ query_states = self.q_proj(hidden_states)
942
+ key_states = self.k_proj(hidden_states)
943
+ value_states = self.v_proj(hidden_states)
944
+
945
+ # Flash attention requires the input to have the shape
946
+ # batch_size x seq_length x head_dim x hidden_dim
947
+ # therefore we just need to keep the original shape
948
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim)
949
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
950
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
951
+
952
+ if past_key_value is not None:
953
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx)
954
+
955
+ # repeat k/v heads if n_kv_heads < n_heads
956
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
957
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
958
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
959
+
960
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
961
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
962
+ # cast them back in float16 just to be sure everything works as expected.
963
+ input_dtype = query_states.dtype
964
+ if input_dtype == torch.float32:
965
+ if torch.is_autocast_enabled():
966
+ target_dtype = torch.get_autocast_gpu_dtype()
967
+ # Handle the case where the model is quantized
968
+ elif hasattr(self.config, "_pre_quantization_dtype"):
969
+ target_dtype = self.config._pre_quantization_dtype
970
+ else:
971
+ target_dtype = self.q_proj.weight.dtype
972
+
973
+ logger.warning_once(
974
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
975
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
976
+ f" {target_dtype}."
977
+ )
978
+
979
+ query_states = query_states.to(target_dtype)
980
+ key_states = key_states.to(target_dtype)
981
+ value_states = value_states.to(target_dtype)
982
+
983
+ # Reashape to the expected shape for Flash Attention
984
+ key_states = key_states.transpose(1, 2)
985
+ value_states = value_states.transpose(1, 2)
986
+
987
+ attn_output = _flash_attention_forward(
988
+ query_states,
989
+ key_states,
990
+ value_states,
991
+ attention_mask,
992
+ q_len,
993
+ dropout=dropout_rate,
994
+ sliding_window=getattr(self.config, "sliding_window", None),
995
+ is_causal=self.is_causal,
996
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
997
+ )
998
+
999
+ #attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
1000
+ attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.head_dim).contiguous()
1001
+ attn_output = self.o_proj(attn_output)
1002
+
1003
+ if not output_attentions:
1004
+ attn_weights = None
1005
+
1006
+ return attn_output, attn_weights, past_key_value
1007
+
1008
+
1009
+ # Adapted from transformers.models.mistral.modeling_mistral.MistralSdpaAttention with Mistral->Jamba
1010
+ #class JambaSdpaAttention(JambaAttention):
1011
+ class NemotronHSdpaAttention(NemotronHAttention):
1012
+ """
1013
+ Jamba attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
1014
+ `JambaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
1015
+ SDPA API.
1016
+ """
1017
+
1018
+ # Adapted from NemotronHAttention.forward
1019
+ def forward(
1020
+ self,
1021
+ hidden_states: torch.Tensor,
1022
+ attention_mask: Optional[torch.Tensor] = None,
1023
+ position_ids: Optional[torch.LongTensor] = None,
1024
+ past_key_value: Optional[HybridMambaAttentionDynamicCache] = None,
1025
+ output_attentions: bool = False,
1026
+ use_cache: bool = False,
1027
+ cache_position: Optional[torch.LongTensor] = None,
1028
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
1029
+ if output_attentions:
1030
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
1031
+ logger.warning_once(
1032
+ "NemotronHModel is using NemotronHSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
1033
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
1034
+ )
1035
+ return super().forward(
1036
+ hidden_states=hidden_states,
1037
+ attention_mask=attention_mask,
1038
+ position_ids=position_ids,
1039
+ past_key_value=past_key_value,
1040
+ output_attentions=output_attentions,
1041
+ use_cache=use_cache,
1042
+ )
1043
+
1044
+ bsz, q_len, _ = hidden_states.size()
1045
+
1046
+ query_states = self.q_proj(hidden_states)
1047
+ key_states = self.k_proj(hidden_states)
1048
+ value_states = self.v_proj(hidden_states)
1049
+
1050
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
1051
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1052
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
1053
+
1054
+ if past_key_value is not None:
1055
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx)
1056
+
1057
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
1058
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
1059
+
1060
+ causal_mask = attention_mask
1061
+ if attention_mask is not None:
1062
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
1063
+
1064
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
1065
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
1066
+ if query_states.device.type == "cuda" and attention_mask is not None:
1067
+ query_states = query_states.contiguous()
1068
+ key_states = key_states.contiguous()
1069
+ value_states = value_states.contiguous()
1070
+
1071
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
1072
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
1073
+ # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
1074
+ is_causal = True if self.is_causal and causal_mask is None and q_len > 1 else False
1075
+
1076
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
1077
+ query_states,
1078
+ key_states,
1079
+ value_states,
1080
+ attn_mask=causal_mask,
1081
+ dropout_p=self.attention_dropout if self.training else 0.0,
1082
+ is_causal=is_causal,
1083
+ )
1084
+
1085
+ attn_output = attn_output.transpose(1, 2).contiguous()
1086
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
1087
+
1088
+ attn_output = self.o_proj(attn_output)
1089
+
1090
+ return attn_output, None, past_key_value
1091
+
1092
+
1093
+ NEMOTRONH_ATTENTION_CLASSES = {
1094
+ "eager": NemotronHAttention,
1095
+ "flash_attention_2": NemotronHFlashAttention2,
1096
+ "sdpa": NemotronHSdpaAttention,
1097
+ }
1098
+
1099
+ # Copied from transformers.models.mamba.modeling_mamba2.Mamba2PreTrainedModel
1100
+ class NemotronHPreTrainedModel(PreTrainedModel):
1101
+ """
1102
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
1103
+ models.
1104
+ """
1105
+
1106
+ config_class = NemotronHConfig
1107
+ base_model_prefix = "backbone"
1108
+ _no_split_modules = ["NemotronHBlock"]
1109
+ supports_gradient_checkpointing = True
1110
+ _is_stateful = True
1111
+
1112
+ def _init_weights(self, module):
1113
+ """Initialize the weights."""
1114
+ if isinstance(module, NemotronHMamba2Mixer):
1115
+ module.A_log._no_weight_decay = True
1116
+ module.D._no_weight_decay = True
1117
+
1118
+ dt = torch.exp(
1119
+ torch.rand(self.config.mamba_num_heads)
1120
+ * (math.log(self.config.time_step_max) - math.log(self.config.time_step_min))
1121
+ + math.log(self.config.time_step_min)
1122
+ ).clamp(min=self.config.time_step_floor)
1123
+
1124
+ # # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
1125
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
1126
+ with torch.no_grad():
1127
+ module.dt_bias.copy_(inv_dt)
1128
+ module.dt_bias._no_reinit = True
1129
+
1130
+ if isinstance(module, nn.Linear):
1131
+ if module.bias is not None:
1132
+ if not getattr(module.bias, "_no_reinit", False):
1133
+ nn.init.zeros_(module.bias)
1134
+ elif isinstance(module, nn.Embedding):
1135
+ nn.init.normal_(module.weight, std=self.config.initializer_range)
1136
+
1137
+ # TODO: Check
1138
+ if self.config.rescale_prenorm_residual:
1139
+ # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
1140
+ # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
1141
+ # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
1142
+ # > -- GPT-2 :: https://openai.com/blog/better-language-models/
1143
+ #
1144
+ # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
1145
+ for name, p in module.named_parameters():
1146
+ if name in ["out_proj.weight"]:
1147
+ # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
1148
+ # Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
1149
+ # We need to reinit p since this code could be called multiple times
1150
+ # Having just p *= scale would repeatedly scale it down
1151
+ nn.init.kaiming_uniform_(p, a=math.sqrt(5))
1152
+ with torch.no_grad():
1153
+ p /= math.sqrt(self.config.num_hidden_layers)
1154
+
1155
+
1156
+ @dataclass
1157
+ # Copied from transformers.models.mamba.modeling_mamba2.Mamba2Output with MAMBA2->NemotronH,Mamba2->NemotronH
1158
+ class NemotronHOutput(ModelOutput):
1159
+ """
1160
+ Class for the NemotronH model outputs.
1161
+
1162
+ Args:
1163
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
1164
+ Sequence of hidden-states at the output of the last layer of the model.
1165
+ cache_params (`HybridMambaAttentionDynamicCache`):
1166
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
1167
+ avoid providing the old `input_ids`.
1168
+
1169
+ Includes both the State space model state matrices after the selective scan, and the Convolutional states
1170
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
1171
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
1172
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
1173
+
1174
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
1175
+ """
1176
+
1177
+ last_hidden_state: Optional[torch.FloatTensor] = None
1178
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None
1179
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
1180
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
1181
+
1182
+
1183
+ @dataclass
1184
+ # Copied from transformers.models.mamba2.modeling_mamba2.MambaCausalLMOutput with Mamba2->NemotronH
1185
+ class NemotronHCausalLMOutput(ModelOutput):
1186
+ """
1187
+ Base class for causal language model (or autoregressive) outputs.
1188
+
1189
+ Args:
1190
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
1191
+ Language modeling loss (for next-token prediction).
1192
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
1193
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
1194
+ cache_params (`HybridMambaAttentionDynamicCache`):
1195
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
1196
+ avoid providing the old `input_ids`.
1197
+
1198
+ Includes both the State space model state matrices after the selective scan, and the Convolutional states
1199
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
1200
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
1201
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
1202
+
1203
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
1204
+ """
1205
+
1206
+ loss: Optional[torch.FloatTensor] = None
1207
+ logits: Optional[torch.FloatTensor] = None
1208
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None
1209
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
1210
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
1211
+
1212
+
1213
+ NEMOTRONH_START_DOCSTRING = r"""
1214
+
1215
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1216
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1217
+ etc.)
1218
+
1219
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1220
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1221
+ and behavior.
1222
+
1223
+ Parameters:
1224
+ config ([`NemotronHConfig`]): Model configuration class with all the parameters of the model.
1225
+ Initializing with a config file does not load the weights associated with the model, only the
1226
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
1227
+ """
1228
+
1229
+ NEMOTRONH_INPUTS_DOCSTRING = r"""
1230
+ Args:
1231
+ input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`, *optional*):
1232
+ Indices of input sequence tokens in the vocabulary.
1233
+
1234
+ If `cache_params.seqlen_offset>0`, only `input_ids` that do not have their past calculated should be passed as
1235
+ `input_ids`.
1236
+
1237
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1238
+ [`PreTrainedTokenizer.__call__`] for details.
1239
+
1240
+ [What are input IDs?](../glossary#input-ids)
1241
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1242
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
1243
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
1244
+ model's internal embedding lookup matrix.
1245
+ position_ids (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1246
+ Indices of positions of each input sequence tokens in the position embeddings.
1247
+ cache_params (`HybridMambaAttentionDynamicCache`, *optional*):
1248
+ If passed along, the model uses the previous state in all the blocks (which will give the output for the
1249
+ `input_ids` provided as if the model add `state_input_ids + input_ids` as context).
1250
+ use_cache (`bool`, *optional*):
1251
+ If set to `True`, the `cache_params` is returned and can be used to quickly generate the next logits.
1252
+ output_attentions (`bool`, *optional*):
1253
+ Whether or not to return the attentions tensors of all attention layers.
1254
+ output_hidden_states (`bool`, *optional*):
1255
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
1256
+ more detail.
1257
+ return_dict (`bool`, *optional*):
1258
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1259
+ cache_position (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1260
+ The position of the current input in the cache. This is used to ensure that the cache is correctly updated.
1261
+ If `cache_params` is passed, `cache_position` should also be passed.
1262
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
1263
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1264
+
1265
+ - 1 for tokens that are **not masked**,
1266
+ - 0 for tokens that are **masked**.
1267
+
1268
+ [What are attention masks?](../glossary#attention-mask)
1269
+ """
1270
+
1271
+
1272
+ @add_start_docstrings(
1273
+ "The bare NemotronH Model transformer outputting raw hidden-states without any specific head on top.",
1274
+ NEMOTRONH_START_DOCSTRING,
1275
+ )
1276
+ class NemotronHModel(NemotronHPreTrainedModel):
1277
+ def __init__(self, config):
1278
+ super().__init__(config)
1279
+
1280
+ self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
1281
+ self.layers = nn.ModuleList([NemotronHBlock(config, layer_idx=idx) for idx in range(config.num_hidden_layers)])
1282
+
1283
+ self.gradient_checkpointing = False
1284
+ self.norm_f = NemotronHRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
1285
+ # Initialize weights and apply final processing
1286
+ self._register_load_state_dict_pre_hook(self.load_hook)
1287
+ self.post_init()
1288
+
1289
+ def load_hook(self, state_dict, prefix, *args):
1290
+ for k in state_dict:
1291
+ if "embedding." in k:
1292
+ state_dict[k.replace("embedding.", "embeddings.")] = state_dict.pop(k)
1293
+ break
1294
+
1295
+ def get_input_embeddings(self):
1296
+ return self.embeddings
1297
+
1298
+ def set_input_embeddings(self, new_embeddings):
1299
+ self.embeddings = new_embeddings
1300
+
1301
+ @add_start_docstrings_to_model_forward(NEMOTRONH_INPUTS_DOCSTRING)
1302
+ @add_code_sample_docstrings(
1303
+ checkpoint=_CHECKPOINT_FOR_DOC,
1304
+ output_type=NemotronHOutput,
1305
+ config_class=_CONFIG_FOR_DOC,
1306
+ )
1307
+ def forward(
1308
+ self,
1309
+ input_ids: Optional[torch.LongTensor] = None,
1310
+ inputs_embeds: Optional[torch.LongTensor] = None,
1311
+ position_ids: Optional[torch.LongTensor] = None,
1312
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
1313
+ use_cache: Optional[bool] = None,
1314
+ output_attentions: Optional[bool] = None,
1315
+ output_hidden_states: Optional[bool] = None,
1316
+ return_dict: Optional[bool] = None,
1317
+ cache_position: Optional[torch.LongTensor] = None,
1318
+ attention_mask: Optional[torch.Tensor] = None,
1319
+ **kwargs,
1320
+ ) -> Union[Tuple, NemotronHOutput]:
1321
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1322
+ output_hidden_states = (
1323
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1324
+ )
1325
+ # use_cache = use_cache if use_cache is not None else self.config.use_cache
1326
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
1327
+
1328
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1329
+
1330
+ if (input_ids is None) ^ (inputs_embeds is not None): # ^ is python for xor
1331
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
1332
+
1333
+ if inputs_embeds is None:
1334
+ inputs_embeds = self.embeddings(input_ids)
1335
+
1336
+ if self.gradient_checkpointing and self.training and use_cache:
1337
+ logger.warning_once(
1338
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
1339
+ )
1340
+ use_cache = False
1341
+
1342
+ # From zamba_modeling.py
1343
+ if use_cache and cache_params is None:
1344
+ logger.warning_once(
1345
+ "NemotronH requires an initialized `NemotronHHybridDynamicCache` to return a cache. None was "
1346
+ "provided, so no cache will be returned."
1347
+ )
1348
+
1349
+ hidden_states = inputs_embeds
1350
+
1351
+ if cache_position is None:
1352
+ cache_position = torch.arange(hidden_states.shape[1], device=hidden_states.device)
1353
+ if position_ids is None:
1354
+ position_ids = cache_position.unsqueeze(0)
1355
+
1356
+ causal_mask = self._update_causal_mask(attention_mask, inputs_embeds, cache_position)
1357
+ mamba_mask = self._update_mamba_mask(attention_mask, cache_position)
1358
+
1359
+ all_hidden_states = () if output_hidden_states else None
1360
+ all_self_attns = () if output_attentions else None
1361
+ # Until HERE
1362
+
1363
+ for layer_idx, mixer_block in enumerate(self.layers):
1364
+ # Depending on the layer type we opt for 2D base attention mask (Mamba) or 4D causal mask (Attention)
1365
+ if mixer_block.block_type == "mamba":
1366
+ layer_mask = mamba_mask
1367
+ elif mixer_block.block_type == "attention":
1368
+ layer_mask = causal_mask
1369
+ elif mixer_block.block_type == "mlp":
1370
+ layer_mask = None
1371
+ else:
1372
+ raise ValueError(f"Invalid block_type: {self.block_type}")
1373
+
1374
+ if output_hidden_states:
1375
+ all_hidden_states += (hidden_states,)
1376
+
1377
+ if self.gradient_checkpointing and self.training:
1378
+ hidden_states = self._gradient_checkpointing_func(
1379
+ mixer_block.__call__, hidden_states, cache_params, cache_position, layer_mask
1380
+ )
1381
+ else:
1382
+ hidden_states = mixer_block(
1383
+ hidden_states,
1384
+ cache_params=cache_params,
1385
+ cache_position=cache_position,
1386
+ attention_mask=layer_mask,
1387
+ )
1388
+
1389
+ # TODO: Store attentions
1390
+ # if output_attentions:
1391
+ # if layer_outputs[1] is not None:
1392
+ # # append attentions only of attention layers. Mamba layers return `None` as the attention weights
1393
+ # all_self_attns += (layer_outputs[1],)
1394
+
1395
+ # TODO (Check): should it happen before the forward pass?
1396
+ # if output_hidden_states:
1397
+ # all_hidden_states = all_hidden_states + (hidden_states,)
1398
+
1399
+ hidden_states = self.norm_f(hidden_states)
1400
+
1401
+ if output_hidden_states:
1402
+ all_hidden_states = all_hidden_states + (hidden_states,)
1403
+
1404
+ if not return_dict:
1405
+ return tuple(v for v in [hidden_states, cache_params, all_hidden_states] if v is not None)
1406
+
1407
+ return NemotronHOutput(
1408
+ last_hidden_state=hidden_states,
1409
+ cache_params=cache_params if use_cache else None,
1410
+ hidden_states=all_hidden_states,
1411
+ attentions=all_self_attns,
1412
+ )
1413
+
1414
+ # Copied from transformers.models.jamba.modeling_jamba.JambaModel._update_causal_mask
1415
+ def _update_causal_mask(self, attention_mask, input_tensor, cache_position):
1416
+ if self.config._attn_implementation == "flash_attention_2":
1417
+ if attention_mask is not None and 0.0 in attention_mask:
1418
+ return attention_mask
1419
+ return None
1420
+
1421
+ dtype, device = input_tensor.dtype, input_tensor.device
1422
+ min_dtype = torch.finfo(dtype).min
1423
+ sequence_length = input_tensor.shape[1]
1424
+ target_length = cache_position[-1] + 1
1425
+
1426
+ causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
1427
+ if sequence_length != 1:
1428
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1429
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1430
+ causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
1431
+ if attention_mask is not None:
1432
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1433
+ if attention_mask.dim() == 2:
1434
+ mask_length = attention_mask.shape[-1]
1435
+ padding_mask = causal_mask[..., :mask_length].eq(0.0) * attention_mask[:, None, None, :].eq(0.0)
1436
+ causal_mask[..., :mask_length] = causal_mask[..., :mask_length].masked_fill(padding_mask, min_dtype)
1437
+
1438
+ if (
1439
+ self.config._attn_implementation == "sdpa"
1440
+ and attention_mask is not None
1441
+ and attention_mask.device.type == "cuda"
1442
+ ):
1443
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1444
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1445
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1446
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1447
+
1448
+ return causal_mask
1449
+
1450
+ def _update_mamba_mask(self, attention_mask, cache_position):
1451
+ """
1452
+ No need for zeroing states when
1453
+ 1. Cached forward
1454
+ 2. Attending to all inputs
1455
+ """
1456
+ mamba_mask = attention_mask
1457
+ if cache_position[0] > 0 or (attention_mask is not None and torch.all(attention_mask == 1)):
1458
+ mamba_mask = None
1459
+ return mamba_mask
1460
+
1461
+
1462
+ @add_start_docstrings(
1463
+ """
1464
+ The NEMOTRONH Model transformer with a language modeling head on top (linear layer with weights not tied to the input
1465
+ embeddings).
1466
+ """,
1467
+ NEMOTRONH_START_DOCSTRING,
1468
+ )
1469
+ class NemotronHForCausalLM(NemotronHPreTrainedModel, GenerationMixin):
1470
+ _tied_weights_keys = ["lm_head.weight"]
1471
+
1472
+ def __init__(self, config):
1473
+ super().__init__(config)
1474
+ self.backbone = NemotronHModel(config)
1475
+ self.vocab_size = config.vocab_size
1476
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1477
+
1478
+ # Initialize weights and apply final processing
1479
+ self.post_init()
1480
+
1481
+ def get_input_embeddings(self):
1482
+ return self.backbone.get_input_embeddings()
1483
+
1484
+ def set_input_embeddings(self, new_embeddings):
1485
+ return self.backbone.set_input_embeddings(new_embeddings)
1486
+
1487
+ def get_output_embeddings(self):
1488
+ return self.lm_head
1489
+
1490
+ def set_output_embeddings(self, new_embeddings):
1491
+ self.lm_head = new_embeddings
1492
+
1493
+ def get_decoder(self):
1494
+ return self.model
1495
+
1496
+ def set_decoder(self, decoder):
1497
+ self.model = decoder
1498
+
1499
+ def prepare_inputs_for_generation(
1500
+ self,
1501
+ input_ids,
1502
+ past_key_values=None,
1503
+ attention_mask=None,
1504
+ inputs_embeds=None,
1505
+ cache_position=None,
1506
+ position_ids=None,
1507
+ use_cache=True,
1508
+ **kwargs,
1509
+ ):
1510
+ # Copy from https://github.com/huggingface/transformers/blob/main/src/transformers/models/jamba/modeling_jamba.py
1511
+ # Overwitten -- uses `cache_params` as opposed to `past_key_values`
1512
+ empty_past_kv = past_key_values is None
1513
+
1514
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
1515
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
1516
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
1517
+ # Exception 3: with synced GPUs cache_position may go out of bounds, but we only want dummy token in that case.
1518
+ # (we can't check exception 3 while compiling)
1519
+ if not empty_past_kv:
1520
+ if (
1521
+ inputs_embeds is not None # Exception 1
1522
+ or cache_position[-1] >= input_ids.shape[1] # Exception 3
1523
+ ):
1524
+ input_ids = input_ids[:, -cache_position.shape[0] :]
1525
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
1526
+ input_ids = input_ids[:, cache_position]
1527
+ else:
1528
+ past_key_values = HybridMambaAttentionDynamicCache(
1529
+ self.config, input_ids.shape[0], self.dtype, device=self.device
1530
+ )
1531
+
1532
+ if attention_mask is not None and position_ids is None:
1533
+ # create position_ids on the fly for batch generation
1534
+ position_ids = attention_mask.long().cumsum(-1) - 1
1535
+ position_ids.masked_fill_(attention_mask == 0, 1)
1536
+ if not empty_past_kv:
1537
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1538
+
1539
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1540
+ if inputs_embeds is not None and empty_past_kv:
1541
+ if input_ids is not None and inputs_embeds.shape[1] < input_ids.shape[1]:
1542
+ new_token_embeds = self.get_input_embeddings()(input_ids[:,inputs_embeds.shape[1]:])
1543
+ inputs_embeds = torch.cat([inputs_embeds, new_token_embeds], dim=1)
1544
+ model_inputs = {"inputs_embeds": inputs_embeds}
1545
+ else:
1546
+ model_inputs = {"input_ids": input_ids.contiguous()} # `contiguous()` needed for compilation use cases
1547
+
1548
+ model_inputs.update(
1549
+ {
1550
+ "position_ids": position_ids,
1551
+ "past_key_values": past_key_values,
1552
+ "use_cache": use_cache,
1553
+ "attention_mask": attention_mask,
1554
+ "logits_to_keep": self.config.num_logits_to_keep,
1555
+ "cache_position": cache_position,
1556
+ }
1557
+ )
1558
+ return model_inputs
1559
+
1560
+ @add_start_docstrings_to_model_forward(NEMOTRONH_INPUTS_DOCSTRING)
1561
+ @add_code_sample_docstrings(
1562
+ checkpoint=_CHECKPOINT_FOR_DOC,
1563
+ output_type=NemotronHCausalLMOutput,
1564
+ config_class=_CONFIG_FOR_DOC,
1565
+ )
1566
+ def forward(
1567
+ self,
1568
+ input_ids: Optional[torch.LongTensor] = None,
1569
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1570
+ position_ids: Optional[torch.LongTensor] = None,
1571
+ cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
1572
+ labels: Optional[torch.LongTensor] = None,
1573
+ output_attentions: Optional[bool] = None,
1574
+ output_hidden_states: Optional[bool] = None,
1575
+ return_dict: Optional[bool] = None,
1576
+ use_cache: Optional[bool] = None,
1577
+ cache_position: Optional[torch.Tensor] = None,
1578
+ attention_mask: Optional[torch.Tensor] = None,
1579
+ **kwargs, # for now we need this for generation
1580
+ ) -> Union[Tuple, NemotronHCausalLMOutput]:
1581
+ r"""
1582
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1583
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1584
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
1585
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
1586
+ """
1587
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1588
+
1589
+ output_hidden_states = (
1590
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1591
+ )
1592
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1593
+
1594
+ nemotron_h_outputs = self.backbone(
1595
+ input_ids,
1596
+ cache_params=cache_params,
1597
+ inputs_embeds=inputs_embeds,
1598
+ output_attentions=output_attentions,
1599
+ output_hidden_states=output_hidden_states,
1600
+ return_dict=return_dict,
1601
+ use_cache=use_cache,
1602
+ cache_position=cache_position,
1603
+ attention_mask=attention_mask,
1604
+ )
1605
+ hidden_states = nemotron_h_outputs[0]
1606
+
1607
+ # TODO: Check zamba_modeling.py: https://github.com/huggingface/transformers/blob/d7188ba600e36d3fd191b12e19f1b3bb81a8404f/src/transformers/models/zamba/modeling_zamba.py#L1284C1-L1286C2
1608
+ #logits = self.lm_head(hidden_states.to(self.lm_head.weight.dtype)).float()
1609
+ logits = self.lm_head(hidden_states.to(self.lm_head.weight.dtype)).float()
1610
+
1611
+ loss = None
1612
+ if labels is not None:
1613
+ # move labels to correct device to enable model parallelism
1614
+ labels = labels.to(logits.device)
1615
+ # Shift so that tokens < n predict n
1616
+ shift_logits = logits[..., :-1, :].contiguous()
1617
+ shift_labels = labels[..., 1:].contiguous()
1618
+ # Flatten the tokens
1619
+ loss_fct = CrossEntropyLoss()
1620
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1621
+
1622
+ if not return_dict:
1623
+ output = (logits,) + nemotron_h_outputs[1:]
1624
+ return ((loss,) + output) if loss is not None else output
1625
+
1626
+ return NemotronHCausalLMOutput(
1627
+ loss=loss,
1628
+ logits=logits,
1629
+ cache_params=nemotron_h_outputs.cache_params,
1630
+ hidden_states=nemotron_h_outputs.hidden_states,
1631
+ attentions=nemotron_h_outputs.attentions,
1632
+ )
preprocessor_config.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "image_processor_type": "NemotronNanoVLV2ImageProcessor",
3
+ "auto_map": {
4
+ "AutoImageProcessor": "image_processing.NemotronNanoVLV2ImageProcessor",
5
+ "AutoVideoProcessor": "video_processing.NemotronNanoVLV2VideoProcessor",
6
+ "AutoProcessor": "processing.NemotronNanoVLV2Processor"
7
+ },
8
+ "image_size": 512,
9
+ "patch_size": 16,
10
+ "downsample_ratio": 0.5,
11
+ "max_num_tiles": 12,
12
+ "use_thumbnail": true,
13
+ "norm_mean": [0.48145466, 0.4578275, 0.40821073],
14
+ "norm_std": [0.26862954, 0.26130258, 0.27577711]
15
+ }
privacy.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Field | Response
2
+ :----------------------------------------------------------------------------------------------------------------------------------|:-----------------------------------------------
3
+ Generatable or reverse engineerable personal data? | No
4
+ Personal data used to create this model? | No
5
+ Was consent obtained for any personal data used? | Not Applicable
6
+ A description of any methods implemented in data acquisition or processing, if any, to address the prevalence of personal data in the training data, where relevant and applicable. | We used only prompts that do not contain any personal data for synthetic data generation.
7
+ How often is dataset reviewed? | Before release and during dataset creation and model training <br><br>
8
+ Is there provenance for all datasets used in training? | Yes
9
+ Does data labeling (annotation, metadata) comply with privacy laws? | Yes
10
+ Is data compliant with data subject requests for data correction or removal, if such a request was made? | No, not possible with externally-sourced data.
11
+ Applicable Privacy Policy | [Privacy Policy](https://www.nvidia.com/en-us/about-nvidia/privacy-policy/)
12
+ During AI model development, strict adherence to copyright policy ensured compliance through risk mitigation and legal reviews. Post-data collection, reserved rights content is identified and removed, with verified opt-out processes for rightsholders. Detailed records document due diligence and transparency.
13
+ We employ automated tools and data processing techniques to scan for Personally Identifiable Information (PII) during pre-training to identify and filter certain categories of personal information, including public-facing contact details such as email addresses and phone numbers. Scans of Common Crawl, CC-News, and Wikimedia datasets did not detect PII in the majority of samples. However, Microsoft Presidio indicated potential findings including business contact information embedded in natural language, such as email addresses and phone numbers. These were removed using verified instances of PII through a combination of automated filtering and human-in-the-loop validation.
processing.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import Optional, Union, List
15
+
16
+ import numpy as np
17
+
18
+ from transformers.feature_extraction_utils import BatchFeature
19
+ from transformers.image_utils import ImageInput
20
+ from transformers.processing_utils import ImagesKwargs, MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack, VideosKwargs
21
+ from transformers.tokenization_utils_base import PreTokenizedInput, TextInput
22
+ from transformers.video_utils import VideoInput
23
+
24
+
25
+ class NemotronNanoVLV2ImagesKwargs(ImagesKwargs):
26
+ min_pixels: Optional[int]
27
+ max_pixels: Optional[int]
28
+ patch_size: Optional[int]
29
+ temporal_patch_size: Optional[int]
30
+ merge_size: Optional[int]
31
+
32
+
33
+ class NemotronNanoVLV2ProcessorKwargs(ProcessingKwargs, total=False):
34
+ images_kwargs: NemotronNanoVLV2ImagesKwargs
35
+ videos_kwargs: VideosKwargs
36
+ _defaults = {
37
+ "text_kwargs": {
38
+ "padding": False,
39
+ },
40
+ }
41
+
42
+
43
+ class NemotronNanoVLV2Processor(ProcessorMixin):
44
+ r"""
45
+ Constructs a Nemotron Nano VL V2 processor which wraps an image processor and a tokenizer into a single processor.
46
+ [`NemotronNanoVLV2Processor`] offers all the functionalities of the image processor and tokenizer. See the
47
+ [`~NemotronNanoVLV2Processor.__call__`] and [`~NemotronNanoVLV2Processor.decode`] for more information.
48
+ Args:
49
+ image_processor ([`AutoImageProcessor`], *optional*):
50
+ The image processor is a required input.
51
+ tokenizer ([`AutoTokenizer`], *optional*):
52
+ The tokenizer is a required input.
53
+ chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
54
+ in a chat into a tokenizable string.
55
+ """
56
+
57
+ attributes = ["image_processor", "tokenizer"]
58
+
59
+ image_processor_class = "AutoImageProcessor"
60
+ video_processor_class = "AutoVideoProcessor"
61
+ tokenizer_class = ("AutoTokenizer")
62
+
63
+ def __init__(self, image_processor=None, tokenizer=None, chat_template=None, **kwargs):
64
+ self.image_token = "<image>" if not hasattr(tokenizer, "image_token") else tokenizer.image_token
65
+ self.video_token = "<video>" if not hasattr(tokenizer, "video_token") else tokenizer.video_token
66
+ self.image_start_token = "<img>" if not hasattr(tokenizer, "image_start_token") else tokenizer.image_start_token
67
+ self.image_end_token = "</img>" if not hasattr(tokenizer, "image_end_token") else tokenizer.image_end_token
68
+ self.image_token_id = (
69
+ tokenizer.image_token_id
70
+ if getattr(tokenizer, "image_token_id", None)
71
+ else tokenizer.convert_tokens_to_ids(self.image_token)
72
+ )
73
+ self.video_token_id = (
74
+ tokenizer.video_token_id
75
+ if getattr(tokenizer, "video_token_id", None)
76
+ else tokenizer.convert_tokens_to_ids(self.video_token)
77
+ )
78
+ super().__init__(image_processor, tokenizer, chat_template=chat_template)
79
+
80
+ def __call__(
81
+ self,
82
+ images: ImageInput = None,
83
+ text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
84
+ videos: VideoInput = None,
85
+ **kwargs: Unpack[NemotronNanoVLV2ProcessorKwargs],
86
+ ) -> BatchFeature:
87
+ """
88
+ Main method to prepare multimodal inputs (text, images, videos) for the model. This method processes text by
89
+ replacing image/video tokens with appropriate placeholder sequences, processes images and videos through the
90
+ image processor, and tokenizes the final text.
91
+
92
+ The method performs the following key operations:
93
+ 1. Processes images using the image processor to get pixel values and patch counts
94
+ 2. Processes videos using the image processor with max_num_tiles=1 to get video pixel values
95
+ 3. Replaces `<image>` tokens in text with `<img>` + image tokens + `</img>` sequences
96
+ 4. Replaces `<video>` tokens in text with frame-by-frame descriptions including timestamps (if metadata provided)
97
+ 5. Tokenizes the processed text and combines all outputs
98
+
99
+ Args:
100
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`, *optional*):
101
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
102
+ tensor. Both channels-first and channels-last formats are supported.
103
+ text (`str`, `List[str]`, *optional*):
104
+ The sequence or batch of sequences to be encoded. Each sequence should be a string. The text can contain
105
+ special tokens `<image>` and `<video>` that will be replaced with appropriate token sequences.
106
+ videos (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`, *optional*):
107
+ The video or batch of videos to be prepared. Each video should be a 4D NumPy array or PyTorch
108
+ tensor with shape (num_frames, channels, height, width). Both channels-first and channels-last formats
109
+ are supported. Note: Currently only supports batch size of 1 for videos.
110
+ images_kwargs (`Dict`, *optional*):
111
+ Additional keyword arguments for image processing, including:
112
+ - `min_pixels` (`int`, *optional*): Minimum number of pixels for image processing
113
+ - `max_pixels` (`int`, *optional*): Maximum number of pixels for image processing
114
+ - `patch_size` (`int`, *optional*): Size of patches for image processing
115
+ - `temporal_patch_size` (`int`, *optional*): Size of temporal patches
116
+ - `merge_size` (`int`, *optional*): Size for merging patches
117
+ videos_kwargs (`Dict`, *optional*):
118
+ Additional keyword arguments for video processing, including:
119
+ - `video_metadata` (`VideoMetadata`, *optional*): Metadata containing fps information for timestamp calculation
120
+ text_kwargs (`Dict`, *optional*):
121
+ Additional keyword arguments for text tokenization, including:
122
+ - `return_tensors` (`str` or [`~utils.TensorType`], *optional*): Framework for returned tensors ('tf', 'pt', 'np', 'jax')
123
+ - `padding` (`bool`, *optional*): Whether to pad sequences (defaults to False)
124
+
125
+ Returns:
126
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
127
+
128
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
129
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
130
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
131
+ `None`).
132
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
133
+ - **num_patches** -- Number of patches per image. Returned when `images` is not `None`.
134
+ - **pixel_values_videos** -- Pixel values of videos to be fed to a model. Returned when `videos` is not `None`.
135
+
136
+ Raises:
137
+ AssertionError: If videos are provided with batch size > 1 (not currently supported).
138
+
139
+ Note:
140
+ - Image tokens `<image>` in text are replaced with `<img>` + repeated image tokens + `</img>`
141
+ - Video tokens `<video>` in text are replaced with frame-by-frame descriptions
142
+ - When video metadata with fps is provided, frame descriptions include timestamps
143
+ - Videos are processed with max_num_tiles=1 regardless of the images setting
144
+ """
145
+ output_kwargs = self._merge_kwargs(
146
+ NemotronNanoVLV2ProcessorKwargs,
147
+ tokenizer_init_kwargs=self.tokenizer.init_kwargs,
148
+ **kwargs,
149
+ )
150
+ image_inputs = videos_inputs = {}
151
+ if images is not None:
152
+ image_inputs = self.image_processor(images=images, **output_kwargs["images_kwargs"])
153
+ image_num_patches = image_inputs["num_patches"]
154
+
155
+ if videos is not None:
156
+ orig_tiles = self.image_processor.max_num_tiles
157
+ self.image_processor.max_num_tiles = 1
158
+ videos_inputs = self.image_processor(images=videos, **output_kwargs["images_kwargs"])
159
+ self.image_processor.max_num_tiles = orig_tiles
160
+ video_num_patches = [sum(videos_inputs["num_patches"])]
161
+ videos_inputs["pixel_values_videos"] = videos_inputs["pixel_values"]
162
+ del videos_inputs["pixel_values"]
163
+
164
+ if not isinstance(text, list):
165
+ text = [text]
166
+
167
+ text = text.copy() # below lines change text in-place
168
+ if images is not None:
169
+ index = 0
170
+ for i in range(len(text)):
171
+ while self.image_token in text[i]:
172
+ text[i] = text[i].replace(self.image_token, self.image_start_token + "<|placeholder|>" * image_num_patches[index] * self.image_processor.num_image_token + self.image_end_token, 1)
173
+ index += 1
174
+ text[i] = text[i].replace("<|placeholder|>", self.image_token)
175
+ if videos is not None:
176
+ assert len(text) == 1, "Video is not supported for batch size > 1"
177
+ video_metadata = output_kwargs.get("videos_kwargs", {}).get("video_metadata", None)
178
+ i = 0
179
+ index = 0
180
+ if self.video_token in text[i]:
181
+ each_frame = self.image_start_token + "<|placeholder|>" * self.image_processor.num_image_token + self.image_end_token
182
+ video_prompt = "This is a video:\n"
183
+ for j in range(video_num_patches[index]):
184
+ if video_metadata is not None and video_metadata.fps is not None:
185
+ timestamp = j / video_metadata.fps
186
+ video_prompt += f"Frame {j+1} sampled at {timestamp:.2f} seconds: {each_frame}\n"
187
+ else:
188
+ # Fallback to original format without timestamps
189
+ video_prompt += f"Frame {j+1}: {each_frame}\n"
190
+
191
+ text[i] = text[i].replace(self.video_token, video_prompt, 1)
192
+ text[i] = text[i].replace("<|placeholder|>", self.video_token)
193
+
194
+ return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
195
+ text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
196
+ return BatchFeature(data={**text_inputs, **image_inputs, **videos_inputs}, tensor_type=return_tensors)
197
+
198
+ def _get_num_multimodal_tokens(self, image_sizes=None, video_sizes=None, **kwargs):
199
+ """
200
+ Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
201
+ Args:
202
+ image_sizes (`list[list[int]]`, *optional*):
203
+ The input sizes formatted as (height, width) per each image.
204
+ video_sizes (`list[list[int]]`, *optional*):
205
+ The input sizes formatted as (num_frames, height, width) per each video.
206
+ Returns:
207
+ `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
208
+ input modalities, along with other useful data.
209
+ """
210
+
211
+ vision_data = {}
212
+ if image_sizes is not None:
213
+ images_kwargs = NemotronNanoVLV2ProcessorKwargs._defaults.get("images_kwargs", {})
214
+ images_kwargs.update(kwargs)
215
+ merge_size = images_kwargs.get("merge_size", None) or self.image_processor.merge_size
216
+
217
+ num_image_patches = [
218
+ self.image_processor.get_number_of_image_patches(*image_size, images_kwargs)
219
+ for image_size in image_sizes
220
+ ]
221
+ num_image_tokens = [(num_patches // merge_size**2) for num_patches in num_image_patches]
222
+ vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
223
+ return MultiModalData(**vision_data)
224
+
225
+ def batch_decode(self, *args, **kwargs):
226
+ """
227
+ This method forwards all its arguments to the tokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please
228
+ refer to the docstring of this method for more information.
229
+ """
230
+ return self.tokenizer.batch_decode(*args, **kwargs)
231
+
232
+ def decode(self, *args, **kwargs):
233
+ """
234
+ This method forwards all its arguments to the tokenizer's [`~PreTrainedTokenizer.decode`]. Please refer to
235
+ the docstring of this method for more information.
236
+ """
237
+ return self.tokenizer.decode(*args, **kwargs)
238
+
239
+ def post_process_image_text_to_text(
240
+ self, generated_outputs, skip_special_tokens=True, clean_up_tokenization_spaces=False, **kwargs
241
+ ):
242
+ """
243
+ Post-process the output of the model to decode the text.
244
+
245
+ Args:
246
+ generated_outputs (`torch.Tensor` or `np.ndarray`):
247
+ The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)`
248
+ or `(sequence_length,)`.
249
+ skip_special_tokens (`bool`, *optional*, defaults to `True`):
250
+ Whether or not to remove special tokens in the output. Argument passed to the tokenizer's `batch_decode` method.
251
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
252
+ Whether or not to clean up the tokenization spaces. Argument passed to the tokenizer's `batch_decode` method.
253
+ **kwargs:
254
+ Additional arguments to be passed to the tokenizer's `batch_decode method`.
255
+
256
+ Returns:
257
+ `list[str]`: The decoded text.
258
+ """
259
+ return self.tokenizer.batch_decode(
260
+ generated_outputs,
261
+ skip_special_tokens=skip_special_tokens,
262
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
263
+ **kwargs,
264
+ )
265
+
266
+ @property
267
+ def model_input_names(self):
268
+ tokenizer_input_names = self.tokenizer.model_input_names
269
+ image_processor_input_names = self.image_processor.model_input_names
270
+ names_from_processor = list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
271
+ return names_from_processor + ["second_per_grid_ts"]
272
+
273
+
274
+ __all__ = ["NemotronNanoVLV2Processor"]
processing_utils.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import List, Optional, Union, Any, Dict
15
+
16
+ from PIL import Image
17
+ import torch
18
+ from transformers.image_processing_base import BatchFeature
19
+ from transformers.image_processing_utils_fast import BaseImageProcessorFast, divide_to_patches
20
+ from transformers.image_utils import (make_list_of_images, get_image_size,
21
+ get_image_type, ImageInput, ImageType, ChannelDimension)
22
+ from transformers.utils import TensorType
23
+ import torchvision.transforms as T
24
+
25
+
26
+ def get_internvl_target_ratios(
27
+ min_num: int,
28
+ max_num: int,
29
+ ) -> list[tuple[int, int]]:
30
+ target_ratios = {(i, j)
31
+ for n in range(min_num, max_num + 1)
32
+ for i in range(1, n + 1)
33
+ for j in range(1, n + 1) if min_num <= i * j <= max_num}
34
+ return sorted(target_ratios, key=lambda x: x[0] * x[1])
35
+
36
+
37
+ def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
38
+ best_factor = float('-inf')
39
+ best_ratio = (1, 1)
40
+ area = width * height
41
+ for ratio in target_ratios:
42
+ target_aspect_ratio = ratio[0] / ratio[1]
43
+ factor_based_on_area_n_ratio = min(
44
+ (ratio[0]*ratio[1]*image_size*image_size)/ area, 0.6
45
+ )* min(
46
+ target_aspect_ratio/aspect_ratio, aspect_ratio/target_aspect_ratio)
47
+ if factor_based_on_area_n_ratio > best_factor:
48
+ best_factor = factor_based_on_area_n_ratio
49
+ best_ratio = ratio
50
+ return best_ratio
51
+
52
+
53
+ def calculate_targets(
54
+ orig_width: int,
55
+ orig_height: int,
56
+ target_ratios: list[tuple[int, int]],
57
+ image_size: int,
58
+ ) -> tuple[int, int, int]:
59
+ aspect_ratio = orig_width / orig_height
60
+
61
+ # find the closest aspect ratio to the target
62
+ target_aspect_ratio = find_closest_aspect_ratio(
63
+ aspect_ratio,
64
+ target_ratios,
65
+ width=orig_width,
66
+ height=orig_height,
67
+ image_size=image_size,
68
+ )
69
+
70
+ # calculate the target width and height
71
+ target_width = image_size * target_aspect_ratio[0]
72
+ target_height = image_size * target_aspect_ratio[1]
73
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
74
+
75
+ return blocks, target_width, target_height
76
+
77
+
78
+ def dynamic_preprocess(image, image_size=512, max_num_tiles=12, use_thumbnail=True):
79
+ orig_height, orig_width = get_image_size(image, channel_dim=ChannelDimension.FIRST)
80
+ target_ratios = get_internvl_target_ratios(1, max_num_tiles)
81
+
82
+ blocks, target_width, target_height = calculate_targets(
83
+ orig_width,
84
+ orig_height,
85
+ target_ratios,
86
+ image_size
87
+ )
88
+ # resize the image
89
+ resized_img = T.Resize((target_width, target_height), interpolation=T.InterpolationMode.BICUBIC)(image)
90
+ patches = divide_to_patches(resized_img, image_size)
91
+ assert len(patches) == blocks
92
+ if use_thumbnail and len(patches) != 1:
93
+ thumbnail_img = T.Resize((image_size, image_size), interpolation=T.InterpolationMode.BICUBIC)(image)
94
+ patches.append(thumbnail_img)
95
+
96
+ return patches
quick_test_image.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Quick test script for image inference with NVIDIA Nemotron Nano VL model."""
16
+
17
+ import argparse
18
+ from typing import List
19
+
20
+ import torch
21
+ from PIL import Image
22
+ from transformers import AutoModelForCausalLM, AutoProcessor, AutoTokenizer
23
+
24
+
25
+ def load_model(model_path: str, device: str = "cuda:0"):
26
+ """Load the VLM model and processor.
27
+
28
+ Args:
29
+ model_path: Path to the pretrained model
30
+ device: Device to load the model on
31
+
32
+ Returns:
33
+ Tuple of (model, tokenizer, processor)
34
+ """
35
+ print(f"Loading model from {model_path}...")
36
+ model = AutoModelForCausalLM.from_pretrained(
37
+ model_path,
38
+ trust_remote_code=True,
39
+ device_map=device,
40
+ torch_dtype=torch.bfloat16
41
+ ).eval()
42
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
43
+ processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
44
+ print("Model loaded successfully!")
45
+ return model, tokenizer, processor
46
+
47
+
48
+ def test_single_image(
49
+ model,
50
+ tokenizer,
51
+ processor,
52
+ image_path: str,
53
+ prompt_text: str = "Describe the image.",
54
+ device: str = "cuda:0",
55
+ max_new_tokens: int = 1024,
56
+ do_sample: bool = False,
57
+ ):
58
+ """Test model inference on a single image.
59
+
60
+ Args:
61
+ model: The VLM model
62
+ tokenizer: The tokenizer
63
+ processor: The processor
64
+ image_path: Path to the image file
65
+ prompt_text: Text prompt for the model
66
+ device: Device to run inference on
67
+ max_new_tokens: Maximum number of tokens to generate
68
+ do_sample: Whether to use sampling for generation
69
+ """
70
+ print(f"\nProcessing: {image_path}")
71
+
72
+ # Load image
73
+ image = Image.open(image_path)
74
+
75
+ # Prepare messages
76
+ messages = [
77
+ {"role": "system", "content": "/no_think"},
78
+ {
79
+ "role": "user",
80
+ "content": [
81
+ {"type": "image", "image": ""},
82
+ {"type": "text", "text": prompt_text},
83
+ ],
84
+ }
85
+ ]
86
+
87
+ # Generate prompt
88
+ prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
89
+
90
+ # Process inputs
91
+ inputs = processor(
92
+ text=[prompt],
93
+ images=[image],
94
+ return_tensors="pt",
95
+ ).to(device)
96
+
97
+ # Generate output
98
+ generated_ids = model.generate(
99
+ pixel_values=inputs.pixel_values,
100
+ input_ids=inputs.input_ids,
101
+ attention_mask=inputs.attention_mask,
102
+ max_new_tokens=max_new_tokens,
103
+ do_sample=do_sample,
104
+ eos_token_id=tokenizer.eos_token_id,
105
+ )
106
+
107
+ # Decode output
108
+ output_text = processor.batch_decode(
109
+ generated_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False
110
+ )[0]
111
+
112
+ print(f"Output: {output_text}\n")
113
+
114
+
115
+ def test_multi_images(
116
+ model,
117
+ tokenizer,
118
+ processor,
119
+ image_paths: List[str],
120
+ prompt_text: str = "Describe the images in detail.",
121
+ device: str = "cuda:0",
122
+ max_new_tokens: int = 1024,
123
+ do_sample: bool = False,
124
+ ):
125
+ """Test model inference on multiple images.
126
+
127
+ Args:
128
+ model: The VLM model
129
+ tokenizer: The tokenizer
130
+ processor: The processor
131
+ image_paths: List of paths to image files
132
+ prompt_text: Text prompt for the model
133
+ device: Device to run inference on
134
+ max_new_tokens: Maximum number of tokens to generate
135
+ do_sample: Whether to use sampling for generation
136
+ """
137
+ print(f"\nProcessing {len(image_paths)} images: {image_paths}")
138
+
139
+ # Load images
140
+ images = [Image.open(img_path) for img_path in image_paths]
141
+
142
+ # Prepare messages with multiple image placeholders
143
+ content = [{"type": "image", "image": f"/path/to/image{i+1}"} for i in range(len(images))]
144
+ content.append({"type": "text", "text": f"\n{prompt_text}"})
145
+
146
+ messages = [
147
+ {"role": "system", "content": "/no_think"},
148
+ {"role": "user", "content": content}
149
+ ]
150
+
151
+ # Generate prompt
152
+ prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
153
+
154
+ # Process inputs
155
+ inputs = processor(
156
+ text=[prompt],
157
+ images=images,
158
+ return_tensors="pt",
159
+ ).to(device)
160
+
161
+ # Generate output
162
+ generated_ids = model.generate(
163
+ pixel_values=inputs.pixel_values,
164
+ input_ids=inputs.input_ids,
165
+ attention_mask=inputs.attention_mask,
166
+ max_new_tokens=max_new_tokens,
167
+ do_sample=do_sample,
168
+ eos_token_id=tokenizer.eos_token_id,
169
+ )
170
+
171
+ # Decode output
172
+ output_text = processor.batch_decode(
173
+ generated_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False
174
+ )[0]
175
+
176
+ print(f"Output: {output_text}\n")
177
+
178
+
179
+ def main():
180
+ parser = argparse.ArgumentParser(description="Test image inference with VLM model")
181
+ parser.add_argument(
182
+ "--model_path",
183
+ type=str,
184
+ required=True,
185
+ help="Path to the pretrained model"
186
+ )
187
+ parser.add_argument(
188
+ "--device",
189
+ type=str,
190
+ default="cuda:0",
191
+ help="Device to run inference on (e.g., cuda:0, cpu)"
192
+ )
193
+ parser.add_argument(
194
+ "--max_new_tokens",
195
+ type=int,
196
+ default=1024,
197
+ help="Maximum number of tokens to generate"
198
+ )
199
+ args = parser.parse_args()
200
+
201
+ # Load model
202
+ model, tokenizer, processor = load_model(args.model_path, args.device)
203
+
204
+ # Test single images
205
+ print("=" * 50)
206
+ print("Testing Single Image Inference")
207
+ print("=" * 50)
208
+
209
+ single_image_paths = [
210
+ "images/example1a.jpeg",
211
+ "images/example1b.jpeg",
212
+ "images/table.png",
213
+ "images/tech.png",
214
+ ]
215
+
216
+ for img_path in single_image_paths:
217
+ test_single_image(
218
+ model, tokenizer, processor, img_path,
219
+ device=args.device,
220
+ max_new_tokens=args.max_new_tokens
221
+ )
222
+
223
+ # Test multi-image inference
224
+ print("=" * 50)
225
+ print("Testing Multi-Image Inference")
226
+ print("=" * 50)
227
+
228
+ multi_image_paths = [
229
+ "images/example1a.jpeg",
230
+ "images/example1b.jpeg",
231
+ ]
232
+
233
+ test_multi_images(
234
+ model, tokenizer, processor, multi_image_paths,
235
+ device=args.device,
236
+ max_new_tokens=args.max_new_tokens
237
+ )
238
+
239
+
240
+ if __name__ == "__main__":
241
+ main()
quick_test_video.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Quick test script for video inference with NVIDIA Nemotron Nano VL model.
16
+
17
+ Note: This script requires pre-extracted video frames. Use ffmpeg or similar tools
18
+ to extract frames from your video first:
19
+ ffmpeg -i video.mp4 -vf fps=1 frames/frame_%04d.jpg
20
+ """
21
+
22
+ import argparse
23
+
24
+ import torch
25
+ from transformers import AutoModelForCausalLM, AutoProcessor, AutoTokenizer
26
+
27
+ import video_io
28
+
29
+
30
+ def load_model(model_path: str, device: str = "cuda:0"):
31
+ """Load the VLM model and processor.
32
+
33
+ Args:
34
+ model_path: Path to the pretrained model
35
+ device: Device to load the model on
36
+
37
+ Returns:
38
+ Tuple of (model, tokenizer, processor)
39
+ """
40
+ print(f"Loading model from {model_path}...")
41
+ model = AutoModelForCausalLM.from_pretrained(
42
+ model_path,
43
+ trust_remote_code=True,
44
+ device_map=device,
45
+ torch_dtype=torch.bfloat16
46
+ ).eval()
47
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
48
+ processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)
49
+ print("Model loaded successfully!")
50
+ return model, tokenizer, processor
51
+
52
+
53
+ def test_video_from_frames(
54
+ model,
55
+ tokenizer,
56
+ processor,
57
+ frames_dir: str,
58
+ video_fps: int = 1,
59
+ prompt_text: str = "Describe what you see.",
60
+ device: str = "cuda:0",
61
+ max_new_tokens: int = 128,
62
+ video_pruning_rate: float = 0.75,
63
+ ):
64
+ """Test model inference on video frames from a directory.
65
+
66
+ Args:
67
+ model: The VLM model
68
+ tokenizer: The tokenizer
69
+ processor: The processor
70
+ frames_dir: Directory containing extracted video frames
71
+ video_fps: FPS used when extracting frames
72
+ prompt_text: Text prompt for the model
73
+ device: Device to run inference on
74
+ max_new_tokens: Maximum number of tokens to generate
75
+ video_pruning_rate: Video pruning rate for efficient inference
76
+ """
77
+ print(f"\nProcessing video frames from: {frames_dir}")
78
+
79
+ # Load frames from directory
80
+ frames = video_io.load_frames_from_directory(frames_dir)
81
+
82
+ # Get data URLs and metadata
83
+ image_urls, metadata = video_io.frames_to_data_urls_with_metadata(frames, video_fps)
84
+
85
+ print(f"Loaded {len(frames)} frames")
86
+ print(f"Metadata: {metadata}")
87
+
88
+ # Prepare messages
89
+ messages = [
90
+ {"role": "system", "content": "/no_think"},
91
+ {
92
+ "role": "user",
93
+ "content": [
94
+ {"type": "video", "video": ""},
95
+ {"type": "text", "text": f"\n{prompt_text}"},
96
+ ],
97
+ }
98
+ ]
99
+
100
+ # Generate prompt
101
+ prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
102
+
103
+ # Process with FPS metadata
104
+ if metadata:
105
+ inputs = processor(
106
+ text=[prompt],
107
+ videos=frames,
108
+ videos_kwargs={'video_metadata': metadata},
109
+ return_tensors="pt",
110
+ )
111
+ else:
112
+ inputs = processor(
113
+ text=[prompt],
114
+ videos=frames,
115
+ return_tensors="pt",
116
+ )
117
+ inputs = inputs.to(device)
118
+
119
+ # Set video pruning rate for efficient inference
120
+ model.video_pruning_rate = video_pruning_rate
121
+
122
+ # Generate output
123
+ generated_ids = model.generate(
124
+ pixel_values_videos=inputs.pixel_values_videos,
125
+ input_ids=inputs.input_ids,
126
+ attention_mask=inputs.attention_mask,
127
+ max_new_tokens=max_new_tokens,
128
+ )
129
+
130
+ # Decode output
131
+ output_text = processor.batch_decode(
132
+ generated_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False
133
+ )[0]
134
+
135
+ print(f"Output: {output_text}\n")
136
+
137
+
138
+ def main():
139
+ parser = argparse.ArgumentParser(
140
+ description="Test video inference with VLM model using pre-extracted frames",
141
+ epilog="Example: Extract frames with ffmpeg first: "
142
+ "ffmpeg -i video.mp4 -vf fps=1 frames/frame_%%04d.jpg"
143
+ )
144
+ parser.add_argument(
145
+ "--model_path",
146
+ type=str,
147
+ required=True,
148
+ help="Path to the pretrained model"
149
+ )
150
+ parser.add_argument(
151
+ "--device",
152
+ type=str,
153
+ default="cuda:0",
154
+ help="Device to run inference on (e.g., cuda:0, cpu)"
155
+ )
156
+ parser.add_argument(
157
+ "--frames_dir",
158
+ type=str,
159
+ default="images/demo_frames",
160
+ help="Directory containing extracted video frames"
161
+ )
162
+ parser.add_argument(
163
+ "--video_fps",
164
+ type=int,
165
+ default=1,
166
+ help="FPS used when extracting frames (for temporal understanding)"
167
+ )
168
+ parser.add_argument(
169
+ "--prompt",
170
+ type=str,
171
+ default="Describe what you see.",
172
+ help="Text prompt for the model"
173
+ )
174
+ parser.add_argument(
175
+ "--max_new_tokens",
176
+ type=int,
177
+ default=128,
178
+ help="Maximum number of tokens to generate"
179
+ )
180
+ parser.add_argument(
181
+ "--video_pruning_rate",
182
+ type=float,
183
+ default=0.75,
184
+ help="Video pruning rate for efficient inference (0.0-1.0)"
185
+ )
186
+ args = parser.parse_args()
187
+
188
+ # Load model
189
+ model, tokenizer, processor = load_model(args.model_path, args.device)
190
+
191
+ # Test video inference from frames
192
+ print("=" * 50)
193
+ print("Testing Video Inference from Frames")
194
+ print("=" * 50)
195
+
196
+ test_video_from_frames(
197
+ model, tokenizer, processor,
198
+ frames_dir=args.frames_dir,
199
+ video_fps=args.video_fps,
200
+ prompt_text=args.prompt,
201
+ device=args.device,
202
+ max_new_tokens=args.max_new_tokens,
203
+ video_pruning_rate=args.video_pruning_rate,
204
+ )
205
+
206
+
207
+ if __name__ == "__main__":
208
+ main()
safety.md ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ Field | Response
2
+ :---------------------------------------------------|:----------------------------------
3
+ Model Application Field(s): | Customer Service, Media & Entertainment, Enterprise Document Intelligence and Processing & Retail
4
+ Describe the life critical impact (if present). | Not Applicable
5
+ Description of methods implemented in data acquisition or processing, if any, to address other types of potentially harmful data in the training, testing, and validation data: | We used a guard model for content safety to exclude potentially harmful data from training.
6
+ Description of any methods implemented in data acquisition or processing, if any, to address illegal or harmful content in the training data, including, but not limited to, child sexual abuse material (CSAM) and non-consensual intimate imagery (NCII) | We used a Gemma-3 4B-based guard model trained on [Nemotron Content Safety Dataset v2](https://huggingface.co/datasets/nvidia/Aegis-AI-Content-Safety-Dataset-2.0) for content safety to exclude potentially illegal or harmful content from the training. We also did CSAM checks on our image datasets for training.
7
+ Use Case Restrictions: | Use of this model is governed by the [ NVIDIA Open Model License Agreement](https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-license/)
8
+ Model and dataset restrictions: | The Principle of least privilege (PoLP) is applied limiting access for dataset generation and model development. Restrictions enforce dataset access during training, and dataset license constraints adhered to.
9
+ This AI model was developed based on our policies to ensure responsible data handling and risk mitigation. The datasets used for training have been scanned for harmful content and illegal content, consistent with our policies including scanning for Child Sexual Abuse Material (CSAM). Ongoing review and monitoring mechanisms are in place based on our policies and to maintain data integrity.
10
+ The model was optimized explicitly for instruction following and as such is more susceptible to prompt injection and jailbreaking in various forms as a result of its instruction tuning. This means that the model should be paired with additional rails or system filtering to limit exposure to instructions from malicious sources -- either directly or indirectly by retrieval (e.g. via visiting a website) -- as they may yield outputs that can lead to harmful, system-level outcomes up to and including remote code execution in agentic systems when effective security controls including guardrails are not in place. The model may generate answers that may be inaccurate, omit key information, include irrelevant or redundant text, or produce socially unacceptable or undesirable text, even if the prompt itself does not include anything explicitly offensive.