Mortie1 commited on
Commit
94aaa8e
·
verified ·
1 Parent(s): 3211040

Upload MyLLaMa

Browse files
Files changed (5) hide show
  1. README.md +199 -0
  2. config.json +16 -0
  3. configure_for_hf.py +54 -0
  4. llama.py +430 -0
  5. model.safetensors +3 -0
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,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "MyLLaMa"
4
+ ],
5
+ "auto_map": {
6
+ "AutoConfig": "configure_for_hf.MyLLaMaConfig",
7
+ "AutoModelForCausalLM": "configure_for_hf.MyLLaMa"
8
+ },
9
+ "embed_dim": 1536,
10
+ "model_type": "LLaMa",
11
+ "n_chckpnt_segments": 24,
12
+ "n_heads": 24,
13
+ "n_layers": 24,
14
+ "torch_dtype": "float32",
15
+ "transformers_version": "4.47.0.dev0"
16
+ }
configure_for_hf.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch import nn
2
+ from transformers import (
3
+ AutoConfig,
4
+ AutoModel,
5
+ AutoModelForCausalLM,
6
+ PretrainedConfig,
7
+ PreTrainedModel,
8
+ )
9
+
10
+ from .llama import CustomAttentionLLaMa
11
+
12
+
13
+ class MyLLaMaConfig(PretrainedConfig):
14
+ model_type = "LLaMa"
15
+
16
+ def __init__(
17
+ self,
18
+ embed_dim: int = 1536,
19
+ n_layers: int = 24,
20
+ n_heads: int = 24,
21
+ n_chckpnt_segments: int = 24,
22
+ **kwargs,
23
+ ):
24
+ self.embed_dim = embed_dim
25
+ self.n_layers = n_layers
26
+ self.n_heads = n_heads
27
+ self.n_chckpnt_segments = n_chckpnt_segments
28
+ super().__init__(**kwargs)
29
+
30
+
31
+ class MyLLaMa(PreTrainedModel):
32
+ config_class = MyLLaMaConfig
33
+
34
+ def __init__(self, config: MyLLaMaConfig):
35
+ super().__init__(config)
36
+ self.model = CustomAttentionLLaMa(
37
+ config.embed_dim,
38
+ config.n_layers,
39
+ config.n_heads,
40
+ dropout=0,
41
+ n_chckpnt_segments=config.n_chckpnt_segments,
42
+ )
43
+
44
+ def forward(self, tensor, labels=None):
45
+ logits = self.model(tensor)["logits"]
46
+ if labels is not None:
47
+ loss = nn.functional.cross_entropy(logits, labels)
48
+ return {"loss": loss, "logits": logits}
49
+ return {"logits": logits}
50
+
51
+
52
+ AutoConfig.register("LLaMa", MyLLaMaConfig)
53
+ AutoModel.register(MyLLaMaConfig, MyLLaMa)
54
+ AutoModelForCausalLM.register(MyLLaMaConfig, MyLLaMa)
llama.py ADDED
@@ -0,0 +1,430 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import Tensor, nn
3
+ from torch.nn import Sequential
4
+ from torch.utils.checkpoint import checkpoint, checkpoint_sequential
5
+ from xformers.components.attention.utils import maybe_merge_masks
6
+ from xformers.components import MultiHeadDispatch
7
+ from xformers.components.attention import ScaledDotProduct
8
+
9
+ from transformers import AutoTokenizer
10
+
11
+
12
+ class RotaryEmbedding(nn.Module):
13
+ def __init__(
14
+ self,
15
+ dim_per_head: int,
16
+ max_seq_len: int = 4096,
17
+ interpolation_ratio: float | None = 0.25,
18
+ device=None,
19
+ dtype=None,
20
+ ):
21
+ super().__init__()
22
+
23
+ self.dim_per_head = dim_per_head
24
+ self.max_seq_len = max_seq_len
25
+ freqs = 1.0 / (
26
+ 10000
27
+ ** (
28
+ torch.arange(0, dim_per_head, 2, device=device, dtype=dtype).float() / 6
29
+ )
30
+ )
31
+ freqs = torch.repeat_interleave(freqs, 2)
32
+
33
+ r = (
34
+ freqs
35
+ * torch.arange(max_seq_len, device=device, dtype=dtype).float()[:, None]
36
+ )
37
+ if interpolation_ratio is not None:
38
+ r = r * interpolation_ratio
39
+
40
+ r1 = r.cos()
41
+ self.register_buffer("r1", r1)
42
+
43
+ r2 = r.sin()
44
+ self.register_buffer("r2", r2)
45
+
46
+ aranged = torch.arange(dim_per_head, device=device, dtype=dtype)
47
+
48
+ mask1 = torch.where(
49
+ aranged % 2 == 1,
50
+ aranged - 1,
51
+ aranged + 1,
52
+ ).float()
53
+ self.register_buffer("mask1", mask1)
54
+
55
+ mask2 = torch.where(aranged % 2 == 0, -1, 1).float()
56
+ self.register_buffer("mask2", mask2)
57
+
58
+ def forward(self, x: Tensor):
59
+ """
60
+ Args:
61
+ x (Tensor): input tensor. shape: (bs, seq_len, n_heads, dim_per_head)
62
+
63
+ Returns:
64
+ Tensor: input tensor with rotary embeddings. shape: (bs, seq_len, n_heads, dim_per_head)
65
+ """
66
+
67
+ assert (
68
+ x.ndim == 4
69
+ ), "input must have 4 dimensions: (bs, n_heads, seq_len, dim_per_head)"
70
+ assert x.shape[3] % 2 == 0, "dim_per_head must be divisible by 2"
71
+
72
+ x = x.transpose(1, 2)
73
+
74
+ return (
75
+ x * self.r1[None, : x.shape[1], None, :]
76
+ + x[
77
+ :,
78
+ :,
79
+ :,
80
+ self.mask1,
81
+ ]
82
+ * self.mask2
83
+ * self.r2[None, : x.shape[1], None, :]
84
+ ).transpose(1, 2)
85
+
86
+ def extra_repr(self) -> str:
87
+ return f"dim_per_head={self.dim_per_head}, max_seq_len={self.max_seq_len}"
88
+
89
+
90
+ class RMSNorm(nn.Module):
91
+ def __init__(self, dim: int, eps: float = 1e-9):
92
+ super().__init__()
93
+
94
+ self.dim = dim
95
+ self.gamma = nn.Parameter(
96
+ data=torch.nn.init.normal_(torch.zeros((dim,))), requires_grad=True
97
+ )
98
+ self.eps = eps
99
+
100
+ def forward(self, x: Tensor):
101
+ """
102
+ Args:
103
+ x (Tensor): input tensor. shape: (bs, seq_len, embed_dim)
104
+
105
+ Returns:
106
+ Tensor: input tensor with rotary embeddings. shape: (bs, seq_len, embed_dim)
107
+ """
108
+
109
+ assert x.ndim == 3, "input must have 3 dimensions: (bs, seq_len, embed_dim)"
110
+
111
+ return (
112
+ x
113
+ / torch.sqrt_(torch.mean(torch.square(x), dim=-1) + self.eps)[:, :, None]
114
+ * self.gamma
115
+ )
116
+
117
+ def extra_repr(self) -> str:
118
+ return f"dim={self.dim}, eps={self.eps}"
119
+
120
+
121
+ class SiLU(nn.Module):
122
+ def __init__(self):
123
+ super().__init__()
124
+
125
+ def forward(self, x: Tensor):
126
+ """
127
+ Args:
128
+ x (Tensor): input
129
+ """
130
+ return x * x.sigmoid()
131
+
132
+
133
+ class SwiGLU(nn.Module):
134
+ def __init__(self, dim: int) -> None:
135
+ super().__init__()
136
+ self.linear_inp1 = nn.Linear(dim, (8 * dim) // 3, bias=False)
137
+ self.linear_inp2 = nn.Linear(dim, (8 * dim) // 3, bias=False)
138
+ self.linear_out = nn.Linear((8 * dim) // 3, dim, bias=False)
139
+ self.silu = SiLU()
140
+
141
+ # nn.init.xavier_uniform_(self.linear_inp1.weight)
142
+ # nn.init.xavier_uniform_(self.linear_inp2.weight)
143
+ # nn.init.xavier_uniform_(self.linear_out.weight)
144
+
145
+ def forward(self, x: Tensor):
146
+ """
147
+ Args:
148
+ x (Tensor): input tensor
149
+ """
150
+ return self.linear_out(self.silu(self.linear_inp1(x)) * self.linear_inp2(x))
151
+
152
+
153
+ class MistralTokenizer(nn.Module):
154
+ def __init__(self, max_length=1024, *args, **kwargs):
155
+ super().__init__()
156
+ self.tokenizer = AutoTokenizer.from_pretrained(
157
+ "mistralai/Mistral-7B-v0.1", *args, **kwargs
158
+ )
159
+ self.tokenizer.add_special_tokens({"pad_token": "<pad>"})
160
+ self.special_tokens_ids = {
161
+ token: id
162
+ for token, id in zip(
163
+ self.tokenizer.special_tokens_map.keys(), self.tokenizer.all_special_ids
164
+ )
165
+ }
166
+ self.max_length = max_length
167
+ self.pad_token_id = self.tokenizer.pad_token_id
168
+
169
+ def forward(self, text):
170
+ return self.tokenizer(
171
+ text,
172
+ return_tensors="pt",
173
+ return_attention_mask=False,
174
+ max_length=self.max_length,
175
+ truncation=True,
176
+ padding=True,
177
+ padding_side="right",
178
+ )
179
+
180
+ def convert_ids_to_tokens(self, ids):
181
+ return self.tokenizer.convert_ids_to_tokens(ids)
182
+
183
+ def decode(self, x):
184
+ return self.tokenizer.batch_decode(x)
185
+
186
+ def __len__(self):
187
+ return len(self.tokenizer)
188
+
189
+
190
+ class MultiHeadAttention(nn.Module):
191
+ def __init__(
192
+ self,
193
+ emb_size: int,
194
+ n_heads: int,
195
+ dropout: float = 0.0,
196
+ use_rotary_embeddings: bool = False,
197
+ bias_qkv: bool = False,
198
+ bias_out: bool = False,
199
+ ):
200
+ super().__init__()
201
+ self.emb_size = emb_size
202
+ self.n_heads = n_heads
203
+ assert (
204
+ self.emb_size % n_heads == 0
205
+ ), "Embedding size needs to be divisible by heads"
206
+
207
+ self.head_dim = emb_size // n_heads
208
+
209
+ self.use_rotary_embeddings = use_rotary_embeddings
210
+ if self.use_rotary_embeddings:
211
+ self.rotary_embed = RotaryEmbedding(self.head_dim)
212
+
213
+ self.qkv = nn.Linear(emb_size, emb_size * 3, bias=bias_qkv)
214
+ self.dropout = nn.Dropout(dropout)
215
+ self.out = nn.Linear(emb_size, emb_size, bias=bias_out)
216
+
217
+ self.scaling = self.head_dim**-0.5
218
+
219
+ def forward(self, x: Tensor, att_mask: Tensor = None):
220
+ qkv = self.qkv(x).chunk(3, dim=-1)
221
+ q, k, v = map(
222
+ lambda t: t.reshape(x.shape[0], -1, self.n_heads, self.head_dim).transpose(
223
+ 1, 2
224
+ ),
225
+ qkv,
226
+ ) # [batch_size, n_heads, seq_len, head_dim]
227
+
228
+ if self.use_rotary_embeddings:
229
+ q, k = self.rotary_embed(q), self.rotary_embed(k)
230
+
231
+ dots = (
232
+ torch.matmul(q, k.transpose(-1, -2)) * self.scaling
233
+ ) # [batch_size, n_heads, seq_len, seq_len]
234
+
235
+ if att_mask is not None:
236
+ dots = dots + att_mask
237
+
238
+ attn = self.dropout(torch.softmax(dots, dim=-1))
239
+ out = (
240
+ torch.matmul(attn, v).transpose(1, 2).reshape(x.shape[0], -1, self.emb_size)
241
+ )
242
+ out = self.out(out)
243
+
244
+ return out
245
+
246
+
247
+ class LLaMADecoderLayer(nn.Module):
248
+ def __init__(
249
+ self,
250
+ emb_size: int,
251
+ n_heads: int,
252
+ dropout: float,
253
+ ) -> None:
254
+ super().__init__()
255
+ self.emb_size = emb_size
256
+ self.multihead_attn = MultiHeadDispatch(
257
+ dim_model=emb_size,
258
+ num_heads=n_heads,
259
+ attention=ScaledDotProduct(
260
+ dropout=dropout,
261
+ ),
262
+ bias=(False, False, False, False),
263
+ use_rotary_embeddings=True,
264
+ )
265
+ self.rmsnorm1 = nn.RMSNorm(emb_size, eps=1e-9)
266
+ self.rmsnorm2 = nn.RMSNorm(emb_size, eps=1e-9)
267
+ self.swiglu = SwiGLU(emb_size)
268
+ self.n_heads = n_heads
269
+
270
+ def forward(self, in_tuple) -> Tensor:
271
+ """
272
+ Args:
273
+ in_tuple (tuple[Tensor, Tensor, Tensor]): tuple, containing 3 tensors:
274
+ x (Tensor): input tensor (bs, seq_len, dim)
275
+ attn_mask (Tensor): attention mask (seq_len, seq_len)
276
+ padding_mask (Tensor): padding mask (bs, seq_len)
277
+
278
+ Returns:
279
+ Tensor: output tensor
280
+ """
281
+ assert len(in_tuple) == 2, "input tuple must have 2 elements"
282
+ x, mask = in_tuple
283
+
284
+ x = self.multihead_attn(self.rmsnorm1(x), att_mask=mask) + x
285
+ return self.swiglu(self.rmsnorm2(x)) + x, mask
286
+
287
+
288
+ class CustomAttentionLLaMaDecoder(LLaMADecoderLayer):
289
+ def __init__(
290
+ self,
291
+ emb_size: int,
292
+ n_heads: int,
293
+ dropout: float,
294
+ ) -> None:
295
+ super().__init__(emb_size, n_heads, dropout)
296
+ self.multihead_attn = MultiHeadAttention(
297
+ emb_size=emb_size,
298
+ n_heads=n_heads,
299
+ bias_qkv=False,
300
+ bias_out=False,
301
+ use_rotary_embeddings=True,
302
+ dropout=dropout,
303
+ )
304
+ self.rmsnorm1 = RMSNorm(emb_size, eps=1e-9)
305
+ self.rmsnorm2 = RMSNorm(emb_size, eps=1e-9)
306
+
307
+
308
+ class LLaMaBase(nn.Module):
309
+ def __init__(
310
+ self,
311
+ embed_dim: int = 512,
312
+ n_layers: int = 2,
313
+ n_heads: int = 8,
314
+ dropout: int = 0.0,
315
+ n_chckpnt_segments: int = 1,
316
+ tokenizer=MistralTokenizer(),
317
+ **kwargs,
318
+ ):
319
+ """
320
+ Args:
321
+ n_feats (int): number of input features.
322
+ n_class (int): number of classes.
323
+ fc_hidden (int): number of hidden features.
324
+ """
325
+ super().__init__()
326
+
327
+ self.tokenizer = tokenizer
328
+ self.vocab_len = len(tokenizer)
329
+ self.n_heads = n_heads
330
+ self.dropout = dropout
331
+ self.n_layers = n_layers
332
+ self.embed_dim = embed_dim
333
+ self.n_segments = n_chckpnt_segments
334
+
335
+ self.embed = nn.Embedding(
336
+ self.vocab_len, embed_dim, padding_idx=self.tokenizer.pad_token_id
337
+ )
338
+ self.head = nn.Linear(embed_dim, self.vocab_len, bias=False)
339
+
340
+ def forward(self, src: Tensor, attn_mask: Tensor, pad_mask: Tensor, **batch):
341
+ """
342
+ Model forward method.
343
+
344
+ Args:
345
+ tokenized (Tensor): input text. shape: (batch_size, seq_len)
346
+ Returns:
347
+ output (dict): output dict containing logits.
348
+ """
349
+
350
+ raise NotImplementedError
351
+
352
+ def __str__(self):
353
+ """
354
+ Model prints with the number of parameters.
355
+ """
356
+ all_parameters = sum([p.numel() for p in self.parameters()])
357
+ trainable_parameters = sum(
358
+ [p.numel() for p in self.parameters() if p.requires_grad]
359
+ )
360
+ embedding_parameters = sum([p.numel() for p in self.embed.parameters()])
361
+
362
+ result_info = super().__str__()
363
+ result_info = result_info + f"\nAll parameters: {all_parameters}"
364
+ result_info = result_info + f"\nTrainable parameters: {trainable_parameters}"
365
+ result_info = (
366
+ result_info
367
+ + f"\nWithout embedding: {trainable_parameters - embedding_parameters}"
368
+ )
369
+
370
+ return result_info
371
+
372
+
373
+ class CustomAttentionLLaMa(LLaMaBase):
374
+ def __init__(
375
+ self,
376
+ embed_dim: int = 512,
377
+ n_layers: int = 2,
378
+ n_heads: int = 8,
379
+ dropout: int = 0.0,
380
+ n_chckpnt_segments: int = 1,
381
+ tokenizer=MistralTokenizer(),
382
+ **kwargs,
383
+ ):
384
+ """
385
+ Args:
386
+ n_feats (int): number of input features.
387
+ n_class (int): number of classes.
388
+ fc_hidden (int): number of hidden features.
389
+ """
390
+ super().__init__(
391
+ embed_dim,
392
+ n_layers,
393
+ n_heads,
394
+ dropout,
395
+ n_chckpnt_segments,
396
+ tokenizer,
397
+ )
398
+
399
+ self.decoders = nn.Sequential(
400
+ *[
401
+ CustomAttentionLLaMaDecoder(
402
+ emb_size=embed_dim, n_heads=self.n_heads, dropout=dropout
403
+ )
404
+ for _ in range(n_layers)
405
+ ]
406
+ )
407
+ self.rmsnorm = RMSNorm(embed_dim, eps=1e-9)
408
+
409
+ def forward(self, src: Tensor, attn_mask: Tensor, pad_mask: Tensor, **batch):
410
+ """
411
+ Model forward method.
412
+
413
+ Args:
414
+ tokenized (Tensor): input text. shape: (batch_size, seq_len)
415
+ Returns:
416
+ output (dict): output dict containing logits.
417
+ """
418
+ x = self.embed(src) # embeds shape: [batch_size, seq_len, embed_dim]
419
+ sizes = x.shape
420
+ mask = maybe_merge_masks(
421
+ attn_mask, pad_mask, sizes[0], sizes[1], self.n_heads
422
+ ).view(x.shape[0], self.n_heads, sizes[1], sizes[1])
423
+ x, _ = checkpoint_sequential(self.decoders, self.n_segments, input=(x, mask))
424
+ # for decoder in self.decoders:
425
+ # x, _, _ = decoder((x, attn_mask, pad_mask))
426
+
427
+ logits = self.head(self.rmsnorm(x))
428
+ return {
429
+ "logits": logits.permute(0, 2, 1)
430
+ } # logits shape: [batch_size, vocab_len, seq_len]
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6380bd512c40cdd9705099299688b1b4965a8da9da94f8f9d4b29a5b3ac5bf06
3
+ size 3161813608