2020-10-06 13:05:20 +00:00
|
|
|
import os
|
2021-05-06 19:05:35 +00:00
|
|
|
|
2020-10-06 13:05:20 +00:00
|
|
|
import torch
|
2021-05-06 19:05:35 +00:00
|
|
|
from torch.utils.data import DataLoader, Dataset
|
|
|
|
|
2020-12-29 08:19:02 +00:00
|
|
|
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):
|
2021-04-25 06:01:25 +00:00
|
|
|
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):
|
2021-04-25 06:01:25 +00:00
|
|
|
loss = self(batch).sum()
|
|
|
|
self.log("valid_loss", loss)
|
2020-10-06 13:05:20 +00:00
|
|
|
|
|
|
|
def test_step(self, batch, batch_idx):
|
2021-04-25 06:01:25 +00:00
|
|
|
loss = self(batch).sum()
|
|
|
|
self.log("test_loss", loss)
|
2020-10-06 13:05:20 +00:00
|
|
|
|
|
|
|
def configure_optimizers(self):
|
2021-04-25 06:01:25 +00:00
|
|
|
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
|
|
|
|
2021-04-25 06:01:25 +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
|
|
|
|
2021-04-25 06:01:25 +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,
|
2021-11-22 11:19:46 +00:00
|
|
|
limit_test_batches=1,
|
2021-04-25 06:01:25 +00:00
|
|
|
num_sanity_val_steps=0,
|
2020-10-06 13:05:20 +00:00
|
|
|
max_epochs=1,
|
2021-10-13 11:50:54 +00:00
|
|
|
enable_model_summary=False,
|
2020-10-06 13:05:20 +00:00
|
|
|
)
|
2021-06-29 12:23:48 +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
|
|
|
|
|
|
|
|
2021-07-26 11:37:35 +00:00
|
|
|
if __name__ == "__main__":
|
2021-04-25 06:01:25 +00:00
|
|
|
run()
|