import tempfile import unittest import numpy as np from PIL import Image import torch from binding_clip.data import compare_scene, encode_caption from binding_clip.evaluate import deltas from binding_clip.infer import rank_captions from binding_clip.model import Config, MODES, build_model, load_model, save_model from binding_clip.train import localization_loss class CaptionTests(unittest.TestCase): def test_counterfactuals_are_false_for_every_object_pair(self): objects = [ ("red", "cube", 0.10, 0.70), ("blue", "sphere", 0.40, 0.70), ("blue", "cube", 0.20, 0.50), ("red", "sphere", 0.80, 0.35), ] comparisons = list(compare_scene(objects)) self.assertTrue(comparisons) for record in comparisons: for index, (color_a, shape_a, relation, color_b, shape_b) in enumerate(record.captions): matches = [ a[2] < b[2] if relation == "left" else a[2] > b[2] for a in objects if a[:2] == (color_a, shape_a) for b in objects if b[:2] == (color_b, shape_b) ] self.assertEqual(any(matches), index == 0) def test_constrained_caption_parser(self): self.assertEqual( encode_caption("A red cube left of a blue sphere."), encode_caption("red cube left of blue sphere"), ) with self.assertRaises(ValueError): encode_caption("A red car above a blue sphere.") class ModelTests(unittest.TestCase): def setUp(self): torch.manual_seed(7) torch.set_num_threads(2) self.captions = ["red cube left of blue sphere", "red cube right of blue sphere"] self.tokens = torch.tensor([encode_caption(caption) for caption in self.captions]).unsqueeze(0) self.images = torch.randint(0, 255, (1, 32, 32, 3), dtype=torch.uint8) def test_trainable_modes_and_checkpoint_roundtrip(self): for mode in MODES: with self.subTest(mode=mode), tempfile.TemporaryDirectory() as folder: model = build_model(Config(mode, 32, 24, 1, 4, 16, 4)).eval() scores, affinities = model(self.images, self.tokens) self.assertEqual(tuple(scores.shape), (1, 2)) objective = scores.square().mean() if affinities is not None: objective += localization_loss(model, affinities, torch.full((1, 2, 2), 0.5)) if mode == "pair": self.assertFalse(torch.equal(model.geometry[0, 1], model.geometry[1, 0])) if mode == "factorized": torch.testing.assert_close(model.allowed_pairs[0], model.allowed_pairs[1].T) objective.backward() self.assertTrue(all(p.grad is not None and torch.isfinite(p.grad).all() for p in model.parameters())) save_model(model, folder) reloaded = load_model(folder) torch.testing.assert_close(reloaded(self.images, self.tokens)[0], scores) image = Image.fromarray(self.images[0].numpy()) results = rank_captions(reloaded, image, self.captions) self.assertEqual({row["caption"] for row in results}, set(self.captions)) self.assertGreaterEqual(results[0]["score"], results[1]["score"]) def test_paired_deltas(self): cross = np.array([True, True, False]) scenes = np.array([0, 0, 1]) first = (np.zeros((3, 2), dtype=bool), cross, scenes) second = (np.ones((3, 2), dtype=bool), cross, scenes) self.assertEqual(deltas(first, second)["joint"]["all"]["accuracy"], 1) if __name__ == "__main__": unittest.main()