Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Apply black on some files #565

Merged
merged 1 commit into from
Dec 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
from torch.utils.data import DataLoader

# Define any torch DataLoaders, need at least train & valid loaders
train_dataset = CIFAR10(root='data/', download=True, train=True, transform=ToTensor())
valid_dataset = CIFAR10(root='data/', download=True, train=False, transform=ToTensor())
train_dataset = CIFAR10(root="data/", download=True, train=True, transform=ToTensor())
valid_dataset = CIFAR10(root="data/", download=True, train=False, transform=ToTensor())

train_loader = DataLoader(train_dataset, shuffle=True, batch_size=16)
valid_loader = DataLoader(valid_dataset, batch_size=32)
Expand All @@ -45,21 +45,24 @@
# Define phase callbacks
phase_callbacks = [
LRSchedulerCallback(scheduler=rop_lr_scheduler, phase=Phase.VALIDATION_EPOCH_END, metric_name="Accuracy"),
LRSchedulerCallback(scheduler=step_lr_scheduler, phase=Phase.TRAIN_EPOCH_END)]
LRSchedulerCallback(scheduler=step_lr_scheduler, phase=Phase.TRAIN_EPOCH_END),
]

# Bring everything together with Trainer and start training
trainer = Trainer("Cifar10_external_objects_example", multi_gpu=MultiGPUMode.OFF)

train_params = {"max_epochs": 300,
"phase_callbacks": phase_callbacks,
"initial_lr": lr,
"loss": loss_fn,
"criterion_params": {},
'optimizer': optimizer,
"train_metrics_list": [Accuracy(), Top5()],
"valid_metrics_list": [Accuracy(), Top5()],
"metric_to_watch": "Accuracy",
"greater_metric_to_watch_is_better": True,
"lr_scheduler_step_type": "epoch"}
train_params = {
"max_epochs": 300,
"phase_callbacks": phase_callbacks,
"initial_lr": lr,
"loss": loss_fn,
"criterion_params": {},
"optimizer": optimizer,
"train_metrics_list": [Accuracy(), Top5()],
"valid_metrics_list": [Accuracy(), Top5()],
"metric_to_watch": "Accuracy",
"greater_metric_to_watch_is_better": True,
"lr_scheduler_step_type": "epoch",
}

trainer.train(model=net, training_params=train_params, train_loader=train_loader, valid_loader=valid_loader)
46 changes: 23 additions & 23 deletions tests/integration_tests/ema_train_integration_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ def do_nothing():


class CallWrapper:

def __init__(self, f, check_before=do_nothing):
self.f = f
self.check_before = check_before
Expand All @@ -21,10 +20,8 @@ def __call__(self, *args, **kwargs):


class EMAIntegrationTest(unittest.TestCase):

def _init_model(self) -> None:
self.trainer = Trainer("resnet18_cifar_ema_test",
device='cpu', multi_gpu=MultiGPUMode.OFF)
self.trainer = Trainer("resnet18_cifar_ema_test", device="cpu", multi_gpu=MultiGPUMode.OFF)
self.model = models.get("resnet18_cifar", arch_params={"num_classes": 5})

@classmethod
Expand All @@ -38,21 +35,24 @@ def test_train(self):
self._train({"exp_activation": False})

def _train(self, ema_params):
training_params = {"max_epochs": 4,
"lr_updates": [4],
"lr_mode": "step",
"lr_decay_factor": 0.1,
"lr_warmup_epochs": 0,
"initial_lr": 0.1,
"loss": "cross_entropy",
"optimizer": "SGD",
"criterion_params": {},
"ema": True,
"ema_params": ema_params,
"optimizer_params": {"weight_decay": 1e-4, "momentum": 0.9},
"train_metrics_list": [Accuracy(), Top5()], "valid_metrics_list": [Accuracy(), Top5()],
"metric_to_watch": "Accuracy",
"greater_metric_to_watch_is_better": True}
training_params = {
"max_epochs": 4,
"lr_updates": [4],
"lr_mode": "step",
"lr_decay_factor": 0.1,
"lr_warmup_epochs": 0,
"initial_lr": 0.1,
"loss": "cross_entropy",
"optimizer": "SGD",
"criterion_params": {},
"ema": True,
"ema_params": ema_params,
"optimizer_params": {"weight_decay": 1e-4, "momentum": 0.9},
"train_metrics_list": [Accuracy(), Top5()],
"valid_metrics_list": [Accuracy(), Top5()],
"metric_to_watch": "Accuracy",
"greater_metric_to_watch_is_better": True,
}

def before_test():
self.assertEqual(self.trainer.net, self.trainer.ema_model.ema)
Expand All @@ -63,12 +63,12 @@ def before_train_epoch():
self.trainer.test = CallWrapper(self.trainer.test, check_before=before_test)
self.trainer._train_epoch = CallWrapper(self.trainer._train_epoch, check_before=before_train_epoch)

self.trainer.train(model=self.model, training_params=training_params,
train_loader=classification_test_dataloader(),
valid_loader=classification_test_dataloader())
self.trainer.train(
model=self.model, training_params=training_params, train_loader=classification_test_dataloader(), valid_loader=classification_test_dataloader()
)

self.assertIsNotNone(self.trainer.ema_model)


if __name__ == '__main__':
if __name__ == "__main__":
unittest.main()
91 changes: 54 additions & 37 deletions tests/unit_tests/kd_ema_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,30 +13,42 @@
class KDEMATest(unittest.TestCase):
@classmethod
def setUp(cls):
cls.sg_trained_teacher = Trainer("sg_trained_teacher", device='cpu')

cls.kd_train_params = {"max_epochs": 3, "lr_updates": [1], "lr_decay_factor": 0.1, "lr_mode": "step",
"lr_warmup_epochs": 0, "initial_lr": 0.1,
"loss": KDLogitsLoss(torch.nn.CrossEntropyLoss()),
"optimizer": "SGD",
"criterion_params": {}, "optimizer_params": {"weight_decay": 1e-4, "momentum": 0.9},
"train_metrics_list": [Accuracy()], "valid_metrics_list": [Accuracy()],
"metric_to_watch": "Accuracy",
'loss_logging_items_names': ["Loss", "Task Loss", "Distillation Loss"],
"greater_metric_to_watch_is_better": True, "average_best_models": False,
"ema": True}
cls.sg_trained_teacher = Trainer("sg_trained_teacher", device="cpu")

cls.kd_train_params = {
"max_epochs": 3,
"lr_updates": [1],
"lr_decay_factor": 0.1,
"lr_mode": "step",
"lr_warmup_epochs": 0,
"initial_lr": 0.1,
"loss": KDLogitsLoss(torch.nn.CrossEntropyLoss()),
"optimizer": "SGD",
"criterion_params": {},
"optimizer_params": {"weight_decay": 1e-4, "momentum": 0.9},
"train_metrics_list": [Accuracy()],
"valid_metrics_list": [Accuracy()],
"metric_to_watch": "Accuracy",
"loss_logging_items_names": ["Loss", "Task Loss", "Distillation Loss"],
"greater_metric_to_watch_is_better": True,
"average_best_models": False,
"ema": True,
}

def test_teacher_ema_not_duplicated(self):
"""Check that the teacher EMA is a reference to the teacher net (not a copy)."""

kd_model = KDTrainer("test_teacher_ema_not_duplicated", device='cpu')
student = models.get('resnet18', arch_params={'num_classes': 1000})
teacher = models.get('resnet50', arch_params={'num_classes': 1000},
pretrained_weights="imagenet")
kd_model = KDTrainer("test_teacher_ema_not_duplicated", device="cpu")
student = models.get("resnet18", arch_params={"num_classes": 1000})
teacher = models.get("resnet50", arch_params={"num_classes": 1000}, pretrained_weights="imagenet")

kd_model.train(training_params=self.kd_train_params, student=student, teacher=teacher,
train_loader=classification_test_dataloader(),
valid_loader=classification_test_dataloader())
kd_model.train(
training_params=self.kd_train_params,
student=student,
teacher=teacher,
train_loader=classification_test_dataloader(),
valid_loader=classification_test_dataloader(),
)

self.assertTrue(kd_model.ema_model.ema.module.teacher is kd_model.net.module.teacher)
self.assertTrue(kd_model.ema_model.ema.module.student is not kd_model.net.module.student)
Expand All @@ -46,27 +58,33 @@ def test_kd_ckpt_reload_net(self):

# Create a KD trainer and train it
train_params = self.kd_train_params.copy()
kd_model = KDTrainer("test_kd_ema_ckpt_reload", device='cpu')
student = models.get('resnet18', arch_params={'num_classes': 1000})
teacher = models.get('resnet50', arch_params={'num_classes': 1000},
pretrained_weights="imagenet")

kd_model.train(training_params=self.kd_train_params, student=student, teacher=teacher,
train_loader=classification_test_dataloader(),
valid_loader=classification_test_dataloader())
kd_model = KDTrainer("test_kd_ema_ckpt_reload", device="cpu")
student = models.get("resnet18", arch_params={"num_classes": 1000})
teacher = models.get("resnet50", arch_params={"num_classes": 1000}, pretrained_weights="imagenet")

kd_model.train(
training_params=self.kd_train_params,
student=student,
teacher=teacher,
train_loader=classification_test_dataloader(),
valid_loader=classification_test_dataloader(),
)
ema_model = kd_model.ema_model.ema
net = kd_model.net

# Load the trained KD trainer
kd_model = KDTrainer("test_kd_ema_ckpt_reload", device='cpu')
student = models.get('resnet18', arch_params={'num_classes': 1000})
teacher = models.get('resnet50', arch_params={'num_classes': 1000},
pretrained_weights="imagenet")
kd_model = KDTrainer("test_kd_ema_ckpt_reload", device="cpu")
student = models.get("resnet18", arch_params={"num_classes": 1000})
teacher = models.get("resnet50", arch_params={"num_classes": 1000}, pretrained_weights="imagenet")

train_params["resume"] = True
kd_model.train(training_params=train_params, student=student, teacher=teacher,
train_loader=classification_test_dataloader(),
valid_loader=classification_test_dataloader())
kd_model.train(
training_params=train_params,
student=student,
teacher=teacher,
train_loader=classification_test_dataloader(),
valid_loader=classification_test_dataloader(),
)
reloaded_ema_model = kd_model.ema_model.ema
reloaded_net = kd_model.net

Expand All @@ -80,12 +98,11 @@ def test_kd_ckpt_reload_net(self):
self.assertTrue(not check_models_have_same_weights(reloaded_net, ema_model))

# loaded student ema == loaded student net (since load_ema_as_net = False)
self.assertTrue(
not check_models_have_same_weights(reloaded_ema_model.module.student, reloaded_net.module.student))
self.assertTrue(not check_models_have_same_weights(reloaded_ema_model.module.student, reloaded_net.module.student))

# loaded teacher ema == loaded teacher net (teacher always loads ema)
self.assertTrue(check_models_have_same_weights(reloaded_ema_model.module.teacher, reloaded_net.module.teacher))


if __name__ == '__main__':
if __name__ == "__main__":
unittest.main()
Loading