fbgemm_fp8.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. # Copyright 2024 The HuggingFace Team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from ..activations import ACT2FN
  15. from ..utils import is_accelerate_available, is_fbgemm_gpu_available, is_torch_available, logging
  16. if is_torch_available():
  17. import torch
  18. from torch import nn
  19. if is_accelerate_available():
  20. from accelerate import init_empty_weights
  21. if is_fbgemm_gpu_available():
  22. import fbgemm_gpu.experimental.gen_ai # noqa: F401
  23. logger = logging.get_logger(__name__)
  24. class FbgemmFp8Linear(torch.nn.Linear):
  25. def __init__(self, in_features, out_features, bias, weight_dtype=torch.float32):
  26. super().__init__(in_features, out_features, bias)
  27. self.in_features = in_features
  28. self.out_features = out_features
  29. self.weight = torch.nn.Parameter(torch.zeros((out_features, in_features), dtype=torch.float8_e4m3fn))
  30. self.weight_scale = torch.nn.Parameter(torch.zeros((out_features, 1), dtype=weight_dtype))
  31. self.register_buffer("input_scale_ub", torch.zeros([1], dtype=torch.float), persistent=False)
  32. if bias:
  33. self.bias = torch.nn.Parameter(torch.zeros((self.out_features), dtype=weight_dtype))
  34. else:
  35. self.bias = None
  36. def forward(self, x):
  37. # quantize_fp8_per_row will squash the leading dimensions, so save the desired shape here
  38. output_shape = (*x.shape[:-1], -1)
  39. # x_quantized and x_scale are not necessarily on the same device as x, this is an issue.
  40. # https://github.com/pytorch/FBGEMM/blob/e08af8539c391437f447173863df0f3f6f6f1855/fbgemm_gpu/experimental/gen_ai/src/quantize/quantize.cu#L1237C3-L1237C45
  41. x_quantized, x_scale = torch.ops.fbgemm.quantize_fp8_per_row(
  42. x.view(-1, x.shape[-1]).contiguous(), scale_ub=self.input_scale_ub
  43. )
  44. # moving x_quantized, x_scale here creates glibberish output ... However, if we move the output, it works
  45. # x_quantized, x_scale = x_quantized.to(x.device), x_scale.to(x.device)
  46. # The computation still happens on the device where self.weight is even if x_quantized is not on the same device as self.weight
  47. weight_scale_float32 = self.weight_scale.to(torch.float32)
  48. output = torch.ops.fbgemm.f8f8bf16_rowwise(
  49. x_quantized, self.weight, x_scale, weight_scale_float32, use_fast_accum=True
  50. )
  51. output = output + self.bias if self.bias is not None else output
  52. # Hacky for now, we have the output to the device of x
  53. output = output.to(x.device)
  54. output = output.reshape(output_shape)
  55. del x_quantized, x_scale
  56. return output
  57. class FbgemmFp8Llama4TextExperts(nn.Module):
  58. def __init__(self, config, dtype=torch.float32):
  59. super().__init__()
  60. self.num_experts = config.num_local_experts
  61. self.intermediate_size = config.intermediate_size
  62. self.hidden_size = config.hidden_size
  63. self.expert_dim = self.intermediate_size
  64. self.act_fn = ACT2FN[config.hidden_act]
  65. # Register FP8 buffers for gate_up_proj
  66. self.gate_up_proj = torch.nn.Parameter(
  67. torch.zeros((self.num_experts, self.hidden_size, 2 * self.expert_dim), dtype=torch.float8_e4m3fn)
  68. )
  69. self.gate_up_proj_scale = torch.nn.Parameter(
  70. torch.zeros((self.num_experts, 1, self.expert_dim * 2), dtype=torch.float32)
  71. )
  72. # Register FP8 buffers for down_proj
  73. self.down_proj = torch.nn.Parameter(
  74. torch.zeros((self.num_experts, self.expert_dim, self.hidden_size), dtype=torch.float8_e4m3fn)
  75. )
  76. self.down_proj_scale = torch.nn.Parameter(
  77. torch.zeros((self.num_experts, self.hidden_size, 1), dtype=torch.float32)
  78. )
  79. # Register input scale upper bound
  80. self.register_buffer("input_scale_ub", torch.zeros([1], dtype=torch.float), persistent=False)
  81. def forward(self, hidden_states):
  82. """
  83. Args:
  84. hidden_states (torch.Tensor): (batch_size * token_num, hidden_size)
  85. Returns:
  86. torch.Tensor: (batch_size * token_num, hidden_size)
  87. """
  88. # Reshape hidden states for expert computation
  89. hidden_states = hidden_states.view(self.num_experts, -1, self.hidden_size)
  90. num_tokens = None
  91. # Pre-allocate tensor for all expert outputs with same shape as hidden_states
  92. next_states = torch.empty_like(hidden_states)
  93. for i in range(self.num_experts):
  94. # Extract expert's hidden states
  95. expert_hidden = hidden_states[i]
  96. expert_hidden_reshaped = expert_hidden.reshape(-1, self.hidden_size)
  97. # Quantize for this expert
  98. expert_quantized, expert_scale = torch.ops.fbgemm.quantize_fp8_per_row(
  99. expert_hidden_reshaped, num_tokens, self.input_scale_ub
  100. )
  101. sharded_expert_dim = self.gate_up_proj.shape[-1] // 2
  102. gate_up_proj_scale_float32 = self.gate_up_proj_scale.to(torch.float32)
  103. gate = torch.ops.fbgemm.f8f8bf16_rowwise(
  104. expert_quantized,
  105. self.gate_up_proj[i].transpose(0, 1)[:sharded_expert_dim].contiguous(),
  106. expert_scale,
  107. gate_up_proj_scale_float32[i][0][:sharded_expert_dim].view(-1, 1).contiguous(),
  108. use_fast_accum=True,
  109. )
  110. up = torch.ops.fbgemm.f8f8bf16_rowwise(
  111. expert_quantized,
  112. self.gate_up_proj[i].transpose(0, 1)[sharded_expert_dim:].contiguous(),
  113. expert_scale,
  114. gate_up_proj_scale_float32[i][0][sharded_expert_dim:].view(-1, 1).contiguous(),
  115. use_fast_accum=True,
  116. )
  117. activated = up * self.act_fn(gate)
  118. activated_quantized, activated_scale = torch.ops.fbgemm.quantize_fp8_per_row(
  119. activated, num_tokens, self.input_scale_ub
  120. )
  121. down_proj_scale_float32 = self.down_proj_scale.to(torch.float32)
  122. expert_output = torch.ops.fbgemm.f8f8bf16_rowwise(
  123. activated_quantized,
  124. self.down_proj[i].transpose(0, 1).contiguous(),
  125. activated_scale,
  126. down_proj_scale_float32[i].view(-1, 1).contiguous(),
  127. use_fast_accum=True,
  128. )
  129. next_states[i] = expert_output
  130. next_states = next_states.to(hidden_states.device)
  131. return next_states.view(-1, self.hidden_size)
  132. def _replace_with_fbgemm_fp8_linear(
  133. model,
  134. modules_to_not_convert=None,
  135. current_key_name=None,
  136. quantization_config=None,
  137. has_been_replaced=False,
  138. pre_quantized=False,
  139. config=None,
  140. tp_plan=None,
  141. ):
  142. """
  143. Private method that wraps the recursion for module replacement.
  144. Returns the converted model and a boolean that indicates if the conversion has been successful or not.
  145. """
  146. import re
  147. if current_key_name is None:
  148. current_key_name = []
  149. for name, module in model.named_children():
  150. current_key_name.append(name)
  151. if (isinstance(module, nn.Linear)) and name not in modules_to_not_convert:
  152. # Check if the current key is not in the `modules_to_not_convert`
  153. current_key_name_str = ".".join(current_key_name)
  154. if not any(
  155. (key + "." in current_key_name_str) or (key == current_key_name_str) for key in modules_to_not_convert
  156. ):
  157. with init_empty_weights(include_buffers=True):
  158. in_features = module.in_features
  159. out_features = module.out_features
  160. model._modules[name] = FbgemmFp8Linear(
  161. in_features,
  162. out_features,
  163. module.bias is not None,
  164. )
  165. has_been_replaced = True
  166. # Force requires grad to False to avoid unexpected errors
  167. model._modules[name].requires_grad_(False)
  168. # set non persistent buffer outside of init_empty_weights
  169. model._modules[name].input_scale_ub = torch.tensor(
  170. [quantization_config.activation_scale_ub],
  171. dtype=torch.float,
  172. )
  173. if module.__class__.__name__ == "Llama4TextExperts" and name not in modules_to_not_convert:
  174. current_key_name_str = ".".join(current_key_name)
  175. if not any(
  176. (key + "." in current_key_name_str) or (key == current_key_name_str) for key in modules_to_not_convert
  177. ):
  178. with init_empty_weights(include_buffers=True):
  179. tp_plan[re.sub(r"\d+", "*", current_key_name_str + ".down_proj_scale")] = None
  180. model._modules[name] = FbgemmFp8Llama4TextExperts(
  181. config.text_config,
  182. )
  183. model._modules[name].input_scale_ub = torch.tensor(
  184. [quantization_config.activation_scale_ub], dtype=torch.float
  185. )
  186. if len(list(module.children())) > 0:
  187. _, has_been_replaced = _replace_with_fbgemm_fp8_linear(
  188. module,
  189. modules_to_not_convert,
  190. current_key_name,
  191. quantization_config,
  192. has_been_replaced=has_been_replaced,
  193. pre_quantized=pre_quantized,
  194. config=config,
  195. tp_plan=tp_plan,
  196. )
  197. # Remove the last key for recursion
  198. current_key_name.pop(-1)
  199. return model, has_been_replaced
  200. def replace_with_fbgemm_fp8_linear(
  201. model,
  202. modules_to_not_convert=None,
  203. current_key_name=None,
  204. quantization_config=None,
  205. pre_quantized=False,
  206. config=None,
  207. tp_plan=None,
  208. ):
  209. """
  210. A helper function to replace all `torch.nn.Linear` modules by `FbgemmFp8Linear` modules.
  211. This will enable running your models using high performance fp8 kernel from FBGEMM library.
  212. The function will be run recursively and replace all `torch.nn.Linear` modules except for the `lm_head` that should
  213. be kept as a `torch.nn.Linear` module. The replacement is done under `init_empty_weights` context manager so no
  214. CPU/GPU memory is required to run this function. Each weight will be quantized along the channel.
  215. Parameters:
  216. model (`torch.nn.Module`):
  217. Input model or `torch.nn.Module` as the function is run recursively.
  218. modules_to_not_convert (`list[`str`]`, *optional*, defaults to `["lm_head"]`):
  219. Names of the modules to not convert in `FP8Linear`. In practice we keep the `lm_head` in full precision
  220. for numerical stability reasons.
  221. current_key_name (`list[`str`]`, *optional*):
  222. An array to track the current key of the recursion. This is used to check whether the current key (part of
  223. it) is not in the list of modules to not convert (for instances modules that are offloaded to `cpu` or
  224. `disk`).
  225. """
  226. modules_to_not_convert = ["lm_head"] if modules_to_not_convert is None else modules_to_not_convert
  227. if quantization_config.modules_to_not_convert is not None:
  228. modules_to_not_convert.extend(quantization_config.modules_to_not_convert)
  229. modules_to_not_convert = list(set(modules_to_not_convert))
  230. model, has_been_replaced = _replace_with_fbgemm_fp8_linear(
  231. model,
  232. modules_to_not_convert,
  233. current_key_name,
  234. quantization_config,
  235. pre_quantized=pre_quantized,
  236. config=config,
  237. tp_plan=tp_plan,
  238. )
  239. if not has_been_replaced:
  240. logger.warning(
  241. "You are loading your model using FP8 quantization but no linear modules were found in your model."
  242. " Please double check your model architecture, or submit an issue on github if you think this is"
  243. " a bug."
  244. )
  245. return model