-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsam3_concept_bank.py
More file actions
1594 lines (1344 loc) · 57.7 KB
/
sam3_concept_bank.py
File metadata and controls
1594 lines (1344 loc) · 57.7 KB
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import re
import json
import copy
import heapq
import gc
import random
import argparse
import time
from collections import OrderedDict
from contextlib import nullcontext
from typing import Dict, List, Tuple, Any, Optional
import numpy as np
from PIL import Image
from tqdm import tqdm
import torch
import torch.distributed as dist
# =========================================================
# 1. DDP Bootstrap
# =========================================================
def setup_distributed_env():
"""Sets CUDA device based on LOCAL_RANK to prevent multi-process conflicts."""
if "LOCAL_RANK" in os.environ:
local_rank = int(os.environ["LOCAL_RANK"])
if torch.cuda.is_available():
torch.cuda.set_device(local_rank)
setup_distributed_env()
from mmengine.config import Config
from mmengine.registry import init_default_scope
from mmengine.utils import mkdir_or_exist
from mmseg.registry import DATASETS
from sam3 import build_sam3_image_model
from sam3.model.sam3_image_processor import Sam3Processor
from sam3.model.data_misc import FindStage, interpolate
try:
import custom_datasets
except Exception:
pass
# =========================================================
# 2. DDP Utilities
# =========================================================
def dist_is_on() -> bool:
return dist.is_available() and dist.is_initialized()
def get_rank() -> int:
return dist.get_rank() if dist_is_on() else 0
def get_world_size() -> int:
return dist.get_world_size() if dist_is_on() else 1
def is_main() -> bool:
return get_rank() == 0
def print0(*args, **kwargs):
if is_main():
print(*args, **kwargs)
def ddp_init(backend: str = "nccl"):
if "WORLD_SIZE" not in os.environ:
return
world_size = int(os.environ["WORLD_SIZE"])
if world_size <= 1:
return
if torch.cuda.is_available() and backend == "nccl":
try:
dist.init_process_group(
backend=backend,
init_method="env://",
device_id=torch.cuda.current_device(),
)
except TypeError:
dist.init_process_group(backend=backend, init_method="env://")
else:
dist.init_process_group(backend=backend if backend else "gloo", init_method="env://")
def ddp_barrier():
if not dist_is_on():
return
try:
if torch.cuda.is_available() and dist.get_backend() == "nccl":
dist.barrier(device_ids=[torch.cuda.current_device()])
else:
dist.barrier()
except Exception:
pass
def ddp_cleanup():
if dist_is_on():
ddp_barrier()
dist.destroy_process_group()
def _dist_reduce_device(prefer: torch.device) -> torch.device:
"""Use CUDA tensors only for NCCL; otherwise reduce on CPU to avoid backend/device mismatch."""
if not dist_is_on():
return prefer
try:
backend = dist.get_backend()
except Exception:
backend = "gloo"
if backend == "nccl" and torch.cuda.is_available():
return prefer if prefer.type == "cuda" else torch.device("cuda")
return torch.device("cpu")
def _ddp_reduce_max_f64(x: float, prefer_device: torch.device) -> float:
if not dist_is_on():
return float(x)
dev = _dist_reduce_device(prefer_device)
t = torch.tensor([float(x)], device=dev, dtype=torch.float64)
dist.all_reduce(t, op=dist.ReduceOp.MAX)
return float(t.item())
def _ddp_reduce_sum_i64(x: int, prefer_device: torch.device) -> int:
if not dist_is_on():
return int(x)
dev = _dist_reduce_device(prefer_device)
t = torch.tensor([int(x)], device=dev, dtype=torch.int64)
dist.all_reduce(t, op=dist.ReduceOp.SUM)
return int(t.item())
def _sec_to_min(x: float) -> float:
return float(x) / 60.0
# =========================================================
# 3. String & Parsing Utilities
# =========================================================
def parse_users_arg(s: str) -> List[Tuple[str, str]]:
out: List[Tuple[str, str]] = []
parts = [p.strip() for p in (s or "").split(",") if p.strip()]
if not parts:
raise RuntimeError("--users is empty. Expect 'name=config.py,...'")
for p in parts:
if "=" not in p:
raise RuntimeError(f"Bad --users item: {p}. Expect name=cfg_path")
name, cfg = p.split("=", 1)
name = name.strip()
cfg = cfg.strip()
if not name or not cfg:
raise RuntimeError(f"Bad --users item: {p}.")
out.append((name, cfg))
names = [n for n, _ in out]
if len(set(names)) != len(names):
raise RuntimeError(f"Duplicate user names in --users: {names}")
return out
def _norm_name(s: str) -> str:
s = s.strip().lower()
s = re.sub(r"[\s_\-]+", "", s)
return s
def dedup_phrases(xs: List[str]) -> List[str]:
seen = set()
out = []
for x in xs:
x = x.strip()
if not x:
continue
k = " ".join(x.lower().split())
if k not in seen:
seen.add(k)
out.append(x)
return out
def load_name_path(name_path: str) -> Tuple[List[str], Dict[str, List[str]]]:
classes: List[str] = []
expanded: Dict[str, List[str]] = {}
with open(name_path, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
if "#" in line:
line = line.split("#", 1)[0].strip()
if not line:
continue
key = None
phrases: List[str] = []
if "\t" in line:
parts = [p.strip() for p in line.split("\t") if p.strip()]
key = parts[0]
rest = parts[1:]
if len(rest) == 1 and any(c in rest[0] for c in ",|;"):
phrases = [x.strip() for x in re.split(r"[,\|\;]", rest[0]) if x.strip()]
else:
phrases = rest
elif ":" in line or "->" in line:
sep = ":" if ":" in line else "->"
key, rest = line.split(sep, 1)
key, rest = key.strip(), rest.strip()
if rest.startswith("[") and rest.endswith("]"):
try:
arr = json.loads(rest)
if isinstance(arr, list):
phrases = [str(x).strip() for x in arr if str(x).strip()]
except Exception:
phrases = []
if not phrases:
phrases = [x.strip() for x in re.split(r"[,\|\;]", rest) if x.strip()]
elif "," in line:
parts = [p.strip() for p in line.split(",") if p.strip()]
key = parts[0]
phrases = parts[1:]
else:
key = line.strip()
if not key:
continue
ph = dedup_phrases([key] + phrases)
classes.append(key)
expanded[key] = ph
if not classes:
raise RuntimeError(f"name_path parsed empty: {name_path}")
return classes, expanded
def parse_extra_calib(s: Optional[str], name2id: Dict[str, int]) -> Dict[int, int]:
out: Dict[int, int] = {}
if not s:
return out
parts = [p.strip() for p in s.split(",") if p.strip()]
for p in parts:
if "=" not in p:
continue
k, v = p.split("=", 1)
k = k.strip()
v = int(v.strip())
if k in name2id:
out[name2id[k]] = v
return out
# =========================================================
# 4. Dataset & Image Utilities
# =========================================================
def _strip_pack_transforms(pipeline: List[dict]) -> List[dict]:
banned = {"PackSegInputs", "PackPILInputs", "PackInputs"}
out = []
for t in pipeline:
if isinstance(t, dict) and t.get("type", "") not in banned:
out.append(t)
return out
def _override_split_in_data_prefix(dataset_cfg: dict, split: str):
if not isinstance(dataset_cfg, dict):
return
coco_map = {"train": "train2017", "val": "val2017", "test": "test2017"}
if "data_prefix" in dataset_cfg:
dp = dataset_cfg["data_prefix"]
if isinstance(dp, dict):
def repl(p: str) -> str:
p = p.replace("\\", "/")
p = re.sub(r"/(train|val|test)(/)?$", lambda m: f"/{split}" + ("/" if m.group(2) else ""), p)
p = re.sub(r"/(train|val|test)/", f"/{split}/", p)
if split in coco_map:
tgt = coco_map[split]
p = re.sub(r"/(train|val|test)2017(?=/|$)", f"/{tgt}", p)
if split == "train":
p = re.sub(r"/validation(/|$)", r"/training\1", p)
elif split == "val":
p = re.sub(r"/training(/|$)", r"/validation\1", p)
return p
for k, v in dp.items():
if isinstance(v, str):
dp[k] = repl(v)
if "ann_file" in dataset_cfg and isinstance(dataset_cfg["ann_file"], str):
af = dataset_cfg["ann_file"].replace("\\", "/")
af = re.sub(r"/(train|val|test)\.txt$", f"/{split}.txt", af)
af = re.sub(r"/trainaug\.txt$", f"/{split}.txt", af)
dataset_cfg["ann_file"] = af
if "split" in dataset_cfg and isinstance(dataset_cfg["split"], str):
dataset_cfg["split"] = split
def _extract_img_and_gt(sample: dict) -> Tuple[Image.Image, np.ndarray]:
img = sample.get("img", sample.get("inputs", None))
gt = sample.get("gt_seg_map", sample.get("gt_semantic_seg", None))
if img is None or gt is None:
raise RuntimeError(f"Cannot extract img/gt from sample keys={list(sample.keys())}")
if isinstance(img, Image.Image):
pil = img.convert("RGB")
else:
arr = img
if torch.is_tensor(arr):
arr = arr.detach().cpu().numpy()
arr = np.asarray(arr)
if arr.ndim == 3 and arr.shape[2] == 3:
pil = Image.fromarray(arr.astype(np.uint8)).convert("RGB")
elif arr.ndim == 2:
pil = Image.fromarray(arr.astype(np.uint8)).convert("RGB")
else:
raise RuntimeError(f"Unsupported img shape: {arr.shape}")
if torch.is_tensor(gt):
gt_np = gt.detach().cpu().numpy()
else:
gt_np = np.asarray(gt)
gt_np = gt_np.astype(np.int32)
return pil, gt_np
def _square_box_from_mask(train_ids: np.ndarray, class_id: int, pad_ratio: float, min_size: int):
ys, xs = np.where(train_ids == class_id)
if len(xs) == 0:
return None
x1, x2 = xs.min(), xs.max()
y1, y2 = ys.min(), ys.max()
w, h = x2 - x1 + 1, y2 - y1 + 1
pad = int(max(w, h) * pad_ratio)
x1p = max(0, x1 - pad)
y1p = max(0, y1 - pad)
x2p = min(train_ids.shape[1] - 1, x2 + pad)
y2p = min(train_ids.shape[0] - 1, y2 + pad)
cx, cy = (x1p + x2p) // 2, (y1p + y2p) // 2
half = max((x2p - x1p + 1), (y2p - y1p + 1), min_size) // 2
x1p, x2p = max(0, cx - half), min(train_ids.shape[1] - 1, cx + half)
y1p, y2p = max(0, cy - half), min(train_ids.shape[0] - 1, cy + half)
return x1p, y1p, x2p, y2p
def make_crop_views_from_np(
img_np: np.ndarray,
train_ids: np.ndarray,
class_id: int,
pad_ratio: float,
min_size: int,
use_context: bool,
use_masked: bool,
):
if not (use_context or use_masked):
use_context = True
box = _square_box_from_mask(train_ids, class_id, pad_ratio, min_size)
if box is None:
return None, None
x1, y1, x2, y2 = box
crop_np = img_np[y1 : y2 + 1, x1 : x2 + 1].copy()
m = (train_ids[y1 : y2 + 1, x1 : x2 + 1] == class_id).astype(np.uint8)
views: List[Image.Image] = []
ctx_view = Image.fromarray(crop_np)
if use_context:
views.append(ctx_view)
if use_masked:
bg = np.full_like(crop_np, 127, dtype=np.uint8)
masked = np.where(m[..., None].astype(bool), crop_np, bg)
views.append(Image.fromarray(masked))
if not views:
views.append(ctx_view)
return views, m
# =========================================================
# 5. Model & Tensor Alignment Utilities
# =========================================================
def _find_dim_of_size(shape: torch.Size, size: int) -> Optional[int]:
for i, s in enumerate(shape):
if s == size:
return i
return None
def _align_3d_to_BTD(x: torch.Tensor, B: int) -> Tuple[torch.Tensor, dict]:
assert x.ndim == 3
bd = _find_dim_of_size(x.shape, B)
if bd is None:
raise RuntimeError(f"Cannot find batch dim B={B} in {tuple(x.shape)}")
rem = [0, 1, 2]
rem.remove(bd)
d_dim = rem[0] if x.shape[rem[0]] >= x.shape[rem[1]] else rem[1]
t_dim = rem[1] if d_dim == rem[0] else rem[0]
x_btd = x.permute(bd, t_dim, d_dim).contiguous()
layout = {"raw_shape": tuple(x.shape), "batch_dim": bd, "token_dim": t_dim, "d_dim": d_dim}
return x_btd, layout
def _align_mask_to_BT(x: torch.Tensor, B: int) -> Tuple[torch.Tensor, dict]:
x = torch.as_tensor(x).squeeze()
if x.ndim == 1:
if B != 1:
raise RuntimeError(f"language_mask is 1D {tuple(x.shape)} but B={B} != 1")
return x.view(1, -1).contiguous(), {"raw_shape": tuple(x.shape), "batch_dim": 0, "token_dim": 1}
if x.ndim != 2:
raise RuntimeError(f"language_mask must be 1D or 2D after squeeze, got {tuple(x.shape)}")
bd = _find_dim_of_size(x.shape, B)
if bd is None:
if B == 1:
if x.shape[0] == 1:
return x.contiguous(), {"raw_shape": tuple(x.shape), "batch_dim": 0, "token_dim": 1}
if x.shape[1] == 1:
return x.t().contiguous(), {"raw_shape": tuple(x.shape), "batch_dim": 0, "token_dim": 1}
raise RuntimeError(f"Cannot find batch dim B={B} in mask {tuple(x.shape)}")
t_dim = 1 - bd
return x.permute(bd, t_dim).contiguous(), {"raw_shape": tuple(x.shape), "batch_dim": bd, "token_dim": t_dim}
def _align_language_outputs(out: Dict[str, Any], B: int):
lf_btd, lf_layout = _align_3d_to_BTD(out["language_features"], B)
pm_bt, pm_layout = _align_mask_to_BT(out["language_mask"], B)
le_btd, le_layout = _align_3d_to_BTD(out["language_embeds"], B)
layout = {"language_features": lf_layout, "language_mask": pm_layout, "language_embeds": le_layout}
return lf_btd, pm_bt, le_btd, layout
def to_raw_from_BTD(x_btd: torch.Tensor, lay: dict) -> torch.Tensor:
bd, td, dd = lay["batch_dim"], lay["token_dim"], lay["d_dim"]
src = [0, 0, 0]
src[bd], src[td], src[dd] = 0, 1, 2
return x_btd.permute(*src).contiguous()
def mask_to_raw_from_BT(x_bt: torch.Tensor, lay: dict) -> torch.Tensor:
bd = lay["batch_dim"]
src = [0, 0]
src[bd], src[1 - bd] = 0, 1
return x_bt.permute(*src).contiguous()
def fuse_tokens(selected: List[Tuple[torch.Tensor, torch.Tensor, torch.Tensor, float]]):
assert len(selected) >= 1
T = selected[0][0].shape[0]
w = torch.tensor([s[3] for s in selected], dtype=torch.float32)
w = w / w.sum().clamp_min(1e-6)
lf = torch.stack([s[0].float() for s in selected], dim=0)
pm = torch.stack([s[1].bool() for s in selected], dim=0)
le = torch.stack([s[2].float() for s in selected], dim=0)
valid = (~pm).float()
denom = (w.view(-1, 1) * valid).sum(dim=0)
valid_f = denom > 1e-6
pm_f = ~valid_f
denom_safe = denom.clamp_min(1e-6).view(1, T, 1)
lf_num = (w.view(-1, 1, 1) * lf * valid.unsqueeze(-1)).sum(dim=0, keepdim=True)
le_num = (w.view(-1, 1, 1) * le * valid.unsqueeze(-1)).sum(dim=0, keepdim=True)
return (lf_num / denom_safe).squeeze(0), pm_f, (le_num / denom_safe).squeeze(0)
# =========================================================
# 6. SAM3 Specific Utilities
# =========================================================
@torch.inference_mode()
def build_prob_map(
outputs: dict,
H: int,
W: int,
confidence_threshold: float,
topk_inst: int,
use_sem: bool = True,
use_presence_instance: bool = True,
):
pres = outputs["presence_logit_dec"].sigmoid().view(-1) # [B]
pl = outputs["pred_logits"]
if pl.ndim == 3 and pl.size(-1) == 1:
pl = pl.squeeze(-1)
scores = pl.sigmoid() # [B,N]
pm = outputs["pred_masks"]
if pm.ndim == 5 and pm.size(2) == 1:
pm = pm.squeeze(2) # [B,N,hf,wf]
sem_up = None
if use_sem and ("semantic_seg" in outputs):
sem = outputs["semantic_seg"] # [B,1,hf,wf]
sem_up = interpolate(sem, (H, W), mode="bilinear", align_corners=False).sigmoid().squeeze(1)
B = scores.shape[0]
out_maps = []
for b in range(B):
s = scores[b]
masks_b = pm[b]
if topk_inst > 0 and s.numel() > topk_inst:
val, idx = torch.topk(s, k=topk_inst, largest=True)
s = val
masks_b = masks_b[idx]
if use_presence_instance:
s = s * pres[b]
keep = s > confidence_threshold
inst_map = torch.zeros((H, W), device=masks_b.device, dtype=torch.float16)
if keep.any():
masks_k = masks_b[keep]
scores_k = s[keep]
masks_up = interpolate(
masks_k.unsqueeze(1), (H, W), mode="bilinear", align_corners=False
).sigmoid().squeeze(1)
inst_map = (masks_up * scores_k.view(-1, 1, 1)).amax(dim=0)
if sem_up is not None:
sem_val = sem_up[b] * pres[b]
inst_map = torch.max(inst_map, sem_val)
out_maps.append(inst_map)
return torch.stack(out_maps, dim=0)
@torch.inference_mode()
def extract_sam3_image_embedding(backbone_out: Dict[str, Any]) -> torch.Tensor:
preferred_keys = [
"image_embedding", "image_embed", "img_embedding", "img_embed",
"vision_embedding", "vision_embed", "image_features", "vision_features",
"backbone_features", "features", "feat", "x",
]
def _iter_tensors(d: Any, prefix: str = ""):
if isinstance(d, dict):
for k, v in d.items():
p = f"{prefix}.{k}" if prefix else str(k)
yield from _iter_tensors(v, p)
elif torch.is_tensor(d):
yield prefix, d
def _pick_tensor():
for k in preferred_keys:
if k in backbone_out and torch.is_tensor(backbone_out[k]):
return backbone_out[k]
candidates = []
for name, t in _iter_tensors(backbone_out):
if t.dtype in (torch.float16, torch.float32, torch.bfloat16):
lname = name.lower()
pri = 0
for i, kk in enumerate(preferred_keys):
if kk in lname:
pri = max(pri, 100 - i)
last_dim = int(t.shape[-1]) if t.ndim >= 2 else int(t.numel())
score = pri * 1_000_000 + last_dim * 1000 + t.ndim * 10
candidates.append((score, t))
if not candidates:
# robust fallback: create a dummy embedding
return torch.zeros((1, 1), dtype=torch.float32)
return sorted(candidates, key=lambda x: x[0], reverse=True)[0][1]
t = _pick_tensor()
if t.ndim == 4:
if t.size(0) == 1:
t = t[0]
if t.ndim == 3:
t = t.mean(dim=(1, 2))
else:
t = t.mean(dim=(0, 2, 3))
elif t.ndim >= 2:
t = t.reshape(-1, t.shape[-1]).mean(dim=0)
else:
t = t.flatten()
emb = t.float()
return emb / emb.norm(p=2).clamp_min(1e-6)
# =========================================================
# 7. Caching & Auto Config
# =========================================================
def auto_cap_from_num_classes(C: int, lo: int = 3, hi: int = 9) -> int:
cap = int(round(np.sqrt(max(C, 1)) / 5.0 + 2.0))
return int(np.clip(cap, lo, hi))
def _stage_cleanup_cuda(empty_cache: bool = True):
gc.collect()
if torch.cuda.is_available() and empty_cache:
torch.cuda.empty_cache()
class LRUEmbCache:
def __init__(self, max_items: int = 8192):
self.max_items = int(max_items)
self.od: OrderedDict = OrderedDict()
def get(self, key):
v = self.od.get(key, None)
if v is not None:
self.od.move_to_end(key)
return v
def put(self, key, value):
if self.max_items <= 0:
return
self.od[key] = value
self.od.move_to_end(key)
if len(self.od) > self.max_items:
self.od.popitem(last=False)
# =========================================================
# 8. Main Builder (One User)
# =========================================================
@torch.inference_mode()
def build_one_user_bank(
user_name: str,
cfg_path: str,
args,
model,
processor,
device: torch.device,
amp_ctx,
rank: int,
world: int,
global_text_layout_cache: dict,
) -> Tuple[Optional[dict], dict, dict]:
init_default_scope("mmseg")
prof: Dict[str, Any] = {
"stage1_sec": 0.0, "stage2_sec": 0.0, "stage3_sec": 0.0,
"stage1_crops": 0, "stage2_crops": 0, "stage3_crops": 0,
"total_sec": 0.0,
}
# --- Config & Dataset Init ---
cfg = Config.fromfile(cfg_path)
if "model" not in cfg or "name_path" not in cfg.model:
raise RuntimeError(f"[{user_name}] config must contain cfg.model.name_path")
name_path = cfg.model.name_path
try:
bg_idx = int(getattr(cfg.model, "bg_idx", 0))
except Exception:
bg_idx = 0
try:
bg_thr = float(getattr(cfg.model, "bg_thr", 0))
except Exception:
bg_thr = 0.0
try:
calib_per_class = int(getattr(cfg.model, "calib_per_class", 10))
except Exception:
calib_per_class = 10
try:
calib_max_class = int(getattr(cfg.model, "calib_max_class", 10))
except Exception:
calib_max_class = 10
classes, expanded = load_name_path(name_path)
C = len(classes)
name2qid = {n: i for i, n in enumerate(classes)}
name2qid_norm = {_norm_name(n): i for i, n in enumerate(classes)}
dl_key = args.dataloader_key if args.dataloader_key else ("train_dataloader" if "train_dataloader" in cfg else "test_dataloader")
if dl_key not in cfg:
raise RuntimeError(f"[{user_name}] {dl_key} not found.")
dataset_cfg = copy.deepcopy(cfg[dl_key]["dataset"])
if "pipeline" in dataset_cfg and isinstance(dataset_cfg["pipeline"], list):
dataset_cfg["pipeline"] = _strip_pack_transforms(dataset_cfg["pipeline"])
if args.split:
_override_split_in_data_prefix(dataset_cfg, args.split)
if args.img_path:
dataset_cfg.setdefault("data_prefix", {})["img_path"] = args.img_path
if args.seg_path:
dataset_cfg.setdefault("data_prefix", {})["seg_map_path"] = args.seg_path
dataset = DATASETS.build(dataset_cfg)
ds_classes = getattr(dataset, "CLASSES", getattr(dataset, "metainfo", {}).get("classes", None))
if ds_classes is None:
ds_classes = classes
ds_classes = list(ds_classes)
dsid_to_qid: Dict[int, int] = {}
for i, n in enumerate(ds_classes):
k = _norm_name(n)
if k in name2qid_norm:
dsid_to_qid[i] = name2qid_norm[k]
for i in range(len(ds_classes)):
if i not in dsid_to_qid and i < C:
dsid_to_qid[i] = i
ignore_index = getattr(dataset, "ignore_index", 255)
try:
ignore_index = int(ignore_index)
except Exception:
ignore_index = 255
N = len(dataset)
indices_shard = list(range(rank, N, world))
disable_tqdm = not is_main()
if is_main():
print0(f"\n========== [USER] {user_name} ==========")
print0(f"[INFO] cfg={cfg_path}, name_path={name_path}, C={C}, N={N}")
extra = parse_extra_calib(args.extra_calib, name2qid)
target = [calib_per_class + extra.get(i, 0) for i in range(C)]
cap_pass1 = auto_cap_from_num_classes(C, lo=3, hi=9)
cap_pass2_init = auto_cap_from_num_classes(C, lo=3, hi=9)
proto_per_class = calib_per_class
if is_main():
print0(f"[AUTO] proto={proto_per_class}, cap1={cap_pass1}, cap2={cap_pass2_init}, cache={args.pass2_emb_cache}")
def _view_weights(views):
if args.use_context_view and args.use_masked_view and len(views) == 2:
w = [args.view_weight_context, args.view_weight_masked]
else:
w = [1.0] * len(views)
s = sum(w)
return [x / max(1e-6, s) for x in w]
@torch.inference_mode()
def compute_crop_embedding_device(views):
ws = _view_weights(views)
emb_acc = None
for v, wv in zip(views, ws):
with amp_ctx:
st = processor.set_image(v)
e = extract_sam3_image_embedding(st["backbone_out"])
e = e.float() * float(wv)
emb_acc = e if emb_acc is None else (emb_acc + e)
return emb_acc / emb_acc.norm(p=2).clamp_min(1e-6)
# =====================================================
# Stage I: Pass 1 Prototype Collection
# =====================================================
_stage_cleanup_cuda()
t_s1_start = time.perf_counter()
D_local = 0
sum_local = None
cnt_local_cpu = np.zeros((C,), dtype=np.int32)
cnt_limit_cpu = np.full((C,), calib_max_class, dtype=np.int32)
it1 = tqdm(indices_shard, desc=f"{user_name}:Pass1(r{rank})", dynamic_ncols=True, disable=disable_tqdm)
for idx in it1:
if (cnt_local_cpu >= cnt_limit_cpu).all():
break
try:
sample = dataset[idx]
img, gt_trainid = _extract_img_and_gt(sample)
except Exception:
continue
img_np = np.asarray(img, dtype=np.uint8)
uniq = [int(x) for x in np.unique(gt_trainid) if int(x) != ignore_index and int(x) >= 0]
if not uniq:
continue
uniq_q = []
for dsid in uniq:
qid = dsid_to_qid.get(dsid, None)
if qid is not None and 0 <= qid < C:
uniq_q.append((qid, dsid))
uniq_q.sort(key=lambda p: (int(cnt_local_cpu[p[0]]), p[0]))
for (qid, dsid) in uniq_q[:cap_pass1]:
if cnt_local_cpu[qid] >= cnt_limit_cpu[qid]:
continue
views, _ = make_crop_views_from_np(
img_np, gt_trainid, dsid,
pad_ratio=args.pad_ratio, min_size=args.min_crop_size,
use_context=args.use_context_view, use_masked=args.use_masked_view,
)
if views is None:
continue
try:
e = compute_crop_embedding_device(views)
except Exception:
continue
if D_local == 0:
D_local = int(e.numel())
if D_local <= 0:
continue
sum_local = torch.zeros((C, D_local), device=device, dtype=torch.float32)
if int(e.numel()) == D_local:
sum_local[qid] += e.float()
cnt_local_cpu[qid] += 1
# Sync/Resolve embedding dim robustly
if dist_is_on():
dev_red = _dist_reduce_device(device)
d_tensor = torch.tensor([int(D_local)], device=dev_red, dtype=torch.int64)
d_list = [torch.zeros_like(d_tensor) for _ in range(world)]
dist.all_gather(d_list, d_tensor)
ds = sorted(set([int(x.item()) for x in d_list if int(x.item()) > 0]))
D_global = ds[0] if ds else 0
else:
D_global = int(D_local)
if D_global <= 0:
# robust fallback: no valid protos
proto_valid_cpu = np.zeros((C,), dtype=bool)
cnt_local = torch.zeros((C,), device=device, dtype=torch.float32)
if is_main():
print0(f"[{user_name}] Pass1: no valid crops for prototype collection; continue with fallback.")
prof["stage1_crops"] = 0
prof["stage1_sec"] = _ddp_reduce_max_f64(time.perf_counter() - t_s1_start, device)
ddp_barrier()
# create dummy proto tensor for shape safety
proto = torch.zeros((C, 1), device=device, dtype=torch.float32)
else:
if sum_local is None:
sum_local = torch.zeros((C, D_global), device=device, dtype=torch.float32)
cnt_local = torch.from_numpy(cnt_local_cpu.astype(np.float32)).to(device)
if dist_is_on():
dist.all_reduce(sum_local, op=dist.ReduceOp.SUM)
dist.all_reduce(cnt_local, op=dist.ReduceOp.SUM)
proto = sum_local / cnt_local.clamp_min(1.0).unsqueeze(1)
proto = proto / proto.norm(p=2, dim=1, keepdim=True).clamp_min(1e-6)
proto_valid_cpu = (cnt_local.detach().cpu().numpy() > 0.5)
if is_main():
print0(f"[{user_name}] Pass1 Done. Valid protos: {int(proto_valid_cpu.sum())}/{C}")
prof["stage1_crops"] = int(cnt_local.sum().item())
ddp_barrier()
prof["stage1_sec"] = _ddp_reduce_max_f64(time.perf_counter() - t_s1_start, device)
# =====================================================
# Stage II: Pass 2 Multi-epoch Fill (Representative Mining)
# =====================================================
t_s2_start = time.perf_counter()
heaps = [[] for _ in range(C)]
tie = 0
emb_cache = LRUEmbCache(max_items=int(args.pass2_emb_cache))
def heap_size(c):
return len(heaps[c])
def all_full():
for c in range(C):
if target[c] > 0 and heap_size(c) < target[c] and proto_valid_cpu[c]:
return False
return True
if D_global > 0 and bool(proto_valid_cpu.any()):
for epoch in range(args.pass2_max_epochs):
if all_full():
break
cap_pass2 = int(min(12, cap_pass2_init * (2 ** epoch)))
it2 = tqdm(indices_shard, desc=f"{user_name}:Pass2(e{epoch},r{rank})", dynamic_ncols=True, disable=disable_tqdm)
for idx in it2:
if all_full():
break
try:
sample = dataset[idx]
img, gt_trainid = _extract_img_and_gt(sample)
except Exception:
continue
img_np = np.asarray(img, dtype=np.uint8)
uniq = [int(x) for x in np.unique(gt_trainid) if int(x) != ignore_index and int(x) >= 0]
if not uniq:
continue
cand = []
for dsid in uniq:
qid = dsid_to_qid.get(dsid, None)
if qid is None or not (0 <= qid < C):
continue
if target[qid] <= 0 or not proto_valid_cpu[qid]:
continue
if heap_size(qid) < target[qid]:
cand.append((target[qid] - heap_size(qid), qid, dsid))
if not cand:
continue
cand.sort(key=lambda x: (-x[0], x[1], x[2]))
qids, dsids, embs = [], [], []
for (_, qid, dsid) in cand[:cap_pass2]:
if heap_size(qid) >= target[qid]:
continue
key = (
int(idx),
int(dsid),
int(args.use_context_view),
int(args.use_masked_view),
float(args.pad_ratio),
int(args.min_crop_size),
)
cached = emb_cache.get(key)
if cached is not None:
e = cached.to(device, dtype=torch.float32, non_blocking=True)
else:
views, _ = make_crop_views_from_np(
img_np, gt_trainid, dsid,
pad_ratio=args.pad_ratio, min_size=args.min_crop_size,
use_context=args.use_context_view, use_masked=args.use_masked_view,
)
if views is None:
continue
try:
e = compute_crop_embedding_device(views)
except Exception:
continue
emb_cache.put(key, e.detach().cpu().half())
if int(e.numel()) == D_global:
qids.append(int(qid))
dsids.append(int(dsid))
embs.append(e)
if not embs:
continue
E = torch.stack(embs, dim=0).float()
P = proto[torch.tensor(qids, device=device)].float()
scores = (E * P).sum(dim=1).detach().cpu().tolist()
for qid, dsid, sc in zip(qids, dsids, scores):
tie += 1
item = (float(sc), tie, int(idx), int(dsid))
h = heaps[qid]
if len(h) < target[qid]:
heapq.heappush(h, item)
elif float(sc) > h[0][0]:
heapq.heapreplace(h, item)
local_cands = [
[(float(s), int(i), int(dsid)) for (s, _, i, dsid) in sorted(heaps[c], key=lambda x: x[0], reverse=True)]
for c in range(C)
]
if dist_is_on():
gathered = [None for _ in range(world)]
dist.all_gather_object(gathered, local_cands)
else:
gathered = [local_cands]
selected_meta = None
if is_main():
selected_meta = [[] for _ in range(C)]
for c in range(C):
all_items = []
for r in range(len(gathered)):
all_items.extend(gathered[r][c])
all_items.sort(key=lambda x: x[0], reverse=True)
K = target[c]
top = all_items[:K] if K > 0 else []
selected_meta[c] = [(idx, dsid, float(score)) for (score, idx, dsid) in top]
if dist_is_on():
obj_list = [selected_meta]
dist.broadcast_object_list(obj_list, src=0)
selected_meta = obj_list[0]
ddp_barrier()
# Stage II crops = selected representative supports (global)
try:
prof["stage2_crops"] = int(sum(len(selected_meta[c]) for c in range(C)))
except Exception:
prof["stage2_crops"] = 0
# Clean up Pass 2 Memory
try:
del sum_local, cnt_local
except Exception:
pass
_stage_cleanup_cuda()
ddp_barrier()
prof["stage2_sec"] = _ddp_reduce_max_f64(time.perf_counter() - t_s2_start, device)