LJTSG commited on
Commit
be4a6c0
Β·
verified Β·
1 Parent(s): 4b82a67

Upload train_decoder.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. train_decoder.py +332 -0
train_decoder.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """train_decoder.py β€” Train the RMM Meaning Decoder.
2
+
3
+ Takes a high-dimensional vector from the entity's embedding space and
4
+ decodes it to text using the entity's own BPE tokenizer. A learned
5
+ projection maps the vector to soft prefix tokens, which condition a
6
+ causal transformer for autoregressive generation.
7
+
8
+ Run: modal run train_decoder.py
9
+ Pull: modal volume get rmm-vol /meaning-decoder/ ./meaning-decoder-out/
10
+
11
+ Requires:
12
+ - spine.json: {"memories": [{"text": "...", "vector": [...3072...], "emotional_weight": 8, "source": "conversation"}, ...]}
13
+ - tokenizer.json: HuggingFace tokenizers-format BPE tokenizer (train with tokenizers lib or use entity's existing one)
14
+ """
15
+ import modal, json
16
+ from pathlib import Path
17
+
18
+ app = modal.App("rmm-decoder")
19
+ image = (modal.Image.debian_slim(python_version="3.11")
20
+ .pip_install("torch==2.6.0", "numpy", "tokenizers"))
21
+ vol = modal.Volume.from_name("rmm-vol", create_if_missing=True)
22
+
23
+ # ── Point these at your entity's data ──
24
+ SPINE_FILE = Path("spine.json")
25
+ TOKENIZER_FILE = Path("tokenizer.json")
26
+
27
+ SPINE_DIM = 3072
28
+ D_MODEL = 384
29
+ N_HEADS = 6
30
+ N_LAYERS = 6
31
+ N_PREFIX = 12
32
+ MAX_SEQ = 128
33
+ VOCAB = 8192
34
+ DROPOUT = 0.12
35
+
36
+
37
+ @app.function(image=image, gpu="A10G", timeout=3600, volumes={"/vol": vol})
38
+ def train(spine_json: str, tokenizer_json: str, smoke: bool = False):
39
+ import os, math, time, json, re
40
+ import numpy as np
41
+ import torch
42
+ import torch.nn as nn
43
+ import torch.nn.functional as F
44
+ from tokenizers import Tokenizer
45
+
46
+ DEV = "cuda"
47
+ print(f"[decoder] gpu={torch.cuda.get_device_name(0)}")
48
+
49
+ tk = Tokenizer.from_str(tokenizer_json)
50
+ eot_id = tk.token_to_id("<eot>")
51
+ print(f"[decoder] tokenizer loaded, vocab={tk.get_vocab_size()}, eot_id={eot_id}")
52
+
53
+ spine_data = json.loads(spine_json)
54
+ mems = spine_data["memories"]
55
+
56
+ # ── Text preprocessing ──
57
+ SURR = re.compile(r'[\ud800-\udfff]')
58
+ PREFIXES = [
59
+ re.compile(r'^\[conversation\]\s*I replied\s*\(puppet\):\s*["\']?', re.I),
60
+ re.compile(r'^[A-Za-z]+:\s*', re.I), # strip "Name:" prefixes
61
+ re.compile(r'^\*[^*]+\*\s*\n*', re.I),
62
+ ]
63
+ FORMAT_HEADERS = [
64
+ re.compile(r'^Sonic Experience:\s*[^\n]*\n+', re.I),
65
+ re.compile(r'^HourlyCycle:\s*HOURLY CHECK-IN\s*\([^)]*\)\s*\n+', re.I),
66
+ re.compile(r'^Journal\s*[---]+\s*[^\n]*\n+', re.I),
67
+ re.compile(r'^(?:Creative|CREATIVE)\s+Work:\s*[^\n]*\n+', re.I),
68
+ ]
69
+
70
+ def clean_text(raw, source):
71
+ t = SURR.sub('', raw).strip()
72
+ for pat in PREFIXES:
73
+ t = pat.sub('', t).strip()
74
+ for pat in FORMAT_HEADERS:
75
+ t = pat.sub('', t).strip()
76
+ t = t.lstrip('"\'- ').strip()
77
+ if len(t) > 250:
78
+ cutoffs = [t.rfind('. ', 0, 250), t.rfind('? ', 0, 250),
79
+ t.rfind('! ', 0, 250), t.rfind('\n', 0, 250)]
80
+ best = max(c for c in cutoffs if c > 50) if any(c > 50 for c in cutoffs) else 250
81
+ t = t[:best+1].strip()
82
+ return t
83
+
84
+ DIALOGUE_SOURCES = {'conversation', 'chat', 'discord', 'puppet'}
85
+
86
+ vectors, texts, ew_list, is_dialogue = [], [], [], []
87
+ for m in mems:
88
+ vec = m.get("vector")
89
+ raw = str(m.get("text") or "")
90
+ source = m.get("source", "unknown")
91
+ text = clean_text(raw, source)
92
+ if vec and len(text) >= 10 and len(vec) == SPINE_DIM:
93
+ vectors.append(vec)
94
+ texts.append(text)
95
+ ew_list.append(m.get("emotional_weight", 5))
96
+ is_dialogue.append(source in DIALOGUE_SOURCES)
97
+
98
+ n_dialogue = sum(is_dialogue)
99
+ print(f"[decoder] {len(vectors)} valid pairs ({n_dialogue} dialogue, {len(vectors)-n_dialogue} other)")
100
+
101
+ # ── Tokenization ──
102
+ encoded = []
103
+ for t in texts:
104
+ ids = tk.encode(t).ids
105
+ if eot_id is not None:
106
+ ids = ids + [eot_id]
107
+ encoded.append(ids[:MAX_SEQ])
108
+
109
+ max_tok_len = min(max(len(e) for e in encoded), MAX_SEQ)
110
+ print(f"[decoder] max token length: {max_tok_len}")
111
+
112
+ vec_tensor = torch.tensor(vectors, dtype=torch.float32)
113
+ vec_tensor = F.normalize(vec_tensor, dim=-1)
114
+
115
+ PAD_ID = -100
116
+ tok_tensor = torch.zeros(len(encoded), max_tok_len, dtype=torch.long)
117
+ tgt_tensor = torch.full((len(encoded), max_tok_len), PAD_ID, dtype=torch.long)
118
+ len_tensor = torch.zeros(len(encoded), dtype=torch.long)
119
+ for i, ids in enumerate(encoded):
120
+ L = min(len(ids), max_tok_len)
121
+ tok_tensor[i, :L] = torch.tensor(ids[:L], dtype=torch.long)
122
+ tgt_tensor[i, :L] = torch.tensor(ids[:L], dtype=torch.long)
123
+ len_tensor[i] = L
124
+
125
+ ew_raw = torch.tensor(ew_list, dtype=torch.float32)
126
+ dial = torch.tensor(is_dialogue, dtype=torch.float32)
127
+ pair_weights = 1.0 + 0.3 * (ew_raw - 5.0) / 5.0
128
+ pair_weights = pair_weights * (1.0 + 0.5 * dial)
129
+ pair_weights = pair_weights / pair_weights.mean()
130
+
131
+ avg_len = len_tensor.float().mean().item()
132
+ print(f"[decoder] avg tokens/memory: {avg_len:.0f}, {len(vec_tensor)} samples")
133
+
134
+ # ── Model ──
135
+ class MeaningDecoder(nn.Module):
136
+ def __init__(self):
137
+ super().__init__()
138
+ self.n_prefix = N_PREFIX
139
+ self.vec_proj = nn.Sequential(
140
+ nn.Linear(SPINE_DIM, 768),
141
+ nn.GELU(),
142
+ nn.Dropout(DROPOUT),
143
+ nn.Linear(768, N_PREFIX * D_MODEL),
144
+ )
145
+ self.tok_emb = nn.Embedding(VOCAB, D_MODEL)
146
+ self.pos_emb = nn.Embedding(N_PREFIX + MAX_SEQ + 1, D_MODEL)
147
+ self.drop = nn.Dropout(DROPOUT)
148
+
149
+ layer = nn.TransformerEncoderLayer(
150
+ d_model=D_MODEL, nhead=N_HEADS,
151
+ dim_feedforward=D_MODEL * 4,
152
+ dropout=DROPOUT, batch_first=True,
153
+ norm_first=True
154
+ )
155
+ self.transformer = nn.TransformerEncoder(layer, num_layers=N_LAYERS)
156
+
157
+ self.ln_f = nn.LayerNorm(D_MODEL)
158
+ self.head = nn.Linear(D_MODEL, VOCAB, bias=False)
159
+ self.head.weight = self.tok_emb.weight
160
+ self._logit_scale = D_MODEL ** -0.5
161
+
162
+ def forward(self, vec, tokens=None):
163
+ B = vec.shape[0]
164
+ prefix = self.vec_proj(vec).reshape(B, self.n_prefix, D_MODEL)
165
+
166
+ if tokens is not None and tokens.shape[1] > 0:
167
+ T = tokens.shape[1]
168
+ tok = self.tok_emb(tokens)
169
+ x = torch.cat([prefix, tok], dim=1)
170
+ else:
171
+ x = prefix
172
+ T = 0
173
+
174
+ total = x.shape[1]
175
+ pos = self.pos_emb(torch.arange(total, device=vec.device))
176
+ x = self.drop(x + pos)
177
+
178
+ mask = nn.Transformer.generate_square_subsequent_mask(
179
+ total, device=vec.device
180
+ )
181
+ x = self.transformer(x, mask=mask)
182
+ x = self.ln_f(x)
183
+ return self.head(x) * self._logit_scale
184
+
185
+ model = MeaningDecoder().to(DEV)
186
+ n_params = sum(p.numel() for p in model.parameters())
187
+ print(f"[decoder] model {n_params/1e6:.1f}M params")
188
+
189
+ # ── Training ──
190
+ ITERS = 200 if smoke else 15000
191
+ BS = 32
192
+ M = len(vec_tensor)
193
+
194
+ opt = torch.optim.AdamW(model.parameters(), lr=3e-4, weight_decay=0.02)
195
+ warmup_steps = 500 if not smoke else 20
196
+ def lr_lambda(step):
197
+ if step < warmup_steps:
198
+ return step / warmup_steps
199
+ progress = (step - warmup_steps) / max(1, ITERS - warmup_steps)
200
+ return 0.5 * (1 + math.cos(math.pi * progress))
201
+ sch = torch.optim.lr_scheduler.LambdaLR(opt, lr_lambda)
202
+
203
+ t0 = time.time()
204
+ best_loss = float('inf')
205
+ best_state = None
206
+ K = N_PREFIX
207
+
208
+ for step in range(ITERS):
209
+ idx = torch.randint(0, M, (BS,))
210
+ v_batch = vec_tensor[idx].to(DEV)
211
+
212
+ v_batch = v_batch + 0.03 * torch.randn_like(v_batch)
213
+ v_batch = F.normalize(v_batch, dim=-1)
214
+
215
+ t_full = tok_tensor[idx].to(DEV)
216
+ targets = tgt_tensor[idx].to(DEV)
217
+
218
+ inputs = t_full[:, :-1]
219
+ T = targets.shape[1]
220
+
221
+ logits = model(v_batch, inputs)
222
+
223
+ pred = logits[:, K-1 : K+T-1, :]
224
+ raw_loss = F.cross_entropy(
225
+ pred.reshape(-1, VOCAB), targets.reshape(-1),
226
+ ignore_index=PAD_ID, reduction='none',
227
+ label_smoothing=0.05,
228
+ )
229
+ raw_loss = raw_loss.view(BS, T)
230
+
231
+ per_sample = raw_loss.sum(dim=1) / (targets != PAD_ID).sum(dim=1).float().clamp(min=1)
232
+ w = pair_weights[idx].to(DEV)
233
+ loss = (per_sample * w).mean()
234
+
235
+ opt.zero_grad()
236
+ loss.backward()
237
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
238
+ opt.step()
239
+ sch.step()
240
+
241
+ if step % (20 if smoke else 500) == 0:
242
+ lv = loss.item()
243
+ ppl = math.exp(min(lv, 20))
244
+ mark = " <-" if lv < best_loss else ""
245
+ print(f" [decoder] step {step:5d} loss={lv:.4f} ppl={ppl:.1f} ({time.time()-t0:.0f}s){mark}")
246
+ if lv < best_loss:
247
+ best_loss = lv
248
+ best_state = {k: v.cpu().clone() for k, v in model.state_dict().items()}
249
+
250
+ if best_state:
251
+ model.load_state_dict(best_state)
252
+
253
+ # ── Save ──
254
+ os.makedirs("/vol/meaning-decoder", exist_ok=True)
255
+ torch.save({k: v.cpu() for k, v in model.state_dict().items()},
256
+ "/vol/meaning-decoder/decoder.pt")
257
+
258
+ config = {
259
+ "spine_dim": SPINE_DIM, "d_model": D_MODEL, "n_heads": N_HEADS,
260
+ "n_layers": N_LAYERS, "n_prefix": N_PREFIX, "max_seq": MAX_SEQ,
261
+ "vocab": VOCAB, "params_m": n_params / 1e6, "best_loss": best_loss,
262
+ "version": 2,
263
+ }
264
+ with open("/vol/meaning-decoder/config.json", "w") as f:
265
+ json.dump(config, f, indent=2)
266
+
267
+ with open("/vol/meaning-decoder/tokenizer.json", "w") as f:
268
+ f.write(tokenizer_json)
269
+
270
+ vol.commit()
271
+ print(f"[decoder] DONE best_loss={best_loss:.4f} saved to /vol/meaning-decoder/")
272
+
273
+ # ── Inference test ──
274
+ model.eval()
275
+
276
+ def generate_from_vec(v, max_len=60, temp=0.7, top_p=0.9, rep_penalty=1.3):
277
+ v = v.unsqueeze(0) if v.dim() == 1 else v
278
+ generated = []
279
+ for _ in range(max_len):
280
+ tok_in = torch.tensor([generated], dtype=torch.long, device=DEV) if generated else None
281
+ with torch.no_grad():
282
+ logits = model(v, tok_in)
283
+ next_logits = logits[0, -1, :] / temp
284
+ if generated:
285
+ for tid in set(generated):
286
+ next_logits[tid] /= rep_penalty
287
+ probs = F.softmax(next_logits, dim=-1)
288
+ sp, si = torch.sort(probs, descending=True)
289
+ cp = sp.cumsum(0)
290
+ sp[cp - sp > top_p] = 0
291
+ sp = sp / sp.sum()
292
+ nxt = si[torch.multinomial(sp, 1)].item()
293
+ if eot_id is not None and nxt == eot_id:
294
+ break
295
+ generated.append(nxt)
296
+ return tk.decode(generated)
297
+
298
+ test_indices = [0, 50, 150, 300, 600, 1000, 2000, 3000]
299
+ for ti in test_indices:
300
+ if ti >= M:
301
+ continue
302
+ v = vec_tensor[ti].to(DEV)
303
+ gen = generate_from_vec(v)
304
+ gt = texts[ti][:120]
305
+ print(f"\n [{ti}] ew={ew_list[ti]}")
306
+ print(f" GT: {gt}")
307
+ print(f" GEN: {gen[:120]}")
308
+
309
+ print("\n--- Interpolation tests ---")
310
+ for (a, b) in [(0, 100), (50, 500), (200, 2000)]:
311
+ if b >= M:
312
+ continue
313
+ va = vec_tensor[a].to(DEV)
314
+ vb = vec_tensor[b].to(DEV)
315
+ vmid = F.normalize(0.5 * va + 0.5 * vb, dim=-1)
316
+ gen = generate_from_vec(vmid)
317
+ print(f"\n [{a}+{b}] interp:")
318
+ print(f" A: {texts[a][:80]}")
319
+ print(f" B: {texts[b][:80]}")
320
+ print(f" MID: {gen[:120]}")
321
+
322
+ return {"best_loss": best_loss, "params_m": n_params / 1e6}
323
+
324
+
325
+ @app.local_entrypoint()
326
+ def main(smoke: bool = False):
327
+ spine_json = SPINE_FILE.read_text(encoding="utf-8", errors="ignore")
328
+ tokenizer_json = TOKENIZER_FILE.read_text(encoding="utf-8")
329
+ spine = json.loads(spine_json)
330
+ print(f"[local] spine={len(spine_json)//1024}KB memories={len(spine['memories'])} tokenizer=loaded smoke={smoke}")
331
+ r = train.remote(spine_json, tokenizer_json, smoke=smoke)
332
+ print(f"[local] done loss={r['best_loss']:.4f} params={r['params_m']:.1f}M")