Safetensors
Japanese
llama_enc
custom_code
shirayukikun commited on
Commit
a1e7954
·
verified ·
1 Parent(s): 8be87bb

Upload folder using huggingface_hub

Browse files
config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "None",
3
+ "architectures": [
4
+ "LlamaEncForMaskedLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoConfig": "configuration_llama_enc.LlamaEncConfig",
10
+ "AutoModel": "modeling_llama_enc.LlamaEncModel",
11
+ "AutoModelForMaskedLM": "modeling_llama_enc.LlamaEncForMaskedLM",
12
+ "AutoModelForQuestionAnswering": "modeling_llama_enc.LlamaEncForQuestionAnswering",
13
+ "AutoModelForSequenceClassification": "modeling_llama_enc.LlamaEncForSequenceClassification",
14
+ "AutoModelForTokenClassification": "modeling_llama_enc.LlamaEncForTokenClassification"
15
+ },
16
+ "bos_token_id": 1,
17
+ "eos_token_id": 2,
18
+ "hidden_act": "silu",
19
+ "hidden_size": 1024,
20
+ "initializer_range": 0.02,
21
+ "intermediate_size": 4096,
22
+ "label_smoothing": 0.0,
23
+ "max_position_embeddings": 8192,
24
+ "mlp_bias": false,
25
+ "model_type": "llama_enc",
26
+ "num_attention_heads": 16,
27
+ "num_hidden_layers": 24,
28
+ "num_key_value_heads": 8,
29
+ "pretraining_tp": 1,
30
+ "rms_norm_eps": 1e-06,
31
+ "rope_scaling": null,
32
+ "rope_theta": 20000.0,
33
+ "tie_word_embeddings": false,
34
+ "torch_dtype": "float32",
35
+ "transformers_version": "4.41.2",
36
+ "trust_remote_code": true,
37
+ "use_cache": true,
38
+ "vocab_size": 99584,
39
+ "window_size_left": -1,
40
+ "window_size_right": -1
41
+ }
configuration_llama_enc.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """ LLaMA model configuration"""
21
+
22
+ from transformers.configuration_utils import PretrainedConfig
23
+ from transformers.utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+
29
+ class LlamaEncConfig(PretrainedConfig):
30
+ r"""
31
+ This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA
32
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
33
+ defaults will yield a similar configuration to that of the LLaMA-7B.
34
+
35
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
36
+ documentation from [`PretrainedConfig`] for more information.
37
+
38
+
39
+ Args:
40
+ vocab_size (`int`, *optional*, defaults to 32000):
41
+ Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
42
+ `inputs_ids` passed when calling [`LlamaModel`]
43
+ hidden_size (`int`, *optional*, defaults to 4096):
44
+ Dimension of the hidden representations.
45
+ intermediate_size (`int`, *optional*, defaults to 11008):
46
+ Dimension of the MLP representations.
47
+ num_hidden_layers (`int`, *optional*, defaults to 32):
48
+ Number of hidden layers in the Transformer decoder.
49
+ num_attention_heads (`int`, *optional*, defaults to 32):
50
+ Number of attention heads for each attention layer in the Transformer decoder.
51
+ num_key_value_heads (`int`, *optional*):
52
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
53
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
54
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
55
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
56
+ by meanpooling all the original heads within that group. For more details checkout [this
57
+ paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
58
+ `num_attention_heads`.
59
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
60
+ The non-linear activation function (function or string) in the decoder.
61
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
62
+ The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens,
63
+ Llama 2 up to 4096, CodeLlama up to 16384.
64
+ initializer_range (`float`, *optional*, defaults to 0.02):
65
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
66
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
67
+ The epsilon used by the rms normalization layers.
68
+ use_cache (`bool`, *optional*, defaults to `True`):
69
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
70
+ relevant if `config.is_decoder=True`.
71
+ pad_token_id (`int`, *optional*):
72
+ Padding token id.
73
+ bos_token_id (`int`, *optional*, defaults to 1):
74
+ Beginning of stream token id.
75
+ eos_token_id (`int`, *optional*, defaults to 2):
76
+ End of stream token id.
77
+ pretraining_tp (`int`, *optional*, defaults to 1):
78
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
79
+ document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to understand more about it. This value is
80
+ necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
81
+ issue](https://github.com/pytorch/pytorch/issues/76232).
82
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
83
+ Whether to tie weight embeddings
84
+ rope_theta (`float`, *optional*, defaults to 10000.0):
85
+ The base period of the RoPE embeddings.
86
+ rope_scaling (`Dict`, *optional*):
87
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
88
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
89
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
90
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
91
+ these scaling strategies behave:
92
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
93
+ experimental feature, subject to breaking API changes in future versions.
94
+ attention_bias (`bool`, *optional*, defaults to `False`):
95
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
96
+ attention_dropout (`float`, *optional*, defaults to 0.0):
97
+ The dropout ratio for the attention probabilities.
98
+ mlp_bias (`bool`, *optional*, defaults to `False`):
99
+ Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
100
+
101
+ ```python
102
+ >>> from transformers import LlamaModel, LlamaConfig
103
+
104
+ >>> # Initializing a LLaMA llama-7b style configuration
105
+ >>> configuration = LlamaConfig()
106
+
107
+ >>> # Initializing a model from the llama-7b style configuration
108
+ >>> model = LlamaModel(configuration)
109
+
110
+ >>> # Accessing the model configuration
111
+ >>> configuration = model.config
112
+ ```"""
113
+ model_type = "llama_enc"
114
+ keys_to_ignore_at_inference = ["past_key_values"]
115
+
116
+ def __init__(
117
+ self,
118
+ vocab_size=32000,
119
+ hidden_size=4096,
120
+ intermediate_size=11008,
121
+ num_hidden_layers=32,
122
+ num_attention_heads=32,
123
+ num_key_value_heads=None,
124
+ hidden_act="silu",
125
+ max_position_embeddings=2048,
126
+ initializer_range=0.02,
127
+ rms_norm_eps=1e-6,
128
+ use_cache=True,
129
+ pad_token_id=None,
130
+ bos_token_id=1,
131
+ eos_token_id=2,
132
+ pretraining_tp=1,
133
+ tie_word_embeddings=False,
134
+ rope_theta=10000.0,
135
+ rope_scaling=None,
136
+ attention_bias=False,
137
+ attention_dropout=0.0,
138
+ mlp_bias=False,
139
+ label_smoothing=0.0,
140
+ window_size_left=-1,
141
+ window_size_right=-1,
142
+ **kwargs,
143
+ ):
144
+ self.vocab_size = vocab_size
145
+ self.max_position_embeddings = max_position_embeddings
146
+ self.hidden_size = hidden_size
147
+ self.intermediate_size = intermediate_size
148
+ self.num_hidden_layers = num_hidden_layers
149
+ self.num_attention_heads = num_attention_heads
150
+
151
+ # for backward compatibility
152
+ if num_key_value_heads is None:
153
+ num_key_value_heads = num_attention_heads
154
+
155
+ self.num_key_value_heads = num_key_value_heads
156
+ self.hidden_act = hidden_act
157
+ self.initializer_range = initializer_range
158
+ self.rms_norm_eps = rms_norm_eps
159
+ self.pretraining_tp = pretraining_tp
160
+ self.use_cache = use_cache
161
+ self.rope_theta = rope_theta
162
+ self.rope_scaling = rope_scaling
163
+ self._rope_scaling_validation()
164
+ self.attention_bias = attention_bias
165
+ self.attention_dropout = attention_dropout
166
+ self.mlp_bias = mlp_bias
167
+ self.label_smoothing = label_smoothing
168
+ self.window_size_left = window_size_left
169
+ self.window_size_right = window_size_right
170
+ super().__init__(
171
+ pad_token_id=pad_token_id,
172
+ bos_token_id=bos_token_id,
173
+ eos_token_id=eos_token_id,
174
+ tie_word_embeddings=tie_word_embeddings,
175
+ **kwargs,
176
+ )
177
+
178
+ def _rope_scaling_validation(self):
179
+ """
180
+ Validate the `rope_scaling` configuration.
181
+ """
182
+ if self.rope_scaling is None:
183
+ return
184
+
185
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
186
+ raise ValueError(
187
+ "`rope_scaling` must be a dictionary with two fields, `type` and `factor`, " f"got {self.rope_scaling}"
188
+ )
189
+ rope_scaling_type = self.rope_scaling.get("type", None)
190
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
191
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
192
+ raise ValueError(
193
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
194
+ )
195
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
196
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:823c96db3bd58291b929cff83a66dd85b6ff41a49678e66ed3427a1890776256
3
+ size 2325967336
modeling_llama_enc.py ADDED
@@ -0,0 +1,1300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """PyTorch LLaMA Encodr model."""
21
+
22
+ import math
23
+ from typing import List, Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.nn.functional as F
27
+ import torch.utils.checkpoint
28
+ from torch import nn
29
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
30
+
31
+ from transformers.activations import ACT2FN
32
+ from transformers.modeling_outputs import (
33
+ BaseModelOutputWithPast,
34
+ CausalLMOutputWithPast,
35
+ QuestionAnsweringModelOutput,
36
+ SequenceClassifierOutputWithPast,
37
+ )
38
+ from transformers.modeling_attn_mask_utils import _prepare_4d_attention_mask_for_sdpa
39
+ from transformers.modeling_utils import PreTrainedModel
40
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
41
+ from transformers.utils import (
42
+ add_start_docstrings,
43
+ add_start_docstrings_to_model_forward,
44
+ is_flash_attn_2_available,
45
+ is_flash_attn_greater_or_equal_2_10,
46
+ logging,
47
+ replace_return_docstrings,
48
+ )
49
+ from .configuration_llama_enc import LlamaEncConfig
50
+
51
+ if is_flash_attn_2_available():
52
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
53
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
54
+
55
+
56
+ logger = logging.get_logger(__name__)
57
+
58
+ _CONFIG_FOR_DOC = "LlamaEncConfig"
59
+
60
+
61
+ def _get_unpad_data(attention_mask):
62
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
63
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
64
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
65
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
66
+ return (
67
+ indices,
68
+ cu_seqlens,
69
+ max_seqlen_in_batch,
70
+ )
71
+
72
+
73
+ class LlamaEncRMSNorm(nn.Module):
74
+ def __init__(self, hidden_size, eps=1e-6):
75
+ """
76
+ LlamaEncRMSNorm is equivalent to T5LayerNorm
77
+ """
78
+ super().__init__()
79
+ self.weight = nn.Parameter(torch.ones(hidden_size))
80
+ self.variance_epsilon = eps
81
+
82
+ def forward(self, hidden_states):
83
+ input_dtype = hidden_states.dtype
84
+ hidden_states = hidden_states.to(torch.float32)
85
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
86
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
87
+ return self.weight * hidden_states.to(input_dtype)
88
+
89
+
90
+ ALL_LAYERNORM_LAYERS.append(LlamaEncRMSNorm)
91
+
92
+
93
+ class LlamaEncRotaryEmbedding(nn.Module):
94
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
95
+ super().__init__()
96
+ self.scaling_factor = scaling_factor
97
+ self.dim = dim
98
+ self.max_position_embeddings = max_position_embeddings
99
+ self.base = base
100
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim))
101
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
102
+ # For BC we register cos and sin cached
103
+ self.max_seq_len_cached = max_position_embeddings
104
+
105
+ @torch.no_grad()
106
+ def forward(self, x, position_ids):
107
+ # x: [bs, num_attention_heads, seq_len, head_size]
108
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
109
+ position_ids_expanded = position_ids[:, None, :].float()
110
+ # Force float32 since bfloat16 loses precision on long contexts
111
+ # See https://github.com/huggingface/transformers/pull/29285
112
+ device_type = x.device.type
113
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
114
+ with torch.autocast(device_type=device_type, enabled=False):
115
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
116
+ emb = torch.cat((freqs, freqs), dim=-1)
117
+ cos = emb.cos()
118
+ sin = emb.sin()
119
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
120
+
121
+
122
+ class LlamaEncLinearScalingRotaryEmbedding(LlamaEncRotaryEmbedding):
123
+ """LlamaEncRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
124
+
125
+ def forward(self, x, position_ids):
126
+ # difference to the original RoPE: a scaling factor is aplied to the position ids
127
+ position_ids = position_ids.float() / self.scaling_factor
128
+ cos, sin = super().forward(x, position_ids)
129
+ return cos, sin
130
+
131
+
132
+ class LlamaEncDynamicNTKScalingRotaryEmbedding(LlamaEncRotaryEmbedding):
133
+ """LlamaEncRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
134
+
135
+ def forward(self, x, position_ids):
136
+ # difference to the original RoPE: inv_freq is recomputed when the sequence length > original length
137
+ seq_len = torch.max(position_ids) + 1
138
+ if seq_len > self.max_position_embeddings:
139
+ base = self.base * (
140
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
141
+ ) ** (self.dim / (self.dim - 2))
142
+ inv_freq = 1.0 / (
143
+ base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(x.device) / self.dim)
144
+ )
145
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: this may break with compilation
146
+
147
+ cos, sin = super().forward(x, position_ids)
148
+ return cos, sin
149
+
150
+
151
+ def rotate_half(x):
152
+ """Rotates half the hidden dims of the input."""
153
+ x1 = x[..., : x.shape[-1] // 2]
154
+ x2 = x[..., x.shape[-1] // 2 :]
155
+ return torch.cat((-x2, x1), dim=-1)
156
+
157
+
158
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
159
+ """Applies Rotary Position Embedding to the query and key tensors.
160
+
161
+ Args:
162
+ q (`torch.Tensor`): The query tensor.
163
+ k (`torch.Tensor`): The key tensor.
164
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
165
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
166
+ position_ids (`torch.Tensor`, *optional*):
167
+ Deprecated and unused.
168
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
169
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
170
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
171
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
172
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
173
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
174
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
175
+ Returns:
176
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
177
+ """
178
+ cos = cos.unsqueeze(unsqueeze_dim)
179
+ sin = sin.unsqueeze(unsqueeze_dim)
180
+ q_embed = (q * cos) + (rotate_half(q) * sin)
181
+ k_embed = (k * cos) + (rotate_half(k) * sin)
182
+ return q_embed, k_embed
183
+
184
+
185
+ class LlamaEncMLP(nn.Module):
186
+ def __init__(self, config):
187
+ super().__init__()
188
+ self.config = config
189
+ self.hidden_size = config.hidden_size
190
+ self.intermediate_size = config.intermediate_size
191
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
192
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
193
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
194
+ self.act_fn = ACT2FN[config.hidden_act]
195
+
196
+ def forward(self, x):
197
+ if self.config.pretraining_tp > 1:
198
+ slice = self.intermediate_size // self.config.pretraining_tp
199
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
200
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
201
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
202
+
203
+ gate_proj = torch.cat(
204
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
205
+ )
206
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
207
+
208
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
209
+ down_proj = [
210
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
211
+ ]
212
+ down_proj = sum(down_proj)
213
+ else:
214
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
215
+
216
+ return down_proj
217
+
218
+
219
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
220
+ """
221
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
222
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
223
+ """
224
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
225
+ if n_rep == 1:
226
+ return hidden_states
227
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
228
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
229
+
230
+
231
+ class LlamaEncAttention(nn.Module):
232
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
233
+
234
+ def __init__(self, config: LlamaEncConfig, layer_idx: Optional[int] = None):
235
+ super().__init__()
236
+ self.config = config
237
+ self.layer_idx = layer_idx
238
+ if layer_idx is None:
239
+ logger.warning_once(
240
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
241
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
242
+ "when creating this class."
243
+ )
244
+
245
+ self.attention_dropout = config.attention_dropout
246
+ self.hidden_size = config.hidden_size
247
+ self.num_heads = config.num_attention_heads
248
+ self.head_dim = self.hidden_size // self.num_heads
249
+ self.num_key_value_heads = config.num_key_value_heads
250
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
251
+ self.max_position_embeddings = config.max_position_embeddings
252
+ self.rope_theta = config.rope_theta
253
+ self.is_causal = False # Encoder model does not use causal attention
254
+ self.window_size = (config.window_size_left, config.window_size_right)
255
+
256
+ if (self.head_dim * self.num_heads) != self.hidden_size:
257
+ raise ValueError(
258
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
259
+ f" and `num_heads`: {self.num_heads})."
260
+ )
261
+
262
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
263
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
264
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
265
+ self.o_proj = nn.Linear(self.hidden_size, self.hidden_size, bias=config.attention_bias)
266
+ self._init_rope()
267
+
268
+ def _init_rope(self):
269
+ if self.config.rope_scaling is None:
270
+ self.rotary_emb = LlamaEncRotaryEmbedding(
271
+ self.head_dim,
272
+ max_position_embeddings=self.max_position_embeddings,
273
+ base=self.rope_theta,
274
+ )
275
+ else:
276
+ scaling_type = self.config.rope_scaling["type"]
277
+ scaling_factor = self.config.rope_scaling["factor"]
278
+ if scaling_type == "linear":
279
+ self.rotary_emb = LlamaEncLinearScalingRotaryEmbedding(
280
+ self.head_dim,
281
+ max_position_embeddings=self.max_position_embeddings,
282
+ scaling_factor=scaling_factor,
283
+ base=self.rope_theta,
284
+ )
285
+ elif scaling_type == "dynamic":
286
+ self.rotary_emb = LlamaEncDynamicNTKScalingRotaryEmbedding(
287
+ self.head_dim,
288
+ max_position_embeddings=self.max_position_embeddings,
289
+ scaling_factor=scaling_factor,
290
+ base=self.rope_theta,
291
+ )
292
+ else:
293
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
294
+
295
+ def forward(
296
+ self,
297
+ hidden_states: torch.Tensor,
298
+ attention_mask: Optional[torch.Tensor] = None,
299
+ position_ids: Optional[torch.LongTensor] = None,
300
+ output_attentions: bool = False,
301
+ **kwargs,
302
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
303
+ bsz, q_len, _ = hidden_states.size()
304
+
305
+ if self.config.pretraining_tp > 1:
306
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
307
+ query_slices = self.q_proj.weight.split(
308
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
309
+ )
310
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
311
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
312
+
313
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
314
+ query_states = torch.cat(query_states, dim=-1)
315
+
316
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
317
+ key_states = torch.cat(key_states, dim=-1)
318
+
319
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
320
+ value_states = torch.cat(value_states, dim=-1)
321
+
322
+ else:
323
+ query_states = self.q_proj(hidden_states)
324
+ key_states = self.k_proj(hidden_states)
325
+ value_states = self.v_proj(hidden_states)
326
+
327
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
328
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
329
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
330
+
331
+ cos, sin = self.rotary_emb(value_states, position_ids)
332
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
333
+
334
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
335
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
336
+
337
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
338
+
339
+ if attention_mask is not None: # no matter the length, we just slice it
340
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
341
+ attn_weights = attn_weights + causal_mask
342
+
343
+ # upcast attention to fp32
344
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
345
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
346
+ attn_output = torch.matmul(attn_weights, value_states)
347
+
348
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
349
+ raise ValueError(
350
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
351
+ f" {attn_output.size()}"
352
+ )
353
+
354
+ attn_output = attn_output.transpose(1, 2).contiguous()
355
+
356
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
357
+
358
+ if self.config.pretraining_tp > 1:
359
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
360
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
361
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
362
+ else:
363
+ attn_output = self.o_proj(attn_output)
364
+
365
+ if not output_attentions:
366
+ attn_weights = None
367
+
368
+ return attn_output, attn_weights
369
+
370
+
371
+ class LlamaEncFlashAttention2(LlamaEncAttention):
372
+ """
373
+ LlamaEnc flash attention module. This module inherits from `LlamaEncAttention` as the weights of the module stays
374
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
375
+ flash attention and deal with padding tokens in case the input contains any of them.
376
+ """
377
+
378
+ def __init__(self, *args, **kwargs):
379
+ super().__init__(*args, **kwargs)
380
+
381
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
382
+ # 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.
383
+ # 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).
384
+
385
+ def forward(
386
+ self,
387
+ hidden_states: torch.Tensor,
388
+ attention_mask: Optional[torch.LongTensor] = None,
389
+ position_ids: Optional[torch.LongTensor] = None,
390
+ output_attentions: bool = False,
391
+ **kwargs,
392
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
393
+ output_attentions = False
394
+
395
+ bsz, q_len, _ = hidden_states.size()
396
+
397
+ query_states = self.q_proj(hidden_states)
398
+ key_states = self.k_proj(hidden_states)
399
+ value_states = self.v_proj(hidden_states)
400
+
401
+ # Flash attention requires the input to have the shape
402
+ # batch_size x seq_length x head_dim x hidden_dim
403
+ # therefore we just need to keep the original shape
404
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
405
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
406
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
407
+
408
+ cos, sin = self.rotary_emb(value_states, position_ids)
409
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
410
+
411
+
412
+ # 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
413
+ # to be able to avoid many of these transpose/reshape/view.
414
+ query_states = query_states.transpose(1, 2)
415
+ key_states = key_states.transpose(1, 2)
416
+ value_states = value_states.transpose(1, 2)
417
+
418
+ dropout_rate = self.attention_dropout if self.training else 0.0
419
+
420
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
421
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
422
+ # cast them back in the correct dtype just to be sure everything works as expected.
423
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
424
+ # in fp32. (LlamaEncRMSNorm handles it correctly)
425
+
426
+ input_dtype = query_states.dtype
427
+ if input_dtype == torch.float32:
428
+ if torch.is_autocast_enabled():
429
+ target_dtype = torch.get_autocast_gpu_dtype()
430
+ # Handle the case where the model is quantized
431
+ elif hasattr(self.config, "_pre_quantization_dtype"):
432
+ target_dtype = self.config._pre_quantization_dtype
433
+ else:
434
+ target_dtype = self.q_proj.weight.dtype
435
+
436
+ logger.warning_once(
437
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
438
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
439
+ f" {target_dtype}."
440
+ )
441
+
442
+ query_states = query_states.to(target_dtype)
443
+ key_states = key_states.to(target_dtype)
444
+ value_states = value_states.to(target_dtype)
445
+
446
+ attn_output = self._flash_attention_forward(
447
+ query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
448
+ )
449
+
450
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
451
+ attn_output = self.o_proj(attn_output)
452
+
453
+ if not output_attentions:
454
+ attn_weights = None
455
+
456
+ return attn_output, attn_weights
457
+
458
+ def _flash_attention_forward(
459
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
460
+ ):
461
+ """
462
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
463
+ first unpad the input, then computes the attention scores and pad the final attention scores.
464
+
465
+ Args:
466
+ query_states (`torch.Tensor`):
467
+ Input query states to be passed to Flash Attention API
468
+ key_states (`torch.Tensor`):
469
+ Input key states to be passed to Flash Attention API
470
+ value_states (`torch.Tensor`):
471
+ Input value states to be passed to Flash Attention API
472
+ attention_mask (`torch.Tensor`):
473
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
474
+ position of padding tokens and 1 for the position of non-padding tokens.
475
+ dropout (`float`):
476
+ Attention dropout
477
+ softmax_scale (`float`, *optional*):
478
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
479
+ """
480
+ causal = self.is_causal
481
+
482
+ # Contains at least one padding token in the sequence
483
+ if attention_mask is not None:
484
+ batch_size = query_states.shape[0]
485
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
486
+ query_states, key_states, value_states, attention_mask, query_length
487
+ )
488
+
489
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
490
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
491
+
492
+ attn_output_unpad = flash_attn_varlen_func(
493
+ query_states,
494
+ key_states,
495
+ value_states,
496
+ cu_seqlens_q=cu_seqlens_q,
497
+ cu_seqlens_k=cu_seqlens_k,
498
+ max_seqlen_q=max_seqlen_in_batch_q,
499
+ max_seqlen_k=max_seqlen_in_batch_k,
500
+ dropout_p=dropout,
501
+ softmax_scale=softmax_scale,
502
+ window_size=self.window_size,
503
+ causal=causal,
504
+ )
505
+
506
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
507
+ else:
508
+ attn_output = flash_attn_func(
509
+ query_states,
510
+ key_states,
511
+ value_states,
512
+ dropout,
513
+ softmax_scale=softmax_scale,
514
+ window_size=self.window_size,
515
+ causal=causal
516
+ )
517
+
518
+ return attn_output
519
+
520
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
521
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
522
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
523
+
524
+ key_layer = index_first_axis(
525
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
526
+ )
527
+ value_layer = index_first_axis(
528
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
529
+ )
530
+ if query_length == kv_seq_len:
531
+ query_layer = index_first_axis(
532
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
533
+ )
534
+ cu_seqlens_q = cu_seqlens_k
535
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
536
+ indices_q = indices_k
537
+ elif query_length == 1:
538
+ max_seqlen_in_batch_q = 1
539
+ cu_seqlens_q = torch.arange(
540
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
541
+ ) # There is a memcpy here, that is very bad.
542
+ indices_q = cu_seqlens_q[:-1]
543
+ query_layer = query_layer.squeeze(1)
544
+ else:
545
+ # The -q_len: slice assumes left padding.
546
+ attention_mask = attention_mask[:, -query_length:]
547
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
548
+
549
+ return (
550
+ query_layer,
551
+ key_layer,
552
+ value_layer,
553
+ indices_q,
554
+ (cu_seqlens_q, cu_seqlens_k),
555
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
556
+ )
557
+
558
+ class LlamaEncSdpaAttention(LlamaEncAttention):
559
+ """
560
+ LlamaEnc attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
561
+ `LlamaEncAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
562
+ SDPA API.
563
+ """
564
+
565
+ # Adapted from LlamaEncAttention.forward
566
+ def forward(
567
+ self,
568
+ hidden_states: torch.Tensor,
569
+ attention_mask: Optional[torch.Tensor] = None,
570
+ position_ids: Optional[torch.LongTensor] = None,
571
+ output_attentions: bool = False,
572
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
573
+ if output_attentions:
574
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
575
+ logger.warning_once(
576
+ "LlamaEncModel is using LlamaEncSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
577
+ '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.'
578
+ )
579
+ return super().forward(
580
+ hidden_states=hidden_states,
581
+ attention_mask=attention_mask,
582
+ position_ids=position_ids,
583
+ output_attentions=output_attentions,
584
+ )
585
+
586
+ bsz, q_len, _ = hidden_states.size()
587
+
588
+ query_states = self.q_proj(hidden_states)
589
+ key_states = self.k_proj(hidden_states)
590
+ value_states = self.v_proj(hidden_states)
591
+
592
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
593
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
594
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
595
+
596
+ cos, sin = self.rotary_emb(value_states, position_ids)
597
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
598
+
599
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
600
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
601
+
602
+ causal_mask = attention_mask
603
+ if attention_mask is not None:
604
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
605
+
606
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
607
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
608
+ if query_states.device.type == "cuda" and causal_mask is not None:
609
+ query_states = query_states.contiguous()
610
+ key_states = key_states.contiguous()
611
+ value_states = value_states.contiguous()
612
+
613
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this if statement instead of an
614
+ # inline conditional assignment to support both torch.compile's `dynamic=True` and `fullgraph=True`
615
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
616
+ query_states,
617
+ key_states,
618
+ value_states,
619
+ attn_mask=causal_mask,
620
+ dropout_p=self.attention_dropout if self.training else 0.0,
621
+ is_causal=False,
622
+ )
623
+
624
+ attn_output = attn_output.transpose(1, 2).contiguous()
625
+ attn_output = attn_output.view(bsz, q_len, self.hidden_size)
626
+
627
+ attn_output = self.o_proj(attn_output)
628
+
629
+ return attn_output, None
630
+
631
+
632
+ LLAMAENC_ATTENTION_CLASSES = {
633
+ "eager": LlamaEncAttention,
634
+ "flash_attention_2": LlamaEncFlashAttention2,
635
+ "sdpa": LlamaEncSdpaAttention,
636
+ }
637
+
638
+
639
+ class LlamaEncDecoderLayer(nn.Module):
640
+ def __init__(self, config: LlamaEncConfig, layer_idx: int):
641
+ super().__init__()
642
+ self.hidden_size = config.hidden_size
643
+
644
+ self.self_attn = LLAMAENC_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
645
+
646
+ self.mlp = LlamaEncMLP(config)
647
+ self.input_layernorm = LlamaEncRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
648
+ self.post_attention_layernorm = LlamaEncRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
649
+
650
+ def forward(
651
+ self,
652
+ hidden_states: torch.Tensor,
653
+ attention_mask: Optional[torch.Tensor] = None,
654
+ position_ids: Optional[torch.LongTensor] = None,
655
+ output_attentions: Optional[bool] = False,
656
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
657
+ """
658
+ Args:
659
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
660
+ attention_mask (`torch.FloatTensor`, *optional*):
661
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
662
+ query_sequence_length, key_sequence_length)` if default attention is used.
663
+ output_attentions (`bool`, *optional*):
664
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
665
+ returned tensors for more detail.
666
+ use_cache (`bool`, *optional*):
667
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
668
+ (see `past_key_values`).
669
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
670
+ """
671
+ residual = hidden_states
672
+
673
+ hidden_states = self.input_layernorm(hidden_states)
674
+
675
+ # Self Attention
676
+ hidden_states, self_attn_weights = self.self_attn(
677
+ hidden_states=hidden_states,
678
+ attention_mask=attention_mask,
679
+ position_ids=position_ids,
680
+ output_attentions=output_attentions,
681
+ )
682
+ hidden_states = residual + hidden_states
683
+
684
+ # Fully Connected
685
+ residual = hidden_states
686
+ hidden_states = self.post_attention_layernorm(hidden_states)
687
+ hidden_states = self.mlp(hidden_states)
688
+ hidden_states = residual + hidden_states
689
+
690
+ outputs = (hidden_states,)
691
+
692
+ if output_attentions:
693
+ outputs += (self_attn_weights,)
694
+
695
+ return outputs
696
+
697
+
698
+ LLAMAENC_START_DOCSTRING = r"""
699
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
700
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
701
+ etc.)
702
+
703
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
704
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
705
+ and behavior.
706
+
707
+ Parameters:
708
+ config ([`LlamaEncConfig`]):
709
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
710
+ load the weights associated with the model, only the configuration. Check out the
711
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
712
+ """
713
+
714
+
715
+ @add_start_docstrings(
716
+ "The bare LlamaEnc Model outputting raw hidden-states without any specific head on top.",
717
+ LLAMAENC_START_DOCSTRING,
718
+ )
719
+ class LlamaEncPreTrainedModel(PreTrainedModel):
720
+ config_class = LlamaEncConfig
721
+ base_model_prefix = "model"
722
+ supports_gradient_checkpointing = True
723
+ _no_split_modules = ["LlamaEncDecoderLayer"]
724
+ _skip_keys_device_placement = ["past_key_values"]
725
+ _supports_flash_attn_2 = True
726
+ _supports_sdpa = True
727
+ _supports_cache_class = True
728
+ _supports_static_cache = True
729
+
730
+ def _init_weights(self, module):
731
+ std = self.config.initializer_range
732
+ if isinstance(module, nn.Linear):
733
+ module.weight.data.normal_(mean=0.0, std=std)
734
+ if module.bias is not None:
735
+ module.bias.data.zero_()
736
+ elif isinstance(module, nn.Embedding):
737
+ module.weight.data.normal_(mean=0.0, std=std)
738
+ if module.padding_idx is not None:
739
+ module.weight.data[module.padding_idx].zero_()
740
+
741
+
742
+ LLAMAENC_INPUTS_DOCSTRING = r"""
743
+ Args:
744
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
745
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
746
+ it.
747
+
748
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
749
+ [`PreTrainedTokenizer.__call__`] for details.
750
+
751
+ [What are input IDs?](../glossary#input-ids)
752
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
753
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
754
+
755
+ - 1 for tokens that are **not masked**,
756
+ - 0 for tokens that are **masked**.
757
+
758
+ [What are attention masks?](../glossary#attention-mask)
759
+
760
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
761
+ [`PreTrainedTokenizer.__call__`] for details.
762
+
763
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
764
+ `past_key_values`).
765
+
766
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
767
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
768
+ information on the default strategy.
769
+
770
+ - 1 indicates the head is **not masked**,
771
+ - 0 indicates the head is **masked**.
772
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
773
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
774
+ config.n_positions - 1]`.
775
+
776
+ [What are position IDs?](../glossary#position-ids)
777
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
778
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
779
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
780
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
781
+
782
+ Two formats are allowed:
783
+ - a [`~cache_utils.Cache`] instance;
784
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
785
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
786
+ cache format.
787
+
788
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
789
+ legacy cache format will be returned.
790
+
791
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
792
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
793
+ of shape `(batch_size, sequence_length)`.
794
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
795
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
796
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
797
+ model's internal embedding lookup matrix.
798
+ use_cache (`bool`, *optional*):
799
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
800
+ `past_key_values`).
801
+ output_attentions (`bool`, *optional*):
802
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
803
+ tensors for more detail.
804
+ output_hidden_states (`bool`, *optional*):
805
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
806
+ more detail.
807
+ return_dict (`bool`, *optional*):
808
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
809
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
810
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
811
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
812
+ the complete sequence length.
813
+ """
814
+
815
+
816
+ @add_start_docstrings(
817
+ "The bare LlamaEnc Model outputting raw hidden-states without any specific head on top.",
818
+ LLAMAENC_START_DOCSTRING,
819
+ )
820
+ class LlamaEncModel(LlamaEncPreTrainedModel):
821
+ """
822
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaEncDecoderLayer`]
823
+
824
+ Args:
825
+ config: LlamaEncConfig
826
+ """
827
+
828
+ def __init__(self, config: LlamaEncConfig):
829
+ super().__init__(config)
830
+ self.padding_idx = config.pad_token_id
831
+ self.vocab_size = config.vocab_size
832
+
833
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
834
+ self.layers = nn.ModuleList(
835
+ [LlamaEncDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
836
+ )
837
+ self.norm = LlamaEncRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
838
+ self.gradient_checkpointing = False
839
+
840
+ # Initialize weights and apply final processing
841
+ self.post_init()
842
+
843
+ def get_input_embeddings(self):
844
+ return self.embed_tokens
845
+
846
+ def set_input_embeddings(self, value):
847
+ self.embed_tokens = value
848
+
849
+ @add_start_docstrings_to_model_forward(LLAMAENC_INPUTS_DOCSTRING)
850
+ def forward(
851
+ self,
852
+ input_ids: torch.LongTensor = None,
853
+ attention_mask: Optional[torch.Tensor] = None,
854
+ position_ids: Optional[torch.LongTensor] = None,
855
+ inputs_embeds: Optional[torch.FloatTensor] = None,
856
+ output_attentions: Optional[bool] = None,
857
+ output_hidden_states: Optional[bool] = None,
858
+ return_dict: Optional[bool] = None,
859
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
860
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
861
+ output_hidden_states = (
862
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
863
+ )
864
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
865
+
866
+ if (input_ids is None) ^ (inputs_embeds is not None):
867
+ raise ValueError(
868
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
869
+ )
870
+
871
+ if inputs_embeds is None:
872
+ inputs_embeds = self.embed_tokens(input_ids)
873
+
874
+ if position_ids is None:
875
+ position_ids = torch.arange(
876
+ 0, inputs_embeds.shape[1], device=inputs_embeds.device
877
+ ).unsqueeze(0)
878
+
879
+ causal_mask = self._update_causal_mask(
880
+ attention_mask, inputs_embeds, output_attentions
881
+ )
882
+
883
+ # embed positions
884
+ hidden_states = inputs_embeds
885
+
886
+ # decoder layers
887
+ all_hidden_states = () if output_hidden_states else None
888
+ all_self_attns = () if output_attentions else None
889
+
890
+ for decoder_layer in self.layers:
891
+ if output_hidden_states:
892
+ all_hidden_states += (hidden_states,)
893
+
894
+ if self.gradient_checkpointing and self.training:
895
+ layer_outputs = self._gradient_checkpointing_func(
896
+ decoder_layer.__call__,
897
+ hidden_states,
898
+ causal_mask,
899
+ position_ids,
900
+ output_attentions,
901
+ )
902
+ else:
903
+ layer_outputs = decoder_layer(
904
+ hidden_states,
905
+ attention_mask=causal_mask,
906
+ position_ids=position_ids,
907
+ output_attentions=output_attentions,
908
+ )
909
+
910
+ hidden_states = layer_outputs[0]
911
+
912
+
913
+ if output_attentions:
914
+ all_self_attns += (layer_outputs[1],)
915
+
916
+ hidden_states = self.norm(hidden_states)
917
+
918
+ # add hidden states from the last decoder layer
919
+ if output_hidden_states:
920
+ all_hidden_states += (hidden_states,)
921
+
922
+
923
+ if not return_dict:
924
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attns] if v is not None)
925
+ return BaseModelOutputWithPast(
926
+ last_hidden_state=hidden_states,
927
+ hidden_states=all_hidden_states,
928
+ attentions=all_self_attns,
929
+ )
930
+
931
+ def _update_causal_mask(
932
+ self,
933
+ attention_mask: torch.Tensor,
934
+ input_tensor: torch.Tensor,
935
+ output_attentions: bool,
936
+ ):
937
+ # 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
938
+ # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
939
+ # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
940
+ # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
941
+ if attention_mask is None:
942
+ return None
943
+
944
+ if self.config._attn_implementation == "flash_attention_2":
945
+ if 0.0 in attention_mask:
946
+ return attention_mask
947
+ return None
948
+
949
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
950
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
951
+ # to infer the attention mask.
952
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
953
+
954
+ if self.config._attn_implementation == "sdpa" and not output_attentions:
955
+ # No padding
956
+ if attention_mask.all():
957
+ return None
958
+
959
+ if attention_mask.dim() == 2:
960
+ return _prepare_4d_attention_mask_for_sdpa(
961
+ attention_mask, input_tensor.dtype, attention_mask.shape[-1]
962
+ )
963
+ if attention_mask is not None and attention_mask.dim() == 4:
964
+ # in this case we assume that the mask comes already in inverted form and requires no inversion or slicing
965
+ if attention_mask.max() != 0:
966
+ raise ValueError("Custom 4D attention mask should be passed in inverted form with max==0`")
967
+ return attention_mask
968
+
969
+ return self.get_extended_attention_mask(
970
+ attention_mask, input_tensor.shape,
971
+ )
972
+
973
+
974
+ class LlamaEncForMaskedLM(LlamaEncPreTrainedModel):
975
+ _tied_weights_keys = ["lm_head.weight"]
976
+
977
+ def __init__(self, config):
978
+ super().__init__(config)
979
+ self.model = LlamaEncModel(config)
980
+ self.vocab_size = config.vocab_size
981
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
982
+
983
+ # Initialize weights and apply final processing
984
+ self.post_init()
985
+
986
+ def get_input_embeddings(self):
987
+ return self.model.embed_tokens
988
+
989
+ def set_input_embeddings(self, value):
990
+ self.model.embed_tokens = value
991
+
992
+ def get_output_embeddings(self):
993
+ return self.lm_head
994
+
995
+ def set_output_embeddings(self, new_embeddings):
996
+ self.lm_head = new_embeddings
997
+
998
+ def set_decoder(self, decoder):
999
+ self.model = decoder
1000
+
1001
+ def get_decoder(self):
1002
+ return self.model
1003
+
1004
+ @add_start_docstrings_to_model_forward(LLAMAENC_INPUTS_DOCSTRING)
1005
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1006
+ def forward(
1007
+ self,
1008
+ input_ids: torch.LongTensor = None,
1009
+ attention_mask: Optional[torch.Tensor] = None,
1010
+ position_ids: Optional[torch.LongTensor] = None,
1011
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1012
+ labels: Optional[torch.LongTensor] = None,
1013
+ output_attentions: Optional[bool] = None,
1014
+ output_hidden_states: Optional[bool] = None,
1015
+ return_dict: Optional[bool] = None,
1016
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1017
+ r"""
1018
+ Args:
1019
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1020
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1021
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1022
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1023
+
1024
+ Returns:
1025
+
1026
+ Example:
1027
+
1028
+ ```python
1029
+ >>> from transformers import AutoTokenizer, LlamaEncForCausalLM
1030
+
1031
+ >>> model = LlamaEncForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
1032
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
1033
+
1034
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1035
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1036
+
1037
+ >>> # Generate
1038
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1039
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1040
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1041
+ ```"""
1042
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1043
+ output_hidden_states = (
1044
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1045
+ )
1046
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1047
+
1048
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1049
+ outputs = self.model(
1050
+ input_ids=input_ids,
1051
+ attention_mask=attention_mask,
1052
+ position_ids=position_ids,
1053
+ inputs_embeds=inputs_embeds,
1054
+ output_attentions=output_attentions,
1055
+ output_hidden_states=output_hidden_states,
1056
+ return_dict=return_dict,
1057
+ )
1058
+
1059
+ hidden_states = outputs[0]
1060
+ if self.config.pretraining_tp > 1:
1061
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1062
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1063
+ logits = torch.cat(logits, dim=-1)
1064
+ else:
1065
+ logits = self.lm_head(hidden_states)
1066
+ logits = logits.float()
1067
+
1068
+ loss = None
1069
+ if labels is not None:
1070
+ loss_fct = CrossEntropyLoss(label_smoothing=self.config.label_smoothing)
1071
+ loss = loss_fct(
1072
+ logits.view(-1, self.config.vocab_size),
1073
+ labels.to(logits.device).view(-1)
1074
+ )
1075
+
1076
+ if not return_dict:
1077
+ output = (logits,) + outputs[1:]
1078
+ return (loss,) + output if loss is not None else output
1079
+
1080
+ return CausalLMOutputWithPast(
1081
+ loss=loss,
1082
+ logits=logits,
1083
+ hidden_states=outputs.hidden_states,
1084
+ attentions=outputs.attentions,
1085
+ )
1086
+
1087
+ @add_start_docstrings(
1088
+ """
1089
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
1090
+
1091
+ [`LlamaEncForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1092
+ (e.g. GPT-2) do.
1093
+
1094
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1095
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1096
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1097
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1098
+ each row of the batch).
1099
+ """,
1100
+ LLAMAENC_START_DOCSTRING,
1101
+ )
1102
+ class LlamaEncForSequenceClassification(LlamaEncPreTrainedModel):
1103
+ def __init__(self, config):
1104
+ super().__init__(config)
1105
+ self.num_labels = config.num_labels
1106
+ self.model = LlamaEncModel(config)
1107
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1108
+
1109
+ # Initialize weights and apply final processing
1110
+ self.post_init()
1111
+
1112
+ def get_input_embeddings(self):
1113
+ return self.model.embed_tokens
1114
+
1115
+ def set_input_embeddings(self, value):
1116
+ self.model.embed_tokens = value
1117
+
1118
+ @add_start_docstrings_to_model_forward(LLAMAENC_INPUTS_DOCSTRING)
1119
+ def forward(
1120
+ self,
1121
+ input_ids: torch.LongTensor = None,
1122
+ attention_mask: Optional[torch.Tensor] = None,
1123
+ position_ids: Optional[torch.LongTensor] = None,
1124
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1125
+ labels: Optional[torch.LongTensor] = None,
1126
+ output_attentions: Optional[bool] = None,
1127
+ output_hidden_states: Optional[bool] = None,
1128
+ return_dict: Optional[bool] = None,
1129
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1130
+ r"""
1131
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1132
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1133
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1134
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1135
+ """
1136
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1137
+
1138
+ transformer_outputs = self.model(
1139
+ input_ids,
1140
+ attention_mask=attention_mask,
1141
+ position_ids=position_ids,
1142
+ inputs_embeds=inputs_embeds,
1143
+ output_attentions=output_attentions,
1144
+ output_hidden_states=output_hidden_states,
1145
+ return_dict=return_dict,
1146
+ )
1147
+ hidden_states = transformer_outputs[0]
1148
+ logits = self.score(hidden_states)
1149
+
1150
+ if input_ids is not None:
1151
+ batch_size = input_ids.shape[0]
1152
+ else:
1153
+ batch_size = inputs_embeds.shape[0]
1154
+
1155
+ if self.config.pad_token_id is None and batch_size != 1:
1156
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1157
+ if self.config.pad_token_id is None:
1158
+ sequence_lengths = -1
1159
+ else:
1160
+ if input_ids is not None:
1161
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1162
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1163
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1164
+ sequence_lengths = sequence_lengths.to(logits.device)
1165
+ else:
1166
+ sequence_lengths = -1
1167
+
1168
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1169
+
1170
+ loss = None
1171
+ if labels is not None:
1172
+ labels = labels.to(logits.device)
1173
+ if self.config.problem_type is None:
1174
+ if self.num_labels == 1:
1175
+ self.config.problem_type = "regression"
1176
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1177
+ self.config.problem_type = "single_label_classification"
1178
+ else:
1179
+ self.config.problem_type = "multi_label_classification"
1180
+
1181
+ if self.config.problem_type == "regression":
1182
+ loss_fct = MSELoss()
1183
+ if self.num_labels == 1:
1184
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1185
+ else:
1186
+ loss = loss_fct(pooled_logits, labels)
1187
+ elif self.config.problem_type == "single_label_classification":
1188
+ loss_fct = CrossEntropyLoss()
1189
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1190
+ elif self.config.problem_type == "multi_label_classification":
1191
+ loss_fct = BCEWithLogitsLoss()
1192
+ loss = loss_fct(pooled_logits, labels)
1193
+ if not return_dict:
1194
+ output = (pooled_logits,) + transformer_outputs[1:]
1195
+ return ((loss,) + output) if loss is not None else output
1196
+
1197
+ return SequenceClassifierOutputWithPast(
1198
+ loss=loss,
1199
+ logits=pooled_logits,
1200
+ past_key_values=transformer_outputs.past_key_values,
1201
+ hidden_states=transformer_outputs.hidden_states,
1202
+ attentions=transformer_outputs.attentions,
1203
+ )
1204
+
1205
+
1206
+ @add_start_docstrings(
1207
+ """
1208
+ The LlamaEnc Model transformer with a span classification head on top for extractive question-answering tasks like
1209
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1210
+ """,
1211
+ LLAMAENC_START_DOCSTRING,
1212
+ )
1213
+ class LlamaEncForQuestionAnswering(LlamaEncPreTrainedModel):
1214
+ base_model_prefix = "transformer"
1215
+
1216
+ # Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->LlamaEnc
1217
+ def __init__(self, config):
1218
+ super().__init__(config)
1219
+ self.transformer = LlamaEncModel(config)
1220
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1221
+
1222
+ # Initialize weights and apply final processing
1223
+ self.post_init()
1224
+
1225
+ def get_input_embeddings(self):
1226
+ return self.transformer.embed_tokens
1227
+
1228
+ def set_input_embeddings(self, value):
1229
+ self.transformer.embed_tokens = value
1230
+
1231
+ @add_start_docstrings_to_model_forward(LLAMAENC_INPUTS_DOCSTRING)
1232
+ def forward(
1233
+ self,
1234
+ input_ids: Optional[torch.LongTensor] = None,
1235
+ attention_mask: Optional[torch.FloatTensor] = None,
1236
+ position_ids: Optional[torch.LongTensor] = None,
1237
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1238
+ start_positions: Optional[torch.LongTensor] = None,
1239
+ end_positions: Optional[torch.LongTensor] = None,
1240
+ output_attentions: Optional[bool] = None,
1241
+ output_hidden_states: Optional[bool] = None,
1242
+ return_dict: Optional[bool] = None,
1243
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1244
+ r"""
1245
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1246
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1247
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1248
+ are not taken into account for computing the loss.
1249
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1250
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1251
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1252
+ are not taken into account for computing the loss.
1253
+ """
1254
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1255
+
1256
+ outputs = self.transformer(
1257
+ input_ids,
1258
+ attention_mask=attention_mask,
1259
+ position_ids=position_ids,
1260
+ inputs_embeds=inputs_embeds,
1261
+ output_attentions=output_attentions,
1262
+ output_hidden_states=output_hidden_states,
1263
+ return_dict=return_dict,
1264
+ )
1265
+
1266
+ sequence_output = outputs[0]
1267
+
1268
+ logits = self.qa_outputs(sequence_output)
1269
+ start_logits, end_logits = logits.split(1, dim=-1)
1270
+ start_logits = start_logits.squeeze(-1).contiguous()
1271
+ end_logits = end_logits.squeeze(-1).contiguous()
1272
+
1273
+ total_loss = None
1274
+ if start_positions is not None and end_positions is not None:
1275
+ # If we are on multi-GPU, split add a dimension
1276
+ if len(start_positions.size()) > 1:
1277
+ start_positions = start_positions.squeeze(-1).to(start_logits.device)
1278
+ if len(end_positions.size()) > 1:
1279
+ end_positions = end_positions.squeeze(-1).to(end_logits.device)
1280
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
1281
+ ignored_index = start_logits.size(1)
1282
+ start_positions = start_positions.clamp(0, ignored_index)
1283
+ end_positions = end_positions.clamp(0, ignored_index)
1284
+
1285
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1286
+ start_loss = loss_fct(start_logits, start_positions)
1287
+ end_loss = loss_fct(end_logits, end_positions)
1288
+ total_loss = (start_loss + end_loss) / 2
1289
+
1290
+ if not return_dict:
1291
+ output = (start_logits, end_logits) + outputs[2:]
1292
+ return ((total_loss,) + output) if total_loss is not None else output
1293
+
1294
+ return QuestionAnsweringModelOutput(
1295
+ loss=total_loss,
1296
+ start_logits=start_logits,
1297
+ end_logits=end_logits,
1298
+ hidden_states=outputs.hidden_states,
1299
+ attentions=outputs.attentions,
1300
+ )
special_tokens_map.json ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "cls_token": {
10
+ "content": "<s>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "eos_token": {
17
+ "content": "</s>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "mask_token": {
24
+ "content": "<MASK>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "pad_token": "<unk>",
31
+ "unk_token": {
32
+ "content": "<unk>",
33
+ "lstrip": false,
34
+ "normalized": false,
35
+ "rstrip": false,
36
+ "single_word": false
37
+ }
38
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_bos_token": true,
3
+ "add_eos_token": true,
4
+ "added_tokens_decoder": {
5
+ "0": {
6
+ "content": "<unk>",
7
+ "lstrip": false,
8
+ "normalized": false,
9
+ "rstrip": false,
10
+ "single_word": false,
11
+ "special": true
12
+ },
13
+ "1": {
14
+ "content": "<s>",
15
+ "lstrip": false,
16
+ "normalized": false,
17
+ "rstrip": false,
18
+ "single_word": false,
19
+ "special": true
20
+ },
21
+ "2": {
22
+ "content": "</s>",
23
+ "lstrip": false,
24
+ "normalized": false,
25
+ "rstrip": false,
26
+ "single_word": false,
27
+ "special": true
28
+ },
29
+ "3": {
30
+ "content": "<MASK>",
31
+ "lstrip": false,
32
+ "normalized": false,
33
+ "rstrip": false,
34
+ "single_word": false,
35
+ "special": true
36
+ }
37
+ },
38
+ "bos_token": "<s>",
39
+ "clean_up_tokenization_spaces": false,
40
+ "cls_token": "<s>",
41
+ "eos_token": "</s>",
42
+ "legacy": true,
43
+ "mask_token": "<MASK>",
44
+ "model_max_length": 1000000000000000019884624838656,
45
+ "pad_token": "<unk>",
46
+ "pad_token_id": 0,
47
+ "padding_side": "right",
48
+ "tokenizer_class": "LlamaTokenizer",
49
+ "unk_token": "<unk>",
50
+ "use_default_system_prompt": false
51
+ }