lightning/pl_examples/bug_report/bug_report_model.py

67 lines
1.7 KiB
Python
Raw Normal View History

2020-10-06 13:05:20 +00:00
import os
2020-10-06 13:05:20 +00:00
import torch
from torch.utils.data import DataLoader, Dataset
from pytorch_lightning import LightningModule, Trainer
2020-10-06 13:05:20 +00:00
class RandomDataset(Dataset):
def __init__(self, size, length):
self.len = length
self.data = torch.randn(length, size)
def __getitem__(self, index):
return self.data[index]
def __len__(self):
return self.len
class BoringModel(LightningModule):
def __init__(self):
super().__init__()
self.layer = torch.nn.Linear(32, 2)
def forward(self, x):
return self.layer(x)
def training_step(self, batch, batch_idx):
loss = self(batch).sum()
self.log("train_loss", loss)
2020-10-06 13:05:20 +00:00
return {"loss": loss}
def validation_step(self, batch, batch_idx):
loss = self(batch).sum()
self.log("valid_loss", loss)
2020-10-06 13:05:20 +00:00
def test_step(self, batch, batch_idx):
loss = self(batch).sum()
self.log("test_loss", loss)
2020-10-06 13:05:20 +00:00
def configure_optimizers(self):
return torch.optim.SGD(self.layer.parameters(), lr=0.1)
2021-01-30 10:17:12 +00:00
2020-10-06 13:05:20 +00:00
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)
2020-10-06 13:05:20 +00:00
model = BoringModel()
2020-10-06 13:05:20 +00:00
trainer = Trainer(
default_root_dir=os.getcwd(),
limit_train_batches=1,
limit_val_batches=1,
limit_test_batches=1,
num_sanity_val_steps=0,
2020-10-06 13:05:20 +00:00
max_epochs=1,
enable_model_summary=False,
2020-10-06 13:05:20 +00:00
)
trainer.fit(model, train_dataloaders=train_data, val_dataloaders=val_data)
trainer.test(model, dataloaders=test_data)
2020-10-06 13:05:20 +00:00
if __name__ == "__main__":
run()