File size: 5,204 Bytes
1d0b885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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
"""GPT-2 with an explicit, weight-shared loop over a contiguous block range."""

import torch
from torch.nn import functional as F
from transformers import GPT2Config, GPT2LMHeadModel
from transformers.modeling_outputs import CausalLMOutputWithCrossAttentions


class LoopedGPT2Config(GPT2Config):
    model_type = "looped_gpt2"

    def __init__(self, loop_start=2, loop_end=4, num_loops=3, **kwargs):
        super().__init__(**kwargs)
        if not 0 <= loop_start < loop_end <= self.n_layer:
            raise ValueError("Require 0 <= loop_start < loop_end <= n_layer")
        if not isinstance(num_loops, int) or num_loops < 1:
            raise ValueError("num_loops must be a positive integer")
        self.loop_start = loop_start
        self.loop_end = loop_end  # exclusive; indices are zero based
        self.num_loops = num_loops
        self.use_cache = False


class LoopedGPT2LMHeadModel(GPT2LMHeadModel):
    """Keep GPT-2's parameters and HF save/load/generate; change execution order.

    KV caching is deliberately disabled: every *execution* of a shared block
    would need its own cache. Reusing a physical layer's cache would be wrong.
    """

    config_class = LoopedGPT2Config

    def __init__(self, config):
        # PyTorch's SDPA handles attention; we provide a causal + padding mask.
        config._attn_implementation = "sdpa"
        super().__init__(config)

    @classmethod
    def from_dense(cls, dense, *, loop_start=2, loop_end=4, num_loops=3):
        config = dense.config.to_dict()
        config.pop("model_type", None)
        config.update(loop_start=loop_start, loop_end=loop_end, num_loops=num_loops)
        model = cls(LoopedGPT2Config(**config))
        model.load_state_dict(dense.state_dict(), strict=True)
        return model

    def layer_order(self, num_loops=None):
        c = self.config
        loops = c.num_loops if num_loops is None else num_loops
        if not isinstance(loops, int) or loops < 1:
            raise ValueError("num_loops must be a positive integer")
        return (list(range(c.loop_start))
                + list(range(c.loop_start, c.loop_end)) * loops
                + list(range(c.loop_end, c.n_layer)))

    def forward(self, input_ids=None, attention_mask=None, labels=None,
                position_ids=None, num_loops=None, use_cache=False,
                past_key_values=None, return_dict=True, logits_to_keep=0,
                **kwargs):
        if use_cache or past_key_values is not None:
            raise ValueError("Looped GPT-2 requires use_cache=False")
        if input_ids is None or input_ids.ndim != 2:
            raise ValueError("Provide input_ids with shape (batch, sequence)")
        if any(kwargs.get(k) is not None for k in (
            "inputs_embeds", "token_type_ids", "encoder_hidden_states", "head_mask"
        )) or kwargs.get("output_attentions") or kwargs.get("output_hidden_states"):
            raise ValueError("This minimal forward supports token IDs, masks and labels only")
        if labels is not None and logits_to_keep:
            raise ValueError("Full logits are required when labels are supplied")
        length = input_ids.shape[1]
        if length > self.config.n_positions:
            raise ValueError("Sequence exceeds the model's position embedding limit")
        if attention_mask is None:
            attention_mask = torch.ones_like(input_ids)
        if position_ids is None:
            position_ids = (attention_mask.long().cumsum(-1) - 1).clamp(min=0)
        t = self.transformer
        hidden = t.drop(t.wte(input_ids) + t.wpe(position_ids))
        causal = torch.ones(length, length, dtype=torch.bool, device=hidden.device).tril()
        allowed = causal[None, None] & attention_mask[:, None, None, :].bool()
        mask = torch.zeros(allowed.shape, dtype=hidden.dtype, device=hidden.device)
        mask.masked_fill_(~allowed, torch.finfo(hidden.dtype).min)

        # The same module objects are called again. No copies and no detach:
        # gradients from all iterations accumulate into each shared parameter.
        for index in self.layer_order(num_loops):
            hidden = t.h[index](hidden, attention_mask=mask, use_cache=False)[0]

        hidden = t.ln_f(hidden)
        logits = self.lm_head(hidden[:, -logits_to_keep:] if logits_to_keep else hidden)
        loss = None
        if labels is not None:
            loss = F.cross_entropy(
                logits[:, :-1].float().reshape(-1, logits.size(-1)),
                labels[:, 1:].reshape(-1), ignore_index=-100,
            )
        if not return_dict:
            return (loss, logits) if loss is not None else (logits,)
        return CausalLMOutputWithCrossAttentions(loss=loss, logits=logits)

    def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **kwargs):
        return dict(input_ids=input_ids, attention_mask=attention_mask,
                    use_cache=False, logits_to_keep=1,
                    num_loops=kwargs.get("num_loops"))


# save_pretrained copies this source and writes auto_map into config.json.
LoopedGPT2Config.register_for_auto_class()
LoopedGPT2LMHeadModel.register_for_auto_class("AutoModelForCausalLM")