2022-05-31 04:00:12 +00:00
|
|
|
import torch
|
2022-06-02 04:13:15 +00:00
|
|
|
from colossalai.tensor.param_op_hook import ParamOpHook
|
|
|
|
from colossalai.tensor.chunk import ChunkManager, TensorState
|
2022-05-31 04:00:12 +00:00
|
|
|
from enum import Enum
|
|
|
|
from typing import List
|
|
|
|
from contextlib import contextmanager
|
|
|
|
from functools import partial
|
2022-06-10 06:48:28 +00:00
|
|
|
from colossalai.gemini.gemini_mgr import GeminiManager
|
2022-05-31 04:00:12 +00:00
|
|
|
|
|
|
|
|
|
|
|
class TrainingPhase(Enum):
|
|
|
|
FORWARD = 0
|
|
|
|
BACKWARD = 1
|
|
|
|
|
|
|
|
|
|
|
|
class ZeROHookV2(ParamOpHook):
|
|
|
|
|
2022-06-10 06:48:28 +00:00
|
|
|
def __init__(self, gemini_manager: GeminiManager) -> None:
|
2022-05-31 04:00:12 +00:00
|
|
|
super().__init__()
|
2022-06-10 06:48:28 +00:00
|
|
|
self._gemini_manager = gemini_manager
|
|
|
|
self._chunk_manager = gemini_manager.chunk_manager
|
2022-05-31 04:00:12 +00:00
|
|
|
self._training_phase = TrainingPhase.FORWARD
|
|
|
|
|
|
|
|
def pre_op(self, params):
|
2022-06-09 12:56:34 +00:00
|
|
|
chunks = self._chunk_manager.get_chunks(params)
|
2022-05-31 04:00:12 +00:00
|
|
|
for p in params:
|
|
|
|
self._chunk_manager.trans_tensor_state(p, TensorState.COMPUTE)
|
|
|
|
self._chunk_manager.exec_lazy_release()
|
2022-06-10 06:48:28 +00:00
|
|
|
self._gemini_manager.sample_overall_data()
|
|
|
|
self._gemini_manager.adjust_layout(chunks, 'fp16_param')
|
2022-06-09 12:56:34 +00:00
|
|
|
for chunk in chunks:
|
|
|
|
self._chunk_manager.access_chunk(chunk)
|
2022-06-10 06:48:28 +00:00
|
|
|
self._gemini_manager.sample_model_data()
|
2022-05-31 04:00:12 +00:00
|
|
|
|
|
|
|
def post_op(self, params):
|
|
|
|
for p in params:
|
|
|
|
tensor_state = TensorState.HOLD if self._training_phase == TrainingPhase.FORWARD or not p.requires_grad else TensorState.HOLD_AFTER_BWD
|
|
|
|
self._chunk_manager.trans_tensor_state(p, tensor_state)
|
|
|
|
self._chunk_manager.add_lazy_release_tensors(params)
|
|
|
|
|
|
|
|
def pre_forward(self, params: List[torch.Tensor]) -> None:
|
|
|
|
self.pre_op(params)
|
|
|
|
|
|
|
|
def post_forward(self, params: List[torch.Tensor]) -> None:
|
|
|
|
self.post_op(params)
|
|
|
|
|
|
|
|
def pre_backward(self, params: List[torch.Tensor]) -> None:
|
|
|
|
self.pre_op(params)
|
|
|
|
|
|
|
|
def post_backward(self, params: List[torch.Tensor]) -> None:
|
|
|
|
self.post_op(params)
|
|
|
|
|
|
|
|
@contextmanager
|
|
|
|
def switch_training_phase(self, training_phase: TrainingPhase = TrainingPhase.BACKWARD):
|
|
|
|
try:
|
|
|
|
old_training_phase = self._training_phase
|
|
|
|
self._training_phase = training_phase
|
|
|
|
yield
|
|
|
|
finally:
|
|
|
|
self._training_phase = old_training_phase
|
|
|
|
|
|
|
|
switch_to_backward = switch_training_phase
|
|
|
|
switch_to_forward = partial(switch_to_backward, training_phase=TrainingPhase.FORWARD)
|