| |
| |
| |
|
|
| from __future__ import annotations |
|
|
| import math |
| from typing import List, Optional |
|
|
| import torch |
| import torch.nn.functional as F |
| from torch import nn |
| from transformers import GPT2Config |
| from transformers.models.gpt2.modeling_gpt2 import ( |
| GPT2Attention, |
| GPT2Block, |
| GPT2Model, |
| GPT2PreTrainedModel, |
| ) |
| from transformers.modeling_outputs import CausalLMOutputWithCrossAttentions |
|
|
|
|
| class GPT2GeometryConfig(GPT2Config): |
| model_type = "gpt2_geometry" |
|
|
| def __init__(self, use_cosine_attention: bool = True, geometry_collapse_layers: Optional[List[int]] = None, **kwargs): |
| self.use_cosine_attention = kwargs.pop("use_cosine_attention", True) |
| self.geometry_collapse_layers = kwargs.pop("geometry_collapse_layers", None) |
| super().__init__(**kwargs) |
|
|
|
|
| def cosine_attention_forward(module, query, key, value, attention_mask, **kwargs): |
| d_k = value.size(-1) |
| Q_norm = F.normalize(query, p=2, dim=-1) |
| K_norm = F.normalize(key, p=2, dim=-1) |
| attn_weights = torch.matmul(Q_norm, K_norm.transpose(-1, -2)) / math.sqrt(d_k) |
| if module.scale_attn_by_inverse_layer_idx and getattr(module, "layer_idx", None) is not None: |
| attn_weights = attn_weights / float(module.layer_idx + 1) |
| if attention_mask is not None: |
| attn_weights = attn_weights + attention_mask |
| attn_weights = nn.functional.softmax(attn_weights, dim=-1) |
| attn_weights = attn_weights.type(value.dtype) |
| attn_weights = module.attn_dropout(attn_weights) |
| attn_output = torch.matmul(attn_weights, value) |
| attn_output = attn_output.transpose(1, 2) |
| return attn_output, attn_weights |
|
|
|
|
| class CosineGPT2Attention(GPT2Attention): |
| def forward( |
| self, |
| hidden_states, |
| past_key_values=None, |
| cache_position=None, |
| attention_mask=None, |
| encoder_hidden_states=None, |
| encoder_attention_mask=None, |
| output_attentions=None, |
| **kwargs, |
| ): |
| is_cross_attention = encoder_hidden_states is not None |
| if is_cross_attention: |
| query_states = self.q_attn(hidden_states) |
| attention_mask = encoder_attention_mask |
| key_states, value_states = self.c_attn(encoder_hidden_states).split(self.split_size, dim=2) |
| else: |
| query_states, key_states, value_states = self.c_attn(hidden_states).split(self.split_size, dim=2) |
| shape_kv = (*key_states.shape[:-1], -1, self.head_dim) |
| key_states = key_states.view(shape_kv).transpose(1, 2) |
| value_states = value_states.view(shape_kv).transpose(1, 2) |
| shape_q = (*query_states.shape[:-1], -1, self.head_dim) |
| query_states = query_states.view(shape_q).transpose(1, 2) |
| attn_output, attn_weights = cosine_attention_forward( |
| self, query_states, key_states, value_states, attention_mask |
| ) |
| attn_output = attn_output.reshape(*attn_output.shape[:-2], -1).contiguous() |
| attn_output = self.c_proj(attn_output) |
| attn_output = self.resid_dropout(attn_output) |
| return attn_output, attn_weights |
|
|
|
|
| def overlap_reg_var(lm_head_weight: torch.Tensor, n_probe: int = 2048) -> torch.Tensor: |
| """Compute Var[(w_i·w_j)²] over LM head row pairs (upper triangle). Only used during training.""" |
| W = lm_head_weight |
| if W.shape[0] < 2: |
| return torch.tensor(0.0, device=W.device, dtype=W.dtype) |
| n = min(n_probe, W.shape[0]) |
| W_sub = W[:n] |
| G = torch.mm(W_sub, W_sub.T) |
| G2 = G ** 2 |
| triu_idx = torch.triu_indices(n, n, 1, device=G2.device) |
| vals = G2[triu_idx[0], triu_idx[1]] |
| return torch.var(vals) |
|
|
|
|
| class GPT2BlockGeometry(GPT2Block): |
| def __init__(self, config, layer_idx=None): |
| super().__init__(config, layer_idx) |
| use_cosine_global = getattr(config, "use_cosine_attention", True) |
| collapse_layers = getattr(config, "geometry_collapse_layers", None) |
| use_cosine_here = use_cosine_global and ( |
| collapse_layers is None or (layer_idx is not None and layer_idx in collapse_layers) |
| ) |
| if use_cosine_here: |
| self.attn = CosineGPT2Attention(config=config, layer_idx=layer_idx) |
| else: |
| self.attn = GPT2Attention(config=config, layer_idx=layer_idx) |
|
|
|
|
| class GPT2ModelGeometry(GPT2Model): |
| def __init__(self, config): |
| super().__init__(config) |
| self.h = nn.ModuleList([GPT2BlockGeometry(config, layer_idx=i) for i in range(config.num_hidden_layers)]) |
|
|
|
|
| class GPT2LMHeadModelGeometry(GPT2PreTrainedModel): |
| config_class = GPT2GeometryConfig |
| _tied_weights_keys = {"lm_head.weight": "transformer.wte.weight"} |
|
|
| def __init__(self, config, overlap_lambda: float = 0.05, **kwargs): |
| super().__init__(config, **kwargs) |
| self.transformer = GPT2ModelGeometry(config) |
| self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False) |
| self.overlap_lambda = overlap_lambda |
| self.post_init() |
|
|
| def get_output_embeddings(self): |
| return self.lm_head |
|
|
| def set_output_embeddings(self, new_embeddings): |
| self.lm_head = new_embeddings |
|
|
| def forward( |
| self, |
| input_ids=None, |
| past_key_values=None, |
| cache_position=None, |
| attention_mask=None, |
| token_type_ids=None, |
| position_ids=None, |
| inputs_embeds=None, |
| labels=None, |
| use_cache=None, |
| output_attentions=None, |
| output_hidden_states=None, |
| return_dict=None, |
| **kwargs, |
| ): |
| return_dict = return_dict if return_dict is not None else self.config.use_return_dict |
| transformer_outputs = self.transformer( |
| input_ids, |
| past_key_values=past_key_values, |
| cache_position=cache_position, |
| attention_mask=attention_mask, |
| token_type_ids=token_type_ids, |
| position_ids=position_ids, |
| inputs_embeds=inputs_embeds, |
| use_cache=use_cache, |
| output_attentions=output_attentions, |
| output_hidden_states=output_hidden_states, |
| return_dict=return_dict, |
| ) |
| hidden_states = transformer_outputs[0] |
| logits = self.lm_head(hidden_states) |
| loss = None |
| if labels is not None: |
| shift_logits = logits[..., :-1, :].contiguous().view(-1, logits.size(-1)) |
| shift_labels = labels[..., 1:].contiguous().view(-1) |
| loss_fct = nn.CrossEntropyLoss() |
| loss = loss_fct(shift_logits, shift_labels) |
| if self.overlap_lambda != 0: |
| overlap_var = overlap_reg_var(self.lm_head.weight) |
| loss = loss + self.overlap_lambda * overlap_var |
| if not return_dict: |
| output = (logits,) + transformer_outputs[1:] |
| return ((loss,) + output) if loss is not None else output |
| return CausalLMOutputWithCrossAttentions( |
| loss=loss, |
| logits=logits, |
| past_key_values=transformer_outputs.past_key_values, |
| hidden_states=transformer_outputs.hidden_states, |
| attentions=transformer_outputs.attentions, |
| ) |
|
|