MCPcopy Create free account
hub / github.com/CERT-Lab/lora-sb / OffloadContext

Class OffloadContext

utils/offload_utils_for_quant/context.py:8–61  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

6
7
8class OffloadContext:
9 def __init__(
10 self,
11 model: torch.nn.Module,
12 named_grads: dict,
13 quant_flag: bool = False,
14 origin_type: str = "bf16",
15 quant_type: str = "int8",
16 no_split_module_classes=None,
17 enable_gradient_offload=True,
18 ):
19 """Offload part of model to cpu.
20
21 Args:
22 model (torch.nn.Module): Model to be offloaded
23 named_grads (dict): Contains the name and gradient of the corresponding module.
24 quant_flag (bool, optional): Whether to quantize the model. Defaults to False.
25 origin_type (str, optional): Origin dtype of model. Defaults to "bf16".
26 quant_type (str, optional): Quantizaion dtype. Defaults to "int8".
27 no_split_module_classes (_type_, optional): no_split_module_classes is an option you can set to ensure that
28 certain classes of modules are not split during the offload process. Defaults to None.
29 enable_gradient_offload (bool, optional): Whether to use this context. Defaults to True.
30 """
31 if no_split_module_classes is None:
32 no_split_module_classes = [
33 "LlamaDecoderLayer", "GPT2TransformerBlock", "T5Block", "GPT2Block", "FlaxGPT2Block",
34 ]
35 num_split_block = get_split_num(origin_type=origin_type, quant_type=quant_type)
36 if quant_flag:
37 print(f"model will be split into {num_split_block} blocks")
38
39 self.modelOffloadHookContext = ModelOffloadHookContext(
40 model=model,
41 no_split_module_classes=no_split_module_classes,
42 num_block=num_split_block,
43 enable=quant_flag,
44 # =========================
45 device="cuda",
46 strategy="block",
47 with_backward_hook=False
48 )
49 self.gradientOffloadHookContext = GradientOffloadHookContext(
50 model=model,
51 enable=enable_gradient_offload,
52 record_dict=named_grads,
53 )
54
55 def __enter__(self):
56 self.modelOffloadHookContext.__enter__()
57 self.gradientOffloadHookContext.__enter__()
58
59 def __exit__(self, exc_type, exc_val, exc_tb):
60 self.modelOffloadHookContext.__exit__(exc_type, exc_val, exc_tb)
61 self.gradientOffloadHookContext.__exit__(exc_type, exc_val, exc_tb)

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected