|
| 1 | +import numpy as np |
| 2 | + |
| 3 | +from transcriptml.data.bundle import DatasetBundle, save_bundle |
| 4 | +from transcriptml.devices import resolve_device |
| 5 | +from transcriptml.interpret.predictor import Predictor |
| 6 | +from transcriptml.models.registry import build_model, save_checkpoint |
| 7 | +from transcriptml.training.evaluation import evaluate_checkpoint |
| 8 | + |
| 9 | + |
| 10 | +def _small_model_config() -> dict[str, object]: |
| 11 | + return { |
| 12 | + "name": "small_cnn", |
| 13 | + "params": { |
| 14 | + "in_ch": 4, |
| 15 | + "n_filters": 4, |
| 16 | + "kernel_size": 3, |
| 17 | + "n_layers": 1, |
| 18 | + "dropout": 0.0, |
| 19 | + "head_hidden": 4, |
| 20 | + }, |
| 21 | + } |
| 22 | + |
| 23 | + |
| 24 | +def _write_checkpoint_and_bundle(tmp_path): |
| 25 | + model_config = _small_model_config() |
| 26 | + model = build_model(model_config) |
| 27 | + checkpoint = tmp_path / "model.pt" |
| 28 | + save_checkpoint(checkpoint, model, model_config) |
| 29 | + |
| 30 | + X = np.zeros((3, 4, 12), dtype=np.float32) |
| 31 | + X[:, 0, :] = 1.0 |
| 32 | + bundle = DatasetBundle( |
| 33 | + X=X, |
| 34 | + y=np.array([0.0, 1.0, 2.0], dtype=np.float32), |
| 35 | + ids=["a", "b", "c"], |
| 36 | + schema="rna4", |
| 37 | + splits={"train": [0], "val": [1], "test": [2]}, |
| 38 | + ) |
| 39 | + dataset = tmp_path / "dataset" |
| 40 | + save_bundle(bundle, dataset) |
| 41 | + return checkpoint, dataset |
| 42 | + |
| 43 | + |
| 44 | +def test_resolve_device_auto_cpu_when_cuda_unavailable(monkeypatch): |
| 45 | + monkeypatch.setattr("torch.cuda.is_available", lambda: False) |
| 46 | + assert str(resolve_device("auto")) == "cpu" |
| 47 | + |
| 48 | + |
| 49 | +def test_evaluate_checkpoint_accepts_auto_device(tmp_path, monkeypatch): |
| 50 | + monkeypatch.setattr("torch.cuda.is_available", lambda: False) |
| 51 | + checkpoint, dataset = _write_checkpoint_and_bundle(tmp_path) |
| 52 | + |
| 53 | + result = evaluate_checkpoint( |
| 54 | + checkpoint, |
| 55 | + dataset, |
| 56 | + tmp_path / "predictions.csv", |
| 57 | + split="test", |
| 58 | + device="auto", |
| 59 | + progress=False, |
| 60 | + ) |
| 61 | + |
| 62 | + assert len(result["predictions"]) == 1 |
| 63 | + assert (tmp_path / "predictions.csv").exists() |
| 64 | + |
| 65 | + |
| 66 | +def test_predictor_from_checkpoint_accepts_auto_device(tmp_path, monkeypatch): |
| 67 | + monkeypatch.setattr("torch.cuda.is_available", lambda: False) |
| 68 | + checkpoint, _ = _write_checkpoint_and_bundle(tmp_path) |
| 69 | + |
| 70 | + predictor = Predictor.from_checkpoint(checkpoint, device="auto", batch_size=2) |
| 71 | + preds = predictor.predict(np.zeros((2, 4, 12), dtype=np.float32)) |
| 72 | + |
| 73 | + assert preds.shape == (2,) |
0 commit comments