Text Generation
Transformers
Safetensors
Urdu
llama
text-generation-inference
custom_code
AhmadMustafa commited on
Commit
4573d98
1 Parent(s): d891f9a

Upload MobiLlamaForCausalLM

Browse files
Files changed (5) hide show
  1. README.md +201 -0
  2. config.json +31 -0
  3. generation_config.json +6 -0
  4. model.safetensors +3 -0
  5. modelling_mobillama.py +869 -0
README.md ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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]
200
+
201
+
config.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "/content/drive/MyDrive/mobillama_fine_tune/checkpoint-8500",
3
+ "architectures": [
4
+ "MobiLlamaForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "auto_map": {
9
+ "AutoModelForCausalLM": "modelling_mobillama.MobiLlamaForCausalLM"
10
+ },
11
+ "bos_token_id": 1,
12
+ "eos_token_id": 2,
13
+ "hidden_act": "silu",
14
+ "hidden_size": 2048,
15
+ "initializer_range": 0.02,
16
+ "intermediate_size": 5632,
17
+ "max_position_embeddings": 2048,
18
+ "model_type": "llama",
19
+ "num_attention_heads": 32,
20
+ "num_hidden_layers": 22,
21
+ "num_key_value_heads": 4,
22
+ "pretraining_tp": 1,
23
+ "rms_norm_eps": 1e-05,
24
+ "rope_scaling": null,
25
+ "rope_theta": 10000.0,
26
+ "tie_word_embeddings": false,
27
+ "torch_dtype": "float32",
28
+ "transformers_version": "4.37.2",
29
+ "use_cache": true,
30
+ "vocab_size": 32000
31
+ }
generation_config.json ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "transformers_version": "4.37.2"
6
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0a7a8140319fcf861cb9aa8b68fe2d8e5dc64e02dd4a90b76a3470bfd2ae37ac
3
+ size 2139484928
modelling_mobillama.py ADDED
@@ -0,0 +1,869 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 model."""
21
+ import math
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.utils.checkpoint
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
31
+ from transformers.modeling_utils import PreTrainedModel
32
+ from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
33
+ from transformers.models.llama.configuration_llama import LlamaConfig
34
+
35
+ # from .configuration_mobillama import MobiLlamaConfig
36
+
37
+ from flash_attn import flash_attn_func
38
+
39
+
40
+ logger = logging.get_logger(__name__)
41
+
42
+ _CONFIG_FOR_DOC = "LlamaConfig"
43
+
44
+
45
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
46
+ def _make_causal_mask(
47
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
48
+ ):
49
+ """
50
+ Make causal mask used for bi-directional self-attention.
51
+ """
52
+ bsz, tgt_len = input_ids_shape
53
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
54
+ mask_cond = torch.arange(mask.size(-1), device=device)
55
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
56
+ mask = mask.to(dtype)
57
+
58
+ if past_key_values_length > 0:
59
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
60
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
61
+
62
+
63
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
64
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
65
+ """
66
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
67
+ """
68
+ bsz, src_len = mask.size()
69
+ tgt_len = tgt_len if tgt_len is not None else src_len
70
+
71
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
72
+
73
+ inverted_mask = 1.0 - expanded_mask
74
+
75
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
76
+
77
+
78
+ class MobiLlamaRMSNorm(nn.Module):
79
+ def __init__(self, hidden_size, eps=1e-6):
80
+ """
81
+ MobiLlamaRMSNorm is equivalent to T5LayerNorm
82
+ """
83
+ super().__init__()
84
+ self.weight = nn.Parameter(torch.ones(hidden_size))
85
+ self.variance_epsilon = eps
86
+
87
+ def forward(self, hidden_states):
88
+ input_dtype = hidden_states.dtype
89
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
90
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
91
+
92
+ return (self.weight * hidden_states).to(input_dtype)
93
+
94
+
95
+ class MobiLlamaRotaryEmbedding(torch.nn.Module):
96
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
97
+ super().__init__()
98
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
99
+ self.register_buffer("inv_freq", inv_freq)
100
+
101
+ # Build here to make `torch.jit.trace` work.
102
+ self.max_seq_len_cached = max_position_embeddings
103
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
104
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
105
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
106
+ emb = torch.cat((freqs, freqs), dim=-1)
107
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
108
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
109
+
110
+ def forward(self, x, seq_len=None):
111
+ # x: [bs, num_attention_heads, seq_len, head_size]
112
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
113
+ if seq_len > self.max_seq_len_cached:
114
+ self.max_seq_len_cached = seq_len
115
+ t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
116
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
117
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
118
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
119
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
120
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
121
+ return (
122
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
123
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
124
+ )
125
+
126
+
127
+ def rotate_half(x):
128
+ """Rotates half the hidden dims of the input."""
129
+ x1 = x[..., : x.shape[-1] // 2]
130
+ x2 = x[..., x.shape[-1] // 2 :]
131
+ return torch.cat((-x2, x1), dim=-1)
132
+
133
+
134
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
135
+ # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
136
+ cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
137
+ sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
138
+ cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
139
+ sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
140
+ q_embed = (q * cos) + (rotate_half(q) * sin)
141
+ k_embed = (k * cos) + (rotate_half(k) * sin)
142
+ return q_embed, k_embed
143
+
144
+
145
+ class MobiLlamaMLP(nn.Module):
146
+ def __init__(
147
+ self,
148
+ hidden_size: int,
149
+ intermediate_size: int,
150
+ hidden_act: str,
151
+ ):
152
+ super().__init__()
153
+ self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
154
+ self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
155
+ self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
156
+ self.act_fn = ACT2FN[hidden_act]
157
+
158
+ def forward(self, x):
159
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
160
+
161
+
162
+ class MobiLlamaAttention(nn.Module):
163
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
164
+
165
+ def __init__(self, config: LlamaConfig):
166
+ super().__init__()
167
+ self.config = config
168
+ self.hidden_size = config.hidden_size
169
+ self.num_heads = config.num_attention_heads
170
+ self.head_dim = self.hidden_size // self.num_heads
171
+ self.max_position_embeddings = config.max_position_embeddings
172
+
173
+ if (self.head_dim * self.num_heads) != self.hidden_size:
174
+ raise ValueError(
175
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
176
+ f" and `num_heads`: {self.num_heads})."
177
+ )
178
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
179
+ self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
180
+ self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
181
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
182
+ self.rotary_emb = MobiLlamaRotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
183
+
184
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
185
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
186
+
187
+ def forward(
188
+ self,
189
+ hidden_states: torch.Tensor,
190
+ attention_mask: Optional[torch.Tensor] = None,
191
+ position_ids: Optional[torch.LongTensor] = None,
192
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
193
+ output_attentions: bool = False,
194
+ use_cache: bool = False,
195
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
196
+ bsz, q_len, _ = hidden_states.size()
197
+
198
+ query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
199
+ key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
200
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
201
+
202
+ kv_seq_len = key_states.shape[-2]
203
+ if past_key_value is not None:
204
+ kv_seq_len += past_key_value[0].shape[-2]
205
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
206
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
207
+ # [bsz, nh, t, hd]
208
+
209
+ if past_key_value is not None:
210
+ # reuse k, v, self_attention
211
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
212
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
213
+
214
+ past_key_value = (key_states, value_states) if use_cache else None
215
+
216
+ attn_output = flash_attn_func(
217
+ q=query_states.transpose(1, 2).to(torch.bfloat16),
218
+ k=key_states.transpose(1, 2).to(torch.bfloat16),
219
+ v=value_states.transpose(1, 2).to(torch.bfloat16),
220
+ causal=True)
221
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
222
+ attn_output = attn_output.to(query_states.dtype)
223
+
224
+ attn_output = self.o_proj(attn_output)
225
+
226
+ # if not output_attentions:
227
+ # attn_weights = None
228
+ assert not output_attentions
229
+ attn_weights = None
230
+
231
+ return attn_output, attn_weights, past_key_value
232
+
233
+
234
+ class MobiLlamaDecoderLayer(nn.Module):
235
+ def __init__(self, config: LlamaConfig, mlp):
236
+ super().__init__()
237
+ self.hidden_size = config.hidden_size
238
+ self.self_attn = MobiLlamaAttention(config=config)
239
+ self.mlp = mlp #LlamaMLP(hidden_size=self.hidden_size,intermediate_size=config.intermediate_size,hidden_act=config.hidden_act,)
240
+ self.input_layernorm = MobiLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
241
+ self.post_attention_layernorm = MobiLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
242
+
243
+ def forward(
244
+ self,
245
+ hidden_states: torch.Tensor,
246
+ attention_mask: Optional[torch.Tensor] = None,
247
+ position_ids: Optional[torch.LongTensor] = None,
248
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
249
+ output_attentions: Optional[bool] = False,
250
+ use_cache: Optional[bool] = False,
251
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
252
+ """
253
+ Args:
254
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
255
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
256
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
257
+ output_attentions (`bool`, *optional*):
258
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
259
+ returned tensors for more detail.
260
+ use_cache (`bool`, *optional*):
261
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
262
+ (see `past_key_values`).
263
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
264
+ """
265
+
266
+ residual = hidden_states
267
+
268
+ hidden_states = self.input_layernorm(hidden_states)
269
+
270
+ # Self Attention
271
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
272
+ hidden_states=hidden_states,
273
+ attention_mask=attention_mask,
274
+ position_ids=position_ids,
275
+ past_key_value=past_key_value,
276
+ output_attentions=output_attentions,
277
+ use_cache=use_cache,
278
+ )
279
+ hidden_states = residual + hidden_states
280
+
281
+ # Fully Connected
282
+ residual = hidden_states
283
+ hidden_states = self.post_attention_layernorm(hidden_states)
284
+ hidden_states = self.mlp(hidden_states)
285
+ hidden_states = residual + hidden_states
286
+
287
+ outputs = (hidden_states,)
288
+
289
+ if output_attentions:
290
+ outputs += (self_attn_weights,)
291
+
292
+ if use_cache:
293
+ outputs += (present_key_value,)
294
+
295
+ return outputs
296
+
297
+
298
+ MOBILLAMA_START_DOCSTRING = r"""
299
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
300
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
301
+ etc.)
302
+
303
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
304
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
305
+ and behavior.
306
+
307
+ Parameters:
308
+ config ([`LlamaConfig`]):
309
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
310
+ load the weights associated with the model, only the configuration. Check out the
311
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
312
+ """
313
+
314
+
315
+ @add_start_docstrings(
316
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
317
+ MOBILLAMA_START_DOCSTRING,
318
+ )
319
+ class MobiLlamaPreTrainedModel(PreTrainedModel):
320
+ config_class = LlamaConfig
321
+ base_model_prefix = "model"
322
+ supports_gradient_checkpointing = True
323
+ _no_split_modules = ["MobiLlamaDecoderLayer"]
324
+ _skip_keys_device_placement = "past_key_values"
325
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
326
+
327
+ def _init_weights(self, module):
328
+ std = self.config.initializer_range
329
+ if isinstance(module, nn.Linear):
330
+ module.weight.data.normal_(mean=0.0, std=std)
331
+ if module.bias is not None:
332
+ module.bias.data.zero_()
333
+ elif isinstance(module, nn.Embedding):
334
+ module.weight.data.normal_(mean=0.0, std=std)
335
+ if module.padding_idx is not None:
336
+ module.weight.data[module.padding_idx].zero_()
337
+
338
+ def _set_gradient_checkpointing(self, module, value=False):
339
+ if isinstance(module, MobiLlamaModel):
340
+ module.gradient_checkpointing = value
341
+
342
+
343
+ MOBILLAMA_INPUTS_DOCSTRING = r"""
344
+ Args:
345
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
346
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
347
+ it.
348
+
349
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
350
+ [`PreTrainedTokenizer.__call__`] for details.
351
+
352
+ [What are input IDs?](../glossary#input-ids)
353
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
354
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
355
+
356
+ - 1 for tokens that are **not masked**,
357
+ - 0 for tokens that are **masked**.
358
+
359
+ [What are attention masks?](../glossary#attention-mask)
360
+
361
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
362
+ [`PreTrainedTokenizer.__call__`] for details.
363
+
364
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
365
+ `past_key_values`).
366
+
367
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
368
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
369
+ information on the default strategy.
370
+
371
+ - 1 indicates the head is **not masked**,
372
+ - 0 indicates the head is **masked**.
373
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
374
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
375
+ config.n_positions - 1]`.
376
+
377
+ [What are position IDs?](../glossary#position-ids)
378
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
379
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
380
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
381
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
382
+
383
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
384
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
385
+
386
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
387
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
388
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
389
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
390
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
391
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
392
+ model's internal embedding lookup matrix.
393
+ use_cache (`bool`, *optional*):
394
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
395
+ `past_key_values`).
396
+ output_attentions (`bool`, *optional*):
397
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
398
+ tensors for more detail.
399
+ output_hidden_states (`bool`, *optional*):
400
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
401
+ more detail.
402
+ return_dict (`bool`, *optional*):
403
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
404
+ """
405
+
406
+
407
+ @add_start_docstrings(
408
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
409
+ MOBILLAMA_START_DOCSTRING,
410
+ )
411
+ class MobiLlamaModel(MobiLlamaPreTrainedModel):
412
+ """
413
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MobiLlamaDecoderLayer`]
414
+
415
+ Args:
416
+ config: LlamaConfig
417
+ """
418
+
419
+ def __init__(self, config: LlamaConfig):
420
+ super().__init__(config)
421
+ self.padding_idx = config.pad_token_id
422
+ self.vocab_size = config.vocab_size
423
+
424
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
425
+ mlp = MobiLlamaMLP(
426
+ hidden_size=config.hidden_size,
427
+ intermediate_size=config.intermediate_size,
428
+ hidden_act=config.hidden_act,
429
+ )
430
+ self.layers = nn.ModuleList([MobiLlamaDecoderLayer(config, mlp) for _ in range(config.num_hidden_layers)])
431
+ self.norm = MobiLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
432
+
433
+ self.gradient_checkpointing = False
434
+ # Initialize weights and apply final processing
435
+ self.post_init()
436
+
437
+ def get_input_embeddings(self):
438
+ return self.embed_tokens
439
+
440
+ def set_input_embeddings(self, value):
441
+ self.embed_tokens = value
442
+
443
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
444
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
445
+ # create causal mask
446
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
447
+ combined_attention_mask = None
448
+ if input_shape[-1] > 1:
449
+ combined_attention_mask = _make_causal_mask(
450
+ input_shape,
451
+ inputs_embeds.dtype,
452
+ device=inputs_embeds.device,
453
+ past_key_values_length=past_key_values_length,
454
+ )
455
+
456
+ if attention_mask is not None:
457
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
458
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
459
+ inputs_embeds.device
460
+ )
461
+ combined_attention_mask = (
462
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
463
+ )
464
+
465
+ return combined_attention_mask
466
+
467
+ @add_start_docstrings_to_model_forward(MOBILLAMA_INPUTS_DOCSTRING)
468
+ def forward(
469
+ self,
470
+ input_ids: torch.LongTensor = None,
471
+ attention_mask: Optional[torch.Tensor] = None,
472
+ position_ids: Optional[torch.LongTensor] = None,
473
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
474
+ inputs_embeds: Optional[torch.FloatTensor] = None,
475
+ use_cache: Optional[bool] = None,
476
+ output_attentions: Optional[bool] = None,
477
+ output_hidden_states: Optional[bool] = None,
478
+ return_dict: Optional[bool] = None,
479
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
480
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
481
+ output_hidden_states = (
482
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
483
+ )
484
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
485
+
486
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
487
+
488
+ # retrieve input_ids and inputs_embeds
489
+ if input_ids is not None and inputs_embeds is not None:
490
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
491
+ elif input_ids is not None:
492
+ batch_size, seq_length = input_ids.shape
493
+ elif inputs_embeds is not None:
494
+ batch_size, seq_length, _ = inputs_embeds.shape
495
+ else:
496
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
497
+
498
+ seq_length_with_past = seq_length
499
+ past_key_values_length = 0
500
+
501
+ if past_key_values is not None:
502
+ past_key_values_length = past_key_values[0][0].shape[2]
503
+ seq_length_with_past = seq_length_with_past + past_key_values_length
504
+
505
+ if position_ids is None:
506
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
507
+ position_ids = torch.arange(
508
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
509
+ )
510
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
511
+ else:
512
+ position_ids = position_ids.view(-1, seq_length).long()
513
+
514
+ if inputs_embeds is None:
515
+ inputs_embeds = self.embed_tokens(input_ids)
516
+ # embed positions
517
+ if attention_mask is None:
518
+ attention_mask = torch.ones(
519
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
520
+ )
521
+ attention_mask = self._prepare_decoder_attention_mask(
522
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
523
+ )
524
+
525
+ hidden_states = inputs_embeds
526
+
527
+ if self.gradient_checkpointing and self.training:
528
+ if use_cache:
529
+ logger.warning_once(
530
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
531
+ )
532
+ use_cache = False
533
+
534
+ # decoder layers
535
+ all_hidden_states = () if output_hidden_states else None
536
+ all_self_attns = () if output_attentions else None
537
+ next_decoder_cache = () if use_cache else None
538
+
539
+ for idx, decoder_layer in enumerate(self.layers):
540
+ if output_hidden_states:
541
+ all_hidden_states += (hidden_states,)
542
+
543
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
544
+
545
+ if self.gradient_checkpointing and self.training:
546
+
547
+ def create_custom_forward(module):
548
+ def custom_forward(*inputs):
549
+ # None for past_key_value
550
+ return module(*inputs, output_attentions, None)
551
+
552
+ return custom_forward
553
+
554
+ layer_outputs = torch.utils.checkpoint.checkpoint(
555
+ create_custom_forward(decoder_layer),
556
+ hidden_states,
557
+ attention_mask,
558
+ position_ids,
559
+ None,
560
+ )
561
+ else:
562
+ layer_outputs = decoder_layer(
563
+ hidden_states,
564
+ attention_mask=attention_mask,
565
+ position_ids=position_ids,
566
+ past_key_value=past_key_value,
567
+ output_attentions=output_attentions,
568
+ use_cache=use_cache,
569
+ )
570
+
571
+ hidden_states = layer_outputs[0]
572
+
573
+ if use_cache:
574
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
575
+
576
+ if output_attentions:
577
+ all_self_attns += (layer_outputs[1],)
578
+
579
+ hidden_states = self.norm(hidden_states)
580
+
581
+ # add hidden states from the last decoder layer
582
+ if output_hidden_states:
583
+ all_hidden_states += (hidden_states,)
584
+
585
+ next_cache = next_decoder_cache if use_cache else None
586
+ if not return_dict:
587
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
588
+ return BaseModelOutputWithPast(
589
+ last_hidden_state=hidden_states,
590
+ past_key_values=next_cache,
591
+ hidden_states=all_hidden_states,
592
+ attentions=all_self_attns,
593
+ )
594
+
595
+
596
+ class MobiLlamaForCausalLM(MobiLlamaPreTrainedModel):
597
+ def __init__(self, config):
598
+ super().__init__(config)
599
+ self.model = MobiLlamaModel(config)
600
+
601
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
602
+
603
+ # Initialize weights and apply final processing
604
+ self.post_init()
605
+
606
+ def get_input_embeddings(self):
607
+ return self.model.embed_tokens
608
+
609
+ def set_input_embeddings(self, value):
610
+ self.model.embed_tokens = value
611
+
612
+ def get_output_embeddings(self):
613
+ return self.lm_head
614
+
615
+ def set_output_embeddings(self, new_embeddings):
616
+ self.lm_head = new_embeddings
617
+
618
+ def set_decoder(self, decoder):
619
+ self.model = decoder
620
+
621
+ def get_decoder(self):
622
+ return self.model
623
+
624
+ @add_start_docstrings_to_model_forward(MOBILLAMA_INPUTS_DOCSTRING)
625
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
626
+ def forward(
627
+ self,
628
+ input_ids: torch.LongTensor = None,
629
+ attention_mask: Optional[torch.Tensor] = None,
630
+ position_ids: Optional[torch.LongTensor] = None,
631
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
632
+ inputs_embeds: Optional[torch.FloatTensor] = None,
633
+ labels: Optional[torch.LongTensor] = None,
634
+ use_cache: Optional[bool] = None,
635
+ output_attentions: Optional[bool] = None,
636
+ output_hidden_states: Optional[bool] = None,
637
+ return_dict: Optional[bool] = None,
638
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
639
+ r"""
640
+ Args:
641
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
642
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
643
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
644
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
645
+
646
+ Returns:
647
+
648
+ Example:
649
+
650
+ ```python
651
+ >>> from transformers import AutoTokenizer, MobiLlamaForCausalLM
652
+
653
+ >>> model = MobiLlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
654
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
655
+
656
+ >>> prompt = "Hey, are you consciours? Can you talk to me?"
657
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
658
+
659
+ >>> # Generate
660
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
661
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
662
+ "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."
663
+ ```"""
664
+
665
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
666
+ output_hidden_states = (
667
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
668
+ )
669
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
670
+
671
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
672
+ outputs = self.model(
673
+ input_ids=input_ids,
674
+ attention_mask=attention_mask,
675
+ position_ids=position_ids,
676
+ past_key_values=past_key_values,
677
+ inputs_embeds=inputs_embeds,
678
+ use_cache=use_cache,
679
+ output_attentions=output_attentions,
680
+ output_hidden_states=output_hidden_states,
681
+ return_dict=return_dict,
682
+ )
683
+
684
+ hidden_states = outputs[0]
685
+ logits = self.lm_head(hidden_states)
686
+
687
+ loss = None
688
+ if labels is not None:
689
+ # Shift so that tokens < n predict n
690
+ shift_logits = logits[..., :-1, :].contiguous()
691
+ shift_labels = labels[..., 1:].contiguous()
692
+ # Flatten the tokens
693
+ loss_fct = CrossEntropyLoss()
694
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
695
+ shift_labels = shift_labels.view(-1)
696
+ # Enable model parallelism
697
+ shift_labels = shift_labels.to(shift_logits.device)
698
+ loss = loss_fct(shift_logits, shift_labels)
699
+
700
+ if not return_dict:
701
+ output = (logits,) + outputs[1:]
702
+ return (loss,) + output if loss is not None else output
703
+
704
+ return CausalLMOutputWithPast(
705
+ loss=loss,
706
+ logits=logits,
707
+ past_key_values=outputs.past_key_values,
708
+ hidden_states=outputs.hidden_states,
709
+ attentions=outputs.attentions,
710
+ )
711
+
712
+ def prepare_inputs_for_generation(
713
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
714
+ ):
715
+ if past_key_values:
716
+ input_ids = input_ids[:, -1:]
717
+
718
+ position_ids = kwargs.get("position_ids", None)
719
+ if attention_mask is not None and position_ids is None:
720
+ # create position_ids on the fly for batch generation
721
+ position_ids = attention_mask.long().cumsum(-1) - 1
722
+ position_ids.masked_fill_(attention_mask == 0, 1)
723
+ if past_key_values:
724
+ position_ids = position_ids[:, -1].unsqueeze(-1)
725
+
726
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
727
+ if inputs_embeds is not None and past_key_values is None:
728
+ model_inputs = {"inputs_embeds": inputs_embeds}
729
+ else:
730
+ model_inputs = {"input_ids": input_ids}
731
+
732
+ model_inputs.update(
733
+ {
734
+ "position_ids": position_ids,
735
+ "past_key_values": past_key_values,
736
+ "use_cache": kwargs.get("use_cache"),
737
+ "attention_mask": attention_mask,
738
+ }
739
+ )
740
+ return model_inputs
741
+
742
+ @staticmethod
743
+ def _reorder_cache(past_key_values, beam_idx):
744
+ reordered_past = ()
745
+ for layer_past in past_key_values:
746
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
747
+ return reordered_past
748
+
749
+
750
+ @add_start_docstrings(
751
+ """
752
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
753
+
754
+ [`MobiLlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
755
+ (e.g. GPT-2) do.
756
+
757
+ Since it does classification on the last token, it requires to know the position of the last token. If a
758
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
759
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
760
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
761
+ each row of the batch).
762
+ """,
763
+ MOBILLAMA_START_DOCSTRING,
764
+ )
765
+ class MobiLlamaForSequenceClassification(MobiLlamaPreTrainedModel):
766
+ _keys_to_ignore_on_load_missing = [r"lm_head.weight"]
767
+
768
+ def __init__(self, config):
769
+ super().__init__(config)
770
+ self.num_labels = config.num_labels
771
+ self.model = MobiLlamaModel(config)
772
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
773
+
774
+ # Initialize weights and apply final processing
775
+ self.post_init()
776
+
777
+ def get_input_embeddings(self):
778
+ return self.model.embed_tokens
779
+
780
+ def set_input_embeddings(self, value):
781
+ self.model.embed_tokens = value
782
+
783
+ @add_start_docstrings_to_model_forward(MOBILLAMA_INPUTS_DOCSTRING)
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[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
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
797
+ r"""
798
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
799
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
800
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
801
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
802
+ """
803
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
804
+
805
+ transformer_outputs = self.model(
806
+ input_ids,
807
+ attention_mask=attention_mask,
808
+ position_ids=position_ids,
809
+ past_key_values=past_key_values,
810
+ inputs_embeds=inputs_embeds,
811
+ use_cache=use_cache,
812
+ output_attentions=output_attentions,
813
+ output_hidden_states=output_hidden_states,
814
+ return_dict=return_dict,
815
+ )
816
+ hidden_states = transformer_outputs[0]
817
+ logits = self.score(hidden_states)
818
+
819
+ if input_ids is not None:
820
+ batch_size = input_ids.shape[0]
821
+ else:
822
+ batch_size = inputs_embeds.shape[0]
823
+
824
+ if self.config.pad_token_id is None and batch_size != 1:
825
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
826
+ if self.config.pad_token_id is None:
827
+ sequence_lengths = -1
828
+ else:
829
+ if input_ids is not None:
830
+ sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
831
+ else:
832
+ sequence_lengths = -1
833
+
834
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
835
+
836
+ loss = None
837
+ if labels is not None:
838
+ labels = labels.to(logits.device)
839
+ if self.config.problem_type is None:
840
+ if self.num_labels == 1:
841
+ self.config.problem_type = "regression"
842
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
843
+ self.config.problem_type = "single_label_classification"
844
+ else:
845
+ self.config.problem_type = "multi_label_classification"
846
+
847
+ if self.config.problem_type == "regression":
848
+ loss_fct = MSELoss()
849
+ if self.num_labels == 1:
850
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
851
+ else:
852
+ loss = loss_fct(pooled_logits, labels)
853
+ elif self.config.problem_type == "single_label_classification":
854
+ loss_fct = CrossEntropyLoss()
855
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
856
+ elif self.config.problem_type == "multi_label_classification":
857
+ loss_fct = BCEWithLogitsLoss()
858
+ loss = loss_fct(pooled_logits, labels)
859
+ if not return_dict:
860
+ output = (pooled_logits,) + transformer_outputs[1:]
861
+ return ((loss,) + output) if loss is not None else output
862
+
863
+ return SequenceClassifierOutputWithPast(
864
+ loss=loss,
865
+ logits=pooled_logits,
866
+ past_key_values=transformer_outputs.past_key_values,
867
+ hidden_states=transformer_outputs.hidden_states,
868
+ attentions=transformer_outputs.attentions,
869
+ )