crumb commited on
Commit
523bf1c
1 Parent(s): f0d115f

Upload model

Browse files
config.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "activation_function": "silu",
3
+ "architectures": [
4
+ "PlusModelForCausalLM"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_nano.NanoConfig",
8
+ "AutoModelForCausalLM": "modeling_nano.PlusModelForCausalLM"
9
+ },
10
+ "bos_token_id": 1,
11
+ "combined_qkv": true,
12
+ "eos_token_id": 2,
13
+ "expanded_lm_head_size": 8192,
14
+ "expanded_wte_size": 8192,
15
+ "experimental_full_adaption_rank": null,
16
+ "ffn": "llamalike",
17
+ "full_adaptation_has_pre_proj": false,
18
+ "full_adaptation_type": "no",
19
+ "hidden_size": 768,
20
+ "initializer_range": 0.02,
21
+ "intermediate_size": 3072,
22
+ "kv_hidden_size": null,
23
+ "layer_norm_epsilon": 1e-06,
24
+ "layernorm": "llamarmsnorm",
25
+ "lm_head_bias": false,
26
+ "lm_head_projection_bias": false,
27
+ "max_position_embeddings": 2048,
28
+ "model_type": "nano",
29
+ "num_attention_heads": 12,
30
+ "num_hidden_layers": 10,
31
+ "pre_proj_dim": null,
32
+ "residual_alpha": false,
33
+ "rope_scaling": null,
34
+ "rope_theta": 10000,
35
+ "torch_dtype": "bfloat16",
36
+ "transformers_version": "4.36.2",
37
+ "use_bias": false,
38
+ "use_cache": true,
39
+ "vocab_size": 32000
40
+ }
configuration_nano.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ from typing import Any, List, Mapping, Optional
3
+
4
+ from transformers import PreTrainedTokenizer, TensorType, is_torch_available
5
+ from transformers.configuration_utils import PretrainedConfig
6
+ from transformers.utils import logging
7
+
8
+ logger = logging.get_logger(__name__)
9
+
10
+
11
+ class NanoConfig(PretrainedConfig):
12
+ model_type = "nano"
13
+ keys_to_ignore_at_inference = ["past_key_values"]
14
+ attribute_map = {
15
+ "hidden_size": "hidden_size",
16
+ "max_position_embeddings": "max_position_embeddings",
17
+ "num_attention_heads": "num_attention_heads",
18
+ "num_hidden_layers": "num_hidden_layers",
19
+ }
20
+
21
+ def __init__(
22
+ self,
23
+ vocab_size=32000,
24
+ max_position_embeddings=2048,
25
+ expanded_wte_size=None,
26
+ expanded_lm_head_size=None,
27
+ hidden_size=768,
28
+ kv_hidden_size=None, # in case you want to use cross-attention
29
+ num_hidden_layers=10,
30
+ num_attention_heads=12,
31
+ intermediate_size=None,
32
+ activation_function="silu",
33
+ layer_norm_epsilon=1e-6,
34
+ initializer_range=0.02,
35
+ use_cache=True,
36
+ bos_token_id=1,
37
+ eos_token_id=2,
38
+ combined_qkv=True,
39
+ use_bias=False,
40
+ lm_head_projection_bias=False,
41
+ lm_head_bias=False,
42
+ layernorm="llamarmsnorm", # layernorm, llamarmsnorm
43
+ rope_scaling=None,
44
+ rope_theta=10000,
45
+ ffn="llama-like",
46
+ experimental_full_adaption_rank = None, # 8
47
+ full_adaptation_has_pre_proj = True,
48
+ pre_proj_dim = 1536,
49
+ full_adaptation_type="no", # "lora", "no", "linear", "linear-r", "linear-ra"
50
+ tie_word_embeddings=False,
51
+ residual_alpha=False,
52
+ **kwargs,
53
+ ):
54
+ self.residual_alpha = residual_alpha
55
+ self.pre_proj_dim = pre_proj_dim
56
+ self.full_adaptation_has_pre_proj = full_adaptation_has_pre_proj
57
+ self.full_adaptation_type = full_adaptation_type
58
+ self.tie_word_embeddings = tie_word_embeddings
59
+ self.experimental_full_adaption_rank = experimental_full_adaption_rank
60
+ self.ffn = ffn
61
+ self.rope_theta=rope_theta
62
+ self.layernorm = layernorm
63
+ self.rope_scaling=rope_scaling
64
+ self.lm_head_projection_bias = lm_head_projection_bias
65
+ self.kv_hidden_size = kv_hidden_size
66
+ self.lm_head_bias = lm_head_bias
67
+ self.use_bias = use_bias
68
+ self.expanded_wte_size = expanded_wte_size
69
+ self.expanded_lm_head_size = expanded_lm_head_size
70
+ self.combined_qkv = combined_qkv
71
+ self.vocab_size = vocab_size
72
+ self.max_position_embeddings = max_position_embeddings
73
+ self.hidden_size = hidden_size
74
+ self.num_hidden_layers = num_hidden_layers
75
+ self.num_attention_heads = num_attention_heads
76
+ self.intermediate_size = (
77
+ intermediate_size if intermediate_size is not None else hidden_size * 4
78
+ )
79
+ self.activation_function = activation_function
80
+ self.layer_norm_epsilon = layer_norm_epsilon
81
+ self.initializer_range = initializer_range
82
+
83
+ self.use_cache = use_cache
84
+
85
+ self.bos_token_id = bos_token_id
86
+ self.eos_token_id = eos_token_id
87
+
88
+ super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
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.36.2"
6
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c5ca3f770208ce4f3cd1e358482ca79f38018aedb49a65f091b9794594f44bda
3
+ size 738239160
modeling_nano.py ADDED
@@ -0,0 +1,701 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import random
4
+ import warnings
5
+ from dataclasses import dataclass
6
+ from typing import Optional, Tuple, Union
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ import torch.utils.checkpoint
12
+ from einops import repeat
13
+ from torch import nn
14
+ from torch.cuda.amp import autocast
15
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
16
+ from transformers.activations import ACT2FN
17
+ from transformers.modeling_outputs import (
18
+ BaseModelOutputWithPastAndCrossAttentions,
19
+ CausalLMOutputWithCrossAttentions, QuestionAnsweringModelOutput,
20
+ SequenceClassifierOutputWithPast, TokenClassifierOutput)
21
+ from transformers.modeling_utils import PreTrainedModel, SequenceSummary
22
+ from transformers.utils import (ModelOutput, logging)
23
+ from transformers.utils.model_parallel_utils import (assert_device_map,
24
+ get_device_map)
25
+
26
+ from .configuration_nano import NanoConfig
27
+ from transformers.models.llama.modeling_llama import LlamaRMSNorm, LlamaDynamicNTKScalingRotaryEmbedding, LlamaRotaryEmbedding, LlamaLinearScalingRotaryEmbedding
28
+
29
+ def rotate_half(x):
30
+ """Rotates half the hidden dims of the input."""
31
+ x1 = x[..., : x.shape[-1] // 2]
32
+ x2 = x[..., x.shape[-1] // 2 :]
33
+ return torch.cat((-x2, x1), dim=-1)
34
+
35
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
36
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
37
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
38
+ q_embed = (q * cos) + (rotate_half(q) * sin)
39
+ k_embed = (k * cos) + (rotate_half(k) * sin)
40
+ return q_embed, k_embed
41
+
42
+ class NanoAttention(nn.Module):
43
+ def __init__(self, config):
44
+ super().__init__()
45
+ self.config = config
46
+ self.head_dim = config.hidden_size // config.num_attention_heads
47
+ assert (
48
+ self.head_dim * config.num_attention_heads == config.hidden_size
49
+ ), "d_model must be divisible by n_head"
50
+ self.use_bias = config.use_bias
51
+
52
+ if not config.combined_qkv or config.kv_hidden_size is not None:
53
+ self.query = nn.Linear(
54
+ config.hidden_size, config.hidden_size, bias=self.use_bias
55
+ )
56
+ self.key = nn.Linear(
57
+ config.hidden_size
58
+ if not config.kv_hidden_size
59
+ else config.kv_hidden_size,
60
+ config.hidden_size,
61
+ bias=self.use_bias,
62
+ )
63
+ self.value = nn.Linear(
64
+ config.hidden_size
65
+ if not config.kv_hidden_size
66
+ else config.kv_hidden_size,
67
+ config.hidden_size,
68
+ bias=self.use_bias,
69
+ )
70
+ else:
71
+ self.qkv = nn.Linear(
72
+ config.hidden_size, config.hidden_size * 3, bias=self.use_bias
73
+ )
74
+ self.out = nn.Linear(config.hidden_size, config.hidden_size, bias=self.use_bias)
75
+ self._init_rope()
76
+
77
+ def _init_rope(self):
78
+ if self.config.rope_scaling is None:
79
+ self.rotary_emb = LlamaRotaryEmbedding(
80
+ self.head_dim,
81
+ max_position_embeddings=self.config.max_position_embeddings,
82
+ base=self.config.rope_theta,
83
+ )
84
+ else:
85
+ scaling_type = self.config.rope_scaling["type"]
86
+ scaling_factor = self.config.rope_scaling["factor"]
87
+ if scaling_type == "linear":
88
+ self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
89
+ self.head_dim,
90
+ max_position_embeddings=self.config.max_position_embeddings,
91
+ scaling_factor=scaling_factor,
92
+ base=self.config.rope_theta,
93
+ )
94
+ elif scaling_type == "dynamic":
95
+ self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
96
+ self.head_dim,
97
+ max_position_embeddings=self.max_position_embeddings,
98
+ scaling_factor=scaling_factor,
99
+ base=self.config.rope_theta,
100
+ )
101
+ else:
102
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
103
+
104
+ def forward(self, x0, x1=None, causal=False, mask=None, position_ids=None, use_cache=True, layer_past=None):
105
+ batch_size = x0.size(0)
106
+
107
+ def split_heads(x):
108
+ return x.view(
109
+ batch_size, -1, self.config.num_attention_heads, self.head_dim
110
+ ).transpose(1, 2)
111
+
112
+ if not self.config.combined_qkv:
113
+ q = split_heads(self.query(x0))
114
+ k = split_heads(self.key(x1) if x1 is not None else self.key(x0))
115
+ v = split_heads(
116
+ self.value(x1 if x1 is not None else x0)
117
+ )
118
+ else:
119
+ q, k, v = self.qkv(x0).chunk(3,-1)
120
+ q = split_heads(q)
121
+ k = split_heads(k)
122
+ v = split_heads(v)
123
+
124
+ if layer_past is not None:
125
+ past_key, past_value = layer_past
126
+ k = torch.cat((past_key, k), dim=-2)
127
+ v = torch.cat((past_value, v), dim=-2)
128
+
129
+ cos, sin = self.rotary_emb(v, seq_len=v.shape[-2])
130
+ if self.config.full_adaptation_type != "no":
131
+ position_ids = position_ids.repeat_interleave(x0.shape[1]//position_ids.shape[-1],dim=1)
132
+ q, k = apply_rotary_pos_emb(q, k, cos, sin, position_ids)
133
+
134
+ if use_cache is True:
135
+ present = (k,v)
136
+ else:
137
+ present = None
138
+
139
+ attn_output = F.scaled_dot_product_attention(
140
+ q, k, v, attn_mask=None, dropout_p=0.0, is_causal=causal
141
+ )
142
+ attn_output = (
143
+ attn_output.transpose(1, 2)
144
+ .contiguous()
145
+ .view(batch_size, -1, self.config.hidden_size)
146
+ )
147
+ return self.out(attn_output), present
148
+
149
+
150
+ class NanoGLU(nn.Module):
151
+ def __init__(self, config):
152
+ super().__init__()
153
+ self.config = config
154
+ self.gate_proj = nn.Linear(
155
+ config.hidden_size, config.intermediate_size, bias=False
156
+ )
157
+ self.up_proj = nn.Linear(
158
+ config.hidden_size, config.intermediate_size, bias=False
159
+ )
160
+ self.down_proj = nn.Linear(
161
+ config.intermediate_size, config.hidden_size, bias=False
162
+ )
163
+ self.act_fn = ACT2FN[config.activation_function]
164
+
165
+ def forward(self, x):
166
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
167
+
168
+
169
+ class NanoBlock(nn.Module):
170
+ def __init__(self, config):
171
+ super().__init__()
172
+ self.config = config
173
+ self.attn = NanoAttention(config)
174
+ self.ffn = NanoGLU(config)
175
+
176
+ ln_class = LlamaRMSNorm if config.layernorm=="llamarmsnorm" else nn.LayerNorm
177
+ self.ln1 = ln_class(config.hidden_size, eps=config.layer_norm_epsilon)
178
+ self.ln2 = ln_class(config.hidden_size, eps=config.layer_norm_epsilon)
179
+
180
+ if config.residual_alpha:
181
+ self.ffn_a = nn.Parameter(torch.tensor(0.))
182
+ self.attn_a = nn.Parameter(torch.tensor(0.))
183
+ else:
184
+ self.ffn_a = 1
185
+ self.attn_a = 1
186
+ def forward(self, x, mask=None, position_ids=None, use_cache=True, layer_past=None):
187
+
188
+ if self.config.ffn == "llamalike":
189
+ residual = x
190
+ x = self.ln1(x)
191
+ attn_out, attn_outs = self.attn(x, causal=True, mask=mask, position_ids=position_ids, use_cache=use_cache, layer_past=layer_past)
192
+ x = residual + attn_out * self.attn_a
193
+
194
+ residual = x
195
+ x = self.ln2(x)
196
+ x = self.ffn(x)
197
+ x = residual + x * self.ffn_a
198
+ else: # ffn == "parallel"
199
+ attn_in = self.ln1(x)
200
+ ffn_in = self.ln2(x)
201
+
202
+ attn_out, attn_outs = self.attn(attn_in, causal=True, mask=mask, position_ids=position_ids, use_cache=use_cache, layer_past=layer_past)
203
+ ffn_out = self.ffn(ffn_in)
204
+
205
+ x = x + attn_out * self.attn_a + ffn_out * self.ffn_a
206
+
207
+ if not use_cache: attn_outs = None
208
+ return (x, attn_outs)
209
+
210
+
211
+
212
+ class NanoPreTrainedModel(PreTrainedModel):
213
+ config_class = NanoConfig
214
+ base_model_prefix = "transformer"
215
+ is_parallelizable = False
216
+ supports_gradient_checkpointing = True
217
+ _no_split_modules = ["NanoBlock"]
218
+ _skip_keys_device_placement = "past_key_values"
219
+
220
+ def __init__(self, *inputs, **kwargs):
221
+ super().__init__(*inputs, **kwargs)
222
+
223
+ def _init_weights(self, module):
224
+ """Initialize the weights."""
225
+ if isinstance(module, (nn.Linear)):
226
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
227
+ if module.bias is not None:
228
+ module.bias.data.zero_()
229
+ elif isinstance(module, nn.Embedding):
230
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
231
+ if module.padding_idx is not None:
232
+ module.weight.data[module.padding_idx].zero_()
233
+ elif isinstance(module, nn.LayerNorm):
234
+ module.bias.data.zero_()
235
+ module.weight.data.fill_(1.0)
236
+
237
+ def _set_gradient_checkpointing(self, module, value=False):
238
+ if isinstance(module, NanoModel):
239
+ module.gradient_checkpointing = value
240
+
241
+ class Split(nn.Module):
242
+ def __init__(self, splits):
243
+ super().__init__()
244
+ self.splits=splits
245
+ def forward(self, x):
246
+ bs, tokens, _ = x.shape
247
+ # print("SPLIT X0 SHAPE", x.shape)
248
+ x = x.view(bs, tokens, self.splits, -1)
249
+ x = x.permute(0, 1, 2, 3).reshape(bs, tokens * self.splits, -1)
250
+ # print("SPLIT X1 SHAPE", x.shape)
251
+ return x
252
+
253
+ class Recombine(nn.Module):
254
+ def __init__(self, splits):
255
+ super().__init__()
256
+ self.splits = splits
257
+ def forward(self, x):
258
+ bs, _, _ = x.shape
259
+ # print("RECOMBINE X SHAPE", x.shape)
260
+ tokens = x.shape[1] // self.splits
261
+ # print("RECOMBINE TOKENS", tokens, bs)
262
+ x = x.view(bs, tokens, -1)
263
+ # print("RECOMBINE X1.SHAPE", x.shape)
264
+ return x
265
+
266
+ class Residual(nn.Module):
267
+ def __init__(self, module, a=None):
268
+ super().__init__()
269
+ self.module = module
270
+ self.a = nn.Parameter(torch.tensor(a, dtype=torch.bfloat16)) if a is not None else None
271
+ def forward(self, x):
272
+ return self.module(x) * (self.a if self.a is not None else 1) + x
273
+
274
+ class LoRA(nn.Module):
275
+ def __init__(self, d, r, a=1):
276
+ super().__init__()
277
+ self.fn_i = nn.Linear(d, r)
278
+ self.fn_o = nn.Linear(r, d)
279
+ self.a = nn.Parameter(torch.tensor(a, dtype=self.fn_i.weight.dtype))
280
+ def forward(self, x):
281
+ return self.fn_o(self.fn_i(x)) * self.a + x
282
+ def get_delta_w(self):
283
+ return torch.mm(self.fn_o.weight, self.fn_i.weight) * self.a
284
+
285
+ class NanoModel(NanoPreTrainedModel):
286
+ def __init__(self, config):
287
+ super().__init__(config)
288
+ ln_class = LlamaRMSNorm if config.layernorm=="llamarmsnorm" else nn.LayerNorm
289
+
290
+ if config.full_adaptation_type == "no":
291
+ if config.expanded_wte_size is not None:
292
+ self.wte = nn.Sequential(
293
+ nn.Embedding(config.vocab_size, config.expanded_wte_size),
294
+ nn.Linear(config.expanded_wte_size, config.hidden_size),
295
+ )
296
+ else:
297
+ self.wte = nn.Embedding(config.vocab_size, config.hidden_size)
298
+ else:
299
+ assert config.expanded_wte_size is not None, "experimental full adaptation of token embeddings requires expanded_wte_size to be set"
300
+ # self.wte = nn.Sequential(
301
+ # nn.Embedding(config.vocab_size, config.expanded_wte_size),
302
+ # LoRA(config.expanded_wte_size, config.experimental_full_adaption_rank),
303
+ # Split(config.expanded_wte_size//config.hidden_size)
304
+ # )
305
+ # print("going w/ adaptation")
306
+ self.d_0 = config.expanded_wte_size if (config.full_adaptation_has_pre_proj == False) else config.pre_proj_dim
307
+ # print("d_0", d_0)
308
+ self.wte = nn.Sequential(
309
+ nn.Embedding(config.vocab_size, config.expanded_wte_size),
310
+ (
311
+ nn.Linear(config.expanded_wte_size, config.pre_proj_dim) if config.full_adaptation_has_pre_proj else nn.Identity()
312
+ ),
313
+ (
314
+ LoRA(self.d_0, config.experimental_full_adaption_rank)
315
+ if config.full_adaptation_type == "lora" else
316
+ nn.Linear(self.d_0, self.d_0)
317
+ if config.full_adaptation_type == "linear" else
318
+ Residual(
319
+ nn.Linear(self.d_0, self.d_0)
320
+ )
321
+ if config.full_adaptation_type == "linear-r" else
322
+ Residual(
323
+ nn.Linear(self.d_0, self.d_0), 1
324
+ )
325
+ if config.full_adaptation_type == "linear-ra" else
326
+ nn.Identity()
327
+ ),
328
+ Split(self.d_0//config.hidden_size)
329
+ )
330
+ self.h = nn.ModuleList(
331
+ [NanoBlock(config) for i in range(config.num_hidden_layers)]
332
+ )
333
+ self.ln_f = ln_class(config.hidden_size, eps=config.layer_norm_epsilon)
334
+ self.model_parallel = False
335
+ self.device_map = None
336
+ self.gradient_checkpointing = False
337
+ self.post_init()
338
+
339
+ def get_input_embeddings(self):
340
+ return self.wte[0] if self.config.expanded_wte_size is not None else self.wte
341
+
342
+ def set_input_embeddings(self, new_embeddings):
343
+ if self.config.expanded_wte_size is not None:
344
+ self.wte[0] = new_embeddings
345
+ else:
346
+ self.wte = new_embeddings
347
+
348
+ def forward(
349
+ self,
350
+ input_ids: Optional[torch.LongTensor] = None,
351
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
352
+ attention_mask: Optional[torch.FloatTensor] = None,
353
+ token_type_ids: Optional[torch.LongTensor] = None,
354
+ position_ids: Optional[torch.LongTensor] = None,
355
+ head_mask: Optional[torch.FloatTensor] = None,
356
+ inputs_embeds: Optional[torch.FloatTensor] = None,
357
+ encoder_hidden_states: Optional[torch.Tensor] = None,
358
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
359
+ use_cache: Optional[bool] = None,
360
+ output_attentions: Optional[bool] = None,
361
+ output_hidden_states: Optional[bool] = None,
362
+ return_dict: Optional[bool] = None,
363
+ ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
364
+ # soooo not all of the params are able to be used, since I just copied this framework from modeling_gpt2
365
+
366
+ output_attentions = (
367
+ output_attentions
368
+ if output_attentions is not None
369
+ else self.config.output_attentions
370
+ )
371
+ output_hidden_states = (
372
+ output_hidden_states
373
+ if output_hidden_states is not None
374
+ else self.config.output_hidden_states
375
+ )
376
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
377
+ return_dict = (
378
+ return_dict if return_dict is not None else self.config.use_return_dict
379
+ )
380
+ if input_ids is not None and inputs_embeds is not None:
381
+ raise ValueError(
382
+ "You cannot specify both input_ids and inputs_embeds at the same time"
383
+ )
384
+ elif input_ids is not None:
385
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
386
+ input_shape = input_ids.size()
387
+ input_ids = input_ids.view(-1, input_shape[-1])
388
+ batch_size = input_ids.shape[0]
389
+ elif inputs_embeds is not None:
390
+ input_shape = inputs_embeds.size()[:-1]
391
+ batch_size = inputs_embeds.shape[0]
392
+ else:
393
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
394
+
395
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
396
+
397
+ if token_type_ids is not None:
398
+ token_type_ids = token_type_ids.view(-1, input_shape[-1])
399
+ if position_ids is not None:
400
+ position_ids = position_ids.view(-1, input_shape[-1])
401
+
402
+ if past_key_values is None:
403
+ past_length = 0
404
+ past_key_values = tuple([None] * len(self.h))
405
+ else:
406
+ past_length = past_key_values[0][0].size(-2)
407
+ if position_ids is None:
408
+ position_ids = torch.arange(
409
+ past_length,
410
+ input_shape[-1] + past_length,
411
+ dtype=torch.long,
412
+ device=device,
413
+ )
414
+ position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
415
+
416
+ if attention_mask is not None:
417
+ if batch_size <= 0:
418
+ raise ValueError("batch_size has to be defined and > 0")
419
+ attention_mask = attention_mask.view(batch_size, -1)
420
+ attention_mask = attention_mask[:, None, None, :]
421
+ attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
422
+ attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
423
+
424
+ if self.config.add_cross_attention and encoder_hidden_states is not None:
425
+ (
426
+ encoder_batch_size,
427
+ encoder_sequence_length,
428
+ _,
429
+ ) = encoder_hidden_states.size()
430
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
431
+ if encoder_attention_mask is None:
432
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
433
+ encoder_attention_mask = self.invert_attention_mask(encoder_attention_mask)
434
+ else:
435
+ encoder_attention_mask = None
436
+
437
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
438
+
439
+ if inputs_embeds is None:
440
+ inputs_embeds = self.wte(input_ids)
441
+ # print("inputs embeds shape", inputs_embeds.shape)
442
+
443
+ hidden_states = inputs_embeds
444
+
445
+ if token_type_ids is not None:
446
+ token_type_embeds = self.wte(token_type_ids)
447
+ hidden_states = hidden_states + token_type_embeds
448
+
449
+ # output_shape = (-1,) + input_shape[1:] + (hidden_states.size(-1),)
450
+ output_shape = (-1,) + (hidden_states.shape[1],) + (hidden_states.size(-1),)
451
+ # print(output_shape, "output shape")
452
+
453
+ if self.gradient_checkpointing and self.training:
454
+ if use_cache:
455
+ # logger.warning_once(
456
+ # "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
457
+ # )
458
+ use_cache = False
459
+
460
+ presents = () if use_cache else None
461
+ all_self_attentions = () if output_attentions else None
462
+ all_cross_attentions = (
463
+ () if output_attentions and self.config.add_cross_attention else None
464
+ )
465
+ all_hidden_states = () if output_hidden_states else None
466
+ for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
467
+ if self.model_parallel:
468
+ torch.cuda.set_device(hidden_states.device)
469
+ if layer_past is not None:
470
+ layer_past = tuple(
471
+ past_state.to(hidden_states.device)
472
+ for past_state in layer_past
473
+ )
474
+ if attention_mask is not None:
475
+ attention_mask = attention_mask.to(hidden_states.device)
476
+ if isinstance(head_mask, torch.Tensor):
477
+ head_mask = head_mask.to(hidden_states.device)
478
+ if output_hidden_states:
479
+ all_hidden_states = all_hidden_states + (hidden_states,)
480
+ outputs = block(hidden_states, mask=attention_mask, position_ids=position_ids, use_cache=use_cache, layer_past=layer_past)
481
+ hidden_states = outputs[0]
482
+ if use_cache == True:
483
+ presents = presents + (outputs[1],)
484
+
485
+ hidden_states = self.ln_f(hidden_states)
486
+ hidden_states = hidden_states.view(output_shape)
487
+ if output_hidden_states:
488
+ all_hidden_states = all_hidden_states + (hidden_states,)
489
+
490
+ if not return_dict:
491
+ return tuple(
492
+ v
493
+ for v in [hidden_states, None, all_hidden_states, None, None]
494
+ if v is not None
495
+ )
496
+
497
+ return BaseModelOutputWithPastAndCrossAttentions(
498
+ last_hidden_state=hidden_states,
499
+ past_key_values=presents,
500
+ hidden_states=all_hidden_states,
501
+ attentions=None,
502
+ cross_attentions=None,
503
+ )
504
+
505
+ class NanoModelForCausalLM(NanoPreTrainedModel):
506
+ _tied_weights_keys = ["lm_head.weight"]
507
+ def __init__(self, config):
508
+ super().__init__(config)
509
+ self.transformer = NanoModel(config)
510
+ if config.full_adaptation_type == "no":
511
+ if (config.expanded_lm_head_size is not None):
512
+ self.lm_head = nn.Sequential(
513
+ nn.Linear(
514
+ config.hidden_size, config.expanded_lm_head_size, bias=config.lm_head_projection_bias
515
+ ),
516
+ nn.Linear(
517
+ config.expanded_lm_head_size, config.vocab_size, bias=config.lm_head_bias
518
+ ),
519
+ )
520
+ else:
521
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size)
522
+ else:
523
+ d_0 = config.expanded_lm_head_size if (not config.full_adaptation_has_pre_proj) else config.pre_proj_dim
524
+ self.lm_head = nn.Sequential(
525
+ Recombine(d_0//config.hidden_size),
526
+ nn.Identity() if not config.full_adaptation_has_pre_proj else nn.Linear(d_0, config.expanded_lm_head_size),
527
+ (
528
+ LoRA(config.expanded_lm_head_size, config.experimental_full_adaption_rank)
529
+ if config.full_adaptation_type == "lora" else
530
+ nn.Linear(config.expanded_lm_head_size, config.expanded_lm_head_size)
531
+ if config.full_adaptation_type == "linear" else
532
+ Residual(
533
+ nn.Linear(config.expanded_lm_head_size, config.expanded_lm_head_size)
534
+ )
535
+ if config.full_adaptation_type == "linear-r" else
536
+ Residual(
537
+ nn.Linear(config.expanded_lm_head_size, config.expanded_lm_head_size), 1
538
+ )
539
+ if config.full_adaptation_type == "linear-ra" else
540
+ nn.Identity()
541
+ ),
542
+
543
+ nn.Linear(config.expanded_lm_head_size, config.vocab_size)
544
+ )
545
+ self.model_parallel = False
546
+ self.device_map = None
547
+ self.post_init()
548
+
549
+ def get_output_embeddings(self):
550
+ return self.lm_head if (self.config.experimental_full_adaption_rank is None and self.config.expanded_lm_head_size is None) else self.lm_head[-1]
551
+
552
+ def set_output_embeddings(self, new_embeddings):
553
+ self.lm_head = new_embeddings
554
+
555
+ def prepare_inputs_for_generation(
556
+ self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs
557
+ ):
558
+ token_type_ids = kwargs.get("token_type_ids", None)
559
+ # only last token for inputs_ids if past is defined in kwargs
560
+ if past_key_values:
561
+ input_ids = input_ids[:, -1].unsqueeze(-1)
562
+ if token_type_ids is not None:
563
+ token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
564
+
565
+ attention_mask = kwargs.get("attention_mask", None)
566
+ position_ids = kwargs.get("position_ids", None)
567
+
568
+ if attention_mask is not None and position_ids is None:
569
+ # create position_ids on the fly for batch generation
570
+ position_ids = attention_mask.long().cumsum(-1) - 1
571
+ position_ids.masked_fill_(attention_mask == 0, 1)
572
+ if past_key_values:
573
+ position_ids = position_ids[:, -1].unsqueeze(-1)
574
+ else:
575
+ position_ids = None
576
+
577
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
578
+ if inputs_embeds is not None and past_key_values is None:
579
+ model_inputs = {"inputs_embeds": inputs_embeds}
580
+ else:
581
+ model_inputs = {"input_ids": input_ids}
582
+
583
+ model_inputs.update(
584
+ {
585
+ "past_key_values": past_key_values,
586
+ "use_cache": kwargs.get("use_cache"),
587
+ "position_ids": position_ids,
588
+ "attention_mask": attention_mask,
589
+ "token_type_ids": token_type_ids,
590
+ }
591
+ )
592
+ return model_inputs
593
+
594
+ def forward(
595
+ self,
596
+ input_ids: Optional[torch.LongTensor] = None,
597
+ past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
598
+ attention_mask: Optional[torch.FloatTensor] = None,
599
+ token_type_ids: Optional[torch.LongTensor] = None,
600
+ position_ids: Optional[torch.LongTensor] = None,
601
+ head_mask: Optional[torch.FloatTensor] = None,
602
+ inputs_embeds: Optional[torch.FloatTensor] = None,
603
+ encoder_hidden_states: Optional[torch.Tensor] = None,
604
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
605
+ labels: Optional[torch.LongTensor] = None,
606
+ use_cache: Optional[bool] = None,
607
+ output_attentions: Optional[bool] = None,
608
+ output_hidden_states: Optional[bool] = None,
609
+ return_dict: Optional[bool] = None,
610
+ ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
611
+ r"""
612
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
613
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
614
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
615
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
616
+ """
617
+ return_dict = (
618
+ return_dict if return_dict is not None else self.config.use_return_dict
619
+ )
620
+
621
+ transformer_outputs = self.transformer(
622
+ input_ids,
623
+ past_key_values=past_key_values,
624
+ attention_mask=attention_mask,
625
+ token_type_ids=token_type_ids,
626
+ position_ids=position_ids,
627
+ head_mask=head_mask,
628
+ inputs_embeds=inputs_embeds,
629
+ encoder_hidden_states=encoder_hidden_states,
630
+ encoder_attention_mask=encoder_attention_mask,
631
+ use_cache=use_cache,
632
+ output_attentions=output_attentions,
633
+ output_hidden_states=output_hidden_states,
634
+ return_dict=return_dict,
635
+ )
636
+ hidden_states = transformer_outputs[0]
637
+ # print("Hidden states shape", hidden_states.shape)
638
+ if self.model_parallel:
639
+ torch.cuda.set_device(self.transformer.first_device)
640
+ hidden_states = hidden_states.to(self.lm_head.weight.device)
641
+
642
+ lm_logits = self.lm_head(hidden_states)
643
+
644
+ loss = None
645
+ if labels is not None:
646
+ # move labels to correct device to enable model parallelism
647
+ labels = labels.to(lm_logits.device)
648
+ # Shift so that tokens < n predict n
649
+ shift_logits = lm_logits[..., :-1, :].contiguous()
650
+ shift_labels = labels[..., 1:].contiguous()
651
+ # Flatten the tokens
652
+ loss_fct = CrossEntropyLoss()
653
+ loss = loss_fct(
654
+ shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1)
655
+ )
656
+
657
+ if not return_dict:
658
+ output = (lm_logits,) + transformer_outputs[1:]
659
+ return ((loss,) + output) if loss is not None else output
660
+
661
+ return CausalLMOutputWithCrossAttentions(
662
+ loss=loss,
663
+ logits=lm_logits,
664
+ past_key_values=transformer_outputs.past_key_values,
665
+ hidden_states=transformer_outputs.hidden_states,
666
+ attentions=transformer_outputs.attentions,
667
+ cross_attentions=transformer_outputs.cross_attentions,
668
+ )
669
+
670
+ @staticmethod
671
+ def _reorder_cache(
672
+ past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
673
+ ) -> Tuple[Tuple[torch.Tensor]]:
674
+ """
675
+ This function is used to re-order the `past_key_values` cache if [`~PreTrainedModel.beam_search`] or
676
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
677
+ beam_idx at every generation step.
678
+ """
679
+ return tuple(
680
+ tuple(
681
+ past_state.index_select(0, beam_idx.to(past_state.device))
682
+ for past_state in layer_past
683
+ )
684
+ for layer_past in past_key_values
685
+ )
686
+
687
+
688
+ class VTMModelForCausalLM(NanoModelForCausalLM):
689
+ _tied_weights_keys = ["lm_head.3.weight"]
690
+ def __init__(self, config):
691
+ super().__init__(config)
692
+
693
+ class VTMPreProjModelForCausalLM(NanoModelForCausalLM):
694
+ _tied_weights_keys = ["lm_head.3.weight"]
695
+ def __init__(self, config):
696
+ super().__init__(config)
697
+
698
+ class PlusModelForCausalLM(NanoModelForCausalLM):
699
+ _tied_weights_keys = ["lm_head.1.weight"]
700
+ def __init__(self, config):
701
+ super().__init__(config)