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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
import math
import torch
import torch.nn as nn
import torch.nn.functional as F

from transformers import PreTrainedModel, GenerationMixin
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
from transformers.cache_utils import Cache, DynamicCache

from rotary_embedding_torch import RotaryEmbedding
from .config import TransformerConfig

# Allows for easier hooking
class Residual(nn.Module):
    def __init__(self):
        super().__init__()

    def forward(self, x, delta):
        return x + delta

class SelfAttention(nn.Module):

    def __init__(self, config, layer_idx=None):
        super().__init__()
        
        self.layer_idx = layer_idx
        self.use_causal_attention = config.use_causal_attention
        
        self.hidden_size = config.hidden_size
        self.embedding_size = config.embedding_size
        self.num_heads = config.num_attention_heads
        self.head_dim = self.hidden_size // self.num_heads
        
        assert self.head_dim * self.num_heads == self.hidden_size

        self.q_proj = nn.Linear(self.embedding_size, self.hidden_size, bias=False)
        self.k_proj = nn.Linear(self.embedding_size, self.hidden_size, bias=False)
        self.v_proj = nn.Linear(self.embedding_size, self.hidden_size, bias=True)
        self.o_proj = nn.Linear(self.hidden_size, self.embedding_size, bias=True)

        self.rotary_emb = RotaryEmbedding(dim=self.head_dim)
        self.scale = self.head_dim ** -0.5

    def forward(self, x, attention_mask=None, past_key_values=None):

        B, T, _ = x.size()
        
        q = self.q_proj(x)
        k = self.k_proj(x)
        v = self.v_proj(x)

        q = q.view(B, T, self.num_heads, self.head_dim).transpose(1, 2)
        k = k.view(B, T, self.num_heads, self.head_dim).transpose(1, 2)
        v = v.view(B, T, self.num_heads, self.head_dim).transpose(1, 2)

        if past_key_values is None:
            
            q = self.rotary_emb.rotate_queries_or_keys(q)
            k = self.rotary_emb.rotate_queries_or_keys(k)

        else:
            
            k_cache, v_cache = past_key_values[self.layer_idx] if self.layer_idx < len(past_key_values) else (None, None)

            k_len = k_cache.shape[-2] if k_cache is not None else 0

            q = self.rotary_emb.rotate_queries_or_keys(q, offset=k_len)
            k = self.rotary_emb.rotate_queries_or_keys(k, offset=k_len)
            
            past_key_values.update(k, v, self.layer_idx)
        
            if k_cache is not None and v_cache is not None:

                k = torch.cat([k_cache, k], dim=-2)
                v = torch.cat([v_cache, v], dim=-2)

        # Uses "is_causal" when possible for efficiency
        attn_output = F.scaled_dot_product_attention(q, k, v, attn_mask=attention_mask, scale=self.scale, is_causal=(self.use_causal_attention and attention_mask is None))

        attn_output = attn_output.transpose(1, 2).contiguous().view(B, T, self.hidden_size)
        out = self.o_proj(attn_output)
            
        return out

class MLP(nn.Module):

    def __init__(self, config):
        super().__init__()

        self.fc_up = nn.Linear(config.embedding_size, config.intermediate_size)
        self.activation = nn.GELU()
        self.fc_down = nn.Linear(config.intermediate_size, config.embedding_size)

    def forward(self, x):
        return self.fc_down(self.activation(self.fc_up(x)))

class TransformerBlock(nn.Module):

    def __init__(self, config, layer_idx=None):
        super().__init__()
        
        self.layer_idx = layer_idx

        self.ln_attn = nn.LayerNorm(config.embedding_size)
        self.attn = SelfAttention(config, layer_idx=layer_idx)
        self.resid_attn = Residual()

        self.ln_mlp = nn.LayerNorm(config.embedding_size)
        self.mlp = MLP(config)
        self.resid_mlp = Residual()

    def forward(self, x, attention_mask=None, past_key_values=None):

        attn_out = self.attn(self.ln_attn(x), attention_mask=attention_mask, past_key_values=past_key_values)
        x = self.resid_attn(x, attn_out)

        mlp_out = self.mlp(self.ln_mlp(x))
        x = self.resid_mlp(x, mlp_out)

        return x

class TransformerPreTrainedModel(PreTrainedModel):
    
    config_class = TransformerConfig
    base_model_prefix = "model"
    _no_split_modules = ["TransformerBlock"]
    _skip_keys_device_placement = ["past_key_values"]
    _supports_flash_attn_2 = True
    _supports_cache_class = True

    # Initialization borrowed from Deepseek and Falcon
    def _init_weights(self, module):
        std = self.config.initializer_range
        if isinstance(module, nn.Linear):
            module.weight.data.normal_(mean=0.0, std=std)
            if module.bias is not None:
                module.bias.data.zero_()
        elif isinstance(module, nn.Embedding):
            module.weight.data.normal_(mean=0.0, std=std)
            if module.padding_idx is not None:
                module.weight.data[module.padding_idx].zero_()
        elif isinstance(module, nn.LayerNorm):
            module.bias.data.zero_()
            module.weight.data.fill_(1.0)

    def calculate_loss(self, logits, target_tokens, l1_loss_lambda=None):
        loss = F.cross_entropy(
            logits.reshape(-1, logits.size(-1)),
            target_tokens.reshape(-1),
            reduction='mean'
            )
        return loss
    
    def count_parameters(self):
        total_params = sum(p.numel() for p in self.parameters())
        embed_params = sum(p.numel() for name, p in self.named_parameters() if "embed" in name.lower())
        non_embed_params = total_params - embed_params
        return total_params, embed_params, non_embed_params

class TransformerModel(TransformerPreTrainedModel):
    
    def __init__(self, config):
        super().__init__(config)

        self.config = config
        self.embedding = nn.Embedding(config.vocab_size, config.embedding_size)

        self.blocks = nn.ModuleList([TransformerBlock(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
        self.ln_out = nn.LayerNorm(config.embedding_size)

        self.post_init()

    def _to_dynamic_cache(self, past_key_values):
        cache = DynamicCache()
        for i, (k, v) in enumerate(past_key_values):
            cache.update({"prev_key": k, "prev_value": v}, layer_idx=i)
        return cache

    def _prepare_causal_attention_mask(self, x, attention_mask=None, past_key_values=None):
        
        device = x.device

        B = x.shape[0]
        T = x.shape[1]

        T_past = past_key_values.get_seq_length() if past_key_values is not None else 0

        T_total = T + T_past

        # Diagonal shift effectively does nothing during training or inference, but here for compatibility
        causal_mask = torch.triu(torch.ones((T, T_total), dtype=torch.bool, device=device), diagonal=(1 + T_past)).unsqueeze(0).unsqueeze(0) # [1, 1, T, S]
        
        # Combine with existing attention mask
        if attention_mask is not None:
            
            attn_len = attention_mask.shape[-1]

            # If passed attention mask is too small (ex. excludes past tokens), pad left
            if attn_len < T_total:
                pad = torch.zeros(B, T_past, device=device, dtype=attention_mask.dtype)
                attention_mask = torch.cat([pad, attention_mask], dim=-1)

            # If passed attention mask is too big, clip to match sequence length
            elif attn_len > T_total:
                attention_mask = attention_mask[:, -T_total:]
            
            expanded_mask = (attention_mask == 0).view(B, 1, 1, T_total)
            causal_mask = causal_mask | expanded_mask

        return causal_mask

    def forward(
        self,
        input_ids=None,
        attention_mask=None,
        inputs_embeds=None,
        past_key_values=None,
        use_cache=None,
        output_hidden_states=None,
        return_dict=None,
        **kwargs
    ):
        
        use_cache = use_cache if use_cache is not None else self.config.use_cache
        output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        if inputs_embeds is None:
            x = self.embedding(input_ids)
        else:
            assert input_ids is None, "You cannot specify both input_ids and inputs_embeds"
            x = inputs_embeds

        if self.config.truncate_activation_size:
            x = x[:, :self.config.max_position_embeddings - 1, :] # Ensures that the padding token doesn't cause the activations to grow beyond max_position_embeddings

        B, T, _ = x.shape
        device = x.device

        if not use_cache:
            past_key_values=None
        elif past_key_values is None:
            past_key_values = DynamicCache()
        elif isinstance(past_key_values, (tuple, list)):
            past_key_values = self._to_dynamic_cache(past_key_values)

        if attention_mask is not None and self.config.use_causal_attention:
            attention_mask = self._prepare_causal_attention_mask(x, attention_mask=attention_mask, past_key_values=past_key_values)

        hidden_states = [] if output_hidden_states else None

        for block in self.blocks:
            
            x = block(x, attention_mask=attention_mask, past_key_values=past_key_values)
            
            if output_hidden_states:
                hidden_states.append(x)

        x = self.ln_out(x)

        if return_dict:
            return BaseModelOutputWithPast(
                last_hidden_state=x,
                past_key_values=past_key_values,
                hidden_states=hidden_states
            )

        return x, past_key_values, hidden_states

class TransformerForCausalLM(GenerationMixin, TransformerPreTrainedModel):
    
    accepts_loss_kwargs = False

    def __init__(self, config):
        super().__init__(config)
    
        self.model = TransformerModel(config)
        self.lm_head = nn.Linear(config.embedding_size, config.vocab_size, bias=False)

        if config.tie_word_embeddings:
            self.tie_weights()
            self._dynamic_tied_weights_keys = {"lm_head.weight": "model.embedding.weight"} # Avoids safetensor naming issues

        self.post_init()

    def get_input_embeddings(self):
        return self.model.embedding

    def set_input_embeddings(self, new_embeddings):
        self.model.embedding = new_embeddings

    def get_output_embeddings(self):
        return self.lm_head

    def set_output_embeddings(self, new_embeddings):
        self.lm_head = new_embeddings

    def tie_weights(self):
        self._tie_or_clone_weights(self.lm_head, self.get_input_embeddings())

    def forward(
        self,
        input_ids=None,
        attention_mask=None,
        past_key_values=None,
        inputs_embeds=None,
        labels=None,
        use_cache=None,
        output_hidden_states=None,
        return_dict=None,
        **kwargs
    ):

        if labels is not None:
            return_dict = True
        else:
            return_dict = return_dict if return_dict is not None else self.config.use_return_dict
    
        model_output = self.model(
            input_ids=input_ids,
            attention_mask=attention_mask,
            inputs_embeds=inputs_embeds,
            past_key_values=past_key_values,
            use_cache=use_cache,
            output_hidden_states=output_hidden_states
        )

        logits = self.lm_head(model_output[0])

        loss = None
        if labels is not None:
            shift_logits = logits[:, :-1, :].contiguous()
            shift_labels = labels[:, 1:].contiguous()
            loss = F.cross_entropy(
                shift_logits.view(-1, shift_logits.size(-1)),
                shift_labels.view(-1),
                ignore_index=self.config.pad_token_id
            )

        if not return_dict:
            output = (logits,) + model_output[1:]
            return ((loss,) + output) if loss is not None else output
        return logits
        # return CausalLMOutputWithPast(
        #     loss=loss,
        #     logits=logits,
        #     past_key_values=model_output.past_key_values,
        #     hidden_states=model_output.hidden_states
        # )

    def _prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **kwargs):
        
        if past_key_values is not None:
            input_ids = input_ids[:, -1:]

        model_inputs = {"input_ids": input_ids, "past_key_values": past_key_values, "use_cache": True}

        if attention_mask is not None:
            model_inputs["attention_mask"] = attention_mask

        for key, value in kwargs.items():
            model_inputs[key] = value

        return model_inputs
    
    def _reorder_cache(self, past_key_values, beam_idx):
        
        reordered_past = []
        
        for layer_past in past_key_values:
            reordered_past.append(tuple(past_state.index_select(0, beam_idx) for past_state in layer_past))
        
        return tuple(reordered_past)
    @torch.no_grad()
    def generate(
        self, 
        input_ids, 
        max_generation_length, 
        tokenizer, 
        temperature=1.0, 
        top_p=0.9, 
        return_generation_only=False
    ):
        # print(temperature,top_p)
        self.eval()

        batch_size = input_ids.size(0)
        device = input_ids.device

        generated = input_ids.clone()
        finished = torch.zeros(batch_size, dtype=torch.bool, device=device)

        for _ in range(max_generation_length):

            logits = self(generated)[:, -1, :] / temperature
            probs = F.softmax(logits, dim=-1)

            sorted_probs, sorted_indices = torch.sort(probs, dim=-1, descending=True)
            cumulative_probs = torch.cumsum(sorted_probs, dim=-1)

            cutoff_mask = cumulative_probs > top_p
            cutoff_mask[:, 1:] = cutoff_mask[:, :-1].clone()
            cutoff_mask[:, 0] = False

            sorted_probs = sorted_probs.masked_fill(cutoff_mask, 0.0)
            normalized_probs = sorted_probs / sorted_probs.sum(dim=-1, keepdim=True)

            probs = torch.zeros_like(normalized_probs).scatter(-1, sorted_indices, normalized_probs)

            next_token = torch.multinomial(probs, num_samples=1).squeeze(-1)
            next_token = torch.where(finished, torch.full_like(next_token, tokenizer.pad_token_id), next_token)

            generated = torch.cat([generated, next_token.unsqueeze(1)], dim=1)

            finished |= next_token == tokenizer.eos_token_id

            if finished.all():
                break

        if return_generation_only:
            return generated[:, input_ids.size(1):]
        else:
            return generated


# cp /cwork/jf381/checkpoints/transformer_353M_bert_update_2_6b -r /work/jf381/checkpoints/transformer_353M_bert_update_2_6b_test
# cp /cwork/jf381/checkpoints/transformer_353M_bert_update_2_6b -r /work/jf381/checkpoints/transformer_353M_bert_update_2_6b