t1101675 commited on
Commit
f62ec09
·
verified ·
1 Parent(s): a241db3

Upload folder using huggingface_hub

Browse files
.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
added_tokens.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "</tool_call>": 151658,
3
+ "<tool_call>": 151657,
4
+ "<|box_end|>": 151649,
5
+ "<|box_start|>": 151648,
6
+ "<|endoftext|>": 151643,
7
+ "<|file_sep|>": 151664,
8
+ "<|fim_middle|>": 151660,
9
+ "<|fim_pad|>": 151662,
10
+ "<|fim_prefix|>": 151659,
11
+ "<|fim_suffix|>": 151661,
12
+ "<|im_end|>": 151645,
13
+ "<|im_start|>": 151644,
14
+ "<|image_pad|>": 151655,
15
+ "<|object_ref_end|>": 151647,
16
+ "<|object_ref_start|>": 151646,
17
+ "<|quad_end|>": 151651,
18
+ "<|quad_start|>": 151650,
19
+ "<|repo_name|>": 151663,
20
+ "<|video_pad|>": 151656,
21
+ "<|vision_end|>": 151653,
22
+ "<|vision_pad|>": 151654,
23
+ "<|vision_start|>": 151652
24
+ }
chat_template.jinja ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- if tools %}
2
+ {{- '<|im_start|>system\n' }}
3
+ {%- if messages[0]['role'] == 'system' %}
4
+ {{- messages[0]['content'] }}
5
+ {%- else %}
6
+ {{- 'You are a helpful assistant.' }}
7
+ {%- endif %}
8
+ {{- "\n\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
9
+ {%- for tool in tools %}
10
+ {{- "\n" }}
11
+ {{- tool | tojson }}
12
+ {%- endfor %}
13
+ {{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
14
+ {%- else %}
15
+ {%- if messages[0]['role'] == 'system' %}
16
+ {{- '<|im_start|>system\n' + messages[0]['content'] + '<|im_end|>\n' }}
17
+ {%- else %}
18
+ {{- '<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n' }}
19
+ {%- endif %}
20
+ {%- endif %}
21
+ {%- for message in messages %}
22
+ {%- if (message.role == "user") or (message.role == "system" and not loop.first) or (message.role == "assistant" and not message.tool_calls) %}
23
+ {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' + '\n' }}
24
+ {%- elif message.role == "assistant" %}
25
+ {{- '<|im_start|>' + message.role }}
26
+ {%- if message.content %}
27
+ {{- '\n' + message.content }}
28
+ {%- endif %}
29
+ {%- for tool_call in message.tool_calls %}
30
+ {%- if tool_call.function is defined %}
31
+ {%- set tool_call = tool_call.function %}
32
+ {%- endif %}
33
+ {{- '\n<tool_call>\n{"name": "' }}
34
+ {{- tool_call.name }}
35
+ {{- '", "arguments": ' }}
36
+ {{- tool_call.arguments | tojson }}
37
+ {{- '}\n</tool_call>' }}
38
+ {%- endfor %}
39
+ {{- '<|im_end|>\n' }}
40
+ {%- elif message.role == "tool" %}
41
+ {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != "tool") %}
42
+ {{- '<|im_start|>user' }}
43
+ {%- endif %}
44
+ {{- '\n<tool_response>\n' }}
45
+ {{- message.content }}
46
+ {{- '\n</tool_response>' }}
47
+ {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
48
+ {{- '<|im_end|>\n' }}
49
+ {%- endif %}
50
+ {%- endif %}
51
+ {%- endfor %}
52
+ {%- if add_generation_prompt %}
53
+ {{- '<|im_start|>assistant\n' }}
54
+ {%- endif %}
config.json ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "JetNemotronForCausalLM"
4
+ ],
5
+ "attention_dropout": 0.0,
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_jet_nemotron.JetNemotronConfig",
8
+ "AutoModelForCausalLM": "modeling_jet_nemotron.JetNemotronForCausalLM"
9
+ },
10
+ "bos_token_id": 151643,
11
+ "efficient_attention_config": {
12
+ "jet": {
13
+ "conv_size": 4,
14
+ "dconv_generator_reduction": 8,
15
+ "dconv_implementation": "triton",
16
+ "expand_v": 2,
17
+ "head_dim": 128,
18
+ "mode": "chunk",
19
+ "norm_eps": "1e-5",
20
+ "num_heads": 16
21
+ },
22
+ "swa": {
23
+ "window_size": 2048
24
+ }
25
+ },
26
+ "eos_token_id": 151643,
27
+ "hidden_act": "silu",
28
+ "hidden_size": 2048,
29
+ "initializer_range": 0.02,
30
+ "intermediate_size": 11008,
31
+ "layer_types": [
32
+ "jet",
33
+ "jet",
34
+ "jet",
35
+ "jet",
36
+ "jet",
37
+ "swa",
38
+ "jet",
39
+ "jet",
40
+ "jet",
41
+ "jet",
42
+ "jet",
43
+ "jet",
44
+ "jet",
45
+ "jet",
46
+ "jet",
47
+ "jet",
48
+ "swa",
49
+ "attn",
50
+ "jet",
51
+ "swa",
52
+ "attn",
53
+ "swa",
54
+ "swa",
55
+ "jet",
56
+ "jet",
57
+ "swa",
58
+ "jet",
59
+ "swa",
60
+ "jet",
61
+ "jet",
62
+ "jet",
63
+ "jet",
64
+ "attn",
65
+ "jet",
66
+ "jet",
67
+ "jet"
68
+ ],
69
+ "max_position_embeddings": 32768,
70
+ "max_window_layers": 36,
71
+ "model_type": "jet_nemotron",
72
+ "num_attention_heads": 16,
73
+ "num_hidden_layers": 36,
74
+ "num_key_value_heads": 2,
75
+ "rms_norm_eps": 1e-06,
76
+ "rope_scaling": null,
77
+ "rope_theta": 1000000.0,
78
+ "tie_word_embeddings": true,
79
+ "torch_dtype": "bfloat16",
80
+ "transformers_version": "4.51.3",
81
+ "use_cache": true,
82
+ "use_mrope": false,
83
+ "vocab_size": 151936
84
+ }
configuration_jet_nemotron.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ # This file is modified from https://github.com/huggingface/transformers/blob/main/src/transformers/models/qwen2/configuration_qwen2.py
18
+
19
+ """Jet-Nemotron model configuration"""
20
+
21
+ from transformers.configuration_utils import PretrainedConfig
22
+ from transformers.modeling_rope_utils import rope_config_validation
23
+ from transformers.utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+
29
+ class JetNemotronConfig(PretrainedConfig):
30
+ r"""
31
+ This is the configuration class to store the configuration of a [`JetModel`]. It is used to instantiate a
32
+ Jet model according to the specified arguments, defining the model architecture.
33
+
34
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
35
+ documentation from [`PretrainedConfig`] for more information.
36
+
37
+
38
+ Args:
39
+ vocab_size (`int`, *optional*, defaults to 151936):
40
+ Vocabulary size of the Jet-Nemotron model. Defines the number of different tokens that can be represented by the
41
+ `inputs_ids` passed when calling [`JetModel`]
42
+ hidden_size (`int`, *optional*, defaults to 4096):
43
+ Dimension of the hidden representations.
44
+ intermediate_size (`int`, *optional*, defaults to 22016):
45
+ Dimension of the MLP representations.
46
+ num_hidden_layers (`int`, *optional*, defaults to 32):
47
+ Number of hidden layers in the Transformer encoder.
48
+ num_attention_heads (`int`, *optional*, defaults to 32):
49
+ Number of attention heads for each attention layer in the Transformer encoder.
50
+ num_key_value_heads (`int`, *optional*, defaults to 32):
51
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
52
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
53
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
54
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
55
+ by meanpooling all the original heads within that group. For more details checkout [this
56
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `32`.
57
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
58
+ The non-linear activation function (function or string) in the decoder.
59
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
60
+ The maximum sequence length that this model might ever be used with.
61
+ initializer_range (`float`, *optional*, defaults to 0.02):
62
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
63
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
64
+ The epsilon used by the rms normalization layers.
65
+ use_cache (`bool`, *optional*, defaults to `True`):
66
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
67
+ relevant if `config.is_decoder=True`.
68
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
69
+ Whether the model's input and output word embeddings should be tied.
70
+ rope_theta (`float`, *optional*, defaults to 10000.0):
71
+ The base period of the RoPE embeddings.
72
+ rope_scaling (`Dict`, *optional*):
73
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
74
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
75
+ accordingly.
76
+ Expected contents:
77
+ `rope_type` (`str`):
78
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
79
+ 'llama3'], with 'default' being the original RoPE implementation.
80
+ `factor` (`float`, *optional*):
81
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
82
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
83
+ original maximum pre-trained length.
84
+ `original_max_position_embeddings` (`int`, *optional*):
85
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
86
+ pretraining.
87
+ `attention_factor` (`float`, *optional*):
88
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
89
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
90
+ `factor` field to infer the suggested value.
91
+ `beta_fast` (`float`, *optional*):
92
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
93
+ ramp function. If unspecified, it defaults to 32.
94
+ `beta_slow` (`float`, *optional*):
95
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
96
+ ramp function. If unspecified, it defaults to 1.
97
+ `short_factor` (`List[float]`, *optional*):
98
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
99
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
100
+ size divided by the number of attention heads divided by 2
101
+ `long_factor` (`List[float]`, *optional*):
102
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
103
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
104
+ size divided by the number of attention heads divided by 2
105
+ `low_freq_factor` (`float`, *optional*):
106
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
107
+ `high_freq_factor` (`float`, *optional*):
108
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
109
+ attention_dropout (`float`, *optional*, defaults to 0.0):
110
+ The dropout ratio for the attention probabilities.
111
+
112
+ ```python
113
+ >>> from transformers import JetModel, JetConfig
114
+
115
+ >>> # Initializing a Jet-Nemotron style configuration
116
+ >>> configuration = JetConfig()
117
+
118
+ >>> # Initializing a model from the Jet-Nemotron-2B style configuration
119
+ >>> model = Jet-Nemotron-Model(configuration)
120
+
121
+ >>> # Accessing the model configuration
122
+ >>> configuration = model.config
123
+ ```"""
124
+
125
+ model_type = "jet_nemotron"
126
+ keys_to_ignore_at_inference = ["past_key_values"]
127
+
128
+ def __init__(
129
+ self,
130
+ vocab_size=151936,
131
+ hidden_size=1536,
132
+ intermediate_size=8960,
133
+ num_hidden_layers=28,
134
+ num_attention_heads=12,
135
+ num_key_value_heads=2,
136
+ hidden_act="silu",
137
+ max_position_embeddings=32768,
138
+ initializer_range=0.02,
139
+ rms_norm_eps=1e-6,
140
+ use_cache=True,
141
+ tie_word_embeddings=True,
142
+ rope_theta=1000000.0,
143
+ rope_scaling=None,
144
+ attention_dropout=0.0,
145
+ layer_types=None,
146
+ efficient_attention_config=None,
147
+ **kwargs,
148
+ ):
149
+ self.vocab_size = vocab_size
150
+ self.max_position_embeddings = max_position_embeddings
151
+ self.hidden_size = hidden_size
152
+ self.intermediate_size = intermediate_size
153
+ self.num_hidden_layers = num_hidden_layers
154
+ self.num_attention_heads = num_attention_heads
155
+
156
+ # for backward compatibility
157
+ if num_key_value_heads is None:
158
+ num_key_value_heads = num_attention_heads
159
+
160
+ self.num_key_value_heads = num_key_value_heads
161
+ self.hidden_act = hidden_act
162
+ self.initializer_range = initializer_range
163
+ self.rms_norm_eps = rms_norm_eps
164
+ self.use_cache = use_cache
165
+ self.rope_theta = rope_theta
166
+ self.rope_scaling = rope_scaling
167
+ self.attention_dropout = attention_dropout
168
+ if layer_types is None:
169
+ self.layer_types = ["attn"] * num_hidden_layers
170
+ elif isinstance(layer_types, str):
171
+ self.layer_types = eval(layer_types)
172
+ else:
173
+ self.layer_types = layer_types
174
+ # Validate the correctness of rotary position embeddings parameters
175
+ # BC: if there is a 'type' field, move it to 'rope_type'.
176
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
177
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
178
+ rope_config_validation(self)
179
+
180
+ self.efficient_attention_config = efficient_attention_config
181
+
182
+ super().__init__(
183
+ tie_word_embeddings=tie_word_embeddings,
184
+ **kwargs,
185
+ )
dconv_fwd_cache.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ import torch
18
+ import triton
19
+ import triton.language as tl
20
+ from einops import rearrange
21
+ import torch.nn.functional as F
22
+ from torch.autograd import Function
23
+
24
+ # Helper function to ensure tensors are contiguous for Triton
25
+ def ensure_contiguous(t: torch.Tensor) -> torch.Tensor:
26
+ return t if t.is_contiguous() else t.contiguous()
27
+
28
+ # --- Forward Kernel (modified for optional cache) ---
29
+ @triton.jit
30
+ def _dynamic_conv_fwd_kernel(
31
+ X_ptr, K_ptr, Out_ptr,
32
+ Cache_ptr, # New: Pointer to cache tensor
33
+ B, T, D, T_CACHE: tl.constexpr, # New: T is shape of x, T_CACHE is shape of cache
34
+ X_stride_b, X_stride_t, X_stride_d,
35
+ K_stride_b, K_stride_t, K_stride_d, K_stride_w,
36
+ Out_stride_b, Out_stride_t, Out_stride_d,
37
+ Cache_stride_b, Cache_stride_t, Cache_stride_d, # New: Strides for cache tensor
38
+ W: tl.constexpr,
39
+ BLOCK_SIZE_D: tl.constexpr,
40
+ ):
41
+ pid_batch_time = tl.program_id(0) # Covers B * T_out
42
+ pid_d_block = tl.program_id(1)
43
+
44
+ # T here is the time dimension of x and Out
45
+ batch_idx = tl.cast(pid_batch_time // T, tl.int64)
46
+ time_idx = pid_batch_time % T # Current output time step for x (0 to T-1)
47
+
48
+ offs_d = pid_d_block * BLOCK_SIZE_D + tl.arange(0, BLOCK_SIZE_D)
49
+ d_mask = offs_d < D
50
+
51
+ accumulator = tl.zeros((BLOCK_SIZE_D,), dtype=tl.float32)
52
+ offs_w = tl.arange(0, W) # Kernel window offsets [0, 1, ..., W-1]
53
+
54
+ # Load Kernels (kernels are aligned with x's T dimension)
55
+ # K_ptr is indexed by time_idx which is the output time relative to x's start
56
+ k_ptrs = K_ptr + (batch_idx * K_stride_b + time_idx * K_stride_t +
57
+ offs_d[:, None] * K_stride_d + offs_w[None, :] * K_stride_w)
58
+ k_vals = tl.load(k_ptrs, mask=d_mask[:, None], other=0.0) # Shape: [BLOCK_SIZE_D, W]
59
+
60
+ # --- Load Input from conceptual [Cache, X] tensor ---
61
+ # `time_idx` is the current output time step (0 to T-1, where T is x.shape[1])
62
+ # `offs_w` is [0, ..., W-1]
63
+ # Convolution input time indices relative to the *start of x*:
64
+ # e.g., for W=3, offs_w - W + 1 gives [-2, -1, 0]
65
+ # so input_time_indices_rel_to_x_start are [time_idx-2, time_idx-1, time_idx]
66
+ input_time_indices_rel_to_x_start = time_idx + offs_w - W + 1 # Shape: [W]
67
+
68
+ # Effective input time indices in the conceptual [Cache, X] sequence:
69
+ # These indices range from 0 (start of cache) to T_CACHE + T - 1 (end of x)
70
+ eff_t_indices = input_time_indices_rel_to_x_start + T_CACHE # Shape: [W]
71
+
72
+ # Overall mask for valid time indices within the conceptual [Cache, X] tensor
73
+ # Total effective length is T_CACHE (for cache) + T (for x)
74
+ eff_t_valid_mask = (eff_t_indices >= 0) & (eff_t_indices < (T_CACHE + T)) # Shape: [W]
75
+
76
+ # --- Load from Cache ---
77
+ # Condition for loading from cache: index is valid AND index < T_CACHE
78
+ # (eff_t_indices are 0-indexed from the start of the cache)
79
+ cache_load_time_mask = eff_t_valid_mask & (eff_t_indices < T_CACHE) # Shape: [W]
80
+ cache_ptr_indices = eff_t_indices # Use directly if in cache range
81
+
82
+ cache_ptrs = Cache_ptr + (batch_idx * Cache_stride_b +
83
+ cache_ptr_indices[None, :] * Cache_stride_t +
84
+ offs_d[:, None] * Cache_stride_d)
85
+ cache_final_load_mask = d_mask[:, None] & cache_load_time_mask[None, :] # Shape: [BLOCK_SIZE_D, W]
86
+ vals_from_cache = tl.load(cache_ptrs, mask=cache_final_load_mask, other=0.0) # Shape: [BLOCK_SIZE_D, W]
87
+
88
+ # --- Load from X ---
89
+ # Condition for loading from X: index is valid AND index >= T_CACHE
90
+ x_load_time_mask = eff_t_valid_mask & (eff_t_indices >= T_CACHE) # Shape: [W]
91
+ # Adjust indices for X_ptr: X_ptr expects indices from 0 to T-1 (relative to start of x)
92
+ x_ptr_indices = eff_t_indices - T_CACHE # Shape: [W]
93
+
94
+ x_ptrs = X_ptr + (batch_idx * X_stride_b +
95
+ x_ptr_indices[None, :] * X_stride_t +
96
+ offs_d[:, None] * X_stride_d)
97
+ x_final_load_mask = d_mask[:, None] & x_load_time_mask[None, :] # Shape: [BLOCK_SIZE_D, W]
98
+ vals_from_x = tl.load(x_ptrs, mask=x_final_load_mask, other=0.0) # Shape: [BLOCK_SIZE_D, W]
99
+
100
+ # Combine values. Masks ensure only one source contributes non-zero per element.
101
+ # If T_CACHE == 0, cache_load_time_mask is all False, so vals_from_cache is 0.0.
102
+ x_input_vals = vals_from_cache + vals_from_x # Shape: [BLOCK_SIZE_D, W]
103
+
104
+ # Compute and Accumulate
105
+ product = k_vals * x_input_vals # Element-wise product
106
+ accumulator += tl.sum(product, axis=1) # Sum over W dimension
107
+
108
+ # Store Result
109
+ out_ptrs = Out_ptr + (batch_idx * Out_stride_b + time_idx * Out_stride_t +
110
+ offs_d * Out_stride_d)
111
+ tl.store(out_ptrs, accumulator, mask=d_mask)
112
+
113
+ # --- Backward Kernel for Input Gradient (dX) ---
114
+ @triton.jit
115
+ def _dynamic_conv_bwd_dx_kernel(
116
+ GradOut_ptr, K_ptr, GradX_ptr, # Note: GradX is accumulated into
117
+ B, T, D,
118
+ GradOut_stride_b, GradOut_stride_t, GradOut_stride_d,
119
+ K_stride_b, K_stride_t, K_stride_d, K_stride_w,
120
+ GradX_stride_b, GradX_stride_t, GradX_stride_d,
121
+ W: tl.constexpr,
122
+ BLOCK_SIZE_D: tl.constexpr,
123
+ ):
124
+ """
125
+ Computes gradient w.r.t. input X.
126
+ Grid: (B * T, cdiv(D, BLOCK_SIZE_D)) - covering GradX output
127
+ GradX[b, t_x, d] = sum_{w=0}^{W-1} GradOut[b, t, d] * K[b, t, d, w]
128
+ where t = t_x + W - 1 - w
129
+ """
130
+ pid_batch_time_x = tl.program_id(0) # Covers B * T for output GradX
131
+ pid_d_block = tl.program_id(1)
132
+
133
+ batch_idx = pid_batch_time_x // T
134
+ time_idx_x = pid_batch_time_x % T # This is t_x
135
+
136
+ offs_d = pid_d_block * BLOCK_SIZE_D + tl.arange(0, BLOCK_SIZE_D)
137
+ d_mask = offs_d < D
138
+
139
+ # Accumulator for GradX elements
140
+ accumulator = tl.zeros((BLOCK_SIZE_D,), dtype=tl.float32)
141
+ offs_w = tl.arange(0, W) # [W]
142
+
143
+ # Loop over W to accumulate contributions
144
+ # Calculate the 't' index needed for GradOut and K based on t_x and w
145
+ # t = t_x + W - 1 - w
146
+ t_k_gradout_offs = time_idx_x + W - 1 - offs_w # Shape [W]
147
+
148
+ # Mask for valid 't' indices [0, T)
149
+ t_k_gradout_mask = (t_k_gradout_offs >= 0) & (t_k_gradout_offs < T) # Shape [W]
150
+
151
+ # --- Load GradOut ---
152
+ # Pointers shape: [BLOCK_SIZE_D, W]
153
+ gradout_ptrs = GradOut_ptr + (batch_idx * GradOut_stride_b +
154
+ t_k_gradout_offs[None, :] * GradOut_stride_t +
155
+ offs_d[:, None] * GradOut_stride_d)
156
+ # Combined mask for loading GradOut (valid D and valid t)
157
+ gradout_load_mask = d_mask[:, None] & t_k_gradout_mask[None, :]
158
+ # Shape: [BLOCK_SIZE_D, W]
159
+ gradout_vals = tl.load(gradout_ptrs, mask=gradout_load_mask, other=0.0)
160
+
161
+ # --- Load Kernels ---
162
+ # Pointers shape: [BLOCK_SIZE_D, W]
163
+ k_ptrs = K_ptr + (batch_idx * K_stride_b +
164
+ t_k_gradout_offs[None, :] * K_stride_t +
165
+ offs_d[:, None] * K_stride_d +
166
+ offs_w[None, :] * K_stride_w) # Index K with 't' and 'w'
167
+ # Combined mask for loading K (valid D and valid t)
168
+ k_load_mask = d_mask[:, None] & t_k_gradout_mask[None, :]
169
+ # Shape: [BLOCK_SIZE_D, W]
170
+ k_vals = tl.load(k_ptrs, mask=k_load_mask, other=0.0)
171
+
172
+ # --- Compute product and accumulate ---
173
+ # Shape: [BLOCK_SIZE_D, W]
174
+ product = gradout_vals * k_vals
175
+ # Sum contributions over the W dimension
176
+ accumulator += tl.sum(product, axis=1) # Shape: [BLOCK_SIZE_D]
177
+
178
+ # --- Store accumulated gradients ---
179
+ gradx_ptrs = GradX_ptr + (batch_idx * GradX_stride_b +
180
+ time_idx_x * GradX_stride_t +
181
+ offs_d * GradX_stride_d)
182
+ tl.store(gradx_ptrs, accumulator, mask=d_mask)
183
+
184
+
185
+ # --- Backward Kernel for Kernel Gradient (dK) ---
186
+ @triton.jit
187
+ def _dynamic_conv_bwd_dk_kernel(
188
+ GradOut_ptr, X_ptr, GradK_ptr, # Note: GradK is written directly
189
+ B, T, D,
190
+ GradOut_stride_b, GradOut_stride_t, GradOut_stride_d,
191
+ X_stride_b, X_stride_t, X_stride_d,
192
+ GradK_stride_b, GradK_stride_t, GradK_stride_d, GradK_stride_w,
193
+ W: tl.constexpr,
194
+ BLOCK_SIZE_D: tl.constexpr,
195
+ ):
196
+ """
197
+ Computes gradient w.r.t. kernels K.
198
+ Grid: (B * T, cdiv(D, BLOCK_SIZE_D)) - covering GradK output dims B, T, D
199
+ GradK[b, t, d, w] = GradOut[b, t, d] * X[b, t + w - W + 1, d]
200
+ """
201
+ pid_batch_time = tl.program_id(0) # Covers B * T for output GradK
202
+ pid_d_block = tl.program_id(1)
203
+
204
+ batch_idx = pid_batch_time // T
205
+ time_idx = pid_batch_time % T # This is 't' for GradK and GradOut
206
+
207
+ offs_d = pid_d_block * BLOCK_SIZE_D + tl.arange(0, BLOCK_SIZE_D)
208
+ d_mask = offs_d < D
209
+
210
+ offs_w = tl.arange(0, W) # [W]
211
+
212
+ # --- Load GradOut ---
213
+ # Pointers shape: [BLOCK_SIZE_D] (only depends on b, t, d)
214
+ gradout_ptrs = GradOut_ptr + (batch_idx * GradOut_stride_b +
215
+ time_idx * GradOut_stride_t +
216
+ offs_d * GradOut_stride_d)
217
+ # Shape: [BLOCK_SIZE_D]
218
+ gradout_vals = tl.load(gradout_ptrs, mask=d_mask, other=0.0)
219
+
220
+ # --- Load Input X with implicit padding ---
221
+ # Calculate X's time index: t_x = t + w - W + 1
222
+ t_in_offs = time_idx + offs_w - W + 1 # Shape [W]
223
+ # Mask for valid t_x index [0, T)
224
+ t_in_mask = (t_in_offs >= 0) & (t_in_offs < T) # Shape [W]
225
+
226
+ # Pointers shape: [BLOCK_SIZE_D, W]
227
+ x_ptrs = X_ptr + (batch_idx * X_stride_b +
228
+ t_in_offs[None, :] * X_stride_t +
229
+ offs_d[:, None] * X_stride_d)
230
+ # Combined mask for loading X (valid D and valid t_x)
231
+ x_load_mask = d_mask[:, None] & t_in_mask[None, :] # Shape [BLOCK_SIZE_D, W]
232
+ # Shape: [BLOCK_SIZE_D, W]
233
+ x_vals = tl.load(x_ptrs, mask=x_load_mask, other=0.0)
234
+
235
+ # --- Compute GradK = GradOut * X ---
236
+ # Broadcast gradout_vals: [BLOCK_SIZE_D, 1] * [BLOCK_SIZE_D, W] -> [BLOCK_SIZE_D, W]
237
+ gradk_vals = gradout_vals[:, None] * x_vals # Shape [BLOCK_SIZE_D, W]
238
+
239
+ # --- Store gradients for Kernels ---
240
+ # Pointers shape: [BLOCK_SIZE_D, W]
241
+ gradk_ptrs = GradK_ptr + (batch_idx * GradK_stride_b +
242
+ time_idx * GradK_stride_t +
243
+ offs_d[:, None] * GradK_stride_d +
244
+ offs_w[None, :] * GradK_stride_w)
245
+ # Mask only needed for D dimension (W is fully computed)
246
+ # Store computed gradient values.
247
+ tl.store(gradk_ptrs, gradk_vals, mask=d_mask[:, None])
248
+
249
+
250
+ # --- Autograd Function ---
251
+ class DynamicConvTritonFunc(Function):
252
+
253
+ @staticmethod
254
+ def forward(ctx, x, kernels, cache=None): # Added cache argument
255
+ """
256
+ Args:
257
+ x: Input tensor [B, T, D]
258
+ kernels: Kernels tensor [B, T, D, W]
259
+ cache: Optional past context tensor [B, T_cache, D]
260
+ """
261
+ x = ensure_contiguous(x)
262
+ kernels = ensure_contiguous(kernels)
263
+
264
+ B, T, D = x.shape # T is the time dimension of the current input x
265
+ _B_k, _T_k, _D_k, W = kernels.shape # Kernels are [B, T_x, D, W]
266
+ assert B == _B_k and T == _T_k and D == _D_k, \
267
+ f"Shape mismatch between x ({x.shape}) and kernels ({kernels.shape}) on B, T, or D dims"
268
+ assert W <= 4, "Kernel W > 4 not expected for this version"
269
+
270
+ out = torch.empty_like(x) # Output shape [B, T, D], corresponds to x
271
+
272
+ T_cache_val = 0
273
+ # Use x's data pointer and zero strides as placeholders if cache is None.
274
+ # These won't be used by the kernel if T_CACHE_VAL is 0 due to masking.
275
+ cache_ptr_val = x
276
+ cache_s_b, cache_s_t, cache_s_d = 0, 0, 0
277
+
278
+ if cache is not None:
279
+ cache = ensure_contiguous(cache)
280
+ B_c, T_c, D_c = cache.shape
281
+ assert B_c == B, f"Batch size mismatch: x ({B}) vs cache ({B_c})"
282
+ assert D_c == D, f"Dimension mismatch: x ({D}) vs cache ({D_c})"
283
+ T_cache_val = T_c
284
+ cache_ptr_val = cache
285
+ cache_s_b, cache_s_t, cache_s_d = cache.stride(0), cache.stride(1), cache.stride(2)
286
+
287
+ grid = lambda meta: (B * T, triton.cdiv(D, meta['BLOCK_SIZE_D']))
288
+ BLOCK_SIZE_D = 128 # Consider tuning
289
+
290
+ _dynamic_conv_fwd_kernel[grid](
291
+ x, kernels, out, # X, K, Out pointers
292
+ cache_ptr_val, # Cache pointer
293
+ B, T, D, T_cache_val, # Shapes: B, T_x, D, T_cache
294
+ x.stride(0), x.stride(1), x.stride(2), # X strides
295
+ kernels.stride(0), kernels.stride(1), kernels.stride(2), kernels.stride(3), # K strides
296
+ out.stride(0), out.stride(1), out.stride(2), # Out strides
297
+ cache_s_b, cache_s_t, cache_s_d, # Cache strides
298
+ W=W,
299
+ BLOCK_SIZE_D=BLOCK_SIZE_D,
300
+ )
301
+
302
+ # Save tensors needed for backward (cache is not needed for current backward)
303
+ ctx.save_for_backward(x, kernels)
304
+ ctx.W = W
305
+ ctx.BLOCK_SIZE_D = BLOCK_SIZE_D
306
+ # ctx.T_cache = T_cache_val # Not needed for current backward
307
+
308
+ return out
309
+
310
+ @staticmethod
311
+ def backward(ctx, grad_out):
312
+ raise NotImplementedError("Backward of cached fwdbwd is not implemented")
313
+
314
+
315
+ # --- User-facing function ---
316
+ def dynamic_conv_triton_cache(x: torch.Tensor, kernels: torch.Tensor, cache: torch.Tensor = None) -> torch.Tensor:
317
+ """
318
+ Fused dynamic convolution with autograd support using Triton kernels.
319
+ Assumes W <= 4.
320
+
321
+ Args:
322
+ x: Input tensor of shape [B, T, D].
323
+ kernels: Dynamic kernels of shape [B, T, D, W].
324
+ cache: Optional past context tensor of shape [B, T_cache, D].
325
+ If provided, treated as concatenated before x for convolution input.
326
+
327
+ Returns:
328
+ Output tensor of shape [B, T, D].
329
+ """
330
+ return DynamicConvTritonFunc.apply(x, kernels, cache)
dconv_fwdbwd.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ import torch
18
+ import triton
19
+ import triton.language as tl
20
+ from einops import rearrange
21
+ import torch.nn.functional as F
22
+ from torch.autograd import Function
23
+
24
+ # Helper function to ensure tensors are contiguous for Triton
25
+ def ensure_contiguous(t: torch.Tensor) -> torch.Tensor:
26
+ return t if t.is_contiguous() else t.contiguous()
27
+
28
+ # --- Forward Kernel (from previous step, slight modifications for autograd context) ---
29
+ @triton.jit
30
+ def _dynamic_conv_fwd_kernel(
31
+ X_ptr, K_ptr, Out_ptr,
32
+ B, T, D,
33
+ X_stride_b, X_stride_t, X_stride_d,
34
+ K_stride_b, K_stride_t, K_stride_d, K_stride_w,
35
+ Out_stride_b, Out_stride_t, Out_stride_d,
36
+ W: tl.constexpr,
37
+ BLOCK_SIZE_D: tl.constexpr,
38
+ ):
39
+ pid_batch_time = tl.program_id(0)
40
+ pid_d_block = tl.program_id(1)
41
+
42
+ batch_idx = tl.cast(pid_batch_time // T, tl.int64)
43
+ time_idx = pid_batch_time % T
44
+
45
+ offs_d = pid_d_block * BLOCK_SIZE_D + tl.arange(0, BLOCK_SIZE_D)
46
+ d_mask = offs_d < D
47
+
48
+ accumulator = tl.zeros((BLOCK_SIZE_D,), dtype=tl.float32)
49
+ offs_w = tl.arange(0, W)
50
+
51
+ # Load Kernels
52
+ k_ptrs = K_ptr + (batch_idx * K_stride_b + time_idx * K_stride_t +
53
+ offs_d[:, None] * K_stride_d + offs_w[None, :] * K_stride_w)
54
+ k_vals = tl.load(k_ptrs, mask=d_mask[:, None], other=0.0)
55
+
56
+ # Load Input X with implicit padding
57
+ t_in_offs = time_idx + offs_w - W + 1
58
+ t_in_mask = (t_in_offs >= 0) & (t_in_offs < T)
59
+ x_ptrs = X_ptr + (batch_idx * X_stride_b + t_in_offs[None, :] * X_stride_t +
60
+ offs_d[:, None] * X_stride_d)
61
+ x_load_mask = d_mask[:, None] & t_in_mask[None, :]
62
+ x_vals = tl.load(x_ptrs, mask=x_load_mask, other=0.0)
63
+
64
+ # Compute and Accumulate
65
+ product = k_vals * x_vals
66
+ accumulator += tl.sum(product, axis=1)
67
+
68
+ # Store Result
69
+ out_ptrs = Out_ptr + (batch_idx * Out_stride_b + time_idx * Out_stride_t +
70
+ offs_d * Out_stride_d)
71
+ tl.store(out_ptrs, accumulator, mask=d_mask)
72
+
73
+ # --- Backward Kernel for Input Gradient (dX) ---
74
+ @triton.jit
75
+ def _dynamic_conv_bwd_dx_kernel(
76
+ GradOut_ptr, K_ptr, GradX_ptr, # Note: GradX is accumulated into
77
+ B, T, D,
78
+ GradOut_stride_b, GradOut_stride_t, GradOut_stride_d,
79
+ K_stride_b, K_stride_t, K_stride_d, K_stride_w,
80
+ GradX_stride_b, GradX_stride_t, GradX_stride_d,
81
+ W: tl.constexpr,
82
+ BLOCK_SIZE_D: tl.constexpr,
83
+ ):
84
+ """
85
+ Computes gradient w.r.t. input X.
86
+ Grid: (B * T, cdiv(D, BLOCK_SIZE_D)) - covering GradX output
87
+ GradX[b, t_x, d] = sum_{w=0}^{W-1} GradOut[b, t, d] * K[b, t, d, w]
88
+ where t = t_x + W - 1 - w
89
+ """
90
+ pid_batch_time_x = tl.program_id(0) # Covers B * T for output GradX
91
+ pid_d_block = tl.program_id(1)
92
+
93
+ batch_idx = pid_batch_time_x // T
94
+ time_idx_x = pid_batch_time_x % T # This is t_x
95
+
96
+ offs_d = pid_d_block * BLOCK_SIZE_D + tl.arange(0, BLOCK_SIZE_D)
97
+ d_mask = offs_d < D
98
+
99
+ # Accumulator for GradX elements
100
+ accumulator = tl.zeros((BLOCK_SIZE_D,), dtype=tl.float32)
101
+ offs_w = tl.arange(0, W) # [W]
102
+
103
+ # Loop over W to accumulate contributions
104
+ # Calculate the 't' index needed for GradOut and K based on t_x and w
105
+ # t = t_x + W - 1 - w
106
+ t_k_gradout_offs = time_idx_x + W - 1 - offs_w # Shape [W]
107
+
108
+ # Mask for valid 't' indices [0, T)
109
+ t_k_gradout_mask = (t_k_gradout_offs >= 0) & (t_k_gradout_offs < T) # Shape [W]
110
+
111
+ # --- Load GradOut ---
112
+ # Pointers shape: [BLOCK_SIZE_D, W]
113
+ gradout_ptrs = GradOut_ptr + (batch_idx * GradOut_stride_b +
114
+ t_k_gradout_offs[None, :] * GradOut_stride_t +
115
+ offs_d[:, None] * GradOut_stride_d)
116
+ # Combined mask for loading GradOut (valid D and valid t)
117
+ gradout_load_mask = d_mask[:, None] & t_k_gradout_mask[None, :]
118
+ # Shape: [BLOCK_SIZE_D, W]
119
+ gradout_vals = tl.load(gradout_ptrs, mask=gradout_load_mask, other=0.0)
120
+
121
+ # --- Load Kernels ---
122
+ # Pointers shape: [BLOCK_SIZE_D, W]
123
+ k_ptrs = K_ptr + (batch_idx * K_stride_b +
124
+ t_k_gradout_offs[None, :] * K_stride_t +
125
+ offs_d[:, None] * K_stride_d +
126
+ offs_w[None, :] * K_stride_w) # Index K with 't' and 'w'
127
+ # Combined mask for loading K (valid D and valid t)
128
+ k_load_mask = d_mask[:, None] & t_k_gradout_mask[None, :]
129
+ # Shape: [BLOCK_SIZE_D, W]
130
+ k_vals = tl.load(k_ptrs, mask=k_load_mask, other=0.0)
131
+
132
+ # --- Compute product and accumulate ---
133
+ # Shape: [BLOCK_SIZE_D, W]
134
+ product = gradout_vals * k_vals
135
+ # Sum contributions over the W dimension
136
+ accumulator += tl.sum(product, axis=1) # Shape: [BLOCK_SIZE_D]
137
+
138
+ # --- Store accumulated gradients ---
139
+ # Note: This kernel computes the *entire* gradient value for GradX[b, t_x, d_block].
140
+ # If this kernel could potentially be called multiple times for the same GradX elements
141
+ # (e.g., in complex graphs), atomic adds would be needed. Here, it seems direct store is fine.
142
+ gradx_ptrs = GradX_ptr + (batch_idx * GradX_stride_b +
143
+ time_idx_x * GradX_stride_t +
144
+ offs_d * GradX_stride_d)
145
+ tl.store(gradx_ptrs, accumulator, mask=d_mask)
146
+
147
+
148
+ # --- Backward Kernel for Kernel Gradient (dK) ---
149
+ @triton.jit
150
+ def _dynamic_conv_bwd_dk_kernel(
151
+ GradOut_ptr, X_ptr, GradK_ptr, # Note: GradK is written directly
152
+ B, T, D,
153
+ GradOut_stride_b, GradOut_stride_t, GradOut_stride_d,
154
+ X_stride_b, X_stride_t, X_stride_d,
155
+ GradK_stride_b, GradK_stride_t, GradK_stride_d, GradK_stride_w,
156
+ W: tl.constexpr,
157
+ BLOCK_SIZE_D: tl.constexpr,
158
+ ):
159
+ """
160
+ Computes gradient w.r.t. kernels K.
161
+ Grid: (B * T, cdiv(D, BLOCK_SIZE_D)) - covering GradK output dims B, T, D
162
+ GradK[b, t, d, w] = GradOut[b, t, d] * X[b, t + w - W + 1, d]
163
+ """
164
+ pid_batch_time = tl.program_id(0) # Covers B * T for output GradK
165
+ pid_d_block = tl.program_id(1)
166
+
167
+ batch_idx = pid_batch_time // T
168
+ time_idx = pid_batch_time % T # This is 't' for GradK and GradOut
169
+
170
+ offs_d = pid_d_block * BLOCK_SIZE_D + tl.arange(0, BLOCK_SIZE_D)
171
+ d_mask = offs_d < D
172
+
173
+ offs_w = tl.arange(0, W) # [W]
174
+
175
+ # --- Load GradOut ---
176
+ # Pointers shape: [BLOCK_SIZE_D] (only depends on b, t, d)
177
+ gradout_ptrs = GradOut_ptr + (batch_idx * GradOut_stride_b +
178
+ time_idx * GradOut_stride_t +
179
+ offs_d * GradOut_stride_d)
180
+ # Shape: [BLOCK_SIZE_D]
181
+ gradout_vals = tl.load(gradout_ptrs, mask=d_mask, other=0.0)
182
+
183
+ # --- Load Input X with implicit padding ---
184
+ # Calculate X's time index: t_x = t + w - W + 1
185
+ t_in_offs = time_idx + offs_w - W + 1 # Shape [W]
186
+ # Mask for valid t_x index [0, T)
187
+ t_in_mask = (t_in_offs >= 0) & (t_in_offs < T) # Shape [W]
188
+
189
+ # Pointers shape: [BLOCK_SIZE_D, W]
190
+ x_ptrs = X_ptr + (batch_idx * X_stride_b +
191
+ t_in_offs[None, :] * X_stride_t +
192
+ offs_d[:, None] * X_stride_d)
193
+ # Combined mask for loading X (valid D and valid t_x)
194
+ x_load_mask = d_mask[:, None] & t_in_mask[None, :] # Shape [BLOCK_SIZE_D, W]
195
+ # Shape: [BLOCK_SIZE_D, W]
196
+ x_vals = tl.load(x_ptrs, mask=x_load_mask, other=0.0)
197
+
198
+ # --- Compute GradK = GradOut * X ---
199
+ # Broadcast gradout_vals: [BLOCK_SIZE_D, 1] * [BLOCK_SIZE_D, W] -> [BLOCK_SIZE_D, W]
200
+ gradk_vals = gradout_vals[:, None] * x_vals # Shape [BLOCK_SIZE_D, W]
201
+
202
+ # --- Store gradients for Kernels ---
203
+ # Pointers shape: [BLOCK_SIZE_D, W]
204
+ gradk_ptrs = GradK_ptr + (batch_idx * GradK_stride_b +
205
+ time_idx * GradK_stride_t +
206
+ offs_d[:, None] * GradK_stride_d +
207
+ offs_w[None, :] * GradK_stride_w)
208
+ # Mask only needed for D dimension (W is fully computed)
209
+ # Store computed gradient values.
210
+ tl.store(gradk_ptrs, gradk_vals, mask=d_mask[:, None])
211
+
212
+
213
+ # --- Autograd Function ---
214
+ class DynamicConvTritonFunc(Function):
215
+
216
+ @staticmethod
217
+ def forward(ctx, x, kernels):
218
+ """
219
+ Args:
220
+ x: Input tensor [B, T, D]
221
+ kernels: Kernels tensor [B, T, D, W]
222
+ """
223
+ x = ensure_contiguous(x)
224
+ kernels = ensure_contiguous(kernels)
225
+
226
+ B, T, D = x.shape
227
+ W = kernels.shape[3]
228
+ assert W <= 4, "Kernel W > 4 not expected for this version"
229
+
230
+ out = torch.empty_like(x) # Output shape [B, T, D]
231
+
232
+ grid = lambda meta: (B * T, triton.cdiv(D, meta['BLOCK_SIZE_D']))
233
+ BLOCK_SIZE_D = 128 # Consider tuning
234
+
235
+ _dynamic_conv_fwd_kernel[grid](
236
+ x, kernels, out,
237
+ B, T, D,
238
+ x.stride(0), x.stride(1), x.stride(2),
239
+ kernels.stride(0), kernels.stride(1), kernels.stride(2), kernels.stride(3),
240
+ out.stride(0), out.stride(1), out.stride(2),
241
+ W=W,
242
+ BLOCK_SIZE_D=BLOCK_SIZE_D,
243
+ )
244
+
245
+ # Save tensors needed for backward
246
+ # Need x for dK, need kernels for dX
247
+ ctx.save_for_backward(x, kernels)
248
+ # Store W and BLOCK_SIZE_D needed for backward kernel calls
249
+ ctx.W = W
250
+ ctx.BLOCK_SIZE_D = BLOCK_SIZE_D
251
+
252
+ return out
253
+
254
+ @staticmethod
255
+ def backward(ctx, grad_out):
256
+ """
257
+ Args:
258
+ grad_out: Gradient w.r.t. the output tensor [B, T, D]
259
+ Returns:
260
+ grad_x: Gradient w.r.t. input x [B, T, D]
261
+ grad_kernels: Gradient w.r.t. kernels [B, T, D, W]
262
+ """
263
+ grad_out = ensure_contiguous(grad_out)
264
+ x, kernels = ctx.saved_tensors
265
+ W = ctx.W
266
+ BLOCK_SIZE_D = ctx.BLOCK_SIZE_D
267
+
268
+ B, T, D = x.shape
269
+
270
+ # Initialize gradients
271
+ # grad_x needs accumulation, start with zeros.
272
+ grad_x = torch.zeros_like(x)
273
+ # grad_kernels is computed directly, can use empty_like if kernel handles all writes.
274
+ # Using empty and relying on kernel writing zeros via masking/other=0.0.
275
+ grad_kernels = torch.empty_like(kernels)
276
+
277
+ # Define grid (can often be the same as forward or similar)
278
+ grid = lambda meta: (B * T, triton.cdiv(D, meta['BLOCK_SIZE_D']))
279
+
280
+ # Kernel call for grad_x
281
+ _dynamic_conv_bwd_dx_kernel[grid](
282
+ grad_out, kernels, grad_x,
283
+ B, T, D,
284
+ grad_out.stride(0), grad_out.stride(1), grad_out.stride(2),
285
+ kernels.stride(0), kernels.stride(1), kernels.stride(2), kernels.stride(3),
286
+ grad_x.stride(0), grad_x.stride(1), grad_x.stride(2),
287
+ W=W,
288
+ BLOCK_SIZE_D=BLOCK_SIZE_D,
289
+ )
290
+
291
+ # Kernel call for grad_kernels
292
+ _dynamic_conv_bwd_dk_kernel[grid](
293
+ grad_out, x, grad_kernels,
294
+ B, T, D,
295
+ grad_out.stride(0), grad_out.stride(1), grad_out.stride(2),
296
+ x.stride(0), x.stride(1), x.stride(2),
297
+ grad_kernels.stride(0), grad_kernels.stride(1), grad_kernels.stride(2), grad_kernels.stride(3),
298
+ W=W,
299
+ BLOCK_SIZE_D=BLOCK_SIZE_D,
300
+ )
301
+
302
+ # Return gradients in the order inputs were received by forward
303
+ return grad_x, grad_kernels
304
+
305
+ # --- User-facing function ---
306
+ def dynamic_conv_triton_autograd(x: torch.Tensor, kernels: torch.Tensor) -> torch.Tensor:
307
+ """
308
+ Fused dynamic convolution with autograd support using Triton kernels.
309
+ Assumes W <= 4.
310
+
311
+ Args:
312
+ x: Input tensor of shape [B, T, D].
313
+ kernels: Dynamic kernels of shape [B, T, D, W].
314
+
315
+ Returns:
316
+ Output tensor of shape [B, T, D].
317
+ """
318
+ return DynamicConvTritonFunc.apply(x, kernels)
dconv_step.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ import torch
18
+ import triton
19
+ import triton.language as tl
20
+ from einops import rearrange
21
+ import torch.nn.functional as F
22
+ from typing import Tuple, Optional
23
+
24
+ # Helper function to ensure tensors are contiguous for Triton
25
+ def ensure_contiguous(t: torch.Tensor) -> torch.Tensor:
26
+ # Ensure tensor is contiguous in memory.
27
+ return t if t.is_contiguous() else t.contiguous()
28
+
29
+ # Removed _apply_activation helper function
30
+
31
+ @triton.jit
32
+ def _causal_conv_step_kernel(
33
+ # --- Input/Output Pointers ---
34
+ X_ptr, # Pointer to current input x [B, D] (after squeeze)
35
+ Cache_ptr, # Pointer to cache [B, D, W], updated IN-PLACE
36
+ Kernels_ptr, # Pointer to generated kernels [B, D, W]
37
+ Out_ptr, # Pointer to output tensor [B, D]
38
+
39
+ # --- Tensor Dimensions ---
40
+ B, D, # Batch size, Feature dimension
41
+
42
+ # --- Tensor Strides ---
43
+ X_stride_b, X_stride_d,
44
+ Cache_stride_b, Cache_stride_d, Cache_stride_w,
45
+ Kernels_stride_b, Kernels_stride_d, Kernels_stride_w,
46
+ Out_stride_b, Out_stride_d,
47
+
48
+ # --- Kernel Meta-Parameters ---
49
+ W: tl.constexpr, # Kernel width (Cache size), passed as compile-time constant (1 < W <= 4)
50
+ BLOCK_SIZE_D: tl.constexpr, # Block size for D dimension (tuning parameter)
51
+ # Removed ACTIVATION: tl.constexpr
52
+ ):
53
+ """
54
+ Triton kernel for a single step (T=1) of causal dynamic convolution.
55
+ Updates the cache in-place and computes the output (without activation).
56
+ Optimized for small W (1 < W <= 4) by manually unrolling the W dimension.
57
+ Does NOT handle separate static bias.
58
+
59
+ Grid: (B, cdiv(D, BLOCK_SIZE_D))
60
+ Updates Cache[b, d, :] and computes Out[b, d].
61
+ """
62
+ # 1. --- Get Program IDs and Calculate Indices ---
63
+ pid_b = tl.program_id(0) # Program ID for batch dimension
64
+ pid_d_block = tl.program_id(1) # Program ID for dimension block
65
+
66
+ offs_d = pid_d_block * BLOCK_SIZE_D + tl.arange(0, BLOCK_SIZE_D)
67
+ d_mask = offs_d < D # Shape: [BLOCK_SIZE_D]
68
+
69
+ # 2. --- Load Current Input X ---
70
+ x_ptrs = X_ptr + pid_b * X_stride_b + offs_d * X_stride_d
71
+ x_curr = tl.load(x_ptrs, mask=d_mask, other=0.0) # Shape: [BLOCK_SIZE_D]
72
+
73
+ # --- Initialize Accumulator ---
74
+ accumulator = tl.zeros((BLOCK_SIZE_D,), dtype=x_curr.dtype) # Use input dtype
75
+
76
+ # --- Manually Unroll Operations for W ---
77
+ # We will load kernel values and cache values step-by-step
78
+ # and perform the calculation and cache update.
79
+
80
+ # --- Step w = 0 ---
81
+ # Compute: cache_val_1 * k_val_0 (part 1)
82
+ # Cache Update: store cache_val_1 at index 0
83
+ if tl.constexpr(W > 1):
84
+ # Load k_val_0
85
+ k_ptr_0 = Kernels_ptr + pid_b * Kernels_stride_b + offs_d * Kernels_stride_d + 0 * Kernels_stride_w
86
+ k_val_0 = tl.load(k_ptr_0, mask=d_mask, other=0.0)
87
+
88
+ # Load cache_val_1 (needed for computation and storing at index 0)
89
+ cache_ptr_1 = Cache_ptr + pid_b * Cache_stride_b + offs_d * Cache_stride_d + 1 * Cache_stride_w
90
+ cache_val_1 = tl.load(cache_ptr_1, mask=d_mask, other=0.0)
91
+
92
+ # Accumulate Part 1
93
+ accumulator += cache_val_1 * k_val_0
94
+
95
+ # Cache Update: Store cache_val_1 -> cache_ptr_0
96
+ cache_ptr_0 = Cache_ptr + pid_b * Cache_stride_b + offs_d * Cache_stride_d + 0 * Cache_stride_w
97
+ tl.store(cache_ptr_0, cache_val_1, mask=d_mask)
98
+
99
+ # --- Step w = 1 ---
100
+ # Compute: cache_val_2 * k_val_1 (part 1)
101
+ # Cache Update: store cache_val_2 at index 1
102
+ if tl.constexpr(W > 2):
103
+ # Load k_val_1
104
+ k_ptr_1 = Kernels_ptr + pid_b * Kernels_stride_b + offs_d * Kernels_stride_d + 1 * Kernels_stride_w
105
+ k_val_1 = tl.load(k_ptr_1, mask=d_mask, other=0.0)
106
+
107
+ # Load cache_val_2
108
+ cache_ptr_2 = Cache_ptr + pid_b * Cache_stride_b + offs_d * Cache_stride_d + 2 * Cache_stride_w
109
+ cache_val_2 = tl.load(cache_ptr_2, mask=d_mask, other=0.0)
110
+
111
+ # Accumulate Part 1
112
+ accumulator += cache_val_2 * k_val_1
113
+
114
+ # Cache Update: Store cache_val_2 -> cache_ptr_1
115
+ cache_ptr_1 = Cache_ptr + pid_b * Cache_stride_b + offs_d * Cache_stride_d + 1 * Cache_stride_w
116
+ tl.store(cache_ptr_1, cache_val_2, mask=d_mask)
117
+
118
+ # --- Step w = 2 ---
119
+ # Compute: cache_val_3 * k_val_2 (part 1)
120
+ # Cache Update: store cache_val_3 at index 2
121
+ if tl.constexpr(W > 3):
122
+ # Load k_val_2
123
+ k_ptr_2 = Kernels_ptr + pid_b * Kernels_stride_b + offs_d * Kernels_stride_d + 2 * Kernels_stride_w
124
+ k_val_2 = tl.load(k_ptr_2, mask=d_mask, other=0.0)
125
+
126
+ # Load cache_val_3
127
+ cache_ptr_3 = Cache_ptr + pid_b * Cache_stride_b + offs_d * Cache_stride_d + 3 * Cache_stride_w
128
+ cache_val_3 = tl.load(cache_ptr_3, mask=d_mask, other=0.0)
129
+
130
+ # Accumulate Part 1
131
+ accumulator += cache_val_3 * k_val_2
132
+
133
+ # Cache Update: Store cache_val_3 -> cache_ptr_2
134
+ cache_ptr_2 = Cache_ptr + pid_b * Cache_stride_b + offs_d * Cache_stride_d + 2 * Cache_stride_w
135
+ tl.store(cache_ptr_2, cache_val_3, mask=d_mask)
136
+
137
+ # --- Final Step (Part 2 and Final Cache Update) ---
138
+ # Compute: x_curr * k_val_{W-1} (part 2)
139
+ # Cache Update: store x_curr at index W-1
140
+
141
+ # Load k_val_{W-1}
142
+ k_ptr_last = Kernels_ptr + pid_b * Kernels_stride_b + offs_d * Kernels_stride_d + (W - 1) * Kernels_stride_w
143
+ k_val_last = tl.load(k_ptr_last, mask=d_mask, other=0.0)
144
+
145
+ # Accumulate Part 2
146
+ accumulator += x_curr * k_val_last
147
+
148
+ # Final Cache Update: Store x_curr -> cache_ptr_{W-1}
149
+ cache_ptr_last = Cache_ptr + pid_b * Cache_stride_b + offs_d * Cache_stride_d + (W - 1) * Cache_stride_w
150
+ tl.store(cache_ptr_last, x_curr, mask=d_mask)
151
+
152
+ # Removed activation application: accumulator = _apply_activation(accumulator, ACTIVATION)
153
+
154
+ # 6. --- Store Output ---
155
+ out_ptrs = Out_ptr + pid_b * Out_stride_b + offs_d * Out_stride_d
156
+ tl.store(out_ptrs, accumulator, mask=d_mask) # Store result without activation
157
+
158
+ # Cache update is now fully handled within the unrolled steps.
159
+
160
+
161
+ # --- Python Wrapper Function ---
162
+ def causal_conv_step_triton(
163
+ x: torch.Tensor, # Input tensor [B, 1, D]
164
+ cache: torch.Tensor, # Cache tensor [B, D, W], modified in-place
165
+ kernels: torch.Tensor, # Kernels tensor [B, D, W]
166
+ # Removed activation parameter
167
+ ) -> torch.Tensor: # Returns output tensor [B, D] (before activation)
168
+ """
169
+ Performs one step of causal dynamic convolution using Triton.
170
+ Updates the cache in-place. Does NOT fuse activation. Assumes 1 < W <= 4.
171
+ Uses manually unrolled kernel for W dimension.
172
+
173
+ Args:
174
+ x: Current input token tensor of shape [B, 1, D].
175
+ cache: Cache tensor of shape [B, D, W]. Will be updated in-place.
176
+ kernels: Dynamically generated kernels tensor of shape [B, D, W].
177
+
178
+ Returns:
179
+ Output tensor of shape [B, D] for the current step (before activation).
180
+ """
181
+ # --- Input Validation and Preparation ---
182
+ assert x.dim() == 3 and x.shape[1] == 1, "Input x must have shape [B, 1, D]"
183
+ assert cache.dim() == 3, "Cache must have shape [B, D, W]"
184
+ assert kernels.dim() == 3, "Kernels must have shape [B, D, W]"
185
+ B, _, D = x.shape
186
+ W = cache.shape[2]
187
+ # Updated assertion: W must be > 1 and <= 4
188
+ assert 1 < W <= 4, f"Kernel W={W}, this optimized version assumes 1 < W <= 4"
189
+ assert cache.shape[0] == B and cache.shape[1] == D, f"Cache shape mismatch: {cache.shape}"
190
+ assert kernels.shape == cache.shape, f"Kernels shape mismatch: {kernels.shape}"
191
+ assert x.is_cuda and cache.is_cuda and kernels.is_cuda, "Inputs must be CUDA tensors"
192
+ # Allow different input dtypes, but ensure they are compatible or handled
193
+ # assert x.dtype == cache.dtype == kernels.dtype, "Input dtypes must match"
194
+
195
+ # Squeeze the time dimension from input x
196
+ x_squeezed = x.squeeze(1) # Shape [B, D]
197
+
198
+ # Ensure tensors are contiguous for correct stride calculations in Triton
199
+ x_squeezed = ensure_contiguous(x_squeezed)
200
+ # Cache MUST be contiguous for in-place updates and loads/stores to work reliably
201
+ cache = ensure_contiguous(cache)
202
+ kernels = ensure_contiguous(kernels)
203
+
204
+ # Create output tensor with the same dtype as input x
205
+ out = torch.empty_like(x_squeezed) # Shape [B, D]
206
+
207
+ # --- Triton Kernel Launch ---
208
+ grid = lambda meta: (B, triton.cdiv(D, meta['BLOCK_SIZE_D']))
209
+ BLOCK_SIZE_D = 64 # Example, tune this value
210
+
211
+ # Launch the kernel
212
+ _causal_conv_step_kernel[grid](
213
+ x_squeezed, cache, kernels, out, # Tensor pointers
214
+ B, D, # Dimensions
215
+ x_squeezed.stride(0), x_squeezed.stride(1), # x strides
216
+ cache.stride(0), cache.stride(1), cache.stride(2), # cache strides
217
+ kernels.stride(0), kernels.stride(1), kernels.stride(2), # kernels strides
218
+ out.stride(0), out.stride(1), # out strides
219
+ # --- Meta-parameters ---
220
+ W=W, # Pass W as constexpr
221
+ BLOCK_SIZE_D=BLOCK_SIZE_D, # Pass BLOCK_SIZE_D as constexpr
222
+ # Removed ACTIVATION=activation
223
+ )
224
+
225
+ return out # Return the computed output [B, D] (before activation)
dynamic_conv.py ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ from __future__ import annotations
18
+
19
+ from collections import OrderedDict
20
+ from typing import Optional, Tuple, Callable
21
+
22
+ import torch
23
+ import torch.nn as nn
24
+ import torch.nn.functional as F
25
+ from einops import rearrange
26
+
27
+ from transformers.activations import ACT2FN
28
+
29
+ from .dconv_fwdbwd import dynamic_conv_triton_autograd
30
+ from .dconv_fwd_cache import dynamic_conv_triton_cache
31
+ from .dconv_step import causal_conv_step_triton
32
+
33
+
34
+ class DynamicShortConvolution(nn.Module):
35
+ """
36
+ Simple wrapper around `nn.Conv1d` that accepts dimension last.
37
+ """
38
+
39
+ def __init__(
40
+ self,
41
+ hidden_size: int,
42
+ kernel_size: int,
43
+ generator_input_size: Optional[int] = None,
44
+ generator_reduction: Optional[int] = None,
45
+ generator_activation: str = 'silu',
46
+ activation: Optional[str] = 'silu',
47
+ static_conv_init: Callable = None,
48
+ use_fast_conv1d: bool = True,
49
+ implementation: str = "naive",
50
+ ) -> DynamicShortConvolution:
51
+ super().__init__()
52
+
53
+ self.hidden_size = hidden_size
54
+ self.generator_input_size = hidden_size if generator_input_size is None else generator_input_size
55
+ self.generator_hidden_size = hidden_size if generator_reduction is None else (hidden_size // generator_reduction)
56
+ self.kernel_size = kernel_size
57
+ self.activation = None
58
+ self.use_fast_conv1d = use_fast_conv1d
59
+ self.implementation = implementation
60
+
61
+ if activation is not None:
62
+ assert activation in ['silu', 'swish'], f"Activation `{activation}` not supported yet."
63
+ self.activation = activation
64
+
65
+ self.static_conv_init = static_conv_init
66
+
67
+ self.kernel_generator = nn.Sequential(
68
+ OrderedDict([
69
+ ("w1", nn.Linear(self.generator_input_size, self.generator_hidden_size, bias=False)),
70
+ ("act", ACT2FN[generator_activation]),
71
+ ("w2", nn.Linear(self.generator_hidden_size, self.hidden_size * self.kernel_size, bias=True)),
72
+ ])
73
+ )
74
+ self._init_kernel_generator()
75
+
76
+ def _init_kernel_generator(self):
77
+ """
78
+ Initialize the kernel generator.
79
+ """
80
+ for layer in self.kernel_generator:
81
+ if isinstance(layer, nn.Linear):
82
+ layer.weight.data.zero_()
83
+ if layer.bias is not None:
84
+ layer.bias.data.zero_()
85
+
86
+ if self.static_conv_init is not None:
87
+ # init for static_bias
88
+ self.static_conv_init(self.kernel_generator.w2.bias)
89
+
90
+ def get_kernel(self, x: torch.Tensor) -> torch.Tensor:
91
+ flat_kernels = self.kernel_generator(x)
92
+ if flat_kernels.dim() == 3:
93
+ kernels = rearrange(flat_kernels, 'b t (d w) -> b t d w', w=self.kernel_size)
94
+ elif flat_kernels.dim() == 2:
95
+ kernels = rearrange(flat_kernels, 'b (d w) -> b d w', w=self.kernel_size)
96
+ else:
97
+ raise ValueError(f"Invalid kernel shape: {flat_kernels.shape}")
98
+ return kernels
99
+
100
+ def forward(
101
+ self,
102
+ x: torch.Tensor,
103
+ mask: Optional[torch.Tensor] = None,
104
+ cache: Optional[torch.Tensor] = None,
105
+ output_final_state: bool = False,
106
+ cu_seqlens: Optional[torch.LongTensor] = None,
107
+ generator_input: Optional[torch.Tensor] = None,
108
+ **kwargs,
109
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
110
+ """
111
+ Args:
112
+ x (`torch.Tensor`):
113
+ Tensor of shape `[B, T, D]`.
114
+ If `seq_idx` is provided, `B` must be 1.
115
+ mask (`Optional[torch.Tensor]`):
116
+ Attention mask dealing with padded positions.
117
+ cache (`Optional[torch.Tensor]`):
118
+ Previous cache tensor of shape `[N, D, W]`, where `W` is the kernel size.
119
+ If provided, the cache is updated **inplace**.
120
+ output_final_state (Optional[bool]):
121
+ Whether to output the final state of shape `[N, D, W]`. Default: `False`.
122
+ cu_seqlens (Optional[torch.LongTensor]):
123
+ Cumulative sequence lengths for each batch. Used for varlen. Default: `None`.
124
+ Shape: [B+1]
125
+
126
+ Returns:
127
+ Tensor of shape `[B, T, D]`.
128
+ """
129
+
130
+ """
131
+ x: [B, T, D]
132
+ return: [B, T, D]
133
+ """
134
+
135
+ assert cu_seqlens is None, "cu_seqlens not supported yet."
136
+
137
+ B, T, D, W = *x.shape, self.kernel_size
138
+ N = B
139
+
140
+ input_dtype = x.dtype
141
+
142
+ if mask is not None:
143
+ x = x.mul_(mask.unsqueeze(-1))
144
+
145
+ implementation = self.implementation
146
+ if implementation == "triton" and not self.training:
147
+ implementation = "triton_cache"
148
+
149
+ # during the decoding phase, we assume the batch is composed of sequences of length 1
150
+ if cache is not None and B * T == N:
151
+ assert T == 1
152
+ if implementation in ["naive", "triton_training"]:
153
+ x, cache = self._step_naive(x, cache, cu_seqlens, generator_input=generator_input)
154
+ elif implementation in ["triton", "triton_cache", "triton_decoding"]:
155
+ x, cache = self._step_triton(x, cache, cu_seqlens, generator_input=generator_input)
156
+ else:
157
+ raise ValueError(f"Unknown implementation: {implementation}")
158
+ return x, cache
159
+
160
+ if output_final_state:
161
+ new_cache = rearrange(x[..., -min(W, T):, :], 'n w d -> n d w')
162
+ else:
163
+ new_cache = None
164
+
165
+ if implementation in ["naive", "triton_decoding"]:
166
+ x = self._forward_naive(x, generator_input=generator_input) # [B, T, D]
167
+ elif implementation in ["triton", "triton_training"]:
168
+ assert cache is None, "Cache not supported in pure triton mode. Please set model.eval() or use triton_cache mode."
169
+ x = self._forward_triton(x, generator_input=generator_input)
170
+ elif implementation == "triton_cache":
171
+ x = self._forward_triton_cache(x, generator_input=generator_input, cache=cache)
172
+ else:
173
+ raise ValueError(f"Unknown implementation: {implementation}")
174
+
175
+ if self.activation is not None:
176
+ x = ACT2FN[self.activation](x)
177
+
178
+ x = x.to(input_dtype)
179
+ if output_final_state:
180
+ if cache is None:
181
+ cache = x.new_zeros(N, D, W)
182
+ cache[:, :, -min(W, T):].copy_(new_cache)
183
+
184
+ return x, cache
185
+
186
+ def _forward_naive(self, x: torch.Tensor, generator_input: Optional[torch.Tensor] = None) -> torch.Tensor:
187
+ W = self.kernel_size
188
+ generator_input = x if generator_input is None else generator_input
189
+ kernels = self.get_kernel(generator_input)
190
+ x = F.pad(x.transpose(1, 2), (W - 1, 0)) # [B, D, T+W-1]
191
+ x = x.unfold(dimension=2, size=W, step=1) # [B, D, T, W]
192
+ x = x.permute(0, 2, 1, 3) # [B, T, D, W]
193
+ x = (x * kernels).sum(dim=-1) # [B, T, D]
194
+ return x
195
+
196
+ def _forward_triton(self, x: torch.Tensor, generator_input: Optional[torch.Tensor] = None) -> torch.Tensor:
197
+ generator_input = x if generator_input is None else generator_input
198
+ kernels = self.get_kernel(generator_input)
199
+ output_triton = dynamic_conv_triton_autograd(x, kernels)
200
+ return output_triton
201
+
202
+ @torch.no_grad
203
+ def _forward_triton_cache(self, x: torch.Tensor, generator_input: Optional[torch.Tensor] = None, cache: Optional[torch.Tensor] = None) -> torch.Tensor:
204
+ generator_input = x if generator_input is None else generator_input
205
+ assert not self.training, "Triton implementation is only available in eval mode."
206
+ # cache: [B, D, T(W)]
207
+ CHUNK_SIZE = 2048
208
+ n_chunk = (x.shape[1] + CHUNK_SIZE - 1) // CHUNK_SIZE
209
+ output_triton = torch.zeros_like(x)
210
+ if cache is not None:
211
+ cache = rearrange(cache, "b d t -> b t d") # [B, T(W), D]
212
+ for i in range(n_chunk):
213
+ start = i * CHUNK_SIZE
214
+ end = min((i + 1) * CHUNK_SIZE, x.shape[1])
215
+ kernels = self.get_kernel(generator_input[:, start:end])
216
+ out = dynamic_conv_triton_cache(x[:, start:end], kernels, cache=cache)
217
+ output_triton[:, i*CHUNK_SIZE:end, :] = out
218
+ cache = x[:, end-self.kernel_size:end, :]
219
+ return output_triton
220
+
221
+ def _step_naive(
222
+ self,
223
+ x: torch.Tensor,
224
+ cache: torch.Tensor,
225
+ cu_seqlens: Optional[torch.LongTensor] = None,
226
+ generator_input: Optional[torch.Tensor] = None
227
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
228
+ assert x.shape[1] == 1, "x must be of shape [B, 1, D]"
229
+ shape = x.shape
230
+ generator_input = x if generator_input is None else generator_input
231
+ x = x.squeeze(1)
232
+ generator_input = generator_input.squeeze(1) # Shape [B, D]
233
+ B, D, W = *x.shape, self.kernel_size
234
+
235
+ # we follow the fast mode that updates the cache in-place
236
+ cache.copy_(cache.roll(shifts=-1, dims=-1))
237
+ cache[:, :, -1] = x # [B, D, T(W)]
238
+
239
+ kernels = self.get_kernel(generator_input) # [B, D, W]
240
+ x = torch.sum(cache * kernels, dim=-1)
241
+
242
+ if self.activation is not None:
243
+ x = ACT2FN[self.activation](x)
244
+
245
+ return x.view(shape), cache
246
+
247
+ def _step_triton(
248
+ self,
249
+ x: torch.Tensor,
250
+ cache: torch.Tensor,
251
+ cu_seqlens: Optional[torch.LongTensor] = None,
252
+ generator_input: Optional[torch.Tensor] = None
253
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
254
+ # --- Triton Implementation ---
255
+ assert x.shape[1] == 1, "x must be of shape [B, 1, D]"
256
+ shape = x.shape # Keep original shape [B, 1, D] for return
257
+ generator_input = x if generator_input is None else generator_input
258
+
259
+ # 1. Generate kernels
260
+ kernels_triton = self.get_kernel(generator_input.squeeze(1)) # [B, D, W]
261
+
262
+ # 2. Call Triton kernel without activation
263
+ x_out_triton = causal_conv_step_triton(
264
+ x,
265
+ cache,
266
+ kernels_triton,
267
+ )
268
+
269
+ # Apply activation (if any) after kernel execution
270
+ if self.activation is not None:
271
+ x_out_triton = ACT2FN[self.activation](x_out_triton)
272
+
273
+ # 3. Return reshaped output and the *same cache tensor* (it was updated in-place)
274
+ return x_out_triton.view(shape), cache
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 151643,
4
+ "eos_token_id": 151643,
5
+ "transformers_version": "4.52.0.dev0"
6
+ }
jet_block.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ # This file is modified from https://github.com/fla-org/flash-linear-attention/blob/main/fla/layers/gated_deltanet.py
18
+
19
+ from __future__ import annotations
20
+
21
+ import math
22
+ from dataclasses import dataclass
23
+ from typing import Optional, Tuple
24
+
25
+ import torch
26
+ import torch.nn as nn
27
+ from torch.nn import functional as F
28
+ from einops import rearrange
29
+
30
+ from fla.layers.utils import get_unpad_data, index_first_axis, pad_input
31
+ from fla.modules import FusedRMSNormGated
32
+ from fla.ops.gated_delta_rule import (chunk_gated_delta_rule,
33
+ fused_recurrent_gated_delta_rule)
34
+
35
+
36
+ from .dynamic_conv import DynamicShortConvolution
37
+ from .configuration_jet_nemotron import JetNemotronConfig
38
+ from .kv_cache import JetNemotronCache
39
+
40
+
41
+ @dataclass
42
+ class JetBlockConfig():
43
+ mode: str = 'chunk'
44
+ expand_v: int = 2.0
45
+ num_heads: int = 6
46
+ head_dim: int = 256
47
+ norm_eps: float = 1e-5
48
+ conv_size: int = 4
49
+ dconv_generator_reduction: int = None
50
+ dconv_implementation: str = 'triton'
51
+
52
+
53
+ def init_linear_conv1d(weight: torch.Tensor, std: float, bias: Optional[torch.Tensor] = None) -> None:
54
+ weight.data.normal_(mean=0.0, std=std)
55
+ if bias is not None:
56
+ if not getattr(bias, "_no_reinit", False):
57
+ nn.init.zeros_(bias)
58
+
59
+
60
+ class JetBlock(nn.Module):
61
+ def __init__(
62
+ self,
63
+ config: Optional[JetNemotronConfig] = None,
64
+ layer_type: str = 'jet',
65
+ layer_idx: Optional[int] = None,
66
+ hidden_size: Optional[int] = None,
67
+ initializer_range: Optional[float] = None,
68
+ jet_block_config: Optional[JetBlockConfig] = None
69
+ ) -> JetBlock:
70
+ super().__init__()
71
+
72
+ if jet_block_config is None:
73
+ assert config.efficient_attention_config is not None, "Efficient attention config must be provided in JetConfig."
74
+ assert layer_type in config.efficient_attention_config, \
75
+ f"{layer_type} configuration must be provided in efficient_attention_config."
76
+ jet_block_config = JetBlockConfig(**config.efficient_attention_config[layer_type])
77
+
78
+ hidden_size = hidden_size or config.hidden_size
79
+ initializer_range = initializer_range or config.initializer_range
80
+
81
+ self.mode = jet_block_config.mode
82
+
83
+ self.hidden_size = hidden_size
84
+ self.expand_v = jet_block_config.expand_v
85
+
86
+ self.conv_size = jet_block_config.conv_size
87
+
88
+ self.head_dim = jet_block_config.head_dim
89
+ self.num_heads = jet_block_config.num_heads
90
+
91
+ self.key_dim = int(self.num_heads * self.head_dim)
92
+ self.value_dim = int(self.key_dim * self.expand_v)
93
+ self.head_k_dim = jet_block_config.head_dim
94
+ self.head_v_dim = int(jet_block_config.head_dim * self.expand_v)
95
+ self.layer_idx = layer_idx
96
+
97
+ self.autotune_interval = 32 * 16 * 1024 # 32 batch size * 16 num head * 1024 sequence length
98
+
99
+ # Consistency check: Ensure expand_v produces integer values
100
+ if not math.isclose(self.key_dim * self.expand_v, self.value_dim, rel_tol=1e-5):
101
+ raise ValueError(
102
+ f"expand_v={self.expand_v} does not produce an integer value when multiplied by key_dim={self.key_dim}. "
103
+ f"Resulting value_dim would be {self.key_dim * self.expand_v}, which is invalid for nn.Linear."
104
+ )
105
+ if not math.isclose(self.head_dim * self.expand_v, self.head_v_dim, rel_tol=1e-5):
106
+ raise ValueError(
107
+ f"expand_v={self.expand_v} does not produce an integer value when multiplied by head_dim={self.head_dim}. "
108
+ f"Resulting head_v_dim would be {self.head_dim * self.expand_v}, which is invalid for FusedRMSNormGated."
109
+ )
110
+ assert self.mode in ['chunk', 'fused_recurrent'], f"Not suppoerted mode `{jet_block_config.mode}`."
111
+
112
+ self.q_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
113
+ self.k_proj = nn.Linear(hidden_size, self.key_dim, bias=False)
114
+ self.v_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
115
+ self.b_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
116
+ self.a_proj = nn.Linear(hidden_size, self.num_heads, bias=False)
117
+
118
+ A = torch.empty(self.num_heads, dtype=torch.float32).uniform_(0, 16)
119
+ self.A_log = nn.Parameter(torch.log(A))
120
+ self.A_log._no_weight_decay = True
121
+ # hard coded for now
122
+ dt_min = 0.001
123
+ dt_max = 0.1
124
+ dt_init_floor = 1e-4
125
+ dt = torch.exp(
126
+ torch.rand(self.num_heads) * (math.log(dt_max) - math.log(dt_min))
127
+ + math.log(dt_min)
128
+ )
129
+ dt = torch.clamp(dt, min=dt_init_floor)
130
+ # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
131
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
132
+ self.dt_bias = nn.Parameter(inv_dt)
133
+ # Just to be explicit. Without this we already don't put wd on dt_bias because of the check
134
+ # name.endswith("bias") in param_grouping.py
135
+ self.dt_bias._no_weight_decay = True
136
+
137
+ self.dynamic_conv1d = DynamicShortConvolution(
138
+ hidden_size=self.value_dim,
139
+ kernel_size=self.conv_size,
140
+ generator_input_size=self.hidden_size,
141
+ generator_reduction=jet_block_config.dconv_generator_reduction,
142
+ static_conv_init=lambda x: init_linear_conv1d(x, std=initializer_range),
143
+ implementation=jet_block_config.dconv_implementation,
144
+ )
145
+
146
+ self.g_proj = nn.Linear(hidden_size, self.value_dim, bias=False)
147
+ self.o_norm = FusedRMSNormGated(self.head_v_dim, eps=float(jet_block_config.norm_eps), autotune_interval=self.autotune_interval)
148
+ self.o_proj = nn.Linear(self.value_dim, hidden_size, bias=False)
149
+
150
+ def forward(
151
+ self,
152
+ hidden_states: torch.Tensor,
153
+ past_key_value: Optional[JetNemotronCache] = None,
154
+ attention_mask: Optional[torch.Tensor] = None,
155
+ use_cache: Optional[bool] = False,
156
+ **kwargs
157
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[JetNemotronCache]]:
158
+ if attention_mask is not None:
159
+ if len(attention_mask.shape) > 2:
160
+ attention_mask = attention_mask.squeeze(1)
161
+ attention_mask = torch.where(attention_mask[:, -1] > -1, 1, 0)
162
+
163
+ assert len(attention_mask.shape) == 2, (
164
+ "Expected attention_mask as a 0-1 matrix with shape [batch_size, seq_len] "
165
+ "for padding purposes (0 indicating padding). "
166
+ "Arbitrary attention masks of shape [batch_size, seq_len, seq_len] are not allowed."
167
+ )
168
+
169
+ batch_size, q_len, _ = hidden_states.shape
170
+ # change to inference mode.
171
+ mode = 'fused_recurrent' if q_len <= 64 else self.mode
172
+ if self.training:
173
+ assert mode == 'chunk', "Only chunk mode is supported in training."
174
+
175
+ last_state = None
176
+ if past_key_value is not None and len(past_key_value) > self.layer_idx:
177
+ last_state = past_key_value[self.layer_idx]
178
+
179
+ cu_seqlens = kwargs.get('cu_seqlens', None)
180
+ if attention_mask is not None and q_len > 1:
181
+ indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:])
182
+
183
+ conv_state = None
184
+
185
+ conv_mask = attention_mask[:, -hidden_states.shape[1]:] if attention_mask is not None else None
186
+
187
+ q = F.silu(self.q_proj(hidden_states))
188
+ k = F.silu(self.k_proj(hidden_states))
189
+
190
+ conv_state_v = None
191
+ if last_state is not None:
192
+ conv_state_v = last_state['conv_state'][-1]
193
+ v, conv_state_v = self.dynamic_conv1d(
194
+ x=self.v_proj(hidden_states),
195
+ generator_input=hidden_states,
196
+ mask=conv_mask,
197
+ cache=conv_state_v,
198
+ output_final_state=use_cache,
199
+ )
200
+ conv_state = conv_state + (conv_state_v,) if conv_state is not None else (conv_state_v,)
201
+
202
+ if attention_mask is not None and q_len > 1:
203
+ q = index_first_axis(rearrange(q, "b s ... -> (b s) ..."), indices).unsqueeze(0)
204
+ k = index_first_axis(rearrange(k, "b s ... -> (b s) ..."), indices).unsqueeze(0)
205
+ v = index_first_axis(rearrange(v, "b s ... -> (b s) ..."), indices).unsqueeze(0)
206
+ hidden_states = index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices).unsqueeze(0)
207
+
208
+ q, k = map(lambda x: rearrange(x, '... (h d) -> ... h d', d=self.head_k_dim), (q, k))
209
+ v = rearrange(v, '... (h d) -> ... h d', d=self.head_v_dim)
210
+ beta = self.b_proj(hidden_states).sigmoid()
211
+
212
+ g = -self.A_log.float().exp() * F.softplus(self.a_proj(hidden_states).float() + self.dt_bias)
213
+
214
+ recurrent_state = last_state['recurrent_state'] if last_state is not None else None
215
+ if mode == 'chunk':
216
+ o, recurrent_state = chunk_gated_delta_rule(
217
+ q=q,
218
+ k=k,
219
+ v=v,
220
+ g=g,
221
+ beta=beta,
222
+ initial_state=recurrent_state,
223
+ output_final_state=use_cache,
224
+ cu_seqlens=cu_seqlens,
225
+ use_qk_l2norm_in_kernel=True,
226
+ autotune_interval=self.autotune_interval
227
+ )
228
+ elif mode == 'fused_recurrent':
229
+ o, recurrent_state = fused_recurrent_gated_delta_rule(
230
+ q=q,
231
+ k=k,
232
+ v=v,
233
+ g=g,
234
+ beta=beta,
235
+ initial_state=recurrent_state,
236
+ output_final_state=use_cache,
237
+ cu_seqlens=cu_seqlens,
238
+ use_qk_l2norm_in_kernel=True
239
+ )
240
+ else:
241
+ raise NotImplementedError(f"Not supported mode `{mode}`.")
242
+
243
+ if past_key_value is not None:
244
+ past_key_value.update(
245
+ recurrent_state=recurrent_state,
246
+ conv_state=conv_state,
247
+ layer_idx=self.layer_idx,
248
+ offset=q_len
249
+ )
250
+
251
+ g = rearrange(self.g_proj(hidden_states), '... (h d) -> ... h d', d=self.head_v_dim)
252
+ o = self.o_norm(o, g)
253
+ o = rearrange(o, 'b t h d -> b t (h d)')
254
+ o = self.o_proj(o)
255
+ if attention_mask is not None and q_len > 1:
256
+ o = pad_input(o.squeeze(0), indices, batch_size, q_len)
257
+
258
+ return o, past_key_value
kv_cache.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ from __future__ import annotations
18
+
19
+ from typing import Any, Optional
20
+
21
+ import torch
22
+ import transformers
23
+
24
+ __all__ = ["JetCache"]
25
+
26
+
27
+ class JetNemotronCache(transformers.cache_utils.Cache):
28
+
29
+ def __init__(
30
+ self,
31
+ seen_tokens: int = 0
32
+ ) -> JetNemotronCache:
33
+
34
+ self.states: list[dict[str, Any]] = []
35
+ self.layer_wise_states: dict[str, Any] = {}
36
+
37
+ self._base_seen_tokens = seen_tokens
38
+ self._seen_tokens = [] # Used in `generate` to keep tally of how many tokens the cache has seen
39
+
40
+ def __getitem__(self, layer_idx: int) -> dict[str, Any]:
41
+ if layer_idx < len(self):
42
+ return self.states[layer_idx]
43
+ else:
44
+ raise KeyError(f"Cache only has {len(self)} layers, attempted to access layer with index {layer_idx}")
45
+
46
+ def __iter__(self):
47
+ for state in self.states:
48
+ yield state
49
+
50
+ def __len__(self):
51
+ return len(self.states)
52
+
53
+ def update(
54
+ self,
55
+ recurrent_state: torch.Tensor = None,
56
+ attn_state: tuple[torch.Tensor, torch.Tensor] = None,
57
+ conv_state: tuple[torch.Tensor] = None,
58
+ ffn_state: torch.Tensor = None,
59
+ layer_idx: int = 0,
60
+ offset: Optional[int] = 1,
61
+ increase_seen_tokens: bool = True,
62
+ cache_kwargs: dict[str, Any] = {},
63
+ ) -> dict[str, Any]:
64
+ """
65
+ Updates the cache with the new `recurrent_state`/`attn_state`/`conv_state` for the layer `layer_idx`.
66
+
67
+ Args:
68
+ recurrent_state (`torch.Tensor`, `optional`):
69
+ The new recurrent state to cache.
70
+ attn_state (`Tuple[torch.Tensor, torch.Tensor]`, `optional`):
71
+ The new attention key/value states to cache.
72
+ conv_state (`Tuple[torch.Tensor]`, `optional`):
73
+ The new convolution state to cache.
74
+ layer_idx (`int`, defaults to 0):
75
+ The index of the layer to cache the states for.
76
+ offset (`int`, `optional`, defaults to 1):
77
+ The number of new tokens being processed.
78
+ cache_kwargs (`Dict[str, Any]`, `optional`):
79
+ Additional arguments for the cache subclass.
80
+
81
+ Return:
82
+ Dictionary of the updated state.
83
+ """
84
+ if len(self._seen_tokens) <= layer_idx:
85
+ self._seen_tokens.append(self._base_seen_tokens)
86
+
87
+ # Update the number of seen tokens
88
+ if increase_seen_tokens:
89
+ self.increase_seen_tokens(layer_idx, offset)
90
+
91
+ if attn_state is not None:
92
+ input_size = attn_state[0].shape[-2]
93
+ window_size = cache_kwargs.get('window_size', None)
94
+ if not isinstance(attn_state, tuple) or len(attn_state) != 2:
95
+ raise ValueError("`attn_state` must be a tuple of two tensors for key/value states")
96
+ if len(self.states) <= layer_idx:
97
+ # in prefilling stage
98
+ state = dict(
99
+ recurrent_state=recurrent_state,
100
+ attn_state=attn_state,
101
+ conv_state=conv_state,
102
+ ffn_state=ffn_state
103
+ )
104
+ if attn_state is not None and window_size is not None:
105
+ # in prefilling stage, the cached and returned key/value states are different
106
+ # original key/value states are returned, but the cached states are the last `window_size` tokens
107
+ _key_state = attn_state[0][..., -window_size:, :]
108
+ _value_state = attn_state[1][..., -window_size:, :]
109
+
110
+ _attn_state = (_key_state, _value_state)
111
+ _state = dict(
112
+ recurrent_state=recurrent_state,
113
+ attn_state=_attn_state,
114
+ conv_state=conv_state,
115
+ ffn_state=ffn_state
116
+ )
117
+ self.states.append(_state)
118
+ else:
119
+ self.states.append(state)
120
+ else:
121
+ state = self.states[layer_idx]
122
+ if recurrent_state is not None:
123
+ state['recurrent_state'] = recurrent_state
124
+ if attn_state is not None:
125
+ key_state, value_state = state['attn_state']
126
+ assert window_size is None or key_state.shape[-2] <= window_size
127
+ if window_size is not None and key_state.shape[-2] == window_size and input_size == 1:
128
+ # DO NOT allocate new memory if the cache is full
129
+ # only works in decoding stage
130
+ # roll the key/value states to the left by `input_size`
131
+
132
+ key_state = key_state.roll(-input_size, -2)
133
+ value_state = value_state.roll(-input_size, -2)
134
+
135
+ # replace the last `input_size` tokens with the new key/value states
136
+ key_state[..., -input_size:, :] = attn_state[0]
137
+ value_state[..., -input_size:, :] = attn_state[1]
138
+
139
+ attn_state = (key_state, value_state)
140
+ else:
141
+ # <= window_size or not sliding window or chunk-prefilling (input_size > 1)
142
+ attn_state = (torch.cat([key_state, attn_state[0]], -2),
143
+ torch.cat([value_state, attn_state[1]], -2),)
144
+ state['attn_state'] = attn_state
145
+ if conv_state is not None:
146
+ state['conv_state'] = conv_state
147
+ if ffn_state is not None:
148
+ state['ffn_state'] = ffn_state
149
+
150
+ assert len(self.states) == len(self._seen_tokens)
151
+
152
+ return state
153
+
154
+ def trim_attn_state(self, layer_idx: int, window_size: int) -> None:
155
+ # handle the case when the input length of SWA > 1 and has a cache, especially the chunk-prefilling case
156
+ # this function is called after attention is donw
157
+ assert layer_idx < len(self.states), f"Layer index {layer_idx} out of range for states with length {len(self.states)}"
158
+ state = self.states[layer_idx]
159
+ assert state["attn_state"] is not None, f"Layer {layer_idx} does not have an attention state"
160
+ key_state, value_state = state["attn_state"]
161
+ if key_state.shape[-2] > window_size:
162
+ state["attn_state"] = (
163
+ key_state[..., -window_size:, :],
164
+ value_state[..., -window_size:, :],
165
+ )
166
+
167
+ def increase_seen_tokens(self, layer_idx: int, offset: int = 1) -> None:
168
+ """Increases the number of seen tokens for the layer `layer_idx` by `offset`."""
169
+ self._seen_tokens[layer_idx] += offset
170
+
171
+ def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
172
+ """Returns the sequence length of the cached states. A layer index can be optionally passed."""
173
+ if len(self._seen_tokens) <= layer_idx:
174
+ return self._base_seen_tokens
175
+ return self._seen_tokens[layer_idx]
176
+
177
+ def get_max_length(self) -> Optional[int]:
178
+ """Returns the maximum sequence length of the cached states. Cache does not have a maximum length."""
179
+ return None
180
+
181
+ def to_legacy_cache(self) -> tuple:
182
+ return tuple(self.states)
183
+
184
+ def print_kv_sizes(self) -> None:
185
+ """Returns the size of the cached key/value states."""
186
+ for layer_idx, state in enumerate(self.states):
187
+ if state.get("attn_state", None) is not None:
188
+ key_state, value_state = state["attn_state"]
189
+ # compute state size in MB
190
+ key_size = key_state.element_size() * key_state.nelement() / (1024**2)
191
+ value_size = value_state.element_size() * value_state.nelement() / (1024**2)
192
+ print(key_state.shape, value_state.shape)
193
+ print(f"Layer {layer_idx}: Attention. cache size: {key_size + value_size:.2f} MB")
194
+ if state.get("conv_state", None) is not None:
195
+ conv_state = state["conv_state"]
196
+ # compute state size in MB
197
+ conv_sizes = []
198
+ for conv in conv_state:
199
+ conv_size = conv.element_size() * conv.nelement() / (1024**2)
200
+ conv_sizes.append(conv_size)
201
+ conv_size = sum(conv_sizes)
202
+ print(f"Layer {layer_idx}: Convolution. cache size: {conv_size:.2f} MB")
203
+ if state.get("ffn_state", None) is not None:
204
+ ffn_state = state["ffn_state"]
205
+ # compute state size in MB
206
+ ffn_size = ffn_state.element_size() * ffn_state.nelement() / (1024**2)
207
+ print(f"Layer {layer_idx}: FFN. cache size: {ffn_size:.2f} MB")
208
+ if state.get("recurrent_state", None) is not None:
209
+ recurrent_state = state["recurrent_state"]
210
+ # compute state size in MB
211
+ recurrent_size = recurrent_state.element_size() * recurrent_state.nelement() / (1024**2)
212
+ print(f"Layer {layer_idx}: Recurrent. cache size: {recurrent_size:.2f} MB")
merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
model-00001-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:742ed763b30a428e5e3a67192ecf237a227329257c6f3ac9121cf645329fe806
3
+ size 4999864768
model-00002-of-00002.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c32a8813bfd15cdb1b926472d77f0443dac17edd523da65980d3ff4c4014158e
3
+ size 2921054832
model.safetensors.index.json ADDED
@@ -0,0 +1,597 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_size": 7920850368
4
+ },
5
+ "weight_map": {
6
+ "model.embed_tokens.weight": "model-00001-of-00002.safetensors",
7
+ "model.layers.0.input_layernorm.weight": "model-00001-of-00002.safetensors",
8
+ "model.layers.0.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
9
+ "model.layers.0.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
10
+ "model.layers.0.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
11
+ "model.layers.0.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
12
+ "model.layers.0.self_attn.A_log": "model-00001-of-00002.safetensors",
13
+ "model.layers.0.self_attn.a_proj.weight": "model-00001-of-00002.safetensors",
14
+ "model.layers.0.self_attn.b_proj.weight": "model-00001-of-00002.safetensors",
15
+ "model.layers.0.self_attn.dt_bias": "model-00001-of-00002.safetensors",
16
+ "model.layers.0.self_attn.dynamic_conv1d.kernel_generator.w1.weight": "model-00001-of-00002.safetensors",
17
+ "model.layers.0.self_attn.dynamic_conv1d.kernel_generator.w2.bias": "model-00001-of-00002.safetensors",
18
+ "model.layers.0.self_attn.dynamic_conv1d.kernel_generator.w2.weight": "model-00001-of-00002.safetensors",
19
+ "model.layers.0.self_attn.g_proj.weight": "model-00001-of-00002.safetensors",
20
+ "model.layers.0.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
21
+ "model.layers.0.self_attn.o_norm.weight": "model-00001-of-00002.safetensors",
22
+ "model.layers.0.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
23
+ "model.layers.0.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
24
+ "model.layers.0.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
25
+ "model.layers.1.input_layernorm.weight": "model-00001-of-00002.safetensors",
26
+ "model.layers.1.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
27
+ "model.layers.1.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
28
+ "model.layers.1.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
29
+ "model.layers.1.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
30
+ "model.layers.1.self_attn.A_log": "model-00001-of-00002.safetensors",
31
+ "model.layers.1.self_attn.a_proj.weight": "model-00001-of-00002.safetensors",
32
+ "model.layers.1.self_attn.b_proj.weight": "model-00001-of-00002.safetensors",
33
+ "model.layers.1.self_attn.dt_bias": "model-00001-of-00002.safetensors",
34
+ "model.layers.1.self_attn.dynamic_conv1d.kernel_generator.w1.weight": "model-00001-of-00002.safetensors",
35
+ "model.layers.1.self_attn.dynamic_conv1d.kernel_generator.w2.bias": "model-00001-of-00002.safetensors",
36
+ "model.layers.1.self_attn.dynamic_conv1d.kernel_generator.w2.weight": "model-00001-of-00002.safetensors",
37
+ "model.layers.1.self_attn.g_proj.weight": "model-00001-of-00002.safetensors",
38
+ "model.layers.1.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
39
+ "model.layers.1.self_attn.o_norm.weight": "model-00001-of-00002.safetensors",
40
+ "model.layers.1.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
41
+ "model.layers.1.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
42
+ "model.layers.1.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
43
+ "model.layers.10.input_layernorm.weight": "model-00001-of-00002.safetensors",
44
+ "model.layers.10.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
45
+ "model.layers.10.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
46
+ "model.layers.10.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
47
+ "model.layers.10.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
48
+ "model.layers.10.self_attn.A_log": "model-00001-of-00002.safetensors",
49
+ "model.layers.10.self_attn.a_proj.weight": "model-00001-of-00002.safetensors",
50
+ "model.layers.10.self_attn.b_proj.weight": "model-00001-of-00002.safetensors",
51
+ "model.layers.10.self_attn.dt_bias": "model-00001-of-00002.safetensors",
52
+ "model.layers.10.self_attn.dynamic_conv1d.kernel_generator.w1.weight": "model-00001-of-00002.safetensors",
53
+ "model.layers.10.self_attn.dynamic_conv1d.kernel_generator.w2.bias": "model-00001-of-00002.safetensors",
54
+ "model.layers.10.self_attn.dynamic_conv1d.kernel_generator.w2.weight": "model-00001-of-00002.safetensors",
55
+ "model.layers.10.self_attn.g_proj.weight": "model-00001-of-00002.safetensors",
56
+ "model.layers.10.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
57
+ "model.layers.10.self_attn.o_norm.weight": "model-00001-of-00002.safetensors",
58
+ "model.layers.10.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
59
+ "model.layers.10.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
60
+ "model.layers.10.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
61
+ "model.layers.11.input_layernorm.weight": "model-00001-of-00002.safetensors",
62
+ "model.layers.11.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
63
+ "model.layers.11.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
64
+ "model.layers.11.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
65
+ "model.layers.11.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
66
+ "model.layers.11.self_attn.A_log": "model-00001-of-00002.safetensors",
67
+ "model.layers.11.self_attn.a_proj.weight": "model-00001-of-00002.safetensors",
68
+ "model.layers.11.self_attn.b_proj.weight": "model-00001-of-00002.safetensors",
69
+ "model.layers.11.self_attn.dt_bias": "model-00001-of-00002.safetensors",
70
+ "model.layers.11.self_attn.dynamic_conv1d.kernel_generator.w1.weight": "model-00001-of-00002.safetensors",
71
+ "model.layers.11.self_attn.dynamic_conv1d.kernel_generator.w2.bias": "model-00001-of-00002.safetensors",
72
+ "model.layers.11.self_attn.dynamic_conv1d.kernel_generator.w2.weight": "model-00001-of-00002.safetensors",
73
+ "model.layers.11.self_attn.g_proj.weight": "model-00001-of-00002.safetensors",
74
+ "model.layers.11.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
75
+ "model.layers.11.self_attn.o_norm.weight": "model-00001-of-00002.safetensors",
76
+ "model.layers.11.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
77
+ "model.layers.11.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
78
+ "model.layers.11.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
79
+ "model.layers.12.input_layernorm.weight": "model-00001-of-00002.safetensors",
80
+ "model.layers.12.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
81
+ "model.layers.12.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
82
+ "model.layers.12.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
83
+ "model.layers.12.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
84
+ "model.layers.12.self_attn.A_log": "model-00001-of-00002.safetensors",
85
+ "model.layers.12.self_attn.a_proj.weight": "model-00001-of-00002.safetensors",
86
+ "model.layers.12.self_attn.b_proj.weight": "model-00001-of-00002.safetensors",
87
+ "model.layers.12.self_attn.dt_bias": "model-00001-of-00002.safetensors",
88
+ "model.layers.12.self_attn.dynamic_conv1d.kernel_generator.w1.weight": "model-00001-of-00002.safetensors",
89
+ "model.layers.12.self_attn.dynamic_conv1d.kernel_generator.w2.bias": "model-00001-of-00002.safetensors",
90
+ "model.layers.12.self_attn.dynamic_conv1d.kernel_generator.w2.weight": "model-00001-of-00002.safetensors",
91
+ "model.layers.12.self_attn.g_proj.weight": "model-00001-of-00002.safetensors",
92
+ "model.layers.12.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
93
+ "model.layers.12.self_attn.o_norm.weight": "model-00001-of-00002.safetensors",
94
+ "model.layers.12.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
95
+ "model.layers.12.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
96
+ "model.layers.12.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
97
+ "model.layers.13.input_layernorm.weight": "model-00001-of-00002.safetensors",
98
+ "model.layers.13.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
99
+ "model.layers.13.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
100
+ "model.layers.13.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
101
+ "model.layers.13.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
102
+ "model.layers.13.self_attn.A_log": "model-00001-of-00002.safetensors",
103
+ "model.layers.13.self_attn.a_proj.weight": "model-00001-of-00002.safetensors",
104
+ "model.layers.13.self_attn.b_proj.weight": "model-00001-of-00002.safetensors",
105
+ "model.layers.13.self_attn.dt_bias": "model-00001-of-00002.safetensors",
106
+ "model.layers.13.self_attn.dynamic_conv1d.kernel_generator.w1.weight": "model-00001-of-00002.safetensors",
107
+ "model.layers.13.self_attn.dynamic_conv1d.kernel_generator.w2.bias": "model-00001-of-00002.safetensors",
108
+ "model.layers.13.self_attn.dynamic_conv1d.kernel_generator.w2.weight": "model-00001-of-00002.safetensors",
109
+ "model.layers.13.self_attn.g_proj.weight": "model-00001-of-00002.safetensors",
110
+ "model.layers.13.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
111
+ "model.layers.13.self_attn.o_norm.weight": "model-00001-of-00002.safetensors",
112
+ "model.layers.13.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
113
+ "model.layers.13.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
114
+ "model.layers.13.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
115
+ "model.layers.14.input_layernorm.weight": "model-00001-of-00002.safetensors",
116
+ "model.layers.14.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
117
+ "model.layers.14.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
118
+ "model.layers.14.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
119
+ "model.layers.14.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
120
+ "model.layers.14.self_attn.A_log": "model-00001-of-00002.safetensors",
121
+ "model.layers.14.self_attn.a_proj.weight": "model-00001-of-00002.safetensors",
122
+ "model.layers.14.self_attn.b_proj.weight": "model-00001-of-00002.safetensors",
123
+ "model.layers.14.self_attn.dt_bias": "model-00001-of-00002.safetensors",
124
+ "model.layers.14.self_attn.dynamic_conv1d.kernel_generator.w1.weight": "model-00001-of-00002.safetensors",
125
+ "model.layers.14.self_attn.dynamic_conv1d.kernel_generator.w2.bias": "model-00001-of-00002.safetensors",
126
+ "model.layers.14.self_attn.dynamic_conv1d.kernel_generator.w2.weight": "model-00001-of-00002.safetensors",
127
+ "model.layers.14.self_attn.g_proj.weight": "model-00001-of-00002.safetensors",
128
+ "model.layers.14.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
129
+ "model.layers.14.self_attn.o_norm.weight": "model-00001-of-00002.safetensors",
130
+ "model.layers.14.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
131
+ "model.layers.14.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
132
+ "model.layers.14.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
133
+ "model.layers.15.input_layernorm.weight": "model-00001-of-00002.safetensors",
134
+ "model.layers.15.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
135
+ "model.layers.15.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
136
+ "model.layers.15.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
137
+ "model.layers.15.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
138
+ "model.layers.15.self_attn.A_log": "model-00001-of-00002.safetensors",
139
+ "model.layers.15.self_attn.a_proj.weight": "model-00001-of-00002.safetensors",
140
+ "model.layers.15.self_attn.b_proj.weight": "model-00001-of-00002.safetensors",
141
+ "model.layers.15.self_attn.dt_bias": "model-00001-of-00002.safetensors",
142
+ "model.layers.15.self_attn.dynamic_conv1d.kernel_generator.w1.weight": "model-00001-of-00002.safetensors",
143
+ "model.layers.15.self_attn.dynamic_conv1d.kernel_generator.w2.bias": "model-00001-of-00002.safetensors",
144
+ "model.layers.15.self_attn.dynamic_conv1d.kernel_generator.w2.weight": "model-00001-of-00002.safetensors",
145
+ "model.layers.15.self_attn.g_proj.weight": "model-00001-of-00002.safetensors",
146
+ "model.layers.15.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
147
+ "model.layers.15.self_attn.o_norm.weight": "model-00001-of-00002.safetensors",
148
+ "model.layers.15.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
149
+ "model.layers.15.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
150
+ "model.layers.15.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
151
+ "model.layers.16.input_layernorm.weight": "model-00001-of-00002.safetensors",
152
+ "model.layers.16.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
153
+ "model.layers.16.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
154
+ "model.layers.16.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
155
+ "model.layers.16.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
156
+ "model.layers.16.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
157
+ "model.layers.16.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
158
+ "model.layers.16.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
159
+ "model.layers.16.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
160
+ "model.layers.16.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
161
+ "model.layers.16.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
162
+ "model.layers.16.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
163
+ "model.layers.17.input_layernorm.weight": "model-00001-of-00002.safetensors",
164
+ "model.layers.17.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
165
+ "model.layers.17.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
166
+ "model.layers.17.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
167
+ "model.layers.17.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
168
+ "model.layers.17.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
169
+ "model.layers.17.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
170
+ "model.layers.17.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
171
+ "model.layers.17.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
172
+ "model.layers.17.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
173
+ "model.layers.17.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
174
+ "model.layers.17.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
175
+ "model.layers.18.input_layernorm.weight": "model-00001-of-00002.safetensors",
176
+ "model.layers.18.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
177
+ "model.layers.18.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
178
+ "model.layers.18.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
179
+ "model.layers.18.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
180
+ "model.layers.18.self_attn.A_log": "model-00001-of-00002.safetensors",
181
+ "model.layers.18.self_attn.a_proj.weight": "model-00001-of-00002.safetensors",
182
+ "model.layers.18.self_attn.b_proj.weight": "model-00001-of-00002.safetensors",
183
+ "model.layers.18.self_attn.dt_bias": "model-00001-of-00002.safetensors",
184
+ "model.layers.18.self_attn.dynamic_conv1d.kernel_generator.w1.weight": "model-00001-of-00002.safetensors",
185
+ "model.layers.18.self_attn.dynamic_conv1d.kernel_generator.w2.bias": "model-00001-of-00002.safetensors",
186
+ "model.layers.18.self_attn.dynamic_conv1d.kernel_generator.w2.weight": "model-00001-of-00002.safetensors",
187
+ "model.layers.18.self_attn.g_proj.weight": "model-00001-of-00002.safetensors",
188
+ "model.layers.18.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
189
+ "model.layers.18.self_attn.o_norm.weight": "model-00001-of-00002.safetensors",
190
+ "model.layers.18.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
191
+ "model.layers.18.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
192
+ "model.layers.18.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
193
+ "model.layers.19.input_layernorm.weight": "model-00001-of-00002.safetensors",
194
+ "model.layers.19.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
195
+ "model.layers.19.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
196
+ "model.layers.19.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
197
+ "model.layers.19.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
198
+ "model.layers.19.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
199
+ "model.layers.19.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
200
+ "model.layers.19.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
201
+ "model.layers.19.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
202
+ "model.layers.19.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
203
+ "model.layers.19.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
204
+ "model.layers.19.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
205
+ "model.layers.2.input_layernorm.weight": "model-00001-of-00002.safetensors",
206
+ "model.layers.2.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
207
+ "model.layers.2.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
208
+ "model.layers.2.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
209
+ "model.layers.2.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
210
+ "model.layers.2.self_attn.A_log": "model-00001-of-00002.safetensors",
211
+ "model.layers.2.self_attn.a_proj.weight": "model-00001-of-00002.safetensors",
212
+ "model.layers.2.self_attn.b_proj.weight": "model-00001-of-00002.safetensors",
213
+ "model.layers.2.self_attn.dt_bias": "model-00001-of-00002.safetensors",
214
+ "model.layers.2.self_attn.dynamic_conv1d.kernel_generator.w1.weight": "model-00001-of-00002.safetensors",
215
+ "model.layers.2.self_attn.dynamic_conv1d.kernel_generator.w2.bias": "model-00001-of-00002.safetensors",
216
+ "model.layers.2.self_attn.dynamic_conv1d.kernel_generator.w2.weight": "model-00001-of-00002.safetensors",
217
+ "model.layers.2.self_attn.g_proj.weight": "model-00001-of-00002.safetensors",
218
+ "model.layers.2.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
219
+ "model.layers.2.self_attn.o_norm.weight": "model-00001-of-00002.safetensors",
220
+ "model.layers.2.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
221
+ "model.layers.2.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
222
+ "model.layers.2.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
223
+ "model.layers.20.input_layernorm.weight": "model-00001-of-00002.safetensors",
224
+ "model.layers.20.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
225
+ "model.layers.20.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
226
+ "model.layers.20.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
227
+ "model.layers.20.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
228
+ "model.layers.20.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
229
+ "model.layers.20.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
230
+ "model.layers.20.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
231
+ "model.layers.20.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
232
+ "model.layers.20.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
233
+ "model.layers.20.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
234
+ "model.layers.20.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
235
+ "model.layers.21.input_layernorm.weight": "model-00002-of-00002.safetensors",
236
+ "model.layers.21.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
237
+ "model.layers.21.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
238
+ "model.layers.21.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
239
+ "model.layers.21.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
240
+ "model.layers.21.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
241
+ "model.layers.21.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
242
+ "model.layers.21.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
243
+ "model.layers.21.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
244
+ "model.layers.21.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
245
+ "model.layers.21.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
246
+ "model.layers.21.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
247
+ "model.layers.22.input_layernorm.weight": "model-00002-of-00002.safetensors",
248
+ "model.layers.22.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
249
+ "model.layers.22.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
250
+ "model.layers.22.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
251
+ "model.layers.22.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
252
+ "model.layers.22.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
253
+ "model.layers.22.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
254
+ "model.layers.22.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
255
+ "model.layers.22.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
256
+ "model.layers.22.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
257
+ "model.layers.22.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
258
+ "model.layers.22.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
259
+ "model.layers.23.input_layernorm.weight": "model-00002-of-00002.safetensors",
260
+ "model.layers.23.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
261
+ "model.layers.23.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
262
+ "model.layers.23.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
263
+ "model.layers.23.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
264
+ "model.layers.23.self_attn.A_log": "model-00002-of-00002.safetensors",
265
+ "model.layers.23.self_attn.a_proj.weight": "model-00002-of-00002.safetensors",
266
+ "model.layers.23.self_attn.b_proj.weight": "model-00002-of-00002.safetensors",
267
+ "model.layers.23.self_attn.dt_bias": "model-00002-of-00002.safetensors",
268
+ "model.layers.23.self_attn.dynamic_conv1d.kernel_generator.w1.weight": "model-00002-of-00002.safetensors",
269
+ "model.layers.23.self_attn.dynamic_conv1d.kernel_generator.w2.bias": "model-00002-of-00002.safetensors",
270
+ "model.layers.23.self_attn.dynamic_conv1d.kernel_generator.w2.weight": "model-00002-of-00002.safetensors",
271
+ "model.layers.23.self_attn.g_proj.weight": "model-00002-of-00002.safetensors",
272
+ "model.layers.23.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
273
+ "model.layers.23.self_attn.o_norm.weight": "model-00002-of-00002.safetensors",
274
+ "model.layers.23.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
275
+ "model.layers.23.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
276
+ "model.layers.23.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
277
+ "model.layers.24.input_layernorm.weight": "model-00002-of-00002.safetensors",
278
+ "model.layers.24.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
279
+ "model.layers.24.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
280
+ "model.layers.24.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
281
+ "model.layers.24.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
282
+ "model.layers.24.self_attn.A_log": "model-00002-of-00002.safetensors",
283
+ "model.layers.24.self_attn.a_proj.weight": "model-00002-of-00002.safetensors",
284
+ "model.layers.24.self_attn.b_proj.weight": "model-00002-of-00002.safetensors",
285
+ "model.layers.24.self_attn.dt_bias": "model-00002-of-00002.safetensors",
286
+ "model.layers.24.self_attn.dynamic_conv1d.kernel_generator.w1.weight": "model-00002-of-00002.safetensors",
287
+ "model.layers.24.self_attn.dynamic_conv1d.kernel_generator.w2.bias": "model-00002-of-00002.safetensors",
288
+ "model.layers.24.self_attn.dynamic_conv1d.kernel_generator.w2.weight": "model-00002-of-00002.safetensors",
289
+ "model.layers.24.self_attn.g_proj.weight": "model-00002-of-00002.safetensors",
290
+ "model.layers.24.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
291
+ "model.layers.24.self_attn.o_norm.weight": "model-00002-of-00002.safetensors",
292
+ "model.layers.24.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
293
+ "model.layers.24.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
294
+ "model.layers.24.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
295
+ "model.layers.25.input_layernorm.weight": "model-00002-of-00002.safetensors",
296
+ "model.layers.25.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
297
+ "model.layers.25.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
298
+ "model.layers.25.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
299
+ "model.layers.25.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
300
+ "model.layers.25.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
301
+ "model.layers.25.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
302
+ "model.layers.25.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
303
+ "model.layers.25.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
304
+ "model.layers.25.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
305
+ "model.layers.25.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
306
+ "model.layers.25.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
307
+ "model.layers.26.input_layernorm.weight": "model-00002-of-00002.safetensors",
308
+ "model.layers.26.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
309
+ "model.layers.26.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
310
+ "model.layers.26.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
311
+ "model.layers.26.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
312
+ "model.layers.26.self_attn.A_log": "model-00002-of-00002.safetensors",
313
+ "model.layers.26.self_attn.a_proj.weight": "model-00002-of-00002.safetensors",
314
+ "model.layers.26.self_attn.b_proj.weight": "model-00002-of-00002.safetensors",
315
+ "model.layers.26.self_attn.dt_bias": "model-00002-of-00002.safetensors",
316
+ "model.layers.26.self_attn.dynamic_conv1d.kernel_generator.w1.weight": "model-00002-of-00002.safetensors",
317
+ "model.layers.26.self_attn.dynamic_conv1d.kernel_generator.w2.bias": "model-00002-of-00002.safetensors",
318
+ "model.layers.26.self_attn.dynamic_conv1d.kernel_generator.w2.weight": "model-00002-of-00002.safetensors",
319
+ "model.layers.26.self_attn.g_proj.weight": "model-00002-of-00002.safetensors",
320
+ "model.layers.26.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
321
+ "model.layers.26.self_attn.o_norm.weight": "model-00002-of-00002.safetensors",
322
+ "model.layers.26.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
323
+ "model.layers.26.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
324
+ "model.layers.26.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
325
+ "model.layers.27.input_layernorm.weight": "model-00002-of-00002.safetensors",
326
+ "model.layers.27.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
327
+ "model.layers.27.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
328
+ "model.layers.27.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
329
+ "model.layers.27.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
330
+ "model.layers.27.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
331
+ "model.layers.27.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
332
+ "model.layers.27.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
333
+ "model.layers.27.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
334
+ "model.layers.27.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
335
+ "model.layers.27.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
336
+ "model.layers.27.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
337
+ "model.layers.28.input_layernorm.weight": "model-00002-of-00002.safetensors",
338
+ "model.layers.28.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
339
+ "model.layers.28.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
340
+ "model.layers.28.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
341
+ "model.layers.28.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
342
+ "model.layers.28.self_attn.A_log": "model-00002-of-00002.safetensors",
343
+ "model.layers.28.self_attn.a_proj.weight": "model-00002-of-00002.safetensors",
344
+ "model.layers.28.self_attn.b_proj.weight": "model-00002-of-00002.safetensors",
345
+ "model.layers.28.self_attn.dt_bias": "model-00002-of-00002.safetensors",
346
+ "model.layers.28.self_attn.dynamic_conv1d.kernel_generator.w1.weight": "model-00002-of-00002.safetensors",
347
+ "model.layers.28.self_attn.dynamic_conv1d.kernel_generator.w2.bias": "model-00002-of-00002.safetensors",
348
+ "model.layers.28.self_attn.dynamic_conv1d.kernel_generator.w2.weight": "model-00002-of-00002.safetensors",
349
+ "model.layers.28.self_attn.g_proj.weight": "model-00002-of-00002.safetensors",
350
+ "model.layers.28.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
351
+ "model.layers.28.self_attn.o_norm.weight": "model-00002-of-00002.safetensors",
352
+ "model.layers.28.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
353
+ "model.layers.28.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
354
+ "model.layers.28.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
355
+ "model.layers.29.input_layernorm.weight": "model-00002-of-00002.safetensors",
356
+ "model.layers.29.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
357
+ "model.layers.29.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
358
+ "model.layers.29.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
359
+ "model.layers.29.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
360
+ "model.layers.29.self_attn.A_log": "model-00002-of-00002.safetensors",
361
+ "model.layers.29.self_attn.a_proj.weight": "model-00002-of-00002.safetensors",
362
+ "model.layers.29.self_attn.b_proj.weight": "model-00002-of-00002.safetensors",
363
+ "model.layers.29.self_attn.dt_bias": "model-00002-of-00002.safetensors",
364
+ "model.layers.29.self_attn.dynamic_conv1d.kernel_generator.w1.weight": "model-00002-of-00002.safetensors",
365
+ "model.layers.29.self_attn.dynamic_conv1d.kernel_generator.w2.bias": "model-00002-of-00002.safetensors",
366
+ "model.layers.29.self_attn.dynamic_conv1d.kernel_generator.w2.weight": "model-00002-of-00002.safetensors",
367
+ "model.layers.29.self_attn.g_proj.weight": "model-00002-of-00002.safetensors",
368
+ "model.layers.29.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
369
+ "model.layers.29.self_attn.o_norm.weight": "model-00002-of-00002.safetensors",
370
+ "model.layers.29.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
371
+ "model.layers.29.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
372
+ "model.layers.29.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
373
+ "model.layers.3.input_layernorm.weight": "model-00001-of-00002.safetensors",
374
+ "model.layers.3.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
375
+ "model.layers.3.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
376
+ "model.layers.3.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
377
+ "model.layers.3.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
378
+ "model.layers.3.self_attn.A_log": "model-00001-of-00002.safetensors",
379
+ "model.layers.3.self_attn.a_proj.weight": "model-00001-of-00002.safetensors",
380
+ "model.layers.3.self_attn.b_proj.weight": "model-00001-of-00002.safetensors",
381
+ "model.layers.3.self_attn.dt_bias": "model-00001-of-00002.safetensors",
382
+ "model.layers.3.self_attn.dynamic_conv1d.kernel_generator.w1.weight": "model-00001-of-00002.safetensors",
383
+ "model.layers.3.self_attn.dynamic_conv1d.kernel_generator.w2.bias": "model-00001-of-00002.safetensors",
384
+ "model.layers.3.self_attn.dynamic_conv1d.kernel_generator.w2.weight": "model-00001-of-00002.safetensors",
385
+ "model.layers.3.self_attn.g_proj.weight": "model-00001-of-00002.safetensors",
386
+ "model.layers.3.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
387
+ "model.layers.3.self_attn.o_norm.weight": "model-00001-of-00002.safetensors",
388
+ "model.layers.3.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
389
+ "model.layers.3.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
390
+ "model.layers.3.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
391
+ "model.layers.30.input_layernorm.weight": "model-00002-of-00002.safetensors",
392
+ "model.layers.30.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
393
+ "model.layers.30.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
394
+ "model.layers.30.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
395
+ "model.layers.30.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
396
+ "model.layers.30.self_attn.A_log": "model-00002-of-00002.safetensors",
397
+ "model.layers.30.self_attn.a_proj.weight": "model-00002-of-00002.safetensors",
398
+ "model.layers.30.self_attn.b_proj.weight": "model-00002-of-00002.safetensors",
399
+ "model.layers.30.self_attn.dt_bias": "model-00002-of-00002.safetensors",
400
+ "model.layers.30.self_attn.dynamic_conv1d.kernel_generator.w1.weight": "model-00002-of-00002.safetensors",
401
+ "model.layers.30.self_attn.dynamic_conv1d.kernel_generator.w2.bias": "model-00002-of-00002.safetensors",
402
+ "model.layers.30.self_attn.dynamic_conv1d.kernel_generator.w2.weight": "model-00002-of-00002.safetensors",
403
+ "model.layers.30.self_attn.g_proj.weight": "model-00002-of-00002.safetensors",
404
+ "model.layers.30.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
405
+ "model.layers.30.self_attn.o_norm.weight": "model-00002-of-00002.safetensors",
406
+ "model.layers.30.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
407
+ "model.layers.30.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
408
+ "model.layers.30.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
409
+ "model.layers.31.input_layernorm.weight": "model-00002-of-00002.safetensors",
410
+ "model.layers.31.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
411
+ "model.layers.31.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
412
+ "model.layers.31.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
413
+ "model.layers.31.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
414
+ "model.layers.31.self_attn.A_log": "model-00002-of-00002.safetensors",
415
+ "model.layers.31.self_attn.a_proj.weight": "model-00002-of-00002.safetensors",
416
+ "model.layers.31.self_attn.b_proj.weight": "model-00002-of-00002.safetensors",
417
+ "model.layers.31.self_attn.dt_bias": "model-00002-of-00002.safetensors",
418
+ "model.layers.31.self_attn.dynamic_conv1d.kernel_generator.w1.weight": "model-00002-of-00002.safetensors",
419
+ "model.layers.31.self_attn.dynamic_conv1d.kernel_generator.w2.bias": "model-00002-of-00002.safetensors",
420
+ "model.layers.31.self_attn.dynamic_conv1d.kernel_generator.w2.weight": "model-00002-of-00002.safetensors",
421
+ "model.layers.31.self_attn.g_proj.weight": "model-00002-of-00002.safetensors",
422
+ "model.layers.31.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
423
+ "model.layers.31.self_attn.o_norm.weight": "model-00002-of-00002.safetensors",
424
+ "model.layers.31.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
425
+ "model.layers.31.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
426
+ "model.layers.31.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
427
+ "model.layers.32.input_layernorm.weight": "model-00002-of-00002.safetensors",
428
+ "model.layers.32.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
429
+ "model.layers.32.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
430
+ "model.layers.32.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
431
+ "model.layers.32.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
432
+ "model.layers.32.self_attn.k_proj.bias": "model-00002-of-00002.safetensors",
433
+ "model.layers.32.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
434
+ "model.layers.32.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
435
+ "model.layers.32.self_attn.q_proj.bias": "model-00002-of-00002.safetensors",
436
+ "model.layers.32.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
437
+ "model.layers.32.self_attn.v_proj.bias": "model-00002-of-00002.safetensors",
438
+ "model.layers.32.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
439
+ "model.layers.33.input_layernorm.weight": "model-00002-of-00002.safetensors",
440
+ "model.layers.33.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
441
+ "model.layers.33.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
442
+ "model.layers.33.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
443
+ "model.layers.33.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
444
+ "model.layers.33.self_attn.A_log": "model-00002-of-00002.safetensors",
445
+ "model.layers.33.self_attn.a_proj.weight": "model-00002-of-00002.safetensors",
446
+ "model.layers.33.self_attn.b_proj.weight": "model-00002-of-00002.safetensors",
447
+ "model.layers.33.self_attn.dt_bias": "model-00002-of-00002.safetensors",
448
+ "model.layers.33.self_attn.dynamic_conv1d.kernel_generator.w1.weight": "model-00002-of-00002.safetensors",
449
+ "model.layers.33.self_attn.dynamic_conv1d.kernel_generator.w2.bias": "model-00002-of-00002.safetensors",
450
+ "model.layers.33.self_attn.dynamic_conv1d.kernel_generator.w2.weight": "model-00002-of-00002.safetensors",
451
+ "model.layers.33.self_attn.g_proj.weight": "model-00002-of-00002.safetensors",
452
+ "model.layers.33.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
453
+ "model.layers.33.self_attn.o_norm.weight": "model-00002-of-00002.safetensors",
454
+ "model.layers.33.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
455
+ "model.layers.33.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
456
+ "model.layers.33.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
457
+ "model.layers.34.input_layernorm.weight": "model-00002-of-00002.safetensors",
458
+ "model.layers.34.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
459
+ "model.layers.34.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
460
+ "model.layers.34.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
461
+ "model.layers.34.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
462
+ "model.layers.34.self_attn.A_log": "model-00002-of-00002.safetensors",
463
+ "model.layers.34.self_attn.a_proj.weight": "model-00002-of-00002.safetensors",
464
+ "model.layers.34.self_attn.b_proj.weight": "model-00002-of-00002.safetensors",
465
+ "model.layers.34.self_attn.dt_bias": "model-00002-of-00002.safetensors",
466
+ "model.layers.34.self_attn.dynamic_conv1d.kernel_generator.w1.weight": "model-00002-of-00002.safetensors",
467
+ "model.layers.34.self_attn.dynamic_conv1d.kernel_generator.w2.bias": "model-00002-of-00002.safetensors",
468
+ "model.layers.34.self_attn.dynamic_conv1d.kernel_generator.w2.weight": "model-00002-of-00002.safetensors",
469
+ "model.layers.34.self_attn.g_proj.weight": "model-00002-of-00002.safetensors",
470
+ "model.layers.34.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
471
+ "model.layers.34.self_attn.o_norm.weight": "model-00002-of-00002.safetensors",
472
+ "model.layers.34.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
473
+ "model.layers.34.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
474
+ "model.layers.34.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
475
+ "model.layers.35.input_layernorm.weight": "model-00002-of-00002.safetensors",
476
+ "model.layers.35.mlp.down_proj.weight": "model-00002-of-00002.safetensors",
477
+ "model.layers.35.mlp.gate_proj.weight": "model-00002-of-00002.safetensors",
478
+ "model.layers.35.mlp.up_proj.weight": "model-00002-of-00002.safetensors",
479
+ "model.layers.35.post_attention_layernorm.weight": "model-00002-of-00002.safetensors",
480
+ "model.layers.35.self_attn.A_log": "model-00002-of-00002.safetensors",
481
+ "model.layers.35.self_attn.a_proj.weight": "model-00002-of-00002.safetensors",
482
+ "model.layers.35.self_attn.b_proj.weight": "model-00002-of-00002.safetensors",
483
+ "model.layers.35.self_attn.dt_bias": "model-00002-of-00002.safetensors",
484
+ "model.layers.35.self_attn.dynamic_conv1d.kernel_generator.w1.weight": "model-00002-of-00002.safetensors",
485
+ "model.layers.35.self_attn.dynamic_conv1d.kernel_generator.w2.bias": "model-00002-of-00002.safetensors",
486
+ "model.layers.35.self_attn.dynamic_conv1d.kernel_generator.w2.weight": "model-00002-of-00002.safetensors",
487
+ "model.layers.35.self_attn.g_proj.weight": "model-00002-of-00002.safetensors",
488
+ "model.layers.35.self_attn.k_proj.weight": "model-00002-of-00002.safetensors",
489
+ "model.layers.35.self_attn.o_norm.weight": "model-00002-of-00002.safetensors",
490
+ "model.layers.35.self_attn.o_proj.weight": "model-00002-of-00002.safetensors",
491
+ "model.layers.35.self_attn.q_proj.weight": "model-00002-of-00002.safetensors",
492
+ "model.layers.35.self_attn.v_proj.weight": "model-00002-of-00002.safetensors",
493
+ "model.layers.4.input_layernorm.weight": "model-00001-of-00002.safetensors",
494
+ "model.layers.4.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
495
+ "model.layers.4.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
496
+ "model.layers.4.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
497
+ "model.layers.4.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
498
+ "model.layers.4.self_attn.A_log": "model-00001-of-00002.safetensors",
499
+ "model.layers.4.self_attn.a_proj.weight": "model-00001-of-00002.safetensors",
500
+ "model.layers.4.self_attn.b_proj.weight": "model-00001-of-00002.safetensors",
501
+ "model.layers.4.self_attn.dt_bias": "model-00001-of-00002.safetensors",
502
+ "model.layers.4.self_attn.dynamic_conv1d.kernel_generator.w1.weight": "model-00001-of-00002.safetensors",
503
+ "model.layers.4.self_attn.dynamic_conv1d.kernel_generator.w2.bias": "model-00001-of-00002.safetensors",
504
+ "model.layers.4.self_attn.dynamic_conv1d.kernel_generator.w2.weight": "model-00001-of-00002.safetensors",
505
+ "model.layers.4.self_attn.g_proj.weight": "model-00001-of-00002.safetensors",
506
+ "model.layers.4.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
507
+ "model.layers.4.self_attn.o_norm.weight": "model-00001-of-00002.safetensors",
508
+ "model.layers.4.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
509
+ "model.layers.4.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
510
+ "model.layers.4.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
511
+ "model.layers.5.input_layernorm.weight": "model-00001-of-00002.safetensors",
512
+ "model.layers.5.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
513
+ "model.layers.5.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
514
+ "model.layers.5.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
515
+ "model.layers.5.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
516
+ "model.layers.5.self_attn.k_proj.bias": "model-00001-of-00002.safetensors",
517
+ "model.layers.5.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
518
+ "model.layers.5.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
519
+ "model.layers.5.self_attn.q_proj.bias": "model-00001-of-00002.safetensors",
520
+ "model.layers.5.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
521
+ "model.layers.5.self_attn.v_proj.bias": "model-00001-of-00002.safetensors",
522
+ "model.layers.5.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
523
+ "model.layers.6.input_layernorm.weight": "model-00001-of-00002.safetensors",
524
+ "model.layers.6.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
525
+ "model.layers.6.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
526
+ "model.layers.6.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
527
+ "model.layers.6.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
528
+ "model.layers.6.self_attn.A_log": "model-00001-of-00002.safetensors",
529
+ "model.layers.6.self_attn.a_proj.weight": "model-00001-of-00002.safetensors",
530
+ "model.layers.6.self_attn.b_proj.weight": "model-00001-of-00002.safetensors",
531
+ "model.layers.6.self_attn.dt_bias": "model-00001-of-00002.safetensors",
532
+ "model.layers.6.self_attn.dynamic_conv1d.kernel_generator.w1.weight": "model-00001-of-00002.safetensors",
533
+ "model.layers.6.self_attn.dynamic_conv1d.kernel_generator.w2.bias": "model-00001-of-00002.safetensors",
534
+ "model.layers.6.self_attn.dynamic_conv1d.kernel_generator.w2.weight": "model-00001-of-00002.safetensors",
535
+ "model.layers.6.self_attn.g_proj.weight": "model-00001-of-00002.safetensors",
536
+ "model.layers.6.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
537
+ "model.layers.6.self_attn.o_norm.weight": "model-00001-of-00002.safetensors",
538
+ "model.layers.6.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
539
+ "model.layers.6.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
540
+ "model.layers.6.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
541
+ "model.layers.7.input_layernorm.weight": "model-00001-of-00002.safetensors",
542
+ "model.layers.7.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
543
+ "model.layers.7.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
544
+ "model.layers.7.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
545
+ "model.layers.7.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
546
+ "model.layers.7.self_attn.A_log": "model-00001-of-00002.safetensors",
547
+ "model.layers.7.self_attn.a_proj.weight": "model-00001-of-00002.safetensors",
548
+ "model.layers.7.self_attn.b_proj.weight": "model-00001-of-00002.safetensors",
549
+ "model.layers.7.self_attn.dt_bias": "model-00001-of-00002.safetensors",
550
+ "model.layers.7.self_attn.dynamic_conv1d.kernel_generator.w1.weight": "model-00001-of-00002.safetensors",
551
+ "model.layers.7.self_attn.dynamic_conv1d.kernel_generator.w2.bias": "model-00001-of-00002.safetensors",
552
+ "model.layers.7.self_attn.dynamic_conv1d.kernel_generator.w2.weight": "model-00001-of-00002.safetensors",
553
+ "model.layers.7.self_attn.g_proj.weight": "model-00001-of-00002.safetensors",
554
+ "model.layers.7.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
555
+ "model.layers.7.self_attn.o_norm.weight": "model-00001-of-00002.safetensors",
556
+ "model.layers.7.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
557
+ "model.layers.7.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
558
+ "model.layers.7.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
559
+ "model.layers.8.input_layernorm.weight": "model-00001-of-00002.safetensors",
560
+ "model.layers.8.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
561
+ "model.layers.8.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
562
+ "model.layers.8.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
563
+ "model.layers.8.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
564
+ "model.layers.8.self_attn.A_log": "model-00001-of-00002.safetensors",
565
+ "model.layers.8.self_attn.a_proj.weight": "model-00001-of-00002.safetensors",
566
+ "model.layers.8.self_attn.b_proj.weight": "model-00001-of-00002.safetensors",
567
+ "model.layers.8.self_attn.dt_bias": "model-00001-of-00002.safetensors",
568
+ "model.layers.8.self_attn.dynamic_conv1d.kernel_generator.w1.weight": "model-00001-of-00002.safetensors",
569
+ "model.layers.8.self_attn.dynamic_conv1d.kernel_generator.w2.bias": "model-00001-of-00002.safetensors",
570
+ "model.layers.8.self_attn.dynamic_conv1d.kernel_generator.w2.weight": "model-00001-of-00002.safetensors",
571
+ "model.layers.8.self_attn.g_proj.weight": "model-00001-of-00002.safetensors",
572
+ "model.layers.8.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
573
+ "model.layers.8.self_attn.o_norm.weight": "model-00001-of-00002.safetensors",
574
+ "model.layers.8.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
575
+ "model.layers.8.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
576
+ "model.layers.8.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
577
+ "model.layers.9.input_layernorm.weight": "model-00001-of-00002.safetensors",
578
+ "model.layers.9.mlp.down_proj.weight": "model-00001-of-00002.safetensors",
579
+ "model.layers.9.mlp.gate_proj.weight": "model-00001-of-00002.safetensors",
580
+ "model.layers.9.mlp.up_proj.weight": "model-00001-of-00002.safetensors",
581
+ "model.layers.9.post_attention_layernorm.weight": "model-00001-of-00002.safetensors",
582
+ "model.layers.9.self_attn.A_log": "model-00001-of-00002.safetensors",
583
+ "model.layers.9.self_attn.a_proj.weight": "model-00001-of-00002.safetensors",
584
+ "model.layers.9.self_attn.b_proj.weight": "model-00001-of-00002.safetensors",
585
+ "model.layers.9.self_attn.dt_bias": "model-00001-of-00002.safetensors",
586
+ "model.layers.9.self_attn.dynamic_conv1d.kernel_generator.w1.weight": "model-00001-of-00002.safetensors",
587
+ "model.layers.9.self_attn.dynamic_conv1d.kernel_generator.w2.bias": "model-00001-of-00002.safetensors",
588
+ "model.layers.9.self_attn.dynamic_conv1d.kernel_generator.w2.weight": "model-00001-of-00002.safetensors",
589
+ "model.layers.9.self_attn.g_proj.weight": "model-00001-of-00002.safetensors",
590
+ "model.layers.9.self_attn.k_proj.weight": "model-00001-of-00002.safetensors",
591
+ "model.layers.9.self_attn.o_norm.weight": "model-00001-of-00002.safetensors",
592
+ "model.layers.9.self_attn.o_proj.weight": "model-00001-of-00002.safetensors",
593
+ "model.layers.9.self_attn.q_proj.weight": "model-00001-of-00002.safetensors",
594
+ "model.layers.9.self_attn.v_proj.weight": "model-00001-of-00002.safetensors",
595
+ "model.norm.weight": "model-00002-of-00002.safetensors"
596
+ }
597
+ }
modeling_jet_nemotron.py ADDED
@@ -0,0 +1,967 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ # This file is modified from https://github.com/huggingface/transformers/blob/main/src/transformers/models/qwen2/modeling_qwen2.py
18
+
19
+ from functools import partial
20
+ from typing import Callable, Optional, Tuple, Union
21
+
22
+ import torch
23
+ from torch import nn
24
+
25
+ from transformers.activations import ACT2FN
26
+ from transformers.generation import GenerationMixin, GenerationConfig
27
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
28
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
29
+ from transformers.modeling_outputs import (
30
+ BaseModelOutputWithPast,
31
+ CausalLMOutputWithPast,
32
+ )
33
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
34
+ from transformers.modeling_utils import PreTrainedModel, ALL_ATTENTION_FUNCTIONS
35
+ from transformers.processing_utils import Unpack
36
+ from transformers.utils import (
37
+ LossKwargs,
38
+ add_start_docstrings,
39
+ add_start_docstrings_to_model_forward,
40
+ can_return_tuple,
41
+ logging,
42
+ replace_return_docstrings,
43
+ )
44
+ from transformers.utils.deprecation import deprecate_kwarg
45
+
46
+
47
+ from .configuration_jet_nemotron import JetNemotronConfig
48
+ from .jet_block import JetBlock
49
+ from .kv_cache import JetNemotronCache
50
+
51
+ try:
52
+ from .dynamic_conv import DynamicShortConvolution
53
+ from .dconv_fwdbwd import dynamic_conv_triton_autograd
54
+ from .dconv_fwd_cache import dynamic_conv_triton_cache
55
+ from .dconv_step import causal_conv_step_triton
56
+ except ImportError:
57
+ raise ImportError(
58
+ "Dynamic convolution is not available. Please install the required dependencies to use this feature."
59
+ )
60
+
61
+ logger = logging.get_logger(__name__)
62
+
63
+ _CHECKPOINT_FOR_DOC = "jet-ai/Jet-Nemotron-2B"
64
+ _CONFIG_FOR_DOC = "JetNemotronConfig"
65
+
66
+
67
+ class JetNemotronMLP(nn.Module):
68
+ def __init__(self, config: JetNemotronConfig):
69
+ super().__init__()
70
+ self.hidden_size = config.hidden_size
71
+ self.intermediate_size = config.intermediate_size
72
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
73
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
74
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
75
+ self.act_fn = ACT2FN[config.hidden_act]
76
+
77
+ def forward(self, hidden_state):
78
+ return self.down_proj(self.act_fn(self.gate_proj(hidden_state)) * self.up_proj(hidden_state))
79
+
80
+
81
+ def rotate_half(x):
82
+ """Rotates half the hidden dims of the input."""
83
+ x1 = x[..., : x.shape[-1] // 2]
84
+ x2 = x[..., x.shape[-1] // 2 :]
85
+ return torch.cat((-x2, x1), dim=-1)
86
+
87
+
88
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
89
+ """Applies Rotary Position Embedding to the query and key tensors.
90
+
91
+ Args:
92
+ q (`torch.Tensor`): The query tensor.
93
+ k (`torch.Tensor`): The key tensor.
94
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
95
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
96
+ position_ids (`torch.Tensor`, *optional*):
97
+ Deprecated and unused.
98
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
99
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
100
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
101
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
102
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
103
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
104
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
105
+ Returns:
106
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
107
+ """
108
+ cos = cos.unsqueeze(unsqueeze_dim)
109
+ sin = sin.unsqueeze(unsqueeze_dim)
110
+ q_embed = (q * cos) + (rotate_half(q) * sin)
111
+ k_embed = (k * cos) + (rotate_half(k) * sin)
112
+ return q_embed, k_embed
113
+
114
+
115
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
116
+ """
117
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
118
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
119
+ """
120
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
121
+ if n_rep == 1:
122
+ return hidden_states
123
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
124
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
125
+
126
+
127
+ def eager_attention_forward(
128
+ module: nn.Module,
129
+ query: torch.Tensor,
130
+ key: torch.Tensor,
131
+ value: torch.Tensor,
132
+ attention_mask: Optional[torch.Tensor],
133
+ scaling: float,
134
+ dropout: float = 0.0,
135
+ **kwargs,
136
+ ):
137
+ key_states = repeat_kv(key, module.num_key_value_groups)
138
+ value_states = repeat_kv(value, module.num_key_value_groups)
139
+
140
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
141
+ if attention_mask is not None:
142
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
143
+ attn_weights = attn_weights + causal_mask
144
+
145
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
146
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
147
+ attn_output = torch.matmul(attn_weights, value_states)
148
+ attn_output = attn_output.transpose(1, 2).contiguous()
149
+
150
+ return attn_output, attn_weights
151
+
152
+
153
+ class JetNemotronAttention(nn.Module):
154
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
155
+
156
+ def __init__(self, config: JetNemotronConfig, layer_idx: Optional[int] = None, sliding_window: Optional[int] = None):
157
+ super().__init__()
158
+ self.config = config
159
+ self.layer_idx = layer_idx
160
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
161
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
162
+ self.scaling = self.head_dim**-0.5
163
+ self.attention_dropout = config.attention_dropout
164
+ self.is_causal = True
165
+ self.sliding_window = sliding_window
166
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=True)
167
+ self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
168
+ self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=True)
169
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
170
+
171
+ def _get_target_length(
172
+ self,
173
+ sequence_length: int,
174
+ past_key_values: JetNemotronCache,
175
+ ):
176
+ past_seen_tokens = past_key_values.get_seq_length(self.layer_idx) if past_key_values is not None else 0
177
+ target_length = sequence_length + min(past_seen_tokens, self.sliding_window - 1)
178
+ return target_length
179
+
180
+ def _update_causal_mask_for_sliding_window(
181
+ self,
182
+ attention_mask: torch.Tensor,
183
+ input_tensor: torch.Tensor,
184
+ past_key_values: JetNemotronCache,
185
+ ) -> torch.Tensor:
186
+
187
+ dtype, device = input_tensor.dtype, input_tensor.device
188
+ min_dtype = torch.finfo(dtype).min
189
+ sequence_length = input_tensor.shape[1]
190
+
191
+ target_length = self._get_target_length(sequence_length, past_key_values)
192
+
193
+ past_seen_tokens = past_key_values.get_seq_length(self.layer_idx) if past_key_values is not None else 0
194
+ cache_position = torch.arange(
195
+ past_seen_tokens, past_seen_tokens + sequence_length, device=input_tensor.device
196
+ )
197
+
198
+ if attention_mask is not None:
199
+ # left padding
200
+ assert attention_mask.dim() == 4, "Attention mask must be 4D"
201
+ diagonal_attend_mask = attention_mask < -1
202
+ diagonal_attend_mask = diagonal_attend_mask[:, :, :, -target_length:]
203
+ else:
204
+ diagonal_attend_mask = torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
205
+ diagonal_attend_mask = diagonal_attend_mask[None, None, :, :]
206
+
207
+ if past_key_values is None or target_length > self.sliding_window:
208
+ # training mode or prefill mode when dealing with long prefix)
209
+ sliding_attend_mask = torch.arange(past_seen_tokens + sequence_length, device=device)[-target_length:] <= (
210
+ cache_position.reshape(-1, 1) - self.sliding_window
211
+ ) # bs, sequence_length, target_length
212
+ sliding_attend_mask = sliding_attend_mask[None, None, :, :]
213
+
214
+ diagonal_attend_mask = diagonal_attend_mask | sliding_attend_mask
215
+
216
+ # training
217
+ causal_mask = torch.full(
218
+ (1, 1, sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
219
+ )
220
+ causal_mask = causal_mask * diagonal_attend_mask
221
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
222
+
223
+ return causal_mask
224
+
225
+ def forward(
226
+ self,
227
+ hidden_states: torch.Tensor,
228
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
229
+ attention_mask: Optional[torch.Tensor],
230
+ past_key_value: Optional[JetNemotronCache] = None,
231
+ cache_position: Optional[torch.LongTensor] = None,
232
+ **kwargs: Unpack[FlashAttentionKwargs],
233
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
234
+ input_shape = hidden_states.shape[:-1]
235
+ hidden_shape = (*input_shape, -1, self.head_dim)
236
+
237
+ if self.sliding_window is not None and self.config._attn_implementation != "flash_attention_2":
238
+ attention_mask = self._update_causal_mask_for_sliding_window(attention_mask, hidden_states, past_key_value)
239
+
240
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
241
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
242
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
243
+
244
+ cos, sin = position_embeddings
245
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
246
+
247
+ if past_key_value is not None:
248
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
249
+ state = past_key_value.update(
250
+ attn_state=(key_states, value_states), layer_idx=self.layer_idx,
251
+ offset = hidden_states.shape[1],
252
+ cache_kwargs={"window_size": self.sliding_window})
253
+ key_states, value_states = state["attn_state"]
254
+
255
+ fa2_sliding_window = None
256
+ if self.sliding_window is not None:
257
+ fa2_sliding_window = self.sliding_window - 1
258
+
259
+ attention_interface: Callable = eager_attention_forward
260
+ if self.config._attn_implementation != "eager":
261
+ if self.config._attn_implementation == "sdpa":
262
+ past_seen_tokens = past_key_value.get_seq_length() if past_key_value is not None else 0
263
+ if self.sliding_window is None:
264
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
265
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
266
+ # to infer the attention mask.
267
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
268
+ attention_mask,
269
+ inputs_embeds=hidden_states,
270
+ past_key_values_length=past_seen_tokens,
271
+ sliding_window=self.sliding_window,
272
+ is_training=self.training,
273
+ ):
274
+ attention_mask = None
275
+
276
+ elif self.config._attn_implementation == "flash_attention_2":
277
+ if attention_mask is not None:
278
+ assert len(attention_mask.shape) == 2, "Attention mask must be 2D"
279
+ attention_mask = attention_mask[:, -key_states.shape[2]:]
280
+ else:
281
+ raise ValueError(
282
+ f"Unsupported attention implementation: {self.config._attn_implementation}. "
283
+ "Supported implementations are: eager, sdpa, flash_attention_2."
284
+ )
285
+
286
+ if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
287
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
288
+ logger.warning_once(
289
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
290
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
291
+ )
292
+ else:
293
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
294
+
295
+ attn_output, attn_weights = attention_interface(
296
+ self,
297
+ query_states,
298
+ key_states,
299
+ value_states,
300
+ attention_mask,
301
+ dropout=0.0 if not self.training else self.attention_dropout,
302
+ scaling=self.scaling,
303
+ sliding_window=fa2_sliding_window, # main diff with Llama
304
+ **kwargs,
305
+ )
306
+
307
+ if self.sliding_window is not None and past_key_value is not None:
308
+ past_key_value.trim_attn_state(self.layer_idx, self.sliding_window)
309
+
310
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
311
+ attn_output = self.o_proj(attn_output)
312
+
313
+ return attn_output, attn_weights
314
+
315
+
316
+ class JetNemotronRMSNorm(nn.Module):
317
+ def __init__(self, hidden_size, eps=1e-6):
318
+ """
319
+ JetNemotronRMSNorm is equivalent to T5LayerNorm
320
+ """
321
+ super().__init__()
322
+ self.weight = nn.Parameter(torch.ones(hidden_size))
323
+ self.variance_epsilon = eps
324
+
325
+ def forward(self, hidden_states):
326
+ input_dtype = hidden_states.dtype
327
+ hidden_states = hidden_states.to(torch.float32)
328
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
329
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
330
+ return (self.weight * hidden_states).to(input_dtype)
331
+
332
+ def extra_repr(self):
333
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
334
+
335
+
336
+ EFFICIENT_ATTENTION_CLASSES = {
337
+ "jet": JetBlock,
338
+ }
339
+
340
+
341
+ class JetNemotronDecoderLayer(nn.Module):
342
+ def __init__(self, config: JetNemotronConfig, layer_idx: int):
343
+ super().__init__()
344
+ self.hidden_size = config.hidden_size
345
+
346
+ if config.layer_types[layer_idx] == "attn":
347
+ self.self_attn = JetNemotronAttention(config, layer_idx)
348
+ elif config.layer_types[layer_idx] == "swa":
349
+ assert config.efficient_attention_config is not None, "Efficient attention config must be provided in JetNemotronConfig."
350
+ assert "swa" in config.efficient_attention_config, (
351
+ "Sliding Window Attention is enabled but no `swa` configuration found in `efficient_attention_config`."
352
+ )
353
+ self.self_attn = JetNemotronAttention(config, layer_idx, sliding_window=config.efficient_attention_config["swa"]["window_size"])
354
+ else:
355
+ assert config.layer_types[layer_idx] in EFFICIENT_ATTENTION_CLASSES, (
356
+ f"Layer type {config.layer_types[layer_idx]} not supported. Supported types are: "
357
+ f"{['attn', 'swa'] + list(EFFICIENT_ATTENTION_CLASSES.keys())}"
358
+ )
359
+ self.self_attn = EFFICIENT_ATTENTION_CLASSES[config.layer_types[layer_idx]](config, config.layer_types[layer_idx], layer_idx)
360
+
361
+ self.mlp = JetNemotronMLP(config)
362
+ self.input_layernorm = JetNemotronRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
363
+ self.post_attention_layernorm = JetNemotronRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
364
+
365
+ def forward(
366
+ self,
367
+ hidden_states: torch.Tensor,
368
+ attention_mask: Optional[torch.Tensor] = None,
369
+ position_ids: Optional[torch.LongTensor] = None,
370
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
371
+ output_attentions: Optional[bool] = False,
372
+ use_cache: Optional[bool] = False,
373
+ cache_position: Optional[torch.LongTensor] = None,
374
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
375
+ **kwargs,
376
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
377
+ residual = hidden_states
378
+
379
+ hidden_states = self.input_layernorm(hidden_states)
380
+
381
+ # Self Attention
382
+ hidden_states, self_attn_weights = self.self_attn(
383
+ hidden_states=hidden_states,
384
+ attention_mask=attention_mask,
385
+ position_ids=position_ids,
386
+ past_key_value=past_key_value,
387
+ output_attentions=output_attentions,
388
+ use_cache=use_cache,
389
+ cache_position=cache_position,
390
+ position_embeddings=position_embeddings,
391
+ )
392
+
393
+ hidden_states = residual + hidden_states
394
+
395
+ # Fully Connected
396
+ residual = hidden_states
397
+ hidden_states = self.post_attention_layernorm(hidden_states)
398
+ hidden_states = self.mlp(hidden_states)
399
+ hidden_states = residual + hidden_states
400
+
401
+ outputs = (hidden_states,)
402
+
403
+ if output_attentions:
404
+ outputs += (self_attn_weights,)
405
+
406
+ return outputs
407
+
408
+
409
+ class JetNemotronRotaryEmbedding(nn.Module):
410
+ def __init__(self, config: JetNemotronConfig, device=None):
411
+ super().__init__()
412
+ # BC: "rope_type" was originally "type"
413
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
414
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
415
+ else:
416
+ self.rope_type = "default"
417
+ self.max_seq_len_cached = config.max_position_embeddings
418
+ self.original_max_seq_len = config.max_position_embeddings
419
+
420
+ self.config = config
421
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
422
+
423
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
424
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
425
+ self.original_inv_freq = self.inv_freq
426
+
427
+ @torch.no_grad()
428
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
429
+ def forward(self, x, position_ids):
430
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
431
+ position_ids_expanded = position_ids[:, None, :].float()
432
+
433
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
434
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
435
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
436
+ emb = torch.cat((freqs, freqs), dim=-1)
437
+ cos = emb.cos() * self.attention_scaling
438
+ sin = emb.sin() * self.attention_scaling
439
+
440
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
441
+
442
+
443
+ JET_START_DOCSTRING = r"""
444
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
445
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
446
+ etc.)
447
+
448
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
449
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
450
+ and behavior.
451
+
452
+ Parameters:
453
+ config ([`JetNemotronConfig`]):
454
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
455
+ load the weights associated with the model, only the configuration. Check out the
456
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
457
+ """
458
+
459
+
460
+ @add_start_docstrings(
461
+ "The bare Jet-Nemotron Model outputting raw hidden-states without any specific head on top.",
462
+ JET_START_DOCSTRING,
463
+ )
464
+ class JetNemotronPreTrainedModel(PreTrainedModel):
465
+ config_class = JetNemotronConfig
466
+ base_model_prefix = "model"
467
+ supports_gradient_checkpointing = True
468
+ _no_split_modules = ["JetNemotronDecoderLayer"]
469
+ _skip_keys_device_placement = "past_key_values"
470
+ _supports_flash_attn_2 = True
471
+ _supports_sdpa = True
472
+ _supports_flex_attn = False
473
+ _supports_cache_class = True
474
+ _supports_quantized_cache = False
475
+ _supports_static_cache = False
476
+ _supports_attention_backend = True
477
+
478
+ def _init_weights(self, module):
479
+ std = self.config.initializer_range
480
+ if isinstance(module, nn.Linear):
481
+ module.weight.data.normal_(mean=0.0, std=std)
482
+ if module.bias is not None:
483
+ module.bias.data.zero_()
484
+ elif isinstance(module, nn.Embedding):
485
+ module.weight.data.normal_(mean=0.0, std=std)
486
+ if module.padding_idx is not None:
487
+ module.weight.data[module.padding_idx].zero_()
488
+
489
+
490
+ JET_INPUTS_DOCSTRING = r"""
491
+ Args:
492
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
493
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
494
+ it.
495
+
496
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
497
+ [`PreTrainedTokenizer.__call__`] for details.
498
+
499
+ [What are input IDs?](../glossary#input-ids)
500
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
501
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
502
+
503
+ - 1 for tokens that are **not masked**,
504
+ - 0 for tokens that are **masked**.
505
+
506
+ [What are attention masks?](../glossary#attention-mask)
507
+
508
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
509
+ [`PreTrainedTokenizer.__call__`] for details.
510
+
511
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
512
+ `past_key_values`).
513
+
514
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
515
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
516
+ information on the default strategy.
517
+
518
+ - 1 indicates the head is **not masked**,
519
+ - 0 indicates the head is **masked**.
520
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
521
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
522
+ config.n_positions - 1]`.
523
+
524
+ [What are position IDs?](../glossary#position-ids)
525
+ past_key_values (`Cache`, *optional*):
526
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
527
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
528
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
529
+
530
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
531
+
532
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
533
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
534
+ of shape `(batch_size, sequence_length)`.
535
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
536
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
537
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
538
+ model's internal embedding lookup matrix.
539
+ use_cache (`bool`, *optional*):
540
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
541
+ `past_key_values`).
542
+ output_attentions (`bool`, *optional*):
543
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
544
+ tensors for more detail.
545
+ output_hidden_states (`bool`, *optional*):
546
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
547
+ more detail.
548
+ return_dict (`bool`, *optional*):
549
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
550
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
551
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
552
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
553
+ the complete sequence length.
554
+ """
555
+
556
+
557
+ @add_start_docstrings(
558
+ "The bare Jet Nemotron Model outputting raw hidden-states without any specific head on top.",
559
+ JET_START_DOCSTRING,
560
+ )
561
+ class JetNemotronModel(JetNemotronPreTrainedModel):
562
+ """
563
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`JetNemotronDecoderLayer`]
564
+
565
+ Args:
566
+ config: JetNemotronConfig
567
+ """
568
+
569
+ def __init__(self, config: JetNemotronConfig):
570
+ super().__init__(config)
571
+ self.padding_idx = config.pad_token_id
572
+ self.vocab_size = config.vocab_size
573
+
574
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
575
+ self.layers = nn.ModuleList(
576
+ [JetNemotronDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
577
+ )
578
+ self._attn_implementation = config._attn_implementation
579
+ assert self._attn_implementation in ["sdpa", "flash_attention_2"]
580
+ self.norm = JetNemotronRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
581
+ self.rotary_emb = JetNemotronRotaryEmbedding(config=config)
582
+
583
+ self.gradient_checkpointing = False
584
+ # Initialize weights and apply final processing
585
+ self.post_init()
586
+
587
+ def get_input_embeddings(self):
588
+ return self.embed_tokens
589
+
590
+ def set_input_embeddings(self, value):
591
+ self.embed_tokens = value
592
+
593
+ @can_return_tuple
594
+ @add_start_docstrings_to_model_forward(JET_INPUTS_DOCSTRING)
595
+ def forward(
596
+ self,
597
+ input_ids: Optional[torch.LongTensor] = None,
598
+ attention_mask: Optional[torch.Tensor] = None,
599
+ position_ids: Optional[torch.LongTensor] = None,
600
+ past_key_values: Optional[JetNemotronCache] = None,
601
+ inputs_embeds: Optional[torch.FloatTensor] = None,
602
+ use_cache: Optional[bool] = None,
603
+ output_attentions: Optional[bool] = None,
604
+ output_hidden_states: Optional[bool] = None,
605
+ cache_position: Optional[torch.LongTensor] = None,
606
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
607
+ ) -> BaseModelOutputWithPast:
608
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
609
+ output_hidden_states = (
610
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
611
+ )
612
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
613
+
614
+ if (input_ids is None) ^ (inputs_embeds is not None):
615
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
616
+
617
+ if self.gradient_checkpointing and self.training and use_cache:
618
+ logger.warning_once(
619
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
620
+ )
621
+ use_cache = False
622
+
623
+ if use_cache and past_key_values is None:
624
+ past_key_values = JetNemotronCache()
625
+
626
+ if inputs_embeds is None:
627
+ inputs_embeds = self.embed_tokens(input_ids)
628
+
629
+ if cache_position is None:
630
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
631
+ cache_position = torch.arange(
632
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
633
+ )
634
+
635
+ if position_ids is None:
636
+ position_ids = cache_position.unsqueeze(0)
637
+
638
+ causal_mask = self._update_causal_mask(
639
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
640
+ )
641
+
642
+ hidden_states = inputs_embeds
643
+
644
+ # create position embeddings to be shared across the decoder layers
645
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
646
+
647
+ # decoder layers
648
+ all_hidden_states = () if output_hidden_states else None
649
+ all_self_attns = () if output_attentions else None
650
+
651
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
652
+ if output_hidden_states:
653
+ all_hidden_states += (hidden_states,)
654
+
655
+ if self.gradient_checkpointing and self.training:
656
+ layer_outputs = self._gradient_checkpointing_func(
657
+ partial(decoder_layer.__call__, **flash_attn_kwargs),
658
+ hidden_states,
659
+ causal_mask,
660
+ position_ids,
661
+ past_key_values,
662
+ output_attentions,
663
+ use_cache,
664
+ cache_position,
665
+ position_embeddings,
666
+ )
667
+ else:
668
+ layer_outputs = decoder_layer(
669
+ hidden_states,
670
+ attention_mask=causal_mask,
671
+ position_ids=position_ids,
672
+ past_key_value=past_key_values,
673
+ output_attentions=output_attentions,
674
+ use_cache=use_cache,
675
+ cache_position=cache_position,
676
+ position_embeddings=position_embeddings,
677
+ **flash_attn_kwargs,
678
+ )
679
+
680
+ hidden_states = layer_outputs[0]
681
+
682
+ if output_attentions:
683
+ all_self_attns += (layer_outputs[1],)
684
+
685
+ hidden_states = self.norm(hidden_states)
686
+
687
+ # add hidden states from the last decoder layer
688
+ if output_hidden_states:
689
+ all_hidden_states += (hidden_states,)
690
+
691
+ return BaseModelOutputWithPast(
692
+ last_hidden_state=hidden_states,
693
+ past_key_values=past_key_values if use_cache else None,
694
+ hidden_states=all_hidden_states,
695
+ attentions=all_self_attns,
696
+ )
697
+
698
+ def _update_causal_mask(
699
+ self,
700
+ attention_mask: torch.Tensor,
701
+ input_tensor: torch.Tensor,
702
+ cache_position: torch.Tensor,
703
+ past_key_values: JetNemotronCache,
704
+ output_attentions: bool,
705
+ ):
706
+ if self.config._attn_implementation == "flash_attention_2":
707
+ if attention_mask is not None and past_key_values is not None:
708
+ is_empty = attention_mask.sum(dim=-1).long() == 0
709
+ last_is_1 = (attention_mask[:, -1].long() == 1) | is_empty
710
+ is_padding_right = last_is_1.sum().item() != input_tensor.size()[0]
711
+ if is_padding_right:
712
+ raise ValueError(
713
+ "You are attempting to perform batched generation with padding_side='right'"
714
+ " this may lead to unexpected behaviour for Flash Attention version of Jet-Nemotron. Make sure to "
715
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
716
+ )
717
+ if attention_mask is not None and 0.0 in attention_mask:
718
+ return attention_mask
719
+ return None
720
+
721
+ if self.config._attn_implementation == "flex_attention":
722
+ raise NotImplementedError(
723
+ "Flex attention is not supported yet. Please use `flash_attention_2`, `eager`, or `sdpa` instead."
724
+ )
725
+
726
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
727
+ dtype, device = input_tensor.dtype, input_tensor.device
728
+ min_dtype = torch.finfo(dtype).min
729
+ sequence_length = input_tensor.shape[1]
730
+
731
+ target_length = (
732
+ attention_mask.shape[-1]
733
+ if isinstance(attention_mask, torch.Tensor)
734
+ else past_seen_tokens + sequence_length + 1
735
+ )
736
+
737
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
738
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
739
+ attention_mask,
740
+ sequence_length=sequence_length,
741
+ target_length=target_length,
742
+ dtype=dtype,
743
+ cache_position=cache_position,
744
+ batch_size=input_tensor.shape[0],
745
+ config=self.config,
746
+ past_key_values=past_key_values,
747
+ )
748
+
749
+ if (
750
+ self.config._attn_implementation == "sdpa"
751
+ and attention_mask is not None
752
+ and attention_mask.device.type == "cuda"
753
+ and not output_attentions
754
+ ):
755
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
756
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
757
+ # Details: https://github.com/pytorch/pytorch/issues/110213
758
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
759
+
760
+ return causal_mask
761
+
762
+ @staticmethod
763
+ def _prepare_4d_causal_attention_mask_with_cache_position(
764
+ attention_mask: torch.Tensor,
765
+ sequence_length: int,
766
+ target_length: int,
767
+ dtype: torch.dtype,
768
+ cache_position: torch.Tensor,
769
+ batch_size: int,
770
+ config: JetNemotronConfig,
771
+ past_key_values: JetNemotronCache,
772
+ ):
773
+ """
774
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
775
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
776
+
777
+ Args:
778
+ attention_mask (`torch.Tensor`):
779
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
780
+ sequence_length (`int`):
781
+ The sequence length being processed.
782
+ target_length (`int`):
783
+ The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
784
+ dtype (`torch.dtype`):
785
+ The dtype to use for the 4D attention mask.
786
+ cache_position (`torch.Tensor`):
787
+ Indices depicting the position of the input sequence tokens in the sequence.
788
+ batch_size (`torch.Tensor`):
789
+ Batch size.
790
+ config (`JetNemotronConfig`):
791
+ The model's configuration class
792
+ past_key_values (`Cache`):
793
+ The cache class that is being used currently to generate
794
+ """
795
+ if attention_mask is not None and attention_mask.dim() == 4:
796
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
797
+ causal_mask = attention_mask
798
+ else:
799
+ min_dtype = torch.finfo(dtype).min
800
+ causal_mask = torch.full(
801
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=cache_position.device
802
+ )
803
+ diagonal_attend_mask = torch.arange(target_length, device=cache_position.device) > cache_position.reshape(
804
+ -1, 1
805
+ )
806
+ causal_mask *= diagonal_attend_mask
807
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
808
+ if attention_mask is not None:
809
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
810
+ if attention_mask.shape[-1] > target_length:
811
+ attention_mask = attention_mask[:, :target_length]
812
+ mask_length = attention_mask.shape[-1]
813
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
814
+ causal_mask.device
815
+ )
816
+ padding_mask = padding_mask == 0
817
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
818
+ padding_mask, min_dtype
819
+ )
820
+ return causal_mask
821
+
822
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
823
+
824
+
825
+ class JetNemotronForCausalLM(JetNemotronPreTrainedModel, GenerationMixin):
826
+ _tied_weights_keys = ["lm_head.weight"]
827
+ _tp_plan = {"lm_head": "colwise_rep"}
828
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
829
+
830
+ def __init__(self, config: JetNemotronConfig):
831
+ super().__init__(config)
832
+ self.model = JetNemotronModel(config)
833
+ self.vocab_size = config.vocab_size
834
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
835
+
836
+ # Initialize weights and apply final processing
837
+ self.post_init()
838
+
839
+ def get_input_embeddings(self):
840
+ return self.model.embed_tokens
841
+
842
+ def set_input_embeddings(self, value):
843
+ self.model.embed_tokens = value
844
+
845
+ def get_output_embeddings(self):
846
+ return self.lm_head
847
+
848
+ def set_output_embeddings(self, new_embeddings):
849
+ self.lm_head = new_embeddings
850
+
851
+ def set_decoder(self, decoder):
852
+ self.model = decoder
853
+
854
+ def get_decoder(self):
855
+ return self.model
856
+
857
+ @can_return_tuple
858
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
859
+ @add_start_docstrings_to_model_forward(JET_INPUTS_DOCSTRING)
860
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
861
+ def forward(
862
+ self,
863
+ input_ids: Optional[torch.LongTensor] = None,
864
+ attention_mask: Optional[torch.Tensor] = None,
865
+ position_ids: Optional[torch.LongTensor] = None,
866
+ past_key_values: Optional[JetNemotronCache] = None,
867
+ inputs_embeds: Optional[torch.FloatTensor] = None,
868
+ labels: Optional[torch.LongTensor] = None,
869
+ use_cache: Optional[bool] = None,
870
+ output_attentions: Optional[bool] = None,
871
+ output_hidden_states: Optional[bool] = None,
872
+ cache_position: Optional[torch.LongTensor] = None,
873
+ logits_to_keep: Union[int, torch.Tensor] = 0,
874
+ **kwargs: Unpack[KwargsForCausalLM],
875
+ ) -> CausalLMOutputWithPast:
876
+ r"""
877
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
878
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
879
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
880
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
881
+
882
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
883
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
884
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
885
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
886
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
887
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
888
+
889
+ Returns:
890
+
891
+ Example:
892
+
893
+ ```python
894
+ >>> from transformers import AutoTokenizer, AutoModelForCausalLM
895
+
896
+ >>> model = AutoModelForCausalLM.from_pretrained("jet-ai/Jet-Nemotron-2B")
897
+ >>> tokenizer = AutoTokenizer.from_pretrained("jet-ai/Jet-Nemotron-2B")
898
+
899
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
900
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
901
+
902
+ >>> # Generate
903
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
904
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
905
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
906
+ ```"""
907
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
908
+ output_hidden_states = (
909
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
910
+ )
911
+
912
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
913
+ outputs: BaseModelOutputWithPast = self.model(
914
+ input_ids=input_ids,
915
+ attention_mask=attention_mask,
916
+ position_ids=position_ids,
917
+ past_key_values=past_key_values,
918
+ inputs_embeds=inputs_embeds,
919
+ use_cache=use_cache,
920
+ output_attentions=output_attentions,
921
+ output_hidden_states=output_hidden_states,
922
+ cache_position=cache_position,
923
+ **kwargs,
924
+ )
925
+
926
+ hidden_states = outputs.last_hidden_state
927
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
928
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
929
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
930
+
931
+ loss = None
932
+ if labels is not None:
933
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
934
+
935
+ return CausalLMOutputWithPast(
936
+ loss=loss,
937
+ logits=logits,
938
+ past_key_values=outputs.past_key_values,
939
+ hidden_states=outputs.hidden_states,
940
+ attentions=outputs.attentions,
941
+ )
942
+
943
+ def _prepare_cache_for_generation(
944
+ self,
945
+ generation_config: GenerationConfig,
946
+ model_kwargs: dict,
947
+ assistant_model: "PreTrainedModel",
948
+ batch_size: int,
949
+ max_cache_length: int,
950
+ device: torch.device,
951
+ ) -> bool:
952
+ assert not generation_config.return_legacy_cache, "Legacy cache is not supported for generation."
953
+ if generation_config.use_cache is False:
954
+ return
955
+ model_kwargs["past_key_values"] = JetNemotronCache()
956
+
957
+ def _beam_search(self, *args, **kwargs):
958
+ raise NotImplementedError("Beam search is not supported for Jet-Nemotron models.")
959
+
960
+ def _contrastive_search(self, *args, **kwargs):
961
+ raise NotImplementedError("Contrastive search is not supported for Jet-Nemotron models.")
962
+
963
+ def _group_beam_search(self, *args, **kwargs):
964
+ raise NotImplementedError("Group beam search is not supported for Jet-Nemotron models.")
965
+
966
+ def _constrained_beam_search(self, *args, **kwargs):
967
+ raise NotImplementedError("Constrained beam search is not supported for Jet-Nemotron models.")
special_tokens_map.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additional_special_tokens": [
3
+ "<|im_start|>",
4
+ "<|im_end|>",
5
+ "<|object_ref_start|>",
6
+ "<|object_ref_end|>",
7
+ "<|box_start|>",
8
+ "<|box_end|>",
9
+ "<|quad_start|>",
10
+ "<|quad_end|>",
11
+ "<|vision_start|>",
12
+ "<|vision_end|>",
13
+ "<|vision_pad|>",
14
+ "<|image_pad|>",
15
+ "<|video_pad|>"
16
+ ],
17
+ "eos_token": {
18
+ "content": "<|endoftext|>",
19
+ "lstrip": false,
20
+ "normalized": false,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ },
24
+ "pad_token": {
25
+ "content": "<|endoftext|>",
26
+ "lstrip": false,
27
+ "normalized": false,
28
+ "rstrip": false,
29
+ "single_word": false
30
+ }
31
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9c5ae00e602b8860cbd784ba82a8aa14e8feecec692e7076590d014d7b7fdafa
3
+ size 11421896
tokenizer_config.json ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": false,
3
+ "add_prefix_space": false,
4
+ "added_tokens_decoder": {
5
+ "151643": {
6
+ "content": "<|endoftext|>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "151644": {
14
+ "content": "<|im_start|>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "151645": {
22
+ "content": "<|im_end|>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "151646": {
30
+ "content": "<|object_ref_start|>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ },
37
+ "151647": {
38
+ "content": "<|object_ref_end|>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false,
43
+ "special": true
44
+ },
45
+ "151648": {
46
+ "content": "<|box_start|>",
47
+ "lstrip": false,
48
+ "normalized": false,
49
+ "rstrip": false,
50
+ "single_word": false,
51
+ "special": true
52
+ },
53
+ "151649": {
54
+ "content": "<|box_end|>",
55
+ "lstrip": false,
56
+ "normalized": false,
57
+ "rstrip": false,
58
+ "single_word": false,
59
+ "special": true
60
+ },
61
+ "151650": {
62
+ "content": "<|quad_start|>",
63
+ "lstrip": false,
64
+ "normalized": false,
65
+ "rstrip": false,
66
+ "single_word": false,
67
+ "special": true
68
+ },
69
+ "151651": {
70
+ "content": "<|quad_end|>",
71
+ "lstrip": false,
72
+ "normalized": false,
73
+ "rstrip": false,
74
+ "single_word": false,
75
+ "special": true
76
+ },
77
+ "151652": {
78
+ "content": "<|vision_start|>",
79
+ "lstrip": false,
80
+ "normalized": false,
81
+ "rstrip": false,
82
+ "single_word": false,
83
+ "special": true
84
+ },
85
+ "151653": {
86
+ "content": "<|vision_end|>",
87
+ "lstrip": false,
88
+ "normalized": false,
89
+ "rstrip": false,
90
+ "single_word": false,
91
+ "special": true
92
+ },
93
+ "151654": {
94
+ "content": "<|vision_pad|>",
95
+ "lstrip": false,
96
+ "normalized": false,
97
+ "rstrip": false,
98
+ "single_word": false,
99
+ "special": true
100
+ },
101
+ "151655": {
102
+ "content": "<|image_pad|>",
103
+ "lstrip": false,
104
+ "normalized": false,
105
+ "rstrip": false,
106
+ "single_word": false,
107
+ "special": true
108
+ },
109
+ "151656": {
110
+ "content": "<|video_pad|>",
111
+ "lstrip": false,
112
+ "normalized": false,
113
+ "rstrip": false,
114
+ "single_word": false,
115
+ "special": true
116
+ },
117
+ "151657": {
118
+ "content": "<tool_call>",
119
+ "lstrip": false,
120
+ "normalized": false,
121
+ "rstrip": false,
122
+ "single_word": false,
123
+ "special": false
124
+ },
125
+ "151658": {
126
+ "content": "</tool_call>",
127
+ "lstrip": false,
128
+ "normalized": false,
129
+ "rstrip": false,
130
+ "single_word": false,
131
+ "special": false
132
+ },
133
+ "151659": {
134
+ "content": "<|fim_prefix|>",
135
+ "lstrip": false,
136
+ "normalized": false,
137
+ "rstrip": false,
138
+ "single_word": false,
139
+ "special": false
140
+ },
141
+ "151660": {
142
+ "content": "<|fim_middle|>",
143
+ "lstrip": false,
144
+ "normalized": false,
145
+ "rstrip": false,
146
+ "single_word": false,
147
+ "special": false
148
+ },
149
+ "151661": {
150
+ "content": "<|fim_suffix|>",
151
+ "lstrip": false,
152
+ "normalized": false,
153
+ "rstrip": false,
154
+ "single_word": false,
155
+ "special": false
156
+ },
157
+ "151662": {
158
+ "content": "<|fim_pad|>",
159
+ "lstrip": false,
160
+ "normalized": false,
161
+ "rstrip": false,
162
+ "single_word": false,
163
+ "special": false
164
+ },
165
+ "151663": {
166
+ "content": "<|repo_name|>",
167
+ "lstrip": false,
168
+ "normalized": false,
169
+ "rstrip": false,
170
+ "single_word": false,
171
+ "special": false
172
+ },
173
+ "151664": {
174
+ "content": "<|file_sep|>",
175
+ "lstrip": false,
176
+ "normalized": false,
177
+ "rstrip": false,
178
+ "single_word": false,
179
+ "special": false
180
+ }
181
+ },
182
+ "additional_special_tokens": [
183
+ "<|im_start|>",
184
+ "<|im_end|>",
185
+ "<|object_ref_start|>",
186
+ "<|object_ref_end|>",
187
+ "<|box_start|>",
188
+ "<|box_end|>",
189
+ "<|quad_start|>",
190
+ "<|quad_end|>",
191
+ "<|vision_start|>",
192
+ "<|vision_end|>",
193
+ "<|vision_pad|>",
194
+ "<|image_pad|>",
195
+ "<|video_pad|>"
196
+ ],
197
+ "bos_token": null,
198
+ "clean_up_tokenization_spaces": false,
199
+ "eos_token": "<|endoftext|>",
200
+ "errors": "replace",
201
+ "extra_special_tokens": {},
202
+ "model_max_length": 131072,
203
+ "pad_token": "<|endoftext|>",
204
+ "split_special_tokens": false,
205
+ "tokenizer_class": "Qwen2Tokenizer",
206
+ "unk_token": null
207
+ }
vocab.json ADDED
The diff for this file is too large to render. See raw diff