OpenTransformer commited on
Commit
04806b0
·
verified ·
1 Parent(s): 8a88d0a

Add experiments/joint_test.py

Browse files
Files changed (1) hide show
  1. experiments/joint_test.py +234 -0
experiments/joint_test.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Joint AR+SAT training - what AGILLM-3 actually does
4
+ Test which attention mechanism works best for BOTH modes simultaneously
5
+ """
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+ import time
11
+ import math
12
+ import argparse
13
+
14
+ DEV = torch.device("cuda" if torch.cuda.is_available() else "cpu")
15
+ VOCAB = 128256
16
+
17
+ def get_mask(n, mode, block_size=4):
18
+ if mode == "nar":
19
+ return None
20
+ elif mode == "ar":
21
+ return torch.triu(torch.full((n, n), float("-inf"), device=DEV), 1)
22
+ elif mode == "sat":
23
+ idx = torch.arange(n, device=DEV)
24
+ block_idx = idx // block_size
25
+ mask = torch.where(
26
+ block_idx.unsqueeze(0) <= block_idx.unsqueeze(1),
27
+ torch.tensor(0.0, device=DEV),
28
+ torch.tensor(float("-inf"), device=DEV)
29
+ )
30
+ return mask
31
+
32
+ def alibi_bias(h, n):
33
+ def slopes(n):
34
+ start = 2 ** (-2 ** -(math.log2(n) - 3))
35
+ return [start * (start ** i) for i in range(n)]
36
+ s = slopes(h) if h > 0 and math.log2(h).is_integer() else slopes(2 ** math.floor(math.log2(max(1,h))))[:h]
37
+ s = torch.tensor(s, device=DEV).view(1, h, 1, 1)
38
+ i = torch.arange(n, device=DEV).view(1, 1, n, 1)
39
+ j = torch.arange(n, device=DEV).view(1, 1, 1, n)
40
+ return -s * (j - i).clamp_min(0).float()
41
+
42
+
43
+ class StandardAttn(nn.Module):
44
+ def __init__(self, d, h):
45
+ super().__init__()
46
+ self.h, self.dk = h, d // h
47
+ self.qkv = nn.Linear(d, 3*d, bias=False)
48
+ self.proj = nn.Linear(d, d, bias=False)
49
+
50
+ def forward(self, x, mask=None):
51
+ B, N, _ = x.shape
52
+ qkv = self.qkv(x).reshape(B, N, 3, self.h, self.dk).permute(2, 0, 3, 1, 4)
53
+ q, k, v = qkv[0], qkv[1], qkv[2]
54
+ att = (q @ k.transpose(-1, -2)) / math.sqrt(self.dk) + alibi_bias(self.h, N)
55
+ if mask is not None:
56
+ att = att + mask.unsqueeze(0).unsqueeze(0)
57
+ return self.proj((att.softmax(-1) @ v).transpose(1, 2).reshape(B, N, -1))
58
+
59
+
60
+ class MQAAttn(nn.Module):
61
+ def __init__(self, d, h):
62
+ super().__init__()
63
+ self.h, self.dk = h, d // h
64
+ self.q = nn.Linear(d, d, bias=False)
65
+ self.k = nn.Linear(d, self.dk, bias=False)
66
+ self.v = nn.Linear(d, self.dk, bias=False)
67
+ self.proj = nn.Linear(d, d, bias=False)
68
+
69
+ def forward(self, x, mask=None):
70
+ B, N, _ = x.shape
71
+ q = self.q(x).view(B, N, self.h, self.dk).transpose(1, 2)
72
+ k = self.k(x).view(B, N, 1, self.dk).transpose(1, 2)
73
+ v = self.v(x).view(B, N, 1, self.dk).transpose(1, 2)
74
+ att = (q @ k.transpose(-1, -2)) / math.sqrt(self.dk) + alibi_bias(self.h, N)
75
+ if mask is not None:
76
+ att = att + mask.unsqueeze(0).unsqueeze(0)
77
+ return self.proj((att.softmax(-1) @ v).transpose(1, 2).reshape(B, N, -1))
78
+
79
+
80
+ class GQAAttn(nn.Module):
81
+ def __init__(self, d, h, kv_heads=2):
82
+ super().__init__()
83
+ self.h, self.dk, self.kv_heads = h, d // h, kv_heads
84
+ self.q = nn.Linear(d, d, bias=False)
85
+ self.k = nn.Linear(d, kv_heads * self.dk, bias=False)
86
+ self.v = nn.Linear(d, kv_heads * self.dk, bias=False)
87
+ self.proj = nn.Linear(d, d, bias=False)
88
+
89
+ def forward(self, x, mask=None):
90
+ B, N, _ = x.shape
91
+ q = self.q(x).view(B, N, self.h, self.dk).transpose(1, 2)
92
+ k = self.k(x).view(B, N, self.kv_heads, self.dk).transpose(1, 2)
93
+ v = self.v(x).view(B, N, self.kv_heads, self.dk).transpose(1, 2)
94
+ k = k.repeat_interleave(self.h // self.kv_heads, dim=1)
95
+ v = v.repeat_interleave(self.h // self.kv_heads, dim=1)
96
+ att = (q @ k.transpose(-1, -2)) / math.sqrt(self.dk) + alibi_bias(self.h, N)
97
+ if mask is not None:
98
+ att = att + mask.unsqueeze(0).unsqueeze(0)
99
+ return self.proj((att.softmax(-1) @ v).transpose(1, 2).reshape(B, N, -1))
100
+
101
+
102
+ class Block(nn.Module):
103
+ def __init__(self, d, h, attn_type):
104
+ super().__init__()
105
+ self.ln1, self.ln2 = nn.LayerNorm(d), nn.LayerNorm(d)
106
+ if attn_type == "standard":
107
+ self.attn = StandardAttn(d, h)
108
+ elif attn_type == "mqa":
109
+ self.attn = MQAAttn(d, h)
110
+ elif attn_type == "gqa":
111
+ self.attn = GQAAttn(d, h, kv_heads=2)
112
+ elif attn_type == "gqa4":
113
+ self.attn = GQAAttn(d, h, kv_heads=4)
114
+ self.ff = nn.Sequential(nn.Linear(d, 4*d), nn.GELU(), nn.Linear(4*d, d))
115
+
116
+ def forward(self, x, mask=None):
117
+ x = x + self.attn(self.ln1(x), mask)
118
+ return x + self.ff(self.ln2(x))
119
+
120
+
121
+ class Model(nn.Module):
122
+ def __init__(self, d, layers, h, attn_type):
123
+ super().__init__()
124
+ self.emb = nn.Embedding(VOCAB, d)
125
+ self.blocks = nn.ModuleList([Block(d, h, attn_type) for _ in range(layers)])
126
+ self.ln = nn.LayerNorm(d)
127
+ self.head = nn.Linear(d, VOCAB, bias=False)
128
+ self.head.weight = self.emb.weight
129
+
130
+ def forward(self, x, mask=None):
131
+ x = self.emb(x)
132
+ for b in self.blocks:
133
+ x = b(x, mask)
134
+ return self.head(self.ln(x))
135
+
136
+
137
+ def train_joint(attn_type, d, layers, h, batch, seq, steps, ar_weight=0.5, block_size=4):
138
+ """Train with mixed AR and SAT objectives"""
139
+ print(f"\n{'='*60}")
140
+ print(f"JOINT AR+SAT: {attn_type.upper()} (AR weight={ar_weight})")
141
+ print(f"{'='*60}")
142
+
143
+ model = Model(d, layers, h, attn_type).to(DEV)
144
+ params = sum(p.numel() for p in model.parameters())
145
+ print(f"Parameters: {params:,}")
146
+
147
+ opt = torch.optim.AdamW(model.parameters(), lr=1e-4)
148
+
149
+ ar_mask = get_mask(seq - 1, "ar")
150
+ sat_mask = get_mask(seq - 1, "sat", block_size)
151
+
152
+ ar_losses, sat_losses, times = [], [], []
153
+
154
+ for step in range(steps):
155
+ ids = torch.randint(0, VOCAB, (batch, seq), device=DEV)
156
+ target = ids[:, 1:]
157
+ input_ids = ids[:, :-1]
158
+
159
+ start = time.time()
160
+ opt.zero_grad()
161
+
162
+ # AR forward
163
+ ar_logits = model(input_ids, ar_mask)
164
+ ar_loss = F.cross_entropy(ar_logits.view(-1, VOCAB), target.reshape(-1))
165
+
166
+ # SAT forward (same input, different mask)
167
+ sat_logits = model(input_ids, sat_mask)
168
+ sat_loss = F.cross_entropy(sat_logits.view(-1, VOCAB), target.reshape(-1))
169
+
170
+ # Combined loss
171
+ loss = ar_weight * ar_loss + (1 - ar_weight) * sat_loss
172
+ loss.backward()
173
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
174
+ opt.step()
175
+
176
+ elapsed = time.time() - start
177
+ ar_losses.append(ar_loss.item())
178
+ sat_losses.append(sat_loss.item())
179
+ times.append(elapsed)
180
+
181
+ if step % 50 == 0 or step == steps - 1:
182
+ tok_s = batch * seq / elapsed
183
+ print(f"Step {step:3d} | AR: {ar_loss.item():.2f} | SAT: {sat_loss.item():.2f} | {tok_s:.0f} tok/s")
184
+
185
+ avg_ar = sum(ar_losses[-20:]) / 20
186
+ avg_sat = sum(sat_losses[-20:]) / 20
187
+ avg_tok = batch * seq / (sum(times[-20:]) / 20)
188
+
189
+ return {"type": attn_type, "ar_loss": avg_ar, "sat_loss": avg_sat, "tok_s": avg_tok, "params": params}
190
+
191
+
192
+ def main():
193
+ parser = argparse.ArgumentParser()
194
+ parser.add_argument("--d", type=int, default=256)
195
+ parser.add_argument("--layers", type=int, default=4)
196
+ parser.add_argument("--heads", type=int, default=8)
197
+ parser.add_argument("--batch", type=int, default=16)
198
+ parser.add_argument("--seq", type=int, default=128)
199
+ parser.add_argument("--steps", type=int, default=200)
200
+ parser.add_argument("--block_size", type=int, default=4)
201
+ args = parser.parse_args()
202
+
203
+ print(f"Device: {DEV}")
204
+ if torch.cuda.is_available():
205
+ print(f"GPU: {torch.cuda.get_device_name()}")
206
+
207
+ print(f"\nJoint AR+SAT Training (block_size={args.block_size})")
208
+
209
+ results = []
210
+ for attn_type in ["standard", "mqa", "gqa", "gqa4"]:
211
+ r = train_joint(attn_type, args.d, args.layers, args.heads,
212
+ args.batch, args.seq, args.steps,
213
+ ar_weight=0.5, block_size=args.block_size)
214
+ results.append(r)
215
+ torch.cuda.empty_cache()
216
+
217
+ print(f"\n{'='*60}")
218
+ print("JOINT AR+SAT RESULTS")
219
+ print(f"{'='*60}")
220
+
221
+ std = next(r for r in results if r['type'] == 'standard')
222
+ for r in sorted(results, key=lambda x: x['ar_loss'] + x['sat_loss']):
223
+ combined = r['ar_loss'] + r['sat_loss']
224
+ std_combined = std['ar_loss'] + std['sat_loss']
225
+ diff = (std_combined - combined) / std_combined * 100
226
+
227
+ kv_ratio = {"standard": "1.00", "mqa": "0.12", "gqa": "0.25", "gqa4": "0.50"}[r['type']]
228
+
229
+ print(f"{r['type']:10s} | AR: {r['ar_loss']:.2f} | SAT: {r['sat_loss']:.2f} | "
230
+ f"Combined: {combined:.2f} ({diff:+.1f}%) | {r['tok_s']:.0f} tok/s | KV: {kv_ratio}x")
231
+
232
+
233
+ if __name__ == "__main__":
234
+ main()