_custom_ops.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. import contextlib
  2. import functools
  3. from typing import List, Optional, Tuple, Type
  4. import torch
  5. from loguru import logger
  6. try:
  7. import aphrodite._C
  8. except ImportError as e:
  9. logger.warning(f"Failed to import from aphrodite._C with {e}")
  10. with contextlib.suppress(ImportError):
  11. import aphrodite._moe_C
  12. with contextlib.suppress(ImportError):
  13. # ruff: noqa: F401
  14. import aphrodite._punica_C
  15. def is_custom_op_supported(op_name: str) -> bool:
  16. op, overloads = torch._C._jit_get_operation(op_name)
  17. return op is not None
  18. def hint_on_error(fn):
  19. @functools.wraps(fn)
  20. def wrapper(*args, **kwargs):
  21. try:
  22. return fn(*args, **kwargs)
  23. except AttributeError as e:
  24. msg = (
  25. f"Error in calling custom op {fn.__name__}: {e}\n"
  26. f"Possibly you have built or installed an obsolete version of aphrodite.\n"
  27. f"Please try a clean build and install of aphrodite,"
  28. f"or remove old built files such as aphrodite/*.so and build/ ."
  29. )
  30. logger.error(msg)
  31. raise e
  32. return wrapper
  33. # activation ops
  34. def silu_and_mul(out: torch.Tensor, x: torch.Tensor) -> None:
  35. torch.ops._C.silu_and_mul(out, x)
  36. def gelu_and_mul(out: torch.Tensor, x: torch.Tensor) -> None:
  37. torch.ops._C.gelu_and_mul(out, x)
  38. def gelu_tanh_and_mul(out: torch.Tensor, x: torch.Tensor) -> None:
  39. torch.ops._C.gelu_tanh_and_mul(out, x)
  40. def gelu_fast(out: torch.Tensor, x: torch.Tensor) -> None:
  41. torch.ops._C.gelu_fast(out, x)
  42. def gelu_new(out: torch.Tensor, x: torch.Tensor) -> None:
  43. torch.ops._C.gelu_new(out, x)
  44. # page attention ops
  45. def paged_attention_v1(
  46. out: torch.Tensor,
  47. query: torch.Tensor,
  48. key_cache: torch.Tensor,
  49. value_cache: torch.Tensor,
  50. num_kv_heads: int,
  51. scale: float,
  52. block_tables: torch.Tensor,
  53. seq_lens: torch.Tensor,
  54. block_size: int,
  55. max_seq_len: int,
  56. alibi_slopes: Optional[torch.Tensor],
  57. kv_cache_dtype: str,
  58. kv_scale: float,
  59. tp_rank: int = 0,
  60. blocksparse_local_blocks: int = 0,
  61. blocksparse_vert_stride: int = 0,
  62. blocksparse_block_size: int = 64,
  63. blocksparse_head_sliding_step: int = 0,
  64. ) -> None:
  65. torch.ops._C.paged_attention_v1(
  66. out, query, key_cache, value_cache, num_kv_heads, scale, block_tables,
  67. seq_lens, block_size, max_seq_len, alibi_slopes, kv_cache_dtype,
  68. kv_scale, tp_rank, blocksparse_local_blocks, blocksparse_vert_stride,
  69. blocksparse_block_size, blocksparse_head_sliding_step)
  70. def paged_attention_v2(
  71. out: torch.Tensor,
  72. exp_sum: torch.Tensor,
  73. max_logits: torch.Tensor,
  74. tmp_out: torch.Tensor,
  75. query: torch.Tensor,
  76. key_cache: torch.Tensor,
  77. value_cache: torch.Tensor,
  78. num_kv_heads: int,
  79. scale: float,
  80. block_tables: torch.Tensor,
  81. seq_lens: torch.Tensor,
  82. block_size: int,
  83. max_seq_len: int,
  84. alibi_slopes: Optional[torch.Tensor],
  85. kv_cache_dtype: str,
  86. kv_scale: float,
  87. tp_rank: int = 0,
  88. blocksparse_local_blocks: int = 0,
  89. blocksparse_vert_stride: int = 0,
  90. blocksparse_block_size: int = 64,
  91. blocksparse_head_sliding_step: int = 0,
  92. ) -> None:
  93. torch.ops._C.paged_attention_v2(
  94. out, exp_sum, max_logits, tmp_out, query, key_cache, value_cache,
  95. num_kv_heads, scale, block_tables, seq_lens, block_size, max_seq_len,
  96. alibi_slopes, kv_cache_dtype, kv_scale, tp_rank,
  97. blocksparse_local_blocks, blocksparse_vert_stride,
  98. blocksparse_block_size, blocksparse_head_sliding_step)
  99. # pos encoding ops
  100. def rotary_embedding(
  101. positions: torch.Tensor,
  102. query: torch.Tensor,
  103. key: torch.Tensor,
  104. head_size: int,
  105. cos_sin_cache: torch.Tensor,
  106. is_neox: bool,
  107. ) -> None:
  108. torch.ops._C.rotary_embedding(positions, query, key, head_size,
  109. cos_sin_cache, is_neox)
  110. def batched_rotary_embedding(positions: torch.Tensor, query: torch.Tensor,
  111. key: torch.Tensor, head_size: int,
  112. cos_sin_cache: torch.Tensor, is_neox: bool,
  113. rot_dim: int,
  114. cos_sin_cache_offsets: torch.Tensor) -> None:
  115. torch.ops._C.batched_rotary_embedding(positions, query, key, head_size,
  116. cos_sin_cache, is_neox, rot_dim,
  117. cos_sin_cache_offsets)
  118. # layer norm ops
  119. def rms_norm(out: torch.Tensor, input: torch.Tensor, weight: torch.Tensor,
  120. epsilon: float) -> None:
  121. torch.ops._C.rms_norm(out, input, weight, epsilon)
  122. def fused_add_rms_norm(input: torch.Tensor, residual: torch.Tensor,
  123. weight: torch.Tensor, epsilon: float) -> None:
  124. torch.ops._C.fused_add_rms_norm(input, residual, weight, epsilon)
  125. # quantization ops
  126. # awq
  127. def awq_dequantize(qweight: torch.Tensor, scales: torch.Tensor,
  128. zeros: torch.Tensor, split_k_iters: int, thx: int,
  129. thy: int) -> torch.Tensor:
  130. return torch.ops._C.awq_dequantize(qweight, scales, zeros, split_k_iters,
  131. thx, thy)
  132. def awq_gemm(input: torch.Tensor, qweight: torch.Tensor, qzeros: torch.Tensor,
  133. scales: torch.Tensor, split_k_iters: int) -> torch.Tensor:
  134. return torch.ops._C.awq_gemm(input, qweight, qzeros, scales, split_k_iters)
  135. # gptq
  136. def gptq_gemm(a: torch.Tensor, b_q_weight: torch.Tensor,
  137. b_gptq_qzeros: torch.Tensor, b_gptq_scales: torch.Tensor,
  138. b_g_idx: torch.Tensor, use_exllama: bool,
  139. bit: int) -> torch.Tensor:
  140. return torch.ops._C.gptq_gemm(a, b_q_weight, b_gptq_qzeros, b_gptq_scales,
  141. b_g_idx, use_exllama, bit)
  142. def gptq_shuffle(q_weight: torch.Tensor, q_perm: torch.Tensor,
  143. bit: int) -> None:
  144. torch.ops._C.gptq_shuffle(q_weight, q_perm, bit)
  145. # squeezellm
  146. def squeezellm_gemm(vec: torch.Tensor, mat: torch.Tensor, mul: torch.Tensor,
  147. lookup_table: torch.Tensor) -> None:
  148. torch.ops._C.squeezellm_gemm(vec, mat, mul, lookup_table)
  149. # marlin
  150. def marlin_gemm(a: torch.Tensor, b_q_weight: torch.Tensor,
  151. b_scales: torch.Tensor, workspace: torch.Tensor, size_m: int,
  152. size_n: int, size_k: int) -> torch.Tensor:
  153. return torch.ops._C.marlin_gemm(a, b_q_weight, b_scales, workspace, size_m,
  154. size_n, size_k)
  155. # marlin_24
  156. def gptq_marlin_24_gemm(a: torch.Tensor, b_q_weight: torch.Tensor,
  157. b_meta: torch.Tensor, b_scales: torch.Tensor,
  158. workspace: torch.Tensor, num_bits: int, size_m: int,
  159. size_n: int, size_k: int) -> torch.Tensor:
  160. return torch.ops._C.gptq_marlin_24_gemm(a, b_q_weight, b_meta, b_scales,
  161. workspace, num_bits, size_m,
  162. size_n, size_k)
  163. # cutlass
  164. def cutlass_scaled_mm_dq(a: torch.Tensor, b: torch.Tensor,
  165. scale_a: torch.Tensor, scale_b: torch.Tensor,
  166. out_dtype: Type[torch.dtype]) -> torch.Tensor:
  167. assert (b.shape[0] % 16 == 0 and b.shape[1] % 16 == 0)
  168. assert (out_dtype is torch.bfloat16 or out_dtype is torch.float16)
  169. m = a.shape[0]
  170. n = b.shape[1]
  171. out = torch.empty((m, n), dtype=out_dtype, device=a.device)
  172. torch.ops._C.cutlass_scaled_mm_dq(out, a, b, scale_a, scale_b)
  173. return out
  174. # aqlm
  175. def aqlm_gemm(input: torch.Tensor, codes: torch.Tensor,
  176. codebooks: torch.Tensor, scales: torch.Tensor,
  177. codebook_partition_sizes: torch.Tensor,
  178. bias: Optional[torch.Tensor]) -> torch.Tensor:
  179. return torch.ops._C.aqlm_gemm(input, codes, codebooks, scales,
  180. codebook_partition_sizes, bias)
  181. def aqlm_dequant(codes: torch.Tensor, codebooks: torch.Tensor,
  182. codebook_partition_sizes: torch.Tensor) -> torch.Tensor:
  183. return torch.ops._C.aqlm_dequant(codes, codebooks,
  184. codebook_partition_sizes)
  185. # gptq_marlin
  186. def gptq_marlin_repack(b_q_weight: torch.Tensor, perm: torch.Tensor,
  187. size_k: int, size_n: int,
  188. num_bits: int) -> torch.Tensor:
  189. return torch.ops._C.gptq_marlin_repack(b_q_weight, perm, size_k, size_n,
  190. num_bits)
  191. def gptq_marlin_gemm(a: torch.Tensor, b_q_weight: torch.Tensor,
  192. b_scales: torch.Tensor, g_idx: torch.Tensor,
  193. perm: torch.Tensor, workspace: torch.Tensor,
  194. num_bits: int, size_m: int, size_n: int, size_k: int,
  195. is_k_full: bool) -> torch.Tensor:
  196. return torch.ops._C.gptq_marlin_gemm(a, b_q_weight, b_scales, g_idx, perm,
  197. workspace, num_bits, size_m, size_n,
  198. size_k, is_k_full)
  199. # fp8
  200. def scaled_fp8_quant(
  201. input: torch.Tensor,
  202. scale: Optional[torch.Tensor] = None,
  203. batch_dim_padding: Optional[int] = None,
  204. ) -> Tuple[torch.Tensor, torch.Tensor]:
  205. """
  206. Quantize input tensor to FP8 and return quantized tensor and scale.
  207. This function supports both static and dynamic quantization: If you
  208. provide the scale, it will use static scaling and if you omit it,
  209. the scale will be determined dynamically. The function also allows
  210. optional padding of the output tensor for downstream kernels that
  211. will benefit from padding.
  212. Args:
  213. input: The input tensor to be quantized to FP8
  214. scale: Optional scaling factor for the FP8 quantization
  215. batch_dim_padding: If specified, pad the first dimension
  216. of the output to at least this value.
  217. Returns:
  218. Tuple[torch.Tensor, torch.Tensor]: The output tensor in FP8 and
  219. scaling factor.
  220. """
  221. if batch_dim_padding:
  222. shape = (max(batch_dim_padding, input.shape[0]), *input.shape[1:])
  223. output = torch.empty(shape,
  224. device=input.device,
  225. dtype=torch.float8_e4m3fn)
  226. else:
  227. output = torch.empty_like(input, dtype=torch.float8_e4m3fn)
  228. if scale is None:
  229. scale = torch.zeros(1, device=input.device, dtype=torch.float32)
  230. torch.ops._C.dynamic_scaled_fp8_quant(output, input, scale)
  231. else:
  232. torch.ops._C.static_scaled_fp8_quant(output, input, scale)
  233. return output, scale
  234. # int8
  235. def scaled_int8_quant(
  236. input: torch.Tensor,
  237. scale: Optional[torch.Tensor] = None
  238. ) -> Tuple[torch.Tensor, torch.Tensor]:
  239. """
  240. Quantize the input tensor to int8 and return the quantized tensor and scale.
  241. Args:
  242. input: The input tensor to be quantized to int8.
  243. scale: Optional scaling factor for the int8 quantization.
  244. When not provided, we invoke dynamic-per-token quantization.
  245. Returns:
  246. Tuple[Torch.Tensor, Torch.Tensor] : Output int8 tensor and scales.
  247. """
  248. output = torch.empty_like(input, dtype=torch.int8)
  249. if scale is not None:
  250. # static-per-tensor quantization.
  251. torch.ops._C.static_scaled_int8_quant(output, input, scale)
  252. return output, scale
  253. # dynamic-per-token quantization.
  254. input_scales = torch.empty((input.numel() // input.shape[-1], 1),
  255. device=input.device,
  256. dtype=torch.float32)
  257. torch.ops._C.dynamic_scaled_int8_quant(output, input, input_scales)
  258. return output, input_scales
  259. # quip#
  260. def quip_gemv(
  261. A: torch.Tensor,
  262. B: torch.Tensor,
  263. CB: torch.Tensor,
  264. ) -> torch.Tensor:
  265. return torch.ops._C.quip_gemv(A, B, CB)
  266. def quip_decompress(
  267. YIs: torch.Tensor,
  268. CB: torch.Tensor,
  269. Y: torch.Tensor,
  270. ) -> torch.Tensor:
  271. return torch.ops._C.quip_decompress(YIs, CB, Y)
  272. # moe
  273. def moe_align_block_size(topk_ids: torch.Tensor, num_experts: int,
  274. block_size: int, sorted_token_ids: torch.Tensor,
  275. experts_ids: torch.Tensor,
  276. num_tokens_post_pad: torch.Tensor) -> None:
  277. torch.ops._C.moe_align_block_size(topk_ids, num_experts, block_size,
  278. sorted_token_ids, experts_ids,
  279. num_tokens_post_pad)
  280. def topk_softmax(topk_weights: torch.Tensor, topk_ids: torch.Tensor,
  281. token_expert_indicies: torch.Tensor,
  282. gating_output: float) -> None:
  283. torch.ops._moe_C.topk_softmax(topk_weights, topk_ids,
  284. token_expert_indicies, gating_output)
  285. def reshape_and_cache(
  286. key: torch.Tensor,
  287. value: torch.Tensor,
  288. key_cache: torch.Tensor,
  289. value_cache: torch.Tensor,
  290. slot_mapping: torch.Tensor,
  291. kv_cache_dtype: str,
  292. kv_scale: float,
  293. ) -> None:
  294. torch.ops._C_cache_ops.reshape_and_cache(key, value, key_cache,
  295. value_cache, slot_mapping,
  296. kv_cache_dtype, kv_scale)
  297. def reshape_and_cache_flash(
  298. key: torch.Tensor,
  299. value: torch.Tensor,
  300. key_cache: torch.Tensor,
  301. value_cache: torch.Tensor,
  302. slot_mapping: torch.Tensor,
  303. kv_cache_dtype: str,
  304. ) -> None:
  305. torch.ops._C_cache_ops.reshape_and_cache_flash(key, value, key_cache,
  306. value_cache, slot_mapping,
  307. kv_cache_dtype)
  308. def copy_blocks(key_caches: torch.Tensor, value_caches: torch.Tensor,
  309. block_mapping: torch.Tensor) -> None:
  310. torch.ops._C_cache_ops.copy_blocks(key_caches, value_caches, block_mapping)
  311. def swap_blocks(src: torch.Tensor, dst: torch.Tensor,
  312. block_mapping: torch.Tensor) -> None:
  313. torch.ops._C_cache_ops.swap_blocks(src, dst, block_mapping)
  314. def convert_fp8(output: torch.Tensor,
  315. input: torch.Tensor,
  316. scale: float = 1.0,
  317. kv_dtype: str = "fp8") -> None:
  318. torch.ops._C_cache_ops.convert_fp8(output, input, scale, kv_dtype)
  319. def get_device_attribute(attribute: int, device: int) -> int:
  320. return torch.ops._C_cuda_utils.get_device_attribute(attribute, device)
  321. def get_max_shared_memory_per_block_device_attribute(device: int) -> int:
  322. # ruff: noqa: E501
  323. return torch.ops._C_cuda_utils.get_max_shared_memory_per_block_device_attribute(
  324. device)
  325. # custom ar
  326. def init_custom_ar(meta: torch.Tensor, rank_data: torch.Tensor,
  327. handles: List[str], offsets: List[int], rank: int,
  328. full_nvlink: bool) -> int:
  329. return torch.ops._C_custom_ar.init_custom_ar(meta, rank_data, handles,
  330. offsets, rank, full_nvlink)
  331. def should_custom_ar(inp: torch.Tensor, max_size: int, world_size: int,
  332. full_nvlink: bool) -> bool:
  333. return torch.ops._C_custom_ar.should_custom_ar(inp, max_size, world_size,
  334. full_nvlink)
  335. def all_reduce_reg(fa: int, inp: torch.Tensor, out: torch.Tensor) -> None:
  336. torch.ops._C_custom_ar.all_reduce_reg(fa, inp, out)
  337. def all_reduce_unreg(fa: int, inp: torch.Tensor, reg_buffer: torch.Tensor,
  338. out: torch.Tensor) -> None:
  339. torch.ops._C_custom_ar.all_reduce_unreg(fa, inp, reg_buffer, out)
  340. def dispose(fa: int) -> None:
  341. torch.ops._C_custom_ar.dispose(fa)
  342. def meta_size() -> int:
  343. return torch.ops._C_custom_ar.meta_size()
  344. def register_buffer(fa: int, t: torch.Tensor, handles: List[str],
  345. offsets: List[int]) -> None:
  346. return torch.ops._C_custom_ar.register_buffer(fa, t, handles, offsets)
  347. def get_graph_buffer_ipc_meta(fa: int) -> Tuple[List[str], List[int]]:
  348. return torch.ops._C_custom_ar.get_graph_buffer_ipc_meta(fa)
  349. def register_graph_buffers(fa: int, handles: List[str],
  350. offsets: List[List[int]]) -> None:
  351. torch.ops._C_custom_ar.register_graph_buffers(fa, handles, offsets)
  352. # punica
  353. def dispatch_bgmv(
  354. y: torch.Tensor,
  355. x: torch.Tensor,
  356. w_t_all: torch.Tensor,
  357. indicies: torch.Tensor,
  358. layer_idx: int,
  359. scale: float,
  360. ) -> None:
  361. torch.ops._punica_C.dispatch_bgmv(y, x, w_t_all, indicies, layer_idx,
  362. scale)
  363. def dispatch_bgmv_low_level(
  364. y: torch.Tensor,
  365. x: torch.Tensor,
  366. w_t_all: torch.Tensor,
  367. indicies: torch.Tensor,
  368. layer_idx: int,
  369. scale: float,
  370. h_in: int,
  371. h_out: int,
  372. y_offset: int,
  373. ) -> None:
  374. torch.ops._punica_C.dispatch_bgmv_low_level(
  375. y,
  376. x,
  377. w_t_all,
  378. indicies,
  379. layer_idx,
  380. scale,
  381. h_in,
  382. h_out,
  383. y_offset,
  384. )
  385. # TODO: remove this later
  386. names_and_values = globals()
  387. names_and_values_to_update = {}
  388. # prepare variables to avoid dict size change during iteration
  389. k, v, arg = None, None, None
  390. fn_type = type(lambda x: x)
  391. for k, v in names_and_values.items():
  392. # find functions that are defined in this file and have torch.Tensor
  393. # in their annotations. `arg == "torch.Tensor"` is used to handle
  394. # the case when users use `import __annotations__` to turn type
  395. # hints into strings.
  396. if isinstance(v, fn_type) \
  397. and v.__code__.co_filename == __file__ \
  398. and any(arg is torch.Tensor or arg == "torch.Tensor"
  399. for arg in v.__annotations__.values()):
  400. names_and_values_to_update[k] = hint_on_error(v)
  401. names_and_values.update(names_and_values_to_update)
  402. del names_and_values_to_update, names_and_values, v, k, fn_type