2019-12-04 15:57:32 +00:00
|
|
|
from abc import ABC
|
2020-04-23 18:47:08 +00:00
|
|
|
import torch
|
2019-12-04 15:57:32 +00:00
|
|
|
|
2020-03-17 22:44:00 +00:00
|
|
|
from pytorch_lightning import _logger as log
|
2020-04-23 18:47:08 +00:00
|
|
|
from pytorch_lightning.utilities import rank_zero_warn
|
2020-03-17 22:44:00 +00:00
|
|
|
|
2019-10-22 01:16:51 +00:00
|
|
|
try:
|
|
|
|
from apex import amp
|
|
|
|
except ImportError:
|
|
|
|
APEX_AVAILABLE = False
|
2020-03-17 00:50:36 +00:00
|
|
|
else:
|
|
|
|
APEX_AVAILABLE = True
|
2019-10-22 01:16:51 +00:00
|
|
|
|
|
|
|
|
2019-12-04 15:57:32 +00:00
|
|
|
class TrainerAMPMixin(ABC):
|
2019-10-22 01:16:51 +00:00
|
|
|
|
2020-02-27 21:21:14 +00:00
|
|
|
# this is just a summary on variables used in this abstract class,
|
|
|
|
# the proper values/initialisation should be done in child class
|
2020-04-06 12:13:24 +00:00
|
|
|
precision: int
|
2020-04-23 18:47:08 +00:00
|
|
|
use_native_amp: bool
|
2020-02-17 21:01:20 +00:00
|
|
|
|
2019-10-22 01:16:51 +00:00
|
|
|
def init_amp(self, use_amp):
|
2020-04-23 18:47:08 +00:00
|
|
|
if self.use_native_amp:
|
2020-06-12 18:37:52 +00:00
|
|
|
rank_zero_warn("`amp_level` has been deprecated since v0.7.4 (native amp does not require it)"
|
|
|
|
" and this argument will be removed in v0.9.0", DeprecationWarning)
|
2020-04-23 18:47:08 +00:00
|
|
|
|
|
|
|
# Backward compatibility, TODO: remove in v0.9.0
|
|
|
|
if use_amp is not None:
|
|
|
|
rank_zero_warn("`use_amp` has been replaced by `precision` since v0.7.0"
|
|
|
|
" and this argument will be removed in v0.9.0", DeprecationWarning)
|
|
|
|
self.precision = 16 if use_amp else 32
|
|
|
|
|
|
|
|
assert self.precision in (16, 32), 'only 32 or 16 bit precision supported'
|
|
|
|
|
|
|
|
if use_amp and self.use_native_amp:
|
|
|
|
log.info('Using 16bit precision.')
|
|
|
|
return
|
|
|
|
|
2020-06-12 18:37:52 +00:00
|
|
|
# TODO: remove all below for v0.9.0
|
2020-03-19 13:14:29 +00:00
|
|
|
if use_amp and not APEX_AVAILABLE: # pragma: no-cover
|
2020-04-06 12:13:24 +00:00
|
|
|
raise ModuleNotFoundError("""
|
2019-12-04 16:39:14 +00:00
|
|
|
You set `use_amp=True` but do not have apex installed.
|
2019-10-22 01:16:51 +00:00
|
|
|
Install apex first using this guide and rerun with use_amp=True:
|
|
|
|
https://github.com/NVIDIA/apex#linux
|
|
|
|
this run will NOT use 16 bit precision
|
2020-04-06 12:13:24 +00:00
|
|
|
""")
|
|
|
|
|
|
|
|
if self.use_amp:
|
|
|
|
log.info('Using 16bit precision.')
|
|
|
|
|
|
|
|
@property
|
|
|
|
def use_amp(self) -> bool:
|
2020-04-23 18:47:08 +00:00
|
|
|
return self.precision == 16
|