manjunath2n7 commited on
Commit
02c7640
·
verified ·
1 Parent(s): 04fa3af

updates for error: . in config and main file ( no trainable param)

Browse files
Files changed (1) hide show
  1. modeling_spin.py +62 -77
modeling_spin.py CHANGED
@@ -1,13 +1,13 @@
1
- from .configuration_spin import SpinConfig
2
  import math
3
  import torch
4
  import torch.nn as nn
5
  import torch.nn.functional as F
6
- from transformers import PreTrainedModel
7
  from transformers.modeling_outputs import CausalLMOutputWithPast
 
8
 
9
- class RMSNorm(nn.Module):
10
 
 
11
  def __init__(self, dim: int, eps: float = 1e-5):
12
  super().__init__()
13
  self.eps = eps
@@ -17,28 +17,18 @@ class RMSNorm(nn.Module):
17
  variance = x.pow(2).mean(-1, keepdim=True)
18
  return x * torch.rsqrt(variance + self.eps) * self.weight
19
 
 
20
  def precompute_freqs_cis(dim: int, max_seq_len: int, theta: float = 10000.0):
21
- freqs = 1.0 / (
22
- theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim)
23
- )
24
  t = torch.arange(max_seq_len, dtype=torch.float32)
25
  freqs = torch.outer(t, freqs)
26
- freqs_cos = torch.cos(freqs)
27
- freqs_sin = torch.sin(freqs)
28
- return freqs_cos, freqs_sin
29
-
30
-
31
- def apply_rotary_emb(
32
- xq: torch.Tensor,
33
- xk: torch.Tensor,
34
- freqs_cos: torch.Tensor,
35
- freqs_sin: torch.Tensor,
36
- ):
37
-
38
  xq_r, xq_i = xq.float().reshape(*xq.shape[:-1], -1, 2).unbind(-1)
39
  xk_r, xk_i = xk.float().reshape(*xk.shape[:-1], -1, 2).unbind(-1)
40
 
41
-
42
  freqs_cos = freqs_cos.unsqueeze(0).unsqueeze(2)
43
  freqs_sin = freqs_sin.unsqueeze(0).unsqueeze(2)
44
 
@@ -51,8 +41,8 @@ def apply_rotary_emb(
51
  xk_out = torch.stack([xk_out_r, xk_out_i], dim=-1).flatten(3)
52
  return xq_out.type_as(xq), xk_out.type_as(xk)
53
 
54
- class SwiGLU(nn.Module):
55
 
 
56
  def __init__(self, d_model: int, d_ff: int):
57
  super().__init__()
58
  self.w_gate = nn.Linear(d_model, d_ff, bias=False)
@@ -62,8 +52,8 @@ class SwiGLU(nn.Module):
62
  def forward(self, x: torch.Tensor) -> torch.Tensor:
63
  return self.w_down(F.silu(self.w_gate(x)) * self.w_up(x))
64
 
65
- class CausalSelfAttention(nn.Module):
66
 
 
67
  def __init__(self, config: SpinConfig):
68
  super().__init__()
69
  self.n_heads = config.n_heads
@@ -74,30 +64,17 @@ class CausalSelfAttention(nn.Module):
74
  self.v_proj = nn.Linear(config.d_model, config.d_model, bias=False)
75
  self.out_proj = nn.Linear(config.d_model, config.d_model, bias=False)
76
 
77
- mask = torch.full(
78
- (config.max_seq_len, config.max_seq_len), float("-inf")
79
- )
80
- mask = torch.triu(mask, diagonal=1)
81
- self.register_buffer("causal_mask", mask)
82
 
83
- def forward(
84
- self,
85
- x: torch.Tensor,
86
- freqs_cos: torch.Tensor,
87
- freqs_sin: torch.Tensor,
88
- kv_cache: tuple[torch.Tensor, torch.Tensor] | None = None,
89
- ) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]:
90
  B, T, C = x.shape
91
-
92
  q = self.q_proj(x).view(B, T, self.n_heads, self.head_dim)
93
  k = self.k_proj(x).view(B, T, self.n_heads, self.head_dim)
94
  v = self.v_proj(x).view(B, T, self.n_heads, self.head_dim)
95
 
96
  q, k = apply_rotary_emb(q, k, freqs_cos, freqs_sin)
97
-
98
- q = q.transpose(1, 2)
99
- k = k.transpose(1, 2)
100
- v = v.transpose(1, 2)
101
 
102
  if kv_cache is not None:
103
  prev_k, prev_v = kv_cache
@@ -105,19 +82,16 @@ class CausalSelfAttention(nn.Module):
105
  v = torch.cat([prev_v, v], dim=2)
106
  new_kv_cache = (k, v)
107
 
108
- total_k_len = k.size(2)
109
  scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim)
110
-
111
  if T > 1:
112
- scores = scores + self.causal_mask[:T, :total_k_len]
113
 
114
  attn_weights = F.softmax(scores, dim=-1)
115
- out = attn_weights @ v
116
- out = out.transpose(1, 2).contiguous().view(B, T, C)
117
  return self.out_proj(out), new_kv_cache
118
-
119
- class TransformerBlock(nn.Module):
120
 
 
 
121
  def __init__(self, config: SpinConfig):
122
  super().__init__()
123
  self.attn_norm = RMSNorm(config.d_model, eps=config.norm_eps)
@@ -125,64 +99,69 @@ class TransformerBlock(nn.Module):
125
  self.ffn_norm = RMSNorm(config.d_model, eps=config.norm_eps)
126
  self.ffn = SwiGLU(config.d_model, config.d_ff)
127
 
128
- def forward(
129
- self,
130
- x: torch.Tensor,
131
- freqs_cos: torch.Tensor,
132
- freqs_sin: torch.Tensor,
133
- kv_cache: tuple[torch.Tensor, torch.Tensor] | None = None,
134
- ) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]:
135
- norm_x = self.attn_norm(x)
136
- attn_out, next_kv = self.attn(
137
- norm_x, freqs_cos, freqs_sin, kv_cache=kv_cache
138
- )
139
  x = x + attn_out
140
  x = x + self.ffn(self.ffn_norm(x))
141
  return x, next_kv
142
 
143
 
144
- class SpinForCausalLM(PreTrainedModel):
145
  config_class = SpinConfig
 
146
 
147
  def __init__(self, config: SpinConfig):
148
  super().__init__(config)
149
  self.config = config
150
  self.tok_embeddings = nn.Embedding(config.vocab_size, config.d_model)
151
- self.layers = nn.ModuleList(
152
- [TransformerBlock(config) for _ in range(config.n_layers)]
153
- )
154
  self.norm = RMSNorm(config.d_model, eps=config.norm_eps)
155
  self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
156
 
157
-
158
- self.tok_embeddings.weight = self.lm_head.weight
159
 
160
  head_dim = config.d_model // config.n_heads
161
- freqs_cos, freqs_sin = precompute_freqs_cis(
162
- head_dim, config.max_seq_len
163
- )
164
- self.register_buffer("freqs_cos", freqs_cos)
165
- self.register_buffer("freqs_sin", freqs_sin)
166
 
167
  self.post_init()
168
 
 
 
 
 
 
 
 
 
 
 
 
 
169
  def forward(
170
  self,
171
- input_ids: torch.Tensor,
172
  labels: torch.Tensor = None,
173
- kv_caches=None,
174
- start_pos: int = 0,
175
  return_dict: bool = True,
 
176
  ):
177
  B, T = input_ids.shape
178
  x = self.tok_embeddings(input_ids)
179
 
 
 
 
 
180
  freqs_cos = self.freqs_cos[start_pos : start_pos + T]
181
  freqs_sin = self.freqs_sin[start_pos : start_pos + T]
182
 
183
  new_kv_caches = []
184
  for i, layer in enumerate(self.layers):
185
- cache_i = kv_caches[i] if kv_caches is not None else None
186
  x, new_cache = layer(x, freqs_cos, freqs_sin, kv_cache=cache_i)
187
  new_kv_caches.append(new_cache)
188
 
@@ -191,17 +170,23 @@ class SpinForCausalLM(PreTrainedModel):
191
 
192
  loss = None
193
  if labels is not None:
194
- loss = F.cross_entropy(
195
- logits.view(-1, self.config.vocab_size),
196
- labels.view(-1),
197
- ignore_index=-100,
198
- )
199
 
200
  if not return_dict:
201
  return (logits, loss, new_kv_caches)
202
 
203
  return CausalLMOutputWithPast(
204
- loss=loss, logits=logits, past_key_values=new_kv_caches
 
 
205
  )
206
 
 
 
 
 
 
 
 
 
207
 
 
 
1
  import math
2
  import torch
3
  import torch.nn as nn
4
  import torch.nn.functional as F
5
+ from transformers import PreTrainedModel, GenerationMixin
6
  from transformers.modeling_outputs import CausalLMOutputWithPast
7
+ from .configuration_spin import SpinConfig
8
 
 
9
 
10
+ class RMSNorm(nn.Module):
11
  def __init__(self, dim: int, eps: float = 1e-5):
12
  super().__init__()
13
  self.eps = eps
 
17
  variance = x.pow(2).mean(-1, keepdim=True)
18
  return x * torch.rsqrt(variance + self.eps) * self.weight
19
 
20
+
21
  def precompute_freqs_cis(dim: int, max_seq_len: int, theta: float = 10000.0):
22
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
 
 
23
  t = torch.arange(max_seq_len, dtype=torch.float32)
24
  freqs = torch.outer(t, freqs)
25
+ return torch.cos(freqs), torch.sin(freqs)
26
+
27
+
28
+ def apply_rotary_emb(xq, xk, freqs_cos, freqs_sin):
 
 
 
 
 
 
 
 
29
  xq_r, xq_i = xq.float().reshape(*xq.shape[:-1], -1, 2).unbind(-1)
30
  xk_r, xk_i = xk.float().reshape(*xk.shape[:-1], -1, 2).unbind(-1)
31
 
 
32
  freqs_cos = freqs_cos.unsqueeze(0).unsqueeze(2)
33
  freqs_sin = freqs_sin.unsqueeze(0).unsqueeze(2)
34
 
 
41
  xk_out = torch.stack([xk_out_r, xk_out_i], dim=-1).flatten(3)
42
  return xq_out.type_as(xq), xk_out.type_as(xk)
43
 
 
44
 
45
+ class SwiGLU(nn.Module):
46
  def __init__(self, d_model: int, d_ff: int):
47
  super().__init__()
48
  self.w_gate = nn.Linear(d_model, d_ff, bias=False)
 
52
  def forward(self, x: torch.Tensor) -> torch.Tensor:
53
  return self.w_down(F.silu(self.w_gate(x)) * self.w_up(x))
54
 
 
55
 
56
+ class CausalSelfAttention(nn.Module):
57
  def __init__(self, config: SpinConfig):
58
  super().__init__()
59
  self.n_heads = config.n_heads
 
64
  self.v_proj = nn.Linear(config.d_model, config.d_model, bias=False)
65
  self.out_proj = nn.Linear(config.d_model, config.d_model, bias=False)
66
 
67
+ mask = torch.full((config.max_seq_len, config.max_seq_len), float("-inf"))
68
+ self.register_buffer("causal_mask", torch.triu(mask, diagonal=1), persistent=False)
 
 
 
69
 
70
+ def forward(self, x, freqs_cos, freqs_sin, kv_cache=None):
 
 
 
 
 
 
71
  B, T, C = x.shape
 
72
  q = self.q_proj(x).view(B, T, self.n_heads, self.head_dim)
73
  k = self.k_proj(x).view(B, T, self.n_heads, self.head_dim)
74
  v = self.v_proj(x).view(B, T, self.n_heads, self.head_dim)
75
 
76
  q, k = apply_rotary_emb(q, k, freqs_cos, freqs_sin)
77
+ q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
 
 
 
78
 
79
  if kv_cache is not None:
80
  prev_k, prev_v = kv_cache
 
82
  v = torch.cat([prev_v, v], dim=2)
83
  new_kv_cache = (k, v)
84
 
 
85
  scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim)
 
86
  if T > 1:
87
+ scores = scores + self.causal_mask[:T, : k.size(2)]
88
 
89
  attn_weights = F.softmax(scores, dim=-1)
90
+ out = (attn_weights @ v).transpose(1, 2).contiguous().view(B, T, C)
 
91
  return self.out_proj(out), new_kv_cache
 
 
92
 
93
+
94
+ class TransformerBlock(nn.Module):
95
  def __init__(self, config: SpinConfig):
96
  super().__init__()
97
  self.attn_norm = RMSNorm(config.d_model, eps=config.norm_eps)
 
99
  self.ffn_norm = RMSNorm(config.d_model, eps=config.norm_eps)
100
  self.ffn = SwiGLU(config.d_model, config.d_ff)
101
 
102
+ def forward(self, x, freqs_cos, freqs_sin, kv_cache=None):
103
+ attn_out, next_kv = self.attn(self.attn_norm(x), freqs_cos, freqs_sin, kv_cache=kv_cache)
 
 
 
 
 
 
 
 
 
104
  x = x + attn_out
105
  x = x + self.ffn(self.ffn_norm(x))
106
  return x, next_kv
107
 
108
 
109
+ class SpinForCausalLM(PreTrainedModel, GenerationMixin):
110
  config_class = SpinConfig
111
+ _tied_weights_keys = ["lm_head.weight"]
112
 
113
  def __init__(self, config: SpinConfig):
114
  super().__init__(config)
115
  self.config = config
116
  self.tok_embeddings = nn.Embedding(config.vocab_size, config.d_model)
117
+ self.layers = nn.ModuleList([TransformerBlock(config) for _ in range(config.n_layers)])
 
 
118
  self.norm = RMSNorm(config.d_model, eps=config.norm_eps)
119
  self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
120
 
121
+ # Weight tying
122
+ self.lm_head.weight = self.tok_embeddings.weight
123
 
124
  head_dim = config.d_model // config.n_heads
125
+ freqs_cos, freqs_sin = precompute_freqs_cis(head_dim, config.max_seq_len)
126
+ self.register_buffer("freqs_cos", freqs_cos, persistent=False)
127
+ self.register_buffer("freqs_sin", freqs_sin, persistent=False)
 
 
128
 
129
  self.post_init()
130
 
131
+ def get_input_embeddings(self):
132
+ return self.tok_embeddings
133
+
134
+ def set_input_embeddings(self, value):
135
+ self.tok_embeddings = value
136
+
137
+ def get_output_embeddings(self):
138
+ return self.lm_head
139
+
140
+ def set_output_embeddings(self, new_embeddings):
141
+ self.lm_head = new_embeddings
142
+
143
  def forward(
144
  self,
145
+ input_ids: torch.Tensor = None,
146
  labels: torch.Tensor = None,
147
+ past_key_values: list = None,
148
+ use_cache: bool = False,
149
  return_dict: bool = True,
150
+ **kwargs,
151
  ):
152
  B, T = input_ids.shape
153
  x = self.tok_embeddings(input_ids)
154
 
155
+ start_pos = 0
156
+ if past_key_values is not None and len(past_key_values) > 0 and past_key_values[0] is not None:
157
+ start_pos = past_key_values[0][0].shape[2]
158
+
159
  freqs_cos = self.freqs_cos[start_pos : start_pos + T]
160
  freqs_sin = self.freqs_sin[start_pos : start_pos + T]
161
 
162
  new_kv_caches = []
163
  for i, layer in enumerate(self.layers):
164
+ cache_i = past_key_values[i] if past_key_values is not None else None
165
  x, new_cache = layer(x, freqs_cos, freqs_sin, kv_cache=cache_i)
166
  new_kv_caches.append(new_cache)
167
 
 
170
 
171
  loss = None
172
  if labels is not None:
173
+ loss = F.cross_entropy(logits.view(-1, self.config.vocab_size), labels.view(-1), ignore_index=-100)
 
 
 
 
174
 
175
  if not return_dict:
176
  return (logits, loss, new_kv_caches)
177
 
178
  return CausalLMOutputWithPast(
179
+ loss=loss,
180
+ logits=logits,
181
+ past_key_values=new_kv_caches if use_cache else None,
182
  )
183
 
184
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **kwargs):
185
+ if past_key_values is not None and len(past_key_values) > 0 and past_key_values[0] is not None:
186
+ input_ids = input_ids[:, -1:]
187
+ return {
188
+ "input_ids": input_ids,
189
+ "past_key_values": past_key_values,
190
+ "use_cache": True,
191
+ }
192