Text Generation
Transformers
Safetensors
nemotron_h
code
Mixture of Experts
pruning
space
conversational
custom_code
🇪🇺 Region: EU
Instructions to use locailabs/Juno-N-Coder-25B-A3B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use locailabs/Juno-N-Coder-25B-A3B with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="locailabs/Juno-N-Coder-25B-A3B", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# Load model directly from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("locailabs/Juno-N-Coder-25B-A3B", trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained("locailabs/Juno-N-Coder-25B-A3B", trust_remote_code=True, device_map="auto") messages = [ {"role": "user", "content": "Who are you?"}, ] inputs = tokenizer.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", ).to(model.device) outputs = model.generate(**inputs, max_new_tokens=40) print(tokenizer.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use locailabs/Juno-N-Coder-25B-A3B with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "locailabs/Juno-N-Coder-25B-A3B" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "locailabs/Juno-N-Coder-25B-A3B", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/locailabs/Juno-N-Coder-25B-A3B
- SGLang
How to use locailabs/Juno-N-Coder-25B-A3B with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "locailabs/Juno-N-Coder-25B-A3B" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "locailabs/Juno-N-Coder-25B-A3B", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "locailabs/Juno-N-Coder-25B-A3B" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "locailabs/Juno-N-Coder-25B-A3B", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use locailabs/Juno-N-Coder-25B-A3B with Docker Model Runner:
docker model run hf.co/locailabs/Juno-N-Coder-25B-A3B
Re-upload with empty README
Browse files- .gitattributes +1 -0
- README.md +0 -0
- chat_template.jinja +195 -0
- config.json +75 -0
- configuration_nemotron_h.py +277 -0
- generation_config.json +12 -0
- model-00001-of-00011.safetensors +3 -0
- model-00002-of-00011.safetensors +3 -0
- model-00003-of-00011.safetensors +3 -0
- model-00004-of-00011.safetensors +3 -0
- model-00005-of-00011.safetensors +3 -0
- model-00006-of-00011.safetensors +3 -0
- model-00007-of-00011.safetensors +3 -0
- model-00008-of-00011.safetensors +3 -0
- model-00009-of-00011.safetensors +3 -0
- model-00010-of-00011.safetensors +3 -0
- model-00011-of-00011.safetensors +3 -0
- model.safetensors.index.json +0 -0
- modeling_nemotron_h.py +1810 -0
- special_tokens_map.json +30 -0
- tokenizer.json +3 -0
- tokenizer_config.json +0 -0
- ultra_v3_reasoning_parser.py +28 -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
|
README.md
ADDED
|
File without changes
|
chat_template.jinja
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 medium_effort = medium_effort if medium_effort is defined else False %}
|
| 14 |
+
{%- set truncate_history_thinking = truncate_history_thinking if truncate_history_thinking is defined else True %}
|
| 15 |
+
{%- set ns = namespace(last_user_idx = -1) %}
|
| 16 |
+
{%- set loop_messages = messages %}
|
| 17 |
+
{%- for m in loop_messages %}
|
| 18 |
+
{%- if m["role"] == "user" %}
|
| 19 |
+
{%- set ns.last_user_idx = loop.index0 %}
|
| 20 |
+
{%- endif %}
|
| 21 |
+
{%- endfor %}
|
| 22 |
+
{%- if messages[0]["role"] == "system" %}
|
| 23 |
+
{%- set system_message = messages[0]["content"] %}
|
| 24 |
+
{%- set loop_messages = messages[1:] %}
|
| 25 |
+
{%- else %}
|
| 26 |
+
{%- set system_message = "" %}
|
| 27 |
+
{%- set loop_messages = messages %}
|
| 28 |
+
{%- endif %}
|
| 29 |
+
{%- if not tools is defined %}
|
| 30 |
+
{%- set tools = [] %}
|
| 31 |
+
{%- endif %}
|
| 32 |
+
{%- set ns = namespace(last_user_idx = -1) %}
|
| 33 |
+
{%- for m in loop_messages %}
|
| 34 |
+
{%- if m["role"] == "user" %}
|
| 35 |
+
{%- set ns.last_user_idx = loop.index0 %}
|
| 36 |
+
{%- endif %}
|
| 37 |
+
{%- endfor %}
|
| 38 |
+
{%- if system_message is defined %}
|
| 39 |
+
{{- "<|im_start|>system\n" + system_message }}
|
| 40 |
+
{%- else %}
|
| 41 |
+
{%- if tools is iterable and tools | length > 0 %}
|
| 42 |
+
{{- "<|im_start|>system\n" }}
|
| 43 |
+
{%- endif %}
|
| 44 |
+
{%- endif %}
|
| 45 |
+
{%- if tools is iterable and tools | length > 0 %}
|
| 46 |
+
{%- if system_message is defined and system_message | length > 0 %}
|
| 47 |
+
{{- "\n\n" }}
|
| 48 |
+
{%- endif %}
|
| 49 |
+
{{- "# Tools\n\nYou have access to the following functions:\n\n" }}
|
| 50 |
+
{{- "<tools>" }}
|
| 51 |
+
{%- for tool in tools %}
|
| 52 |
+
{%- if tool.function is defined %}
|
| 53 |
+
{%- set tool = tool.function %}
|
| 54 |
+
{%- endif %}
|
| 55 |
+
{{- "\n<function>\n<name>" ~ tool.name ~ "</name>" }}
|
| 56 |
+
{%- if tool.description is defined %}
|
| 57 |
+
{{- '\n<description>' ~ (tool.description | trim) ~ '</description>' }}
|
| 58 |
+
{%- endif %}
|
| 59 |
+
{{- '\n<parameters>' }}
|
| 60 |
+
{%- if tool.parameters is defined and tool.parameters is mapping and tool.parameters.properties is defined and tool.parameters.properties is mapping %}
|
| 61 |
+
{%- for param_name, param_fields in tool.parameters.properties|items %}
|
| 62 |
+
{{- '\n<parameter>' }}
|
| 63 |
+
{{- '\n<name>' ~ param_name ~ '</name>' }}
|
| 64 |
+
{%- if param_fields.type is defined %}
|
| 65 |
+
{{- '\n<type>' ~ (param_fields.type | string) ~ '</type>' }}
|
| 66 |
+
{%- endif %}
|
| 67 |
+
{%- if param_fields.description is defined %}
|
| 68 |
+
{{- '\n<description>' ~ (param_fields.description | trim) ~ '</description>' }}
|
| 69 |
+
{%- endif %}
|
| 70 |
+
{%- if param_fields.enum is defined %}
|
| 71 |
+
{{- '\n<enum>' ~ (param_fields.enum | tojson | safe) ~ '</enum>' }}
|
| 72 |
+
{%- endif %}
|
| 73 |
+
{%- set handled_keys = ['name', 'type', 'description', 'enum'] %}
|
| 74 |
+
{{- render_extra_keys(param_fields, handled_keys) }}
|
| 75 |
+
{{- '\n</parameter>' }}
|
| 76 |
+
{%- endfor %}
|
| 77 |
+
{%- endif %}
|
| 78 |
+
{% set handled_keys = ['type', 'properties', 'required'] %}
|
| 79 |
+
{{- render_extra_keys(tool.parameters, handled_keys) }}
|
| 80 |
+
{%- if tool.parameters is defined and tool.parameters.required is defined %}
|
| 81 |
+
{{- '\n<required>' ~ (tool.parameters.required | tojson | safe) ~ '</required>' }}
|
| 82 |
+
{%- endif %}
|
| 83 |
+
{{- '\n</parameters>' }}
|
| 84 |
+
{%- set handled_keys = ['type', 'name', 'description', 'parameters'] %}
|
| 85 |
+
{{- render_extra_keys(tool, handled_keys) }}
|
| 86 |
+
{{- '\n</function>' }}
|
| 87 |
+
{%- endfor %}
|
| 88 |
+
{{- "\n</tools>" }}
|
| 89 |
+
{{- '\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>' }}
|
| 90 |
+
{%- endif %}
|
| 91 |
+
{%- if system_message is defined %}
|
| 92 |
+
{{- '<|im_end|>\n' }}
|
| 93 |
+
{%- else %}
|
| 94 |
+
{%- if tools is iterable and tools | length > 0 %}
|
| 95 |
+
{{- '<|im_end|>\n' }}
|
| 96 |
+
{%- endif %}
|
| 97 |
+
{%- endif %}
|
| 98 |
+
{%- for message in loop_messages %}
|
| 99 |
+
{%- if message.role == "assistant" %}
|
| 100 |
+
{%- if message.reasoning_content is defined and message.reasoning_content is string and message.reasoning_content | trim | length > 0 %}
|
| 101 |
+
{%- set content = "<think>\n" ~ message.reasoning_content ~ "</think>" ~ (message.content | default('', true)) %}
|
| 102 |
+
{%- else %}
|
| 103 |
+
{%- set content = message.content | default('', true) %}
|
| 104 |
+
{%- if content is string -%}
|
| 105 |
+
{%- if '<think>' not in content and '</think>' not in content -%}
|
| 106 |
+
{%- set content = "<think></think>" ~ content -%}
|
| 107 |
+
{%- endif -%}
|
| 108 |
+
{%- else -%}
|
| 109 |
+
{%- set content = content -%}
|
| 110 |
+
{%- endif -%}
|
| 111 |
+
{%- endif %}
|
| 112 |
+
{%- if message.tool_calls is defined and message.tool_calls is iterable and message.tool_calls | length > 0 %}
|
| 113 |
+
{{- '<|im_start|>assistant\n' }}
|
| 114 |
+
{%- set include_content = not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %}
|
| 115 |
+
{%- if content is string and content | trim | length > 0 %}
|
| 116 |
+
{%- if include_content %}
|
| 117 |
+
{{- (content | trim) ~ '\n' -}}
|
| 118 |
+
{%- else %}
|
| 119 |
+
{%- set c = (content | string) %}
|
| 120 |
+
{%- if '</think>' in c %}
|
| 121 |
+
{%- set c = c.split('</think>')[-1] %}
|
| 122 |
+
{%- elif '<think>' in c %}
|
| 123 |
+
{%- set c = c.split('<think>')[0] %}
|
| 124 |
+
{%- endif %}
|
| 125 |
+
{%- set c = "<think></think>" ~ c %}
|
| 126 |
+
{%- if c | length > 0 %}
|
| 127 |
+
{{- c ~ '\n' -}}
|
| 128 |
+
{%- endif %}
|
| 129 |
+
{%- endif %}
|
| 130 |
+
{%- else %}
|
| 131 |
+
{{- "<think></think>" -}}
|
| 132 |
+
{%- endif %}
|
| 133 |
+
{%- for tool_call in message.tool_calls %}
|
| 134 |
+
{%- if tool_call.function is defined %}
|
| 135 |
+
{%- set tool_call = tool_call.function %}
|
| 136 |
+
{%- endif %}
|
| 137 |
+
{{- '<tool_call>\n<function=' ~ tool_call.name ~ '>\n' -}}
|
| 138 |
+
{%- if tool_call.arguments is defined %}
|
| 139 |
+
{%- for args_name, args_value in tool_call.arguments|items %}
|
| 140 |
+
{{- '<parameter=' ~ args_name ~ '>\n' -}}
|
| 141 |
+
{%- 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 %}
|
| 142 |
+
{{- args_value ~ '\n</parameter>\n' -}}
|
| 143 |
+
{%- endfor %}
|
| 144 |
+
{%- endif %}
|
| 145 |
+
{{- '</function>\n</tool_call>\n' -}}
|
| 146 |
+
{%- endfor %}
|
| 147 |
+
{{- '<|im_end|>\n' }}
|
| 148 |
+
{%- else %}
|
| 149 |
+
{%- if not (truncate_history_thinking and loop.index0 < ns.last_user_idx) %}
|
| 150 |
+
{{- '<|im_start|>assistant\n' ~ (content | default('', true) | string | trim) ~ '<|im_end|>\n' }}
|
| 151 |
+
{%- else %}
|
| 152 |
+
{%- set c = (content | default('', true) | string) %}
|
| 153 |
+
{%- if '<think>' in c and '</think>' in c %}
|
| 154 |
+
{%- set c = "<think></think>" ~ c.split('</think>')[-1] %}
|
| 155 |
+
{%- endif %}
|
| 156 |
+
{%- set c = c | trim %}
|
| 157 |
+
{%- if c | length > 0 %}
|
| 158 |
+
{{- '<|im_start|>assistant\n' ~ c ~ '<|im_end|>\n' }}
|
| 159 |
+
{%- else %}
|
| 160 |
+
{{- '<|im_start|>assistant\n<|im_end|>\n' }}
|
| 161 |
+
{%- endif %}
|
| 162 |
+
{%- endif %}
|
| 163 |
+
{%- endif %}
|
| 164 |
+
{%- elif message.role == "user" or message.role == "system" %}
|
| 165 |
+
{{- '<|im_start|>' + message.role + '\n' }}
|
| 166 |
+
{%- set content = message.content | string %}
|
| 167 |
+
{%- if message.role == "user" and loop.index0 == ns.last_user_idx and medium_effort %}
|
| 168 |
+
{{- content + '\n\n{reasoning effort: efficient}' }}
|
| 169 |
+
{%- else %}
|
| 170 |
+
{{- content }}
|
| 171 |
+
{%- endif %}
|
| 172 |
+
{{- '<|im_end|>\n' }}
|
| 173 |
+
{%- elif message.role == "tool" %}
|
| 174 |
+
{%- if loop.previtem and loop.previtem.role != "tool" %}
|
| 175 |
+
{{- '<|im_start|>user\n' }}
|
| 176 |
+
{%- endif %}
|
| 177 |
+
{{- '<tool_response>\n' }}
|
| 178 |
+
{{- message.content }}
|
| 179 |
+
{{- '\n</tool_response>\n' }}
|
| 180 |
+
{%- if not loop.last and loop.nextitem.role != "tool" %}
|
| 181 |
+
{{- '<|im_end|>\n' }}
|
| 182 |
+
{%- elif loop.last %}
|
| 183 |
+
{{- '<|im_end|>\n' }}
|
| 184 |
+
{%- endif %}
|
| 185 |
+
{%- else %}
|
| 186 |
+
{{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>\n' }}
|
| 187 |
+
{%- endif %}
|
| 188 |
+
{%- endfor %}
|
| 189 |
+
{%- if add_generation_prompt %}
|
| 190 |
+
{%- if enable_thinking %}
|
| 191 |
+
{{- '<|im_start|>assistant\n<think>\n' }}
|
| 192 |
+
{%- else %}
|
| 193 |
+
{{- '<|im_start|>assistant\n<think></think>' }}
|
| 194 |
+
{%- endif %}
|
| 195 |
+
{%- endif %}
|
config.json
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"NemotronHForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"attention_bias": false,
|
| 6 |
+
"attention_dropout": 0.0,
|
| 7 |
+
"auto_map": {
|
| 8 |
+
"AutoConfig": "configuration_nemotron_h.NemotronHConfig",
|
| 9 |
+
"AutoModel": "modeling_nemotron_h.NemotronHForCausalLM",
|
| 10 |
+
"AutoModelForCausalLM": "modeling_nemotron_h.NemotronHForCausalLM"
|
| 11 |
+
},
|
| 12 |
+
"bos_token_id": 1,
|
| 13 |
+
"chunk_size": 128,
|
| 14 |
+
"conv_kernel": 4,
|
| 15 |
+
"dtype": "bfloat16",
|
| 16 |
+
"eos_token_id": 2,
|
| 17 |
+
"expand": 2,
|
| 18 |
+
"head_dim": 128,
|
| 19 |
+
"hidden_dropout": 0.0,
|
| 20 |
+
"hidden_size": 2688,
|
| 21 |
+
"hybrid_override_pattern": "MEMEM*EMEMEM*EMEMEM*EMEMEM*EMEMEM*EMEMEMEM*EMEMEMEME",
|
| 22 |
+
"initializer_range": 0.02,
|
| 23 |
+
"intermediate_size": 1856,
|
| 24 |
+
"layer_norm_epsilon": 1e-05,
|
| 25 |
+
"mamba_head_dim": 64,
|
| 26 |
+
"mamba_hidden_act": "silu",
|
| 27 |
+
"mamba_num_heads": 64,
|
| 28 |
+
"mamba_proj_bias": false,
|
| 29 |
+
"mamba_ssm_cache_dtype": "float32",
|
| 30 |
+
"max_position_embeddings": 262144,
|
| 31 |
+
"mlp_bias": false,
|
| 32 |
+
"mlp_hidden_act": "relu2",
|
| 33 |
+
"model_type": "nemotron_h",
|
| 34 |
+
"moe_intermediate_size": 1856,
|
| 35 |
+
"moe_latent_size": null,
|
| 36 |
+
"moe_shared_expert_intermediate_size": 3712,
|
| 37 |
+
"moe_shared_expert_overlap": true,
|
| 38 |
+
"mtp_hybrid_override_pattern": "*E",
|
| 39 |
+
"n_group": 1,
|
| 40 |
+
"n_groups": 8,
|
| 41 |
+
"n_routed_experts": 96,
|
| 42 |
+
"n_shared_experts": 1,
|
| 43 |
+
"norm_eps": 1e-05,
|
| 44 |
+
"norm_topk_prob": true,
|
| 45 |
+
"num_attention_heads": 32,
|
| 46 |
+
"num_experts_per_tok": 6,
|
| 47 |
+
"num_hidden_layers": 52,
|
| 48 |
+
"num_key_value_heads": 2,
|
| 49 |
+
"num_logits_to_keep": 1,
|
| 50 |
+
"num_nextn_predict_layers": 1,
|
| 51 |
+
"pad_token_id": 0,
|
| 52 |
+
"partial_rotary_factor": 1.0,
|
| 53 |
+
"rescale_prenorm_residual": true,
|
| 54 |
+
"residual_in_fp32": false,
|
| 55 |
+
"rope_theta": 10000,
|
| 56 |
+
"routed_scaling_factor": 2.5,
|
| 57 |
+
"sliding_window": null,
|
| 58 |
+
"ssm_state_size": 128,
|
| 59 |
+
"tie_word_embeddings": false,
|
| 60 |
+
"time_step_floor": 0.0001,
|
| 61 |
+
"time_step_limit": [
|
| 62 |
+
0.0,
|
| 63 |
+
Infinity
|
| 64 |
+
],
|
| 65 |
+
"time_step_max": 0.1,
|
| 66 |
+
"time_step_min": 0.001,
|
| 67 |
+
"topk_group": 1,
|
| 68 |
+
"torch_dtype": "bfloat16",
|
| 69 |
+
"transformers_version": "4.55.0",
|
| 70 |
+
"use_bias": false,
|
| 71 |
+
"use_cache": true,
|
| 72 |
+
"use_conv_bias": true,
|
| 73 |
+
"use_mamba_kernels": true,
|
| 74 |
+
"vocab_size": 131072
|
| 75 |
+
}
|
configuration_nemotron_h.py
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
moe_latent_size=None,
|
| 182 |
+
moe_shared_expert_overlap=True,
|
| 183 |
+
num_experts_per_tok=2,
|
| 184 |
+
routed_scaling_factor=1.0,
|
| 185 |
+
n_group=1,
|
| 186 |
+
topk_group=1,
|
| 187 |
+
norm_topk_prob=True,
|
| 188 |
+
mamba_ssm_cache_dtype="float32",
|
| 189 |
+
num_nextn_predict_layers=0,
|
| 190 |
+
mtp_hybrid_override_pattern="*E",
|
| 191 |
+
**kwargs,
|
| 192 |
+
):
|
| 193 |
+
self.vocab_size = vocab_size
|
| 194 |
+
self.tie_word_embeddings = tie_word_embeddings
|
| 195 |
+
self.hidden_size = hidden_size
|
| 196 |
+
self.intermediate_size = intermediate_size
|
| 197 |
+
self.num_hidden_layers = num_hidden_layers
|
| 198 |
+
self.hybrid_override_pattern = hybrid_override_pattern
|
| 199 |
+
self.num_attention_heads = num_attention_heads
|
| 200 |
+
self.head_dim = head_dim
|
| 201 |
+
self.sliding_window = sliding_window
|
| 202 |
+
self.max_position_embeddings = max_position_embeddings
|
| 203 |
+
self.attention_dropout = attention_dropout
|
| 204 |
+
self.hidden_dropout = hidden_dropout
|
| 205 |
+
|
| 206 |
+
# Validate hybrid_override_pattern
|
| 207 |
+
# M: Mamba2, *: Attention, -: MLP
|
| 208 |
+
assert len(self.hybrid_override_pattern) == self.num_hidden_layers, "hybrid_override_pattern must have the same length as num_hidden_layers"
|
| 209 |
+
assert re.match(r"^[ME*-]+$", self.hybrid_override_pattern), "hybrid_override_pattern must only contain characters 'M', '*', 'E',or '-'"
|
| 210 |
+
|
| 211 |
+
# for backward compatibility
|
| 212 |
+
if num_key_value_heads is None:
|
| 213 |
+
num_key_value_heads = num_attention_heads
|
| 214 |
+
|
| 215 |
+
self.num_key_value_heads = num_key_value_heads
|
| 216 |
+
self.mlp_hidden_act = mlp_hidden_act
|
| 217 |
+
self.attention_bias = attention_bias
|
| 218 |
+
self.mlp_bias = mlp_bias
|
| 219 |
+
self.use_bias = use_bias
|
| 220 |
+
self.initializer_range = initializer_range
|
| 221 |
+
self.layer_norm_epsilon = layer_norm_epsilon
|
| 222 |
+
self.residual_in_fp32 = residual_in_fp32
|
| 223 |
+
|
| 224 |
+
self.use_cache = use_cache
|
| 225 |
+
self.num_logits_to_keep = num_logits_to_keep
|
| 226 |
+
|
| 227 |
+
self.use_mamba_kernels = use_mamba_kernels
|
| 228 |
+
self.n_groups = mamba_n_groups
|
| 229 |
+
self.mamba_head_dim = mamba_head_dim
|
| 230 |
+
self.ssm_state_size = ssm_state_size
|
| 231 |
+
self.mamba_num_heads = mamba_num_heads
|
| 232 |
+
self.conv_kernel = mamba_d_conv
|
| 233 |
+
self.expand = mamba_expand
|
| 234 |
+
self.mamba_hidden_act = mamba_hidden_act
|
| 235 |
+
self.time_step_min = mamba_dt_min
|
| 236 |
+
self.time_step_max = mamba_dt_max
|
| 237 |
+
self.time_step_limit = mamba_dt_limit
|
| 238 |
+
self.time_step_floor = mamba_dt_init_floor
|
| 239 |
+
self.use_conv_bias = mamba_conv_bias
|
| 240 |
+
self.mamba_proj_bias = mamba_proj_bias
|
| 241 |
+
self.chunk_size = mamba_chunk_size
|
| 242 |
+
self.rescale_prenorm_residual = rescale_prenorm_residual
|
| 243 |
+
self.n_routed_experts = n_routed_experts
|
| 244 |
+
self.n_shared_experts = n_shared_experts
|
| 245 |
+
self.moe_intermediate_size = moe_intermediate_size
|
| 246 |
+
self.moe_shared_expert_intermediate_size = moe_shared_expert_intermediate_size
|
| 247 |
+
self.moe_latent_size = moe_latent_size
|
| 248 |
+
self.moe_shared_expert_overlap = moe_shared_expert_overlap
|
| 249 |
+
self.num_experts_per_tok = num_experts_per_tok
|
| 250 |
+
self.routed_scaling_factor = routed_scaling_factor
|
| 251 |
+
self.n_group = n_group
|
| 252 |
+
self.topk_group = topk_group
|
| 253 |
+
self.norm_topk_prob = norm_topk_prob
|
| 254 |
+
self.mamba_ssm_cache_dtype = mamba_ssm_cache_dtype
|
| 255 |
+
|
| 256 |
+
# MTP config
|
| 257 |
+
# TODO(liding):--keep-mtp-spec-in-bf16
|
| 258 |
+
self.num_nextn_predict_layers = num_nextn_predict_layers
|
| 259 |
+
self.mtp_hybrid_override_pattern = mtp_hybrid_override_pattern
|
| 260 |
+
if self.num_nextn_predict_layers > 0:
|
| 261 |
+
assert re.match(r"^[ME*-]+$", self.mtp_hybrid_override_pattern), "mtp_hybrid_override_pattern must only contain characters 'M', '*', 'E',or '-'"
|
| 262 |
+
|
| 263 |
+
super().__init__(
|
| 264 |
+
pad_token_id=pad_token_id,
|
| 265 |
+
bos_token_id=bos_token_id,
|
| 266 |
+
eos_token_id=eos_token_id,
|
| 267 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 268 |
+
**kwargs,
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
@property
|
| 272 |
+
def layers_block_type(self):
|
| 273 |
+
return [
|
| 274 |
+
"mamba" if self.hybrid_override_pattern[i] == "M" else
|
| 275 |
+
"attention" if self.hybrid_override_pattern[i] == "*" else
|
| 276 |
+
"mlp" if self.hybrid_override_pattern[i] == "-" else "moe"
|
| 277 |
+
for i in range(self.num_hidden_layers)]
|
generation_config.json
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"bos_token_id": 1,
|
| 4 |
+
"do_sample": true,
|
| 5 |
+
"eos_token_id": [
|
| 6 |
+
2,
|
| 7 |
+
11
|
| 8 |
+
],
|
| 9 |
+
"pad_token_id": 0,
|
| 10 |
+
"top_p": 0.95,
|
| 11 |
+
"transformers_version": "4.55.0"
|
| 12 |
+
}
|
model-00001-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1db773e848c953a23d760d81a66638badb5d53310b97555352faf53a98ad8e04
|
| 3 |
+
size 4996113352
|
model-00002-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9bd22083e25c9bab925104c5fcdc22ef9d96b10618171df219126267b83cf63e
|
| 3 |
+
size 4995347984
|
model-00003-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0f13dd09765cd7d85dfc21278924b49a0fbba397af852411d1cd52e461273b7a
|
| 3 |
+
size 4992257112
|
model-00004-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c101f804e5c436454781754206b391c904f54ce05929e4c0839c3aa2dd64dc98
|
| 3 |
+
size 4990445912
|
model-00005-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:452975a72ff93eb63c3ab780dd86ae82a9475a8f7842a2da767b6c9fadc6701d
|
| 3 |
+
size 4992257112
|
model-00006-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0b8fd51a60d0550c603f4f4e6ab54d9f8953a85206f2f392b01dac18b862d738
|
| 3 |
+
size 4990445912
|
model-00007-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1484492f3872fa6bef65ebc3b6a3ad017ac59cd8a46a1e05464ed4046995dd15
|
| 3 |
+
size 4995348392
|
model-00008-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3031abcb08c898e908bdf46ba3755188ed9b034fa39a812c664ad51f0caa360a
|
| 3 |
+
size 4990445912
|
model-00009-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6813a62eb7128bf66b824c8fcd5050e7d49a94034cbc10ad26f679186fd38b11
|
| 3 |
+
size 4995348392
|
model-00010-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:31e3e2fe9e74ae29aedad43b64296b02519b29f14fd7f2c5e78c32a45ecf34ed
|
| 3 |
+
size 4800197848
|
model-00011-of-00011.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b101621b59cde63c2bdad91bbfcf93be7e5fba567c74662e8f9fe060abce0c6c
|
| 3 |
+
size 758848264
|
model.safetensors.index.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
modeling_nemotron_h.py
ADDED
|
@@ -0,0 +1,1810 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 HuggingFace Inc. team.
|
| 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 |
+
"""PyTorch NemotronH model."""
|
| 17 |
+
|
| 18 |
+
import copy
|
| 19 |
+
import math
|
| 20 |
+
from dataclasses import dataclass
|
| 21 |
+
from typing import Any, Dict, Optional, Tuple, Union
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
import torch.utils.checkpoint
|
| 25 |
+
from torch import nn
|
| 26 |
+
from torch.nn import CrossEntropyLoss
|
| 27 |
+
import torch.nn.functional as F
|
| 28 |
+
|
| 29 |
+
from transformers.activations import ACT2FN
|
| 30 |
+
from transformers.cache_utils import DynamicCache # we need __iter__ and __len__ of pkv
|
| 31 |
+
from transformers.generation import GenerationMixin
|
| 32 |
+
from transformers.modeling_attn_mask_utils import (
|
| 33 |
+
AttentionMaskConverter,
|
| 34 |
+
)
|
| 35 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 36 |
+
from transformers.utils import (
|
| 37 |
+
ModelOutput,
|
| 38 |
+
add_code_sample_docstrings,
|
| 39 |
+
add_start_docstrings,
|
| 40 |
+
add_start_docstrings_to_model_forward,
|
| 41 |
+
logging,
|
| 42 |
+
)
|
| 43 |
+
from transformers.utils.import_utils import (
|
| 44 |
+
is_causal_conv1d_available,
|
| 45 |
+
is_flash_attn_2_available,
|
| 46 |
+
is_flash_attn_greater_or_equal_2_10,
|
| 47 |
+
is_mamba_2_ssm_available,
|
| 48 |
+
)
|
| 49 |
+
from .configuration_nemotron_h import NemotronHConfig
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
logger = logging.get_logger(__name__)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# Copied from transformers.models.mamba.modeling_mamba2.modeling_mamba2.py with MAMBA2->NEMOTRONH,Mamba2->NemotronH
|
| 56 |
+
# For Mamba2 components Mamba2->NemotronHMamba2
|
| 57 |
+
if is_mamba_2_ssm_available():
|
| 58 |
+
from mamba_ssm.ops.triton.selective_state_update import selective_state_update
|
| 59 |
+
from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined
|
| 60 |
+
else:
|
| 61 |
+
mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined, selective_state_update = None, None, None
|
| 62 |
+
|
| 63 |
+
try:
|
| 64 |
+
#from mamba_ssm.ops.triton.layernorm_gated import RMSNorm as RMSNormGated
|
| 65 |
+
from mamba_ssm.ops.triton.layernorm_gated import rmsnorm_fn
|
| 66 |
+
except ImportError:
|
| 67 |
+
raise ImportError("mamba-ssm is required by the Mamba model but cannot be imported")
|
| 68 |
+
|
| 69 |
+
if is_causal_conv1d_available():
|
| 70 |
+
from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
|
| 71 |
+
else:
|
| 72 |
+
causal_conv1d_update, causal_conv1d_fn = None, None
|
| 73 |
+
|
| 74 |
+
if is_flash_attn_2_available():
|
| 75 |
+
from transformers.modeling_flash_attention_utils import _flash_attention_forward
|
| 76 |
+
|
| 77 |
+
is_fast_path_available = all(
|
| 78 |
+
(
|
| 79 |
+
selective_state_update,
|
| 80 |
+
mamba_chunk_scan_combined,
|
| 81 |
+
mamba_split_conv1d_scan_combined,
|
| 82 |
+
causal_conv1d_fn,
|
| 83 |
+
causal_conv1d_update,
|
| 84 |
+
)
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
_CHECKPOINT_FOR_DOC = "nvidia/Nemotron-H-56B-Base-8K"
|
| 89 |
+
_CONFIG_FOR_DOC = "NemotronHConfig"
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
# Helper methods for segment sum computation
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def pad_tensor_by_size(input_tensor: torch.Tensor, pad_size: int):
|
| 96 |
+
"""
|
| 97 |
+
Padding x tensor with `pad_size` on the seq_len dim (dim=1)
|
| 98 |
+
|
| 99 |
+
Assumes that we only have tensors of either size 4 or 3
|
| 100 |
+
"""
|
| 101 |
+
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)
|
| 102 |
+
|
| 103 |
+
return torch.nn.functional.pad(input_tensor, pad_shape, mode="constant", value=0)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def reshape_into_chunks(input_tensor, pad_size, chunk_size):
|
| 107 |
+
"""
|
| 108 |
+
Padding input_tensor with `pad_size` on the seq_len dim (dim=1) and
|
| 109 |
+
simultaneously splitting it into chunk sequences.
|
| 110 |
+
|
| 111 |
+
Assumes that we only have tensors of either size 4 or 3
|
| 112 |
+
"""
|
| 113 |
+
# [bsz, seq_len, ...] -> [bsz, seq_len multiple of chunk_size, ...]
|
| 114 |
+
input_tensor = pad_tensor_by_size(input_tensor, pad_size)
|
| 115 |
+
|
| 116 |
+
if len(input_tensor.shape) == 3:
|
| 117 |
+
# [bsz, seq_len multiple of chunk_size, num_heads] -> [bsz, -1, chunk_size, num_heads]
|
| 118 |
+
return input_tensor.reshape(input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2])
|
| 119 |
+
else:
|
| 120 |
+
# [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]
|
| 121 |
+
return input_tensor.reshape(
|
| 122 |
+
input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2], input_tensor.shape[3]
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def segment_sum(input_tensor):
|
| 127 |
+
"""
|
| 128 |
+
More stable segment sum calculation. Uses cumulative sums and masking instead of direct subtractions.
|
| 129 |
+
"""
|
| 130 |
+
chunk_size = input_tensor.size(-1)
|
| 131 |
+
# 1. expand input tensor to have an additional dimension and repeat along that dimension
|
| 132 |
+
# [..., chunk_size] -> [..., chunk_size, chunk_size]
|
| 133 |
+
input_tensor = input_tensor[..., None].expand(*input_tensor.size(), chunk_size)
|
| 134 |
+
# 2. create a lower triangular mask with the diagonal set to 0 to 0 out elements above diag
|
| 135 |
+
mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=-1)
|
| 136 |
+
input_tensor = input_tensor.masked_fill(~mask, 0)
|
| 137 |
+
# 3. compute actual cumsum
|
| 138 |
+
tensor_segsum = torch.cumsum(input_tensor, dim=-2)
|
| 139 |
+
|
| 140 |
+
# 4. apply mask to keep only the lower triangular part of the cumulative sum result (incl diagonal this time)
|
| 141 |
+
mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=0)
|
| 142 |
+
tensor_segsum = tensor_segsum.masked_fill(~mask, -torch.inf)
|
| 143 |
+
return tensor_segsum
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def apply_mask_to_padding_states(hidden_states, attention_mask):
|
| 147 |
+
"""
|
| 148 |
+
Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66
|
| 149 |
+
"""
|
| 150 |
+
if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
|
| 151 |
+
dtype = hidden_states.dtype
|
| 152 |
+
hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
|
| 153 |
+
|
| 154 |
+
return hidden_states
|
| 155 |
+
|
| 156 |
+
# Copied from https://github.com/huggingface/transformers/blob/main/src/transformers/models/jamba/modeling_jamba.py
|
| 157 |
+
class HybridMambaAttentionDynamicCache(DynamicCache):
|
| 158 |
+
"""
|
| 159 |
+
A dynamic cache that can handle both the attention cache (which has a seq_len dimension) and the mamba cache
|
| 160 |
+
(which has a constant shape regardless of seq_len).
|
| 161 |
+
|
| 162 |
+
This cache has two sets of lists of tensors: `key_cache` and `value_cache` for attention cache and `conv_states`
|
| 163 |
+
and `ssm_states` for mamba cache. Each of these lists has `num_layers` tensors. The expected shape for each tensor
|
| 164 |
+
For attention layers, `key_cache` and `value_cache` have a shape of `(batch_size, num_heads, seq_len, head_dim)`,
|
| 165 |
+
while `conv_states` and `ssm_states` have a shape of `(batch_size, 0)` (empty tensors).
|
| 166 |
+
For mamba layers, `key_cache` and `value_cache` have a shape of `(batch_size, 0)` (empty tensors),
|
| 167 |
+
while `conv_states` represents the convolution state and has a shape of `(batch_size, d_inner, d_conv)`,
|
| 168 |
+
and `ssm_states` represents the ssm state and has a shape of `(batch_size, d_inner, d_state)`.
|
| 169 |
+
"""
|
| 170 |
+
|
| 171 |
+
def __init__(self, config, batch_size, dtype=torch.float16, device=None):
|
| 172 |
+
super().__init__()
|
| 173 |
+
self.dtype = dtype
|
| 174 |
+
self.hybrid_override_pattern = config.hybrid_override_pattern
|
| 175 |
+
self.has_previous_state = False # only used by mamba
|
| 176 |
+
intermediate_size = config.mamba_num_heads * config.mamba_head_dim
|
| 177 |
+
ssm_state_size = config.ssm_state_size
|
| 178 |
+
conv_kernel_size = config.conv_kernel
|
| 179 |
+
self.conv_states = []
|
| 180 |
+
self.ssm_states = []
|
| 181 |
+
self.transformer_layers = []
|
| 182 |
+
for i in range(config.num_hidden_layers):
|
| 183 |
+
if self.hybrid_override_pattern[i] == "M":
|
| 184 |
+
# Mamba layer
|
| 185 |
+
self.conv_states += [
|
| 186 |
+
torch.zeros(batch_size, intermediate_size, conv_kernel_size, device=device, dtype=dtype)
|
| 187 |
+
]
|
| 188 |
+
self.ssm_states += [
|
| 189 |
+
torch.zeros(batch_size, intermediate_size, ssm_state_size, device=device, dtype=dtype)
|
| 190 |
+
]
|
| 191 |
+
else:
|
| 192 |
+
# Attention or MLP layer
|
| 193 |
+
self.conv_states += [torch.tensor([[]] * batch_size, device=device)]
|
| 194 |
+
self.ssm_states += [torch.tensor([[]] * batch_size, device=device)]
|
| 195 |
+
self.transformer_layers.append(i)
|
| 196 |
+
|
| 197 |
+
self.key_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
|
| 198 |
+
self.value_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
|
| 199 |
+
|
| 200 |
+
def update(
|
| 201 |
+
self,
|
| 202 |
+
key_states: torch.Tensor,
|
| 203 |
+
value_states: torch.Tensor,
|
| 204 |
+
layer_idx: int,
|
| 205 |
+
cache_kwargs: Optional[Dict[str, Any]] = None,
|
| 206 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 207 |
+
# Update the cache
|
| 208 |
+
if self.key_cache[layer_idx].shape[-1] == 0:
|
| 209 |
+
self.key_cache[layer_idx] = key_states
|
| 210 |
+
self.value_cache[layer_idx] = value_states
|
| 211 |
+
else:
|
| 212 |
+
self.key_cache[layer_idx] = torch.cat([self.key_cache[layer_idx], key_states], dim=2)
|
| 213 |
+
self.value_cache[layer_idx] = torch.cat([self.value_cache[layer_idx], value_states], dim=2)
|
| 214 |
+
|
| 215 |
+
return self.key_cache[layer_idx], self.value_cache[layer_idx]
|
| 216 |
+
|
| 217 |
+
def reorder_cache(self, beam_idx: torch.LongTensor):
|
| 218 |
+
"""Reorders the cache for beam search, given the selected beam indices."""
|
| 219 |
+
for layer_idx in range(len(self.key_cache)):
|
| 220 |
+
device = self.key_cache[layer_idx].device
|
| 221 |
+
self.key_cache[layer_idx] = self.key_cache[layer_idx].index_select(0, beam_idx.to(device))
|
| 222 |
+
device = self.value_cache[layer_idx].device
|
| 223 |
+
self.value_cache[layer_idx] = self.value_cache[layer_idx].index_select(0, beam_idx.to(device))
|
| 224 |
+
|
| 225 |
+
device = self.conv_states[layer_idx].device
|
| 226 |
+
self.conv_states[layer_idx] = self.conv_states[layer_idx].index_select(0, beam_idx.to(device))
|
| 227 |
+
device = self.ssm_states[layer_idx].device
|
| 228 |
+
self.ssm_states[layer_idx] = self.ssm_states[layer_idx].index_select(0, beam_idx.to(device))
|
| 229 |
+
|
| 230 |
+
def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
|
| 231 |
+
"""Returns the sequence length of the cached states. A layer index can be optionally passed."""
|
| 232 |
+
# take any layer that contains cache and not empty tensor
|
| 233 |
+
layer_idx = self.transformer_layers[0] if layer_idx not in self.transformer_layers else layer_idx
|
| 234 |
+
if len(self.key_cache) <= layer_idx:
|
| 235 |
+
return 0
|
| 236 |
+
return self.key_cache[layer_idx].shape[-2]
|
| 237 |
+
|
| 238 |
+
def to_legacy_cache(self) -> Tuple[Tuple[torch.Tensor], Tuple[torch.Tensor]]:
|
| 239 |
+
raise NotImplementedError("HybridMambaAttentionDynamicCache does not have a legacy cache equivalent.")
|
| 240 |
+
|
| 241 |
+
@classmethod
|
| 242 |
+
def from_legacy_cache(cls, past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None) -> "DynamicCache":
|
| 243 |
+
raise NotImplementedError("HybridMambaAttentionDynamicCache does not have a legacy cache equivalent.")
|
| 244 |
+
|
| 245 |
+
# Copied from modeling_mamba2.py
|
| 246 |
+
def update_conv_state(
|
| 247 |
+
self, layer_idx: int, new_conv_state: torch.Tensor, cache_init: bool = False
|
| 248 |
+
) -> torch.Tensor:
|
| 249 |
+
if cache_init:
|
| 250 |
+
self.conv_states[layer_idx] = new_conv_state.to(self.conv_states.device)
|
| 251 |
+
else:
|
| 252 |
+
self.conv_states[layer_idx] = self.conv_states[layer_idx].roll(shifts=-1, dims=-1)
|
| 253 |
+
self.conv_states[layer_idx][:, :, -1] = new_conv_state[:, 0, :].to(self.conv_states.device)
|
| 254 |
+
return self.conv_states[layer_idx]
|
| 255 |
+
|
| 256 |
+
def update_ssm_state(self, layer_idx: int, new_ssm_state: torch.Tensor):
|
| 257 |
+
self.ssm_states[layer_idx] = new_ssm_state.to(self.ssm_states.device)
|
| 258 |
+
return self.ssm_states[layer_idx]
|
| 259 |
+
|
| 260 |
+
def reset(self):
|
| 261 |
+
self.conv_states.zero_()
|
| 262 |
+
self.ssm_states.zero_()
|
| 263 |
+
|
| 264 |
+
class MambaRMSNormGated(torch.nn.Module):
|
| 265 |
+
def __init__(self, hidden_size, group_size, eps=1e-5):
|
| 266 |
+
super().__init__()
|
| 267 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 268 |
+
self.variance_epsilon = eps
|
| 269 |
+
self.group_size = group_size
|
| 270 |
+
|
| 271 |
+
# jan28b version
|
| 272 |
+
def forward(self, hidden_states, gate=None):
|
| 273 |
+
return rmsnorm_fn(x=hidden_states,
|
| 274 |
+
weight=self.weight,
|
| 275 |
+
bias=None, # No bias
|
| 276 |
+
z=gate,
|
| 277 |
+
eps=self.variance_epsilon,
|
| 278 |
+
group_size=self.group_size,
|
| 279 |
+
norm_before_gate=False
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
class NemotronHMamba2Mixer(nn.Module):
|
| 283 |
+
"""
|
| 284 |
+
Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
|
| 285 |
+
A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
|
| 286 |
+
∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
|
| 287 |
+
and is why Mamba is called **selective** state spaces)
|
| 288 |
+
"""
|
| 289 |
+
|
| 290 |
+
def __init__(self, config: NemotronHConfig, layer_idx: int):
|
| 291 |
+
super().__init__()
|
| 292 |
+
self.num_heads = config.mamba_num_heads
|
| 293 |
+
self.hidden_size = config.hidden_size
|
| 294 |
+
self.ssm_state_size = config.ssm_state_size
|
| 295 |
+
self.conv_kernel_size = config.conv_kernel
|
| 296 |
+
self.intermediate_size = config.mamba_num_heads * config.mamba_head_dim
|
| 297 |
+
self.layer_idx = layer_idx
|
| 298 |
+
self.use_conv_bias = config.use_conv_bias
|
| 299 |
+
self.activation = config.mamba_hidden_act
|
| 300 |
+
self.act = ACT2FN[config.mamba_hidden_act]
|
| 301 |
+
|
| 302 |
+
self.layer_norm_epsilon = config.layer_norm_epsilon
|
| 303 |
+
|
| 304 |
+
self.n_groups = config.n_groups
|
| 305 |
+
self.head_dim = config.mamba_head_dim
|
| 306 |
+
self.chunk_size = config.chunk_size
|
| 307 |
+
|
| 308 |
+
self.time_step_limit = config.time_step_limit
|
| 309 |
+
self.time_step_min = config.time_step_min
|
| 310 |
+
self.time_step_max = config.time_step_max
|
| 311 |
+
|
| 312 |
+
self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size
|
| 313 |
+
self.conv1d = nn.Conv1d(
|
| 314 |
+
in_channels=self.conv_dim,
|
| 315 |
+
out_channels=self.conv_dim,
|
| 316 |
+
bias=config.use_conv_bias,
|
| 317 |
+
kernel_size=config.conv_kernel,
|
| 318 |
+
groups=self.conv_dim,
|
| 319 |
+
padding=config.conv_kernel - 1,
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
# projection of the input hidden states
|
| 323 |
+
projection_size = self.intermediate_size + self.conv_dim + self.num_heads
|
| 324 |
+
self.in_proj = nn.Linear(
|
| 325 |
+
self.hidden_size,
|
| 326 |
+
projection_size,
|
| 327 |
+
bias=config.use_bias,
|
| 328 |
+
)
|
| 329 |
+
# selective projection used to make dt, B and C input dependant
|
| 330 |
+
|
| 331 |
+
# time step projection (discretization)
|
| 332 |
+
# instantiate once and copy inv_dt in init_weights of PretrainedModel
|
| 333 |
+
self.dt_bias = nn.Parameter(torch.ones(self.num_heads))
|
| 334 |
+
|
| 335 |
+
# S4D real initialization. These are not discretized!
|
| 336 |
+
# The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
|
| 337 |
+
A = torch.arange(1, self.num_heads + 1)
|
| 338 |
+
self.A_log = nn.Parameter(torch.log(A))
|
| 339 |
+
self.A_log._no_weight_decay = True
|
| 340 |
+
self.norm = MambaRMSNormGated(self.intermediate_size, eps=self.layer_norm_epsilon, group_size=self.intermediate_size // self.n_groups)
|
| 341 |
+
self.D = nn.Parameter(torch.ones(self.num_heads))
|
| 342 |
+
self.D._no_weight_decay = True
|
| 343 |
+
|
| 344 |
+
self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.use_bias)
|
| 345 |
+
self.use_bias = config.use_bias
|
| 346 |
+
|
| 347 |
+
if not is_fast_path_available:
|
| 348 |
+
logger.warning_once(
|
| 349 |
+
"The fast path is not available because on of `(selective_state_update, causal_conv1d_fn, causal_conv1d_update)`"
|
| 350 |
+
" is None. Falling back to the naive implementation. To install follow https://github.com/state-spaces/mamba/#installation and"
|
| 351 |
+
" https://github.com/Dao-AILab/causal-conv1d"
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
def cuda_kernels_forward(
|
| 355 |
+
self,
|
| 356 |
+
hidden_states: torch.Tensor,
|
| 357 |
+
cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
|
| 358 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 359 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 360 |
+
):
|
| 361 |
+
# 1. Gated MLP's linear projection
|
| 362 |
+
hidden_states = apply_mask_to_padding_states(hidden_states, attention_mask)
|
| 363 |
+
projected_states = self.in_proj(hidden_states)
|
| 364 |
+
|
| 365 |
+
# Set up dimensions for reshapes later
|
| 366 |
+
batch_size, seq_len, _ = hidden_states.shape
|
| 367 |
+
groups_time_state_size = self.n_groups * self.ssm_state_size
|
| 368 |
+
d_mlp = (
|
| 369 |
+
projected_states.shape[-1]
|
| 370 |
+
- 2 * self.intermediate_size
|
| 371 |
+
- 2 * self.n_groups * self.ssm_state_size
|
| 372 |
+
- self.num_heads
|
| 373 |
+
) // 2
|
| 374 |
+
|
| 375 |
+
# Single step calculations via cache
|
| 376 |
+
if cache_params is not None and cache_position is not None and cache_position[0] > 0:
|
| 377 |
+
_, _, gate, hidden_states_B_C, dt = projected_states.squeeze(1).split(
|
| 378 |
+
[d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
# 2. Convolution sequence transformation
|
| 382 |
+
hidden_states_B_C = causal_conv1d_update(
|
| 383 |
+
hidden_states_B_C,
|
| 384 |
+
cache_params.conv_states[self.layer_idx],
|
| 385 |
+
self.conv1d.weight.squeeze(1),
|
| 386 |
+
self.conv1d.bias,
|
| 387 |
+
self.activation,
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
hidden_states, B, C = torch.split(
|
| 391 |
+
hidden_states_B_C,
|
| 392 |
+
[self.intermediate_size, groups_time_state_size, groups_time_state_size],
|
| 393 |
+
dim=-1,
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
# 3. SSM transformation
|
| 397 |
+
A = -torch.exp(self.A_log.float()) # (nheads,)
|
| 398 |
+
A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
|
| 399 |
+
dt = dt[:, :, None].expand(-1, -1, self.head_dim)
|
| 400 |
+
dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
|
| 401 |
+
D = self.D[:, None, ...].expand(-1, self.head_dim)
|
| 402 |
+
B = B.view(batch_size, self.n_groups, B.shape[1] // self.n_groups)
|
| 403 |
+
C = C.view(batch_size, self.n_groups, C.shape[1] // self.n_groups)
|
| 404 |
+
hidden_states_reshaped = hidden_states.view(batch_size, self.num_heads, self.head_dim)
|
| 405 |
+
hidden_states = selective_state_update(
|
| 406 |
+
cache_params.ssm_states[self.layer_idx],
|
| 407 |
+
hidden_states_reshaped,
|
| 408 |
+
dt,
|
| 409 |
+
A,
|
| 410 |
+
B,
|
| 411 |
+
C,
|
| 412 |
+
D,
|
| 413 |
+
z=None,
|
| 414 |
+
dt_bias=dt_bias,
|
| 415 |
+
dt_softplus=True,
|
| 416 |
+
)
|
| 417 |
+
hidden_states = hidden_states.view(batch_size, self.num_heads * self.head_dim)
|
| 418 |
+
hidden_states = self.norm(hidden_states, gate)
|
| 419 |
+
|
| 420 |
+
# 4. Final linear projection
|
| 421 |
+
out = self.out_proj(hidden_states)[:, None, ...]
|
| 422 |
+
|
| 423 |
+
# Fused calculations or step by step if no initialized cache is found
|
| 424 |
+
else:
|
| 425 |
+
A = -torch.exp(self.A_log.float()) # (num_heads) or (intermediate_size, state_size)
|
| 426 |
+
dt_limit_kwargs = {} if self.time_step_limit == (0.0, float("inf")) else {"dt_limit": self.time_step_limit}
|
| 427 |
+
|
| 428 |
+
# 2-4. Fused kernel for conv1d, SSM, and the final projection
|
| 429 |
+
if self.training and cache_params is None:
|
| 430 |
+
out = mamba_split_conv1d_scan_combined(
|
| 431 |
+
projected_states,
|
| 432 |
+
self.conv1d.weight.squeeze(1),
|
| 433 |
+
self.conv1d.bias,
|
| 434 |
+
self.dt_bias,
|
| 435 |
+
A,
|
| 436 |
+
D=self.D,
|
| 437 |
+
chunk_size=self.chunk_size,
|
| 438 |
+
seq_idx=None, # was seq_idx
|
| 439 |
+
activation=self.activation,
|
| 440 |
+
rmsnorm_weight=self.norm.weight,
|
| 441 |
+
rmsnorm_eps=self.norm.variance_epsilon,
|
| 442 |
+
outproj_weight=self.out_proj.weight,
|
| 443 |
+
outproj_bias=self.out_proj.bias,
|
| 444 |
+
headdim=self.head_dim,
|
| 445 |
+
ngroups=self.n_groups,
|
| 446 |
+
norm_before_gate=False,
|
| 447 |
+
return_final_states=False,
|
| 448 |
+
**dt_limit_kwargs,
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
else:
|
| 452 |
+
_, _, gate, hidden_states_B_C, dt = projected_states.split(
|
| 453 |
+
[d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
|
| 454 |
+
)
|
| 455 |
+
|
| 456 |
+
# 2. Convolution sequence transformation
|
| 457 |
+
# Init cache
|
| 458 |
+
if cache_params is not None:
|
| 459 |
+
hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2)
|
| 460 |
+
conv_states = nn.functional.pad(
|
| 461 |
+
hidden_states_B_C_transposed,
|
| 462 |
+
(cache_params.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0),
|
| 463 |
+
)
|
| 464 |
+
cache_params.update_conv_state(
|
| 465 |
+
layer_idx=self.layer_idx, new_conv_state=conv_states, cache_init=True
|
| 466 |
+
)
|
| 467 |
+
|
| 468 |
+
if self.activation not in ["silu", "swish"]:
|
| 469 |
+
hidden_states_B_C = self.act(
|
| 470 |
+
self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2)
|
| 471 |
+
)
|
| 472 |
+
else:
|
| 473 |
+
hidden_states_B_C = causal_conv1d_fn(
|
| 474 |
+
x=hidden_states_B_C.transpose(1, 2),
|
| 475 |
+
weight=self.conv1d.weight.squeeze(1),
|
| 476 |
+
bias=self.conv1d.bias,
|
| 477 |
+
activation=self.activation,
|
| 478 |
+
).transpose(1, 2)
|
| 479 |
+
hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
|
| 480 |
+
hidden_states, B, C = torch.split(
|
| 481 |
+
hidden_states_B_C,
|
| 482 |
+
[self.intermediate_size, groups_time_state_size, groups_time_state_size],
|
| 483 |
+
dim=-1,
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
# 3. SSM transformation
|
| 487 |
+
scan_output, ssm_state = mamba_chunk_scan_combined(
|
| 488 |
+
hidden_states.view(batch_size, seq_len, -1, self.head_dim),
|
| 489 |
+
dt,
|
| 490 |
+
A,
|
| 491 |
+
B.view(batch_size, seq_len, self.n_groups, -1),
|
| 492 |
+
C.view(batch_size, seq_len, self.n_groups, -1),
|
| 493 |
+
chunk_size=self.chunk_size,
|
| 494 |
+
D=self.D,
|
| 495 |
+
z=None,
|
| 496 |
+
seq_idx=None,
|
| 497 |
+
return_final_states=True,
|
| 498 |
+
dt_bias=self.dt_bias,
|
| 499 |
+
dt_softplus=True,
|
| 500 |
+
**dt_limit_kwargs,
|
| 501 |
+
)
|
| 502 |
+
|
| 503 |
+
# Init cache
|
| 504 |
+
if ssm_state is not None and cache_params is not None:
|
| 505 |
+
cache_params.update_ssm_state(layer_idx=self.layer_idx, new_ssm_state=ssm_state)
|
| 506 |
+
|
| 507 |
+
scan_output = scan_output.view(batch_size, seq_len, -1)
|
| 508 |
+
|
| 509 |
+
# Multiply "gate" branch and apply extra normalization layer
|
| 510 |
+
scan_output = self.norm(scan_output, gate)
|
| 511 |
+
|
| 512 |
+
# 4. Final linear projection
|
| 513 |
+
out = self.out_proj(scan_output)
|
| 514 |
+
return out
|
| 515 |
+
|
| 516 |
+
# fmt: off
|
| 517 |
+
def torch_forward(self, input_states, cache_params: Optional[HybridMambaAttentionDynamicCache]=None, cache_position:Optional[torch.LongTensor]=None, attention_mask: Optional[torch.Tensor]=None):
|
| 518 |
+
batch_size, seq_len, _ = input_states.shape
|
| 519 |
+
dtype = input_states.dtype
|
| 520 |
+
|
| 521 |
+
# 1. Gated MLP's linear projection
|
| 522 |
+
input_states = apply_mask_to_padding_states(input_states, attention_mask)
|
| 523 |
+
projected_states = self.in_proj(input_states)
|
| 524 |
+
d_mlp = (projected_states.shape[-1] - 2 * self.intermediate_size - 2 * self.n_groups * self.ssm_state_size-self.num_heads) // 2
|
| 525 |
+
_, _, gate, hidden_states_B_C, dt = projected_states.split(
|
| 526 |
+
[d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
# 2. Convolution sequence transformation
|
| 530 |
+
if cache_params is not None and cache_position is not None and cache_position[0] > 0:
|
| 531 |
+
cache_params.update_conv_state(layer_idx=self.layer_idx, new_conv_state=hidden_states_B_C, cache_init=False)
|
| 532 |
+
|
| 533 |
+
# We need to guarantee that anything regarding the cache is on the same device
|
| 534 |
+
conv_states = cache_params.conv_states[self.layer_idx].to(device=self.conv1d.weight.device)
|
| 535 |
+
|
| 536 |
+
hidden_states_B_C = torch.sum(
|
| 537 |
+
conv_states * self.conv1d.weight.squeeze(1), dim=-1
|
| 538 |
+
)
|
| 539 |
+
if self.use_conv_bias:
|
| 540 |
+
hidden_states_B_C = hidden_states_B_C + self.conv1d.bias
|
| 541 |
+
hidden_states_B_C = self.act(hidden_states_B_C)
|
| 542 |
+
else:
|
| 543 |
+
# Init cache
|
| 544 |
+
if cache_params is not None:
|
| 545 |
+
hidden_states_B_C_transposed = hidden_states_B_C.transpose(1, 2)
|
| 546 |
+
conv_states = nn.functional.pad(
|
| 547 |
+
hidden_states_B_C_transposed, (cache_params.conv_kernel_size - hidden_states_B_C_transposed.shape[-1], 0)
|
| 548 |
+
)
|
| 549 |
+
cache_params.update_conv_state(layer_idx=self.layer_idx, new_conv_state=conv_states, cache_init=True)
|
| 550 |
+
|
| 551 |
+
hidden_states_B_C = self.act(self.conv1d(hidden_states_B_C.transpose(1, 2))[..., :seq_len].transpose(1, 2))
|
| 552 |
+
|
| 553 |
+
hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask)
|
| 554 |
+
hidden_states, B, C = torch.split(
|
| 555 |
+
hidden_states_B_C,
|
| 556 |
+
[self.intermediate_size, self.n_groups * self.ssm_state_size, self.n_groups * self.ssm_state_size],
|
| 557 |
+
dim=-1
|
| 558 |
+
)
|
| 559 |
+
|
| 560 |
+
# 3. SSM transformation
|
| 561 |
+
A = -torch.exp(self.A_log.float()) # [num_heads]
|
| 562 |
+
if cache_params is not None and cache_position is not None and cache_position[0] > 0:
|
| 563 |
+
# We need to guarantee that anything regarding the cache is on the same device
|
| 564 |
+
cache_device = cache_params.ssm_states.device
|
| 565 |
+
|
| 566 |
+
# Note: there is no need to pad parameter matrices here, as there is just one new token
|
| 567 |
+
# for batched generation
|
| 568 |
+
dt = dt[:, 0, :][:, None, ...]
|
| 569 |
+
dt = dt.transpose(1, 2).expand(batch_size, dt.shape[-1], self.head_dim)
|
| 570 |
+
# [num_heads] -> [num_heads, head_dim]
|
| 571 |
+
dt_bias = self.dt_bias[..., None].expand(self.dt_bias.shape[0], self.head_dim)
|
| 572 |
+
|
| 573 |
+
dt = torch.nn.functional.softplus(dt + dt_bias.to(dt.dtype))
|
| 574 |
+
dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
|
| 575 |
+
A = A[..., None, None].expand(self.num_heads, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
|
| 576 |
+
# [bsz, num_heads, head_dim, state_size]
|
| 577 |
+
dA = (torch.exp(dt[..., None] * A)).to(device=cache_device)
|
| 578 |
+
|
| 579 |
+
# Discretize B
|
| 580 |
+
# [bsz, n_groups * state_size] -> [bsz, n_groups, 1, state_size] ->
|
| 581 |
+
# -> [bsz, n_groups, group to head repetition factor, state_size] -> [bsz, num_heads, state_size]
|
| 582 |
+
B = B.reshape(batch_size, self.n_groups, -1)[..., None, :]
|
| 583 |
+
B = B.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, B.shape[-1]).contiguous()
|
| 584 |
+
B = B.reshape(batch_size, -1, B.shape[-1])
|
| 585 |
+
# [bsz, num_heads, head_dim, state_size]
|
| 586 |
+
dB = dt[..., None] * B[..., None, :]
|
| 587 |
+
|
| 588 |
+
# Discretize x into dB
|
| 589 |
+
# [bsz, intermediate_size] -> [bsz, num_heads, head_dim]
|
| 590 |
+
hidden_states = hidden_states.reshape(batch_size, -1, self.head_dim)
|
| 591 |
+
dBx = (dB * hidden_states[..., None]).to(device=cache_device)
|
| 592 |
+
|
| 593 |
+
# State calculation
|
| 594 |
+
cache_params.update_ssm_state(
|
| 595 |
+
layer_idx=self.layer_idx,
|
| 596 |
+
new_ssm_state=cache_params.ssm_states[self.layer_idx] * dA + dBx
|
| 597 |
+
)
|
| 598 |
+
|
| 599 |
+
# Subsequent output
|
| 600 |
+
# [bsz, n_groups * state_size] -> [bsz, num_heads, state_size]
|
| 601 |
+
C = C.reshape(batch_size, self.n_groups, -1)[..., None, :]
|
| 602 |
+
C = C.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, C.shape[-1]).contiguous()
|
| 603 |
+
C = C.reshape(batch_size, -1, C.shape[-1])
|
| 604 |
+
# [bsz, num_heads, head_dim]
|
| 605 |
+
|
| 606 |
+
ssm_states = cache_params.ssm_states[self.layer_idx].to(device=C.device, dtype=C.dtype) # Shape: [b, h, d, n]
|
| 607 |
+
# Reshape ssm_states to merge the first two dimensions
|
| 608 |
+
ssm_states_reshaped = ssm_states.view(batch_size * self.num_heads, self.head_dim, self.ssm_state_size) # Shape: [b*h, d, n]
|
| 609 |
+
C_reshaped = C.view(batch_size * self.num_heads, self.ssm_state_size, 1) # Shape: [b*h, n, 1]
|
| 610 |
+
y = torch.bmm(ssm_states_reshaped, C_reshaped)
|
| 611 |
+
y = y.view(batch_size, self.num_heads, self.head_dim)
|
| 612 |
+
|
| 613 |
+
# D skip connection
|
| 614 |
+
# [num_heads] -> [num_heads, head_dim]
|
| 615 |
+
D = self.D[..., None].expand(self.D.shape[0], self.head_dim)
|
| 616 |
+
y = (y + hidden_states * D).to(y.dtype)
|
| 617 |
+
|
| 618 |
+
# [bsz, num_heads, head_dim] -> [bsz, 1, intermediate_size]
|
| 619 |
+
y = y.reshape(batch_size, -1)[:, None, ...]
|
| 620 |
+
else:
|
| 621 |
+
# begin ssd naive implementation without einsums
|
| 622 |
+
dt = nn.functional.softplus(dt + self.dt_bias)
|
| 623 |
+
dt = torch.clamp(dt, self.time_step_limit[0], self.time_step_limit[1])
|
| 624 |
+
hidden_states = hidden_states.reshape(batch_size, seq_len, -1, self.head_dim).float()
|
| 625 |
+
B = B.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
|
| 626 |
+
C = C.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
|
| 627 |
+
B = B.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
|
| 628 |
+
C = C.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
|
| 629 |
+
pad_size = (self.chunk_size - seq_len % self.chunk_size) % self.chunk_size
|
| 630 |
+
|
| 631 |
+
D_residual = self.D[..., None] * pad_tensor_by_size(hidden_states, pad_size)
|
| 632 |
+
|
| 633 |
+
# Discretize x and A
|
| 634 |
+
hidden_states = hidden_states * dt[..., None]
|
| 635 |
+
A = A.to(hidden_states.dtype) * dt
|
| 636 |
+
|
| 637 |
+
# Rearrange into blocks/chunks
|
| 638 |
+
hidden_states, A, B, C = [reshape_into_chunks(t, pad_size, self.chunk_size) for t in (hidden_states, A, B, C)]
|
| 639 |
+
|
| 640 |
+
# [bsz, -1, chunk_size, num_heads] -> [bsz, num_heads, -1, chunk_size]
|
| 641 |
+
A = A.permute(0, 3, 1, 2)
|
| 642 |
+
A_cumsum = torch.cumsum(A, dim=-1)
|
| 643 |
+
|
| 644 |
+
# 1. Compute the output for each intra-chunk (diagonal blocks)
|
| 645 |
+
# This is the analog of a causal mask
|
| 646 |
+
L = torch.exp(segment_sum(A))
|
| 647 |
+
|
| 648 |
+
# Contraction of C and B to get G (attention-weights like)
|
| 649 |
+
G_intermediate = C[:, :, :, None, :, :] * B[:, :, None, :, :, :] # shape: (b, c, l, s, h, n)
|
| 650 |
+
G = G_intermediate.sum(dim=-1) # shape: (b, c, l, s, h)
|
| 651 |
+
|
| 652 |
+
# Compute M, equivalent to applying attention mask to weights
|
| 653 |
+
M_intermediate = G[..., None] * L.permute(0, 2, 3, 4, 1)[..., None]
|
| 654 |
+
M = M_intermediate.sum(dim=-1)
|
| 655 |
+
|
| 656 |
+
# Compute Y_diag (apply to values)
|
| 657 |
+
Y_diag = (M[..., None] * hidden_states[:, :, None]).sum(dim=3)
|
| 658 |
+
|
| 659 |
+
# 2. Compute the state for each intra-chunk
|
| 660 |
+
# (right term of low-rank factorization of off-diagonal blocks; B terms)
|
| 661 |
+
decay_states = torch.exp((A_cumsum[:, :, :, -1:] - A_cumsum))
|
| 662 |
+
B_decay = B * decay_states.permute(0, -2, -1, 1)[..., None]
|
| 663 |
+
states = (B_decay[..., None, :] * hidden_states[..., None]).sum(dim=2)
|
| 664 |
+
|
| 665 |
+
# 3. Compute the inter-chunk SSM recurrence; produces correct SSM states at chunk boundaries
|
| 666 |
+
# (middle term of factorization of off-diag blocks; A terms)
|
| 667 |
+
if cache_params is not None and cache_position is not None and cache_position[0] > 0:
|
| 668 |
+
previous_states = cache_params.ssm_states[self.layer_idx][:, None, ...].to(device=states.device)
|
| 669 |
+
else:
|
| 670 |
+
previous_states = torch.zeros_like(states[:, :1])
|
| 671 |
+
states = torch.cat([previous_states, states], dim=1)
|
| 672 |
+
decay_chunk = torch.exp(segment_sum(nn.functional.pad(A_cumsum[:, :, :, -1], (1, 0))))
|
| 673 |
+
decay_chunk = decay_chunk.transpose(1, 3)
|
| 674 |
+
new_states = (decay_chunk[..., None, None] * states[:, :, None, ...]).sum(dim=1)
|
| 675 |
+
states, ssm_state = new_states[:, :-1], new_states[:, -1]
|
| 676 |
+
|
| 677 |
+
# 4. Compute state -> output conversion per chunk
|
| 678 |
+
# (left term of low-rank factorization of off-diagonal blocks; C terms)
|
| 679 |
+
state_decay_out = torch.exp(A_cumsum)
|
| 680 |
+
C_times_states = (C[..., None, :] * states[:, :, None, ...])
|
| 681 |
+
state_decay_out_permuted = state_decay_out.permute(0, 2, 3, 1)
|
| 682 |
+
Y_off = (C_times_states.sum(-1) * state_decay_out_permuted[..., None])
|
| 683 |
+
|
| 684 |
+
# Add output of intra-chunk and inter-chunk terms (diagonal and off-diagonal blocks)
|
| 685 |
+
y = Y_diag + Y_off
|
| 686 |
+
# [bsz, -1, self.chunk_size, num_heads, head_dim] -> [bsz, (padded) seq_len, num_heads, head_dim]
|
| 687 |
+
y = y.reshape(batch_size, -1, self.num_heads, self.head_dim)
|
| 688 |
+
|
| 689 |
+
y = y + D_residual
|
| 690 |
+
# Cutting off padded chunks
|
| 691 |
+
if pad_size > 0:
|
| 692 |
+
y = y[:, :seq_len, :, :]
|
| 693 |
+
y = y.reshape(batch_size, seq_len, -1)
|
| 694 |
+
|
| 695 |
+
# Init cache
|
| 696 |
+
if ssm_state is not None and cache_params is not None:
|
| 697 |
+
cache_params.update_ssm_state(layer_idx=self.layer_idx, new_ssm_state=ssm_state)
|
| 698 |
+
|
| 699 |
+
scan_output = self.norm(y, gate)
|
| 700 |
+
|
| 701 |
+
# end ssd naive
|
| 702 |
+
|
| 703 |
+
# 4. Final linear projection
|
| 704 |
+
contextualized_states = self.out_proj(scan_output.to(dtype)) # [batch, seq_len, hidden_size]
|
| 705 |
+
return contextualized_states
|
| 706 |
+
# fmt: on
|
| 707 |
+
|
| 708 |
+
def forward(
|
| 709 |
+
self,
|
| 710 |
+
hidden_states,
|
| 711 |
+
cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
|
| 712 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 713 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 714 |
+
):
|
| 715 |
+
if is_fast_path_available and "cuda" in self.in_proj.weight.device.type:
|
| 716 |
+
return self.cuda_kernels_forward(hidden_states, cache_params, cache_position, attention_mask)
|
| 717 |
+
dtype = hidden_states.dtype
|
| 718 |
+
if attention_mask is not None and attention_mask.shape[1] > 1 and attention_mask.shape[0] > 1:
|
| 719 |
+
# tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
|
| 720 |
+
hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
|
| 721 |
+
|
| 722 |
+
return self.torch_forward(hidden_states, cache_params, cache_position, attention_mask)
|
| 723 |
+
|
| 724 |
+
|
| 725 |
+
class NemotronHRMSNorm(nn.Module):
|
| 726 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 727 |
+
"""
|
| 728 |
+
NemotronHRMSNorm is equivalent to T5LayerNorm and LlamaRMSNorm
|
| 729 |
+
"""
|
| 730 |
+
super().__init__()
|
| 731 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 732 |
+
self.variance_epsilon = eps
|
| 733 |
+
|
| 734 |
+
def forward(self, hidden_states):
|
| 735 |
+
input_dtype = hidden_states.dtype
|
| 736 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 737 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 738 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 739 |
+
# Weights are in float32
|
| 740 |
+
return (self.weight.to(torch.float32) * hidden_states).to(input_dtype)
|
| 741 |
+
|
| 742 |
+
class NemotronHBlock(nn.Module):
|
| 743 |
+
def __init__(self, config, layer_idx):
|
| 744 |
+
super().__init__()
|
| 745 |
+
self.config = config
|
| 746 |
+
self.layer_idx = layer_idx
|
| 747 |
+
self.residual_in_fp32 = config.residual_in_fp32
|
| 748 |
+
self.norm = NemotronHRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
|
| 749 |
+
|
| 750 |
+
# M: Mamba2, *: Attention, -: MLP
|
| 751 |
+
self.block_type = config.layers_block_type[layer_idx]
|
| 752 |
+
if self.block_type == "mamba":
|
| 753 |
+
self.mixer = NemotronHMamba2Mixer(config, layer_idx=layer_idx)
|
| 754 |
+
elif self.block_type == "attention":
|
| 755 |
+
self.mixer = NEMOTRONH_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx=layer_idx)
|
| 756 |
+
elif self.block_type == "mlp":
|
| 757 |
+
self.mixer = NemotronHMLP(config, layer_idx=layer_idx)
|
| 758 |
+
elif self.block_type == "moe":
|
| 759 |
+
self.mixer = NemotronHMOE(config, layer_idx=layer_idx)
|
| 760 |
+
else:
|
| 761 |
+
raise ValueError(f"Invalid layer pattern {config.hybrid_override_pattern[layer_idx]}")
|
| 762 |
+
|
| 763 |
+
def forward(
|
| 764 |
+
self,
|
| 765 |
+
hidden_states,
|
| 766 |
+
cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
|
| 767 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 768 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 769 |
+
):
|
| 770 |
+
with torch.cuda.stream(torch.cuda.default_stream(hidden_states.device)):
|
| 771 |
+
# * Use torch.cuda.stream() to avoid NaN issues when using multiple GPUs
|
| 772 |
+
residual = hidden_states
|
| 773 |
+
hidden_states = self.norm(hidden_states.to(dtype=self.norm.weight.dtype))
|
| 774 |
+
if self.residual_in_fp32:
|
| 775 |
+
residual = residual.to(torch.float32)
|
| 776 |
+
|
| 777 |
+
if self.block_type == "mamba":
|
| 778 |
+
hidden_states = self.mixer(
|
| 779 |
+
hidden_states, cache_params=cache_params, cache_position=cache_position
|
| 780 |
+
)
|
| 781 |
+
elif self.block_type == "attention":
|
| 782 |
+
hidden_states = self.mixer(
|
| 783 |
+
hidden_states, cache_position=cache_position
|
| 784 |
+
)
|
| 785 |
+
hidden_states = hidden_states[0]
|
| 786 |
+
elif self.block_type in ["mlp", "moe"]:
|
| 787 |
+
hidden_states = self.mixer(
|
| 788 |
+
hidden_states
|
| 789 |
+
)
|
| 790 |
+
else:
|
| 791 |
+
raise ValueError(f"Invalid block_type: {self.block_type}")
|
| 792 |
+
|
| 793 |
+
hidden_states = residual + hidden_states
|
| 794 |
+
return hidden_states
|
| 795 |
+
|
| 796 |
+
|
| 797 |
+
# Copied from transformers.models.nemotron.modeling_nemotron Nemotron->NemotronH
|
| 798 |
+
class NemotronHMLP(nn.Module):
|
| 799 |
+
def __init__(self, config, intermediate_size=None, layer_idx: Optional[int] = None, is_expert=False):
|
| 800 |
+
super().__init__()
|
| 801 |
+
self.config = config
|
| 802 |
+
self.layer_idx = layer_idx
|
| 803 |
+
if layer_idx is None:
|
| 804 |
+
logger.warning_once(
|
| 805 |
+
f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
|
| 806 |
+
"lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
|
| 807 |
+
"when creating this class."
|
| 808 |
+
)
|
| 809 |
+
use_latent_size = (self.config.moe_latent_size is not None) and is_expert
|
| 810 |
+
self.hidden_size = config.hidden_size
|
| 811 |
+
input_size = self.hidden_size if not use_latent_size else config.moe_latent_size
|
| 812 |
+
|
| 813 |
+
self.intermediate_size = intermediate_size or config.intermediate_size
|
| 814 |
+
self.up_proj = nn.Linear(input_size, self.intermediate_size, bias=config.mlp_bias)
|
| 815 |
+
self.down_proj = nn.Linear(self.intermediate_size, input_size, bias=config.mlp_bias)
|
| 816 |
+
self.act_fn = ACT2FN[config.mlp_hidden_act]
|
| 817 |
+
|
| 818 |
+
def forward(self, x):
|
| 819 |
+
return self.down_proj(self.act_fn(self.up_proj(x)))
|
| 820 |
+
|
| 821 |
+
|
| 822 |
+
class NemotronHMOE(nn.Module):
|
| 823 |
+
def __init__(self, config, layer_idx: Optional[int] = None):
|
| 824 |
+
super().__init__()
|
| 825 |
+
self.config = config
|
| 826 |
+
self.experts = nn.ModuleList(
|
| 827 |
+
[
|
| 828 |
+
NemotronHMLP(config, intermediate_size=config.moe_intermediate_size, layer_idx=layer_idx, is_expert=True)
|
| 829 |
+
for _ in range(config.n_routed_experts)
|
| 830 |
+
]
|
| 831 |
+
)
|
| 832 |
+
self.gate = NemotronHTopkRouter(config)
|
| 833 |
+
self.shared_experts = NemotronHMLP(
|
| 834 |
+
config=config, intermediate_size=config.moe_shared_expert_intermediate_size, layer_idx=layer_idx, is_expert=False
|
| 835 |
+
)
|
| 836 |
+
|
| 837 |
+
if config.moe_latent_size is not None:
|
| 838 |
+
self.fc1_latent_proj = nn.Linear(config.hidden_size, config.moe_latent_size, bias=config.mlp_bias)
|
| 839 |
+
self.fc2_latent_proj = nn.Linear(config.moe_latent_size, config.hidden_size, bias=config.mlp_bias)
|
| 840 |
+
else:
|
| 841 |
+
self.fc1_latent_proj = nn.Identity()
|
| 842 |
+
self.fc2_latent_proj = nn.Identity()
|
| 843 |
+
|
| 844 |
+
def moe(self, hidden_states: torch.Tensor, topk_indices: torch.Tensor, topk_weights: torch.Tensor):
|
| 845 |
+
r"""
|
| 846 |
+
CALL FOR CONTRIBUTION! I don't have time to optimise this right now, but expert weights need to be fused
|
| 847 |
+
to not have to do a loop here (deepseek has 256 experts soooo yeah).
|
| 848 |
+
"""
|
| 849 |
+
final_hidden_states = torch.zeros_like(hidden_states, dtype=topk_weights.dtype)
|
| 850 |
+
expert_mask = torch.nn.functional.one_hot(topk_indices, num_classes=len(self.experts))
|
| 851 |
+
expert_mask = expert_mask.permute(2, 0, 1)
|
| 852 |
+
|
| 853 |
+
for expert_idx in range(len(self.experts)):
|
| 854 |
+
expert = self.experts[expert_idx]
|
| 855 |
+
mask = expert_mask[expert_idx]
|
| 856 |
+
token_indices, weight_indices = torch.where(mask)
|
| 857 |
+
|
| 858 |
+
if token_indices.numel() > 0:
|
| 859 |
+
expert_weights = topk_weights[token_indices, weight_indices]
|
| 860 |
+
expert_input = hidden_states[token_indices]
|
| 861 |
+
expert_output = expert(expert_input)
|
| 862 |
+
weighted_output = expert_output * expert_weights.unsqueeze(-1)
|
| 863 |
+
final_hidden_states.index_add_(0, token_indices, weighted_output)
|
| 864 |
+
else:
|
| 865 |
+
# Local empty expert: no-op compute that still marks params as used.
|
| 866 |
+
expert_dtype = expert.down_proj.weight.dtype
|
| 867 |
+
dummy_out = expert(torch.zeros_like(hidden_states[0]).unsqueeze(0).to(expert_dtype))
|
| 868 |
+
final_hidden_states = final_hidden_states + dummy_out
|
| 869 |
+
|
| 870 |
+
|
| 871 |
+
# in original deepseek, the output of the experts are gathered once we leave this module
|
| 872 |
+
# thus the moe module is itelsf an IsolatedParallel module
|
| 873 |
+
# and all expert are "local" meaning we shard but we don't gather
|
| 874 |
+
return final_hidden_states.type(hidden_states.dtype)
|
| 875 |
+
|
| 876 |
+
def forward(self, hidden_states):
|
| 877 |
+
residuals = hidden_states
|
| 878 |
+
orig_shape = hidden_states.shape
|
| 879 |
+
topk_indices, topk_weights = self.gate(hidden_states)
|
| 880 |
+
hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
|
| 881 |
+
|
| 882 |
+
hidden_states = self.fc1_latent_proj(hidden_states)
|
| 883 |
+
hidden_states = self.moe(hidden_states, topk_indices, topk_weights)
|
| 884 |
+
hidden_states = self.fc2_latent_proj(hidden_states)
|
| 885 |
+
|
| 886 |
+
hidden_states = hidden_states.view(*orig_shape)
|
| 887 |
+
|
| 888 |
+
hidden_states = hidden_states + self.shared_experts(residuals)
|
| 889 |
+
return hidden_states
|
| 890 |
+
|
| 891 |
+
|
| 892 |
+
class NemotronHTopkRouter(nn.Module):
|
| 893 |
+
def __init__(self, config):
|
| 894 |
+
super().__init__()
|
| 895 |
+
self.config = config
|
| 896 |
+
self.top_k = config.num_experts_per_tok
|
| 897 |
+
self.n_routed_experts = config.n_routed_experts
|
| 898 |
+
self.routed_scaling_factor = config.routed_scaling_factor
|
| 899 |
+
self.n_group = config.n_group
|
| 900 |
+
self.topk_group = config.topk_group
|
| 901 |
+
self.norm_topk_prob = config.norm_topk_prob
|
| 902 |
+
|
| 903 |
+
self.weight = nn.Parameter(torch.empty((self.n_routed_experts, config.hidden_size)))
|
| 904 |
+
self.register_buffer("e_score_correction_bias", torch.zeros(self.n_routed_experts, dtype=torch.float32))
|
| 905 |
+
|
| 906 |
+
@torch.no_grad()
|
| 907 |
+
def get_topk_indices(self, scores):
|
| 908 |
+
scores_for_choice = scores.view(-1, self.n_routed_experts) + self.e_score_correction_bias.unsqueeze(0)
|
| 909 |
+
group_scores = (
|
| 910 |
+
scores_for_choice.view(-1, self.n_group, self.n_routed_experts // self.n_group)
|
| 911 |
+
.topk(2, dim=-1)[0]
|
| 912 |
+
.sum(dim=-1)
|
| 913 |
+
)
|
| 914 |
+
group_idx = torch.topk(group_scores, k=self.topk_group, dim=-1, sorted=False)[1]
|
| 915 |
+
group_mask = torch.zeros_like(group_scores)
|
| 916 |
+
group_mask.scatter_(1, group_idx, 1)
|
| 917 |
+
score_mask = (
|
| 918 |
+
group_mask.unsqueeze(-1)
|
| 919 |
+
.expand(-1, self.n_group, self.n_routed_experts // self.n_group)
|
| 920 |
+
.reshape(-1, self.n_routed_experts)
|
| 921 |
+
)
|
| 922 |
+
scores_for_choice = scores_for_choice.masked_fill(~score_mask.bool(), 0.0)
|
| 923 |
+
topk_indices = torch.topk(scores_for_choice, k=self.top_k, dim=-1, sorted=False)[1]
|
| 924 |
+
return topk_indices
|
| 925 |
+
|
| 926 |
+
def forward(self, hidden_states):
|
| 927 |
+
self._maintain_float32_expert_bias()
|
| 928 |
+
|
| 929 |
+
hidden_states = hidden_states.view(-1, self.config.hidden_size)
|
| 930 |
+
router_logits = F.linear(hidden_states.type(torch.float32), self.weight.type(torch.float32))
|
| 931 |
+
scores = router_logits.sigmoid()
|
| 932 |
+
topk_indices = self.get_topk_indices(scores)
|
| 933 |
+
topk_weights = scores.gather(1, topk_indices)
|
| 934 |
+
if self.norm_topk_prob:
|
| 935 |
+
denominator = topk_weights.sum(dim=-1, keepdim=True) + 1e-20
|
| 936 |
+
topk_weights /= denominator
|
| 937 |
+
topk_weights = topk_weights * self.routed_scaling_factor
|
| 938 |
+
return topk_indices, topk_weights
|
| 939 |
+
|
| 940 |
+
def _maintain_float32_expert_bias(self):
|
| 941 |
+
if self.e_score_correction_bias.dtype != torch.float32:
|
| 942 |
+
self.e_score_correction_bias.data = self.e_score_correction_bias.data.to(torch.float32)
|
| 943 |
+
|
| 944 |
+
|
| 945 |
+
class NemotronHMultiTokenPredictorLayer(NemotronHBlock):
|
| 946 |
+
def __init__(self, config, layer_idx, is_first=False, is_last=False):
|
| 947 |
+
super().__init__(config, layer_idx)
|
| 948 |
+
self.is_first = is_first
|
| 949 |
+
self.is_last = is_last
|
| 950 |
+
|
| 951 |
+
if self.is_first:
|
| 952 |
+
self.eh_proj = nn.Linear(2*config.hidden_size, config.hidden_size, bias=config.mlp_bias)
|
| 953 |
+
self.enorm = NemotronHRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
|
| 954 |
+
self.hnorm = NemotronHRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
|
| 955 |
+
|
| 956 |
+
if self.is_last:
|
| 957 |
+
self.final_layernorm = nn.LayerNorm(config.hidden_size, bias=config.mlp_bias)
|
| 958 |
+
|
| 959 |
+
def forward(self, x):
|
| 960 |
+
raise NotImplementedError("NemotronHMultiTokenPredictorLayer is not implemented in HuggingFace yet")
|
| 961 |
+
|
| 962 |
+
|
| 963 |
+
class NemotronHMultiTokenPredictor(nn.Module):
|
| 964 |
+
def __init__(self, config):
|
| 965 |
+
super().__init__()
|
| 966 |
+
|
| 967 |
+
config_mtp = copy.deepcopy(config)
|
| 968 |
+
config_mtp.hybrid_override_pattern = config.mtp_hybrid_override_pattern
|
| 969 |
+
config_mtp.num_hidden_layers = len(config_mtp.mtp_hybrid_override_pattern)
|
| 970 |
+
|
| 971 |
+
layers = []
|
| 972 |
+
for _ in range(config.num_nextn_predict_layers):
|
| 973 |
+
for layer_idx in range(config_mtp.num_hidden_layers):
|
| 974 |
+
is_first = (layer_idx == 0)
|
| 975 |
+
is_last = (layer_idx == config_mtp.num_hidden_layers - 1)
|
| 976 |
+
layers.append(
|
| 977 |
+
NemotronHMultiTokenPredictorLayer(
|
| 978 |
+
config=config_mtp,
|
| 979 |
+
layer_idx=layer_idx,
|
| 980 |
+
is_first=is_first,
|
| 981 |
+
is_last=is_last
|
| 982 |
+
)
|
| 983 |
+
)
|
| 984 |
+
self.layers = torch.nn.ModuleList(layers)
|
| 985 |
+
|
| 986 |
+
def forward(self, x):
|
| 987 |
+
raise NotImplementedError("NemotronHMultiTokenPredictor is not implemented in HuggingFace yet")
|
| 988 |
+
|
| 989 |
+
|
| 990 |
+
# Copied from transformers.models.llama.modeling_llama.repeat_kv
|
| 991 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 992 |
+
"""
|
| 993 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 994 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 995 |
+
"""
|
| 996 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 997 |
+
if n_rep == 1:
|
| 998 |
+
return hidden_states
|
| 999 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 1000 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 1001 |
+
|
| 1002 |
+
|
| 1003 |
+
class NemotronHAttention(nn.Module):
|
| 1004 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 1005 |
+
|
| 1006 |
+
def __init__(self, config: NemotronHConfig, layer_idx: Optional[int] = None):
|
| 1007 |
+
super().__init__()
|
| 1008 |
+
self.config = config
|
| 1009 |
+
self.layer_idx = layer_idx
|
| 1010 |
+
if layer_idx is None:
|
| 1011 |
+
logger.warning_once(
|
| 1012 |
+
f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
|
| 1013 |
+
"lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
|
| 1014 |
+
"when creating this class."
|
| 1015 |
+
)
|
| 1016 |
+
|
| 1017 |
+
self.attention_dropout = config.attention_dropout
|
| 1018 |
+
self.hidden_size = config.hidden_size
|
| 1019 |
+
self.num_heads = config.num_attention_heads
|
| 1020 |
+
if config.head_dim is not None:
|
| 1021 |
+
self.head_dim = config.head_dim
|
| 1022 |
+
else:
|
| 1023 |
+
self.head_dim = config.hidden_size // config.num_attention_heads
|
| 1024 |
+
self.num_key_value_heads = config.num_key_value_heads
|
| 1025 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
| 1026 |
+
self.max_position_embeddings = config.max_position_embeddings
|
| 1027 |
+
self.is_causal = True
|
| 1028 |
+
|
| 1029 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
|
| 1030 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
| 1031 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
| 1032 |
+
self.o_proj = nn.Linear(self.head_dim * self.num_heads, self.hidden_size, bias=config.attention_bias)
|
| 1033 |
+
|
| 1034 |
+
def forward(
|
| 1035 |
+
self,
|
| 1036 |
+
hidden_states: torch.Tensor,
|
| 1037 |
+
# position_embeddings: Tuple[torch.Tensor, torch.Tensor], #TODO
|
| 1038 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1039 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1040 |
+
past_key_value: Optional[HybridMambaAttentionDynamicCache] = None,
|
| 1041 |
+
output_attentions: bool = False,
|
| 1042 |
+
use_cache: bool = False,
|
| 1043 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 1044 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 1045 |
+
bsz, q_len, _ = hidden_states.size()
|
| 1046 |
+
|
| 1047 |
+
query_states = self.q_proj(hidden_states)
|
| 1048 |
+
key_states = self.k_proj(hidden_states)
|
| 1049 |
+
value_states = self.v_proj(hidden_states)
|
| 1050 |
+
|
| 1051 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 1052 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 1053 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 1054 |
+
|
| 1055 |
+
if past_key_value is not None:
|
| 1056 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx)
|
| 1057 |
+
|
| 1058 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
| 1059 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
| 1060 |
+
|
| 1061 |
+
causal_mask = attention_mask
|
| 1062 |
+
if attention_mask is not None: # no matter the length, we just slice it
|
| 1063 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
| 1064 |
+
|
| 1065 |
+
if query_states.device.type == "cuda" and attention_mask is not None:
|
| 1066 |
+
query_states = query_states.contiguous()
|
| 1067 |
+
key_states = key_states.contiguous()
|
| 1068 |
+
value_states = value_states.contiguous()
|
| 1069 |
+
|
| 1070 |
+
is_causal = True if causal_mask is None and q_len > 1 else False
|
| 1071 |
+
|
| 1072 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
| 1073 |
+
query_states,
|
| 1074 |
+
key_states,
|
| 1075 |
+
value_states,
|
| 1076 |
+
attn_mask=causal_mask,
|
| 1077 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
| 1078 |
+
is_causal=is_causal,
|
| 1079 |
+
)
|
| 1080 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 1081 |
+
#attn_output = attn_output.view(bsz, q_len, self.hidden_size)
|
| 1082 |
+
attn_output = attn_output.view(bsz, q_len, self.num_heads * self.head_dim)
|
| 1083 |
+
|
| 1084 |
+
attn_output = self.o_proj(attn_output)
|
| 1085 |
+
|
| 1086 |
+
return attn_output, None, past_key_value
|
| 1087 |
+
|
| 1088 |
+
|
| 1089 |
+
# Adapted from transformers.models.mistral.modeling_mistral.MistralFlashAttention2 with Mistral->Jamba
|
| 1090 |
+
#class JambaFlashAttention2(JambaAttention):
|
| 1091 |
+
class NemotronHFlashAttention2(NemotronHAttention):
|
| 1092 |
+
"""
|
| 1093 |
+
Jamba flash attention module. This module inherits from `JambaAttention` as the weights of the module stays
|
| 1094 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
| 1095 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
| 1096 |
+
"""
|
| 1097 |
+
def __init__(self, *args, **kwargs):
|
| 1098 |
+
super().__init__(*args, **kwargs)
|
| 1099 |
+
|
| 1100 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
| 1101 |
+
# flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
|
| 1102 |
+
# Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
|
| 1103 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
| 1104 |
+
|
| 1105 |
+
def forward(
|
| 1106 |
+
self,
|
| 1107 |
+
hidden_states: torch.Tensor,
|
| 1108 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1109 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1110 |
+
past_key_value: Optional[HybridMambaAttentionDynamicCache] = None,
|
| 1111 |
+
output_attentions: bool = False,
|
| 1112 |
+
use_cache: bool = False,
|
| 1113 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 1114 |
+
**kwargs,
|
| 1115 |
+
):
|
| 1116 |
+
bsz, q_len, _ = hidden_states.size()
|
| 1117 |
+
|
| 1118 |
+
query_states = self.q_proj(hidden_states)
|
| 1119 |
+
key_states = self.k_proj(hidden_states)
|
| 1120 |
+
value_states = self.v_proj(hidden_states)
|
| 1121 |
+
|
| 1122 |
+
# Flash attention requires the input to have the shape
|
| 1123 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
| 1124 |
+
# therefore we just need to keep the original shape
|
| 1125 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim)
|
| 1126 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 1127 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 1128 |
+
|
| 1129 |
+
if past_key_value is not None:
|
| 1130 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx)
|
| 1131 |
+
|
| 1132 |
+
# repeat k/v heads if n_kv_heads < n_heads
|
| 1133 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
| 1134 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
| 1135 |
+
dropout_rate = 0.0 if not self.training else self.attention_dropout
|
| 1136 |
+
|
| 1137 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
| 1138 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
| 1139 |
+
# cast them back in float16 just to be sure everything works as expected.
|
| 1140 |
+
input_dtype = query_states.dtype
|
| 1141 |
+
if input_dtype == torch.float32:
|
| 1142 |
+
if torch.is_autocast_enabled():
|
| 1143 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
| 1144 |
+
# Handle the case where the model is quantized
|
| 1145 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
| 1146 |
+
target_dtype = self.config._pre_quantization_dtype
|
| 1147 |
+
else:
|
| 1148 |
+
target_dtype = self.q_proj.weight.dtype
|
| 1149 |
+
|
| 1150 |
+
logger.warning_once(
|
| 1151 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
| 1152 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
| 1153 |
+
f" {target_dtype}."
|
| 1154 |
+
)
|
| 1155 |
+
|
| 1156 |
+
query_states = query_states.to(target_dtype)
|
| 1157 |
+
key_states = key_states.to(target_dtype)
|
| 1158 |
+
value_states = value_states.to(target_dtype)
|
| 1159 |
+
|
| 1160 |
+
# Reashape to the expected shape for Flash Attention
|
| 1161 |
+
key_states = key_states.transpose(1, 2)
|
| 1162 |
+
value_states = value_states.transpose(1, 2)
|
| 1163 |
+
|
| 1164 |
+
attn_output = _flash_attention_forward(
|
| 1165 |
+
query_states,
|
| 1166 |
+
key_states,
|
| 1167 |
+
value_states,
|
| 1168 |
+
attention_mask,
|
| 1169 |
+
q_len,
|
| 1170 |
+
dropout=dropout_rate,
|
| 1171 |
+
sliding_window=getattr(self.config, "sliding_window", None),
|
| 1172 |
+
is_causal=self.is_causal,
|
| 1173 |
+
use_top_left_mask=self._flash_attn_uses_top_left_mask,
|
| 1174 |
+
)
|
| 1175 |
+
|
| 1176 |
+
#attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
| 1177 |
+
attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.head_dim).contiguous()
|
| 1178 |
+
attn_output = self.o_proj(attn_output)
|
| 1179 |
+
|
| 1180 |
+
if not output_attentions:
|
| 1181 |
+
attn_weights = None
|
| 1182 |
+
|
| 1183 |
+
return attn_output, attn_weights, past_key_value
|
| 1184 |
+
|
| 1185 |
+
|
| 1186 |
+
# Adapted from transformers.models.mistral.modeling_mistral.MistralSdpaAttention with Mistral->Jamba
|
| 1187 |
+
#class JambaSdpaAttention(JambaAttention):
|
| 1188 |
+
class NemotronHSdpaAttention(NemotronHAttention):
|
| 1189 |
+
"""
|
| 1190 |
+
Jamba attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
|
| 1191 |
+
`JambaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
|
| 1192 |
+
SDPA API.
|
| 1193 |
+
"""
|
| 1194 |
+
|
| 1195 |
+
# Adapted from NemotronHAttention.forward
|
| 1196 |
+
def forward(
|
| 1197 |
+
self,
|
| 1198 |
+
hidden_states: torch.Tensor,
|
| 1199 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1200 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1201 |
+
past_key_value: Optional[HybridMambaAttentionDynamicCache] = None,
|
| 1202 |
+
output_attentions: bool = False,
|
| 1203 |
+
use_cache: bool = False,
|
| 1204 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 1205 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
| 1206 |
+
if output_attentions:
|
| 1207 |
+
# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
|
| 1208 |
+
logger.warning_once(
|
| 1209 |
+
"NemotronHModel is using NemotronHSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
|
| 1210 |
+
'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
| 1211 |
+
)
|
| 1212 |
+
return super().forward(
|
| 1213 |
+
hidden_states=hidden_states,
|
| 1214 |
+
attention_mask=attention_mask,
|
| 1215 |
+
position_ids=position_ids,
|
| 1216 |
+
past_key_value=past_key_value,
|
| 1217 |
+
output_attentions=output_attentions,
|
| 1218 |
+
use_cache=use_cache,
|
| 1219 |
+
)
|
| 1220 |
+
|
| 1221 |
+
bsz, q_len, _ = hidden_states.size()
|
| 1222 |
+
|
| 1223 |
+
query_states = self.q_proj(hidden_states)
|
| 1224 |
+
key_states = self.k_proj(hidden_states)
|
| 1225 |
+
value_states = self.v_proj(hidden_states)
|
| 1226 |
+
|
| 1227 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
| 1228 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 1229 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
| 1230 |
+
|
| 1231 |
+
if past_key_value is not None:
|
| 1232 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx)
|
| 1233 |
+
|
| 1234 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
| 1235 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
| 1236 |
+
|
| 1237 |
+
causal_mask = attention_mask
|
| 1238 |
+
if attention_mask is not None:
|
| 1239 |
+
causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
|
| 1240 |
+
|
| 1241 |
+
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
|
| 1242 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577.
|
| 1243 |
+
if query_states.device.type == "cuda" and attention_mask is not None:
|
| 1244 |
+
query_states = query_states.contiguous()
|
| 1245 |
+
key_states = key_states.contiguous()
|
| 1246 |
+
value_states = value_states.contiguous()
|
| 1247 |
+
|
| 1248 |
+
# We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
|
| 1249 |
+
# in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
|
| 1250 |
+
# The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
|
| 1251 |
+
is_causal = True if self.is_causal and causal_mask is None and q_len > 1 else False
|
| 1252 |
+
|
| 1253 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
| 1254 |
+
query_states,
|
| 1255 |
+
key_states,
|
| 1256 |
+
value_states,
|
| 1257 |
+
attn_mask=causal_mask,
|
| 1258 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
| 1259 |
+
is_causal=is_causal,
|
| 1260 |
+
)
|
| 1261 |
+
|
| 1262 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 1263 |
+
attn_output = attn_output.view(bsz, q_len, self.hidden_size)
|
| 1264 |
+
|
| 1265 |
+
attn_output = self.o_proj(attn_output)
|
| 1266 |
+
|
| 1267 |
+
return attn_output, None, past_key_value
|
| 1268 |
+
|
| 1269 |
+
|
| 1270 |
+
NEMOTRONH_ATTENTION_CLASSES = {
|
| 1271 |
+
"eager": NemotronHAttention,
|
| 1272 |
+
"flash_attention_2": NemotronHFlashAttention2,
|
| 1273 |
+
"sdpa": NemotronHSdpaAttention,
|
| 1274 |
+
}
|
| 1275 |
+
|
| 1276 |
+
# Copied from transformers.models.mamba.modeling_mamba2.Mamba2PreTrainedModel
|
| 1277 |
+
class NemotronHPreTrainedModel(PreTrainedModel):
|
| 1278 |
+
"""
|
| 1279 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 1280 |
+
models.
|
| 1281 |
+
"""
|
| 1282 |
+
|
| 1283 |
+
config_class = NemotronHConfig
|
| 1284 |
+
base_model_prefix = "backbone"
|
| 1285 |
+
_no_split_modules = ["NemotronHBlock"]
|
| 1286 |
+
supports_gradient_checkpointing = True
|
| 1287 |
+
_is_stateful = True
|
| 1288 |
+
|
| 1289 |
+
def _init_weights(self, module):
|
| 1290 |
+
"""Initialize the weights."""
|
| 1291 |
+
if isinstance(module, NemotronHMamba2Mixer):
|
| 1292 |
+
module.A_log._no_weight_decay = True
|
| 1293 |
+
module.D._no_weight_decay = True
|
| 1294 |
+
|
| 1295 |
+
dt = torch.exp(
|
| 1296 |
+
torch.rand(self.config.mamba_num_heads)
|
| 1297 |
+
* (math.log(self.config.time_step_max) - math.log(self.config.time_step_min))
|
| 1298 |
+
+ math.log(self.config.time_step_min)
|
| 1299 |
+
).clamp(min=self.config.time_step_floor)
|
| 1300 |
+
|
| 1301 |
+
# # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
|
| 1302 |
+
inv_dt = dt + torch.log(-torch.expm1(-dt))
|
| 1303 |
+
with torch.no_grad():
|
| 1304 |
+
module.dt_bias.copy_(inv_dt)
|
| 1305 |
+
module.dt_bias._no_reinit = True
|
| 1306 |
+
|
| 1307 |
+
if isinstance(module, nn.Linear):
|
| 1308 |
+
if module.bias is not None:
|
| 1309 |
+
if not getattr(module.bias, "_no_reinit", False):
|
| 1310 |
+
nn.init.zeros_(module.bias)
|
| 1311 |
+
elif isinstance(module, nn.Embedding):
|
| 1312 |
+
nn.init.normal_(module.weight, std=self.config.initializer_range)
|
| 1313 |
+
|
| 1314 |
+
# TODO: Check
|
| 1315 |
+
if self.config.rescale_prenorm_residual:
|
| 1316 |
+
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
|
| 1317 |
+
# > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
|
| 1318 |
+
# > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
|
| 1319 |
+
# > -- GPT-2 :: https://openai.com/blog/better-language-models/
|
| 1320 |
+
#
|
| 1321 |
+
# Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
|
| 1322 |
+
for name, p in module.named_parameters():
|
| 1323 |
+
if name in ["out_proj.weight"]:
|
| 1324 |
+
# Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
|
| 1325 |
+
# Following Pytorch init, except scale by 1/sqrt(2 * n_layer)
|
| 1326 |
+
# We need to reinit p since this code could be called multiple times
|
| 1327 |
+
# Having just p *= scale would repeatedly scale it down
|
| 1328 |
+
nn.init.kaiming_uniform_(p, a=math.sqrt(5))
|
| 1329 |
+
with torch.no_grad():
|
| 1330 |
+
p /= math.sqrt(self.config.num_hidden_layers)
|
| 1331 |
+
|
| 1332 |
+
|
| 1333 |
+
@dataclass
|
| 1334 |
+
# Copied from transformers.models.mamba.modeling_mamba2.Mamba2Output with MAMBA2->NemotronH,Mamba2->NemotronH
|
| 1335 |
+
class NemotronHOutput(ModelOutput):
|
| 1336 |
+
"""
|
| 1337 |
+
Class for the NemotronH model outputs.
|
| 1338 |
+
|
| 1339 |
+
Args:
|
| 1340 |
+
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
|
| 1341 |
+
Sequence of hidden-states at the output of the last layer of the model.
|
| 1342 |
+
cache_params (`HybridMambaAttentionDynamicCache`):
|
| 1343 |
+
The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
|
| 1344 |
+
avoid providing the old `input_ids`.
|
| 1345 |
+
|
| 1346 |
+
Includes both the State space model state matrices after the selective scan, and the Convolutional states
|
| 1347 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 1348 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 1349 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 1350 |
+
|
| 1351 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 1352 |
+
"""
|
| 1353 |
+
|
| 1354 |
+
last_hidden_state: Optional[torch.FloatTensor] = None
|
| 1355 |
+
cache_params: Optional[HybridMambaAttentionDynamicCache] = None
|
| 1356 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 1357 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 1358 |
+
|
| 1359 |
+
|
| 1360 |
+
@dataclass
|
| 1361 |
+
# Copied from transformers.models.mamba2.modeling_mamba2.MambaCausalLMOutput with Mamba2->NemotronH
|
| 1362 |
+
class NemotronHCausalLMOutput(ModelOutput):
|
| 1363 |
+
"""
|
| 1364 |
+
Base class for causal language model (or autoregressive) outputs.
|
| 1365 |
+
|
| 1366 |
+
Args:
|
| 1367 |
+
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
|
| 1368 |
+
Language modeling loss (for next-token prediction).
|
| 1369 |
+
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
| 1370 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
| 1371 |
+
cache_params (`HybridMambaAttentionDynamicCache`):
|
| 1372 |
+
The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
|
| 1373 |
+
avoid providing the old `input_ids`.
|
| 1374 |
+
|
| 1375 |
+
Includes both the State space model state matrices after the selective scan, and the Convolutional states
|
| 1376 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
| 1377 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
|
| 1378 |
+
one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
|
| 1379 |
+
|
| 1380 |
+
Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
|
| 1381 |
+
"""
|
| 1382 |
+
|
| 1383 |
+
loss: Optional[torch.FloatTensor] = None
|
| 1384 |
+
logits: Optional[torch.FloatTensor] = None
|
| 1385 |
+
cache_params: Optional[HybridMambaAttentionDynamicCache] = None
|
| 1386 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
| 1387 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
| 1388 |
+
|
| 1389 |
+
|
| 1390 |
+
NEMOTRONH_START_DOCSTRING = r"""
|
| 1391 |
+
|
| 1392 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
| 1393 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
| 1394 |
+
etc.)
|
| 1395 |
+
|
| 1396 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
| 1397 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
| 1398 |
+
and behavior.
|
| 1399 |
+
|
| 1400 |
+
Parameters:
|
| 1401 |
+
config ([`NemotronHConfig`]): Model configuration class with all the parameters of the model.
|
| 1402 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
| 1403 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
| 1404 |
+
"""
|
| 1405 |
+
|
| 1406 |
+
NEMOTRONH_INPUTS_DOCSTRING = r"""
|
| 1407 |
+
Args:
|
| 1408 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, input_ids_length)`, *optional*):
|
| 1409 |
+
Indices of input sequence tokens in the vocabulary.
|
| 1410 |
+
|
| 1411 |
+
If `cache_params.seqlen_offset>0`, only `input_ids` that do not have their past calculated should be passed as
|
| 1412 |
+
`input_ids`.
|
| 1413 |
+
|
| 1414 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
| 1415 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
| 1416 |
+
|
| 1417 |
+
[What are input IDs?](../glossary#input-ids)
|
| 1418 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
| 1419 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
| 1420 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
| 1421 |
+
model's internal embedding lookup matrix.
|
| 1422 |
+
position_ids (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1423 |
+
Indices of positions of each input sequence tokens in the position embeddings.
|
| 1424 |
+
cache_params (`HybridMambaAttentionDynamicCache`, *optional*):
|
| 1425 |
+
If passed along, the model uses the previous state in all the blocks (which will give the output for the
|
| 1426 |
+
`input_ids` provided as if the model add `state_input_ids + input_ids` as context).
|
| 1427 |
+
use_cache (`bool`, *optional*):
|
| 1428 |
+
If set to `True`, the `cache_params` is returned and can be used to quickly generate the next logits.
|
| 1429 |
+
output_attentions (`bool`, *optional*):
|
| 1430 |
+
Whether or not to return the attentions tensors of all attention layers.
|
| 1431 |
+
output_hidden_states (`bool`, *optional*):
|
| 1432 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
| 1433 |
+
more detail.
|
| 1434 |
+
return_dict (`bool`, *optional*):
|
| 1435 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
| 1436 |
+
cache_position (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
| 1437 |
+
The position of the current input in the cache. This is used to ensure that the cache is correctly updated.
|
| 1438 |
+
If `cache_params` is passed, `cache_position` should also be passed.
|
| 1439 |
+
attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1440 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
| 1441 |
+
|
| 1442 |
+
- 1 for tokens that are **not masked**,
|
| 1443 |
+
- 0 for tokens that are **masked**.
|
| 1444 |
+
|
| 1445 |
+
[What are attention masks?](../glossary#attention-mask)
|
| 1446 |
+
"""
|
| 1447 |
+
|
| 1448 |
+
|
| 1449 |
+
@add_start_docstrings(
|
| 1450 |
+
"The bare NemotronH Model transformer outputting raw hidden-states without any specific head on top.",
|
| 1451 |
+
NEMOTRONH_START_DOCSTRING,
|
| 1452 |
+
)
|
| 1453 |
+
class NemotronHModel(NemotronHPreTrainedModel):
|
| 1454 |
+
def __init__(self, config):
|
| 1455 |
+
super().__init__(config)
|
| 1456 |
+
|
| 1457 |
+
self.embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
|
| 1458 |
+
self.layers = nn.ModuleList([NemotronHBlock(config, layer_idx=idx) for idx in range(config.num_hidden_layers)])
|
| 1459 |
+
|
| 1460 |
+
self.gradient_checkpointing = False
|
| 1461 |
+
self.norm_f = NemotronHRMSNorm(config.hidden_size, eps=config.layer_norm_epsilon)
|
| 1462 |
+
# Initialize weights and apply final processing
|
| 1463 |
+
self._register_load_state_dict_pre_hook(self.load_hook)
|
| 1464 |
+
self.post_init()
|
| 1465 |
+
|
| 1466 |
+
def load_hook(self, state_dict, prefix, *args):
|
| 1467 |
+
for k in state_dict:
|
| 1468 |
+
if "embedding." in k:
|
| 1469 |
+
state_dict[k.replace("embedding.", "embeddings.")] = state_dict.pop(k)
|
| 1470 |
+
break
|
| 1471 |
+
|
| 1472 |
+
def get_input_embeddings(self):
|
| 1473 |
+
return self.embeddings
|
| 1474 |
+
|
| 1475 |
+
def set_input_embeddings(self, new_embeddings):
|
| 1476 |
+
self.embeddings = new_embeddings
|
| 1477 |
+
|
| 1478 |
+
@add_start_docstrings_to_model_forward(NEMOTRONH_INPUTS_DOCSTRING)
|
| 1479 |
+
@add_code_sample_docstrings(
|
| 1480 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1481 |
+
output_type=NemotronHOutput,
|
| 1482 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1483 |
+
)
|
| 1484 |
+
def forward(
|
| 1485 |
+
self,
|
| 1486 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1487 |
+
inputs_embeds: Optional[torch.LongTensor] = None,
|
| 1488 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1489 |
+
cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
|
| 1490 |
+
use_cache: Optional[bool] = None,
|
| 1491 |
+
output_attentions: Optional[bool] = None,
|
| 1492 |
+
output_hidden_states: Optional[bool] = None,
|
| 1493 |
+
return_dict: Optional[bool] = None,
|
| 1494 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 1495 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1496 |
+
**kwargs,
|
| 1497 |
+
) -> Union[Tuple, NemotronHOutput]:
|
| 1498 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1499 |
+
output_hidden_states = (
|
| 1500 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1501 |
+
)
|
| 1502 |
+
# use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 1503 |
+
use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
|
| 1504 |
+
|
| 1505 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1506 |
+
|
| 1507 |
+
if (input_ids is None) ^ (inputs_embeds is not None): # ^ is python for xor
|
| 1508 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 1509 |
+
|
| 1510 |
+
if inputs_embeds is None:
|
| 1511 |
+
inputs_embeds = self.embeddings(input_ids)
|
| 1512 |
+
|
| 1513 |
+
if self.gradient_checkpointing and self.training and use_cache:
|
| 1514 |
+
logger.warning_once(
|
| 1515 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
|
| 1516 |
+
)
|
| 1517 |
+
use_cache = False
|
| 1518 |
+
|
| 1519 |
+
# From zamba_modeling.py
|
| 1520 |
+
if use_cache and cache_params is None:
|
| 1521 |
+
logger.warning_once(
|
| 1522 |
+
"NemotronH requires an initialized `NemotronHHybridDynamicCache` to return a cache. None was "
|
| 1523 |
+
"provided, so no cache will be returned."
|
| 1524 |
+
)
|
| 1525 |
+
|
| 1526 |
+
hidden_states = inputs_embeds
|
| 1527 |
+
|
| 1528 |
+
if cache_position is None:
|
| 1529 |
+
cache_position = torch.arange(hidden_states.shape[1], device=hidden_states.device)
|
| 1530 |
+
if position_ids is None:
|
| 1531 |
+
position_ids = cache_position.unsqueeze(0)
|
| 1532 |
+
|
| 1533 |
+
causal_mask = self._update_causal_mask(attention_mask, inputs_embeds, cache_position)
|
| 1534 |
+
mamba_mask = self._update_mamba_mask(attention_mask, cache_position)
|
| 1535 |
+
|
| 1536 |
+
all_hidden_states = () if output_hidden_states else None
|
| 1537 |
+
all_self_attns = () if output_attentions else None
|
| 1538 |
+
# Until HERE
|
| 1539 |
+
|
| 1540 |
+
for layer_idx, mixer_block in enumerate(self.layers):
|
| 1541 |
+
# Depending on the layer type we opt for 2D base attention mask (Mamba) or 4D causal mask (Attention)
|
| 1542 |
+
if mixer_block.block_type == "mamba":
|
| 1543 |
+
layer_mask = mamba_mask
|
| 1544 |
+
elif mixer_block.block_type == "attention":
|
| 1545 |
+
layer_mask = causal_mask
|
| 1546 |
+
elif mixer_block.block_type in ["mlp", "moe"]:
|
| 1547 |
+
layer_mask = None
|
| 1548 |
+
else:
|
| 1549 |
+
raise ValueError(f"Invalid block_type: {self.block_type}")
|
| 1550 |
+
|
| 1551 |
+
if output_hidden_states:
|
| 1552 |
+
all_hidden_states += (hidden_states,)
|
| 1553 |
+
|
| 1554 |
+
if self.gradient_checkpointing and self.training:
|
| 1555 |
+
hidden_states = self._gradient_checkpointing_func(
|
| 1556 |
+
mixer_block.__call__, hidden_states, cache_params, cache_position, layer_mask
|
| 1557 |
+
)
|
| 1558 |
+
else:
|
| 1559 |
+
hidden_states = mixer_block(
|
| 1560 |
+
hidden_states,
|
| 1561 |
+
cache_params=cache_params,
|
| 1562 |
+
cache_position=cache_position,
|
| 1563 |
+
attention_mask=layer_mask,
|
| 1564 |
+
)
|
| 1565 |
+
|
| 1566 |
+
# TODO: Store attentions
|
| 1567 |
+
# if output_attentions:
|
| 1568 |
+
# if layer_outputs[1] is not None:
|
| 1569 |
+
# # append attentions only of attention layers. Mamba layers return `None` as the attention weights
|
| 1570 |
+
# all_self_attns += (layer_outputs[1],)
|
| 1571 |
+
|
| 1572 |
+
# TODO (Check): should it happen before the forward pass?
|
| 1573 |
+
# if output_hidden_states:
|
| 1574 |
+
# all_hidden_states = all_hidden_states + (hidden_states,)
|
| 1575 |
+
|
| 1576 |
+
hidden_states = self.norm_f(hidden_states)
|
| 1577 |
+
|
| 1578 |
+
if output_hidden_states:
|
| 1579 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
| 1580 |
+
|
| 1581 |
+
if not return_dict:
|
| 1582 |
+
return tuple(v for v in [hidden_states, cache_params, all_hidden_states] if v is not None)
|
| 1583 |
+
|
| 1584 |
+
return NemotronHOutput(
|
| 1585 |
+
last_hidden_state=hidden_states,
|
| 1586 |
+
cache_params=cache_params if use_cache else None,
|
| 1587 |
+
hidden_states=all_hidden_states,
|
| 1588 |
+
attentions=all_self_attns,
|
| 1589 |
+
)
|
| 1590 |
+
|
| 1591 |
+
# Copied from transformers.models.jamba.modeling_jamba.JambaModel._update_causal_mask
|
| 1592 |
+
def _update_causal_mask(self, attention_mask, input_tensor, cache_position):
|
| 1593 |
+
if self.config._attn_implementation == "flash_attention_2":
|
| 1594 |
+
if attention_mask is not None and 0.0 in attention_mask:
|
| 1595 |
+
return attention_mask
|
| 1596 |
+
return None
|
| 1597 |
+
|
| 1598 |
+
dtype, device = input_tensor.dtype, input_tensor.device
|
| 1599 |
+
min_dtype = torch.finfo(dtype).min
|
| 1600 |
+
sequence_length = input_tensor.shape[1]
|
| 1601 |
+
target_length = cache_position[-1] + 1
|
| 1602 |
+
|
| 1603 |
+
causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
|
| 1604 |
+
if sequence_length != 1:
|
| 1605 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)
|
| 1606 |
+
causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
|
| 1607 |
+
causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
|
| 1608 |
+
if attention_mask is not None:
|
| 1609 |
+
causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
|
| 1610 |
+
if attention_mask.dim() == 2:
|
| 1611 |
+
mask_length = attention_mask.shape[-1]
|
| 1612 |
+
padding_mask = causal_mask[..., :mask_length].eq(0.0) * attention_mask[:, None, None, :].eq(0.0)
|
| 1613 |
+
causal_mask[..., :mask_length] = causal_mask[..., :mask_length].masked_fill(padding_mask, min_dtype)
|
| 1614 |
+
|
| 1615 |
+
if (
|
| 1616 |
+
self.config._attn_implementation == "sdpa"
|
| 1617 |
+
and attention_mask is not None
|
| 1618 |
+
and attention_mask.device.type == "cuda"
|
| 1619 |
+
):
|
| 1620 |
+
# Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
|
| 1621 |
+
# using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
|
| 1622 |
+
# Details: https://github.com/pytorch/pytorch/issues/110213
|
| 1623 |
+
causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
|
| 1624 |
+
|
| 1625 |
+
return causal_mask
|
| 1626 |
+
|
| 1627 |
+
def _update_mamba_mask(self, attention_mask, cache_position):
|
| 1628 |
+
"""
|
| 1629 |
+
No need for zeroing states when
|
| 1630 |
+
1. Cached forward
|
| 1631 |
+
2. Attending to all inputs
|
| 1632 |
+
"""
|
| 1633 |
+
mamba_mask = attention_mask
|
| 1634 |
+
if cache_position[0] > 0 or (attention_mask is not None and torch.all(attention_mask == 1)):
|
| 1635 |
+
mamba_mask = None
|
| 1636 |
+
return mamba_mask
|
| 1637 |
+
|
| 1638 |
+
|
| 1639 |
+
@add_start_docstrings(
|
| 1640 |
+
"""
|
| 1641 |
+
The NEMOTRONH Model transformer with a language modeling head on top (linear layer with weights not tied to the input
|
| 1642 |
+
embeddings).
|
| 1643 |
+
""",
|
| 1644 |
+
NEMOTRONH_START_DOCSTRING,
|
| 1645 |
+
)
|
| 1646 |
+
class NemotronHForCausalLM(NemotronHPreTrainedModel, GenerationMixin):
|
| 1647 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 1648 |
+
_keys_to_ignore_on_load_missing = [r"mtp.*"]
|
| 1649 |
+
|
| 1650 |
+
def __init__(self, config):
|
| 1651 |
+
super().__init__(config)
|
| 1652 |
+
self.backbone = NemotronHModel(config)
|
| 1653 |
+
self.vocab_size = config.vocab_size
|
| 1654 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 1655 |
+
|
| 1656 |
+
if config.num_nextn_predict_layers > 0:
|
| 1657 |
+
self.mtp = NemotronHMultiTokenPredictor(config)
|
| 1658 |
+
|
| 1659 |
+
# Initialize weights and apply final processing
|
| 1660 |
+
self.post_init()
|
| 1661 |
+
|
| 1662 |
+
def get_input_embeddings(self):
|
| 1663 |
+
return self.backbone.get_input_embeddings()
|
| 1664 |
+
|
| 1665 |
+
def set_input_embeddings(self, new_embeddings):
|
| 1666 |
+
return self.backbone.set_input_embeddings(new_embeddings)
|
| 1667 |
+
|
| 1668 |
+
def get_output_embeddings(self):
|
| 1669 |
+
return self.lm_head
|
| 1670 |
+
|
| 1671 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1672 |
+
self.lm_head = new_embeddings
|
| 1673 |
+
|
| 1674 |
+
def get_decoder(self):
|
| 1675 |
+
return self.model
|
| 1676 |
+
|
| 1677 |
+
def set_decoder(self, decoder):
|
| 1678 |
+
self.model = decoder
|
| 1679 |
+
|
| 1680 |
+
def prepare_inputs_for_generation(
|
| 1681 |
+
self,
|
| 1682 |
+
input_ids,
|
| 1683 |
+
past_key_values=None,
|
| 1684 |
+
attention_mask=None,
|
| 1685 |
+
inputs_embeds=None,
|
| 1686 |
+
cache_position=None,
|
| 1687 |
+
position_ids=None,
|
| 1688 |
+
use_cache=True,
|
| 1689 |
+
**kwargs,
|
| 1690 |
+
):
|
| 1691 |
+
# Copy from https://github.com/huggingface/transformers/blob/main/src/transformers/models/jamba/modeling_jamba.py
|
| 1692 |
+
# Overwitten -- uses `cache_params` as opposed to `past_key_values`
|
| 1693 |
+
empty_past_kv = past_key_values is None
|
| 1694 |
+
|
| 1695 |
+
# If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
|
| 1696 |
+
# Exception 1: when passing input_embeds, input_ids may be missing entries
|
| 1697 |
+
# Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
|
| 1698 |
+
# Exception 3: with synced GPUs cache_position may go out of bounds, but we only want dummy token in that case.
|
| 1699 |
+
# (we can't check exception 3 while compiling)
|
| 1700 |
+
if not empty_past_kv:
|
| 1701 |
+
if (
|
| 1702 |
+
inputs_embeds is not None # Exception 1
|
| 1703 |
+
or cache_position[-1] >= input_ids.shape[1] # Exception 3
|
| 1704 |
+
):
|
| 1705 |
+
input_ids = input_ids[:, -cache_position.shape[0] :]
|
| 1706 |
+
elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
|
| 1707 |
+
input_ids = input_ids[:, cache_position]
|
| 1708 |
+
else:
|
| 1709 |
+
past_key_values = HybridMambaAttentionDynamicCache(
|
| 1710 |
+
self.config, input_ids.shape[0], self.dtype, device=self.device
|
| 1711 |
+
)
|
| 1712 |
+
|
| 1713 |
+
if attention_mask is not None and position_ids is None:
|
| 1714 |
+
# create position_ids on the fly for batch generation
|
| 1715 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
| 1716 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
| 1717 |
+
if not empty_past_kv:
|
| 1718 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
| 1719 |
+
|
| 1720 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
| 1721 |
+
if inputs_embeds is not None and empty_past_kv:
|
| 1722 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
| 1723 |
+
else:
|
| 1724 |
+
model_inputs = {"input_ids": input_ids.contiguous()} # `contiguous()` needed for compilation use cases
|
| 1725 |
+
|
| 1726 |
+
model_inputs.update(
|
| 1727 |
+
{
|
| 1728 |
+
"position_ids": position_ids,
|
| 1729 |
+
"past_key_values": past_key_values,
|
| 1730 |
+
"use_cache": use_cache,
|
| 1731 |
+
"attention_mask": attention_mask,
|
| 1732 |
+
"logits_to_keep": self.config.num_logits_to_keep,
|
| 1733 |
+
"cache_position": cache_position,
|
| 1734 |
+
}
|
| 1735 |
+
)
|
| 1736 |
+
return model_inputs
|
| 1737 |
+
|
| 1738 |
+
@add_start_docstrings_to_model_forward(NEMOTRONH_INPUTS_DOCSTRING)
|
| 1739 |
+
@add_code_sample_docstrings(
|
| 1740 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
| 1741 |
+
output_type=NemotronHCausalLMOutput,
|
| 1742 |
+
config_class=_CONFIG_FOR_DOC,
|
| 1743 |
+
)
|
| 1744 |
+
def forward(
|
| 1745 |
+
self,
|
| 1746 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1747 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1748 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1749 |
+
cache_params: Optional[HybridMambaAttentionDynamicCache] = None,
|
| 1750 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1751 |
+
output_attentions: Optional[bool] = None,
|
| 1752 |
+
output_hidden_states: Optional[bool] = None,
|
| 1753 |
+
return_dict: Optional[bool] = None,
|
| 1754 |
+
use_cache: Optional[bool] = None,
|
| 1755 |
+
cache_position: Optional[torch.Tensor] = None,
|
| 1756 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1757 |
+
**kwargs, # for now we need this for generation
|
| 1758 |
+
) -> Union[Tuple, NemotronHCausalLMOutput]:
|
| 1759 |
+
r"""
|
| 1760 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1761 |
+
Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
|
| 1762 |
+
`labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
|
| 1763 |
+
are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
|
| 1764 |
+
"""
|
| 1765 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1766 |
+
|
| 1767 |
+
output_hidden_states = (
|
| 1768 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1769 |
+
)
|
| 1770 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1771 |
+
|
| 1772 |
+
nemotron_h_outputs = self.backbone(
|
| 1773 |
+
input_ids,
|
| 1774 |
+
cache_params=cache_params,
|
| 1775 |
+
inputs_embeds=inputs_embeds,
|
| 1776 |
+
output_attentions=output_attentions,
|
| 1777 |
+
output_hidden_states=output_hidden_states,
|
| 1778 |
+
return_dict=return_dict,
|
| 1779 |
+
use_cache=use_cache,
|
| 1780 |
+
cache_position=cache_position,
|
| 1781 |
+
attention_mask=attention_mask,
|
| 1782 |
+
)
|
| 1783 |
+
hidden_states = nemotron_h_outputs[0]
|
| 1784 |
+
|
| 1785 |
+
# TODO: Check zamba_modeling.py: https://github.com/huggingface/transformers/blob/d7188ba600e36d3fd191b12e19f1b3bb81a8404f/src/transformers/models/zamba/modeling_zamba.py#L1284C1-L1286C2
|
| 1786 |
+
#logits = self.lm_head(hidden_states.to(self.lm_head.weight.dtype)).float()
|
| 1787 |
+
logits = self.lm_head(hidden_states.to(self.lm_head.weight.dtype)).float()
|
| 1788 |
+
|
| 1789 |
+
loss = None
|
| 1790 |
+
if labels is not None:
|
| 1791 |
+
# move labels to correct device to enable model parallelism
|
| 1792 |
+
labels = labels.to(logits.device)
|
| 1793 |
+
# Shift so that tokens < n predict n
|
| 1794 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 1795 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 1796 |
+
# Flatten the tokens
|
| 1797 |
+
loss_fct = CrossEntropyLoss()
|
| 1798 |
+
loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
|
| 1799 |
+
|
| 1800 |
+
if not return_dict:
|
| 1801 |
+
output = (logits,) + nemotron_h_outputs[1:]
|
| 1802 |
+
return ((loss,) + output) if loss is not None else output
|
| 1803 |
+
|
| 1804 |
+
return NemotronHCausalLMOutput(
|
| 1805 |
+
loss=loss,
|
| 1806 |
+
logits=logits,
|
| 1807 |
+
cache_params=nemotron_h_outputs.cache_params,
|
| 1808 |
+
hidden_states=nemotron_h_outputs.hidden_states,
|
| 1809 |
+
attentions=nemotron_h_outputs.attentions,
|
| 1810 |
+
)
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"pad_token": {
|
| 17 |
+
"content": "<|im_end|>",
|
| 18 |
+
"lstrip": false,
|
| 19 |
+
"normalized": false,
|
| 20 |
+
"rstrip": false,
|
| 21 |
+
"single_word": false
|
| 22 |
+
},
|
| 23 |
+
"unk_token": {
|
| 24 |
+
"content": "<unk>",
|
| 25 |
+
"lstrip": false,
|
| 26 |
+
"normalized": false,
|
| 27 |
+
"rstrip": false,
|
| 28 |
+
"single_word": false
|
| 29 |
+
}
|
| 30 |
+
}
|
tokenizer.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:623c34567aebb18582765289fbe23d901c62704d6518d71866e0e58db892b5b7
|
| 3 |
+
size 17077484
|
tokenizer_config.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
ultra_v3_reasoning_parser.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from vllm.reasoning.abs_reasoning_parsers import ReasoningParserManager
|
| 2 |
+
from vllm.reasoning.deepseek_r1_reasoning_parser import DeepSeekR1ReasoningParser
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
@ReasoningParserManager.register_module("ultra_v3")
|
| 6 |
+
class UltraV3ReasoningParser(DeepSeekR1ReasoningParser):
|
| 7 |
+
def extract_reasoning(self, model_output, request):
|
| 8 |
+
reasoning_content, final_content = super().extract_reasoning(
|
| 9 |
+
model_output, request
|
| 10 |
+
)
|
| 11 |
+
if (
|
| 12 |
+
hasattr(request, "chat_template_kwargs")
|
| 13 |
+
and request.chat_template_kwargs
|
| 14 |
+
and (
|
| 15 |
+
request.chat_template_kwargs.get("enable_thinking") is False
|
| 16 |
+
or request.chat_template_kwargs.get("force_nonempty_content") is True
|
| 17 |
+
)
|
| 18 |
+
and final_content is None
|
| 19 |
+
):
|
| 20 |
+
"""
|
| 21 |
+
The original `deepseek_r1` reasoning parser this inherits from will automatically put everything in the reasoning content when it cannot parse out reasoning. This was fine for the DeepSeek R1 model that was not intended to be used without reasoning.
|
| 22 |
+
1. Since the Nemotron 3 Nano and Super both have thinking off modes modulated by "enable_thinking=false" in the chat template kwargs, this change instead which will properly place the content in cases where there is no thinking enabled via config.
|
| 23 |
+
2. There are rare cases where the model will output only reasoning without an end-think token `</think>` (e.g. reasoning exceeds max length), which results in empty content returned. End users may want to unilaterally avoid such cases and always have a content response even if the model does not finish its reasoning.
|
| 24 |
+
"""
|
| 25 |
+
# Put all nonempty content into the content, rather than return content
|
| 26 |
+
reasoning_content, final_content = None, reasoning_content
|
| 27 |
+
|
| 28 |
+
return reasoning_content, final_content
|