Compare commits

..
41 Commits
Author SHA1 Message Date
William Falcon 15ca7a40a6 release v 2019-05-24 15:30:55 -04:00
William Falcon 96903c7910 added amp level option 2019-05-16 16:01:15 -04:00
William Falcon eb13bb8313 added amp level option 2019-05-16 15:58:58 -04:00
William Falcon d560fac104 added amp level option 2019-05-16 15:58:14 -04:00
William Falcon 2d3977046e added amp level option 2019-05-16 15:58:06 -04:00
William Falcon fa0a223ccb added amp level option 2019-05-16 15:55:29 -04:00
William Falcon 60d4b80322 added amp level option 2019-05-16 15:55:21 -04:00
William Falcon e052a3bc92 added amp level option 2019-05-16 15:52:00 -04:00
William Falcon 35ca80683e added amp level option 2019-05-16 15:47:21 -04:00
William Falcon b2ef6a6366 added amp level option 2019-05-16 15:46:17 -04:00
William Falcon 9d19ab5850 added amp level option 2019-05-16 15:45:56 -04:00
William Falcon 92f9b3e062 fixed alternating loss 2019-05-14 06:40:11 -04:00
William Falcon 5fa2a6a723 tng and val steps now have batch nbs 2019-05-14 06:37:56 -04:00
William Falcon 8531f33549 tng and val steps now have batch nbs 2019-05-14 06:36:26 -04:00
William Falcon 98b26c5c7e fixed error with shorter batch cycles 2019-05-14 06:11:52 -04:00
William Falcon c973245ba1 fixed error with shorter batch cycles 2019-05-14 06:11:16 -04:00
William Falcon ed787fb061 release v0.1.dev182 2019-05-14 05:53:58 -04:00
William Falcon 04681eeda9 release v0.1.dev18 2019-05-14 05:46:55 -04:00
William Falcon 6519c29119 added 16 bit training support with --use_amp flag 2019-05-14 05:44:33 -04:00
William Falcon 3b0fd7a6cb added option to change default tensor 2019-05-13 22:03:56 -04:00
William Falcon a8e57602d3 added option to change default tensor 2019-05-13 22:03:47 -04:00
William Falcon 8836f4f7a5 added option to change default tensor 2019-05-13 22:02:53 -04:00
William Falcon f246ae7fab added option to change default tensor 2019-05-13 21:55:57 -04:00
William Falcon 1c7d477d03 added option to change default tensor 2019-05-13 21:52:02 -04:00
William Falcon 90a460ec62 added option to change default tensor 2019-05-13 21:47:07 -04:00
William Falcon edd406f419 added option to change default tensor 2019-05-13 21:28:28 -04:00
William Falcon 8a68466710 added option to change default tensor 2019-05-13 21:27:01 -04:00
William Falcon 4dbf38093a added option to change default tensor 2019-05-13 21:22:50 -04:00
William Falcon 38717abcd4 added option to change default tensor 2019-05-13 21:19:37 -04:00
William Falcon 8e49fc6cf7 added option to change default tensor 2019-05-13 21:19:07 -04:00
William Falcon 5f0a71c414 added option to change default tensor 2019-05-13 21:18:17 -04:00
William Falcon 88fbf6cc4b added option to change default tensor 2019-05-13 20:44:25 -04:00
William Falcon 7002de1d4e added option to change default tensor 2019-05-13 20:43:26 -04:00
William Falcon fecd6a00cb added option to change default tensor 2019-05-13 20:41:23 -04:00
William Falcon 4693276494 added option to change default tensor 2019-05-13 20:40:07 -04:00
William Falcon f228e5ae66 added option to change default tensor 2019-05-13 19:39:56 -04:00
William Falcon e3425ec6a0 added option to change default tensor 2019-05-13 19:30:06 -04:00
William Falcon 5a7ad19403 fixed gpu map location 2019-05-13 05:32:18 -04:00
William Falcon d6bc203f05 release v0.1.dev16 2019-05-05 12:16:52 -04:00
William Falcon 12352f1949 fixed epoch continuation from checkpoint 2019-05-05 12:15:04 -04:00
William Falcon f881bf6750 added log saving when early epoch stop 2019-04-23 11:12:01 -04:00
5 changed files with 69 additions and 25 deletions
+52 -18
View File
@@ -5,7 +5,13 @@ from pytorch_lightning.root_module.memory import get_gpu_memory_map
import traceback
from pytorch_lightning.root_module.model_saving import TrainerIO
from torch.optim.lr_scheduler import MultiStepLR
import pdb
try:
from apex import amp
APEX_AVAILABLE = True
except ModuleNotFoundError:
APEX_AVAILABLE = False
class Trainer(TrainerIO):
@@ -26,6 +32,9 @@ class Trainer(TrainerIO):
train_percent_check=1.0, val_percent_check=1.0, test_percent_check=1.0, val_check_interval=0.95,
log_save_interval=1, add_log_row_interval=1,
lr_scheduler_milestones=None,
use_amp=False,
check_grad_nans=False,
amp_level='O2',
nb_sanity_val_steps=5):
# Transfer params
@@ -51,6 +60,8 @@ class Trainer(TrainerIO):
self.nb_sanity_val_steps = nb_sanity_val_steps
self.lr_scheduler_milestones = [] if lr_scheduler_milestones is None else [int(x.strip()) for x in lr_scheduler_milestones.split(',')]
self.lr_schedulers = []
self.amp_level = amp_level
self.check_grad_nans = check_grad_nans
# training state
self.optimizers = None
@@ -73,6 +84,11 @@ class Trainer(TrainerIO):
self.__determine_data_use_amount(train_percent_check, val_percent_check, test_percent_check, overfit_pct)
print('gpu available: {}, used: {}'.format(torch.cuda.is_available(), self.on_gpu))
# apex test
self.use_amp = use_amp and APEX_AVAILABLE
if self.use_amp:
print('using 16bit precision')
def __determine_data_use_amount(self, train_percent_check, val_percent_check, test_percent_check, overfit_pct):
"""
Use less data for debugging purposes
@@ -110,21 +126,21 @@ class Trainer(TrainerIO):
self.tqdm_metrics = {}
# determine number of training batches
nb_tng_batches = self.model.nb_batches(self.tng_dataloader)
self.nb_tng_batches = int(nb_tng_batches * self.train_percent_check)
self.nb_tng_batches = self.model.nb_batches(self.tng_dataloader)
self.nb_tng_batches = int(self.nb_tng_batches * self.train_percent_check)
# determine number of validation batches
nb_val_batches = self.model.nb_batches(self.val_dataloader)
nb_val_batches = int(nb_val_batches * self.val_percent_check)
nb_val_batches = max(1, nb_val_batches)
self.nb_val_batches = nb_val_batches
self.nb_val_batches = self.model.nb_batches(self.val_dataloader)
self.nb_val_batches = int(self.nb_val_batches * self.val_percent_check)
self.nb_val_batches = max(1, self.nb_val_batches)
self.nb_val_batches = self.nb_val_batches
# determine number of test batches
nb_test_batches = self.model.nb_batches(self.test_dataloader)
self.nb_test_batches = int(nb_test_batches * self.test_percent_check)
self.nb_test_batches = self.model.nb_batches(self.test_dataloader)
self.nb_test_batches = int(self.nb_test_batches * self.test_percent_check)
# determine when to check validation
self.val_check_batch = int(nb_tng_batches * self.val_check_interval)
self.val_check_batch = int(self.nb_tng_batches * self.val_check_interval)
def __add_tqdm_metrics(self, metrics):
for k, v in metrics.items():
@@ -151,19 +167,19 @@ class Trainer(TrainerIO):
outputs = []
# run training
for i, data_batch in enumerate(dataloader):
for batch_i, data_batch in enumerate(dataloader):
if data_batch is None:
continue
# stop short when on fast dev run
if max_batches is not None and i >= max_batches:
if max_batches is not None and batch_i >= max_batches:
break
# -----------------
# RUN VALIDATION STEP
# -----------------
output = model.validation_step(data_batch)
output = model.validation_step(data_batch, batch_i)
outputs.append(output)
# batch done
@@ -207,6 +223,14 @@ class Trainer(TrainerIO):
# filter out the weights that were done on gpu so we can load on good old cpus
self.optimizers = model.configure_optimizers()
if self.use_amp:
# An example
self.model, optimizer = amp.initialize(
self.model, self.optimizers[0], opt_level=self.amp_level,
)
self.optimizers[0] = optimizer
model.trainer = self
# add lr schedulers
if self.lr_scheduler_milestones is not None:
for optimizer in self.optimizers:
@@ -270,7 +294,7 @@ class Trainer(TrainerIO):
# ---------------
# RUN TRAIN STEP
# ---------------
batch_result = self.__run_tng_batch(data_batch)
batch_result = self.__run_tng_batch(data_batch, batch_nb)
early_stop_epoch = batch_result == -1
# ---------------
@@ -281,11 +305,11 @@ class Trainer(TrainerIO):
self.__run_validation()
# when batch should be saved
if (batch_nb + 1) % self.log_save_interval == 0:
if (batch_nb + 1) % self.log_save_interval == 0 or early_stop_epoch:
self.experiment.save()
# when metrics should be logged
if batch_nb % self.add_log_row_interval == 0:
if batch_nb % self.add_log_row_interval == 0 or early_stop_epoch:
# count items in memory
# nb_params, nb_tensors = count_mem_items()
@@ -328,7 +352,7 @@ class Trainer(TrainerIO):
return
def __run_tng_batch(self, data_batch):
def __run_tng_batch(self, data_batch, batch_nb):
if data_batch is None:
return 0
@@ -343,11 +367,21 @@ class Trainer(TrainerIO):
# forward pass
# return a scalar value and a dic with tqdm metrics
loss, model_specific_tqdm_metrics_dic = self.model.training_step(data_batch)
loss, model_specific_tqdm_metrics_dic = self.model.training_step(data_batch, batch_nb)
self.__add_tqdm_metrics(model_specific_tqdm_metrics_dic)
# backward pass
loss.backward()
if self.use_amp:
for optimizer in self.optimizers:
with amp.scale_loss(loss, optimizer) as scaled_loss:
scaled_loss.backward()
else:
loss.backward()
if self.check_grad_nans:
for param in self.model.parameters():
print(param.grad.float().sum())
self.batch_loss_value += loss.item()
# gradient update with accumulated gradients
@@ -88,6 +88,7 @@ class TrainerIO(object):
self.early_stop_callback.wait = checkpoint['early_stop_callback_wait']
self.early_stop_callback.patience = checkpoint['early_stop_callback_patience']
self.global_step = checkpoint['global_step']
self.current_epoch = checkpoint['epoch']
# restore the optimizers
optimizer_states = checkpoint['optimizer_states']
+9 -6
View File
@@ -40,8 +40,7 @@ class RootModule(GradInformation, ModelIO, OptimizerConfig, ModelHooks):
if self.on_gpu:
print('running on gpu...')
self.dtype = torch.cuda.FloatTensor
torch.set_default_tensor_type('torch.cuda.FloatTensor')
torch.set_default_tensor_type(hparams.default_tensor_type)
def forward(self, *args, **kwargs):
"""
@@ -52,7 +51,7 @@ class RootModule(GradInformation, ModelIO, OptimizerConfig, ModelHooks):
"""
raise NotImplementedError
def validation_step(self, data_batch):
def validation_step(self, data_batch, batch_nb):
"""
return whatever outputs will need to be aggregated in validation_end
:param data_batch:
@@ -68,7 +67,7 @@ class RootModule(GradInformation, ModelIO, OptimizerConfig, ModelHooks):
"""
raise NotImplementedError
def training_step(self, data_batch):
def training_step(self, data_batch, batch_nb):
"""
return loss, dict with metrics for tqdm
:param data_batch:
@@ -151,19 +150,23 @@ class RootModule(GradInformation, ModelIO, OptimizerConfig, ModelHooks):
return 0, 0
@classmethod
def load_from_metrics(cls, weights_path, tags_csv, on_gpu):
def load_from_metrics(cls, weights_path, tags_csv, on_gpu, map_location=None):
"""
Primary way of loading model from csv weights path
:param weights_path:
:param tags_csv:
:param on_gpu:
:param map_location: dic for mapping storage {'cuda:1':'cuda:0'}
:return:
"""
hparams = load_hparams_from_tags_csv(tags_csv)
hparams.__setattr__('on_gpu', on_gpu)
if on_gpu:
checkpoint = torch.load(weights_path)
if map_location is not None:
checkpoint = torch.load(weights_path, map_location=map_location)
else:
checkpoint = torch.load(weights_path)
else:
checkpoint = torch.load(weights_path, map_location=lambda storage, loc: storage)
+5
View File
@@ -49,6 +49,11 @@ def add_default_args(parser, root_dir, rand_seed=None, possible_model_names=None
parser.add_argument('--gpus', default='0', type=str)
parser.add_argument('--single_run_gpu', dest='single_run_gpu', action='store_true')
parser.add_argument('--disable_cuda', dest='disable_cuda', action='store_true')
parser.add_argument('--default_tensor_type', default='torch.cuda.FloatTensor', type=str)
parser.add_argument('--use_amp', dest='use_amp', action='store_true')
parser.add_argument('--check_grad_nans', dest='check_grad_nans', action='store_true')
parser.add_argument('--amp_level', default='O2',type=str)
# run on hpc
parser.add_argument('--on_cluster', dest='on_cluster', action='store_true')
+2 -1
View File
@@ -7,7 +7,7 @@ from setuptools import setup, find_packages
# http://blog.ionelmc.ro/2014/05/25/python-packaging/
setup(
name="pytorch-lightning",
version='0.1.dev15',
version='0.1.dev1832',
description="The Keras for ML researchers using PyTorch",
author="William Falcon",
author_email="waf2107@columbia.edu",
@@ -23,6 +23,7 @@ setup(
],
packages=find_packages(),
long_description=open("README.md", encoding="utf-8").read(),
long_description_content_type='text/markdown',
include_package_data=True,
zip_safe=False,
)