File size: 10,298 Bytes
dadf189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Centralized configuration for the fingerprint graph model.

All model, backbone, training, data, loss, and inference settings are defined
here so that experiments can be reproduced by swapping a single config object.
"""

from dataclasses import dataclass, field
from typing import Literal


# ─────────────────────────────────────────────  Graph  ──────
@dataclass
class GraphConfig:
    """Dynamic k-NN graph construction."""
    k: int = 10
    dynamic_graph: bool = True
    distance_metric: Literal["euclidean", "cosine"] = "euclidean"


# ─────────────────────────────────────────────  RPE  ────────
@dataclass
class RelationalPEConfig:
    """Pairwise relational PE: (dx, dy, d, cos a, sin a, cos dtheta, sin dtheta)."""
    input_dim: int = 7
    hidden_dim: int = 64
    output_dim: int = 64
    num_layers: int = 2
    activation: str = "gelu"


# ─────────────────────────────────────────────  Attention  ──
@dataclass
class AttentionConfig:
    """Local multi-head attention on k-NN graph."""
    num_heads: int = 4
    head_dim: int = 64
    dropout: float = 0.1


# ─────────────────────────────────────────────  Pooling  ────
@dataclass
class PoolingConfig:
    """Global pooling over variable-length minutiae sets."""
    method: Literal["meanmax", "attentive", "multihead"] = "attentive"
    num_heads: int = 4
    hidden_dim: int = 256


# ─────────────────────────────────────────────  Backbone  ───
@dataclass
class BackboneConfig:
    """FLaRE CNN backbone settings."""
    num_in: int = 1                             # grayscale
    extract_layer: str = "layer2"               # 128D, H/4
    image_size: tuple[int, int] = (256, 256)    # (H, W)


# ─────────────────────────────────────────────  Sampler  ────
@dataclass
class SamplerConfig:
    """Bilinear feature sampling at minutiae locations."""
    append_geometry: bool = True                # concat cos theta, sin theta


# ─────────────────────────────────────────────  Loss  ───────
@dataclass
class ArcFaceConfig:
    """ArcFace (additive angular margin) loss."""
    scale: float = 32.0
    margin: float = 0.50
    easy_margin: bool = False


@dataclass
class TripletConfig:
    """Triplet loss with hard mining."""
    margin: float = 0.3
    mining: Literal["hard", "semihard", "all"] = "semihard"


@dataclass
class LossConfig:
    """Combined loss wrapper."""
    arcface: ArcFaceConfig = field(default_factory=ArcFaceConfig)
    triplet: TripletConfig = field(default_factory=TripletConfig)
    arcface_weight: float = 1.0
    triplet_weight: float = 1.0


# ─────────────────────────────────────────────  Data  ───────
@dataclass
class AugmentConfig:
    """Joint augmentation for image + minutiae."""
    rotate: bool = True
    rotate_range: float = 180.0
    translate: bool = True
    translate_range: float = 10.0
    jitter_std: float = 2.0
    minutia_dropout: float = 0.15
    min_keep: int = 5
    spurious_rate: float = 0.08


@dataclass
class DataConfig:
    """Dataset & dataloader parameters."""
    image_dir: str = "data/images"
    image_size: tuple[int, int] = (256, 256)
    num_workers: int = 4
    pin_memory: bool = True
    augment: AugmentConfig = field(default_factory=AugmentConfig)


# ─────────────────────────────────────────────  Train  ──────
@dataclass
class SchedulerConfig:
    """Warmup + cosine annealing schedule."""
    warmup_epochs: int = 5
    min_lr: float = 1e-6


@dataclass
class TrainConfig:
    """Training hyper-parameters."""
    epochs: int = 100
    batch_size: int = 32
    lr: float = 3e-4
    weight_decay: float = 1e-4
    optimizer: Literal["adamw", "sgd"] = "adamw"
    grad_clip: float = 1.0
    scheduler: SchedulerConfig = field(default_factory=SchedulerConfig)
    mixed_precision: bool = False
    seed: int = 42
    save_dir: str = "checkpoints"
    log_every: int = 50
    eval_every: int = 1


# ─────────────────────────────  Master Config  ─────────────
@dataclass
class Config:
    """Root configuration β€” single import gives access to everything."""
    backbone: BackboneConfig = field(default_factory=BackboneConfig)
    sampler: SamplerConfig = field(default_factory=SamplerConfig)
    graph: GraphConfig = field(default_factory=GraphConfig)
    rpe: RelationalPEConfig = field(default_factory=RelationalPEConfig)
    attention: AttentionConfig = field(default_factory=AttentionConfig)
    pooling: PoolingConfig = field(default_factory=PoolingConfig)
    embed_dim: int = 256
    num_layers: int = 6
    output_dim: int = 192
    train: TrainConfig = field(default_factory=TrainConfig)
    loss: LossConfig = field(default_factory=LossConfig)
    data: DataConfig = field(default_factory=DataConfig)


def get_default_config() -> Config:
    """Return a fresh default configuration."""
    return Config()


# ═══════════════════════════════════════════════════════════════
#  ViT-Graph (Option C) configuration
# ═══════════════════════════════════════════════════════════════

@dataclass
class ViTConfig:
    """Pretrained ViT backbone settings.

    Default: DINOv2 ViT-B/14 (768-D embeddings).
    With image_size=224 and patch_size=14 β†’ 16Γ—16 = 256 patch tokens.
    """
    model_name: str = "vit_base_patch14_dinov2.lvd142m"
    pretrained: bool = True
    freeze: bool = True
    image_size: int = 224


@dataclass
class TRAMConfig:
    """TRAM multilayer centrality token selection.

    K tokens are selected from the ViT patch grid based on attention
    centrality β€” analogous to 30-80 minutiae on a fingerprint.
    """
    num_tokens: int = 30
    power_iterations: int = 10
    layer_weights: Literal["uniform", "last_heavy", "exponential"] = "uniform"


@dataclass
class GridRPEConfig:
    """Grid-position relational PE (5-dim: Ξ”row, Ξ”col, dist, cos Ξ±, sin Ξ±)."""
    input_dim: int = 5
    hidden_dim: int = 64
    output_dim: int = 64
    num_layers: int = 2
    activation: str = "gelu"


@dataclass
class ViTGraphConfig:
    """Root configuration for the ViT-Graph model.

    Separate from Config (MDGT) β€” these two models can coexist.
    Reuses GraphConfig, AttentionConfig, PoolingConfig, TrainConfig,
    LossConfig, DataConfig from MDGT where applicable.
    """
    vit: ViTConfig = field(default_factory=ViTConfig)
    tram: TRAMConfig = field(default_factory=TRAMConfig)
    grid_rpe: GridRPEConfig = field(default_factory=GridRPEConfig)
    graph: GraphConfig = field(default_factory=lambda: GraphConfig(k=9))
    attention: AttentionConfig = field(default_factory=AttentionConfig)
    pooling: PoolingConfig = field(default_factory=PoolingConfig)
    embed_dim: int = 256
    num_layers: int = 3          # fewer than MDGT (ViT features are rich)
    output_dim: int = 192
    train: TrainConfig = field(default_factory=TrainConfig)
    loss: LossConfig = field(default_factory=LossConfig)
    data: DataConfig = field(default_factory=DataConfig)


def get_vit_graph_config() -> ViTGraphConfig:
    """Return a fresh ViT-Graph default configuration."""
    return ViTGraphConfig()


# ═══════════════════════════════════════════════════════════════
#  MDGT v2 (ViT from scratch + TRAM + GNN) β€” docx plan
# ═══════════════════════════════════════════════════════════════

@dataclass
class V2TrainConfig:
    """Two-phase training configuration for MDGT v2.

    Phase 1: Freeze ViT backbone, train GNN + pooling + heads.
    Phase 2: Unfreeze ViT with smaller LR, train end-to-end.
    """
    # Phase 1 β€” frozen ViT
    phase1_epochs: int = 50
    phase1_lr_gnn: float = 1e-3
    phase1_batch_size: int = 64
    # Phase 2 β€” end-to-end
    phase2_epochs: int = 150
    phase2_lr_vit: float = 1e-5
    phase2_lr_gnn: float = 1e-4
    phase2_batch_size: int = 32
    # Shared
    weight_decay: float = 0.05
    warmup_epochs: int = 5
    grad_clip: float = 1.0
    seed: int = 42
    save_dir: str = "checkpoints_v2"
    log_every: int = 50
    eval_every: int = 1
    num_workers: int = 4
    pin_memory: bool = True


@dataclass
class V2Config:
    """Root configuration for MDGT v2 pipeline.

    Matches the docx plan: ViT-Tiny + TRAM + 2-layer GAT + multi-head pool.
    """
    vit_variant: Literal["tiny", "small", "base"] = "tiny"
    image_size: int = 224
    tram_k: int = 30
    gnn_layers: int = 2
    gnn_dim: int = 0        # 0 = auto (192 for tiny, 256 for base)
    gnn_heads: int = 4
    gnn_k: int = 5
    pool_heads: int = 4
    output_dim: int = 256
    drop_rate: float = 0.0
    drop_path_rate: float = 0.1
    # Loss
    arcface_scale: float = 30.0
    arcface_margin: float = 0.50
    triplet_margin: float = 0.3
    triplet_weight: float = 0.1
    cls_weight: float = 0.1
    # Training
    train: V2TrainConfig = field(default_factory=V2TrainConfig)


def get_v2_config() -> V2Config:
    """Return a fresh MDGT v2 default configuration."""
    return V2Config()