Stage 4B: 15.67M student + cosine loss on 768-D, F1 0.723 (+0.013 over Stage 4)
Browse files- stage_4b/README.md +42 -0
- stage_4b/__pycache__/student.cpython-311.pyc +0 -0
- stage_4b/prepare_targets_768.py +44 -0
- stage_4b/student.py +68 -0
- stage_4b/student_ep10.safetensors +3 -0
- stage_4b/student_ep15.safetensors +3 -0
- stage_4b/student_ep5.safetensors +3 -0
- stage_4b/student_final.safetensors +3 -0
- stage_4b/train.py +176 -0
- stage_4b/training_log.json +127 -0
stage_4b/README.md
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Stage 4B: Larger Specialist with Cosine Loss
|
| 2 |
+
|
| 3 |
+
Tried the natural next knobs on Stage 4's specialist student: 5× bigger model, cosine similarity loss on the full 768-D pooled teacher output, longer schedule.
|
| 4 |
+
|
| 5 |
+
## Setup
|
| 6 |
+
|
| 7 |
+
- **Architecture**: depth 8, embed 384, 6 heads, MLP ratio 4, patch 16 → **15.67M parameters**
|
| 8 |
+
- **Target**: full 768-D pooled layernormed output from EUPE-ViT-B (not the 40-dim subset used in Stage 4)
|
| 9 |
+
- **Loss**: 1 − cosine_similarity(student_output, teacher_target)
|
| 10 |
+
- **Schedule**: 15 epochs × 117,266 COCO train images, batch 16, AdamW lr 5e-4, cosine schedule with 3 % warmup
|
| 11 |
+
- **Eval**: apply Stage 0 classifier weights to the 40 classifier-relevant dims of the student's 768-D output; sweep threshold
|
| 12 |
+
|
| 13 |
+
## Result
|
| 14 |
+
|
| 15 |
+
```
|
| 16 |
+
Stage Student params Loss F1
|
| 17 |
+
4 3.27 M MSE on 40-D 0.710
|
| 18 |
+
4B 15.67 M cosine on 768-D 0.723
|
| 19 |
+
0 85.64 M (ViT-B) baseline 0.889
|
| 20 |
+
```
|
| 21 |
+
|
| 22 |
+
Cosine loss converged in epoch 1 (0.072 → 0.061) and stayed flat through epoch 15. F1 plateau'd at 0.723 on the 500-image COCO val subset.
|
| 23 |
+
|
| 24 |
+
## What this says
|
| 25 |
+
|
| 26 |
+
The student reproduces the teacher's pooled feature geometry well in aggregate (cosine ≈ 0.94 across 768 dims), but the 40 classifier-relevant dims are not all equal. Even a small average error on those specific axes destroys Stage 0's precision — every epoch shows precision around 0.57 and recall approaching 1.0, i.e., the student is consistently over-firing.
|
| 27 |
+
|
| 28 |
+
Two candidate next iterations:
|
| 29 |
+
|
| 30 |
+
1. **Dim-weighted cosine**: scale the cosine loss by a per-dim importance weight, with the 40 classifier-relevant dims weighted heavily. The student would then be forced to reproduce those exact values rather than any 40 dims of equal average fidelity.
|
| 31 |
+
2. **Direct classifier supervision**: train the student to minimize `|score_student - score_teacher|` where `score = sum(pos_dims) - sum(neg_dims)`, not the 768-D vector.
|
| 32 |
+
|
| 33 |
+
Either is cheaper than further capacity/epoch scaling.
|
| 34 |
+
|
| 35 |
+
## Files
|
| 36 |
+
|
| 37 |
+
- `student.py` — architecture
|
| 38 |
+
- `prepare_targets_768.py` — builds the 768-D teacher target tensor from the ViT-B cache
|
| 39 |
+
- `train.py` — training loop
|
| 40 |
+
- `student_ep{5,10,15}.safetensors` — intermediate checkpoints
|
| 41 |
+
- `student_final.safetensors` — final weights
|
| 42 |
+
- `training_log.json` — per-epoch loss + F1
|
stage_4b/__pycache__/student.cpython-311.pyc
ADDED
|
Binary file (6.39 kB). View file
|
|
|
stage_4b/prepare_targets_768.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stage 4B: build the 768-D teacher-target tensor from the ViT-B COCO cache.
|
| 2 |
+
|
| 3 |
+
Per image: layernorm 768 channels across patches, max-pool patches → one
|
| 4 |
+
768-D vector. Save as (N, 768) float16 + aligned img_ids.
|
| 5 |
+
|
| 6 |
+
Output: /home/zootest/datasets/coco/stage4b_teacher_targets/targets.pt
|
| 7 |
+
"""
|
| 8 |
+
import os, glob, time
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
|
| 12 |
+
COCO_ROOT = '/home/zootest/datasets/coco'
|
| 13 |
+
CACHE = f'{COCO_ROOT}/feature_cache_768'
|
| 14 |
+
OUT_DIR = f'{COCO_ROOT}/stage4b_teacher_targets'
|
| 15 |
+
D = 768
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def main():
|
| 19 |
+
os.makedirs(OUT_DIR, exist_ok=True)
|
| 20 |
+
shards = sorted(glob.glob(f'{CACHE}/shard_*.pt'))
|
| 21 |
+
print(f'[init] {len(shards)} shards', flush=True)
|
| 22 |
+
|
| 23 |
+
targets, img_ids = [], []
|
| 24 |
+
t0 = time.time()
|
| 25 |
+
for si, sp in enumerate(shards):
|
| 26 |
+
shard = torch.load(sp, map_location='cpu', weights_only=False)
|
| 27 |
+
for entry in shard:
|
| 28 |
+
feat = entry['spatial'].float() # (768, 48, 48)
|
| 29 |
+
ln = F.layer_norm(feat.permute(1, 2, 0).reshape(-1, D), [D]) # (2304, 768)
|
| 30 |
+
pooled = ln.max(dim=0).values # (768,)
|
| 31 |
+
targets.append(pooled.half())
|
| 32 |
+
img_ids.append(int(entry.get('img_id', len(img_ids))))
|
| 33 |
+
rate = (si + 1) / max(time.time() - t0, 1e-6)
|
| 34 |
+
print(f' shard {si+1}/{len(shards)} n={len(targets)} '
|
| 35 |
+
f'{(time.time()-t0):.0f}s ETA {(len(shards)-si-1)/rate:.0f}s', flush=True)
|
| 36 |
+
|
| 37 |
+
targets = torch.stack(targets)
|
| 38 |
+
torch.save({'targets': targets, 'img_ids': img_ids},
|
| 39 |
+
f'{OUT_DIR}/targets.pt')
|
| 40 |
+
print(f'[done] {targets.shape} -> {OUT_DIR}/targets.pt', flush=True)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
if __name__ == '__main__':
|
| 44 |
+
main()
|
stage_4b/student.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stage 4B bigger specialist student.
|
| 2 |
+
|
| 3 |
+
Depth 8, embed 384, 6 heads, MLP ratio 4. Emits a 768-D vector per image
|
| 4 |
+
(matches the full EUPE-ViT-B pooled layernormed output) for cosine-similarity
|
| 5 |
+
distillation.
|
| 6 |
+
"""
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class PatchEmbed(nn.Module):
|
| 13 |
+
def __init__(self, in_ch=3, embed_dim=384, patch_size=16):
|
| 14 |
+
super().__init__()
|
| 15 |
+
self.proj = nn.Conv2d(in_ch, embed_dim, patch_size, stride=patch_size)
|
| 16 |
+
|
| 17 |
+
def forward(self, x):
|
| 18 |
+
x = self.proj(x)
|
| 19 |
+
return x.flatten(2).transpose(1, 2)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class Block(nn.Module):
|
| 23 |
+
def __init__(self, dim, heads, mlp_ratio=4.0):
|
| 24 |
+
super().__init__()
|
| 25 |
+
self.norm1 = nn.LayerNorm(dim)
|
| 26 |
+
self.attn = nn.MultiheadAttention(dim, heads, batch_first=True)
|
| 27 |
+
self.norm2 = nn.LayerNorm(dim)
|
| 28 |
+
hidden = int(dim * mlp_ratio)
|
| 29 |
+
self.mlp = nn.Sequential(nn.Linear(dim, hidden), nn.GELU(), nn.Linear(hidden, dim))
|
| 30 |
+
|
| 31 |
+
def forward(self, x):
|
| 32 |
+
h = self.norm1(x)
|
| 33 |
+
h, _ = self.attn(h, h, h, need_weights=False)
|
| 34 |
+
x = x + h
|
| 35 |
+
x = x + self.mlp(self.norm2(x))
|
| 36 |
+
return x
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class Stage4BStudent(nn.Module):
|
| 40 |
+
"""Outputs a 768-D vector per image to match the EUPE-ViT-B teacher."""
|
| 41 |
+
def __init__(self, out_dim=768, embed_dim=384, depth=8, heads=6,
|
| 42 |
+
patch_size=16, img_size=768, mlp_ratio=4.0):
|
| 43 |
+
super().__init__()
|
| 44 |
+
self.patch = PatchEmbed(3, embed_dim, patch_size)
|
| 45 |
+
self.num_patches = (img_size // patch_size) ** 2
|
| 46 |
+
self.pos = nn.Parameter(torch.zeros(1, self.num_patches, embed_dim))
|
| 47 |
+
nn.init.trunc_normal_(self.pos, std=0.02)
|
| 48 |
+
self.blocks = nn.ModuleList([Block(embed_dim, heads, mlp_ratio) for _ in range(depth)])
|
| 49 |
+
self.norm = nn.LayerNorm(embed_dim)
|
| 50 |
+
self.head = nn.Linear(embed_dim, out_dim)
|
| 51 |
+
|
| 52 |
+
def forward(self, x):
|
| 53 |
+
tokens = self.patch(x)
|
| 54 |
+
tokens = tokens + self.pos[:, :tokens.shape[1]]
|
| 55 |
+
for blk in self.blocks:
|
| 56 |
+
tokens = blk(tokens)
|
| 57 |
+
tokens = self.norm(tokens)
|
| 58 |
+
pooled = tokens.max(dim=1).values
|
| 59 |
+
return self.head(pooled)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
if __name__ == '__main__':
|
| 63 |
+
m = Stage4BStudent()
|
| 64 |
+
total = sum(p.numel() for p in m.parameters())
|
| 65 |
+
print(f'Stage 4B student: {total:,} params = {total/1e6:.2f}M')
|
| 66 |
+
x = torch.randn(2, 3, 768, 768)
|
| 67 |
+
y = m(x)
|
| 68 |
+
print(f'forward OK output shape: {tuple(y.shape)}')
|
stage_4b/student_ep10.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8e29f518c514d0ea26b5340104e054273e48a2a74ee7db025ce47c42cc28b523
|
| 3 |
+
size 62698160
|
stage_4b/student_ep15.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bd541b1fce0fe10af77471404fa8743960f10fb1798e4ebc0409437f30cdb83f
|
| 3 |
+
size 62698160
|
stage_4b/student_ep5.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4be68d45bc8922a2d5a34ff040b617030abbb505071463b684c83c4f67f7b1bb
|
| 3 |
+
size 62698160
|
stage_4b/student_final.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bd541b1fce0fe10af77471404fa8743960f10fb1798e4ebc0409437f30cdb83f
|
| 3 |
+
size 62698160
|
stage_4b/train.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stage 4B training: cosine loss on full 768-D pooled teacher output, 30 epochs."""
|
| 2 |
+
import os, sys, time, json, math
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from PIL import Image
|
| 8 |
+
from pycocotools.coco import COCO
|
| 9 |
+
from safetensors.torch import save_file
|
| 10 |
+
|
| 11 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 12 |
+
sys.path.insert(0, HERE)
|
| 13 |
+
from student import Stage4BStudent
|
| 14 |
+
|
| 15 |
+
COCO_ROOT = '/home/zootest/datasets/coco'
|
| 16 |
+
TARGETS = f'{COCO_ROOT}/stage4b_teacher_targets/targets.pt'
|
| 17 |
+
CLASSIFIER = '/mnt/d/_tmp/1pc_repo/stage_0/classifier.json'
|
| 18 |
+
OUT_DIR = '/mnt/d/_tmp/1pc_repo/stage_4b'
|
| 19 |
+
DEVICE = 'cuda'
|
| 20 |
+
RES = 768
|
| 21 |
+
BATCH = 16
|
| 22 |
+
LR = 5e-4
|
| 23 |
+
WD = 1e-4
|
| 24 |
+
EPOCHS = 15
|
| 25 |
+
WARMUP_FRAC = 0.03
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class CocoImgDataset(torch.utils.data.Dataset):
|
| 29 |
+
def __init__(self, coco_root, pack):
|
| 30 |
+
self.root = f'{coco_root}/train2017'
|
| 31 |
+
coco = COCO(f'{coco_root}/annotations/instances_train2017.json')
|
| 32 |
+
self.img_ids = pack['img_ids']
|
| 33 |
+
self.targets = pack['targets']
|
| 34 |
+
self.id_to_file = {i['id']: i['file_name']
|
| 35 |
+
for i in coco.loadImgs(coco.getImgIds())}
|
| 36 |
+
|
| 37 |
+
def __len__(self):
|
| 38 |
+
return len(self.img_ids)
|
| 39 |
+
|
| 40 |
+
def __getitem__(self, i):
|
| 41 |
+
img_id = self.img_ids[i]
|
| 42 |
+
target = self.targets[i].float()
|
| 43 |
+
fname = self.id_to_file.get(img_id)
|
| 44 |
+
if fname is None:
|
| 45 |
+
return None
|
| 46 |
+
try:
|
| 47 |
+
img = Image.open(f'{self.root}/{fname}').convert('RGB').resize((RES, RES), Image.BILINEAR)
|
| 48 |
+
except Exception:
|
| 49 |
+
return None
|
| 50 |
+
arr = np.asarray(img, dtype=np.uint8).copy()
|
| 51 |
+
x = torch.from_numpy(arr).permute(2, 0, 1).float() / 255.0
|
| 52 |
+
mean = torch.tensor([0.485, 0.456, 0.406]).view(3, 1, 1)
|
| 53 |
+
std = torch.tensor([0.229, 0.224, 0.225]).view(3, 1, 1)
|
| 54 |
+
return (x - mean) / std, target
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def collate(batch):
|
| 58 |
+
batch = [b for b in batch if b is not None]
|
| 59 |
+
if not batch:
|
| 60 |
+
return None
|
| 61 |
+
xs, ts = zip(*batch)
|
| 62 |
+
return torch.stack(xs), torch.stack(ts)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def cosine_loss(pred, target):
|
| 66 |
+
# 1 - cosine similarity (per-sample mean)
|
| 67 |
+
return (1.0 - F.cosine_similarity(pred, target, dim=-1)).mean()
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def eval_f1_via_stage0(student, classifier_json, n=500):
|
| 71 |
+
with open(classifier_json) as f:
|
| 72 |
+
c = json.load(f)
|
| 73 |
+
pos = torch.tensor(c['pos_dims'], device=DEVICE)
|
| 74 |
+
neg = torch.tensor(c['neg_dims'], device=DEVICE)
|
| 75 |
+
thr = c['threshold']
|
| 76 |
+
coco = COCO(f'{COCO_ROOT}/annotations/instances_val2017.json')
|
| 77 |
+
img_ids = sorted(coco.getImgIds())[:n]
|
| 78 |
+
id_to_file = {i['id']: i['file_name']
|
| 79 |
+
for i in coco.loadImgs(coco.getImgIds())}
|
| 80 |
+
MEAN = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1).to(DEVICE)
|
| 81 |
+
STD = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1).to(DEVICE)
|
| 82 |
+
scores, labels = [], []
|
| 83 |
+
student.eval()
|
| 84 |
+
with torch.inference_mode():
|
| 85 |
+
for img_id in img_ids:
|
| 86 |
+
fname = id_to_file.get(img_id)
|
| 87 |
+
if not fname:
|
| 88 |
+
continue
|
| 89 |
+
img = Image.open(f'{COCO_ROOT}/val2017/{fname}').convert('RGB').resize((RES, RES), Image.BILINEAR)
|
| 90 |
+
arr = np.asarray(img, dtype=np.uint8).copy()
|
| 91 |
+
x = torch.from_numpy(arr).permute(2, 0, 1).unsqueeze(0).to(DEVICE).float() / 255.0
|
| 92 |
+
x = (x - MEAN) / STD
|
| 93 |
+
with torch.autocast('cuda', dtype=torch.bfloat16):
|
| 94 |
+
out = student(x).float() # (1, 768)
|
| 95 |
+
s = (out[0, pos].sum() - out[0, neg].sum()).item()
|
| 96 |
+
scores.append(s)
|
| 97 |
+
labels.append(any(a['category_id'] == 1
|
| 98 |
+
for a in coco.loadAnns(coco.getAnnIds(imgIds=img_id, iscrowd=False))))
|
| 99 |
+
scores = torch.tensor(scores)
|
| 100 |
+
labels = torch.tensor(labels, dtype=torch.bool)
|
| 101 |
+
uniq = torch.unique(scores).sort().values
|
| 102 |
+
best = (0, 0, 0, 0)
|
| 103 |
+
for t in uniq.tolist()[::max(1, len(uniq) // 500)]:
|
| 104 |
+
pred = scores > t
|
| 105 |
+
tp = (pred & labels).sum().float()
|
| 106 |
+
fp = (pred & ~labels).sum().float()
|
| 107 |
+
fn = (~pred & labels).sum().float()
|
| 108 |
+
prec = tp / (tp + fp).clamp(min=1)
|
| 109 |
+
rec = tp / (tp + fn).clamp(min=1)
|
| 110 |
+
f1 = (2 * prec * rec / (prec + rec).clamp(min=1e-9)).item()
|
| 111 |
+
if f1 > best[0]:
|
| 112 |
+
best = (f1, t, prec.item(), rec.item())
|
| 113 |
+
return best
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def main():
|
| 117 |
+
os.makedirs(OUT_DIR, exist_ok=True)
|
| 118 |
+
print('[init] loading targets', flush=True)
|
| 119 |
+
pack = torch.load(TARGETS, map_location='cpu', weights_only=False)
|
| 120 |
+
print(f' {pack["targets"].shape[0]} teacher targets, dim {pack["targets"].shape[1]}', flush=True)
|
| 121 |
+
|
| 122 |
+
ds = CocoImgDataset(COCO_ROOT, pack)
|
| 123 |
+
loader = torch.utils.data.DataLoader(
|
| 124 |
+
ds, batch_size=BATCH, shuffle=True, num_workers=4,
|
| 125 |
+
pin_memory=True, collate_fn=collate, drop_last=True)
|
| 126 |
+
|
| 127 |
+
student = Stage4BStudent().to(DEVICE)
|
| 128 |
+
nparams = sum(p.numel() for p in student.parameters())
|
| 129 |
+
print(f'[student] {nparams:,} params = {nparams/1e6:.2f}M', flush=True)
|
| 130 |
+
|
| 131 |
+
total_steps = EPOCHS * len(loader)
|
| 132 |
+
warmup = int(total_steps * WARMUP_FRAC)
|
| 133 |
+
opt = torch.optim.AdamW(student.parameters(), lr=LR, weight_decay=WD)
|
| 134 |
+
sched = torch.optim.lr_scheduler.LambdaLR(
|
| 135 |
+
opt, lambda s: s / max(1, warmup) if s < warmup
|
| 136 |
+
else 0.5 * (1 + math.cos(math.pi * (s - warmup) / max(1, total_steps - warmup))))
|
| 137 |
+
|
| 138 |
+
log = {'student_params': nparams, 'loss': 'cosine_1_minus_sim', 'target_dim': 768, 'epochs': []}
|
| 139 |
+
step = 0; t0 = time.time()
|
| 140 |
+
for ep in range(EPOCHS):
|
| 141 |
+
student.train()
|
| 142 |
+
ep_loss, n_batches = 0.0, 0
|
| 143 |
+
for batch in loader:
|
| 144 |
+
if batch is None:
|
| 145 |
+
continue
|
| 146 |
+
x, y = batch
|
| 147 |
+
x = x.to(DEVICE, non_blocking=True); y = y.to(DEVICE, non_blocking=True)
|
| 148 |
+
with torch.autocast('cuda', dtype=torch.bfloat16):
|
| 149 |
+
pred = student(x)
|
| 150 |
+
loss = cosine_loss(pred.float(), y)
|
| 151 |
+
opt.zero_grad(set_to_none=True)
|
| 152 |
+
loss.backward()
|
| 153 |
+
torch.nn.utils.clip_grad_norm_(student.parameters(), 1.0)
|
| 154 |
+
opt.step(); sched.step()
|
| 155 |
+
ep_loss += loss.item(); n_batches += 1; step += 1
|
| 156 |
+
if step % 500 == 0:
|
| 157 |
+
print(f' ep {ep+1}/{EPOCHS} step {step}/{total_steps} '
|
| 158 |
+
f'loss={loss.item():.4f} lr={opt.param_groups[0]["lr"]:.2e} '
|
| 159 |
+
f'{(time.time()-t0)/60:.1f} min', flush=True)
|
| 160 |
+
avg = ep_loss / max(1, n_batches)
|
| 161 |
+
f1, thr, p, r = eval_f1_via_stage0(student, CLASSIFIER)
|
| 162 |
+
print(f'[ep {ep+1}] loss={avg:.4f} F1={f1:.4f} P={p:.4f} R={r:.4f} '
|
| 163 |
+
f'θ={thr:.3f} {(time.time()-t0)/60:.1f} min', flush=True)
|
| 164 |
+
log['epochs'].append({'epoch': ep + 1, 'loss': avg,
|
| 165 |
+
'F1': f1, 'precision': p, 'recall': r, 'threshold': thr})
|
| 166 |
+
if (ep + 1) % 5 == 0 or ep == EPOCHS - 1:
|
| 167 |
+
save_file(student.state_dict(), f'{OUT_DIR}/student_ep{ep+1}.safetensors')
|
| 168 |
+
with open(f'{OUT_DIR}/training_log.json', 'w') as f:
|
| 169 |
+
json.dump(log, f, indent=2)
|
| 170 |
+
|
| 171 |
+
save_file(student.state_dict(), f'{OUT_DIR}/student_final.safetensors')
|
| 172 |
+
print(f'[done] total {(time.time()-t0)/60:.1f} min', flush=True)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
if __name__ == '__main__':
|
| 176 |
+
main()
|
stage_4b/training_log.json
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"student_params": 15672192,
|
| 3 |
+
"loss": "cosine_1_minus_sim",
|
| 4 |
+
"target_dim": 768,
|
| 5 |
+
"epochs": [
|
| 6 |
+
{
|
| 7 |
+
"epoch": 1,
|
| 8 |
+
"loss": 0.07253991591294745,
|
| 9 |
+
"F1": 0.7222222089767456,
|
| 10 |
+
"precision": 0.5759493708610535,
|
| 11 |
+
"recall": 0.9680851101875305,
|
| 12 |
+
"threshold": 77.3359375
|
| 13 |
+
},
|
| 14 |
+
{
|
| 15 |
+
"epoch": 2,
|
| 16 |
+
"loss": 0.06178997803267662,
|
| 17 |
+
"F1": 0.7249357104301453,
|
| 18 |
+
"precision": 0.5685483813285828,
|
| 19 |
+
"recall": 1.0,
|
| 20 |
+
"threshold": 107.1875
|
| 21 |
+
},
|
| 22 |
+
{
|
| 23 |
+
"epoch": 3,
|
| 24 |
+
"loss": 0.0617156123302943,
|
| 25 |
+
"F1": 0.7195902466773987,
|
| 26 |
+
"precision": 0.563126266002655,
|
| 27 |
+
"recall": 0.9964538812637329,
|
| 28 |
+
"threshold": 148.1875
|
| 29 |
+
},
|
| 30 |
+
{
|
| 31 |
+
"epoch": 4,
|
| 32 |
+
"loss": 0.061347012896584736,
|
| 33 |
+
"F1": 0.7253885865211487,
|
| 34 |
+
"precision": 0.5714285969734192,
|
| 35 |
+
"recall": 0.9929078221321106,
|
| 36 |
+
"threshold": 153.75
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"epoch": 5,
|
| 40 |
+
"loss": 0.06122595644468568,
|
| 41 |
+
"F1": 0.7237353920936584,
|
| 42 |
+
"precision": 0.5705521702766418,
|
| 43 |
+
"recall": 0.9893617033958435,
|
| 44 |
+
"threshold": 159.734375
|
| 45 |
+
},
|
| 46 |
+
{
|
| 47 |
+
"epoch": 6,
|
| 48 |
+
"loss": 0.06132089458562277,
|
| 49 |
+
"F1": 0.7195902466773987,
|
| 50 |
+
"precision": 0.563126266002655,
|
| 51 |
+
"recall": 0.9964538812637329,
|
| 52 |
+
"threshold": 156.5625
|
| 53 |
+
},
|
| 54 |
+
{
|
| 55 |
+
"epoch": 7,
|
| 56 |
+
"loss": 0.061309009904699646,
|
| 57 |
+
"F1": 0.7220779061317444,
|
| 58 |
+
"precision": 0.5696721076965332,
|
| 59 |
+
"recall": 0.9858155846595764,
|
| 60 |
+
"threshold": 174.6875
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
"epoch": 8,
|
| 64 |
+
"loss": 0.06113341519135151,
|
| 65 |
+
"F1": 0.720720648765564,
|
| 66 |
+
"precision": 0.5656565427780151,
|
| 67 |
+
"recall": 0.9929078221321106,
|
| 68 |
+
"threshold": 168.375
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"epoch": 9,
|
| 72 |
+
"loss": 0.060983790468551714,
|
| 73 |
+
"F1": 0.7205128073692322,
|
| 74 |
+
"precision": 0.564257025718689,
|
| 75 |
+
"recall": 0.9964538812637329,
|
| 76 |
+
"threshold": 168.28125
|
| 77 |
+
},
|
| 78 |
+
{
|
| 79 |
+
"epoch": 10,
|
| 80 |
+
"loss": 0.061084045586111,
|
| 81 |
+
"F1": 0.7260638475418091,
|
| 82 |
+
"precision": 0.5808510780334473,
|
| 83 |
+
"recall": 0.9680851101875305,
|
| 84 |
+
"threshold": 165.9375
|
| 85 |
+
},
|
| 86 |
+
{
|
| 87 |
+
"epoch": 11,
|
| 88 |
+
"loss": 0.061100886026898504,
|
| 89 |
+
"F1": 0.7221510410308838,
|
| 90 |
+
"precision": 0.5651302337646484,
|
| 91 |
+
"recall": 1.0,
|
| 92 |
+
"threshold": 171.53125
|
| 93 |
+
},
|
| 94 |
+
{
|
| 95 |
+
"epoch": 12,
|
| 96 |
+
"loss": 0.06096925960034696,
|
| 97 |
+
"F1": 0.7195902466773987,
|
| 98 |
+
"precision": 0.563126266002655,
|
| 99 |
+
"recall": 0.9964538812637329,
|
| 100 |
+
"threshold": 168.1875
|
| 101 |
+
},
|
| 102 |
+
{
|
| 103 |
+
"epoch": 13,
|
| 104 |
+
"loss": 0.060978461868108035,
|
| 105 |
+
"F1": 0.7253613471984863,
|
| 106 |
+
"precision": 0.5762004256248474,
|
| 107 |
+
"recall": 0.978723406791687,
|
| 108 |
+
"threshold": 167.40625
|
| 109 |
+
},
|
| 110 |
+
{
|
| 111 |
+
"epoch": 14,
|
| 112 |
+
"loss": 0.060976944405298966,
|
| 113 |
+
"F1": 0.7216494679450989,
|
| 114 |
+
"precision": 0.5668016076087952,
|
| 115 |
+
"recall": 0.9929078221321106,
|
| 116 |
+
"threshold": 168.125
|
| 117 |
+
},
|
| 118 |
+
{
|
| 119 |
+
"epoch": 15,
|
| 120 |
+
"loss": 0.06102545032333958,
|
| 121 |
+
"F1": 0.7230768799781799,
|
| 122 |
+
"precision": 0.5662650465965271,
|
| 123 |
+
"recall": 1.0,
|
| 124 |
+
"threshold": 168.09375
|
| 125 |
+
}
|
| 126 |
+
]
|
| 127 |
+
}
|