MarxistLeninist commited on
Commit
abf63b5
·
verified ·
1 Parent(s): 961f534

Upload train.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. train.py +219 -0
train.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Training loop for the Binary Looped Transformer-Mamba Hybrid LM.
3
+
4
+ Data: streamed live from HuggingFace with datasets streaming=True
5
+ (byte-level; no corpus is downloaded). Falls back through a list of
6
+ datasets until one streams successfully.
7
+
8
+ Logs step/loss/tokens-per-second to state.json (atomic rewrite) and
9
+ history.jsonl for the GUI monitor. Checkpoints to ckpt_last.pt.
10
+ Exits cleanly when a file named STOP appears in this folder.
11
+ """
12
+
13
+ import json
14
+ import math
15
+ import os
16
+ import time
17
+ import traceback
18
+
19
+ import torch
20
+ import torch.nn.functional as F
21
+
22
+ from model import BinaryLoopHybridLM, count_params
23
+
24
+ HERE = os.path.dirname(os.path.abspath(__file__))
25
+ STATE = os.path.join(HERE, "state.json")
26
+ HISTORY = os.path.join(HERE, "history.jsonl")
27
+ CKPT = os.path.join(HERE, "ckpt_last.pt")
28
+ STOP = os.path.join(HERE, "STOP")
29
+
30
+ # ---------------------------------------------------------------------------
31
+ CFG = dict(
32
+ d_model=256, seq_len=256, batch_size=16,
33
+ n_ssm=3, n_loop_blocks=3, loops=3, n_head=8,
34
+ d_inner=384, d_state=8,
35
+ lr=3e-3, warmup=100, max_steps=200000,
36
+ ckpt_every=1000, sample_every=500,
37
+ )
38
+ # ---------------------------------------------------------------------------
39
+
40
+ DATASETS = [
41
+ ("roneneldan/TinyStories", None),
42
+ ("Salesforce/wikitext", "wikitext-103-raw-v1"),
43
+ ("Salesforce/wikitext", "wikitext-2-raw-v1"),
44
+ ]
45
+
46
+
47
+ def make_stream():
48
+ from datasets import load_dataset
49
+ last_err = None
50
+ for name, cfg in DATASETS:
51
+ try:
52
+ ds = load_dataset(name, cfg, split="train", streaming=True)
53
+ it = iter(ds)
54
+ buf = bytearray()
55
+ while len(buf) < 1 << 16:
56
+ row = next(it)
57
+ buf += row["text"].encode("utf-8", "ignore") + b"\n"
58
+ return name, it, buf
59
+ except Exception as e: # noqa: BLE001
60
+ last_err = e
61
+ continue
62
+ raise RuntimeError(f"no dataset could be streamed: {last_err}")
63
+
64
+
65
+ def refill(it, buf, need):
66
+ while len(buf) < need:
67
+ try:
68
+ row = next(it)
69
+ except StopIteration:
70
+ raise RuntimeError("stream ended")
71
+ buf += row["text"].encode("utf-8", "ignore") + b"\n"
72
+ return buf
73
+
74
+
75
+ def get_batch(it, buf, bs, seq, device):
76
+ need = bs * (seq + 1) * 2
77
+ buf = refill(it, buf, need)
78
+ chunk = bytes(buf[: bs * (seq + 1)])
79
+ del buf[: bs * (seq + 1) // 2] # slide by half a batch
80
+ arr = torch.frombuffer(bytearray(chunk), dtype=torch.uint8)
81
+ arr = arr.view(bs, seq + 1).long()
82
+ x = arr[:, :-1].to(device, non_blocking=True)
83
+ y = arr[:, 1:].to(device, non_blocking=True)
84
+ return x, y, buf
85
+
86
+
87
+ def write_state(state):
88
+ """Atomic state write. On Windows, os.replace can fail with WinError 5
89
+ while the GUI monitor has state.json open for reading; retry briefly
90
+ and never let a state-write failure kill training."""
91
+ tmp = STATE + ".tmp"
92
+ with open(tmp, "w", encoding="utf-8") as f:
93
+ json.dump(state, f)
94
+ for attempt in range(20):
95
+ try:
96
+ os.replace(tmp, STATE)
97
+ return
98
+ except PermissionError:
99
+ time.sleep(0.05)
100
+ except OSError:
101
+ return
102
+
103
+
104
+ def main():
105
+ torch.backends.cudnn.benchmark = True
106
+ device = "cuda" if torch.cuda.is_available() else "cpu"
107
+ cfg = CFG
108
+ model = BinaryLoopHybridLM(
109
+ d_model=cfg["d_model"], seq_len=cfg["seq_len"],
110
+ n_ssm=cfg["n_ssm"], n_loop_blocks=cfg["n_loop_blocks"],
111
+ loops=cfg["loops"], n_head=cfg["n_head"],
112
+ d_inner=cfg["d_inner"], d_state=cfg["d_state"]).to(device)
113
+ n_params = count_params(model)
114
+ n_binary = sum(p.numel() for m in model.modules()
115
+ if m.__class__.__name__ == "BinaryLinear"
116
+ for p in m.parameters(recurse=False)
117
+ if p.dim() == 2)
118
+ print(f"params total={n_params:,} binary-latent={n_binary:,}", flush=True)
119
+
120
+ ds_name, it, buf = make_stream()
121
+ print(f"streaming dataset: {ds_name}", flush=True)
122
+
123
+ opt = torch.optim.AdamW(model.parameters(), lr=cfg["lr"],
124
+ betas=(0.9, 0.95), weight_decay=0.0)
125
+
126
+ def lr_at(step):
127
+ if step < cfg["warmup"]:
128
+ return cfg["lr"] * (step + 1) / cfg["warmup"]
129
+ t = (step - cfg["warmup"]) / max(1, cfg["max_steps"] - cfg["warmup"])
130
+ return cfg["lr"] * (0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * min(t, 1))))
131
+
132
+ scaler = torch.amp.GradScaler("cuda", enabled=(device == "cuda"))
133
+ model.train()
134
+ step = 0
135
+ ema_loss = None
136
+ t0 = time.time()
137
+ tok_window = 0
138
+ t_window = time.time()
139
+ tok_s = 0.0
140
+ sample_text = ""
141
+ hist = open(HISTORY, "a", encoding="utf-8")
142
+
143
+ while step < cfg["max_steps"]:
144
+ if step % 20 == 0 and os.path.exists(STOP):
145
+ print("STOP file seen, exiting cleanly", flush=True)
146
+ break
147
+ for g in opt.param_groups:
148
+ g["lr"] = lr_at(step)
149
+ x, y, buf = get_batch(it, buf, cfg["batch_size"], cfg["seq_len"],
150
+ device)
151
+ with torch.amp.autocast("cuda", dtype=torch.float16,
152
+ enabled=(device == "cuda")):
153
+ logits = model(x)
154
+ loss = F.cross_entropy(
155
+ logits.reshape(-1, logits.size(-1)), y.reshape(-1))
156
+ scaler.scale(loss).backward()
157
+ scaler.unscale_(opt)
158
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
159
+ scaler.step(opt)
160
+ scaler.update()
161
+ opt.zero_grad(set_to_none=True)
162
+
163
+ lv = loss.item()
164
+ ema_loss = lv if ema_loss is None else 0.98 * ema_loss + 0.02 * lv
165
+ tok_window += cfg["batch_size"] * cfg["seq_len"]
166
+ step += 1
167
+
168
+ if step % 500 == 0:
169
+ try:
170
+ ids = model.generate(b"The ", 48, device)
171
+ sample_text = bytes(ids).decode("utf-8", "replace")
172
+ except Exception: # noqa: BLE001
173
+ sample_text = "(sample failed)"
174
+
175
+ if step % 5 == 0 or step == 1:
176
+ now = time.time()
177
+ dt = now - t_window
178
+ if dt > 0:
179
+ tok_s = tok_window / dt
180
+ tok_window = 0
181
+ t_window = now
182
+ gpu_mb = (torch.cuda.max_memory_allocated() / 1e6
183
+ if device == "cuda" else 0.0)
184
+ state = dict(
185
+ step=step, loss=round(lv, 4), ema_loss=round(ema_loss, 4),
186
+ tok_s=round(tok_s, 1), lr=lr_at(step),
187
+ elapsed_s=round(now - t0, 1), dataset=ds_name,
188
+ params=n_params, binary_latent_params=n_binary,
189
+ loops=cfg["loops"], d_model=cfg["d_model"],
190
+ batch_size=cfg["batch_size"], seq_len=cfg["seq_len"],
191
+ device=device, gpu_mem_mb=round(gpu_mb, 1),
192
+ sample=sample_text, pid=os.getpid(),
193
+ )
194
+ write_state(state)
195
+ try:
196
+ hist.write(json.dumps(state) + "\n")
197
+ hist.flush()
198
+ except OSError:
199
+ pass
200
+ print(f"step {step} loss {lv:.4f} ema {ema_loss:.4f} "
201
+ f"tok/s {tok_s:.0f}", flush=True)
202
+
203
+ if step % cfg["ckpt_every"] == 0:
204
+ try:
205
+ torch.save({"step": step, "model": model.state_dict(),
206
+ "cfg": cfg}, CKPT)
207
+ except OSError:
208
+ pass
209
+
210
+ torch.save({"step": step, "model": model.state_dict(), "cfg": cfg}, CKPT)
211
+ print("training finished", flush=True)
212
+
213
+
214
+ if __name__ == "__main__":
215
+ try:
216
+ main()
217
+ except Exception:
218
+ traceback.print_exc()
219
+ raise