AbstractPhil commited on
Commit
9ff1530
·
verified ·
1 Parent(s): 64736e9

Create qwen_simple_test_trainer.py

Browse files
Files changed (1) hide show
  1. qwen_simple_test_trainer.py +620 -0
qwen_simple_test_trainer.py ADDED
@@ -0,0 +1,620 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =============================================================================
2
+ # CELL 4: Qwen × Geometric Classifier Cross-Contrast Training
3
+ # Requires: Cell 1 (constants), Cell 2 (model classes), Cell 3 (trained checkpoint)
4
+ # Outputs: crosscontrast/ and qwen_embeddings/ on HF
5
+ #
6
+ # Features:
7
+ # - Loads geo classifier from Cell 3 checkpoint (no notebook scope dependency)
8
+ # - Uses model.forward()["features"] (no duplicated internals)
9
+ # - Dataset + Qwen embeddings cached to disk
10
+ # - CC model checkpointed with resume
11
+ # =============================================================================
12
+
13
+ import math, time, json, os
14
+ from pathlib import Path
15
+ from tqdm.auto import tqdm
16
+ import torch
17
+ import torch.nn as nn
18
+ import torch.nn.functional as F
19
+
20
+ HF_REPO = "AbstractPhil/grid-geometric-classifier-proto"
21
+ CKPT_DIR = Path("./checkpoints")
22
+ CC_CKPT_DIR = Path("./cc_checkpoints")
23
+
24
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
25
+ torch.backends.cuda.matmul.allow_tf32 = True
26
+ torch.backends.cudnn.allow_tf32 = True
27
+ torch.backends.cudnn.benchmark = True
28
+
29
+ use_amp = device.type == "cuda"
30
+ amp_dtype = torch.bfloat16 if (device.type == "cuda" and
31
+ torch.cuda.is_bf16_supported()) else torch.float16
32
+
33
+
34
+ # =============================================================================
35
+ # Shape Descriptions
36
+ # =============================================================================
37
+
38
+ SHAPE_DESCRIPTIONS = {
39
+ "point": "A zero-dimensional geometric primitive occupying a single discrete location in three-dimensional space with no extent along any axis.",
40
+ "line_x": "A one-dimensional line segment extending along the horizontal x-axis, connecting two endpoints with uniform spacing between occupied voxels.",
41
+ "line_y": "A one-dimensional line segment extending along the vertical y-axis, a straight structure rising upward through the grid.",
42
+ "line_z": "A one-dimensional line segment extending along the depth z-axis, projecting straight backward through the voxel grid.",
43
+ "line_diag": "A one-dimensional diagonal line segment cutting across multiple axes simultaneously, connecting opposite corners of the grid.",
44
+ "cross": "Two perpendicular line segments intersecting at their midpoints forming a plus-shaped cross pattern in a single plane.",
45
+ "l_shape": "Two connected line segments meeting at a right angle to form an L-shaped corner, like two edges of a rectangle.",
46
+ "collinear": "Three or more points arranged along a single straight line with equal spacing, demonstrating perfect linear alignment.",
47
+ "triangle_xy": "A flat triangular outline formed by three connected edges lying in the horizontal xy-plane, the simplest polygon.",
48
+ "triangle_xz": "A flat triangular outline formed by three connected edges lying in the vertical xz-plane, a triangle standing upright.",
49
+ "triangle_3d": "A triangular outline with vertices at different heights, forming a non-planar triangle tilted in three-dimensional space.",
50
+ "square_xy": "A square outline formed by four equal edges in the xy-plane, a regular quadrilateral with right angles at each corner.",
51
+ "square_xz": "A square outline formed by four equal edges in the xz-plane, a square standing vertically like a window frame.",
52
+ "rectangle": "A rectangular outline with two pairs of parallel edges of different lengths, wider than it is tall.",
53
+ "coplanar": "A set of points all lying in the same plane but not forming a regular polygon, a scattered planar arrangement.",
54
+ "plane": "A solid flat surface filling an entire plane with occupied voxels, a two-dimensional sheet extending across the grid.",
55
+ "tetrahedron": "A three-dimensional simplex with four triangular faces meeting at four vertices and six edges, the simplest polyhedron.",
56
+ "pyramid": "A solid with a square base and four triangular faces converging to a single apex point above the base center.",
57
+ "pentachoron": "A four-dimensional simplex projected into three dimensions, consisting of five tetrahedral cells sharing faces.",
58
+ "cube": "A regular hexahedron with six identical square faces, twelve edges, and eight vertices forming a perfect box shape.",
59
+ "cuboid": "A rectangular box with six rectangular faces, similar to a cube but with at least one pair of edges longer than the others.",
60
+ "triangular_prism": "A solid with two parallel triangular faces connected by three rectangular faces, like a tent or Toblerone shape.",
61
+ "octahedron": "A regular polyhedron with eight equilateral triangular faces, twelve edges, and six vertices, like two pyramids base-to-base.",
62
+ "arc": "A curved one-dimensional segment forming part of a circle, a smooth bend connecting two endpoints along a circular path.",
63
+ "helix": "A three-dimensional spiral curve that winds around a central axis while advancing along it, like a corkscrew or spring.",
64
+ "circle": "A closed curved outline where every point is equidistant from the center, forming a perfect round ring in a plane.",
65
+ "ellipse": "A closed curved outline forming an elongated circle, an oval shape with two focal points and varying curvature.",
66
+ "disc": "A solid filled circular region, a flat round plate occupying all voxels within a circular boundary in a plane.",
67
+ "sphere": "A perfectly round three-dimensional solid where every surface point is equidistant from the center, fully filled inside.",
68
+ "hemisphere": "Half of a sphere cut along a great circle, a dome shape with a flat base and a convex curved upper surface.",
69
+ "cylinder": "A solid with two parallel circular faces connected by a curved rectangular surface, like a can or pillar.",
70
+ "cone": "A solid tapering smoothly from a circular base to a single apex point, with a curved surface of decreasing radius.",
71
+ "capsule": "A cylinder capped with hemispheres at both ends, a smooth elongated pill shape with no sharp edges.",
72
+ "torus": "A donut-shaped solid formed by revolving a circle around an external axis, with a hole through the center.",
73
+ "shell": "A hollow spherical surface with no interior fill, an empty ball where only the outer boundary layer is occupied.",
74
+ "tube": "A hollow cylindrical surface with no interior fill, an empty pipe where only the curved wall is occupied.",
75
+ "bowl": "A concave open surface curving inward like a dish, the bottom half of a hollow sphere with the opening facing up.",
76
+ "saddle": "A hyperbolic surface that curves upward along one axis and downward along the perpendicular axis, like a horse saddle.",
77
+ }
78
+ assert set(SHAPE_DESCRIPTIONS.keys()) == set(CLASS_NAMES), "Description/class mismatch!"
79
+
80
+
81
+ # =============================================================================
82
+ # Qwen Embedding Extractor
83
+ # =============================================================================
84
+
85
+ class QwenEmbeddingExtractor:
86
+ MODEL_NAME = "Qwen/Qwen2.5-1.5B-Instruct"
87
+ HIDDEN_DIM = 1536
88
+
89
+ def __init__(self, device="cuda"):
90
+ self.device = device
91
+ self.model = None
92
+ self.tokenizer = None
93
+
94
+ def load_model(self):
95
+ from transformers import AutoModelForCausalLM, AutoTokenizer
96
+ print(f"Loading {self.MODEL_NAME}...")
97
+ self.tokenizer = AutoTokenizer.from_pretrained(self.MODEL_NAME, trust_remote_code=True)
98
+ self.model = AutoModelForCausalLM.from_pretrained(
99
+ self.MODEL_NAME, dtype=torch.float16,
100
+ device_map=self.device, trust_remote_code=True)
101
+ self.model.eval()
102
+ print(f"Qwen loaded: {self.HIDDEN_DIM}-dim hidden states")
103
+
104
+ def _build_encode_prompt(self, description):
105
+ messages = [
106
+ {"role": "system", "content": "You are a geometric shape analyst."},
107
+ {"role": "user", "content": f"Analyze this shape: {description}"},
108
+ ]
109
+ return self.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
110
+
111
+ @torch.no_grad()
112
+ def extract_embedding(self, text):
113
+ prompt = self._build_encode_prompt(text)
114
+ inputs = self.tokenizer(prompt, return_tensors="pt", max_length=512, truncation=True).to(self.device)
115
+ outputs = self.model(**inputs, output_hidden_states=True)
116
+ hidden = outputs.hidden_states[-1]
117
+ return hidden.mean(dim=1).squeeze(0).float()
118
+
119
+ def cache_all_embeddings(self, class_names):
120
+ print(f"Extracting embeddings for {len(class_names)} classes...")
121
+ embeddings = {}
122
+ for name in class_names:
123
+ embeddings[name] = self.extract_embedding(SHAPE_DESCRIPTIONS[name])
124
+ emb_tensor = torch.stack([embeddings[n] for n in class_names])
125
+ normed = F.normalize(emb_tensor, dim=-1)
126
+ sim = normed @ normed.T
127
+ mean_sim = (sim.sum() - sim.trace()) / (len(class_names) * (len(class_names) - 1))
128
+ print(f"Cached: {emb_tensor.shape} | mean cross-class sim: {mean_sim:.4f}")
129
+ return emb_tensor
130
+
131
+ def unload(self):
132
+ del self.model, self.tokenizer
133
+ self.model = self.tokenizer = None
134
+ torch.cuda.empty_cache()
135
+ print("Qwen unloaded")
136
+
137
+
138
+ # =============================================================================
139
+ # Projection Heads + Cross-Contrast Model
140
+ # =============================================================================
141
+
142
+ class TextProjection(nn.Module):
143
+ def __init__(self, text_dim=1536, latent_dim=256):
144
+ super().__init__()
145
+ self.proj = nn.Sequential(
146
+ nn.Linear(text_dim, latent_dim * 2), nn.GELU(),
147
+ nn.Linear(latent_dim * 2, latent_dim), nn.GELU(),
148
+ nn.Linear(latent_dim, latent_dim))
149
+ self.norm = nn.LayerNorm(latent_dim)
150
+ def forward(self, x): return self.norm(self.proj(x))
151
+
152
+ class VoxelProjection(nn.Module):
153
+ def __init__(self, voxel_dim=645, latent_dim=256):
154
+ super().__init__()
155
+ self.proj = nn.Sequential(
156
+ nn.Linear(voxel_dim, latent_dim * 2), nn.GELU(),
157
+ nn.Linear(latent_dim * 2, latent_dim), nn.GELU(),
158
+ nn.Linear(latent_dim, latent_dim))
159
+ self.norm = nn.LayerNorm(latent_dim)
160
+ def forward(self, x): return self.norm(self.proj(x))
161
+
162
+
163
+ class CrossContrastModel(nn.Module):
164
+ def __init__(self, text_dim=1536, voxel_dim=645, latent_dim=256,
165
+ n_classes=38, temperature=0.07):
166
+ super().__init__()
167
+ self.text_proj = TextProjection(text_dim, latent_dim)
168
+ self.voxel_proj = VoxelProjection(voxel_dim, latent_dim)
169
+ self.log_temperature = nn.Parameter(torch.tensor(math.log(1.0 / temperature)))
170
+
171
+ @property
172
+ def temperature(self):
173
+ return torch.exp(-self.log_temperature)
174
+
175
+ def forward(self, voxel_features, class_labels, text_embeddings_table):
176
+ text_emb = text_embeddings_table[class_labels]
177
+ z_text = F.normalize(self.text_proj(text_emb), dim=-1)
178
+ z_voxel = F.normalize(self.voxel_proj(voxel_features), dim=-1)
179
+
180
+ temp = self.temperature
181
+ logits_v2t = z_voxel @ z_text.T / temp
182
+ logits_t2v = z_text @ z_voxel.T / temp
183
+
184
+ labels_matrix = (class_labels.unsqueeze(0) == class_labels.unsqueeze(1)).float()
185
+ labels_matrix = labels_matrix / labels_matrix.sum(dim=1, keepdim=True).clamp(min=1)
186
+
187
+ loss_v2t = (-labels_matrix * F.log_softmax(logits_v2t, dim=1)).sum(dim=1).mean()
188
+ loss_t2v = (-labels_matrix * F.log_softmax(logits_t2v, dim=1)).sum(dim=1).mean()
189
+ loss = (loss_v2t + loss_t2v) / 2.0
190
+
191
+ with torch.no_grad():
192
+ v2t_preds = logits_v2t.argmax(dim=1)
193
+ pred_classes = class_labels[v2t_preds]
194
+ acc = (pred_classes == class_labels).float().mean()
195
+ pos_sim = (z_voxel * z_text).sum(dim=-1).mean()
196
+ neg_mask = ~(class_labels.unsqueeze(0) == class_labels.unsqueeze(1))
197
+ neg_sim = (z_voxel @ z_text.T)[neg_mask].mean() if neg_mask.any() else torch.tensor(0.0)
198
+
199
+ return loss, {"acc": acc.item(), "pos_sim": pos_sim.item(),
200
+ "neg_sim": neg_sim.item(), "temperature": temp.item()}
201
+
202
+
203
+ # =============================================================================
204
+ # Helpers
205
+ # =============================================================================
206
+
207
+ def get_hf_token():
208
+ try:
209
+ from google.colab import userdata
210
+ return userdata.get('HF_TOKEN')
211
+ except Exception:
212
+ return os.environ.get('HF_TOKEN')
213
+
214
+
215
+ def load_geo_model(ckpt_dir=CKPT_DIR):
216
+ """Load trained GeometricShapeClassifier from Cell 3 checkpoint."""
217
+ latest = ckpt_dir / "latest.pt"
218
+ if not latest.exists():
219
+ raise FileNotFoundError(
220
+ f"No checkpoint at {latest}. Run Cell 3 first to train the classifier.")
221
+ print(f"Loading geo classifier from {latest}...")
222
+ ckpt = torch.load(latest, weights_only=False, map_location=device)
223
+ geo = GeometricShapeClassifier().to(device)
224
+ geo.load_state_dict(ckpt["model_state_dict"])
225
+ geo.eval()
226
+ for p in geo.parameters():
227
+ p.requires_grad = False
228
+ print(f"Loaded: epoch {ckpt['epoch']}, val_acc={ckpt['best_val_acc']:.4f}, "
229
+ f"{sum(p.numel() for p in geo.parameters()):,} params (frozen)")
230
+ return geo
231
+
232
+
233
+ @torch.no_grad()
234
+ def extract_voxel_features(geo_model, grid):
235
+ """Extract pre-classifier features using model.forward()['features']."""
236
+ with torch.amp.autocast('cuda', enabled=use_amp, dtype=amp_dtype):
237
+ out = geo_model(grid)
238
+ return out["features"].float()
239
+
240
+
241
+ def save_cc_checkpoint(cc_model, cc_opt, cc_sched, epoch, best_acc, ckpt_dir=CC_CKPT_DIR):
242
+ ckpt_dir.mkdir(parents=True, exist_ok=True)
243
+ ckpt = {
244
+ "epoch": epoch,
245
+ "best_cc_acc": best_acc,
246
+ "cc_model_state_dict": cc_model.state_dict(),
247
+ "cc_optimizer_state_dict": cc_opt.state_dict(),
248
+ "cc_scheduler_state_dict": cc_sched.state_dict(),
249
+ }
250
+ torch.save(ckpt, ckpt_dir / "latest.pt")
251
+
252
+
253
+ def load_cc_checkpoint(cc_model, cc_opt, cc_sched, ckpt_dir=CC_CKPT_DIR):
254
+ latest = ckpt_dir / "latest.pt"
255
+ if not latest.exists():
256
+ return 0, 0.0
257
+ print(f"Resuming CC from {latest}...")
258
+ ckpt = torch.load(latest, weights_only=False)
259
+ cc_model.load_state_dict(ckpt["cc_model_state_dict"])
260
+ cc_opt.load_state_dict(ckpt["cc_optimizer_state_dict"])
261
+ cc_sched.load_state_dict(ckpt["cc_scheduler_state_dict"])
262
+ start = ckpt["epoch"] + 1
263
+ best = ckpt["best_cc_acc"]
264
+ print(f"Resumed: epoch {start}, best_cc_acc={best:.4f}")
265
+ return start, best
266
+
267
+
268
+ def upload_cc_to_hf(cc_model, best_acc, epoch, token, reason="periodic",
269
+ text_dim_=None, voxel_dim_=None, latent_dim_=None):
270
+ """Upload crosscontrast weights + config to HF. Called mid-training and at end."""
271
+ if not token:
272
+ return
273
+ try:
274
+ from huggingface_hub import HfApi, create_repo
275
+ from safetensors.torch import save_file as st_save
276
+
277
+ staging = Path("./hf_staging/crosscontrast")
278
+ staging.mkdir(parents=True, exist_ok=True)
279
+
280
+ st_save(cc_model.text_proj.state_dict(), str(staging / "text_proj.safetensors"))
281
+ st_save(cc_model.voxel_proj.state_dict(), str(staging / "voxel_proj.safetensors"))
282
+ st_save({"log_temperature": cc_model.log_temperature.data.unsqueeze(0)},
283
+ str(staging / "temperature.safetensors"))
284
+
285
+ # Write config so uploads are self-contained
286
+ if text_dim_ and voxel_dim_ and latent_dim_:
287
+ cfg = {
288
+ "model_type": "CrossContrastModel",
289
+ "text_dim": text_dim_, "voxel_dim": voxel_dim_,
290
+ "latent_dim": latent_dim_,
291
+ "best_val_accuracy": best_acc,
292
+ "epoch": epoch + 1, "upload_reason": reason,
293
+ "temperature": cc_model.temperature.item(),
294
+ }
295
+ with open(staging / "config.json", "w") as f:
296
+ json.dump(cfg, f, indent=2)
297
+
298
+ api = HfApi(token=token)
299
+ create_repo(HF_REPO, token=token, exist_ok=True)
300
+ api.upload_folder(
301
+ folder_path=str(staging), repo_id=HF_REPO,
302
+ path_in_repo="crosscontrast", token=token,
303
+ commit_message=f"crosscontrast ep{epoch+1} | acc={best_acc:.4f} | {reason}")
304
+ tqdm.write(f" ✓ HF upload ({reason}): ep{epoch+1} acc={best_acc:.4f}")
305
+ except Exception as e:
306
+ tqdm.write(f" ⚠ HF upload failed: {e}")
307
+
308
+
309
+ # =============================================================================
310
+ # PHASE 1: Qwen Embeddings (cached)
311
+ # =============================================================================
312
+
313
+ print("=" * 70)
314
+ print("Phase 1: Qwen Embeddings")
315
+ print("=" * 70)
316
+
317
+ cache_path = Path("qwen_geo_cache.pt")
318
+ if cache_path.exists():
319
+ _cache = torch.load(cache_path, map_location="cpu", weights_only=True)
320
+ text_embeddings = _cache["embeddings"]
321
+ print(f"Loaded cached: {text_embeddings.shape}")
322
+ else:
323
+ extractor = QwenEmbeddingExtractor(device=str(device))
324
+ extractor.load_model()
325
+ text_embeddings = extractor.cache_all_embeddings(CLASS_NAMES)
326
+ torch.save({"embeddings": text_embeddings.cpu(), "class_names": CLASS_NAMES}, cache_path)
327
+ extractor.unload()
328
+
329
+ text_embeddings = text_embeddings.to(device)
330
+ text_dim = text_embeddings.shape[1]
331
+
332
+ # Upload qwen_embeddings/ to HF
333
+ hf_token = get_hf_token()
334
+ qwen_staging = Path("./hf_staging/qwen_embeddings")
335
+ qwen_staging.mkdir(parents=True, exist_ok=True)
336
+
337
+ qwen_config = {
338
+ "model_name": QwenEmbeddingExtractor.MODEL_NAME,
339
+ "hidden_dim": QwenEmbeddingExtractor.HIDDEN_DIM,
340
+ "extraction_method": "mean_pool_last_layer",
341
+ "prompt_style": "2shot_geometric",
342
+ "num_classes": NUM_CLASSES,
343
+ "class_names": CLASS_NAMES,
344
+ "embedding_shape": list(text_embeddings.shape),
345
+ }
346
+ with open(qwen_staging / "config.json", "w") as f:
347
+ json.dump(qwen_config, f, indent=2)
348
+ with open(qwen_staging / "descriptions.json", "w") as f:
349
+ json.dump(SHAPE_DESCRIPTIONS, f, indent=2)
350
+
351
+ try:
352
+ from safetensors.torch import save_file as st_save
353
+ st_save({"embeddings": text_embeddings.cpu()}, str(qwen_staging / "embeddings.safetensors"))
354
+ except ImportError:
355
+ torch.save({"embeddings": text_embeddings.cpu()}, qwen_staging / "embeddings.pt")
356
+
357
+ if hf_token:
358
+ try:
359
+ from huggingface_hub import HfApi, create_repo
360
+ api = HfApi(token=hf_token)
361
+ create_repo(HF_REPO, token=hf_token, exist_ok=True)
362
+ api.upload_folder(
363
+ folder_path=str(qwen_staging), repo_id=HF_REPO,
364
+ path_in_repo="qwen_embeddings", token=hf_token,
365
+ commit_message=f"qwen_embeddings | {QwenEmbeddingExtractor.MODEL_NAME} | {NUM_CLASSES} classes")
366
+ print(f"Uploaded: https://huggingface.co/{HF_REPO}/tree/main/qwen_embeddings")
367
+ except Exception as e:
368
+ print(f"Upload failed: {e}")
369
+ else:
370
+ print("No HF_TOKEN — saved locally")
371
+
372
+
373
+ # =============================================================================
374
+ # PHASE 2: Load Geo Model + Dataset
375
+ # =============================================================================
376
+
377
+ print("\n" + "=" * 70)
378
+ print("Phase 2: Geo Model + Voxel Data")
379
+ print("=" * 70)
380
+
381
+ geo_model = load_geo_model()
382
+
383
+ CC_SAMPLES = 500000
384
+ CC_BATCH = 4096
385
+ CC_EPOCHS = 40
386
+ CC_LR = 2e-3
387
+ CC_LATENT = 256
388
+
389
+ # Reuse Cell 3's cached dataset
390
+ DATASET_PATH = Path("./cached_dataset.pt")
391
+ if not DATASET_PATH.exists():
392
+ raise FileNotFoundError("No cached_dataset.pt — run Cell 3 first.")
393
+
394
+ print(f"Loading dataset from {DATASET_PATH}...")
395
+ _cached = torch.load(DATASET_PATH, weights_only=True)
396
+ cc_train_ds = ShapeDataset.__new__(ShapeDataset)
397
+ cc_val_ds = ShapeDataset.__new__(ShapeDataset)
398
+ for k in ["grids", "labels", "dim_conf", "peak_dim", "volume", "cm_det", "is_curved", "curvature"]:
399
+ setattr(cc_train_ds, k, _cached["train"][k])
400
+ setattr(cc_val_ds, k, _cached["val"][k])
401
+ print(f"Loaded {len(cc_train_ds)} train + {len(cc_val_ds)} val (from Cell 3 cache)")
402
+
403
+ cc_train_loader = torch.utils.data.DataLoader(
404
+ cc_train_ds, batch_size=CC_BATCH, shuffle=True,
405
+ num_workers=4, pin_memory=True, persistent_workers=True)
406
+ cc_val_loader = torch.utils.data.DataLoader(
407
+ cc_val_ds, batch_size=CC_BATCH, shuffle=False,
408
+ num_workers=4, pin_memory=True, persistent_workers=True)
409
+
410
+ # Probe voxel feature dim
411
+ with torch.no_grad():
412
+ _dummy = torch.zeros(1, GS, GS, GS, device=device)
413
+ voxel_dim = extract_voxel_features(geo_model, _dummy).shape[1]
414
+ print(f"Voxel dim: {voxel_dim} | Text dim: {text_dim}")
415
+
416
+
417
+ # =============================================================================
418
+ # PHASE 3: Cross-Contrast Training
419
+ # =============================================================================
420
+
421
+ print("\n" + "=" * 70)
422
+ print("Phase 3: Cross-Contrast Training")
423
+ print("=" * 70)
424
+
425
+ cc_model = CrossContrastModel(
426
+ text_dim=text_dim, voxel_dim=voxel_dim,
427
+ latent_dim=CC_LATENT, n_classes=NUM_CLASSES
428
+ ).to(device)
429
+ cc_params = sum(p.numel() for p in cc_model.parameters())
430
+ print(f"CrossContrast: {cc_params:,} params | latent={CC_LATENT}")
431
+
432
+ cc_opt = torch.optim.AdamW(cc_model.parameters(), lr=CC_LR, weight_decay=1e-4)
433
+ _warmup = 3
434
+ def _cc_lr(ep):
435
+ if ep < _warmup: return (ep + 1) / _warmup
436
+ return 0.5 * (1 + math.cos(math.pi * (ep - _warmup) / (CC_EPOCHS - _warmup)))
437
+ cc_sched = torch.optim.lr_scheduler.LambdaLR(cc_opt, _cc_lr)
438
+
439
+ # Resume CC training if checkpoint exists
440
+ cc_start, best_cc_acc = load_cc_checkpoint(cc_model, cc_opt, cc_sched)
441
+
442
+ t_start = time.time()
443
+ epoch_bar = tqdm(range(cc_start, CC_EPOCHS), desc="Training", unit="ep")
444
+
445
+ for epoch in epoch_bar:
446
+ t0 = time.time()
447
+ cc_model.train()
448
+ tot_loss, tot_acc, nb = 0, 0, 0
449
+
450
+ batch_bar = tqdm(cc_train_loader, desc=f"Ep {epoch+1}/{CC_EPOCHS} train",
451
+ leave=False, unit="batch")
452
+ for grid, label, *_ in batch_bar:
453
+ grid = grid.to(device, non_blocking=True)
454
+ label = label.to(device, non_blocking=True)
455
+ vf = extract_voxel_features(geo_model, grid)
456
+
457
+ cc_opt.zero_grad(set_to_none=True)
458
+ with torch.amp.autocast('cuda', enabled=use_amp, dtype=amp_dtype):
459
+ loss, metrics = cc_model(vf, label, text_embeddings)
460
+
461
+ loss.backward()
462
+ torch.nn.utils.clip_grad_norm_(cc_model.parameters(), 1.0)
463
+ cc_opt.step()
464
+ tot_loss += loss.item(); tot_acc += metrics["acc"]; nb += 1
465
+ batch_bar.set_postfix(loss=f"{loss.item():.4f}", acc=f"{metrics['acc']:.3f}")
466
+
467
+ cc_sched.step()
468
+
469
+ cc_model.eval()
470
+ vl, va, vps, vns, vnb = 0, 0, 0, 0, 0
471
+ with torch.no_grad(), torch.amp.autocast('cuda', enabled=use_amp, dtype=amp_dtype):
472
+ for grid, label, *_ in tqdm(cc_val_loader, desc=f"Ep {epoch+1}/{CC_EPOCHS} val",
473
+ leave=False, unit="batch"):
474
+ grid = grid.to(device, non_blocking=True)
475
+ label = label.to(device, non_blocking=True)
476
+ vf = extract_voxel_features(geo_model, grid)
477
+ loss, m = cc_model(vf, label, text_embeddings)
478
+ vl += loss.item(); va += m["acc"]; vps += m["pos_sim"]; vns += m["neg_sim"]; vnb += 1
479
+
480
+ tl = tot_loss/max(nb,1); ta = tot_acc/max(nb,1)
481
+ vl_ = vl/max(vnb,1); va_ = va/max(vnb,1)
482
+ ps = vps/max(vnb,1); ns = vns/max(vnb,1)
483
+ temp = cc_model.temperature.item()
484
+ dt = time.time() - t0
485
+ mk = " *" if va_ > best_cc_acc else ""
486
+ if va_ > best_cc_acc: best_cc_acc = va_
487
+
488
+ save_cc_checkpoint(cc_model, cc_opt, cc_sched, epoch, best_cc_acc)
489
+
490
+ # Upload to HF on new best or every 10 epochs
491
+ is_new_best = mk == " *"
492
+ periodic = (epoch + 1) % 10 == 0
493
+ if is_new_best:
494
+ upload_cc_to_hf(cc_model, best_cc_acc, epoch, hf_token, reason="new_best",
495
+ text_dim_=text_dim, voxel_dim_=voxel_dim, latent_dim_=CC_LATENT)
496
+ elif periodic:
497
+ upload_cc_to_hf(cc_model, best_cc_acc, epoch, hf_token, reason="periodic",
498
+ text_dim_=text_dim, voxel_dim_=voxel_dim, latent_dim_=CC_LATENT)
499
+
500
+ epoch_bar.set_postfix(loss=f"{vl_:.4f}", acc=f"{va_:.3f}", best=f"{best_cc_acc:.3f}",
501
+ tau=f"{temp:.4f}")
502
+
503
+ if (epoch+1) % 5 == 0 or epoch == cc_start or mk:
504
+ tqdm.write(f"Ep {epoch+1:3d}/{CC_EPOCHS} [{dt:.1f}s] | "
505
+ f"loss {tl:.4f}/{vl_:.4f} | acc {ta:.3f}/{va_:.3f} | "
506
+ f"pos {ps:.3f} neg {ns:.3f} | τ {temp:.4f}{mk}")
507
+
508
+ if epoch == cc_start and device.type == "cuda":
509
+ tqdm.write(f"VRAM peak: {torch.cuda.max_memory_allocated()/1e9:.2f}GB")
510
+
511
+ tt = time.time() - t_start
512
+ print(f"\nDone in {tt:.0f}s ({tt/60:.1f}min) | Best acc: {best_cc_acc:.4f}")
513
+
514
+
515
+ # =============================================================================
516
+ # Per-Class Alignment Analysis
517
+ # =============================================================================
518
+
519
+ print("\n" + "=" * 70)
520
+ print("Per-Class Alignment")
521
+ print("=" * 70)
522
+
523
+ cc_model.eval()
524
+ cls_vox = {n: [] for n in CLASS_NAMES}
525
+ with torch.no_grad():
526
+ text_proj_all = F.normalize(cc_model.text_proj(text_embeddings), dim=-1)
527
+
528
+ with torch.no_grad(), torch.amp.autocast('cuda', enabled=use_amp, dtype=amp_dtype):
529
+ for grid, label, *_ in cc_val_loader:
530
+ grid = grid.to(device, non_blocking=True)
531
+ label = label.to(device, non_blocking=True)
532
+ vf = extract_voxel_features(geo_model, grid)
533
+ zv = F.normalize(cc_model.voxel_proj(vf), dim=-1)
534
+ for k in range(len(label)):
535
+ cls_vox[CLASS_NAMES[label[k].item()]].append(zv[k].cpu())
536
+
537
+ print(f"\n{'Class':22s} | {'Align':>6s} | {'N':>5s} | {'Nearest':22s} | {'OK':>3s}")
538
+ print("-" * 70)
539
+ correct = 0; total_c = 0
540
+ for name in CLASS_NAMES:
541
+ if not cls_vox[name]: continue
542
+ mv = F.normalize(torch.stack(cls_vox[name]).mean(dim=0), dim=-1)
543
+ own = text_proj_all[CLASS_NAMES.index(name)].cpu()
544
+ align = (mv * own).sum().item()
545
+ sims = (mv.unsqueeze(0) @ text_proj_all.cpu().T).squeeze(0)
546
+ ni = sims.argmax().item(); nn_ = CLASS_NAMES[ni]
547
+ ok = "Y" if nn_ == name else f"X->{nn_}"
548
+ if nn_ == name: correct += 1
549
+ total_c += 1
550
+ print(f" {name:20s} | {align:.4f} | {len(cls_vox[name]):5d} | {nn_:22s} | {ok}")
551
+ print(f"\nNearest-text accuracy: {correct}/{total_c} = {correct/max(total_c,1):.1%}")
552
+
553
+ print("\nTop 10 Text-Space Confusions:")
554
+ with torch.no_grad():
555
+ sim = (text_proj_all @ text_proj_all.T).cpu().numpy()
556
+ import numpy as np
557
+ confusions = []
558
+ for i in range(len(CLASS_NAMES)):
559
+ for j in range(i+1, len(CLASS_NAMES)):
560
+ confusions.append((CLASS_NAMES[i], CLASS_NAMES[j], sim[i,j]))
561
+ confusions.sort(key=lambda x: x[2], reverse=True)
562
+ for a, b, s in confusions[:10]:
563
+ print(f" {a:20s} <-> {b:20s} | {s:.4f}")
564
+
565
+
566
+ # =============================================================================
567
+ # Upload crosscontrast/ to HuggingFace (final — with full configs)
568
+ # =============================================================================
569
+
570
+ print("\n" + "=" * 70)
571
+ print("Saving crosscontrast/ to HuggingFace")
572
+ print("=" * 70)
573
+
574
+ cc_staging = Path("./hf_staging/crosscontrast")
575
+ cc_staging.mkdir(parents=True, exist_ok=True)
576
+
577
+ # Write detailed architecture config (overwrites minimal mid-training config)
578
+ cc_arch = {
579
+ "model_type": "CrossContrastModel",
580
+ "text_dim": text_dim,
581
+ "voxel_dim": voxel_dim,
582
+ "latent_dim": CC_LATENT,
583
+ "n_classes": NUM_CLASSES,
584
+ "text_proj_layers": [text_dim, CC_LATENT * 2, CC_LATENT, CC_LATENT],
585
+ "voxel_proj_layers": [voxel_dim, CC_LATENT * 2, CC_LATENT, CC_LATENT],
586
+ "activation": "GELU",
587
+ "normalization": "LayerNorm",
588
+ "total_params": cc_params,
589
+ "class_names": CLASS_NAMES,
590
+ "text_encoder": QwenEmbeddingExtractor.MODEL_NAME,
591
+ "voxel_encoder": "GeometricShapeClassifier_v8",
592
+ }
593
+ with open(cc_staging / "config.json", "w") as f:
594
+ json.dump(cc_arch, f, indent=2)
595
+
596
+ cc_train_cfg = {
597
+ "n_samples": CC_SAMPLES, "epochs": CC_EPOCHS, "batch_size": CC_BATCH,
598
+ "lr": CC_LR, "weight_decay": 1e-4, "optimizer": "AdamW",
599
+ "scheduler": "cosine_with_warmup", "warmup_epochs": _warmup,
600
+ "loss": "symmetric_InfoNCE", "initial_temperature": 0.07,
601
+ "final_temperature": cc_model.temperature.item(),
602
+ "amp_dtype": str(amp_dtype),
603
+ "best_val_accuracy": best_cc_acc,
604
+ "nearest_text_accuracy": correct / max(total_c, 1),
605
+ "total_training_time_seconds": tt,
606
+ }
607
+ with open(cc_staging / "training_config.json", "w") as f:
608
+ json.dump(cc_train_cfg, f, indent=2)
609
+
610
+ # Final upload with full configs + weights
611
+ upload_cc_to_hf(cc_model, best_cc_acc, CC_EPOCHS - 1, hf_token, reason="final",
612
+ text_dim_=text_dim, voxel_dim_=voxel_dim, latent_dim_=CC_LATENT)
613
+ if not hf_token:
614
+ print("No HF_TOKEN — saved locally at ./hf_staging/crosscontrast/")
615
+
616
+ print(f"\nAll three subdirectories staged:")
617
+ print(f" geometric_classifier/ — from Cell 3")
618
+ print(f" qwen_embeddings/ — {text_embeddings.shape}")
619
+ print(f" crosscontrast/ — latent={CC_LATENT}, acc={best_cc_acc:.4f}")
620
+ print(f" Repo: https://huggingface.co/{HF_REPO}")