learning
Module diagram
classDiagram
class learning {
}
class device {
}
class meter {
}
class optimizer {
}
class scheduler {
}
class trainer {
}
scheduler --> optimizer
learning
Device manager 및 기본적인 metric 관리 클래스와 기본 Trainer 클래스를 제공합니다.
BaseTrainer 클래스는 Saige Vision2 Engine 학습 API의 베이스 인터페이스를 제공하며, 이를 상속받아 사용자 정의 Trainer를 구현할 수 있습니다. 구현 메서드들은 error_handler를 씌워 노출되어야 합니다.
device
"Device Manager, converting modules and data tensors to device
AttributeDataParallel
Bases: DataParallel
DataParallel class with attribute get method.
You can now use expressions like:
Possible with origial DataParallel class.
... self.network(x) ... # Not possible with origial DataParallel class. ... self.network.feature_extractor(x)
...where self.network is a AttributeDataParallel class instance.
DeviceManager
DeviceManager(device: DeviceType = 'cpu', multi_gpu: bool = False)
converting torch.nn.modules and torch.tensors to selected device.
Attributes:
-
device(device) –name of target device for learning.
-
multi_gpu(bool) –whether use multi-gpu learning.
initializing DeviceManager
Parameters:
-
device(Optional[Union[device, str, int]], default:'cpu') –user defined device. Defaults to None.
-
multi_gpu(bool, default:False) –set to class attribute. Defaults to False.
Source code in SaigeToolkit/learning/device.py
set_gpu
set_gpu(device: DeviceType = 'cpu') -> None
If user gives device string, use the defined device.
Parameters:
-
device(Optional[Union[device, str, int]], default:'cpu') –user defined device. Defaults to None.
Source code in SaigeToolkit/learning/device.py
module_to_device
converting torch modules to device
Parameters:
-
module(object) –task specific modules # XXX: isinstance of BaseModule?
Returns:
-
List[Optional[Module]]–List[torch.nn.Module]: network module list which needs to be reset after iteration step.
Source code in SaigeToolkit/learning/device.py
data_to_device
convetring tensor-type data to device
Parameters:
-
data(dict, default:{}) –data with tensors and also non-tensors.
Raises:
-
AssertionError–input data should be dict type.
Returns:
-
dict(dict) –data dict with tensors converted to device
Source code in SaigeToolkit/learning/device.py
cuda_empty_cache
cuda_empty_cache(device: DeviceType) -> None
CUDA device의 torch cache를 비웁니다 Multi-GPU 환경에서 0번이 아닌 device에 대해 empty_cache 호출 시 0번 device에 메모리 올리는 이슈를 해결
Source code in SaigeToolkit/learning/device.py
self_device_context
method에 self.device context 적용
Source code in SaigeToolkit/learning/device.py
apply_self_device_context
class의 모든 method에 self.device context 적용 (staticmethod, classmethod 및 기본으로 정의된 method 제외)
Note: 모든 메소드에 적용하기 때문에 퍼포먼스 이슈가 발생할 수 있습니다
Source code in SaigeToolkit/learning/device.py
meter
Meter, updates and stores loss values and report average value.
Meter
Computes and stores the average and current losses by keys
Attributes:
-
meters(dict) –stored loss information by keys
Source code in SaigeToolkit/learning/meter.py
update
update result loss from network
Parameters:
-
loss(Union[Dict[str, float], List[float], float]) –loss to be stored. can be three types of data.
Source code in SaigeToolkit/learning/meter.py
AverageMeter
Computes and stores the average and current value Attributes: val (float): last input loss value avg (float): average loss value sum (float): summed loss value min (float): min loss value max (float): max loss value count (int): total number of loss inputs
update
update single loss value
Parameters:
-
val(float) –current loss value
-
n(int, default:1) –current number of loss inputs. Defaults to 1.
Source code in SaigeToolkit/learning/meter.py
get_meter
get loss/score average meter for training and validation
Returns:
Source code in SaigeToolkit/learning/meter.py
optimizer
building torch optimizers with simple configs
build_optimizer
build optimizer object
Parameters:
-
model_params(Iterator[Parameter]) –parameters of model to be trained
-
_target_(str, default:'SGD') –optimizer name. Defaults to "SGD".
Raises:
-
NotImplementedError–description
Returns:
-
Optimizer(Optimizer) –optimizer object
Source code in SaigeToolkit/learning/optimizer.py
scheduler
torch learning rate schdulers and Few custom schedulers
FixedLR
Bases: _LRScheduler
constant learning rate
initializing FixedLR
Parameters:
-
optimizer(Optimizer) –optimizer
-
last_epoch(int, default:-1) –index of last epoch. Defaults to -1.
Source code in SaigeToolkit/learning/scheduler.py
PolynomialLR
PolynomialLR(optimizer: Optimizer, max_iter: int, decay_iter: int = 1, gamma: float = 0.9, last_epoch: int = -1)
Bases: _LRScheduler
polynomial learning rate scheduler
Attributes:
-
decay_iter(int) –decaying iteration number
-
max_iter(int) –max iteration number for decaying
-
gamma(float) –learning rate decay rate (exponents)
initializing PolynomialLR
Parameters:
-
optimizer(Optimizer) –optimizer
-
max_iter(int) –max iteration number for decaying
-
decay_iter(int, default:1) –decaying iteration number. Defaults to 1.
-
gamma(float, default:0.9) –learning rate decay rate (exponents). Defaults to 0.9.
-
last_epoch(int, default:-1) –index of last epoch. Defaults to -1.
Source code in SaigeToolkit/learning/scheduler.py
WarmUpLR
WarmUpLR(optimizer: Optimizer, scheduler: dict, mode: str = 'linear', warmup_iters: int = 100, gamma: float = 0.2)
Bases: _LRScheduler
Wrapper for learning rate scheduler with warm-up stage
Attributes:
-
mode(str) –base schduler mode after warm-up stage
-
scheduler(_LRScheduler) –schduler for cold_lrs (warm-up stage)
-
warmup_iters(int) –number of iterations for warm-up stage
-
gamma(float) –learning rate decay rate
Parameters:
-
scheduler(dict) –schduler dict for cold_lrs (warm-up stage)
-
mode(str, default:'linear') –base schduler mode after warm-up stage. Defaults to "linear".
-
warmup_iters(int, default:100) –number of iterations for warm-up stage. Defaults to 100.
-
gamma(float, default:0.2) –learning rate decay ratev. Defaults to 0.2.
Source code in SaigeToolkit/learning/scheduler.py
state_dict
Returns the state of the scheduler as a :class:dict.
It contains an entry for every variable in self.dict which
is not the optimizer.
Source code in SaigeToolkit/learning/scheduler.py
load_state_dict
Loads the schedulers state.
Parameters:
-
state_dict(dict) –scheduler state. Should be an object returned from a call to :meth:
state_dict.
Source code in SaigeToolkit/learning/scheduler.py
CosineAnnealingWarmUpRestarts
CosineAnnealingWarmUpRestarts(optimizer: Optimizer, T_0: int, T_mult: int = 1, eta_max: float = 0.1, T_up: int = 0, gamma: float = 1.0, last_epoch: int = -1)
Bases: _LRScheduler
Cosine Anneeling scheduler with Warmup restarts (SGDR).
Modified from https://github.com/pytorch/pytorch/blob/v1.1.0/torch/optim/lr_scheduler.py#L655, implementing initial warmup stage.
Usage:
optimizer: ... target: sgd ... lr: 0.0 # optimizer lr should be zero or very small value!!! ... momentum: 0.9 ... weight_decay: 0.0001 ... scheduler: ... target: CosineAnnealingWarmUpRestarts ... T_0: 50000 ... T_mult: 1 ... eta_max: 0.005 ... T_up: 500 ... gamma: 0.5
Parameters:
-
optimizer(Optimizer) –Pytorch optimizer instance.
-
T_0(int) –Initial annealing cycle length.
-
T_mult(int, default:1) –Cycle multiplication scale after the first cycle. Defaults to 1.
-
eta_max(float, default:0.1) –Max learning rate. Defaults to 0.1.
-
T_up(int, default:0) –Warmup step size. Defaults to 0.
-
gamma(float, default:1.0) –eta_max multiplication scale after the first cycle. Defaults to 1..
-
last_epoch(int, default:-1) –Last epoch of the scheduler. Defaults to -1.
Raises:
-
ValueError–Expected positive integer T_0
-
ValueError–Expected integer T_mult >= 1
-
ValueError–Expected positive integer T_up
Source code in SaigeToolkit/learning/scheduler.py
ProportionalMultiStepLR
Bases: MultiStepLR
전체 iteration에 대한 비율로 milestone을 설정하는 MultiStepLR 스케줄러
Source code in SaigeToolkit/learning/scheduler.py
SaigeVision1_5080_LR
Bases: ProportionalMultiStepLR
SaigeVision1 제품에 적용된 스케줄러. 전체 iteration의 50%, 80% 지점에서 learning rate을 0.5배씩 줄입니다.
Source code in SaigeToolkit/learning/scheduler.py
build_scheduler
builds leraning rate scheduler
Parameters:
-
optimizer(Optimizer) –optimizer object
-
_target_(str, default:'FixedLR') –learning rate scheduler configuration dict. Defaults to "FixedLR".
Raises:
-
NotImplementedError–description
Returns:
-
_LRScheduler(_LRScheduler) –learning rate scheduler object
Source code in SaigeToolkit/learning/scheduler.py
trainer
BaseTrainer
Bases: ABC
Saige Vision2 Engine 학습 API의 베이스 인터페이스 입니다. 기본적인 규약만 정해져있으며 각 태스크에 맞게 abstractmethod들을 구현하고, error_handler를 씌워서 노출시키면 됩니다.
About Init
init 메소드 작성 시 util.reproducibility.store_config 데코레이터를 활용하면 _config를 쉽게 저장할 수 있습니다.
Example: class Trainer(BaseTrainer): @store_config(attr="_config") # 인스턴스 생성 시 self._config 변수에 생성 파라미터들 저장됨 def init(self, param1, param2): ...
About Checkpoint
체크포인트를 저장/로드 하는 인터페이스는 save_checkpoint, load_checkpoint로 이미 구현되어 있으며, 태스크에 맞게 state_dict, load_state_dict를 구현하면 해당 함수를 이용해 상태를 저장/로드 하는 방식입니다.