Spaces:
Sleeping
Sleeping
File size: 4,712 Bytes
1024e04 | 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 | """Offline contract tests: python -m unittest engine.test_engine -v."""
import hashlib
import os
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
import numpy as np
import torch
from torchvision.transforms import Resize
from torchvision.transforms._transforms_video import ToTensorVideo
from .architecture import SyntaxModel, artery_model, classifier_stream
from .dicom import InferenceError
from .preprocessing import MEAN, STD, preprocess_classifier, preprocess_score, to_uint8
from .runtime import combine_folds
from .weights import MANIFEST, weight_file
class EngineTests(unittest.TestCase):
def test_transform_matches_reference_and_repeat_center_order(self):
source = np.arange(10 * 25 * 27, dtype=np.uint16).reshape(10, 25, 27)
video = (source.astype(np.float32) * (255.0 / int(source.max()))).clip(0, 255).astype(np.uint8)
video = np.concatenate([video, video, video, video])[4:36]
expected = ToTensorVideo()(torch.from_numpy(np.stack([video] * 3, axis=-1)))
expected = Resize((256, 256), antialias=True)(expected)
expected = (expected - torch.tensor(MEAN)[:, None, None, None]) / torch.tensor(STD)[:, None, None, None]
torch.testing.assert_close(preprocess_score(source), expected, rtol=0, atol=0)
def test_signed_and_empty_inputs_fail(self):
for video in [np.zeros((10, 2, 2), dtype=np.int16), np.zeros((0, 2, 2), dtype=np.uint8),
np.zeros((10, 2, 2), dtype=np.uint16)]:
with self.assertRaises(InferenceError):
to_uint8(video)
def test_classifier_transform_pins_historical_resize_and_all_frames(self):
source = np.random.default_rng(7).integers(0, 256, (35, 29, 31), dtype=np.uint8)
expected = ToTensorVideo()(torch.from_numpy(np.stack([source] * 3, axis=-1)))
expected = Resize((224, 224), antialias=False)(expected)
expected = (expected - torch.tensor(MEAN)[:, None, None, None]) / torch.tensor(STD)[:, None, None, None]
torch.testing.assert_close(preprocess_classifier(source), expected, rtol=0, atol=0)
self.assertFalse(MANIFEST["preprocessing"]["classifier"]["antialias"])
self.assertTrue(MANIFEST["preprocessing"]["score"]["antialias"])
def test_calibration_pairs_folds_and_clips_only_final_mean(self):
left = [-4., 1., 2., 3., 4.]
right = [1., 2., -4., 0., 1.]
coefficients = MANIFEST["calibration"]["folds"]
result = combine_folds(left, right, coefficients)
expected = sum(c["a"] * (l + r) + c["b"] for l, r, c in zip(left, right, coefficients)) / 5
self.assertAlmostEqual(result["calibrated"], max(0., expected))
self.assertEqual(result["per_fold"][0]["raw"], -3.)
self.assertEqual(result["per_fold"][2]["raw"], -2.)
with self.assertRaises(InferenceError):
combine_folds(left[:-1], right, coefficients)
with self.assertRaises(InferenceError):
combine_folds([float("nan")] * 5, right, coefficients)
def test_streamed_architecture_matches_batched_and_uses_projection_order(self):
torch.manual_seed(1)
torch.set_num_threads(2)
model = SyntaxModel().eval()
clips = torch.randn(1, 3, 3, 4, 32, 32)
with torch.inference_mode():
batch = model(clips)
stream = model.forward_stream(iter(clips[0]))
reverse = model.forward_stream(iter(clips[0].flip(0)))
torch.testing.assert_close(batch, stream, rtol=1e-5, atol=1e-6)
self.assertFalse(torch.allclose(stream, reverse, rtol=1e-5, atol=1e-6))
def test_corrupt_checkpoint_rejected_before_loading(self):
with tempfile.TemporaryDirectory() as folder, patch.dict(os.environ, {"SYNTAX_MODEL_CACHE": folder}):
path = Path(folder) / "model.safetensors"
path.write_bytes(b"bad")
with self.assertRaisesRegex(InferenceError, "checksum"):
weight_file({"path": path.name, "size": 3, "sha256": hashlib.sha256(b"yes").hexdigest()})
def test_classifier_temporal_tiling_matches_all_frames(self):
torch.manual_seed(9)
torch.set_num_threads(2)
model = artery_model().eval()
# Exercise real boundaries and non-stride-aligned total lengths.
for frames in (7, 127, 195):
clip = torch.randn(3, frames, 24, 24)
with torch.inference_mode():
full = model(clip.unsqueeze(0))
tiled = classifier_stream(model, frames, lambda a, b: clip[:, a:b], chunk_outputs=4)
torch.testing.assert_close(full, tiled, rtol=2e-5, atol=2e-6)
if __name__ == "__main__":
unittest.main()
|