-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
7 changed files
with
190 additions
and
79 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,67 +1,106 @@ | ||
import logging | ||
import os | ||
from typing import Any, Dict | ||
|
||
import torch | ||
from torch.utils.data import DataLoader, Dataset | ||
import torch.nn as nn | ||
import torch.optim as optim | ||
from torch.optim import AdamW | ||
from torch.utils.data import DataLoader | ||
|
||
from pytorch_lightning import LightningModule, Trainer | ||
import pytorch_lightning as pl | ||
from pytorch_lightning.callbacks import LearningRateMonitor, ModelCheckpoint | ||
|
||
|
||
class RandomDataset(Dataset): | ||
class ToyModel(nn.Module): | ||
|
||
def __init__(self, size, length): | ||
self.len = length | ||
self.data = torch.randn(length, size) | ||
|
||
def __getitem__(self, index): | ||
return self.data[index] | ||
def __init__(self): | ||
super().__init__() | ||
self.net1 = nn.Linear(10, 10) | ||
self.relu = nn.ReLU() | ||
self.net2 = nn.Linear(10, 5) | ||
|
||
def __len__(self): | ||
return self.len | ||
def forward(self, x): | ||
return self.net2(self.relu(self.net1(x))) | ||
|
||
|
||
class BoringModel(LightningModule): | ||
class ToyTask(pl.LightningModule): | ||
|
||
def __init__(self): | ||
super().__init__() | ||
self.layer = torch.nn.Linear(32, 2) | ||
self.loss_fn = nn.MSELoss() | ||
|
||
def setup(self, stage: str): | ||
if stage == "test": | ||
return | ||
self.setup_model_and_optimizer() | ||
print("setup called") | ||
|
||
def setup_model_and_optimizer(self): | ||
self.model = ToyModel() | ||
self.optimizer = AdamW( | ||
self.model.parameters(), lr=0.001, betas=[0.9, 0.999], eps=1.0e-08, weight_decay=0, amsgrad=False | ||
) | ||
|
||
def forward(self, x): | ||
return self.layer(x) | ||
return self.model(x) | ||
|
||
def training_step(self, batch, batch_idx): | ||
loss = self(batch).sum() | ||
self.log("train_loss", loss) | ||
return {"loss": loss} | ||
targets = self.forward(batch["model_input"]) | ||
loss = self.loss_fn(targets, batch["label"]) | ||
|
||
def validation_step(self, batch, batch_idx): | ||
loss = self(batch).sum() | ||
self.log("valid_loss", loss) | ||
# Log loss results per train step and per epoch | ||
self.log("loss", loss) | ||
|
||
def test_step(self, batch, batch_idx): | ||
loss = self(batch).sum() | ||
self.log("test_loss", loss) | ||
# Tell Lightning to minimize loss | ||
return loss | ||
|
||
def configure_optimizers(self): | ||
return torch.optim.SGD(self.layer.parameters(), lr=0.1) | ||
|
||
|
||
def run(): | ||
train_data = DataLoader(RandomDataset(32, 64), batch_size=2) | ||
val_data = DataLoader(RandomDataset(32, 64), batch_size=2) | ||
test_data = DataLoader(RandomDataset(32, 64), batch_size=2) | ||
|
||
model = BoringModel() | ||
trainer = Trainer( | ||
default_root_dir=os.getcwd(), | ||
limit_train_batches=1, | ||
limit_val_batches=1, | ||
num_sanity_val_steps=0, | ||
max_epochs=1, | ||
weights_summary=None, | ||
return self.optimizer | ||
|
||
# def on_load_checkpoint(self, checkpoint: Dict[str, Any]) -> None: | ||
# self.setup_model_and_optimizer() | ||
|
||
|
||
if __name__ == "__main__": | ||
task = ToyTask() | ||
|
||
dataset = [{"model_input": torch.randn(20, 10), "label": torch.randn(20, 5)} for _ in range(10)] | ||
|
||
train_dataloader = DataLoader(dataset, batch_size=None) | ||
val_dataloader = DataLoader(dataset, batch_size=None) | ||
|
||
model_checkpoint = ModelCheckpoint( | ||
save_last=True, | ||
every_n_val_epochs=1, | ||
) | ||
trainer.fit(model, train_dataloader=train_data, val_dataloaders=val_data) | ||
trainer.test(model, test_dataloaders=test_data) | ||
|
||
trainer = pl.Trainer( | ||
gpus=2, | ||
precision=16, | ||
max_epochs=3, | ||
progress_bar_refresh_rate=100, | ||
log_gpu_memory=None, | ||
reload_dataloaders_every_epoch=True, | ||
limit_train_batches=10, | ||
limit_val_batches=10, | ||
limit_test_batches=10, | ||
callbacks=[model_checkpoint], | ||
) | ||
|
||
results = trainer.fit(task, train_dataloader) | ||
|
||
if __name__ == '__main__': | ||
run() | ||
print(model_checkpoint.last_model_path) | ||
|
||
trainer = pl.Trainer( | ||
gpus=2, | ||
precision=16, | ||
max_epochs=4, | ||
reload_dataloaders_every_epoch=True, | ||
limit_train_batches=10, | ||
limit_val_batches=10, | ||
limit_test_batches=10, | ||
callbacks=[model_checkpoint], | ||
resume_from_checkpoint=model_checkpoint.last_model_path, | ||
) | ||
trainer.fit(task, train_dataloader) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
import torch | ||
from torch.utils.data import DataLoader | ||
|
||
import pytorch_lightning as pl | ||
from pl_examples.bug_report_model import ToyTask | ||
from pytorch_lightning.callbacks import ModelCheckpoint | ||
|
||
if __name__ == "__main__": | ||
task = ToyTask() | ||
|
||
dataset = [{"model_input": torch.randn(20, 10), "label": torch.randn(20, 5)} for _ in range(10)] | ||
|
||
train_dataloader = DataLoader(dataset, batch_size=None) | ||
val_dataloader = DataLoader(dataset, batch_size=None) | ||
|
||
model_checkpoint = ModelCheckpoint( | ||
save_last=True, | ||
every_n_val_epochs=1, | ||
) | ||
|
||
trainer = pl.Trainer( | ||
gpus=2, | ||
precision=16, | ||
max_epochs=4, | ||
reload_dataloaders_every_epoch=True, | ||
limit_train_batches=10, | ||
limit_val_batches=10, | ||
limit_test_batches=10, | ||
callbacks=[model_checkpoint], | ||
resume_from_checkpoint= | ||
"/home/adrian/repositories/pytorch-lightning/lightning_logs/version_82/checkpoints/last.ckpt", | ||
) | ||
trainer.fit(task, train_dataloader) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.