cyrilvallez HF staff commited on
Commit
248989f
·
verified ·
1 Parent(s): cdbe0f2

Upload DummyLlamaForCausalLM

Browse files
README.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: transformers
3
+ tags: []
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+ This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
config.json ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "DummyLlamaForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_dummy_llama.DummyLlamaConfig",
9
+ "AutoModelForCausalLM": "modeling_dummy_llama.DummyLlamaForCausalLM"
10
+ },
11
+ "bos_token_id": 128000,
12
+ "eos_token_id": [
13
+ 128001,
14
+ 128008,
15
+ 128009
16
+ ],
17
+ "head_dim": 64,
18
+ "hidden_act": "silu",
19
+ "hidden_size": 2048,
20
+ "initializer_range": 0.02,
21
+ "intermediate_size": 8192,
22
+ "max_position_embeddings": 131072,
23
+ "mlp_bias": false,
24
+ "model_type": "dummy_llama",
25
+ "num_attention_heads": 32,
26
+ "num_hidden_layers": 16,
27
+ "num_key_value_heads": 8,
28
+ "pretraining_tp": 1,
29
+ "rms_norm_eps": 1e-05,
30
+ "rope_scaling": {
31
+ "factor": 32.0,
32
+ "high_freq_factor": 4.0,
33
+ "low_freq_factor": 1.0,
34
+ "original_max_position_embeddings": 8192,
35
+ "rope_type": "llama3"
36
+ },
37
+ "rope_theta": 500000.0,
38
+ "tie_word_embeddings": true,
39
+ "torch_dtype": "float32",
40
+ "transformers_version": "4.49.0.dev0",
41
+ "use_cache": true,
42
+ "vocab_size": 128256
43
+ }
configuration_dummy_llama.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.modeling_rope_utils import rope_config_validation
24
+
25
+
26
+ class DummyLlamaConfig(PretrainedConfig):
27
+ r"""
28
+ This is the configuration class to store the configuration of a [`DummyLlamaModel`]. It is used to instantiate an LLaMA
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 LLaMA-7B.
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 32000):
38
+ Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
39
+ `inputs_ids` passed when calling [`DummyLlamaModel`]
40
+ hidden_size (`int`, *optional*, defaults to 4096):
41
+ Dimension of the hidden representations.
42
+ intermediate_size (`int`, *optional*, defaults to 11008):
43
+ Dimension of the MLP representations.
44
+ num_hidden_layers (`int`, *optional*, defaults to 32):
45
+ Number of hidden layers in the Transformer decoder.
46
+ num_attention_heads (`int`, *optional*, defaults to 32):
47
+ Number of attention heads for each attention layer in the Transformer decoder.
48
+ num_key_value_heads (`int`, *optional*):
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 2048):
59
+ The maximum sequence length that this model might ever be used with. DummyLlama 1 supports up to 2048 tokens,
60
+ DummyLlama 2 up to 4096, CodeDummyLlama up to 16384.
61
+ initializer_range (`float`, *optional*, defaults to 0.02):
62
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
63
+ rms_norm_eps (`float`, *optional*, defaults to 1e-06):
64
+ The epsilon used by the rms normalization layers.
65
+ use_cache (`bool`, *optional*, defaults to `True`):
66
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
67
+ relevant if `config.is_decoder=True`.
68
+ pad_token_id (`int`, *optional*):
69
+ Padding token id.
70
+ bos_token_id (`int`, *optional*, defaults to 1):
71
+ Beginning of stream token id.
72
+ eos_token_id (`int`, *optional*, defaults to 2):
73
+ End of stream token id.
74
+ pretraining_tp (`int`, *optional*, defaults to 1):
75
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
76
+ document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to
77
+ understand more about it. This value is necessary to ensure exact reproducibility of the pretraining
78
+ results. Please refer to [this issue](https://github.com/pytorch/pytorch/issues/76232).
79
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
80
+ Whether to tie weight embeddings
81
+ rope_theta (`float`, *optional*, defaults to 10000.0):
82
+ The base period of the RoPE embeddings.
83
+ rope_scaling (`Dict`, *optional*):
84
+ Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
85
+ and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
86
+ accordingly.
87
+ Expected contents:
88
+ `rope_type` (`str`):
89
+ The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
90
+ 'llama3'], with 'default' being the original RoPE implementation.
91
+ `factor` (`float`, *optional*):
92
+ Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
93
+ most scaling types, a `factor` of x will enable the model to handle sequences of length x *
94
+ original maximum pre-trained length.
95
+ `original_max_position_embeddings` (`int`, *optional*):
96
+ Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
97
+ pretraining.
98
+ `attention_factor` (`float`, *optional*):
99
+ Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
100
+ computation. If unspecified, it defaults to value recommended by the implementation, using the
101
+ `factor` field to infer the suggested value.
102
+ `beta_fast` (`float`, *optional*):
103
+ Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
104
+ ramp function. If unspecified, it defaults to 32.
105
+ `beta_slow` (`float`, *optional*):
106
+ Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
107
+ ramp function. If unspecified, it defaults to 1.
108
+ `short_factor` (`List[float]`, *optional*):
109
+ Only used with 'longrope'. The scaling factor to be applied to short contexts (<
110
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
111
+ size divided by the number of attention heads divided by 2
112
+ `long_factor` (`List[float]`, *optional*):
113
+ Only used with 'longrope'. The scaling factor to be applied to long contexts (<
114
+ `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
115
+ size divided by the number of attention heads divided by 2
116
+ `low_freq_factor` (`float`, *optional*):
117
+ Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
118
+ `high_freq_factor` (`float`, *optional*):
119
+ Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
120
+ attention_bias (`bool`, *optional*, defaults to `False`):
121
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
122
+ attention_dropout (`float`, *optional*, defaults to 0.0):
123
+ The dropout ratio for the attention probabilities.
124
+ mlp_bias (`bool`, *optional*, defaults to `False`):
125
+ Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
126
+ head_dim (`int`, *optional*):
127
+ The attention head dimension. If None, it will default to hidden_size // num_attention_heads
128
+
129
+ ```python
130
+ >>> from transformers import DummyLlamaModel, DummyLlamaConfig
131
+
132
+ >>> # Initializing a LLaMA llama-7b style configuration
133
+ >>> configuration = DummyLlamaConfig()
134
+
135
+ >>> # Initializing a model from the llama-7b style configuration
136
+ >>> model = DummyLlamaModel(configuration)
137
+
138
+ >>> # Accessing the model configuration
139
+ >>> configuration = model.config
140
+ ```"""
141
+
142
+ model_type = "dummy_llama"
143
+ keys_to_ignore_at_inference = ["past_key_values"]
144
+ # Default tensor parallel plan for base model `DummyLlamaModel`
145
+ base_model_tp_plan = {
146
+ "layers.*.self_attn.q_proj": "colwise",
147
+ "layers.*.self_attn.k_proj": "colwise",
148
+ "layers.*.self_attn.v_proj": "colwise",
149
+ "layers.*.self_attn.o_proj": "rowwise",
150
+ "layers.*.mlp.gate_proj": "colwise",
151
+ "layers.*.mlp.up_proj": "colwise",
152
+ "layers.*.mlp.down_proj": "rowwise",
153
+ }
154
+
155
+ def __init__(
156
+ self,
157
+ vocab_size=32000,
158
+ hidden_size=4096,
159
+ intermediate_size=11008,
160
+ num_hidden_layers=32,
161
+ num_attention_heads=32,
162
+ num_key_value_heads=None,
163
+ hidden_act="silu",
164
+ max_position_embeddings=2048,
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
+ attention_bias=False,
176
+ attention_dropout=0.0,
177
+ mlp_bias=False,
178
+ head_dim=None,
179
+ **kwargs,
180
+ ):
181
+ self.vocab_size = vocab_size
182
+ self.max_position_embeddings = max_position_embeddings
183
+ self.hidden_size = hidden_size
184
+ self.intermediate_size = intermediate_size
185
+ self.num_hidden_layers = num_hidden_layers
186
+ self.num_attention_heads = num_attention_heads
187
+
188
+ # for backward compatibility
189
+ if num_key_value_heads is None:
190
+ num_key_value_heads = num_attention_heads
191
+
192
+ self.num_key_value_heads = num_key_value_heads
193
+ self.hidden_act = hidden_act
194
+ self.initializer_range = initializer_range
195
+ self.rms_norm_eps = rms_norm_eps
196
+ self.pretraining_tp = pretraining_tp
197
+ self.use_cache = use_cache
198
+ self.rope_theta = rope_theta
199
+ self.rope_scaling = rope_scaling
200
+ self.attention_bias = attention_bias
201
+ self.attention_dropout = attention_dropout
202
+ self.mlp_bias = mlp_bias
203
+ self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
204
+ # Validate the correctness of rotary position embeddings parameters
205
+ # BC: if there is a 'type' field, copy it it to 'rope_type'.
206
+ if self.rope_scaling is not None and "type" in self.rope_scaling:
207
+ self.rope_scaling["rope_type"] = self.rope_scaling["type"]
208
+ rope_config_validation(self)
209
+
210
+ super().__init__(
211
+ pad_token_id=pad_token_id,
212
+ bos_token_id=bos_token_id,
213
+ eos_token_id=eos_token_id,
214
+ tie_word_embeddings=tie_word_embeddings,
215
+ **kwargs,
216
+ )
217
+
218
+
219
+ __all__ = ["DummyLlamaConfig"]
generation_config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 128000,
4
+ "eos_token_id": [
5
+ 128001,
6
+ 128008,
7
+ 128009
8
+ ],
9
+ "transformers_version": "4.49.0.dev0"
10
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:87caa701f46316c08d9c16e1e22cfd9fc9b57b45ad8cbddb5549232c21fd34dd
3
+ size 4943274328
modeling_dummy_llama.py ADDED
@@ -0,0 +1,1161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 typing import Callable, List, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+
26
+ from transformers.activations import ACT2FN
27
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
28
+ from transformers.generation import GenerationMixin
29
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
30
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
31
+ from transformers.modeling_outputs import (
32
+ BaseModelOutputWithPast,
33
+ CausalLMOutputWithPast,
34
+ QuestionAnsweringModelOutput,
35
+ SequenceClassifierOutputWithPast,
36
+ TokenClassifierOutput,
37
+ )
38
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
39
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
40
+ from transformers.processing_utils import Unpack
41
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
42
+ from transformers.utils import (
43
+ LossKwargs,
44
+ add_code_sample_docstrings,
45
+ add_start_docstrings,
46
+ add_start_docstrings_to_model_forward,
47
+ logging,
48
+ replace_return_docstrings,
49
+ )
50
+ from transformers.utils.deprecation import deprecate_kwarg
51
+ from .configuration_dummy_llama import DummyLlamaConfig
52
+
53
+
54
+ logger = logging.get_logger(__name__)
55
+
56
+ _CHECKPOINT_FOR_DOC = "meta-llama/DummyLlama-2-7b-hf"
57
+ _CONFIG_FOR_DOC = "DummyLlamaConfig"
58
+
59
+
60
+ class DummyLlamaRMSNorm(nn.Module):
61
+ def __init__(self, hidden_size, eps=1e-6):
62
+ """
63
+ DummyLlamaRMSNorm is equivalent to T5LayerNorm
64
+ """
65
+ super().__init__()
66
+ self.weight = nn.Parameter(torch.ones(hidden_size))
67
+ self.variance_epsilon = eps
68
+
69
+ def forward(self, hidden_states):
70
+ input_dtype = hidden_states.dtype
71
+ hidden_states = hidden_states.to(torch.float32)
72
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
73
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
74
+ return self.weight * hidden_states.to(input_dtype)
75
+
76
+ def extra_repr(self):
77
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
78
+
79
+
80
+ ALL_LAYERNORM_LAYERS.append(DummyLlamaRMSNorm)
81
+
82
+
83
+ class DummyLlamaRotaryEmbedding(nn.Module):
84
+ def __init__(self, config: DummyLlamaConfig, device=None):
85
+ super().__init__()
86
+ # BC: "rope_type" was originally "type"
87
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
88
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
89
+ else:
90
+ self.rope_type = "default"
91
+ self.max_seq_len_cached = config.max_position_embeddings
92
+ self.original_max_seq_len = config.max_position_embeddings
93
+
94
+ self.config = config
95
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
96
+
97
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
98
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
99
+ self.original_inv_freq = self.inv_freq
100
+
101
+ def _dynamic_frequency_update(self, position_ids, device):
102
+ """
103
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
104
+ 1 - growing beyond the cached sequence length (allow scaling)
105
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
106
+ """
107
+ seq_len = torch.max(position_ids) + 1
108
+ if seq_len > self.max_seq_len_cached: # growth
109
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
110
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
111
+ self.max_seq_len_cached = seq_len
112
+
113
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
114
+ # This .to() is needed if the model has been moved to a device after being initialized (because
115
+ # the buffer is automatically moved, but not the original copy)
116
+ self.original_inv_freq = self.original_inv_freq.to(device)
117
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
118
+ self.max_seq_len_cached = self.original_max_seq_len
119
+
120
+ @torch.no_grad()
121
+ def forward(self, x, position_ids):
122
+ if "dynamic" in self.rope_type:
123
+ self._dynamic_frequency_update(position_ids, device=x.device)
124
+
125
+ # Core RoPE block
126
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
127
+ position_ids_expanded = position_ids[:, None, :].float()
128
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
129
+ device_type = x.device.type
130
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
131
+ with torch.autocast(device_type=device_type, enabled=False):
132
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
133
+ emb = torch.cat((freqs, freqs), dim=-1)
134
+ cos = emb.cos()
135
+ sin = emb.sin()
136
+
137
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
138
+ cos = cos * self.attention_scaling
139
+ sin = sin * self.attention_scaling
140
+
141
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
142
+
143
+
144
+ def rotate_half(x):
145
+ """Rotates half the hidden dims of the input."""
146
+ x1 = x[..., : x.shape[-1] // 2]
147
+ x2 = x[..., x.shape[-1] // 2 :]
148
+ return torch.cat((-x2, x1), dim=-1)
149
+
150
+
151
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
152
+ """Applies Rotary Position Embedding to the query and key tensors.
153
+
154
+ Args:
155
+ q (`torch.Tensor`): The query tensor.
156
+ k (`torch.Tensor`): The key tensor.
157
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
158
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
159
+ position_ids (`torch.Tensor`, *optional*):
160
+ Deprecated and unused.
161
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
162
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
163
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
164
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
165
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
166
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
167
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
168
+ Returns:
169
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
170
+ """
171
+ cos = cos.unsqueeze(unsqueeze_dim)
172
+ sin = sin.unsqueeze(unsqueeze_dim)
173
+ q_embed = (q * cos) + (rotate_half(q) * sin)
174
+ k_embed = (k * cos) + (rotate_half(k) * sin)
175
+ return q_embed, k_embed
176
+
177
+
178
+ class DummyLlamaMLP(nn.Module):
179
+ def __init__(self, config):
180
+ super().__init__()
181
+ self.config = config
182
+ self.hidden_size = config.hidden_size
183
+ self.intermediate_size = config.intermediate_size
184
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
185
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
186
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
187
+ self.act_fn = ACT2FN[config.hidden_act]
188
+
189
+ def forward(self, x):
190
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
191
+ return down_proj
192
+
193
+
194
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
195
+ """
196
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
197
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
198
+ """
199
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
200
+ if n_rep == 1:
201
+ return hidden_states
202
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
203
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
204
+
205
+
206
+ def eager_attention_forward(
207
+ module: nn.Module,
208
+ query: torch.Tensor,
209
+ key: torch.Tensor,
210
+ value: torch.Tensor,
211
+ attention_mask: Optional[torch.Tensor],
212
+ scaling: float,
213
+ dropout: float = 0.0,
214
+ **kwargs,
215
+ ):
216
+ key_states = repeat_kv(key, module.num_key_value_groups)
217
+ value_states = repeat_kv(value, module.num_key_value_groups)
218
+
219
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
220
+ if attention_mask is not None:
221
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
222
+ attn_weights = attn_weights + causal_mask
223
+
224
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
225
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
226
+ attn_output = torch.matmul(attn_weights, value_states)
227
+ attn_output = attn_output.transpose(1, 2).contiguous()
228
+
229
+ return attn_output, attn_weights
230
+
231
+
232
+ class DummyLlamaAttention(nn.Module):
233
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
234
+
235
+ def __init__(self, config: DummyLlamaConfig, layer_idx: int):
236
+ super().__init__()
237
+ self.config = config
238
+ self.layer_idx = layer_idx
239
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
240
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
241
+ self.scaling = self.head_dim**-0.5
242
+ self.attention_dropout = config.attention_dropout
243
+ self.is_causal = True
244
+
245
+ self.q_proj = nn.Linear(
246
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
247
+ )
248
+ self.k_proj = nn.Linear(
249
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
250
+ )
251
+ self.v_proj = nn.Linear(
252
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
253
+ )
254
+ self.o_proj = nn.Linear(
255
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
256
+ )
257
+
258
+ def forward(
259
+ self,
260
+ hidden_states: torch.Tensor,
261
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
262
+ attention_mask: Optional[torch.Tensor],
263
+ past_key_value: Optional[Cache] = None,
264
+ cache_position: Optional[torch.LongTensor] = None,
265
+ **kwargs: Unpack[FlashAttentionKwargs],
266
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
267
+ input_shape = hidden_states.shape[:-1]
268
+ hidden_shape = (*input_shape, -1, self.head_dim)
269
+
270
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
271
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
272
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
273
+
274
+ cos, sin = position_embeddings
275
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
276
+
277
+ if past_key_value is not None:
278
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
279
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
280
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
281
+
282
+ attention_interface: Callable = eager_attention_forward
283
+ if self.config._attn_implementation != "eager":
284
+ if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
285
+ logger.warning_once(
286
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
287
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
288
+ )
289
+ else:
290
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
291
+
292
+ attn_output, attn_weights = attention_interface(
293
+ self,
294
+ query_states,
295
+ key_states,
296
+ value_states,
297
+ attention_mask,
298
+ dropout=0.0 if not self.training else self.attention_dropout,
299
+ scaling=self.scaling,
300
+ **kwargs,
301
+ )
302
+
303
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
304
+ attn_output = self.o_proj(attn_output)
305
+ return attn_output, attn_weights
306
+
307
+
308
+ class DummyLlamaDecoderLayer(nn.Module):
309
+ def __init__(self, config: DummyLlamaConfig, layer_idx: int):
310
+ super().__init__()
311
+ self.hidden_size = config.hidden_size
312
+
313
+ self.self_attn = DummyLlamaAttention(config=config, layer_idx=layer_idx)
314
+
315
+ self.mlp = DummyLlamaMLP(config)
316
+ self.input_layernorm = DummyLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
317
+ self.post_attention_layernorm = DummyLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
318
+
319
+ def forward(
320
+ self,
321
+ hidden_states: torch.Tensor,
322
+ attention_mask: Optional[torch.Tensor] = None,
323
+ position_ids: Optional[torch.LongTensor] = None,
324
+ past_key_value: Optional[Cache] = None,
325
+ output_attentions: Optional[bool] = False,
326
+ use_cache: Optional[bool] = False,
327
+ cache_position: Optional[torch.LongTensor] = None,
328
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
329
+ **kwargs: Unpack[FlashAttentionKwargs],
330
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
331
+ residual = hidden_states
332
+
333
+ hidden_states = self.input_layernorm(hidden_states)
334
+
335
+ # Self Attention
336
+ hidden_states, self_attn_weights = self.self_attn(
337
+ hidden_states=hidden_states,
338
+ attention_mask=attention_mask,
339
+ position_ids=position_ids,
340
+ past_key_value=past_key_value,
341
+ output_attentions=output_attentions,
342
+ use_cache=use_cache,
343
+ cache_position=cache_position,
344
+ position_embeddings=position_embeddings,
345
+ **kwargs,
346
+ )
347
+ hidden_states = residual + hidden_states
348
+
349
+ # Fully Connected
350
+ residual = hidden_states
351
+ hidden_states = self.post_attention_layernorm(hidden_states)
352
+ hidden_states = self.mlp(hidden_states)
353
+ hidden_states = residual + hidden_states
354
+
355
+ outputs = (hidden_states,)
356
+ if output_attentions:
357
+ outputs += (self_attn_weights,)
358
+
359
+ return outputs
360
+
361
+
362
+ LLAMA_START_DOCSTRING = r"""
363
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
364
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
365
+ etc.)
366
+
367
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
368
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
369
+ and behavior.
370
+
371
+ Parameters:
372
+ config ([`DummyLlamaConfig`]):
373
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
374
+ load the weights associated with the model, only the configuration. Check out the
375
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
376
+ """
377
+
378
+
379
+ @add_start_docstrings(
380
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
381
+ LLAMA_START_DOCSTRING,
382
+ )
383
+ class DummyLlamaPreTrainedModel(PreTrainedModel):
384
+ config_class = DummyLlamaConfig
385
+ base_model_prefix = "model"
386
+ supports_gradient_checkpointing = True
387
+ _no_split_modules = ["DummyLlamaDecoderLayer"]
388
+ _skip_keys_device_placement = ["past_key_values"]
389
+ _supports_flash_attn_2 = True
390
+ _supports_sdpa = True
391
+ _supports_flex_attn = True
392
+ _supports_cache_class = True
393
+ _supports_quantized_cache = True
394
+ _supports_static_cache = True
395
+ _supports_attention_backend = True
396
+
397
+ def _init_weights(self, module):
398
+ std = self.config.initializer_range
399
+ if isinstance(module, nn.Linear):
400
+ module.weight.data.normal_(mean=0.0, std=std)
401
+ if module.bias is not None:
402
+ module.bias.data.zero_()
403
+ elif isinstance(module, nn.Embedding):
404
+ module.weight.data.normal_(mean=0.0, std=std)
405
+ if module.padding_idx is not None:
406
+ module.weight.data[module.padding_idx].zero_()
407
+
408
+
409
+ LLAMA_INPUTS_DOCSTRING = r"""
410
+ Args:
411
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
412
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
413
+ it.
414
+
415
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
416
+ [`PreTrainedTokenizer.__call__`] for details.
417
+
418
+ [What are input IDs?](../glossary#input-ids)
419
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
420
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
421
+
422
+ - 1 for tokens that are **not masked**,
423
+ - 0 for tokens that are **masked**.
424
+
425
+ [What are attention masks?](../glossary#attention-mask)
426
+
427
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
428
+ [`PreTrainedTokenizer.__call__`] for details.
429
+
430
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
431
+ `past_key_values`).
432
+
433
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
434
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
435
+ information on the default strategy.
436
+
437
+ - 1 indicates the head is **not masked**,
438
+ - 0 indicates the head is **masked**.
439
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
440
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
441
+ config.n_positions - 1]`.
442
+
443
+ [What are position IDs?](../glossary#position-ids)
444
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
445
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
446
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
447
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
448
+
449
+ Two formats are allowed:
450
+ - a [`~cache_utils.Cache`] instance, see our
451
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
452
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
453
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
454
+ cache format.
455
+
456
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
457
+ legacy cache format will be returned.
458
+
459
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
460
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
461
+ of shape `(batch_size, sequence_length)`.
462
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
463
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
464
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
465
+ model's internal embedding lookup matrix.
466
+ use_cache (`bool`, *optional*):
467
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
468
+ `past_key_values`).
469
+ output_attentions (`bool`, *optional*):
470
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
471
+ tensors for more detail.
472
+ output_hidden_states (`bool`, *optional*):
473
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
474
+ more detail.
475
+ return_dict (`bool`, *optional*):
476
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
477
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
478
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
479
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
480
+ the complete sequence length.
481
+ """
482
+
483
+
484
+ @add_start_docstrings(
485
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
486
+ LLAMA_START_DOCSTRING,
487
+ )
488
+ class DummyLlamaModel(DummyLlamaPreTrainedModel):
489
+ """
490
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DummyLlamaDecoderLayer`]
491
+
492
+ Args:
493
+ config: DummyLlamaConfig
494
+ """
495
+
496
+ def __init__(self, config: DummyLlamaConfig):
497
+ super().__init__(config)
498
+ self.padding_idx = config.pad_token_id
499
+ self.vocab_size = config.vocab_size
500
+
501
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
502
+ self.layers = nn.ModuleList(
503
+ [DummyLlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
504
+ )
505
+ self.norm = DummyLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
506
+ self.rotary_emb = DummyLlamaRotaryEmbedding(config=config)
507
+ self.gradient_checkpointing = False
508
+
509
+ # Initialize weights and apply final processing
510
+ self.post_init()
511
+
512
+ def get_input_embeddings(self):
513
+ return self.embed_tokens
514
+
515
+ def set_input_embeddings(self, value):
516
+ self.embed_tokens = value
517
+
518
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
519
+ def forward(
520
+ self,
521
+ input_ids: torch.LongTensor = None,
522
+ attention_mask: Optional[torch.Tensor] = None,
523
+ position_ids: Optional[torch.LongTensor] = None,
524
+ past_key_values: Optional[Cache] = None,
525
+ inputs_embeds: Optional[torch.FloatTensor] = None,
526
+ use_cache: Optional[bool] = None,
527
+ output_attentions: Optional[bool] = None,
528
+ output_hidden_states: Optional[bool] = None,
529
+ return_dict: Optional[bool] = None,
530
+ cache_position: Optional[torch.LongTensor] = None,
531
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
532
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
533
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
534
+ output_hidden_states = (
535
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
536
+ )
537
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
538
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
539
+
540
+ if (input_ids is None) ^ (inputs_embeds is not None):
541
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
542
+
543
+ if self.gradient_checkpointing and self.training and use_cache:
544
+ logger.warning_once(
545
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
546
+ )
547
+ use_cache = False
548
+
549
+ if inputs_embeds is None:
550
+ inputs_embeds = self.embed_tokens(input_ids)
551
+
552
+ if use_cache and past_key_values is None:
553
+ past_key_values = DynamicCache()
554
+
555
+ if cache_position is None:
556
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
557
+ cache_position = torch.arange(
558
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
559
+ )
560
+
561
+ if position_ids is None:
562
+ position_ids = cache_position.unsqueeze(0)
563
+
564
+ causal_mask = self._update_causal_mask(
565
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
566
+ )
567
+
568
+ hidden_states = inputs_embeds
569
+
570
+ # create position embeddings to be shared across the decoder layers
571
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
572
+
573
+ # decoder layers
574
+ all_hidden_states = () if output_hidden_states else None
575
+ all_self_attns = () if output_attentions else None
576
+
577
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
578
+ if output_hidden_states:
579
+ all_hidden_states += (hidden_states,)
580
+
581
+ if self.gradient_checkpointing and self.training:
582
+ layer_outputs = self._gradient_checkpointing_func(
583
+ decoder_layer.__call__,
584
+ hidden_states,
585
+ causal_mask,
586
+ position_ids,
587
+ past_key_values,
588
+ output_attentions,
589
+ use_cache,
590
+ cache_position,
591
+ position_embeddings,
592
+ )
593
+ else:
594
+ layer_outputs = decoder_layer(
595
+ hidden_states,
596
+ attention_mask=causal_mask,
597
+ position_ids=position_ids,
598
+ past_key_value=past_key_values,
599
+ output_attentions=output_attentions,
600
+ use_cache=use_cache,
601
+ cache_position=cache_position,
602
+ position_embeddings=position_embeddings,
603
+ **flash_attn_kwargs,
604
+ )
605
+
606
+ hidden_states = layer_outputs[0]
607
+
608
+ if output_attentions:
609
+ all_self_attns += (layer_outputs[1],)
610
+
611
+ hidden_states = self.norm(hidden_states)
612
+
613
+ # add hidden states from the last decoder layer
614
+ if output_hidden_states:
615
+ all_hidden_states += (hidden_states,)
616
+
617
+ output = BaseModelOutputWithPast(
618
+ last_hidden_state=hidden_states,
619
+ past_key_values=past_key_values if use_cache else None,
620
+ hidden_states=all_hidden_states,
621
+ attentions=all_self_attns,
622
+ )
623
+ return output if return_dict else output.to_tuple()
624
+
625
+ def _update_causal_mask(
626
+ self,
627
+ attention_mask: torch.Tensor,
628
+ input_tensor: torch.Tensor,
629
+ cache_position: torch.Tensor,
630
+ past_key_values: Cache,
631
+ output_attentions: bool,
632
+ ):
633
+ if self.config._attn_implementation == "flash_attention_2":
634
+ if attention_mask is not None and (attention_mask == 0.0).any():
635
+ return attention_mask
636
+ return None
637
+
638
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
639
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
640
+ # to infer the attention mask.
641
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
642
+ using_static_cache = isinstance(past_key_values, StaticCache)
643
+
644
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
645
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
646
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
647
+ attention_mask,
648
+ inputs_embeds=input_tensor,
649
+ past_key_values_length=past_seen_tokens,
650
+ is_training=self.training,
651
+ ):
652
+ return None
653
+
654
+ dtype, device = input_tensor.dtype, input_tensor.device
655
+ sequence_length = input_tensor.shape[1]
656
+ if using_static_cache:
657
+ target_length = past_key_values.get_max_cache_shape()
658
+ else:
659
+ target_length = (
660
+ attention_mask.shape[-1]
661
+ if isinstance(attention_mask, torch.Tensor)
662
+ else past_seen_tokens + sequence_length + 1
663
+ )
664
+
665
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
666
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
667
+ attention_mask,
668
+ sequence_length=sequence_length,
669
+ target_length=target_length,
670
+ dtype=dtype,
671
+ device=device,
672
+ cache_position=cache_position,
673
+ batch_size=input_tensor.shape[0],
674
+ )
675
+
676
+ if (
677
+ self.config._attn_implementation == "sdpa"
678
+ and attention_mask is not None
679
+ and attention_mask.device.type == "cuda"
680
+ and not output_attentions
681
+ ):
682
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
683
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
684
+ # Details: https://github.com/pytorch/pytorch/issues/110213
685
+ min_dtype = torch.finfo(dtype).min
686
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
687
+
688
+ return causal_mask
689
+
690
+ @staticmethod
691
+ def _prepare_4d_causal_attention_mask_with_cache_position(
692
+ attention_mask: torch.Tensor,
693
+ sequence_length: int,
694
+ target_length: int,
695
+ dtype: torch.dtype,
696
+ device: torch.device,
697
+ cache_position: torch.Tensor,
698
+ batch_size: int,
699
+ **kwargs,
700
+ ):
701
+ """
702
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
703
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
704
+
705
+ Args:
706
+ attention_mask (`torch.Tensor`):
707
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
708
+ `(batch_size, 1, query_length, key_value_length)`.
709
+ sequence_length (`int`):
710
+ The sequence length being processed.
711
+ target_length (`int`):
712
+ The target length: when generating with static cache, the mask should be as long as the static cache,
713
+ to account for the 0 padding, the part of the cache that is not filled yet.
714
+ dtype (`torch.dtype`):
715
+ The dtype to use for the 4D attention mask.
716
+ device (`torch.device`):
717
+ The device to plcae the 4D attention mask on.
718
+ cache_position (`torch.Tensor`):
719
+ Indices depicting the position of the input sequence tokens in the sequence.
720
+ batch_size (`torch.Tensor`):
721
+ Batch size.
722
+ """
723
+ if attention_mask is not None and attention_mask.dim() == 4:
724
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
725
+ causal_mask = attention_mask
726
+ else:
727
+ min_dtype = torch.finfo(dtype).min
728
+ causal_mask = torch.full(
729
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
730
+ )
731
+ if sequence_length != 1:
732
+ causal_mask = torch.triu(causal_mask, diagonal=1)
733
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
734
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
735
+ if attention_mask is not None:
736
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
737
+ mask_length = attention_mask.shape[-1]
738
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
739
+ padding_mask = padding_mask == 0
740
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
741
+ padding_mask, min_dtype
742
+ )
743
+
744
+ return causal_mask
745
+
746
+
747
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
748
+
749
+
750
+ class DummyLlamaForCausalLM(DummyLlamaPreTrainedModel, GenerationMixin):
751
+ _tied_weights_keys = ["lm_head.weight"]
752
+ _tp_plan = {"lm_head": "colwise_rep"}
753
+
754
+ def __init__(self, config):
755
+ super().__init__(config)
756
+ self.model = DummyLlamaModel(config)
757
+ self.vocab_size = config.vocab_size
758
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
759
+
760
+ # Initialize weights and apply final processing
761
+ self.post_init()
762
+
763
+ def get_input_embeddings(self):
764
+ return self.model.embed_tokens
765
+
766
+ def set_input_embeddings(self, value):
767
+ self.model.embed_tokens = value
768
+
769
+ def get_output_embeddings(self):
770
+ return self.lm_head
771
+
772
+ def set_output_embeddings(self, new_embeddings):
773
+ self.lm_head = new_embeddings
774
+
775
+ def set_decoder(self, decoder):
776
+ self.model = decoder
777
+
778
+ def get_decoder(self):
779
+ return self.model
780
+
781
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
782
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
783
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
784
+ def forward(
785
+ self,
786
+ input_ids: torch.LongTensor = None,
787
+ attention_mask: Optional[torch.Tensor] = None,
788
+ position_ids: Optional[torch.LongTensor] = None,
789
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
790
+ inputs_embeds: Optional[torch.FloatTensor] = None,
791
+ labels: Optional[torch.LongTensor] = None,
792
+ use_cache: Optional[bool] = None,
793
+ output_attentions: Optional[bool] = None,
794
+ output_hidden_states: Optional[bool] = None,
795
+ return_dict: Optional[bool] = None,
796
+ cache_position: Optional[torch.LongTensor] = None,
797
+ logits_to_keep: Union[int, torch.Tensor] = 0,
798
+ **kwargs: Unpack[KwargsForCausalLM],
799
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
800
+ r"""
801
+ Args:
802
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
803
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
804
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
805
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
806
+
807
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
808
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
809
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
810
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
811
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
812
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
813
+
814
+ Returns:
815
+
816
+ Example:
817
+
818
+ ```python
819
+ >>> from transformers import AutoTokenizer, DummyLlamaForCausalLM
820
+
821
+ >>> model = DummyLlamaForCausalLM.from_pretrained("meta-llama/DummyLlama-2-7b-hf")
822
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/DummyLlama-2-7b-hf")
823
+
824
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
825
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
826
+
827
+ >>> # Generate
828
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
829
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
830
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
831
+ ```"""
832
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
833
+ output_hidden_states = (
834
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
835
+ )
836
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
837
+
838
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
839
+ outputs = self.model(
840
+ input_ids=input_ids,
841
+ attention_mask=attention_mask,
842
+ position_ids=position_ids,
843
+ past_key_values=past_key_values,
844
+ inputs_embeds=inputs_embeds,
845
+ use_cache=use_cache,
846
+ output_attentions=output_attentions,
847
+ output_hidden_states=output_hidden_states,
848
+ return_dict=return_dict,
849
+ cache_position=cache_position,
850
+ **kwargs,
851
+ )
852
+
853
+ hidden_states = outputs[0]
854
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
855
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
856
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
857
+
858
+ loss = None
859
+ if labels is not None:
860
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
861
+
862
+ if not return_dict:
863
+ output = (logits,) + outputs[1:]
864
+ return (loss,) + output if loss is not None else output
865
+
866
+ return CausalLMOutputWithPast(
867
+ loss=loss,
868
+ logits=logits,
869
+ past_key_values=outputs.past_key_values,
870
+ hidden_states=outputs.hidden_states,
871
+ attentions=outputs.attentions,
872
+ )
873
+
874
+
875
+ @add_start_docstrings(
876
+ """
877
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
878
+
879
+ [`DummyLlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
880
+ (e.g. GPT-2) do.
881
+
882
+ Since it does classification on the last token, it requires to know the position of the last token. If a
883
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
884
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
885
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
886
+ each row of the batch).
887
+ """,
888
+ LLAMA_START_DOCSTRING,
889
+ )
890
+ class DummyLlamaForSequenceClassification(DummyLlamaPreTrainedModel):
891
+ def __init__(self, config):
892
+ super().__init__(config)
893
+ self.num_labels = config.num_labels
894
+ self.model = DummyLlamaModel(config)
895
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
896
+
897
+ # Initialize weights and apply final processing
898
+ self.post_init()
899
+
900
+ def get_input_embeddings(self):
901
+ return self.model.embed_tokens
902
+
903
+ def set_input_embeddings(self, value):
904
+ self.model.embed_tokens = value
905
+
906
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
907
+ def forward(
908
+ self,
909
+ input_ids: Optional[torch.LongTensor] = None,
910
+ attention_mask: Optional[torch.Tensor] = None,
911
+ position_ids: Optional[torch.LongTensor] = None,
912
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
913
+ inputs_embeds: Optional[torch.FloatTensor] = None,
914
+ labels: Optional[torch.LongTensor] = None,
915
+ use_cache: Optional[bool] = None,
916
+ output_attentions: Optional[bool] = None,
917
+ output_hidden_states: Optional[bool] = None,
918
+ return_dict: Optional[bool] = None,
919
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
920
+ r"""
921
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
922
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
923
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
924
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
925
+ """
926
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
927
+
928
+ transformer_outputs = self.model(
929
+ input_ids,
930
+ attention_mask=attention_mask,
931
+ position_ids=position_ids,
932
+ past_key_values=past_key_values,
933
+ inputs_embeds=inputs_embeds,
934
+ use_cache=use_cache,
935
+ output_attentions=output_attentions,
936
+ output_hidden_states=output_hidden_states,
937
+ return_dict=return_dict,
938
+ )
939
+ hidden_states = transformer_outputs[0]
940
+ logits = self.score(hidden_states)
941
+
942
+ if input_ids is not None:
943
+ batch_size = input_ids.shape[0]
944
+ else:
945
+ batch_size = inputs_embeds.shape[0]
946
+
947
+ if self.config.pad_token_id is None and batch_size != 1:
948
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
949
+ if self.config.pad_token_id is None:
950
+ sequence_lengths = -1
951
+ else:
952
+ if input_ids is not None:
953
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
954
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
955
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
956
+ sequence_lengths = sequence_lengths.to(logits.device)
957
+ else:
958
+ sequence_lengths = -1
959
+
960
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
961
+
962
+ loss = None
963
+ if labels is not None:
964
+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
965
+
966
+ if not return_dict:
967
+ output = (pooled_logits,) + transformer_outputs[1:]
968
+ return ((loss,) + output) if loss is not None else output
969
+
970
+ return SequenceClassifierOutputWithPast(
971
+ loss=loss,
972
+ logits=pooled_logits,
973
+ past_key_values=transformer_outputs.past_key_values,
974
+ hidden_states=transformer_outputs.hidden_states,
975
+ attentions=transformer_outputs.attentions,
976
+ )
977
+
978
+
979
+ @add_start_docstrings(
980
+ """
981
+ The DummyLlama Model transformer with a span classification head on top for extractive question-answering tasks like
982
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
983
+ """,
984
+ LLAMA_START_DOCSTRING,
985
+ )
986
+ class DummyLlamaForQuestionAnswering(DummyLlamaPreTrainedModel):
987
+ base_model_prefix = "transformer"
988
+
989
+ # Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->DummyLlama
990
+ def __init__(self, config):
991
+ super().__init__(config)
992
+ self.transformer = DummyLlamaModel(config)
993
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
994
+
995
+ # Initialize weights and apply final processing
996
+ self.post_init()
997
+
998
+ def get_input_embeddings(self):
999
+ return self.transformer.embed_tokens
1000
+
1001
+ def set_input_embeddings(self, value):
1002
+ self.transformer.embed_tokens = value
1003
+
1004
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1005
+ def forward(
1006
+ self,
1007
+ input_ids: Optional[torch.LongTensor] = None,
1008
+ attention_mask: Optional[torch.FloatTensor] = None,
1009
+ position_ids: Optional[torch.LongTensor] = None,
1010
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1011
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1012
+ start_positions: Optional[torch.LongTensor] = None,
1013
+ end_positions: Optional[torch.LongTensor] = None,
1014
+ output_attentions: Optional[bool] = None,
1015
+ output_hidden_states: Optional[bool] = None,
1016
+ return_dict: Optional[bool] = None,
1017
+ **kwargs,
1018
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1019
+ r"""
1020
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1021
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1022
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1023
+ are not taken into account for computing the loss.
1024
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1025
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1026
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1027
+ are not taken into account for computing the loss.
1028
+ """
1029
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1030
+
1031
+ outputs = self.transformer(
1032
+ input_ids,
1033
+ attention_mask=attention_mask,
1034
+ position_ids=position_ids,
1035
+ past_key_values=past_key_values,
1036
+ inputs_embeds=inputs_embeds,
1037
+ output_attentions=output_attentions,
1038
+ output_hidden_states=output_hidden_states,
1039
+ return_dict=return_dict,
1040
+ )
1041
+
1042
+ sequence_output = outputs[0]
1043
+
1044
+ logits = self.qa_outputs(sequence_output)
1045
+ start_logits, end_logits = logits.split(1, dim=-1)
1046
+ start_logits = start_logits.squeeze(-1).contiguous()
1047
+ end_logits = end_logits.squeeze(-1).contiguous()
1048
+
1049
+ loss = None
1050
+ if start_positions is not None and end_positions is not None:
1051
+ loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
1052
+
1053
+ if not return_dict:
1054
+ output = (start_logits, end_logits) + outputs[2:]
1055
+ return ((loss,) + output) if loss is not None else output
1056
+
1057
+ return QuestionAnsweringModelOutput(
1058
+ loss=loss,
1059
+ start_logits=start_logits,
1060
+ end_logits=end_logits,
1061
+ hidden_states=outputs.hidden_states,
1062
+ attentions=outputs.attentions,
1063
+ )
1064
+
1065
+
1066
+ @add_start_docstrings(
1067
+ """
1068
+ The DummyLlama Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1069
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1070
+ """,
1071
+ LLAMA_START_DOCSTRING,
1072
+ )
1073
+ class DummyLlamaForTokenClassification(DummyLlamaPreTrainedModel):
1074
+ def __init__(self, config):
1075
+ super().__init__(config)
1076
+ self.num_labels = config.num_labels
1077
+ self.model = DummyLlamaModel(config)
1078
+ if getattr(config, "classifier_dropout", None) is not None:
1079
+ classifier_dropout = config.classifier_dropout
1080
+ elif getattr(config, "hidden_dropout", None) is not None:
1081
+ classifier_dropout = config.hidden_dropout
1082
+ else:
1083
+ classifier_dropout = 0.1
1084
+ self.dropout = nn.Dropout(classifier_dropout)
1085
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1086
+
1087
+ # Initialize weights and apply final processing
1088
+ self.post_init()
1089
+
1090
+ def get_input_embeddings(self):
1091
+ return self.model.embed_tokens
1092
+
1093
+ def set_input_embeddings(self, value):
1094
+ self.model.embed_tokens = value
1095
+
1096
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1097
+ @add_code_sample_docstrings(
1098
+ checkpoint=_CHECKPOINT_FOR_DOC,
1099
+ output_type=TokenClassifierOutput,
1100
+ config_class=_CONFIG_FOR_DOC,
1101
+ )
1102
+ def forward(
1103
+ self,
1104
+ input_ids: Optional[torch.LongTensor] = None,
1105
+ attention_mask: Optional[torch.Tensor] = None,
1106
+ position_ids: Optional[torch.LongTensor] = None,
1107
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1108
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1109
+ labels: Optional[torch.LongTensor] = None,
1110
+ use_cache: Optional[bool] = None,
1111
+ output_attentions: Optional[bool] = None,
1112
+ output_hidden_states: Optional[bool] = None,
1113
+ return_dict: Optional[bool] = None,
1114
+ ) -> Union[Tuple, TokenClassifierOutput]:
1115
+ r"""
1116
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1117
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1118
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1119
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1120
+ """
1121
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1122
+
1123
+ outputs = self.model(
1124
+ input_ids,
1125
+ attention_mask=attention_mask,
1126
+ position_ids=position_ids,
1127
+ past_key_values=past_key_values,
1128
+ inputs_embeds=inputs_embeds,
1129
+ use_cache=use_cache,
1130
+ output_attentions=output_attentions,
1131
+ output_hidden_states=output_hidden_states,
1132
+ return_dict=return_dict,
1133
+ )
1134
+ sequence_output = outputs[0]
1135
+ sequence_output = self.dropout(sequence_output)
1136
+ logits = self.score(sequence_output)
1137
+
1138
+ loss = None
1139
+ if labels is not None:
1140
+ loss = self.loss_function(logits, labels, self.config)
1141
+
1142
+ if not return_dict:
1143
+ output = (logits,) + outputs[2:]
1144
+ return ((loss,) + output) if loss is not None else output
1145
+
1146
+ return TokenClassifierOutput(
1147
+ loss=loss,
1148
+ logits=logits,
1149
+ hidden_states=outputs.hidden_states,
1150
+ attentions=outputs.attentions,
1151
+ )
1152
+
1153
+
1154
+ __all__ = [
1155
+ "DummyLlamaForCausalLM",
1156
+ "DummyLlamaModel",
1157
+ "DummyLlamaPreTrainedModel",
1158
+ "DummyLlamaForSequenceClassification",
1159
+ "DummyLlamaForQuestionAnswering",
1160
+ "DummyLlamaForTokenClassification",
1161
+ ]