From 6e38eafebec514cd670758a0fb06b37bd01d224e Mon Sep 17 00:00:00 2001 From: hxwang Date: Wed, 15 May 2024 16:51:44 +0800 Subject: [PATCH 01/12] [gemini] prefetch chunks --- colossalai/zero/gemini/chunk/chunk.py | 12 ++-- colossalai/zero/gemini/chunk/manager.py | 10 +-- colossalai/zero/gemini/gemini_ddp.py | 4 +- colossalai/zero/gemini/gemini_hook.py | 87 +++++++++++++++++++++++-- 4 files changed, 96 insertions(+), 17 deletions(-) diff --git a/colossalai/zero/gemini/chunk/chunk.py b/colossalai/zero/gemini/chunk/chunk.py index cad2622f2..299ea0518 100644 --- a/colossalai/zero/gemini/chunk/chunk.py +++ b/colossalai/zero/gemini/chunk/chunk.py @@ -357,14 +357,14 @@ class Chunk: else: raise NotImplementedError - def access_chunk(self): + def access_chunk(self, async_access: bool = False) -> Optional[dist.Work]: """Make the chunk usable for the parameters inside it. It's an operation done in CUDA.""" # sanity check assert self.chunk_temp is None - if not self.is_gathered: - self.__gather() + return self.__gather(async_op=async_access) self.__update_tensors_ptr() + return None def release_chunk(self): """Release the usable chunk. It's an operation done in CUDA.""" @@ -498,17 +498,19 @@ class Chunk: def get_tensors(self) -> List[torch.Tensor]: return list(self.tensors_info.keys()) - def __gather(self): + def __gather(self, async_op: bool = False) -> Optional[dist.Work]: if not self.is_gathered: # sanity check assert self.cuda_shard is not None alloc_storage(self.cuda_global_chunk) gather_list = list(torch.chunk(input=self.cuda_global_chunk, chunks=self.pg_size, dim=0)) - dist.all_gather(gather_list, self.cuda_shard, self.torch_pg) + work = dist.all_gather(gather_list, self.cuda_shard, self.torch_pg, async_op=async_op) self.cuda_shard = None self.is_gathered = True + return work + return None def __scatter(self): if self.keep_gathered: diff --git a/colossalai/zero/gemini/chunk/manager.py b/colossalai/zero/gemini/chunk/manager.py index 333a3f224..9cee5223e 100644 --- a/colossalai/zero/gemini/chunk/manager.py +++ b/colossalai/zero/gemini/chunk/manager.py @@ -111,15 +111,16 @@ class ChunkManager: for group_name in self.chunk_groups: self.__close_one_chunk(self.chunk_groups[group_name][-1]) - def access_chunk(self, chunk: Chunk) -> None: + def access_chunk(self, chunk: Chunk, async_access: bool = False) -> Optional[dist.Work]: """Make the chunk can be used for calculation.""" if chunk in self.accessed_chunks: return self.__sub_memory_usage(chunk.memory_usage) if chunk.device_type == "cpu": chunk.shard_move(get_accelerator().get_current_device()) - self.__add_accessed_chunk(chunk) + maybe_work = self.__add_accessed_chunk(chunk, async_access=async_access) self.__add_memory_usage(chunk.memory_usage) + return maybe_work def release_chunk(self, chunk: Chunk) -> None: """Scatter the chunk in CUDA.""" @@ -251,10 +252,11 @@ class ChunkManager: for k, v in usage.items(): self.total_mem[k] += v - def __add_accessed_chunk(self, chunk: Chunk): - chunk.access_chunk() + def __add_accessed_chunk(self, chunk: Chunk, async_access: bool = False) -> Optional[dist.Work]: + maybe_work = chunk.access_chunk(async_access=async_access) self.accessed_chunks.add(chunk) self.accessed_mem += chunk.chunk_mem + return maybe_work def __sub_accessed_chunk(self, chunk: Chunk): chunk.release_chunk() diff --git a/colossalai/zero/gemini/gemini_ddp.py b/colossalai/zero/gemini/gemini_ddp.py index c1029097a..21448bdae 100644 --- a/colossalai/zero/gemini/gemini_ddp.py +++ b/colossalai/zero/gemini/gemini_ddp.py @@ -78,6 +78,7 @@ class GeminiDDP(ModelWrapper): chunk_init_device: torch.device = torch.device("cpu"), placement_policy: str = "static", enable_gradient_accumulation: bool = False, + max_prefetch: int = 0, shard_param_frac: float = 1.0, # only for static placement offload_optim_frac: float = 0.0, # only for static placement offload_param_frac: float = 0.0, # only for static placement @@ -132,7 +133,6 @@ class GeminiDDP(ModelWrapper): steady_cuda_cap_ratio=steady_cuda_cap_ratio, ) self.force_outputs_fp32 = force_outputs_fp32 - self.param_op_hook = GeminiZeROHook(self.gemini_manager) self.fp32_params: List[torch.Tensor] = list() self.fp16_params: List[ColoParameter] = list() self.grads_device: Dict[torch.Tensor, torch.device] = dict() @@ -157,6 +157,8 @@ class GeminiDDP(ModelWrapper): for p in module.parameters(): param_order.append(p) + self.param_op_hook = GeminiZeROHook(self.gemini_manager, param_order=param_order, max_prefetch=max_prefetch) + for name, param in module.named_parameters(): self.param2name[param] = name for m_name, m_var in module.named_modules(): diff --git a/colossalai/zero/gemini/gemini_hook.py b/colossalai/zero/gemini/gemini_hook.py index 480a14511..7f75f2471 100644 --- a/colossalai/zero/gemini/gemini_hook.py +++ b/colossalai/zero/gemini/gemini_hook.py @@ -1,14 +1,18 @@ +from chunk import Chunk from contextlib import contextmanager from enum import Enum from functools import partial -from typing import List +from typing import Dict, List import torch +import torch.distributed as dist +from colossalai.tensor.colo_parameter import ColoParameter from colossalai.tensor.param_op_hook import ColoParamOpHook from colossalai.utils import is_ddp_ignored from colossalai.zero.gemini import TensorState from colossalai.zero.gemini.gemini_mgr import GeminiManager +from colossalai.zero.gemini.memory_tracer.param_runtime_order import OrderedParamGenerator class TrainingPhase(Enum): @@ -16,23 +20,92 @@ class TrainingPhase(Enum): BACKWARD = 1 +DEBUG = True # TODO @botbw: remove + + class GeminiZeROHook(ColoParamOpHook): - def __init__(self, gemini_manager: GeminiManager) -> None: + def __init__( + self, gemini_manager: GeminiManager, param_order: OrderedParamGenerator, max_prefetch: int = 0 + ) -> None: super().__init__() self._gemini_manager = gemini_manager self._chunk_manager = gemini_manager.chunk_manager self._training_phase = TrainingPhase.FORWARD + self._cur_param = None + # param_visited_order might be updated somewhere else + self._param_visited_order = param_order.param_visited_order + self._max_prefetch = max_prefetch + self._async_works: Dict[Chunk, dist.work] = {} - def pre_op(self, params): - params = [p for p in params if not is_ddp_ignored(p)] - chunks = self._chunk_manager.get_chunks(params) + # used by get_prefetch_chunks to track current param + self._cur_param_idx = 0 + + def get_prefetch_chunks(self, all_params: List[ColoParameter]) -> List[Chunk]: + chunks_to_prefetch = set() + if self._training_phase == TrainingPhase.FORWARD: # forward phrase: increase + self._cur_param_idx += len(all_params) # need to update first + idx = self._cur_param_idx + 1 + # still have params and prefetched chunks don't exceed the limit + while idx < len(self._param_visited_order) and len(chunks_to_prefetch) + 1 < self._max_prefetch: + param = self._param_visited_order[idx] + if is_ddp_ignored(param): + idx += 1 + continue + chunk = self._chunk_manager.get_chunk(param) + chunks_to_prefetch.add(chunk) + idx += 1 + else: + assert self._training_phase == TrainingPhase.BACKWARD + self._cur_param_idx -= len(all_params) + idx = self._cur_param_idx - 1 + chunks_to_prefetch = set() + while idx >= 0 and len(chunks_to_prefetch) + 1 < self._max_prefetch: + param = self._param_visited_order[idx] + if is_ddp_ignored(param): + idx -= 1 + continue + chunk = self._chunk_manager.get_chunk(self._param_visited_order[idx]) + chunks_to_prefetch.add(chunk) + idx -= 1 + return list(chunks_to_prefetch) + + def wait_chunks(self, chunks: List[Chunk]) -> List[Chunk]: + non_prefetched_chunks = [] + for chunk in chunks: + if chunk in self._async_works: + self._async_works[chunk].wait() + del self._async_works[chunk] + else: + non_prefetched_chunks.append(chunk) + return non_prefetched_chunks + + def pre_op(self, all_params): + if DEBUG: # TODO @botbw: remove + idxs = list(map(lambda x: self._linked_param_order.param_visited_order.index(x), all_params)) + mx = max(idxs) + idxs = sorted(map(lambda x: x - mx, idxs)) + assert list(range(len(idxs))) == idxs, f"{idxs=}" + + # deal with current needed chunks + params = [p for p in all_params if not is_ddp_ignored(p)] + all_chunks = self._chunk_manager.get_chunks(params) + chunks_wo_work = self.wait_chunks(all_chunks) for p in params: self._chunk_manager.trans_tensor_state(p, TensorState.COMPUTE) self._gemini_manager.sample_overall_data() - self._gemini_manager.adjust_layout(chunks) - for chunk in chunks: + self._gemini_manager.adjust_layout(chunks_wo_work) + + # deal with chunks that are to be async fetched + prefetch_chunks = self.get_prefetch_chunks(all_params) + + # deal with chunks that are to be fetched now + for chunk in chunks_wo_work: self._chunk_manager.access_chunk(chunk) + # deal with chunks that are to be pre fetched TODO @botbw: the order here matters? + for chunk in prefetch_chunks: + self._async_works[chunk] = self._chunk_manager.access_chunk(chunk, async_access=True) + # record cuda model data of the current OP self._gemini_manager.record_model_data_volume() From b2e97458883c64e4f357059f585ff2585fa12edd Mon Sep 17 00:00:00 2001 From: hxwang Date: Thu, 16 May 2024 04:45:06 +0000 Subject: [PATCH 02/12] [chore] sync --- colossalai/booster/plugin/gemini_plugin.py | 2 + colossalai/zero/gemini/gemini_hook.py | 57 ++++++++++++++-------- 2 files changed, 39 insertions(+), 20 deletions(-) diff --git a/colossalai/booster/plugin/gemini_plugin.py b/colossalai/booster/plugin/gemini_plugin.py index 964cd302a..b1f8ea24a 100644 --- a/colossalai/booster/plugin/gemini_plugin.py +++ b/colossalai/booster/plugin/gemini_plugin.py @@ -329,6 +329,7 @@ class GeminiPlugin(DPPluginBase): chunk_init_device: Optional[torch.device] = None, placement_policy: str = "static", enable_gradient_accumulation: bool = False, + max_prefetch:int = 0, shard_param_frac: float = 1.0, # only for static placement offload_optim_frac: float = 0.0, # only for static placement offload_param_frac: float = 0.0, # only for static placement @@ -386,6 +387,7 @@ class GeminiPlugin(DPPluginBase): memstats=memstats, mixed_precision=PRECISION_STR_TO_DTYPE[precision], master_weights=master_weights, + max_prefetch=max_prefetch, ) self.zero_optim_config = dict( gpu_margin_mem_ratio=gpu_margin_mem_ratio, diff --git a/colossalai/zero/gemini/gemini_hook.py b/colossalai/zero/gemini/gemini_hook.py index 7f75f2471..01d9c9d07 100644 --- a/colossalai/zero/gemini/gemini_hook.py +++ b/colossalai/zero/gemini/gemini_hook.py @@ -1,4 +1,3 @@ -from chunk import Chunk from contextlib import contextmanager from enum import Enum from functools import partial @@ -13,15 +12,16 @@ from colossalai.utils import is_ddp_ignored from colossalai.zero.gemini import TensorState from colossalai.zero.gemini.gemini_mgr import GeminiManager from colossalai.zero.gemini.memory_tracer.param_runtime_order import OrderedParamGenerator +from colossalai.logging import DistributedLogger +from .chunk import Chunk class TrainingPhase(Enum): FORWARD = 0 BACKWARD = 1 -DEBUG = True # TODO @botbw: remove - +logger = DistributedLogger("gemini_hook") class GeminiZeROHook(ColoParamOpHook): def __init__( @@ -31,16 +31,14 @@ class GeminiZeROHook(ColoParamOpHook): self._gemini_manager = gemini_manager self._chunk_manager = gemini_manager.chunk_manager self._training_phase = TrainingPhase.FORWARD - self._cur_param = None # param_visited_order might be updated somewhere else self._param_visited_order = param_order.param_visited_order self._max_prefetch = max_prefetch self._async_works: Dict[Chunk, dist.work] = {} - # used by get_prefetch_chunks to track current param self._cur_param_idx = 0 - def get_prefetch_chunks(self, all_params: List[ColoParameter]) -> List[Chunk]: + def get_prefetch_chunks(self, all_params: List[ColoParameter], cur_chunks: List[Chunk]) -> List[Chunk]: chunks_to_prefetch = set() if self._training_phase == TrainingPhase.FORWARD: # forward phrase: increase self._cur_param_idx += len(all_params) # need to update first @@ -52,10 +50,10 @@ class GeminiZeROHook(ColoParamOpHook): idx += 1 continue chunk = self._chunk_manager.get_chunk(param) - chunks_to_prefetch.add(chunk) + if chunk not in cur_chunks: + chunks_to_prefetch.add(chunk) idx += 1 else: - assert self._training_phase == TrainingPhase.BACKWARD self._cur_param_idx -= len(all_params) idx = self._cur_param_idx - 1 chunks_to_prefetch = set() @@ -65,14 +63,17 @@ class GeminiZeROHook(ColoParamOpHook): idx -= 1 continue chunk = self._chunk_manager.get_chunk(self._param_visited_order[idx]) - chunks_to_prefetch.add(chunk) + if chunk not in cur_chunks: + chunks_to_prefetch.add(chunk) idx -= 1 + print(f"cur id {self._cur_param_idx}") return list(chunks_to_prefetch) def wait_chunks(self, chunks: List[Chunk]) -> List[Chunk]: non_prefetched_chunks = [] for chunk in chunks: if chunk in self._async_works: + print(f"prefetched {chunk.count_id}") self._async_works[chunk].wait() del self._async_works[chunk] else: @@ -80,31 +81,42 @@ class GeminiZeROHook(ColoParamOpHook): return non_prefetched_chunks def pre_op(self, all_params): - if DEBUG: # TODO @botbw: remove - idxs = list(map(lambda x: self._linked_param_order.param_visited_order.index(x), all_params)) - mx = max(idxs) - idxs = sorted(map(lambda x: x - mx, idxs)) - assert list(range(len(idxs))) == idxs, f"{idxs=}" + # def find_idx(param): + # for i, p in enumerate(self._param_visited_order): + # if param is p: + # return i + # assert False + + # idxs = [find_idx(p) for p in all_params] + # max_id = min(idxs) + # idxs = [i - max_id for i in idxs] + # assert list(range(len(idxs))) == sorted(idxs), f'{idxs}' # deal with current needed chunks params = [p for p in all_params if not is_ddp_ignored(p)] all_chunks = self._chunk_manager.get_chunks(params) - chunks_wo_work = self.wait_chunks(all_chunks) + chunks_need_to_fetch_sync = tuple(self.wait_chunks(all_chunks)) for p in params: self._chunk_manager.trans_tensor_state(p, TensorState.COMPUTE) self._gemini_manager.sample_overall_data() - self._gemini_manager.adjust_layout(chunks_wo_work) + self._gemini_manager.adjust_layout(chunks_need_to_fetch_sync) # deal with chunks that are to be async fetched - prefetch_chunks = self.get_prefetch_chunks(all_params) + chunks_can_be_fetch_async = self.get_prefetch_chunks(all_params=all_params, cur_chunks=chunks_need_to_fetch_sync) + print(f"cur_chunks {' '.join([str(x.count_id) for x in chunks_need_to_fetch_sync])}, prefetch {' '.join([str(x.count_id) for x in chunks_can_be_fetch_async])}") # deal with chunks that are to be fetched now - for chunk in chunks_wo_work: + for chunk in chunks_need_to_fetch_sync: self._chunk_manager.access_chunk(chunk) # deal with chunks that are to be pre fetched TODO @botbw: the order here matters? - for chunk in prefetch_chunks: - self._async_works[chunk] = self._chunk_manager.access_chunk(chunk, async_access=True) + for chunk in chunks_can_be_fetch_async: + if chunk in self._async_works: + continue + maybe_work = self._chunk_manager.access_chunk(chunk, async_access=True) + if maybe_work is not None: + print(f"prefetch {chunk.count_id}") + self._async_works[chunk] = maybe_work # record cuda model data of the current OP self._gemini_manager.record_model_data_volume() @@ -133,6 +145,11 @@ class GeminiZeROHook(ColoParamOpHook): @contextmanager def switch_training_phase(self, training_phase: TrainingPhase = TrainingPhase.BACKWARD): + if training_phase == TrainingPhase.FORWARD: + self._cur_param_idx = 0 + else: + self._cur_param_idx = len(self._param_visited_order) - 1 + old_training_phase = self._training_phase try: self._training_phase = training_phase From 4148ceed9f17446a6c247b49c33805b5abd17984 Mon Sep 17 00:00:00 2001 From: hxwang Date: Thu, 16 May 2024 13:17:26 +0800 Subject: [PATCH 03/12] [gemini] use compute_chunk to find next chunk --- colossalai/zero/gemini/chunk/manager.py | 2 +- colossalai/zero/gemini/gemini_ddp.py | 3 +- colossalai/zero/gemini/gemini_hook.py | 85 ++++------------------ colossalai/zero/gemini/gemini_mgr.py | 22 ++++-- colossalai/zero/gemini/placement_policy.py | 19 +++++ 5 files changed, 52 insertions(+), 79 deletions(-) diff --git a/colossalai/zero/gemini/chunk/manager.py b/colossalai/zero/gemini/chunk/manager.py index 9cee5223e..c7bdd5e1f 100644 --- a/colossalai/zero/gemini/chunk/manager.py +++ b/colossalai/zero/gemini/chunk/manager.py @@ -114,7 +114,7 @@ class ChunkManager: def access_chunk(self, chunk: Chunk, async_access: bool = False) -> Optional[dist.Work]: """Make the chunk can be used for calculation.""" if chunk in self.accessed_chunks: - return + return None self.__sub_memory_usage(chunk.memory_usage) if chunk.device_type == "cpu": chunk.shard_move(get_accelerator().get_current_device()) diff --git a/colossalai/zero/gemini/gemini_ddp.py b/colossalai/zero/gemini/gemini_ddp.py index 21448bdae..b75f69a3b 100644 --- a/colossalai/zero/gemini/gemini_ddp.py +++ b/colossalai/zero/gemini/gemini_ddp.py @@ -133,6 +133,7 @@ class GeminiDDP(ModelWrapper): steady_cuda_cap_ratio=steady_cuda_cap_ratio, ) self.force_outputs_fp32 = force_outputs_fp32 + self.param_op_hook = GeminiZeROHook(self.gemini_manager, max_prefetch=max_prefetch) self.fp32_params: List[torch.Tensor] = list() self.fp16_params: List[ColoParameter] = list() self.grads_device: Dict[torch.Tensor, torch.device] = dict() @@ -157,8 +158,6 @@ class GeminiDDP(ModelWrapper): for p in module.parameters(): param_order.append(p) - self.param_op_hook = GeminiZeROHook(self.gemini_manager, param_order=param_order, max_prefetch=max_prefetch) - for name, param in module.named_parameters(): self.param2name[param] = name for m_name, m_var in module.named_modules(): diff --git a/colossalai/zero/gemini/gemini_hook.py b/colossalai/zero/gemini/gemini_hook.py index 01d9c9d07..82d890975 100644 --- a/colossalai/zero/gemini/gemini_hook.py +++ b/colossalai/zero/gemini/gemini_hook.py @@ -6,16 +6,15 @@ from typing import Dict, List import torch import torch.distributed as dist -from colossalai.tensor.colo_parameter import ColoParameter +from colossalai.logging import DistributedLogger from colossalai.tensor.param_op_hook import ColoParamOpHook from colossalai.utils import is_ddp_ignored from colossalai.zero.gemini import TensorState from colossalai.zero.gemini.gemini_mgr import GeminiManager -from colossalai.zero.gemini.memory_tracer.param_runtime_order import OrderedParamGenerator -from colossalai.logging import DistributedLogger from .chunk import Chunk + class TrainingPhase(Enum): FORWARD = 0 BACKWARD = 1 @@ -23,51 +22,15 @@ class TrainingPhase(Enum): logger = DistributedLogger("gemini_hook") + class GeminiZeROHook(ColoParamOpHook): - def __init__( - self, gemini_manager: GeminiManager, param_order: OrderedParamGenerator, max_prefetch: int = 0 - ) -> None: + def __init__(self, gemini_manager: GeminiManager, max_prefetch: int = 0) -> None: super().__init__() self._gemini_manager = gemini_manager self._chunk_manager = gemini_manager.chunk_manager self._training_phase = TrainingPhase.FORWARD - # param_visited_order might be updated somewhere else - self._param_visited_order = param_order.param_visited_order self._max_prefetch = max_prefetch self._async_works: Dict[Chunk, dist.work] = {} - # used by get_prefetch_chunks to track current param - self._cur_param_idx = 0 - - def get_prefetch_chunks(self, all_params: List[ColoParameter], cur_chunks: List[Chunk]) -> List[Chunk]: - chunks_to_prefetch = set() - if self._training_phase == TrainingPhase.FORWARD: # forward phrase: increase - self._cur_param_idx += len(all_params) # need to update first - idx = self._cur_param_idx + 1 - # still have params and prefetched chunks don't exceed the limit - while idx < len(self._param_visited_order) and len(chunks_to_prefetch) + 1 < self._max_prefetch: - param = self._param_visited_order[idx] - if is_ddp_ignored(param): - idx += 1 - continue - chunk = self._chunk_manager.get_chunk(param) - if chunk not in cur_chunks: - chunks_to_prefetch.add(chunk) - idx += 1 - else: - self._cur_param_idx -= len(all_params) - idx = self._cur_param_idx - 1 - chunks_to_prefetch = set() - while idx >= 0 and len(chunks_to_prefetch) + 1 < self._max_prefetch: - param = self._param_visited_order[idx] - if is_ddp_ignored(param): - idx -= 1 - continue - chunk = self._chunk_manager.get_chunk(self._param_visited_order[idx]) - if chunk not in cur_chunks: - chunks_to_prefetch.add(chunk) - idx -= 1 - print(f"cur id {self._cur_param_idx}") - return list(chunks_to_prefetch) def wait_chunks(self, chunks: List[Chunk]) -> List[Chunk]: non_prefetched_chunks = [] @@ -80,45 +43,25 @@ class GeminiZeROHook(ColoParamOpHook): non_prefetched_chunks.append(chunk) return non_prefetched_chunks - def pre_op(self, all_params): - # def find_idx(param): - # for i, p in enumerate(self._param_visited_order): - # if param is p: - # return i - # assert False - - # idxs = [find_idx(p) for p in all_params] - # max_id = min(idxs) - # idxs = [i - max_id for i in idxs] - # assert list(range(len(idxs))) == sorted(idxs), f'{idxs}' - - # deal with current needed chunks - params = [p for p in all_params if not is_ddp_ignored(p)] + def pre_op(self, params): + params = [p for p in params if not is_ddp_ignored(p)] all_chunks = self._chunk_manager.get_chunks(params) - chunks_need_to_fetch_sync = tuple(self.wait_chunks(all_chunks)) + # wait for prefetched chunks, filter those are not prefetched + chunks_fetch_sync = tuple(self.wait_chunks(all_chunks)) for p in params: self._chunk_manager.trans_tensor_state(p, TensorState.COMPUTE) self._gemini_manager.sample_overall_data() - self._gemini_manager.adjust_layout(chunks_need_to_fetch_sync) - - # deal with chunks that are to be async fetched - chunks_can_be_fetch_async = self.get_prefetch_chunks(all_params=all_params, cur_chunks=chunks_need_to_fetch_sync) - - print(f"cur_chunks {' '.join([str(x.count_id) for x in chunks_need_to_fetch_sync])}, prefetch {' '.join([str(x.count_id) for x in chunks_can_be_fetch_async])}") - # deal with chunks that are to be fetched now - for chunk in chunks_need_to_fetch_sync: + self._gemini_manager.adjust_layout(all_chunks, record_anyway=self._max_prefetch > 0) + # fetch the rest chunks synchronously + for chunk in chunks_fetch_sync: self._chunk_manager.access_chunk(chunk) - - # deal with chunks that are to be pre fetched TODO @botbw: the order here matters? - for chunk in chunks_can_be_fetch_async: - if chunk in self._async_works: - continue + chunks_fetch_async = self._gemini_manager.placement_policy.get_prefetch_chunks(max_prefetch=self._max_prefetch) + for chunk in chunks_fetch_async: maybe_work = self._chunk_manager.access_chunk(chunk, async_access=True) if maybe_work is not None: - print(f"prefetch {chunk.count_id}") self._async_works[chunk] = maybe_work - # record cuda model data of the current OP + # record cuda model data of the current OP, including memory for prefetched chunks self._gemini_manager.record_model_data_volume() def post_op(self, params): diff --git a/colossalai/zero/gemini/gemini_mgr.py b/colossalai/zero/gemini/gemini_mgr.py index 150932e3d..0362d6523 100644 --- a/colossalai/zero/gemini/gemini_mgr.py +++ b/colossalai/zero/gemini/gemini_mgr.py @@ -6,7 +6,7 @@ import torch from .chunk import Chunk, ChunkManager from .memory_tracer import ChunkMemStatsCollector, MemStats -from .placement_policy import PlacementPolicyFactory +from .placement_policy import PlacementPolicy, PlacementPolicyFactory class GeminiManager: @@ -91,13 +91,13 @@ class GeminiManager: self._warmup = False self.reset_attributes() - def adjust_layout(self, chunks: Tuple[Chunk, ...]) -> None: + def adjust_layout(self, chunks: Tuple[Chunk, ...], record_anyway: bool = False) -> None: """Adjust the layout of stateful tensors according to the information provided by mem_stats_collector, which should belongs to a Sharded Model. """ # find stateful tensor in state COMPUTE start = time() - self._record_chunks_order(chunks) + self._record_warmup_chunks_order(chunks, record_anyway=record_anyway) cuda_demand, hold_cuda_tensor_list = self._get_layout_info(self._compute_idx, self._warmup, chunks) self._layout_time += time() - start @@ -133,9 +133,9 @@ class GeminiManager: can_evict_chunks = self._chunk_manager.get_cuda_movable_chunks() return cuda_demand, can_evict_chunks - def _record_chunks_order(self, chunks: Tuple[Chunk, ...]) -> None: + def _record_warmup_chunks_order(self, chunks: Tuple[Chunk, ...], record_anyway: bool = False) -> None: self._compute_idx += 1 - if self._warmup and self._placement_policy.need_mem_stats: + if self._warmup and (self._placement_policy.need_mem_stats or record_anyway): self._compute_list.append(chunks) def sample_overall_data(self): @@ -156,6 +156,18 @@ class GeminiManager: return self._mem_stats_collector.cuda_margin_mem return None + @property + def compute_list(self) -> List[Tuple[Chunk, ...]]: + return self._compute_list + + @property + def compute_idx(self) -> int: + return self._compute_idx + + @property + def placement_policy(self) -> PlacementPolicy: + return self._placement_policy + @property def is_cuda_margin_mem_avail(self) -> bool: return self._placement_policy.need_mem_stats diff --git a/colossalai/zero/gemini/placement_policy.py b/colossalai/zero/gemini/placement_policy.py index 388999549..452687b7d 100644 --- a/colossalai/zero/gemini/placement_policy.py +++ b/colossalai/zero/gemini/placement_policy.py @@ -33,6 +33,10 @@ class PlacementPolicy(ABC): ) -> None: raise NotImplementedError + @abstractmethod + def get_prefetch_chunks(self, max_prefetch: int) -> List[Chunk]: + raise NotImplementedError + class StaticPlacementPolicy(PlacementPolicy): def __init__( @@ -95,6 +99,18 @@ class StaticPlacementPolicy(PlacementPolicy): self.keep_gathered_chunk_mem = total_chunk_mem * (1 - self.shard_param_frac) self.keep_cuda_chunk_mem = total_chunk_mem * (1 - self.offload_param_frac) + def get_prefetch_chunks(self, max_prefetch: int) -> List[Chunk]: + prefetch = [] + for i in range(self.chunk_manager.compute_idx + 1, len(self.chunk_manager.compute_list)): + for chunk in self.chunk_manager.compute_list[i]: + if len(prefetch) >= max_prefetch: + break + if chunk not in prefetch: + prefetch.append(chunk) + if len(prefetch) >= max_prefetch: + break + return prefetch + class AutoPlacementPolicy(PlacementPolicy): need_mem_stats: bool = True @@ -198,6 +214,9 @@ class AutoPlacementPolicy(PlacementPolicy): else: grads_device_map[p] = torch.device("cpu") + def get_prefetch_chunks(self, max_prefetch: int) -> List[Chunk]: + return [] # TODO @botbw: implement prefetching for auto + class PlacementPolicyFactory: policies: Dict[str, Type[PlacementPolicy]] = { From 5bedea6e10db044c8395c8410d0fcab9f4fbb3d9 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 16 May 2024 05:20:00 +0000 Subject: [PATCH 04/12] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- colossalai/booster/plugin/gemini_plugin.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/colossalai/booster/plugin/gemini_plugin.py b/colossalai/booster/plugin/gemini_plugin.py index b1f8ea24a..aeef14487 100644 --- a/colossalai/booster/plugin/gemini_plugin.py +++ b/colossalai/booster/plugin/gemini_plugin.py @@ -329,7 +329,7 @@ class GeminiPlugin(DPPluginBase): chunk_init_device: Optional[torch.device] = None, placement_policy: str = "static", enable_gradient_accumulation: bool = False, - max_prefetch:int = 0, + max_prefetch: int = 0, shard_param_frac: float = 1.0, # only for static placement offload_optim_frac: float = 0.0, # only for static placement offload_param_frac: float = 0.0, # only for static placement From 2e68eebdfe9a8f68c0cb9a260ce7f2de4e6b6e27 Mon Sep 17 00:00:00 2001 From: hxwang Date: Thu, 16 May 2024 07:22:10 +0000 Subject: [PATCH 05/12] [chore] refactor & sync --- colossalai/zero/gemini/chunk/chunk.py | 1 + colossalai/zero/gemini/gemini_ddp.py | 3 +- colossalai/zero/gemini/gemini_hook.py | 55 ++++++++++--------- colossalai/zero/gemini/gemini_mgr.py | 27 +++++++-- colossalai/zero/gemini/placement_policy.py | 31 +++++++---- examples/language/gpt/gemini/commons/utils.py | 5 +- .../language/gpt/gemini/train_gpt_demo.py | 6 +- 7 files changed, 82 insertions(+), 46 deletions(-) diff --git a/colossalai/zero/gemini/chunk/chunk.py b/colossalai/zero/gemini/chunk/chunk.py index 299ea0518..81b6192ad 100644 --- a/colossalai/zero/gemini/chunk/chunk.py +++ b/colossalai/zero/gemini/chunk/chunk.py @@ -567,6 +567,7 @@ class Chunk: return self is __o def __repr__(self, detailed: bool = True): + return f"Chunk({self.count_id})" output = [ "Chunk Information:\n", "\tchunk size: {}, chunk dtype: {}, process group size: {}\n".format( diff --git a/colossalai/zero/gemini/gemini_ddp.py b/colossalai/zero/gemini/gemini_ddp.py index b75f69a3b..6bf0b4019 100644 --- a/colossalai/zero/gemini/gemini_ddp.py +++ b/colossalai/zero/gemini/gemini_ddp.py @@ -131,9 +131,10 @@ class GeminiDDP(ModelWrapper): offload_param_frac=offload_param_frac, warmup_non_model_data_ratio=warmup_non_model_data_ratio, steady_cuda_cap_ratio=steady_cuda_cap_ratio, + max_prefetch=max_prefetch ) self.force_outputs_fp32 = force_outputs_fp32 - self.param_op_hook = GeminiZeROHook(self.gemini_manager, max_prefetch=max_prefetch) + self.param_op_hook = GeminiZeROHook(self.gemini_manager) self.fp32_params: List[torch.Tensor] = list() self.fp16_params: List[ColoParameter] = list() self.grads_device: Dict[torch.Tensor, torch.device] = dict() diff --git a/colossalai/zero/gemini/gemini_hook.py b/colossalai/zero/gemini/gemini_hook.py index 82d890975..1d734bd83 100644 --- a/colossalai/zero/gemini/gemini_hook.py +++ b/colossalai/zero/gemini/gemini_hook.py @@ -1,7 +1,7 @@ from contextlib import contextmanager from enum import Enum from functools import partial -from typing import Dict, List +from typing import Dict, List, Iterable, Tuple import torch import torch.distributed as dist @@ -22,45 +22,55 @@ class TrainingPhase(Enum): logger = DistributedLogger("gemini_hook") +import os +rank = int(os.environ['RANK']) class GeminiZeROHook(ColoParamOpHook): - def __init__(self, gemini_manager: GeminiManager, max_prefetch: int = 0) -> None: + def __init__(self, gemini_manager: GeminiManager) -> None: super().__init__() self._gemini_manager = gemini_manager self._chunk_manager = gemini_manager.chunk_manager self._training_phase = TrainingPhase.FORWARD - self._max_prefetch = max_prefetch - self._async_works: Dict[Chunk, dist.work] = {} - def wait_chunks(self, chunks: List[Chunk]) -> List[Chunk]: - non_prefetched_chunks = [] - for chunk in chunks: - if chunk in self._async_works: - print(f"prefetched {chunk.count_id}") - self._async_works[chunk].wait() - del self._async_works[chunk] - else: - non_prefetched_chunks.append(chunk) - return non_prefetched_chunks def pre_op(self, params): + # map params to chunks params = [p for p in params if not is_ddp_ignored(p)] all_chunks = self._chunk_manager.get_chunks(params) + # wait for prefetched chunks, filter those are not prefetched - chunks_fetch_sync = tuple(self.wait_chunks(all_chunks)) + unique_chunks = set(all_chunks) + chunks_fetch_sync = self._gemini_manager.wait_chunks(all_chunks) + + # transfer state for p in params: self._chunk_manager.trans_tensor_state(p, TensorState.COMPUTE) self._gemini_manager.sample_overall_data() - self._gemini_manager.adjust_layout(all_chunks, record_anyway=self._max_prefetch > 0) - # fetch the rest chunks synchronously + + # evit chunks, aware of async fetched + self._gemini_manager.adjust_layout(all_chunks, record_anyway=self._gemini_manager.placement_policy.max_prefetch > 0) + + # fetch the rest synchronously for chunk in chunks_fetch_sync: self._chunk_manager.access_chunk(chunk) - chunks_fetch_async = self._gemini_manager.placement_policy.get_prefetch_chunks(max_prefetch=self._max_prefetch) + + # get possible chunks to prefetch + chunks_fetch_async = self._gemini_manager.placement_policy.get_prefetch_chunks() + if rank == 0 and not self._gemini_manager.is_warmup(): + print(f"compute_id: {self._gemini_manager.compute_idx} self._gemini_manager.compute_list: {self._gemini_manager.compute_list}") + print(f"{all_chunks=}") + print(f"accessed_chunks={self._chunk_manager.accessed_chunks}") + print(f"{chunks_fetch_sync=}") + print(f"{chunks_fetch_async=}") + print(f"works={list(self._gemini_manager._async_works.keys())}") + + # prefetch for chunk in chunks_fetch_async: maybe_work = self._chunk_manager.access_chunk(chunk, async_access=True) if maybe_work is not None: - self._async_works[chunk] = maybe_work - + self._gemini_manager.add_work(chunk, maybe_work) + if rank == 0 and not self._gemini_manager.is_warmup(): + print(f"post accessed_chunks={self._chunk_manager.accessed_chunks}") # record cuda model data of the current OP, including memory for prefetched chunks self._gemini_manager.record_model_data_volume() @@ -88,11 +98,6 @@ class GeminiZeROHook(ColoParamOpHook): @contextmanager def switch_training_phase(self, training_phase: TrainingPhase = TrainingPhase.BACKWARD): - if training_phase == TrainingPhase.FORWARD: - self._cur_param_idx = 0 - else: - self._cur_param_idx = len(self._param_visited_order) - 1 - old_training_phase = self._training_phase try: self._training_phase = training_phase diff --git a/colossalai/zero/gemini/gemini_mgr.py b/colossalai/zero/gemini/gemini_mgr.py index 0362d6523..6640bf03b 100644 --- a/colossalai/zero/gemini/gemini_mgr.py +++ b/colossalai/zero/gemini/gemini_mgr.py @@ -1,8 +1,9 @@ import functools from time import time -from typing import Dict, List, Optional, Tuple +from typing import Dict, List, Optional, Tuple, Iterable import torch +import torch.distributed as dist from .chunk import Chunk, ChunkManager from .memory_tracer import ChunkMemStatsCollector, MemStats @@ -41,9 +42,10 @@ class GeminiManager: self._mem_stats_collector = ( ChunkMemStatsCollector(chunk_manager, self._memstats) if policy_cls.need_mem_stats else None ) - self._placement_policy = policy_cls(chunk_manager, self._mem_stats_collector, **placement_kwargs) + self._placement_policy = policy_cls(self, chunk_manager, self._mem_stats_collector, **placement_kwargs) self._compute_list: List[Tuple[Chunk, ...]] = [] self._compute_idx: int = -1 + self._async_works: Dict[Chunk, dist.work] = {} self._h2d_volume = 0 self._d2h_volume = 0 @@ -98,11 +100,13 @@ class GeminiManager: # find stateful tensor in state COMPUTE start = time() self._record_warmup_chunks_order(chunks, record_anyway=record_anyway) - cuda_demand, hold_cuda_tensor_list = self._get_layout_info(self._compute_idx, self._warmup, chunks) + cuda_demand, can_evict_chunks = self._get_layout_info(self._compute_idx, self._warmup, chunks) + # don't evict chunks that are asynchronously fetched + can_evict_chunks = [chunk for chunk in can_evict_chunks if chunk not in self._async_works] self._layout_time += time() - start vol, evict_time = self._placement_policy.evict_tensors( - can_evict_chunks=hold_cuda_tensor_list, + can_evict_chunks=can_evict_chunks, cuda_demand=cuda_demand, warmup=self._warmup, compute_list=self._compute_list, @@ -114,6 +118,21 @@ class GeminiManager: # move COMPUTE tensors to CUDA self._h2d_volume += cuda_demand + def wait_chunks(self, chunks: Iterable[Chunk]) -> Tuple[Chunk]: + non_prefetched_chunks = [] + for chunk in chunks: + if chunk in self._async_works: + self._async_works[chunk].wait() + del self._async_works[chunk] + else: + non_prefetched_chunks.append(chunk) + return tuple(non_prefetched_chunks) + + def add_work(self, chunk: Chunk, work: dist.Work): + assert work is not None + assert chunk not in self._async_works + self._async_works[chunk] = work + @functools.lru_cache(maxsize=None) def _get_layout_info(self, compute_idx: int, warmup: bool, chunks: Tuple[Chunk, ...]): start = time() diff --git a/colossalai/zero/gemini/placement_policy.py b/colossalai/zero/gemini/placement_policy.py index 452687b7d..aad97321c 100644 --- a/colossalai/zero/gemini/placement_policy.py +++ b/colossalai/zero/gemini/placement_policy.py @@ -13,15 +13,16 @@ from colossalai.zero.gemini.chunk import Chunk from .chunk import Chunk, ChunkManager from .memory_tracer import ChunkMemStatsCollector - class PlacementPolicy(ABC): need_mem_stats: bool = False def __init__( - self, chunk_manager: ChunkManager, mem_stats_collector: Optional[ChunkMemStatsCollector] = None, **kwargs + self, gemini_manager: 'GeminiManager', chunk_manager: ChunkManager, mem_stats_collector: Optional[ChunkMemStatsCollector] = None, max_prefetch:int = 0, **kwargs ) -> None: + self.gemini_manager = gemini_manager self.chunk_manager = chunk_manager self.mem_stats_collector: Optional[ChunkMemStatsCollector] = mem_stats_collector + self.max_prefetch = max_prefetch @abstractmethod def evict_tensors(self, can_evict_chunks: List[Chunk], **kwargs) -> Tuple[int, float]: @@ -34,21 +35,25 @@ class PlacementPolicy(ABC): raise NotImplementedError @abstractmethod - def get_prefetch_chunks(self, max_prefetch: int) -> List[Chunk]: + def get_prefetch_chunks(self) -> List[Chunk]: raise NotImplementedError +import os +rank = int(os.environ["RANK"]) class StaticPlacementPolicy(PlacementPolicy): def __init__( self, + gemini_manager: 'GeminiManager', chunk_manager: ChunkManager, mem_stats_collector: Optional[ChunkMemStatsCollector] = None, + max_prefetch: int = 0, shard_param_frac: float = 1.0, offload_optim_frac: float = 0.0, offload_param_frac: float = 0.0, **kwargs, ) -> None: - super().__init__(chunk_manager, mem_stats_collector=mem_stats_collector) + super().__init__(gemini_manager, chunk_manager, mem_stats_collector=mem_stats_collector, max_prefetch=max_prefetch) if offload_param_frac > 0.0 and (shard_param_frac != 1.0 or offload_optim_frac != 1.0): warnings.warn("offload_param_frac is ignored when shard_param_frac != 1.0 or offload_optim_frac != 1.0") offload_param_frac = 0.0 @@ -99,15 +104,17 @@ class StaticPlacementPolicy(PlacementPolicy): self.keep_gathered_chunk_mem = total_chunk_mem * (1 - self.shard_param_frac) self.keep_cuda_chunk_mem = total_chunk_mem * (1 - self.offload_param_frac) - def get_prefetch_chunks(self, max_prefetch: int) -> List[Chunk]: + def get_prefetch_chunks(self) -> List[Chunk]: + if self.gemini_manager.is_warmup(): # no prefetch during warmup since we need compute_list + return [] prefetch = [] - for i in range(self.chunk_manager.compute_idx + 1, len(self.chunk_manager.compute_list)): - for chunk in self.chunk_manager.compute_list[i]: - if len(prefetch) >= max_prefetch: + for i in range(self.gemini_manager.compute_idx + 1, len(self.gemini_manager.compute_list)): + for chunk in self.gemini_manager.compute_list[i]: + if len(prefetch) >= self.max_prefetch: break - if chunk not in prefetch: + if chunk not in prefetch and chunk not in self.chunk_manager.accessed_chunks: prefetch.append(chunk) - if len(prefetch) >= max_prefetch: + if len(prefetch) >= self.max_prefetch: break return prefetch @@ -117,13 +124,15 @@ class AutoPlacementPolicy(PlacementPolicy): def __init__( self, + gemini_manager: 'GeminiManager', chunk_manager: ChunkManager, mem_stats_collector: Optional[ChunkMemStatsCollector] = None, + max_prefetch: int = 0, warmup_non_model_data_ratio: float = 0.8, steady_cuda_cap_ratio: float = 0.9, **kwargs, ) -> None: - super().__init__(chunk_manager, mem_stats_collector=mem_stats_collector) + super().__init__(gemini_manager, chunk_manager, mem_stats_collector=mem_stats_collector, max_prefetch=max_prefetch) # model data will use 1-_warmup_non_model_data_ratio CUDA memory in warmup phase # you can set them by AutoPlacementPolicy.set_warmup_non_model_data_ratio() # and AutoPlacementPolicy.set_steady_cuda_cap_ratio() diff --git a/examples/language/gpt/gemini/commons/utils.py b/examples/language/gpt/gemini/commons/utils.py index 7ed5fdb92..03054c0a2 100644 --- a/examples/language/gpt/gemini/commons/utils.py +++ b/examples/language/gpt/gemini/commons/utils.py @@ -30,8 +30,9 @@ def get_profile_context(enable_flag, warmup_steps, active_steps, save_dir): activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], schedule=schedule(wait=0, warmup=warmup_steps, active=active_steps), on_trace_ready=tensorboard_trace_handler(save_dir), - record_shapes=True, - profile_memory=True, + # record_shapes=True, + # profile_memory=True, + with_stack=True, ) else: return nullcontext(DummyProfiler()) diff --git a/examples/language/gpt/gemini/train_gpt_demo.py b/examples/language/gpt/gemini/train_gpt_demo.py index 4911ff124..6db74231a 100644 --- a/examples/language/gpt/gemini/train_gpt_demo.py +++ b/examples/language/gpt/gemini/train_gpt_demo.py @@ -129,7 +129,7 @@ def main(): WARMUP_STEPS = 1 assert WARMUP_STEPS < NUM_STEPS, "warmup steps should smaller than the total steps" assert (NUM_STEPS - WARMUP_STEPS) % 2 == 1, "the number of valid steps should be odd to take the median" - PROF_FLAG = False # The flag of profiling, False by default + PROF_FLAG = True # The flag of profiling, False by default disable_existing_loggers() colossalai.launch_from_torch() @@ -166,7 +166,7 @@ def main(): stage=zero_stage, reduce_bucket_size_in_m=12, overlap_communication=True, verbose=True ) elif args.distplan == "CAI_Gemini": - plugin = GeminiPlugin(search_range_m=128, hidden_dim=model.config.n_embd) + plugin = GeminiPlugin(search_range_m=128, hidden_dim=model.config.n_embd, max_prefetch=1) else: raise RuntimeError @@ -248,7 +248,7 @@ def main(): prof.step() tflops_list.sort() - median_index = ((NUM_STEPS - WARMUP_STEPS) >> 1) + WARMUP_STEPS + median_index = min(((NUM_STEPS - WARMUP_STEPS) >> 1) + WARMUP_STEPS, len(tflops_list) - 1) logger.info(f"Median TFLOPS is {tflops_list[median_index]:.3f}") torch.cuda.synchronize() From 6bbe956316d62202f1b19ea1033419d6a3ee91ea Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Thu, 16 May 2024 07:26:19 +0000 Subject: [PATCH 06/12] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- colossalai/zero/gemini/gemini_ddp.py | 2 +- colossalai/zero/gemini/gemini_hook.py | 20 ++++++++++--------- colossalai/zero/gemini/gemini_mgr.py | 4 ++-- colossalai/zero/gemini/placement_policy.py | 23 +++++++++++++++++----- 4 files changed, 32 insertions(+), 17 deletions(-) diff --git a/colossalai/zero/gemini/gemini_ddp.py b/colossalai/zero/gemini/gemini_ddp.py index 6bf0b4019..3a0ae59fc 100644 --- a/colossalai/zero/gemini/gemini_ddp.py +++ b/colossalai/zero/gemini/gemini_ddp.py @@ -131,7 +131,7 @@ class GeminiDDP(ModelWrapper): offload_param_frac=offload_param_frac, warmup_non_model_data_ratio=warmup_non_model_data_ratio, steady_cuda_cap_ratio=steady_cuda_cap_ratio, - max_prefetch=max_prefetch + max_prefetch=max_prefetch, ) self.force_outputs_fp32 = force_outputs_fp32 self.param_op_hook = GeminiZeROHook(self.gemini_manager) diff --git a/colossalai/zero/gemini/gemini_hook.py b/colossalai/zero/gemini/gemini_hook.py index 1d734bd83..e6b8cf8ef 100644 --- a/colossalai/zero/gemini/gemini_hook.py +++ b/colossalai/zero/gemini/gemini_hook.py @@ -1,10 +1,9 @@ from contextlib import contextmanager from enum import Enum from functools import partial -from typing import Dict, List, Iterable, Tuple +from typing import List import torch -import torch.distributed as dist from colossalai.logging import DistributedLogger from colossalai.tensor.param_op_hook import ColoParamOpHook @@ -12,8 +11,6 @@ from colossalai.utils import is_ddp_ignored from colossalai.zero.gemini import TensorState from colossalai.zero.gemini.gemini_mgr import GeminiManager -from .chunk import Chunk - class TrainingPhase(Enum): FORWARD = 0 @@ -23,7 +20,9 @@ class TrainingPhase(Enum): logger = DistributedLogger("gemini_hook") import os -rank = int(os.environ['RANK']) + +rank = int(os.environ["RANK"]) + class GeminiZeROHook(ColoParamOpHook): def __init__(self, gemini_manager: GeminiManager) -> None: @@ -32,14 +31,13 @@ class GeminiZeROHook(ColoParamOpHook): self._chunk_manager = gemini_manager.chunk_manager self._training_phase = TrainingPhase.FORWARD - def pre_op(self, params): # map params to chunks params = [p for p in params if not is_ddp_ignored(p)] all_chunks = self._chunk_manager.get_chunks(params) # wait for prefetched chunks, filter those are not prefetched - unique_chunks = set(all_chunks) + set(all_chunks) chunks_fetch_sync = self._gemini_manager.wait_chunks(all_chunks) # transfer state @@ -48,7 +46,9 @@ class GeminiZeROHook(ColoParamOpHook): self._gemini_manager.sample_overall_data() # evit chunks, aware of async fetched - self._gemini_manager.adjust_layout(all_chunks, record_anyway=self._gemini_manager.placement_policy.max_prefetch > 0) + self._gemini_manager.adjust_layout( + all_chunks, record_anyway=self._gemini_manager.placement_policy.max_prefetch > 0 + ) # fetch the rest synchronously for chunk in chunks_fetch_sync: @@ -57,7 +57,9 @@ class GeminiZeROHook(ColoParamOpHook): # get possible chunks to prefetch chunks_fetch_async = self._gemini_manager.placement_policy.get_prefetch_chunks() if rank == 0 and not self._gemini_manager.is_warmup(): - print(f"compute_id: {self._gemini_manager.compute_idx} self._gemini_manager.compute_list: {self._gemini_manager.compute_list}") + print( + f"compute_id: {self._gemini_manager.compute_idx} self._gemini_manager.compute_list: {self._gemini_manager.compute_list}" + ) print(f"{all_chunks=}") print(f"accessed_chunks={self._chunk_manager.accessed_chunks}") print(f"{chunks_fetch_sync=}") diff --git a/colossalai/zero/gemini/gemini_mgr.py b/colossalai/zero/gemini/gemini_mgr.py index 6640bf03b..11bde789c 100644 --- a/colossalai/zero/gemini/gemini_mgr.py +++ b/colossalai/zero/gemini/gemini_mgr.py @@ -1,6 +1,6 @@ import functools from time import time -from typing import Dict, List, Optional, Tuple, Iterable +from typing import Dict, Iterable, List, Optional, Tuple import torch import torch.distributed as dist @@ -101,7 +101,7 @@ class GeminiManager: start = time() self._record_warmup_chunks_order(chunks, record_anyway=record_anyway) cuda_demand, can_evict_chunks = self._get_layout_info(self._compute_idx, self._warmup, chunks) - # don't evict chunks that are asynchronously fetched + # don't evict chunks that are asynchronously fetched can_evict_chunks = [chunk for chunk in can_evict_chunks if chunk not in self._async_works] self._layout_time += time() - start diff --git a/colossalai/zero/gemini/placement_policy.py b/colossalai/zero/gemini/placement_policy.py index aad97321c..e5f61a033 100644 --- a/colossalai/zero/gemini/placement_policy.py +++ b/colossalai/zero/gemini/placement_policy.py @@ -13,11 +13,17 @@ from colossalai.zero.gemini.chunk import Chunk from .chunk import Chunk, ChunkManager from .memory_tracer import ChunkMemStatsCollector + class PlacementPolicy(ABC): need_mem_stats: bool = False def __init__( - self, gemini_manager: 'GeminiManager', chunk_manager: ChunkManager, mem_stats_collector: Optional[ChunkMemStatsCollector] = None, max_prefetch:int = 0, **kwargs + self, + gemini_manager: "GeminiManager", + chunk_manager: ChunkManager, + mem_stats_collector: Optional[ChunkMemStatsCollector] = None, + max_prefetch: int = 0, + **kwargs, ) -> None: self.gemini_manager = gemini_manager self.chunk_manager = chunk_manager @@ -38,13 +44,16 @@ class PlacementPolicy(ABC): def get_prefetch_chunks(self) -> List[Chunk]: raise NotImplementedError + import os + rank = int(os.environ["RANK"]) + class StaticPlacementPolicy(PlacementPolicy): def __init__( self, - gemini_manager: 'GeminiManager', + gemini_manager: "GeminiManager", chunk_manager: ChunkManager, mem_stats_collector: Optional[ChunkMemStatsCollector] = None, max_prefetch: int = 0, @@ -53,7 +62,9 @@ class StaticPlacementPolicy(PlacementPolicy): offload_param_frac: float = 0.0, **kwargs, ) -> None: - super().__init__(gemini_manager, chunk_manager, mem_stats_collector=mem_stats_collector, max_prefetch=max_prefetch) + super().__init__( + gemini_manager, chunk_manager, mem_stats_collector=mem_stats_collector, max_prefetch=max_prefetch + ) if offload_param_frac > 0.0 and (shard_param_frac != 1.0 or offload_optim_frac != 1.0): warnings.warn("offload_param_frac is ignored when shard_param_frac != 1.0 or offload_optim_frac != 1.0") offload_param_frac = 0.0 @@ -124,7 +135,7 @@ class AutoPlacementPolicy(PlacementPolicy): def __init__( self, - gemini_manager: 'GeminiManager', + gemini_manager: "GeminiManager", chunk_manager: ChunkManager, mem_stats_collector: Optional[ChunkMemStatsCollector] = None, max_prefetch: int = 0, @@ -132,7 +143,9 @@ class AutoPlacementPolicy(PlacementPolicy): steady_cuda_cap_ratio: float = 0.9, **kwargs, ) -> None: - super().__init__(gemini_manager, chunk_manager, mem_stats_collector=mem_stats_collector, max_prefetch=max_prefetch) + super().__init__( + gemini_manager, chunk_manager, mem_stats_collector=mem_stats_collector, max_prefetch=max_prefetch + ) # model data will use 1-_warmup_non_model_data_ratio CUDA memory in warmup phase # you can set them by AutoPlacementPolicy.set_warmup_non_model_data_ratio() # and AutoPlacementPolicy.set_steady_cuda_cap_ratio() From 5470e5f94e302b1a60ee2c1add0caf5f0e879e42 Mon Sep 17 00:00:00 2001 From: genghaozhe <939857490@qq.com> Date: Thu, 16 May 2024 08:03:40 +0000 Subject: [PATCH 07/12] a commit for fake push test --- tests/test_zero/test_gemini/test_optim.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/tests/test_zero/test_gemini/test_optim.py b/tests/test_zero/test_gemini/test_optim.py index a9366e7bc..1c914ca0e 100644 --- a/tests/test_zero/test_gemini/test_optim.py +++ b/tests/test_zero/test_gemini/test_optim.py @@ -40,9 +40,7 @@ EXAMPLE_MODELS = [ ] # bfloat16 cannot represent them exactly -BF16_IGNORED_KEYS = [ - "masked_bias", -] +BF16_IGNORED_KEYS = ["masked_bias"] def check_param(model: GeminiDDP, torch_model: torch.nn.Module, dtype: torch.dtype): From f45f8a2aa74e6734f0f7ad89729d7e00b5d3d985 Mon Sep 17 00:00:00 2001 From: hxwang Date: Thu, 16 May 2024 16:12:53 +0800 Subject: [PATCH 08/12] [gemini] maxprefetch means maximum work to keep --- colossalai/zero/gemini/placement_policy.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/colossalai/zero/gemini/placement_policy.py b/colossalai/zero/gemini/placement_policy.py index e5f61a033..c0f92fa50 100644 --- a/colossalai/zero/gemini/placement_policy.py +++ b/colossalai/zero/gemini/placement_policy.py @@ -118,14 +118,15 @@ class StaticPlacementPolicy(PlacementPolicy): def get_prefetch_chunks(self) -> List[Chunk]: if self.gemini_manager.is_warmup(): # no prefetch during warmup since we need compute_list return [] + can_prefetch = self.max_prefetch - len(self.gemini_manager._async_works) prefetch = [] for i in range(self.gemini_manager.compute_idx + 1, len(self.gemini_manager.compute_list)): for chunk in self.gemini_manager.compute_list[i]: - if len(prefetch) >= self.max_prefetch: + if len(prefetch) >= can_prefetch: break if chunk not in prefetch and chunk not in self.chunk_manager.accessed_chunks: prefetch.append(chunk) - if len(prefetch) >= self.max_prefetch: + if len(prefetch) >= can_prefetch: break return prefetch From 20701d45330df8bd2eed3a803f58b67a990e5ece Mon Sep 17 00:00:00 2001 From: hxwang Date: Thu, 16 May 2024 16:45:50 +0800 Subject: [PATCH 09/12] [chore] remove print --- colossalai/zero/gemini/gemini_hook.py | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) diff --git a/colossalai/zero/gemini/gemini_hook.py b/colossalai/zero/gemini/gemini_hook.py index e6b8cf8ef..d1fd0867f 100644 --- a/colossalai/zero/gemini/gemini_hook.py +++ b/colossalai/zero/gemini/gemini_hook.py @@ -19,10 +19,6 @@ class TrainingPhase(Enum): logger = DistributedLogger("gemini_hook") -import os - -rank = int(os.environ["RANK"]) - class GeminiZeROHook(ColoParamOpHook): def __init__(self, gemini_manager: GeminiManager) -> None: @@ -56,23 +52,13 @@ class GeminiZeROHook(ColoParamOpHook): # get possible chunks to prefetch chunks_fetch_async = self._gemini_manager.placement_policy.get_prefetch_chunks() - if rank == 0 and not self._gemini_manager.is_warmup(): - print( - f"compute_id: {self._gemini_manager.compute_idx} self._gemini_manager.compute_list: {self._gemini_manager.compute_list}" - ) - print(f"{all_chunks=}") - print(f"accessed_chunks={self._chunk_manager.accessed_chunks}") - print(f"{chunks_fetch_sync=}") - print(f"{chunks_fetch_async=}") - print(f"works={list(self._gemini_manager._async_works.keys())}") # prefetch for chunk in chunks_fetch_async: maybe_work = self._chunk_manager.access_chunk(chunk, async_access=True) if maybe_work is not None: self._gemini_manager.add_work(chunk, maybe_work) - if rank == 0 and not self._gemini_manager.is_warmup(): - print(f"post accessed_chunks={self._chunk_manager.accessed_chunks}") + # record cuda model data of the current OP, including memory for prefetched chunks self._gemini_manager.record_model_data_volume() From 6efbadba25d6192ed1b54f3d50491a8b91aacc77 Mon Sep 17 00:00:00 2001 From: hxwang Date: Thu, 16 May 2024 16:46:39 +0800 Subject: [PATCH 10/12] [chore] remove debugging info --- colossalai/zero/gemini/chunk/chunk.py | 1 - 1 file changed, 1 deletion(-) diff --git a/colossalai/zero/gemini/chunk/chunk.py b/colossalai/zero/gemini/chunk/chunk.py index 81b6192ad..299ea0518 100644 --- a/colossalai/zero/gemini/chunk/chunk.py +++ b/colossalai/zero/gemini/chunk/chunk.py @@ -567,7 +567,6 @@ class Chunk: return self is __o def __repr__(self, detailed: bool = True): - return f"Chunk({self.count_id})" output = [ "Chunk Information:\n", "\tchunk size: {}, chunk dtype: {}, process group size: {}\n".format( From 013690a86b6906d0b3eaa11173a9510856be09b3 Mon Sep 17 00:00:00 2001 From: genghaozhe <939857490@qq.com> Date: Thu, 16 May 2024 09:57:51 +0000 Subject: [PATCH 11/12] remove set(all_chunks) --- colossalai/zero/gemini/gemini_hook.py | 1 - 1 file changed, 1 deletion(-) diff --git a/colossalai/zero/gemini/gemini_hook.py b/colossalai/zero/gemini/gemini_hook.py index d1fd0867f..27a19c132 100644 --- a/colossalai/zero/gemini/gemini_hook.py +++ b/colossalai/zero/gemini/gemini_hook.py @@ -33,7 +33,6 @@ class GeminiZeROHook(ColoParamOpHook): all_chunks = self._chunk_manager.get_chunks(params) # wait for prefetched chunks, filter those are not prefetched - set(all_chunks) chunks_fetch_sync = self._gemini_manager.wait_chunks(all_chunks) # transfer state From e57812c6727e325971cb0d8769c0789c088f62ae Mon Sep 17 00:00:00 2001 From: botbw Date: Fri, 17 May 2024 13:42:18 +0800 Subject: [PATCH 12/12] [chore] Update placement_policy.py --- colossalai/zero/gemini/placement_policy.py | 5 ----- 1 file changed, 5 deletions(-) diff --git a/colossalai/zero/gemini/placement_policy.py b/colossalai/zero/gemini/placement_policy.py index c0f92fa50..e9e871b46 100644 --- a/colossalai/zero/gemini/placement_policy.py +++ b/colossalai/zero/gemini/placement_policy.py @@ -45,11 +45,6 @@ class PlacementPolicy(ABC): raise NotImplementedError -import os - -rank = int(os.environ["RANK"]) - - class StaticPlacementPolicy(PlacementPolicy): def __init__( self,