AbstractPhil commited on
Commit
cf3bcc2
Β·
verified Β·
1 Parent(s): 2e7a9f5

Create cell2_model.py

Browse files
Files changed (1) hide show
  1. cell2_model.py +363 -0
cell2_model.py ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Patch Cross-Attention Shape Classifier β€” VAE-Matched (8Γ—16Γ—16)
3
+ ================================================================
4
+ Replaces Conv3d backbone with v11-style decomposition + cross-attention.
5
+
6
+ Input: (B, 8, 16, 16) binary voxel grid
7
+ β†’ Decompose into patches (macro grid)
8
+ β†’ Shared patch encoder (MLP + handcrafted)
9
+ β†’ Positional embedding
10
+ β†’ Cross-attention layers (patches attend to each other)
11
+ β†’ Pool β†’ Classify
12
+
13
+ Patch scheme: 2Γ—4Γ—4 patches β†’ 4Γ—4Γ—4 macro grid (64 patches, 32 voxels each)
14
+ - Preserves aspect ratio at macro level
15
+ - 32 voxels per patch = tractable for shared MLP
16
+ - 64 patches = reasonable sequence length for attention
17
+ """
18
+
19
+ import math
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+
24
+ # === Grid Constants ===========================================================
25
+ GZ = 8
26
+ GY = 16
27
+ GX = 16
28
+ GRID_SHAPE = (GZ, GY, GX)
29
+ GRID_VOLUME = GZ * GY * GX # 2048
30
+
31
+ # Patch decomposition
32
+ PATCH_Z = 2
33
+ PATCH_Y = 4
34
+ PATCH_X = 4
35
+ PATCH_VOL = PATCH_Z * PATCH_Y * PATCH_X # 32
36
+
37
+ MACRO_Z = GZ // PATCH_Z # 4
38
+ MACRO_Y = GY // PATCH_Y # 4
39
+ MACRO_X = GX // PATCH_X # 4
40
+ MACRO_N = MACRO_Z * MACRO_Y * MACRO_X # 64
41
+
42
+ # Shape classes
43
+ NUM_CLASSES = 38
44
+ NUM_CURVATURES = 8
45
+
46
+ CLASS_NAMES = [
47
+ "point", "line_x", "line_y", "line_z", "line_diag",
48
+ "cross", "l_shape", "collinear",
49
+ "triangle_xy", "triangle_xz", "triangle_3d",
50
+ "square_xy", "square_xz", "rectangle", "coplanar", "plane",
51
+ "tetrahedron", "pyramid", "pentachoron",
52
+ "cube", "cuboid", "triangular_prism", "octahedron",
53
+ "arc", "helix", "circle", "ellipse", "disc",
54
+ "sphere", "hemisphere", "cylinder", "cone", "capsule",
55
+ "torus", "shell", "tube", "bowl", "saddle",
56
+ ]
57
+
58
+ CURVATURE_NAMES = ["none", "convex", "concave", "cylindrical",
59
+ "conical", "toroidal", "hyperbolic", "helical"]
60
+
61
+
62
+ # === SwiGLU ===================================================================
63
+
64
+ class SwiGLU(nn.Module):
65
+ def __init__(self, in_dim, out_dim):
66
+ super().__init__()
67
+ self.w1 = nn.Linear(in_dim, out_dim)
68
+ self.w2 = nn.Linear(in_dim, out_dim)
69
+
70
+ def forward(self, x):
71
+ return self.w1(x) * F.silu(self.w2(x))
72
+
73
+
74
+ # === Patch Encoder ============================================================
75
+
76
+ class PatchEncoder(nn.Module):
77
+ """
78
+ Shared encoder for each 2Γ—4Γ—4 local patch.
79
+ Input: (M, 2, 4, 4) binary grids where M = B * 64
80
+ Output: (M, patch_feat_dim) feature vectors
81
+ """
82
+
83
+ def __init__(self, patch_feat_dim=96):
84
+ super().__init__()
85
+
86
+ # Learned features from raw voxels
87
+ self.mlp = nn.Sequential(
88
+ nn.Linear(PATCH_VOL, 256), nn.GELU(),
89
+ nn.Linear(256, 128), nn.GELU(),
90
+ nn.Linear(128, patch_feat_dim))
91
+
92
+ # Handcrafted: occupancy(1) + 3 axis std(3) + surface ratio(1)
93
+ # + z_spread(1) + yx_spread(1) = 7
94
+ n_hand = 7
95
+ self.combine = nn.Sequential(
96
+ nn.Linear(patch_feat_dim + n_hand, patch_feat_dim), nn.GELU(),
97
+ nn.Linear(patch_feat_dim, patch_feat_dim))
98
+
99
+ def forward(self, patches):
100
+ """patches: (M, 2, 4, 4)"""
101
+ M = patches.shape[0]
102
+ flat = patches.reshape(M, -1)
103
+
104
+ learned = self.mlp(flat)
105
+
106
+ # Handcrafted features
107
+ occ = flat.mean(dim=-1, keepdim=True)
108
+
109
+ ax_z = patches.mean(dim=(2, 3)).std(dim=1, keepdim=True)
110
+ ax_y = patches.mean(dim=(1, 3)).std(dim=1, keepdim=True)
111
+ ax_x = patches.mean(dim=(1, 2)).std(dim=1, keepdim=True)
112
+
113
+ # Surface ratio
114
+ padded = F.pad(patches.unsqueeze(1), (1,1,1,1,1,1), mode='constant', value=0)
115
+ neighbors = F.avg_pool3d(padded, kernel_size=3, stride=1, padding=0)
116
+ neighbors = neighbors.squeeze(1)
117
+ surface = ((neighbors < 1.0) & (patches > 0.5)).float().sum(dim=(1,2,3))
118
+ total = flat.sum(dim=-1).clamp(min=1)
119
+ surf_ratio = (surface / total).unsqueeze(-1)
120
+
121
+ # Spread: how much of the z vs yx space is used
122
+ z_spread = (patches.sum(dim=(2, 3)) > 0).float().mean(dim=1, keepdim=True)
123
+ yx_spread = (patches.sum(dim=1) > 0).float().mean(dim=(1, 2)).unsqueeze(-1)
124
+
125
+ hand = torch.cat([occ, ax_z, ax_y, ax_x, surf_ratio, z_spread, yx_spread], dim=-1)
126
+
127
+ return self.combine(torch.cat([learned, hand], dim=-1))
128
+
129
+
130
+ # === Cross-Attention Block ====================================================
131
+
132
+ class CrossAttentionBlock(nn.Module):
133
+ """
134
+ Pre-norm transformer block: LN β†’ MHA β†’ residual β†’ LN β†’ FFN β†’ residual.
135
+ Patches cross-attend to each other (self-attention over patch sequence).
136
+ """
137
+
138
+ def __init__(self, embed_dim, num_heads=8, ff_mult=2, dropout=0.05):
139
+ super().__init__()
140
+ self.ln1 = nn.LayerNorm(embed_dim)
141
+ self.attn = nn.MultiheadAttention(
142
+ embed_dim, num_heads=num_heads, batch_first=True, dropout=dropout)
143
+ self.ln2 = nn.LayerNorm(embed_dim)
144
+ self.ff = nn.Sequential(
145
+ nn.Linear(embed_dim, embed_dim * ff_mult), nn.GELU(),
146
+ nn.Linear(embed_dim * ff_mult, embed_dim),
147
+ nn.Dropout(dropout))
148
+
149
+ def forward(self, x):
150
+ # Self-attention (each patch attends to all patches)
151
+ normed = self.ln1(x)
152
+ attn_out, _ = self.attn(normed, normed, normed)
153
+ x = x + attn_out
154
+ x = x + self.ff(self.ln2(x))
155
+ return x
156
+
157
+
158
+ # === Main Classifier ==========================================================
159
+
160
+ class PatchCrossAttentionClassifier(nn.Module):
161
+ """
162
+ 8Γ—16Γ—16 β†’ patch decomposition β†’ shared encoder β†’ cross-attention β†’ classify.
163
+
164
+ Architecture:
165
+ 1. Decompose (B, 8, 16, 16) into (B, 64, 2, 4, 4) patches
166
+ 2. Shared PatchEncoder β†’ (B, 64, patch_feat_dim)
167
+ 3. Project + add 3D positional embedding β†’ (B, 64, embed_dim)
168
+ 4. N cross-attention layers
169
+ 5. Global pool β†’ classify
170
+
171
+ ~2-3M params depending on config.
172
+ """
173
+
174
+ def __init__(self, n_classes=NUM_CLASSES, embed_dim=128, patch_feat_dim=96,
175
+ n_layers=3, n_heads=8, dropout=0.05):
176
+ super().__init__()
177
+ self.embed_dim = embed_dim
178
+ self.patch_feat_dim = patch_feat_dim
179
+
180
+ # Shared patch encoder
181
+ self.patch_encoder = PatchEncoder(patch_feat_dim)
182
+
183
+ # Project patch features + occupancy + position β†’ embed_dim
184
+ patch_in = patch_feat_dim + 1 + 3 # feat + occ + 3D pos
185
+ self.patch_proj = nn.Sequential(
186
+ nn.Linear(patch_in, embed_dim), nn.GELU(),
187
+ nn.Linear(embed_dim, embed_dim))
188
+
189
+ # Learnable 3D positional embedding for macro grid
190
+ self.pos_embed = nn.Parameter(torch.randn(1, MACRO_N, embed_dim) * 0.02)
191
+
192
+ # Cross-attention layers
193
+ self.layers = nn.ModuleList([
194
+ CrossAttentionBlock(embed_dim, n_heads, ff_mult=2, dropout=dropout)
195
+ for _ in range(n_layers)
196
+ ])
197
+
198
+ # Final norm before pooling
199
+ self.final_ln = nn.LayerNorm(embed_dim)
200
+
201
+ # Global features: occupancy stats from full grid
202
+ n_global = 11 # same as VAEShapeClassifier handcrafted
203
+ self.global_proj = nn.Sequential(
204
+ nn.Linear(n_global, 64), nn.GELU(),
205
+ nn.Linear(64, 64))
206
+
207
+ # Classification
208
+ class_in = embed_dim + 64 # pooled attention + global features
209
+ self.class_in = class_in
210
+ self.classifier = nn.Sequential(
211
+ nn.Linear(class_in, 256), nn.GELU(), nn.Dropout(0.1),
212
+ nn.Linear(256, 128), nn.GELU(),
213
+ nn.Linear(128, n_classes))
214
+
215
+ # Auxiliary heads
216
+ self.dim_head = nn.Sequential(
217
+ nn.Linear(class_in, 64), nn.GELU(), nn.Linear(64, 4))
218
+ self.curved_head = nn.Sequential(
219
+ nn.Linear(class_in, 64), nn.GELU(), nn.Linear(64, 1))
220
+ self.curv_type_head = nn.Sequential(
221
+ nn.Linear(class_in, 64), nn.GELU(), nn.Linear(64, NUM_CURVATURES))
222
+
223
+ # Precompute macro grid positions (normalized)
224
+ coords = torch.stack(torch.meshgrid(
225
+ torch.arange(MACRO_Z, dtype=torch.float32) / max(MACRO_Z - 1, 1),
226
+ torch.arange(MACRO_Y, dtype=torch.float32) / max(MACRO_Y - 1, 1),
227
+ torch.arange(MACRO_X, dtype=torch.float32) / max(MACRO_X - 1, 1),
228
+ indexing="ij"), dim=-1)
229
+ self.register_buffer("macro_pos", coords.reshape(1, MACRO_N, 3))
230
+
231
+ def _decompose_patches(self, grid):
232
+ """
233
+ (B, 8, 16, 16) β†’ (B*64, 2, 4, 4)
234
+
235
+ Reshape into (B, 4, 2, 4, 4, 4, 4) then permute/flatten.
236
+ Z: 8 = 4 macro Γ— 2 local
237
+ Y: 16 = 4 macro Γ— 4 local
238
+ X: 16 = 4 macro Γ— 4 local
239
+ """
240
+ B = grid.shape[0]
241
+ # (B, 8, 16, 16) β†’ (B, MZ, PZ, MY, PY, MX, PX)
242
+ x = grid.reshape(B, MACRO_Z, PATCH_Z, MACRO_Y, PATCH_Y, MACRO_X, PATCH_X)
243
+ # β†’ (B, MZ, MY, MX, PZ, PY, PX)
244
+ x = x.permute(0, 1, 3, 5, 2, 4, 6).contiguous()
245
+ # β†’ (B*64, 2, 4, 4)
246
+ return x.reshape(B * MACRO_N, PATCH_Z, PATCH_Y, PATCH_X)
247
+
248
+ def _global_features(self, grid):
249
+ """Extract global geometric statistics from (B, 8, 16, 16) grid."""
250
+ B = grid.shape[0]
251
+ flat = grid.reshape(B, -1)
252
+
253
+ occ = flat.mean(dim=-1, keepdim=True)
254
+
255
+ ax_z = grid.mean(dim=(2, 3)).std(dim=1, keepdim=True)
256
+ ax_y = grid.mean(dim=(1, 3)).std(dim=1, keepdim=True)
257
+ ax_x = grid.mean(dim=(1, 2)).std(dim=1, keepdim=True)
258
+
259
+ # Surface ratio
260
+ padded = F.pad(grid.unsqueeze(1), (1,1,1,1,1,1), mode='constant', value=0)
261
+ neighbors = F.avg_pool3d(padded, kernel_size=3, stride=1, padding=0)
262
+ neighbors = neighbors.squeeze(1)
263
+ surface = ((neighbors < 1.0) & (grid > 0.5)).float().sum(dim=(1,2,3))
264
+ total = flat.sum(dim=-1).clamp(min=1)
265
+ surf_ratio = (surface / total).unsqueeze(-1)
266
+
267
+ # Axis projection symmetry
268
+ proj_z = grid.max(dim=1).values
269
+ proj_y = grid.max(dim=2).values
270
+ proj_x = grid.max(dim=3).values
271
+
272
+ sym_z = 1.0 - (proj_z - torch.flip(proj_z, [1, 2])).abs().mean(dim=(1, 2))
273
+ sym_y = 1.0 - (proj_y - torch.flip(proj_y, [1, 2])).abs().mean(dim=(1, 2))
274
+ sym_x = 1.0 - (proj_x - torch.flip(proj_x, [1, 2])).abs().mean(dim=(1, 2))
275
+ sym = torch.stack([sym_z, sym_y, sym_x], dim=-1)
276
+
277
+ # Spatial extent
278
+ z_extent = (grid.sum(dim=(2, 3)) > 0).float().sum(dim=1, keepdim=True) / GZ
279
+ y_extent = (grid.sum(dim=(1, 3)) > 0).float().sum(dim=1, keepdim=True) / GY
280
+ x_extent = (grid.sum(dim=(1, 2)) > 0).float().sum(dim=1, keepdim=True) / GX
281
+ extent = torch.cat([z_extent, y_extent, x_extent], dim=-1)
282
+
283
+ return torch.cat([occ, ax_z, ax_y, ax_x, surf_ratio, sym, extent], dim=-1)
284
+
285
+ def forward(self, grid, labels=None):
286
+ """
287
+ grid: (B, 8, 16, 16) binary voxel grid
288
+ """
289
+ B = grid.shape[0]
290
+
291
+ # === Global features ===
292
+ global_feat = self.global_proj(self._global_features(grid))
293
+
294
+ # === Patch decomposition + encoding ===
295
+ patches = self._decompose_patches(grid) # (B*64, 2, 4, 4)
296
+ patch_feats = self.patch_encoder(patches) # (B*64, patch_feat_dim)
297
+ patch_feats = patch_feats.reshape(B, MACRO_N, self.patch_feat_dim)
298
+
299
+ # Per-patch occupancy
300
+ patch_occ = patches.reshape(B, MACRO_N, PATCH_VOL).mean(dim=-1, keepdim=True)
301
+
302
+ # Combine: features + occupancy + position
303
+ pos = self.macro_pos.expand(B, -1, -1)
304
+ patch_input = torch.cat([patch_feats, patch_occ, pos], dim=-1)
305
+ x = self.patch_proj(patch_input)
306
+
307
+ # Add learnable positional embedding
308
+ x = x + self.pos_embed
309
+
310
+ # === Cross-attention layers ===
311
+ for layer in self.layers:
312
+ x = layer(x)
313
+
314
+ x = self.final_ln(x)
315
+
316
+ # === Pool: mean over patches ===
317
+ pooled = x.mean(dim=1) # (B, embed_dim)
318
+
319
+ # === Combine with global features ===
320
+ feat = torch.cat([pooled, global_feat], dim=-1) # (B, class_in)
321
+
322
+ # === Classification ===
323
+ class_logits = self.classifier(feat)
324
+ dim_logits = self.dim_head(feat)
325
+ is_curved = self.curved_head(feat)
326
+ curv_logits = self.curv_type_head(feat)
327
+
328
+ return {
329
+ "class_logits": class_logits,
330
+ "dim_logits": dim_logits,
331
+ "is_curved_pred": is_curved,
332
+ "curv_type_logits": curv_logits,
333
+ "features": feat,
334
+ }
335
+
336
+
337
+ # === Confidence ===============================================================
338
+
339
+ def compute_confidence(logits):
340
+ probs = F.softmax(logits, dim=-1)
341
+ max_prob, _ = probs.max(dim=-1)
342
+ top2 = probs.topk(2, dim=-1).values
343
+ margin = top2[:, 0] - top2[:, 1]
344
+ log_probs = F.log_softmax(logits, dim=-1)
345
+ entropy = -(probs * log_probs).sum(dim=-1)
346
+ max_entropy = math.log(logits.shape[-1])
347
+ return {"max_prob": max_prob, "margin": margin,
348
+ "entropy": entropy / max_entropy, "confidence": margin}
349
+
350
+
351
+ # === Sanity check =============================================================
352
+ if __name__ == "__main__":
353
+ _m = PatchCrossAttentionClassifier()
354
+ _n = sum(p.numel() for p in _m.parameters())
355
+ print(f'PatchCrossAttentionClassifier: {_n:,} params')
356
+ print(f' Patches: {MACRO_Z}Γ—{MACRO_Y}Γ—{MACRO_X} = {MACRO_N} patches of {PATCH_Z}Γ—{PATCH_Y}Γ—{PATCH_X}')
357
+ _dummy = torch.zeros(2, GZ, GY, GX)
358
+ with torch.no_grad():
359
+ _out = _m(_dummy)
360
+ print(f' class_logits: {_out["class_logits"].shape}')
361
+ print(f' features: {_out["features"].shape}')
362
+ print(f' class_in: {_m.class_in}')
363
+ del _m, _dummy, _out