AbstractPhil commited on
Commit
ab5baae
Β·
verified Β·
1 Parent(s): ac36de0

Create geolip_image_encoder_conv.py

Browse files
Files changed (1) hide show
  1. geolip_image_encoder_conv.py +442 -0
geolip_image_encoder_conv.py ADDED
@@ -0,0 +1,442 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ GeoLIP Image Encoder - CONV variation
3
+ =====================================
4
+ Complete trainable model: conv encoder β†’ S^(d-1) β†’ magnitude β†’ constellation β†’ classify.
5
+
6
+ Classes:
7
+ ConvEncoder: 8-layer conv β†’ D-dim projection
8
+ InternalConstellationCore: Three-domain head (external + geometric + internal)
9
+ GeoLIPImageEncoder: Full pipeline: encoder + MagnitudeFlow + core
10
+
11
+ Usage:
12
+ from geolip_encoder import GeoLIPImageEncoder
13
+
14
+ model = GeoLIPImageEncoder(num_classes=100, output_dim=384, n_anchors=2048)
15
+ out = model.forward_paired(v1, v2)
16
+ loss, ld = model.compute_loss(out, targets)
17
+
18
+ Author: AbstractPhil + Claude Opus 4.6
19
+ License: Apache 2.0
20
+ """
21
+
22
+ import torch
23
+ import torch.nn as nn
24
+ import torch.nn.functional as F
25
+
26
+ from geolip_core import (
27
+ Constellation, Patchwork, MagnitudeFlow,
28
+ make_activation, param_count, model_summary,
29
+ )
30
+ from geolip_losses import (
31
+ cv_loss, cv_metric, spread_loss, attraction_loss,
32
+ nce_loss, ce_loss_paired, bridge_loss_paired,
33
+ assign_bce_loss, assign_nce_loss, knn_accuracy,
34
+ )
35
+
36
+
37
+ # ══════════════════════════════════════════════════════════════════
38
+ # CONV ENCODER β€” 8-layer, proven on CIFAR-100
39
+ # ══════════════════════════════════════════════════════════════════
40
+
41
+ class ConvEncoder(nn.Module):
42
+ """8-layer conv β†’ D-dim projection on S^(d-1).
43
+
44
+ Architecture: 4 blocks of (conv-BN-GELU, conv-BN-GELU, MaxPool)
45
+ Channels: 64 β†’ 128 β†’ 256 β†’ 384
46
+ Output: (B, output_dim) after linear + LayerNorm
47
+
48
+ Note: L2 normalization is NOT applied here β€” the caller decides
49
+ when to normalize (preserving raw magnitude for MagnitudeFlow).
50
+ """
51
+
52
+ def __init__(self, output_dim=256):
53
+ super().__init__()
54
+ self.output_dim = output_dim
55
+ self.features = nn.Sequential(
56
+ nn.Conv2d(3, 64, 3, padding=1), nn.BatchNorm2d(64), nn.GELU(),
57
+ nn.Conv2d(64, 64, 3, padding=1), nn.BatchNorm2d(64), nn.GELU(),
58
+ nn.MaxPool2d(2),
59
+ nn.Conv2d(64, 128, 3, padding=1), nn.BatchNorm2d(128), nn.GELU(),
60
+ nn.Conv2d(128, 128, 3, padding=1), nn.BatchNorm2d(128), nn.GELU(),
61
+ nn.MaxPool2d(2),
62
+ nn.Conv2d(128, 256, 3, padding=1), nn.BatchNorm2d(256), nn.GELU(),
63
+ nn.Conv2d(256, 256, 3, padding=1), nn.BatchNorm2d(256), nn.GELU(),
64
+ nn.MaxPool2d(2),
65
+ nn.Conv2d(256, 384, 3, padding=1), nn.BatchNorm2d(384), nn.GELU(),
66
+ nn.Conv2d(384, 384, 3, padding=1), nn.BatchNorm2d(384), nn.GELU(),
67
+ nn.MaxPool2d(2),
68
+ nn.AdaptiveAvgPool2d(1),
69
+ nn.Flatten(),
70
+ )
71
+ self.proj = nn.Sequential(
72
+ nn.Linear(384, output_dim),
73
+ nn.LayerNorm(output_dim),
74
+ )
75
+
76
+ def forward(self, x):
77
+ """Returns: (B, output_dim) unnormalized features."""
78
+ return self.proj(self.features(x))
79
+
80
+
81
+ # ══════════════════════════════════════════════════════════════════
82
+ # INTERNAL CONSTELLATION CORE β€” three-domain head
83
+ # ══════════════════════════════════════════════════════════════════
84
+
85
+ class InternalConstellationCore(nn.Module):
86
+ """Constellation with independent internal + external objectives.
87
+
88
+ The constellation discovers its own structure. The task head reads it.
89
+
90
+ Three domains:
91
+ EXTERNAL: CE + embedding NCE β†’ task_head, patchwork, encoder
92
+ GEOMETRIC: patchwork NCE + bridge β†’ patchwork, encoder, anchors
93
+ INTERNAL: assign + tri NCE + attract + CV + spread β†’ anchors, encoder
94
+
95
+ Args:
96
+ num_classes: classification targets
97
+ dim: embedding dimension
98
+ n_anchors: anchors on S^(dim-1)
99
+ n_comp: patchwork compartments
100
+ d_comp: hidden dim per compartment
101
+ anchor_drop: training anchor dropout
102
+ activation: activation function name
103
+ cv_target: target CV for geometric loss
104
+ infonce_temp: embedding NCE temperature
105
+ assign_temp: assignment temperature
106
+ assign_sharpness: BCE target sharpness
107
+ """
108
+
109
+ def __init__(
110
+ self,
111
+ num_classes=100,
112
+ dim=256,
113
+ n_anchors=128,
114
+ n_comp=8,
115
+ d_comp=64,
116
+ anchor_drop=0.15,
117
+ activation='squared_relu',
118
+ cv_target=0.22,
119
+ infonce_temp=0.07,
120
+ assign_temp=0.1,
121
+ assign_sharpness=5.0,
122
+ ):
123
+ super().__init__()
124
+ self.num_classes = num_classes
125
+ self.dim = dim
126
+ self.n_anchors = n_anchors
127
+ self.cv_target = cv_target
128
+ self.infonce_temp = infonce_temp
129
+ self.assign_temp = assign_temp
130
+ self.assign_sharpness = assign_sharpness
131
+
132
+ self.config = {k: v for k, v in locals().items()
133
+ if k != 'self' and not k.startswith('_')}
134
+
135
+ # Constellation β€” owns its own geometry
136
+ self.constellation = Constellation(n_anchors, dim, anchor_drop)
137
+
138
+ # Patchwork β€” interprets distance patterns
139
+ self.patchwork = Patchwork(n_anchors, n_comp, d_comp, activation)
140
+ pw_dim = self.patchwork.output_dim
141
+
142
+ # Bridge: patchwork predicts constellation's assignment
143
+ self.bridge = nn.Sequential(nn.Linear(pw_dim, n_anchors))
144
+
145
+ # Task head: reads assignment + patchwork + embedding
146
+ total_feat = n_anchors + pw_dim + dim
147
+ self.task_head = nn.Sequential(
148
+ nn.Linear(total_feat, pw_dim),
149
+ make_activation(activation),
150
+ nn.LayerNorm(pw_dim),
151
+ nn.Dropout(0.1),
152
+ nn.Linear(pw_dim, num_classes),
153
+ )
154
+
155
+ # Buffers
156
+ self.register_buffer('anchor_classes', torch.zeros(n_anchors, dtype=torch.long))
157
+ self.register_buffer('class_centroids', torch.zeros(num_classes, dim))
158
+
159
+ def _triangulate(self, emb):
160
+ """emb β†’ (cos, tri, nearest, soft_assign)."""
161
+ anchors_n = F.normalize(self.constellation.anchors, dim=-1)
162
+ cos = emb @ anchors_n.T
163
+ tri = 1.0 - cos
164
+ _, nearest = cos.max(dim=-1)
165
+ soft_assign = F.softmax(cos / self.assign_temp, dim=-1)
166
+ return cos, tri, nearest, soft_assign
167
+
168
+ def forward_paired(self, emb1, emb2, mag1=None, mag2=None):
169
+ """Paired forward for training. Returns dict with all intermediates."""
170
+ cos1, tri1, nearest1, assign1 = self._triangulate(emb1)
171
+ cos2, tri2, nearest2, assign2 = self._triangulate(emb2)
172
+
173
+ # Magnitude weighting
174
+ tri1_w = tri1 * mag1 if mag1 is not None else tri1
175
+ tri2_w = tri2 * mag2 if mag2 is not None else tri2
176
+
177
+ # Patchwork
178
+ pw1 = self.patchwork(tri1_w)
179
+ pw2 = self.patchwork(tri2_w)
180
+
181
+ # Bridge
182
+ bridge1 = self.bridge(pw1)
183
+ bridge2 = self.bridge(pw2)
184
+
185
+ # Task head
186
+ feat1 = torch.cat([assign1, pw1, emb1], dim=-1)
187
+ feat2 = torch.cat([assign2, pw2, emb2], dim=-1)
188
+ logits1 = self.task_head(feat1)
189
+ logits2 = self.task_head(feat2)
190
+
191
+ return {
192
+ 'embedding': emb1, 'embedding_aug': emb2,
193
+ 'mag1': mag1, 'mag2': mag2,
194
+ 'cos1': cos1, 'cos2': cos2,
195
+ 'tri1': tri1, 'tri2': tri2,
196
+ 'nearest': nearest1,
197
+ 'assign1': assign1, 'assign2': assign2,
198
+ 'patchwork1': pw1, 'patchwork1_aug': pw2,
199
+ 'bridge1': bridge1, 'bridge2': bridge2,
200
+ 'logits': logits1, 'logits_aug': logits2,
201
+ }
202
+
203
+ def forward(self, emb, mag=None):
204
+ """Single view for eval."""
205
+ out = self.forward_paired(emb, emb, mag, mag)
206
+ return {
207
+ 'logits': out['logits'],
208
+ 'embedding': emb,
209
+ 'magnitude': mag,
210
+ 'triangulation': out['tri1'],
211
+ 'cos_to_anchors': out['cos1'],
212
+ 'nearest': out['nearest'],
213
+ 'assignment': out['assign1'],
214
+ 'patchwork': out['patchwork1'],
215
+ }
216
+
217
+ def compute_loss(self, output, targets,
218
+ w_ce=1.0, w_nce_emb=0.5,
219
+ w_nce_pw=1.0, w_bridge=1.0,
220
+ w_assign=0.5, w_assign_nce=0.25,
221
+ w_nce_tri=0.5, w_attract=0.25,
222
+ w_cv=0.01, w_spread=0.01,
223
+ cv_batched=True):
224
+ """Three-domain cooperative loss.
225
+
226
+ Returns:
227
+ total_loss, loss_dict
228
+ """
229
+ ld = {}
230
+ emb1, emb2 = output['embedding'], output['embedding_aug']
231
+
232
+ # ── EXTERNAL ──
233
+ l_ce, acc = ce_loss_paired(output['logits'], output['logits_aug'], targets)
234
+ ld['ce'], ld['acc'] = l_ce, acc
235
+
236
+ l_nce_emb, nce_emb_acc = nce_loss(emb1, emb2, self.infonce_temp, normalize=False)
237
+ ld['nce_emb'], ld['nce_emb_acc'] = l_nce_emb, nce_emb_acc
238
+
239
+ # ── GEOMETRIC ──
240
+ l_nce_pw, nce_pw_acc = nce_loss(
241
+ output['patchwork1'], output['patchwork1_aug'], self.assign_temp, normalize=True)
242
+ ld['nce_pw'], ld['nce_pw_acc'] = l_nce_pw, nce_pw_acc
243
+
244
+ l_bridge, bridge_acc = bridge_loss_paired(
245
+ output['bridge1'], output['bridge2'],
246
+ output['assign1'], output['assign2'])
247
+ ld['bridge'], ld['bridge_acc'] = l_bridge, bridge_acc
248
+
249
+ # ── INTERNAL ──
250
+ l_assign, assign_ent = assign_bce_loss(output['assign1'], output['cos1'])
251
+ ld['assign'], ld['assign_entropy'] = l_assign, assign_ent
252
+
253
+ l_assign_nce, assign_nce_acc = assign_nce_loss(
254
+ output['assign1'], output['assign2'], self.assign_temp)
255
+ ld['assign_nce'], ld['assign_nce_acc'] = l_assign_nce, assign_nce_acc
256
+
257
+ l_nce_tri, nce_tri_acc = nce_loss(
258
+ output['tri1'], output['tri2'], 0.1, normalize=True)
259
+ ld['nce_tri'], ld['nce_tri_acc'] = l_nce_tri, nce_tri_acc
260
+
261
+ l_attract, nearest_cos = attraction_loss(output['cos1'])
262
+ ld['attract'], ld['nearest_cos'] = l_attract, nearest_cos
263
+
264
+ l_cv = cv_loss(emb1, target=self.cv_target, batched=cv_batched)
265
+ ld['cv'] = l_cv
266
+
267
+ l_spread = spread_loss(self.constellation.anchors)
268
+ ld['spread'] = l_spread
269
+
270
+ # ── kNN ──
271
+ ld['knn_acc'] = knn_accuracy(emb1, targets)
272
+
273
+ # ── TOTAL ──
274
+ loss_external = w_ce * l_ce + w_nce_emb * l_nce_emb
275
+ loss_geometric = w_nce_pw * l_nce_pw + w_bridge * l_bridge
276
+ loss_internal = (w_assign * l_assign + w_assign_nce * l_assign_nce
277
+ + w_nce_tri * l_nce_tri + w_attract * l_attract
278
+ + w_cv * l_cv + w_spread * l_spread)
279
+
280
+ loss = loss_external + loss_geometric + loss_internal
281
+
282
+ ld['loss_external'] = loss_external.item()
283
+ ld['loss_geometric'] = loss_geometric.item()
284
+ ld['loss_internal'] = loss_internal.item()
285
+ ld['t_ce'] = l_ce.item()
286
+ ld['t_nce_emb'] = l_nce_emb.item()
287
+ ld['t_nce_pw'] = l_nce_pw.item()
288
+ ld['t_bridge'] = l_bridge.item()
289
+ ld['t_assign'] = l_assign.item()
290
+ ld['t_assign_nce'] = l_assign_nce.item()
291
+ ld['t_nce_tri'] = l_nce_tri.item()
292
+ ld['t_attract'] = l_attract.item()
293
+ ld['total'] = loss
294
+
295
+ return loss, ld
296
+
297
+
298
+ # ══════════════════════════════════════════════════════════════════
299
+ # GEOLIP IMAGE ENCODER β€” full pipeline
300
+ # ══════════════════════════════════════════════════════════════════
301
+
302
+ class GeoLIPImageEncoder(nn.Module):
303
+ """Complete GeoLIP model: ConvEncoder β†’ S^(d-1) β†’ MagnitudeFlow β†’ Core.
304
+
305
+ Args:
306
+ num_classes: classification targets
307
+ output_dim: embedding dimension on S^(d-1)
308
+ n_anchors: constellation anchors
309
+ n_comp: patchwork compartments
310
+ d_comp: per-compartment hidden dim
311
+ anchor_drop: training anchor dropout
312
+ activation: activation function name
313
+ cv_target: CV loss target
314
+ infonce_temp: embedding NCE temperature
315
+ assign_temp: assignment temperature
316
+ assign_sharpness: BCE sharpness
317
+ mag_hidden: magnitude relay patchwork hidden dim
318
+ mag_heads: unused (API compat)
319
+ mag_layers: relay layers in MagnitudeFlow
320
+ mag_min: minimum magnitude
321
+ mag_max: maximum magnitude
322
+ """
323
+
324
+ def __init__(
325
+ self,
326
+ num_classes=100,
327
+ output_dim=384,
328
+ n_anchors=512,
329
+ n_comp=8,
330
+ d_comp=64,
331
+ anchor_drop=0.15,
332
+ activation='squared_relu',
333
+ cv_target=0.22,
334
+ infonce_temp=0.07,
335
+ assign_temp=0.1,
336
+ assign_sharpness=5.0,
337
+ mag_hidden=64,
338
+ mag_heads=4,
339
+ mag_layers=2,
340
+ mag_min=0.1,
341
+ mag_max=5.0,
342
+ ):
343
+ super().__init__()
344
+ self.output_dim = output_dim
345
+ self.config = {k: v for k, v in locals().items()
346
+ if k != 'self' and not k.startswith('_')}
347
+
348
+ self.encoder = ConvEncoder(output_dim)
349
+
350
+ self.mag_flow = MagnitudeFlow(
351
+ dim=output_dim, n_anchors=n_anchors,
352
+ hidden_dim=mag_hidden, n_heads=mag_heads, n_layers=mag_layers,
353
+ mag_min=mag_min, mag_max=mag_max, n_comp=n_comp,
354
+ )
355
+
356
+ self.core = InternalConstellationCore(
357
+ num_classes=num_classes, dim=output_dim,
358
+ n_anchors=n_anchors, n_comp=n_comp, d_comp=d_comp,
359
+ anchor_drop=anchor_drop, activation=activation,
360
+ cv_target=cv_target, infonce_temp=infonce_temp,
361
+ assign_temp=assign_temp, assign_sharpness=assign_sharpness,
362
+ )
363
+
364
+ self._init_encoder_weights()
365
+
366
+ def _init_encoder_weights(self):
367
+ for m in self.encoder.modules():
368
+ if isinstance(m, nn.Linear):
369
+ nn.init.trunc_normal_(m.weight, std=0.02)
370
+ if m.bias is not None: nn.init.zeros_(m.bias)
371
+ elif isinstance(m, nn.Conv2d):
372
+ nn.init.kaiming_normal_(m.weight, mode='fan_out')
373
+ if m.bias is not None: nn.init.zeros_(m.bias)
374
+ elif isinstance(m, (nn.BatchNorm2d, nn.LayerNorm)):
375
+ nn.init.ones_(m.weight); nn.init.zeros_(m.bias)
376
+
377
+ def _encode(self, x):
378
+ """Pixels β†’ S^(d-1) + per-anchor magnitude."""
379
+ feat = self.encoder(x)
380
+ raw_mag = feat.norm(dim=-1, keepdim=True)
381
+ emb = F.normalize(feat, dim=-1)
382
+
383
+ anchors_n = F.normalize(self.core.constellation.anchors, dim=-1)
384
+ tri = emb @ anchors_n.T
385
+ mag, mag_comp = self.mag_flow(emb, tri, raw_mag)
386
+
387
+ return emb, mag, mag_comp
388
+
389
+ def forward_paired(self, v1, v2):
390
+ """Training: two views β†’ full pipeline."""
391
+ emb1, mag1, mc1 = self._encode(v1)
392
+ emb2, mag2, mc2 = self._encode(v2)
393
+ out = self.core.forward_paired(emb1, emb2, mag1, mag2)
394
+ out['mag_comp1'] = mc1
395
+ out['mag_comp2'] = mc2
396
+ return out
397
+
398
+ def forward(self, x):
399
+ """Eval: single view β†’ classify."""
400
+ emb, mag, mag_comp = self._encode(x)
401
+ out = self.core(emb, mag)
402
+ out['mag_comp'] = mag_comp
403
+ return out
404
+
405
+ def compute_loss(self, output, targets, **kwargs):
406
+ """Delegate to core's three-domain loss."""
407
+ return self.core.compute_loss(output, targets, **kwargs)
408
+
409
+ def get_anchor_param_ids(self):
410
+ """Return set of param ids that should have weight_decay=0.
411
+
412
+ Includes constellation anchors + all relay layer anchors.
413
+ """
414
+ ids = set(id(p) for p in self.core.constellation.parameters())
415
+ for relay in self.mag_flow.relays:
416
+ ids.add(id(relay.anchors))
417
+ return ids
418
+
419
+ def make_optimizer(self, lr=3e-4, weight_decay=0.05):
420
+ """Build AdamW with proper anchor exclusion from weight decay."""
421
+ anchor_ids = self.get_anchor_param_ids()
422
+ decay = [p for p in self.parameters() if id(p) not in anchor_ids]
423
+ nodecay = [p for p in self.parameters() if id(p) in anchor_ids]
424
+ return torch.optim.AdamW([
425
+ {'params': decay, 'weight_decay': weight_decay},
426
+ {'params': nodecay, 'weight_decay': 0.0},
427
+ ], lr=lr)
428
+
429
+ def summary(self):
430
+ """Print parameter breakdown."""
431
+ print("GeoLIPImageEncoder Summary")
432
+ print("=" * 50)
433
+ param_count(self.encoder, "encoder")
434
+ param_count(self.mag_flow, "mag_flow")
435
+ param_count(self.core.constellation, "constellation")
436
+ param_count(self.core.patchwork, "patchwork")
437
+ param_count(self.core.bridge, "bridge")
438
+ param_count(self.core.task_head, "task_head")
439
+ print("-" * 50)
440
+ total = model_summary(self)
441
+ print(f"\n Config: {self.config}")
442
+ return total