WonsukYangTL commited on
Commit
d8d35f5
·
verified ·
1 Parent(s): 49955d1

Upload 2 files

Browse files
Files changed (2) hide show
  1. configuration_trillion.py +227 -0
  2. modeling_trillion.py +866 -0
configuration_trillion.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """Trillion model configuration"""
21
+
22
+ from transformers.configuration_utils import PretrainedConfig
23
+ from transformers.modeling_rope_utils import rope_config_validation
24
+
25
+
26
+ class TrillionConfig(PretrainedConfig):
27
+ r"""
28
+ This is the configuration class to store the configuration of a [`TrillionModel`]. It is used to instantiate an Trillion
29
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
30
+ defaults will yield a similar configuration to that of the Tri-70B-preview-SFT.
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+
36
+ Args:
37
+ vocab_size (`int`, *optional*, defaults to 124416):
38
+ Vocabulary size of the Trillion model. Defines the number of different tokens that can be represented by the
39
+ `inputs_ids` passed when calling [`TrillionModel`]
40
+ hidden_size (`int`, *optional*, defaults to 8192):
41
+ Dimension of the hidden representations.
42
+ intermediate_size (`int`, *optional*, defaults to 28672):
43
+ Dimension of the MLP representations.
44
+ num_hidden_layers (`int`, *optional*, defaults to 80):
45
+ Number of hidden layers in the Transformer decoder.
46
+ num_attention_heads (`int`, *optional*, defaults to 64):
47
+ Number of attention heads for each attention layer in the Transformer decoder.
48
+ num_key_value_heads (`int`, *optional*, defaults to 8):
49
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
50
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
51
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
52
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
53
+ by meanpooling all the original heads within that group. For more details checkout [this
54
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
55
+ `num_attention_heads`.
56
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
57
+ The non-linear activation function (function or string) in the decoder.
58
+ max_position_embeddings (`int`, *optional*, defaults to 32768):
59
+ The maximum sequence length that this model might ever be used with.
60
+ initializer_range (`float`, *optional*, defaults to 0.02):
61
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
62
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
63
+ The epsilon used by the rms normalization layers.
64
+ use_cache (`bool`, *optional*, defaults to `True`):
65
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
66
+ relevant if `config.is_decoder=True`.
67
+ pad_token_id (`int`, *optional*):
68
+ Padding token id.
69
+ bos_token_id (`int`, *optional*, defaults to 1):
70
+ Beginning of stream token id.
71
+ eos_token_id (`int`, *optional*, defaults to 2):
72
+ End of stream token id.
73
+ pretraining_tp (`int`, *optional*, defaults to 1):
74
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
75
+ document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to
76
+ understand more about it. This value is necessary to ensure exact reproducibility of the pretraining
77
+ results. Please refer to [this issue](https://github.com/pytorch/pytorch/issues/76232).
78
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
79
+ Whether to tie weight embeddings
80
+ rope_theta (`float`, *optional*, defaults to 10000.0):
81
+ The base period of the RoPE embeddings.
82
+ rope_scaling (`Dict`, *optional*):
83
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
84
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
85
+ accordingly.
86
+ Expected contents:
87
+ `rope_type` (`str`):
88
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope'],
89
+ with 'default' being the original RoPE implementation.
90
+ `factor` (`float`, *optional*):
91
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
92
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
93
+ original maximum pre-trained length.
94
+ `original_max_position_embeddings` (`int`, *optional*):
95
+ Used with 'dynamic' and 'longrope'. The original max position embeddings used during
96
+ pretraining.
97
+ `attention_factor` (`float`, *optional*):
98
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
99
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
100
+ `factor` field to infer the suggested value.
101
+ `beta_fast` (`float`, *optional*):
102
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
103
+ ramp function. If unspecified, it defaults to 32.
104
+ `beta_slow` (`float`, *optional*):
105
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
106
+ ramp function. If unspecified, it defaults to 1.
107
+ `short_factor` (`List[float]`, *optional*):
108
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
109
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
110
+ size divided by the number of attention heads divided by 2
111
+ `long_factor` (`List[float]`, *optional*):
112
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
113
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
114
+ size divided by the number of attention heads divided by 2
115
+ attention_bias (`bool`, *optional*, defaults to `False`):
116
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
117
+ attention_dropout (`float`, *optional*, defaults to 0.0):
118
+ The dropout ratio for the attention probabilities.
119
+ mlp_bias (`bool`, *optional*, defaults to `False`):
120
+ Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
121
+ head_dim (`int`, *optional*):
122
+ The attention head dimension. If None, it will default to hidden_size // num_attention_heads
123
+
124
+ ```python
125
+ >>> from transformers import TrillionModel, TrillionConfig
126
+
127
+ >>> # Initializing a Tri-70B-preview-SFT style configuration
128
+ >>> configuration = TrillionConfig()
129
+
130
+ >>> # Initializing a model from the Tri-70B-preview-SFT style configuration
131
+ >>> model = TrillionModel(configuration)
132
+
133
+ >>> # Accessing the model configuration
134
+ >>> configuration = model.config
135
+ ```"""
136
+
137
+ model_type = "trillion"
138
+ keys_to_ignore_at_inference = ["past_key_values"]
139
+ # Default tensor parallel plan for base model `TrillionModel`
140
+ base_model_tp_plan = {
141
+ "layers.*.self_attn.q_proj": "colwise",
142
+ "layers.*.self_attn.k_proj": "colwise",
143
+ "layers.*.self_attn.v_proj": "colwise",
144
+ "layers.*.self_attn.o_proj": "rowwise",
145
+ "layers.*.mlp.gate_proj": "colwise",
146
+ "layers.*.mlp.up_proj": "colwise",
147
+ "layers.*.mlp.down_proj": "rowwise",
148
+ }
149
+ base_model_pp_plan = {
150
+ "embed_tokens": (["input_ids"], ["inputs_embeds"]),
151
+ "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
152
+ "norm": (["hidden_states"], ["hidden_states"]),
153
+ }
154
+
155
+ def __init__(
156
+ self,
157
+ vocab_size=124416,
158
+ hidden_size=8192,
159
+ intermediate_size=28672,
160
+ num_hidden_layers=80,
161
+ num_attention_heads=64,
162
+ num_key_value_heads=8,
163
+ hidden_act="silu",
164
+ max_position_embeddings=32768,
165
+ initializer_range=0.02,
166
+ rms_norm_eps=1e-6,
167
+ use_cache=True,
168
+ pad_token_id=None,
169
+ bos_token_id=1,
170
+ eos_token_id=2,
171
+ pretraining_tp=1,
172
+ tie_word_embeddings=False,
173
+ rope_theta=10000.0,
174
+ rope_scaling=None,
175
+ global_attention_freq=4,
176
+ attn_temperature_tuning=True,
177
+ floor_scale=1.0,
178
+ attn_scale=1.0,
179
+ attention_bias=False,
180
+ attention_dropout=0.0,
181
+ mlp_bias=False,
182
+ head_dim=None,
183
+ **kwargs,
184
+ ):
185
+ self.attn_temperature_tuning = attn_temperature_tuning
186
+ self.attn_scale = attn_scale
187
+ self.floor_scale = floor_scale
188
+ self.global_attention_freq = global_attention_freq
189
+ self.vocab_size = vocab_size
190
+ self.max_position_embeddings = max_position_embeddings
191
+ self.hidden_size = hidden_size
192
+ self.intermediate_size = intermediate_size
193
+ self.num_hidden_layers = num_hidden_layers
194
+ self.num_attention_heads = num_attention_heads
195
+
196
+ # for backward compatibility
197
+ if num_key_value_heads is None:
198
+ num_key_value_heads = num_attention_heads
199
+
200
+ self.num_key_value_heads = num_key_value_heads
201
+ self.hidden_act = hidden_act
202
+ self.initializer_range = initializer_range
203
+ self.rms_norm_eps = rms_norm_eps
204
+ self.pretraining_tp = pretraining_tp
205
+ self.use_cache = use_cache
206
+ self.rope_theta = rope_theta
207
+ self.rope_scaling = rope_scaling
208
+ self.attention_bias = attention_bias
209
+ self.attention_dropout = attention_dropout
210
+ self.mlp_bias = mlp_bias
211
+ self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
212
+ # Validate the correctness of rotary position embeddings parameters
213
+ # BC: if there is a 'type' field, copy it it to 'rope_type'.
214
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
215
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
216
+ rope_config_validation(self)
217
+
218
+ super().__init__(
219
+ pad_token_id=pad_token_id,
220
+ bos_token_id=bos_token_id,
221
+ eos_token_id=eos_token_id,
222
+ tie_word_embeddings=tie_word_embeddings,
223
+ **kwargs,
224
+ )
225
+
226
+
227
+ __all__ = ["TrillionConfig"]
modeling_trillion.py ADDED
@@ -0,0 +1,866 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ from functools import partial
21
+ from typing import Callable, Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.utils.checkpoint
25
+ from torch import nn
26
+
27
+ from transformers.activations import ACT2FN
28
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
29
+ from transformers.generation import GenerationMixin
30
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
31
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
32
+ from transformers.modeling_outputs import (
33
+ BaseModelOutputWithPast,
34
+ CausalLMOutputWithPast,
35
+ )
36
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
37
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
38
+ from transformers.processing_utils import Unpack
39
+ from transformers.utils import (
40
+ TransformersKwargs,
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ can_return_tuple,
44
+ is_torch_flex_attn_available,
45
+ logging,
46
+ replace_return_docstrings,
47
+ )
48
+ from .configuration_trillion import TrillionConfig
49
+
50
+
51
+ if is_torch_flex_attn_available():
52
+ from torch.nn.attention.flex_attention import BlockMask
53
+
54
+ from transformers.integrations.flex_attention import make_flex_block_causal_mask
55
+
56
+ from transformers.integrations import use_kernel_forward_from_hub
57
+
58
+
59
+ logger = logging.get_logger(__name__)
60
+
61
+ _CHECKPOINT_FOR_DOC = "trillionlabs/Tri-70B-preview-SFT"
62
+ _CONFIG_FOR_DOC = "TrillionConfig"
63
+
64
+
65
+ @use_kernel_forward_from_hub("RMSNorm")
66
+ class TrillionRMSNorm(nn.Module):
67
+ def __init__(self, hidden_size, eps=1e-6):
68
+ """
69
+ TrillionRMSNorm is equivalent to T5LayerNorm
70
+ """
71
+ super().__init__()
72
+ self.weight = nn.Parameter(torch.ones(hidden_size))
73
+ self.variance_epsilon = eps
74
+
75
+ def forward(self, hidden_states):
76
+ input_dtype = hidden_states.dtype
77
+ hidden_states = hidden_states.to(torch.float32)
78
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
79
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
80
+ return self.weight * hidden_states.to(input_dtype)
81
+
82
+ def extra_repr(self):
83
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
84
+
85
+
86
+ class TrillionRotaryEmbedding(nn.Module):
87
+ def __init__(self, config: TrillionConfig, device=None):
88
+ super().__init__()
89
+ # BC: "rope_type" was originally "type"
90
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
91
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
92
+ else:
93
+ self.rope_type = "default"
94
+ self.max_seq_len_cached = config.max_position_embeddings
95
+ self.original_max_seq_len = config.max_position_embeddings
96
+
97
+ self.config = config
98
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
99
+
100
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
101
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
102
+ self.original_inv_freq = self.inv_freq
103
+
104
+ @torch.no_grad()
105
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
106
+ def forward(self, x, position_ids):
107
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
108
+ position_ids_expanded = position_ids[:, None, :].float()
109
+
110
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
111
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
112
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
113
+ emb = torch.cat((freqs, freqs), dim=-1)
114
+ cos = emb.cos() * self.attention_scaling
115
+ sin = emb.sin() * self.attention_scaling
116
+
117
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
118
+
119
+
120
+ def rotate_half(x):
121
+ """Rotates half the hidden dims of the input."""
122
+ x1 = x[..., : x.shape[-1] // 2]
123
+ x2 = x[..., x.shape[-1] // 2 :]
124
+ return torch.cat((-x2, x1), dim=-1)
125
+
126
+
127
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
128
+ """Applies Rotary Position Embedding to the query and key tensors.
129
+
130
+ Args:
131
+ q (`torch.Tensor`): The query tensor.
132
+ k (`torch.Tensor`): The key tensor.
133
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
134
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
135
+ position_ids (`torch.Tensor`, *optional*):
136
+ Deprecated and unused.
137
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
138
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
139
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
140
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
141
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
142
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
143
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
144
+ Returns:
145
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
146
+ """
147
+ cos = cos.unsqueeze(unsqueeze_dim)
148
+ sin = sin.unsqueeze(unsqueeze_dim)
149
+ q_embed = (q * cos) + (rotate_half(q) * sin)
150
+ k_embed = (k * cos) + (rotate_half(k) * sin)
151
+ return q_embed, k_embed
152
+
153
+
154
+ class TrillionMLP(nn.Module):
155
+ def __init__(self, config):
156
+ super().__init__()
157
+ self.config = config
158
+ self.hidden_size = config.hidden_size
159
+ self.intermediate_size = config.intermediate_size
160
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
161
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
162
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
163
+ self.act_fn = ACT2FN[config.hidden_act]
164
+
165
+ def forward(self, x):
166
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
167
+ return down_proj
168
+
169
+
170
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
171
+ """
172
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
173
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
174
+ """
175
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
176
+ if n_rep == 1:
177
+ return hidden_states
178
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
179
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
180
+
181
+
182
+ def eager_attention_forward(
183
+ module: nn.Module,
184
+ query: torch.Tensor,
185
+ key: torch.Tensor,
186
+ value: torch.Tensor,
187
+ attention_mask: Optional[torch.Tensor],
188
+ scaling: float,
189
+ dropout: float = 0.0,
190
+ **kwargs,
191
+ ):
192
+ key_states = repeat_kv(key, module.num_key_value_groups)
193
+ value_states = repeat_kv(value, module.num_key_value_groups)
194
+
195
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
196
+ if attention_mask is not None:
197
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
198
+ attn_weights = attn_weights + causal_mask
199
+
200
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
201
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
202
+ attn_output = torch.matmul(attn_weights, value_states)
203
+ attn_output = attn_output.transpose(1, 2).contiguous()
204
+
205
+ return attn_output, attn_weights
206
+
207
+
208
+ class TrillionAttention(nn.Module):
209
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
210
+
211
+ def __init__(self, config: TrillionConfig, layer_idx: int):
212
+ super().__init__()
213
+ self.config = config
214
+ self.layer_idx = layer_idx
215
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
216
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
217
+ self.scaling = self.head_dim**-0.5
218
+ self.attention_dropout = config.attention_dropout
219
+ self.global_attention_freq = config.global_attention_freq
220
+ self.attn_scale = config.attn_scale
221
+ self.floor_scale = config.floor_scale
222
+ self.attn_temperature_tuning = config.attn_temperature_tuning
223
+ self.is_causal = True
224
+ self.use_rope = (layer_idx + 1) % self.global_attention_freq != 0 # rope used for local attention only
225
+
226
+ self.q_proj = nn.Linear(
227
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
228
+ )
229
+ self.k_proj = nn.Linear(
230
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
231
+ )
232
+ self.v_proj = nn.Linear(
233
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
234
+ )
235
+ self.o_proj = nn.Linear(
236
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
237
+ )
238
+
239
+ def forward(
240
+ self,
241
+ hidden_states: torch.Tensor,
242
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
243
+ attention_mask: Optional[torch.Tensor],
244
+ past_key_value: Optional[Cache] = None,
245
+ cache_position: Optional[torch.LongTensor] = None,
246
+ **kwargs: Unpack[FlashAttentionKwargs],
247
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
248
+ input_shape = hidden_states.shape[:-1]
249
+ hidden_shape = (*input_shape, -1, self.head_dim)
250
+
251
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
252
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
253
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
254
+
255
+ if self.use_rope:
256
+ cos, sin = position_embeddings
257
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
258
+
259
+ if self.attn_temperature_tuning and not self.use_rope:
260
+ attn_scales = (
261
+ torch.log(torch.floor((cache_position.float() + 1.0) / self.floor_scale) + 1.0) * self.attn_scale + 1.0
262
+ )
263
+ attn_scales = attn_scales.view((1, input_shape[-1], 1, 1)).expand((*input_shape, 1, 1)).transpose(1, 2)
264
+ query_states = (query_states * attn_scales).to(query_states.dtype)
265
+
266
+ if past_key_value is not None:
267
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
268
+ cache_kwargs = {"cache_position": cache_position}
269
+ if self.use_rope:
270
+ cache_kwargs["cos"] = cos
271
+ cache_kwargs["sin"] = sin
272
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
273
+
274
+ attention_interface: Callable = eager_attention_forward
275
+
276
+ if self.config._attn_implementation != "eager":
277
+ if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
278
+ logger.warning_once(
279
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
280
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
281
+ )
282
+ else:
283
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
284
+
285
+ attn_output, attn_weights = attention_interface(
286
+ self,
287
+ query_states,
288
+ key_states,
289
+ value_states,
290
+ attention_mask,
291
+ dropout=0.0 if not self.training else self.attention_dropout,
292
+ scaling=self.scaling,
293
+ **kwargs,
294
+ )
295
+
296
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
297
+ attn_output = self.o_proj(attn_output)
298
+ return attn_output, attn_weights
299
+
300
+
301
+ class TrillionDecoderLayer(nn.Module):
302
+ def __init__(self, config: TrillionConfig, layer_idx: int):
303
+ super().__init__()
304
+ self.hidden_size = config.hidden_size
305
+
306
+ self.self_attn = TrillionAttention(config=config, layer_idx=layer_idx)
307
+
308
+ self.mlp = TrillionMLP(config)
309
+ self.input_layernorm = TrillionRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
310
+ self.post_attention_layernorm = TrillionRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
311
+
312
+ def forward(
313
+ self,
314
+ hidden_states: torch.Tensor,
315
+ attention_mask: Optional[torch.Tensor] = None,
316
+ position_ids: Optional[torch.LongTensor] = None,
317
+ past_key_value: Optional[Cache] = None,
318
+ output_attentions: Optional[bool] = False,
319
+ use_cache: Optional[bool] = False,
320
+ cache_position: Optional[torch.LongTensor] = None,
321
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
322
+ **kwargs: Unpack[FlashAttentionKwargs],
323
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
324
+ residual = hidden_states
325
+ hidden_states = self.input_layernorm(hidden_states)
326
+
327
+ # Self Attention
328
+ hidden_states, self_attn_weights = self.self_attn(
329
+ hidden_states=hidden_states,
330
+ attention_mask=attention_mask,
331
+ position_ids=position_ids,
332
+ past_key_value=past_key_value,
333
+ output_attentions=output_attentions,
334
+ use_cache=use_cache,
335
+ cache_position=cache_position,
336
+ position_embeddings=position_embeddings,
337
+ **kwargs,
338
+ )
339
+ hidden_states = residual + hidden_states
340
+
341
+ # Fully Connected
342
+ residual = hidden_states
343
+ hidden_states = self.post_attention_layernorm(hidden_states)
344
+ hidden_states = self.mlp(hidden_states)
345
+ hidden_states = residual + hidden_states
346
+
347
+ outputs = (hidden_states,)
348
+ if output_attentions:
349
+ outputs += (self_attn_weights,)
350
+
351
+ return outputs
352
+
353
+
354
+ TRILLION_START_DOCSTRING = r"""
355
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
356
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
357
+ etc.)
358
+
359
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
360
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
361
+ and behavior.
362
+
363
+ Parameters:
364
+ config ([`TrillionConfig`]):
365
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
366
+ load the weights associated with the model, only the configuration. Check out the
367
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
368
+ """
369
+
370
+
371
+ @add_start_docstrings(
372
+ "The bare Trillion Model outputting raw hidden-states without any specific head on top.",
373
+ TRILLION_START_DOCSTRING,
374
+ )
375
+ class TrillionPreTrainedModel(PreTrainedModel):
376
+ config_class = TrillionConfig
377
+ base_model_prefix = "model"
378
+ supports_gradient_checkpointing = True
379
+ _no_split_modules = ["TrillionDecoderLayer"]
380
+ _skip_keys_device_placement = ["past_key_values"]
381
+ _supports_flash_attn_2 = True
382
+ _supports_sdpa = True
383
+ _supports_flex_attn = True
384
+ _supports_cache_class = True
385
+ _supports_quantized_cache = True
386
+ _supports_static_cache = True
387
+ _supports_attention_backend = True
388
+
389
+ def _init_weights(self, module):
390
+ std = self.config.initializer_range
391
+ if isinstance(module, nn.Linear):
392
+ module.weight.data.normal_(mean=0.0, std=std)
393
+ if module.bias is not None:
394
+ module.bias.data.zero_()
395
+ elif isinstance(module, nn.Embedding):
396
+ module.weight.data.normal_(mean=0.0, std=std)
397
+ if module.padding_idx is not None:
398
+ module.weight.data[module.padding_idx].zero_()
399
+ elif isinstance(module, TrillionRMSNorm):
400
+ module.weight.data.fill_(1.0)
401
+
402
+
403
+ TRILLION_INPUTS_DOCSTRING = r"""
404
+ Args:
405
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
406
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
407
+ it.
408
+
409
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
410
+ [`PreTrainedTokenizer.__call__`] for details.
411
+
412
+ [What are input IDs?](../glossary#input-ids)
413
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length) or `BlockMask`, *optional*):
414
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
415
+
416
+ - 1 for tokens that are **not masked**,
417
+ - 0 for tokens that are **masked**.
418
+
419
+ If the model is configured to use flex_attention, it will attempt to convert the mask Tensor into a BlockMask,
420
+ but you can also pass a `BlockMask` object directly here.
421
+
422
+ [What are attention masks?](../glossary#attention-mask)
423
+
424
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
425
+ [`PreTrainedTokenizer.__call__`] for details.
426
+
427
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
428
+ `past_key_values`).
429
+
430
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
431
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
432
+ information on the default strategy.
433
+
434
+ - 1 indicates the head is **not masked**,
435
+ - 0 indicates the head is **masked**.
436
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
437
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
438
+ config.n_positions - 1]`.
439
+
440
+ [What are position IDs?](../glossary#position-ids)
441
+ past_key_values (`Cache`, *optional*):
442
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
443
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
444
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
445
+
446
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
447
+
448
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
449
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
450
+ of shape `(batch_size, sequence_length)`.
451
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
452
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
453
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
454
+ model's internal embedding lookup matrix.
455
+ use_cache (`bool`, *optional*):
456
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
457
+ `past_key_values`).
458
+ output_attentions (`bool`, *optional*):
459
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
460
+ tensors for more detail.
461
+ output_hidden_states (`bool`, *optional*):
462
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
463
+ more detail.
464
+ return_dict (`bool`, *optional*):
465
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
466
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
467
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
468
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
469
+ the complete sequence length.
470
+ """
471
+
472
+
473
+ @add_start_docstrings(
474
+ "The bare Trillion Model outputting raw hidden-states without any specific head on top.",
475
+ TRILLION_START_DOCSTRING,
476
+ )
477
+ class TrillionModel(TrillionPreTrainedModel):
478
+ """
479
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`TrillionDecoderLayer`]
480
+
481
+ Args:
482
+ config: TrillionConfig
483
+ """
484
+
485
+ def __init__(self, config: TrillionConfig):
486
+ super().__init__(config)
487
+ self.padding_idx = config.pad_token_id
488
+ self.vocab_size = config.vocab_size
489
+
490
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
491
+ self.layers = nn.ModuleList(
492
+ [TrillionDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
493
+ )
494
+ self.norm = TrillionRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
495
+ self.rotary_emb = TrillionRotaryEmbedding(config=config)
496
+ self.gradient_checkpointing = False
497
+
498
+ # Initialize weights and apply final processing
499
+ self.post_init()
500
+
501
+ def get_input_embeddings(self):
502
+ return self.embed_tokens
503
+
504
+ def set_input_embeddings(self, value):
505
+ self.embed_tokens = value
506
+
507
+ @can_return_tuple
508
+ @add_start_docstrings_to_model_forward(TRILLION_INPUTS_DOCSTRING)
509
+ def forward(
510
+ self,
511
+ input_ids: Optional[torch.LongTensor] = None,
512
+ attention_mask: Optional[torch.Tensor] = None,
513
+ position_ids: Optional[torch.LongTensor] = None,
514
+ past_key_values: Optional[Cache] = None,
515
+ inputs_embeds: Optional[torch.FloatTensor] = None,
516
+ use_cache: Optional[bool] = None,
517
+ output_attentions: Optional[bool] = None,
518
+ output_hidden_states: Optional[bool] = None,
519
+ cache_position: Optional[torch.LongTensor] = None,
520
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
521
+ ) -> BaseModelOutputWithPast:
522
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
523
+ output_hidden_states = (
524
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
525
+ )
526
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
527
+
528
+ if (input_ids is None) ^ (inputs_embeds is not None):
529
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
530
+
531
+ if self.gradient_checkpointing and self.training and use_cache:
532
+ logger.warning_once(
533
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
534
+ )
535
+ use_cache = False
536
+
537
+ # TODO (joao): remove this exception in v4.56 -- it exists for users that try to pass a legacy cache
538
+ if not isinstance(past_key_values, (type(None), Cache)):
539
+ raise ValueError("The `past_key_values` should be either a `Cache` object or `None`.")
540
+
541
+ if inputs_embeds is None:
542
+ inputs_embeds = self.embed_tokens(input_ids)
543
+
544
+ if use_cache and past_key_values is None:
545
+ past_key_values = DynamicCache()
546
+
547
+ if cache_position is None:
548
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
549
+ cache_position = torch.arange(
550
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
551
+ )
552
+
553
+ if position_ids is None:
554
+ position_ids = cache_position.unsqueeze(0)
555
+
556
+ causal_mask = self._update_causal_mask(
557
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
558
+ )
559
+
560
+ hidden_states = inputs_embeds
561
+
562
+ # create position embeddings to be shared across the decoder layers
563
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
564
+
565
+ # decoder layers
566
+ all_hidden_states = () if output_hidden_states else None
567
+ all_self_attns = () if output_attentions else None
568
+
569
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
570
+ if output_hidden_states:
571
+ all_hidden_states += (hidden_states,)
572
+
573
+ if self.gradient_checkpointing and self.training:
574
+ layer_outputs = self._gradient_checkpointing_func(
575
+ partial(decoder_layer.__call__, **flash_attn_kwargs),
576
+ hidden_states,
577
+ causal_mask,
578
+ position_ids,
579
+ past_key_values,
580
+ output_attentions,
581
+ use_cache,
582
+ cache_position,
583
+ position_embeddings,
584
+ )
585
+ else:
586
+ layer_outputs = decoder_layer(
587
+ hidden_states,
588
+ attention_mask=causal_mask,
589
+ position_ids=position_ids,
590
+ past_key_value=past_key_values,
591
+ output_attentions=output_attentions,
592
+ use_cache=use_cache,
593
+ cache_position=cache_position,
594
+ position_embeddings=position_embeddings,
595
+ **flash_attn_kwargs,
596
+ )
597
+
598
+ hidden_states = layer_outputs[0]
599
+
600
+ if output_attentions:
601
+ all_self_attns += (layer_outputs[1],)
602
+
603
+ hidden_states = self.norm(hidden_states)
604
+
605
+ # add hidden states from the last decoder layer
606
+ if output_hidden_states:
607
+ all_hidden_states += (hidden_states,)
608
+
609
+ return BaseModelOutputWithPast(
610
+ last_hidden_state=hidden_states,
611
+ past_key_values=past_key_values if use_cache else None,
612
+ hidden_states=all_hidden_states,
613
+ attentions=all_self_attns,
614
+ )
615
+
616
+ def _update_causal_mask(
617
+ self,
618
+ attention_mask: Union[torch.Tensor, "BlockMask"],
619
+ input_tensor: torch.Tensor,
620
+ cache_position: torch.Tensor,
621
+ past_key_values: Cache,
622
+ output_attentions: bool = False,
623
+ ):
624
+ if self.config._attn_implementation == "flash_attention_2":
625
+ if attention_mask is not None and (attention_mask == 0.0).any():
626
+ return attention_mask
627
+ return None
628
+ if self.config._attn_implementation == "flex_attention":
629
+ if isinstance(attention_mask, torch.Tensor):
630
+ attention_mask = make_flex_block_causal_mask(attention_mask)
631
+ return attention_mask
632
+
633
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
634
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
635
+ # to infer the attention mask.
636
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
637
+ using_static_cache = isinstance(past_key_values, StaticCache)
638
+
639
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
640
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
641
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
642
+ attention_mask,
643
+ inputs_embeds=input_tensor,
644
+ past_key_values_length=past_seen_tokens,
645
+ is_training=self.training,
646
+ ):
647
+ return None
648
+
649
+ dtype, device = input_tensor.dtype, input_tensor.device
650
+ sequence_length = input_tensor.shape[1]
651
+ if using_static_cache:
652
+ target_length = past_key_values.get_max_cache_shape()
653
+ else:
654
+ target_length = (
655
+ attention_mask.shape[-1]
656
+ if isinstance(attention_mask, torch.Tensor)
657
+ else past_seen_tokens + sequence_length + 1
658
+ )
659
+
660
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
661
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
662
+ attention_mask,
663
+ sequence_length=sequence_length,
664
+ target_length=target_length,
665
+ dtype=dtype,
666
+ device=device,
667
+ cache_position=cache_position,
668
+ batch_size=input_tensor.shape[0],
669
+ )
670
+
671
+ if (
672
+ self.config._attn_implementation == "sdpa"
673
+ and attention_mask is not None
674
+ and attention_mask.device.type in ["cuda", "xpu", "npu"]
675
+ and not output_attentions
676
+ ):
677
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
678
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
679
+ # Details: https://github.com/pytorch/pytorch/issues/110213
680
+ min_dtype = torch.finfo(dtype).min
681
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
682
+
683
+ return causal_mask
684
+
685
+ @staticmethod
686
+ def _prepare_4d_causal_attention_mask_with_cache_position(
687
+ attention_mask: torch.Tensor,
688
+ sequence_length: int,
689
+ target_length: int,
690
+ dtype: torch.dtype,
691
+ device: torch.device,
692
+ cache_position: torch.Tensor,
693
+ batch_size: int,
694
+ **kwargs,
695
+ ):
696
+ """
697
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
698
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
699
+
700
+ Args:
701
+ attention_mask (`torch.Tensor`):
702
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
703
+ `(batch_size, 1, query_length, key_value_length)`.
704
+ sequence_length (`int`):
705
+ The sequence length being processed.
706
+ target_length (`int`):
707
+ The target length: when generating with static cache, the mask should be as long as the static cache,
708
+ to account for the 0 padding, the part of the cache that is not filled yet.
709
+ dtype (`torch.dtype`):
710
+ The dtype to use for the 4D attention mask.
711
+ device (`torch.device`):
712
+ The device to place the 4D attention mask on.
713
+ cache_position (`torch.Tensor`):
714
+ Indices depicting the position of the input sequence tokens in the sequence.
715
+ batch_size (`torch.Tensor`):
716
+ Batch size.
717
+ """
718
+ if attention_mask is not None and attention_mask.dim() == 4:
719
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
720
+ causal_mask = attention_mask
721
+ else:
722
+ min_dtype = torch.finfo(dtype).min
723
+ causal_mask = torch.full(
724
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
725
+ )
726
+ if sequence_length != 1:
727
+ causal_mask = torch.triu(causal_mask, diagonal=1)
728
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
729
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
730
+ if attention_mask is not None:
731
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
732
+ mask_length = attention_mask.shape[-1]
733
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
734
+ causal_mask.device
735
+ )
736
+ padding_mask = padding_mask == 0
737
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
738
+ padding_mask, min_dtype
739
+ )
740
+
741
+ return causal_mask
742
+
743
+
744
+ class TrillionForCausalLM(TrillionPreTrainedModel, GenerationMixin):
745
+ _tied_weights_keys = ["lm_head.weight"]
746
+ _tp_plan = {"lm_head": "colwise_rep"}
747
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
748
+
749
+ def __init__(self, config):
750
+ super().__init__(config)
751
+ self.model = TrillionModel(config)
752
+ self.vocab_size = config.vocab_size
753
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
754
+
755
+ # Initialize weights and apply final processing
756
+ self.post_init()
757
+
758
+ def get_input_embeddings(self):
759
+ return self.model.embed_tokens
760
+
761
+ def set_input_embeddings(self, value):
762
+ self.model.embed_tokens = value
763
+
764
+ def get_output_embeddings(self):
765
+ return self.lm_head
766
+
767
+ def set_output_embeddings(self, new_embeddings):
768
+ self.lm_head = new_embeddings
769
+
770
+ def set_decoder(self, decoder):
771
+ self.model = decoder
772
+
773
+ def get_decoder(self):
774
+ return self.model
775
+
776
+ @can_return_tuple
777
+ @add_start_docstrings_to_model_forward(TRILLION_INPUTS_DOCSTRING)
778
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
779
+ def forward(
780
+ self,
781
+ input_ids: Optional[torch.LongTensor] = None,
782
+ attention_mask: Optional[torch.Tensor] = None,
783
+ position_ids: Optional[torch.LongTensor] = None,
784
+ past_key_values: Optional[Cache] = None,
785
+ inputs_embeds: Optional[torch.FloatTensor] = None,
786
+ labels: Optional[torch.LongTensor] = None,
787
+ use_cache: Optional[bool] = None,
788
+ output_attentions: Optional[bool] = None,
789
+ output_hidden_states: Optional[bool] = None,
790
+ cache_position: Optional[torch.LongTensor] = None,
791
+ logits_to_keep: Union[int, torch.Tensor] = 0,
792
+ **kwargs: Unpack[TransformersKwargs],
793
+ ) -> CausalLMOutputWithPast:
794
+ r"""
795
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
796
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
797
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
798
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
799
+
800
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
801
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
802
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
803
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
804
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
805
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
806
+
807
+ Returns:
808
+
809
+ Example:
810
+
811
+ ```python
812
+ >>> from transformers import AutoTokenizer, TrillionForCausalLM
813
+
814
+ >>> model = TrillionForCausalLM.from_pretrained("trillionlabs/Tri-70B-preview-SFT")
815
+ >>> tokenizer = AutoTokenizer.from_pretrained("trillionlabs/Tri-70B-preview-SFT")
816
+
817
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
818
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
819
+
820
+ >>> # Generate
821
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
822
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
823
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
824
+ ```"""
825
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
826
+ output_hidden_states = (
827
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
828
+ )
829
+
830
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
831
+ outputs: BaseModelOutputWithPast = self.model(
832
+ input_ids=input_ids,
833
+ attention_mask=attention_mask,
834
+ position_ids=position_ids,
835
+ past_key_values=past_key_values,
836
+ inputs_embeds=inputs_embeds,
837
+ use_cache=use_cache,
838
+ output_attentions=output_attentions,
839
+ output_hidden_states=output_hidden_states,
840
+ cache_position=cache_position,
841
+ **kwargs,
842
+ )
843
+
844
+ hidden_states = outputs.last_hidden_state
845
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
846
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
847
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
848
+
849
+ loss = None
850
+ if labels is not None:
851
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
852
+
853
+ return CausalLMOutputWithPast(
854
+ loss=loss,
855
+ logits=logits,
856
+ past_key_values=outputs.past_key_values,
857
+ hidden_states=outputs.hidden_states,
858
+ attentions=outputs.attentions,
859
+ )
860
+
861
+
862
+ __all__ = [
863
+ "TrillionForCausalLM",
864
+ "TrillionModel",
865
+ "TrillionPreTrainedModel",
866
+ ]