bitnet.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. from ..utils import is_accelerate_available, is_torch_available, logging
  2. if is_accelerate_available():
  3. from accelerate import init_empty_weights
  4. if is_torch_available():
  5. import torch
  6. import torch.nn as nn
  7. import torch.nn.functional as F
  8. logger = logging.get_logger(__name__)
  9. # the weights are ternary so can be represented with 2 bits, and they are packed in uint8 tensors, hence the number of values per item is 4
  10. VALUES_PER_ITEM = 4
  11. def pack_weights(quantized_weights: torch.Tensor) -> torch.Tensor:
  12. """
  13. Packs a tensor of quantized weights into a compact format using 2 bits per value.
  14. Parameters:
  15. -----------
  16. quantized_weights : torch.Tensor
  17. A tensor containing ternary quantized weights with values in {-1, 0, 1}. These values are adjusted to
  18. {0, 1, 2} before being packed.
  19. Returns:
  20. --------
  21. torch.Tensor
  22. A packed tensor where each element stores 4 quantized values (each using 2 bits) in an 8-bit format.
  23. """
  24. original_shape = quantized_weights.shape
  25. row_dim = (original_shape[0] + VALUES_PER_ITEM - 1) // VALUES_PER_ITEM
  26. if len(original_shape) == 1:
  27. packed_tensor_shape = (row_dim,)
  28. else:
  29. packed_tensor_shape = (row_dim, *original_shape[1:])
  30. quantized_weights += 1
  31. packed = torch.zeros(packed_tensor_shape, device=quantized_weights.device, dtype=torch.uint8)
  32. unpacked = quantized_weights.to(torch.uint8)
  33. it = min(VALUES_PER_ITEM, (original_shape[0] // row_dim) + 1)
  34. for i in range(it):
  35. start = i * row_dim
  36. end = min(start + row_dim, original_shape[0])
  37. packed[: (end - start)] |= unpacked[start:end] << 2 * i
  38. return packed
  39. @torch.compile
  40. def unpack_weights(packed: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
  41. """
  42. Unpacks a tensor of quantized weights that were stored in a packed format using 2 bits per value.
  43. Parameters:
  44. -----------
  45. packed : torch.Tensor
  46. A tensor containing packed weights where each element represents 4 quantized values (using 2 bits per value).
  47. dtype : torch.dtype
  48. The dtype of the returned Tensor
  49. Returns:
  50. --------
  51. torch.Tensor
  52. A tensor of unpacked weights, where each value is converted from its packed 2-bit representation.
  53. Example:
  54. --------
  55. packed = torch.tensor([[0b10100001, 0b00011000],
  56. [0b10010000, 0b00001010]], dtype=torch.uint8)
  57. # Unpack the values
  58. unpacked = unpack_weights(packed)
  59. # Resulting unpacked tensor
  60. print(unpacked)
  61. # Output: tensor([[ 0, -1],
  62. [-1, 1],
  63. [-1, 1],
  64. [-1, 1],
  65. [ 1, 0],
  66. [ 0, -1],
  67. [ 1, -1],
  68. [ 1, -1]])
  69. Explanation of the example:
  70. ---------------------------
  71. Let's take the first value for example 0b10100001, we we will only focus on the first column,
  72. because every element is unpacked across the first dimension
  73. - First 2 bits: `01` → 0 at [0][0]
  74. - Second 2 bits: `00` → -1 at [0][2]
  75. - Third 2 bits: `10` → 1 at [0][4]
  76. - Fourth 2 bits: `10` → 1 at [0][6]
  77. the second value of the same row (0b10010000) will give the values for [0][1], [0][3], [0][5], [0][7]
  78. We subtract 1 because during the packing process, it's easier to work with values like 0, 1, and 2. To make this possible,
  79. we add 1 to the original ternary weights (which are typically -1, 0, and 1) when packing them. When unpacking, we reverse
  80. this by subtracting 1 to restore the original ternary values.
  81. """
  82. packed_shape = packed.shape
  83. if len(packed_shape) == 1:
  84. original_row_dim = packed_shape[0] * VALUES_PER_ITEM
  85. unpacked_shape = (original_row_dim,)
  86. else:
  87. original_row_dim = packed_shape[0] * VALUES_PER_ITEM
  88. unpacked_shape = (original_row_dim, *packed_shape[1:])
  89. unpacked = torch.zeros(unpacked_shape, device=packed.device, dtype=torch.uint8)
  90. for i in range(VALUES_PER_ITEM):
  91. start = i * packed_shape[0]
  92. end = start + packed_shape[0]
  93. mask = 3 << (2 * i)
  94. unpacked[start:end] = (packed & mask) >> (2 * i)
  95. return unpacked.to(dtype) - 1
  96. class BitLinear(nn.Module):
  97. def __init__(self, in_features: int, out_features: int, bias: bool, device=None, dtype=None):
  98. super().__init__()
  99. self.dtype = dtype
  100. self.register_buffer(
  101. "weight",
  102. torch.zeros(
  103. (out_features // VALUES_PER_ITEM, in_features),
  104. dtype=torch.uint8,
  105. device=device,
  106. ),
  107. )
  108. self.register_buffer(
  109. "weight_scale",
  110. torch.ones(
  111. (1),
  112. dtype=dtype,
  113. device=device,
  114. ),
  115. )
  116. if bias:
  117. self.register_buffer("bias", torch.zeros((out_features), dtype=dtype, device=device))
  118. else:
  119. self.bias = None
  120. @torch.compile
  121. def activation_quant(self, input, num_bits=8):
  122. """
  123. Activation function : Performs symmetric, per-token quantization on the input activations.
  124. Parameters:
  125. -----------
  126. x : torch.Tensor
  127. Input activations to be quantized.
  128. num_bits : int, optional (default=8)
  129. Number of bits to use for quantization, determining the quantization range.
  130. Returns:
  131. --------
  132. result : torch.Tensor
  133. Quantized activation tensor, with values mapped to an `int8` range.
  134. scale : torch.Tensor
  135. The per-channel scaling factors used to quantize the tensor.
  136. """
  137. Qn = -(2 ** (num_bits - 1))
  138. Qp = 2 ** (num_bits - 1) - 1
  139. scale = Qp / input.abs().max(dim=-1, keepdim=True).values.clamp(min=1e-5)
  140. result = (input * scale).round().clamp(Qn, Qp)
  141. return result.to(torch.int8), scale
  142. @torch.compile
  143. def post_quant_process(self, input, input_scale, weight_scale):
  144. out = input / (input_scale * weight_scale)
  145. return out
  146. def forward(self, input):
  147. w = self.weight
  148. w_quant = unpack_weights(w, dtype=self.dtype)
  149. input_quant, input_scale = self.activation_quant(input)
  150. y = F.linear(input_quant.to(self.dtype), w_quant)
  151. y = self.post_quant_process(y, self.weight_scale, input_scale)
  152. if self.bias is not None:
  153. y += self.bias.view(1, -1).expand_as(y)
  154. return y
  155. def _replace_with_bitnet_linear(
  156. model,
  157. modules_to_not_convert=None,
  158. current_key_name=None,
  159. quantization_config=None,
  160. has_been_replaced=False,
  161. pre_quantized=False,
  162. ):
  163. """
  164. Private method that wraps the recursion for module replacement.
  165. Returns the converted model and a boolean that indicates if the conversion has been successfull or not.
  166. """
  167. if current_key_name is None:
  168. current_key_name = []
  169. for name, module in model.named_children():
  170. if current_key_name is None:
  171. current_key_name = []
  172. current_key_name.append(name)
  173. # Check if the current key is not in the `modules_to_not_convert`
  174. if not any(key in ".".join(current_key_name) for key in modules_to_not_convert):
  175. with init_empty_weights():
  176. if isinstance(module, nn.Linear) and name not in modules_to_not_convert:
  177. in_features = module.in_features
  178. out_features = module.out_features
  179. model._modules[name] = BitLinear(
  180. in_features=in_features,
  181. out_features=out_features,
  182. bias=module.bias is not None,
  183. device=module.weight.device,
  184. dtype=module.weight.dtype,
  185. )
  186. has_been_replaced = True
  187. model._modules[name].requires_grad_(False)
  188. if len(list(module.children())) > 0:
  189. _, has_been_replaced = _replace_with_bitnet_linear(
  190. module,
  191. modules_to_not_convert=modules_to_not_convert,
  192. current_key_name=current_key_name,
  193. quantization_config=quantization_config,
  194. has_been_replaced=has_been_replaced,
  195. )
  196. # Remove the last key for recursion
  197. current_key_name.pop(-1)
  198. return model, has_been_replaced
  199. def replace_with_bitnet_linear(
  200. model,
  201. modules_to_not_convert=None,
  202. current_key_name=None,
  203. quantization_config=None,
  204. pre_quantized=False,
  205. ):
  206. """
  207. A helper function to replace all `torch.nn.Linear` modules by `BitLinear158` modules`.
  208. The function will be run recursively and replace all `torch.nn.Linear` modules except for the `lm_head` that should
  209. be kept as a `torch.nn.Linear` module. The replacement is done under `init_empty_weights` context manager so no
  210. CPU/GPU memory is required to run this function. Each weight will be quantized along the channel.
  211. Parameters:
  212. model (`torch.nn.Module`):
  213. Input model or `torch.nn.Module` as the function is run recursively.
  214. modules_to_not_convert (`List[`str`]`, *optional*, defaults to `["lm_head"]`):
  215. Names of the modules to not convert in `EetqLinear`. In practice we keep the `lm_head` in full precision
  216. for numerical stability reasons.
  217. current_key_name (`List[`str`]`, *optional*):
  218. An array to track the current key of the recursion. This is used to check whether the current key (part of
  219. it) is not in the list of modules to not convert (for instances modules that are offloaded to `cpu` or
  220. `disk`).
  221. """
  222. modules_to_not_convert = ["lm_head"] if modules_to_not_convert is None else modules_to_not_convert
  223. if quantization_config and quantization_config.modules_to_not_convert is not None:
  224. modules_to_not_convert.extend(quantization_config.modules_to_not_convert)
  225. modules_to_not_convert = list(set(modules_to_not_convert))
  226. model, has_been_replaced = _replace_with_bitnet_linear(
  227. model,
  228. modules_to_not_convert,
  229. current_key_name,
  230. quantization_config,
  231. pre_quantized=pre_quantized,
  232. )
  233. if not has_been_replaced:
  234. logger.warning(
  235. "You are loading your model using bitnet but no linear modules were found in your model."
  236. " Please double check your model architecture, or submit an issue on github if you think this is"
  237. " a bug."
  238. )
  239. return model