|
1 | 1 | import os |
| 2 | +import sys |
2 | 3 | import tempfile |
3 | 4 | import unittest |
| 5 | +import zipfile |
4 | 6 | from types import SimpleNamespace |
| 7 | +from unittest import mock |
| 8 | + |
| 9 | +try: |
| 10 | + # torch is an optional, lazily-imported SDK dependency; absent in CI. Tests that |
| 11 | + # round-trip a real checkpoint through `_process_rfdetr` are skipped without it. |
| 12 | + import torch |
| 13 | + |
| 14 | + _HAS_TORCH = True |
| 15 | +except ImportError: |
| 16 | + _HAS_TORCH = False |
5 | 17 |
|
6 | 18 | from roboflow.config import TASK_CLS, TASK_DET, TASK_OBB, TASK_POSE, TASK_SEG, TASK_SEM |
7 | 19 | from roboflow.util.model_processor import ( |
| 20 | + _RFDETR_MODEL_TYPE_TO_CLASS, |
8 | 21 | _detect_rfdetr_task, |
9 | 22 | _detect_yolo_task, |
| 23 | + _is_ptl_checkpoint, |
| 24 | + _process_rfdetr, |
| 25 | + _require_rfdetr, |
10 | 26 | get_classnames_txt_for_rfdetr, |
11 | 27 | task_of_model_type, |
12 | 28 | ) |
@@ -110,5 +126,161 @@ def test_namespace_args(self): |
110 | 126 | ) |
111 | 127 |
|
112 | 128 |
|
| 129 | +class RfdetrModelTypeToClassTest(unittest.TestCase): |
| 130 | + def test_representative_mappings(self): |
| 131 | + self.assertEqual(_RFDETR_MODEL_TYPE_TO_CLASS["rfdetr-seg-medium"], "RFDETRSegMedium") |
| 132 | + self.assertEqual(_RFDETR_MODEL_TYPE_TO_CLASS["rfdetr-base"], "RFDETRBase") |
| 133 | + |
| 134 | + def test_keys_are_rfdetr_types_and_values_are_class_names(self): |
| 135 | + for model_type, class_name in _RFDETR_MODEL_TYPE_TO_CLASS.items(): |
| 136 | + self.assertTrue(model_type.startswith("rfdetr-"), model_type) |
| 137 | + self.assertTrue(class_name.startswith("RFDETR"), class_name) |
| 138 | + # Segmentation types must map to Seg classes (and detection types must not). |
| 139 | + for model_type, class_name in _RFDETR_MODEL_TYPE_TO_CLASS.items(): |
| 140 | + self.assertEqual("seg" in model_type, "Seg" in class_name, model_type) |
| 141 | + |
| 142 | + |
| 143 | +class IsPtlCheckpointTest(unittest.TestCase): |
| 144 | + def test_true_when_lightning_version_present(self): |
| 145 | + self.assertTrue(_is_ptl_checkpoint({"pytorch-lightning_version": "2.1.0", "args": {}})) |
| 146 | + |
| 147 | + def test_false_for_plain_checkpoint(self): |
| 148 | + self.assertFalse(_is_ptl_checkpoint({"args": {}, "model": {}})) |
| 149 | + |
| 150 | + def test_false_for_non_dict(self): |
| 151 | + self.assertFalse(_is_ptl_checkpoint(None)) |
| 152 | + self.assertFalse(_is_ptl_checkpoint(SimpleNamespace(**{"pytorch-lightning_version": "2.1.0"}))) |
| 153 | + |
| 154 | + |
| 155 | +class _StubBundleModel: |
| 156 | + """Stub rf-detr model whose export_for_roboflow writes a dummy bundle on disk.""" |
| 157 | + |
| 158 | + def __init__(self, class_names=("cat", "dog")): |
| 159 | + self.class_names = list(class_names) |
| 160 | + |
| 161 | + def export_for_roboflow(self, output_dir): |
| 162 | + torch.save({"dummy": True}, os.path.join(output_dir, "weights.pt")) |
| 163 | + with open(os.path.join(output_dir, "class_names.txt"), "w") as f: |
| 164 | + for name in self.class_names: |
| 165 | + f.write(name + "\n") |
| 166 | + |
| 167 | + |
| 168 | +def _make_fake_rfdetr(*, from_checkpoint_raises=False, capabilities=True): |
| 169 | + """Build a fake `rfdetr` module for injection via sys.modules.""" |
| 170 | + |
| 171 | + stub_model = _StubBundleModel() |
| 172 | + calls = {"from_checkpoint": 0, "fallback_constructed": 0, "constructor_kwargs": None} |
| 173 | + |
| 174 | + class _RFDETR: |
| 175 | + @staticmethod |
| 176 | + def from_checkpoint(path): |
| 177 | + calls["from_checkpoint"] += 1 |
| 178 | + if from_checkpoint_raises: |
| 179 | + raise ValueError("cannot infer model class") |
| 180 | + return stub_model |
| 181 | + |
| 182 | + class _SizedModel(_StubBundleModel): |
| 183 | + def __init__(self, *, pretrain_weights): |
| 184 | + super().__init__() |
| 185 | + calls["fallback_constructed"] += 1 |
| 186 | + calls["constructor_kwargs"] = {"pretrain_weights": pretrain_weights} |
| 187 | + |
| 188 | + module = SimpleNamespace() |
| 189 | + module.RFDETR = _RFDETR |
| 190 | + # The SDK fallback resolves the subclass by name via _RFDETR_MODEL_TYPE_TO_CLASS, |
| 191 | + # e.g. "rfdetr-seg-medium" -> getattr(rfdetr, "RFDETRSegMedium"). |
| 192 | + module.RFDETRSegMedium = _SizedModel |
| 193 | + |
| 194 | + if capabilities: |
| 195 | + _RFDETR.export_for_roboflow = _StubBundleModel.export_for_roboflow # capability marker on class |
| 196 | + |
| 197 | + module._calls = calls |
| 198 | + return module |
| 199 | + |
| 200 | + |
| 201 | +class RequireRfdetrTest(unittest.TestCase): |
| 202 | + def test_raises_when_not_installed(self): |
| 203 | + with mock.patch.dict(sys.modules, {"rfdetr": None}): |
| 204 | + with self.assertRaises(RuntimeError) as ctx: |
| 205 | + _require_rfdetr() |
| 206 | + self.assertIn("pip install", str(ctx.exception).lower()) |
| 207 | + self.assertIn("rfdetr", str(ctx.exception).lower()) |
| 208 | + |
| 209 | + def test_raises_when_capability_missing(self): |
| 210 | + # rfdetr present but RFDETR lacks export_for_roboflow (too old) |
| 211 | + fake = SimpleNamespace(RFDETR=type("RFDETR", (), {})) |
| 212 | + with mock.patch.dict(sys.modules, {"rfdetr": fake}): |
| 213 | + with self.assertRaises(RuntimeError) as ctx: |
| 214 | + _require_rfdetr() |
| 215 | + self.assertIn("upgrade", str(ctx.exception).lower()) |
| 216 | + |
| 217 | + def test_returns_module_when_capable(self): |
| 218 | + fake = _make_fake_rfdetr() |
| 219 | + with mock.patch.dict(sys.modules, {"rfdetr": fake}): |
| 220 | + self.assertIs(_require_rfdetr(), fake) |
| 221 | + |
| 222 | + |
| 223 | +@unittest.skipUnless(_HAS_TORCH, "requires torch") |
| 224 | +class ProcessRfdetrPtlTest(unittest.TestCase): |
| 225 | + def _write_ptl_checkpoint(self, model_path, *, segmentation_head=False, class_names=("cat", "dog")): |
| 226 | + checkpoint = { |
| 227 | + "pytorch-lightning_version": "2.1.0", |
| 228 | + "args": {"segmentation_head": segmentation_head, "class_names": list(class_names)}, |
| 229 | + } |
| 230 | + torch.save(checkpoint, os.path.join(model_path, "checkpoint_best_ema.pth")) |
| 231 | + |
| 232 | + def test_from_checkpoint_success_produces_bundle(self): |
| 233 | + fake = _make_fake_rfdetr() |
| 234 | + with tempfile.TemporaryDirectory() as model_path: |
| 235 | + self._write_ptl_checkpoint(model_path) |
| 236 | + with mock.patch.dict(sys.modules, {"rfdetr": fake}): |
| 237 | + zip_name, model_type = _process_rfdetr("rfdetr-base", model_path, "checkpoint_best_ema.pth") |
| 238 | + self.assertEqual(model_type, "rfdetr-base") |
| 239 | + self.assertEqual(fake._calls["from_checkpoint"], 1) |
| 240 | + self.assertEqual(fake._calls["fallback_constructed"], 0) |
| 241 | + with zipfile.ZipFile(os.path.join(model_path, zip_name)) as z: |
| 242 | + self.assertIn("weights.pt", z.namelist()) |
| 243 | + |
| 244 | + def test_from_checkpoint_valueerror_falls_back_to_model_type(self): |
| 245 | + fake = _make_fake_rfdetr(from_checkpoint_raises=True) |
| 246 | + with tempfile.TemporaryDirectory() as model_path: |
| 247 | + self._write_ptl_checkpoint(model_path, segmentation_head=True) |
| 248 | + pth = os.path.join(model_path, "checkpoint_best_ema.pth") |
| 249 | + with mock.patch.dict(sys.modules, {"rfdetr": fake}): |
| 250 | + zip_name, model_type = _process_rfdetr("rfdetr-seg-medium", model_path, "checkpoint_best_ema.pth") |
| 251 | + self.assertEqual(model_type, "rfdetr-seg-medium") |
| 252 | + self.assertEqual(fake._calls["from_checkpoint"], 1) |
| 253 | + self.assertEqual(fake._calls["fallback_constructed"], 1) |
| 254 | + self.assertEqual(fake._calls["constructor_kwargs"], {"pretrain_weights": pth}) |
| 255 | + with zipfile.ZipFile(os.path.join(model_path, zip_name)) as z: |
| 256 | + self.assertIn("weights.pt", z.namelist()) |
| 257 | + |
| 258 | + def test_ptl_path_raises_when_rfdetr_absent(self): |
| 259 | + with tempfile.TemporaryDirectory() as model_path: |
| 260 | + self._write_ptl_checkpoint(model_path) |
| 261 | + with mock.patch.dict(sys.modules, {"rfdetr": None}): |
| 262 | + with self.assertRaises(RuntimeError): |
| 263 | + _process_rfdetr("rfdetr-base", model_path, "checkpoint_best_ema.pth") |
| 264 | + |
| 265 | + |
| 266 | +@unittest.skipUnless(_HAS_TORCH, "requires torch") |
| 267 | +class ProcessRfdetrLegacyTest(unittest.TestCase): |
| 268 | + def _write_legacy_checkpoint(self, model_path): |
| 269 | + checkpoint = {"args": {"segmentation_head": False, "class_names": ["cat", "dog"]}} |
| 270 | + torch.save(checkpoint, os.path.join(model_path, "weights.pt")) |
| 271 | + |
| 272 | + def test_legacy_path_produces_bundle_without_importing_rfdetr(self): |
| 273 | + with tempfile.TemporaryDirectory() as model_path: |
| 274 | + self._write_legacy_checkpoint(model_path) |
| 275 | + # Make any attempt to import rfdetr fail loudly. |
| 276 | + with mock.patch.dict(sys.modules, {"rfdetr": None}): |
| 277 | + zip_name, model_type = _process_rfdetr("rfdetr-base", model_path, "weights.pt") |
| 278 | + self.assertEqual(model_type, "rfdetr-base") |
| 279 | + with zipfile.ZipFile(os.path.join(model_path, zip_name)) as z: |
| 280 | + names = z.namelist() |
| 281 | + self.assertIn("weights.pt", names) |
| 282 | + self.assertIn("class_names.txt", names) |
| 283 | + |
| 284 | + |
113 | 285 | if __name__ == "__main__": |
114 | 286 | unittest.main() |
0 commit comments