AbstractPhil commited on
Commit
05ced82
Β·
verified Β·
1 Parent(s): d48e4dc

Create geolip_image_encoder_conv.py

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