PaulD commited on
Commit
327f8b3
·
verified ·
1 Parent(s): b910699

Add custom code

Browse files
Files changed (2) hide show
  1. configuration_nemotron.py +186 -0
  2. modeling_nemotron.py +1537 -0
configuration_nemotron.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 HuggingFace Inc. team. All rights reserved.
3
+ # Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """Nemotron model configuration"""
17
+
18
+ from ...configuration_utils import PretrainedConfig
19
+ from ...utils import logging
20
+
21
+
22
+ logger = logging.get_logger(__name__)
23
+
24
+
25
+ class NemotronConfig(PretrainedConfig):
26
+ r"""
27
+ This is the configuration class to store the configuration of a [`NemotronModel`]. It is used to instantiate an Nemotron
28
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
29
+ defaults will yield a similar configuration to that of the Nemotron-8B.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+
35
+ Args:
36
+ vocab_size (`int`, *optional*, defaults to 32000):
37
+ Vocabulary size of the Nemotron model. Defines the number of different tokens that can be represented by the
38
+ `inputs_ids` passed when calling [`NemotronModel`]
39
+ hidden_size (`int`, *optional*, defaults to 4096):
40
+ Dimension of the hidden representations.
41
+ intermediate_size (`int`, *optional*, defaults to 11008):
42
+ Dimension of the MLP representations.
43
+ num_hidden_layers (`int`, *optional*, defaults to 32):
44
+ Number of hidden layers in the Transformer decoder.
45
+ num_attention_heads (`int`, *optional*, defaults to 32):
46
+ Number of attention heads for each attention layer in the Transformer decoder.
47
+ kv_channels (`int`, *optional*, defaults to None):
48
+ Projection weights dimension in multi-head attention. Set to hidden_size // num_attention_heads if None
49
+ num_key_value_heads (`int`, *optional*):
50
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
51
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
52
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
53
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
54
+ by meanpooling all the original heads within that group. For more details checkout [this
55
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
56
+ `num_attention_heads`.
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 2048):
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
+ norm_eps (`float`, *optional*, defaults to 1e-06):
64
+ The epsilon used by the 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
+ pad_token_id (`int`, *optional*):
69
+ Padding token id.
70
+ bos_token_id (`int`, *optional*, defaults to 1):
71
+ Beginning of stream token id.
72
+ eos_token_id (`int`, *optional*, defaults to 2):
73
+ End of stream token id.
74
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
75
+ Whether to tie weight embeddings
76
+ rope_theta (`float`, *optional*, defaults to 10000.0):
77
+ The base period of the RoPE embeddings.
78
+ rope_scaling (`Dict`, *optional*):
79
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
80
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
81
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
82
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
83
+ these scaling strategies behave:
84
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
85
+ experimental feature, subject to breaking API changes in future versions.
86
+ attention_bias (`bool`, *optional*, defaults to `False`):
87
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
88
+ attention_dropout (`float`, *optional*, defaults to 0.0):
89
+ The dropout ratio for the attention probabilities.
90
+ mlp_bias (`bool`, *optional*, defaults to `False`):
91
+ Whether to use a bias in up_proj and down_proj layers in the MLP layers.
92
+
93
+ ```python
94
+ >>> from transformers import NemotronModel, NemotronConfig
95
+
96
+ >>> # Initializing a Nemotron nemotron-15b style configuration
97
+ >>> configuration = NemotronConfig()
98
+
99
+ >>> # Initializing a model from the nemotron-15b style configuration
100
+ >>> model = NemotronModel(configuration)
101
+
102
+ >>> # Accessing the model configuration
103
+ >>> configuration = model.config
104
+ ```"""
105
+
106
+ model_type = "nemotron"
107
+ keys_to_ignore_at_inference = ["past_key_values"]
108
+
109
+ def __init__(
110
+ self,
111
+ vocab_size=256000,
112
+ hidden_size=6144,
113
+ intermediate_size=24576,
114
+ num_hidden_layers=32,
115
+ num_attention_heads=48,
116
+ kv_channels=None,
117
+ num_key_value_heads=None,
118
+ hidden_act="relu2",
119
+ max_position_embeddings=4096,
120
+ initializer_range=0.0134,
121
+ norm_eps=1e-5,
122
+ use_cache=True,
123
+ pad_token_id=None,
124
+ bos_token_id=2,
125
+ eos_token_id=3,
126
+ tie_word_embeddings=False,
127
+ rope_theta=10000.0,
128
+ rope_scaling=None,
129
+ rope_percentage=0.5,
130
+ attention_bias=False,
131
+ attention_dropout=0.0,
132
+ mlp_bias=False,
133
+ **kwargs,
134
+ ):
135
+ self.vocab_size = vocab_size
136
+ self.max_position_embeddings = max_position_embeddings
137
+ self.hidden_size = hidden_size
138
+ self.intermediate_size = intermediate_size
139
+ self.num_hidden_layers = num_hidden_layers
140
+ self.num_attention_heads = num_attention_heads
141
+ self.kv_channels = kv_channels
142
+
143
+ # for backward compatibility
144
+ if num_key_value_heads is None:
145
+ num_key_value_heads = num_attention_heads
146
+
147
+ self.num_key_value_heads = num_key_value_heads
148
+ self.hidden_act = hidden_act
149
+ self.initializer_range = initializer_range
150
+ self.norm_eps = norm_eps
151
+ self.use_cache = use_cache
152
+ self.rope_theta = rope_theta
153
+ self.rope_scaling = rope_scaling
154
+ self.rope_percentage = rope_percentage
155
+ self._rope_scaling_validation()
156
+ self.attention_bias = attention_bias
157
+ self.attention_dropout = attention_dropout
158
+ self.mlp_bias = mlp_bias
159
+
160
+ super().__init__(
161
+ pad_token_id=pad_token_id,
162
+ bos_token_id=bos_token_id,
163
+ eos_token_id=eos_token_id,
164
+ tie_word_embeddings=tie_word_embeddings,
165
+ **kwargs,
166
+ )
167
+
168
+ def _rope_scaling_validation(self):
169
+ """
170
+ Validate the `rope_scaling` configuration.
171
+ """
172
+ if self.rope_scaling is None:
173
+ return
174
+
175
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
176
+ raise ValueError(
177
+ "`rope_scaling` must be a dictionary with two fields, `type` and `factor`, " f"got {self.rope_scaling}"
178
+ )
179
+ rope_scaling_type = self.rope_scaling.get("type", None)
180
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
181
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
182
+ raise ValueError(
183
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
184
+ )
185
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
186
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
modeling_nemotron.py ADDED
@@ -0,0 +1,1537 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 HuggingFace Inc. team. All rights reserved.
3
+ # Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """PyTorch Nemotron model."""
17
+
18
+ import math
19
+ from typing import List, Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.nn.functional as F
23
+ import torch.utils.checkpoint
24
+ from torch import nn, Tensor, Size
25
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
26
+
27
+ from ...activations import ACT2FN
28
+ from ...cache_utils import Cache, DynamicCache, StaticCache
29
+ from ...modeling_attn_mask_utils import AttentionMaskConverter
30
+ from ...modeling_outputs import (
31
+ BaseModelOutputWithPast,
32
+ CausalLMOutputWithPast,
33
+ QuestionAnsweringModelOutput,
34
+ SequenceClassifierOutputWithPast,
35
+ TokenClassifierOutput,
36
+ )
37
+ from ...modeling_utils import PreTrainedModel
38
+ from ...pytorch_utils import ALL_LAYERNORM_LAYERS
39
+ from ...utils import (
40
+ add_start_docstrings,
41
+ add_start_docstrings_to_model_forward,
42
+ is_flash_attn_2_available,
43
+ is_flash_attn_greater_or_equal_2_10,
44
+ logging,
45
+ replace_return_docstrings,
46
+ )
47
+ from .configuration_nemotron import NemotronConfig
48
+
49
+
50
+ if is_flash_attn_2_available():
51
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
52
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
53
+
54
+
55
+ logger = logging.get_logger(__name__)
56
+
57
+ _CONFIG_FOR_DOC = "NemotronConfig"
58
+
59
+
60
+ def _get_unpad_data(attention_mask):
61
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
62
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
63
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
64
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
65
+ return (
66
+ indices,
67
+ cu_seqlens,
68
+ max_seqlen_in_batch,
69
+ )
70
+
71
+ def _cast_if_autocast_enabled(*args):
72
+ if not torch.is_autocast_enabled():
73
+ return args
74
+ else:
75
+ return torch.cuda.amp.autocast_mode._cast(args, torch.get_autocast_gpu_dtype())
76
+
77
+
78
+ class LayerNorm1P(nn.LayerNorm):
79
+ def __init__(self, normalized_shape: Union[int, List[int], Size], eps: float = 1e-5, elementwise_affine: bool = True,
80
+ bias: bool = True, device=None, dtype=None):
81
+ super().__init__(normalized_shape, eps, elementwise_affine, bias, device, dtype)
82
+ def forward(self, input: Tensor) -> Tensor:
83
+ args = _cast_if_autocast_enabled(input, self.normalized_shape, self.weight + 1, self.bias, self.eps)
84
+ with torch.cuda.amp.autocast(enabled=False):
85
+ return F.layer_norm(*args)
86
+
87
+
88
+ ALL_LAYERNORM_LAYERS.append(LayerNorm1P)
89
+
90
+
91
+ # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with LLAMA->NEMOTRON,Llama->Nemotron,llama->nemotron
92
+ class NemotronRotaryEmbedding(nn.Module):
93
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0, rotary_percent=1.):
94
+ super().__init__()
95
+ self.scaling_factor = scaling_factor
96
+ self.dim = dim
97
+ if rotary_percent < 1.0:
98
+ self.dim = int(self.dim * rotary_percent)
99
+ self.rotary_percent = rotary_percent
100
+ self.max_position_embeddings = max_position_embeddings
101
+ self.base = base
102
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
103
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
104
+ # For BC we register cos and sin cached
105
+ self.max_seq_len_cached = max_position_embeddings
106
+
107
+ @torch.no_grad()
108
+ def forward(self, x, position_ids):
109
+ # x: [bs, num_attention_heads, seq_len, head_size]
110
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
111
+ position_ids_expanded = position_ids[:, None, :].float()
112
+ # Force float32 since bfloat16 loses precision on long contexts
113
+ # See https://github.com/huggingface/transformers/pull/29285
114
+ device_type = x.device.type
115
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
116
+ with torch.autocast(device_type=device_type, enabled=False):
117
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
118
+ emb = torch.cat((freqs, freqs), dim=-1)
119
+ cos = emb.cos()
120
+ sin = emb.sin()
121
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
122
+
123
+
124
+ # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with LLAMA->NEMOTRON,Llama->Nemotron,llama->nemotron
125
+ class NemotronLinearScalingRotaryEmbedding(NemotronRotaryEmbedding):
126
+ """NemotronRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
127
+
128
+ def forward(self, x, position_ids):
129
+ # difference to the original RoPE: a scaling factor is aplied to the position ids
130
+ position_ids = position_ids.float() / self.scaling_factor
131
+ cos, sin = super().forward(x, position_ids)
132
+ return cos, sin
133
+
134
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
135
+ def rotate_half(x):
136
+ """Rotates half the hidden dims of the input."""
137
+ x1 = x[..., : x.shape[-1] // 2]
138
+ x2 = x[..., x.shape[-1] // 2 :]
139
+ return torch.cat((-x2, x1), dim=-1)
140
+
141
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
142
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
143
+ """Applies Rotary Position Embedding to the query and key tensors.
144
+
145
+ Args:
146
+ q (`torch.Tensor`): The query tensor.
147
+ k (`torch.Tensor`): The key tensor.
148
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
149
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
150
+ position_ids (`torch.Tensor`, *optional*):
151
+ Deprecated and unused.
152
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
153
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
154
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
155
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
156
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
157
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
158
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
159
+ Returns:
160
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
161
+ """
162
+ cos = cos.unsqueeze(unsqueeze_dim)
163
+ sin = sin.unsqueeze(unsqueeze_dim)
164
+
165
+ rot_dim = cos.shape[-1]
166
+ # If q_pass/k_pass is empty, rotary pos embedding is applied to all tensor q/k
167
+ q, q_pass = q[..., :rot_dim], q[..., rot_dim:]
168
+ k, k_pass = k[..., :rot_dim], k[..., rot_dim:]
169
+
170
+ q_embed = (q * cos) + (rotate_half(q) * sin)
171
+ k_embed = (k * cos) + (rotate_half(k) * sin)
172
+ return torch.cat((q_embed, q_pass), dim=-1), torch.cat((k_embed, k_pass), dim=-1)
173
+
174
+
175
+ class NemotronMLP(nn.Module):
176
+ def __init__(self, config):
177
+ super().__init__()
178
+ self.config = config
179
+ self.hidden_size = config.hidden_size
180
+ self.intermediate_size = config.intermediate_size
181
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
182
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
183
+ self.act_fn = ACT2FN[config.hidden_act]
184
+
185
+ def forward(self, x):
186
+
187
+ return self.down_proj(self.act_fn(self.up_proj(x)))
188
+
189
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
190
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
191
+ """
192
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
193
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
194
+ """
195
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
196
+ if n_rep == 1:
197
+ return hidden_states
198
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
199
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
200
+
201
+ # Copied from transformers.models.llama.modeling_llama.LlamaAttention with LLAMA->NEMOTRON,Llama->Nemotron,llama->nemotron
202
+ class NemotronAttention(nn.Module):
203
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
204
+
205
+ def __init__(self, config: NemotronConfig, layer_idx: Optional[int] = None):
206
+ super().__init__()
207
+ self.config = config
208
+ self.layer_idx = layer_idx
209
+ if layer_idx is None:
210
+ logger.warning_once(
211
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
212
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
213
+ "when creating this class."
214
+ )
215
+
216
+ self.attention_dropout = config.attention_dropout
217
+ self.hidden_size = config.hidden_size
218
+ self.num_heads = config.num_attention_heads
219
+ self.head_dim = self.hidden_size // self.num_heads if config.kv_channels is None else config.kv_channels
220
+ self.num_key_value_heads = config.num_key_value_heads
221
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
222
+ self.max_position_embeddings = config.max_position_embeddings
223
+ self.rope_theta = config.rope_theta
224
+ self.rotary_percent = config.rope_percentage
225
+ self.is_causal = True
226
+
227
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
228
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
229
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
230
+ self.o_proj = nn.Linear(self.head_dim * self.num_heads, self.hidden_size, bias=config.attention_bias)
231
+ self._init_rope()
232
+
233
+ def _init_rope(self):
234
+ if self.config.rope_scaling is None:
235
+ self.rotary_emb = NemotronRotaryEmbedding(
236
+ self.head_dim,
237
+ max_position_embeddings=self.max_position_embeddings,
238
+ base=self.rope_theta,
239
+ rotary_percent=self.rotary_percent,
240
+ )
241
+ else:
242
+ scaling_type = self.config.rope_scaling["type"]
243
+ scaling_factor = self.config.rope_scaling["factor"]
244
+ if scaling_type == "linear":
245
+ self.rotary_emb = NemotronLinearScalingRotaryEmbedding(
246
+ self.head_dim,
247
+ max_position_embeddings=self.max_position_embeddings,
248
+ scaling_factor=scaling_factor,
249
+ base=self.rope_theta,
250
+ rotary_percent=self.rotary_percent,
251
+ )
252
+ else:
253
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
254
+
255
+ def forward(
256
+ self,
257
+ hidden_states: torch.Tensor,
258
+ attention_mask: Optional[torch.Tensor] = None,
259
+ position_ids: Optional[torch.LongTensor] = None,
260
+ past_key_value: Optional[Cache] = None,
261
+ output_attentions: bool = False,
262
+ use_cache: bool = False,
263
+ cache_position: Optional[torch.LongTensor] = None,
264
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
265
+ bsz, q_len, _ = hidden_states.size()
266
+
267
+
268
+ query_states = self.q_proj(hidden_states)
269
+ key_states = self.k_proj(hidden_states)
270
+ value_states = self.v_proj(hidden_states)
271
+
272
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
273
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
274
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
275
+
276
+ cos, sin = self.rotary_emb(value_states, position_ids)
277
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
278
+
279
+ if past_key_value is not None:
280
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
281
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
282
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
283
+
284
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
285
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
286
+
287
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
288
+
289
+ if attention_mask is not None: # no matter the length, we just slice it
290
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
291
+ attn_weights = attn_weights + causal_mask
292
+
293
+ # upcast attention to fp32
294
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
295
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
296
+ attn_output = torch.matmul(attn_weights, value_states)
297
+
298
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
299
+ raise ValueError(
300
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
301
+ f" {attn_output.size()}"
302
+ )
303
+
304
+ attn_output = attn_output.transpose(1, 2).contiguous()
305
+
306
+ attn_output = attn_output.reshape(bsz, q_len, self.head_dim * self.num_heads)
307
+
308
+
309
+ attn_output = self.o_proj(attn_output)
310
+
311
+ if not output_attentions:
312
+ attn_weights = None
313
+
314
+ return attn_output, attn_weights, past_key_value
315
+
316
+
317
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with LLAMA->NEMOTRON,Llama->Nemotron,llama->nemotron
318
+ class NemotronFlashAttention2(NemotronAttention):
319
+ """
320
+ Nemotron flash attention module. This module inherits from `NemotronAttention` as the weights of the module stays
321
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
322
+ flash attention and deal with padding tokens in case the input contains any of them.
323
+ """
324
+
325
+ def __init__(self, *args, **kwargs):
326
+ super().__init__(*args, **kwargs)
327
+
328
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
329
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
330
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
331
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
332
+
333
+ def forward(
334
+ self,
335
+ hidden_states: torch.Tensor,
336
+ attention_mask: Optional[torch.LongTensor] = None,
337
+ position_ids: Optional[torch.LongTensor] = None,
338
+ past_key_value: Optional[Cache] = None,
339
+ output_attentions: bool = False,
340
+ use_cache: bool = False,
341
+ cache_position: Optional[torch.LongTensor] = None,
342
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
343
+ if isinstance(past_key_value, StaticCache):
344
+ raise ValueError(
345
+ "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
346
+ "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
347
+ )
348
+
349
+ output_attentions = False
350
+
351
+ bsz, q_len, _ = hidden_states.size()
352
+
353
+ query_states = self.q_proj(hidden_states)
354
+ key_states = self.k_proj(hidden_states)
355
+ value_states = self.v_proj(hidden_states)
356
+
357
+ # Flash attention requires the input to have the shape
358
+ # batch_size x seq_length x head_dim x hidden_dim
359
+ # therefore we just need to keep the original shape
360
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
361
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
362
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
363
+
364
+ cos, sin = self.rotary_emb(value_states, position_ids)
365
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
366
+
367
+ if past_key_value is not None:
368
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
369
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
370
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
371
+
372
+ # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
373
+ # to be able to avoid many of these transpose/reshape/view.
374
+ query_states = query_states.transpose(1, 2)
375
+ key_states = key_states.transpose(1, 2)
376
+ value_states = value_states.transpose(1, 2)
377
+
378
+ dropout_rate = self.attention_dropout if self.training else 0.0
379
+
380
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
381
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
382
+ # cast them back in the correct dtype just to be sure everything works as expected.
383
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
384
+ # in fp32. (NemotronRMSNorm handles it correctly)
385
+
386
+ input_dtype = query_states.dtype
387
+ if input_dtype == torch.float32:
388
+ if torch.is_autocast_enabled():
389
+ target_dtype = torch.get_autocast_gpu_dtype()
390
+ # Handle the case where the model is quantized
391
+ elif hasattr(self.config, "_pre_quantization_dtype"):
392
+ target_dtype = self.config._pre_quantization_dtype
393
+ else:
394
+ target_dtype = self.q_proj.weight.dtype
395
+
396
+ logger.warning_once(
397
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
398
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
399
+ f" {target_dtype}."
400
+ )
401
+
402
+ query_states = query_states.to(target_dtype)
403
+ key_states = key_states.to(target_dtype)
404
+ value_states = value_states.to(target_dtype)
405
+
406
+ attn_output = self._flash_attention_forward(
407
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
408
+ )
409
+
410
+ attn_output = attn_output.reshape(bsz, q_len, self.head_dim * self.num_heads).contiguous()
411
+ attn_output = self.o_proj(attn_output)
412
+
413
+ if not output_attentions:
414
+ attn_weights = None
415
+
416
+ return attn_output, attn_weights, past_key_value
417
+
418
+ def _flash_attention_forward(
419
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
420
+ ):
421
+ """
422
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
423
+ first unpad the input, then computes the attention scores and pad the final attention scores.
424
+
425
+ Args:
426
+ query_states (`torch.Tensor`):
427
+ Input query states to be passed to Flash Attention API
428
+ key_states (`torch.Tensor`):
429
+ Input key states to be passed to Flash Attention API
430
+ value_states (`torch.Tensor`):
431
+ Input value states to be passed to Flash Attention API
432
+ attention_mask (`torch.Tensor`):
433
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
434
+ position of padding tokens and 1 for the position of non-padding tokens.
435
+ dropout (`float`):
436
+ Attention dropout
437
+ softmax_scale (`float`, *optional*):
438
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
439
+ """
440
+ if not self._flash_attn_uses_top_left_mask:
441
+ causal = self.is_causal
442
+ else:
443
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in NemotronFlashAttention2 __init__.
444
+ causal = self.is_causal and query_length != 1
445
+
446
+ # Contains at least one padding token in the sequence
447
+ if attention_mask is not None:
448
+ batch_size = query_states.shape[0]
449
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
450
+ query_states, key_states, value_states, attention_mask, query_length
451
+ )
452
+
453
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
454
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
455
+
456
+ attn_output_unpad = flash_attn_varlen_func(
457
+ query_states,
458
+ key_states,
459
+ value_states,
460
+ cu_seqlens_q=cu_seqlens_q,
461
+ cu_seqlens_k=cu_seqlens_k,
462
+ max_seqlen_q=max_seqlen_in_batch_q,
463
+ max_seqlen_k=max_seqlen_in_batch_k,
464
+ dropout_p=dropout,
465
+ softmax_scale=softmax_scale,
466
+ causal=causal,
467
+ )
468
+
469
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
470
+ else:
471
+ attn_output = flash_attn_func(
472
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
473
+ )
474
+
475
+ return attn_output
476
+
477
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
478
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
479
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
480
+
481
+ key_layer = index_first_axis(
482
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
483
+ )
484
+ value_layer = index_first_axis(
485
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
486
+ )
487
+ if query_length == kv_seq_len:
488
+ query_layer = index_first_axis(
489
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
490
+ )
491
+ cu_seqlens_q = cu_seqlens_k
492
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
493
+ indices_q = indices_k
494
+ elif query_length == 1:
495
+ max_seqlen_in_batch_q = 1
496
+ cu_seqlens_q = torch.arange(
497
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
498
+ ) # There is a memcpy here, that is very bad.
499
+ indices_q = cu_seqlens_q[:-1]
500
+ query_layer = query_layer.squeeze(1)
501
+ else:
502
+ # The -q_len: slice assumes left padding.
503
+ attention_mask = attention_mask[:, -query_length:]
504
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
505
+
506
+ return (
507
+ query_layer,
508
+ key_layer,
509
+ value_layer,
510
+ indices_q,
511
+ (cu_seqlens_q, cu_seqlens_k),
512
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
513
+ )
514
+
515
+
516
+ # Copied from transformers.models.llama.modeling_llama.LlamaSdpaAttention with LLAMA->NEMOTRON,Llama->Nemotron,llama->nemotron
517
+ class NemotronSdpaAttention(NemotronAttention):
518
+ """
519
+ Nemotron attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
520
+ `NemotronAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
521
+ SDPA API.
522
+ """
523
+
524
+ # Adapted from NemotronAttention.forward
525
+ def forward(
526
+ self,
527
+ hidden_states: torch.Tensor,
528
+ attention_mask: Optional[torch.Tensor] = None,
529
+ position_ids: Optional[torch.LongTensor] = None,
530
+ past_key_value: Optional[Cache] = None,
531
+ output_attentions: bool = False,
532
+ use_cache: bool = False,
533
+ cache_position: Optional[torch.LongTensor] = None,
534
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
535
+ if output_attentions:
536
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
537
+ logger.warning_once(
538
+ "NemotronModel is using NemotronSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
539
+ 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
540
+ )
541
+ return super().forward(
542
+ hidden_states=hidden_states,
543
+ attention_mask=attention_mask,
544
+ position_ids=position_ids,
545
+ past_key_value=past_key_value,
546
+ output_attentions=output_attentions,
547
+ use_cache=use_cache,
548
+ cache_position=cache_position,
549
+ )
550
+
551
+ bsz, q_len, _ = hidden_states.size()
552
+
553
+ query_states = self.q_proj(hidden_states)
554
+ key_states = self.k_proj(hidden_states)
555
+ value_states = self.v_proj(hidden_states)
556
+
557
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
558
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
559
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
560
+
561
+ cos, sin = self.rotary_emb(value_states, position_ids)
562
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
563
+
564
+ if past_key_value is not None:
565
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
566
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
567
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
568
+
569
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
570
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
571
+
572
+ causal_mask = attention_mask
573
+ if attention_mask is not None:
574
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
575
+
576
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
577
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
578
+ if query_states.device.type == "cuda" and causal_mask is not None:
579
+ query_states = query_states.contiguous()
580
+ key_states = key_states.contiguous()
581
+ value_states = value_states.contiguous()
582
+
583
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
584
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
585
+ is_causal = True if causal_mask is None and q_len > 1 else False
586
+
587
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
588
+ query_states,
589
+ key_states,
590
+ value_states,
591
+ attn_mask=causal_mask,
592
+ dropout_p=self.attention_dropout if self.training else 0.0,
593
+ is_causal=is_causal,
594
+ )
595
+
596
+ attn_output = attn_output.transpose(1, 2).contiguous()
597
+ attn_output = attn_output.view(bsz, q_len, self.head_dim * self.num_heads)
598
+
599
+ attn_output = self.o_proj(attn_output)
600
+
601
+ return attn_output, None, past_key_value
602
+
603
+
604
+ NEMOTRON_ATTENTION_CLASSES = {
605
+ "eager": NemotronAttention,
606
+ "flash_attention_2": NemotronFlashAttention2,
607
+ "sdpa": NemotronSdpaAttention,
608
+ }
609
+
610
+
611
+ # Copied from transformers.models.llama.modeling_llama.LlamaDecoderLayer with LLAMA->NEMOTRON,Llama->Nemotron,llama->nemotron
612
+ class NemotronDecoderLayer(nn.Module):
613
+ def __init__(self, config: NemotronConfig, layer_idx: int):
614
+ super().__init__()
615
+ self.hidden_size = config.hidden_size
616
+
617
+ self.self_attn = NEMOTRON_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
618
+
619
+ self.mlp = NemotronMLP(config)
620
+ self.input_layernorm = LayerNorm1P(config.hidden_size, eps=config.norm_eps)
621
+ self.post_attention_layernorm = LayerNorm1P(config.hidden_size, eps=config.norm_eps)
622
+
623
+ def forward(
624
+ self,
625
+ hidden_states: torch.Tensor,
626
+ attention_mask: Optional[torch.Tensor] = None,
627
+ position_ids: Optional[torch.LongTensor] = None,
628
+ past_key_value: Optional[Cache] = None,
629
+ output_attentions: Optional[bool] = False,
630
+ use_cache: Optional[bool] = False,
631
+ cache_position: Optional[torch.LongTensor] = None,
632
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
633
+ """
634
+ Args:
635
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
636
+ attention_mask (`torch.FloatTensor`, *optional*):
637
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
638
+ query_sequence_length, key_sequence_length)` if default attention is used.
639
+ output_attentions (`bool`, *optional*):
640
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
641
+ returned tensors for more detail.
642
+ use_cache (`bool`, *optional*):
643
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
644
+ (see `past_key_values`).
645
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
646
+ """
647
+ residual = hidden_states
648
+
649
+ hidden_states = self.input_layernorm(hidden_states)
650
+
651
+ # Self Attention
652
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
653
+ hidden_states=hidden_states,
654
+ attention_mask=attention_mask,
655
+ position_ids=position_ids,
656
+ past_key_value=past_key_value,
657
+ output_attentions=output_attentions,
658
+ use_cache=use_cache,
659
+ cache_position=cache_position,
660
+ )
661
+ hidden_states = residual + hidden_states
662
+
663
+ # Fully Connected
664
+ residual = hidden_states
665
+ hidden_states = self.post_attention_layernorm(hidden_states)
666
+ hidden_states = self.mlp(hidden_states)
667
+ hidden_states = residual + hidden_states
668
+
669
+ outputs = (hidden_states,)
670
+
671
+ if output_attentions:
672
+ outputs += (self_attn_weights,)
673
+
674
+ if use_cache:
675
+ outputs += (present_key_value,)
676
+
677
+ return outputs
678
+
679
+
680
+ NEMOTRON_START_DOCSTRING = r"""
681
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
682
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
683
+ etc.)
684
+
685
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
686
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
687
+ and behavior.
688
+
689
+ Parameters:
690
+ config ([`NemotronConfig`]):
691
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
692
+ load the weights associated with the model, only the configuration. Check out the
693
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
694
+ """
695
+
696
+
697
+ @add_start_docstrings(
698
+ "The bare Nemotron Model outputting raw hidden-states without any specific head on top.",
699
+ NEMOTRON_START_DOCSTRING,
700
+ )
701
+ class NemotronPreTrainedModel(PreTrainedModel):
702
+ config_class = NemotronConfig
703
+ base_model_prefix = "model"
704
+ supports_gradient_checkpointing = True
705
+ _no_split_modules = ["NemotronDecoderLayer"]
706
+ _skip_keys_device_placement = ["past_key_values"]
707
+ _supports_flash_attn_2 = True
708
+ _supports_sdpa = True
709
+ _supports_cache_class = True
710
+ _supports_quantized_cache = True
711
+ _supports_static_cache = True
712
+
713
+ def _init_weights(self, module):
714
+ std = self.config.initializer_range
715
+ if isinstance(module, nn.Linear):
716
+ module.weight.data.normal_(mean=0.0, std=std)
717
+ if module.bias is not None:
718
+ module.bias.data.zero_()
719
+ elif isinstance(module, nn.Embedding):
720
+ module.weight.data.normal_(mean=0.0, std=std)
721
+ if module.padding_idx is not None:
722
+ module.weight.data[module.padding_idx].zero_()
723
+
724
+
725
+ NEMOTRON_INPUTS_DOCSTRING = r"""
726
+ Args:
727
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
728
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
729
+ it.
730
+
731
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
732
+ [`PreTrainedTokenizer.__call__`] for details.
733
+
734
+ [What are input IDs?](../glossary#input-ids)
735
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
736
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
737
+
738
+ - 1 for tokens that are **not masked**,
739
+ - 0 for tokens that are **masked**.
740
+
741
+ [What are attention masks?](../glossary#attention-mask)
742
+
743
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
744
+ [`PreTrainedTokenizer.__call__`] for details.
745
+
746
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
747
+ `past_key_values`).
748
+
749
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
750
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
751
+ information on the default strategy.
752
+
753
+ - 1 indicates the head is **not masked**,
754
+ - 0 indicates the head is **masked**.
755
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
756
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
757
+ config.n_positions - 1]`.
758
+
759
+ [What are position IDs?](../glossary#position-ids)
760
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
761
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
762
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
763
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
764
+
765
+ Two formats are allowed:
766
+ - a [`~cache_utils.Cache`] instance;
767
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
768
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
769
+ cache format.
770
+
771
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
772
+ legacy cache format will be returned.
773
+
774
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
775
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
776
+ of shape `(batch_size, sequence_length)`.
777
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
778
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
779
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
780
+ model's internal embedding lookup matrix.
781
+ use_cache (`bool`, *optional*):
782
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
783
+ `past_key_values`).
784
+ output_attentions (`bool`, *optional*):
785
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
786
+ tensors for more detail.
787
+ output_hidden_states (`bool`, *optional*):
788
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
789
+ more detail.
790
+ return_dict (`bool`, *optional*):
791
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
792
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
793
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
794
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
795
+ the complete sequence length.
796
+ """
797
+
798
+
799
+ @add_start_docstrings(
800
+ "The bare Nemotron Model outputting raw hidden-states without any specific head on top.",
801
+ NEMOTRON_START_DOCSTRING,
802
+ )
803
+ class NemotronModel(NemotronPreTrainedModel):
804
+ """
805
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`NemotronDecoderLayer`]
806
+
807
+ Args:
808
+ config: NemotronConfig
809
+ """
810
+
811
+ def __init__(self, config: NemotronConfig):
812
+ super().__init__(config)
813
+ self.padding_idx = config.pad_token_id
814
+ self.vocab_size = config.vocab_size
815
+
816
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
817
+ self.layers = nn.ModuleList(
818
+ [NemotronDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
819
+ )
820
+ self.norm = LayerNorm1P(config.hidden_size, eps=config.norm_eps)
821
+ self.gradient_checkpointing = False
822
+
823
+ # Initialize weights and apply final processing
824
+ self.post_init()
825
+
826
+ def get_input_embeddings(self):
827
+ return self.embed_tokens
828
+
829
+ def set_input_embeddings(self, value):
830
+ self.embed_tokens = value
831
+
832
+ @add_start_docstrings_to_model_forward(NEMOTRON_INPUTS_DOCSTRING)
833
+ def forward(
834
+ self,
835
+ input_ids: torch.LongTensor = None,
836
+ attention_mask: Optional[torch.Tensor] = None,
837
+ position_ids: Optional[torch.LongTensor] = None,
838
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
839
+ inputs_embeds: Optional[torch.FloatTensor] = None,
840
+ use_cache: Optional[bool] = None,
841
+ output_attentions: Optional[bool] = None,
842
+ output_hidden_states: Optional[bool] = None,
843
+ return_dict: Optional[bool] = None,
844
+ cache_position: Optional[torch.LongTensor] = None,
845
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
846
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
847
+ output_hidden_states = (
848
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
849
+ )
850
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
851
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
852
+
853
+ if (input_ids is None) ^ (inputs_embeds is not None):
854
+ raise ValueError(
855
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
856
+ )
857
+
858
+ if self.gradient_checkpointing and self.training and use_cache:
859
+ logger.warning_once(
860
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
861
+ )
862
+ use_cache = False
863
+
864
+ if inputs_embeds is None:
865
+ inputs_embeds = self.embed_tokens(input_ids)
866
+
867
+ return_legacy_cache = False
868
+ if use_cache and not isinstance(past_key_values, Cache): # kept for BC (non `Cache` `past_key_values` inputs)
869
+ return_legacy_cache = True
870
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
871
+
872
+ if cache_position is None:
873
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
874
+ cache_position = torch.arange(
875
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
876
+ )
877
+ if position_ids is None:
878
+ position_ids = cache_position.unsqueeze(0)
879
+
880
+ causal_mask = self._update_causal_mask(
881
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
882
+ )
883
+
884
+ # embed positions
885
+ hidden_states = inputs_embeds
886
+
887
+ # decoder layers
888
+ all_hidden_states = () if output_hidden_states else None
889
+ all_self_attns = () if output_attentions else None
890
+ next_decoder_cache = None
891
+
892
+ for decoder_layer in self.layers:
893
+ if output_hidden_states:
894
+ all_hidden_states += (hidden_states,)
895
+
896
+ if self.gradient_checkpointing and self.training:
897
+ layer_outputs = self._gradient_checkpointing_func(
898
+ decoder_layer.__call__,
899
+ hidden_states,
900
+ causal_mask,
901
+ position_ids,
902
+ past_key_values,
903
+ output_attentions,
904
+ use_cache,
905
+ cache_position,
906
+ )
907
+ else:
908
+ layer_outputs = decoder_layer(
909
+ hidden_states,
910
+ attention_mask=causal_mask,
911
+ position_ids=position_ids,
912
+ past_key_value=past_key_values,
913
+ output_attentions=output_attentions,
914
+ use_cache=use_cache,
915
+ cache_position=cache_position,
916
+ )
917
+
918
+ hidden_states = layer_outputs[0]
919
+
920
+ if use_cache:
921
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
922
+
923
+ if output_attentions:
924
+ all_self_attns += (layer_outputs[1],)
925
+
926
+ hidden_states = self.norm(hidden_states)
927
+
928
+ # add hidden states from the last decoder layer
929
+ if output_hidden_states:
930
+ all_hidden_states += (hidden_states,)
931
+
932
+ next_cache = next_decoder_cache if use_cache else None
933
+ if return_legacy_cache:
934
+ next_cache = next_cache.to_legacy_cache()
935
+
936
+ if not return_dict:
937
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
938
+ return BaseModelOutputWithPast(
939
+ last_hidden_state=hidden_states,
940
+ past_key_values=next_cache,
941
+ hidden_states=all_hidden_states,
942
+ attentions=all_self_attns,
943
+ )
944
+
945
+ def _update_causal_mask(
946
+ self,
947
+ attention_mask: torch.Tensor,
948
+ input_tensor: torch.Tensor,
949
+ cache_position: torch.Tensor,
950
+ past_key_values: Cache,
951
+ output_attentions: bool,
952
+ ):
953
+ # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
954
+ # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
955
+ # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
956
+ # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
957
+
958
+ if self.config._attn_implementation == "flash_attention_2":
959
+ if attention_mask is not None and 0.0 in attention_mask:
960
+ return attention_mask
961
+ return None
962
+
963
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
964
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
965
+ # to infer the attention mask.
966
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
967
+ using_static_cache = isinstance(past_key_values, StaticCache)
968
+
969
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
970
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
971
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
972
+ attention_mask,
973
+ inputs_embeds=input_tensor,
974
+ past_key_values_length=past_seen_tokens,
975
+ is_training=self.training,
976
+ ):
977
+ return None
978
+
979
+ dtype, device = input_tensor.dtype, input_tensor.device
980
+ min_dtype = torch.finfo(dtype).min
981
+ sequence_length = input_tensor.shape[1]
982
+ if using_static_cache:
983
+ target_length = past_key_values.get_max_length()
984
+ else:
985
+ target_length = (
986
+ attention_mask.shape[-1]
987
+ if isinstance(attention_mask, torch.Tensor)
988
+ else past_seen_tokens + sequence_length + 1
989
+ )
990
+
991
+ if attention_mask is not None and attention_mask.dim() == 4:
992
+ # in this case we assume that the mask comes already in inverted form and requires no inversion or slicing
993
+ if attention_mask.max() != 0:
994
+ raise ValueError("Custom 4D attention mask should be passed in inverted form with max==0`")
995
+ causal_mask = attention_mask
996
+ else:
997
+ causal_mask = torch.full(
998
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
999
+ )
1000
+ if sequence_length != 1:
1001
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1002
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1003
+ causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
1004
+ if attention_mask is not None:
1005
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1006
+ mask_length = attention_mask.shape[-1]
1007
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
1008
+ padding_mask = padding_mask == 0
1009
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1010
+ padding_mask, min_dtype
1011
+ )
1012
+ if (
1013
+ self.config._attn_implementation == "sdpa"
1014
+ and attention_mask is not None
1015
+ and attention_mask.device.type == "cuda"
1016
+ and not output_attentions
1017
+ ):
1018
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1019
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1020
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1021
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1022
+
1023
+ return causal_mask
1024
+
1025
+
1026
+ # Copied from transformers.models.llama.modeling_llama.LlamaForCausalLM with LLAMA->NEMOTRON,Llama->Nemotron,llama->nemotron
1027
+ class NemotronForCausalLM(NemotronPreTrainedModel):
1028
+ _tied_weights_keys = ["lm_head.weight"]
1029
+
1030
+ def __init__(self, config):
1031
+ super().__init__(config)
1032
+ self.model = NemotronModel(config)
1033
+ self.vocab_size = config.vocab_size
1034
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1035
+
1036
+ # Initialize weights and apply final processing
1037
+ self.post_init()
1038
+
1039
+ def get_input_embeddings(self):
1040
+ return self.model.embed_tokens
1041
+
1042
+ def set_input_embeddings(self, value):
1043
+ self.model.embed_tokens = value
1044
+
1045
+ def get_output_embeddings(self):
1046
+ return self.lm_head
1047
+
1048
+ def set_output_embeddings(self, new_embeddings):
1049
+ self.lm_head = new_embeddings
1050
+
1051
+ def set_decoder(self, decoder):
1052
+ self.model = decoder
1053
+
1054
+ def get_decoder(self):
1055
+ return self.model
1056
+
1057
+ @add_start_docstrings_to_model_forward(NEMOTRON_INPUTS_DOCSTRING)
1058
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1059
+ def forward(
1060
+ self,
1061
+ input_ids: torch.LongTensor = None,
1062
+ attention_mask: Optional[torch.Tensor] = None,
1063
+ position_ids: Optional[torch.LongTensor] = None,
1064
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1065
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1066
+ labels: Optional[torch.LongTensor] = None,
1067
+ use_cache: Optional[bool] = None,
1068
+ output_attentions: Optional[bool] = None,
1069
+ output_hidden_states: Optional[bool] = None,
1070
+ return_dict: Optional[bool] = None,
1071
+ cache_position: Optional[torch.LongTensor] = None,
1072
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1073
+ r"""
1074
+ Args:
1075
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1076
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1077
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1078
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1079
+
1080
+ Returns:
1081
+
1082
+ Example:
1083
+
1084
+ ```python
1085
+ >>> from transformers import AutoTokenizer, NemotronForCausalLM
1086
+
1087
+ >>> model = NemotronForCausalLM.from_pretrained("nvidia/nemotron4-15b")
1088
+ >>> tokenizer = AutoTokenizer.from_pretrained("nvidia/nemotron4-15b")
1089
+
1090
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1091
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1092
+
1093
+ >>> # Generate
1094
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1095
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1096
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1097
+ ```"""
1098
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1099
+ output_hidden_states = (
1100
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1101
+ )
1102
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1103
+
1104
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1105
+ outputs = self.model(
1106
+ input_ids=input_ids,
1107
+ attention_mask=attention_mask,
1108
+ position_ids=position_ids,
1109
+ past_key_values=past_key_values,
1110
+ inputs_embeds=inputs_embeds,
1111
+ use_cache=use_cache,
1112
+ output_attentions=output_attentions,
1113
+ output_hidden_states=output_hidden_states,
1114
+ return_dict=return_dict,
1115
+ cache_position=cache_position,
1116
+ )
1117
+
1118
+ hidden_states = outputs[0]
1119
+ logits = self.lm_head(hidden_states)
1120
+ logits = logits.float()
1121
+
1122
+ loss = None
1123
+ if labels is not None:
1124
+ # Shift so that tokens < n predict n
1125
+ shift_logits = logits[..., :-1, :].contiguous()
1126
+ shift_labels = labels[..., 1:].contiguous()
1127
+ # Flatten the tokens
1128
+ loss_fct = CrossEntropyLoss()
1129
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1130
+ shift_labels = shift_labels.view(-1)
1131
+ # Enable model parallelism
1132
+ shift_labels = shift_labels.to(shift_logits.device)
1133
+ loss = loss_fct(shift_logits, shift_labels)
1134
+
1135
+ if not return_dict:
1136
+ output = (logits,) + outputs[1:]
1137
+ return (loss,) + output if loss is not None else output
1138
+
1139
+ return CausalLMOutputWithPast(
1140
+ loss=loss,
1141
+ logits=logits,
1142
+ past_key_values=outputs.past_key_values,
1143
+ hidden_states=outputs.hidden_states,
1144
+ attentions=outputs.attentions,
1145
+ )
1146
+
1147
+ def prepare_inputs_for_generation(
1148
+ self,
1149
+ input_ids,
1150
+ past_key_values=None,
1151
+ attention_mask=None,
1152
+ inputs_embeds=None,
1153
+ cache_position=None,
1154
+ use_cache=True,
1155
+ **kwargs,
1156
+ ):
1157
+ past_length = 0
1158
+ if past_key_values is not None:
1159
+ # Past key values are always initialized with a `Cache` object -> no need for if-else anymore
1160
+ past_length = cache_position[0] if cache_position is not None else past_key_values.get_seq_length()
1161
+ max_cache_length = (
1162
+ torch.tensor(past_key_values.get_max_length(), device=input_ids.device)
1163
+ if past_key_values.get_max_length() is not None
1164
+ else None
1165
+ )
1166
+ cache_length = past_length if max_cache_length is None else torch.min(max_cache_length, past_length)
1167
+
1168
+ # Keep only the unprocessed tokens:
1169
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1170
+ # some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as input)
1171
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1172
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1173
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1174
+ # input_ids based on the past_length.
1175
+ elif past_length < input_ids.shape[1]:
1176
+ input_ids = input_ids[:, past_length:]
1177
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1178
+
1179
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1180
+ if (
1181
+ max_cache_length is not None
1182
+ and attention_mask is not None
1183
+ and cache_length + input_ids.shape[1] > max_cache_length
1184
+ ):
1185
+ attention_mask = attention_mask[:, -max_cache_length:]
1186
+
1187
+ position_ids = kwargs.get("position_ids", None)
1188
+ if attention_mask is not None and position_ids is None:
1189
+ # create position_ids on the fly for batch generation
1190
+ position_ids = attention_mask.long().cumsum(-1) - 1
1191
+ position_ids.masked_fill_(attention_mask == 0, 1)
1192
+ if past_key_values:
1193
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1194
+
1195
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1196
+ if inputs_embeds is not None and past_length == 0:
1197
+ model_inputs = {"inputs_embeds": inputs_embeds}
1198
+ else:
1199
+ # The `contiguous()` here is necessary to have a static stride during decoding. torchdynamo otherwise
1200
+ # recompiles graphs as the stride of the inputs is a guard. Ref: https://github.com/huggingface/transformers/pull/29114
1201
+ # TODO: use `next_tokens` directly instead.
1202
+ model_inputs = {"input_ids": input_ids.contiguous()}
1203
+
1204
+ input_length = position_ids.shape[-1] if position_ids is not None else input_ids.shape[-1]
1205
+ if cache_position is None:
1206
+ cache_position = torch.arange(past_length, past_length + input_length, device=input_ids.device)
1207
+ elif use_cache:
1208
+ cache_position = cache_position[-input_length:]
1209
+
1210
+ model_inputs.update(
1211
+ {
1212
+ "position_ids": position_ids,
1213
+ "cache_position": cache_position,
1214
+ "past_key_values": past_key_values,
1215
+ "use_cache": use_cache,
1216
+ "attention_mask": attention_mask,
1217
+ }
1218
+ )
1219
+ return model_inputs
1220
+
1221
+ @staticmethod
1222
+ def _reorder_cache(past_key_values, beam_idx):
1223
+ reordered_past = ()
1224
+ for layer_past in past_key_values:
1225
+ reordered_past += (
1226
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1227
+ )
1228
+ return reordered_past
1229
+
1230
+
1231
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with LLAMA->NEMOTRON,Llama->Nemotron,llama->nemotron
1232
+ @add_start_docstrings(
1233
+ """
1234
+ The Nemotron Model transformer with a sequence classification head on top (linear layer).
1235
+
1236
+ [`NemotronForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1237
+ (e.g. GPT-2) do.
1238
+
1239
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1240
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1241
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1242
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1243
+ each row of the batch).
1244
+ """,
1245
+ NEMOTRON_START_DOCSTRING,
1246
+ )
1247
+ class NemotronForSequenceClassification(NemotronPreTrainedModel):
1248
+ def __init__(self, config):
1249
+ super().__init__(config)
1250
+ self.num_labels = config.num_labels
1251
+ self.model = NemotronModel(config)
1252
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1253
+
1254
+ # Initialize weights and apply final processing
1255
+ self.post_init()
1256
+
1257
+ def get_input_embeddings(self):
1258
+ return self.model.embed_tokens
1259
+
1260
+ def set_input_embeddings(self, value):
1261
+ self.model.embed_tokens = value
1262
+
1263
+ @add_start_docstrings_to_model_forward(NEMOTRON_INPUTS_DOCSTRING)
1264
+ def forward(
1265
+ self,
1266
+ input_ids: torch.LongTensor = None,
1267
+ attention_mask: Optional[torch.Tensor] = None,
1268
+ position_ids: Optional[torch.LongTensor] = None,
1269
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1270
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1271
+ labels: Optional[torch.LongTensor] = None,
1272
+ use_cache: Optional[bool] = None,
1273
+ output_attentions: Optional[bool] = None,
1274
+ output_hidden_states: Optional[bool] = None,
1275
+ return_dict: Optional[bool] = None,
1276
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1277
+ r"""
1278
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1279
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1280
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1281
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1282
+ """
1283
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1284
+
1285
+ transformer_outputs = self.model(
1286
+ input_ids,
1287
+ attention_mask=attention_mask,
1288
+ position_ids=position_ids,
1289
+ past_key_values=past_key_values,
1290
+ inputs_embeds=inputs_embeds,
1291
+ use_cache=use_cache,
1292
+ output_attentions=output_attentions,
1293
+ output_hidden_states=output_hidden_states,
1294
+ return_dict=return_dict,
1295
+ )
1296
+ hidden_states = transformer_outputs[0]
1297
+ logits = self.score(hidden_states)
1298
+
1299
+ if input_ids is not None:
1300
+ batch_size = input_ids.shape[0]
1301
+ else:
1302
+ batch_size = inputs_embeds.shape[0]
1303
+
1304
+ if self.config.pad_token_id is None and batch_size != 1:
1305
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1306
+ if self.config.pad_token_id is None:
1307
+ sequence_lengths = -1
1308
+ else:
1309
+ if input_ids is not None:
1310
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1311
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1312
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1313
+ sequence_lengths = sequence_lengths.to(logits.device)
1314
+ else:
1315
+ sequence_lengths = -1
1316
+
1317
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1318
+
1319
+ loss = None
1320
+ if labels is not None:
1321
+ labels = labels.to(logits.device)
1322
+ if self.config.problem_type is None:
1323
+ if self.num_labels == 1:
1324
+ self.config.problem_type = "regression"
1325
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1326
+ self.config.problem_type = "single_label_classification"
1327
+ else:
1328
+ self.config.problem_type = "multi_label_classification"
1329
+
1330
+ if self.config.problem_type == "regression":
1331
+ loss_fct = MSELoss()
1332
+ if self.num_labels == 1:
1333
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1334
+ else:
1335
+ loss = loss_fct(pooled_logits, labels)
1336
+ elif self.config.problem_type == "single_label_classification":
1337
+ loss_fct = CrossEntropyLoss()
1338
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1339
+ elif self.config.problem_type == "multi_label_classification":
1340
+ loss_fct = BCEWithLogitsLoss()
1341
+ loss = loss_fct(pooled_logits, labels)
1342
+ if not return_dict:
1343
+ output = (pooled_logits,) + transformer_outputs[1:]
1344
+ return ((loss,) + output) if loss is not None else output
1345
+
1346
+ return SequenceClassifierOutputWithPast(
1347
+ loss=loss,
1348
+ logits=pooled_logits,
1349
+ past_key_values=transformer_outputs.past_key_values,
1350
+ hidden_states=transformer_outputs.hidden_states,
1351
+ attentions=transformer_outputs.attentions,
1352
+ )
1353
+
1354
+
1355
+ # Copied from transformers.models.llama.modeling_llama.LlamaForQuestionAnswering with LLAMA->NEMOTRON,Llama->Nemotron,llama->nemotron
1356
+ @add_start_docstrings(
1357
+ """
1358
+ The Nemotron Model transformer with a span classification head on top for extractive question-answering tasks like
1359
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1360
+ """,
1361
+ NEMOTRON_START_DOCSTRING,
1362
+ )
1363
+ class NemotronForQuestionAnswering(NemotronPreTrainedModel):
1364
+ base_model_prefix = "transformer"
1365
+
1366
+ # Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->Nemotron
1367
+ def __init__(self, config):
1368
+ super().__init__(config)
1369
+ self.transformer = NemotronModel(config)
1370
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1371
+
1372
+ # Initialize weights and apply final processing
1373
+ self.post_init()
1374
+
1375
+ def get_input_embeddings(self):
1376
+ return self.transformer.embed_tokens
1377
+
1378
+ def set_input_embeddings(self, value):
1379
+ self.transformer.embed_tokens = value
1380
+
1381
+ @add_start_docstrings_to_model_forward(NEMOTRON_INPUTS_DOCSTRING)
1382
+ def forward(
1383
+ self,
1384
+ input_ids: Optional[torch.LongTensor] = None,
1385
+ attention_mask: Optional[torch.FloatTensor] = None,
1386
+ position_ids: Optional[torch.LongTensor] = None,
1387
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1388
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1389
+ start_positions: Optional[torch.LongTensor] = None,
1390
+ end_positions: Optional[torch.LongTensor] = None,
1391
+ output_attentions: Optional[bool] = None,
1392
+ output_hidden_states: Optional[bool] = None,
1393
+ return_dict: Optional[bool] = None,
1394
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1395
+ r"""
1396
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1397
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1398
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1399
+ are not taken into account for computing the loss.
1400
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1401
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1402
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1403
+ are not taken into account for computing the loss.
1404
+ """
1405
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1406
+
1407
+ outputs = self.transformer(
1408
+ input_ids,
1409
+ attention_mask=attention_mask,
1410
+ position_ids=position_ids,
1411
+ past_key_values=past_key_values,
1412
+ inputs_embeds=inputs_embeds,
1413
+ output_attentions=output_attentions,
1414
+ output_hidden_states=output_hidden_states,
1415
+ return_dict=return_dict,
1416
+ )
1417
+
1418
+ sequence_output = outputs[0]
1419
+
1420
+ logits = self.qa_outputs(sequence_output)
1421
+ start_logits, end_logits = logits.split(1, dim=-1)
1422
+ start_logits = start_logits.squeeze(-1).contiguous()
1423
+ end_logits = end_logits.squeeze(-1).contiguous()
1424
+
1425
+ total_loss = None
1426
+ if start_positions is not None and end_positions is not None:
1427
+ # If we are on multi-GPU, split add a dimension
1428
+ if len(start_positions.size()) > 1:
1429
+ start_positions = start_positions.squeeze(-1).to(start_logits.device)
1430
+ if len(end_positions.size()) > 1:
1431
+ end_positions = end_positions.squeeze(-1).to(end_logits.device)
1432
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1433
+ ignored_index = start_logits.size(1)
1434
+ start_positions = start_positions.clamp(0, ignored_index)
1435
+ end_positions = end_positions.clamp(0, ignored_index)
1436
+
1437
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1438
+ start_loss = loss_fct(start_logits, start_positions)
1439
+ end_loss = loss_fct(end_logits, end_positions)
1440
+ total_loss = (start_loss + end_loss) / 2
1441
+
1442
+ if not return_dict:
1443
+ output = (start_logits, end_logits) + outputs[2:]
1444
+ return ((total_loss,) + output) if total_loss is not None else output
1445
+
1446
+ return QuestionAnsweringModelOutput(
1447
+ loss=total_loss,
1448
+ start_logits=start_logits,
1449
+ end_logits=end_logits,
1450
+ hidden_states=outputs.hidden_states,
1451
+ attentions=outputs.attentions,
1452
+ )
1453
+
1454
+
1455
+ # Copied from transformers.models.llama.modeling_llama.LlamaForTokenClassification with LLAMA->NEMOTRON,Llama->Nemotron,llama->nemotron
1456
+ @add_start_docstrings(
1457
+ """
1458
+ The Nemotron Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1459
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1460
+ """,
1461
+ NEMOTRON_START_DOCSTRING,
1462
+ )
1463
+ class NemotronForTokenClassification(NemotronPreTrainedModel):
1464
+ def __init__(self, config):
1465
+ super().__init__(config)
1466
+ self.num_labels = config.num_labels
1467
+ self.model = NemotronModel(config)
1468
+ if getattr(config, "classifier_dropout", None) is not None:
1469
+ classifier_dropout = config.classifier_dropout
1470
+ elif getattr(config, "hidden_dropout", None) is not None:
1471
+ classifier_dropout = config.hidden_dropout
1472
+ else:
1473
+ classifier_dropout = 0.1
1474
+ self.dropout = nn.Dropout(classifier_dropout)
1475
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1476
+
1477
+ # Initialize weights and apply final processing
1478
+ self.post_init()
1479
+
1480
+ def get_input_embeddings(self):
1481
+ return self.model.embed_tokens
1482
+
1483
+ def set_input_embeddings(self, value):
1484
+ self.model.embed_tokens = value
1485
+
1486
+ @add_start_docstrings_to_model_forward(NEMOTRON_INPUTS_DOCSTRING)
1487
+ def forward(
1488
+ self,
1489
+ input_ids: torch.LongTensor = None,
1490
+ attention_mask: Optional[torch.Tensor] = None,
1491
+ position_ids: Optional[torch.LongTensor] = None,
1492
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1493
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1494
+ labels: Optional[torch.LongTensor] = None,
1495
+ use_cache: Optional[bool] = None,
1496
+ output_attentions: Optional[bool] = None,
1497
+ output_hidden_states: Optional[bool] = None,
1498
+ return_dict: Optional[bool] = None,
1499
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1500
+ r"""
1501
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1502
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1503
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1504
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1505
+ """
1506
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1507
+
1508
+ outputs = self.model(
1509
+ input_ids,
1510
+ attention_mask=attention_mask,
1511
+ position_ids=position_ids,
1512
+ past_key_values=past_key_values,
1513
+ inputs_embeds=inputs_embeds,
1514
+ use_cache=use_cache,
1515
+ output_attentions=output_attentions,
1516
+ output_hidden_states=output_hidden_states,
1517
+ return_dict=return_dict,
1518
+ )
1519
+ sequence_output = outputs[0]
1520
+ sequence_output = self.dropout(sequence_output)
1521
+ logits = self.score(sequence_output)
1522
+
1523
+ loss = None
1524
+ if labels is not None:
1525
+ loss_fct = CrossEntropyLoss()
1526
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1527
+
1528
+ if not return_dict:
1529
+ output = (logits,) + outputs[2:]
1530
+ return ((loss,) + output) if loss is not None else output
1531
+
1532
+ return TokenClassifierOutput(
1533
+ loss=loss,
1534
+ logits=logits,
1535
+ hidden_states=outputs.hidden_states,
1536
+ attentions=outputs.attentions,
1537
+ )