-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_trainer.py
More file actions
59 lines (43 loc) · 1.84 KB
/
Copy pathtest_trainer.py
File metadata and controls
59 lines (43 loc) · 1.84 KB
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
import pytest
from src.models import EmoteVisionModel
from src import Trainer
import os
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, TensorDataset
class DummyTrainDataModule:
"""Minimal data model"""
def get_train_loader(self):
x = torch.randn(10,2)
y = torch.randint(0, 2, (10,))
return DataLoader(TensorDataset(x, y), batch_size = 2)
@pytest.fixture
def trainer_setup():
model = nn.Linear(2, 2)
optimizer = torch.optim.SGD(model.parameters(), lr = 0.1)
criterion = nn.CrossEntropyLoss()
trainer = Trainer(model = model, optimizer = optimizer, criterion = criterion, epochs = 1)
return trainer, model
def test_fit_with_no_data_provider(trainer_setup):
trainer, _ = trainer_setup
with pytest.raises(AttributeError):
trainer.fit(data_provider = None)
def test_fit_with_a_valid_data_provider(trainer_setup):
trainer, _ = trainer_setup
dummy_data = DummyTrainDataModule()
# completes the test without issues with one epoch
trainer.fit(data_provider = dummy_data)
def test_fit_changes_model_weight(trainer_setup):
trainer, model = trainer_setup
dummy_data = DummyTrainDataModule()
initial_weight = model.weight.clone()
trainer.fit(data_provider = dummy_data)
assert not torch.equal(initial_weight, model.weight), "Model weights did not update during training!"
def test_fit_saves_model_in_artifacts(tmp_path, trainer_setup, monkeypatch):
trainer, _ = trainer_setup
monkeypatch.setattr("src.trainer.ARTIFACTS_DIR", str(tmp_path / "artifacts"))
artifacts_folder = tmp_path / "artifacts" / "models"
dummy_data = DummyTrainDataModule()
trainer.fit(data_provider=dummy_data)
assert artifacts_folder.exists(), "Models directory was not created"
assert any(artifacts_folder.iterdir()), "Models directory is empty"