|
| 1 | +from torch_xla import runtime as xr |
| 2 | +import torch_xla.utils.utils as xu |
| 3 | +import torch_xla.core.xla_model as xm |
| 4 | +import torch_xla.distributed.parallel_loader as pl |
| 5 | + |
| 6 | +import time |
| 7 | +import itertools |
| 8 | + |
| 9 | +import torch |
| 10 | +import torch_xla |
| 11 | +import torchvision |
| 12 | +import torch.optim as optim |
| 13 | +import torch.nn as nn |
| 14 | + |
| 15 | + |
| 16 | +def _train_update(step, loss, tracker, epoch): |
| 17 | + print(f'epoch: {epoch}, step: {step}, loss: {loss}, rate: {tracker.rate()}') |
| 18 | + |
| 19 | + |
| 20 | +class TrainResNetBase(): |
| 21 | + |
| 22 | + def __init__(self): |
| 23 | + img_dim = 224 |
| 24 | + self.batch_size = 128 |
| 25 | + self.num_steps = 300 |
| 26 | + self.num_epochs = 1 |
| 27 | + train_dataset_len = 1200000 # Roughly the size of Imagenet dataset. |
| 28 | + # For the purpose of this example, we are going to use fake data. |
| 29 | + train_loader = xu.SampleGenerator( |
| 30 | + data=(torch.zeros(self.batch_size, 3, img_dim, img_dim), |
| 31 | + torch.zeros(self.batch_size, dtype=torch.int64)), |
| 32 | + sample_count=train_dataset_len // self.batch_size // xr.world_size()) |
| 33 | + |
| 34 | + self.device = torch_xla.device() |
| 35 | + self.train_device_loader = pl.MpDeviceLoader(train_loader, self.device) |
| 36 | + self.model = torchvision.models.resnet50().to(self.device) |
| 37 | + self.optimizer = optim.SGD(self.model.parameters(), weight_decay=1e-4) |
| 38 | + self.loss_fn = nn.CrossEntropyLoss() |
| 39 | + |
| 40 | + def run_optimizer(self): |
| 41 | + self.optimizer.step() |
| 42 | + |
| 43 | + def start_training(self): |
| 44 | + |
| 45 | + def train_loop_fn(loader, epoch): |
| 46 | + tracker = xm.RateTracker() |
| 47 | + self.model.train() |
| 48 | + loader = itertools.islice(loader, self.num_steps) |
| 49 | + for step, (data, target) in enumerate(loader): |
| 50 | + self.optimizer.zero_grad() |
| 51 | + output = self.model(data) |
| 52 | + loss = self.loss_fn(output, target) |
| 53 | + loss.backward() |
| 54 | + self.run_optimizer() |
| 55 | + tracker.add(self.batch_size) |
| 56 | + if step % 10 == 0: |
| 57 | + xm.add_step_closure(_train_update, args=(step, loss, tracker, epoch)) |
| 58 | + |
| 59 | + for epoch in range(1, self.num_epochs + 1): |
| 60 | + xm.master_print('Epoch {} train begin {}'.format( |
| 61 | + epoch, time.strftime('%l:%M%p %Z on %b %d, %Y'))) |
| 62 | + train_loop_fn(self.train_device_loader, epoch) |
| 63 | + xm.master_print('Epoch {} train end {}'.format( |
| 64 | + epoch, time.strftime('%l:%M%p %Z on %b %d, %Y'))) |
| 65 | + xm.wait_device_ops() |
| 66 | + |
| 67 | + |
| 68 | +if __name__ == '__main__': |
| 69 | + base = TrainResNetBase() |
| 70 | + base.start_training() |
0 commit comments