krystv commited on
Commit
2c078fc
·
verified ·
1 Parent(s): 4197dd6

Upload train_gpu.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. train_gpu.py +174 -0
train_gpu.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ LRF Extended Training — more epochs on CPU with cached latents.
4
+ Uses the same proven architecture from v3, just trains longer.
5
+ Pushes results to HF Hub.
6
+ """
7
+ import math, os, sys, time, json
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ from torch.utils.data import DataLoader, TensorDataset
12
+ from einops import rearrange
13
+ import numpy as np
14
+
15
+ DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
16
+
17
+ # Reuse the exact architecture from lrf_v3.py
18
+ sys.path.insert(0, '/app')
19
+ from lrf_v3 import LRF, FlowScheduler, get_taesd, get_cifar, precompute, save_grid, gen
20
+
21
+ def main():
22
+ OUT = '/app/lrf_extended'
23
+ REPO = 'krystv/LatentRecurrentFlow'
24
+ os.makedirs(OUT, exist_ok=True)
25
+
26
+ EPOCHS = 100 # 3x more than v3
27
+ BS = 128 # Bigger batch
28
+ LR = 5e-4 # Slightly higher LR for faster convergence
29
+
30
+ print("=" * 60, flush=True)
31
+ print(f"LRF Extended Training — {EPOCHS} epochs, bs={BS}", flush=True)
32
+ print(f"Device: {DEVICE}", flush=True)
33
+ print("=" * 60, flush=True)
34
+
35
+ # VAE + Data (use cached latents from v3 if available)
36
+ print("\n[1] Loading TAESD + CIFAR-10...", flush=True)
37
+ vae = get_taesd(DEVICE)
38
+ tr, te = get_cifar()
39
+
40
+ # Check for cached latents from previous run
41
+ cache_dir = '/app/lrf_out'
42
+ if os.path.exists(f'{cache_dir}/cache_train.pt'):
43
+ print(" Using cached latents from v3 run!", flush=True)
44
+ tr_lat, tr_lab = precompute(vae, tr, 256, DEVICE, f'{cache_dir}/cache_train.pt')
45
+ else:
46
+ tr_lat, tr_lab = precompute(vae, tr, 256, DEVICE, f'{OUT}/cache_train.pt')
47
+
48
+ # Model — use the proven fast config
49
+ print("\n[2] Creating model...", flush=True)
50
+ cfg = LRF.default()
51
+ model = LRF(cfg).to(DEVICE)
52
+ print(f" {model.count():,} params", flush=True)
53
+
54
+ # Try to warm-start from v3 checkpoint
55
+ v3_ckpt = '/app/lrf_out/model.pt'
56
+ if os.path.exists(v3_ckpt):
57
+ print(f" Warm-starting from {v3_ckpt}", flush=True)
58
+ ckpt = torch.load(v3_ckpt, map_location=DEVICE, weights_only=False)
59
+ model.load_state_dict(ckpt['state'])
60
+ prev_losses = ckpt.get('losses', [])
61
+ print(f" Previous best loss: {min(prev_losses):.4f}", flush=True)
62
+ else:
63
+ prev_losses = []
64
+
65
+ # Train
66
+ print(f"\n[3] Training {EPOCHS} epochs...", flush=True)
67
+ sched = FlowScheduler()
68
+ opt = torch.optim.AdamW(model.parameters(), lr=LR, weight_decay=0.01, betas=(0.9, 0.95))
69
+ total_steps = EPOCHS * (len(tr_lat) // BS)
70
+ lr_sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, total_steps, LR * 0.01)
71
+ ema = {n: p.clone().detach() for n, p in model.named_parameters()}
72
+ losses = list(prev_losses) # Continue loss history
73
+
74
+ dl = DataLoader(TensorDataset(tr_lat, tr_lab), BS, shuffle=True, drop_last=True, num_workers=0)
75
+ best_loss = min(losses) if losses else 999
76
+ t0 = time.time()
77
+
78
+ for ep in range(EPOCHS):
79
+ model.train()
80
+ el, nb = 0, 0
81
+ for lat, lab in dl:
82
+ lat, lab = lat.to(DEVICE), lab.to(DEVICE)
83
+ B = lat.shape[0]
84
+ t = sched.sample_t(B, DEVICE)
85
+ eps = torch.randn_like(lat)
86
+ zt = sched.add_noise(lat, eps, t)
87
+ vp = model.predict_v(zt, t, lab, cfg_drop=0.1)
88
+ vt = sched.velocity(lat, eps)
89
+ lps = (vp - vt).pow(2).mean([1,2,3])
90
+ w = 1.0 / (t * (1-t) + 0.01); w = w / w.mean()
91
+ loss = (lps * w).mean()
92
+ opt.zero_grad(); loss.backward()
93
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
94
+ opt.step(); lr_sched.step()
95
+ with torch.no_grad():
96
+ for n, p in model.named_parameters():
97
+ ema[n].mul_(0.9995).add_(p, alpha=0.0005)
98
+ el += loss.item(); nb += 1
99
+
100
+ al = el / nb
101
+ losses.append(al)
102
+ if al < best_loss: best_loss = al
103
+ elapsed = time.time() - t0
104
+
105
+ if (ep+1) % 10 == 0 or ep == 0 or ep == EPOCHS-1:
106
+ print(f" Ep {ep+1:3d}/{EPOCHS}: loss={al:.4f} best={best_loss:.4f} "
107
+ f"lr={opt.param_groups[0]['lr']:.1e} {elapsed:.0f}s", flush=True)
108
+
109
+ # Sample every 25 epochs
110
+ if (ep+1) % 25 == 0 or ep == EPOCHS-1:
111
+ bak = {n: p.clone() for n, p in model.named_parameters()}
112
+ with torch.no_grad():
113
+ for n, p in model.named_parameters(): p.copy_(ema[n])
114
+ model.eval()
115
+ samps = gen(model, vae, sched, DEVICE, 16, 20, 2.5)
116
+ save_grid(samps, f'{OUT}/ep{ep+1:03d}.png', 4)
117
+ with torch.no_grad():
118
+ for n, p in model.named_parameters(): p.copy_(bak[n])
119
+
120
+ # Final EMA
121
+ with torch.no_grad():
122
+ for n, p in model.named_parameters(): p.copy_(ema[n])
123
+ model.eval()
124
+
125
+ # Final generation
126
+ print(f"\n[4] Final generation...", flush=True)
127
+ classes = ['airplane','auto','bird','cat','deer','dog','frog','horse','ship','truck']
128
+ all_s = []
129
+ for ci in range(10):
130
+ s = gen(model, vae, sched, DEVICE, 8, 50, 3.0, ci)
131
+ all_s.append(s)
132
+ print(f" {classes[ci]:10s}: std={s.std():.3f}", flush=True)
133
+ save_grid(torch.cat(all_s), f'{OUT}/final.png', 8)
134
+
135
+ # Save
136
+ torch.save({'state': model.state_dict(), 'cfg': cfg, 'losses': losses}, f'{OUT}/model.pt')
137
+
138
+ # Loss plot
139
+ try:
140
+ import matplotlib; matplotlib.use('Agg'); import matplotlib.pyplot as plt
141
+ plt.figure(figsize=(10,4))
142
+ plt.plot(losses, 'b-', alpha=0.7)
143
+ if prev_losses:
144
+ plt.axvline(x=len(prev_losses), color='r', linestyle='--', alpha=0.5, label='Extended training start')
145
+ plt.legend()
146
+ plt.xlabel('Epoch'); plt.ylabel('Loss')
147
+ plt.title(f'LRF Training (best={best_loss:.4f})')
148
+ plt.grid(True, alpha=0.3)
149
+ plt.savefig(f'{OUT}/loss.png', dpi=150, bbox_inches='tight'); plt.close()
150
+ except: pass
151
+
152
+ # Push to Hub
153
+ print(f"\n[5] Pushing to Hub...", flush=True)
154
+ from huggingface_hub import HfApi
155
+ api = HfApi()
156
+ for f in sorted(os.listdir(OUT)):
157
+ fp = os.path.join(OUT, f)
158
+ if f.endswith(('.pt', '.png')) and os.path.getsize(fp) < 100_000_000 and 'cache' not in f:
159
+ api.upload_file(path_or_fileobj=fp, path_in_repo=f'gpu_trained/{f}',
160
+ repo_id=REPO, repo_type='model')
161
+ print(f" Uploaded gpu_trained/{f}", flush=True)
162
+
163
+ # Upload train script
164
+ api.upload_file(path_or_fileobj='/app/train_extended.py', path_in_repo='train_gpu.py',
165
+ repo_id=REPO, repo_type='model')
166
+ print(f" Uploaded train_gpu.py", flush=True)
167
+
168
+ print(f"\n{'='*60}", flush=True)
169
+ print(f"DONE! Best loss: {best_loss:.4f}", flush=True)
170
+ print(f"See: https://huggingface.co/{REPO}", flush=True)
171
+ print(f"{'='*60}", flush=True)
172
+
173
+ if __name__ == '__main__':
174
+ main()