summerstars commited on
Commit
a7b725f
·
verified ·
1 Parent(s): c4f28f1

Create model.py

Browse files
Files changed (1) hide show
  1. model.py +118 -0
model.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from transformers import AutoTokenizer, AutoModelForCausalLM
5
+
6
+ # ====================================================
7
+ # 1. StabilizedInfiniteGPT(推論用フル定義)
8
+ # ====================================================
9
+ class StabilizedInfiniteGPT(nn.Module):
10
+ def __init__(self, state_dim, model_name='gpt2'):
11
+ super().__init__()
12
+ print(f">>> Loading Backbone: {model_name}")
13
+
14
+ self.backbone = AutoModelForCausalLM.from_pretrained(model_name)
15
+
16
+ if hasattr(self.backbone.config, "n_embd"):
17
+ self.embed_dim = self.backbone.config.n_embd
18
+ else:
19
+ self.embed_dim = self.backbone.config.hidden_size
20
+
21
+ self.vocab_size = self.backbone.config.vocab_size
22
+ self.state_dim = state_dim
23
+
24
+ self.input_proj = nn.Linear(self.embed_dim, state_dim)
25
+ self.forget_gate = nn.Linear(state_dim, state_dim)
26
+ self.in_gate = nn.Linear(state_dim, state_dim)
27
+ self.layer_norm = nn.LayerNorm(state_dim)
28
+
29
+ self.memory_readout = nn.Linear(state_dim, self.vocab_size, bias=False)
30
+
31
+ self.gating_param = nn.Parameter(torch.tensor(0.1))
32
+
33
+ def forward_gen_step(self, context_ids, prev_state):
34
+ with torch.no_grad():
35
+ gpt_out = self.backbone(context_ids, output_hidden_states=True)
36
+ last_hidden = gpt_out.hidden_states[-1][:, -1:, :]
37
+ base_logits = gpt_out.logits[:, -1:, :]
38
+
39
+ if prev_state is None:
40
+ prev_state = torch.zeros(
41
+ context_ids.size(0), 1, self.state_dim,
42
+ device=context_ids.device, dtype=last_hidden.dtype
43
+ )
44
+
45
+ h = torch.tanh(self.input_proj(last_hidden))
46
+ f = torch.sigmoid(self.forget_gate(h))
47
+ u = torch.tanh(self.in_gate(h))
48
+ next_state = f * prev_state + (1 - f) * u
49
+
50
+ norm_state = self.layer_norm(next_state)
51
+ mem_logits = self.memory_readout(norm_state)
52
+
53
+ gate = torch.tanh(self.gating_param)
54
+ final_logits = base_logits + (gate * mem_logits)
55
+
56
+ return final_logits, next_state
57
+
58
+ # ====================================================
59
+ # 2. モデルロード関数
60
+ # ====================================================
61
+ def load_infinite_model(save_dir, device="cuda"):
62
+ print(f">>> Loading from {save_dir}...")
63
+
64
+ checkpoint = torch.load(f"{save_dir}/adapter_weights.pt", map_location=device)
65
+ config = checkpoint["config"]
66
+
67
+ tokenizer = AutoTokenizer.from_pretrained(save_dir)
68
+
69
+ model = StabilizedInfiniteGPT(
70
+ state_dim=config["state_dim"],
71
+ model_name=config["model_name"]
72
+ )
73
+
74
+ model.load_state_dict(checkpoint["model_state"], strict=False)
75
+
76
+ model.to(device)
77
+ model.eval()
78
+ return model, tokenizer
79
+
80
+ # ====================================================
81
+ # 3. 実行
82
+ # ====================================================
83
+ if __name__ == "__main__":
84
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
85
+ save_dir = "/content/my_infinite_model" # ← ここだけ変えれば OK
86
+
87
+ model, tokenizer = load_infinite_model(save_dir, device)
88
+
89
+ prompt_text = "def fibonacci(n):"
90
+ print(f"\nPrompt: {prompt_text}")
91
+ print("-" * 40)
92
+ print(prompt_text, end="", flush=True)
93
+
94
+ input_ids = tokenizer.encode(prompt_text, return_tensors="pt").to(device)
95
+
96
+ gen_state = None
97
+ curr_ids = input_ids
98
+ max_new_tokens = 100
99
+
100
+ for _ in range(max_new_tokens):
101
+ context = curr_ids[:, -1024:]
102
+
103
+ logits, gen_state = model.forward_gen_step(context, prev_state=gen_state)
104
+ next_logit = logits[:, -1, :]
105
+
106
+ top_k = 40
107
+ top_k_logits, top_k_indices = torch.topk(next_logit, top_k)
108
+ probs = F.softmax(top_k_logits, dim=-1)
109
+
110
+ idx = torch.multinomial(probs, 1)
111
+ next_token = torch.gather(top_k_indices, -1, idx)
112
+
113
+ word = tokenizer.decode(next_token[0])
114
+ print(word, end="", flush=True)
115
+
116
+ curr_ids = torch.cat([curr_ids, next_token], dim=-1)
117
+
118
+ print("\n\n>>> Generation Complete.")