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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
import os
import glob
import json
import argparse
from typing import Dict, List, Tuple

import torch
import torch.nn as nn
import torch.nn.functional as F
from safetensors.torch import load_file
from huggingface_hub import hf_hub_download
from transformers import AutoImageProcessor, AutoModelForCausalLM, AutoTokenizer

# -----------------------------
# Utils
# -----------------------------
def load_jsonl(path: str) -> List[dict]:
    data = []
    with open(path, "r") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            data.append(json.loads(line))
    return data


def load_safetensor_from_hf(repo_id, filename, repo_type="dataset"):
    cached_path = hf_hub_download(
        repo_id=repo_id,
        filename=filename,
        repo_type=repo_type,
        local_files_only=False
    )
    return load_file(cached_path)


def to_vchw(point_map: torch.Tensor) -> torch.Tensor:
    """
    Convert point_map to (V, 3, H, W) float tensor.
    Accepts common layouts:
      (V, 3, H, W)  -> ok
      (V, H, W, 3)  -> permute
      (V, H, W, C) where C=3 -> permute
    """
    if point_map.dim() != 4:
        raise ValueError(f"Expected point_map to be 4D (V,*,*,*), got shape={tuple(point_map.shape)}")

    V, a, b, c = point_map.shape

    # (V, 3, H, W)
    if a == 3:
        out = point_map
    # (V, H, W, 3)
    elif c == 3:
        out = point_map.permute(0, 3, 1, 2).contiguous()
    else:
        raise ValueError(f"Unrecognized point_map layout: shape={tuple(point_map.shape)}")

    return out.float()


def load_pretrain(model, pretrain_ckpt_path):
    print(f"📂 Loading pretrained weights from: {str(pretrain_ckpt_path)}")
    
    # Search for safetensors files
    model_weight_path_pattern = pretrain_ckpt_path + "/model*.safetensors"
    model_weight_paths = glob.glob(model_weight_path_pattern)

    if len(model_weight_paths) == 0:
        raise FileNotFoundError(f"❌ Cannot find any .safetensors file in {str(pretrain_ckpt_path)}")

    # Load and merge weights
    weights = {}
    for model_weight_path in model_weight_paths:
        print(f"📥 Loading weights from: {model_weight_path}")
        weights.update(load_file(model_weight_path, device="cpu"))

    # Load weights with strict=False
    result = model.load_state_dict(weights, strict=False)
    
    model_keys = set(model.state_dict().keys())
    loaded_keys = model_keys.intersection(weights.keys())
    missing_keys = result.missing_keys
    unexpected_keys = result.unexpected_keys
    print(f"✅ Loaded keys:      {len(loaded_keys)} / {len(model_keys)}")
    print(f"❌ Missing keys:     {len(missing_keys)}")
    print(f"⚠️ Unexpected keys:  {len(unexpected_keys)}")

class _GlobalViewAttnBlock(nn.Module):
    """One pre-norm Transformer-style block over view tokens (B,V,D)."""
    def __init__(
        self,
        dim: int,
        num_heads: int,
        mlp_ratio: float,
        dropout: float,
        zero_init_residual: bool,
        zero_init_attn_out: bool,
    ):
        super().__init__()
        self.zero_init_residual = zero_init_residual
        self.zero_init_attn_out = zero_init_attn_out

        self.norm1 = nn.LayerNorm(dim)
        self.attn = nn.MultiheadAttention(
            embed_dim=dim,
            num_heads=num_heads,
            dropout=dropout,
            batch_first=True,
            bias=True,
        )

        self.norm2 = nn.LayerNorm(dim)
        hidden_dim = int(dim * mlp_ratio)
        self.mlp = nn.Sequential(
            nn.Linear(dim, hidden_dim),
            nn.GELU(),
            nn.Dropout(dropout),
            nn.Linear(hidden_dim, dim),
            nn.Dropout(dropout),
        )

        self._init_weights()

    def forward(self, x, key_padding_mask=None):
        h = self.norm1(x)
        attn_out, _ = self.attn(
            h, h, h,
            key_padding_mask=key_padding_mask,
            need_weights=False,
        )
        x = x + attn_out
        x = x + self.mlp(self.norm2(x))
        return x

    @torch.no_grad()
    def _init_weights(self):
        # LayerNorm
        for ln in (self.norm1, self.norm2):
            nn.init.ones_(ln.weight)
            nn.init.zeros_(ln.bias)

        # MultiheadAttention: in_proj for qkv (3D, D)
        if getattr(self.attn, "in_proj_weight", None) is not None:
            nn.init.xavier_uniform_(self.attn.in_proj_weight)
        if getattr(self.attn, "in_proj_bias", None) is not None:
            nn.init.zeros_(self.attn.in_proj_bias)

        # out proj
        nn.init.xavier_uniform_(self.attn.out_proj.weight)
        if self.attn.out_proj.bias is not None:
            nn.init.zeros_(self.attn.out_proj.bias)

        # optional: start attn residual near-zero
        if self.zero_init_attn_out:
            nn.init.zeros_(self.attn.out_proj.weight)
            if self.attn.out_proj.bias is not None:
                nn.init.zeros_(self.attn.out_proj.bias)

        # MLP
        fc1: nn.Linear = self.mlp[0]
        fc2: nn.Linear = self.mlp[3]

        nn.init.xavier_uniform_(fc1.weight)
        if fc1.bias is not None:
            nn.init.zeros_(fc1.bias)

        # zero-init last projection for stable residual start (recommended)
        if self.zero_init_residual:
            nn.init.zeros_(fc2.weight)
            if fc2.bias is not None:
                nn.init.zeros_(fc2.bias)
        else:
            nn.init.xavier_uniform_(fc2.weight)
            if fc2.bias is not None:
                nn.init.zeros_(fc2.bias)

class _GlobalViewGatedAttnBlock(nn.Module):
    """Pre-norm Transformer block over view tokens (B,V,D) with gated residuals."""
    def __init__(
        self,
        dim: int,
        num_heads: int,
        mlp_ratio: float,
        dropout: float,
        zero_init_residual: bool,
        zero_init_attn_out: bool,
        gate_bias_init: float = -2.0,   # sigmoid(-2)≈0.12, starts near-identity (small updates)
    ):
        super().__init__()
        self.zero_init_residual = zero_init_residual
        self.zero_init_attn_out = zero_init_attn_out

        self.norm1 = nn.LayerNorm(dim)
        self.attn = nn.MultiheadAttention(
            embed_dim=dim,
            num_heads=num_heads,
            dropout=dropout,
            batch_first=True,
            bias=True,
        )

        # --- Gating for attention residual ---
        # Produces per-token, per-channel gates in (0,1)
        self.attn_gate = nn.Linear(dim, dim, bias=True)

        self.norm2 = nn.LayerNorm(dim)
        hidden_dim = int(dim * mlp_ratio)
        self.mlp = nn.Sequential(
            nn.Linear(dim, hidden_dim),
            nn.GELU(),
            nn.Dropout(dropout),
            nn.Linear(hidden_dim, dim),
            nn.Dropout(dropout),
        )

        # --- Gating for MLP residual ---
        self.mlp_gate = nn.Linear(dim, dim, bias=True)

        self._init_weights(gate_bias_init=gate_bias_init)

    def forward(self, x: torch.Tensor, key_padding_mask=None) -> torch.Tensor:
        # x: (B, V, D)
        h1 = self.norm1(x)
        attn_out, _ = self.attn(
            h1, h1, h1,
            key_padding_mask=key_padding_mask,
            need_weights=False,
        )
        g_attn = torch.sigmoid(self.attn_gate(h1))          # (B, V, D)
        x = x + g_attn * attn_out

        h2 = self.norm2(x)
        mlp_out = self.mlp(h2)
        g_mlp = torch.sigmoid(self.mlp_gate(h2))            # (B, V, D)
        x = x + g_mlp * mlp_out
        return x

    @torch.no_grad()
    def _init_weights(self, gate_bias_init: float):
        # LayerNorm
        for ln in (self.norm1, self.norm2):
            nn.init.ones_(ln.weight)
            nn.init.zeros_(ln.bias)

        # MultiheadAttention: in_proj for qkv
        if getattr(self.attn, "in_proj_weight", None) is not None:
            nn.init.xavier_uniform_(self.attn.in_proj_weight)
        if getattr(self.attn, "in_proj_bias", None) is not None:
            nn.init.zeros_(self.attn.in_proj_bias)

        # out proj
        nn.init.xavier_uniform_(self.attn.out_proj.weight)
        if self.attn.out_proj.bias is not None:
            nn.init.zeros_(self.attn.out_proj.bias)

        # optional: start attn residual near-zero
        if self.zero_init_attn_out:
            nn.init.zeros_(self.attn.out_proj.weight)
            if self.attn.out_proj.bias is not None:
                nn.init.zeros_(self.attn.out_proj.bias)

        # MLP
        fc1: nn.Linear = self.mlp[0]
        fc2: nn.Linear = self.mlp[3]
        nn.init.xavier_uniform_(fc1.weight)
        if fc1.bias is not None:
            nn.init.zeros_(fc1.bias)

        if self.zero_init_residual:
            nn.init.zeros_(fc2.weight)
            if fc2.bias is not None:
                nn.init.zeros_(fc2.bias)
        else:
            nn.init.xavier_uniform_(fc2.weight)
            if fc2.bias is not None:
                nn.init.zeros_(fc2.bias)

        # Gates: start “mostly closed” so training is stable, then learn to open
        nn.init.zeros_(self.attn_gate.weight)
        nn.init.constant_(self.attn_gate.bias, gate_bias_init)

        nn.init.zeros_(self.mlp_gate.weight)
        nn.init.constant_(self.mlp_gate.bias, gate_bias_init)
                
class GlobalViewAttention(nn.Module):
    """
    Multi-layer global self-attention over multi-view tokens.

    Input:  x ∈ (B, V, D)
    Output: x' ∈ (B, V, D)
    """
    def __init__(
        self,
        dim: int,
        num_layers: int = 1,
        num_heads: int = 8,
        mlp_ratio: float = 4.0,
        dropout: float = 0.0,
        zero_init_residual: bool = True,   # recommended (stable when adding layers)
        zero_init_attn_out: bool = False,  # optional extra safety
    ):
        super().__init__()
        assert num_layers >= 1, "num_layers must be >= 1"

        self.dim = dim
        self.num_layers = num_layers
        self.num_heads = num_heads
        self.layers = nn.ModuleList([
            _GlobalViewAttnBlock(
                dim=dim,
                num_heads=num_heads,
                mlp_ratio=mlp_ratio,
                dropout=dropout,
                zero_init_residual=zero_init_residual,
                zero_init_attn_out=zero_init_attn_out,
            )
            for _ in range(num_layers)
        ])

    def forward(self, x, key_padding_mask=None):
        """
        x: (B, V, D)
        key_padding_mask: (B, V), True = ignore (padding)
        """
        for layer in self.layers:
            x = layer(x, key_padding_mask=key_padding_mask)
        return x
    
class RepModel(nn.Module):
    def __init__(self, model_root: str = "fg-clip-base"):
        super().__init__()

        self.pm_encoder = AutoModelForCausalLM.from_pretrained(f'../{model_root}', trust_remote_code=True)
        # self.global_attn = GlobalViewAttention(dim=512, num_heads=8, mlp_ratio=4.0, dropout=0.1)
        self.tokenizer = AutoTokenizer.from_pretrained(f'../{model_root}', trust_remote_code=True, use_fast=True)
        self.image_processor = AutoImageProcessor.from_pretrained(f'../{model_root}')

        # Optional: print trainable params
        try:
            self.pm_encoder.print_trainable_parameters()
        except Exception:
            pass

    @torch.no_grad()
    def encode_views(self, pm_batched):
        # Expect (1,V,3,H,W) or (V,3,H,W)
        # pm_batched = self.image_processor(images=pm_batched, return_tensors="pt").to('cuda')
        _, feats = self.pm_encoder.get_image_features(pm_batched)
        # feats = self.global_attn(feats)
        feats = torch.nn.functional.normalize(feats.float(), dim=-1)
        return feats
    
    @torch.no_grad()
    def encode_text(self, texts):
        tok = self.tokenizer(texts, padding="max_length", truncation=True, max_length=248, return_tensors="pt").to('cuda')
        feats = self.pm_encoder.get_text_features(tok["input_ids"], walk_short_pos=False)
        feats = torch.nn.functional.normalize(feats.float(), dim=-1)
        return feats


# -----------------------------
# Retrieval evaluation
# -----------------------------
@torch.no_grad()
def eval_view_retrieval(
    model: RepModel,
    items: List[dict],
    scan_root: str,
    device: str = "cuda",
    batch_views: int = 32,
    recall_ks: Tuple[int, ...] = (1, 5, 10),
) -> Dict[str, float]:
    model.eval()
    model.to(device)

    # Cache: scan_id -> (V, D) view features
    scan_cache: Dict[str, torch.Tensor] = {}

    total = 0
    top1_correct = 0
    recall_correct = {k: 0 for k in recall_ks}

    for it in items:
        scan_id = it["scan_id"]
        utter = it["utterance"]
        gt_views = it.get("view_ground_truth", None)
        if not gt_views:
            continue
        gt = int(gt_views[0])  # "the first of the view gt"

        # Load / cache view features for this scan
        if scan_id not in scan_cache:
            filename = f'light_scannet/{scan_id}.safetensors'
            data = load_safetensor_from_hf('MatchLab/ScenePoint', filename, repo_type="dataset")

            # if "point_map" not in data:
            #     raise KeyError(f"{st_path} does not contain key 'point_map'. keys={list(data.keys())}")

            pm = to_vchw(data["point_map"])  # (V, 3, H, W)
            # pm = data['color_images']
            
            V = pm.shape[0]

            feats = model.encode_views(pm.to(device, non_blocking=True))  # (chunk, D)
            scan_cache[scan_id] = feats  # (V, D) on CPU

        view_feats = scan_cache[scan_id]  # (V, D), CPU
        V = view_feats.shape[0]
        if gt < 0 or gt >= V:
            # skip invalid gt index
            continue

        # Encode text
        text_feat = model.encode_text(utter).squeeze(0).unsqueeze(-1)  # (D,)

        # Similarity: (V,)
        sims = (view_feats @ text_feat).squeeze(-1)
    
        # rank views by similarity (high -> low)
        ranked = torch.argsort(sims, descending=True)

        pred = int(ranked[0].item())
        total += 1

        if pred == gt:
            top1_correct += 1
        else:
            # per-sample print (optional)
            print(f"GT: {gt}, Pred: {pred}, Utterance: {utter}")

        # Recall@K
        for k in recall_ks:
            k_eff = min(k, V)
            if (ranked[:k_eff] == gt).any().item():
                recall_correct[k] += 1

    # ----- after the loop -----
    out = {}
    if total == 0:
        return {"n": 0}

    out["n"] = total
    out["top1_acc"] = top1_correct / total
    for k in recall_ks:
        out[f"recall@{k}"] = recall_correct[k] / total

    return out

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--jsonl", type=str, required=True, help="SR3D-style jsonl file")
    ap.add_argument("--scan_root", type=str, required=True, help="Root dir containing scan safetensors")
    ap.add_argument("--ckpt", type=str, default="", help="Optional: path to .pth/.pt or dir with model*.safetensors")
    ap.add_argument("--model_root", type=str, default="fg-clip-base")
    ap.add_argument("--device", type=str, default="cuda")
    ap.add_argument("--batch_views", type=int, default=32)
    ap.add_argument("--max_items", type=int, default=-1)
    args = ap.parse_args()

    items = load_jsonl(args.jsonl)
    if args.max_items > 0:
        items = items[: args.max_items]

    model = RepModel(model_root=args.model_root)
    if args.ckpt:
        load_pretrain(model, args.ckpt)

    metrics = eval_view_retrieval(
        model=model,
        items=items,
        scan_root=args.scan_root,
        device=args.device,
        batch_views=args.batch_views,
        recall_ks=(1, 5, 10),
    )

    print("\n=== View Retrieval Results ===")
    for k, v in metrics.items():
        if isinstance(v, float):
            print(f"{k:>10}: {v:.4f}")
        else:
            print(f"{k:>10}: {v}")


if __name__ == "__main__":
    main()