linear.py 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  1. from abc import abstractmethod
  2. from typing import Dict, List, Optional, Tuple
  3. import torch
  4. import torch.nn.functional as F
  5. from loguru import logger
  6. from torch.nn.parameter import Parameter, UninitializedParameter
  7. # yapf: disable
  8. from aphrodite.distributed import (divide,
  9. get_current_tp_rank_partition_offset,
  10. get_current_tp_rank_partition_size,
  11. get_tensor_model_parallel_rank,
  12. get_tensor_model_parallel_world_size,
  13. split_tensor_along_last_dim,
  14. tensor_model_parallel_all_gather,
  15. tensor_model_parallel_all_reduce)
  16. from aphrodite.modeling.parameter import (BaseAphroditeParameter,
  17. PackedAphroditeParameter,
  18. PerTensorScaleParameter)
  19. # yapf: enable
  20. from aphrodite.modeling.utils import set_weight_attrs
  21. from aphrodite.quantization.base_config import (QuantizationConfig,
  22. QuantizeMethodBase)
  23. WEIGHT_LOADER_V2_SUPPORTED = [
  24. "CompressedTensorsLinearMethod", "GPTQMarlinLinearMethod",
  25. "AWQMarlinLinearMethod", "AWQLinearMethod",
  26. ]
  27. def adjust_marlin_shard(param, shard_size, shard_offset):
  28. marlin_tile_size = getattr(param, "marlin_tile_size", None)
  29. if marlin_tile_size is None:
  30. return shard_size, shard_offset
  31. return shard_size * marlin_tile_size, shard_offset * marlin_tile_size
  32. def adjust_bitsandbytes_shard(param: Parameter,
  33. qkv_offsets: Dict[str, Tuple[int, int]],
  34. loaded_shard_id: str) -> Tuple[int, int]:
  35. """Adjust the quantization offsets and sizes for BitsAndBytes sharding."""
  36. total, _ = qkv_offsets["total"]
  37. orig_offset, orig_size = qkv_offsets[loaded_shard_id]
  38. quantized_total = param.data.shape[0]
  39. quantized_offset = orig_offset * quantized_total // total
  40. quantized_size = orig_size * quantized_total // total
  41. return quantized_size, quantized_offset
  42. def adjust_scalar_to_fused_array(param, loaded_weight, shard_id):
  43. """For fused modules (QKV and MLP) we have an array of length
  44. N that holds 1 scale for each "logical" matrix. So the param
  45. is an array of length N. The loaded_weight corresponds to
  46. one of the shards on disk. Here, we slice the param based on
  47. the shard_id for loading.
  48. """
  49. qkv_idxs = {"q": 0, "k": 1, "v": 2}
  50. if isinstance(shard_id, str):
  51. shard_id = qkv_idxs[shard_id]
  52. elif not isinstance(shard_id, int):
  53. raise ValueError(f"Unknown Shard Id {shard_id}")
  54. # AutoFP8 scales do not have a shape
  55. # compressed-tensors scales do have a shape
  56. if len(loaded_weight.shape) != 0:
  57. assert loaded_weight.shape[0] == 1
  58. loaded_weight = loaded_weight[0]
  59. return param[shard_id], loaded_weight
  60. class LinearMethodBase(QuantizeMethodBase):
  61. """Base class for different (maybe quantized) linear methods."""
  62. @abstractmethod
  63. def create_weights(self, layer: torch.nn.Module,
  64. input_size_per_partition: int,
  65. output_partition_sizes: List[int], input_size: int,
  66. output_size: int, params_dtype: torch.dtype,
  67. **extra_weight_attrs):
  68. """Create weights for a linear layer.
  69. The weights will be set as attributes of the layer.
  70. Args:
  71. layer: The layer that is using the LinearMethodBase factory.
  72. input_size_per_partition: Size of the weight input dim on rank X.
  73. output_partition_sizes: Sizes of the output dim of each logical
  74. weight on rank X. E.g., output_partition_sizes for QKVLinear
  75. is a list contains the width of Wq, Wk, Wv on rank X.
  76. input_size: Size of the input dim of the weight across all ranks.
  77. output_size: Size of the output dim of the weight across all ranks.
  78. params_dtype: Datatype of the parameters.
  79. """
  80. raise NotImplementedError
  81. @abstractmethod
  82. def apply(self,
  83. layer: torch.nn.Module,
  84. x: torch.Tensor,
  85. bias: Optional[torch.Tensor] = None) -> torch.Tensor:
  86. """Apply the weights in layer to the input tensor.
  87. Expects create_weights to have been called before on the layer."""
  88. raise NotImplementedError
  89. class UnquantizedLinearMethod(LinearMethodBase):
  90. """Linear method without quantization."""
  91. def create_weights(self, layer: torch.nn.Module,
  92. input_size_per_partition: int,
  93. output_partition_sizes: List[int], input_size: int,
  94. output_size: int, params_dtype: torch.dtype,
  95. **extra_weight_attrs):
  96. weight = Parameter(torch.empty(sum(output_partition_sizes),
  97. input_size_per_partition,
  98. dtype=params_dtype),
  99. requires_grad=False)
  100. set_weight_attrs(weight, {"input_dim": 1, "output_dim": 0})
  101. layer.register_parameter("weight", weight)
  102. set_weight_attrs(weight, extra_weight_attrs)
  103. def apply(self,
  104. layer: torch.nn.Module,
  105. x: torch.Tensor,
  106. bias: Optional[torch.Tensor] = None) -> torch.Tensor:
  107. return F.linear(x, layer.weight, bias)
  108. class LinearBase(torch.nn.Module):
  109. """Base linear layer.
  110. Args:
  111. input_size: input dimension of the linear layer.
  112. output_size: output dimension of the linear layer.
  113. bias: If true, add bias.
  114. skip_bias_add: If true, skip adding bias but instead return it.
  115. params_dtype: Data type for the parameters.
  116. quant_config: Quantization configure.
  117. """
  118. def __init__(
  119. self,
  120. input_size: int,
  121. output_size: int,
  122. skip_bias_add: bool = False,
  123. params_dtype: Optional[torch.dtype] = None,
  124. quant_config: Optional[QuantizationConfig] = None,
  125. prefix: str = "",
  126. ):
  127. super().__init__()
  128. # Keep input parameters
  129. self.input_size = input_size
  130. self.output_size = output_size
  131. self.skip_bias_add = skip_bias_add
  132. if params_dtype is None:
  133. params_dtype = torch.get_default_dtype()
  134. self.params_dtype = params_dtype
  135. if quant_config is None:
  136. self.quant_method: Optional[
  137. QuantizeMethodBase] = UnquantizedLinearMethod()
  138. else:
  139. self.quant_method = quant_config.get_quant_method(self,
  140. prefix=prefix)
  141. def forward(self, x: torch.Tensor) -> torch.Tensor:
  142. raise NotImplementedError
  143. class ReplicatedLinear(LinearBase):
  144. """Replicated linear layer.
  145. Args:
  146. input_size: input dimension of the linear layer.
  147. output_size: output dimension of the linear layer.
  148. bias: If true, add bias.
  149. skip_bias_add: If true, skip adding bias but instead return it.
  150. params_dtype: Data type for the parameters.
  151. quant_config: Quantization configure.
  152. prefix: The name of the layer in the state dict, including all parents
  153. (e.g. model.layers.0.qkv_proj)
  154. """
  155. def __init__(self,
  156. input_size: int,
  157. output_size: int,
  158. bias: bool = True,
  159. skip_bias_add: bool = False,
  160. params_dtype: Optional[torch.dtype] = None,
  161. quant_config: Optional[QuantizationConfig] = None,
  162. prefix: str = ""):
  163. super().__init__(input_size,
  164. output_size,
  165. skip_bias_add,
  166. params_dtype,
  167. quant_config,
  168. prefix=prefix)
  169. # All the linear layer supports quant method.
  170. assert self.quant_method is not None
  171. self.quant_method.create_weights(self,
  172. self.input_size, [self.output_size],
  173. self.input_size,
  174. self.output_size,
  175. self.params_dtype,
  176. prefix=prefix)
  177. if bias:
  178. self.bias = Parameter(
  179. torch.empty(self.output_size, dtype=self.params_dtype))
  180. set_weight_attrs(self.bias, {"output_dim": 0})
  181. else:
  182. self.register_parameter("bias", None)
  183. def weight_loader(self, param: Parameter, loaded_weight: torch.Tensor):
  184. # If the weight on disk does not have a shape, give it one
  185. # (such scales for AutoFp8).
  186. if len(loaded_weight.shape) == 0:
  187. loaded_weight = loaded_weight.reshape(1)
  188. assert param.size() == loaded_weight.size()
  189. param.data.copy_(loaded_weight)
  190. def forward(self, x: torch.Tensor) -> torch.Tensor:
  191. bias = self.bias if not self.skip_bias_add else None
  192. assert self.quant_method is not None
  193. output = self.quant_method.apply(self, x, bias)
  194. output_bias = self.bias if self.skip_bias_add else None
  195. return output, output_bias
  196. def extra_repr(self) -> str:
  197. s = f"in_features={self.input_size}"
  198. s += f", output_features={self.output_size}"
  199. s += f", bias={self.bias is not None}"
  200. return s
  201. class ColumnParallelLinear(LinearBase):
  202. """Linear layer with column parallelism.
  203. The linear layer is defined as Y = XA + b. A is parallelized along
  204. its second dimension as A = [A_1, ..., A_p].
  205. Args:
  206. input_size: first dimension of matrix A.
  207. output_size: second dimension of matrix A.
  208. bias: If true, add bias.
  209. gather_output: If true, call all-gather on output and make Y available
  210. to all GPUs, otherwise, every GPU will have its output
  211. which is Y_i = XA_i
  212. skip_bias_add: This was added to enable performance optimizations where
  213. bias can be fused with other element-wise operations. we
  214. skip adding bias but instead return it.
  215. params_dtype: Data type for the parameters.
  216. quant_config: Quantization configure.
  217. output_sizes: list of output sizes packed into one output, like for QKV
  218. the list would be size 3.
  219. prefix: The name of the layer in the state dict, including all parents
  220. (e.g. model.layers.0.qkv_proj)
  221. """
  222. def __init__(self,
  223. input_size: int,
  224. output_size: int,
  225. bias: bool = True,
  226. gather_output: bool = False,
  227. skip_bias_add: bool = False,
  228. params_dtype: Optional[torch.dtype] = None,
  229. quant_config: Optional[QuantizationConfig] = None,
  230. output_sizes: Optional[List[int]] = None,
  231. prefix: str = ""):
  232. super().__init__(input_size, output_size, skip_bias_add, params_dtype,
  233. quant_config, prefix)
  234. self.gather_output = gather_output
  235. # Divide the weight matrix along the last dimension.
  236. tp_rank = get_tensor_model_parallel_rank()
  237. tp_size = get_tensor_model_parallel_world_size()
  238. assert self.quant_method is not None
  239. if quant_config is None:
  240. self.output_size_per_partition = get_current_tp_rank_partition_size(
  241. output_size, tp_rank, tp_size)
  242. else:
  243. self.output_size_per_partition = divide(self.output_size, tp_size)
  244. self.output_partition_sizes = [self.output_size_per_partition]
  245. # If QKV or MergedColumn, use output size of each partition.
  246. if hasattr(self, "output_sizes"):
  247. if quant_config is None:
  248. self.output_partition_sizes = [
  249. get_current_tp_rank_partition_size(output_size, tp_rank,
  250. tp_size)
  251. for output_size in self.output_sizes
  252. ]
  253. else:
  254. self.output_partition_sizes = [
  255. divide(output_size, tp_size)
  256. for output_size in self.output_sizes
  257. ]
  258. if output_sizes is None:
  259. output_sizes = [output_size]
  260. self.quant_method.create_weights(
  261. layer=self,
  262. input_size_per_partition=self.input_size,
  263. output_partition_sizes=self.output_partition_sizes,
  264. input_size=self.input_size,
  265. output_size=self.output_size,
  266. params_dtype=self.params_dtype,
  267. weight_loader=(
  268. self.weight_loader_v2 if self.quant_method.__class__.__name__
  269. in WEIGHT_LOADER_V2_SUPPORTED else self.weight_loader),
  270. prefix=prefix)
  271. if bias:
  272. self.bias = Parameter(
  273. torch.empty(self.output_size_per_partition,
  274. dtype=params_dtype))
  275. set_weight_attrs(self.bias, {
  276. "output_dim": 0,
  277. "weight_loader": self.weight_loader,
  278. })
  279. else:
  280. self.register_parameter("bias", None)
  281. def weight_loader(self, param: Parameter, loaded_weight: torch.Tensor):
  282. tp_rank = get_tensor_model_parallel_rank()
  283. output_dim = getattr(param, "output_dim", None)
  284. # Special case for GGUF
  285. is_gguf_weight = getattr(param, "is_gguf_weight", False)
  286. is_gguf_weight_type = getattr(param, "is_gguf_weight_type", False)
  287. if is_gguf_weight_type:
  288. param.weight_type = loaded_weight.item()
  289. # Materialize GGUF UninitializedParameter
  290. if is_gguf_weight and isinstance(param, UninitializedParameter):
  291. param.materialize(loaded_weight.shape, dtype=loaded_weight.dtype)
  292. param_data = param.data
  293. if output_dim is not None:
  294. shard_size = param_data.shape[output_dim]
  295. start_idx = tp_rank * shard_size
  296. loaded_weight = loaded_weight.narrow(output_dim, start_idx,
  297. shard_size)
  298. # Special case for loading scales off disk, which often do not
  299. # have a shape (such as in the case of AutoFP8).
  300. if len(loaded_weight.shape) == 0:
  301. loaded_weight = loaded_weight.reshape(1)
  302. assert param_data.shape == loaded_weight.shape
  303. param_data.copy_(loaded_weight)
  304. def weight_loader_v2(self, param: Parameter, loaded_weight: torch.Tensor):
  305. param.load_column_parallel_weight(loaded_weight=loaded_weight)
  306. def forward(self, input_):
  307. bias = self.bias if not self.skip_bias_add else None
  308. # Matrix multiply.
  309. assert self.quant_method is not None
  310. output_parallel = self.quant_method.apply(self, input_, bias)
  311. if self.gather_output:
  312. # All-gather across the partitions.
  313. output = tensor_model_parallel_all_gather(output_parallel)
  314. else:
  315. output = output_parallel
  316. output_bias = self.bias if self.skip_bias_add else None
  317. return output, output_bias
  318. def extra_repr(self) -> str:
  319. s = f"in_features={self.input_size}"
  320. s += f", output_features={self.output_size_per_partition}"
  321. s += f", bias={self.bias is not None}"
  322. s += f", tp_size={get_tensor_model_parallel_world_size()}"
  323. s += f", gather_output={self.gather_output}"
  324. return s
  325. class MergedColumnParallelLinear(ColumnParallelLinear):
  326. """Packed linear layers with column parallelism.
  327. Similar to ColumnParallelLinear, but the weight matrix is concatenated
  328. along the output dimension. When the weight matrix is loaded, the
  329. different partitions are sharded separately.
  330. Args:
  331. input_size: input dimension of the linear layer.
  332. output_sizes: list of output dimensions of the linear layer.
  333. bias: If true, add bias.
  334. gather_output: If true, call all-gather on output and make the output
  335. available to all GPUs, otherwise, every GPU will have
  336. its own output.
  337. skip_bias_add: This was added to enable performance optimizations where
  338. bias can be fused with other element-wise operations. we
  339. skip adding bias but instead return it.
  340. params_dtype: Data type for the parameters.
  341. quant_config: Quantization configure.
  342. prefix: The name of the layer in the state dict, including all parents
  343. (e.g. model.layers.0.qkv_proj)
  344. """
  345. def __init__(self,
  346. input_size: int,
  347. output_sizes: List[int],
  348. bias: bool = True,
  349. gather_output: bool = False,
  350. skip_bias_add: bool = False,
  351. params_dtype: Optional[torch.dtype] = None,
  352. quant_config: Optional[QuantizationConfig] = None,
  353. prefix: str = ""):
  354. self.output_sizes = output_sizes
  355. self.quant_config = quant_config
  356. if quant_config is not None:
  357. tp_size = get_tensor_model_parallel_world_size()
  358. assert all(output_size % tp_size == 0
  359. for output_size in output_sizes)
  360. super().__init__(input_size=input_size,
  361. output_size=sum(output_sizes),
  362. bias=bias,
  363. gather_output=gather_output,
  364. skip_bias_add=skip_bias_add,
  365. params_dtype=params_dtype,
  366. quant_config=quant_config,
  367. prefix=prefix)
  368. def weight_loader(self,
  369. param: Parameter,
  370. loaded_weight: torch.Tensor,
  371. loaded_shard_id: Optional[int] = None):
  372. # Special case for GGUF
  373. # initialize GGUF param after we know the quantize type
  374. is_gguf_weight = getattr(param, "is_gguf_weight", False)
  375. is_gguf_weight_type = getattr(param, "is_gguf_weight_type", False)
  376. if is_gguf_weight_type:
  377. param.data[loaded_shard_id].copy_(loaded_weight)
  378. param.shard_weight_type[loaded_shard_id] = loaded_weight.item()
  379. return
  380. if is_gguf_weight and isinstance(param, UninitializedParameter):
  381. from gguf.constants import GGML_QUANT_SIZES
  382. ori_shape = param.tensor_shape
  383. weight_types = self.qweight_type.shard_weight_type.values()
  384. row_size = []
  385. for weight_type in weight_types:
  386. block_size, type_size = GGML_QUANT_SIZES[weight_type]
  387. row_size.append(ori_shape[1] // block_size * type_size)
  388. q_shape = (ori_shape[0], max(row_size))
  389. param.materialize(q_shape, dtype=loaded_weight.dtype)
  390. param_data = param.data
  391. output_dim = getattr(param, "output_dim", None)
  392. # Special case for AQLM codebooks.
  393. is_metadata = getattr(param, "is_metadata", False)
  394. # Special case for per-tensor scale to load scalar into fused array.
  395. needs_scalar_to_array = getattr(param, "needs_scalar_to_array", False)
  396. if loaded_shard_id is None:
  397. # Loaded weight is already fused on disk (qkv/mlp).
  398. if output_dim is None:
  399. if needs_scalar_to_array:
  400. param_data, loaded_weight = adjust_scalar_to_fused_array(
  401. param_data, loaded_weight, 0)
  402. assert param_data.shape == loaded_weight.shape
  403. param_data.copy_(loaded_weight)
  404. return
  405. current_shard_offset = 0
  406. shard_offsets: List[Tuple[int, int, int]] = []
  407. for i, output_size in enumerate(self.output_sizes):
  408. shard_offsets.append((i, current_shard_offset, output_size))
  409. current_shard_offset += output_size
  410. packed_dim = getattr(param, "packed_dim", None)
  411. for shard_id, shard_offset, shard_size in shard_offsets:
  412. # Special case for Quantization.
  413. # If quantized, we need to adjust the offset and size to account
  414. # for the packing.
  415. if packed_dim == output_dim:
  416. shard_size = shard_size // param.pack_factor
  417. shard_offset = shard_offset // param.pack_factor
  418. # Special case for Marlin.
  419. shard_size, shard_offset = adjust_marlin_shard(
  420. param, shard_size, shard_offset)
  421. loaded_weight_shard = loaded_weight.narrow(
  422. output_dim, shard_offset, shard_size)
  423. self.weight_loader(param, loaded_weight_shard, shard_id)
  424. return
  425. assert loaded_shard_id < len(self.output_sizes)
  426. tp_rank = get_tensor_model_parallel_rank()
  427. tp_size = get_tensor_model_parallel_world_size()
  428. if output_dim is not None:
  429. if self.quant_config is None:
  430. shard_offset = sum(
  431. get_current_tp_rank_partition_size(output_size, tp_rank,
  432. tp_size)
  433. for output_size in self.output_sizes[:loaded_shard_id])
  434. shard_size = get_current_tp_rank_partition_size(
  435. self.output_sizes[loaded_shard_id], tp_rank, tp_size)
  436. else:
  437. shard_offset = sum(
  438. self.output_sizes[:loaded_shard_id]) // tp_size
  439. shard_size = self.output_sizes[loaded_shard_id] // tp_size
  440. # Special case for quantization.
  441. # If quantized, we need to adjust the offset and size to account
  442. # for the packing.
  443. packed_dim = getattr(param, "packed_dim", None)
  444. if packed_dim == output_dim:
  445. shard_size = shard_size // param.pack_factor
  446. shard_offset = shard_offset // param.pack_factor
  447. # Special case for Marlin.
  448. shard_size, shard_offset = adjust_marlin_shard(
  449. param, shard_size, shard_offset)
  450. use_bitsandbytes = getattr(param, "use_bitsandbytes", False)
  451. if use_bitsandbytes:
  452. shard_size = loaded_weight.shape[output_dim]
  453. shard_offset = loaded_weight.shape[output_dim] * \
  454. loaded_shard_id
  455. if is_gguf_weight:
  456. tp_size = get_tensor_model_parallel_world_size()
  457. output_dim = getattr(param, "output_dim", None)
  458. shard_shape = list(loaded_weight.shape)
  459. shard_shape[output_dim] = shard_shape[output_dim] // tp_size
  460. param.shard_id.append(loaded_shard_id)
  461. param.shard_size[loaded_shard_id] = shard_shape
  462. input_dim = getattr(param, "input_dim", None)
  463. input_size = loaded_weight.shape[input_dim]
  464. param_data = param_data.narrow(input_dim, 0, input_size)
  465. param_data = param_data.narrow(output_dim, shard_offset,
  466. shard_size)
  467. if self.quant_config is None:
  468. start_idx = get_current_tp_rank_partition_offset(
  469. loaded_weight.shape[output_dim], tp_rank, tp_size)
  470. else:
  471. start_idx = tp_rank * shard_size
  472. loaded_weight = loaded_weight.narrow(output_dim, start_idx,
  473. shard_size)
  474. # Special case for AQLM codebooks.
  475. elif is_metadata:
  476. # metadata indicates fixed size concatenated along dim 0
  477. shard_size = loaded_weight.shape[0]
  478. shard_offset = loaded_shard_id * shard_size
  479. param_data = param_data.narrow(0, shard_offset, shard_size)
  480. # Special case for per-tensor scales in fused case.
  481. elif needs_scalar_to_array:
  482. param_data, loaded_weight = adjust_scalar_to_fused_array(
  483. param_data, loaded_weight, loaded_shard_id)
  484. else:
  485. ignore_warning = getattr(param, "ignore_warning", False)
  486. if not ignore_warning:
  487. logger.warning(
  488. "Loading a weight without `output_dim` attribute in "
  489. "MergedColumnParallelLinear, assume the weight is "
  490. "the same for all partitions.")
  491. assert param_data.shape == loaded_weight.shape
  492. param_data.copy_(loaded_weight)
  493. def _load_fused_module_from_checkpoint(self, param: BaseAphroditeParameter,
  494. loaded_weight: torch.Tensor):
  495. """
  496. Handle special case for models where MLP layers are already
  497. fused on disk. In this case, we have no shard id. This function
  498. determines the shard id by splitting these layers and then calls
  499. the weight loader using the shard id.
  500. An example of a model with these fused layers:
  501. https://huggingface.co/microsoft/Phi-3-mini-4k-instruct
  502. """
  503. current_shard_offset = 0
  504. shard_offsets: List[Tuple[int, int, int]] = []
  505. for i, output_size in enumerate(self.output_sizes):
  506. shard_offsets.append((i, current_shard_offset, output_size))
  507. current_shard_offset += output_size
  508. for shard_id, shard_offset, shard_size in shard_offsets:
  509. # Special case for Quantization.
  510. # If quantized, we need to adjust the offset and size to account
  511. # for the packing.
  512. if isinstance(param, PackedAphroditeParameter
  513. ) and param.packed_dim == param.output_dim:
  514. param.adjust_shard_indexes_for_packing(
  515. shard_size=shard_size, shard_offset=shard_offset)
  516. loaded_weight_shard = loaded_weight.narrow(param.output_dim,
  517. shard_offset,
  518. shard_size)
  519. self.weight_loader_v2(param, loaded_weight_shard, shard_id)
  520. def weight_loader_v2(self,
  521. param: BaseAphroditeParameter,
  522. loaded_weight: torch.Tensor,
  523. loaded_shard_id: Optional[int] = None):
  524. if loaded_shard_id is None:
  525. if isinstance(param, PerTensorScaleParameter):
  526. param.load_merged_column_weight(loaded_weight=loaded_weight,
  527. shard_id=0)
  528. return
  529. elif type(param) is BaseAphroditeParameter:
  530. param.load_merged_column_weight(loaded_weight=loaded_weight)
  531. return
  532. self._load_fused_module_from_checkpoint(param, loaded_weight)
  533. return
  534. assert loaded_shard_id < len(self.output_sizes)
  535. tp_size = get_tensor_model_parallel_world_size()
  536. shard_offset = sum(self.output_sizes[:loaded_shard_id]) // tp_size
  537. shard_size = self.output_sizes[loaded_shard_id] // tp_size
  538. param.load_merged_column_weight(loaded_weight=loaded_weight,
  539. shard_id=loaded_shard_id,
  540. shard_offset=shard_offset,
  541. shard_size=shard_size)
  542. class QKVParallelLinear(ColumnParallelLinear):
  543. """Linear layers for the attention's QKV transformation.
  544. Linear layers for the linear transformation of the query, key, and value
  545. vectors in the attention layer. The weight matrix is concatenated along
  546. the output dimension. The layer is parallelized along the head dimension.
  547. When the number of key/value heads is smaller than the number of query
  548. heads (e.g., multi-query/grouped-query attention), the key/value head may
  549. be replicated while the query heads are partitioned.
  550. Args:
  551. hidden_size: input hidden state size of the transformer.
  552. head_size: size of each attention head.
  553. total_num_heads: total number of attention query heads.
  554. total_num_kv_heads: total number of attention key/value heads. If
  555. None, assume total_num_kv_heads = total_num_heads.
  556. bias: If true, add bias.
  557. skip_bias_add: This was added to enable performance optimizations where
  558. bias can be fused with other element-wise operations. we
  559. skip adding bias but instead return it.
  560. params_dtype: Data type for the parameters.
  561. quant_config: Quantization configure.
  562. prefix: The name of the layer in the state dict, including all parents
  563. (e.g. model.layers.0.qkv_proj)
  564. """
  565. def __init__(self,
  566. hidden_size: int,
  567. head_size: int,
  568. total_num_heads: int,
  569. total_num_kv_heads: Optional[int] = None,
  570. bias: bool = True,
  571. skip_bias_add: bool = False,
  572. params_dtype: Optional[torch.dtype] = None,
  573. quant_config: Optional[QuantizationConfig] = None,
  574. prefix: str = ""):
  575. self.hidden_size = hidden_size
  576. self.head_size = head_size
  577. self.total_num_heads = total_num_heads
  578. self.quant_config = quant_config
  579. if total_num_kv_heads is None:
  580. total_num_kv_heads = total_num_heads
  581. self.total_num_kv_heads = total_num_kv_heads
  582. # Divide the weight matrix along the last dimension.
  583. tp_size = get_tensor_model_parallel_world_size()
  584. tp_rank = get_tensor_model_parallel_rank()
  585. if quant_config is None:
  586. self.num_heads_per_kv_head = (self.total_num_heads //
  587. self.total_num_kv_heads)
  588. self.num_kv_heads = get_current_tp_rank_partition_size(
  589. self.total_num_kv_heads, tp_rank, tp_size)
  590. self.num_heads = self.num_kv_heads * self.num_heads_per_kv_head
  591. self.num_kv_head_replicas = 1
  592. else:
  593. self.num_heads = divide(self.total_num_heads, tp_size)
  594. if tp_size >= self.total_num_kv_heads:
  595. self.num_kv_heads = 1
  596. self.num_kv_head_replicas = divide(tp_size,
  597. self.total_num_kv_heads)
  598. elif tp_size < self.total_num_kv_heads and quant_config is not None:
  599. self.num_kv_heads = divide(self.total_num_kv_heads, tp_size)
  600. self.num_kv_head_replicas = 1
  601. input_size = self.hidden_size
  602. output_size = (self.num_heads +
  603. 2 * self.num_kv_heads) * tp_size * self.head_size
  604. self.output_sizes = [
  605. self.num_heads * self.head_size * tp_size, # q_proj
  606. self.num_kv_heads * self.head_size * tp_size, # k_proj
  607. self.num_kv_heads * self.head_size * tp_size, # v_proj
  608. ]
  609. super().__init__(input_size=input_size,
  610. output_size=output_size,
  611. bias=bias,
  612. gather_output=False,
  613. skip_bias_add=skip_bias_add,
  614. params_dtype=params_dtype,
  615. quant_config=quant_config,
  616. prefix=prefix)
  617. def _get_shard_offset_mapping(self, loaded_shard_id: str):
  618. shard_offset_mapping = {
  619. "q": 0,
  620. "k": self.num_heads * self.head_size,
  621. "v": (self.num_heads + self.num_kv_heads) * self.head_size,
  622. "total": (self.num_heads + 2 * self.num_kv_heads) * self.head_size
  623. }
  624. return shard_offset_mapping.get(loaded_shard_id)
  625. def _get_shard_size_mapping(self, loaded_shard_id: str):
  626. shard_size_mapping = {
  627. "q": self.num_heads * self.head_size,
  628. "k": self.num_kv_heads * self.head_size,
  629. "v": self.num_kv_heads * self.head_size,
  630. }
  631. return shard_size_mapping.get(loaded_shard_id)
  632. def _load_fused_module_from_checkpoint(self, param: BaseAphroditeParameter,
  633. loaded_weight: torch.Tensor):
  634. """
  635. Handle special case for models where QKV layers are already
  636. fused on disk. In this case, we have no shard id. This function
  637. determmines the shard id by splitting these layers and then calls
  638. the weight loader using the shard id.
  639. An example of a model with these fused layers:
  640. https://huggingface.co/microsoft/Phi-3-mini-4k-instruct
  641. """
  642. shard_offsets = [
  643. # (shard_id, shard_offset, shard_size)
  644. ("q", 0, self.total_num_heads * self.head_size),
  645. ("k", self.total_num_heads * self.head_size,
  646. self.total_num_kv_heads * self.head_size),
  647. ("v",
  648. (self.total_num_heads + self.total_num_kv_heads) * self.head_size,
  649. self.total_num_kv_heads * self.head_size),
  650. ]
  651. for shard_id, shard_offset, shard_size in shard_offsets:
  652. # Special case for Quantization.
  653. # If quantized, we need to adjust the offset and size to account
  654. # for the packing.
  655. if isinstance(param, PackedAphroditeParameter
  656. ) and param.packed_dim == param.output_dim:
  657. param.adjust_shard_indexes_for_packing(
  658. shard_size=shard_size, shard_offset=shard_offset)
  659. loaded_weight_shard = loaded_weight.narrow(param.output_dim,
  660. shard_offset,
  661. shard_size)
  662. self.weight_loader_v2(param, loaded_weight_shard, shard_id)
  663. def weight_loader_v2(self,
  664. param: BaseAphroditeParameter,
  665. loaded_weight: torch.Tensor,
  666. loaded_shard_id: Optional[str] = None):
  667. if loaded_shard_id is None: # special case for certain models
  668. if isinstance(param, PerTensorScaleParameter):
  669. param.load_merged_column_weight(loaded_weight=loaded_weight,
  670. shard_id=0)
  671. return
  672. elif type(param) is BaseAphroditeParameter:
  673. param.load_merged_column_weight(loaded_weight=loaded_weight)
  674. return
  675. self._load_fused_module_from_checkpoint(param, loaded_weight)
  676. return
  677. assert loaded_shard_id in ["q", "k", "v"]
  678. shard_offset = self._get_shard_offset_mapping(loaded_shard_id)
  679. shard_size = self._get_shard_size_mapping(loaded_shard_id)
  680. param.load_qkv_weight(loaded_weight=loaded_weight,
  681. num_heads=self.num_kv_head_replicas,
  682. shard_id=loaded_shard_id,
  683. shard_offset=shard_offset,
  684. shard_size=shard_size)
  685. def weight_loader(self,
  686. param: Parameter,
  687. loaded_weight: torch.Tensor,
  688. loaded_shard_id: Optional[str] = None):
  689. # Special case for GGUF
  690. # initialize GGUF param after we know the quantize type
  691. is_gguf_weight = getattr(param, "is_gguf_weight", False)
  692. is_gguf_weight_type = getattr(param, "is_gguf_weight_type", False)
  693. if is_gguf_weight_type and loaded_shard_id is not None:
  694. idx_map = {"q": 0, "k": 1, "v": 2}
  695. param.data[idx_map[loaded_shard_id]].copy_(loaded_weight)
  696. param.shard_weight_type[loaded_shard_id] = loaded_weight.item()
  697. return
  698. if is_gguf_weight and isinstance(param, UninitializedParameter):
  699. from gguf.constants import GGML_QUANT_SIZES
  700. ori_shape = param.tensor_shape
  701. weight_types = self.qweight_type.shard_weight_type.values()
  702. row_size = []
  703. for weight_type in weight_types:
  704. block_size, type_size = GGML_QUANT_SIZES[weight_type]
  705. row_size.append(ori_shape[1] // block_size * type_size)
  706. q_shape = (ori_shape[0], max(row_size))
  707. param.materialize(q_shape, dtype=loaded_weight.dtype)
  708. param_data = param.data
  709. output_dim = getattr(param, "output_dim", None)
  710. # Special case for AQLM codebooks.
  711. is_metadata = getattr(param, "is_metadata", False)
  712. # Special case for per-tensor scales in fused case.
  713. needs_scalar_to_array = getattr(param, "needs_scalar_to_array", False)
  714. if loaded_shard_id is None:
  715. # Loaded weight is already fused on disk (qkv/mlp).
  716. if output_dim is None:
  717. if needs_scalar_to_array:
  718. param_data, loaded_weight = adjust_scalar_to_fused_array(
  719. param_data, loaded_weight, 0)
  720. assert param_data.shape == loaded_weight.shape
  721. param_data.copy_(loaded_weight)
  722. return
  723. shard_offsets = [
  724. # (shard_id, shard_offset, shard_size)
  725. ("q", 0, self.total_num_heads * self.head_size),
  726. ("k", self.total_num_heads * self.head_size,
  727. self.total_num_kv_heads * self.head_size),
  728. ("v", (self.total_num_heads + self.total_num_kv_heads) *
  729. self.head_size, self.total_num_kv_heads * self.head_size),
  730. ]
  731. packed_dim = getattr(param, "packed_dim", None)
  732. for shard_id, shard_offset, shard_size in shard_offsets:
  733. # Special case for Quantized Weights.
  734. # If quantized, we need to adjust the offset and size to account
  735. # for the packing.
  736. if packed_dim == output_dim:
  737. shard_size = shard_size // param.pack_factor
  738. shard_offset = shard_offset // param.pack_factor
  739. # Special case for Marlin.
  740. shard_size, shard_offset = adjust_marlin_shard(
  741. param, shard_size, shard_offset)
  742. loaded_weight_shard = loaded_weight.narrow(
  743. output_dim, shard_offset, shard_size)
  744. self.weight_loader(param, loaded_weight_shard, shard_id)
  745. return
  746. tp_rank = get_tensor_model_parallel_rank()
  747. assert loaded_shard_id in ["q", "k", "v"]
  748. # If output dim is defined, use the default loading process.
  749. if output_dim is not None:
  750. if loaded_shard_id == "q":
  751. shard_offset = 0
  752. shard_size = self.num_heads * self.head_size
  753. if self.quant_config is None:
  754. multiple_of = self.head_size * self.num_heads_per_kv_head
  755. elif loaded_shard_id == "k":
  756. shard_offset = self.num_heads * self.head_size
  757. shard_size = self.num_kv_heads * self.head_size
  758. if self.quant_config is None:
  759. multiple_of = self.head_size
  760. elif loaded_shard_id == "v":
  761. shard_offset = (self.num_heads +
  762. self.num_kv_heads) * self.head_size
  763. shard_size = self.num_kv_heads * self.head_size
  764. if self.quant_config is None:
  765. multiple_of = self.head_size
  766. # Special case for Quantized Weights.
  767. # If quantized, we need to adjust the offset and size to account
  768. # for the packing.
  769. packed_dim = getattr(param, "packed_dim", None)
  770. if packed_dim == output_dim:
  771. shard_size = shard_size // param.pack_factor
  772. shard_offset = shard_offset // param.pack_factor
  773. if self.quant_config is None:
  774. multiple_of = multiple_of // param.pack_factor
  775. # Special case for Marlin.
  776. shard_size, shard_offset = adjust_marlin_shard(
  777. param, shard_size, shard_offset)
  778. use_bitsandbytes = getattr(param, "use_bitsandbytes", False)
  779. if use_bitsandbytes:
  780. orig_qkv_offsets = {
  781. "q": (0, self.num_heads * self.head_size),
  782. "k": (self.num_heads * self.head_size,
  783. self.num_kv_heads * self.head_size),
  784. "v":
  785. ((self.num_heads + self.num_kv_heads) * self.head_size,
  786. self.num_kv_heads * self.head_size),
  787. "total":
  788. ((self.num_heads + 2 * self.num_kv_heads) * self.head_size,
  789. 0)
  790. }
  791. shard_size, shard_offset = adjust_bitsandbytes_shard(
  792. param, orig_qkv_offsets, loaded_shard_id)
  793. if is_gguf_weight:
  794. tp_size = get_tensor_model_parallel_world_size()
  795. output_dim = getattr(param, "output_dim", None)
  796. shard_shape = list(loaded_weight.shape)
  797. shard_shape[output_dim] = shard_shape[output_dim] // tp_size
  798. param.shard_id.append(loaded_shard_id)
  799. param.shard_size[loaded_shard_id] = shard_shape
  800. input_dim = getattr(param, "input_dim", None)
  801. input_size = loaded_weight.shape[input_dim]
  802. param_data = param_data.narrow(input_dim, 0, input_size)
  803. param_data = param_data.narrow(output_dim, shard_offset,
  804. shard_size)
  805. if self.quant_config is None:
  806. tp_size = get_tensor_model_parallel_world_size()
  807. total_size = loaded_weight.shape[output_dim]
  808. start_idx = get_current_tp_rank_partition_offset(
  809. total_size, tp_rank, tp_size, multiple_of=multiple_of)
  810. else:
  811. if loaded_shard_id == "q":
  812. shard_id = tp_rank
  813. else:
  814. shard_id = tp_rank // self.num_kv_head_replicas
  815. start_idx = shard_id * shard_size
  816. loaded_weight = loaded_weight.narrow(output_dim, start_idx,
  817. shard_size)
  818. # Special case for for AQLM codebooks.
  819. elif is_metadata:
  820. # metadata indicates fixed size concatenated along dim 0
  821. shard_size = loaded_weight.shape[0]
  822. shard_index = ["q", "k", "v"].index(loaded_shard_id)
  823. param_data = param_data.narrow(0, shard_index * shard_size,
  824. shard_size)
  825. # Special case for per-tensor scales in fused case.
  826. elif needs_scalar_to_array:
  827. param_data, loaded_weight = adjust_scalar_to_fused_array(
  828. param_data, loaded_weight, loaded_shard_id)
  829. else:
  830. ignore_warning = getattr(param, "ignore_warning", False)
  831. if not ignore_warning:
  832. logger.warning(
  833. "Loading a weight without `output_dim` attribute in "
  834. "QKVParallelLinear, assume the weight is the same "
  835. "for all partitions.")
  836. assert param_data.shape == loaded_weight.shape
  837. param_data.copy_(loaded_weight)
  838. class RowParallelLinear(LinearBase):
  839. """Linear layer with row parallelism.
  840. The linear layer is defined as Y = XA + b. A is parallelized along
  841. its first dimension and X along its second dimension as:
  842. - -
  843. | A_1 |
  844. | . |
  845. A = | . | X = [X_1, ..., X_p]
  846. | . |
  847. | A_p |
  848. - -
  849. Arguments:
  850. input_size: first dimension of matrix A.
  851. output_size: second dimension of matrix A.
  852. bias: If true, add bias. Note that bias is not parallelized.
  853. input_is_parallel: If true, we assume that the input is already
  854. split across the GPUs and we do not split
  855. again.
  856. skip_bias_add: This was added to enable performance optimization where
  857. bias can be fused with other element-wise operations.
  858. We skip adding bias but instead return it.
  859. params_dtype: Data type for the parameters.
  860. quant_config: Quantization configure.
  861. partition_multiple_of: Partitions will be divided,
  862. so each partition is a multiple of this number.
  863. """
  864. def __init__(self,
  865. input_size: int,
  866. output_size: int,
  867. bias: bool = True,
  868. input_is_parallel: bool = True,
  869. skip_bias_add: bool = False,
  870. params_dtype: Optional[torch.dtype] = None,
  871. reduce_results: bool = True,
  872. quant_config: Optional[QuantizationConfig] = None,
  873. partition_multiple_of: int = 1,
  874. prefix: str = ""):
  875. super().__init__(input_size, output_size, skip_bias_add, params_dtype,
  876. quant_config, prefix)
  877. self.input_is_parallel = input_is_parallel
  878. self.reduce_results = reduce_results
  879. self.quant_config = quant_config
  880. # Divide the weight matrix along the last dimension.
  881. self.tp_rank = get_tensor_model_parallel_rank()
  882. self.tp_size = get_tensor_model_parallel_world_size()
  883. self.tp_rank = get_tensor_model_parallel_rank()
  884. if quant_config is None:
  885. self.partition_multiple_of = partition_multiple_of
  886. self.input_size_per_partition = get_current_tp_rank_partition_size(
  887. input_size, self.tp_rank, self.tp_size, partition_multiple_of)
  888. else:
  889. self.input_size_per_partition = divide(input_size, self.tp_size)
  890. assert self.quant_method is not None
  891. self.quant_method.create_weights(
  892. layer=self,
  893. input_size_per_partition=self.input_size_per_partition,
  894. output_partition_sizes=[self.output_size],
  895. input_size=self.input_size,
  896. output_size=self.output_size,
  897. params_dtype=self.params_dtype,
  898. weight_loader=(
  899. self.weight_loader_v2 if self.quant_method.__class__.__name__
  900. in WEIGHT_LOADER_V2_SUPPORTED else self.weight_loader),
  901. prefix=prefix)
  902. if not reduce_results and (bias and not skip_bias_add):
  903. raise ValueError("When not reduce the results, adding bias to the "
  904. "results can lead to incorrect results")
  905. if bias:
  906. self.bias = Parameter(
  907. torch.empty(self.output_size, dtype=params_dtype))
  908. set_weight_attrs(self.bias, {
  909. "output_dim": 0,
  910. "weight_loader": self.weight_loader,
  911. })
  912. else:
  913. self.register_parameter("bias", None)
  914. def weight_loader(self, param: Parameter, loaded_weight: torch.Tensor):
  915. tp_size = get_tensor_model_parallel_world_size()
  916. input_dim = getattr(param, "input_dim", None)
  917. # Special case for GGUF
  918. is_gguf_weight = getattr(param, "is_gguf_weight", False)
  919. is_gguf_weight_type = getattr(param, "is_gguf_weight_type", False)
  920. if is_gguf_weight_type:
  921. param.weight_type = loaded_weight.item()
  922. # Materialize GGUF UninitializedParameter
  923. if is_gguf_weight and isinstance(param, UninitializedParameter):
  924. weight_shape = list(loaded_weight.shape)
  925. if input_dim:
  926. weight_shape[input_dim] = weight_shape[input_dim] // tp_size
  927. param.materialize(tuple(weight_shape), dtype=loaded_weight.dtype)
  928. param_data = param.data
  929. if input_dim is not None:
  930. shard_size = param_data.shape[input_dim]
  931. if self.quant_config is None:
  932. start_idx = get_current_tp_rank_partition_offset(
  933. self.input_size,
  934. self.tp_rank,
  935. self.tp_size,
  936. multiple_of=self.partition_multiple_of)
  937. else:
  938. start_idx = self.tp_rank * shard_size
  939. loaded_weight = loaded_weight.narrow(input_dim, start_idx,
  940. shard_size)
  941. # Special case for loading scales off disk, which often do not
  942. # have a shape (such as in the case of AutoFP8).
  943. if len(loaded_weight.shape) == 0:
  944. loaded_weight = loaded_weight.reshape(1)
  945. assert param_data.shape == loaded_weight.shape
  946. param_data.copy_(loaded_weight)
  947. def weight_loader_v2(self, param: BaseAphroditeParameter,
  948. loaded_weight: torch.Tensor):
  949. param.load_row_parallel_weight(loaded_weight=loaded_weight)
  950. def forward(self, input_):
  951. if self.input_is_parallel:
  952. input_parallel = input_
  953. else:
  954. tp_rank = get_tensor_model_parallel_rank()
  955. splitted_input = split_tensor_along_last_dim(
  956. input_, num_partitions=self.tp_size)
  957. input_parallel = splitted_input[tp_rank].contiguous()
  958. # Matrix multiply.
  959. assert self.quant_method is not None
  960. # Only fuse bias add into GEMM for rank 0 (this ensures that
  961. # bias will not get added more than once in TP>1 case)
  962. bias_ = None if (self.tp_rank > 0 or self.skip_bias_add) else self.bias
  963. output_parallel = self.quant_method.apply(self,
  964. input_parallel,
  965. bias=bias_)
  966. if self.reduce_results and self.tp_size > 1:
  967. output = tensor_model_parallel_all_reduce(output_parallel)
  968. else:
  969. output = output_parallel
  970. output_bias = self.bias if self.skip_bias_add else None
  971. return output, output_bias
  972. def extra_repr(self) -> str:
  973. s = f"input_features={self.input_size_per_partition}"
  974. s += f", output_features={self.output_size}"
  975. s += f", bias={self.bias is not None}"
  976. s += f", tp_size={self.tp_size}"
  977. s += f", reduce_results={self.reduce_results}"
  978. return s