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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
import math
import os
import torch
import torch.nn as nn
import sys

from training.file_utils import pt_load
sys.path.append("..")
from clipself.src.open_clip.tiny_clip.factory import create_model, get_tokenizer
from prompts.imagenet_template import openai_imagenet_template, sub_imagenet_template
from mmseg.models.segmentors import BaseSegmentor
from mmengine.structures import PixelData
from mmseg.registry import MODELS
import torch.nn.functional as F
from mmseg.models.data_preprocessor import SegDataPreProcessor
from segment_anything import sam_model_registry
from myutils import UnNormalize
from torchvision import transforms

@MODELS.register_module()
class TinyCLIPProxySegmentation(BaseSegmentor):
    def __init__(
        self,
        clip_type,
        name_path,
        vfm_model,
        checkpoint,
        mode="proxyclip",
        device=torch.device("cuda:0"),
        prob_thd=0.0,
        logit_scale=40,
        beta=1.2,
        gamma=3.0,
        slide_stride=112,
        slide_crop=336,
    ):
        data_preprocessor = SegDataPreProcessor(
            mean=[122.771, 116.746, 104.094],
            std=[68.501, 66.632, 70.323],
            bgr_to_rgb=True
        )
        super().__init__(data_preprocessor=data_preprocessor)

        # 使用tiny_clip的factory创建模型
        # 使用 fp16 精度以匹配 VFM 模型和输入类型
        if checkpoint and os.path.exists(checkpoint):
            self.clip = create_model(
                clip_type,
                pretrained=checkpoint,
                precision="fp16",
                device=device,
                cache_dir=None,
            )
        else:
            self.clip = create_model(
                clip_type,
                pretrained="",
                precision="fp16",
                device=device,
                cache_dir=None,
            )

        self.tokenizer = get_tokenizer(model_name=clip_type)
        self.clip.eval().to(device)
        
        # Explicitly convert model to half precision to ensure ALL parameters are fp16
        # This is necessary because convert_weights_to_fp16 in factory.py doesn't convert
        # Embedding layers (token_embedding) and Parameters (positional_embedding, class_embedding)
        # Using .half() ensures all parameters including embeddings are converted to fp16
        self.clip = self.clip.half()

        # VFM model setup (same as proxyclip_segmentor.py)
        self.vfm_model = vfm_model

        sam_ckpts = {
            "sam-B": "/mnt/SSD8T/home/wjj/code/ProxyCLIP/sam_ckpts/sam_vit_b_01ec64.pth",
            "sam-L": "/mnt/SSD8T/home/wjj/code/ProxyCLIP/sam_ckpts/sam_vit_l_0b3195.pth",
        }

        dinov2_ckpts = {
            "dinov2-L": "dinov2_vitl14_reg",
            "dinov2-B": "dinov2_vitb14_reg",
            "dinov2-B-noreg": "dinov2_vitb14",
            "dinov2-L-noreg": "dinov2_vitl14",
        }

        dino_ckpts = {
            "dino-B-8": "dino_vitb8",
            "dino-B-16": "dino_vitb16",
        }

        vfm = None
        if vfm_model.startswith("dinov2"):
            if vfm_model in dinov2_ckpts:
                model_name = dinov2_ckpts[vfm_model]
                hub_path = "/mnt/SSD8T/home/wjj/.cache/torch/hub/facebookresearch_dinov2_main"
                try:
                    vfm = torch.hub.load(hub_path, model_name, source="local").half()
                except Exception as e:
                    raise RuntimeError(f"Failed to load DINOv2 model '{vfm_model}': {e}")
            else:
                raise NotImplementedError(
                    f"VLM model '{vfm_model}' not supported under DINOv2 category."
                )

        elif vfm_model.startswith("dino"):
            if vfm_model in dino_ckpts:
                model_name = dino_ckpts[vfm_model]
                hub_path = "/mnt/SSD8T/home/wjj/.cache/torch/hub/facebookresearch_dino_main"
                try:
                    vfm = torch.hub.load(hub_path, model_name, source="local").half()
                except Exception as e:
                    raise RuntimeError(f"Failed to load DINO model '{vfm_model}': {e}")
            else:
                raise NotImplementedError(
                    f"VLM model '{vfm_model}' not supported under DINO category."
                )

        elif vfm_model.startswith("sam"):
            if vfm_model in sam_ckpts:
                vit_type = "vit_b" if "B" in vfm_model else "vit_l"
                checkpoint_path = sam_ckpts[vfm_model]
                try:
                    vfm = sam_model_registry[vit_type](checkpoint=checkpoint_path).half()
                except Exception as e:
                    raise RuntimeError(
                        f"Failed to load SAM model '{vfm_model}' with checkpoint '{checkpoint_path}': {e}"
                    )
            else:
                # 为了向后兼容,如果只传入 'sam',默认使用 sam-B
                if vfm_model == "sam":
                    vfm = sam_model_registry["vit_b"](checkpoint=sam_ckpts["sam-B"]).half()
                else:
                    raise NotImplementedError(
                        f"VLM model '{vfm_model}' not supported under SAM category."
                    )
        else:
            raise NotImplementedError(f"VLM model '{vfm_model}' not supported.")

        for p in vfm.parameters():
            p.requires_grad = False
        self.vfm = vfm.eval().to(device)

        self.unnorm = UnNormalize(
            [0.48145466, 0.4578275, 0.40821073], [0.26862954, 0.26130258, 0.27577711]
        )
        self.norm = transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])

        query_words, self.query_idx = get_cls_idx(name_path)
        self.num_queries = len(query_words)
        self.num_classes = max(self.query_idx) + 1
        self.query_idx = torch.Tensor(self.query_idx).to(torch.int64).to(device)
        self.mode = mode

        query_features = []
        with torch.no_grad():
            for qw in query_words:
                query = self.tokenizer([temp(qw) for temp in openai_imagenet_template]).to(
                    device
                )
                feature = self.clip.encode_text(query)
                feature /= feature.norm(dim=-1, keepdim=True)
                feature = feature.mean(dim=0)
                feature /= feature.norm()
                query_features.append(feature.unsqueeze(0))
        self.query_features = torch.cat(query_features, dim=0).detach()

        self.dtype = self.query_features.dtype
        self.logit_scale = logit_scale
        self.prob_thd = prob_thd
        self.slide_stride = slide_stride
        self.slide_crop = slide_crop
        self.beta = beta
        self.gamma = gamma

    @torch.no_grad()
    def forward_feature(self, img, logit_size=None):
        if type(img) == list:
            img = img[0]

        clip_token_size = (
            img.shape[-2] // self.clip.visual.patch_size[0],
            img.shape[-1] // self.clip.visual.patch_size[1],
        )
        imgs_norm = [self.norm(self.unnorm(img[i])) for i in range(len(img))]
        imgs_norm = torch.stack(imgs_norm, dim=0)
        imgs_norm = imgs_norm.half()

        # Extract external features from VFM
        if self.vfm_model.startswith("sam"):
            patch_size = self.vfm.image_encoder.patch_embed.proj.kernel_size
            imgs_norm = F.interpolate(
                imgs_norm, size=(1024, 1024), mode="bilinear", align_corners=False
            )
            I, J = (
                imgs_norm.shape[-2] // patch_size[0],
                imgs_norm.shape[-2] // patch_size[1],
            )
            ex_feats = self.vfm.image_encoder(imgs_norm)
        elif self.vfm_model.startswith("dino") and not self.vfm_model.startswith("dinov2"):
            feat_out = {}

            def hook_fn_forward_qkv(module, input, output):
                feat_out["qkv"] = output

            self.vfm._modules["blocks"][-1]._modules["attn"]._modules[
                "qkv"
            ].register_forward_hook(hook_fn_forward_qkv)
            # Forward pass in the model
            feat = self.vfm.get_intermediate_layers(imgs_norm)[0]
            nb_im = feat.shape[0]  # Batch size
            nb_tokens = feat.shape[1]  # Number of tokens
            nh = self.vfm.blocks[0].attn.num_heads  # Number of heads

            qkv = (
                feat_out["qkv"]
                .reshape(nb_im, nb_tokens, 3, nh, -1 // nh)
                .permute(2, 0, 3, 1, 4)
            )
            q, k, v = qkv[0], qkv[1], qkv[2]
            k = k.transpose(1, 2).reshape(nb_im, nb_tokens, -1)[:, 1:, :]
            q = q.transpose(1, 2).reshape(nb_im, nb_tokens, -1)[:, 1:, :]
            v = v.transpose(1, 2).reshape(nb_im, nb_tokens, -1)[:, 1:, :]

            patch_size = self.vfm.patch_embed.patch_size
            I, J = (
                imgs_norm[0].shape[-2] // patch_size,
                imgs_norm[0].shape[-1] // patch_size,
            )
            ex_feats = feat[:, 1:, :].reshape(nb_im, I, J, -1).permute(0, 3, 1, 2)

        elif self.vfm_model.startswith("dinov2"):
            patch_size = self.vfm.patch_embed.patch_size
            I, J = (
                imgs_norm.shape[-2] // patch_size[0],
                imgs_norm.shape[-2] // patch_size[1],
            )
            ex_feats = self.vfm.get_intermediate_layers(imgs_norm, reshape=True)[0]
        else:
            I, J = clip_token_size
            ex_feats = None

        # Encode with TinyCLIP using proxyclip mode
        # Ensure ex_feats is half precision to match CLIP model (fp16)
        if ex_feats is not None:
            ex_feats = ex_feats.half()
            # For proxyclip mode, I, J should match ex_feats spatial dimensions
            # This matches the behavior in encode_dense where it uses ex_feats.shape[2:4]
            _, _, H_vfm, W_vfm = ex_feats.shape
            I, J = H_vfm, W_vfm
        
        image_features = self.clip.encode_dense(
            img.half(),
            normalize=True,
            keep_shape=False,
            mode=self.mode,
            ex_feats=ex_feats,
            beta=self.beta,
            gamma=self.gamma,
        )

        # For proxyclip mode, image_features token count should match I * J (VFM resolution)
        # Verify and adjust if needed (shouldn't be necessary, but for safety)
        N = image_features.shape[1]
        if N != I * J:
            # If mismatch, recalculate I, J from actual token count
            # This should rarely happen, but handle it gracefully
            clip_h, clip_w = clip_token_size
            aspect_ratio = clip_w / clip_h if clip_h > 0 else 1.0
            I = int(round((N / aspect_ratio) ** 0.5))
            J = N // I
            if I * J != N:
                J = int(round((N * aspect_ratio) ** 0.5))
                I = N // J
                if I * J != N:
                    # Find factors that exactly divide N
                    sqrt_N = int(round(N ** 0.5))
                    for i in range(sqrt_N, 0, -1):
                        if N % i == 0:
                            I, J = i, N // i
                            break
        
        # For proxyclip mode, image_features is at VFM resolution (I*J, embed_dim)
        logits = image_features @ self.query_features.T
        logits = logits.permute(0, 2, 1).reshape(-1, logits.shape[-1], I, J)
        if logit_size == None:
            logits = nn.functional.interpolate(logits, size=img.shape[-2:], mode="bilinear")
        else:
            logits = nn.functional.interpolate(logits, size=logit_size, mode="bilinear")
        return logits

    def predict(self, inputs, data_samples):
        if data_samples is not None:
            batch_img_metas = [data_sample.metainfo for data_sample in data_samples]
        else:
            batch_img_metas = [
                dict(
                    ori_shape=inputs.shape[2:],
                    img_shape=inputs.shape[2:],
                    pad_shape=inputs.shape[2:],
                    padding_size=[0, 0, 0, 0],
                )
            ] * inputs.shape[0]

        ori_shape = batch_img_metas[0]["ori_shape"]
        resize_shape = batch_img_metas[0]["resize_shape"]
        img_shape = batch_img_metas[0]["img_shape"]
        if self.slide_crop > 0:
            seg_logits = self.forward_slide(
                inputs, batch_img_metas, self.slide_stride, self.slide_crop
            )
        else:
            seg_logits = self.forward_feature(inputs, img_shape)
            seg_logits = seg_logits[:, :, : resize_shape[0], : resize_shape[1]]
            seg_logits = nn.functional.interpolate(seg_logits, size=ori_shape, mode="bilinear")
        result = self.postprocess_result(seg_logits, data_samples)
        return result

    def _get_vfm_patch_size(self):
        """Get the patch size of the VFM model for padding calculation."""
        if self.vfm_model.startswith("sam"):
            patch_size = self.vfm.image_encoder.patch_embed.proj.kernel_size
            # SAM patch_size is a tuple like (16, 16)
            return patch_size[0] if isinstance(patch_size, (tuple, list)) else patch_size
        elif self.vfm_model.startswith("dino") and not self.vfm_model.startswith("dinov2"):
            patch_size = self.vfm.patch_embed.patch_size
            # DINO patch_size is an integer like 16
            return patch_size if isinstance(patch_size, int) else patch_size[0]
        elif self.vfm_model.startswith("dinov2"):
            patch_size = self.vfm.patch_embed.patch_size
            # DINOv2 patch_size is a tuple like (14, 14)
            return patch_size[0] if isinstance(patch_size, (tuple, list)) else patch_size
        else:
            # Default to CLIP patch_size (usually 16)
            return self.clip.visual.patch_size[0] if hasattr(self.clip.visual, 'patch_size') else 16

    def forward_slide(self, img, img_metas, stride=112, crop_size=224):
        """Inference by sliding-window with overlap.
        If h_crop > h_img or w_crop > w_img, the small patch will be used to
        decode without padding.
        """
        if type(img) == list:
            img = img[0].unsqueeze(0)
        if type(stride) == int:
            stride = (stride, stride)
        if type(crop_size) == int:
            crop_size = (crop_size, crop_size)
        h_stride, w_stride = stride
        h_crop, w_crop = crop_size
        batch_size, _, h_img, w_img = img.shape
        out_channels = self.num_queries
        h_grids = max(h_img - h_crop + h_stride - 1, 0) // h_stride + 1
        w_grids = max(w_img - w_crop + w_stride - 1, 0) // w_stride + 1
        preds = img.new_zeros((batch_size, out_channels, h_img, w_img))
        count_mat = img.new_zeros((batch_size, 1, h_img, w_img))
        # Get the correct patch_size based on VFM model
        vfm_patch_size = self._get_vfm_patch_size()
        for h_idx in range(h_grids):
            for w_idx in range(w_grids):
                y1 = h_idx * h_stride
                x1 = w_idx * w_stride
                y2 = min(y1 + h_crop, h_img)
                x2 = min(x1 + w_crop, w_img)
                y1 = max(y2 - h_crop, 0)
                x1 = max(x2 - w_crop, 0)
                crop_img = img[:, :, y1:y2, x1:x2]
                # pad image when (image_size % patch_size != 0)
                H, W = crop_img.shape[2:]  # original image shape
                pad = self.compute_padsize(H, W, vfm_patch_size)
                if any(pad):
                    crop_img = nn.functional.pad(crop_img, pad)  # zero padding
                crop_seg_logit = self.forward_feature(crop_img).detach()
                torch.cuda.empty_cache()
                # mask cutting for padded image
                if any(pad):
                    l, t = pad[0], pad[2]
                    crop_seg_logit = crop_seg_logit[:, :, t : t + H, l : l + W]

                preds += nn.functional.pad(
                    crop_seg_logit,
                    (
                        int(x1),
                        int(preds.shape[3] - x2),
                        int(y1),
                        int(preds.shape[2] - y2),
                    ),
                )

                count_mat[:, :, y1:y2, x1:x2] += 1
        assert (count_mat == 0).sum() == 0
        preds = preds / count_mat
        img_size = img_metas[0]["ori_shape"][:2]
        logits = nn.functional.interpolate(preds, size=img_size, mode="bilinear")
        return logits

    def compute_padsize(self, H: int, W: int, patch_size: int):
        l, r, t, b = 0, 0, 0, 0
        if W % patch_size:
            lr = patch_size - (W % patch_size)
            l = lr // 2
            r = lr - l

        if H % patch_size:
            tb = patch_size - (H % patch_size)
            t = tb // 2
            b = tb - t

        return l, r, t, b

    def postprocess_result(self, seg_logits, data_samples):
        batch_size = seg_logits.shape[0]
        for i in range(batch_size):
            seg_logits = seg_logits[i] * self.logit_scale
            seg_logits = seg_logits.softmax(0)  # n_queries * w * h

            num_cls, num_queries = max(self.query_idx) + 1, len(self.query_idx)
            if num_cls != num_queries:
                seg_logits = seg_logits.unsqueeze(0)
                cls_index = nn.functional.one_hot(self.query_idx)
                cls_index = cls_index.T.view(num_cls, num_queries, 1, 1)
                seg_logits = (seg_logits * cls_index).max(1)[0]

            seg_pred = seg_logits.argmax(0, keepdim=True)
            seg_pred[seg_logits.max(0, keepdim=True)[0] < self.prob_thd] = 0
            if data_samples is None:
                return seg_pred
            else:
                data_samples[i].set_data(
                    {
                        "seg_logits": PixelData(**{"data": seg_logits}),
                        "pred_sem_seg": PixelData(**{"data": seg_pred}),
                    }
                )
        return data_samples

    def _forward(data_samples):
        """
        """

    def inference(self, img, batch_img_metas):
        """
        """

    def encode_decode(self, inputs, batch_img_metas):
        """
        """

    def extract_feat(self, inputs):
        """
        """

    def loss(self, inputs, data_samples):
        """
        """


def get_cls_idx(path):
    with open(path, "r") as f:
        name_sets = f.readlines()
    num_cls = len(name_sets)

    class_names, class_indices = [], []
    for idx in range(num_cls):
        names_i = name_sets[idx].split("; ")
        class_names += names_i
        class_indices += [idx for _ in range(len(names_i))]
    class_names = [item.replace("\n", "") for item in class_names]
    return class_names, class_indices