phanerozoic commited on
Commit
864ba61
·
verified ·
1 Parent(s): e477540

Stage 4: specialist student (3.27M params, F1 0.710 vs 0.894 baseline)

Browse files
stage_4/README.md CHANGED
@@ -1,5 +1,73 @@
1
  # Stage 4: Specialist Backbone
2
 
3
- Reserved. See repo root README for plan.
4
 
5
- Scope: train a small student network that emits only the 100 target dims of EUPE-ViT-B, supervised against those dims on a large image corpus.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # Stage 4: Specialist Backbone
2
 
3
+ Train a compact student to reproduce the 40 target dimensions (20 person-positive + 20 person-negative) that the Stage 0 classifier reads out of EUPE-ViT-B. The student takes the same 768 pixel input as the teacher and emits a 40-D vector per image. Composed with the Stage 0 ternary classifier, this gives a full person-detection pipeline of **3.27M parameters**, versus 85.64M for the teacher.
4
 
5
+ ## Student architecture
6
+
7
+ Compact ViT, defined in `student.py`:
8
+
9
+ - Patch size 16, input 768 px → 48×48 = 2304 tokens
10
+ - Embed dim 192, depth 6 blocks, 3 heads per block, MLP ratio 4
11
+ - Final LayerNorm → max-pool over patches → Linear(192, 40)
12
+ - Total: 3,267,304 parameters (3.27M)
13
+
14
+ ## Training recipe
15
+
16
+ - Data: COCO train 2017 (117,266 images), resized to 768×768, ImageNet normalization
17
+ - Teacher targets: pre-computed by `prepare_targets.py` from the existing EUPE-ViT-B feature cache
18
+ - Loss: MSE on the 40-D output
19
+ - Optimizer: AdamW, lr 3e-4, weight decay 1e-4
20
+ - Schedule: cosine with 3% warmup
21
+ - Batch 16, 10 epochs, bfloat16 autocast
22
+ - Wall time: 26 minutes on one RTX 6000 Ada
23
+
24
+ ## Result
25
+
26
+ F1 = 0.710 on the 1000-image COCO val subset (Stage 0 classifier applied on top of the student's 40-D output, threshold swept).
27
+
28
+ ```
29
+ epoch loss F1 P R
30
+ 1 2.25 0.707 0.55 1.00
31
+ 3 2.01 0.717 0.57 0.97
32
+ 5 2.00 0.712 0.56 0.98
33
+ 10 1.99 0.710 0.57 0.95
34
+ ```
35
+
36
+ Loss plateaus around 2.0 after epoch 2. F1 converges near 0.71. Precision stays ~0.57 across all epochs while recall is >0.95 — the student learns "when in doubt, call it person" and rarely misses a true positive, but fires false on about half of person-negatives.
37
+
38
+ ## Comparison
39
+
40
+ ```
41
+ model params F1 on COCO val 1K
42
+ Stage 0 (EUPE-ViT-B + classifier) 85.64M 0.894
43
+ Stage 2 K=10 head prune + classifier 83.67M 0.916
44
+ Stage 4 student + classifier 3.27M 0.710
45
+ ```
46
+
47
+ 26× smaller than the full EUPE-ViT-B pipeline, F1 drop of 0.18 from baseline. A proof that the 40-D target manifold is learnable by a compact specialist but not yet a drop-in replacement for the teacher.
48
+
49
+ ## What this stage ships
50
+
51
+ - `student.py` — architecture definition
52
+ - `prepare_targets.py` — builds teacher target tensor from ViT-B feature cache
53
+ - `train.py` — distillation loop
54
+ - `student_final.safetensors` — trained student weights (10 epochs)
55
+ - `student_ep*.safetensors` — per-epoch checkpoints
56
+ - `training_log.json` — loss + F1 per epoch
57
+
58
+ ## Where the F1 gap comes from
59
+
60
+ The student converged on a high-recall / low-precision operating mode. Three likely contributors:
61
+
62
+ 1. **Capacity mismatch.** Going from 85.6M to 3.27M is an aggressive compression ratio. The EUPE teacher itself was distilled from a 1.9B proxy, then again to 86M — a further order-of-magnitude compression to 3M is harder than it looks.
63
+ 2. **Data limit.** Training on 117K COCO images is narrow. The teacher was trained on LVD-1689M (1.7B images) and absorbs much broader scene statistics. Re-training with a larger image corpus (ImageNet-1k or OpenImages) would likely help.
64
+ 3. **Loss choice.** MSE on 40 dimensions is a coarse target. Cosine similarity or a reconstruction-plus-contrastive loss over the teacher's full 768-D pooled vector would preserve more structure.
65
+
66
+ ## Natural next iteration (Stage 4B)
67
+
68
+ 1. Scale the student to 10–15M params (depth 8, dim 256).
69
+ 2. Add ImageNet as a second training corpus once its cache finishes.
70
+ 3. Switch loss to cosine on full 768-D pooled teacher output, project to 40-D only at inference.
71
+ 4. Longer schedule: 30 epochs.
72
+
73
+ Target: bring F1 above 0.85 at ≤15M total specialist-pipeline parameters.
stage_4/__pycache__/student.cpython-311.pyc ADDED
Binary file (6.72 kB). View file
 
stage_4/__pycache__/student.cpython-313.pyc ADDED
Binary file (5.88 kB). View file
 
stage_4/prepare_targets.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build the per-image 100-D teacher target tensor from the existing ViT-B
2
+ COCO train feature cache. One-time, ~5 min.
3
+
4
+ For each image in /home/zootest/datasets/coco/feature_cache_768 (the 419 GB
5
+ train cache of EUPE-ViT-B at 768 px), apply LayerNorm across the 768 channel
6
+ axis, max-pool across 2304 patches, and select the 100 classifier-relevant
7
+ dims (pos + neg). Save as a flat (N, 100) float16 tensor + index list.
8
+
9
+ Output: /home/zootest/datasets/coco/stage4_teacher_targets/targets.pt
10
+ containing {'targets': (N, 100) float16, 'img_ids': list, 'dims': (100,) long}
11
+ """
12
+ import os, glob, json, time
13
+ import torch
14
+ import torch.nn.functional as F
15
+
16
+ COCO_ROOT = '/home/zootest/datasets/coco'
17
+ CACHE = f'{COCO_ROOT}/feature_cache_768'
18
+ CLASSIFIER = '/mnt/d/_tmp/1pc_repo/stage_0/classifier.json'
19
+ OUT_DIR = f'{COCO_ROOT}/stage4_teacher_targets'
20
+ D = 768
21
+
22
+
23
+ def main():
24
+ os.makedirs(OUT_DIR, exist_ok=True)
25
+ with open(CLASSIFIER) as f:
26
+ c = json.load(f)
27
+ dims = torch.tensor(c['pos_dims'] + c['neg_dims'], dtype=torch.long)
28
+ print(f'[init] using {len(dims)} target dims', flush=True)
29
+
30
+ shards = sorted(glob.glob(f'{CACHE}/shard_*.pt'))
31
+ print(f'[init] {len(shards)} teacher shards to process', flush=True)
32
+
33
+ all_targets = []
34
+ all_img_ids = []
35
+ t0 = time.time()
36
+ for si, spath in enumerate(shards):
37
+ shard = torch.load(spath, map_location='cpu', weights_only=False)
38
+ for entry in shard:
39
+ sp = entry['spatial'].float() # (768, 48, 48)
40
+ ln = F.layer_norm(sp.permute(1, 2, 0).reshape(-1, D), [D])
41
+ pooled = ln.max(dim=0).values # (768,)
42
+ target = pooled[dims].half() # (100,)
43
+ all_targets.append(target)
44
+ # Some caches may not have img_id; use an ordinal if missing
45
+ img_id = entry.get('img_id', len(all_img_ids))
46
+ all_img_ids.append(int(img_id) if isinstance(img_id, (int, float)) else len(all_img_ids))
47
+ elapsed = time.time() - t0
48
+ rate = (si + 1) / max(elapsed, 1e-6)
49
+ eta = (len(shards) - si - 1) / max(rate, 1e-6)
50
+ print(f' shard {si+1}/{len(shards)} cumulative n={len(all_targets)} '
51
+ f'{elapsed:.0f}s ETA {eta:.1f}s', flush=True)
52
+
53
+ targets = torch.stack(all_targets)
54
+ torch.save({
55
+ 'targets': targets,
56
+ 'img_ids': all_img_ids,
57
+ 'dims': dims,
58
+ }, f'{OUT_DIR}/targets.pt')
59
+ print(f'[done] {targets.shape[0]} targets shape {tuple(targets.shape)} '
60
+ f'-> {OUT_DIR}/targets.pt', flush=True)
61
+
62
+
63
+ if __name__ == '__main__':
64
+ main()
stage_4/student.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stage 4 specialist student architecture.
2
+
3
+ Compact ViT designed to reproduce the 100 target dims of EUPE-ViT-B that
4
+ feed the Stage 0 classifier. Depth 6, embed 192, patch 16, 3 heads. Emits a
5
+ 100-D vector per image via a final projection from the max-pooled patch
6
+ tokens (plus global pool of CLS). Designed to pair with a frozen ternary
7
+ classifier head.
8
+ """
9
+ import math
10
+ import torch
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+
14
+
15
+ class PatchEmbed(nn.Module):
16
+ def __init__(self, in_ch=3, embed_dim=192, patch_size=16):
17
+ super().__init__()
18
+ self.proj = nn.Conv2d(in_ch, embed_dim, patch_size, stride=patch_size)
19
+
20
+ def forward(self, x):
21
+ x = self.proj(x)
22
+ B, C, H, W = x.shape
23
+ return x.flatten(2).transpose(1, 2), H, W # (B, HW, C)
24
+
25
+
26
+ class Block(nn.Module):
27
+ def __init__(self, dim, heads, mlp_ratio=4.0):
28
+ super().__init__()
29
+ self.norm1 = nn.LayerNorm(dim)
30
+ self.attn = nn.MultiheadAttention(dim, heads, batch_first=True)
31
+ self.norm2 = nn.LayerNorm(dim)
32
+ hidden = int(dim * mlp_ratio)
33
+ self.mlp = nn.Sequential(
34
+ nn.Linear(dim, hidden), nn.GELU(), nn.Linear(hidden, dim))
35
+
36
+ def forward(self, x):
37
+ h = self.norm1(x)
38
+ h, _ = self.attn(h, h, h, need_weights=False)
39
+ x = x + h
40
+ x = x + self.mlp(self.norm2(x))
41
+ return x
42
+
43
+
44
+ class SpecialistStudent(nn.Module):
45
+ """Compact ViT that outputs a 100-D vector per image."""
46
+
47
+ def __init__(self, out_dim=40, embed_dim=192, depth=6, heads=3,
48
+ patch_size=16, img_size=768, mlp_ratio=4.0):
49
+ super().__init__()
50
+ self.patch = PatchEmbed(3, embed_dim, patch_size)
51
+ self.num_patches = (img_size // patch_size) ** 2
52
+ self.pos = nn.Parameter(torch.zeros(1, self.num_patches, embed_dim))
53
+ nn.init.trunc_normal_(self.pos, std=0.02)
54
+ self.blocks = nn.ModuleList([Block(embed_dim, heads, mlp_ratio) for _ in range(depth)])
55
+ self.norm = nn.LayerNorm(embed_dim)
56
+ self.head = nn.Linear(embed_dim, out_dim)
57
+
58
+ def forward(self, x):
59
+ """x: (B, 3, H, W). Returns (B, out_dim)."""
60
+ tokens, H, W = self.patch(x)
61
+ tokens = tokens + self.pos[:, :tokens.shape[1]]
62
+ for blk in self.blocks:
63
+ tokens = blk(tokens)
64
+ tokens = self.norm(tokens) # (B, HW, embed_dim)
65
+ pooled = tokens.max(dim=1).values # (B, embed_dim) max-pool per image
66
+ return self.head(pooled) # (B, out_dim)
67
+
68
+
69
+ if __name__ == '__main__':
70
+ m = SpecialistStudent()
71
+ total = sum(p.numel() for p in m.parameters())
72
+ print(f'Specialist student total params: {total:,} = {total/1e6:.2f}M')
73
+ x = torch.randn(2, 3, 768, 768)
74
+ y = m(x)
75
+ print(f'forward OK output shape: {tuple(y.shape)}')
stage_4/student_ep1.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d1c1ecaa9ba94f1bd27b168caeecbb9ad358579d5c649f47eedc3ff9bcdc0eee
3
+ size 13076256
stage_4/student_ep10.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ecaec32943f4fef9b213af254789ac975418835a4ec0785f9e2ecc7e91abd831
3
+ size 13076256
stage_4/student_ep2.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:611b0be943b75d267c86f4b354ed0cbcb02d6f9d40f22ea4c0c21e63eda54575
3
+ size 13076256
stage_4/student_ep3.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8326f6df6637e0d5b1c4219fa4f7b731a2d6707a4969378eddf6429074085273
3
+ size 13076256
stage_4/student_ep4.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:51952f8338bb9f8c59de5f4f80eeaa69258c17daafa35bb9330e197b2f1aa615
3
+ size 13076256
stage_4/student_ep5.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d2159c00b9a59c23fa0acfcd29c320c0bb09c7cdc246e107e2e7b38194aa058b
3
+ size 13076256
stage_4/student_ep6.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1cc56f6025185e2ba31c9303db151fb1c1f1531b4fba679751cfaffdbc7623b2
3
+ size 13076256
stage_4/student_ep7.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8b9c7130ef5986d9190a173a7af0b0b0421f5d85a25b213006562b501bddc203
3
+ size 13076256
stage_4/student_ep8.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:07835d3a06a5c128d86e174830ec3d77148e0c067a60bcc76190395d4a65af0d
3
+ size 13076256
stage_4/student_ep9.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b2896d19e53ef2ad5d5be9e19c7df64702446f1d8053a3f1492923758464d0e2
3
+ size 13076256
stage_4/student_final.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ecaec32943f4fef9b213af254789ac975418835a4ec0785f9e2ecc7e91abd831
3
+ size 13076256
stage_4/train.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stage 4 training loop.
2
+
3
+ Train the compact specialist student to reproduce the 100 target dims that
4
+ EUPE-ViT-B produces for each COCO train image, using the per-image raw image
5
+ (resized to 768) as input. Target tensor is pre-computed by prepare_targets.py.
6
+
7
+ Loss: MSE on the 100-D output.
8
+ Optimizer: AdamW.
9
+ Schedule: cosine with 3% warmup.
10
+
11
+ Saves:
12
+ student_final.safetensors — best student weights
13
+ training_log.json — per-epoch loss + held-out F1 via Stage 0 classifier
14
+ """
15
+ import os, sys, time, json, math
16
+ import numpy as np
17
+ import torch
18
+ import torch.nn as nn
19
+ import torch.nn.functional as F
20
+ from PIL import Image
21
+ from pycocotools.coco import COCO
22
+ from safetensors.torch import save_file
23
+
24
+ HERE = os.path.dirname(os.path.abspath(__file__))
25
+ sys.path.insert(0, HERE)
26
+ from student import SpecialistStudent
27
+
28
+ COCO_ROOT = '/home/zootest/datasets/coco'
29
+ TARGETS = f'{COCO_ROOT}/stage4_teacher_targets/targets.pt'
30
+ CLASSIFIER = '/mnt/d/_tmp/1pc_repo/stage_0/classifier.json'
31
+ OUT_DIR = '/mnt/d/_tmp/1pc_repo/stage_4'
32
+ DEVICE = 'cuda'
33
+ RES = 768
34
+ BATCH = 16
35
+ LR = 3e-4
36
+ WD = 1e-4
37
+ EPOCHS = 10
38
+ WARMUP_FRAC = 0.03
39
+
40
+
41
+ class CocoImgDataset(torch.utils.data.Dataset):
42
+ def __init__(self, coco_root, targets_pack):
43
+ self.root = f'{coco_root}/train2017'
44
+ self.coco = COCO(f'{coco_root}/annotations/instances_train2017.json')
45
+ self.img_ids = targets_pack['img_ids']
46
+ self.targets = targets_pack['targets']
47
+ # Build filename lookup
48
+ self.id_to_file = {info['id']: info['file_name']
49
+ for info in self.coco.loadImgs(self.coco.getImgIds())}
50
+
51
+ def __len__(self):
52
+ return len(self.img_ids)
53
+
54
+ def __getitem__(self, i):
55
+ img_id = self.img_ids[i]
56
+ target = self.targets[i].float()
57
+ fname = self.id_to_file.get(img_id, None)
58
+ if fname is None:
59
+ return None
60
+ path = f'{self.root}/{fname}'
61
+ try:
62
+ img = Image.open(path).convert('RGB').resize((RES, RES), Image.BILINEAR)
63
+ except Exception:
64
+ return None
65
+ arr = np.asarray(img, dtype=np.uint8).copy()
66
+ x = torch.from_numpy(arr).permute(2, 0, 1).float() / 255.0
67
+ mean = torch.tensor([0.485, 0.456, 0.406]).view(3, 1, 1)
68
+ std = torch.tensor([0.229, 0.224, 0.225]).view(3, 1, 1)
69
+ x = (x - mean) / std
70
+ return x, target
71
+
72
+
73
+ def collate(batch):
74
+ batch = [b for b in batch if b is not None]
75
+ if len(batch) == 0:
76
+ return None
77
+ xs, ts = zip(*batch)
78
+ return torch.stack(xs), torch.stack(ts)
79
+
80
+
81
+ def eval_f1(student, classifier_json):
82
+ """Eval on COCO val 2017 image-level person classification."""
83
+ with open(classifier_json) as f:
84
+ c = json.load(f)
85
+ pos = c['pos_dims']
86
+ neg = c['neg_dims']
87
+ # Targets for student output are dims = pos + neg → 100-D. Inside that 100,
88
+ # pos is [0..19], neg is [20..39].
89
+ pos_idx = list(range(len(pos)))
90
+ neg_idx = list(range(len(pos), len(pos) + len(neg)))
91
+
92
+ coco = COCO(f'{COCO_ROOT}/annotations/instances_val2017.json')
93
+ img_ids = sorted(coco.getImgIds())[:1000]
94
+ id_to_file = {info['id']: info['file_name']
95
+ for info in coco.loadImgs(coco.getImgIds())}
96
+ MEAN = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1).to(DEVICE)
97
+ STD = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1).to(DEVICE)
98
+ scores = []
99
+ labels = []
100
+ with torch.inference_mode():
101
+ for img_id in img_ids:
102
+ fname = id_to_file.get(img_id)
103
+ if fname is None:
104
+ continue
105
+ img = Image.open(f'{COCO_ROOT}/val2017/{fname}').convert('RGB').resize((RES, RES), Image.BILINEAR)
106
+ arr = np.asarray(img, dtype=np.uint8).copy()
107
+ x = torch.from_numpy(arr).permute(2, 0, 1).unsqueeze(0).to(DEVICE).float() / 255.0
108
+ x = (x - MEAN) / STD
109
+ out = student(x).squeeze(0)
110
+ s = out[pos_idx].sum() - out[neg_idx].sum()
111
+ scores.append(s.item())
112
+ labels.append(any(a['category_id'] == 1
113
+ for a in coco.loadAnns(coco.getAnnIds(imgIds=img_id, iscrowd=False))))
114
+ scores = torch.tensor(scores)
115
+ labels = torch.tensor(labels, dtype=torch.bool)
116
+ # Sweep threshold
117
+ uniq = torch.unique(scores).sort().values
118
+ best = (0, 0, 0, 0)
119
+ for t in uniq.tolist()[::max(1, len(uniq) // 500)]:
120
+ pred = scores > t
121
+ tp = (pred & labels).sum().float()
122
+ fp = (pred & ~labels).sum().float()
123
+ fn = (~pred & labels).sum().float()
124
+ prec = tp / (tp + fp).clamp(min=1)
125
+ rec = tp / (tp + fn).clamp(min=1)
126
+ f1 = (2 * prec * rec / (prec + rec).clamp(min=1e-9)).item()
127
+ if f1 > best[0]:
128
+ best = (f1, t, prec.item(), rec.item())
129
+ return best
130
+
131
+
132
+ def main():
133
+ os.makedirs(OUT_DIR, exist_ok=True)
134
+ print('[init] loading targets', flush=True)
135
+ pack = torch.load(TARGETS, map_location='cpu', weights_only=False)
136
+ print(f' {pack["targets"].shape[0]} teacher targets', flush=True)
137
+
138
+ dataset = CocoImgDataset(COCO_ROOT, pack)
139
+ loader = torch.utils.data.DataLoader(
140
+ dataset, batch_size=BATCH, shuffle=True, num_workers=4,
141
+ pin_memory=True, collate_fn=collate, drop_last=True,
142
+ )
143
+
144
+ student = SpecialistStudent().to(DEVICE)
145
+ print(f'[student] {sum(p.numel() for p in student.parameters())/1e6:.2f}M params', flush=True)
146
+
147
+ total_steps = EPOCHS * len(loader)
148
+ warmup = int(total_steps * WARMUP_FRAC)
149
+ opt = torch.optim.AdamW(student.parameters(), lr=LR, weight_decay=WD)
150
+ sched = torch.optim.lr_scheduler.LambdaLR(
151
+ opt, lambda s: s / max(1, warmup) if s < warmup
152
+ else 0.5 * (1 + math.cos(math.pi * (s - warmup) / max(1, total_steps - warmup))))
153
+
154
+ log = {'epochs': [], 'student_params': int(sum(p.numel() for p in student.parameters()))}
155
+ step = 0
156
+ t0 = time.time()
157
+ for ep in range(EPOCHS):
158
+ student.train()
159
+ ep_loss, n_batches = 0.0, 0
160
+ for batch in loader:
161
+ if batch is None:
162
+ continue
163
+ x, y = batch
164
+ x = x.to(DEVICE, non_blocking=True)
165
+ y = y.to(DEVICE, non_blocking=True)
166
+ with torch.autocast('cuda', dtype=torch.bfloat16):
167
+ pred = student(x)
168
+ loss = F.mse_loss(pred.float(), y)
169
+ opt.zero_grad(set_to_none=True)
170
+ loss.backward()
171
+ torch.nn.utils.clip_grad_norm_(student.parameters(), 1.0)
172
+ opt.step()
173
+ sched.step()
174
+ ep_loss += loss.item()
175
+ n_batches += 1
176
+ step += 1
177
+ if step % 200 == 0:
178
+ print(f' ep {ep+1}/{EPOCHS} step {step}/{total_steps} '
179
+ f'loss={loss.item():.4f} lr={opt.param_groups[0]["lr"]:.2e} '
180
+ f'{(time.time()-t0)/60:.1f} min', flush=True)
181
+ avg = ep_loss / max(1, n_batches)
182
+ student.eval()
183
+ f1, thr, p, r = eval_f1(student, CLASSIFIER)
184
+ print(f'[ep {ep+1}] loss={avg:.4f} F1={f1:.4f} P={p:.4f} R={r:.4f} θ={thr:.3f}',
185
+ flush=True)
186
+ log['epochs'].append({'epoch': ep + 1, 'loss': avg,
187
+ 'F1': f1, 'precision': p, 'recall': r, 'threshold': thr})
188
+ # Save after each epoch
189
+ save_file(student.state_dict(), f'{OUT_DIR}/student_ep{ep+1}.safetensors')
190
+ with open(f'{OUT_DIR}/training_log.json', 'w') as f:
191
+ json.dump(log, f, indent=2)
192
+
193
+ # Final save
194
+ save_file(student.state_dict(), f'{OUT_DIR}/student_final.safetensors')
195
+ print(f'[done] total time {(time.time()-t0)/60:.1f} min', flush=True)
196
+
197
+
198
+ if __name__ == '__main__':
199
+ main()
stage_4/training_log.json ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "epochs": [
3
+ {
4
+ "epoch": 1,
5
+ "loss": 2.2497359863064306,
6
+ "F1": 0.7068741917610168,
7
+ "precision": 0.5471887588500977,
8
+ "recall": 0.9981684684753418,
9
+ "threshold": 27.844703674316406
10
+ },
11
+ {
12
+ "epoch": 2,
13
+ "loss": 2.006192959226011,
14
+ "F1": 0.7077131867408752,
15
+ "precision": 0.5611587762832642,
16
+ "recall": 0.9578754305839539,
17
+ "threshold": 29.012691497802734
18
+ },
19
+ {
20
+ "epoch": 3,
21
+ "loss": 2.0050793833516254,
22
+ "F1": 0.7173912525177002,
23
+ "precision": 0.5701943635940552,
24
+ "recall": 0.9670329689979553,
25
+ "threshold": 26.3531494140625
26
+ },
27
+ {
28
+ "epoch": 4,
29
+ "loss": 2.008850994551679,
30
+ "F1": 0.7111111283302307,
31
+ "precision": 0.5528455376625061,
32
+ "recall": 0.9963369965553284,
33
+ "threshold": 26.654373168945312
34
+ },
35
+ {
36
+ "epoch": 5,
37
+ "loss": 1.9956948308571767,
38
+ "F1": 0.7116155028343201,
39
+ "precision": 0.5598739385604858,
40
+ "recall": 0.976190447807312,
41
+ "threshold": 26.531875610351562
42
+ },
43
+ {
44
+ "epoch": 6,
45
+ "loss": 2.001336439533982,
46
+ "F1": 0.7114093899726868,
47
+ "precision": 0.5614407062530518,
48
+ "recall": 0.970695972442627,
49
+ "threshold": 25.896560668945312
50
+ },
51
+ {
52
+ "epoch": 7,
53
+ "loss": 1.9895635365096358,
54
+ "F1": 0.7127659916877747,
55
+ "precision": 0.5594989657402039,
56
+ "recall": 0.9816849827766418,
57
+ "threshold": 26.533084869384766
58
+ },
59
+ {
60
+ "epoch": 8,
61
+ "loss": 1.9920095616759776,
62
+ "F1": 0.7133058905601501,
63
+ "precision": 0.5701754093170166,
64
+ "recall": 0.9523809552192688,
65
+ "threshold": 26.670108795166016
66
+ },
67
+ {
68
+ "epoch": 9,
69
+ "loss": 1.9944281049740566,
70
+ "F1": 0.7095890045166016,
71
+ "precision": 0.5667396187782288,
72
+ "recall": 0.9487179517745972,
73
+ "threshold": 26.39623260498047
74
+ },
75
+ {
76
+ "epoch": 10,
77
+ "loss": 1.9913188398937247,
78
+ "F1": 0.7101648449897766,
79
+ "precision": 0.5681318640708923,
80
+ "recall": 0.946886420249939,
81
+ "threshold": 26.328819274902344
82
+ }
83
+ ],
84
+ "student_params": 3267304
85
+ }