|
1 | 1 | import re |
2 | 2 | import os |
3 | | -import json |
4 | 3 | import torch |
5 | 4 | import torch.distributed as dist |
6 | 5 | from typing import List, Union |
|
13 | 12 | from lightllm.utils.envs_utils import get_unique_server_name, get_env_start_args |
14 | 13 | from lightllm.distributed.pynccl import PyNcclCommunicator |
15 | 14 | from lightllm.utils.dist_utils import get_current_device_id |
16 | | -from lightllm.utils.envs_utils import get_kv_quant_calibration_inference_count |
17 | | -from lightllm.utils.envs_utils import get_kv_quant_calibration_warmup_count |
18 | | -from lightllm.utils.dist_utils import get_global_rank |
19 | | -from lightllm.utils.config_utils import get_model_architectures |
20 | 15 |
|
21 | 16 | logger = init_logger(__name__) |
22 | 17 |
|
23 | 18 |
|
24 | | -class OfflineFP8QuantManager: |
25 | | - def __init__(self, layer_num, head_num): |
26 | | - self.qmin = torch.finfo(torch.float8_e4m3fn).min |
27 | | - self.qmax = torch.finfo(torch.float8_e4m3fn).max |
28 | | - self.model_arch = get_model_architectures(get_env_start_args().model_dir) |
29 | | - self.layer_num = layer_num |
30 | | - self.head_num = head_num |
31 | | - self.total_head_num = head_num * dist.get_world_size() if dist.is_initialized() else head_num |
32 | | - self.scales_shape = [layer_num, 2 * head_num] if get_env_start_args().enable_fa3 else [layer_num, 2] |
33 | | - self.scales = None |
34 | | - self.scales_list = [] |
35 | | - self.abs_max = None |
36 | | - self.warmup_counts = get_kv_quant_calibration_warmup_count() |
37 | | - self.inference_counts = get_kv_quant_calibration_inference_count() |
38 | | - self.count = 0 |
39 | | - self.enable_calib = False |
40 | | - if get_env_start_args().export_kv_quant_calibration: |
41 | | - self.abs_max = torch.zeros(self.scales_shape, dtype=torch.float32, device="cuda") |
42 | | - elif get_env_start_args().kv_quant_calibration_config_path is not None: |
43 | | - logger.info( |
44 | | - f"kv_quant_calibration_config_path {get_env_start_args().kv_quant_calibration_config_path} is set, " |
45 | | - "will load kv quant calibration config" |
46 | | - ) |
47 | | - if os.path.exists(get_env_start_args().kv_quant_calibration_config_path): |
48 | | - with open(get_env_start_args().kv_quant_calibration_config_path, "r") as f: |
49 | | - cfg = json.load(f) |
50 | | - |
51 | | - if cfg["architectures"] != self.model_arch: |
52 | | - raise ValueError( |
53 | | - f"architectures {cfg['architectures']} in config " |
54 | | - f"not match current model_arch {self.model_arch}" |
55 | | - ) |
56 | | - if cfg["num_layers"] != layer_num: |
57 | | - raise ValueError( |
58 | | - f"num_layers {cfg['num_layers']} in config " f"not match current layer_num {layer_num}" |
59 | | - ) |
60 | | - if cfg["num_head"] != self.total_head_num: |
61 | | - raise ValueError( |
62 | | - f"num_head {cfg['num_head']} in config " |
63 | | - f"not match current model head num {self.total_head_num}" |
64 | | - ) |
65 | | - if get_env_start_args().enable_fa3: |
66 | | - if cfg["quant_type"] != "per_head": |
67 | | - raise ValueError(f"quant type {cfg['num_head']} in config not match fa3 backend") |
68 | | - else: |
69 | | - if cfg["quant_type"] != "per_tensor": |
70 | | - raise ValueError(f"quant type {cfg['quant_type']} in config not match flashinfer backend") |
71 | | - |
72 | | - self.qmin = cfg["qmin"] |
73 | | - self.qmax = cfg["qmax"] |
74 | | - self.scales_shape = cfg["scales_shape"] |
75 | | - |
76 | | - full_scales_list = cfg["scales"] |
77 | | - self.scales_list = full_scales_list |
78 | | - self.scales = torch.tensor(self.scales_list, dtype=torch.float32, device="cuda").view(self.scales_shape) |
79 | | - if not get_env_start_args().enable_fa3: |
80 | | - self.scales = torch.repeat_interleave(self.scales, self.head_num, dim=-1) |
81 | | - if get_env_start_args().enable_fa3 and dist.is_initialized() and dist.get_world_size() > 1: |
82 | | - half_head = self.total_head_num // 2 |
83 | | - start_head = dist.get_rank() * head_num |
84 | | - end_head = start_head + head_num |
85 | | - k_scales = self.scales[:, start_head:end_head].contiguous() |
86 | | - v_scales = self.scales[:, start_head + half_head : end_head + half_head].contiguous() |
87 | | - current_scales = torch.cat((k_scales, v_scales), dim=-1) |
88 | | - |
89 | | - self.scales_list = current_scales.tolist() |
90 | | - self.scales = current_scales |
91 | | - else: |
92 | | - raise FileNotFoundError( |
93 | | - f"kv_quant_calibration_config {get_env_start_args().kv_quant_calibration_config_path} not found" |
94 | | - ) |
95 | | - elif "calibration_fp8kv" in get_env_start_args().mode: |
96 | | - logger.warning("scales is None, no kv_quant_calibration_config_path be set") |
97 | | - |
98 | | - def enable_calibration(self): |
99 | | - assert get_env_start_args().disable_cudagraph, "Calibration is not supported in cudagraph mode" |
100 | | - logger.info("Enable kv cache calibration, will collect kv cache data for quantization calibration") |
101 | | - self.enable_calib = True |
102 | | - |
103 | | - def update_calibration_data(self, kv_buffer: torch.Tensor, layer_index: int): |
104 | | - if not self.enable_calib or self.count >= self.warmup_counts + self.inference_counts: |
105 | | - return |
106 | | - |
107 | | - if self.abs_max is not None and self.count >= self.warmup_counts: |
108 | | - if get_env_start_args().enable_fa3: |
109 | | - kv_max = kv_buffer.abs().amax(dim=(0, 2)).to(torch.float32) |
110 | | - else: |
111 | | - k_max = kv_buffer[:, : self.head_num, :].abs().amax(dim=()).to(torch.float32) |
112 | | - v_max = kv_buffer[:, self.head_num :, :].abs().amax(dim=()).to(torch.float32) |
113 | | - kv_max = torch.tensor([k_max, v_max], device="cuda", dtype=torch.float32) |
114 | | - self.abs_max[layer_index] = torch.maximum(self.abs_max[layer_index], kv_max) |
115 | | - if self.count == self.warmup_counts + self.inference_counts - 1 and layer_index == self.layer_num - 1: |
116 | | - final_abs_max = self.abs_max |
117 | | - if dist.is_initialized() and dist.get_world_size() > 1: |
118 | | - if get_env_start_args().enable_fa3: |
119 | | - k_max, v_max = torch.chunk(self.abs_max, 2, dim=-1) |
120 | | - k_max = k_max.contiguous() |
121 | | - v_max = v_max.contiguous() |
122 | | - gathered_k_max = [torch.zeros_like(k_max) for _ in range(dist.get_world_size())] |
123 | | - gathered_v_max = [torch.zeros_like(v_max) for _ in range(dist.get_world_size())] |
124 | | - dist.all_gather(gathered_k_max, k_max, group=None, async_op=False) |
125 | | - dist.all_gather(gathered_v_max, v_max, group=None, async_op=False) |
126 | | - k_max = torch.cat(gathered_k_max, dim=-1) |
127 | | - v_max = torch.cat(gathered_v_max, dim=-1) |
128 | | - final_abs_max = torch.cat((k_max, v_max), dim=-1) |
129 | | - else: |
130 | | - dist.all_reduce(self.abs_max, op=dist.ReduceOp.MAX, group=None, async_op=False) |
131 | | - |
132 | | - self.scales = final_abs_max / self.qmax |
133 | | - self.scales = torch.where(self.scales > 0, self.scales, torch.ones_like(self.scales)) |
134 | | - |
135 | | - if get_global_rank() == 0: |
136 | | - self.abs_max = final_abs_max |
137 | | - self._export_calibration_data() |
138 | | - |
139 | | - if layer_index == self.layer_num - 1: |
140 | | - self.count += 1 |
141 | | - |
142 | | - def _export_calibration_data(self): |
143 | | - cfg = { |
144 | | - "version": "1.0", |
145 | | - "architectures": self.model_arch, |
146 | | - "quant_type": "per_head" if get_env_start_args().enable_fa3 else "per_tensor", |
147 | | - "qmin": self.qmin, |
148 | | - "qmax": self.qmax, |
149 | | - "num_layers": self.layer_num, |
150 | | - "num_head": self.total_head_num, |
151 | | - "scales_shape": list(self.abs_max.shape), |
152 | | - "scales": self.scales.cpu().numpy().tolist(), |
153 | | - } |
154 | | - with open("./kv_cache_calib.json", "w") as f: |
155 | | - json.dump(cfg, f, indent=4) |
156 | | - logger.info( |
157 | | - f"Export kv cache calibration data to kv_cache_calib.json, " |
158 | | - f"architectures: {self.model_arch}, " |
159 | | - f"qmin: {self.qmin}, qmax: {self.qmax}, " |
160 | | - f"total heads: {self.total_head_num}, " |
161 | | - f"scales_shape: {list(self.abs_max.shape)}, " |
162 | | - ) |
163 | | - |
164 | | - |
165 | 19 | class MemoryManager: |
166 | 20 | def __init__(self, size, dtype, head_num, head_dim, layer_num, always_copy=False, mem_fraction=0.9): |
167 | 21 | self.size = size |
@@ -198,7 +52,6 @@ def __init__(self, size, dtype, head_num, head_dim, layer_num, always_copy=False |
198 | 52 | layer_num, |
199 | 53 | ) |
200 | 54 | self.HOLD_TOKEN_MEMINDEX = self.size |
201 | | - self.offline_fp8_quant_manager = OfflineFP8QuantManager(layer_num, head_num) |
202 | 55 |
|
203 | 56 | def get_cell_size(self): |
204 | 57 | return 2 * self.head_num * self.head_dim * self.layer_num * torch._utils._element_size(self.dtype) |
|
0 commit comments