当前位置:网站首页>Pytorch lightning tool learning

Pytorch lightning tool learning

2020-12-08 10:54:59 pprp

【GiantPandaCV Introduction 】Pytorch Lightning Is in Pytorch Based on the encapsulation of the library , In order to allow users to be detached from PyTorch Some tedious details , Focus on building core code , Provides a lot of utilities , Can make the experiment more efficient . This article will introduce the installation method 、 Design logic 、 Examples of transformation, etc .

PyTorch Lightning Provides the following more convenient functions :

  • multi-GPU Training
  • Semi precision training
  • TPU Training
  • Abstract the training details , So you can iterate quickly

Pytorch Lightning

1. Brief introduction

PyTorch lightning Is for AI Related professional The researchers 、 Graduate student 、 Doctors and other people developed .PyTorch Namely William Falcon Created in his Ph.D , The goal is to make AI The research is more scalable , Ignore some time-consuming details .

at present PyTorch Lightning Kuo already has a certain influence ,star already 1w+, At the same time, there are more than 1 Thousands of researchers are working together to maintain this framework .

PyTorch Lightning library

meanwhile PyTorch Lightning Along with PyTorch Version updates are also iterating .

 Version support

Official documents also support , Is constantly updated :

 Official documents

Here's how to install .

2. Installation method

Pytorch Lightning Easy to install , Recommended conda Environment for installation .

source activate you_env
pip install pytorch-lightning

Or use it directly pip install :

pip install pytorch-lightning

Or by conda install :

conda install pytorch-lightning -c conda-forge

3. Lightning Design idea

Lightning Most of them AI The code is divided into three parts :

  • Research code , Mainly the structure of the model 、 Training and so on . Abstracted as LightningModule class .

  • Project code , This part of the code is repetitive , such as 16 Bit accuracy , Distributed training . Abstracted as Trainer class .

  • Unnecessary code , This part of the code has nothing to do with the experiment , It's OK to , Plus it can help , Like gradient check ,log Output, etc . Abstracted as Callbacks class .

Lightning take Research code Divided into the following components :

  • Model
  • Data processing
  • Loss function
  • Optimizer

All of the above four components will be integrated into LightningModule Class , Is in Module Class is extended , A functional supplement , For example, the original optimizer was used in main Function , Is a process oriented usage , Now integrate into LightningModule in , As a method of a class .

4. LightningModule Life cycle

This part refers to https://zhuanlan.zhihu.com/p/120331610 and Official documents https://pytorch-lightning.readthedocs.io/en/latest/trainer.html

In this module , take PyTorch The code is organized in five parts :

  • Computations(init) Initialize the relevant calculation
  • Train Loop(training_step) Every step Code executed in
  • Validation Loop(validation_step) In a epoch After training Valid
  • Test Loop(test_step) After the entire training is completed Test
  • Optimizer(configure_optimizers) Configuration optimizer, etc

Show a minimalist code :

>>> import pytorch_lightning as pl
>>> class LitModel(pl.LightningModule):
...
...     def __init__(self):
...         super().__init__()
...         self.l1 = torch.nn.Linear(28 * 28, 10)
...
...     def forward(self, x):
...         return torch.relu(self.l1(x.view(x.size(0), -1)))
...
...     def training_step(self, batch, batch_idx):
...         x, y = batch
...         y_hat = self(x)
...         loss = F.cross_entropy(y_hat, y)
...         return loss
...
...     def configure_optimizers(self):
...         return torch.optim.Adam(self.parameters(), lr=0.02)

So how is the whole life cycle process organized ?

4.1 preparation

This part includes LightningModule The initialization 、 Prepare the data 、 Configuration optimizer . Only once at a time , It is equivalent to the function of a constructor .

  • __init__()( initialization LightningModule )
  • prepare_data() ( Prepare the data , Including download data 、 Preprocessing and so on )
  • configure_optimizers() ( Configuration optimizer )

4.2 test Verification part

Before actually running the code , The model will then be initialized , Then run a validation code , This prevents you from training a few epoch And then it's going to be Valid We found that the verification part was wrong . Mainly test the following functions :

  • val_dataloader()
  • validation_step()
  • validation_epoch_end()

4.3 Load data

Call the following method to load data .

  • train_dataloader()
  • val_dataloader()

4.4 Training

  • Every batch Training is called a step, So run first train_step function .

  • When passing through multiple batch, Default 49 individual step After training , It will be verified , function validation_step function .

  • When finishing a epoch After training , It will be for the whole epoch The results are verified , function validation_epoch_end function

  • (option) If necessary , You can call the test part of the code :

    • test_dataloader()
    • test_step()
    • test_epoch_end()

5. Example

With MNIST For example , take PyTorch To version code PyTorch Lightning.

5.1 PyTorch Version training MNIST

For one PyTorch In terms of code , This is the way to build a network ( Source code from PyTorch Medium example library ).

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 32, 3, 1)
        self.conv2 = nn.Conv2d(32, 64, 3, 1)
        self.dropout1 = nn.Dropout(0.25)
        self.dropout2 = nn.Dropout(0.5)
        self.fc1 = nn.Linear(9216, 128)
        self.fc2 = nn.Linear(128, 10)

    def forward(self, x):
        x = self.conv1(x)
        x = F.relu(x)
        x = self.conv2(x)
        x = F.relu(x)
        x = F.max_pool2d(x, 2)
        x = self.dropout1(x)
        x = torch.flatten(x, 1)
        x = self.fc1(x)
        x = F.relu(x)
        x = self.dropout2(x)
        x = self.fc2(x)
        output = F.log_softmax(x, dim=1)
        return output

There are two main tasks to build training function and test function .

It needs to be done in the training function :

  • Data acquisition data, target = data.to(device), target.to(device)
  • Clear optimizer gradient optimizer.zero_grad()
  • Forward propagation output = model(data)
  • Calculate the loss function loss = F.nll_loss(output, target)
  • Back propagation loss.backward()
  • The optimizer performs a single optimization optimizer.step()
def train(args, model, device, train_loader, optimizer, epoch):
    model.train()
    for batch_idx, (data, target) in enumerate(train_loader):
        data, target = data.to(device), target.to(device)
        optimizer.zero_grad()
        output = model(data)
        loss = F.nll_loss(output, target)
        loss.backward()
        optimizer.step()
        if batch_idx % args.log_interval == 0:
            print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
                epoch, batch_idx * len(data), len(train_loader.dataset),
                100. * batch_idx / len(train_loader), loss.item()))
            if args.dry_run:
                break

def test(model, device, test_loader):
    model.eval()
    test_loss = 0
    correct = 0
    with torch.no_grad():
        for data, target in test_loader:
            data, target = data.to(device), target.to(device)
            output = model(data)
            test_loss += F.nll_loss(output, target, reduction='sum').item()  # sum up batch loss
            pred = output.argmax(dim=1, keepdim=True)  # get the index of the max log-probability
            correct += pred.eq(target.view_as(pred)).sum().item()

    test_loss /= len(test_loader.dataset)

    print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
        test_loss, correct, len(test_loader.dataset),
        100. * correct / len(test_loader.dataset)))

Other parts like data loading 、 Data augmentation 、 Optimizer 、 The training process is all in main Implemented in , It's a process oriented approach .

def main():
    # Training settings
    parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
    parser.add_argument('--batch-size', type=int, default=64, metavar='N',
                        help='input batch size for training (default: 64)')
    parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',
                        help='input batch size for testing (default: 1000)')
    parser.add_argument('--epochs', type=int, default=14, metavar='N',
                        help='number of epochs to train (default: 14)')
    parser.add_argument('--lr', type=float, default=1.0, metavar='LR',
                        help='learning rate (default: 1.0)')
    parser.add_argument('--gamma', type=float, default=0.7, metavar='M',
                        help='Learning rate step gamma (default: 0.7)')
    parser.add_argument('--no-cuda', action='store_true', default=False,
                        help='disables CUDA training')
    parser.add_argument('--dry-run', action='store_true', default=False,
                        help='quickly check a single pass')
    parser.add_argument('--seed', type=int, default=1, metavar='S',
                        help='random seed (default: 1)')
    parser.add_argument('--log-interval', type=int, default=10, metavar='N',
                        help='how many batches to wait before logging training status')
    parser.add_argument('--save-model', action='store_true', default=False,
                        help='For Saving the current Model')
    args = parser.parse_args()
    use_cuda = not args.no_cuda and torch.cuda.is_available()

    torch.manual_seed(args.seed)

    device = torch.device("cuda" if use_cuda else "cpu")

    train_kwargs = {'batch_size': args.batch_size}
    test_kwargs = {'batch_size': args.test_batch_size}
    if use_cuda:
        cuda_kwargs = {'num_workers': 1,
                       'pin_memory': True,
                       'shuffle': True}
        train_kwargs.update(cuda_kwargs)
        test_kwargs.update(cuda_kwargs)

    transform=transforms.Compose([
        transforms.ToTensor(),
        transforms.Normalize((0.1307,), (0.3081,))
        ])
    dataset1 = datasets.MNIST('../data', train=True, download=True,
                       transform=transform)
    dataset2 = datasets.MNIST('../data', train=False,
                       transform=transform)
    train_loader = torch.utils.data.DataLoader(dataset1,**train_kwargs)
    test_loader = torch.utils.data.DataLoader(dataset2, **test_kwargs)

    model = Net().to(device)
    optimizer = optim.Adadelta(model.parameters(), lr=args.lr)

    scheduler = StepLR(optimizer, step_size=1, gamma=args.gamma)
    for epoch in range(1, args.epochs + 1):
        train(args, model, device, train_loader, optimizer, epoch)
        test(model, device, test_loader)
        scheduler.step()

    if args.save_model:
        torch.save(model.state_dict(), "mnist_cnn.pt")

5.2 Lightning Version training MNIST

The first part , It's called research code , Mainly the structure of the model 、 Training and so on . Abstracted as LightningModule class .

class LitClassifier(pl.LightningModule):
    def __init__(self, hidden_dim=128, learning_rate=1e-3):
        super().__init__()
        self.save_hyperparameters()

        self.l1 = torch.nn.Linear(28 * 28, self.hparams.hidden_dim)
        self.l2 = torch.nn.Linear(self.hparams.hidden_dim, 10)

    def forward(self, x):
        x = x.view(x.size(0), -1)
        x = torch.relu(self.l1(x))
        x = torch.relu(self.l2(x))
        return x

    def training_step(self, batch, batch_idx):
        x, y = batch
        y_hat = self(x)
        loss = F.cross_entropy(y_hat, y)
        return loss

    def validation_step(self, batch, batch_idx):
        x, y = batch
        y_hat = self(x)
        loss = F.cross_entropy(y_hat, y)
        self.log('valid_loss', loss)

    def test_step(self, batch, batch_idx):
        x, y = batch
        y_hat = self(x)
        loss = F.cross_entropy(y_hat, y)
        self.log('test_loss', loss)

    def configure_optimizers(self):
        return torch.optim.Adam(self.parameters(), lr=self.hparams.learning_rate)

    @staticmethod
    def add_model_specific_args(parent_parser):
        parser = ArgumentParser(parents=[parent_parser], add_help=False)
        parser.add_argument('--hidden_dim', type=int, default=128)
        parser.add_argument('--learning_rate', type=float, default=0.0001)
        return parser

It can be seen that , and PyTorch The biggest difference of the version is that it has several more process processing functions :

  • training_step, It's equivalent to dealing with one during training batch The content of
  • validation_step, It is equivalent to processing a batch The content of
  • test_step, ditto
  • configure_optimizers, This part is used to deal with optimizer and scheduler
  • add_module_specific_args On behalf of this part, the parameters related to the model are controlled

in addition to ,main The function has the following parts :

  • args Processing parameters
  • data part
  • model part
  • Training part
  • Test part
def cli_main():
    pl.seed_everything(1234) #  This is for fixing seed use 

    # args
    parser = ArgumentParser()
    parser = pl.Trainer.add_argparse_args(parser)
    parser = LitClassifier.add_model_specific_args(parser)
    parser = MNISTDataModule.add_argparse_args(parser)
    args = parser.parse_args()

    # data
    dm = MNISTDataModule.from_argparse_args(args)

    # model
    model = LitClassifier(args.hidden_dim, args.learning_rate)

    # training
    trainer = pl.Trainer.from_argparse_args(args)
    trainer.fit(model, datamodule=dm)

    result = trainer.test(model, datamodule=dm)
    pprint(result)

It can be seen that Lightning The code amount of version is slightly less than PyTorch edition , But at the same time, some details are ignored , For example, the specific process of training is directly used fit Get it done , It won't happen that you forget to empty optimizer And so on .

6. evaluation

On the whole ,PyTorch Lightning It's a rapidly developing framework , Like fastai、keras、ignite The framework of secondary encapsulation is the same , Although ease of use has been improved , Allows users to complete tasks with shorter code , But when it comes to mistakes , Often you need to check API Even involving the framework source code can solve . The former lowers the threshold , The latter raises the threshold slightly .

I've been using this framework for about a week , Talk about the advantages and disadvantages from the user's point of view :

6.1 advantage

  • Simplified part of the code , If you want to go to GPU On , Need to use to(device) Methods to judge , And then turn around . With PyTorch lightning With the help of the , It can handle it for you automatically , By setting trainer Medium gpus Parameters can be .
  • Provides some useful tools , For example, mixed precision training 、 Distributed training 、Horovod
  • Code migration is easier
  • API Relatively perfect , Most of them have examples , A few of them are not detailed enough .
  • The community is still active , If there are questions , Can be in issue Asking questions .
  • The experimental results are well organized , Divide each experiment into version 0-n, It can be used at the same time tensorboard Compare multiple experiments , Very friendly .

6.2 shortcoming

  • Some new concepts have been introduced , It further increases the learning cost of users , such as pl_bolts
  • A lot of people used to be in Pytorch The function used in , stay PyTorch Lightning You have to check API Can be used , For example, I want to use scheduler, You need to check API, And then found out in configure_optimizers Function , Then imitate demo Realization , So it also brings a certain threshold .
  • Some mistakes are more confusing , The author has encountered the problem of multithreading when executing , It's hard to find out , Finally, by changing distributed_backend It's solved . Meet a new pit to go to API Find out the answer , If it's not solved, go on Issue Find out the answer .

7. Reference resources

版权声明
本文为[pprp]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/202012081054448893.html