Image Classification
PyTorch
few-shot-learning
parameter-efficient
File size: 22,750 Bytes
6edcaab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
"""
ALPINE: Adaptive Localization for Parameter- and Sample-Efficient Few-Shot Learning
Official Model Architecture & Checkpoint Loader

This module defines:
  - Canonical EXP-F3 (22,249 parameters): ALPINE_CIFAR, ALPINE_Native
  - Optional Variant EXP-F3-35k (34,917 parameters): ALPINE_35k_CIFAR, ALPINE_35k_Native
  - Gabor edge-energy guided windowed patch locator
  - Convenient `load_alpine_model` checkpoint loader
"""

import math
import os
import torch
import torch.nn as nn
import torch.nn.functional as F

try:
    from .irfe_p1_canonical import (
        GaborPreprocess,
        PatchEncoderCIFARP1,
        SubPatchEncoderCIFARP1,
        BoundaryEncoderCIFARP1,
        PatchEncoderNativeP1,
        SubPatchEncoderNativeP1,
        BoundaryEncoderNativeP1
    )
except ImportError:
    from irfe_p1_canonical import (
        GaborPreprocess,
        PatchEncoderCIFARP1,
        SubPatchEncoderCIFARP1,
        BoundaryEncoderCIFARP1,
        PatchEncoderNativeP1,
        SubPatchEncoderNativeP1,
        BoundaryEncoderNativeP1
    )


def get_exp_p1_base_centers():
    """Returns canonical base 5-patch center coordinates in normalized [-1, 1] range."""
    return torch.tensor([
        [-0.5161, -0.5161],
        [-0.5161,  0.5161],
        [ 0.0000,  0.0000],
        [ 0.5161, -0.5161],
        [ 0.5161,  0.5161]
    ], dtype=torch.float32)


class WideWindowAdaptivePatchLocator(nn.Module):
    """
    Windowed Adaptive Patch Locator (EXP-F3).
    Dynamically displaces patch sampling centers toward salient features
    within a Gaussian spatial window around canonical base centers,
    guided by Gabor edge-energy response E(y, x).
    """
    def __init__(self, base_centers, window_frac=0.50, temperature=1.0):
        super().__init__()
        self.register_buffer("base_centers", base_centers)
        self.num_patches = base_centers.shape[0]
        self.window_frac = window_frac
        self.temperature = nn.Parameter(torch.tensor(temperature, dtype=torch.float32))

    def forward(self, energy_map):
        B, _, H, W = energy_map.shape
        ys = torch.linspace(-1, 1, H, device=energy_map.device)
        xs = torch.linspace(-1, 1, W, device=energy_map.device)
        gy, gx = torch.meshgrid(ys, xs, indexing='ij')

        flat_energy = energy_map.squeeze(1)

        centers = []
        for k in range(self.num_patches):
            cy0 = self.base_centers[k, 0]
            cx0 = self.base_centers[k, 1]
            
            dist_sq = (gy - cy0)**2 + (gx - cx0)**2
            log_window = -dist_sq / (2 * (self.window_frac**2) + 1e-6)
            
            weighted_energy = flat_energy / (self.temperature.abs() + 1e-4) + log_window
            w = F.softmax(weighted_energy.view(B, -1), dim=-1)
            cy = (w * gy.reshape(-1)).sum(-1)
            cx = (w * gx.reshape(-1)).sum(-1)
            centers.append(torch.stack([cx, cy], dim=-1))
        return torch.stack(centers, dim=1)  # Shape: (B, 5, 2)


def extract_patches_grid_sample(x, centers, patch_scale=0.5):
    """Bilinearly extracts image patches around adaptive centers using grid_sample."""
    B, C, H, W = x.shape
    patch_h = int(round(H * patch_scale))
    patch_w = int(round(W * patch_scale))

    patches = []
    for k in range(centers.size(1)):
        cx = centers[:, k, 0]
        cy = centers[:, k, 1]
        
        theta = torch.zeros(B, 2, 3, device=x.device, dtype=x.dtype)
        theta[:, 0, 0] = patch_scale
        theta[:, 1, 1] = patch_scale
        theta[:, 0, 2] = cx
        theta[:, 1, 2] = cy

        grid = F.affine_grid(theta, torch.Size([B, C, patch_h, patch_w]), align_corners=False)
        p = F.grid_sample(x, grid, align_corners=False, mode='bilinear', padding_mode='reflection')
        patches.append(p)
    return patches


# =====================================================================
# CANONICAL EXP-F3 (22,249 PARAMETERS)
# =====================================================================

class ALPINE_CIFAR(nn.Module):
    """
    Canonical ALPINE / EXP-F3 architecture for CIFAR-FS (32x32).
    Total Trainable Parameters: 22,249.
    """
    def __init__(self, window_frac=0.50, embed_dim=16, num_heads=4):
        super().__init__()
        self.embed_dim        = embed_dim
        base_centers          = get_exp_p1_base_centers()
        self.locator          = WideWindowAdaptivePatchLocator(base_centers, window_frac=window_frac)
        self.encoder          = PatchEncoderCIFARP1(out_dim=embed_dim)
        self.sub_encoder      = SubPatchEncoderCIFARP1(out_dim=embed_dim)
        self.boundary_encoder = BoundaryEncoderCIFARP1(out_dim=embed_dim)
        self.sub_fusion       = nn.Sequential(
            nn.Linear(embed_dim * 4, embed_dim), nn.LayerNorm(embed_dim), nn.ReLU()
        )
        self.rel_proj = nn.Sequential(
            nn.Linear(embed_dim * 2, embed_dim), nn.LayerNorm(embed_dim), nn.ReLU()
        )
        self.mha          = nn.MultiheadAttention(embed_dim, num_heads, batch_first=True)
        self.ln_attn      = nn.LayerNorm(embed_dim)
        self.ws_query     = nn.Parameter(torch.randn(1, 1, embed_dim) * 0.02)
        self.gate_net     = nn.Sequential(
            nn.Linear(embed_dim * 2, 16), nn.ReLU(), nn.Linear(16, embed_dim * 2)
        )

    def _split_boundaries(self, x):
        return (x[:,:, 8:16, 8:16], x[:,:, 8:16, 16:24],
                x[:,:, 16:24, 8:16], x[:,:, 16:24, 16:24])

    def _encode_patch(self, p):
        v_c = self.encoder(p)
        sp = [p[:,:, r:r+8, c:c+8] for r in [0, 8] for c in [0, 8]]
        v_f = self.sub_fusion(torch.cat([self.sub_encoder(s) for s in sp], dim=1))
        return v_c + v_f

    def _rel(self, va, vb):
        return self.rel_proj(torch.cat([va - vb, va * vb], dim=1))

    def extract_with_rel_tokens(self, x):
        B = x.size(0)
        gabor_out = self.encoder.gabor(x)
        energy_map = gabor_out[:, 3:7].abs().sum(dim=1, keepdim=True)
        centers    = self.locator(energy_map)

        raw_patches = extract_patches_grid_sample(x, centers, patch_scale=0.5)
        patches     = [self._encode_patch(p) for p in raw_patches]
        edges       = [self._rel(patches[i], patches[j]) for i in range(5) for j in range(i+1, 5)]
        boundaries  = [self.boundary_encoder(b) for b in self._split_boundaries(x)]
        
        tokens  = torch.stack(patches + edges + boundaries, dim=1)
        attn, _ = self.mha(tokens, tokens, tokens)
        refined = self.ln_attn(tokens + attn)
        ws      = self.ws_query.expand(B, -1, -1)
        scores  = torch.bmm(ws, refined.transpose(1, 2)) / math.sqrt(self.embed_dim)
        W       = torch.bmm(F.softmax(scores, dim=-1), refined).squeeze(1)
        
        patch_pool = refined[:, :5, :].mean(dim=1)
        g       = torch.cat([patch_pool, W], dim=1)
        gate    = 2.0 * torch.sigmoid(self.gate_net(g)) - 1.0
        out_feat= g + g * gate

        rel_tokens = torch.stack(edges, dim=1)
        return out_feat, centers, rel_tokens

    def extract(self, x):
        """Extracts fixed-dimensional feature representations for few-shot metric classification."""
        feat, _, _ = self.extract_with_rel_tokens(x)
        return feat

    def compute_prototypes(self, sx, sy, n=5):
        """Computes support prototypes for n-way classification."""
        f = self.extract(sx)
        return torch.stack([f[sy == c].mean(0) for c in range(n)])

    def predict_proto(self, qx, protos):
        """Computes negative squared Euclidean distance between query representations and prototypes."""
        return -(torch.cdist(self.extract(qx), protos) ** 2)


class ALPINE_Native(nn.Module):
    """
    Canonical ALPINE / EXP-F3 architecture for MiniImageNet Native (84x84).
    Total Trainable Parameters: 22,249.
    """
    def __init__(self, window_frac=0.50, embed_dim=16, num_heads=4):
        super().__init__()
        self.embed_dim        = embed_dim
        base_centers          = get_exp_p1_base_centers()
        self.locator          = WideWindowAdaptivePatchLocator(base_centers, window_frac=window_frac)
        self.encoder          = PatchEncoderNativeP1(out_dim=embed_dim)
        self.sub_encoder      = SubPatchEncoderNativeP1(out_dim=embed_dim)
        self.boundary_encoder = BoundaryEncoderNativeP1(out_dim=embed_dim)
        self.sub_fusion       = nn.Sequential(
            nn.Linear(embed_dim * 4, embed_dim), nn.LayerNorm(embed_dim), nn.ReLU()
        )
        self.rel_proj = nn.Sequential(
            nn.Linear(embed_dim * 2, embed_dim), nn.LayerNorm(embed_dim), nn.ReLU()
        )
        self.mha          = nn.MultiheadAttention(embed_dim, num_heads, batch_first=True)
        self.ln_attn      = nn.LayerNorm(embed_dim)
        self.ws_query     = nn.Parameter(torch.randn(1, 1, embed_dim) * 0.02)
        self.gate_net     = nn.Sequential(
            nn.Linear(embed_dim * 2, 16), nn.ReLU(), nn.Linear(16, embed_dim * 2)
        )

    def _split_boundaries(self, x):
        return (x[:,:, 18:48, 18:48], x[:,:, 18:48, 36:66],
                x[:,:, 36:66, 18:48], x[:,:, 36:66, 36:66])

    def _encode_patch(self, p):
        v_c = self.encoder(p)
        sp = [p[:,:, r:r+24, c:c+24] for r in [0, 24] for c in [0, 24]]
        v_f = self.sub_fusion(torch.cat([self.sub_encoder(s) for s in sp], dim=1))
        return v_c + v_f

    def _rel(self, va, vb):
        return self.rel_proj(torch.cat([va - vb, va * vb], dim=1))

    def extract_with_rel_tokens(self, x):
        B = x.size(0)
        gabor_out = self.encoder.gabor(x)
        energy_map = gabor_out[:, 3:7].abs().sum(dim=1, keepdim=True)
        centers    = self.locator(energy_map)

        raw_patches = extract_patches_grid_sample(x, centers, patch_scale=48.0/84.0)
        patches     = [self._encode_patch(p) for p in raw_patches]
        edges       = [self._rel(patches[i], patches[j]) for i in range(5) for j in range(i+1, 5)]
        boundaries  = [self.boundary_encoder(b) for b in self._split_boundaries(x)]
        
        tokens  = torch.stack(patches + edges + boundaries, dim=1)
        attn, _ = self.mha(tokens, tokens, tokens)
        refined = self.ln_attn(tokens + attn)
        ws      = self.ws_query.expand(B, -1, -1)
        scores  = torch.bmm(ws, refined.transpose(1, 2)) / math.sqrt(self.embed_dim)
        W       = torch.bmm(F.softmax(scores, dim=-1), refined).squeeze(1)
        
        patch_pool = refined[:, :5, :].mean(dim=1)
        g       = torch.cat([patch_pool, W], dim=1)
        gate    = 2.0 * torch.sigmoid(self.gate_net(g)) - 1.0
        out_feat= g + g * gate

        rel_tokens = torch.stack(edges, dim=1)
        return out_feat, centers, rel_tokens

    def extract(self, x):
        feat, _, _ = self.extract_with_rel_tokens(x)
        return feat

    def compute_prototypes(self, sx, sy, n=5):
        f = self.extract(sx)
        return torch.stack([f[sy == c].mean(0) for c in range(n)])

    def predict_proto(self, qx, protos):
        return -(torch.cdist(self.extract(qx), protos) ** 2)


# Aliases for backward compatibility
IRFEExpF3_CIFAR = ALPINE_CIFAR
IRFEExpF3_Native = ALPINE_Native


# =====================================================================
# OPTIONAL VARIANT EXP-F3-35k (34,917 PARAMETERS)
# =====================================================================

class PatchEncoderCIFARGeneric(nn.Module):
    def __init__(self, c1, c2, out_dim):
        super().__init__()
        self.gabor = GaborPreprocess(ksize=5)
        self.conv1 = nn.Conv2d(7, c1, 3, padding=1)
        self.conv2 = nn.Conv2d(c1, c2, 3, padding=1)
        self.pool  = nn.MaxPool2d(2, 2)
        self.fc    = nn.Linear(c2 * 4 * 4, out_dim)
        self.ln    = nn.LayerNorm(out_dim)

    def forward(self, x):
        x = self.gabor(x)
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        return self.ln(self.fc(x.view(x.size(0), -1)))


class SubPatchEncoderCIFARGeneric(nn.Module):
    def __init__(self, sub_c, out_dim):
        super().__init__()
        self.gabor = GaborPreprocess(ksize=5)
        self.conv  = nn.Conv2d(7, sub_c, 3, padding=1)
        self.pool  = nn.AdaptiveAvgPool2d((4, 4))
        self.fc    = nn.Linear(sub_c * 4 * 4, out_dim)

    def forward(self, x):
        x = self.gabor(x)
        return F.relu(self.fc(self.pool(F.relu(self.conv(x))).view(x.size(0), -1)))


class BoundaryEncoderCIFARGeneric(nn.Module):
    def __init__(self, sub_c, out_dim):
        super().__init__()
        self.gabor = GaborPreprocess(ksize=5)
        self.conv  = nn.Conv2d(7, sub_c, 3, padding=1)
        self.pool  = nn.AdaptiveAvgPool2d((4, 4))
        self.fc    = nn.Linear(sub_c * 4 * 4, out_dim)

    def forward(self, x):
        x = self.gabor(x)
        return F.relu(self.fc(self.pool(F.relu(self.conv(x))).view(x.size(0), -1)))


class PatchEncoderNativeGeneric(nn.Module):
    def __init__(self, c1, c2, out_dim):
        super().__init__()
        self.gabor = GaborPreprocess(ksize=5)
        self.conv1 = nn.Conv2d(7, c1, 3, padding=1)
        self.conv2 = nn.Conv2d(c1, c2, 3, padding=1)
        self.pool  = nn.MaxPool2d(2, 2)
        self.adap  = nn.AdaptiveAvgPool2d((4, 4))
        self.fc    = nn.Linear(c2 * 4 * 4, out_dim)
        self.ln    = nn.LayerNorm(out_dim)

    def forward(self, x):
        x = self.gabor(x)
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = self.adap(x)
        return self.ln(self.fc(x.view(x.size(0), -1)))


class SubPatchEncoderNativeGeneric(nn.Module):
    def __init__(self, sub_c, out_dim):
        super().__init__()
        self.gabor = GaborPreprocess(ksize=5)
        self.conv  = nn.Conv2d(7, sub_c, 3, padding=1)
        self.pool  = nn.AdaptiveAvgPool2d((4, 4))
        self.fc    = nn.Linear(sub_c * 4 * 4, out_dim)

    def forward(self, x):
        x = self.gabor(x)
        return F.relu(self.fc(self.pool(F.relu(self.conv(x))).view(x.size(0), -1)))


class BoundaryEncoderNativeGeneric(nn.Module):
    def __init__(self, sub_c, out_dim):
        super().__init__()
        self.gabor = GaborPreprocess(ksize=5)
        self.conv  = nn.Conv2d(7, sub_c, 3, padding=1)
        self.pool  = nn.AdaptiveAvgPool2d((4, 4))
        self.fc    = nn.Linear(sub_c * 4 * 4, out_dim)

    def forward(self, x):
        x = self.gabor(x)
        return F.relu(self.fc(self.pool(F.relu(self.conv(x))).view(x.size(0), -1)))


class ALPINE_35k_CIFAR(nn.Module):
    """
    Optional Variant: ALPINE / EXP-F3-35k for CIFAR-FS (32x32).
    Total Trainable Parameters: 34,917.
    """
    def __init__(self, c1=15, c2=19, sub_c=8, gate_h=12, embed_dim=32, window_frac=0.50, num_heads=4):
        super().__init__()
        self.embed_dim        = embed_dim
        base_centers          = get_exp_p1_base_centers()
        self.locator          = WideWindowAdaptivePatchLocator(base_centers, window_frac=window_frac)
        self.encoder          = PatchEncoderCIFARGeneric(c1, c2, out_dim=embed_dim)
        self.sub_encoder      = SubPatchEncoderCIFARGeneric(sub_c, out_dim=embed_dim)
        self.boundary_encoder = BoundaryEncoderCIFARGeneric(sub_c, out_dim=embed_dim)
        self.sub_fusion       = nn.Sequential(
            nn.Linear(embed_dim * 4, embed_dim), nn.LayerNorm(embed_dim), nn.ReLU()
        )
        self.rel_proj = nn.Sequential(
            nn.Linear(embed_dim * 2, embed_dim), nn.LayerNorm(embed_dim), nn.ReLU()
        )
        self.mha          = nn.MultiheadAttention(embed_dim, num_heads, batch_first=True)
        self.ln_attn      = nn.LayerNorm(embed_dim)
        self.ws_query     = nn.Parameter(torch.randn(1, 1, embed_dim) * 0.02)
        self.gate_net     = nn.Sequential(
            nn.Linear(embed_dim * 2, gate_h), nn.ReLU(), nn.Linear(gate_h, embed_dim * 2)
        )

    def _split_boundaries(self, x):
        return (x[:,:, 8:16, 8:16], x[:,:, 8:16, 16:24],
                x[:,:, 16:24, 8:16], x[:,:, 16:24, 16:24])

    def _encode_patch(self, p):
        v_c = self.encoder(p)
        sp = [p[:,:, r:r+8, c:c+8] for r in [0, 8] for c in [0, 8]]
        v_f = self.sub_fusion(torch.cat([self.sub_encoder(s) for s in sp], dim=1))
        return v_c + v_f

    def _rel(self, va, vb):
        return self.rel_proj(torch.cat([va - vb, va * vb], dim=1))

    def extract_with_rel_tokens(self, x):
        B = x.size(0)
        gabor_out = self.encoder.gabor(x)
        energy_map = gabor_out[:, 3:7].abs().sum(dim=1, keepdim=True)
        centers    = self.locator(energy_map)

        raw_patches = extract_patches_grid_sample(x, centers, patch_scale=0.5)
        patches     = [self._encode_patch(p) for p in raw_patches]
        edges       = [self._rel(patches[i], patches[j]) for i in range(5) for j in range(i+1, 5)]
        boundaries  = [self.boundary_encoder(b) for b in self._split_boundaries(x)]
        
        tokens  = torch.stack(patches + edges + boundaries, dim=1)
        attn, _ = self.mha(tokens, tokens, tokens)
        refined = self.ln_attn(tokens + attn)
        ws      = self.ws_query.expand(B, -1, -1)
        scores  = torch.bmm(ws, refined.transpose(1, 2)) / math.sqrt(self.embed_dim)
        W       = torch.bmm(F.softmax(scores, dim=-1), refined).squeeze(1)
        
        patch_pool = refined[:, :5, :].mean(dim=1)
        g       = torch.cat([patch_pool, W], dim=1)
        gate    = 2.0 * torch.sigmoid(self.gate_net(g)) - 1.0
        out_feat= g + g * gate
        rel_tokens = torch.stack(edges, dim=1)
        return out_feat, centers, rel_tokens

    def extract(self, x):
        feat, _, _ = self.extract_with_rel_tokens(x)
        return feat

    def compute_prototypes(self, sx, sy, n=5):
        f = self.extract(sx)
        return torch.stack([f[sy == c].mean(0) for c in range(n)])

    def predict_proto(self, qx, protos):
        return -(torch.cdist(self.extract(qx), protos) ** 2)


class ALPINE_35k_Native(nn.Module):
    """
    Optional Variant: ALPINE / EXP-F3-35k for MiniImageNet Native (84x84).
    Total Trainable Parameters: 34,917.
    """
    def __init__(self, c1=15, c2=19, sub_c=8, gate_h=12, embed_dim=32, window_frac=0.50, num_heads=4):
        super().__init__()
        self.embed_dim        = embed_dim
        base_centers          = get_exp_p1_base_centers()
        self.locator          = WideWindowAdaptivePatchLocator(base_centers, window_frac=window_frac)
        self.encoder          = PatchEncoderNativeGeneric(c1, c2, out_dim=embed_dim)
        self.sub_encoder      = SubPatchEncoderNativeGeneric(sub_c, out_dim=embed_dim)
        self.boundary_encoder = BoundaryEncoderNativeGeneric(sub_c, out_dim=embed_dim)
        self.sub_fusion       = nn.Sequential(
            nn.Linear(embed_dim * 4, embed_dim), nn.LayerNorm(embed_dim), nn.ReLU()
        )
        self.rel_proj = nn.Sequential(
            nn.Linear(embed_dim * 2, embed_dim), nn.LayerNorm(embed_dim), nn.ReLU()
        )
        self.mha          = nn.MultiheadAttention(embed_dim, num_heads, batch_first=True)
        self.ln_attn      = nn.LayerNorm(embed_dim)
        self.ws_query     = nn.Parameter(torch.randn(1, 1, embed_dim) * 0.02)
        self.gate_net     = nn.Sequential(
            nn.Linear(embed_dim * 2, gate_h), nn.ReLU(), nn.Linear(gate_h, embed_dim * 2)
        )

    def _split_boundaries(self, x):
        return (x[:,:, 18:48, 18:48], x[:,:, 18:48, 36:66],
                x[:,:, 36:66, 18:48], x[:,:, 36:66, 36:66])

    def _encode_patch(self, p):
        v_c = self.encoder(p)
        sp = [p[:,:, r:r+24, c:c+24] for r in [0, 24] for c in [0, 24]]
        v_f = self.sub_fusion(torch.cat([self.sub_encoder(s) for s in sp], dim=1))
        return v_c + v_f

    def _rel(self, va, vb):
        return self.rel_proj(torch.cat([va - vb, va * vb], dim=1))

    def extract_with_rel_tokens(self, x):
        B = x.size(0)
        gabor_out = self.encoder.gabor(x)
        energy_map = gabor_out[:, 3:7].abs().sum(dim=1, keepdim=True)
        centers    = self.locator(energy_map)

        raw_patches = extract_patches_grid_sample(x, centers, patch_scale=48.0/84.0)
        patches     = [self._encode_patch(p) for p in raw_patches]
        edges       = [self._rel(patches[i], patches[j]) for i in range(5) for j in range(i+1, 5)]
        boundaries  = [self.boundary_encoder(b) for b in self._split_boundaries(x)]
        
        tokens  = torch.stack(patches + edges + boundaries, dim=1)
        attn, _ = self.mha(tokens, tokens, tokens)
        refined = self.ln_attn(tokens + attn)
        ws      = self.ws_query.expand(B, -1, -1)
        scores  = torch.bmm(ws, refined.transpose(1, 2)) / math.sqrt(self.embed_dim)
        W       = torch.bmm(F.softmax(scores, dim=-1), refined).squeeze(1)
        
        patch_pool = refined[:, :5, :].mean(dim=1)
        g       = torch.cat([patch_pool, W], dim=1)
        gate    = 2.0 * torch.sigmoid(self.gate_net(g)) - 1.0
        out_feat= g + g * gate
        rel_tokens = torch.stack(edges, dim=1)
        return out_feat, centers, rel_tokens

    def extract(self, x):
        feat, _, _ = self.extract_with_rel_tokens(x)
        return feat

    def compute_prototypes(self, sx, sy, n=5):
        f = self.extract(sx)
        return torch.stack([f[sy == c].mean(0) for c in range(n)])

    def predict_proto(self, qx, protos):
        return -(torch.cdist(self.extract(qx), protos) ** 2)


# Aliases for 35k variant
IRFEExpF3_35k_CIFAR = ALPINE_35k_CIFAR
IRFEExpF3_35k_Native = ALPINE_35k_Native


def load_alpine_model(checkpoint_path, model_type="canonical", dataset="cifar", device="cpu"):
    """
    Convenience loader for ALPINE model checkpoints.
    
    Args:
        checkpoint_path (str): Path to .pt checkpoint file.
        model_type (str): 'canonical' (22,249 params) or 'variant-35k' (34,917 params).
        dataset (str): 'cifar' (32x32 images) or 'mini' (84x84 images).
        device (str or torch.device): Device to load model onto.
        
    Returns:
        nn.Module: Loaded ALPINE model ready in eval mode.
    """
    device = torch.device(device)
    model_type = model_type.lower()
    dataset = dataset.lower()

    if "35k" in model_type:
        if dataset in ["cifar", "cifar-fs", "cifar_fs"]:
            model = ALPINE_35k_CIFAR()
        else:
            model = ALPINE_35k_Native()
    else:
        if dataset in ["cifar", "cifar-fs", "cifar_fs"]:
            model = ALPINE_CIFAR()
        else:
            model = ALPINE_Native()

    checkpoint = torch.load(checkpoint_path, map_location=device, weights_only=False)
    state_dict = checkpoint["model_state_dict"] if isinstance(checkpoint, dict) and "model_state_dict" in checkpoint else checkpoint
    model.load_state_dict(state_dict)
    model.to(device)
    model.eval()
    return model