File size: 20,819 Bytes
d7ff85b | 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 | import unittest
import types
import sys
import torch
import numpy as np
# Import the canonical & generated classes
from canonical import PointCLIPV2_ZS_C as CanonicalCls
from zeroshot import PointCLIPV2_ZS as GeneratedCls
# ---------- Helper stubs for light inference (previous approach) ----------
class DummyVisualEncoderTorch:
"""
Deterministic visual encoder.
Input: tensor images of shape (V, C, H, W), only V is used.
Output: tensor of shape (V, D) with features feat[v, d] = (v+1)*(d+1).
"""
def __init__(self, feature_dim: int = 8):
self.feature_dim = feature_dim
def __call__(self, images: torch.Tensor) -> torch.Tensor:
V = images.shape[0]
v_idx = torch.arange(1, V + 1, dtype=torch.float32, device=images.device).unsqueeze(1)
d_idx = torch.arange(1, self.feature_dim + 1, dtype=torch.float32, device=images.device).unsqueeze(0)
feats = v_idx * d_idx
return feats
def make_stub_instance(Cls, num_views: int, feat_dim: int, num_classes: int, view_weights, device, force_dtype=None):
"""
Build a lightweight class instance without calling heavy build_model.
Inject all necessary fields for model_inference.
"""
inst = object.__new__(Cls)
inst.num_views = num_views
inst.channel = feat_dim
inst.dtype = force_dtype if force_dtype is not None else torch.float32
inst.visual_encoder = DummyVisualEncoderTorch(feature_dim=feat_dim)
inst.view_weights = torch.tensor(view_weights, dtype=torch.float32, device=device)
# Build normalized text features in float32, then (optionally) cast to inst.dtype
text_feat = torch.arange(1, num_classes * num_views * feat_dim + 1, dtype=torch.float32, device=device)
text_feat = text_feat.view(num_classes, num_views * feat_dim)
text_feat = text_feat / (text_feat.norm(dim=-1, keepdim=True) + 1e-12)
if force_dtype is not None:
text_feat = text_feat.to(force_dtype)
inst.text_feat = text_feat
inst.feat_store = []
inst.label_store = []
# Realistic projection stub: returns zeros with the correct V and spatial size.
def real_proj_stub(pc, imsize=224):
return torch.zeros((num_views, 3, imsize, imsize), dtype=torch.float32, device=device)
inst.real_proj = real_proj_stub
return inst
def to_numpy_2d(x):
if isinstance(x, torch.Tensor):
arr = x.detach().cpu().numpy()
else:
arr = np.array(x)
if arr.ndim == 1:
arr = arr[None, :]
return arr
def assert_same_logits(testcase, can_logits, gen_logits, rtol=1e-6, atol=1e-8, msg=""):
a, b = to_numpy_2d(can_logits), to_numpy_2d(gen_logits)
testcase.assertEqual(a.shape, b.shape, f"Shape mismatch: {a.shape} vs {b.shape}. {msg}")
np.testing.assert_allclose(a, b, rtol=rtol, atol=atol, err_msg=msg)
# ---------- Minimal CFG / DM dummies for build_model path ----------
class _Dot:
"""Tiny helper to set nested attributes like cfg.MODEL.BACKBONE.NAME."""
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
class DummyDM:
def __init__(self, classnames):
self.dataset = _Dot(classnames=classnames)
# ---------- Monkeypatch helpers ----------
class NoCudaTensorMonkeypatch:
"""Context manager to make tensor.cuda() a no-op (safe on CPU-only)."""
def __enter__(self):
self._orig_cuda = torch.Tensor.cuda
torch.Tensor.cuda = lambda self, *a, **k: self
return self
def __exit__(self, exc_type, exc, tb):
torch.Tensor.cuda = self._orig_cuda
def make_dummy_clip_module(embed_dim=32):
"""
Build a dummy 'clip' module that matches what canonical.py expects:
- _MODELS, _download
- tokenize(str or list[str]) -> torch.int tensor
- build_model(state_dict_or_weights) -> model with visual, encode_text, dtype, logit_scale
"""
clip_mod = types.SimpleNamespace()
clip_mod._MODELS = {"ViT-B/32": "dummy-url"}
def _download(url):
return "dummy.pt"
clip_mod._download = _download
def tokenize(x):
# Return a tensor; downstream calls .cuda() and encode_text() expects tensor-like
if isinstance(x, str):
toks = [x]
else:
toks = list(x)
# produce length = len(str) as a silly tokenization
lens = [max(1, len(s) if isinstance(s, str) else 1) for s in toks]
return torch.tensor(lens, dtype=torch.int64)
clip_mod.tokenize = tokenize
class _DummyVisual:
def __init__(self, d=embed_dim):
self.d = d
def __call__(self, images):
# images: (V, C, H, W) -> return (V, d)
V = images.shape[0]
v = torch.arange(1, V + 1, dtype=torch.float32, device=images.device).unsqueeze(1)
d = torch.arange(1, self.d + 1, dtype=torch.float32, device=images.device).unsqueeze(0)
return v * d
class _DummyModel:
def __init__(self, d=embed_dim):
self.visual = _DummyVisual(d=d)
self.dtype = torch.float32
self.logit_scale = torch.tensor(4.6052) # ~ log(100)
def encode_text(self, tokens):
# tokens shape (N,) -> return (N, d) deterministic
N = tokens.numel()
d = embed_dim
base = torch.arange(1, N*d + 1, dtype=torch.float32).view(N, d)
return base
def state_dict(self):
return {"weights": torch.tensor([1.0])}
def eval(self):
return self
def cuda(self):
return self
def build_model(arg):
# arg can be None, dict, or state dict. Ignore content and return dummy.
return _DummyModel(d=embed_dim)
clip_mod.build_model = build_model
return clip_mod
def patch_canonical_for_build_model(testcase, num_views=3, backbone="ViT-B/32", backbone_name2="vitb32",
dataset_name="MockSet", channel=8, classnames=None):
"""
Monkeypatch canonical module to allow build_model to run:
- clip module
- best_prompt_weight entries
- Realistic_Projection.get_img
- No-CUDA environment
Returns (cfg, dm)
"""
import canonical as canonical_mod
# 1) patch clip module used by canonical
canonical_mod.clip = types.SimpleNamespace(**make_dummy_clip_module(embed_dim=channel).__dict__)
# 2) patch best_prompt_weight for prompts/weights keys
key_p = f"{dataset_name.lower()}_{backbone_name2}_test_prompts"
key_w = f"{dataset_name.lower()}_{backbone_name2}_test_weights"
fake_prompts = [f"a 3d object of class {i}" for i in (classnames or ["a", "b", "c"])]
fake_weights = [1.0/num_views] * num_views
canonical_mod.best_prompt_weight = {key_p: fake_prompts, key_w: fake_weights}
# 3) patch Realistic_Projection
class _RP:
def get_img(self, pc):
# produce (V, 3, 32, 32) tensor
return torch.zeros((num_views, 3, 32, 32), dtype=torch.float32)
canonical_mod.Realistic_Projection = _RP
# 4) cfg + dm
cfg = _Dot(
MODEL=_Dot(
BACKBONE=_Dot(NAME=backbone, NAME2=backbone_name2, CHANNEL=channel),
PROJECT=_Dot(NUM_VIEWS=num_views)
),
DATASET=_Dot(NAME=dataset_name)
)
dm = DummyDM(classnames or ["chair", "table", "car", "lamp"])
# 5) attach to a fresh instance
inst = CanonicalCls.__new__(CanonicalCls)
inst.cfg = cfg
inst.dm = dm
return inst, canonical_mod
# ---------- Tests ----------
class TestPointCLIPV2ClassEquivalence(unittest.TestCase):
def setUp(self):
self.device = torch.device("cpu")
self.pc_small = [
[0.0, 0.0, 0.0],
[0.1, 0.2, 0.3],
[1.0, 2.0, 3.0],
[-0.5, 0.2, 0.9],
]
self.feat_dim = 8
self.num_classes = 6
self.view_weights_mv = [0.6, 0.3, 0.1]
self.view_weights_sv = [1.0]
def _run_both(self, view_weights, pc=None, feat_dim=None, num_classes=None, force_dtype=None):
if pc is None:
pc = self.pc_small
if feat_dim is None:
feat_dim = self.feat_dim
if num_classes is None:
num_classes = self.num_classes
num_views = len(view_weights)
can = make_stub_instance(CanonicalCls, num_views, feat_dim, num_classes, view_weights, self.device, force_dtype=force_dtype)
gen = make_stub_instance(GeneratedCls, num_views, feat_dim, num_classes, view_weights, self.device, force_dtype=force_dtype)
with torch.no_grad():
can_logits = CanonicalCls.model_inference(can, pc, label=None)
gen_logits = GeneratedCls.model_inference(gen, pc, label=None)
return can, gen, can_logits, gen_logits
# ---- Original-style equivalence tests ----
def test_equivalence_multiview(self):
_, _, can_logits, gen_logits = self._run_both(self.view_weights_mv)
assert_same_logits(self, can_logits, gen_logits, msg="Mismatch for multi-view inputs.")
can_np = to_numpy_2d(can_logits)
self.assertEqual(can_np.shape[0], 1)
self.assertEqual(can_np.shape[1], self.num_classes)
def test_equivalence_singleview(self):
_, _, can_logits, gen_logits = self._run_both(self.view_weights_sv)
assert_same_logits(self, can_logits, gen_logits, msg="Mismatch for single-view inputs.")
def test_equivalence_different_cloud(self):
pc_other = [
[0.2, -0.1, 0.0],
[0.3, 0.4, -0.2],
[0.5, 0.0, 0.1],
]
_, _, can_logits, gen_logits = self._run_both(self.view_weights_mv, pc=pc_other)
assert_same_logits(self, can_logits, gen_logits, msg="Mismatch for alternative point cloud.")
def test_equivalence_under_weight_scaling(self):
scale = 2.5
weights_scaled = [w * scale for w in self.view_weights_mv]
_, _, can_logits_base, gen_logits_base = self._run_both(self.view_weights_mv)
_, _, can_logits_scaled, gen_logits_scaled = self._run_both(weights_scaled)
assert_same_logits(self, can_logits_scaled, gen_logits_scaled, msg="Mismatch when scaling view weights.")
a = to_numpy_2d(can_logits_base)
a_scaled = to_numpy_2d(can_logits_scaled)
np.testing.assert_allclose(a * scale, a_scaled, rtol=1e-6, atol=1e-8,
err_msg="Scaling all view weights should scale logits linearly.")
def test_output_is_finite_and_2d(self):
_, _, can_logits, gen_logits = self._run_both(self.view_weights_mv)
can_np, gen_np = to_numpy_2d(can_logits), to_numpy_2d(gen_logits)
self.assertEqual(can_np.ndim, 2)
self.assertEqual(gen_np.ndim, 2)
self.assertTrue(np.isfinite(can_np).all())
self.assertTrue(np.isfinite(gen_np).all())
# ---- Coverage boosters: param sweeps / shapes / determinism ----
def test_param_sweep_views_feats_classes(self):
configs = [
([1.0], 4, 3),
([0.7, 0.3], 8, 5),
([0.5, 0.3, 0.2], 6, 7),
([0.4, 0.3, 0.2, 0.1], 5, 4),
]
for vw, feat_dim, num_classes in configs:
with self.subTest(vw=vw, feat_dim=feat_dim, num_classes=num_classes):
_, _, can_logits, gen_logits = self._run_both(vw, feat_dim=feat_dim, num_classes=num_classes)
assert_same_logits(self, can_logits, gen_logits, msg="Param sweep mismatch.")
def test_attributes_and_devices(self):
can, gen, _, _ = self._run_both(self.view_weights_mv)
self.assertEqual(can.channel, self.feat_dim)
self.assertEqual(gen.channel, self.feat_dim)
self.assertEqual(can.dtype, torch.float32)
self.assertEqual(gen.dtype, torch.float32)
self.assertEqual(can.view_weights.device.type, 'cpu')
self.assertTrue(can.view_weights.shape[0] == len(self.view_weights_mv))
def test_real_proj_imsize(self):
num_views = len(self.view_weights_mv)
can = make_stub_instance(CanonicalCls, num_views, self.feat_dim, self.num_classes, self.view_weights_mv, self.device)
gen = make_stub_instance(GeneratedCls, num_views, self.feat_dim, self.num_classes, self.view_weights_mv, self.device)
for s in (56, 112, 224, 320):
with self.subTest(imsize=s):
# Use injected instance methods
img_can = can.real_proj(self.pc_small, imsize=s)
img_gen = gen.real_proj(self.pc_small, imsize=s)
self.assertEqual(tuple(img_can.shape), (num_views, 3, s, s))
self.assertEqual(tuple(img_gen.shape), (num_views, 3, s, s))
np.testing.assert_array_equal(img_can.cpu().numpy(), img_gen.cpu().numpy())
def test_stateful_feature_and_label_storage(self):
can, gen, _, _ = self._run_both(self.view_weights_mv, pc=self.pc_small)
with torch.no_grad():
_ = CanonicalCls.model_inference(can, self.pc_small, label=7)
_ = GeneratedCls.model_inference(gen, self.pc_small, label=7)
self.assertEqual(len(can.feat_store), 2)
self.assertEqual(len(gen.feat_store), 2)
self.assertEqual(len(can.label_store), 2)
self.assertEqual(can.label_store[-1], 7)
self.assertEqual(gen.label_store[-1], 7)
stored_can = torch.cat(can.feat_store, dim=0)
self.assertEqual(stored_can.shape[-1], len(self.view_weights_mv) * self.feat_dim)
def test_mismatch_num_views_raises(self):
can = make_stub_instance(CanonicalCls, 3, self.feat_dim, self.num_classes, self.view_weights_mv, self.device)
gen = make_stub_instance(GeneratedCls, 3, self.feat_dim, self.num_classes, self.view_weights_mv, self.device)
can.num_views = 4
gen.num_views = 4
with torch.no_grad():
with self.assertRaises(Exception):
_ = CanonicalCls.model_inference(can, self.pc_small, label=None)
with self.assertRaises(Exception):
_ = GeneratedCls.model_inference(gen, self.pc_small, label=None)
def test_mixed_dtype_float16_path(self):
force_dtype = torch.float16
_, _, can_logits, gen_logits = self._run_both(self.view_weights_mv, force_dtype=force_dtype)
assert_same_logits(self, can_logits, gen_logits, msg="Mismatch under float16 casting.")
def test_determinism_across_calls(self):
_, _, can_logits1, gen_logits1 = self._run_both(self.view_weights_mv)
_, _, can_logits2, gen_logits2 = self._run_both(self.view_weights_mv)
np.testing.assert_array_equal(to_numpy_2d(can_logits1), to_numpy_2d(can_logits2))
np.testing.assert_array_equal(to_numpy_2d(gen_logits1), to_numpy_2d(gen_logits2))
def test_non_uniform_view_weights_patterns(self):
patterns = [
[1.0],
[1.0, 0.0],
[0.0, 1.0],
[0.2, 0.5, 0.3],
[1e-3, 1e-2, 1e-1],
]
for vw in patterns:
with self.subTest(vw=vw):
_, _, can_logits, gen_logits = self._run_both(vw)
assert_same_logits(self, can_logits, gen_logits, msg=f"Mismatch for weights {vw}.")
# ---- NEW: directly cover load_clip_to_cpu both branches ----
def test_load_clip_to_cpu_jit_branch(self):
import canonical as canonical_mod
# Patch clip and torch.jit.load success path
canonical_mod.clip = make_dummy_clip_module(embed_dim=8)
called = {"jit": False, "build": False}
class _JitObj:
def eval(self):
return self
def state_dict(self):
return {"k": 1}
def fake_jit_load(path, map_location="cpu"):
called["jit"] = True
return _JitObj()
orig_jit_load = torch.jit.load
torch.jit.load = fake_jit_load
def fake_build(state_or_weights):
called["build"] = True
# Return model with the required interface
return make_dummy_clip_module(embed_dim=8).build_model(None)
orig_build = canonical_mod.clip.build_model
canonical_mod.clip.build_model = fake_build
try:
model = canonical_mod.load_clip_to_cpu(_Dot(MODEL=_Dot(BACKBONE=_Dot(NAME="ViT-B/32"))))
self.assertTrue(called["jit"] and called["build"])
# smoke check model api
_ = model.encode_text(torch.tensor([1,2]))
finally:
torch.jit.load = orig_jit_load
canonical_mod.clip.build_model = orig_build
def test_load_clip_to_cpu_state_dict_branch(self):
import canonical as canonical_mod
canonical_mod.clip = make_dummy_clip_module(embed_dim=8)
called = {"jit": False, "torch_load": False, "build": False}
def fake_jit_load(*a, **k):
called["jit"] = True
raise RuntimeError("force non-jit path")
orig_jit_load = torch.jit.load
torch.jit.load = fake_jit_load
def fake_torch_load(path, map_location="cpu"):
called["torch_load"] = True
return {"dummy": 1}
orig_torch_load = torch.load
torch.load = fake_torch_load
def fake_build(state_or_weights):
called["build"] = True
return make_dummy_clip_module(embed_dim=8).build_model(None)
orig_build = canonical_mod.clip.build_model
canonical_mod.clip.build_model = fake_build
try:
model = canonical_mod.load_clip_to_cpu(_Dot(MODEL=_Dot(BACKBONE=_Dot(NAME="ViT-B/32"))))
self.assertTrue(called["jit"] and called["torch_load"] and called["build"])
_ = model.encode_text(torch.tensor([1,2]))
finally:
torch.jit.load = orig_jit_load
torch.load = orig_torch_load
canonical_mod.clip.build_model = orig_build
# ---- NEW: end-to-end build_model + inference (canonical vs generated) ----
def test_build_model_end_to_end_equivalence(self):
"""
Run the real build_model and textual encoder with dummy clip/projection,
then perform model_inference on both classes and compare.
"""
# Patch canonical + generated modules similarly
can_inst, can_mod = patch_canonical_for_build_model(
self, num_views=3, backbone="ViT-B/32", backbone_name2="vitb32",
dataset_name="MockSet", channel=self.feat_dim,
classnames=[f"class_{i}" for i in range(self.num_classes)]
)
import zeroshot as generated_mod
# Mirror the same patches for the generated module API names
generated_mod.clip = can_mod.clip
generated_mod.best_prompt_weight = can_mod.best_prompt_weight
generated_mod.Realistic_Projection = can_mod.Realistic_Projection
# cfg/dm for gen instance
gen_inst = GeneratedCls.__new__(GeneratedCls)
gen_inst.cfg = can_inst.cfg
gen_inst.dm = can_inst.dm
with NoCudaTensorMonkeypatch():
# --- Patch torch.jit.load to avoid real filesystem access ---
class _JitObj:
def eval(self): # canonical code calls .eval()
return self
def state_dict(self): # canonical passes model.state_dict() to clip.build_model
return {"weights": torch.tensor([1.0])}
orig_jit_load = torch.jit.load
torch.jit.load = lambda *a, **k: _JitObj()
try:
# build both models (will exercise load_clip_to_cpu JIT path)
CanonicalCls.build_model(can_inst)
GeneratedCls.build_model(gen_inst)
# sanity checks from your original code
self.assertEqual(can_inst.num_views, 3)
self.assertEqual(gen_inst.num_views, 3)
self.assertEqual(can_inst.channel, self.feat_dim)
self.assertEqual(gen_inst.channel, self.feat_dim)
self.assertEqual(can_inst.text_feat.shape[-1], gen_inst.text_feat.shape[-1])
# end-to-end inference using real_proj/visual encoders created by build_model
with torch.no_grad():
can_logits = CanonicalCls.model_inference(can_inst, self.pc_small, label=1)
gen_logits = GeneratedCls.model_inference(gen_inst, self.pc_small, label=1)
assert_same_logits(self, can_logits, gen_logits,
msg="E2E logits mismatch after build_model.")
self.assertTrue(len(can_inst.feat_store) >= 1)
self.assertTrue(len(gen_inst.label_store) >= 1)
finally:
# always restore to avoid side-effects on other tests
torch.jit.load = orig_jit_load
if __name__ == "__main__":
unittest.main()
|