Text Generation
MLX
Safetensors
English
NemotronH_Nano_Omni_Reasoning_V3
nemotron
multimodal
mamba2
Mixture of Experts
quantized
rotorquant
apple-silicon
mlx-lm
text-tower-only
conversational
custom_code
2-bit
Instructions to use majentik/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-RotorQuant-MLX-2bit with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MLX
How to use majentik/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-RotorQuant-MLX-2bit with MLX:
# Make sure mlx-lm is installed # pip install --upgrade mlx-lm # Generate text with mlx-lm from mlx_lm import load, generate model, tokenizer = load("majentik/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-RotorQuant-MLX-2bit") prompt = "Write a story about Einstein" messages = [{"role": "user", "content": prompt}] prompt = tokenizer.apply_chat_template( messages, add_generation_prompt=True ) text = generate(model, tokenizer, prompt=prompt, verbose=True) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- LM Studio
- Pi
How to use majentik/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-RotorQuant-MLX-2bit with Pi:
Start the MLX server
# Install MLX LM: uv tool install mlx-lm # Start a local OpenAI-compatible server: mlx_lm.server --model "majentik/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-RotorQuant-MLX-2bit"
Configure the model in Pi
# Install Pi: npm install -g @mariozechner/pi-coding-agent # Add to ~/.pi/agent/models.json: { "providers": { "mlx-lm": { "baseUrl": "http://localhost:8080/v1", "api": "openai-completions", "apiKey": "none", "models": [ { "id": "majentik/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-RotorQuant-MLX-2bit" } ] } } }Run Pi
# Start Pi in your project directory: pi
- Hermes Agent new
How to use majentik/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-RotorQuant-MLX-2bit with Hermes Agent:
Start the MLX server
# Install MLX LM: uv tool install mlx-lm # Start a local OpenAI-compatible server: mlx_lm.server --model "majentik/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-RotorQuant-MLX-2bit"
Configure Hermes
# Install Hermes: curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash hermes setup # Point Hermes at the local server: hermes config set model.provider custom hermes config set model.base_url http://127.0.0.1:8080/v1 hermes config set model.default majentik/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-RotorQuant-MLX-2bit
Run Hermes
hermes
- OpenClaw new
How to use majentik/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-RotorQuant-MLX-2bit with OpenClaw:
Start the MLX server
# Install MLX LM: uv tool install mlx-lm # Start a local OpenAI-compatible server: mlx_lm.server --model "majentik/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-RotorQuant-MLX-2bit"
Configure OpenClaw
# Install OpenClaw: npm install -g openclaw@latest # Register the local server and set it as the default model: openclaw onboard --non-interactive --mode local \ --auth-choice custom-api-key \ --custom-base-url http://127.0.0.1:8080/v1 \ --custom-model-id "majentik/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-RotorQuant-MLX-2bit" \ --custom-provider-id mlx-lm \ --custom-compatibility openai \ --custom-text-input \ --accept-risk \ --skip-health
Run OpenClaw
openclaw agent --local --agent main --message "Hello from Hugging Face"
- MLX LM
How to use majentik/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-RotorQuant-MLX-2bit with MLX LM:
Generate or start a chat session
# Install MLX LM uv tool install mlx-lm # Interactive chat REPL mlx_lm.chat --model "majentik/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-RotorQuant-MLX-2bit"
Run an OpenAI-compatible server
# Install MLX LM uv tool install mlx-lm # Start the server mlx_lm.server --model "majentik/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-RotorQuant-MLX-2bit" # Calling the OpenAI-compatible server with curl curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "majentik/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-RotorQuant-MLX-2bit", "messages": [ {"role": "user", "content": "Hello"} ] }'
feat: upload RotorQuant-MLX-2bit (text-tower quantized; encoders BF16)
Browse files- .gitattributes +1 -0
- LICENSE +126 -0
- README.md +53 -0
- audio_model.py +174 -0
- chat_template.jinja +273 -0
- config.json +371 -0
- configuration.py +123 -0
- configuration_nemotron_h.py +276 -0
- configuration_radio.py +152 -0
- evs.py +73 -0
- generation_config.json +14 -0
- image_processing.py +228 -0
- model-00001-of-00003.safetensors +3 -0
- model-00002-of-00003.safetensors +3 -0
- model-00003-of-00003.safetensors +3 -0
- model.safetensors.index.json +0 -0
- modeling.py +638 -0
- modeling_nemotron_h.py +1368 -0
- preprocessor_config.json +15 -0
- processing.py +509 -0
- processing_utils.py +83 -0
- special_tokens_map.json +23 -0
- tokenizer.json +3 -0
- tokenizer_config.json +0 -0
- video_io.py +166 -0
- video_processing.py +166 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* 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
|
|
|
|
|
|
| 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
|
LICENSE
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
NVIDIA Open Model License Agreement
|
| 2 |
+
This NVIDIA Open Model License Agreement (the “Agreement”) is a legal agreement between the Legal Entity You represent, or if no
|
| 3 |
+
entity is identified, You and NVIDIA Corporation and its Affiliates (“NVIDIA”) and governs Your use of the Models that NVIDIA
|
| 4 |
+
provides to You under this Agreement. NVIDIA and You are each a “party” and collectively the “parties.”
|
| 5 |
+
NVIDIA models released under this Agreement are intended to be used permissively and enable the further development of AI
|
| 6 |
+
technologies. Subject to the terms of this Agreement, NVIDIA confirms that:
|
| 7 |
+
•
|
| 8 |
+
|
| 9 |
+
Models are commercially useable.
|
| 10 |
+
|
| 11 |
+
•
|
| 12 |
+
|
| 13 |
+
You are free to create and distribute Derivative Models.
|
| 14 |
+
|
| 15 |
+
•
|
| 16 |
+
|
| 17 |
+
NVIDIA does not claim ownership to any outputs generated using the Models or Model Derivatives.
|
| 18 |
+
|
| 19 |
+
By using, reproducing, modifying, distributing, performing or displaying any portion or element of the Model or Derivative Model, or
|
| 20 |
+
otherwise accepting the terms of this Agreement, you agree to be bound by this Agreement.
|
| 21 |
+
1.
|
| 22 |
+
|
| 23 |
+
Definitions. The following definitions apply to this Agreement:
|
| 24 |
+
|
| 25 |
+
1.1.
|
| 26 |
+
|
| 27 |
+
“Derivative Model” means all (a) modifications to the Model, (b) works based on the Model, and (c) any other derivative
|
| 28 |
+
works of the Model. An output is not a Derivative Model.
|
| 29 |
+
|
| 30 |
+
1.2.
|
| 31 |
+
|
| 32 |
+
“Legal Entity” means the union of the acting entity and all other entities that control, are controlled by, or are under common
|
| 33 |
+
control with that entity. For the purposes of this definition, “control” means (a) the power, direct or indirect, to cause the
|
| 34 |
+
direction or management of such entity, whether by contract or otherwise, or (b) ownership of fifty percent (50%) or more
|
| 35 |
+
of the outstanding shares, or (c) beneficial ownership of such entity.
|
| 36 |
+
|
| 37 |
+
1.3.
|
| 38 |
+
|
| 39 |
+
“Model” means the machine learning model, software, checkpoints, learnt weights, algorithms, parameters, configuration
|
| 40 |
+
files and documentation shared under this Agreement.
|
| 41 |
+
|
| 42 |
+
1.4.
|
| 43 |
+
|
| 44 |
+
“You” or “Your” means an individual or Legal Entity exercising permissions granted by this Agreement.
|
| 45 |
+
|
| 46 |
+
2.
|
| 47 |
+
|
| 48 |
+
Conditions for Use, License Grant, AI Ethics and IP Ownership.
|
| 49 |
+
|
| 50 |
+
2.1.
|
| 51 |
+
Conditions for Use. The Model and any Derivative Model are subject to additional terms as described in Section 2 and
|
| 52 |
+
Section 3 of this Agreement and govern Your use. If You institute copyright or patent litigation against any entity (including a crossclaim or counterclaim in a lawsuit) alleging that the Model or a Derivative Model constitutes direct or contributory copyright or
|
| 53 |
+
patent infringement, then any licenses granted to You under this Agreement for that Model or Derivative Model will terminate as of
|
| 54 |
+
the date such litigation is filed. NVIDIA may update this Agreement to comply with legal and regulatory requirements at any time
|
| 55 |
+
and You agree to either comply with any updated license or cease Your copying, use, and distribution of the Model and any
|
| 56 |
+
Derivative Model.
|
| 57 |
+
2.2.
|
| 58 |
+
License Grant. The rights granted herein are explicitly conditioned on Your full compliance with the terms of this
|
| 59 |
+
Agreement. Subject to the terms and conditions of this Agreement, NVIDIA hereby grants to You a perpetual, worldwide, nonexclusive, no-charge, royalty-free, revocable (as stated in Section 2.1) license to publicly perform, publicly display, reproduce, use,
|
| 60 |
+
create derivative works of, make, have made, sell, offer for sale, distribute (through multiple tiers of distribution) and import the
|
| 61 |
+
Model.
|
| 62 |
+
2.3.
|
| 63 |
+
AI Ethics. NVIDIA is committed to safety, trust and transparency in AI development. NVIDIA encourages You to (a) ensure
|
| 64 |
+
that the product or service You develop, use, offer as a service or distributes meets the legal and ethical requirements of the
|
| 65 |
+
relevant industry or use case, (b) take reasonable measures to address unintended bias and to mitigate harm to others, including
|
| 66 |
+
underrepresented or vulnerable groups, and (c) inform users of the nature and limitations of the product or service. NVIDIA
|
| 67 |
+
expressly prohibits the use of its products or services for any purpose in violation of applicable law or regulation, including but not
|
| 68 |
+
limited to (a) illegal surveillance, (b) illegal collection or processing of biometric information without the consent of the subject
|
| 69 |
+
where required under applicable law, or (c) illegal harassment, abuse, threatening or bullying of individuals or groups of individuals
|
| 70 |
+
or intentionally misleading or deceiving others.
|
| 71 |
+
2.4.
|
| 72 |
+
NVIDIA owns the Model and any Model Derivatives created by NVIDIA. Subject to NVIDIA’s underlying ownership rights in
|
| 73 |
+
the Model or its Model Derivatives, You are and will be the owner of Your Model Derivatives. NVIDIA claims no ownership rights in
|
| 74 |
+
outputs. You are responsible for outputs and their subsequent uses. Except as expressly granted in this Agreement, (a) NVIDIA
|
| 75 |
+
reserves all rights, interests and remedies in connection with the Model and (b) no other license or right is granted to you by
|
| 76 |
+
implication, estoppel or otherwise.
|
| 77 |
+
3.
|
| 78 |
+
Redistribution. You may reproduce and distribute copies of the Model or Derivative Models thereof in any medium, with or
|
| 79 |
+
without modifications, provided that You meet the following conditions:
|
| 80 |
+
|
| 81 |
+
3.1.
|
| 82 |
+
If you distribute the Model, You must give any other recipients of the Model a copy of this Agreement and include the
|
| 83 |
+
following attribution notice within a “Notice” text file with such copies: “Licensed by NVIDIA Corporation under the NVIDIA Open
|
| 84 |
+
Model License”; and
|
| 85 |
+
3.2.
|
| 86 |
+
You may add Your own copyright statement to Your modifications and may provide additional or different license terms
|
| 87 |
+
and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Models as a whole, provided
|
| 88 |
+
Your use, reproduction, and distribution of the Model otherwise complies with the conditions stated in this Agreement.
|
| 89 |
+
4.
|
| 90 |
+
Trademarks. This Agreement does not grant permission to use the trade names, trademarks, service marks, or product
|
| 91 |
+
names of NVIDIA, except as required for reasonable and customary use in describing the origin of the Model and reproducing the
|
| 92 |
+
content of the “Notice” text file.
|
| 93 |
+
5.
|
| 94 |
+
Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, NVIDIA provides the Model on an “AS
|
| 95 |
+
IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any
|
| 96 |
+
warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
|
| 97 |
+
solely responsible for determining the appropriateness of using or redistributing the Model, Derivative Models and outputs and
|
| 98 |
+
assume any risks associated with Your exercise of permissions under this Agreement.
|
| 99 |
+
6.
|
| 100 |
+
Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or
|
| 101 |
+
otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, will NVIDIA be
|
| 102 |
+
liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a
|
| 103 |
+
result of this Agreement or out of the use or inability to use the Model, Derivative Models or outputs (including but not limited to
|
| 104 |
+
damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or
|
| 105 |
+
losses), even if NVIDIA has been advised of the possibility of such damages.
|
| 106 |
+
7.
|
| 107 |
+
Indemnity. You will indemnify and hold harmless NVIDIA from and against any claim by any third party arising out of or
|
| 108 |
+
related to your use or distribution of the Model, Model Derivatives or outputs.
|
| 109 |
+
8.
|
| 110 |
+
You.
|
| 111 |
+
|
| 112 |
+
Feedback. NVIDIA appreciates your feedback, and You agree that NVIDIA may use it without restriction or compensation to
|
| 113 |
+
|
| 114 |
+
9.
|
| 115 |
+
Governing Law. This Agreement will be governed in all respects by the laws of the United States and the laws of the State
|
| 116 |
+
of Delaware, without regard to conflict of laws principles or the United Nations Convention on Contracts for the International Sale of
|
| 117 |
+
Goods. The state and federal courts residing in Santa Clara County, California will have exclusive jurisdiction over any dispute or
|
| 118 |
+
claim arising out of or related to this Agreement, and the parties irrevocably consent to personal jurisdiction and venue in those
|
| 119 |
+
courts; except that, either party may apply for injunctive remedies or an equivalent type of urgent legal relief in any jurisdiction.
|
| 120 |
+
10.
|
| 121 |
+
Trade and Compliance. You agree to comply with all applicable export, import, trade and economic sanctions laws and
|
| 122 |
+
regulations, as amended, including without limitation U.S. Export Administration Regulations and Office of Foreign Assets Control
|
| 123 |
+
regulations. These laws include restrictions on destinations, end-users and end-use.
|
| 124 |
+
Version Release Date: June 14, 2024
|
| 125 |
+
|
| 126 |
+
|
README.md
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: other
|
| 3 |
+
license_name: nvidia-open-model-license
|
| 4 |
+
license_link: https://developer.download.nvidia.com/licenses/nvidia-open-model-license-agreement-june-2024.pdf
|
| 5 |
+
base_model: nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16
|
| 6 |
+
tags: [nemotron, multimodal, mamba2, moe, quantized, rotorquant, mlx]
|
| 7 |
+
---
|
| 8 |
+
|
| 9 |
+
# Nemotron-3-Nano-Omni-30B-A3B-Reasoning - RotorQuant MLX 2-bit
|
| 10 |
+
|
| 11 |
+
MLX 2-bit quantization of the **text tower** of `Nemotron-3-Nano-Omni-30B-A3B-Reasoning` (`nvidia/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-BF16`)
|
| 12 |
+
with RotorQuant weight method. Apple Silicon native via `mlx-lm`.
|
| 13 |
+
|
| 14 |
+
This variant covers the LLM backbone only. Vision (CRADIO v4-H) + audio (Parakeet-TDT-0.6B-v2)
|
| 15 |
+
encoders are NOT included — MLX-VLM Nemotron-Omni model class is **pending upstream support**
|
| 16 |
+
(no PR observed as of 2026-05-04). For multimodal inference, use the GGUF variants with
|
| 17 |
+
`llama-mtmd-cli` instead.
|
| 18 |
+
|
| 19 |
+
For the matched-KV stack — RotorQuant weights + RotorQuant KV-cache modifier —
|
| 20 |
+
see [`majentik/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-RotorQuant-MLX-2bit-RQ-KV`](https://huggingface.co/majentik/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-RotorQuant-MLX-2bit-RQ-KV).
|
| 21 |
+
For the runtime KV-cache modifier itself, see
|
| 22 |
+
[`majentik/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-RotorQuant`](https://huggingface.co/majentik/Nemotron-3-Nano-Omni-30B-A3B-Reasoning-RotorQuant).
|
| 23 |
+
|
| 24 |
+
## Modality matrix
|
| 25 |
+
|
| 26 |
+
| Modality | Encoder | Quantization in this variant |
|
| 27 |
+
|---|---|---|
|
| 28 |
+
| Text | LLM backbone (Mamba-2 + Transformer hybrid Sparse MoE) | per the variant suffix |
|
| 29 |
+
| Image | CRADIO v4-H | **BF16** (kept full-precision in every non-GGUF variant; GGUF uses mmproj-F16 split file) |
|
| 30 |
+
| Audio | Parakeet-TDT-0.6B-v2 | **BF16** (same rationale) |
|
| 31 |
+
| Video | Parakeet-TDT-0.6B-v2 + frame sampler | **BF16** (≤ 2 min, 256 frames @ 2 FPS) |
|
| 32 |
+
|
| 33 |
+
NVIDIA's official FP8 / NVFP4 recipe keeps both encoders + the cross-modal
|
| 34 |
+
MLP projectors in BF16 to preserve multimodal accuracy. We follow that
|
| 35 |
+
convention in every quantized variant we ship.
|
| 36 |
+
|
| 37 |
+
## Runtime quirks
|
| 38 |
+
|
| 39 |
+
### MLX-LM (text-only)
|
| 40 |
+
|
| 41 |
+
This variant covers the LLM backbone only. Vision + audio encoders
|
| 42 |
+
are NOT included — MLX-VLM Nemotron-Omni model class is
|
| 43 |
+
**pending upstream support** (no PR observed as of 2026-05-04).
|
| 44 |
+
|
| 45 |
+
Use the `mlx_lm.generate` API; `enable_thinking` is a runtime flag
|
| 46 |
+
(see below).
|
| 47 |
+
|
| 48 |
+
### Reasoning mode
|
| 49 |
+
|
| 50 |
+
`enable_thinking` defaults to `True`. To disable extended reasoning
|
| 51 |
+
(e.g., for latency-sensitive cases), pass `enable_thinking=False`
|
| 52 |
+
to the chat template / generate call. No separate "no-think"
|
| 53 |
+
variant card exists — this is a runtime flag, not a model variant.
|
audio_model.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""Sound/Audio model components for multimodal integration.
|
| 16 |
+
|
| 17 |
+
This module provides the SoundEncoder (wrapping Parakeet from HuggingFace transformers)
|
| 18 |
+
and SoundProjection (MLP to project audio embeddings to LLM hidden size).
|
| 19 |
+
|
| 20 |
+
The Parakeet model in HuggingFace transformers is documented at:
|
| 21 |
+
https://huggingface.co/docs/transformers/en/model_doc/parakeet
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
from typing import Optional
|
| 25 |
+
|
| 26 |
+
import torch
|
| 27 |
+
import torch.nn as nn
|
| 28 |
+
|
| 29 |
+
from transformers import ParakeetEncoder, ParakeetEncoderConfig
|
| 30 |
+
from transformers.utils import logging
|
| 31 |
+
|
| 32 |
+
logger = logging.get_logger(__name__)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class SquaredReLU(nn.Module):
|
| 36 |
+
"""Squared ReLU activation function."""
|
| 37 |
+
def forward(self, x):
|
| 38 |
+
return torch.pow(torch.nn.functional.relu(x), 2)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class RMSNorm(nn.Module):
|
| 42 |
+
def __init__(self, hidden_size, eps=1e-5):
|
| 43 |
+
super().__init__()
|
| 44 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 45 |
+
self.eps = eps
|
| 46 |
+
|
| 47 |
+
def forward(self, hidden_states):
|
| 48 |
+
input_dtype = hidden_states.dtype
|
| 49 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 50 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 51 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
|
| 52 |
+
return (self.weight.to(torch.float32) * hidden_states).to(input_dtype)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class SoundProjection(nn.Module):
|
| 56 |
+
"""MLP projection from sound encoder hidden size to LLM hidden size.
|
| 57 |
+
|
| 58 |
+
Architecture: RMSNorm -> linear1 -> SquaredReLU -> linear2
|
| 59 |
+
|
| 60 |
+
This matches the Megatron checkpoint conversion structure:
|
| 61 |
+
- sound_projection.norm.weight
|
| 62 |
+
- sound_projection.linear1.weight
|
| 63 |
+
- sound_projection.linear2.weight
|
| 64 |
+
- sound_projection.linear1.bias (optional)
|
| 65 |
+
- sound_projection.linear2.bias (optional)
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
def __init__(
|
| 69 |
+
self,
|
| 70 |
+
sound_hidden_size: int,
|
| 71 |
+
projection_hidden_size: int,
|
| 72 |
+
llm_hidden_size: int,
|
| 73 |
+
bias: bool = True,
|
| 74 |
+
eps: float = 1e-5,
|
| 75 |
+
):
|
| 76 |
+
super().__init__()
|
| 77 |
+
self.norm = RMSNorm(sound_hidden_size, eps=eps)
|
| 78 |
+
self.linear1 = nn.Linear(sound_hidden_size, projection_hidden_size, bias=bias)
|
| 79 |
+
self.activation = SquaredReLU()
|
| 80 |
+
self.linear2 = nn.Linear(projection_hidden_size, llm_hidden_size, bias=bias)
|
| 81 |
+
|
| 82 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 83 |
+
"""Project sound embeddings to LLM embedding space.
|
| 84 |
+
|
| 85 |
+
Args:
|
| 86 |
+
hidden_states: Sound encoder output [batch, seq_len, sound_hidden_size]
|
| 87 |
+
|
| 88 |
+
Returns:
|
| 89 |
+
Projected embeddings [batch, seq_len, llm_hidden_size]
|
| 90 |
+
"""
|
| 91 |
+
hidden_states = self.norm(hidden_states)
|
| 92 |
+
hidden_states = self.linear1(hidden_states)
|
| 93 |
+
hidden_states = self.activation(hidden_states)
|
| 94 |
+
hidden_states = self.linear2(hidden_states)
|
| 95 |
+
return hidden_states
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class SoundEncoder(nn.Module):
|
| 99 |
+
"""Wrapper around the Parakeet encoder from HuggingFace transformers.
|
| 100 |
+
|
| 101 |
+
The Parakeet model is an ASR model with a Fast Conformer encoder.
|
| 102 |
+
We use only the encoder portion to extract audio embeddings.
|
| 103 |
+
|
| 104 |
+
Checkpoint structure:
|
| 105 |
+
- sound_encoder.encoder.feature_extractor.* -> Feature extraction (mel spectrogram)
|
| 106 |
+
- sound_encoder.encoder.pre_encode.* -> Pre-encoding convolutions
|
| 107 |
+
- sound_encoder.encoder.layers.* -> Conformer layers
|
| 108 |
+
|
| 109 |
+
Reference: https://huggingface.co/docs/transformers/en/model_doc/parakeet
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
def __init__(self, config=None):
|
| 113 |
+
super().__init__()
|
| 114 |
+
|
| 115 |
+
if config is not None:
|
| 116 |
+
# Build from config - handle both dict and config object
|
| 117 |
+
if hasattr(config, '__dict__'):
|
| 118 |
+
# It's a config object, extract relevant params for ParakeetConfig
|
| 119 |
+
config_dict = {
|
| 120 |
+
'attention_bias': getattr(config, 'attention_bias', False),
|
| 121 |
+
'hidden_size': getattr(config, 'hidden_size', 1024),
|
| 122 |
+
'num_attention_heads': getattr(config, 'num_attention_heads', 8),
|
| 123 |
+
'num_hidden_layers': getattr(config, 'num_hidden_layers', 24),
|
| 124 |
+
'intermediate_size': getattr(config, 'intermediate_size', 4096),
|
| 125 |
+
'conv_kernel_size': getattr(config, 'conv_kernel_size', 31),
|
| 126 |
+
'convolution_bias': getattr(config, 'convolution_bias', False),
|
| 127 |
+
'feat_in': getattr(config, 'feat_in', 80),
|
| 128 |
+
'subsampling_factor': getattr(config, 'subsampling_factor', 8),
|
| 129 |
+
'subsampling_conv_channels': getattr(config, 'subsampling_conv_channels', 256),
|
| 130 |
+
'subsampling_conv_kernel_size': getattr(config, 'subsampling_conv_kernel_size', 3),
|
| 131 |
+
'subsampling_conv_stride': getattr(config, 'subsampling_conv_stride', 2),
|
| 132 |
+
'num_mel_bins': getattr(config, 'num_mel_bins', 128),
|
| 133 |
+
'scale_input': getattr(config, 'scale_input', False),
|
| 134 |
+
}
|
| 135 |
+
elif isinstance(config, dict):
|
| 136 |
+
config_dict = config
|
| 137 |
+
else:
|
| 138 |
+
config_dict = {}
|
| 139 |
+
|
| 140 |
+
# Create ParakeetConfig with the extracted parameters
|
| 141 |
+
parakeet_config = ParakeetEncoderConfig(**config_dict)
|
| 142 |
+
self.config = parakeet_config
|
| 143 |
+
self.encoder = ParakeetEncoder(parakeet_config)
|
| 144 |
+
else:
|
| 145 |
+
raise ValueError(
|
| 146 |
+
"config must be provided, "
|
| 147 |
+
"and ParakeetEncoder must be available in transformers."
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
def forward(
|
| 151 |
+
self,
|
| 152 |
+
input_features: torch.Tensor,
|
| 153 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 154 |
+
) -> torch.Tensor:
|
| 155 |
+
"""Encode audio features.
|
| 156 |
+
|
| 157 |
+
Args:
|
| 158 |
+
input_features: Mel spectrogram features [batch, seq_len, feature_dim]
|
| 159 |
+
attention_mask: Optional attention mask [batch, seq_len]
|
| 160 |
+
|
| 161 |
+
Returns:
|
| 162 |
+
Audio embeddings [batch, encoded_seq_len, hidden_size]
|
| 163 |
+
"""
|
| 164 |
+
outputs = self.encoder(
|
| 165 |
+
input_features=input_features,
|
| 166 |
+
attention_mask=attention_mask,
|
| 167 |
+
)
|
| 168 |
+
# Return the last hidden state
|
| 169 |
+
return outputs.last_hidden_state
|
| 170 |
+
|
| 171 |
+
@property
|
| 172 |
+
def hidden_size(self) -> int:
|
| 173 |
+
"""Return the hidden size of the encoder."""
|
| 174 |
+
return self.config.hidden_size
|
chat_template.jinja
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{% macro render_extra_keys(json_dict, handled_keys) %}
|
| 2 |
+
{%- if json_dict is mapping %}
|
| 3 |
+
{%- for json_key in json_dict if json_key not in handled_keys %}
|
| 4 |
+
{%- if json_dict[json_key] is mapping or (json_dict[json_key] is sequence and json_dict[json_key] is not string) %}
|
| 5 |
+
{{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | tojson | safe) ~ '</' ~ json_key ~ '>' }}
|
| 6 |
+
{%- else %}
|
| 7 |
+
{{- '\n<' ~ json_key ~ '>' ~ (json_dict[json_key] | string) ~ '</' ~ json_key ~ '>' }}
|
| 8 |
+
{%- endif %}
|
| 9 |
+
{%- endfor %}
|
| 10 |
+
{%- endif %}
|
| 11 |
+
{%- endmacro -%}
|
| 12 |
+
{%- set enable_thinking = enable_thinking if enable_thinking is defined else True %}
|
| 13 |
+
{%- set reasoning_budget = reasoning_budget if reasoning_budget is defined else None %}
|
| 14 |
+
{%- set truncate_history_thinking = truncate_history_thinking if truncate_history_thinking is defined else True %}
|
| 15 |
+
|
| 16 |
+
{#- Scan messages for VLM thinking toggles to override enable_thinking -#}
|
| 17 |
+
{%- set toggle = namespace(enable=enable_thinking) %}
|
| 18 |
+
{%- for m in messages %}
|
| 19 |
+
{%- if m['role'] == 'user' or m['role'] == 'system' -%}
|
| 20 |
+
{%- if m['content'] is string -%}
|
| 21 |
+
{%- set c = m['content'] %}
|
| 22 |
+
{%- if '/think' in c.replace('</think>', '') -%}
|
| 23 |
+
{%- set toggle.enable = true -%}
|
| 24 |
+
{%- elif '/no_think' in c -%}
|
| 25 |
+
{%- set toggle.enable = false -%}
|
| 26 |
+
{%- endif -%}
|
| 27 |
+
{%- else -%}
|
| 28 |
+
{%- for part in m['content'] -%}
|
| 29 |
+
{%- if part['type'] == 'text' -%}
|
| 30 |
+
{%- set c = part['text'] %}
|
| 31 |
+
{%- if '/think' in c.replace('</think>', '') -%}
|
| 32 |
+
{%- set toggle.enable = true -%}
|
| 33 |
+
{%- elif '/no_think' in c -%}
|
| 34 |
+
{%- set toggle.enable = false -%}
|
| 35 |
+
{%- endif -%}
|
| 36 |
+
{%- endif -%}
|
| 37 |
+
{%- endfor -%}
|
| 38 |
+
{%- endif -%}
|
| 39 |
+
{%- endif -%}
|
| 40 |
+
{%- endfor -%}
|
| 41 |
+
{#- Prepare message iteration similar to LM template -#}
|
| 42 |
+
{%- set ns = namespace(last_user_idx = -1) %}
|
| 43 |
+
{%- set loop_messages = messages %}
|
| 44 |
+
{%- for m in loop_messages %}
|
| 45 |
+
{%- if m["role"] == "user" %}
|
| 46 |
+
{%- set ns.last_user_idx = loop.index0 %}
|
| 47 |
+
{%- endif %}
|
| 48 |
+
{%- endfor -%}
|
| 49 |
+
|
| 50 |
+
{%- if messages[0]["role"] == "system" %}
|
| 51 |
+
{%- set system_message = messages[0]["content"] %}
|
| 52 |
+
{%- set loop_messages = messages[1:] %}
|
| 53 |
+
{%- else %}
|
| 54 |
+
{%- set system_message = "" %}
|
| 55 |
+
{%- set loop_messages = messages %}
|
| 56 |
+
{%- endif %}
|
| 57 |
+
{%- if not tools is defined %}
|
| 58 |
+
{%- set tools = [] %}
|
| 59 |
+
{%- endif %}
|
| 60 |
+
{#- Recompute last_user_idx relative to loop_messages after handling system -#}
|
| 61 |
+
{%- set ns = namespace(last_user_idx = -1) %}
|
| 62 |
+
{%- for m in loop_messages %}
|
| 63 |
+
{%- if m["role"] == "user" %}
|
| 64 |
+
{%- set ns.last_user_idx = loop.index0 %}
|
| 65 |
+
{%- endif %}
|
| 66 |
+
{%- endfor -%}
|
| 67 |
+
{#- System preamble with LM formatting, sanitize thinking toggles -#}
|
| 68 |
+
{%- if system_message is defined %}
|
| 69 |
+
{%- set sys_content = system_message | string %}
|
| 70 |
+
{%- set sys_content = sys_content.replace('</think>', '<_end_think>').replace('/think', '').replace('/no_think', '').replace('<_end_think>', '</think>') %}
|
| 71 |
+
{{- "<|im_start|>system\n" + sys_content }}
|
| 72 |
+
{%- else %}
|
| 73 |
+
{%- if tools is iterable and tools | length > 0 %}
|
| 74 |
+
{{- "<|im_start|>system\n" }}
|
| 75 |
+
{%- endif %}
|
| 76 |
+
{%- endif %}
|
| 77 |
+
{%- if tools is iterable and tools | length > 0 %}
|
| 78 |
+
{%- if system_message is defined and system_message | length > 0 %}
|
| 79 |
+
{{- "\n\n" }}
|
| 80 |
+
{%- endif %}
|
| 81 |
+
{{- "# Tools\n\nYou have access to the following functions:\n\n" }}
|
| 82 |
+
{{- "<tools>" }}
|
| 83 |
+
{%- for tool in tools %}
|
| 84 |
+
{%- if tool.function is defined %}
|
| 85 |
+
{%- set tool = tool.function %}
|
| 86 |
+
{%- endif %}
|
| 87 |
+
{{- "\n<function>\n<name>" ~ tool.name ~ "</name>" }}
|
| 88 |
+
{%- if tool.description is defined %}
|
| 89 |
+
{{- '\n<description>' ~ (tool.description | trim) ~ '</description>' }}
|
| 90 |
+
{%- endif %}
|
| 91 |
+
{{- '\n<parameters>' }}
|
| 92 |
+
{%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %}
|
| 93 |
+
{%- for param_name, param_fields in tool.parameters.properties|items %}
|
| 94 |
+
{{- '\n<parameter>' }}
|
| 95 |
+
{{- '\n<name>' ~ param_name ~ '</name>' }}
|
| 96 |
+
{%- if param_fields.type is defined %}
|
| 97 |
+
{{- '\n<type>' ~ (param_fields.type | string) ~ '</type>' }}
|
| 98 |
+
{%- endif %}
|
| 99 |
+
{%- if param_fields.description is defined %}
|
| 100 |
+
{{- '\n<description>' ~ (param_fields.description | trim) ~ '</description>' }}
|
| 101 |
+
{%- endif %}
|
| 102 |
+
{%- if param_fields.enum is defined %}
|
| 103 |
+
{{- '\n<enum>' ~ (param_fields.enum | tojson | safe) ~ '</enum>' }}
|
| 104 |
+
{%- endif %}
|
| 105 |
+
{%- set handled_keys = ['name', 'type', 'description', 'enum'] %}
|
| 106 |
+
{{- render_extra_keys(param_fields, handled_keys) }}
|
| 107 |
+
{{- '\n</parameter>' }}
|
| 108 |
+
{%- endfor %}
|
| 109 |
+
{%- endif %}
|
| 110 |
+
{%- set handled_keys = ['type', 'properties', 'required'] %}
|
| 111 |
+
{{- render_extra_keys(tool.parameters, handled_keys) }}
|
| 112 |
+
{%- if tool.parameters is defined and tool.parameters.required is defined %}
|
| 113 |
+
{{- '\n<required>' ~ (tool.parameters.required | tojson | safe) ~ '</required>' }}
|
| 114 |
+
{%- endif %}
|
| 115 |
+
{{- '\n</parameters>' }}
|
| 116 |
+
{%- set handled_keys = ['type', 'name', 'description', 'parameters'] %}
|
| 117 |
+
{{- render_extra_keys(tool, handled_keys) }}
|
| 118 |
+
{{- '\n</function>' }}
|
| 119 |
+
{%- endfor %}
|
| 120 |
+
{{- "\n</tools>" }}
|
| 121 |
+
|
| 122 |
+
{{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
|
| 123 |
+
{%- endif -%}
|
| 124 |
+
{%- if system_message is defined %}
|
| 125 |
+
{{- '<|im_end|>\n' }}
|
| 126 |
+
{%- else %}
|
| 127 |
+
{%- if tools is iterable and tools | length > 0 %}
|
| 128 |
+
{{- '<|im_end|>\n' }}
|
| 129 |
+
{%- endif %}
|
| 130 |
+
{%- endif -%}
|
| 131 |
+
{#- Iterate conversation -#}
|
| 132 |
+
{%- for message in loop_messages %}
|
| 133 |
+
{%- if message.role == "assistant" %}
|
| 134 |
+
{#- Use LM assistant handling -#}
|
| 135 |
+
{%- if message.reasoning_content is defined and message.reasoning_content is string and message.reasoning_content | trim | length > 0 %}
|
| 136 |
+
{%- set content = "<think>\n" ~ message.reasoning_content ~ "\n</think>\n" ~ (message.content | default('', true)) %}
|
| 137 |
+
{%- else %}
|
| 138 |
+
{%- set content = message.content | default('', true) %}
|
| 139 |
+
{%- if content is string -%}
|
| 140 |
+
{%- if '<think>' not in content and '</think>' not in content -%}
|
| 141 |
+
{%- set content = "<think></think>" ~ content -%}
|
| 142 |
+
{%- endif -%}
|
| 143 |
+
{%- else -%}
|
| 144 |
+
{%- set content = content -%}
|
| 145 |
+
{%- endif -%}
|
| 146 |
+
{%- endif %}
|
| 147 |
+
{%- if message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %}
|
| 148 |
+
{{- '<|im_start|>assistant\n' }}
|
| 149 |
+
{%- set include_content = not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %}
|
| 150 |
+
{%- if content is string and content | trim | length > 0 %}
|
| 151 |
+
{%- if include_content %}
|
| 152 |
+
{{- (content | trim) ~ '\n' -}}
|
| 153 |
+
{%- else %}
|
| 154 |
+
{%- set c = (content | string) %}
|
| 155 |
+
{%- if '</think>' in c %}
|
| 156 |
+
{%- set c = c.split('</think>')[-1] %}
|
| 157 |
+
{%- elif '<think>' in c %}
|
| 158 |
+
{%- set c = c.split('<think>')[0] %}
|
| 159 |
+
{%- endif %}
|
| 160 |
+
{%- set c = "<think></think>" ~ c | trim %}
|
| 161 |
+
{%- if c | length > 0 %}
|
| 162 |
+
{{- c ~ '\n' -}}
|
| 163 |
+
{%- endif %}
|
| 164 |
+
{%- endif %}
|
| 165 |
+
{%- else %}
|
| 166 |
+
{{- "<think></think>" -}}
|
| 167 |
+
{%- endif %}
|
| 168 |
+
{%- for tool_call in message.tool_calls %}
|
| 169 |
+
{%- if tool_call.function is defined %}
|
| 170 |
+
{%- set tool_call = tool_call.function %}
|
| 171 |
+
{%- endif %}
|
| 172 |
+
{{- '<tool_call>\n<function=' ~ tool_call.name ~ '>\n' -}}
|
| 173 |
+
{%- if tool_call.arguments is defined %}
|
| 174 |
+
{%- for args_name, args_value in tool_call.arguments|items %}
|
| 175 |
+
{{- '<parameter=' ~ args_name ~ '>\n' -}}
|
| 176 |
+
{%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %}
|
| 177 |
+
{{- args_value ~ '\n</parameter>\n' -}}
|
| 178 |
+
{%- endfor %}
|
| 179 |
+
{%- endif %}
|
| 180 |
+
{{- '</function>\n</tool_call>\n' -}}
|
| 181 |
+
{%- endfor %}
|
| 182 |
+
{{- '<|im_end|>\n' }}
|
| 183 |
+
{%- else %}
|
| 184 |
+
{%- if not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %}
|
| 185 |
+
{{- '<|im_start|>assistant\n' ~ (content | default('', true) | string | trim) ~ '<|im_end|>\n' }}
|
| 186 |
+
{%- else %}
|
| 187 |
+
{%- set c = (content | default('', true) | string) %}
|
| 188 |
+
{%- if '<think>' in c and '</think>' in c %}
|
| 189 |
+
{%- set c = "<think></think>" ~ c.split('</think>')[-1] %}
|
| 190 |
+
{%- endif %}
|
| 191 |
+
{%- set c = c | trim %}
|
| 192 |
+
{%- if c | length > 0 %}
|
| 193 |
+
{{- '<|im_start|>assistant\n' ~ c ~ '<|im_end|>\n' }}
|
| 194 |
+
{%- else %}
|
| 195 |
+
{{- '<|im_start|>assistant\n<|im_end|>\n' }}
|
| 196 |
+
{%- endif %}
|
| 197 |
+
{%- endif %}
|
| 198 |
+
{%- endif %}
|
| 199 |
+
{%- elif message.role == "user" or message.role == "system" %}
|
| 200 |
+
{{- '<|im_start|>' + message.role + '\n' }}
|
| 201 |
+
{#- Build VLM multimodal content when content is a sequence -#}
|
| 202 |
+
{%- if message.content is string -%}
|
| 203 |
+
{%- set content = (message.content | string) %}
|
| 204 |
+
{%- else -%}
|
| 205 |
+
{%- set text_ns = namespace(val='') -%}
|
| 206 |
+
{%- set mm_content = '' -%}
|
| 207 |
+
{%- set counters = namespace(images=0, videos=0, audios=0) -%}
|
| 208 |
+
{%- for part in message['content'] -%}
|
| 209 |
+
{%- if part['type'] == 'image' or part['type'] == 'image_url' -%}
|
| 210 |
+
{%- set counters.images = counters.images + 1 -%}
|
| 211 |
+
{%- elif part['type'] == 'video' or part['type'] == 'video_url' -%}
|
| 212 |
+
{%- set counters.videos = counters.videos + 1 -%}
|
| 213 |
+
{%- elif part['type'] == 'audio' or part['type'] == 'audio_url' -%}
|
| 214 |
+
{%- set counters.audios = counters.audios + 1 -%}
|
| 215 |
+
{%- elif part['type'] == 'text' -%}
|
| 216 |
+
{%- set text_ns.val = text_ns.val + part['text'] -%}
|
| 217 |
+
{%- endif -%}
|
| 218 |
+
{%- endfor -%}
|
| 219 |
+
{%- if '<image>' in text_ns.val -%}
|
| 220 |
+
{%- set counters.images = 0 -%}
|
| 221 |
+
{%- endif -%}
|
| 222 |
+
{%- if '<video>' in text_ns.val -%}
|
| 223 |
+
{%- set counters.videos = 0 -%}
|
| 224 |
+
{%- endif -%}
|
| 225 |
+
{%- if '<so_embedding>' in text_ns.val -%}
|
| 226 |
+
{%- set counters.audios = 0 -%}
|
| 227 |
+
{%- endif -%}
|
| 228 |
+
{%- if counters.images > 1 -%}
|
| 229 |
+
{%- set image_tags = namespace(tags=[]) -%}
|
| 230 |
+
{%- for i in range(counters.images) -%}
|
| 231 |
+
{%- set image_tags.tags = image_tags.tags + ['<image ' + (i + 1)|string + '><image>'] -%}
|
| 232 |
+
{%- endfor -%}
|
| 233 |
+
{%- set mm_content = ' '.join(image_tags.tags) + '\n' -%}
|
| 234 |
+
{%- elif counters.images == 1 -%}
|
| 235 |
+
{%- set mm_content = '<image>\n' -%}
|
| 236 |
+
{%- endif -%}
|
| 237 |
+
{%- set mm_content = mm_content + '<video>\n' * counters.videos -%}
|
| 238 |
+
{%- set mm_content = mm_content + '<so_embedding>\n' * counters.audios -%}
|
| 239 |
+
{%- set content = mm_content + text_ns.val.lstrip('\n') -%}
|
| 240 |
+
{%- endif -%}
|
| 241 |
+
{#- Sanitize thinking toggle directives from user/system content -#}
|
| 242 |
+
{%- set content = content.replace('</think>', '<_end_think>').replace('/think', '').replace('/no_think', '').replace('<_end_think>', '</think>') -%}
|
| 243 |
+
{%- set content = content | trim -%}
|
| 244 |
+
{%- if message.role == "user" and loop.index0 == ns.last_user_idx and reasoning_budget is not none -%}
|
| 245 |
+
{{- content + '\n\n{thinking token budget: ' + (reasoning_budget | string) + '}' -}}
|
| 246 |
+
{%- else -%}
|
| 247 |
+
{{- content -}}
|
| 248 |
+
{%- endif -%}
|
| 249 |
+
{{- '<|im_end|>\n' }}
|
| 250 |
+
{%- elif message.role == "tool" %}
|
| 251 |
+
{%- if loop.previtem and loop.previtem.role != "tool" %}
|
| 252 |
+
{{- '<|im_start|>user\n' }}
|
| 253 |
+
{%- endif %}
|
| 254 |
+
{{- '<tool_response>\n' }}
|
| 255 |
+
{{- message.content }}
|
| 256 |
+
{{- '\n</tool_response>\n' }}
|
| 257 |
+
{%- if not loop.last and loop.nextitem.role != "tool" %}
|
| 258 |
+
{{- '<|im_end|>\n' }}
|
| 259 |
+
{%- elif loop.last %}
|
| 260 |
+
{{- '<|im_end|>\n' }}
|
| 261 |
+
{%- endif %}
|
| 262 |
+
{%- else %}
|
| 263 |
+
{{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' }}
|
| 264 |
+
{%- endif %}
|
| 265 |
+
{%- endfor -%}
|
| 266 |
+
{#- Generation prompt using computed thinking toggle -#}
|
| 267 |
+
{%- if add_generation_prompt %}
|
| 268 |
+
{%- if toggle.enable %}
|
| 269 |
+
{{- '<|im_start|>assistant\n<think>\n' }}
|
| 270 |
+
{%- else %}
|
| 271 |
+
{{- '<|im_start|>assistant\n<think></think>' }}
|
| 272 |
+
{%- endif %}
|
| 273 |
+
{%- endif %}
|
config.json
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"NemotronH_Nano_Omni_Reasoning_V3"
|
| 4 |
+
],
|
| 5 |
+
"auto_map": {
|
| 6 |
+
"AutoConfig": "configuration.NemotronH_Nano_Omni_Reasoning_V3_Config",
|
| 7 |
+
"AutoModel": "modeling.NemotronH_Nano_Omni_Reasoning_V3",
|
| 8 |
+
"AutoModelForCausalLM": "modeling.NemotronH_Nano_Omni_Reasoning_V3"
|
| 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": 11,
|
| 16 |
+
"model_type": "NemotronH_Nano_Omni_Reasoning_V3",
|
| 17 |
+
"ps_version": "v2",
|
| 18 |
+
"template": "n5h_5p5_nanov2",
|
| 19 |
+
"torch_dtype": "bfloat16",
|
| 20 |
+
"image_tag_type": "internvl",
|
| 21 |
+
"img_context_token_id": 18,
|
| 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 |
+
"vit_hidden_size": 1280,
|
| 28 |
+
"projector_hidden_size": 20480,
|
| 29 |
+
"norm_mean": [
|
| 30 |
+
0.48145466,
|
| 31 |
+
0.4578275,
|
| 32 |
+
0.40821073
|
| 33 |
+
],
|
| 34 |
+
"norm_std": [
|
| 35 |
+
0.26862954,
|
| 36 |
+
0.26130258,
|
| 37 |
+
0.27577711
|
| 38 |
+
],
|
| 39 |
+
"video_pruning_rate": 0.7,
|
| 40 |
+
"sound_context_token_id": 27,
|
| 41 |
+
"sound_context_token": "<so_embedding>",
|
| 42 |
+
"sound_config": {
|
| 43 |
+
"model_type": "parakeet",
|
| 44 |
+
"hidden_size": 1024,
|
| 45 |
+
"num_attention_heads": 8,
|
| 46 |
+
"num_hidden_layers": 24,
|
| 47 |
+
"intermediate_size": 4096,
|
| 48 |
+
"conv_kernel_size": 9,
|
| 49 |
+
"convolution_bias": false,
|
| 50 |
+
"subsampling_conv_channels": 256,
|
| 51 |
+
"subsampling_conv_kernel_size": 3,
|
| 52 |
+
"subsampling_conv_stride": 2,
|
| 53 |
+
"subsampling_factor": 8,
|
| 54 |
+
"num_mel_bins": 128,
|
| 55 |
+
"projection_hidden_size": 4096,
|
| 56 |
+
"projection_bias": false,
|
| 57 |
+
"sampling_rate": 16000
|
| 58 |
+
},
|
| 59 |
+
"llm_config": {
|
| 60 |
+
"architectures": [
|
| 61 |
+
"NemotronHForCausalLM"
|
| 62 |
+
],
|
| 63 |
+
"auto_map": {
|
| 64 |
+
"AutoConfig": "configuration_nemotron_h.NemotronHConfig",
|
| 65 |
+
"AutoModelForCausalLM": "modeling_nemotron_h.NemotronHForCausalLM"
|
| 66 |
+
},
|
| 67 |
+
"model_type": "nemotron_h",
|
| 68 |
+
"bos_token_id": 1,
|
| 69 |
+
"chunk_size": 128,
|
| 70 |
+
"conv_kernel": 4,
|
| 71 |
+
"expand": 2,
|
| 72 |
+
"eos_token_id": 11,
|
| 73 |
+
"pad_token_id": 0,
|
| 74 |
+
"torch_dtype": "bfloat16",
|
| 75 |
+
"transformers_version": "4.55.4",
|
| 76 |
+
"attention_bias": false,
|
| 77 |
+
"attention_dropout": 0.0,
|
| 78 |
+
"head_dim": 128,
|
| 79 |
+
"hidden_dropout": 0.0,
|
| 80 |
+
"hidden_size": 2688,
|
| 81 |
+
"hybrid_override_pattern": "MEMEM*EMEMEM*EMEMEM*EMEMEM*EMEMEM*EMEMEMEM*EMEMEMEME",
|
| 82 |
+
"initializer_range": 0.02,
|
| 83 |
+
"intermediate_size": 1856,
|
| 84 |
+
"layer_norm_epsilon": 1e-05,
|
| 85 |
+
"mamba_head_dim": 64,
|
| 86 |
+
"mamba_hidden_act": "silu",
|
| 87 |
+
"mamba_num_heads": 64,
|
| 88 |
+
"mamba_proj_bias": false,
|
| 89 |
+
"max_position_embeddings": 262144,
|
| 90 |
+
"mlp_bias": false,
|
| 91 |
+
"mlp_hidden_act": "relu2",
|
| 92 |
+
"moe_intermediate_size": 1856,
|
| 93 |
+
"moe_shared_expert_intermediate_size": 3712,
|
| 94 |
+
"n_group": 1,
|
| 95 |
+
"n_groups": 8,
|
| 96 |
+
"n_routed_experts": 128,
|
| 97 |
+
"n_shared_experts": 1,
|
| 98 |
+
"norm_eps": 1e-05,
|
| 99 |
+
"norm_topk_prob": true,
|
| 100 |
+
"num_attention_heads": 32,
|
| 101 |
+
"num_experts_per_tok": 6,
|
| 102 |
+
"num_hidden_layers": 52,
|
| 103 |
+
"num_key_value_heads": 2,
|
| 104 |
+
"num_logits_to_keep": 1,
|
| 105 |
+
"partial_rotary_factor": 1.0,
|
| 106 |
+
"rescale_prenorm_residual": true,
|
| 107 |
+
"residual_in_fp32": false,
|
| 108 |
+
"rope_theta": 10000,
|
| 109 |
+
"routed_scaling_factor": 2.5,
|
| 110 |
+
"sliding_window": null,
|
| 111 |
+
"ssm_state_size": 128,
|
| 112 |
+
"tie_word_embeddings": false,
|
| 113 |
+
"time_step_floor": 0.0001,
|
| 114 |
+
"time_step_limit": [
|
| 115 |
+
0.0,
|
| 116 |
+
1e+30
|
| 117 |
+
],
|
| 118 |
+
"time_step_max": 0.1,
|
| 119 |
+
"time_step_min": 0.001,
|
| 120 |
+
"topk_group": 1,
|
| 121 |
+
"use_bias": false,
|
| 122 |
+
"use_cache": true,
|
| 123 |
+
"use_conv_bias": true,
|
| 124 |
+
"use_mamba_kernels": true,
|
| 125 |
+
"vocab_size": 131072
|
| 126 |
+
},
|
| 127 |
+
"vision_config": {
|
| 128 |
+
"auto_map": {
|
| 129 |
+
"AutoConfig": "nvidia/C-RADIOv2-H--hf_model.RADIOConfig",
|
| 130 |
+
"AutoModel": "nvidia/C-RADIOv2-H--hf_model.RADIOModel"
|
| 131 |
+
},
|
| 132 |
+
"adaptor_configs": {},
|
| 133 |
+
"adaptor_names": null,
|
| 134 |
+
"architectures": [
|
| 135 |
+
"RADIOModel"
|
| 136 |
+
],
|
| 137 |
+
"args": {
|
| 138 |
+
"aa": null,
|
| 139 |
+
"amp": true,
|
| 140 |
+
"amp_dtype": "bfloat16",
|
| 141 |
+
"amp_impl": "native",
|
| 142 |
+
"aug_repeats": 0,
|
| 143 |
+
"aug_splits": 0,
|
| 144 |
+
"bn_eps": null,
|
| 145 |
+
"bn_momentum": null,
|
| 146 |
+
"cache_dir": null,
|
| 147 |
+
"channels_last": false,
|
| 148 |
+
"checkpoint_hist": 10,
|
| 149 |
+
"chk_keep_forever": 100,
|
| 150 |
+
"class_map": "",
|
| 151 |
+
"clip_grad": null,
|
| 152 |
+
"clip_mode": "norm",
|
| 153 |
+
"cls_token_per_teacher": true,
|
| 154 |
+
"coco_annotations_file": "/datasets/coco2017-adlsa/annotations/captions_val2017.json",
|
| 155 |
+
"coco_image_dir": "/datasets/coco2017-adlsa/val2017",
|
| 156 |
+
"color_jitter": 0.4,
|
| 157 |
+
"cooldown_epochs": 0,
|
| 158 |
+
"cpe_max_size": 2048,
|
| 159 |
+
"crd_loss": false,
|
| 160 |
+
"crd_loss_weight": 0.8,
|
| 161 |
+
"crop_pct": null,
|
| 162 |
+
"cutmix": 0.0,
|
| 163 |
+
"cutmix_minmax": null,
|
| 164 |
+
"dataset_download": false,
|
| 165 |
+
"debug_full_knn": false,
|
| 166 |
+
"decay_epochs": 90,
|
| 167 |
+
"decay_milestones": [
|
| 168 |
+
90,
|
| 169 |
+
180,
|
| 170 |
+
270
|
| 171 |
+
],
|
| 172 |
+
"decay_rate": 0.1,
|
| 173 |
+
"depchain": true,
|
| 174 |
+
"dist_bn": "reduce",
|
| 175 |
+
"dist_norm_weight": 0.0,
|
| 176 |
+
"distributed": true,
|
| 177 |
+
"drop": 0.0,
|
| 178 |
+
"drop_block": null,
|
| 179 |
+
"drop_connect": null,
|
| 180 |
+
"drop_path": null,
|
| 181 |
+
"dtype": "bfloat16",
|
| 182 |
+
"epoch_repeats": 0.0,
|
| 183 |
+
"eval": false,
|
| 184 |
+
"eval_metric": "knn_top1",
|
| 185 |
+
"eval_teacher": false,
|
| 186 |
+
"eval_teacher_only": false,
|
| 187 |
+
"eval_throughput": false,
|
| 188 |
+
"fast_norm": false,
|
| 189 |
+
"fd_loss_fn": "MSE",
|
| 190 |
+
"feature_normalization": "SHIP_NORM",
|
| 191 |
+
"feature_summarizer": "cls_token",
|
| 192 |
+
"feature_upscale_factor": null,
|
| 193 |
+
"force_new_wandb_id": false,
|
| 194 |
+
"force_spectral_reparam": true,
|
| 195 |
+
"freeze_bn": false,
|
| 196 |
+
"fsdp": false,
|
| 197 |
+
"fuser": "",
|
| 198 |
+
"gp": null,
|
| 199 |
+
"grad_accum_steps": 1,
|
| 200 |
+
"grad_checkpointing": false,
|
| 201 |
+
"head_init_bias": null,
|
| 202 |
+
"head_init_scale": null,
|
| 203 |
+
"head_warmup": 5,
|
| 204 |
+
"head_weight_decay": 0.001,
|
| 205 |
+
"hflip": 0.5,
|
| 206 |
+
"img_size": null,
|
| 207 |
+
"in_chans": null,
|
| 208 |
+
"initial_checkpoint": null,
|
| 209 |
+
"input_size": null,
|
| 210 |
+
"interpolation": "",
|
| 211 |
+
"layer_decay": null,
|
| 212 |
+
"local_rank": 0,
|
| 213 |
+
"log_interval": 50,
|
| 214 |
+
"log_mlflow": false,
|
| 215 |
+
"log_wandb": true,
|
| 216 |
+
"loss_auto_balance": false,
|
| 217 |
+
"lr_base": 0.1,
|
| 218 |
+
"lr_base_scale": "",
|
| 219 |
+
"lr_base_size": 256,
|
| 220 |
+
"lr_cycle_decay": 0.5,
|
| 221 |
+
"lr_cycle_limit": 1,
|
| 222 |
+
"lr_cycle_mul": 1.0,
|
| 223 |
+
"lr_k_decay": 1.0,
|
| 224 |
+
"lr_noise": null,
|
| 225 |
+
"lr_noise_pct": 0.67,
|
| 226 |
+
"lr_noise_std": 1.0,
|
| 227 |
+
"mean": null,
|
| 228 |
+
"mesa": false,
|
| 229 |
+
"min_lr": 0,
|
| 230 |
+
"mixup": 0.0,
|
| 231 |
+
"mixup_mode": "batch",
|
| 232 |
+
"mixup_off_epoch": 0,
|
| 233 |
+
"mixup_prob": 1.0,
|
| 234 |
+
"mixup_switch_prob": 0.5,
|
| 235 |
+
"mlp_hidden_size": 1520,
|
| 236 |
+
"mlp_num_inner": 3,
|
| 237 |
+
"mlp_version": "v2",
|
| 238 |
+
"model": "vit_huge_patch16_224",
|
| 239 |
+
"model_kwargs": {},
|
| 240 |
+
"model_norm": false,
|
| 241 |
+
"momentum": 0.9,
|
| 242 |
+
"no_aug": false,
|
| 243 |
+
"no_ddp_bb": true,
|
| 244 |
+
"no_prefetcher": false,
|
| 245 |
+
"no_resume_opt": false,
|
| 246 |
+
"num_classes": null,
|
| 247 |
+
"opt_betas": null,
|
| 248 |
+
"opt_eps": null,
|
| 249 |
+
"patience_epochs": 10,
|
| 250 |
+
"pin_mem": false,
|
| 251 |
+
"prefetcher": true,
|
| 252 |
+
"pretrained": false,
|
| 253 |
+
"rank": 0,
|
| 254 |
+
"ratio": [
|
| 255 |
+
0.75,
|
| 256 |
+
1.3333333333333333
|
| 257 |
+
],
|
| 258 |
+
"recount": 1,
|
| 259 |
+
"recovery_interval": 0,
|
| 260 |
+
"register_multiple": 10,
|
| 261 |
+
"remode": "pixel",
|
| 262 |
+
"reprob": 0.0,
|
| 263 |
+
"reset_loss_state": false,
|
| 264 |
+
"resplit": false,
|
| 265 |
+
"save_images": false,
|
| 266 |
+
"scale": [
|
| 267 |
+
0.5,
|
| 268 |
+
1.0
|
| 269 |
+
],
|
| 270 |
+
"sched": "cosine",
|
| 271 |
+
"seed": 42,
|
| 272 |
+
"smoothing": 0.1,
|
| 273 |
+
"spectral_heads": false,
|
| 274 |
+
"spectral_reparam": false,
|
| 275 |
+
"split_bn": false,
|
| 276 |
+
"start_epoch": null,
|
| 277 |
+
"std": null,
|
| 278 |
+
"stream_teachers": true,
|
| 279 |
+
"sync_bn": false,
|
| 280 |
+
"synchronize_step": false,
|
| 281 |
+
"teachers": [
|
| 282 |
+
{
|
| 283 |
+
"fd_normalize": false,
|
| 284 |
+
"feature_distillation": true,
|
| 285 |
+
"input_size": 378,
|
| 286 |
+
"model": "ViT-H-14-378-quickgelu",
|
| 287 |
+
"name": "clip",
|
| 288 |
+
"pretrained": "dfn5b",
|
| 289 |
+
"type": "open_clip",
|
| 290 |
+
"use_summary": true
|
| 291 |
+
},
|
| 292 |
+
{
|
| 293 |
+
"fd_normalize": false,
|
| 294 |
+
"feature_distillation": true,
|
| 295 |
+
"input_size": 378,
|
| 296 |
+
"model": "ViT-SO400M-14-SigLIP-384",
|
| 297 |
+
"name": "siglip",
|
| 298 |
+
"pretrained": "webli",
|
| 299 |
+
"type": "open_clip",
|
| 300 |
+
"use_summary": true
|
| 301 |
+
},
|
| 302 |
+
{
|
| 303 |
+
"fd_normalize": false,
|
| 304 |
+
"feature_distillation": true,
|
| 305 |
+
"input_size": 378,
|
| 306 |
+
"model": "dinov2_vitg14_reg",
|
| 307 |
+
"name": "dino_v2",
|
| 308 |
+
"type": "dino_v2",
|
| 309 |
+
"use_summary": true
|
| 310 |
+
},
|
| 311 |
+
{
|
| 312 |
+
"fd_normalize": false,
|
| 313 |
+
"feature_distillation": true,
|
| 314 |
+
"input_size": 1024,
|
| 315 |
+
"model": "vit-h",
|
| 316 |
+
"name": "sam",
|
| 317 |
+
"type": "sam",
|
| 318 |
+
"use_summary": false
|
| 319 |
+
}
|
| 320 |
+
],
|
| 321 |
+
"torchcompile": null,
|
| 322 |
+
"torchscript": false,
|
| 323 |
+
"train_interpolation": "random",
|
| 324 |
+
"train_split": "train",
|
| 325 |
+
"tta": 0,
|
| 326 |
+
"use_coco": false,
|
| 327 |
+
"use_multi_epochs_loader": false,
|
| 328 |
+
"val_ema_only": false,
|
| 329 |
+
"val_split": "val",
|
| 330 |
+
"vflip": 0.0,
|
| 331 |
+
"vitdet_version": 1,
|
| 332 |
+
"wandb_entity": "",
|
| 333 |
+
"wandb_job_type": "",
|
| 334 |
+
"wandb_name": "",
|
| 335 |
+
"wandb_project": "",
|
| 336 |
+
"warmup_lr": 1e-05,
|
| 337 |
+
"warmup_prefix": false,
|
| 338 |
+
"worker_seeding": "all",
|
| 339 |
+
"workers": 8,
|
| 340 |
+
"world_size": 256,
|
| 341 |
+
"min_num_patches": 1024,
|
| 342 |
+
"max_num_patches": 13312
|
| 343 |
+
},
|
| 344 |
+
"feature_normalizer_config": null,
|
| 345 |
+
"inter_feature_normalizer_config": null,
|
| 346 |
+
"max_resolution": 2048,
|
| 347 |
+
"patch_size": 16,
|
| 348 |
+
"preferred_resolution": [
|
| 349 |
+
768,
|
| 350 |
+
768
|
| 351 |
+
],
|
| 352 |
+
"torch_dtype": "bfloat16",
|
| 353 |
+
"version": "radio_v2.5-h",
|
| 354 |
+
"vitdet_window_size": null,
|
| 355 |
+
"min_num_patches": 1024,
|
| 356 |
+
"max_num_patches": 13312,
|
| 357 |
+
"video_target_num_patches": 1024,
|
| 358 |
+
"video_maintain_aspect_ratio": true,
|
| 359 |
+
"video_temporal_patch_size": 2,
|
| 360 |
+
"video_prompt_version": 2,
|
| 361 |
+
"separate_video_embedder": true
|
| 362 |
+
},
|
| 363 |
+
"quantization": {
|
| 364 |
+
"group_size": 64,
|
| 365 |
+
"bits": 2
|
| 366 |
+
},
|
| 367 |
+
"quantization_config": {
|
| 368 |
+
"group_size": 64,
|
| 369 |
+
"bits": 2
|
| 370 |
+
}
|
| 371 |
+
}
|
configuration.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 22 |
+
class SoundConfig(PretrainedConfig):
|
| 23 |
+
"""Configuration for the sound/audio model (Parakeet encoder + projection)."""
|
| 24 |
+
model_type = "parakeet"
|
| 25 |
+
|
| 26 |
+
def __init__(
|
| 27 |
+
self,
|
| 28 |
+
# Parakeet encoder config
|
| 29 |
+
hidden_size: int = 1024,
|
| 30 |
+
num_attention_heads: int = 8,
|
| 31 |
+
num_hidden_layers: int = 24,
|
| 32 |
+
intermediate_size: int = 4096,
|
| 33 |
+
conv_kernel_size: int = 31,
|
| 34 |
+
feat_in: int = 80, # Mel features
|
| 35 |
+
subsampling_factor: int = 8,
|
| 36 |
+
# Projection config
|
| 37 |
+
projection_hidden_size: int = 20480,
|
| 38 |
+
projection_bias: bool = True,
|
| 39 |
+
# Audio processing
|
| 40 |
+
sampling_rate: int = 16000,
|
| 41 |
+
**kwargs,
|
| 42 |
+
):
|
| 43 |
+
super().__init__(**kwargs)
|
| 44 |
+
self.hidden_size = hidden_size
|
| 45 |
+
self.num_attention_heads = num_attention_heads
|
| 46 |
+
self.num_hidden_layers = num_hidden_layers
|
| 47 |
+
self.intermediate_size = intermediate_size
|
| 48 |
+
self.conv_kernel_size = conv_kernel_size
|
| 49 |
+
self.feat_in = feat_in
|
| 50 |
+
self.subsampling_factor = subsampling_factor
|
| 51 |
+
self.projection_hidden_size = projection_hidden_size
|
| 52 |
+
self.projection_bias = projection_bias
|
| 53 |
+
self.sampling_rate = sampling_rate
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class NemotronH_Nano_Omni_Reasoning_V3_Config(PretrainedConfig):
|
| 57 |
+
model_type = 'NemotronH_Nano_Omni_Reasoning_V3'
|
| 58 |
+
is_composition = True
|
| 59 |
+
|
| 60 |
+
def __init__(
|
| 61 |
+
self,
|
| 62 |
+
vision_config=None,
|
| 63 |
+
llm_config=None,
|
| 64 |
+
sound_config=None,
|
| 65 |
+
force_image_size=None,
|
| 66 |
+
downsample_ratio=0.5,
|
| 67 |
+
template=None,
|
| 68 |
+
ps_version='v1',
|
| 69 |
+
image_tag_type="internvl",
|
| 70 |
+
projector_hidden_size=4096,
|
| 71 |
+
vit_hidden_size=1280,
|
| 72 |
+
attn_implementation="flash_attention_2",
|
| 73 |
+
video_pruning_rate: float = 0.0,
|
| 74 |
+
video_temporal_patch_size: int = 2,
|
| 75 |
+
# Sound/audio settings
|
| 76 |
+
sound_context_token_id: int = None,
|
| 77 |
+
sound_context_token: str = "<audio>",
|
| 78 |
+
**kwargs
|
| 79 |
+
):
|
| 80 |
+
super().__init__(**kwargs)
|
| 81 |
+
|
| 82 |
+
if vision_config is not None:
|
| 83 |
+
self.vision_config = RADIOConfig(**vision_config)
|
| 84 |
+
else:
|
| 85 |
+
self.vision_config = RADIOConfig()
|
| 86 |
+
|
| 87 |
+
# Handle both cases: when loading from JSON (llm_config is dict) and when called internally by transformers (llm_config is None)
|
| 88 |
+
if llm_config is not None:
|
| 89 |
+
self.llm_config = NemotronHConfig(**llm_config)
|
| 90 |
+
else:
|
| 91 |
+
self.llm_config = NemotronHConfig()
|
| 92 |
+
|
| 93 |
+
# Sound/audio model configuration
|
| 94 |
+
if sound_config is not None:
|
| 95 |
+
self.sound_config = SoundConfig(**sound_config)
|
| 96 |
+
else:
|
| 97 |
+
self.sound_config = None # Sound model is optional
|
| 98 |
+
|
| 99 |
+
# Assign configuration values
|
| 100 |
+
self.force_image_size = force_image_size
|
| 101 |
+
self.downsample_ratio = downsample_ratio
|
| 102 |
+
self.template = template # TODO move out of here and into the tokenizer
|
| 103 |
+
self.ps_version = ps_version # Pixel shuffle version
|
| 104 |
+
self.image_tag_type = image_tag_type # TODO: into the tokenizer too?
|
| 105 |
+
self.projector_hidden_size = projector_hidden_size
|
| 106 |
+
self.vit_hidden_size = vit_hidden_size
|
| 107 |
+
self.video_pruning_rate = video_pruning_rate
|
| 108 |
+
self.video_temporal_patch_size = video_temporal_patch_size
|
| 109 |
+
|
| 110 |
+
# Sound/audio token settings
|
| 111 |
+
self.sound_context_token_id = sound_context_token_id
|
| 112 |
+
self.sound_context_token = sound_context_token
|
| 113 |
+
|
| 114 |
+
self._attn_implementation = attn_implementation
|
| 115 |
+
self.vision_config.use_flash_attn = self._attn_implementation is not None and "flash_attention" in self._attn_implementation
|
| 116 |
+
self.llm_config._attn_implementation = self._attn_implementation
|
| 117 |
+
|
| 118 |
+
# vLLM's `NemotronH_Nano_VL_V2` implementation reads the language-model sub-config as
|
| 119 |
+
# `config.text_config`. Our HF config stores it as `config.llm_config`; expose an alias so the
|
| 120 |
+
# same config object loads under both loaders without having to duplicate the dict on disk.
|
| 121 |
+
@property
|
| 122 |
+
def text_config(self):
|
| 123 |
+
return self.llm_config
|
configuration_nemotron_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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 AI21 Labs Ltd. and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
# you may not use this file except in compliance with the License.
|
| 7 |
+
# You may obtain a copy of the License at
|
| 8 |
+
#
|
| 9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
#
|
| 11 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
# See the License for the specific language governing permissions and
|
| 15 |
+
# limitations under the License.
|
| 16 |
+
"""NemotronH model configuration"""
|
| 17 |
+
|
| 18 |
+
import re
|
| 19 |
+
|
| 20 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 21 |
+
from transformers.utils import logging
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
logger = logging.get_logger(__name__)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class NemotronHConfig(PretrainedConfig):
|
| 28 |
+
r"""
|
| 29 |
+
This is the configuration class to store the configuration of a [`NemotronHModel`]. It is used to instantiate a
|
| 30 |
+
NemotronH model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
| 31 |
+
with the defaults will yield a similar configuration to that of the NemotronH-v0.1 model.
|
| 32 |
+
|
| 33 |
+
[todo](todo)
|
| 34 |
+
|
| 35 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
| 36 |
+
documentation from [`PretrainedConfig`] for more information.
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
vocab_size (`int`, *optional*, defaults to 131072):
|
| 41 |
+
Vocabulary size of the NemotronH model. Defines the number of different tokens that can be represented by the
|
| 42 |
+
`inputs_ids` passed when calling [`NemotronHModel`]
|
| 43 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
| 44 |
+
Whether the model's input and output word embeddings should be tied. Note that this is only relevant if the
|
| 45 |
+
model has a output word embedding layer.
|
| 46 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
| 47 |
+
Dimension of the hidden representations.
|
| 48 |
+
intermediate_size (`int`, *optional*, defaults to 21504):
|
| 49 |
+
Dimension of the MLP representations.
|
| 50 |
+
num_hidden_layers (`int`, *optional*, defaults to 52):
|
| 51 |
+
Number of hidden layers in the Transformer encoder.
|
| 52 |
+
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-"`):
|
| 53 |
+
The pattern of the hybrid model. The pattern is a string of characters where each character represents M: Mamba2, *: Attention, -: MLP
|
| 54 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
| 55 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
| 56 |
+
head_dim (`int`, *optional*, defaults to 128):
|
| 57 |
+
Dimension of each attention head.
|
| 58 |
+
num_key_value_heads (`int`, *optional*, defaults to 8):
|
| 59 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
| 60 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
| 61 |
+
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used.
|
| 62 |
+
mlp_hidden_act (`str`, *optional*, defaults to "relu2"):
|
| 63 |
+
The non-linear activation function in the MLP layers.
|
| 64 |
+
attention_bias (`bool`, *optional*, defaults to `False`):
|
| 65 |
+
Whether to use bias in attention layers.
|
| 66 |
+
mlp_bias (`bool`, *optional*, defaults to `False`):
|
| 67 |
+
Whether to use bias in MLP layers.
|
| 68 |
+
use_bias (`bool`, *optional*, defaults to `False`):
|
| 69 |
+
Whether to use bias in the model.
|
| 70 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
| 71 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
| 72 |
+
layer_norm_epsilon (`float`, *optional*, defaults to 1e-5):
|
| 73 |
+
The epsilon used by the layer normalization layers.
|
| 74 |
+
residual_in_fp32 (`bool`, *optional*, defaults to `False`):
|
| 75 |
+
Whether or not residuals should be in `float32`. If set to `False` residuals will keep the same `dtype` as the rest of the model.
|
| 76 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
| 77 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
| 78 |
+
relevant if `config.is_decoder=True`.
|
| 79 |
+
num_logits_to_keep (`int` or `None`, *optional*, defaults to 1):
|
| 80 |
+
Number of prompt logits to calculate during generation. If `None`, all logits will be calculated. If an
|
| 81 |
+
integer value, only last `num_logits_to_keep` logits will be calculated.
|
| 82 |
+
pad_token_id (`int`, *optional*, defaults to 0):
|
| 83 |
+
The id of the padding token.
|
| 84 |
+
bos_token_id (`int`, *optional*, defaults to 1):
|
| 85 |
+
The id of the "beginning-of-sequence" token.
|
| 86 |
+
eos_token_id (`int`, *optional*, defaults to 2):
|
| 87 |
+
The id of the "end-of-sequence" token.
|
| 88 |
+
sliding_window (`int`, *optional*, defaults to None):
|
| 89 |
+
Sliding window attention window size.
|
| 90 |
+
max_position_embeddings (`int`, *optional*, defaults to 4096):
|
| 91 |
+
The maximum sequence length that this model might ever be used with.
|
| 92 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
| 93 |
+
The dropout ratio for the attention probabilities.
|
| 94 |
+
hidden_dropout (`float`, *optional*, defaults to 0.0):
|
| 95 |
+
The dropout ratio for the hidden states.
|
| 96 |
+
use_mamba_kernels (`bool`, *optional*, defaults to `True`):
|
| 97 |
+
Flag indicating whether or not to use the fast mamba kernels. These are available only if `mamba-ssm` and
|
| 98 |
+
`causal-conv1d` are installed, and the mamba modules are running on a CUDA device.
|
| 99 |
+
ssm_state_size (`int`, *optional*, defaults to 128):
|
| 100 |
+
The dimension of the mamba state space latents.
|
| 101 |
+
mamba_num_heads (`int`, *optional*, defaults to 128):
|
| 102 |
+
Number of heads in Mamba layers.
|
| 103 |
+
mamba_n_groups (`int`, *optional*, defaults to 8):
|
| 104 |
+
Number of groups in Mamba layers.
|
| 105 |
+
mamba_head_dim (`int`, *optional*, defaults to 64):
|
| 106 |
+
Dimension of each Mamba head.
|
| 107 |
+
mamba_d_conv (`int`, *optional*, defaults to 4):
|
| 108 |
+
The size of the mamba convolution kernel.
|
| 109 |
+
mamba_expand (`int`, *optional*, defaults to 2):
|
| 110 |
+
Expanding factor used to determine the mamba intermediate size.
|
| 111 |
+
mamba_hidden_act (`str`, *optional*, defaults to "silu"):
|
| 112 |
+
The non-linear activation function in the Mamba layers.
|
| 113 |
+
mamba_dt_min (`float`, *optional*, defaults to 0.001):
|
| 114 |
+
Minimum value for the time step in Mamba.
|
| 115 |
+
mamba_dt_max (`float`, *optional*, defaults to 0.1):
|
| 116 |
+
Maximum value for the time step in Mamba.
|
| 117 |
+
mamba_dt_limit (`tuple`, *optional*, defaults to (0.0, float("inf"))):
|
| 118 |
+
Limits for the time step in Mamba.
|
| 119 |
+
mamba_dt_init_floor (`float`, *optional*, defaults to 1e-4):
|
| 120 |
+
Floor value for time step initialization in Mamba.
|
| 121 |
+
mamba_conv_bias (`bool`, *optional*, defaults to `True`):
|
| 122 |
+
Whether to use bias in the convolution layer of the mamba mixer block.
|
| 123 |
+
mamba_proj_bias (`bool`, *optional*, defaults to `False`):
|
| 124 |
+
Whether to use bias in the input and output projections of the mamba mixer block.
|
| 125 |
+
mamba_chunk_size (`int`, *optional*, defaults to 256):
|
| 126 |
+
Size of chunks for Mamba processing.
|
| 127 |
+
rescale_prenorm_residual (`bool`, *optional*, defaults to `True`):
|
| 128 |
+
Whether to rescale the pre-normalization residual connections.
|
| 129 |
+
"""
|
| 130 |
+
|
| 131 |
+
model_type = "nemotron_h"
|
| 132 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 133 |
+
|
| 134 |
+
def __init__(
|
| 135 |
+
self,
|
| 136 |
+
vocab_size=131072,
|
| 137 |
+
tie_word_embeddings=False,
|
| 138 |
+
hidden_size=4096,
|
| 139 |
+
intermediate_size=21504,
|
| 140 |
+
num_hidden_layers=52,
|
| 141 |
+
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-",
|
| 142 |
+
num_attention_heads=32,
|
| 143 |
+
head_dim=128,
|
| 144 |
+
num_key_value_heads=8, # nemo: num_query_groups
|
| 145 |
+
mlp_hidden_act="relu2",
|
| 146 |
+
attention_bias=False,
|
| 147 |
+
mlp_bias=False,
|
| 148 |
+
use_bias=False,
|
| 149 |
+
initializer_range=0.02, # nemo: init_method_std
|
| 150 |
+
layer_norm_epsilon=1e-5, # nemo: layernorm_epsilon
|
| 151 |
+
residual_in_fp32=False, # Megatron Core default value
|
| 152 |
+
use_cache=True,
|
| 153 |
+
num_logits_to_keep=1,
|
| 154 |
+
pad_token_id=0,
|
| 155 |
+
bos_token_id=1,
|
| 156 |
+
eos_token_id=2,
|
| 157 |
+
sliding_window=None,
|
| 158 |
+
max_position_embeddings=4096,
|
| 159 |
+
attention_dropout=0.0,
|
| 160 |
+
hidden_dropout=0.0, # * ADDED
|
| 161 |
+
use_mamba_kernels=True,
|
| 162 |
+
ssm_state_size=128, # mamba_state_size
|
| 163 |
+
mamba_num_heads=128,
|
| 164 |
+
mamba_n_groups=8, # nemo: mamba_ssm_ngroups = num_heads
|
| 165 |
+
mamba_head_dim=64,
|
| 166 |
+
mamba_d_conv=4,
|
| 167 |
+
mamba_expand=2,
|
| 168 |
+
mamba_hidden_act="silu",
|
| 169 |
+
mamba_dt_min=0.001,
|
| 170 |
+
mamba_dt_max=0.1,
|
| 171 |
+
mamba_dt_limit=(0.0, float("inf")),
|
| 172 |
+
mamba_dt_init_floor=1e-4,
|
| 173 |
+
mamba_conv_bias=True,
|
| 174 |
+
mamba_proj_bias=False,
|
| 175 |
+
mamba_chunk_size=128,
|
| 176 |
+
rescale_prenorm_residual=True,
|
| 177 |
+
n_routed_experts=8,
|
| 178 |
+
n_shared_experts=1,
|
| 179 |
+
moe_intermediate_size=7688,
|
| 180 |
+
moe_shared_expert_intermediate_size=7688,
|
| 181 |
+
num_experts_per_tok=2,
|
| 182 |
+
routed_scaling_factor=1.0,
|
| 183 |
+
n_group=1,
|
| 184 |
+
topk_group=1,
|
| 185 |
+
norm_topk_prob=True,
|
| 186 |
+
**kwargs,
|
| 187 |
+
):
|
| 188 |
+
self.vocab_size = vocab_size
|
| 189 |
+
self.tie_word_embeddings = tie_word_embeddings
|
| 190 |
+
self.hidden_size = hidden_size
|
| 191 |
+
self.intermediate_size = intermediate_size
|
| 192 |
+
self.num_hidden_layers = num_hidden_layers
|
| 193 |
+
self.hybrid_override_pattern = hybrid_override_pattern
|
| 194 |
+
self.num_attention_heads = num_attention_heads
|
| 195 |
+
self.head_dim = head_dim
|
| 196 |
+
self.sliding_window = sliding_window
|
| 197 |
+
self.max_position_embeddings = max_position_embeddings
|
| 198 |
+
self.attention_dropout = attention_dropout
|
| 199 |
+
self.hidden_dropout = hidden_dropout
|
| 200 |
+
|
| 201 |
+
# Validate hybrid_override_pattern
|
| 202 |
+
# M: Mamba2, *: Attention, -: MLP, E: MoE
|
| 203 |
+
assert len(self.hybrid_override_pattern) == self.num_hidden_layers, "hybrid_override_pattern must have the same length as num_hidden_layers"
|
| 204 |
+
assert re.match(r"^[*\-ME]+$", self.hybrid_override_pattern), "hybrid_override_pattern must only contain characters 'M', '*', '-', or 'E'"
|
| 205 |
+
|
| 206 |
+
# for backward compatibility
|
| 207 |
+
if num_key_value_heads is None:
|
| 208 |
+
num_key_value_heads = num_attention_heads
|
| 209 |
+
|
| 210 |
+
self.num_key_value_heads = num_key_value_heads
|
| 211 |
+
self.mlp_hidden_act = mlp_hidden_act
|
| 212 |
+
self.attention_bias = attention_bias
|
| 213 |
+
self.mlp_bias = mlp_bias
|
| 214 |
+
self.use_bias = use_bias
|
| 215 |
+
self.initializer_range = initializer_range
|
| 216 |
+
self.layer_norm_epsilon = layer_norm_epsilon
|
| 217 |
+
self.residual_in_fp32 = residual_in_fp32
|
| 218 |
+
|
| 219 |
+
self.use_cache = use_cache
|
| 220 |
+
self.num_logits_to_keep = num_logits_to_keep
|
| 221 |
+
|
| 222 |
+
self.use_mamba_kernels = use_mamba_kernels
|
| 223 |
+
self.n_groups = mamba_n_groups
|
| 224 |
+
self.mamba_head_dim = mamba_head_dim
|
| 225 |
+
self.ssm_state_size = ssm_state_size
|
| 226 |
+
self.mamba_num_heads = mamba_num_heads
|
| 227 |
+
self.conv_kernel = mamba_d_conv
|
| 228 |
+
self.expand = mamba_expand
|
| 229 |
+
self.mamba_hidden_act = mamba_hidden_act
|
| 230 |
+
self.time_step_min = mamba_dt_min
|
| 231 |
+
self.time_step_max = mamba_dt_max
|
| 232 |
+
self.time_step_limit = mamba_dt_limit
|
| 233 |
+
self.time_step_floor = mamba_dt_init_floor
|
| 234 |
+
self.use_conv_bias = mamba_conv_bias
|
| 235 |
+
self.mamba_proj_bias = mamba_proj_bias
|
| 236 |
+
self.chunk_size = mamba_chunk_size
|
| 237 |
+
self.rescale_prenorm_residual = rescale_prenorm_residual
|
| 238 |
+
self.n_routed_experts = n_routed_experts
|
| 239 |
+
self.n_shared_experts = n_shared_experts
|
| 240 |
+
self.moe_intermediate_size = moe_intermediate_size
|
| 241 |
+
self.moe_shared_expert_intermediate_size = moe_shared_expert_intermediate_size
|
| 242 |
+
self.num_experts_per_tok = num_experts_per_tok
|
| 243 |
+
self.routed_scaling_factor = routed_scaling_factor
|
| 244 |
+
self.n_group = n_group
|
| 245 |
+
self.topk_group = topk_group
|
| 246 |
+
self.norm_topk_prob = norm_topk_prob
|
| 247 |
+
|
| 248 |
+
# Derived per-layer block type list. Transformers 5.6+ looks this up as `layer_types` on the
|
| 249 |
+
# config to pick the correct cache structure (linear attention vs full attention). MLP (stateless)
|
| 250 |
+
# layers are tagged as "moe" here only because the transformers cache validator rejects "mlp";
|
| 251 |
+
# from the cache's point of view, both MLP and MoE layers need no kv cache (they become
|
| 252 |
+
# LinearAttentionLayer with zero state).
|
| 253 |
+
self.layer_types = [
|
| 254 |
+
"mamba" if self.hybrid_override_pattern[i] == "M" else
|
| 255 |
+
"attention" if self.hybrid_override_pattern[i] == "*" else
|
| 256 |
+
"moe" if self.hybrid_override_pattern[i] == "-" else "moe"
|
| 257 |
+
for i in range(self.num_hidden_layers)
|
| 258 |
+
]
|
| 259 |
+
# Per-layer semantic labels used by the modeling code (includes "mlp", which the
|
| 260 |
+
# transformers `layer_types` validator would reject — that's why `layer_types` above maps
|
| 261 |
+
# "-" → "moe" for cache purposes, while this attribute keeps the true label for the block
|
| 262 |
+
# dispatch in NemotronHBlock).
|
| 263 |
+
self.layers_block_type = [
|
| 264 |
+
"mamba" if self.hybrid_override_pattern[i] == "M" else
|
| 265 |
+
"attention" if self.hybrid_override_pattern[i] == "*" else
|
| 266 |
+
"mlp" if self.hybrid_override_pattern[i] == "-" else "moe"
|
| 267 |
+
for i in range(self.num_hidden_layers)
|
| 268 |
+
]
|
| 269 |
+
|
| 270 |
+
super().__init__(
|
| 271 |
+
pad_token_id=pad_token_id,
|
| 272 |
+
bos_token_id=bos_token_id,
|
| 273 |
+
eos_token_id=eos_token_id,
|
| 274 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 275 |
+
**kwargs,
|
| 276 |
+
)
|
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,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from typing import Tuple
|
| 3 |
+
|
| 4 |
+
class EfficientVideoSampling:
|
| 5 |
+
@staticmethod
|
| 6 |
+
def compute_retention_mask(
|
| 7 |
+
*,
|
| 8 |
+
video_embeds: torch.FloatTensor,
|
| 9 |
+
thw: torch.LongTensor,
|
| 10 |
+
spatial_merge_size: int,
|
| 11 |
+
q: float,
|
| 12 |
+
):
|
| 13 |
+
"""
|
| 14 |
+
Computes the retention mask for video embeddings based on the grid dimensions.
|
| 15 |
+
|
| 16 |
+
Args:
|
| 17 |
+
video_embeds (`torch.FloatTensor` of shape `(T * H * W, hidden_size)`):
|
| 18 |
+
The video embeddings to compute the retention mask for.
|
| 19 |
+
thw (`torch.LongTensor` of shape `(3)`):
|
| 20 |
+
The temporal, height and width of feature shape of each video in LLM.
|
| 21 |
+
spatial_merge_size (`int`): The spatial merge size of the video embeddings.
|
| 22 |
+
If embeddings will be downsampled *later*, this should be the downsampling factor.
|
| 23 |
+
q: (`float`): Pruning rate factor, indicating number of tokens to prune (remove)
|
| 24 |
+
|
| 25 |
+
Returns:
|
| 26 |
+
`torch.Tensor`: The retention mask for the video embeddings (T * H * W).
|
| 27 |
+
1 for tokens to keep, 0 for tokens to prune.
|
| 28 |
+
"""
|
| 29 |
+
T, H, W = thw
|
| 30 |
+
|
| 31 |
+
# video_embeds = einops.rearrange(
|
| 32 |
+
# video_embeds,
|
| 33 |
+
# "(T H W) C -> T H W C",
|
| 34 |
+
# T=T,
|
| 35 |
+
# H=H // spatial_merge_size,
|
| 36 |
+
# W=W // spatial_merge_size,
|
| 37 |
+
# )
|
| 38 |
+
# Use reshape instead of einops to avoid graph breaks
|
| 39 |
+
video_embeds = video_embeds.reshape(
|
| 40 |
+
T, H // spatial_merge_size, W // spatial_merge_size, video_embeds.size(-1)
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
# Core EVS
|
| 44 |
+
similarity = torch.nn.functional.cosine_similarity(
|
| 45 |
+
video_embeds[1:, ...], video_embeds[:-1, ...], dim=-1
|
| 46 |
+
)
|
| 47 |
+
dissimilarity = 1 - similarity
|
| 48 |
+
|
| 49 |
+
# Always ensure we include all tokens from the first frame
|
| 50 |
+
dissimilarity = torch.cat(
|
| 51 |
+
[255 * torch.ones_like(video_embeds[:1, :, :, 0]), dissimilarity], dim=0
|
| 52 |
+
)
|
| 53 |
+
dissimilarity_flat = dissimilarity.view(-1)
|
| 54 |
+
|
| 55 |
+
min_num_tokens = (H // spatial_merge_size) * (W // spatial_merge_size) # a single frame
|
| 56 |
+
evs_num_tokens = int(T * min_num_tokens * (1 - q))
|
| 57 |
+
num_tokens_to_keep = max(min_num_tokens, evs_num_tokens)
|
| 58 |
+
|
| 59 |
+
order = torch.argsort(dissimilarity_flat,
|
| 60 |
+
dim=-1,
|
| 61 |
+
descending=True,
|
| 62 |
+
stable=True)
|
| 63 |
+
topk_indices = order[:num_tokens_to_keep]
|
| 64 |
+
|
| 65 |
+
retention_mask = torch.zeros_like(dissimilarity_flat, dtype=torch.bool)
|
| 66 |
+
retention_mask[topk_indices] = True
|
| 67 |
+
retention_mask = retention_mask.reshape(dissimilarity.size())
|
| 68 |
+
|
| 69 |
+
# print(
|
| 70 |
+
# f"Computed retention mask of shape {retention_mask.shape=} with sparsity {retention_mask.float().mean().item():.4f} for {q=}",
|
| 71 |
+
# )
|
| 72 |
+
mask = retention_mask.view(-1) # "T H W -> (T H W)"
|
| 73 |
+
return mask
|
generation_config.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"bos_token_id": 1,
|
| 4 |
+
"eos_token_id": [2, 11],
|
| 5 |
+
"pad_token_id": 0,
|
| 6 |
+
"do_sample": true,
|
| 7 |
+
"temperature": 0.6,
|
| 8 |
+
"top_p": 0.95,
|
| 9 |
+
"max_new_tokens": 16384,
|
| 10 |
+
"reasoning_budget": 16384,
|
| 11 |
+
"reasoning_grace": 512,
|
| 12 |
+
"repetition_penalty": 1.0,
|
| 13 |
+
"transformers_version": "4.55.4"
|
| 14 |
+
}
|
image_processing.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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from typing import List, Optional, Union
|
| 3 |
+
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import torch
|
| 6 |
+
from transformers.image_processing_base import BatchFeature
|
| 7 |
+
from transformers.image_processing_utils_fast import BaseImageProcessorFast
|
| 8 |
+
from transformers.image_utils import make_list_of_images, get_image_type, ImageInput, ImageType
|
| 9 |
+
from transformers.utils import TensorType
|
| 10 |
+
import torchvision.transforms as T
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class NemotronH_Nano_Omni_Reasoning_V3ImageProcessor(BaseImageProcessorFast):
|
| 14 |
+
"""
|
| 15 |
+
Dynamic-resolution image processor for the V3 omni model.
|
| 16 |
+
|
| 17 |
+
Each image is resized to a single tile whose patch-grid `(h_patches, w_patches)` is chosen to
|
| 18 |
+
land between `min_num_patches` and `max_num_patches` (on a 16×16-pixel grid), respecting
|
| 19 |
+
aspect ratio. This matches the algorithm in vLLM's `DynamicResolutionImageTiler`
|
| 20 |
+
(`vllm/model_executor/models/nano_nemotron_vl.py`) so HF and vLLM inference see identical pixel
|
| 21 |
+
inputs.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
model_input_names = ["pixel_values"]
|
| 25 |
+
|
| 26 |
+
def __init__(
|
| 27 |
+
self,
|
| 28 |
+
norm_mean=None,
|
| 29 |
+
norm_std=None,
|
| 30 |
+
patch_size=16,
|
| 31 |
+
downsample_ratio=0.5,
|
| 32 |
+
min_num_patches=1024,
|
| 33 |
+
max_num_patches=13312,
|
| 34 |
+
max_model_len=16384,
|
| 35 |
+
video_target_num_patches=1024,
|
| 36 |
+
video_maintain_aspect_ratio=True,
|
| 37 |
+
**kwargs,
|
| 38 |
+
):
|
| 39 |
+
super().__init__(**kwargs)
|
| 40 |
+
self.norm_mean = norm_mean
|
| 41 |
+
self.norm_std = norm_std
|
| 42 |
+
self.patch_size = patch_size
|
| 43 |
+
self.downsample_ratio = downsample_ratio
|
| 44 |
+
# Integer reduction factor for pixel_shuffle (downsample_ratio = 0.5 → factor 2).
|
| 45 |
+
self._downsample_factor = int(round(1.0 / downsample_ratio))
|
| 46 |
+
# Per-image patch-grid bounds (on the pre-pixel-shuffle 16×16 grid).
|
| 47 |
+
self.min_num_patches = min_num_patches
|
| 48 |
+
self.max_num_patches = max_num_patches
|
| 49 |
+
self.max_model_len = max_model_len
|
| 50 |
+
# Video frames use a separate (fixed) target-patch budget with aspect-ratio preserved.
|
| 51 |
+
# Matches vLLM's `_compute_aspect_preserving_size` in `nano_nemotron_vl.py`.
|
| 52 |
+
self.video_target_num_patches = video_target_num_patches
|
| 53 |
+
self.video_maintain_aspect_ratio = video_maintain_aspect_ratio
|
| 54 |
+
|
| 55 |
+
# Keep the PIL image through to `_preprocess` — we need PIL.resize (bicubic) to match vLLM's
|
| 56 |
+
# algorithm exactly; resizing a tensor via `torchvision.transforms.Resize` uses different
|
| 57 |
+
# kernels and breaks bit-exact agreement.
|
| 58 |
+
def _process_image(self, image: ImageInput, **kwargs):
|
| 59 |
+
if get_image_type(image) == ImageType.PIL:
|
| 60 |
+
if image.mode != "RGB":
|
| 61 |
+
image = image.convert("RGB")
|
| 62 |
+
return image
|
| 63 |
+
|
| 64 |
+
# transformers 5.6 renamed this hook from `_process_image` to `process_image`; alias both.
|
| 65 |
+
process_image = _process_image
|
| 66 |
+
|
| 67 |
+
# Toggled by `processing.py` around video calls (the strict `ImagesKwargs` validator won't let
|
| 68 |
+
# us thread a new kwarg down, so we use a flag on the instance instead).
|
| 69 |
+
_is_video_mode: bool = False
|
| 70 |
+
|
| 71 |
+
def _preprocess(
|
| 72 |
+
self,
|
| 73 |
+
images,
|
| 74 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 75 |
+
**kwargs,
|
| 76 |
+
) -> BatchFeature:
|
| 77 |
+
"""Port of vLLM's `DynamicResolutionImageTiler._images_to_pixel_values_lst`.
|
| 78 |
+
|
| 79 |
+
When `self._is_video_mode=True` (flipped by `processing.py` before the video call), each
|
| 80 |
+
input is resized using the **video** target-size rule (`video_target_num_patches`,
|
| 81 |
+
aspect-ratio preserved) instead of the image dynamic-res rule. This matches vLLM's split
|
| 82 |
+
between `video_to_pixel_values` (video path) and `DynamicResolutionImageTiler` (image
|
| 83 |
+
path).
|
| 84 |
+
"""
|
| 85 |
+
is_video = self._is_video_mode
|
| 86 |
+
images = make_list_of_images(images)
|
| 87 |
+
|
| 88 |
+
target_sizes = []
|
| 89 |
+
if is_video:
|
| 90 |
+
for img in images:
|
| 91 |
+
target_w_patches, target_h_patches = self._compute_target_patches_video(img)
|
| 92 |
+
target_sizes.append((target_w_patches, target_h_patches))
|
| 93 |
+
else:
|
| 94 |
+
# Image path: per-image budget bounded by [min_num_patches, max_num_patches], with a
|
| 95 |
+
# global cap derived from `max_model_len` × pixel-shuffle factor².
|
| 96 |
+
num_tokens_available = self.max_model_len - 4 # match vLLM's reserve
|
| 97 |
+
budget = num_tokens_available * (self._downsample_factor ** 2)
|
| 98 |
+
budget = max(budget, self.min_num_patches * len(images))
|
| 99 |
+
max_budget = self.max_num_patches if (self.max_num_patches and self.max_num_patches > 0) else float("inf")
|
| 100 |
+
per_image_budget = [max(min(budget, max_budget), self.min_num_patches) for _ in images]
|
| 101 |
+
# Single-pass — vLLM has an iterative scale-down for the batch, but it rarely binds in
|
| 102 |
+
# single-image / small-batch inference.
|
| 103 |
+
for img, tokens_for_media in zip(images, per_image_budget):
|
| 104 |
+
target_w_patches, target_h_patches = self._compute_target_patches(img, tokens_for_media)
|
| 105 |
+
target_sizes.append((target_w_patches, target_h_patches))
|
| 106 |
+
|
| 107 |
+
import numpy as np
|
| 108 |
+
norm_mean = torch.tensor(self.norm_mean).view(1, 3, 1, 1)
|
| 109 |
+
norm_std = torch.tensor(self.norm_std).view(1, 3, 1, 1)
|
| 110 |
+
|
| 111 |
+
pixel_values_list = []
|
| 112 |
+
num_tokens_per_image = []
|
| 113 |
+
imgs_sizes = []
|
| 114 |
+
for img, (wp, hp) in zip(images, target_sizes):
|
| 115 |
+
target_w = wp * self.patch_size
|
| 116 |
+
target_h = hp * self.patch_size
|
| 117 |
+
# Use torch's antialiased bicubic interpolation to match vLLM's
|
| 118 |
+
# `_bicubic_resize_and_normalize` (`torch.nn.functional.interpolate`, `antialias=True`).
|
| 119 |
+
# PIL's bicubic uses a different kernel (and no antialiasing), producing visibly different
|
| 120 |
+
# pixel values that amplify through the 52-layer ViT / mamba stack and cause HF/vLLM
|
| 121 |
+
# outputs to diverge past the first few tokens.
|
| 122 |
+
arr = np.asarray(img, dtype=np.uint8) # (H, W, 3)
|
| 123 |
+
t = torch.from_numpy(arr).permute(2, 0, 1).unsqueeze(0).to(dtype=torch.float32) # (1, 3, H, W)
|
| 124 |
+
if t.shape[-2] != target_h or t.shape[-1] != target_w:
|
| 125 |
+
t = torch.nn.functional.interpolate(
|
| 126 |
+
t, size=(target_h, target_w), mode="bicubic", align_corners=False, antialias=True
|
| 127 |
+
)
|
| 128 |
+
t = (t / 255.0 - norm_mean) / norm_std
|
| 129 |
+
pixel_values_list.append(t.squeeze(0)) # (3, H, W)
|
| 130 |
+
num_tokens_per_image.append((wp * hp) // (self._downsample_factor ** 2))
|
| 131 |
+
imgs_sizes.append((target_h, target_w))
|
| 132 |
+
|
| 133 |
+
# Stack if all images have the same target size (common for same-aspect-ratio batches);
|
| 134 |
+
# otherwise keep as a list of (3, H_i, W_i) tensors. The outer model's `extract_feature`
|
| 135 |
+
# handles both.
|
| 136 |
+
all_same_shape = all(t.shape == pixel_values_list[0].shape for t in pixel_values_list)
|
| 137 |
+
if all_same_shape:
|
| 138 |
+
pixel_values = torch.stack(pixel_values_list, dim=0)
|
| 139 |
+
else:
|
| 140 |
+
pixel_values = pixel_values_list
|
| 141 |
+
|
| 142 |
+
return BatchFeature(
|
| 143 |
+
data={
|
| 144 |
+
"pixel_values": pixel_values,
|
| 145 |
+
# One tile per image in dynamic mode — `num_tokens` is what the text-side
|
| 146 |
+
# placeholder expansion should use.
|
| 147 |
+
"num_patches": [1] * len(images),
|
| 148 |
+
"num_tokens": num_tokens_per_image,
|
| 149 |
+
"imgs_sizes": imgs_sizes,
|
| 150 |
+
},
|
| 151 |
+
tensor_type=(return_tensors if all_same_shape else None),
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
def _compute_target_patches(self, img: Image.Image, tokens_available: int):
|
| 155 |
+
"""Port of `DynamicResolutionImageTiler.process_media` (image-only, no thumbnail)."""
|
| 156 |
+
orig_w, orig_h = img.width, img.height
|
| 157 |
+
# Ceil-ish: `round(x + 0.5)` == `floor(x) + 1` for non-integer x, `x` for integer.
|
| 158 |
+
closest_patch_h = round(orig_h / self.patch_size + 0.5)
|
| 159 |
+
closest_patch_w = round(orig_w / self.patch_size + 0.5)
|
| 160 |
+
patches = closest_patch_h * closest_patch_w
|
| 161 |
+
|
| 162 |
+
# Downscale to fit the token budget.
|
| 163 |
+
factor = min(math.sqrt(tokens_available / patches), 1.0)
|
| 164 |
+
target_h = math.floor(factor * closest_patch_h)
|
| 165 |
+
target_w = math.floor(factor * closest_patch_w)
|
| 166 |
+
|
| 167 |
+
# Scale up if below the per-image minimum.
|
| 168 |
+
if (
|
| 169 |
+
tokens_available > self.min_num_patches
|
| 170 |
+
and target_h * target_w < self.min_num_patches
|
| 171 |
+
):
|
| 172 |
+
up = math.sqrt(self.min_num_patches / (target_h * target_w))
|
| 173 |
+
target_h = math.ceil(up * target_h)
|
| 174 |
+
target_w = math.ceil(up * target_w)
|
| 175 |
+
|
| 176 |
+
# Round each dim to a multiple of the pixel_shuffle factor so tokens divide evenly.
|
| 177 |
+
divisor = self._downsample_factor
|
| 178 |
+
rem_h = target_h % divisor
|
| 179 |
+
if rem_h:
|
| 180 |
+
inc_h = divisor - rem_h
|
| 181 |
+
if (target_h + inc_h) * target_w <= tokens_available:
|
| 182 |
+
target_h += inc_h
|
| 183 |
+
else:
|
| 184 |
+
target_h = max(divisor, target_h - rem_h)
|
| 185 |
+
rem_w = target_w % divisor
|
| 186 |
+
if rem_w:
|
| 187 |
+
inc_w = divisor - rem_w
|
| 188 |
+
if target_h * (target_w + inc_w) <= tokens_available:
|
| 189 |
+
target_w += inc_w
|
| 190 |
+
else:
|
| 191 |
+
target_w = max(divisor, target_w - rem_w)
|
| 192 |
+
|
| 193 |
+
return target_w, target_h
|
| 194 |
+
|
| 195 |
+
def _compute_target_patches_video(self, img: Image.Image):
|
| 196 |
+
"""Port of vLLM's `_compute_aspect_preserving_size` for video frames.
|
| 197 |
+
|
| 198 |
+
Each frame is resized to roughly `video_target_num_patches` (default 1024) on the 16×16
|
| 199 |
+
grid, with aspect ratio preserved and dims snapped to a multiple of the pixel_shuffle
|
| 200 |
+
factor. For `maintain_aspect_ratio=False`, it falls back to a square of sqrt(target)
|
| 201 |
+
patches.
|
| 202 |
+
"""
|
| 203 |
+
orig_w, orig_h = img.width, img.height
|
| 204 |
+
target = self.video_target_num_patches
|
| 205 |
+
divisor = self._downsample_factor # 2 for pixel_shuffle
|
| 206 |
+
if self.video_maintain_aspect_ratio:
|
| 207 |
+
aspect_wh = orig_w / max(orig_h, 1)
|
| 208 |
+
ph = max(round(math.sqrt(target / aspect_wh)), 1)
|
| 209 |
+
pw = max(round(math.sqrt(target * aspect_wh)), 1)
|
| 210 |
+
if divisor > 1:
|
| 211 |
+
rem_h = ph % divisor
|
| 212 |
+
rem_w = pw % divisor
|
| 213 |
+
ph_up = ph + (divisor - rem_h if rem_h else 0)
|
| 214 |
+
ph_down = ph - rem_h
|
| 215 |
+
pw_up = pw + (divisor - rem_w if rem_w else 0)
|
| 216 |
+
pw_down = pw - rem_w
|
| 217 |
+
# Prefer rounding up when the up-rounded patch count still fits the target;
|
| 218 |
+
# otherwise round down (mirrors vLLM's logic exactly).
|
| 219 |
+
if ph_up * pw_up <= target:
|
| 220 |
+
ph, pw = ph_up, pw_up
|
| 221 |
+
else:
|
| 222 |
+
ph = max(divisor, ph_down)
|
| 223 |
+
pw = max(divisor, pw_down)
|
| 224 |
+
else:
|
| 225 |
+
side = int(math.sqrt(target))
|
| 226 |
+
side = max(divisor, (side // divisor) * divisor)
|
| 227 |
+
ph = pw = side
|
| 228 |
+
return pw, ph
|
model-00001-of-00003.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3669a3b0a1d86932bc8a488dec22a31ebfe254f87fb29254842a98393f5af16a
|
| 3 |
+
size 5369082200
|
model-00002-of-00003.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:687ad1d7c704441fa92ae0c17bb7be74db63a5ec69abbf30efe6e95f576f8a14
|
| 3 |
+
size 5369220700
|
model-00003-of-00003.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6fca102c7761671c814bb6f1172b4889bc36a5a5fc26242f89407042f736a553
|
| 3 |
+
size 2009537281
|
model.safetensors.index.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
modeling.py
ADDED
|
@@ -0,0 +1,638 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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_Omni_Reasoning_V3_Config
|
| 28 |
+
from .modeling_nemotron_h import NemotronHForCausalLM
|
| 29 |
+
from .evs import EfficientVideoSampling
|
| 30 |
+
from .audio_model import SoundEncoder, SoundProjection
|
| 31 |
+
|
| 32 |
+
logger = logging.get_logger(__name__)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
"""
|
| 36 |
+
The following code is adapted from the
|
| 37 |
+
https://huggingface.co/OpenGVLab/InternVL2-Llama3-76B/blob/main/modeling_internvl_chat.py repository
|
| 38 |
+
|
| 39 |
+
The chat function is adapted to handle NVLM 1-D tile-tagging design for dynamic high-resolution images.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class SquaredReLU(nn.Module):
|
| 44 |
+
def forward(self, x):
|
| 45 |
+
return torch.pow(torch.nn.functional.relu(x), 2)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class RMSNorm(nn.Module):
|
| 49 |
+
def __init__(self, hidden_size, eps=1e-5):
|
| 50 |
+
super().__init__()
|
| 51 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 52 |
+
self.eps = eps
|
| 53 |
+
|
| 54 |
+
def forward(self, hidden_states):
|
| 55 |
+
input_dtype = hidden_states.dtype
|
| 56 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 57 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 58 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
|
| 59 |
+
return (self.weight.to(torch.float32) * hidden_states).to(input_dtype)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def version_cmp(v1, v2, op='eq'):
|
| 63 |
+
import operator
|
| 64 |
+
|
| 65 |
+
from packaging import version
|
| 66 |
+
op_func = getattr(operator, op)
|
| 67 |
+
return op_func(version.parse(v1), version.parse(v2))
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class NemotronH_Nano_Omni_Reasoning_V3(PreTrainedModel):
|
| 71 |
+
config_class = NemotronH_Nano_Omni_Reasoning_V3_Config
|
| 72 |
+
main_input_name = 'pixel_values'
|
| 73 |
+
_supports_flash_attn_2 = True
|
| 74 |
+
_supports_flash_attn = True
|
| 75 |
+
_no_split_modules = ['NemotronHBlock']
|
| 76 |
+
|
| 77 |
+
def __init__(self, config: NemotronH_Nano_Omni_Reasoning_V3_Config):
|
| 78 |
+
super().__init__(config)
|
| 79 |
+
|
| 80 |
+
assert version_cmp(transformers.__version__, '4.36.2', 'ge')
|
| 81 |
+
image_size = config.force_image_size
|
| 82 |
+
patch_size = config.patch_size
|
| 83 |
+
self.patch_size = patch_size
|
| 84 |
+
self.template = config.template
|
| 85 |
+
self.num_image_token = int((image_size // patch_size) ** 2 * (config.downsample_ratio ** 2))
|
| 86 |
+
self.downsample_ratio = config.downsample_ratio
|
| 87 |
+
self.ps_version = config.ps_version
|
| 88 |
+
self.image_tag_type = config.image_tag_type
|
| 89 |
+
self.img_context_token_id = config.img_context_token_id
|
| 90 |
+
self.video_context_token_id = config.video_context_token_id
|
| 91 |
+
|
| 92 |
+
logger.info(f'num_image_token: {self.num_image_token}')
|
| 93 |
+
logger.info(f'ps_version: {self.ps_version}')
|
| 94 |
+
|
| 95 |
+
# Instantiate LM directly to avoid Hugging Face dynamic module lookup requiring a repo id.
|
| 96 |
+
self.language_model = NemotronHForCausalLM(config.llm_config)
|
| 97 |
+
self.vision_model = AutoModel.from_config(config.vision_config, trust_remote_code=True)
|
| 98 |
+
self.vision_model.model._initialize_weights = self.vision_model.model._init_weights # WAR for transformers issue 38358
|
| 99 |
+
self.vision_model.radio_model.make_preprocessor_external()
|
| 100 |
+
|
| 101 |
+
# Attach a separate 3D patch projection for video frames. The RADIO ViT ships with only a 2D
|
| 102 |
+
# `embedder` (shape `[embed_dim, C·P²]`); this repo's checkpoint also carries a
|
| 103 |
+
# `video_embedder` (shape `[embed_dim, T·C·P²]`) used for temporally-packed video patches,
|
| 104 |
+
# so we construct the module here to make the weight bind. `T = video_temporal_patch_size`
|
| 105 |
+
# is the number of frames collapsed into each temporal patch.
|
| 106 |
+
self.video_temporal_patch_dim = config.video_temporal_patch_size
|
| 107 |
+
pg = self.vision_model.radio_model.model.patch_generator
|
| 108 |
+
pg.video_embedder = nn.Linear(
|
| 109 |
+
in_features=self.video_temporal_patch_dim * 3 * pg.patch_size * pg.patch_size,
|
| 110 |
+
out_features=pg.embed_dim,
|
| 111 |
+
bias=False,
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
# Align CPE position-embedding interpolation with Megatron training + vLLM inference.
|
| 115 |
+
# The `nvidia/C-RADIOv2-H` remote code uses `align_corners=True` in eval mode, but the V3
|
| 116 |
+
# checkpoint was trained against `align_corners=False` (see Megatron's `radio.py`). That
|
| 117 |
+
# single-flag mismatch shifts every pos_embed by a fraction of a cell, which compounds
|
| 118 |
+
# through 52 ViT layers and is the main cause of HF/vLLM divergence for video (where CPE
|
| 119 |
+
# mode is active — dynamic-res tubelets don't match the model's native 2048-sized grid).
|
| 120 |
+
self._patch_cpe_align_corners(pg)
|
| 121 |
+
|
| 122 |
+
self.vision_model = self.vision_model.to(self.language_model.config.torch_dtype)
|
| 123 |
+
|
| 124 |
+
self.drop_vision_class_token = True
|
| 125 |
+
|
| 126 |
+
# Construct the vision projection.
|
| 127 |
+
# Default
|
| 128 |
+
vit_hidden_size = config.vit_hidden_size
|
| 129 |
+
vision_projection_hidden_size = config.projector_hidden_size
|
| 130 |
+
llm_hidden_size = config.llm_config.hidden_size
|
| 131 |
+
|
| 132 |
+
self.video_pruning_rate = config.video_pruning_rate
|
| 133 |
+
|
| 134 |
+
self.mlp1 = nn.Sequential(
|
| 135 |
+
RMSNorm(vit_hidden_size * int(1 / self.downsample_ratio) ** 2, eps=1e-5),
|
| 136 |
+
nn.Linear(vit_hidden_size * int(1 / self.downsample_ratio) ** 2, vision_projection_hidden_size, bias=False),
|
| 137 |
+
SquaredReLU(),
|
| 138 |
+
nn.Linear(vision_projection_hidden_size, llm_hidden_size, bias=False)
|
| 139 |
+
)
|
| 140 |
+
self.mlp1 = self.mlp1.to(self.language_model.config.torch_dtype)
|
| 141 |
+
|
| 142 |
+
# Sound/audio model components (optional - only if sound_config is provided)
|
| 143 |
+
self.sound_context_token_id = getattr(config, 'sound_context_token_id', None)
|
| 144 |
+
if config.sound_config is not None:
|
| 145 |
+
sound_config = config.sound_config
|
| 146 |
+
sound_hidden_size = sound_config.hidden_size
|
| 147 |
+
sound_projection_hidden_size = sound_config.projection_hidden_size
|
| 148 |
+
|
| 149 |
+
# Initialize sound feature extractor for converting raw audio to mel spectrograms
|
| 150 |
+
from transformers import ParakeetFeatureExtractor
|
| 151 |
+
sampling_rate = getattr(sound_config, 'sampling_rate', 16000)
|
| 152 |
+
feature_size = getattr(sound_config, 'num_mel_bins', 128)
|
| 153 |
+
self.sound_feature_extractor = ParakeetFeatureExtractor(
|
| 154 |
+
sampling_rate=sampling_rate,
|
| 155 |
+
feature_size=feature_size,
|
| 156 |
+
)
|
| 157 |
+
logger.info(f'Sound feature extractor initialized with sampling_rate={sampling_rate}, feature_size={feature_size}')
|
| 158 |
+
|
| 159 |
+
# Initialize sound encoder - wraps Parakeet from transformers
|
| 160 |
+
self.sound_encoder = SoundEncoder(config=sound_config)
|
| 161 |
+
self.sound_encoder = self.sound_encoder.to(self.language_model.config.torch_dtype)
|
| 162 |
+
|
| 163 |
+
# Initialize sound projection MLP
|
| 164 |
+
self.sound_projection = SoundProjection(
|
| 165 |
+
sound_hidden_size=sound_hidden_size,
|
| 166 |
+
projection_hidden_size=sound_projection_hidden_size,
|
| 167 |
+
llm_hidden_size=llm_hidden_size,
|
| 168 |
+
bias=sound_config.projection_bias,
|
| 169 |
+
)
|
| 170 |
+
self.sound_projection = self.sound_projection.to(self.language_model.config.torch_dtype)
|
| 171 |
+
|
| 172 |
+
logger.info(f'Sound model initialized with hidden_size={sound_hidden_size}')
|
| 173 |
+
else:
|
| 174 |
+
self.sound_encoder = None
|
| 175 |
+
self.sound_projection = None
|
| 176 |
+
self.sound_feature_extractor = None
|
| 177 |
+
|
| 178 |
+
self.all_tied_weights_keys = {}
|
| 179 |
+
|
| 180 |
+
def forward(
|
| 181 |
+
self,
|
| 182 |
+
pixel_values: torch.FloatTensor,
|
| 183 |
+
input_ids: torch.LongTensor = None,
|
| 184 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 185 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 186 |
+
image_flags: Optional[torch.LongTensor] = None,
|
| 187 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
| 188 |
+
labels: Optional[torch.LongTensor] = None,
|
| 189 |
+
inputs_embeds = None,
|
| 190 |
+
use_cache: Optional[bool] = None,
|
| 191 |
+
output_attentions: Optional[bool] = None,
|
| 192 |
+
output_hidden_states: Optional[bool] = None,
|
| 193 |
+
return_dict: Optional[bool] = None,
|
| 194 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
| 195 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 196 |
+
|
| 197 |
+
if inputs_embeds is None:
|
| 198 |
+
inputs_embeds = self.language_model.get_input_embeddings()(input_ids)
|
| 199 |
+
|
| 200 |
+
image_flags = image_flags.squeeze(-1)
|
| 201 |
+
|
| 202 |
+
B, N, C = inputs_embeds.shape
|
| 203 |
+
inputs_embeds = inputs_embeds.reshape(B * N, C)
|
| 204 |
+
|
| 205 |
+
input_ids = input_ids.reshape(B * N)
|
| 206 |
+
selected = (input_ids == self.img_context_token_id)
|
| 207 |
+
|
| 208 |
+
vit_batch_size = pixel_values.shape[0]
|
| 209 |
+
vit_embeds = self.extract_feature(pixel_values)
|
| 210 |
+
|
| 211 |
+
del pixel_values
|
| 212 |
+
|
| 213 |
+
if torch.distributed.get_rank() == 0:
|
| 214 |
+
print(f'dynamic ViT batch size: {vit_batch_size}, images per sample: {vit_batch_size / B}, dynamic token length: {N}')
|
| 215 |
+
|
| 216 |
+
vit_embeds = vit_embeds[image_flags == 1]
|
| 217 |
+
try:
|
| 218 |
+
inputs_embeds[selected] = inputs_embeds[selected] * 0.0 + vit_embeds.reshape(-1, C)
|
| 219 |
+
except Exception as e:
|
| 220 |
+
vit_embeds = vit_embeds.reshape(-1, C)
|
| 221 |
+
print(f'warning: {e}, inputs_embeds[selected].shape={inputs_embeds[selected].shape}, '
|
| 222 |
+
f'vit_embeds.shape={vit_embeds.shape}')
|
| 223 |
+
n_token = selected.sum()
|
| 224 |
+
inputs_embeds[selected] = inputs_embeds[selected] * 0.0 + vit_embeds[:n_token]
|
| 225 |
+
|
| 226 |
+
del vit_embeds
|
| 227 |
+
|
| 228 |
+
inputs_embeds = inputs_embeds.reshape(B, N, C)
|
| 229 |
+
|
| 230 |
+
outputs = self.language_model(
|
| 231 |
+
inputs_embeds=inputs_embeds,
|
| 232 |
+
attention_mask=attention_mask,
|
| 233 |
+
position_ids=position_ids,
|
| 234 |
+
past_key_values=past_key_values,
|
| 235 |
+
use_cache=use_cache,
|
| 236 |
+
output_attentions=output_attentions,
|
| 237 |
+
output_hidden_states=output_hidden_states,
|
| 238 |
+
return_dict=return_dict,
|
| 239 |
+
)
|
| 240 |
+
logits = outputs.logits
|
| 241 |
+
|
| 242 |
+
loss = None
|
| 243 |
+
if labels is not None:
|
| 244 |
+
# Shift so that tokens < n predict n
|
| 245 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 246 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 247 |
+
# Flatten the tokens
|
| 248 |
+
loss_fct = CrossEntropyLoss()
|
| 249 |
+
shift_logits = shift_logits.view(-1, self.language_model.config.vocab_size)
|
| 250 |
+
shift_labels = shift_labels.view(-1)
|
| 251 |
+
# Enable model parallelism
|
| 252 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
| 253 |
+
loss = loss_fct(shift_logits, shift_labels)
|
| 254 |
+
|
| 255 |
+
if not return_dict:
|
| 256 |
+
output = (logits,) + outputs[1:]
|
| 257 |
+
return (loss,) + output if loss is not None else output
|
| 258 |
+
|
| 259 |
+
return CausalLMOutputWithPast(
|
| 260 |
+
loss=loss,
|
| 261 |
+
logits=logits,
|
| 262 |
+
past_key_values=outputs.past_key_values,
|
| 263 |
+
hidden_states=outputs.hidden_states,
|
| 264 |
+
attentions=outputs.attentions,
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
@staticmethod
|
| 268 |
+
def _patch_cpe_align_corners(patch_generator) -> None:
|
| 269 |
+
"""Monkey-patch `patch_generator._get_pos_embeddings` so the CPE-mode eval-path interpolation
|
| 270 |
+
uses `align_corners=False` (Megatron training + vLLM inference convention) instead of the
|
| 271 |
+
`align_corners=True` that the `nvidia/C-RADIOv2-H` remote code ships with.
|
| 272 |
+
"""
|
| 273 |
+
import math
|
| 274 |
+
import torch.nn.functional as F
|
| 275 |
+
|
| 276 |
+
orig_method = patch_generator._get_pos_embeddings.__func__ if hasattr(
|
| 277 |
+
patch_generator._get_pos_embeddings, "__func__"
|
| 278 |
+
) else patch_generator._get_pos_embeddings
|
| 279 |
+
|
| 280 |
+
def _get_pos_embeddings_aligned(self, batch_size, input_dims):
|
| 281 |
+
if (self.num_rows, self.num_cols) == input_dims:
|
| 282 |
+
return self.pos_embed
|
| 283 |
+
pos_embed = self.pos_embed.reshape(1, self.num_rows, self.num_cols, -1).permute(0, 3, 1, 2)
|
| 284 |
+
|
| 285 |
+
def window_select(pe):
|
| 286 |
+
if input_dims[0] < pe.shape[-2]:
|
| 287 |
+
pe = pe[..., :input_dims[0], :]
|
| 288 |
+
if input_dims[1] < pe.shape[-1]:
|
| 289 |
+
pe = pe[..., :, :input_dims[1]]
|
| 290 |
+
return pe
|
| 291 |
+
|
| 292 |
+
if self.cpe_mode:
|
| 293 |
+
if self.training:
|
| 294 |
+
# Keep the original training-time jitter path (grid_sample + align_corners=True);
|
| 295 |
+
# only patch the eval branch, which is what Megatron/vLLM use and where the bug is.
|
| 296 |
+
return orig_method(self, batch_size, input_dims)
|
| 297 |
+
max_dim = max(input_dims)
|
| 298 |
+
pos_embed = F.interpolate(
|
| 299 |
+
pos_embed.float(), size=(max_dim, max_dim), align_corners=False, mode="bilinear"
|
| 300 |
+
).to(pos_embed.dtype)
|
| 301 |
+
pos_embed = window_select(pos_embed)
|
| 302 |
+
else:
|
| 303 |
+
pos_embed = window_select(pos_embed)
|
| 304 |
+
|
| 305 |
+
if pos_embed.shape[-2:] != input_dims:
|
| 306 |
+
pos_embed = F.interpolate(
|
| 307 |
+
pos_embed.float(), size=input_dims, align_corners=False, mode="bilinear"
|
| 308 |
+
).to(pos_embed.dtype)
|
| 309 |
+
|
| 310 |
+
pos_embed = pos_embed.flatten(2).permute(0, 2, 1)
|
| 311 |
+
return pos_embed
|
| 312 |
+
|
| 313 |
+
import types
|
| 314 |
+
patch_generator._get_pos_embeddings = types.MethodType(_get_pos_embeddings_aligned, patch_generator)
|
| 315 |
+
|
| 316 |
+
def pixel_shuffle(self, x, scale_factor=0.5):
|
| 317 |
+
n, w, h, c = x.size()
|
| 318 |
+
# N, W, H, C --> N, W, H * scale, C // scale
|
| 319 |
+
x = x.view(n, w, int(h * scale_factor), int(c / scale_factor))
|
| 320 |
+
# N, W, H * scale, C // scale --> N, H * scale, W, C // scale
|
| 321 |
+
x = x.permute(0, 2, 1, 3).contiguous()
|
| 322 |
+
# N, H * scale, W, C // scale --> N, H * scale, W * scale, C // (scale ** 2)
|
| 323 |
+
x = x.view(n, int(h * scale_factor), int(w * scale_factor),
|
| 324 |
+
int(c / (scale_factor * scale_factor)))
|
| 325 |
+
if self.ps_version == 'v1':
|
| 326 |
+
warnings.warn("In ps_version 'v1', the height and width have not been swapped back, "
|
| 327 |
+
'which results in a transposed image.')
|
| 328 |
+
else:
|
| 329 |
+
x = x.permute(0, 2, 1, 3).contiguous()
|
| 330 |
+
return x
|
| 331 |
+
|
| 332 |
+
def extract_feature(self, pixel_values):
|
| 333 |
+
"""Run the ViT on a batch of image tiles.
|
| 334 |
+
|
| 335 |
+
Handles two layouts:
|
| 336 |
+
- A single 4D tensor `(B, 3, H, W)` with all tiles sharing the same spatial size (legacy
|
| 337 |
+
fixed-tile path **or** dynamic-resolution path when every image in the batch resizes to
|
| 338 |
+
the same target).
|
| 339 |
+
- A list of 4D tensors `[(1, 3, H_i, W_i), …]` when dynamic resolution picks different
|
| 340 |
+
target sizes per image. Each is run through the ViT independently and the output tokens
|
| 341 |
+
are concatenated along the sequence dim.
|
| 342 |
+
|
| 343 |
+
The patch grid `(h, w)` is computed from the actual input shape, not assumed square — this
|
| 344 |
+
is required for dynamic resolution where the tile aspect ratio matches the original image.
|
| 345 |
+
"""
|
| 346 |
+
if isinstance(pixel_values, (list, tuple)):
|
| 347 |
+
outs = [self._extract_feature_single(pv) for pv in pixel_values]
|
| 348 |
+
return torch.cat(outs, dim=0)
|
| 349 |
+
return self._extract_feature_single(pixel_values)
|
| 350 |
+
|
| 351 |
+
def _extract_feature_single(self, pixel_values):
|
| 352 |
+
vit_embeds = self.vision_model(pixel_values).features
|
| 353 |
+
vit_embeds = vit_embeds.to(dtype=torch.bfloat16)
|
| 354 |
+
# Compute patch grid from the input tile dims; pixel-shuffle needs the real (h, w).
|
| 355 |
+
patch_size = self.vision_model.radio_model.model.patch_generator.patch_size
|
| 356 |
+
B, _, H, W = pixel_values.shape
|
| 357 |
+
h = H // patch_size
|
| 358 |
+
w = W // patch_size
|
| 359 |
+
vit_embeds = vit_embeds.reshape(B, h, w, -1)
|
| 360 |
+
vit_embeds = self.pixel_shuffle(vit_embeds, scale_factor=self.downsample_ratio)
|
| 361 |
+
vit_embeds = vit_embeds.reshape(B, -1, vit_embeds.shape[-1])
|
| 362 |
+
vit_embeds = self.mlp1(vit_embeds)
|
| 363 |
+
return vit_embeds
|
| 364 |
+
|
| 365 |
+
def extract_video_feature(self, pixel_values_videos):
|
| 366 |
+
"""
|
| 367 |
+
Extract features from video frames using the 3D `video_embedder`.
|
| 368 |
+
|
| 369 |
+
Consecutive `T = video_temporal_patch_dim` frames are packed into a single temporal patch
|
| 370 |
+
before the ViT, so the output has `N_frames // T` temporal units (each with the usual number
|
| 371 |
+
of spatial tokens) instead of one ViT output per frame.
|
| 372 |
+
|
| 373 |
+
Implementation trick: RADIO's patch_generator uses a channel-agnostic `Im2Patches` rearrange
|
| 374 |
+
followed by `self.embedder(patches)`. If we stack the T temporal frames into the channel
|
| 375 |
+
dim — `(N_frames, C, H, W)` → `(N_frames/T, T·C, H, W)` — the rearrange produces patches of
|
| 376 |
+
shape `(·, num_patches, T·C·P²)`, which is exactly what `video_embedder` expects. Temporarily
|
| 377 |
+
swapping `embedder ↔ video_embedder` lets us reuse the full ViT forward without duplicating
|
| 378 |
+
the transformer blocks, pos-embed handling, cls_token, etc.
|
| 379 |
+
"""
|
| 380 |
+
pg = self.vision_model.radio_model.model.patch_generator
|
| 381 |
+
T = self.video_temporal_patch_dim
|
| 382 |
+
N, C, H, W = pixel_values_videos.shape
|
| 383 |
+
|
| 384 |
+
# Pad to a multiple of T by repeating the last frame so frame pairs align cleanly.
|
| 385 |
+
if N % T != 0:
|
| 386 |
+
pad = pixel_values_videos[-1:].expand(T - (N % T), -1, -1, -1)
|
| 387 |
+
pixel_values_videos = torch.cat([pixel_values_videos, pad], dim=0)
|
| 388 |
+
N = pixel_values_videos.shape[0]
|
| 389 |
+
num_groups = N // T
|
| 390 |
+
|
| 391 |
+
# Stack T frames into the channel dim. `.view` here preserves the (frame,channel) row-major
|
| 392 |
+
# layout → per-patch feature order is [t=0,c=0..C-1, t=1,c=0..C-1, ...], matching how the
|
| 393 |
+
# `video_embedder` weights are stored in the checkpoint.
|
| 394 |
+
x = pixel_values_videos.reshape(num_groups, T * C, H, W)
|
| 395 |
+
|
| 396 |
+
orig_embedder = pg.embedder
|
| 397 |
+
pg.embedder = pg.video_embedder
|
| 398 |
+
try:
|
| 399 |
+
vit_embeds = self.vision_model(x).features
|
| 400 |
+
finally:
|
| 401 |
+
pg.embedder = orig_embedder
|
| 402 |
+
|
| 403 |
+
# Same spatial post-processing as `extract_feature`. Compute `(h, w)` from the reshaped
|
| 404 |
+
# input so dynamic-res video frames (non-square patch grid) are handled correctly.
|
| 405 |
+
vit_embeds = vit_embeds.to(dtype=torch.bfloat16)
|
| 406 |
+
patch_size = pg.patch_size
|
| 407 |
+
h = H // patch_size
|
| 408 |
+
w = W // patch_size
|
| 409 |
+
vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], h, w, -1)
|
| 410 |
+
vit_embeds = self.pixel_shuffle(vit_embeds, scale_factor=self.downsample_ratio)
|
| 411 |
+
vit_embeds = vit_embeds.reshape(vit_embeds.shape[0], -1, vit_embeds.shape[-1])
|
| 412 |
+
vit_embeds = self.mlp1(vit_embeds)
|
| 413 |
+
return vit_embeds
|
| 414 |
+
|
| 415 |
+
def extract_sound_feature(
|
| 416 |
+
self,
|
| 417 |
+
input_features: torch.Tensor,
|
| 418 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 419 |
+
) -> torch.Tensor:
|
| 420 |
+
"""Extract and project sound features from audio input.
|
| 421 |
+
|
| 422 |
+
Args:
|
| 423 |
+
input_features: Mel spectrogram features [batch, seq_len, feature_dim]
|
| 424 |
+
attention_mask: Optional attention mask [batch, seq_len]
|
| 425 |
+
|
| 426 |
+
Returns:
|
| 427 |
+
Sound embeddings projected to LLM hidden size [batch, encoded_seq_len, llm_hidden_size]
|
| 428 |
+
"""
|
| 429 |
+
if self.sound_encoder is None:
|
| 430 |
+
raise RuntimeError("Sound encoder not initialized. Check if sound_config is provided.")
|
| 431 |
+
|
| 432 |
+
# Encode audio features
|
| 433 |
+
sound_embeds = self.sound_encoder(input_features, attention_mask)
|
| 434 |
+
sound_embeds = sound_embeds.to(dtype=torch.bfloat16)
|
| 435 |
+
|
| 436 |
+
# Project to LLM hidden size
|
| 437 |
+
sound_embeds = self.sound_projection(sound_embeds)
|
| 438 |
+
|
| 439 |
+
return sound_embeds
|
| 440 |
+
|
| 441 |
+
@torch.no_grad()
|
| 442 |
+
def generate(
|
| 443 |
+
self,
|
| 444 |
+
pixel_values: Optional[torch.FloatTensor] = None,
|
| 445 |
+
pixel_values_videos: Optional[torch.FloatTensor] = None,
|
| 446 |
+
sound_clips: Optional[torch.FloatTensor] = None,
|
| 447 |
+
sound_length: Optional[torch.Tensor] = None,
|
| 448 |
+
input_ids: Optional[torch.FloatTensor] = None,
|
| 449 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
| 450 |
+
generation_config: Optional[GenerationConfig] = None,
|
| 451 |
+
output_hidden_states: Optional[bool] = None,
|
| 452 |
+
return_dict: Optional[bool] = None,
|
| 453 |
+
**generate_kwargs,
|
| 454 |
+
) -> torch.LongTensor:
|
| 455 |
+
"""Generate text given images, videos, and/or audio.
|
| 456 |
+
|
| 457 |
+
Args:
|
| 458 |
+
pixel_values: Image pixel values [num_tiles, C, H, W]
|
| 459 |
+
pixel_values_videos: Video pixel values [num_frames, C, H, W]
|
| 460 |
+
sound_clips: Raw audio waveforms. Can be:
|
| 461 |
+
- A list of numpy arrays or torch tensors (one per audio clip)
|
| 462 |
+
- A single numpy array or torch tensor for a single audio clip
|
| 463 |
+
- Pre-extracted mel spectrogram features [batch, seq_len, num_mel_bins]
|
| 464 |
+
sound_length: Length of each audio clip in samples (optional, used for batched audio)
|
| 465 |
+
input_ids: Input token IDs [batch, seq_len]
|
| 466 |
+
attention_mask: Attention mask [batch, seq_len]
|
| 467 |
+
generation_config: Generation configuration
|
| 468 |
+
output_hidden_states: Whether to output hidden states
|
| 469 |
+
return_dict: Whether to return a dict
|
| 470 |
+
**generate_kwargs: Additional generation arguments
|
| 471 |
+
|
| 472 |
+
Returns:
|
| 473 |
+
Generated token IDs
|
| 474 |
+
"""
|
| 475 |
+
assert self.img_context_token_id is not None
|
| 476 |
+
|
| 477 |
+
has_images = pixel_values is not None
|
| 478 |
+
has_videos = pixel_values_videos is not None
|
| 479 |
+
has_sound = sound_clips is not None and self.sound_encoder is not None
|
| 480 |
+
|
| 481 |
+
if has_images or has_videos or has_sound:
|
| 482 |
+
image_vit_embeds, video_vit_embeds, sound_embeds = None, None, None
|
| 483 |
+
|
| 484 |
+
# Process images
|
| 485 |
+
if has_images:
|
| 486 |
+
pixel_values = pixel_values.to(dtype=self.vision_model.config.torch_dtype)
|
| 487 |
+
image_vit_embeds = self.extract_feature(pixel_values)
|
| 488 |
+
|
| 489 |
+
# Process videos
|
| 490 |
+
if has_videos:
|
| 491 |
+
pixel_values_videos = pixel_values_videos.to(dtype=self.vision_model.config.torch_dtype)
|
| 492 |
+
video_vit_embeds = self.extract_video_feature(pixel_values_videos)
|
| 493 |
+
|
| 494 |
+
# Process sound/audio
|
| 495 |
+
if has_sound:
|
| 496 |
+
# Extract features from raw audio using the feature extractor
|
| 497 |
+
# Handle different input types:
|
| 498 |
+
# - list/tuple of waveforms
|
| 499 |
+
# - 1D tensor/array (single waveform)
|
| 500 |
+
# - 2D tensor [batch, samples] (batched raw waveforms)
|
| 501 |
+
# - 3D tensor [batch, seq_len, num_mel_bins] (pre-extracted features)
|
| 502 |
+
import numpy as np
|
| 503 |
+
|
| 504 |
+
is_raw_waveform = False
|
| 505 |
+
if isinstance(sound_clips, (list, tuple)):
|
| 506 |
+
# List of audio clips (waveforms)
|
| 507 |
+
is_raw_waveform = True
|
| 508 |
+
waveforms = sound_clips
|
| 509 |
+
elif isinstance(sound_clips, np.ndarray):
|
| 510 |
+
# Numpy array - raw waveform
|
| 511 |
+
is_raw_waveform = True
|
| 512 |
+
waveforms = [sound_clips.squeeze()] if sound_clips.ndim > 1 else [sound_clips]
|
| 513 |
+
elif isinstance(sound_clips, torch.Tensor):
|
| 514 |
+
if sound_clips.dim() == 1:
|
| 515 |
+
# 1D tensor - single raw waveform
|
| 516 |
+
is_raw_waveform = True
|
| 517 |
+
waveforms = [sound_clips.cpu().numpy()]
|
| 518 |
+
elif sound_clips.dim() == 2:
|
| 519 |
+
# 2D tensor [batch, samples] - batched raw waveforms
|
| 520 |
+
is_raw_waveform = True
|
| 521 |
+
waveforms = [clip.cpu().numpy() for clip in sound_clips]
|
| 522 |
+
else:
|
| 523 |
+
# 3D tensor [batch, seq_len, num_mel_bins] - pre-extracted features
|
| 524 |
+
is_raw_waveform = False
|
| 525 |
+
else:
|
| 526 |
+
is_raw_waveform = False
|
| 527 |
+
|
| 528 |
+
if is_raw_waveform:
|
| 529 |
+
# Convert raw waveforms to mel spectrogram features
|
| 530 |
+
audio_inputs = self.sound_feature_extractor(
|
| 531 |
+
waveforms,
|
| 532 |
+
sampling_rate=self.sound_feature_extractor.sampling_rate,
|
| 533 |
+
return_tensors="pt",
|
| 534 |
+
)
|
| 535 |
+
sound_input_features = audio_inputs.input_features
|
| 536 |
+
sound_attention_mask = audio_inputs.get("attention_mask", None)
|
| 537 |
+
else:
|
| 538 |
+
# Already extracted features
|
| 539 |
+
sound_input_features = sound_clips
|
| 540 |
+
sound_attention_mask = None
|
| 541 |
+
|
| 542 |
+
# Move to correct device and dtype
|
| 543 |
+
target_device = self.sound_encoder.encoder.subsampling.linear.weight.device
|
| 544 |
+
target_dtype = self.language_model.config.torch_dtype
|
| 545 |
+
|
| 546 |
+
sound_input_features = sound_input_features.to(dtype=target_dtype, device=target_device)
|
| 547 |
+
if sound_attention_mask is not None:
|
| 548 |
+
sound_attention_mask = sound_attention_mask.to(device=target_device)
|
| 549 |
+
|
| 550 |
+
sound_embeds = self.extract_sound_feature(sound_input_features, sound_attention_mask)
|
| 551 |
+
|
| 552 |
+
inputs_embeds = self.language_model.get_input_embeddings()(input_ids)
|
| 553 |
+
B, N, C = inputs_embeds.shape
|
| 554 |
+
inputs_embeds = inputs_embeds.reshape(B * N, C)
|
| 555 |
+
input_ids_copy = input_ids.reshape(B * N)
|
| 556 |
+
|
| 557 |
+
# Replace image tokens with image embeddings
|
| 558 |
+
if image_vit_embeds is not None:
|
| 559 |
+
image_mask = (input_ids_copy == self.img_context_token_id)
|
| 560 |
+
assert image_mask.sum() != 0, "No image tokens found in input_ids"
|
| 561 |
+
inputs_embeds[image_mask] = image_vit_embeds.reshape(-1, C).to(inputs_embeds.device, inputs_embeds.dtype)
|
| 562 |
+
|
| 563 |
+
# Replace video tokens with video embeddings. The tokenizer has no distinct `<video>`
|
| 564 |
+
# token (`video_context_token_id` in config doesn't decode to any printable string), so
|
| 565 |
+
# the processor uses `<image>` (id = `img_context_token_id`) as the placeholder for
|
| 566 |
+
# video positions too. We rely on the caller passing `pixel_values_videos` (not
|
| 567 |
+
# `pixel_values`) to signal video vs. image — both share the same token id in the prompt.
|
| 568 |
+
if video_vit_embeds is not None:
|
| 569 |
+
if B > 1:
|
| 570 |
+
raise NotImplementedError("Video is not supported for batch size > 1")
|
| 571 |
+
video_mask = (input_ids_copy == self.img_context_token_id)
|
| 572 |
+
assert video_mask.sum() != 0, "No video tokens found in input_ids"
|
| 573 |
+
inputs_embeds[video_mask] = video_vit_embeds.reshape(-1, C).to(inputs_embeds.device, inputs_embeds.dtype)
|
| 574 |
+
|
| 575 |
+
# Replace sound tokens with sound embeddings.
|
| 576 |
+
# `sound_embeds` has shape `(B_sound, T_out_max, C)` where `T_out_max`
|
| 577 |
+
# is the encoder output length for the longest clip in the batch.
|
| 578 |
+
# When `B_sound > 1` the shorter clips have padding at the tail, so
|
| 579 |
+
# we must gather only the valid positions per row before scattering
|
| 580 |
+
# into `sound_mask`. The encoder's `_get_subsampling_output_length`
|
| 581 |
+
# converts each input mel-frame count (from the feature extractor's
|
| 582 |
+
# attention_mask) to its post-subsampling token count.
|
| 583 |
+
if sound_embeds is not None and self.sound_context_token_id is not None:
|
| 584 |
+
sound_mask = (input_ids_copy == self.sound_context_token_id)
|
| 585 |
+
assert sound_mask.sum() != 0, "No sound tokens found in input_ids"
|
| 586 |
+
if sound_embeds.dim() == 3 and sound_embeds.shape[0] > 1 and sound_attention_mask is not None:
|
| 587 |
+
# `attention_mask.sum() = L_i // hop` per row, but
|
| 588 |
+
# `ParakeetFeatureExtractor` pads each row to `1 + L_i // hop`
|
| 589 |
+
# mel frames in single-call mode (the trailing frame comes
|
| 590 |
+
# from STFT center padding) — and the existing batch=1 path
|
| 591 |
+
# consumes that frame's embed too. Add 1 here to match.
|
| 592 |
+
natural_input_lengths = sound_attention_mask.sum(-1) + 1
|
| 593 |
+
output_lengths = self.sound_encoder.encoder._get_subsampling_output_length(natural_input_lengths)
|
| 594 |
+
flat = torch.cat(
|
| 595 |
+
[sound_embeds[i, : int(n)] for i, n in enumerate(output_lengths.tolist())],
|
| 596 |
+
dim=0,
|
| 597 |
+
)
|
| 598 |
+
else:
|
| 599 |
+
flat = sound_embeds.reshape(-1, C)
|
| 600 |
+
assert sound_mask.sum().item() == flat.shape[0], (
|
| 601 |
+
f"sound token count ({sound_mask.sum().item()}) != encoder output count ({flat.shape[0]})"
|
| 602 |
+
)
|
| 603 |
+
inputs_embeds[sound_mask] = flat.to(inputs_embeds.device, inputs_embeds.dtype)
|
| 604 |
+
|
| 605 |
+
# Apply video pruning (EVS) if enabled
|
| 606 |
+
if video_vit_embeds is not None and self.video_pruning_rate > 0: # EVS
|
| 607 |
+
h = w = int(video_vit_embeds.shape[1] ** 0.5) # assumption here (and everywhere else) is that shape is square
|
| 608 |
+
evs_mask = EfficientVideoSampling.compute_retention_mask(
|
| 609 |
+
video_embeds=video_vit_embeds,
|
| 610 |
+
thw=(video_vit_embeds.shape[0], h, w),
|
| 611 |
+
spatial_merge_size=1, # we already work on vision embeddings, so no downsampling to follow
|
| 612 |
+
q=self.video_pruning_rate,
|
| 613 |
+
)
|
| 614 |
+
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}%)")
|
| 615 |
+
|
| 616 |
+
retention_mask = torch.ones_like(input_ids_copy, dtype=torch.bool)
|
| 617 |
+
retention_mask[video_mask] = evs_mask.view(-1)
|
| 618 |
+
inputs_embeds = inputs_embeds[retention_mask].unsqueeze(0) # adding batch=1
|
| 619 |
+
if attention_mask is not None:
|
| 620 |
+
attention_mask = attention_mask[:, retention_mask].contiguous()
|
| 621 |
+
if input_ids is not None:
|
| 622 |
+
input_ids = input_ids[:, retention_mask].contiguous()
|
| 623 |
+
else:
|
| 624 |
+
inputs_embeds = inputs_embeds.reshape(B, N, C)
|
| 625 |
+
else:
|
| 626 |
+
inputs_embeds = self.language_model.get_input_embeddings()(input_ids)
|
| 627 |
+
|
| 628 |
+
outputs = self.language_model.generate(
|
| 629 |
+
input_ids=input_ids,
|
| 630 |
+
inputs_embeds=inputs_embeds,
|
| 631 |
+
attention_mask=attention_mask,
|
| 632 |
+
generation_config=generation_config,
|
| 633 |
+
output_hidden_states=output_hidden_states,
|
| 634 |
+
use_cache=True,
|
| 635 |
+
**generate_kwargs,
|
| 636 |
+
)
|
| 637 |
+
|
| 638 |
+
return outputs
|
modeling_nemotron_h.py
ADDED
|
@@ -0,0 +1,1368 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/nemotron_h/modular_nemotron_h.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_nemotron_h.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
| 8 |
+
# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
|
| 9 |
+
#
|
| 10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 11 |
+
# you may not use this file except in compliance with the License.
|
| 12 |
+
# You may obtain a copy of the License at
|
| 13 |
+
#
|
| 14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 15 |
+
#
|
| 16 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 19 |
+
# See the License for the specific language governing permissions and
|
| 20 |
+
# limitations under the License.
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
import contextlib
|
| 24 |
+
import math
|
| 25 |
+
from collections.abc import Callable
|
| 26 |
+
from typing import Any
|
| 27 |
+
|
| 28 |
+
import torch
|
| 29 |
+
import torch.nn.functional as F
|
| 30 |
+
from torch import nn
|
| 31 |
+
|
| 32 |
+
import copy
|
| 33 |
+
|
| 34 |
+
from transformers import initialization as init
|
| 35 |
+
from transformers.activations import ACT2FN
|
| 36 |
+
from transformers.generation import GenerationMixin
|
| 37 |
+
from transformers.integrations import (
|
| 38 |
+
lazy_load_kernel,
|
| 39 |
+
use_kernel_forward_from_hub,
|
| 40 |
+
use_kernel_func_from_hub,
|
| 41 |
+
use_kernelized_func,
|
| 42 |
+
)
|
| 43 |
+
from transformers.masking_utils import create_causal_mask
|
| 44 |
+
from transformers.modeling_layers import GradientCheckpointingLayer
|
| 45 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 46 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 47 |
+
from transformers.models.zamba2.modeling_zamba2 import Zamba2RMSNormGated
|
| 48 |
+
from transformers.processing_utils import Unpack
|
| 49 |
+
from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple, is_torchdynamo_compiling, logging
|
| 50 |
+
from transformers.utils.generic import merge_with_config_defaults
|
| 51 |
+
from transformers.utils.import_utils import resolve_internal_import
|
| 52 |
+
from transformers.utils.output_capturing import capture_outputs
|
| 53 |
+
from .configuration_nemotron_h import NemotronHConfig
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
logger = logging.get_logger(__name__)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class NemotronHHybridDynamicCache:
|
| 60 |
+
"""
|
| 61 |
+
A dynamic cache that can handle both the attention cache (which has a seq_len dimension) and the mamba cache
|
| 62 |
+
(which has a constant shape regardless of seq_len).
|
| 63 |
+
|
| 64 |
+
This cache has two sets of lists of tensors: `key_cache` and `value_cache` for attention cache and `conv_states`
|
| 65 |
+
and `ssm_states` for mamba cache. Each of these lists has `num_layers` tensors. The expected shape for each tensor
|
| 66 |
+
For attention layers, `key_cache` and `value_cache` have a shape of `(batch_size, num_heads, seq_len, head_dim)`,
|
| 67 |
+
while `conv_states` and `ssm_states` have a shape of `(batch_size, 0)` (empty tensors).
|
| 68 |
+
For mamba layers, `key_cache` and `value_cache` have a shape of `(batch_size, 0)` (empty tensors),
|
| 69 |
+
while `conv_states` represents the convolution state and has a shape of `(batch_size, d_inner, d_conv)`,
|
| 70 |
+
and `ssm_states` represents the ssm state and has a shape of `(batch_size, d_inner, d_state)`.
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
is_compileable = False
|
| 74 |
+
|
| 75 |
+
def __init__(
|
| 76 |
+
self, config: NemotronHConfig, batch_size: int, dtype: torch.dtype = torch.float16, device: str | None = None
|
| 77 |
+
):
|
| 78 |
+
self.dtype = dtype
|
| 79 |
+
self.layers_block_type = config.layers_block_type
|
| 80 |
+
self.has_previous_state = False
|
| 81 |
+
self.intermediate_size = int(config.mamba_num_heads * config.mamba_head_dim)
|
| 82 |
+
self.ssm_state_size = config.ssm_state_size
|
| 83 |
+
self.conv_kernel_size = config.conv_kernel
|
| 84 |
+
self.n_mamba_heads = config.mamba_num_heads
|
| 85 |
+
self.transformer_layers = []
|
| 86 |
+
self._modules = {}
|
| 87 |
+
self._parameters = {}
|
| 88 |
+
self._buffers = {}
|
| 89 |
+
self.conv_states = {}
|
| 90 |
+
self.ssm_states = {}
|
| 91 |
+
for i in range(config.num_hidden_layers):
|
| 92 |
+
if self.layers_block_type[i] == "mamba":
|
| 93 |
+
# Only allocate mamba cache for mamba layers
|
| 94 |
+
self.conv_states[i] = torch.zeros(
|
| 95 |
+
batch_size,
|
| 96 |
+
self.intermediate_size + 2 * config.n_groups * self.ssm_state_size,
|
| 97 |
+
self.conv_kernel_size,
|
| 98 |
+
device=device,
|
| 99 |
+
dtype=dtype,
|
| 100 |
+
)
|
| 101 |
+
self.ssm_states[i] = torch.zeros(
|
| 102 |
+
batch_size,
|
| 103 |
+
self.n_mamba_heads,
|
| 104 |
+
config.mamba_head_dim,
|
| 105 |
+
self.ssm_state_size,
|
| 106 |
+
device=device,
|
| 107 |
+
dtype=dtype,
|
| 108 |
+
)
|
| 109 |
+
else:
|
| 110 |
+
# For attention and moe layers, use empty tensors
|
| 111 |
+
self.conv_states[i] = torch.tensor([[]] * batch_size, device=device)
|
| 112 |
+
self.ssm_states[i] = torch.tensor([[]] * batch_size, device=device)
|
| 113 |
+
|
| 114 |
+
if self.layers_block_type[i] == "attention":
|
| 115 |
+
self.transformer_layers.append(i)
|
| 116 |
+
self.key_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
|
| 117 |
+
self.value_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
|
| 118 |
+
|
| 119 |
+
def __len__(self):
|
| 120 |
+
return len(self.key_cache)
|
| 121 |
+
|
| 122 |
+
def update(
|
| 123 |
+
self,
|
| 124 |
+
key_states: torch.Tensor,
|
| 125 |
+
value_states: torch.Tensor,
|
| 126 |
+
layer_idx: int,
|
| 127 |
+
cache_kwargs: dict[str, Any] | None = None,
|
| 128 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 129 |
+
# Update the cache
|
| 130 |
+
if self.key_cache[layer_idx].shape[-1] == 0:
|
| 131 |
+
self.key_cache[layer_idx] = key_states
|
| 132 |
+
self.value_cache[layer_idx] = value_states
|
| 133 |
+
else:
|
| 134 |
+
self.key_cache[layer_idx] = torch.cat([self.key_cache[layer_idx], key_states], dim=2)
|
| 135 |
+
self.value_cache[layer_idx] = torch.cat([self.value_cache[layer_idx], value_states], dim=2)
|
| 136 |
+
|
| 137 |
+
return self.key_cache[layer_idx], self.value_cache[layer_idx]
|
| 138 |
+
|
| 139 |
+
def reorder_cache(self, beam_idx: torch.LongTensor):
|
| 140 |
+
"""Reorders the cache for beam search, given the selected beam indices."""
|
| 141 |
+
if self.get_seq_length() > 0:
|
| 142 |
+
for layer_idx in range(len(self.key_cache)):
|
| 143 |
+
device = self.key_cache[layer_idx].device
|
| 144 |
+
self.key_cache[layer_idx] = self.key_cache[layer_idx].index_select(0, beam_idx.to(device))
|
| 145 |
+
device = self.value_cache[layer_idx].device
|
| 146 |
+
self.value_cache[layer_idx] = self.value_cache[layer_idx].index_select(0, beam_idx.to(device))
|
| 147 |
+
|
| 148 |
+
device = self.conv_states[layer_idx].device
|
| 149 |
+
self.conv_states[layer_idx] = self.conv_states[layer_idx].index_select(0, beam_idx.to(device))
|
| 150 |
+
device = self.ssm_states[layer_idx].device
|
| 151 |
+
self.ssm_states[layer_idx] = self.ssm_states[layer_idx].index_select(0, beam_idx.to(device))
|
| 152 |
+
|
| 153 |
+
def get_seq_length(self, layer_idx: int | None = 0) -> int:
|
| 154 |
+
"""Returns the sequence length of the cached states. A layer index can be optionally passed."""
|
| 155 |
+
# take any layer that contains cache and not empty tensor
|
| 156 |
+
layer_idx = self.transformer_layers[0] if layer_idx not in self.transformer_layers else layer_idx
|
| 157 |
+
if len(self.key_cache) <= layer_idx or self.key_cache[layer_idx].numel() == 0:
|
| 158 |
+
return 0
|
| 159 |
+
return self.key_cache[layer_idx].shape[-2]
|
| 160 |
+
|
| 161 |
+
def get_mask_sizes(self, query_length, layer_idx: int) -> tuple[int, int]:
|
| 162 |
+
"""Return the length and offset of the cache, used to generate the mask"""
|
| 163 |
+
# transformers >= 5.6 passes `query_length` as int; earlier versions passed a `cache_position` tensor.
|
| 164 |
+
if isinstance(query_length, torch.Tensor):
|
| 165 |
+
query_length = query_length.shape[0]
|
| 166 |
+
kv_offset = 0
|
| 167 |
+
kv_length = self.get_seq_length(layer_idx) + query_length
|
| 168 |
+
return kv_length, kv_offset
|
| 169 |
+
|
| 170 |
+
def update_conv_state(
|
| 171 |
+
self, layer_idx: int, new_conv_state: torch.Tensor, cache_position: torch.LongTensor
|
| 172 |
+
) -> torch.Tensor:
|
| 173 |
+
conv_state = self.conv_states[layer_idx]
|
| 174 |
+
cache_position = cache_position.clamp(0, self.conv_kernel_size - 1)
|
| 175 |
+
|
| 176 |
+
conv_state = conv_state.roll(shifts=-1, dims=-1)
|
| 177 |
+
conv_state[:, :, cache_position] = new_conv_state.to(conv_state.device)
|
| 178 |
+
self.conv_states[layer_idx].zero_()
|
| 179 |
+
self.conv_states[layer_idx] += conv_state
|
| 180 |
+
return self.conv_states[layer_idx]
|
| 181 |
+
|
| 182 |
+
def reset(self):
|
| 183 |
+
self.conv_states.zero_()
|
| 184 |
+
self.ssm_states.zero_()
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
# Helper methods for segment sum computation
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def pad_tensor_by_size(input_tensor: torch.Tensor, pad_size: int):
|
| 191 |
+
"""
|
| 192 |
+
Padding x tensor with `pad_size` on the seq_len dim (dim=1)
|
| 193 |
+
|
| 194 |
+
Assumes that we only have tensors of either size 4 or 3
|
| 195 |
+
"""
|
| 196 |
+
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)
|
| 197 |
+
|
| 198 |
+
return torch.nn.functional.pad(input_tensor, pad_shape, mode="constant", value=0)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def reshape_into_chunks(input_tensor, pad_size, chunk_size):
|
| 202 |
+
"""
|
| 203 |
+
Padding input_tensor with `pad_size` on the seq_len dim (dim=1) and
|
| 204 |
+
simultaneously splitting it into chunk sequences.
|
| 205 |
+
|
| 206 |
+
Assumes that we only have tensors of either size 4 or 3
|
| 207 |
+
"""
|
| 208 |
+
# [bsz, seq_len, ...] -> [bsz, seq_len multiple of chunk_size, ...]
|
| 209 |
+
input_tensor = pad_tensor_by_size(input_tensor, pad_size)
|
| 210 |
+
|
| 211 |
+
if len(input_tensor.shape) == 3:
|
| 212 |
+
# [bsz, seq_len multiple of chunk_size, num_heads] -> [bsz, -1, chunk_size, num_heads]
|
| 213 |
+
return input_tensor.reshape(input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2])
|
| 214 |
+
else:
|
| 215 |
+
# [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]
|
| 216 |
+
return input_tensor.reshape(
|
| 217 |
+
input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2], input_tensor.shape[3]
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def segment_sum(input_tensor):
|
| 222 |
+
"""
|
| 223 |
+
More stable segment sum calculation. Uses cumulative sums and masking instead of direct subtractions.
|
| 224 |
+
"""
|
| 225 |
+
chunk_size = input_tensor.size(-1)
|
| 226 |
+
# 1. expand input tensor to have an additional dimension and repeat along that dimension
|
| 227 |
+
# [..., chunk_size] -> [..., chunk_size, chunk_size]
|
| 228 |
+
input_tensor = input_tensor[..., None].expand(*input_tensor.size(), chunk_size)
|
| 229 |
+
# 2. create a lower triangular mask with the diagonal set to 0 to 0 out elements above diag
|
| 230 |
+
mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=-1)
|
| 231 |
+
input_tensor = input_tensor.masked_fill(~mask, 0)
|
| 232 |
+
# 3. compute actual cumsum
|
| 233 |
+
tensor_segsum = torch.cumsum(input_tensor, dim=-2)
|
| 234 |
+
|
| 235 |
+
# 4. apply mask to keep only the lower triangular part of the cumulative sum result (incl diagonal this time)
|
| 236 |
+
mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=0)
|
| 237 |
+
tensor_segsum = tensor_segsum.masked_fill(~mask, -torch.inf)
|
| 238 |
+
return tensor_segsum
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
class NemotronHMamba2Mixer(nn.Module):
|
| 242 |
+
"""
|
| 243 |
+
Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
|
| 244 |
+
A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
|
| 245 |
+
∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
|
| 246 |
+
and is why Mamba is called **selective** state spaces)
|
| 247 |
+
"""
|
| 248 |
+
|
| 249 |
+
def __init__(self, config: NemotronHConfig, layer_idx: int | None = None):
|
| 250 |
+
super().__init__()
|
| 251 |
+
self.config = config
|
| 252 |
+
self.hidden_size = config.hidden_size
|
| 253 |
+
self.ssm_state_size = config.ssm_state_size
|
| 254 |
+
self.conv_kernel_size = config.conv_kernel
|
| 255 |
+
self.intermediate_size = config.mamba_num_heads * config.mamba_head_dim
|
| 256 |
+
self.layer_idx = layer_idx
|
| 257 |
+
self.use_conv_bias = config.use_conv_bias
|
| 258 |
+
self.activation = config.mamba_hidden_act
|
| 259 |
+
self.act = ACT2FN[config.mamba_hidden_act]
|
| 260 |
+
self.use_mem_eff_path = True
|
| 261 |
+
|
| 262 |
+
self.n_groups = config.n_groups
|
| 263 |
+
self.head_dim = config.mamba_head_dim
|
| 264 |
+
self.num_heads = config.mamba_num_heads
|
| 265 |
+
self.chunk_size = config.chunk_size
|
| 266 |
+
|
| 267 |
+
self.time_step_limit = config.time_step_limit
|
| 268 |
+
self.time_step_min = config.time_step_min
|
| 269 |
+
self.time_step_max = config.time_step_max
|
| 270 |
+
|
| 271 |
+
self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size
|
| 272 |
+
|
| 273 |
+
self.conv1d = nn.Conv1d(
|
| 274 |
+
in_channels=self.conv_dim,
|
| 275 |
+
out_channels=self.conv_dim,
|
| 276 |
+
bias=config.use_conv_bias,
|
| 277 |
+
kernel_size=self.conv_kernel_size,
|
| 278 |
+
groups=self.conv_dim,
|
| 279 |
+
padding=self.conv_kernel_size - 1,
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
# projection of the input hidden states
|
| 283 |
+
projection_size = self.intermediate_size + self.conv_dim + self.num_heads
|
| 284 |
+
|
| 285 |
+
self.in_proj = nn.Linear(
|
| 286 |
+
self.hidden_size,
|
| 287 |
+
projection_size,
|
| 288 |
+
bias=config.use_bias,
|
| 289 |
+
)
|
| 290 |
+
# selective projection used to make dt, B and C input dependent
|
| 291 |
+
|
| 292 |
+
# time step projection (discretization)
|
| 293 |
+
# instantiate once and copy inv_dt in init_weights of PretrainedModel
|
| 294 |
+
self.dt_bias = nn.Parameter(torch.ones(self.num_heads))
|
| 295 |
+
|
| 296 |
+
# S4D real initialization. These are not discretized!
|
| 297 |
+
# The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
|
| 298 |
+
A = torch.arange(1, self.num_heads + 1)
|
| 299 |
+
self.A_log = nn.Parameter(torch.log(A))
|
| 300 |
+
|
| 301 |
+
self.norm = Zamba2RMSNormGated(
|
| 302 |
+
self.intermediate_size, group_size=self.intermediate_size // self.n_groups, eps=config.layer_norm_epsilon
|
| 303 |
+
)
|
| 304 |
+
self.D = nn.Parameter(torch.ones(self.num_heads))
|
| 305 |
+
|
| 306 |
+
self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.use_bias)
|
| 307 |
+
|
| 308 |
+
global causal_conv1d_update, causal_conv1d_fn
|
| 309 |
+
causal_conv1d = lazy_load_kernel("causal-conv1d")
|
| 310 |
+
causal_conv1d_update = getattr(causal_conv1d, "causal_conv1d_update", None)
|
| 311 |
+
causal_conv1d_fn = getattr(causal_conv1d, "causal_conv1d_fn", None)
|
| 312 |
+
|
| 313 |
+
global selective_state_update, mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined
|
| 314 |
+
mamba_ssm = lazy_load_kernel("mamba-ssm")
|
| 315 |
+
selective_state_update = resolve_internal_import(
|
| 316 |
+
mamba_ssm, chained_path="ops.triton.selective_state_update.selective_state_update"
|
| 317 |
+
)
|
| 318 |
+
mamba_chunk_scan_combined = resolve_internal_import(
|
| 319 |
+
mamba_ssm, chained_path="ops.triton.ssd_combined.mamba_chunk_scan_combined"
|
| 320 |
+
)
|
| 321 |
+
mamba_split_conv1d_scan_combined = resolve_internal_import(
|
| 322 |
+
mamba_ssm, chained_path="ops.triton.ssd_combined.mamba_split_conv1d_scan_combined"
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
global is_fast_path_available
|
| 326 |
+
is_fast_path_available = all(
|
| 327 |
+
(
|
| 328 |
+
selective_state_update,
|
| 329 |
+
mamba_chunk_scan_combined,
|
| 330 |
+
mamba_split_conv1d_scan_combined,
|
| 331 |
+
causal_conv1d_fn,
|
| 332 |
+
causal_conv1d_update,
|
| 333 |
+
)
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
if not is_fast_path_available:
|
| 337 |
+
logger.warning_once(
|
| 338 |
+
"The fast path is not available because one of `(selective_state_update, causal_conv1d_fn, causal_conv1d_update)`"
|
| 339 |
+
" is None. Falling back to the naive implementation. To install follow https://github.com/state-spaces/mamba/#installation and"
|
| 340 |
+
" https://github.com/Dao-AILab/causal-conv1d"
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
def cuda_kernels_forward(
|
| 344 |
+
self,
|
| 345 |
+
hidden_states: torch.Tensor,
|
| 346 |
+
cache_params: NemotronHHybridDynamicCache | None = None,
|
| 347 |
+
attention_mask: torch.Tensor | None = None,
|
| 348 |
+
):
|
| 349 |
+
# set up dimensions for reshapes later
|
| 350 |
+
|
| 351 |
+
batch_size, seq_len, _ = hidden_states.shape
|
| 352 |
+
groups_time_state_size = self.n_groups * self.ssm_state_size
|
| 353 |
+
d_to_remove = 2 * self.intermediate_size + 2 * self.n_groups * self.ssm_state_size + self.num_heads
|
| 354 |
+
|
| 355 |
+
# getting projected states from cache if it exists
|
| 356 |
+
if cache_params is not None and cache_params.has_previous_state:
|
| 357 |
+
in_projected_states = self.in_proj(hidden_states.squeeze(1)) # (B 2D)
|
| 358 |
+
d_mlp = (in_projected_states.shape[-1] - d_to_remove) // 2
|
| 359 |
+
split_projection_dim = [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads]
|
| 360 |
+
_, _, gate, hidden_states_B_C, dt = torch.split(in_projected_states, split_projection_dim, dim=-1)
|
| 361 |
+
|
| 362 |
+
hidden_states_B_C = causal_conv1d_update(
|
| 363 |
+
hidden_states_B_C,
|
| 364 |
+
cache_params.conv_states[self.layer_idx],
|
| 365 |
+
self.conv1d.weight.squeeze(1),
|
| 366 |
+
self.conv1d.bias,
|
| 367 |
+
self.activation,
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
hidden_states, B, C = torch.split(
|
| 371 |
+
hidden_states_B_C,
|
| 372 |
+
[self.intermediate_size, groups_time_state_size, groups_time_state_size],
|
| 373 |
+
dim=-1,
|
| 374 |
+
)
|
| 375 |
+
A = -torch.exp(self.A_log.float()) # (nheads,)
|
| 376 |
+
|
| 377 |
+
A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
|
| 378 |
+
dt = dt[:, :, None].expand(-1, -1, self.head_dim)
|
| 379 |
+
dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
|
| 380 |
+
D = self.D[:, None, ...].expand(-1, self.head_dim)
|
| 381 |
+
B = B.view(batch_size, self.n_groups, B.shape[1] // self.n_groups)
|
| 382 |
+
C = C.view(batch_size, self.n_groups, C.shape[1] // self.n_groups)
|
| 383 |
+
hidden_states_reshaped = hidden_states.view(batch_size, self.num_heads, self.head_dim)
|
| 384 |
+
hidden_states = selective_state_update(
|
| 385 |
+
cache_params.ssm_states[self.layer_idx],
|
| 386 |
+
hidden_states_reshaped,
|
| 387 |
+
dt,
|
| 388 |
+
A,
|
| 389 |
+
B,
|
| 390 |
+
C,
|
| 391 |
+
D,
|
| 392 |
+
z=None,
|
| 393 |
+
dt_bias=dt_bias,
|
| 394 |
+
dt_softplus=True,
|
| 395 |
+
)
|
| 396 |
+
hidden_states = hidden_states.view(batch_size, self.num_heads * self.head_dim)
|
| 397 |
+
hidden_states = self.norm(hidden_states, gate)
|
| 398 |
+
out = self.out_proj(hidden_states)[:, None, ...]
|
| 399 |
+
# if no cache is found, calling the kernel
|
| 400 |
+
else:
|
| 401 |
+
if attention_mask is not None and not torch.all(attention_mask == 1):
|
| 402 |
+
# tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
|
| 403 |
+
dtype = hidden_states.dtype
|
| 404 |
+
hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
|
| 405 |
+
# 1. Gated MLP's linear projection
|
| 406 |
+
projected_states = self.in_proj(hidden_states)
|
| 407 |
+
A = -torch.exp(self.A_log.float()) # (num_heads) or (intermediate_size, state_size)
|
| 408 |
+
dt_limit_kwargs = {} if self.time_step_limit is None else {"dt_limit": self.time_step_limit}
|
| 409 |
+
if attention_mask is not None:
|
| 410 |
+
input_not_masked = torch.all(attention_mask == 1)
|
| 411 |
+
else:
|
| 412 |
+
input_not_masked = True
|
| 413 |
+
|
| 414 |
+
if self.use_mem_eff_path and self.training and cache_params is None and input_not_masked:
|
| 415 |
+
out, ssm_state = mamba_split_conv1d_scan_combined(
|
| 416 |
+
projected_states,
|
| 417 |
+
self.conv1d.weight.squeeze(1),
|
| 418 |
+
self.conv1d.bias,
|
| 419 |
+
self.dt_bias,
|
| 420 |
+
A,
|
| 421 |
+
D=self.D,
|
| 422 |
+
chunk_size=self.chunk_size,
|
| 423 |
+
seq_idx=None,
|
| 424 |
+
activation=self.activation,
|
| 425 |
+
rmsnorm_weight=self.norm.weight,
|
| 426 |
+
rmsnorm_eps=self.norm.variance_epsilon,
|
| 427 |
+
outproj_weight=self.out_proj.weight,
|
| 428 |
+
outproj_bias=self.out_proj.bias,
|
| 429 |
+
headdim=self.head_dim,
|
| 430 |
+
ngroups=self.n_groups,
|
| 431 |
+
norm_before_gate=False,
|
| 432 |
+
return_final_states=True,
|
| 433 |
+
**dt_limit_kwargs,
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
else:
|
| 437 |
+
gate, hidden_states_B_C, time_step = torch.split(
|
| 438 |
+
projected_states,
|
| 439 |
+
[self.intermediate_size, self.conv_dim, self.num_heads],
|
| 440 |
+
dim=-1,
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
# 1D Convolution
|
| 444 |
+
if cache_params is not None:
|
| 445 |
+
hidden_states_B_C_t = hidden_states_B_C.transpose(1, 2)
|
| 446 |
+
conv_state = nn.functional.pad(
|
| 447 |
+
hidden_states_B_C_t, (self.conv_kernel_size - hidden_states_B_C_t.shape[-1], 0)
|
| 448 |
+
)
|
| 449 |
+
cache_params.conv_states[self.layer_idx].copy_(conv_state)
|
| 450 |
+
if causal_conv1d_fn is None or self.activation not in ["silu", "swish"]:
|
| 451 |
+
hidden_states_B_C = self.act(
|
| 452 |
+
self.conv1d(hidden_states_B_C.transpose(1, 2)).transpose(1, 2)[:, :seq_len]
|
| 453 |
+
) # (B, L, self.d_inner + 2 * ngroups * d_state)
|
| 454 |
+
else:
|
| 455 |
+
hidden_states_B_C = causal_conv1d_fn(
|
| 456 |
+
x=hidden_states_B_C.transpose(1, 2),
|
| 457 |
+
weight=self.conv1d.weight.squeeze(1),
|
| 458 |
+
bias=self.conv1d.bias,
|
| 459 |
+
activation=self.activation,
|
| 460 |
+
).transpose(1, 2)[:, :seq_len]
|
| 461 |
+
hidden_states, B, C = torch.split(
|
| 462 |
+
hidden_states_B_C,
|
| 463 |
+
[self.intermediate_size, groups_time_state_size, groups_time_state_size],
|
| 464 |
+
dim=-1,
|
| 465 |
+
)
|
| 466 |
+
if attention_mask is not None and not torch.all(attention_mask == 1):
|
| 467 |
+
# tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
|
| 468 |
+
dtype = hidden_states.dtype
|
| 469 |
+
hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
|
| 470 |
+
scan_output, ssm_state = mamba_chunk_scan_combined(
|
| 471 |
+
hidden_states.view(batch_size, seq_len, -1, self.head_dim),
|
| 472 |
+
time_step,
|
| 473 |
+
A,
|
| 474 |
+
B.view(batch_size, seq_len, self.n_groups, -1),
|
| 475 |
+
C.view(batch_size, seq_len, self.n_groups, -1),
|
| 476 |
+
chunk_size=self.chunk_size,
|
| 477 |
+
D=self.D,
|
| 478 |
+
z=None,
|
| 479 |
+
seq_idx=None,
|
| 480 |
+
return_final_states=True,
|
| 481 |
+
dt_bias=self.dt_bias,
|
| 482 |
+
dt_softplus=True,
|
| 483 |
+
**dt_limit_kwargs,
|
| 484 |
+
)
|
| 485 |
+
if ssm_state is not None and cache_params is not None:
|
| 486 |
+
cache_params.ssm_states[self.layer_idx].copy_(ssm_state)
|
| 487 |
+
scan_output = scan_output.view(batch_size, seq_len, -1)
|
| 488 |
+
# Multiply "gate" branch and apply extra normalization layer
|
| 489 |
+
scan_output = self.norm(scan_output, gate)
|
| 490 |
+
out = self.out_proj(scan_output)
|
| 491 |
+
return out
|
| 492 |
+
|
| 493 |
+
# fmt: off
|
| 494 |
+
def torch_forward(self, input_states, cache_params: NemotronHHybridDynamicCache | None=None, attention_mask: torch.Tensor | None=None):
|
| 495 |
+
batch_size, seq_len, _ = input_states.shape
|
| 496 |
+
dtype = input_states.dtype
|
| 497 |
+
# Gated MLP's linear projection
|
| 498 |
+
if cache_params is not None and cache_params.has_previous_state:
|
| 499 |
+
projected_states = self.in_proj(input_states.squeeze(1))
|
| 500 |
+
else:
|
| 501 |
+
if attention_mask is not None:
|
| 502 |
+
# tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
|
| 503 |
+
input_states = (input_states * attention_mask[:, :, None]).to(dtype)
|
| 504 |
+
projected_states = self.in_proj(input_states)
|
| 505 |
+
d_mlp = (projected_states.shape[-1] - 2 * self.intermediate_size - 2 * self.n_groups * self.ssm_state_size- self.num_heads) // 2
|
| 506 |
+
_, _, gate, hidden_states, dt = projected_states.split(
|
| 507 |
+
[d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
# Convolution sequence transformation
|
| 511 |
+
if cache_params is not None:
|
| 512 |
+
ssm_state = cache_params.ssm_states[self.layer_idx].clone()
|
| 513 |
+
ssm_state = ssm_state.to(hidden_states.device)
|
| 514 |
+
if cache_params.has_previous_state:
|
| 515 |
+
gate = gate.unsqueeze(1)
|
| 516 |
+
conv_state = cache_params.conv_states[self.layer_idx] # [batch, intermediate_size, conv_kernel_size]
|
| 517 |
+
conv_state = torch.roll(conv_state, shifts=-1, dims=-1)
|
| 518 |
+
# handle batched generation - states are copied through
|
| 519 |
+
conv_state[:, :, -1] = hidden_states[:, 0, :] if hidden_states.ndim == 3 else hidden_states
|
| 520 |
+
cache_params.conv_states[self.layer_idx].copy_(conv_state)
|
| 521 |
+
hidden_states = torch.sum(conv_state.to(projected_states.device) * self.conv1d.weight[:, 0, :], dim=-1)
|
| 522 |
+
if self.use_conv_bias:
|
| 523 |
+
hidden_states += self.conv1d.bias
|
| 524 |
+
hidden_states = self.act(hidden_states).to(dtype)[:, None, ...] # [batch, 1, intermediate_size] : decoding
|
| 525 |
+
else:
|
| 526 |
+
hidden_states = hidden_states.transpose(1,2)
|
| 527 |
+
conv_state = nn.functional.pad(
|
| 528 |
+
hidden_states,
|
| 529 |
+
(self.conv_kernel_size - hidden_states.shape[-1], 0)
|
| 530 |
+
)
|
| 531 |
+
cache_params.conv_states[self.layer_idx].copy_(conv_state)
|
| 532 |
+
hidden_states = self.act(self.conv1d(hidden_states).transpose(1,2))[:, :seq_len, :] # [batch, intermediate_size, seq_len]
|
| 533 |
+
if attention_mask is not None:
|
| 534 |
+
dtype = hidden_states.dtype
|
| 535 |
+
# tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
|
| 536 |
+
hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
|
| 537 |
+
else:
|
| 538 |
+
ssm_state = torch.zeros(
|
| 539 |
+
(batch_size, self.num_heads, self.head_dim, self.ssm_state_size),
|
| 540 |
+
device=hidden_states.device, dtype=dtype
|
| 541 |
+
)
|
| 542 |
+
hidden_states = self.act(self.conv1d(hidden_states.transpose(1, 2))[..., :seq_len].transpose(1, 2))
|
| 543 |
+
hidden_states, B, C = torch.split(hidden_states, [self.intermediate_size, self.n_groups * self.ssm_state_size, self.n_groups * self.ssm_state_size], dim=-1)
|
| 544 |
+
A = -torch.exp(self.A_log.float()) # [num_heads]
|
| 545 |
+
if cache_params is not None and cache_params.has_previous_state:
|
| 546 |
+
# Note: there is no need to pad parameter matrices here, as there is just one new token
|
| 547 |
+
# for batched generation
|
| 548 |
+
dt = dt[:, None, ...] if dt.ndim == 2 else dt[:, 0, :][:, None, ...]
|
| 549 |
+
dt = dt.transpose(1, 2).expand(batch_size, dt.shape[-1], self.head_dim)
|
| 550 |
+
# [num_heads] -> [num_heads, head_dim]
|
| 551 |
+
dt_bias = self.dt_bias[..., None].expand(self.dt_bias.shape[0], self.head_dim)
|
| 552 |
+
|
| 553 |
+
dt = torch.nn.functional.softplus(dt + dt_bias.to(dt.dtype))
|
| 554 |
+
dt = torch.clamp(dt, self.time_step_min) #, self.time_step_max)
|
| 555 |
+
A = A[..., None, None].expand(self.num_heads, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
|
| 556 |
+
# [bsz, num_heads, head_dim, state_size]
|
| 557 |
+
dA = torch.exp(dt[..., None] * A)
|
| 558 |
+
|
| 559 |
+
# Discretize B
|
| 560 |
+
# [bsz, n_groups * state_size] -> [bsz, n_groups, 1, state_size] ->
|
| 561 |
+
# -> [bsz, n_groups, group to head repetition factor, state_size] -> [bsz, num_heads, state_size]
|
| 562 |
+
B = B.reshape(batch_size, self.n_groups, -1)[..., None, :]
|
| 563 |
+
B = B.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, B.shape[-1]).contiguous()
|
| 564 |
+
B = B.reshape(batch_size, -1, B.shape[-1])
|
| 565 |
+
# [bsz, num_heads, head_dim, state_size]
|
| 566 |
+
dB = dt[..., None] * B[..., None, :]
|
| 567 |
+
|
| 568 |
+
# Discretize x into dB
|
| 569 |
+
# [bsz, intermediate_size] -> [bsz, num_heads, head_dim]
|
| 570 |
+
hidden_states = hidden_states.reshape(batch_size, -1, self.head_dim)
|
| 571 |
+
dBx = dB * hidden_states[..., None]
|
| 572 |
+
|
| 573 |
+
# State calculation
|
| 574 |
+
cache_params.ssm_states[self.layer_idx].copy_(
|
| 575 |
+
cache_params.ssm_states[self.layer_idx] * dA + dBx
|
| 576 |
+
)
|
| 577 |
+
|
| 578 |
+
# Subsequent output
|
| 579 |
+
# [bsz, n_groups * state_size] -> [bsz, num_heads, state_size]
|
| 580 |
+
C = C.reshape(batch_size, self.n_groups, -1)[..., None, :]
|
| 581 |
+
C = C.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, C.shape[-1]).contiguous()
|
| 582 |
+
C = C.reshape(batch_size, -1, C.shape[-1])
|
| 583 |
+
# [bsz, num_heads, head_dim]
|
| 584 |
+
|
| 585 |
+
ssm_states = cache_params.ssm_states[self.layer_idx].to(C.dtype) # Shape: [b, h, d, n]
|
| 586 |
+
# Reshape ssm_states to merge the first two dimensions
|
| 587 |
+
ssm_states_reshaped = ssm_states.view(batch_size * self.num_heads, self.head_dim, self.ssm_state_size) # Shape: [b*h, d, n]
|
| 588 |
+
C_reshaped = C.view(batch_size * self.num_heads, self.ssm_state_size, 1) # Shape: [b*h, n, 1]
|
| 589 |
+
y = torch.bmm(ssm_states_reshaped, C_reshaped)
|
| 590 |
+
y = y.view(batch_size, self.num_heads, self.head_dim)
|
| 591 |
+
|
| 592 |
+
# D skip connection
|
| 593 |
+
# [num_heads] -> [num_heads, head_dim]
|
| 594 |
+
D = self.D[..., None].expand(self.D.shape[0], self.head_dim)
|
| 595 |
+
y = (y + hidden_states * D).to(y.dtype)
|
| 596 |
+
|
| 597 |
+
# [bsz, num_heads, head_dim] -> [bsz, 1, intermediate_size]
|
| 598 |
+
y = y.reshape(batch_size, -1)[:, None, ...]
|
| 599 |
+
else:
|
| 600 |
+
# begin ssd naive implementation without einsums
|
| 601 |
+
dt = nn.functional.softplus(dt + self.dt_bias)
|
| 602 |
+
dt = torch.clamp(dt, self.time_step_min)
|
| 603 |
+
hidden_states = hidden_states.reshape(batch_size, seq_len, -1, self.head_dim).float()
|
| 604 |
+
B = B.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
|
| 605 |
+
C = C.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
|
| 606 |
+
B = B.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
|
| 607 |
+
C = C.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
|
| 608 |
+
pad_size = (self.chunk_size - seq_len % self.chunk_size) % self.chunk_size
|
| 609 |
+
|
| 610 |
+
D_residual = self.D[..., None] * pad_tensor_by_size(hidden_states, pad_size)
|
| 611 |
+
|
| 612 |
+
# Discretize x and A
|
| 613 |
+
hidden_states = hidden_states * dt[..., None]
|
| 614 |
+
A = A.to(hidden_states.dtype) * dt
|
| 615 |
+
|
| 616 |
+
# Rearrange into blocks/chunks
|
| 617 |
+
hidden_states, A, B, C = [reshape_into_chunks(t, pad_size, self.chunk_size) for t in (hidden_states, A, B, C)]
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
# [bsz, -1, chunk_size, num_heads] -> [bsz, num_heads, -1, chunk_size]
|
| 621 |
+
A = A.permute(0, 3, 1, 2)
|
| 622 |
+
A_cumsum = torch.cumsum(A, dim=-1)
|
| 623 |
+
|
| 624 |
+
# 1. Compute the output for each intra-chunk (diagonal blocks)
|
| 625 |
+
# This is the analog of a causal mask
|
| 626 |
+
L = torch.exp(segment_sum(A))
|
| 627 |
+
|
| 628 |
+
# First, contraction of C and B to get G (attention-weights like)
|
| 629 |
+
G_intermediate = C[:, :, :, None, :, :] * B[:, :, None, :, : ,:] # shape: (b, c, l, s, h, n)
|
| 630 |
+
G = G_intermediate.sum(dim=-1) # shape: (b, c, l, s, h)
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
# Step 2: Compute M, equivalent to applying attention mask to weights
|
| 634 |
+
M_intermediate = G[..., None] * L.permute(0, 2, 3, 4, 1)[..., None]
|
| 635 |
+
M = M_intermediate.sum(dim=-1)
|
| 636 |
+
|
| 637 |
+
# Step 3: Compute Y_diag (apply to values)
|
| 638 |
+
Y_diag = (M[..., None] * hidden_states[:, :, None]).sum(3)
|
| 639 |
+
|
| 640 |
+
# (right term of low-rank factorization of off-diagonal blocks; B terms)
|
| 641 |
+
|
| 642 |
+
decay_states = torch.exp(A_cumsum[:, :, :, -1:] - A_cumsum)
|
| 643 |
+
B_decay_contraction = B * decay_states.permute(0, 2, 3, 1)[..., None]
|
| 644 |
+
# permute back B * decay states
|
| 645 |
+
states = (B_decay_contraction.permute(0, 1, 3, 2, 4)[..., None] * hidden_states.permute(0, 1, 3, 2, 4)[..., None, :]).sum(dim=3).permute(0, 1, 2, 4, 3)
|
| 646 |
+
if cache_params is not None and cache_params.has_previous_state:
|
| 647 |
+
previous_states = cache_params.ssm_states[self.layer_idx][:, None, ...]
|
| 648 |
+
else:
|
| 649 |
+
previous_states = torch.zeros_like(states[:, :1])
|
| 650 |
+
states = torch.cat([previous_states, states], dim=1)
|
| 651 |
+
decay_chunk = torch.exp(segment_sum(nn.functional.pad(A_cumsum[:, :, :, -1], (1, 0))))
|
| 652 |
+
|
| 653 |
+
states_permuted = states.permute(0, 2, 1, 3, 4)
|
| 654 |
+
result = (decay_chunk[..., None, None] * states_permuted[:, :, None, ...]).sum(dim=2)
|
| 655 |
+
new_states = result.permute(0, 2, 1, 3, 4)
|
| 656 |
+
states, ssm_state = new_states[:, :-1], new_states[:, -1]
|
| 657 |
+
|
| 658 |
+
# Compute state -> output conversion per chunk
|
| 659 |
+
# (left term of low-rank factorization of off-diagonal blocks; C terms)
|
| 660 |
+
state_decay_out = torch.exp(A_cumsum)
|
| 661 |
+
# compute Yoff
|
| 662 |
+
C_times_states = (C[..., None, :] * states[:, :, None, ...])
|
| 663 |
+
state_decay_out_permuted = state_decay_out.permute(0, 2, 3, 1)
|
| 664 |
+
Y_off = (C_times_states.sum(-1) * state_decay_out_permuted[..., None])
|
| 665 |
+
# Add output of intra-chunk and inter-chunk terms (diagonal and off-diagonal blocks)
|
| 666 |
+
|
| 667 |
+
y = Y_diag + Y_off
|
| 668 |
+
# [bsz, -1, self.chunk_size, num_heads, head_dim] -> [bsz, (padded) seq_len, num_heads, head_dim]
|
| 669 |
+
y = y.reshape(batch_size, -1, self.num_heads, self.head_dim)
|
| 670 |
+
|
| 671 |
+
y = y + D_residual
|
| 672 |
+
# Cutting off padded chunks
|
| 673 |
+
if pad_size > 0:
|
| 674 |
+
y = y[:, :seq_len, :, :]
|
| 675 |
+
y = y.reshape(batch_size, seq_len, -1)
|
| 676 |
+
if ssm_state is not None and cache_params is not None:
|
| 677 |
+
cache_params.ssm_states[self.layer_idx].copy_(ssm_state)
|
| 678 |
+
|
| 679 |
+
scan_output = self.norm(y, gate)
|
| 680 |
+
|
| 681 |
+
# end ssd naive
|
| 682 |
+
|
| 683 |
+
# 4. Final linear projection
|
| 684 |
+
contextualized_states = self.out_proj(scan_output.to(dtype)) # [batch, seq_len, hidden_size]
|
| 685 |
+
return contextualized_states
|
| 686 |
+
# fmt: on
|
| 687 |
+
|
| 688 |
+
def forward(
|
| 689 |
+
self,
|
| 690 |
+
hidden_states,
|
| 691 |
+
cache_params: NemotronHHybridDynamicCache | None = None,
|
| 692 |
+
attention_mask: torch.Tensor | None = None,
|
| 693 |
+
):
|
| 694 |
+
if is_fast_path_available and "cuda" in self.in_proj.weight.device.type and not is_torchdynamo_compiling():
|
| 695 |
+
return self.cuda_kernels_forward(hidden_states, cache_params, attention_mask)
|
| 696 |
+
|
| 697 |
+
return self.torch_forward(hidden_states, cache_params, attention_mask)
|
| 698 |
+
|
| 699 |
+
|
| 700 |
+
@use_kernel_forward_from_hub("RMSNorm")
|
| 701 |
+
class NemotronHRMSNorm(nn.Module):
|
| 702 |
+
def __init__(self, hidden_size, eps: float = 1e-6) -> None:
|
| 703 |
+
"""
|
| 704 |
+
NemotronHRMSNorm is equivalent to T5LayerNorm
|
| 705 |
+
"""
|
| 706 |
+
super().__init__()
|
| 707 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 708 |
+
self.variance_epsilon = eps
|
| 709 |
+
|
| 710 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 711 |
+
input_dtype = hidden_states.dtype
|
| 712 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 713 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 714 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 715 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 716 |
+
|
| 717 |
+
def extra_repr(self):
|
| 718 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 719 |
+
|
| 720 |
+
|
| 721 |
+
class NemotronHMLP(nn.Module):
|
| 722 |
+
def __init__(self, config, intermediate_size=None):
|
| 723 |
+
super().__init__()
|
| 724 |
+
self.config = config
|
| 725 |
+
self.hidden_size = config.hidden_size
|
| 726 |
+
self.intermediate_size = intermediate_size or config.intermediate_size
|
| 727 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
|
| 728 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
|
| 729 |
+
self.act_fn = ACT2FN[config.mlp_hidden_act]
|
| 730 |
+
|
| 731 |
+
def forward(self, x):
|
| 732 |
+
return self.down_proj(self.act_fn(self.up_proj(x)))
|
| 733 |
+
|
| 734 |
+
|
| 735 |
+
class NemotronHMoE(nn.Module):
|
| 736 |
+
"""
|
| 737 |
+
Mixture-of-Experts (MoE) module for NemotronH.
|
| 738 |
+
|
| 739 |
+
- Experts are stored as an nn.ModuleList of NemotronHMLP, to match the per-expert checkpoint
|
| 740 |
+
format (`experts.<idx>.up_proj.weight` / `experts.<idx>.down_proj.weight`).
|
| 741 |
+
- Optional latent projection wraps the experts.
|
| 742 |
+
"""
|
| 743 |
+
|
| 744 |
+
def __init__(self, config, layer_idx: int | None = None):
|
| 745 |
+
super().__init__()
|
| 746 |
+
self.config = config
|
| 747 |
+
self.n_routed_experts = config.n_routed_experts
|
| 748 |
+
self.n_group = config.n_group
|
| 749 |
+
self.topk_group = config.topk_group
|
| 750 |
+
self.norm_topk_prob = config.norm_topk_prob
|
| 751 |
+
self.routed_scaling_factor = config.routed_scaling_factor
|
| 752 |
+
self.top_k = config.num_experts_per_tok
|
| 753 |
+
|
| 754 |
+
self.gate = NemotronHTopkRouter(config)
|
| 755 |
+
|
| 756 |
+
# Optional latent projection; `moe_latent_size` is absent on older configs.
|
| 757 |
+
moe_latent_size = getattr(config, "moe_latent_size", None)
|
| 758 |
+
if moe_latent_size is not None:
|
| 759 |
+
self.fc1_latent_proj = nn.Linear(config.hidden_size, moe_latent_size, bias=config.mlp_bias)
|
| 760 |
+
self.fc2_latent_proj = nn.Linear(moe_latent_size, config.hidden_size, bias=config.mlp_bias)
|
| 761 |
+
expert_input_dim = moe_latent_size
|
| 762 |
+
else:
|
| 763 |
+
self.fc1_latent_proj = nn.Identity()
|
| 764 |
+
self.fc2_latent_proj = nn.Identity()
|
| 765 |
+
expert_input_dim = config.hidden_size
|
| 766 |
+
|
| 767 |
+
# Shallow-copy config so each expert's NemotronHMLP runs in `expert_input_dim` dim without
|
| 768 |
+
# mutating the top-level config.
|
| 769 |
+
expert_config = copy.copy(config)
|
| 770 |
+
expert_config.hidden_size = expert_input_dim
|
| 771 |
+
self.experts = nn.ModuleList(
|
| 772 |
+
[NemotronHMLP(expert_config, intermediate_size=config.moe_intermediate_size) for _ in range(self.n_routed_experts)]
|
| 773 |
+
)
|
| 774 |
+
self.shared_experts = NemotronHMLP(config=config, intermediate_size=config.moe_shared_expert_intermediate_size)
|
| 775 |
+
|
| 776 |
+
def route_tokens_to_experts(self, router_logits):
|
| 777 |
+
router_logits = router_logits.sigmoid()
|
| 778 |
+
router_logits_for_choice = router_logits + self.gate.e_score_correction_bias
|
| 779 |
+
group_scores = (
|
| 780 |
+
router_logits_for_choice.view(-1, self.n_group, self.n_routed_experts // self.n_group)
|
| 781 |
+
.topk(2, dim=-1)[0]
|
| 782 |
+
.sum(dim=-1)
|
| 783 |
+
)
|
| 784 |
+
group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1]
|
| 785 |
+
group_mask = torch.zeros_like(group_scores)
|
| 786 |
+
group_mask.scatter_(1, group_idx, 1)
|
| 787 |
+
score_mask = (
|
| 788 |
+
group_mask.unsqueeze(-1)
|
| 789 |
+
.expand(-1, self.n_group, self.n_routed_experts // self.n_group)
|
| 790 |
+
.reshape(-1, self.n_routed_experts)
|
| 791 |
+
)
|
| 792 |
+
scores_for_choice = router_logits_for_choice.masked_fill(~score_mask.bool(), 0.0)
|
| 793 |
+
topk_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1]
|
| 794 |
+
topk_weights = router_logits.gather(1, topk_indices)
|
| 795 |
+
if self.norm_topk_prob:
|
| 796 |
+
denominator = topk_weights.sum(dim=-1, keepdim=True) + 1e-20
|
| 797 |
+
topk_weights /= denominator
|
| 798 |
+
topk_weights = topk_weights * self.routed_scaling_factor
|
| 799 |
+
return topk_indices, topk_weights
|
| 800 |
+
|
| 801 |
+
def forward(self, hidden_states):
|
| 802 |
+
residuals = hidden_states
|
| 803 |
+
orig_shape = hidden_states.shape
|
| 804 |
+
router_logits = self.gate(hidden_states)
|
| 805 |
+
topk_indices, topk_weights = self.route_tokens_to_experts(router_logits)
|
| 806 |
+
hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
|
| 807 |
+
|
| 808 |
+
# Route each token through its top-k experts (ModuleList version).
|
| 809 |
+
expert_inputs = self.fc1_latent_proj(hidden_states)
|
| 810 |
+
expert_outputs = torch.zeros_like(expert_inputs, dtype=topk_weights.dtype)
|
| 811 |
+
|
| 812 |
+
with torch.no_grad():
|
| 813 |
+
expert_mask = torch.nn.functional.one_hot(topk_indices, num_classes=self.n_routed_experts)
|
| 814 |
+
expert_mask = expert_mask.permute(2, 1, 0) # (num_experts, top_k, num_tokens)
|
| 815 |
+
expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero().squeeze(-1)
|
| 816 |
+
|
| 817 |
+
for expert_idx in expert_hit:
|
| 818 |
+
expert_idx = expert_idx.item()
|
| 819 |
+
top_k_pos, token_idx = torch.where(expert_mask[expert_idx])
|
| 820 |
+
if token_idx.numel() == 0:
|
| 821 |
+
continue
|
| 822 |
+
current_state = expert_inputs[token_idx]
|
| 823 |
+
current_hidden_states = self.experts[expert_idx](current_state)
|
| 824 |
+
current_hidden_states = current_hidden_states * topk_weights[token_idx, top_k_pos, None]
|
| 825 |
+
expert_outputs.index_add_(0, token_idx, current_hidden_states.to(expert_outputs.dtype))
|
| 826 |
+
|
| 827 |
+
expert_outputs = expert_outputs.to(expert_inputs.dtype)
|
| 828 |
+
hidden_states = self.fc2_latent_proj(expert_outputs)
|
| 829 |
+
|
| 830 |
+
hidden_states = hidden_states.view(*orig_shape)
|
| 831 |
+
hidden_states = hidden_states + self.shared_experts(residuals)
|
| 832 |
+
return hidden_states
|
| 833 |
+
|
| 834 |
+
|
| 835 |
+
class NemotronHTopkRouter(nn.Module):
|
| 836 |
+
def __init__(self, config):
|
| 837 |
+
super().__init__()
|
| 838 |
+
self.config = config
|
| 839 |
+
self.n_routed_experts = config.n_routed_experts
|
| 840 |
+
|
| 841 |
+
self.weight = nn.Parameter(torch.empty((self.n_routed_experts, config.hidden_size)))
|
| 842 |
+
self.register_buffer("e_score_correction_bias", torch.zeros(self.n_routed_experts))
|
| 843 |
+
|
| 844 |
+
def forward(self, hidden_states):
|
| 845 |
+
hidden_states = hidden_states.view(-1, self.config.hidden_size)
|
| 846 |
+
router_logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32))
|
| 847 |
+
return router_logits
|
| 848 |
+
|
| 849 |
+
|
| 850 |
+
def rotate_half(x):
|
| 851 |
+
"""Rotates half the hidden dims of the input."""
|
| 852 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 853 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
| 854 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 855 |
+
|
| 856 |
+
|
| 857 |
+
@use_kernel_func_from_hub("rotary_pos_emb")
|
| 858 |
+
def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
|
| 859 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 860 |
+
|
| 861 |
+
Args:
|
| 862 |
+
q (`torch.Tensor`): The query tensor.
|
| 863 |
+
k (`torch.Tensor`): The key tensor.
|
| 864 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 865 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 866 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 867 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 868 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 869 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 870 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 871 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 872 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 873 |
+
Returns:
|
| 874 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 875 |
+
"""
|
| 876 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 877 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 878 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 879 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 880 |
+
return q_embed, k_embed
|
| 881 |
+
|
| 882 |
+
|
| 883 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 884 |
+
"""
|
| 885 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 886 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 887 |
+
"""
|
| 888 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 889 |
+
if n_rep == 1:
|
| 890 |
+
return hidden_states
|
| 891 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 892 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 893 |
+
|
| 894 |
+
|
| 895 |
+
def eager_attention_forward(
|
| 896 |
+
module: nn.Module,
|
| 897 |
+
query: torch.Tensor,
|
| 898 |
+
key: torch.Tensor,
|
| 899 |
+
value: torch.Tensor,
|
| 900 |
+
attention_mask: torch.Tensor | None,
|
| 901 |
+
scaling: float,
|
| 902 |
+
dropout: float = 0.0,
|
| 903 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 904 |
+
):
|
| 905 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 906 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 907 |
+
|
| 908 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 909 |
+
if attention_mask is not None:
|
| 910 |
+
attn_weights = attn_weights + attention_mask
|
| 911 |
+
|
| 912 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 913 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 914 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 915 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 916 |
+
|
| 917 |
+
return attn_output, attn_weights
|
| 918 |
+
|
| 919 |
+
|
| 920 |
+
@use_kernelized_func(apply_rotary_pos_emb)
|
| 921 |
+
class NemotronHAttention(nn.Module):
|
| 922 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 923 |
+
|
| 924 |
+
def __init__(self, config: NemotronHConfig, layer_idx: int):
|
| 925 |
+
super().__init__()
|
| 926 |
+
self.config = config
|
| 927 |
+
self.layer_idx = layer_idx
|
| 928 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 929 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 930 |
+
self.scaling = self.head_dim**-0.5
|
| 931 |
+
self.attention_dropout = config.attention_dropout
|
| 932 |
+
self.is_causal = True
|
| 933 |
+
self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=False)
|
| 934 |
+
self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
|
| 935 |
+
self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
|
| 936 |
+
self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
|
| 937 |
+
|
| 938 |
+
def forward(
|
| 939 |
+
self,
|
| 940 |
+
hidden_states: torch.Tensor,
|
| 941 |
+
attention_mask: torch.Tensor | None = None,
|
| 942 |
+
past_key_values: NemotronHHybridDynamicCache | None = None,
|
| 943 |
+
cache_position: torch.LongTensor | None = None,
|
| 944 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 945 |
+
) -> tuple[torch.Tensor, torch.Tensor | None]:
|
| 946 |
+
input_shape = hidden_states.shape[:-1]
|
| 947 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 948 |
+
|
| 949 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 950 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 951 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 952 |
+
|
| 953 |
+
if past_key_values is not None:
|
| 954 |
+
key_states, value_states = past_key_values.update(
|
| 955 |
+
key_states, value_states, self.layer_idx, {"cache_position": cache_position}
|
| 956 |
+
)
|
| 957 |
+
|
| 958 |
+
attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
|
| 959 |
+
self.config._attn_implementation, eager_attention_forward
|
| 960 |
+
)
|
| 961 |
+
|
| 962 |
+
attn_output, attn_weights = attention_interface(
|
| 963 |
+
self,
|
| 964 |
+
query_states,
|
| 965 |
+
key_states,
|
| 966 |
+
value_states,
|
| 967 |
+
attention_mask,
|
| 968 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 969 |
+
scaling=self.scaling,
|
| 970 |
+
**kwargs,
|
| 971 |
+
)
|
| 972 |
+
|
| 973 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 974 |
+
attn_output = self.o_proj(attn_output)
|
| 975 |
+
return attn_output, attn_weights
|
| 976 |
+
|
| 977 |
+
|
| 978 |
+
MIXER_TYPES = {
|
| 979 |
+
"mamba": NemotronHMamba2Mixer,
|
| 980 |
+
"attention": NemotronHAttention,
|
| 981 |
+
"moe": NemotronHMoE,
|
| 982 |
+
}
|
| 983 |
+
|
| 984 |
+
|
| 985 |
+
class NemotronHBlock(GradientCheckpointingLayer):
|
| 986 |
+
"""
|
| 987 |
+
A single transformer block in the NemotronH model.
|
| 988 |
+
|
| 989 |
+
This block can contain different types of mixers (Mamba, Attention, MLP, or MoE)
|
| 990 |
+
depending on the configuration. Each block applies pre-normalization followed by
|
| 991 |
+
the mixer, then adds a residual connection.
|
| 992 |
+
|
| 993 |
+
Args:
|
| 994 |
+
config (`NemotronHConfig`):
|
| 995 |
+
Model configuration specifying the block architecture.
|
| 996 |
+
layer_idx (`int`):
|
| 997 |
+
Index of this block in the model. Used to determine the block type from
|
| 998 |
+
`config.layers_block_type[layer_idx]`.
|
| 999 |
+
"""
|
| 1000 |
+
|
| 1001 |
+
def __init__(self, config, layer_idx):
|
| 1002 |
+
super().__init__()
|
| 1003 |
+
self.config = config
|
| 1004 |
+
self.layer_idx = layer_idx
|
| 1005 |
+
self.norm = NemotronHRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
|
| 1006 |
+
|
| 1007 |
+
self.block_type = config.layers_block_type[layer_idx]
|
| 1008 |
+
self.mixer = MIXER_TYPES[self.block_type](config, layer_idx=layer_idx)
|
| 1009 |
+
|
| 1010 |
+
def forward(
|
| 1011 |
+
self,
|
| 1012 |
+
hidden_states,
|
| 1013 |
+
past_key_values: NemotronHHybridDynamicCache | None = None,
|
| 1014 |
+
cache_position: torch.LongTensor | None = None,
|
| 1015 |
+
attention_mask: torch.Tensor | None = None,
|
| 1016 |
+
position_ids: torch.LongTensor | None = None,
|
| 1017 |
+
use_cache: bool | None = False,
|
| 1018 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1019 |
+
):
|
| 1020 |
+
if hidden_states.device.type == "cuda":
|
| 1021 |
+
# Use cuda stream to avoid NaN when using multiple GPUs, which is caused by multi-GPU synchronization issue.
|
| 1022 |
+
# Mamba might launch on the default cuda stream that not strictly respect the current Pytorch cuda stream.
|
| 1023 |
+
# This leads to kernel reading uninitialized memory before the data transfer is complete.
|
| 1024 |
+
stream_context = torch.cuda.stream(torch.cuda.default_stream(hidden_states.device))
|
| 1025 |
+
else:
|
| 1026 |
+
stream_context = contextlib.nullcontext()
|
| 1027 |
+
|
| 1028 |
+
with stream_context:
|
| 1029 |
+
residual = hidden_states
|
| 1030 |
+
hidden_states = self.norm(hidden_states.to(dtype=self.norm.weight.dtype))
|
| 1031 |
+
|
| 1032 |
+
if self.block_type == "mamba":
|
| 1033 |
+
hidden_states = self.mixer(hidden_states, cache_params=past_key_values, attention_mask=attention_mask)
|
| 1034 |
+
elif self.block_type == "attention":
|
| 1035 |
+
hidden_states, _ = self.mixer(
|
| 1036 |
+
hidden_states=hidden_states,
|
| 1037 |
+
past_key_values=past_key_values,
|
| 1038 |
+
attention_mask=attention_mask,
|
| 1039 |
+
position_ids=position_ids,
|
| 1040 |
+
user_cache=use_cache,
|
| 1041 |
+
cache_position=cache_position,
|
| 1042 |
+
**kwargs,
|
| 1043 |
+
)
|
| 1044 |
+
else:
|
| 1045 |
+
hidden_states = self.mixer(hidden_states)
|
| 1046 |
+
|
| 1047 |
+
hidden_states = residual + hidden_states
|
| 1048 |
+
return hidden_states
|
| 1049 |
+
|
| 1050 |
+
|
| 1051 |
+
class NemotronHPreTrainedModel(PreTrainedModel):
|
| 1052 |
+
config: NemotronHConfig
|
| 1053 |
+
base_model_prefix = "backbone"
|
| 1054 |
+
_no_split_modules = ["NemotronHBlock"]
|
| 1055 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 1056 |
+
_supports_flash_attn = True
|
| 1057 |
+
_supports_flash_attn_2 = True
|
| 1058 |
+
_supports_sdpa = True
|
| 1059 |
+
_supports_flex_attn = True
|
| 1060 |
+
_is_stateful = True
|
| 1061 |
+
_can_record_outputs = {
|
| 1062 |
+
"hidden_states": NemotronHBlock,
|
| 1063 |
+
"attentions": NemotronHAttention,
|
| 1064 |
+
}
|
| 1065 |
+
_keep_in_fp32_modules_strict = [
|
| 1066 |
+
"e_score_correction_bias",
|
| 1067 |
+
]
|
| 1068 |
+
_tied_weights_keys = {}
|
| 1069 |
+
_keys_to_ignore_on_load_unexpected = [r"mtp.*"]
|
| 1070 |
+
|
| 1071 |
+
@torch.no_grad()
|
| 1072 |
+
def _init_weights(self, module):
|
| 1073 |
+
"""Initialize the weights."""
|
| 1074 |
+
super()._init_weights(module)
|
| 1075 |
+
if isinstance(module, NemotronHMamba2Mixer):
|
| 1076 |
+
# Initialize A_log and D parameters
|
| 1077 |
+
A = torch.arange(1, self.config.mamba_num_heads + 1)
|
| 1078 |
+
init.copy_(module.A_log, torch.log(A))
|
| 1079 |
+
init.ones_(module.D)
|
| 1080 |
+
|
| 1081 |
+
dt = torch.exp(
|
| 1082 |
+
torch.rand(self.config.mamba_num_heads)
|
| 1083 |
+
* (math.log(self.config.time_step_max) - math.log(self.config.time_step_min))
|
| 1084 |
+
+ math.log(self.config.time_step_min)
|
| 1085 |
+
).clamp(min=self.config.time_step_floor)
|
| 1086 |
+
|
| 1087 |
+
# # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
|
| 1088 |
+
inv_dt = dt + torch.log(-torch.expm1(-dt))
|
| 1089 |
+
with torch.no_grad():
|
| 1090 |
+
init.copy_(module.dt_bias, inv_dt)
|
| 1091 |
+
module.dt_bias._no_reinit = True
|
| 1092 |
+
elif isinstance(module, NemotronHTopkRouter):
|
| 1093 |
+
init.normal_(module.weight, mean=0.0, std=self.config.initializer_range)
|
| 1094 |
+
init.zeros_(module.e_score_correction_bias)
|
| 1095 |
+
# Experts are now an nn.ModuleList of NemotronHMLP; their nn.Linear submodules are handled by
|
| 1096 |
+
# the generic branch below, so no special init branch is needed.
|
| 1097 |
+
|
| 1098 |
+
if isinstance(module, nn.Linear):
|
| 1099 |
+
if module.bias is not None:
|
| 1100 |
+
if not getattr(module.bias, "_no_reinit", False):
|
| 1101 |
+
init.zeros_(module.bias)
|
| 1102 |
+
elif isinstance(module, nn.Embedding):
|
| 1103 |
+
init.normal_(module.weight, std=self.config.initializer_range)
|
| 1104 |
+
|
| 1105 |
+
if self.config.rescale_prenorm_residual:
|
| 1106 |
+
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
|
| 1107 |
+
# > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
|
| 1108 |
+
# > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
|
| 1109 |
+
# > -- GPT-2 :: https://openai.com/blog/better-language-models/
|
| 1110 |
+
#
|
| 1111 |
+
# Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
|
| 1112 |
+
for name, p in module.named_parameters():
|
| 1113 |
+
if name == "out_proj.weight":
|
| 1114 |
+
# Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
|
| 1115 |
+
# Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
|
| 1116 |
+
# We need to reinit p since this code could be called multiple times
|
| 1117 |
+
# Having just p *= scale would repeatedly scale it down
|
| 1118 |
+
init.kaiming_uniform_(p, a=math.sqrt(5))
|
| 1119 |
+
with torch.no_grad():
|
| 1120 |
+
p_new = p / math.sqrt(self.config.num_hidden_layers)
|
| 1121 |
+
init.copy_(p, p_new)
|
| 1122 |
+
|
| 1123 |
+
|
| 1124 |
+
class NemotronHModel(NemotronHPreTrainedModel):
|
| 1125 |
+
def __init__(self, config):
|
| 1126 |
+
super().__init__(config)
|
| 1127 |
+
|
| 1128 |
+
self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
|
| 1129 |
+
self.layers = nn.ModuleList([NemotronHBlock(config, layer_idx=idx) for idx in range(config.num_hidden_layers)])
|
| 1130 |
+
|
| 1131 |
+
self.norm_f = NemotronHRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
|
| 1132 |
+
|
| 1133 |
+
# Legacy checkpoints may use "embedding." (singular); rewrite to "embeddings." on load.
|
| 1134 |
+
self._register_load_state_dict_pre_hook(self.load_hook)
|
| 1135 |
+
|
| 1136 |
+
# Initialize weights and apply final processing
|
| 1137 |
+
self.post_init()
|
| 1138 |
+
|
| 1139 |
+
def load_hook(self, state_dict, prefix, *args):
|
| 1140 |
+
for k in list(state_dict.keys()):
|
| 1141 |
+
if "embedding." in k:
|
| 1142 |
+
state_dict[k.replace("embedding.", "embeddings.")] = state_dict.pop(k)
|
| 1143 |
+
|
| 1144 |
+
def get_input_embeddings(self):
|
| 1145 |
+
return self.embeddings
|
| 1146 |
+
|
| 1147 |
+
def set_input_embeddings(self, new_embeddings):
|
| 1148 |
+
self.embeddings = new_embeddings
|
| 1149 |
+
|
| 1150 |
+
@merge_with_config_defaults
|
| 1151 |
+
@capture_outputs
|
| 1152 |
+
def forward(
|
| 1153 |
+
self,
|
| 1154 |
+
input_ids: torch.LongTensor | None = None,
|
| 1155 |
+
inputs_embeds: torch.LongTensor | None = None,
|
| 1156 |
+
position_ids: torch.LongTensor | None = None,
|
| 1157 |
+
past_key_values: NemotronHHybridDynamicCache | None = None,
|
| 1158 |
+
use_cache: bool | None = None,
|
| 1159 |
+
cache_position: torch.LongTensor | None = None,
|
| 1160 |
+
attention_mask: torch.Tensor | None = None,
|
| 1161 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1162 |
+
) -> tuple | BaseModelOutputWithPast:
|
| 1163 |
+
if (input_ids is None) ^ (inputs_embeds is not None): # ^ is python for xor
|
| 1164 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 1165 |
+
|
| 1166 |
+
if inputs_embeds is None:
|
| 1167 |
+
inputs_embeds = self.embeddings(input_ids)
|
| 1168 |
+
|
| 1169 |
+
if use_cache and past_key_values is None:
|
| 1170 |
+
past_key_values = NemotronHHybridDynamicCache(
|
| 1171 |
+
config=self.config,
|
| 1172 |
+
batch_size=inputs_embeds.shape[0],
|
| 1173 |
+
dtype=inputs_embeds.dtype,
|
| 1174 |
+
device=inputs_embeds.device,
|
| 1175 |
+
)
|
| 1176 |
+
|
| 1177 |
+
hidden_states = inputs_embeds
|
| 1178 |
+
|
| 1179 |
+
if cache_position is None:
|
| 1180 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 1181 |
+
cache_position = torch.arange(
|
| 1182 |
+
past_seen_tokens, past_seen_tokens + hidden_states.shape[1], device=hidden_states.device
|
| 1183 |
+
)
|
| 1184 |
+
if position_ids is None:
|
| 1185 |
+
position_ids = cache_position.unsqueeze(0)
|
| 1186 |
+
|
| 1187 |
+
causal_mask = create_causal_mask(
|
| 1188 |
+
config=self.config,
|
| 1189 |
+
input_embeds=inputs_embeds,
|
| 1190 |
+
attention_mask=attention_mask,
|
| 1191 |
+
cache_position=cache_position,
|
| 1192 |
+
past_key_values=past_key_values,
|
| 1193 |
+
position_ids=position_ids,
|
| 1194 |
+
)
|
| 1195 |
+
mamba_mask = self._update_mamba_mask(attention_mask, cache_position)
|
| 1196 |
+
|
| 1197 |
+
# Map block types to their corresponding masks
|
| 1198 |
+
block_type_to_mask = {
|
| 1199 |
+
"mamba": mamba_mask,
|
| 1200 |
+
"attention": causal_mask,
|
| 1201 |
+
"moe": None,
|
| 1202 |
+
}
|
| 1203 |
+
|
| 1204 |
+
for layer_idx, mixer_block in enumerate(self.layers):
|
| 1205 |
+
layer_mask = block_type_to_mask[mixer_block.block_type]
|
| 1206 |
+
|
| 1207 |
+
hidden_states = mixer_block(
|
| 1208 |
+
hidden_states,
|
| 1209 |
+
attention_mask=layer_mask,
|
| 1210 |
+
position_ids=position_ids,
|
| 1211 |
+
past_key_values=past_key_values,
|
| 1212 |
+
use_cache=use_cache,
|
| 1213 |
+
cache_position=cache_position,
|
| 1214 |
+
**kwargs,
|
| 1215 |
+
)
|
| 1216 |
+
|
| 1217 |
+
hidden_states = self.norm_f(hidden_states)
|
| 1218 |
+
|
| 1219 |
+
if past_key_values is not None and not past_key_values.has_previous_state:
|
| 1220 |
+
past_key_values.has_previous_state = True
|
| 1221 |
+
|
| 1222 |
+
return BaseModelOutputWithPast(
|
| 1223 |
+
last_hidden_state=hidden_states,
|
| 1224 |
+
past_key_values=past_key_values if use_cache else None,
|
| 1225 |
+
)
|
| 1226 |
+
|
| 1227 |
+
def _update_mamba_mask(self, attention_mask, cache_position):
|
| 1228 |
+
"""
|
| 1229 |
+
No need for zeroing states when
|
| 1230 |
+
1. Cached forward
|
| 1231 |
+
2. Attending to all inputs
|
| 1232 |
+
"""
|
| 1233 |
+
mamba_mask = attention_mask
|
| 1234 |
+
if (cache_position is not None and cache_position[0] > 0) or (
|
| 1235 |
+
attention_mask is not None and torch.all(attention_mask == 1)
|
| 1236 |
+
):
|
| 1237 |
+
mamba_mask = None
|
| 1238 |
+
return mamba_mask
|
| 1239 |
+
|
| 1240 |
+
|
| 1241 |
+
# Adapted from transformers.models.jamba.modeling_jamba.JambaForCausalLM with Jamba->NemotronH, JAMBA->NEMOTRON_H
|
| 1242 |
+
class NemotronHForCausalLM(NemotronHPreTrainedModel, GenerationMixin):
|
| 1243 |
+
_tied_weights_keys = {}
|
| 1244 |
+
|
| 1245 |
+
@classmethod
|
| 1246 |
+
def _supports_default_dynamic_cache(cls) -> bool:
|
| 1247 |
+
# This model supplies its own `NemotronHHybridDynamicCache` via `prepare_inputs_for_generation`.
|
| 1248 |
+
# Preventing transformers from injecting a plain `DynamicCache` keeps our mixer code
|
| 1249 |
+
# (which reads `cache_params.conv_states[layer_idx]` / `.has_previous_state`) happy.
|
| 1250 |
+
return False
|
| 1251 |
+
|
| 1252 |
+
def __init__(self, config):
|
| 1253 |
+
super().__init__(config)
|
| 1254 |
+
# Attribute name matches the checkpoint key prefix ("backbone.").
|
| 1255 |
+
self.backbone = NemotronHModel(config)
|
| 1256 |
+
self.vocab_size = config.vocab_size
|
| 1257 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 1258 |
+
|
| 1259 |
+
# Initialize weights and apply final processing
|
| 1260 |
+
self.post_init()
|
| 1261 |
+
|
| 1262 |
+
def get_input_embeddings(self):
|
| 1263 |
+
return self.backbone.get_input_embeddings()
|
| 1264 |
+
|
| 1265 |
+
def set_input_embeddings(self, new_embeddings):
|
| 1266 |
+
return self.backbone.set_input_embeddings(new_embeddings)
|
| 1267 |
+
|
| 1268 |
+
@can_return_tuple
|
| 1269 |
+
@auto_docstring
|
| 1270 |
+
def forward(
|
| 1271 |
+
self,
|
| 1272 |
+
input_ids: torch.LongTensor | None = None,
|
| 1273 |
+
attention_mask: torch.Tensor | None = None,
|
| 1274 |
+
position_ids: torch.LongTensor | None = None,
|
| 1275 |
+
past_key_values: NemotronHHybridDynamicCache | None = None,
|
| 1276 |
+
inputs_embeds: torch.FloatTensor | None = None,
|
| 1277 |
+
labels: torch.LongTensor | None = None,
|
| 1278 |
+
use_cache: bool | None = None,
|
| 1279 |
+
cache_position: torch.LongTensor | None = None,
|
| 1280 |
+
logits_to_keep: int | torch.Tensor = 0,
|
| 1281 |
+
**kwargs,
|
| 1282 |
+
) -> tuple | CausalLMOutputWithPast:
|
| 1283 |
+
r"""
|
| 1284 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1285 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 1286 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 1287 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 1288 |
+
|
| 1289 |
+
Example:
|
| 1290 |
+
|
| 1291 |
+
```python
|
| 1292 |
+
>>> from transformers import AutoTokenizer, NemotronHForCausalLM
|
| 1293 |
+
|
| 1294 |
+
>>> model = NemotronHForCausalLM.from_pretrained("Zyphra/NemotronH-7B-v1")
|
| 1295 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("Zyphra/NemotronH-7B-v1")
|
| 1296 |
+
|
| 1297 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
| 1298 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
| 1299 |
+
|
| 1300 |
+
>>> # Generate
|
| 1301 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
| 1302 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 1303 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
| 1304 |
+
```"""
|
| 1305 |
+
outputs = self.backbone(
|
| 1306 |
+
input_ids=input_ids,
|
| 1307 |
+
attention_mask=attention_mask,
|
| 1308 |
+
position_ids=position_ids,
|
| 1309 |
+
past_key_values=past_key_values,
|
| 1310 |
+
inputs_embeds=inputs_embeds,
|
| 1311 |
+
use_cache=use_cache,
|
| 1312 |
+
cache_position=cache_position,
|
| 1313 |
+
**kwargs,
|
| 1314 |
+
)
|
| 1315 |
+
|
| 1316 |
+
hidden_states = outputs[0]
|
| 1317 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 1318 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 1319 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :]).float()
|
| 1320 |
+
|
| 1321 |
+
loss = None
|
| 1322 |
+
if labels is not None:
|
| 1323 |
+
loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
|
| 1324 |
+
|
| 1325 |
+
return CausalLMOutputWithPast(
|
| 1326 |
+
loss=loss,
|
| 1327 |
+
logits=logits,
|
| 1328 |
+
past_key_values=outputs.past_key_values,
|
| 1329 |
+
hidden_states=outputs.hidden_states,
|
| 1330 |
+
attentions=outputs.attentions,
|
| 1331 |
+
)
|
| 1332 |
+
|
| 1333 |
+
def prepare_inputs_for_generation(
|
| 1334 |
+
self,
|
| 1335 |
+
input_ids,
|
| 1336 |
+
past_key_values=None,
|
| 1337 |
+
attention_mask=None,
|
| 1338 |
+
inputs_embeds=None,
|
| 1339 |
+
cache_position=None,
|
| 1340 |
+
position_ids=None,
|
| 1341 |
+
use_cache=True,
|
| 1342 |
+
is_first_iteration=False,
|
| 1343 |
+
**kwargs,
|
| 1344 |
+
):
|
| 1345 |
+
# Overwritten -- has a unique cache type, `NemotronHHybridDynamicCache`
|
| 1346 |
+
|
| 1347 |
+
if past_key_values is None:
|
| 1348 |
+
past_key_values = NemotronHHybridDynamicCache(
|
| 1349 |
+
self.config, input_ids.shape[0], dtype=self.dtype, device=self.device
|
| 1350 |
+
)
|
| 1351 |
+
|
| 1352 |
+
kwargs["logits_to_keep"] = self.config.num_logits_to_keep
|
| 1353 |
+
model_inputs = super().prepare_inputs_for_generation(
|
| 1354 |
+
input_ids,
|
| 1355 |
+
past_key_values=past_key_values,
|
| 1356 |
+
attention_mask=attention_mask,
|
| 1357 |
+
inputs_embeds=inputs_embeds,
|
| 1358 |
+
cache_position=cache_position,
|
| 1359 |
+
position_ids=position_ids,
|
| 1360 |
+
use_cache=use_cache,
|
| 1361 |
+
is_first_iteration=is_first_iteration,
|
| 1362 |
+
**kwargs,
|
| 1363 |
+
)
|
| 1364 |
+
|
| 1365 |
+
return model_inputs
|
| 1366 |
+
|
| 1367 |
+
|
| 1368 |
+
__all__ = ["NemotronHPreTrainedModel", "NemotronHModel", "NemotronHForCausalLM"]
|
preprocessor_config.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"image_processor_type": "NemotronH_Nano_Omni_Reasoning_V3ImageProcessor",
|
| 3 |
+
"auto_map": {
|
| 4 |
+
"AutoImageProcessor": "image_processing.NemotronH_Nano_Omni_Reasoning_V3ImageProcessor",
|
| 5 |
+
"AutoVideoProcessor": "video_processing.NemotronH_Nano_Omni_Reasoning_V3VideoProcessor",
|
| 6 |
+
"AutoProcessor": "processing.NemotronH_Nano_Omni_Reasoning_V3Processor"
|
| 7 |
+
},
|
| 8 |
+
"patch_size": 16,
|
| 9 |
+
"downsample_ratio": 0.5,
|
| 10 |
+
"norm_mean": [0.48145466, 0.4578275, 0.40821073],
|
| 11 |
+
"norm_std": [0.26862954, 0.26130258, 0.27577711],
|
| 12 |
+
"min_num_patches": 1024,
|
| 13 |
+
"max_num_patches": 13312,
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
import math
|
| 16 |
+
import numpy as np
|
| 17 |
+
import torch
|
| 18 |
+
|
| 19 |
+
from transformers.feature_extraction_utils import BatchFeature
|
| 20 |
+
from transformers.image_utils import ImageInput
|
| 21 |
+
from transformers.processing_utils import ImagesKwargs, MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack, VideosKwargs
|
| 22 |
+
from transformers.tokenization_utils_base import PreTokenizedInput, TextInput
|
| 23 |
+
from transformers.video_utils import VideoInput
|
| 24 |
+
|
| 25 |
+
# Audio input type - can be file paths, numpy arrays, or torch tensors
|
| 26 |
+
AudioInput = Union[str, np.ndarray, torch.Tensor, List[str], List[np.ndarray], List[torch.Tensor]]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class NemotronH_Nano_Omni_Reasoning_V3ImagesKwargs(ImagesKwargs):
|
| 30 |
+
min_pixels: Optional[int]
|
| 31 |
+
max_pixels: Optional[int]
|
| 32 |
+
patch_size: Optional[int]
|
| 33 |
+
temporal_patch_size: Optional[int]
|
| 34 |
+
merge_size: Optional[int]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class NemotronH_Nano_Omni_Reasoning_V3AudioKwargs(ProcessingKwargs, total=False):
|
| 38 |
+
sampling_rate: Optional[int]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class NemotronH_Nano_Omni_Reasoning_V3ProcessorKwargs(ProcessingKwargs, total=False):
|
| 42 |
+
images_kwargs: NemotronH_Nano_Omni_Reasoning_V3ImagesKwargs
|
| 43 |
+
videos_kwargs: VideosKwargs
|
| 44 |
+
audio_kwargs: NemotronH_Nano_Omni_Reasoning_V3AudioKwargs
|
| 45 |
+
_defaults = {
|
| 46 |
+
"text_kwargs": {
|
| 47 |
+
"padding": False,
|
| 48 |
+
},
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class NemotronH_Nano_Omni_Reasoning_V3Processor(ProcessorMixin):
|
| 53 |
+
r"""
|
| 54 |
+
Constructs a Nemotron-3-Nano-Omni-30B-A3B-Reasoning processor which wraps an image processor, audio feature extractor,
|
| 55 |
+
and a tokenizer into a single processor.
|
| 56 |
+
[`NemotronH_Nano_Omni_Reasoning_V3Processor`] offers all the functionalities of the image processor, audio processor,
|
| 57 |
+
and tokenizer. See the [`~NemotronH_Nano_Omni_Reasoning_V3Processor.__call__`] and [`~NemotronH_Nano_Omni_Reasoning_V3Processor.decode`]
|
| 58 |
+
for more information.
|
| 59 |
+
Args:
|
| 60 |
+
image_processor ([`AutoImageProcessor`], *optional*):
|
| 61 |
+
The image processor is a required input.
|
| 62 |
+
tokenizer ([`AutoTokenizer`], *optional*):
|
| 63 |
+
The tokenizer is a required input.
|
| 64 |
+
chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
|
| 65 |
+
in a chat into a tokenizable string.
|
| 66 |
+
audio_sampling_rate (`int`, *optional*): Sampling rate for audio processing (default: 16000).
|
| 67 |
+
audio_subsampling_factor (`int`, *optional*): Subsampling factor for audio encoder (default: 8).
|
| 68 |
+
audio_hop_length (`int`, *optional*): Hop length in samples for feature extraction (default: 160).
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
attributes = ["image_processor", "tokenizer"]
|
| 72 |
+
|
| 73 |
+
image_processor_class = "AutoImageProcessor"
|
| 74 |
+
video_processor_class = "AutoVideoProcessor"
|
| 75 |
+
tokenizer_class = ("AutoTokenizer")
|
| 76 |
+
|
| 77 |
+
def __init__(
|
| 78 |
+
self,
|
| 79 |
+
image_processor=None,
|
| 80 |
+
tokenizer=None,
|
| 81 |
+
chat_template=None,
|
| 82 |
+
audio_sampling_rate: int = 16000,
|
| 83 |
+
audio_subsampling_factor: int = 8,
|
| 84 |
+
audio_hop_length: int = 160,
|
| 85 |
+
video_temporal_patch_dim: int = 2,
|
| 86 |
+
**kwargs
|
| 87 |
+
):
|
| 88 |
+
# Number of frames collapsed into a single temporal patch by the model's `video_embedder`.
|
| 89 |
+
# The `<video>` expansion below issues one placeholder block per temporal patch.
|
| 90 |
+
self.video_temporal_patch_dim = video_temporal_patch_dim
|
| 91 |
+
self.image_token = "<image>" if not hasattr(tokenizer, "image_token") else tokenizer.image_token
|
| 92 |
+
self.video_token = "<video>" if not hasattr(tokenizer, "video_token") else tokenizer.video_token
|
| 93 |
+
self.audio_token = "<so_embedding>" if not hasattr(tokenizer, "audio_token") else tokenizer.audio_token
|
| 94 |
+
self.audio_start_token = "<so_start>"
|
| 95 |
+
self.audio_end_token = "<so_end>"
|
| 96 |
+
self.image_start_token = "<img>" if not hasattr(tokenizer, "image_start_token") else tokenizer.image_start_token
|
| 97 |
+
self.image_end_token = "</img>" if not hasattr(tokenizer, "image_end_token") else tokenizer.image_end_token
|
| 98 |
+
self.image_token_id = (
|
| 99 |
+
tokenizer.image_token_id
|
| 100 |
+
if getattr(tokenizer, "image_token_id", None)
|
| 101 |
+
else tokenizer.convert_tokens_to_ids(self.image_token)
|
| 102 |
+
)
|
| 103 |
+
self.video_token_id = (
|
| 104 |
+
tokenizer.video_token_id
|
| 105 |
+
if getattr(tokenizer, "video_token_id", None)
|
| 106 |
+
else tokenizer.convert_tokens_to_ids(self.video_token)
|
| 107 |
+
)
|
| 108 |
+
self.audio_token_id = (
|
| 109 |
+
tokenizer.audio_token_id
|
| 110 |
+
if getattr(tokenizer, "audio_token_id", None)
|
| 111 |
+
else tokenizer.convert_tokens_to_ids(self.audio_token)
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
# Audio processing parameters
|
| 115 |
+
self.audio_sampling_rate = audio_sampling_rate
|
| 116 |
+
self.audio_subsampling_factor = audio_subsampling_factor
|
| 117 |
+
self.audio_hop_length = audio_hop_length
|
| 118 |
+
|
| 119 |
+
super().__init__(image_processor, tokenizer, chat_template=chat_template)
|
| 120 |
+
|
| 121 |
+
def __call__(
|
| 122 |
+
self,
|
| 123 |
+
images: ImageInput = None,
|
| 124 |
+
text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None,
|
| 125 |
+
videos: VideoInput = None,
|
| 126 |
+
audio: AudioInput = None,
|
| 127 |
+
**kwargs: Unpack[NemotronH_Nano_Omni_Reasoning_V3ProcessorKwargs],
|
| 128 |
+
) -> BatchFeature:
|
| 129 |
+
"""
|
| 130 |
+
Main method to prepare multimodal inputs (text, images, videos, audio) for the model. This method processes
|
| 131 |
+
text by replacing image/video/audio tokens with appropriate placeholder sequences, processes images and videos
|
| 132 |
+
through the image processor, and tokenizes the final text.
|
| 133 |
+
|
| 134 |
+
The method performs the following key operations:
|
| 135 |
+
1. Processes images using the image processor to get pixel values and patch counts
|
| 136 |
+
2. Processes videos using the image processor with max_num_tiles=1 to get video pixel values
|
| 137 |
+
3. Processes audio to compute the number of audio tokens based on duration
|
| 138 |
+
4. Replaces `<image>` tokens in text with `<img>` + image tokens + `</img>` sequences
|
| 139 |
+
5. Replaces `<video>` tokens in text with frame-by-frame descriptions including timestamps (if metadata provided)
|
| 140 |
+
6. Replaces `<audio>` tokens in text with repeated audio tokens based on duration
|
| 141 |
+
7. Tokenizes the processed text and combines all outputs
|
| 142 |
+
|
| 143 |
+
Args:
|
| 144 |
+
images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`, *optional*):
|
| 145 |
+
The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
|
| 146 |
+
tensor. Both channels-first and channels-last formats are supported.
|
| 147 |
+
text (`str`, `List[str]`, *optional*):
|
| 148 |
+
The sequence or batch of sequences to be encoded. Each sequence should be a string. The text can contain
|
| 149 |
+
special tokens `<image>`, `<video>`, and `<audio>` that will be replaced with appropriate token sequences.
|
| 150 |
+
videos (`np.ndarray`, `torch.Tensor`, `List[np.ndarray]`, `List[torch.Tensor]`, *optional*):
|
| 151 |
+
The video or batch of videos to be prepared. Each video should be a 4D NumPy array or PyTorch
|
| 152 |
+
tensor with shape (num_frames, channels, height, width). Both channels-first and channels-last formats
|
| 153 |
+
are supported. Note: Currently only supports batch size of 1 for videos.
|
| 154 |
+
audio (`str`, `np.ndarray`, `torch.Tensor`, `List[str]`, `List[np.ndarray]`, `List[torch.Tensor]`, *optional*):
|
| 155 |
+
The audio or batch of audio clips to be prepared. Can be file paths, numpy arrays (waveforms),
|
| 156 |
+
or torch tensors. Waveforms should be 1D arrays at the expected sampling rate.
|
| 157 |
+
images_kwargs (`Dict`, *optional*):
|
| 158 |
+
Additional keyword arguments for image processing, including:
|
| 159 |
+
- `min_pixels` (`int`, *optional*): Minimum number of pixels for image processing
|
| 160 |
+
- `max_pixels` (`int`, *optional*): Maximum number of pixels for image processing
|
| 161 |
+
- `patch_size` (`int`, *optional*): Size of patches for image processing
|
| 162 |
+
- `temporal_patch_size` (`int`, *optional*): Size of temporal patches
|
| 163 |
+
- `merge_size` (`int`, *optional*): Size for merging patches
|
| 164 |
+
videos_kwargs (`Dict`, *optional*):
|
| 165 |
+
Additional keyword arguments for video processing, including:
|
| 166 |
+
- `video_metadata` (`VideoMetadata`, *optional*): Metadata containing fps information for timestamp calculation
|
| 167 |
+
audio_kwargs (`Dict`, *optional*):
|
| 168 |
+
Additional keyword arguments for audio processing, including:
|
| 169 |
+
- `sampling_rate` (`int`, *optional*): Target sampling rate for audio
|
| 170 |
+
text_kwargs (`Dict`, *optional*):
|
| 171 |
+
Additional keyword arguments for text tokenization, including:
|
| 172 |
+
- `return_tensors` (`str` or [`~utils.TensorType`], *optional*): Framework for returned tensors ('tf', 'pt', 'np', 'jax')
|
| 173 |
+
- `padding` (`bool`, *optional*): Whether to pad sequences (defaults to False)
|
| 174 |
+
|
| 175 |
+
Returns:
|
| 176 |
+
[`BatchFeature`]: A [`BatchFeature`] with the following fields:
|
| 177 |
+
|
| 178 |
+
- **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
|
| 179 |
+
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
|
| 180 |
+
`return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
|
| 181 |
+
`None`).
|
| 182 |
+
- **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
|
| 183 |
+
- **num_patches** -- Number of patches per image. Returned when `images` is not `None`.
|
| 184 |
+
- **pixel_values_videos** -- Pixel values of videos to be fed to a model. Returned when `videos` is not `None`.
|
| 185 |
+
- **sound_clips** -- Raw audio waveforms to be fed to a model. Returned when `audio` is not `None`.
|
| 186 |
+
|
| 187 |
+
Raises:
|
| 188 |
+
AssertionError: If videos are provided with batch size > 1 (not currently supported).
|
| 189 |
+
|
| 190 |
+
Note:
|
| 191 |
+
- Image tokens `<image>` in text are replaced with `<img>` + repeated image tokens + `</img>`
|
| 192 |
+
- Video tokens `<video>` in text are replaced with frame-by-frame descriptions
|
| 193 |
+
- Audio tokens `<audio>` in text are replaced with repeated audio placeholder tokens
|
| 194 |
+
- When video metadata with fps is provided, frame descriptions include timestamps
|
| 195 |
+
- Videos are processed with max_num_tiles=1 regardless of the images setting
|
| 196 |
+
"""
|
| 197 |
+
output_kwargs = self._merge_kwargs(
|
| 198 |
+
NemotronH_Nano_Omni_Reasoning_V3ProcessorKwargs,
|
| 199 |
+
tokenizer_init_kwargs=self.tokenizer.init_kwargs,
|
| 200 |
+
**kwargs,
|
| 201 |
+
)
|
| 202 |
+
image_inputs, videos_inputs, audio_inputs = {}, {}, {}
|
| 203 |
+
|
| 204 |
+
if images is not None:
|
| 205 |
+
image_inputs = self.image_processor(images=images, **output_kwargs["images_kwargs"])
|
| 206 |
+
image_num_tokens = image_inputs["num_tokens"]
|
| 207 |
+
|
| 208 |
+
if videos is not None:
|
| 209 |
+
# One tile per frame, but sized with the **video** rule (`video_target_num_patches` +
|
| 210 |
+
# aspect ratio) — different from the image rule. We flip a flag on the image processor
|
| 211 |
+
# around the call rather than routing a new kwarg through `ImagesKwargs`, which is a
|
| 212 |
+
# strict-dataclass and rejects unknown fields.
|
| 213 |
+
self.image_processor._is_video_mode = True
|
| 214 |
+
try:
|
| 215 |
+
videos_inputs = self.image_processor(images=videos, **output_kwargs["images_kwargs"])
|
| 216 |
+
finally:
|
| 217 |
+
self.image_processor._is_video_mode = False
|
| 218 |
+
video_num_patches = [sum(videos_inputs["num_patches"])]
|
| 219 |
+
videos_inputs["pixel_values_videos"] = videos_inputs["pixel_values"]
|
| 220 |
+
del videos_inputs["pixel_values"]
|
| 221 |
+
|
| 222 |
+
# Process audio inputs
|
| 223 |
+
audio_num_tokens = []
|
| 224 |
+
if audio is not None:
|
| 225 |
+
audio_clips, audio_num_tokens = self._process_audio(audio, output_kwargs.get("audio_kwargs", {}))
|
| 226 |
+
# Keep as list of numpy arrays - don't let BatchFeature convert to tensor
|
| 227 |
+
# The model's generate function will handle conversion
|
| 228 |
+
audio_inputs["sound_clips"] = audio_clips
|
| 229 |
+
|
| 230 |
+
if not isinstance(text, list):
|
| 231 |
+
text = [text]
|
| 232 |
+
|
| 233 |
+
text = text.copy() # below lines change text in-place
|
| 234 |
+
if images is not None:
|
| 235 |
+
index = 0
|
| 236 |
+
for i in range(len(text)):
|
| 237 |
+
while self.image_token in text[i]:
|
| 238 |
+
n_tokens = image_num_tokens[index]
|
| 239 |
+
text[i] = text[i].replace(
|
| 240 |
+
self.image_token,
|
| 241 |
+
self.image_start_token + "<|placeholder|>" * n_tokens + self.image_end_token,
|
| 242 |
+
1,
|
| 243 |
+
)
|
| 244 |
+
index += 1
|
| 245 |
+
text[i] = text[i].replace("<|placeholder|>", self.image_token)
|
| 246 |
+
|
| 247 |
+
if videos is not None:
|
| 248 |
+
assert len(text) == 1, "Video is not supported for batch size > 1"
|
| 249 |
+
video_metadata = output_kwargs.get("videos_kwargs", {}).get("video_metadata", None)
|
| 250 |
+
i = 0
|
| 251 |
+
index = 0
|
| 252 |
+
if self.video_token in text[i]:
|
| 253 |
+
# Matches vLLM's `get_video_repl` (`vllm/transformers_utils/processors/
|
| 254 |
+
# nano_nemotron_vl.py`): one `<img>…</img>` chunk per temporal patch (tubelet),
|
| 255 |
+
# labeled with the per-frame timestamps joined by " and " — capitalized "Frame"
|
| 256 |
+
# for the first frame in the tubelet, lowercase "frame" for the rest. No "This is
|
| 257 |
+
# a video:\n" prefix is emitted by the processor — it's expected to come from the
|
| 258 |
+
# client message, consistent with vLLM and training.
|
| 259 |
+
tokens_per_tubelet = videos_inputs["num_tokens"][0]
|
| 260 |
+
each_group = self.image_start_token + "<|placeholder|>" * tokens_per_tubelet + self.image_end_token
|
| 261 |
+
T = self.video_temporal_patch_dim
|
| 262 |
+
n_frames = video_num_patches[index]
|
| 263 |
+
n_groups = (n_frames + T - 1) // T
|
| 264 |
+
|
| 265 |
+
# vLLM formula: int(source_frame_idx) * int(1000 / source_fps) / 1000
|
| 266 |
+
# Requires source fps and source frame indices from video_metadata.
|
| 267 |
+
source_fps = video_metadata.fps if (video_metadata is not None and video_metadata.fps) else None
|
| 268 |
+
frames_indices = video_metadata.frames_indices if video_metadata is not None else None
|
| 269 |
+
if source_fps is not None:
|
| 270 |
+
frame_duration_ms = int(1000.0 / source_fps)
|
| 271 |
+
|
| 272 |
+
frame_labels = []
|
| 273 |
+
for g in range(n_groups):
|
| 274 |
+
parts = []
|
| 275 |
+
for j in range(T):
|
| 276 |
+
fi = g * T + j
|
| 277 |
+
if fi >= n_frames:
|
| 278 |
+
break # last group may be short
|
| 279 |
+
prefix = "Frame" if j == 0 else "frame"
|
| 280 |
+
if source_fps is not None and frames_indices is not None and fi < len(frames_indices):
|
| 281 |
+
ts = int(frames_indices[fi]) * frame_duration_ms / 1000.0
|
| 282 |
+
parts.append(f"{prefix} {fi+1} sampled at {ts:.2f} seconds")
|
| 283 |
+
elif source_fps is not None:
|
| 284 |
+
ts = fi / source_fps
|
| 285 |
+
parts.append(f"{prefix} {fi+1} sampled at {ts:.2f} seconds")
|
| 286 |
+
else:
|
| 287 |
+
parts.append(f"{prefix} {fi+1}")
|
| 288 |
+
frame_labels.append(" and ".join(parts) + ": ")
|
| 289 |
+
|
| 290 |
+
video_prompt = ""
|
| 291 |
+
for g, label in enumerate(frame_labels):
|
| 292 |
+
if g > 0:
|
| 293 |
+
video_prompt += "\n"
|
| 294 |
+
video_prompt += label + each_group
|
| 295 |
+
|
| 296 |
+
text[i] = text[i].replace(self.video_token, video_prompt, 1)
|
| 297 |
+
# The tokenizer has no real `<video>` token (the 131081 id in the config doesn't decode
|
| 298 |
+
# to any printable string), so we reuse `<image>` (id 18) as the placeholder. The outer
|
| 299 |
+
# model distinguishes image vs. video by which `pixel_values_*` arg was passed.
|
| 300 |
+
text[i] = text[i].replace("<|placeholder|>", self.image_token)
|
| 301 |
+
|
| 302 |
+
# Replace audio tokens with the correct number of placeholder tokens.
|
| 303 |
+
# The expansion loop is per-row, so batch size > 1 is supported as long
|
| 304 |
+
# as `audio_num_tokens` has one entry per `<so_embedding>` placeholder
|
| 305 |
+
# across the batch (in row-major order).
|
| 306 |
+
if audio is not None:
|
| 307 |
+
index = 0
|
| 308 |
+
for i in range(len(text)):
|
| 309 |
+
while self.audio_token in text[i]:
|
| 310 |
+
num_tokens = audio_num_tokens[index] if index < len(audio_num_tokens) else 1
|
| 311 |
+
# Replace <audio> with repeated audio tokens
|
| 312 |
+
text[i] = text[i].replace(self.audio_token, self.audio_start_token + "<|audio_placeholder|>" * num_tokens + self.audio_end_token, 1)
|
| 313 |
+
index += 1
|
| 314 |
+
text[i] = text[i].replace("<|audio_placeholder|>", self.audio_token)
|
| 315 |
+
|
| 316 |
+
return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
|
| 317 |
+
text_inputs = self.tokenizer(text, **output_kwargs["text_kwargs"])
|
| 318 |
+
|
| 319 |
+
# Build output - exclude audio from tensor conversion since it's raw waveforms
|
| 320 |
+
output_data = {**text_inputs, **image_inputs, **videos_inputs}
|
| 321 |
+
result = BatchFeature(data=output_data, tensor_type=return_tensors)
|
| 322 |
+
|
| 323 |
+
# Add audio clips separately (as list of numpy arrays, not tensors)
|
| 324 |
+
if audio_inputs:
|
| 325 |
+
result["sound_clips"] = audio_inputs["sound_clips"]
|
| 326 |
+
|
| 327 |
+
return result
|
| 328 |
+
|
| 329 |
+
def _process_audio(
|
| 330 |
+
self,
|
| 331 |
+
audio: AudioInput,
|
| 332 |
+
audio_kwargs: dict
|
| 333 |
+
) -> tuple:
|
| 334 |
+
"""Process audio inputs and compute the number of audio tokens.
|
| 335 |
+
|
| 336 |
+
Args:
|
| 337 |
+
audio: Audio input (file path, waveform array, or list thereof)
|
| 338 |
+
audio_kwargs: Additional audio processing arguments
|
| 339 |
+
|
| 340 |
+
Returns:
|
| 341 |
+
Tuple of (audio_clips, num_tokens_per_clip)
|
| 342 |
+
"""
|
| 343 |
+
# Get sampling rate from kwargs or use default
|
| 344 |
+
sampling_rate = audio_kwargs.get("sampling_rate", self.audio_sampling_rate)
|
| 345 |
+
|
| 346 |
+
# Normalize audio to list
|
| 347 |
+
if not isinstance(audio, list):
|
| 348 |
+
audio = [audio]
|
| 349 |
+
|
| 350 |
+
audio_clips = []
|
| 351 |
+
num_tokens = []
|
| 352 |
+
|
| 353 |
+
for audio_item in audio:
|
| 354 |
+
# Load audio if it's a file path
|
| 355 |
+
if isinstance(audio_item, str):
|
| 356 |
+
waveform = self._load_audio(audio_item, sampling_rate)
|
| 357 |
+
elif isinstance(audio_item, torch.Tensor):
|
| 358 |
+
waveform = audio_item.numpy() if audio_item.dim() == 1 else audio_item.squeeze().numpy()
|
| 359 |
+
elif isinstance(audio_item, np.ndarray):
|
| 360 |
+
waveform = audio_item.squeeze() if audio_item.ndim > 1 else audio_item
|
| 361 |
+
else:
|
| 362 |
+
raise ValueError(f"Unsupported audio type: {type(audio_item)}")
|
| 363 |
+
|
| 364 |
+
audio_clips.append(waveform)
|
| 365 |
+
|
| 366 |
+
n_tokens = self._estimate_audio_num_embeddings(len(waveform))
|
| 367 |
+
num_tokens.append(max(1, n_tokens)) # At least 1 token
|
| 368 |
+
|
| 369 |
+
return audio_clips, num_tokens
|
| 370 |
+
|
| 371 |
+
def _estimate_audio_num_embeddings(self, audio_length_samples: int) -> int:
|
| 372 |
+
"""Predict the exact number of `<so_embedding>` tokens that the sound
|
| 373 |
+
encoder will produce for an audio clip of `audio_length_samples` raw
|
| 374 |
+
samples. Replaces the previous heuristic, which under-counted by 1 for
|
| 375 |
+
certain lengths and tripped a shape mismatch in `modeling.py::generate`.
|
| 376 |
+
|
| 377 |
+
Mirrors `ParakeetFeatureExtractor` (center-padded STFT → ``1 + L // hop``
|
| 378 |
+
mel frames) followed by `ParakeetEncoder._get_subsampling_output_length`
|
| 379 |
+
(``log2(subsampling_factor)`` stages of stride-2 conv with kernel-size
|
| 380 |
+
``subsampling_conv_kernel_size``, symmetric padding ``(kernel-1)//2`` on
|
| 381 |
+
each side).
|
| 382 |
+
"""
|
| 383 |
+
# Mel frame count (center=True is HF Parakeet's default).
|
| 384 |
+
n_frames = 1 + audio_length_samples // self.audio_hop_length
|
| 385 |
+
# Conv-subsampling: ``log2(subsampling_factor)`` stages, stride 2,
|
| 386 |
+
# kernel ``subsampling_conv_kernel_size``, symmetric padding.
|
| 387 |
+
kernel_size = getattr(self, "audio_subsampling_conv_kernel_size", 3)
|
| 388 |
+
stride = getattr(self, "audio_subsampling_conv_stride", 2)
|
| 389 |
+
num_layers = int(math.log2(self.audio_subsampling_factor))
|
| 390 |
+
all_paddings = (kernel_size - 1) // 2 * 2
|
| 391 |
+
add_pad = all_paddings - kernel_size # kernel=3, sym pad=1 → -1
|
| 392 |
+
L = n_frames
|
| 393 |
+
for _ in range(num_layers):
|
| 394 |
+
L = (L + add_pad) // stride + 1
|
| 395 |
+
return L
|
| 396 |
+
|
| 397 |
+
def _load_audio(self, audio_path: str, target_sr: int) -> np.ndarray:
|
| 398 |
+
"""Load audio from file and resample if necessary.
|
| 399 |
+
|
| 400 |
+
Args:
|
| 401 |
+
audio_path: Path to audio file
|
| 402 |
+
target_sr: Target sampling rate
|
| 403 |
+
|
| 404 |
+
Returns:
|
| 405 |
+
Audio waveform as numpy array
|
| 406 |
+
"""
|
| 407 |
+
try:
|
| 408 |
+
import librosa
|
| 409 |
+
waveform, sr = librosa.load(audio_path, sr=target_sr, mono=True)
|
| 410 |
+
return waveform
|
| 411 |
+
except ImportError:
|
| 412 |
+
pass
|
| 413 |
+
|
| 414 |
+
try:
|
| 415 |
+
import soundfile as sf
|
| 416 |
+
waveform, sr = sf.read(audio_path)
|
| 417 |
+
if waveform.ndim > 1:
|
| 418 |
+
waveform = waveform.mean(axis=1) # Convert to mono
|
| 419 |
+
if sr != target_sr:
|
| 420 |
+
# Simple resampling using numpy
|
| 421 |
+
import scipy.signal
|
| 422 |
+
num_samples = int(len(waveform) * target_sr / sr)
|
| 423 |
+
waveform = scipy.signal.resample(waveform, num_samples)
|
| 424 |
+
return waveform.astype(np.float32)
|
| 425 |
+
except ImportError:
|
| 426 |
+
pass
|
| 427 |
+
|
| 428 |
+
raise ImportError(
|
| 429 |
+
"Audio loading requires either librosa or soundfile. "
|
| 430 |
+
"Install with: pip install librosa soundfile"
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
def _get_num_multimodal_tokens(self, image_sizes=None, video_sizes=None, **kwargs):
|
| 434 |
+
"""
|
| 435 |
+
Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
|
| 436 |
+
Args:
|
| 437 |
+
image_sizes (`list[list[int]]`, *optional*):
|
| 438 |
+
The input sizes formatted as (height, width) per each image.
|
| 439 |
+
video_sizes (`list[list[int]]`, *optional*):
|
| 440 |
+
The input sizes formatted as (num_frames, height, width) per each video.
|
| 441 |
+
Returns:
|
| 442 |
+
`MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
|
| 443 |
+
input modalities, along with other useful data.
|
| 444 |
+
"""
|
| 445 |
+
|
| 446 |
+
vision_data = {}
|
| 447 |
+
if image_sizes is not None:
|
| 448 |
+
images_kwargs = NemotronH_Nano_Omni_Reasoning_V3ProcessorKwargs._defaults.get("images_kwargs", {})
|
| 449 |
+
images_kwargs.update(kwargs)
|
| 450 |
+
merge_size = images_kwargs.get("merge_size", None) or self.image_processor.merge_size
|
| 451 |
+
|
| 452 |
+
num_image_patches = [
|
| 453 |
+
self.image_processor.get_number_of_image_patches(*image_size, images_kwargs)
|
| 454 |
+
for image_size in image_sizes
|
| 455 |
+
]
|
| 456 |
+
num_image_tokens = [(num_patches // merge_size**2) for num_patches in num_image_patches]
|
| 457 |
+
vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
|
| 458 |
+
return MultiModalData(**vision_data)
|
| 459 |
+
|
| 460 |
+
def batch_decode(self, *args, **kwargs):
|
| 461 |
+
"""
|
| 462 |
+
This method forwards all its arguments to the tokenizer's [`~PreTrainedTokenizer.batch_decode`]. Please
|
| 463 |
+
refer to the docstring of this method for more information.
|
| 464 |
+
"""
|
| 465 |
+
return self.tokenizer.batch_decode(*args, **kwargs)
|
| 466 |
+
|
| 467 |
+
def decode(self, *args, **kwargs):
|
| 468 |
+
"""
|
| 469 |
+
This method forwards all its arguments to the tokenizer's [`~PreTrainedTokenizer.decode`]. Please refer to
|
| 470 |
+
the docstring of this method for more information.
|
| 471 |
+
"""
|
| 472 |
+
return self.tokenizer.decode(*args, **kwargs)
|
| 473 |
+
|
| 474 |
+
def post_process_image_text_to_text(
|
| 475 |
+
self, generated_outputs, skip_special_tokens=True, clean_up_tokenization_spaces=False, **kwargs
|
| 476 |
+
):
|
| 477 |
+
"""
|
| 478 |
+
Post-process the output of the model to decode the text.
|
| 479 |
+
|
| 480 |
+
Args:
|
| 481 |
+
generated_outputs (`torch.Tensor` or `np.ndarray`):
|
| 482 |
+
The output of the model `generate` function. The output is expected to be a tensor of shape `(batch_size, sequence_length)`
|
| 483 |
+
or `(sequence_length,)`.
|
| 484 |
+
skip_special_tokens (`bool`, *optional*, defaults to `True`):
|
| 485 |
+
Whether or not to remove special tokens in the output. Argument passed to the tokenizer's `batch_decode` method.
|
| 486 |
+
clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
|
| 487 |
+
Whether or not to clean up the tokenization spaces. Argument passed to the tokenizer's `batch_decode` method.
|
| 488 |
+
**kwargs:
|
| 489 |
+
Additional arguments to be passed to the tokenizer's `batch_decode method`.
|
| 490 |
+
|
| 491 |
+
Returns:
|
| 492 |
+
`list[str]`: The decoded text.
|
| 493 |
+
"""
|
| 494 |
+
return self.tokenizer.batch_decode(
|
| 495 |
+
generated_outputs,
|
| 496 |
+
skip_special_tokens=skip_special_tokens,
|
| 497 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
| 498 |
+
**kwargs,
|
| 499 |
+
)
|
| 500 |
+
|
| 501 |
+
@property
|
| 502 |
+
def model_input_names(self):
|
| 503 |
+
tokenizer_input_names = self.tokenizer.model_input_names
|
| 504 |
+
image_processor_input_names = self.image_processor.model_input_names
|
| 505 |
+
names_from_processor = list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
|
| 506 |
+
return names_from_processor + ["second_per_grid_ts"]
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
__all__ = ["NemotronH_Nano_Omni_Reasoning_V3Processor"]
|
processing_utils.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Optional, Union, Any, Dict
|
| 2 |
+
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import torch
|
| 5 |
+
from transformers.image_processing_base import BatchFeature
|
| 6 |
+
from transformers.image_processing_utils_fast import BaseImageProcessorFast, divide_to_patches
|
| 7 |
+
from transformers.image_utils import (make_list_of_images, get_image_size,
|
| 8 |
+
get_image_type, ImageInput, ImageType, ChannelDimension)
|
| 9 |
+
from transformers.utils import TensorType
|
| 10 |
+
import torchvision.transforms as T
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def get_internvl_target_ratios(
|
| 14 |
+
min_num: int,
|
| 15 |
+
max_num: int,
|
| 16 |
+
) -> list[tuple[int, int]]:
|
| 17 |
+
target_ratios = {(i, j)
|
| 18 |
+
for n in range(min_num, max_num + 1)
|
| 19 |
+
for i in range(1, n + 1)
|
| 20 |
+
for j in range(1, n + 1) if min_num <= i * j <= max_num}
|
| 21 |
+
return sorted(target_ratios, key=lambda x: x[0] * x[1])
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
|
| 25 |
+
best_factor = float('-inf')
|
| 26 |
+
best_ratio = (1, 1)
|
| 27 |
+
area = width * height
|
| 28 |
+
for ratio in target_ratios:
|
| 29 |
+
target_aspect_ratio = ratio[0] / ratio[1]
|
| 30 |
+
factor_based_on_area_n_ratio = min(
|
| 31 |
+
(ratio[0]*ratio[1]*image_size*image_size)/ area, 0.6
|
| 32 |
+
)* min(
|
| 33 |
+
target_aspect_ratio/aspect_ratio, aspect_ratio/target_aspect_ratio)
|
| 34 |
+
if factor_based_on_area_n_ratio > best_factor:
|
| 35 |
+
best_factor = factor_based_on_area_n_ratio
|
| 36 |
+
best_ratio = ratio
|
| 37 |
+
return best_ratio
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def calculate_targets(
|
| 41 |
+
orig_width: int,
|
| 42 |
+
orig_height: int,
|
| 43 |
+
target_ratios: list[tuple[int, int]],
|
| 44 |
+
image_size: int,
|
| 45 |
+
) -> tuple[int, int, int]:
|
| 46 |
+
aspect_ratio = orig_width / orig_height
|
| 47 |
+
|
| 48 |
+
# find the closest aspect ratio to the target
|
| 49 |
+
target_aspect_ratio = find_closest_aspect_ratio(
|
| 50 |
+
aspect_ratio,
|
| 51 |
+
target_ratios,
|
| 52 |
+
width=orig_width,
|
| 53 |
+
height=orig_height,
|
| 54 |
+
image_size=image_size,
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
# calculate the target width and height
|
| 58 |
+
target_width = image_size * target_aspect_ratio[0]
|
| 59 |
+
target_height = image_size * target_aspect_ratio[1]
|
| 60 |
+
blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
|
| 61 |
+
|
| 62 |
+
return blocks, target_width, target_height
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def dynamic_preprocess(image, image_size=512, max_num_tiles=12, use_thumbnail=True):
|
| 66 |
+
orig_height, orig_width = get_image_size(image, channel_dim=ChannelDimension.FIRST)
|
| 67 |
+
target_ratios = get_internvl_target_ratios(1, max_num_tiles)
|
| 68 |
+
|
| 69 |
+
blocks, target_width, target_height = calculate_targets(
|
| 70 |
+
orig_width,
|
| 71 |
+
orig_height,
|
| 72 |
+
target_ratios,
|
| 73 |
+
image_size
|
| 74 |
+
)
|
| 75 |
+
# resize the image
|
| 76 |
+
resized_img = T.Resize((target_width, target_height), interpolation=T.InterpolationMode.BICUBIC)(image)
|
| 77 |
+
patches = divide_to_patches(resized_img, image_size)
|
| 78 |
+
assert len(patches) == blocks
|
| 79 |
+
if use_thumbnail and len(patches) != 1:
|
| 80 |
+
thumbnail_img = T.Resize((image_size, image_size), interpolation=T.InterpolationMode.BICUBIC)(image)
|
| 81 |
+
patches.append(thumbnail_img)
|
| 82 |
+
|
| 83 |
+
return patches
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token": {
|
| 3 |
+
"content": "<s>",
|
| 4 |
+
"lstrip": false,
|
| 5 |
+
"normalized": false,
|
| 6 |
+
"rstrip": false,
|
| 7 |
+
"single_word": false
|
| 8 |
+
},
|
| 9 |
+
"eos_token": {
|
| 10 |
+
"content": "<|im_end|>",
|
| 11 |
+
"lstrip": false,
|
| 12 |
+
"normalized": false,
|
| 13 |
+
"rstrip": false,
|
| 14 |
+
"single_word": false
|
| 15 |
+
},
|
| 16 |
+
"unk_token": {
|
| 17 |
+
"content": "<unk>",
|
| 18 |
+
"lstrip": false,
|
| 19 |
+
"normalized": false,
|
| 20 |
+
"rstrip": false,
|
| 21 |
+
"single_word": false
|
| 22 |
+
}
|
| 23 |
+
}
|
tokenizer.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e5e7dc84d72e8f248321611c3d6dce23407b135f55f8caf5b26119798d12f85f
|
| 3 |
+
size 17077367
|
tokenizer_config.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
video_io.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import base64
|
| 3 |
+
import mimetypes
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import io
|
| 6 |
+
from transformers.video_utils import VideoMetadata
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def encode_pil_to_jpeg_data_url(pil_image):
|
| 10 |
+
from io import BytesIO
|
| 11 |
+
buf = BytesIO()
|
| 12 |
+
pil_image.save(buf, format="JPEG")
|
| 13 |
+
b64 = base64.b64encode(buf.getvalue()).decode("utf-8")
|
| 14 |
+
return f"data:image/jpeg;base64,{b64}"
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def sample_video_frames_to_data_urls(video_path_local, fps=1, nframe=0, nframe_max=-1):
|
| 18 |
+
"""
|
| 19 |
+
Sample frames from a video and return base64-encoded data URLs along with metadata.
|
| 20 |
+
|
| 21 |
+
Args:
|
| 22 |
+
video_path_local: Path to the video file
|
| 23 |
+
fps: Target frames per second for sampling (if > 0, uses fps-based sampling)
|
| 24 |
+
nframe: Number of frames to sample (used if fps <= 0)
|
| 25 |
+
nframe_max: Maximum number of frames to sample
|
| 26 |
+
|
| 27 |
+
Returns:
|
| 28 |
+
tuple: (frame_data_urls, metadata)
|
| 29 |
+
- frame_data_urls: List of base64-encoded frame images
|
| 30 |
+
- metadata: VideoMetadata dataclass containing info about the sampled frames:
|
| 31 |
+
- total_num_frames: Number of sampled frames
|
| 32 |
+
- fps: Effective frame rate of the sampled frames
|
| 33 |
+
- duration: Duration covered by the sampled frames (in seconds)
|
| 34 |
+
- video_backend: Backend used for video processing ('decord')
|
| 35 |
+
"""
|
| 36 |
+
import numpy as np
|
| 37 |
+
from PIL import Image
|
| 38 |
+
import decord
|
| 39 |
+
|
| 40 |
+
vid = decord.VideoReader(video_path_local)
|
| 41 |
+
total_frames = len(vid)
|
| 42 |
+
video_fps = vid.get_avg_fps()
|
| 43 |
+
total_duration = total_frames / max(1e-6, video_fps)
|
| 44 |
+
|
| 45 |
+
if fps > 0:
|
| 46 |
+
required_frames = int(total_duration * fps)
|
| 47 |
+
desired_frames = max(1, required_frames)
|
| 48 |
+
if nframe_max > 0 and desired_frames > nframe_max:
|
| 49 |
+
desired_frames = nframe_max
|
| 50 |
+
if desired_frames >= total_frames:
|
| 51 |
+
indices = list(range(total_frames))
|
| 52 |
+
elif desired_frames == 1:
|
| 53 |
+
indices = [0] # Always use first frame for single frame sampling
|
| 54 |
+
else:
|
| 55 |
+
# Generate evenly spaced indices and ensure uniqueness
|
| 56 |
+
raw_indices = np.linspace(0, total_frames - 1, desired_frames)
|
| 57 |
+
indices = list(np.unique(np.round(raw_indices).astype(int)))
|
| 58 |
+
else:
|
| 59 |
+
desired_frames = max(1, int(nframe) if nframe and nframe > 0 else 8)
|
| 60 |
+
if nframe_max > 0 and desired_frames > nframe_max:
|
| 61 |
+
desired_frames = nframe_max
|
| 62 |
+
if desired_frames >= total_frames:
|
| 63 |
+
indices = list(range(total_frames))
|
| 64 |
+
elif desired_frames == 1:
|
| 65 |
+
indices = [0] # Always use first frame for single frame sampling
|
| 66 |
+
else:
|
| 67 |
+
# Generate evenly spaced indices and ensure uniqueness
|
| 68 |
+
raw_indices = np.linspace(0, total_frames - 1, desired_frames)
|
| 69 |
+
indices = list(np.unique(np.round(raw_indices).astype(int)))
|
| 70 |
+
|
| 71 |
+
images = [Image.fromarray(vid[i].asnumpy()) for i in indices]
|
| 72 |
+
frame_urls = [encode_pil_to_jpeg_data_url(im) for im in images]
|
| 73 |
+
|
| 74 |
+
sampled_num_frames = len(indices)
|
| 75 |
+
|
| 76 |
+
# Pass source fps and source frame indices so the processor can compute
|
| 77 |
+
# timestamps with vLLM's formula: int(source_frame_idx) * int(1000/source_fps) / 1000
|
| 78 |
+
metadata = VideoMetadata(
|
| 79 |
+
total_num_frames=sampled_num_frames,
|
| 80 |
+
fps=video_fps,
|
| 81 |
+
frames_indices=[int(i) for i in indices],
|
| 82 |
+
duration=total_duration,
|
| 83 |
+
video_backend=None,
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
return frame_urls, metadata
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def maybe_path_or_url_to_data_urls(path_or_url, fps=1, nframe=0, nframe_max=-1):
|
| 90 |
+
"""
|
| 91 |
+
Convert a path or URL to data URLs, handling videos, images, and remote files.
|
| 92 |
+
|
| 93 |
+
Args:
|
| 94 |
+
path_or_url: Path or URL to the media file
|
| 95 |
+
fps: Target frames per second for video sampling (if > 0, uses fps-based sampling)
|
| 96 |
+
nframe: Number of frames to sample from video (used if fps <= 0)
|
| 97 |
+
nframe_max: Maximum number of frames to sample
|
| 98 |
+
|
| 99 |
+
Returns:
|
| 100 |
+
tuple: (data_urls, metadata)
|
| 101 |
+
- data_urls: List of base64-encoded data URLs
|
| 102 |
+
- metadata: VideoMetadata dataclass with video metadata or None for images
|
| 103 |
+
"""
|
| 104 |
+
val = str(path_or_url or "")
|
| 105 |
+
low = val.lower()
|
| 106 |
+
|
| 107 |
+
# Handle data URLs
|
| 108 |
+
if low.startswith("data:"):
|
| 109 |
+
if low.startswith("data:video/mp4"):
|
| 110 |
+
header, _, b64part = val.partition(",")
|
| 111 |
+
if not b64part:
|
| 112 |
+
return [val], None
|
| 113 |
+
import tempfile
|
| 114 |
+
tmp = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False)
|
| 115 |
+
try:
|
| 116 |
+
tmp.write(base64.b64decode(b64part))
|
| 117 |
+
tmp.flush(); tmp.close()
|
| 118 |
+
return sample_video_frames_to_data_urls(tmp.name, fps=fps, nframe=nframe, nframe_max=nframe_max)
|
| 119 |
+
finally:
|
| 120 |
+
try:
|
| 121 |
+
os.unlink(tmp.name)
|
| 122 |
+
except Exception:
|
| 123 |
+
pass
|
| 124 |
+
return [val], None
|
| 125 |
+
|
| 126 |
+
# Remote URL
|
| 127 |
+
if low.startswith("http://") or low.startswith("https://"):
|
| 128 |
+
if low.endswith(".mp4"):
|
| 129 |
+
try:
|
| 130 |
+
import tempfile, urllib.request
|
| 131 |
+
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmpf:
|
| 132 |
+
urllib.request.urlretrieve(val, tmpf.name)
|
| 133 |
+
local_path = tmpf.name
|
| 134 |
+
result = sample_video_frames_to_data_urls(local_path, fps=fps, nframe=nframe, nframe_max=nframe_max)
|
| 135 |
+
try:
|
| 136 |
+
os.unlink(local_path)
|
| 137 |
+
except Exception:
|
| 138 |
+
pass
|
| 139 |
+
return result
|
| 140 |
+
except Exception:
|
| 141 |
+
return [val], None
|
| 142 |
+
return [val], None
|
| 143 |
+
|
| 144 |
+
# Local path
|
| 145 |
+
if os.path.exists(val):
|
| 146 |
+
mime, _ = mimetypes.guess_type(val)
|
| 147 |
+
if mime and mime.startswith("image/"):
|
| 148 |
+
with open(val, "rb") as f:
|
| 149 |
+
b64 = base64.b64encode(f.read()).decode("utf-8")
|
| 150 |
+
return [f"data:{mime};base64,{b64}"], None
|
| 151 |
+
if mime == "video/mp4" or (mime is None and val.endswith(".mp4")):
|
| 152 |
+
return sample_video_frames_to_data_urls(val, fps=fps, nframe=nframe, nframe_max=nframe_max)
|
| 153 |
+
# Fallback: treat as binary image
|
| 154 |
+
with open(val, "rb") as f:
|
| 155 |
+
b64 = base64.b64encode(f.read()).decode("utf-8")
|
| 156 |
+
return [f"data:image/jpeg;base64,{b64}"], None
|
| 157 |
+
|
| 158 |
+
return [val], None
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def pil_image_from_base64(b64_str: str) -> Image.Image:
|
| 162 |
+
# Handle data URLs like "data:image/png;base64,...."
|
| 163 |
+
if b64_str.startswith('data:'):
|
| 164 |
+
b64_str = b64_str.split(',', 1)[1]
|
| 165 |
+
img_bytes = base64.b64decode(b64_str)
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
|
| 5 |
+
# and OPT implementations in this library. It has been modified from its
|
| 6 |
+
# original forms to accommodate minor architectural differences compared
|
| 7 |
+
# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
|
| 8 |
+
#
|
| 9 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 10 |
+
# you may not use this file except in compliance with the License.
|
| 11 |
+
# You may obtain a copy of the License at
|
| 12 |
+
#
|
| 13 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 14 |
+
#
|
| 15 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 16 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 17 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 18 |
+
# See the License for the specific language governing permissions and
|
| 19 |
+
# limitations under the License.
|
| 20 |
+
"""video processor class for Qwen2-VL."""
|
| 21 |
+
|
| 22 |
+
import math
|
| 23 |
+
from typing import Optional, Union
|
| 24 |
+
|
| 25 |
+
from transformers.image_processing_utils import (
|
| 26 |
+
BatchFeature,
|
| 27 |
+
)
|
| 28 |
+
from transformers.image_utils import (
|
| 29 |
+
OPENAI_CLIP_MEAN,
|
| 30 |
+
OPENAI_CLIP_STD,
|
| 31 |
+
ChannelDimension,
|
| 32 |
+
SizeDict,
|
| 33 |
+
get_image_size,
|
| 34 |
+
)
|
| 35 |
+
from transformers.processing_utils import Unpack, VideosKwargs
|
| 36 |
+
from transformers.utils import (
|
| 37 |
+
TensorType,
|
| 38 |
+
add_start_docstrings,
|
| 39 |
+
is_torch_available,
|
| 40 |
+
is_torchvision_available,
|
| 41 |
+
is_torchvision_v2_available,
|
| 42 |
+
is_vision_available,
|
| 43 |
+
)
|
| 44 |
+
from transformers.utils.import_utils import requires
|
| 45 |
+
from transformers.video_processing_utils import (
|
| 46 |
+
BASE_VIDEO_PROCESSOR_DOCSTRING,
|
| 47 |
+
BaseVideoProcessor,
|
| 48 |
+
)
|
| 49 |
+
from transformers.video_utils import VideoMetadata, group_videos_by_shape, reorder_videos
|
| 50 |
+
import torchvision.transforms as T
|
| 51 |
+
|
| 52 |
+
from .processing_utils import get_internvl_target_ratios, calculate_targets
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
if is_torchvision_available():
|
| 56 |
+
if is_torchvision_v2_available():
|
| 57 |
+
from torchvision.transforms.v2 import functional as F
|
| 58 |
+
else:
|
| 59 |
+
from torchvision.transforms import functional as F
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
if is_torch_available():
|
| 63 |
+
import torch
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@requires(backends=("torchvision",))
|
| 67 |
+
class NemotronH_Nano_Omni_Reasoning_V3VideoProcessor(BaseVideoProcessor):
|
| 68 |
+
model_input_names = ["pixel_values_videos", "video_grid_thw"]
|
| 69 |
+
|
| 70 |
+
def __init__(self, image_size=512, max_num_tiles=12, norm_mean=None, norm_std=None, **kwargs):
|
| 71 |
+
super().__init__(**kwargs)
|
| 72 |
+
self.image_size = image_size
|
| 73 |
+
self.max_num_tiles = max_num_tiles
|
| 74 |
+
self.norm_mean = norm_mean
|
| 75 |
+
self.norm_std = norm_std
|
| 76 |
+
|
| 77 |
+
def _preprocess(
|
| 78 |
+
self,
|
| 79 |
+
videos: list["torch.Tensor"],
|
| 80 |
+
video_metadata: Union[list[VideoMetadata], list[dict]],
|
| 81 |
+
do_sample_frames: bool,
|
| 82 |
+
fps: Optional[int] = None,
|
| 83 |
+
num_frames: Optional[int] = None,
|
| 84 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
| 85 |
+
device: Optional["torch.Tensor"] = None,
|
| 86 |
+
**kwargs,
|
| 87 |
+
):
|
| 88 |
+
if do_sample_frames:
|
| 89 |
+
# Sample video frames
|
| 90 |
+
videos = [
|
| 91 |
+
self.sample_frames(
|
| 92 |
+
video,
|
| 93 |
+
metadata=metadata,
|
| 94 |
+
num_frames=num_frames,
|
| 95 |
+
fps=fps,
|
| 96 |
+
)
|
| 97 |
+
for video, metadata in zip(videos, video_metadata)
|
| 98 |
+
]
|
| 99 |
+
|
| 100 |
+
# We need to sample frames first before moving to device, if `do_sample_frames=True`. Otherwise
|
| 101 |
+
# moving the whole video incurs high GPU mem usage for long videos
|
| 102 |
+
if device is not None:
|
| 103 |
+
videos = [video.to(device) for video in videos]
|
| 104 |
+
|
| 105 |
+
# Group videos by size for batched resizing
|
| 106 |
+
grouped_videos, grouped_videos_index = group_videos_by_shape(videos)
|
| 107 |
+
resized_videos_grouped = {}
|
| 108 |
+
processed_grids = {}
|
| 109 |
+
for shape, stacked_videos in grouped_videos.items():
|
| 110 |
+
height, width = get_image_size(stacked_videos[0], channel_dim=ChannelDimension.FIRST)
|
| 111 |
+
batch_size, grid_t, channel = stacked_videos.shape[:3]
|
| 112 |
+
|
| 113 |
+
target_ratios = get_internvl_target_ratios(1, self.max_num_tiles)
|
| 114 |
+
blocks, resize_width, resize_height = calculate_targets(
|
| 115 |
+
width,
|
| 116 |
+
height,
|
| 117 |
+
target_ratios,
|
| 118 |
+
self.image_size
|
| 119 |
+
)
|
| 120 |
+
stacked_videos = self.resize(
|
| 121 |
+
image=stacked_videos,
|
| 122 |
+
size=SizeDict(height=resize_height, width=resize_width),
|
| 123 |
+
interpolation=T.InterpolationMode.BICUBIC,
|
| 124 |
+
)
|
| 125 |
+
# stacked_videos = T.Resize((resize_width, resize_height), interpolation=T.InterpolationMode.BICUBIC)(stacked_videos)
|
| 126 |
+
norm_mean = torch.as_tensor(self.norm_mean, dtype=stacked_videos.dtype, device=stacked_videos.device).view(1, 1, 3, 1, 1)
|
| 127 |
+
norm_std = torch.as_tensor(self.norm_std, dtype=stacked_videos.dtype, device=stacked_videos.device).view(1, 1, 3, 1, 1)
|
| 128 |
+
stacked_videos = (stacked_videos - norm_mean) / norm_std
|
| 129 |
+
resized_videos_grouped[shape] = stacked_videos
|
| 130 |
+
grid_h, grid_w = resize_height // self.image_size, resize_width // self.image_size
|
| 131 |
+
processed_grids[shape] = [[grid_t, grid_h, grid_w]] * batch_size
|
| 132 |
+
resized_videos = reorder_videos(resized_videos_grouped, grouped_videos_index)
|
| 133 |
+
processed_grids = reorder_videos(processed_grids, grouped_videos_index)
|
| 134 |
+
pixel_values_videos = torch.cat(resized_videos, dim=0)
|
| 135 |
+
video_grid_thw = torch.tensor(processed_grids)
|
| 136 |
+
|
| 137 |
+
return BatchFeature(
|
| 138 |
+
data={"pixel_values_videos": pixel_values_videos, "video_grid_thw": video_grid_thw},
|
| 139 |
+
tensor_type=return_tensors,
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
def get_num_of_video_patches(self, num_frames: int, height: int, width: int):
|
| 143 |
+
"""
|
| 144 |
+
A utility that returns number of video patches a given video size.
|
| 145 |
+
|
| 146 |
+
Args:
|
| 147 |
+
num_frames (`int`):
|
| 148 |
+
Number of frames in the input video.
|
| 149 |
+
height (`int`):
|
| 150 |
+
Height of the input video.
|
| 151 |
+
width (`int`):
|
| 152 |
+
Width of the input video.
|
| 153 |
+
Returns:
|
| 154 |
+
`Tuple(int, int)`: Number of placeholder tokens required and number of patches per image.
|
| 155 |
+
"""
|
| 156 |
+
target_ratios = get_internvl_target_ratios(1, self.max_num_tiles)
|
| 157 |
+
blocks, _, _ = calculate_targets(
|
| 158 |
+
width,
|
| 159 |
+
height,
|
| 160 |
+
target_ratios,
|
| 161 |
+
self.image_size
|
| 162 |
+
)
|
| 163 |
+
return num_frames * blocks
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
__all__ = ["NemotronH_Nano_Omni_Reasoning_V3VideoProcessor"]
|