pretrain_vit.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. # coding=utf-8
  2. # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Pretrain VIT"""
  16. import torch
  17. import torch.nn.functional as F
  18. from functools import partial
  19. from megatron import get_args, get_timers, mpu, print_rank_0
  20. from megatron.data.vit_dataset import build_train_valid_datasets
  21. from megatron.model.vit_model import VitModel
  22. from megatron.training import pretrain
  23. from megatron.utils import average_losses_across_data_parallel_group
  24. def model_provider(pre_process=True, post_process=True):
  25. """Build the model."""
  26. print_rank_0("building VIT model ...")
  27. args = get_args()
  28. model = VitModel(num_classes=args.num_classes,
  29. pre_process=pre_process,
  30. post_process=post_process)
  31. return model
  32. def get_batch(data_iterator):
  33. """Build the batch."""
  34. data = next(data_iterator)
  35. # only data parallelism; no need for broadcast
  36. images = data[0].cuda()
  37. labels = data[1].cuda()
  38. return images, labels
  39. def loss_func(labels, output_tensor):
  40. logits = output_tensor.contiguous().float()
  41. loss = F.cross_entropy(logits, labels)
  42. outputs = torch.argmax(logits, -1)
  43. correct = (outputs == labels).float()
  44. accuracy = torch.mean(correct)
  45. averaged_loss = average_losses_across_data_parallel_group([loss, accuracy])
  46. return loss, {"loss": averaged_loss[0], "accuracy": averaged_loss[1]}
  47. def forward_step(data_iterator, model):
  48. """Forward step."""
  49. timers = get_timers()
  50. # Get the batch.
  51. timers("batch-generator").start()
  52. (
  53. images,
  54. labels,
  55. ) = get_batch(data_iterator)
  56. timers("batch-generator").stop()
  57. # Forward model. lm_labels
  58. output_tensor = model(images)
  59. return output_tensor, partial(loss_func, labels)
  60. def train_valid_test_datasets_provider(train_val_test_num_samples):
  61. """Build train, valid, and test datasets."""
  62. args = get_args()
  63. print_rank_0(
  64. "> building train, validation, and test datasets " "for VIT ..."
  65. )
  66. train_ds, valid_ds = build_train_valid_datasets(data_path=args.data_path)
  67. print_rank_0("> finished creating VIT datasets ...")
  68. return train_ds, valid_ds, None
  69. if __name__ == "__main__":
  70. pretrain(
  71. train_valid_test_datasets_provider,
  72. model_provider,
  73. forward_step,
  74. args_defaults={'dataloader_type': 'cyclic'}
  75. )