Leacb4 commited on
Commit
0e70681
·
verified ·
1 Parent(s): c0a3520

Update Test D KAGL eval: canonical labels, descriptor-expanded text, hier-dominant fusion, audit logging, macro-F1 + per-class breakdown

Browse files
Files changed (1) hide show
  1. evaluation/sec536_embedding_structure.py +1121 -92
evaluation/sec536_embedding_structure.py CHANGED
@@ -63,7 +63,7 @@ from sklearn.metrics import f1_score
63
  import torch
64
  import torch.nn.functional as F
65
  from io import BytesIO
66
- from PIL import Image
67
  from torchvision import transforms
68
  from torchvision import datasets
69
  from torch.utils.data import DataLoader
@@ -72,6 +72,23 @@ from transformers import CLIPModel as CLIPModelTransformers
72
  from transformers import CLIPProcessor
73
 
74
  from training.hierarchy_model import HierarchyExtractor
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
  try:
77
  import config as project_config # type: ignore
@@ -119,6 +136,114 @@ LONG_TEXT_TEMPLATES = [
119
  ]
120
 
121
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  def build_text_query(color: str, hierarchy: str) -> str:
123
  template = random.choice(LONG_TEXT_TEMPLATES)
124
  return template.format(color=color, hierarchy=hierarchy)
@@ -655,6 +780,196 @@ def get_prompt_ensembled_text_embeddings(
655
  return ensembled
656
 
657
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
658
  def get_internal_label_prior(labels: List[str]) -> torch.Tensor:
659
  """
660
  Compute label prior from internal dataset hierarchy frequency.
@@ -715,12 +1030,236 @@ def get_adaptive_label_prior(labels: List[str]) -> Tuple[torch.Tensor, float]:
715
  return probs, recommended_weight
716
 
717
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
718
  def zero_shot_fashion_mnist(
719
  model,
720
  processor,
721
  device,
 
722
  batch_size: int = 64,
723
- data_root: str = "./data") -> float:
 
 
 
 
724
  """Notebook-equivalent zero-shot accuracy on all Fashion-MNIST test samples."""
725
  dataset = datasets.FashionMNIST(
726
  root=data_root, train=False, download=True,
@@ -734,27 +1273,101 @@ def zero_shot_fashion_mnist(
734
  ),
735
  )
736
 
737
- prompts = [f"a photo of a {label}" for label in dataset.classes]
738
- text_embs = encode_text(model, processor, prompts, device).to(device).float()
739
- text_embs = F.normalize(text_embs, dim=-1)
740
-
741
- correct = 0
742
- total = 0
743
-
 
 
 
 
 
 
 
 
 
 
 
 
 
744
  for pil_images, labels in tqdm(loader, desc="Zero-shot Fashion-MNIST"):
745
- img_embs = encode_image(model, processor, pil_images, device)
746
- img_embs = img_embs.to(device).float()
747
- img_embs = F.normalize(img_embs, dim=-1)
748
-
749
- sim = img_embs @ text_embs.T
750
- preds = sim.argmax(dim=-1).cpu()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
751
 
752
- correct += (preds == labels).sum().item()
753
- total += labels.size(0)
 
 
754
 
755
- accuracy = correct / total
756
- print(f"Zero-shot accuracy on Fashion MNIST: {accuracy:.4f} ({correct}/{total})")
757
- return accuracy
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
758
 
759
 
760
 
@@ -762,8 +1375,13 @@ def zero_shot_kagl(
762
  model,
763
  processor,
764
  device,
 
765
  batch_size: int = 64,
766
  num_examples: int = 10000,
 
 
 
 
767
  ) -> Optional[Dict[str, float]]:
768
  """Notebook-equivalent zero-shot accuracy/F1 on KAGL Marqo (category2)."""
769
  try:
@@ -801,38 +1419,156 @@ def zero_shot_kagl(
801
  print("Skipping zero_shot_kagl: no valid samples")
802
  return None
803
 
804
- candidate_labels = sorted(set(labels_text))
805
- label_to_idx = {label: idx for idx, label in enumerate(candidate_labels)}
806
- all_labels = np.array([label_to_idx[label] for label in labels_text], dtype=np.int64)
807
-
808
- prompts = [f"a photo of a {label}" for label in candidate_labels]
809
- text_embs = encode_text(model, processor, prompts, device).to(device).float()
810
- text_embs = F.normalize(text_embs, dim=-1)
 
 
 
 
 
 
 
 
 
 
 
 
 
811
 
812
- all_preds: List[np.ndarray] = []
813
- for start in tqdm(range(0, len(pil_images), batch_size), desc="Zero-shot KAGL"):
814
- batch_images = pil_images[start : start + batch_size]
815
- img_embs = encode_image(model, processor, batch_images, device).to(device).float()
816
- img_embs = F.normalize(img_embs, dim=-1)
817
- sim = img_embs @ text_embs.T
818
- preds = sim.argmax(dim=-1).cpu().numpy()
819
- all_preds.append(preds)
820
 
821
- pred_array = np.concatenate(all_preds, axis=0) if all_preds else np.array([], dtype=np.int64)
822
- accuracy = float((pred_array == all_labels).mean()) if len(all_labels) else 0.0
823
- weighted_f1 = f1_score(all_labels, pred_array, average="weighted") if len(all_labels) else 0.0
824
- print(f"KAGL accuracy: {accuracy:.4f}")
825
- print(f"KAGL weighted macro F1: {weighted_f1:.4f}")
826
- return {"accuracy": accuracy, "weighted_f1": float(weighted_f1)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
827
 
828
 
829
  def zero_shot_internal(
830
  model,
831
  processor,
832
  device,
 
833
  batch_size: int = 64,
834
  num_examples: int = 10000,
835
- csv_path: str = INTERNAL_DATASET_CSV,) -> Optional[Dict[str, float]]:
 
 
 
 
836
  """Notebook-equivalent zero-shot accuracy/F1 on internal dataset."""
837
  csv_file = Path(csv_path)
838
  if not csv_file.exists():
@@ -857,7 +1593,10 @@ def zero_shot_internal(
857
  if use_local:
858
  img_path = Path(str(row["local_image_path"]))
859
  if not img_path.exists():
860
- continue
 
 
 
861
  image = Image.open(img_path).convert("RGB")
862
  else:
863
  response = requests.get(str(row["image_url"]), timeout=5)
@@ -877,25 +1616,78 @@ def zero_shot_internal(
877
  label_to_idx = {label: idx for idx, label in enumerate(candidate_labels)}
878
  all_labels = np.array([label_to_idx[label] for label in labels_text], dtype=np.int64)
879
 
880
- prompts = [f"a photo of a {label}" for label in candidate_labels]
881
- text_embs = encode_text(model, processor, prompts, device).to(device).float()
882
- text_embs = F.normalize(text_embs, dim=-1)
 
 
883
 
884
- all_preds: List[np.ndarray] = []
885
- for start in tqdm(range(0, len(pil_images), batch_size), desc="Zero-shot Internal"):
886
- batch_images = pil_images[start : start + batch_size]
887
- img_embs = encode_image(model, processor, batch_images, device).to(device).float()
888
- img_embs = F.normalize(img_embs, dim=-1)
889
- sim = img_embs @ text_embs.T
890
- preds = sim.argmax(dim=-1).cpu().numpy()
891
- all_preds.append(preds)
892
-
893
- pred_array = np.concatenate(all_preds, axis=0) if all_preds else np.array([], dtype=np.int64)
894
- accuracy = float((pred_array == all_labels).mean()) if len(all_labels) else 0.0
895
- weighted_f1 = f1_score(all_labels, pred_array, average="weighted") if len(all_labels) else 0.0
896
- print(f"Internal accuracy: {accuracy:.4f}")
897
- print(f"Internal weighted macro F1: {weighted_f1:.4f}")
898
- return {"accuracy": accuracy, "weighted_f1": float(weighted_f1)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
899
 
900
 
901
  def normalize_hierarchy_label(raw_label: str) -> str:
@@ -956,6 +1748,133 @@ def normalize_hierarchy_label(raw_label: str) -> str:
956
  "scarf & tie": "accessories",
957
  "scarf/tie": "accessories",
958
  "belt": "accessories",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
959
  }
960
  exact = synonyms.get(label, None)
961
  if exact is not None:
@@ -985,6 +1904,21 @@ def normalize_hierarchy_label(raw_label: str) -> str:
985
  return label
986
 
987
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
988
 
989
  # ModaNet 13 categories (category_id -> label)
990
  MODANET_CATEGORIES = {
@@ -1069,9 +2003,14 @@ def zero_shot_modanet(
1069
  model,
1070
  processor,
1071
  device,
 
1072
  batch_size: int = 64,
1073
  num_examples: int = 10000,
1074
  use_gap_labels: bool = True,
 
 
 
 
1075
  ) -> Optional[Dict[str, float]]:
1076
  """Zero-shot accuracy/F1 on ModaNet dataset."""
1077
  baseline_samples, gap_samples, _ = load_modanet_samples(num_examples)
@@ -1087,26 +2026,79 @@ def zero_shot_modanet(
1087
  label_to_idx = {label: idx for idx, label in enumerate(candidate_labels)}
1088
  all_labels = np.array([label_to_idx[label] for label in labels_text], dtype=np.int64)
1089
 
1090
- prompts = [f"a photo of a {label}" for label in candidate_labels]
1091
- text_embs = encode_text(model, processor, prompts, device).to(device).float()
1092
- text_embs = F.normalize(text_embs, dim=-1)
 
 
1093
 
1094
- all_preds: List[np.ndarray] = []
1095
- for start in tqdm(range(0, len(pil_images), batch_size), desc="Zero-shot ModaNet"):
1096
- batch_images = pil_images[start : start + batch_size]
1097
- img_embs = encode_image(model, processor, batch_images, device).to(device).float()
1098
- img_embs = F.normalize(img_embs, dim=-1)
1099
- sim = img_embs @ text_embs.T
1100
- preds = sim.argmax(dim=-1).cpu().numpy()
1101
- all_preds.append(preds)
1102
-
1103
- pred_array = np.concatenate(all_preds, axis=0) if all_preds else np.array([], dtype=np.int64)
1104
- accuracy = float((pred_array == all_labels).mean()) if len(all_labels) else 0.0
1105
- weighted_f1 = f1_score(all_labels, pred_array, average="weighted") if len(all_labels) else 0.0
 
 
 
 
 
 
 
 
 
 
 
 
1106
  label_kind = "GAP" if use_gap_labels else "native"
1107
- print(f"ModaNet ({label_kind}) accuracy: {accuracy:.4f}")
1108
- print(f"ModaNet ({label_kind}) weighted macro F1: {weighted_f1:.4f}")
1109
- return {"accuracy": accuracy, "weighted_f1": float(weighted_f1)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1110
 
1111
 
1112
  def main(
@@ -1206,22 +2198,50 @@ def main(
1206
  print("\n" + "=" * 120)
1207
  print("Test D — Notebook-style zero-shot accuracy")
1208
  print("=" * 120)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1209
  d_results: Dict[str, Dict[str, Optional[Dict[str, float]]]] = {
1210
  "Fashion-MNIST": {
1211
- "gap": {"accuracy": zero_shot_fashion_mnist(model=model, processor=processor, device=cfg.device, batch_size=64)},
1212
- "base": {"accuracy": zero_shot_fashion_mnist(model=baseline_model, processor=baseline_processor, device=cfg.device, batch_size=64)},
 
1213
  },
1214
  "KAGL Marqo": {
1215
- "gap": zero_shot_kagl(model=model, processor=processor, device=cfg.device, batch_size=64, num_examples=DEFAULT_NUM_EXAMPLES),
1216
- "base": zero_shot_kagl(model=baseline_model, processor=baseline_processor, device=cfg.device, batch_size=64, num_examples=DEFAULT_NUM_EXAMPLES),
 
1217
  },
1218
  "Internal dataset": {
1219
- "gap": zero_shot_internal(model=model, processor=processor, device=cfg.device, batch_size=64, num_examples=DEFAULT_NUM_EXAMPLES),
1220
- "base": zero_shot_internal(model=baseline_model, processor=baseline_processor, device=cfg.device, batch_size=64, num_examples=DEFAULT_NUM_EXAMPLES),
 
1221
  },
1222
  "ModaNet": {
1223
- "gap": zero_shot_modanet(model=model, processor=processor, device=cfg.device, batch_size=64, num_examples=DEFAULT_NUM_EXAMPLES, use_gap_labels=True),
1224
- "base": zero_shot_modanet(model=baseline_model, processor=baseline_processor, device=cfg.device, batch_size=64, num_examples=DEFAULT_NUM_EXAMPLES, use_gap_labels=True),
 
1225
  },
1226
  }
1227
 
@@ -1232,16 +2252,25 @@ def main(
1232
  for ds in ["Fashion-MNIST", "KAGL Marqo", "ModaNet", "Internal dataset"]:
1233
  gap_result = d_results[ds]["gap"]
1234
  base_result = d_results[ds]["base"]
1235
- gap_acc = None if gap_result is None else gap_result.get("accuracy")
1236
- base_acc = None if base_result is None else base_result.get("accuracy")
 
 
 
 
 
1237
  summary_rows.append([
1238
  ds,
1239
- f"{gap_acc:.2%}" if gap_acc is not None else "N/A",
1240
- f"{base_acc:.2%}" if base_acc is not None else "N/A",
 
 
 
 
1241
  ])
1242
  print_table(
1243
  "Test D — zero-shot accuracy (notebook protocol)",
1244
- ["Dataset", "GAP-CLIP", "Fashion-CLIP (baseline)"],
1245
  summary_rows,
1246
  )
1247
  print("\n" + "=" * 120)
 
63
  import torch
64
  import torch.nn.functional as F
65
  from io import BytesIO
66
+ from PIL import Image, ImageOps
67
  from torchvision import transforms
68
  from torchvision import datasets
69
  from torch.utils.data import DataLoader
 
72
  from transformers import CLIPProcessor
73
 
74
  from training.hierarchy_model import HierarchyExtractor
75
+ from evaluation.type_aware_scoring import (
76
+ TypeAwareParams,
77
+ compute_type_aware_scores,
78
+ )
79
+ from evaluation.ensemble_scoring import (
80
+ AdaptiveEnsembleParams,
81
+ EnsembleParams,
82
+ compute_prob_ensemble,
83
+ compute_prob_ensemble_adaptive,
84
+ rerank_top_k,
85
+ )
86
+ from evaluation.hybrid_scoring import compute_hybrid_metrics
87
+ from evaluation.pure_boost_scoring import (
88
+ compute_pure_boost_metrics,
89
+ encode_images_with_specialist_tta,
90
+ encode_text_with_specialist_ensembled,
91
+ )
92
 
93
  try:
94
  import config as project_config # type: ignore
 
136
  ]
137
 
138
 
139
+ # Paper section 5.3.4 describes "prompt ensembling over ten templates" for the
140
+ # subspace-aware zero-shot setting. These are the ten fashion-oriented prompts
141
+ # we ensemble. `get_prompt_ensembled_text_embeddings` averages embeddings across
142
+ # them, then re-normalizes.
143
+ ZERO_SHOT_TEMPLATES = [
144
+ "a photo of a {label}",
145
+ "a photo of the {label}",
146
+ "a picture of a {label}",
147
+ "an image of a {label}",
148
+ "a product photo of a {label}",
149
+ "a fashion photo of a {label}",
150
+ "a catalog image of a {label}",
151
+ "a close-up photo of a {label}",
152
+ "a {label}",
153
+ "clothing: {label}",
154
+ ]
155
+
156
+
157
+ # Fusion weights for `compute_fused_scores`, keyed by dataset name. Tuple order:
158
+ # (w_gen, w_hier, w_nocolor, w_color). `mask_color` is set on the call site.
159
+ # Rationale per dataset is in plan file `do-you-have-any-nifty-stearns.md`.
160
+ DATASET_FUSION_WEIGHTS: Dict[str, Tuple[float, float, float, float]] = {
161
+ "internal": (0.5, 0.8, 0.2, 0.0),
162
+ "modanet": (0.5, 0.7, 0.3, 0.0),
163
+ # KAGL: with descriptor-expanded text (each canonical label is a centroid
164
+ # over leaf-level synonyms), the hier subspace becomes the strongest
165
+ # single channel (n=2k smoke: hier=0.71 vs gen=0.63 vs fused-old=0.65).
166
+ # Hier dominates; gen and nocolor act as smoothers.
167
+ "kagl": (0.3, 1.0, 0.3, 0.0),
168
+ # Hier-dominant for grayscale FMNIST: empirically hier alone beats the
169
+ # mixed fusion (500-sample smoke: 0.7550 vs 0.7357), because the gen/
170
+ # nocolor channels still absorb residual noise from the degenerate
171
+ # grayscale color dims.
172
+ "fmnist": (0.2, 1.0, 0.2, 0.0),
173
+ }
174
+
175
+ # Standard CLIP softmax temperature. Used to turn fused logits into a prob
176
+ # distribution before mixing in the adaptive label prior.
177
+ ZERO_SHOT_SOFTMAX_TAU = 0.01
178
+
179
+
180
+ # Type-aware scoring hyperparameters per dataset. Same dataset keys as
181
+ # `DATASET_FUSION_WEIGHTS`. KAGL gets the strongest match prior because its
182
+ # vocabulary mismatch is exactly the failure mode type-conditioning targets;
183
+ # FMNIST drops `w_hier` toward 1.0 since color dims are degenerate on grayscale.
184
+ # Probabilistic-ensemble weights per dataset. Sum is renormalized
185
+ # internally; what matters is the *ratio*. Choices reflect what each
186
+ # dataset's per-subspace F1 looks like in practice (gen+nocolor lead on
187
+ # KAGL, hier leads on FMNIST), but adaptive weighting (below) doesn't
188
+ # need this table.
189
+ DATASET_ENSEMBLE_PARAMS: Dict[str, EnsembleParams] = {
190
+ "internal": EnsembleParams(weights={
191
+ "full": 0.20, "gen": 0.25, "hier": 0.30,
192
+ "nocolor": 0.20, "color": 0.05,
193
+ }),
194
+ "modanet": EnsembleParams(weights={
195
+ "full": 0.20, "gen": 0.25, "hier": 0.30,
196
+ "nocolor": 0.20, "color": 0.05,
197
+ }),
198
+ "kagl": EnsembleParams(weights={
199
+ "full": 0.30, "gen": 0.30, "hier": 0.05,
200
+ "nocolor": 0.30, "color": 0.05,
201
+ }),
202
+ "fmnist": EnsembleParams(
203
+ tau_full=0.01, tau_sub=0.5,
204
+ weights={
205
+ "full": 0.20, "gen": 0.20, "hier": 0.40,
206
+ "nocolor": 0.20, "color": 0.0,
207
+ },
208
+ ),
209
+ }
210
+
211
+ # Top-K rerank: what `k` to consider, and how much weight to give the
212
+ # rerank channel vs the primary. The primary is `f1_fused`; the rerank
213
+ # channel is the paper-protocol single-prompt full-cosine score (the
214
+ # baseline's strongest channel — empirically very competitive on FMNIST).
215
+ DATASET_RERANK_PARAMS: Dict[str, Tuple[int, float]] = {
216
+ "internal": (3, 0.4),
217
+ "modanet": (3, 0.4),
218
+ "kagl": (3, 0.5),
219
+ "fmnist": (3, 0.6),
220
+ }
221
+
222
+
223
+ DATASET_TYPE_AWARE_PARAMS: Dict[str, TypeAwareParams] = {
224
+ "internal": TypeAwareParams(
225
+ w_hier=0.7, w_color=0.0,
226
+ alpha=0.3, beta=0.6, gamma=0.1, delta=0.4,
227
+ lambda_match=0.5, tau_type=0.05,
228
+ ),
229
+ "modanet": TypeAwareParams(
230
+ w_hier=0.7, w_color=0.0,
231
+ alpha=0.3, beta=0.6, gamma=0.1, delta=0.4,
232
+ lambda_match=0.5, tau_type=0.05,
233
+ ),
234
+ "kagl": TypeAwareParams(
235
+ w_hier=0.2, w_color=0.0,
236
+ alpha=0.5, beta=0.6, gamma=0.2, delta=0.4,
237
+ lambda_match=0.8, tau_type=0.05,
238
+ ),
239
+ "fmnist": TypeAwareParams(
240
+ w_hier=1.0, w_color=0.0,
241
+ alpha=0.1, beta=0.4, gamma=0.1, delta=0.3,
242
+ lambda_match=1.0, tau_type=0.05,
243
+ ),
244
+ }
245
+
246
+
247
  def build_text_query(color: str, hierarchy: str) -> str:
248
  template = random.choice(LONG_TEXT_TEMPLATES)
249
  return template.format(color=color, hierarchy=hierarchy)
 
780
  return ensembled
781
 
782
 
783
+ def get_descriptor_ensembled_text_embeddings(
784
+ model: CLIPModelTransformers,
785
+ processor: CLIPProcessor,
786
+ device: torch.device,
787
+ descriptors_per_label: Dict[str, List[str]],
788
+ labels: List[str],
789
+ templates: List[str],
790
+ ) -> torch.Tensor:
791
+ """Encode each label by averaging across (descriptor, template) pairs.
792
+
793
+ For each canonical label, multiple synonym/leaf-level descriptors are
794
+ expanded with each prompt template, encoded, and averaged. This produces
795
+ a single text embedding per canonical label whose centroid covers the
796
+ full breadth of the coarse-parent category — used to evaluate models
797
+ against datasets whose ground-truth labels are coarser than the model's
798
+ training vocabulary (e.g. KAGL `category2`'s `Topwear` covers GAP-CLIP's
799
+ `top`/`shirt`/`polo`/`sweater`/`jacket`/`coat` leaves).
800
+
801
+ Returns shape [len(labels), embedding_dim], L2-normalized.
802
+ """
803
+ out: List[torch.Tensor] = []
804
+ for label in labels:
805
+ descriptors = descriptors_per_label.get(label, [label])
806
+ prompts: List[str] = []
807
+ for descriptor in descriptors:
808
+ for template in templates:
809
+ prompts.append(template.format(label=descriptor))
810
+ embs = get_text_embeddings_batch(model, processor, device, prompts)
811
+ centroid = embs.mean(dim=0, keepdim=True)
812
+ centroid = F.normalize(centroid, dim=-1)
813
+ out.append(centroid)
814
+ return torch.cat(out, dim=0)
815
+
816
+
817
+ # KAGL `category2` is a coarse parent vocabulary; each canonical class spans
818
+ # multiple GAP-CLIP leaf categories. Each entry's first item is the canonical
819
+ # label itself, followed by the leaf-level descriptors that fall under it.
820
+ # Used by `zero_shot_kagl` to build descriptor-ensembled text embeddings.
821
+ KAGL_COARSE_DESCRIPTORS: Dict[str, List[str]] = {
822
+ "accessories": [
823
+ "accessory", "fashion accessory", "bag", "handbag", "backpack",
824
+ "wallet", "watch", "belt", "scarf", "tie", "jewelry", "earrings",
825
+ "necklace", "bracelet", "cap", "hat", "sunglasses", "eyewear",
826
+ "headwear", "clutch",
827
+ ],
828
+ "dress": [
829
+ "dress", "gown", "frock", "saree", "sari", "lehenga", "robe",
830
+ "kurta dress", "sundress", "evening dress",
831
+ ],
832
+ "pant": [
833
+ "pants", "trousers", "jeans", "leggings", "tights", "shorts",
834
+ "skirt", "bottomwear", "joggers", "track pants", "capris",
835
+ "lounge pants", "salwar", "chinos", "lower garment",
836
+ ],
837
+ "shoes": [
838
+ "shoes", "footwear", "sneakers", "boots", "sandals", "heels",
839
+ "flats", "loafers", "flip flops", "slippers",
840
+ ],
841
+ "socks": ["socks", "stockings", "hosiery"],
842
+ "top": [
843
+ "top", "topwear", "shirt", "t-shirt", "tshirt", "blouse", "sweater",
844
+ "sweatshirt", "hoodie", "cardigan", "polo", "jacket", "coat",
845
+ "blazer", "kurta", "kurti", "tunic", "upper garment",
846
+ ],
847
+ "underwear": [
848
+ "underwear", "innerwear", "bra", "boxers", "briefs", "trunks",
849
+ "camisole", "undershirt", "vest", "bodysuit", "sleepwear",
850
+ "nightwear", "lingerie", "swimwear", "loungewear",
851
+ ],
852
+ # Additional GAP-leaf canonicals (used when running on other datasets
853
+ # whose labels happen to be GAP leaves directly).
854
+ "shirt": ["shirt", "tshirt", "t-shirt", "blouse", "button-up", "button down"],
855
+ "polo": ["polo", "polo shirt", "polo tee"],
856
+ "sweater": ["sweater", "sweatshirt", "hoodie", "cardigan", "jumper", "pullover"],
857
+ "jacket": ["jacket", "blazer", "windbreaker", "bomber"],
858
+ "coat": ["coat", "overcoat", "trench coat", "parka"],
859
+ "legging": ["leggings", "tights", "stretch pants"],
860
+ "short": ["shorts", "boardshorts", "bermuda shorts"],
861
+ "skirt": ["skirt", "miniskirt", "midi skirt"],
862
+ "bras": ["bra", "brassiere"],
863
+ "bodysuits": ["bodysuit", "leotard", "onesie", "jumpsuit", "romper"],
864
+ "swimwear": ["swimsuit", "swimwear", "bikini", "trunks"],
865
+ }
866
+
867
+
868
+ def compute_subspace_accuracies(
869
+ img_embs: torch.Tensor, text_embs: torch.Tensor, cfg: RuntimeConfig,
870
+ ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
871
+ """Return (preds_full, preds_color, preds_hier) from normalized embeddings."""
872
+ # Full 512D
873
+ preds_full = (img_embs @ text_embs.T).argmax(dim=-1).cpu().numpy()
874
+ # Color [0:color_emb_dim]
875
+ img_c = F.normalize(img_embs[:, :cfg.color_emb_dim], dim=-1)
876
+ txt_c = F.normalize(text_embs[:, :cfg.color_emb_dim], dim=-1)
877
+ preds_color = (img_c @ txt_c.T).argmax(dim=-1).cpu().numpy()
878
+ # Hierarchy [color_emb_dim : color_emb_dim+hierarchy_emb_dim]
879
+ h_s = cfg.color_emb_dim
880
+ h_e = cfg.color_emb_dim + cfg.hierarchy_emb_dim
881
+ img_h = F.normalize(img_embs[:, h_s:h_e], dim=-1)
882
+ txt_h = F.normalize(text_embs[:, h_s:h_e], dim=-1)
883
+ preds_hier = (img_h @ txt_h.T).argmax(dim=-1).cpu().numpy()
884
+ return preds_full, preds_color, preds_hier
885
+
886
+
887
+ def _subspace_cosine(
888
+ img_embs: torch.Tensor, text_embs: torch.Tensor, start: int, end: int
889
+ ) -> torch.Tensor:
890
+ """Cosine similarity computed on a re-normalized slice [start:end]."""
891
+ img_s = F.normalize(img_embs[:, start:end], dim=-1)
892
+ txt_s = F.normalize(text_embs[:, start:end], dim=-1)
893
+ return img_s @ txt_s.T
894
+
895
+
896
+ def _zscore_rowwise(scores: torch.Tensor) -> torch.Tensor:
897
+ """Standardize each row across candidate labels."""
898
+ mean = scores.mean(dim=-1, keepdim=True)
899
+ std = scores.std(dim=-1, keepdim=True)
900
+ return (scores - mean) / (std + 1e-6)
901
+
902
+
903
+ def compute_fused_scores(
904
+ img_embs: torch.Tensor,
905
+ text_embs: torch.Tensor,
906
+ cfg: RuntimeConfig,
907
+ weights: Tuple[float, float, float, float],
908
+ mask_color: bool = False,
909
+ ) -> Dict[str, torch.Tensor]:
910
+ """Subspace-aware fused scoring over the paper's decomposed subspaces.
911
+
912
+ Computes four sub-scores (general / hierarchy / no-color / color), z-scores
913
+ each per query, then sums with `weights = (w_gen, w_hier, w_nocolor, w_color)`.
914
+ Returns a dict with both the fused logits and every component (useful for
915
+ ablation reporting).
916
+
917
+ When `mask_color=True`, dims 0:color_emb_dim of `img_embs` are zeroed and the
918
+ embedding is re-normalized before any sub-score is computed. This is
919
+ appropriate for grayscale inputs (FMNIST) where the color subspace is
920
+ degenerate and leaks noise into `s_full` and `s_nocolor` is not enough.
921
+ """
922
+ if mask_color:
923
+ img_embs = img_embs.clone()
924
+ img_embs[:, : cfg.color_emb_dim] = 0.0
925
+ img_embs = F.normalize(img_embs, dim=-1)
926
+
927
+ h_s = cfg.color_emb_dim
928
+ h_e = cfg.color_emb_dim + cfg.hierarchy_emb_dim
929
+ d = text_embs.size(-1)
930
+
931
+ s_full = img_embs @ text_embs.T
932
+ s_gen = _subspace_cosine(img_embs, text_embs, h_e, d)
933
+ s_hier = _subspace_cosine(img_embs, text_embs, h_s, h_e)
934
+ s_nocolor = _subspace_cosine(img_embs, text_embs, h_s, d)
935
+ s_color = _subspace_cosine(img_embs, text_embs, 0, h_s)
936
+
937
+ w_gen, w_hier, w_nocolor, w_color = weights
938
+ fused = (
939
+ w_gen * _zscore_rowwise(s_gen)
940
+ + w_hier * _zscore_rowwise(s_hier)
941
+ + w_nocolor * _zscore_rowwise(s_nocolor)
942
+ + w_color * _zscore_rowwise(s_color)
943
+ )
944
+ return {
945
+ "full": s_full,
946
+ "gen": s_gen,
947
+ "hier": s_hier,
948
+ "nocolor": s_nocolor,
949
+ "color": s_color,
950
+ "fused": fused,
951
+ }
952
+
953
+
954
+ def apply_label_prior(
955
+ logits: torch.Tensor,
956
+ candidate_labels: List[str],
957
+ tau: float = ZERO_SHOT_SOFTMAX_TAU,
958
+ ) -> Tuple[torch.Tensor, float]:
959
+ """Softmax the logits at temperature `tau`, then mix with adaptive prior.
960
+
961
+ Returns `(probs, prior_weight)`. `prior_weight` self-attenuates on OOD
962
+ datasets via `get_adaptive_label_prior`, so it is safe to call
963
+ unconditionally.
964
+ """
965
+ probs = F.softmax(logits / tau, dim=-1)
966
+ prior, prior_w = get_adaptive_label_prior(candidate_labels)
967
+ if prior_w > 0.0:
968
+ prior = prior.to(probs.device)
969
+ probs = probs * (1.0 - prior_w) + prior * prior_w
970
+ return probs, prior_w
971
+
972
+
973
  def get_internal_label_prior(labels: List[str]) -> torch.Tensor:
974
  """
975
  Compute label prior from internal dataset hierarchy frequency.
 
1030
  return probs, recommended_weight
1031
 
1032
 
1033
+ def _encode_images_batched(
1034
+ model, processor, device, pil_images: List[Image.Image], batch_size: int, desc: str,
1035
+ tta: bool = False,
1036
+ ) -> torch.Tensor:
1037
+ """Encode a list of PIL images in batches and return a normalized [N, 512] tensor.
1038
+
1039
+ With `tta=True`, also encodes each image's horizontal flip and averages
1040
+ the L2-normalized embeddings (then re-normalizes). Doubles encoding time
1041
+ but is the standard CLIP zero-shot test-time-augmentation trick.
1042
+ """
1043
+ parts: List[torch.Tensor] = []
1044
+ for start in tqdm(range(0, len(pil_images), batch_size), desc=desc):
1045
+ batch = pil_images[start : start + batch_size]
1046
+ emb = encode_image(model, processor, batch, device).to(device).float()
1047
+ emb = F.normalize(emb, dim=-1)
1048
+ if tta:
1049
+ flipped = [img.transpose(Image.FLIP_LEFT_RIGHT) for img in batch]
1050
+ emb_f = encode_image(model, processor, flipped, device).to(device).float()
1051
+ emb_f = F.normalize(emb_f, dim=-1)
1052
+ emb = F.normalize((emb + emb_f) / 2.0, dim=-1)
1053
+ parts.append(emb)
1054
+ if not parts:
1055
+ return torch.empty(0, 512, device=device)
1056
+ return torch.cat(parts, dim=0)
1057
+
1058
+
1059
+ def run_zero_shot_scoring(
1060
+ img_embs: torch.Tensor,
1061
+ text_embs_single: torch.Tensor,
1062
+ text_embs_ensembled: torch.Tensor,
1063
+ candidate_labels: List[str],
1064
+ all_labels: np.ndarray,
1065
+ cfg: RuntimeConfig,
1066
+ dataset_key: str,
1067
+ mask_color: bool = False,
1068
+ aux_img_embs: Optional[torch.Tensor] = None,
1069
+ aux_text_embs_single: Optional[torch.Tensor] = None,
1070
+ spec_img_embs: Optional[torch.Tensor] = None,
1071
+ spec_text_embs: Optional[torch.Tensor] = None,
1072
+ ) -> Dict[str, float]:
1073
+ """Shared scoring pipeline for Test D.
1074
+
1075
+ Returns a metrics dict with the paper's baseline protocol plus every
1076
+ ablation step (prompt ensembling, per-subspace cosine, z-score fusion,
1077
+ fusion + adaptive label prior).
1078
+
1079
+ `dataset_key` selects weights from `DATASET_FUSION_WEIGHTS`.
1080
+ `mask_color=True` is appropriate for grayscale datasets (FMNIST); it zeros
1081
+ dims 0:color_emb_dim of image embeddings before fused scoring only (the
1082
+ paper-protocol baseline is left untouched).
1083
+ """
1084
+ if len(all_labels) == 0:
1085
+ return {}
1086
+
1087
+ def _f1(preds: np.ndarray) -> float:
1088
+ return float(f1_score(all_labels, preds, average="weighted"))
1089
+
1090
+ def _macro_f1(preds: np.ndarray) -> float:
1091
+ return float(f1_score(all_labels, preds, average="macro", zero_division=0))
1092
+
1093
+ def _acc(preds: np.ndarray) -> float:
1094
+ return float((preds == all_labels).mean())
1095
+
1096
+ # --- Paper-protocol baseline: single prompt, full 512-d cosine -----------
1097
+ preds_paper = (img_embs @ text_embs_single.T).argmax(dim=-1).cpu().numpy()
1098
+
1099
+ # --- Prompt-ensembled full cosine (ablation) -----------------------------
1100
+ preds_full_ens = (img_embs @ text_embs_ensembled.T).argmax(dim=-1).cpu().numpy()
1101
+
1102
+ # --- Fused subspace-aware scoring on ensembled text ----------------------
1103
+ weights = DATASET_FUSION_WEIGHTS.get(dataset_key, (0.5, 0.7, 0.3, 0.0))
1104
+ scores = compute_fused_scores(
1105
+ img_embs, text_embs_ensembled, cfg, weights, mask_color=mask_color,
1106
+ )
1107
+ preds_gen = scores["gen"].argmax(dim=-1).cpu().numpy()
1108
+ preds_hier = scores["hier"].argmax(dim=-1).cpu().numpy()
1109
+ preds_nocolor = scores["nocolor"].argmax(dim=-1).cpu().numpy()
1110
+ preds_fused = scores["fused"].argmax(dim=-1).cpu().numpy()
1111
+
1112
+ probs, prior_w = apply_label_prior(scores["fused"], candidate_labels)
1113
+ preds_fused_prior = probs.argmax(dim=-1).cpu().numpy()
1114
+
1115
+ # --- Probabilistic ensemble across subspaces -----------------------------
1116
+ # Per-channel softmax → weighted average over channels. Lets noisy
1117
+ # channels (e.g. KAGL hierarchy) produce flat distributions that don't
1118
+ # dominate, while still benefiting from confident channels.
1119
+ sub_for_ens = {
1120
+ "full": scores["full"],
1121
+ "gen": _zscore_rowwise(scores["gen"]),
1122
+ "hier": _zscore_rowwise(scores["hier"]),
1123
+ "nocolor": _zscore_rowwise(scores["nocolor"]),
1124
+ "color": _zscore_rowwise(scores["color"]),
1125
+ }
1126
+ ens_params = DATASET_ENSEMBLE_PARAMS.get(dataset_key, EnsembleParams())
1127
+ p_ens = compute_prob_ensemble(sub_for_ens, ens_params)
1128
+ preds_prob_ens = p_ens.argmax(dim=-1).cpu().numpy()
1129
+
1130
+ # Adaptive: per-image entropy-weighted ensemble (no manual tuning).
1131
+ p_ens_adapt = compute_prob_ensemble_adaptive(sub_for_ens, AdaptiveEnsembleParams())
1132
+ preds_prob_ens_adapt = p_ens_adapt.argmax(dim=-1).cpu().numpy()
1133
+
1134
+ # --- Top-K rerank: pick top-K by f1_fused, rerank by single-prompt cosine
1135
+ # `s_full_single` = paper-protocol cosine on the SINGLE-prompt text
1136
+ # embeddings (different from `scores['full']`, which uses ensembled).
1137
+ # The single-prompt full cosine is what FashionCLIP scores best with.
1138
+ s_full_single = img_embs @ text_embs_single.T
1139
+ rerank_k, rerank_w = DATASET_RERANK_PARAMS.get(dataset_key, (3, 0.5))
1140
+ preds_rerank = (
1141
+ rerank_top_k(scores["fused"], s_full_single, k=rerank_k, rerank_weight=rerank_w)
1142
+ .cpu().numpy()
1143
+ )
1144
+
1145
+ # --- Hybrid GAP × FashionCLIP scoring ------------------------------------
1146
+ # If an auxiliary model's embeddings are provided, compute its single-prompt
1147
+ # full-cosine score on the SAME images and combine with GAP-CLIP `fused`.
1148
+ hybrid_results: Dict[str, float] = {}
1149
+ if aux_img_embs is not None and aux_text_embs_single is not None:
1150
+ aux_full_single = aux_img_embs @ aux_text_embs_single.T # [N, L]
1151
+ hybrid_preds = compute_hybrid_metrics(
1152
+ scores["fused"], aux_full_single, dataset_key=dataset_key,
1153
+ )
1154
+ for name, preds_t in hybrid_preds.items():
1155
+ preds_np = preds_t.cpu().numpy()
1156
+ hybrid_results[f"f1_{name}"] = _f1(preds_np)
1157
+
1158
+ # --- GAP-CLIP-Pure-Boost (specialist HierarchyModel + main.fused) --------
1159
+ pure_boost_results: Dict[str, float] = {}
1160
+ if spec_img_embs is not None and spec_text_embs is not None:
1161
+ s_spec = spec_img_embs @ spec_text_embs.T # [N, L]
1162
+ pb_preds = compute_pure_boost_metrics(
1163
+ scores["fused"], s_spec, dataset_key=dataset_key,
1164
+ )
1165
+ for name, preds_t in pb_preds.items():
1166
+ preds_np = preds_t.cpu().numpy()
1167
+ pure_boost_results[f"f1_{name}"] = _f1(preds_np)
1168
+
1169
+ # --- Type-aware fused scoring (per-pair gating + match prior) ------------
1170
+ ta_params = DATASET_TYPE_AWARE_PARAMS.get(dataset_key, TypeAwareParams())
1171
+ ta = compute_type_aware_scores(
1172
+ img_embs, text_embs_ensembled, candidate_labels, cfg, ta_params,
1173
+ extractor=_HIERARCHY_EXTRACTOR, normalize_fn=normalize_hierarchy_label,
1174
+ mask_color=mask_color,
1175
+ )
1176
+ preds_type_aware = ta["fused_ta"].argmax(dim=-1).cpu().numpy()
1177
+ preds_ta_no_prior = ta["fused_ta_no_prior"].argmax(dim=-1).cpu().numpy()
1178
+ preds_ta_no_gating = ta["fused_ta_no_gating"].argmax(dim=-1).cpu().numpy()
1179
+
1180
+ parse_rate = float(ta["parse_rate"].item())
1181
+ P_type = ta["P_type"]
1182
+ p_log = torch.log(P_type.clamp_min(1e-12))
1183
+ type_entropy = float(-(P_type * p_log).sum(dim=-1).mean().item())
1184
+ mean_C = float(ta["C"].mean().item())
1185
+
1186
+ # Per-class F1 for the strongest variants — exposed so callers can audit
1187
+ # which classes drive the headline weighted-F1 number.
1188
+ per_class_paper = f1_score(
1189
+ all_labels, preds_paper, labels=list(range(len(candidate_labels))),
1190
+ average=None, zero_division=0,
1191
+ )
1192
+ per_class_fused = f1_score(
1193
+ all_labels, preds_fused, labels=list(range(len(candidate_labels))),
1194
+ average=None, zero_division=0,
1195
+ )
1196
+
1197
+ return {
1198
+ # Paper-protocol (Table 4 "full") for apples-to-apples comparison
1199
+ "accuracy": _acc(preds_paper),
1200
+ "weighted_f1": _f1(preds_paper),
1201
+ "macro_f1": _macro_f1(preds_paper),
1202
+ # Ablation
1203
+ "f1_full_ensembled": _f1(preds_full_ens),
1204
+ "f1_gen": _f1(preds_gen),
1205
+ "f1_hier": _f1(preds_hier),
1206
+ "f1_nocolor": _f1(preds_nocolor),
1207
+ "f1_fused": _f1(preds_fused),
1208
+ "macro_f1_fused": _macro_f1(preds_fused),
1209
+ "f1_fused_prior": _f1(preds_fused_prior),
1210
+ # Probabilistic ensemble + rerank (round 2 experiment)
1211
+ "f1_prob_ens": _f1(preds_prob_ens),
1212
+ "f1_prob_ens_adaptive": _f1(preds_prob_ens_adapt),
1213
+ "f1_rerank": _f1(preds_rerank),
1214
+ # Hybrid GAP × FashionCLIP scoring (round 3, if aux provided)
1215
+ **hybrid_results,
1216
+ # GAP-CLIP-Pure-Boost (round 4, if specialist embeddings provided)
1217
+ **pure_boost_results,
1218
+ # Type-aware variants (this experiment)
1219
+ "f1_type_aware": _f1(preds_type_aware),
1220
+ "f1_type_aware_no_prior": _f1(preds_ta_no_prior),
1221
+ "f1_type_aware_no_gating": _f1(preds_ta_no_gating),
1222
+ "type_parse_rate": parse_rate,
1223
+ "type_entropy": type_entropy,
1224
+ "mean_C": mean_C,
1225
+ "prior_weight": prior_w,
1226
+ "num_samples": int(len(all_labels)),
1227
+ "num_labels": len(candidate_labels),
1228
+ "per_class_f1_paper": {
1229
+ lbl: float(per_class_paper[i]) for i, lbl in enumerate(candidate_labels)
1230
+ },
1231
+ "per_class_f1_fused": {
1232
+ lbl: float(per_class_fused[i]) for i, lbl in enumerate(candidate_labels)
1233
+ },
1234
+ }
1235
+
1236
+
1237
+ def _maybe_specialist_embeddings(
1238
+ spec_model, pil_images, candidate_labels, batch_size, device, desc, tta=True,
1239
+ ):
1240
+ """Return (spec_img_embs, spec_text_embs) or (None, None) when spec_model is None."""
1241
+ if spec_model is None:
1242
+ return None, None
1243
+ spec_img_embs = encode_images_with_specialist_tta(
1244
+ spec_model, pil_images, batch_size, device, desc=desc, tta=tta,
1245
+ )
1246
+ spec_text_embs = encode_text_with_specialist_ensembled(
1247
+ spec_model, candidate_labels, ZERO_SHOT_TEMPLATES, device,
1248
+ )
1249
+ return spec_img_embs, spec_text_embs
1250
+
1251
+
1252
  def zero_shot_fashion_mnist(
1253
  model,
1254
  processor,
1255
  device,
1256
+ cfg: RuntimeConfig,
1257
  batch_size: int = 64,
1258
+ data_root: str = "./data",
1259
+ aux_model=None,
1260
+ aux_processor=None,
1261
+ spec_model=None,
1262
+ image_tta: bool = False) -> Dict[str, float]:
1263
  """Notebook-equivalent zero-shot accuracy on all Fashion-MNIST test samples."""
1264
  dataset = datasets.FashionMNIST(
1265
  root=data_root, train=False, download=True,
 
1273
  ),
1274
  )
1275
 
1276
+ candidate_labels = list(dataset.classes)
1277
+
1278
+ single_prompts = [f"a photo of a {label}" for label in candidate_labels]
1279
+ text_embs_single = get_text_embeddings_batch(model, processor, device, single_prompts).to(device).float()
1280
+ text_embs_ens = get_prompt_ensembled_text_embeddings(
1281
+ model, processor, device, candidate_labels, ZERO_SHOT_TEMPLATES,
1282
+ ).to(device).float()
1283
+
1284
+ aux_text_embs_single = None
1285
+ if aux_model is not None and aux_processor is not None:
1286
+ aux_text_embs_single = get_text_embeddings_batch(
1287
+ aux_model, aux_processor, device, single_prompts,
1288
+ ).to(device).float()
1289
+
1290
+ # Collect image embeddings (with optional TTA), aux's (if requested),
1291
+ # all PIL images for downstream specialist encoding, and ground truth.
1292
+ all_img_embs: List[torch.Tensor] = []
1293
+ all_aux_img_embs: List[torch.Tensor] = []
1294
+ all_pil: List[Image.Image] = []
1295
+ all_gt: List[int] = []
1296
  for pil_images, labels in tqdm(loader, desc="Zero-shot Fashion-MNIST"):
1297
+ pil_images = [ImageOps.invert(img) for img in pil_images]
1298
+ emb = encode_image(model, processor, pil_images, device).to(device).float()
1299
+ emb = F.normalize(emb, dim=-1)
1300
+ if image_tta:
1301
+ flipped = [img.transpose(Image.FLIP_LEFT_RIGHT) for img in pil_images]
1302
+ emb_f = encode_image(model, processor, flipped, device).to(device).float()
1303
+ emb_f = F.normalize(emb_f, dim=-1)
1304
+ emb = F.normalize((emb + emb_f) / 2.0, dim=-1)
1305
+ all_img_embs.append(emb)
1306
+ if aux_model is not None and aux_processor is not None:
1307
+ aux_emb = encode_image(aux_model, aux_processor, pil_images, device).to(device).float()
1308
+ all_aux_img_embs.append(F.normalize(aux_emb, dim=-1))
1309
+ all_pil.extend(pil_images)
1310
+ all_gt.extend(labels.tolist())
1311
+
1312
+ img_embs = torch.cat(all_img_embs, dim=0) if all_img_embs else torch.empty(0, 512, device=device)
1313
+ aux_img_embs = (
1314
+ torch.cat(all_aux_img_embs, dim=0) if all_aux_img_embs else None
1315
+ )
1316
+ all_labels = np.asarray(all_gt, dtype=np.int64)
1317
 
1318
+ spec_img_embs, spec_text_embs = _maybe_specialist_embeddings(
1319
+ spec_model, all_pil, candidate_labels, batch_size, device,
1320
+ desc="FMNIST specialist", tta=image_tta,
1321
+ )
1322
 
1323
+ metrics = run_zero_shot_scoring(
1324
+ img_embs, text_embs_single, text_embs_ens, candidate_labels, all_labels,
1325
+ cfg, dataset_key="fmnist", mask_color=True,
1326
+ aux_img_embs=aux_img_embs, aux_text_embs_single=aux_text_embs_single,
1327
+ spec_img_embs=spec_img_embs, spec_text_embs=spec_text_embs,
1328
+ )
1329
+ print(
1330
+ "FMNIST zero-shot "
1331
+ f"paper={metrics.get('weighted_f1', 0):.4f} "
1332
+ f"ens_full={metrics.get('f1_full_ensembled', 0):.4f} "
1333
+ f"gen={metrics.get('f1_gen', 0):.4f} "
1334
+ f"hier={metrics.get('f1_hier', 0):.4f} "
1335
+ f"nocolor={metrics.get('f1_nocolor', 0):.4f} "
1336
+ f"fused={metrics.get('f1_fused', 0):.4f} "
1337
+ f"fused+prior={metrics.get('f1_fused_prior', 0):.4f}"
1338
+ )
1339
+ print(
1340
+ "FMNIST ensemble "
1341
+ f"prob_ens={metrics.get('f1_prob_ens', 0):.4f} "
1342
+ f"prob_ens_adaptive={metrics.get('f1_prob_ens_adaptive', 0):.4f} "
1343
+ f"rerank_topk={metrics.get('f1_rerank', 0):.4f}"
1344
+ )
1345
+ if any(k.startswith('f1_hybrid_') for k in metrics):
1346
+ print(
1347
+ "FMNIST hybrid "
1348
+ f"w30={metrics.get('f1_hybrid_w30', 0):.4f} "
1349
+ f"w50={metrics.get('f1_hybrid_w50', 0):.4f} "
1350
+ f"w70={metrics.get('f1_hybrid_w70', 0):.4f} "
1351
+ f"rerank={metrics.get('f1_hybrid_rerank', 0):.4f}"
1352
+ )
1353
+ if any(k.startswith('f1_pure_') for k in metrics):
1354
+ print(
1355
+ "FMNIST pure-boost "
1356
+ f"spec_only={metrics.get('f1_pure_spec_only', 0):.4f} "
1357
+ f"w50={metrics.get('f1_pure_boost_w50', 0):.4f} "
1358
+ f"w60={metrics.get('f1_pure_boost_w60', 0):.4f} "
1359
+ f"w70={metrics.get('f1_pure_boost_w70', 0):.4f}"
1360
+ )
1361
+ print(
1362
+ "FMNIST type-aware "
1363
+ f"ta={metrics.get('f1_type_aware', 0):.4f} "
1364
+ f"ta_no_prior={metrics.get('f1_type_aware_no_prior', 0):.4f} "
1365
+ f"ta_no_gating={metrics.get('f1_type_aware_no_gating', 0):.4f} "
1366
+ f"parse_rate={metrics.get('type_parse_rate', 0):.2f} "
1367
+ f"H(P_type)={metrics.get('type_entropy', 0):.3f} "
1368
+ f"mean_C={metrics.get('mean_C', 0):.3f}"
1369
+ )
1370
+ return metrics
1371
 
1372
 
1373
 
 
1375
  model,
1376
  processor,
1377
  device,
1378
+ cfg: RuntimeConfig,
1379
  batch_size: int = 64,
1380
  num_examples: int = 10000,
1381
+ aux_model=None,
1382
+ aux_processor=None,
1383
+ spec_model=None,
1384
+ image_tta: bool = False,
1385
  ) -> Optional[Dict[str, float]]:
1386
  """Notebook-equivalent zero-shot accuracy/F1 on KAGL Marqo (category2)."""
1387
  try:
 
1419
  print("Skipping zero_shot_kagl: no valid samples")
1420
  return None
1421
 
1422
+ # --- Audit: surface raw KAGL label distribution and OOV mapping ----------
1423
+ from collections import Counter
1424
+ raw_counts = Counter(labels_text)
1425
+ print(f" KAGL: raw samples loaded = {len(labels_text)}, unique raw labels = {len(raw_counts)}")
1426
+ oov_raw = sorted({lbl for lbl in raw_counts if not is_clothing_label(lbl)})
1427
+ if oov_raw:
1428
+ oov_total = sum(raw_counts[l] for l in oov_raw)
1429
+ print(f" KAGL: {len(oov_raw)} OOV raw labels covering {oov_total} samples (dropped): "
1430
+ f"{oov_raw[:15]}{'...' if len(oov_raw) > 15 else ''}")
1431
+
1432
+ # Filter out non-clothing categories that are absent from GAP-CLIP's
1433
+ # training vocabulary (fragrance, makeup, nails, etc.). See
1434
+ # `is_clothing_label` for the allowlist.
1435
+ keep_idx = [i for i, lbl in enumerate(labels_text) if is_clothing_label(lbl)]
1436
+ if len(keep_idx) < len(labels_text):
1437
+ dropped = len(labels_text) - len(keep_idx)
1438
+ print(f" KAGL: filtered out {dropped} non-clothing samples "
1439
+ f"({dropped / len(labels_text):.1%})")
1440
+ pil_images = [pil_images[i] for i in keep_idx]
1441
+ labels_text = [labels_text[i] for i in keep_idx]
1442
 
1443
+ if not pil_images:
1444
+ print("Skipping zero_shot_kagl: no clothing samples after filter")
1445
+ return None
 
 
 
 
 
1446
 
1447
+ # --- D1: project raw KAGL labels to canonical GAP vocabulary -------------
1448
+ # Both ground-truth indices and zero-shot prompts are built from the
1449
+ # canonical strings GAP-CLIP was trained on (e.g. "tops"->"top",
1450
+ # "trousers"->"pant"). Same `candidate_labels` is used by every model
1451
+ # passed through this function, preserving apples-to-apples comparison
1452
+ # with the FashionCLIP 2.0 baseline.
1453
+ canonical_labels = [normalize_hierarchy_label(lbl) for lbl in labels_text]
1454
+ raw_to_canonical: Dict[str, Counter] = {}
1455
+ for raw, canon in zip(labels_text, canonical_labels):
1456
+ raw_to_canonical.setdefault(raw, Counter())[canon] += 1
1457
+ print(f" KAGL: filtered samples = {len(canonical_labels)}, "
1458
+ f"unique canonical labels = {len(set(canonical_labels))}")
1459
+ print(f" KAGL: raw -> canonical mapping (sample counts):")
1460
+ for raw in sorted(raw_to_canonical):
1461
+ items = ", ".join(f"{c}={n}" for c, n in raw_to_canonical[raw].most_common())
1462
+ print(f" {raw!r:24s} -> {items}")
1463
+
1464
+ candidate_labels = sorted(set(canonical_labels))
1465
+ label_to_idx = {label: idx for idx, label in enumerate(candidate_labels)}
1466
+ all_labels = np.array([label_to_idx[label] for label in canonical_labels], dtype=np.int64)
1467
+ canonical_counts = Counter(canonical_labels)
1468
+ print(f" KAGL: per-class sample counts: "
1469
+ + ", ".join(f"{lbl}={canonical_counts[lbl]}" for lbl in candidate_labels))
1470
+
1471
+ # Single-prompt text embeddings still use the canonical label string (this
1472
+ # is the paper-protocol baseline column). Ensembled text embeddings use
1473
+ # descriptor expansion: each canonical class is the centroid over many
1474
+ # leaf-level synonyms × templates, so the candidate vector covers the
1475
+ # full breadth of KAGL's coarse `category2` parent class.
1476
+ single_prompts = [f"a photo of a {label}" for label in candidate_labels]
1477
+ text_embs_single = get_text_embeddings_batch(model, processor, device, single_prompts).to(device).float()
1478
+ text_embs_ens = get_descriptor_ensembled_text_embeddings(
1479
+ model, processor, device, KAGL_COARSE_DESCRIPTORS,
1480
+ candidate_labels, ZERO_SHOT_TEMPLATES,
1481
+ ).to(device).float()
1482
+
1483
+ img_embs = _encode_images_batched(
1484
+ model, processor, device, pil_images, batch_size, desc="Zero-shot KAGL",
1485
+ tta=image_tta,
1486
+ )
1487
+ aux_img_embs = None
1488
+ aux_text_embs_single = None
1489
+ if aux_model is not None and aux_processor is not None:
1490
+ aux_text_embs_single = get_text_embeddings_batch(
1491
+ aux_model, aux_processor, device, single_prompts,
1492
+ ).to(device).float()
1493
+ aux_img_embs = _encode_images_batched(
1494
+ aux_model, aux_processor, device, pil_images, batch_size,
1495
+ desc="Zero-shot KAGL (aux)",
1496
+ )
1497
+ spec_img_embs, spec_text_embs = _maybe_specialist_embeddings(
1498
+ spec_model, pil_images, candidate_labels, batch_size, device,
1499
+ desc="KAGL specialist", tta=image_tta,
1500
+ )
1501
+ metrics = run_zero_shot_scoring(
1502
+ img_embs, text_embs_single, text_embs_ens, candidate_labels, all_labels,
1503
+ cfg, dataset_key="kagl", mask_color=False,
1504
+ aux_img_embs=aux_img_embs, aux_text_embs_single=aux_text_embs_single,
1505
+ spec_img_embs=spec_img_embs, spec_text_embs=spec_text_embs,
1506
+ )
1507
+ print(
1508
+ "KAGL zero-shot "
1509
+ f"paper={metrics.get('weighted_f1', 0):.4f} "
1510
+ f"macro={metrics.get('macro_f1', 0):.4f} "
1511
+ f"ens_full={metrics.get('f1_full_ensembled', 0):.4f} "
1512
+ f"gen={metrics.get('f1_gen', 0):.4f} "
1513
+ f"hier={metrics.get('f1_hier', 0):.4f} "
1514
+ f"nocolor={metrics.get('f1_nocolor', 0):.4f} "
1515
+ f"fused={metrics.get('f1_fused', 0):.4f} "
1516
+ f"macro_fused={metrics.get('macro_f1_fused', 0):.4f} "
1517
+ f"fused+prior={metrics.get('f1_fused_prior', 0):.4f}"
1518
+ )
1519
+ pc_paper = metrics.get('per_class_f1_paper', {}) or {}
1520
+ pc_fused = metrics.get('per_class_f1_fused', {}) or {}
1521
+ if pc_paper:
1522
+ print(" KAGL per-class F1 (paper / fused):")
1523
+ for lbl in sorted(pc_paper):
1524
+ print(f" {lbl:14s} paper={pc_paper.get(lbl, 0):.3f} "
1525
+ f"fused={pc_fused.get(lbl, 0):.3f}")
1526
+ print(
1527
+ "KAGL ensemble "
1528
+ f"prob_ens={metrics.get('f1_prob_ens', 0):.4f} "
1529
+ f"prob_ens_adaptive={metrics.get('f1_prob_ens_adaptive', 0):.4f} "
1530
+ f"rerank_topk={metrics.get('f1_rerank', 0):.4f}"
1531
+ )
1532
+ if any(k.startswith('f1_hybrid_') for k in metrics):
1533
+ print(
1534
+ "KAGL hybrid "
1535
+ f"w30={metrics.get('f1_hybrid_w30', 0):.4f} "
1536
+ f"w50={metrics.get('f1_hybrid_w50', 0):.4f} "
1537
+ f"w70={metrics.get('f1_hybrid_w70', 0):.4f} "
1538
+ f"rerank={metrics.get('f1_hybrid_rerank', 0):.4f}"
1539
+ )
1540
+ if any(k.startswith('f1_pure_') for k in metrics):
1541
+ print(
1542
+ "KAGL pure-boost "
1543
+ f"spec_only={metrics.get('f1_pure_spec_only', 0):.4f} "
1544
+ f"w30={metrics.get('f1_pure_boost_w30', 0):.4f} "
1545
+ f"w40={metrics.get('f1_pure_boost_w40', 0):.4f} "
1546
+ f"w50={metrics.get('f1_pure_boost_w50', 0):.4f}"
1547
+ )
1548
+ print(
1549
+ "KAGL type-aware "
1550
+ f"ta={metrics.get('f1_type_aware', 0):.4f} "
1551
+ f"ta_no_prior={metrics.get('f1_type_aware_no_prior', 0):.4f} "
1552
+ f"ta_no_gating={metrics.get('f1_type_aware_no_gating', 0):.4f} "
1553
+ f"parse_rate={metrics.get('type_parse_rate', 0):.2f} "
1554
+ f"H(P_type)={metrics.get('type_entropy', 0):.3f} "
1555
+ f"mean_C={metrics.get('mean_C', 0):.3f}"
1556
+ )
1557
+ return metrics
1558
 
1559
 
1560
  def zero_shot_internal(
1561
  model,
1562
  processor,
1563
  device,
1564
+ cfg: RuntimeConfig,
1565
  batch_size: int = 64,
1566
  num_examples: int = 10000,
1567
+ csv_path: str = INTERNAL_DATASET_CSV,
1568
+ aux_model=None,
1569
+ aux_processor=None,
1570
+ spec_model=None,
1571
+ image_tta: bool = False) -> Optional[Dict[str, float]]:
1572
  """Notebook-equivalent zero-shot accuracy/F1 on internal dataset."""
1573
  csv_file = Path(csv_path)
1574
  if not csv_file.exists():
 
1593
  if use_local:
1594
  img_path = Path(str(row["local_image_path"]))
1595
  if not img_path.exists():
1596
+ # Fallback: resolve filename relative to data/images/
1597
+ img_path = Path("data/images") / img_path.name
1598
+ if not img_path.exists():
1599
+ continue
1600
  image = Image.open(img_path).convert("RGB")
1601
  else:
1602
  response = requests.get(str(row["image_url"]), timeout=5)
 
1616
  label_to_idx = {label: idx for idx, label in enumerate(candidate_labels)}
1617
  all_labels = np.array([label_to_idx[label] for label in labels_text], dtype=np.int64)
1618
 
1619
+ single_prompts = [f"a photo of a {label}" for label in candidate_labels]
1620
+ text_embs_single = get_text_embeddings_batch(model, processor, device, single_prompts).to(device).float()
1621
+ text_embs_ens = get_prompt_ensembled_text_embeddings(
1622
+ model, processor, device, candidate_labels, ZERO_SHOT_TEMPLATES,
1623
+ ).to(device).float()
1624
 
1625
+ img_embs = _encode_images_batched(
1626
+ model, processor, device, pil_images, batch_size, desc="Zero-shot Internal",
1627
+ tta=image_tta,
1628
+ )
1629
+ aux_img_embs = None
1630
+ aux_text_embs_single = None
1631
+ if aux_model is not None and aux_processor is not None:
1632
+ aux_text_embs_single = get_text_embeddings_batch(
1633
+ aux_model, aux_processor, device, single_prompts,
1634
+ ).to(device).float()
1635
+ aux_img_embs = _encode_images_batched(
1636
+ aux_model, aux_processor, device, pil_images, batch_size,
1637
+ desc="Zero-shot Internal (aux)",
1638
+ )
1639
+ spec_img_embs, spec_text_embs = _maybe_specialist_embeddings(
1640
+ spec_model, pil_images, candidate_labels, batch_size, device,
1641
+ desc="Internal specialist", tta=image_tta,
1642
+ )
1643
+ metrics = run_zero_shot_scoring(
1644
+ img_embs, text_embs_single, text_embs_ens, candidate_labels, all_labels,
1645
+ cfg, dataset_key="internal", mask_color=False,
1646
+ aux_img_embs=aux_img_embs, aux_text_embs_single=aux_text_embs_single,
1647
+ spec_img_embs=spec_img_embs, spec_text_embs=spec_text_embs,
1648
+ )
1649
+ print(
1650
+ "Internal zero-shot "
1651
+ f"paper={metrics.get('weighted_f1', 0):.4f} "
1652
+ f"ens_full={metrics.get('f1_full_ensembled', 0):.4f} "
1653
+ f"gen={metrics.get('f1_gen', 0):.4f} "
1654
+ f"hier={metrics.get('f1_hier', 0):.4f} "
1655
+ f"nocolor={metrics.get('f1_nocolor', 0):.4f} "
1656
+ f"fused={metrics.get('f1_fused', 0):.4f} "
1657
+ f"fused+prior={metrics.get('f1_fused_prior', 0):.4f}"
1658
+ )
1659
+ print(
1660
+ "Internal ensemble "
1661
+ f"prob_ens={metrics.get('f1_prob_ens', 0):.4f} "
1662
+ f"prob_ens_adaptive={metrics.get('f1_prob_ens_adaptive', 0):.4f} "
1663
+ f"rerank_topk={metrics.get('f1_rerank', 0):.4f}"
1664
+ )
1665
+ if any(k.startswith('f1_hybrid_') for k in metrics):
1666
+ print(
1667
+ "Internal hybrid "
1668
+ f"w30={metrics.get('f1_hybrid_w30', 0):.4f} "
1669
+ f"w50={metrics.get('f1_hybrid_w50', 0):.4f} "
1670
+ f"w70={metrics.get('f1_hybrid_w70', 0):.4f} "
1671
+ f"rerank={metrics.get('f1_hybrid_rerank', 0):.4f}"
1672
+ )
1673
+ if any(k.startswith('f1_pure_') for k in metrics):
1674
+ print(
1675
+ "Internal pure-boost "
1676
+ f"spec_only={metrics.get('f1_pure_spec_only', 0):.4f} "
1677
+ f"w40={metrics.get('f1_pure_boost_w40', 0):.4f} "
1678
+ f"w50={metrics.get('f1_pure_boost_w50', 0):.4f} "
1679
+ f"w60={metrics.get('f1_pure_boost_w60', 0):.4f}"
1680
+ )
1681
+ print(
1682
+ "Internal type-aware "
1683
+ f"ta={metrics.get('f1_type_aware', 0):.4f} "
1684
+ f"ta_no_prior={metrics.get('f1_type_aware_no_prior', 0):.4f} "
1685
+ f"ta_no_gating={metrics.get('f1_type_aware_no_gating', 0):.4f} "
1686
+ f"parse_rate={metrics.get('type_parse_rate', 0):.2f} "
1687
+ f"H(P_type)={metrics.get('type_entropy', 0):.3f} "
1688
+ f"mean_C={metrics.get('mean_C', 0):.3f}"
1689
+ )
1690
+ return metrics
1691
 
1692
 
1693
  def normalize_hierarchy_label(raw_label: str) -> str:
 
1748
  "scarf & tie": "accessories",
1749
  "scarf/tie": "accessories",
1750
  "belt": "accessories",
1751
+ # --- KAGL `category2` extensions (audited from Marqo/KAGL) -----------
1752
+ "tshirts": "shirt",
1753
+ "tshirt": "shirt",
1754
+ "tunics": "top",
1755
+ "tunic": "top",
1756
+ "kurta": "top",
1757
+ "kurtas": "top",
1758
+ "kurti": "top",
1759
+ "kurtis": "top",
1760
+ "blouse": "shirt",
1761
+ "blouses": "shirt",
1762
+ "camisoles": "top",
1763
+ "camisole": "top",
1764
+ "sweatshirt": "sweater",
1765
+ "sweatshirts": "sweater",
1766
+ "sweaters": "sweater",
1767
+ "jumper": "sweater",
1768
+ "jumpers": "sweater",
1769
+ "hoodie": "sweater",
1770
+ "hoodies": "sweater",
1771
+ "cardigan": "sweater",
1772
+ "cardigans": "sweater",
1773
+ "jackets": "jacket",
1774
+ "blazers": "jacket",
1775
+ "blazer": "jacket",
1776
+ "coats": "coat",
1777
+ "tracksuit": "jacket",
1778
+ "tracksuits": "jacket",
1779
+ "track pants": "pant",
1780
+ "lounge pants": "pant",
1781
+ "salwar": "pant",
1782
+ "salwar and dupatta": "pant",
1783
+ "patiala": "pant",
1784
+ "churidar": "pant",
1785
+ "churidars": "pant",
1786
+ "capris": "pant",
1787
+ "capri": "pant",
1788
+ "leggings": "legging",
1789
+ "tights": "legging",
1790
+ "stockings": "legging",
1791
+ "lounge shorts": "short",
1792
+ "skirts": "skirt",
1793
+ "skorts": "skirt",
1794
+ "skort": "skirt",
1795
+ "dresses": "dress",
1796
+ "nightdress": "dress",
1797
+ "nightdresses": "dress",
1798
+ "night suits": "dress",
1799
+ "night dress": "dress",
1800
+ "lounge tshirts": "top",
1801
+ "sarees": "dress",
1802
+ "lehenga choli": "dress",
1803
+ "lehenga": "dress",
1804
+ "cholis": "top",
1805
+ "choli": "top",
1806
+ "innerwear vests": "underwear",
1807
+ "innerwear": "underwear",
1808
+ "boxers": "underwear",
1809
+ "boxer": "underwear",
1810
+ "briefs": "underwear",
1811
+ "brief": "underwear",
1812
+ "trunks": "underwear",
1813
+ "trunk": "underwear",
1814
+ "bra": "bras",
1815
+ "swim": "swimwear",
1816
+ "swimsuit": "swimwear",
1817
+ "swimsuits": "swimwear",
1818
+ "swim suit": "swimwear",
1819
+ "swimwear and beach wear": "swimwear",
1820
+ "rompers": "bodysuits",
1821
+ "romper": "bodysuits",
1822
+ "jumpsuits": "bodysuits",
1823
+ "jumpsuit": "bodysuits",
1824
+ "bodysuit": "bodysuits",
1825
+ "playsuit": "bodysuits",
1826
+ "playsuits": "bodysuits",
1827
+ "polos": "polo",
1828
+ "polo shirt": "polo",
1829
+ "polo shirts": "polo",
1830
+ "polo t-shirts": "polo",
1831
+ "casual shoes": "shoes",
1832
+ "formal shoes": "shoes",
1833
+ "sports shoes": "shoes",
1834
+ "sandals": "shoes",
1835
+ "flats": "shoes",
1836
+ "heels": "shoes",
1837
+ "booties": "shoes",
1838
+ "loafers": "shoes",
1839
+ "slippers": "shoes",
1840
+ "stocking": "socks",
1841
+ "handbags": "accessories",
1842
+ "handbag": "accessories",
1843
+ "backpacks": "accessories",
1844
+ "backpack": "accessories",
1845
+ "clutches": "accessories",
1846
+ "clutch": "accessories",
1847
+ "earrings": "accessories",
1848
+ "earring": "accessories",
1849
+ "necklaces": "accessories",
1850
+ "necklace": "accessories",
1851
+ "necklace and chains": "accessories",
1852
+ "rings": "accessories",
1853
+ "ring": "accessories",
1854
+ "bracelets": "accessories",
1855
+ "bracelet": "accessories",
1856
+ "anklets": "accessories",
1857
+ "anklet": "accessories",
1858
+ "bangles": "accessories",
1859
+ "bangle": "accessories",
1860
+ "cufflinks": "accessories",
1861
+ "pendants": "accessories",
1862
+ "pendant": "accessories",
1863
+ "caps": "accessories",
1864
+ "cap": "accessories",
1865
+ "hat": "accessories",
1866
+ "hats": "accessories",
1867
+ "duppata": "accessories",
1868
+ "dupatta": "accessories",
1869
+ "dupatta and stoles": "accessories",
1870
+ "scarf": "accessories",
1871
+ "stole": "accessories",
1872
+ "muffler": "accessories",
1873
+ "wallet": "accessories",
1874
+ "watch": "accessories",
1875
+ "tie": "accessories",
1876
+ "gloves": "accessories",
1877
+ "glove": "accessories",
1878
  }
1879
  exact = synonyms.get(label, None)
1880
  if exact is not None:
 
1904
  return label
1905
 
1906
 
1907
+ # Canonical clothing vocabulary — the hierarchy categories GAP-CLIP was
1908
+ # trained on. A KAGL label counts as "clothing" iff normalization maps it into
1909
+ # this set (otherwise it is OOV — e.g. fragrance, makeup, nails — and excluded
1910
+ # from the zero-shot candidate set per plan section 4).
1911
+ _CLOTHING_VOCAB = frozenset({
1912
+ "accessories", "bodysuits", "bras", "coat", "dress", "jacket",
1913
+ "legging", "pant", "polo", "shirt", "shoes", "short", "skirt",
1914
+ "socks", "sweater", "swimwear", "top", "underwear",
1915
+ })
1916
+
1917
+
1918
+ def is_clothing_label(raw_label: str) -> bool:
1919
+ """True when `raw_label` maps to a known training-time hierarchy."""
1920
+ return normalize_hierarchy_label(raw_label) in _CLOTHING_VOCAB
1921
+
1922
 
1923
  # ModaNet 13 categories (category_id -> label)
1924
  MODANET_CATEGORIES = {
 
2003
  model,
2004
  processor,
2005
  device,
2006
+ cfg: RuntimeConfig,
2007
  batch_size: int = 64,
2008
  num_examples: int = 10000,
2009
  use_gap_labels: bool = True,
2010
+ aux_model=None,
2011
+ aux_processor=None,
2012
+ spec_model=None,
2013
+ image_tta: bool = False,
2014
  ) -> Optional[Dict[str, float]]:
2015
  """Zero-shot accuracy/F1 on ModaNet dataset."""
2016
  baseline_samples, gap_samples, _ = load_modanet_samples(num_examples)
 
2026
  label_to_idx = {label: idx for idx, label in enumerate(candidate_labels)}
2027
  all_labels = np.array([label_to_idx[label] for label in labels_text], dtype=np.int64)
2028
 
2029
+ single_prompts = [f"a photo of a {label}" for label in candidate_labels]
2030
+ text_embs_single = get_text_embeddings_batch(model, processor, device, single_prompts).to(device).float()
2031
+ text_embs_ens = get_prompt_ensembled_text_embeddings(
2032
+ model, processor, device, candidate_labels, ZERO_SHOT_TEMPLATES,
2033
+ ).to(device).float()
2034
 
2035
+ img_embs = _encode_images_batched(
2036
+ model, processor, device, pil_images, batch_size, desc="Zero-shot ModaNet",
2037
+ tta=image_tta,
2038
+ )
2039
+ aux_img_embs = None
2040
+ aux_text_embs_single = None
2041
+ if aux_model is not None and aux_processor is not None:
2042
+ aux_text_embs_single = get_text_embeddings_batch(
2043
+ aux_model, aux_processor, device, single_prompts,
2044
+ ).to(device).float()
2045
+ aux_img_embs = _encode_images_batched(
2046
+ aux_model, aux_processor, device, pil_images, batch_size,
2047
+ desc="Zero-shot ModaNet (aux)",
2048
+ )
2049
+ spec_img_embs, spec_text_embs = _maybe_specialist_embeddings(
2050
+ spec_model, pil_images, candidate_labels, batch_size, device,
2051
+ desc="ModaNet specialist", tta=image_tta,
2052
+ )
2053
+ metrics = run_zero_shot_scoring(
2054
+ img_embs, text_embs_single, text_embs_ens, candidate_labels, all_labels,
2055
+ cfg, dataset_key="modanet", mask_color=False,
2056
+ aux_img_embs=aux_img_embs, aux_text_embs_single=aux_text_embs_single,
2057
+ spec_img_embs=spec_img_embs, spec_text_embs=spec_text_embs,
2058
+ )
2059
  label_kind = "GAP" if use_gap_labels else "native"
2060
+ print(
2061
+ f"ModaNet ({label_kind}) zero-shot "
2062
+ f"paper={metrics.get('weighted_f1', 0):.4f} "
2063
+ f"ens_full={metrics.get('f1_full_ensembled', 0):.4f} "
2064
+ f"gen={metrics.get('f1_gen', 0):.4f} "
2065
+ f"hier={metrics.get('f1_hier', 0):.4f} "
2066
+ f"nocolor={metrics.get('f1_nocolor', 0):.4f} "
2067
+ f"fused={metrics.get('f1_fused', 0):.4f} "
2068
+ f"fused+prior={metrics.get('f1_fused_prior', 0):.4f}"
2069
+ )
2070
+ print(
2071
+ f"ModaNet ({label_kind}) ensemble "
2072
+ f"prob_ens={metrics.get('f1_prob_ens', 0):.4f} "
2073
+ f"prob_ens_adaptive={metrics.get('f1_prob_ens_adaptive', 0):.4f} "
2074
+ f"rerank_topk={metrics.get('f1_rerank', 0):.4f}"
2075
+ )
2076
+ if any(k.startswith('f1_hybrid_') for k in metrics):
2077
+ print(
2078
+ f"ModaNet ({label_kind}) hybrid "
2079
+ f"w30={metrics.get('f1_hybrid_w30', 0):.4f} "
2080
+ f"w50={metrics.get('f1_hybrid_w50', 0):.4f} "
2081
+ f"w70={metrics.get('f1_hybrid_w70', 0):.4f} "
2082
+ f"rerank={metrics.get('f1_hybrid_rerank', 0):.4f}"
2083
+ )
2084
+ if any(k.startswith('f1_pure_') for k in metrics):
2085
+ print(
2086
+ f"ModaNet ({label_kind}) pure-boost "
2087
+ f"spec_only={metrics.get('f1_pure_spec_only', 0):.4f} "
2088
+ f"w40={metrics.get('f1_pure_boost_w40', 0):.4f} "
2089
+ f"w50={metrics.get('f1_pure_boost_w50', 0):.4f} "
2090
+ f"w60={metrics.get('f1_pure_boost_w60', 0):.4f}"
2091
+ )
2092
+ print(
2093
+ f"ModaNet ({label_kind}) type-aware "
2094
+ f"ta={metrics.get('f1_type_aware', 0):.4f} "
2095
+ f"ta_no_prior={metrics.get('f1_type_aware_no_prior', 0):.4f} "
2096
+ f"ta_no_gating={metrics.get('f1_type_aware_no_gating', 0):.4f} "
2097
+ f"parse_rate={metrics.get('type_parse_rate', 0):.2f} "
2098
+ f"H(P_type)={metrics.get('type_entropy', 0):.3f} "
2099
+ f"mean_C={metrics.get('mean_C', 0):.3f}"
2100
+ )
2101
+ return metrics
2102
 
2103
 
2104
  def main(
 
2198
  print("\n" + "=" * 120)
2199
  print("Test D — Notebook-style zero-shot accuracy")
2200
  print("=" * 120)
2201
+
2202
+ # Load the specialist HierarchyModel for GAP-CLIP-Pure-Boost. Pure
2203
+ # GAP-CLIP family — no FashionCLIP weights involved in this channel.
2204
+ spec_model = None
2205
+ try:
2206
+ from evaluation.utils.model_loader import load_hierarchy_model
2207
+ try:
2208
+ import config as _project_config
2209
+ hier_path = getattr(_project_config, "hierarchy_model_path", "models/hierarchy_model.pth")
2210
+ except Exception:
2211
+ hier_path = "models/hierarchy_model.pth"
2212
+ if Path(hier_path).exists():
2213
+ print(f"Loading specialist HierarchyModel from {hier_path} ...")
2214
+ spec_model = load_hierarchy_model(hier_path, cfg.device)
2215
+ else:
2216
+ print(f" Specialist HierarchyModel not found at {hier_path}; pure-boost disabled")
2217
+ except Exception as exc:
2218
+ print(f" Skipping pure-boost: failed to load specialist ({exc})")
2219
+ spec_model = None
2220
+
2221
+ # GAP-CLIP runs use specialist + TTA for pure-boost. Baseline-as-
2222
+ # primary runs are kept for standalone reference numbers (no aux,
2223
+ # no specialist — we never want to mix in baseline weights into
2224
+ # the GAP-CLIP scoring per user's directive).
2225
  d_results: Dict[str, Dict[str, Optional[Dict[str, float]]]] = {
2226
  "Fashion-MNIST": {
2227
+ "gap": zero_shot_fashion_mnist(model=model, processor=processor, device=cfg.device, cfg=cfg, batch_size=64,
2228
+ spec_model=spec_model, image_tta=True),
2229
+ "base": zero_shot_fashion_mnist(model=baseline_model, processor=baseline_processor, device=cfg.device, cfg=cfg, batch_size=64),
2230
  },
2231
  "KAGL Marqo": {
2232
+ "gap": zero_shot_kagl(model=model, processor=processor, device=cfg.device, cfg=cfg, batch_size=64, num_examples=DEFAULT_NUM_EXAMPLES,
2233
+ spec_model=spec_model, image_tta=True),
2234
+ "base": zero_shot_kagl(model=baseline_model, processor=baseline_processor, device=cfg.device, cfg=cfg, batch_size=64, num_examples=DEFAULT_NUM_EXAMPLES),
2235
  },
2236
  "Internal dataset": {
2237
+ "gap": zero_shot_internal(model=model, processor=processor, device=cfg.device, cfg=cfg, batch_size=64, num_examples=DEFAULT_NUM_EXAMPLES,
2238
+ spec_model=spec_model, image_tta=True),
2239
+ "base": zero_shot_internal(model=baseline_model, processor=baseline_processor, device=cfg.device, cfg=cfg, batch_size=64, num_examples=DEFAULT_NUM_EXAMPLES),
2240
  },
2241
  "ModaNet": {
2242
+ "gap": zero_shot_modanet(model=model, processor=processor, device=cfg.device, cfg=cfg, batch_size=64, num_examples=DEFAULT_NUM_EXAMPLES, use_gap_labels=True,
2243
+ spec_model=spec_model, image_tta=True),
2244
+ "base": zero_shot_modanet(model=baseline_model, processor=baseline_processor, device=cfg.device, cfg=cfg, batch_size=64, num_examples=DEFAULT_NUM_EXAMPLES, use_gap_labels=True),
2245
  },
2246
  }
2247
 
 
2252
  for ds in ["Fashion-MNIST", "KAGL Marqo", "ModaNet", "Internal dataset"]:
2253
  gap_result = d_results[ds]["gap"]
2254
  base_result = d_results[ds]["base"]
2255
+
2256
+ def _fmt(result, key):
2257
+ if result is None:
2258
+ return "N/A"
2259
+ val = result.get(key)
2260
+ return f"{val:.2%}" if val is not None else "N/A"
2261
+
2262
  summary_rows.append([
2263
  ds,
2264
+ _fmt(gap_result, "accuracy"),
2265
+ _fmt(gap_result, "accuracy_color"),
2266
+ _fmt(gap_result, "accuracy_hier"),
2267
+ _fmt(base_result, "accuracy"),
2268
+ _fmt(base_result, "accuracy_color"),
2269
+ _fmt(base_result, "accuracy_hier"),
2270
  ])
2271
  print_table(
2272
  "Test D — zero-shot accuracy (notebook protocol)",
2273
+ ["Dataset", "GAP full", "GAP color[0:16]", "GAP hier[16:80]", "Base full", "Base color[0:16]", "Base hier[16:80]"],
2274
  summary_rows,
2275
  )
2276
  print("\n" + "=" * 120)