_custom_ops.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. import contextlib
  2. import functools
  3. from typing import List, Optional, Tuple, Type, Union
  4. import torch
  5. from loguru import logger
  6. from aphrodite._core_ext import ScalarType
  7. from aphrodite.common.utils import is_hip
  8. from aphrodite.platforms import current_platform
  9. if not current_platform.is_tpu():
  10. try:
  11. import aphrodite._C
  12. except ImportError as e:
  13. logger.warning(f"Failed to import from aphrodite._C with {e}")
  14. if current_platform.is_cuda():
  15. try:
  16. import aphrodite._hadamard_C
  17. except ImportError as e:
  18. logger.warning(f"Failed to import from aphrodite._hadamard_C with {e}")
  19. with contextlib.suppress(ImportError):
  20. # ruff: noqa: F401
  21. import aphrodite._moe_C
  22. def hint_on_error(fn):
  23. @functools.wraps(fn)
  24. def wrapper(*args, **kwargs):
  25. try:
  26. return fn(*args, **kwargs)
  27. except AttributeError as e:
  28. msg = (
  29. f"Error in calling custom op {fn.__name__}: {e}\n"
  30. f"Possibly you have built or installed an obsolete version of aphrodite.\n"
  31. f"Please try a clean build and install of aphrodite,"
  32. f"or remove old built files such as aphrodite/*.so and build/ ."
  33. )
  34. logger.error(msg)
  35. raise e
  36. return wrapper
  37. # activation ops
  38. def silu_and_mul(out: torch.Tensor, x: torch.Tensor) -> None:
  39. torch.ops._C.silu_and_mul(out, x)
  40. def gelu_and_mul(out: torch.Tensor, x: torch.Tensor) -> None:
  41. torch.ops._C.gelu_and_mul(out, x)
  42. def gelu_tanh_and_mul(out: torch.Tensor, x: torch.Tensor) -> None:
  43. torch.ops._C.gelu_tanh_and_mul(out, x)
  44. def gelu_fast(out: torch.Tensor, x: torch.Tensor) -> None:
  45. torch.ops._C.gelu_fast(out, x)
  46. def gelu_new(out: torch.Tensor, x: torch.Tensor) -> None:
  47. torch.ops._C.gelu_new(out, x)
  48. def gelu_quick(out: torch.Tensor, x: torch.Tensor) -> None:
  49. torch.ops._C.gelu_quick(out, x)
  50. # page attention ops
  51. def paged_attention_v1(
  52. out: torch.Tensor,
  53. query: torch.Tensor,
  54. key_cache: torch.Tensor,
  55. value_cache: torch.Tensor,
  56. num_kv_heads: int,
  57. scale: float,
  58. block_tables: torch.Tensor,
  59. seq_lens: torch.Tensor,
  60. block_size: int,
  61. max_seq_len: int,
  62. alibi_slopes: Optional[torch.Tensor],
  63. kv_cache_dtype: str,
  64. k_scale: float,
  65. v_scale: float,
  66. tp_rank: int = 0,
  67. blocksparse_local_blocks: int = 0,
  68. blocksparse_vert_stride: int = 0,
  69. blocksparse_block_size: int = 64,
  70. blocksparse_head_sliding_step: int = 0,
  71. ) -> None:
  72. torch.ops._C.paged_attention_v1(
  73. out, query, key_cache, value_cache, num_kv_heads, scale, block_tables,
  74. seq_lens, block_size, max_seq_len, alibi_slopes, kv_cache_dtype,
  75. k_scale, v_scale, tp_rank, blocksparse_local_blocks,
  76. blocksparse_vert_stride, blocksparse_block_size,
  77. blocksparse_head_sliding_step)
  78. def paged_attention_v2(
  79. out: torch.Tensor,
  80. exp_sum: torch.Tensor,
  81. max_logits: torch.Tensor,
  82. tmp_out: torch.Tensor,
  83. query: torch.Tensor,
  84. key_cache: torch.Tensor,
  85. value_cache: torch.Tensor,
  86. num_kv_heads: int,
  87. scale: float,
  88. block_tables: torch.Tensor,
  89. seq_lens: torch.Tensor,
  90. block_size: int,
  91. max_seq_len: int,
  92. alibi_slopes: Optional[torch.Tensor],
  93. kv_cache_dtype: str,
  94. k_scale: float,
  95. v_scale: float,
  96. tp_rank: int = 0,
  97. blocksparse_local_blocks: int = 0,
  98. blocksparse_vert_stride: int = 0,
  99. blocksparse_block_size: int = 64,
  100. blocksparse_head_sliding_step: int = 0,
  101. ) -> None:
  102. torch.ops._C.paged_attention_v2(
  103. out, exp_sum, max_logits, tmp_out, query, key_cache, value_cache,
  104. num_kv_heads, scale, block_tables, seq_lens, block_size, max_seq_len,
  105. alibi_slopes, kv_cache_dtype, k_scale, v_scale, tp_rank,
  106. blocksparse_local_blocks, blocksparse_vert_stride,
  107. blocksparse_block_size, blocksparse_head_sliding_step)
  108. # pos encoding ops
  109. def rotary_embedding(
  110. positions: torch.Tensor,
  111. query: torch.Tensor,
  112. key: torch.Tensor,
  113. head_size: int,
  114. cos_sin_cache: torch.Tensor,
  115. is_neox: bool,
  116. ) -> None:
  117. torch.ops._C.rotary_embedding(positions, query, key, head_size,
  118. cos_sin_cache, is_neox)
  119. def batched_rotary_embedding(positions: torch.Tensor, query: torch.Tensor,
  120. key: torch.Tensor, head_size: int,
  121. cos_sin_cache: torch.Tensor, is_neox: bool,
  122. rot_dim: int,
  123. cos_sin_cache_offsets: torch.Tensor) -> None:
  124. torch.ops._C.batched_rotary_embedding(positions, query, key, head_size,
  125. cos_sin_cache, is_neox, rot_dim,
  126. cos_sin_cache_offsets)
  127. # layer norm ops
  128. def rms_norm(out: torch.Tensor, input: torch.Tensor, weight: torch.Tensor,
  129. epsilon: float) -> None:
  130. torch.ops._C.rms_norm(out, input, weight, epsilon)
  131. def fused_add_rms_norm(input: torch.Tensor, residual: torch.Tensor,
  132. weight: torch.Tensor, epsilon: float) -> None:
  133. torch.ops._C.fused_add_rms_norm(input, residual, weight, epsilon)
  134. def advance_step(num_seqs: int, num_queries: int, block_size: int,
  135. input_tokens: torch.Tensor, sampled_token_ids: torch.Tensor,
  136. input_positions: torch.Tensor, seq_lens: torch.Tensor,
  137. slot_mapping: torch.Tensor,
  138. block_tables: torch.Tensor) -> None:
  139. """Advance a step on GPU for existing inputs for a multi-step runner"""
  140. return torch.ops._C.advance_step(num_seqs, num_queries, block_size,
  141. input_tokens, sampled_token_ids,
  142. input_positions, seq_lens, slot_mapping,
  143. block_tables)
  144. # quantization ops
  145. # awq
  146. def awq_dequantize(qweight: torch.Tensor, scales: torch.Tensor,
  147. zeros: torch.Tensor, split_k_iters: int, thx: int,
  148. thy: int) -> torch.Tensor:
  149. return torch.ops._C.awq_dequantize(qweight, scales, zeros, split_k_iters,
  150. thx, thy)
  151. def awq_gemm(input: torch.Tensor, qweight: torch.Tensor, qzeros: torch.Tensor,
  152. scales: torch.Tensor, split_k_iters: int) -> torch.Tensor:
  153. return torch.ops._C.awq_gemm(input, qweight, qzeros, scales, split_k_iters)
  154. # gptq
  155. def gptq_gemm(a: torch.Tensor, b_q_weight: torch.Tensor,
  156. b_gptq_qzeros: torch.Tensor, b_gptq_scales: torch.Tensor,
  157. b_g_idx: torch.Tensor, use_exllama: bool,
  158. bit: int) -> torch.Tensor:
  159. return torch.ops._C.gptq_gemm(a, b_q_weight, b_gptq_qzeros, b_gptq_scales,
  160. b_g_idx, use_exllama, bit)
  161. def gptq_shuffle(q_weight: torch.Tensor, q_perm: torch.Tensor,
  162. bit: int) -> None:
  163. torch.ops._C.gptq_shuffle(q_weight, q_perm, bit)
  164. # squeezellm
  165. def squeezellm_gemm(vec: torch.Tensor, mat: torch.Tensor, mul: torch.Tensor,
  166. lookup_table: torch.Tensor) -> None:
  167. torch.ops._C.squeezellm_gemm(vec, mat, mul, lookup_table)
  168. # marlin
  169. def marlin_gemm(a: torch.Tensor, b_q_weight: torch.Tensor,
  170. b_scales: torch.Tensor, workspace: torch.Tensor, size_m: int,
  171. size_n: int, size_k: int) -> torch.Tensor:
  172. return torch.ops._C.marlin_gemm(a, b_q_weight, b_scales, workspace, size_m,
  173. size_n, size_k)
  174. # marlin_24
  175. def gptq_marlin_24_gemm(a: torch.Tensor, b_q_weight: torch.Tensor,
  176. b_meta: torch.Tensor, b_scales: torch.Tensor,
  177. workspace: torch.Tensor, b_q_type: ScalarType,
  178. size_m: int, size_n: int, size_k: int) -> torch.Tensor:
  179. return torch.ops._C.gptq_marlin_24_gemm(a, b_q_weight, b_meta, b_scales,
  180. workspace, b_q_type, size_m,
  181. size_n, size_k)
  182. # fp8 marlin
  183. def fp8_marlin_gemm(a: torch.Tensor, b_q_weight: torch.Tensor,
  184. b_scales: torch.Tensor, workspace: torch.Tensor,
  185. num_bits: int, size_m: int, size_n: int,
  186. size_k: int) -> torch.Tensor:
  187. return torch.ops._C.fp8_marlin_gemm(a, b_q_weight, b_scales, workspace,
  188. num_bits, size_m, size_n, size_k)
  189. # cutlass
  190. def cutlass_scaled_mm_supports_fp8(cuda_device_capability: int) -> bool:
  191. return torch.ops._C.cutlass_scaled_mm_supports_fp8(cuda_device_capability)
  192. def cutlass_scaled_mm(a: torch.Tensor,
  193. b: torch.Tensor,
  194. scale_a: torch.Tensor,
  195. scale_b: torch.Tensor,
  196. out_dtype: Type[torch.dtype],
  197. bias: Optional[torch.Tensor] = None) -> torch.Tensor:
  198. assert (b.shape[0] % 16 == 0 and b.shape[1] % 16 == 0)
  199. assert (out_dtype is torch.bfloat16 or out_dtype is torch.float16)
  200. assert bias is None or bias.shape[0] == b.shape[
  201. 1] and bias.dtype == out_dtype
  202. m = a.shape[0]
  203. n = b.shape[1]
  204. out = torch.empty((m, n), dtype=out_dtype, device=a.device)
  205. torch.ops._C.cutlass_scaled_mm(out, a, b, scale_a, scale_b, bias)
  206. return out
  207. def cutlass_scaled_mm_azp(a: torch.Tensor,
  208. b: torch.Tensor,
  209. scale_a: torch.Tensor,
  210. scale_b: torch.Tensor,
  211. out_dtype: torch.dtype,
  212. azp_adj: torch.Tensor,
  213. azp: Optional[torch.Tensor] = None,
  214. bias: Optional[torch.Tensor] = None) -> torch.Tensor:
  215. assert (b.shape[0] % 16 == 0 and b.shape[1] % 16 == 0)
  216. assert (out_dtype is torch.bfloat16 or out_dtype is torch.float16)
  217. assert bias is None or bias.numel(
  218. ) == b.shape[1] and bias.dtype == out_dtype
  219. m = a.shape[0]
  220. n = b.shape[1]
  221. out = torch.empty((m, n), dtype=out_dtype, device=a.device)
  222. torch.ops._C.cutlass_scaled_mm_azp(out, a, b, scale_a, scale_b, azp_adj,
  223. azp, bias)
  224. return out
  225. # aqlm
  226. def aqlm_gemm(input: torch.Tensor, codes: torch.Tensor,
  227. codebooks: torch.Tensor, scales: torch.Tensor,
  228. codebook_partition_sizes: List[int],
  229. bias: Optional[torch.Tensor]) -> torch.Tensor:
  230. return torch.ops._C.aqlm_gemm(input, codes, codebooks, scales,
  231. codebook_partition_sizes, bias)
  232. def aqlm_dequant(codes: torch.Tensor, codebooks: torch.Tensor,
  233. codebook_partition_sizes: List[int]) -> torch.Tensor:
  234. return torch.ops._C.aqlm_dequant(codes, codebooks,
  235. codebook_partition_sizes)
  236. # gptq_marlin
  237. def gptq_marlin_repack(b_q_weight: torch.Tensor, perm: torch.Tensor,
  238. size_k: int, size_n: int,
  239. num_bits: int) -> torch.Tensor:
  240. return torch.ops._C.gptq_marlin_repack(b_q_weight, perm, size_k, size_n,
  241. num_bits)
  242. def awq_marlin_repack(b_q_weight: torch.Tensor, size_k: int, size_n: int,
  243. num_bits: int) -> torch.Tensor:
  244. return torch.ops._C.awq_marlin_repack(b_q_weight, size_k, size_n, num_bits)
  245. def gptq_marlin_gemm(a: torch.Tensor,
  246. b_q_weight: torch.Tensor,
  247. b_scales: torch.Tensor,
  248. b_zeros: torch.Tensor,
  249. g_idx: torch.Tensor,
  250. perm: torch.Tensor,
  251. workspace: torch.Tensor,
  252. b_q_type: ScalarType,
  253. size_m: int,
  254. size_n: int,
  255. size_k: int,
  256. is_k_full: bool,
  257. has_zp: bool = False,
  258. use_fp32_reduce: bool = False,
  259. is_zp_float: bool = False) -> torch.Tensor:
  260. return torch.ops._C.gptq_marlin_gemm(a, b_q_weight, b_scales, b_zeros,
  261. g_idx, perm, workspace, b_q_type,
  262. size_m, size_n, size_k, is_k_full,
  263. has_zp, use_fp32_reduce,
  264. is_zp_float)
  265. # machete
  266. def machete_supported_schedules(b_type: ScalarType) -> List[str]:
  267. return torch.ops._C.machete_supported_schedules(b_type)
  268. def machete_gemm(
  269. a: torch.Tensor,
  270. b_q: torch.Tensor, # Should be the tensor returned by machete_prepack_B
  271. b_type: ScalarType,
  272. b_scales: Optional[torch.Tensor] = None,
  273. b_zeros: Optional[torch.Tensor] = None,
  274. b_group_size: Optional[int] = None,
  275. c: Optional[torch.Tensor] = None,
  276. alpha: Optional[float] = None,
  277. beta: Optional[float] = None,
  278. schedule: Optional[str] = None,
  279. ) -> torch.Tensor:
  280. return torch.ops._C.machete_gemm(a, b_q, b_type, b_scales, b_zeros,
  281. b_group_size, c, alpha, beta, schedule)
  282. def machete_prepack_B(b_q_weight: torch.Tensor,
  283. b_type: ScalarType) -> torch.Tensor:
  284. return torch.ops._C.machete_prepack_B(b_q_weight, b_type)
  285. def permute_cols(a: torch.Tensor, perm: torch.Tensor) -> torch.Tensor:
  286. return torch.ops._C.permute_cols(a, perm)
  287. # fp8
  288. def scaled_fp8_quant(
  289. input: torch.Tensor,
  290. scale: Optional[torch.Tensor] = None,
  291. num_token_padding: Optional[int] = None,
  292. scale_ub: Optional[torch.Tensor] = None,
  293. use_per_token_if_dynamic: bool = False,
  294. ) -> Tuple[torch.Tensor, torch.Tensor]:
  295. """
  296. Quantize input tensor to FP8 and return quantized tensor and scale.
  297. This function supports both static and dynamic quantization: If you
  298. provide the scale, it will use static scaling and if you omit it,
  299. the scale will be determined dynamically. The function also allows
  300. optional padding of the output tensors for downstream kernels that
  301. will benefit from padding.
  302. Args:
  303. input: The input tensor to be quantized to FP8
  304. scale: Optional scaling factor for the FP8 quantization
  305. num_token_padding: If specified, pad the first dimension
  306. of the output to at least this value.
  307. use_per_token_if_dynamic: Whether to do per_tensor or per_token
  308. in the dynamic quantization case.
  309. Returns:
  310. Tuple[torch.Tensor, torch.Tensor]: The output tensor in FP8 and
  311. scaling factor.
  312. """
  313. # This code assumes batch_dim and num_tokens are flattened
  314. assert (input.ndim == 2)
  315. shape = input.shape
  316. # For rocm, the output fp8 dtype is torch.float_e3m3fnuz
  317. out_dtype: torch.dtype = torch.float8_e4m3fnuz if \
  318. is_hip() else torch.float8_e4m3fn
  319. if num_token_padding:
  320. shape = (max(num_token_padding, input.shape[0]), shape[1])
  321. output = torch.empty(shape, device=input.device, dtype=out_dtype)
  322. if scale is None:
  323. if use_per_token_if_dynamic:
  324. scale = torch.empty((shape[0], 1),
  325. device=input.device,
  326. dtype=torch.float32)
  327. torch.ops._C.dynamic_per_token_scaled_fp8_quant(
  328. output, input, scale, scale_ub)
  329. else:
  330. scale = torch.zeros(1, device=input.device, dtype=torch.float32)
  331. torch.ops._C.dynamic_scaled_fp8_quant(output, input, scale)
  332. else:
  333. # num_token_padding not implemented for this case
  334. assert (scale.numel() == 1 or num_token_padding is None)
  335. torch.ops._C.static_scaled_fp8_quant(output, input, scale)
  336. return output, scale
  337. # int8
  338. def scaled_int8_quant(
  339. input: torch.Tensor,
  340. scale: Optional[torch.Tensor] = None
  341. ) -> Tuple[torch.Tensor, torch.Tensor]:
  342. """
  343. Quantize the input tensor to int8 and return the quantized tensor and scale.
  344. Args:
  345. input: The input tensor to be quantized to int8.
  346. scale: Optional scaling factor for the int8 quantization.
  347. When not provided, we invoke dynamic-per-token quantization.
  348. Returns:
  349. Tuple[Torch.Tensor, Torch.Tensor] : Output int8 tensor and scales.
  350. """
  351. output = torch.empty_like(input, dtype=torch.int8)
  352. if scale is not None:
  353. # static-per-tensor quantization.
  354. torch.ops._C.static_scaled_int8_quant(output, input, scale)
  355. return output, scale
  356. # dynamic-per-token quantization.
  357. input_scales = torch.empty((input.numel() // input.shape[-1], 1),
  358. device=input.device,
  359. dtype=torch.float32)
  360. torch.ops._C.dynamic_scaled_int8_quant(output, input, input_scales)
  361. return output, input_scales
  362. # quip#
  363. def quip_gemv(
  364. A: torch.Tensor,
  365. B: torch.Tensor,
  366. CB: torch.Tensor,
  367. ) -> torch.Tensor:
  368. return torch.ops._C.quip_gemv(A, B, CB)
  369. def quip_decompress(
  370. YIs: torch.Tensor,
  371. CB: torch.Tensor,
  372. Y: torch.Tensor,
  373. ) -> torch.Tensor:
  374. return torch.ops._C.quip_decompress(YIs, CB, Y)
  375. # qqq ops
  376. def marlin_qqq_gemm(a: torch.Tensor, b_q_weight: torch.Tensor,
  377. s_tok: torch.Tensor, s_ch: torch.Tensor,
  378. s_group: torch.Tensor, workspace: torch.Tensor,
  379. size_m: int, size_n: int, size_k: int) -> torch.Tensor:
  380. return torch.ops._C.marlin_qqq_gemm(a, b_q_weight, s_tok, s_ch, s_group,
  381. workspace, size_m, size_n, size_k)
  382. # gguf
  383. def ggml_dequantize(W: torch.Tensor, quant_type: int, m: int,
  384. n: int) -> torch.Tensor:
  385. return torch.ops._C.ggml_dequantize(W, quant_type, m, n)
  386. def ggml_mul_mat_vec_a8(
  387. W: torch.Tensor,
  388. X: torch.Tensor,
  389. quant_type: int,
  390. row: int,
  391. ) -> torch.Tensor:
  392. return torch.ops._C.ggml_mul_mat_vec_a8(W, X, quant_type, row)
  393. def ggml_mul_mat_a8(
  394. W: torch.Tensor,
  395. X: torch.Tensor,
  396. quant_type: int,
  397. row: int,
  398. ) -> torch.Tensor:
  399. return torch.ops._C.ggml_mul_mat_a8(W, X, quant_type, row)
  400. # fp6
  401. def fp_eXmY_linear_forward_cuda(
  402. EXPONENT: int,
  403. MANTISSA: int,
  404. _in_feats: torch.Tensor,
  405. _weights: torch.Tensor,
  406. _scales: torch.Tensor,
  407. splitK: int = 1,
  408. ) -> torch.Tensor:
  409. return torch.ops._C.fp_eXmY_linear_forward_cuda(EXPONENT, MANTISSA,
  410. _in_feats, _weights,
  411. _scales, splitK)
  412. # mamba
  413. def causal_conv1d_fwd(x: torch.Tensor, weight: torch.Tensor,
  414. bias_: Optional[torch.Tensor],
  415. seq_idx_: Optional[torch.Tensor],
  416. initial_states_: Optional[torch.Tensor],
  417. final_states_out_: Optional[torch.Tensor],
  418. silu_activation: bool) -> torch.Tensor:
  419. return torch.ops._C.causal_conv1d_fwd(x, weight, bias_, seq_idx_, None,
  420. initial_states_, final_states_out_,
  421. silu_activation)
  422. def causal_conv1d_update(x: torch.Tensor, conv_state: torch.Tensor,
  423. weight: torch.Tensor, bias_: Optional[torch.Tensor],
  424. silu_activation: bool) -> torch.Tensor:
  425. return torch.ops._C.causal_conv1d_update(x, conv_state, weight, bias_,
  426. silu_activation)
  427. def selective_scan_fwd(u: torch.Tensor, delta: torch.Tensor, A: torch.Tensor,
  428. B: torch.Tensor, C: torch.Tensor,
  429. D_: Optional[torch.Tensor], z_: Optional[torch.Tensor],
  430. delta_bias_: Optional[torch.Tensor],
  431. delta_softplus: bool, index_: Optional[torch.Tensor],
  432. x: Optional[torch.Tensor]) -> List[torch.Tensor]:
  433. return torch.ops._C.selective_scan_fwd(u, delta, A, B, C, D_, z_,
  434. delta_bias_, delta_softplus, index_,
  435. x)
  436. # moe
  437. def moe_align_block_size(topk_ids: torch.Tensor, num_experts: int,
  438. block_size: int, sorted_token_ids: torch.Tensor,
  439. experts_ids: torch.Tensor,
  440. num_tokens_post_pad: torch.Tensor) -> None:
  441. torch.ops._C.moe_align_block_size(topk_ids, num_experts, block_size,
  442. sorted_token_ids, experts_ids,
  443. num_tokens_post_pad)
  444. def topk_softmax(topk_weights: torch.Tensor, topk_ids: torch.Tensor,
  445. token_expert_indicies: torch.Tensor,
  446. gating_output: float) -> None:
  447. torch.ops._moe_C.topk_softmax(topk_weights, topk_ids,
  448. token_expert_indicies, gating_output)
  449. def reshape_and_cache(
  450. key: torch.Tensor,
  451. value: torch.Tensor,
  452. key_cache: torch.Tensor,
  453. value_cache: torch.Tensor,
  454. slot_mapping: torch.Tensor,
  455. kv_cache_dtype: str,
  456. k_scale: float,
  457. v_scale: float,
  458. ) -> None:
  459. torch.ops._C_cache_ops.reshape_and_cache(key, value, key_cache,
  460. value_cache, slot_mapping,
  461. kv_cache_dtype, k_scale, v_scale)
  462. def reshape_and_cache_flash(
  463. key: torch.Tensor,
  464. value: torch.Tensor,
  465. key_cache: torch.Tensor,
  466. value_cache: torch.Tensor,
  467. slot_mapping: torch.Tensor,
  468. kv_cache_dtype: str,
  469. k_scale: float,
  470. v_scale: float,
  471. ) -> None:
  472. torch.ops._C_cache_ops.reshape_and_cache_flash(key, value, key_cache,
  473. value_cache, slot_mapping,
  474. kv_cache_dtype, k_scale,
  475. v_scale)
  476. def copy_blocks(key_caches: List[torch.Tensor],
  477. value_caches: List[torch.Tensor],
  478. block_mapping: torch.Tensor) -> None:
  479. torch.ops._C_cache_ops.copy_blocks(key_caches, value_caches, block_mapping)
  480. def swap_blocks(src: torch.Tensor, dst: torch.Tensor,
  481. block_mapping: torch.Tensor) -> None:
  482. torch.ops._C_cache_ops.swap_blocks(src, dst, block_mapping)
  483. def convert_fp8(output: torch.Tensor,
  484. input: torch.Tensor,
  485. scale: float = 1.0,
  486. kv_dtype: str = "fp8") -> None:
  487. torch.ops._C_cache_ops.convert_fp8(output, input, scale, kv_dtype)
  488. def get_device_attribute(attribute: int, device: int) -> int:
  489. return torch.ops._C_cuda_utils.get_device_attribute(attribute, device)
  490. def get_max_shared_memory_per_block_device_attribute(device: int) -> int:
  491. # ruff: noqa: E501
  492. return torch.ops._C_cuda_utils.get_max_shared_memory_per_block_device_attribute(
  493. device)
  494. # custom ar
  495. def init_custom_ar(meta: torch.Tensor, rank_data: torch.Tensor,
  496. handles: List[str], offsets: List[int], rank: int,
  497. full_nvlink: bool) -> int:
  498. return torch.ops._C_custom_ar.init_custom_ar(meta, rank_data, handles,
  499. offsets, rank, full_nvlink)
  500. def should_custom_ar(inp: torch.Tensor, max_size: int, world_size: int,
  501. full_nvlink: bool) -> bool:
  502. return torch.ops._C_custom_ar.should_custom_ar(inp, max_size, world_size,
  503. full_nvlink)
  504. def all_reduce_reg(fa: int, inp: torch.Tensor, out: torch.Tensor) -> None:
  505. torch.ops._C_custom_ar.all_reduce_reg(fa, inp, out)
  506. def all_reduce_unreg(fa: int, inp: torch.Tensor, reg_buffer: torch.Tensor,
  507. out: torch.Tensor) -> None:
  508. torch.ops._C_custom_ar.all_reduce_unreg(fa, inp, reg_buffer, out)
  509. def dispose(fa: int) -> None:
  510. torch.ops._C_custom_ar.dispose(fa)
  511. def meta_size() -> int:
  512. return torch.ops._C_custom_ar.meta_size()
  513. def register_buffer(fa: int, t: torch.Tensor, handles: List[str],
  514. offsets: List[int]) -> None:
  515. return torch.ops._C_custom_ar.register_buffer(fa, t, handles, offsets)
  516. def get_graph_buffer_ipc_meta(fa: int) -> Tuple[List[str], List[int]]:
  517. return torch.ops._C_custom_ar.get_graph_buffer_ipc_meta(fa)
  518. def register_graph_buffers(fa: int, handles: List[str],
  519. offsets: List[List[int]]) -> None:
  520. torch.ops._C_custom_ar.register_graph_buffers(fa, handles, offsets)
  521. # Sampling Kernels
  522. def sampling_from_probs(probs: torch.Tensor,
  523. uniform_samplers: torch.Tensor,
  524. deterministic: bool = True,
  525. check_nan: bool = False) -> torch.Tensor:
  526. if check_nan and torch.any(torch.isnan(probs)):
  527. raise ValueError("NaN detected in probs")
  528. return torch.ops._C.sampling_from_probs(probs, uniform_samplers,
  529. deterministic)
  530. def _to_tensor_scalar_tuple(x):
  531. if isinstance(x, torch.Tensor):
  532. return (x, 0)
  533. else:
  534. return (None, x)
  535. def top_p_sampling_from_probs(
  536. probs: torch.Tensor,
  537. uniform_samples: torch.Tensor,
  538. top_p: Union[torch.Tensor, float],
  539. deterministic: bool = True,
  540. check_nan: bool = False) -> Tuple[torch.Tensor, torch.Tensor]:
  541. if check_nan and torch.any(torch.isnan(probs)):
  542. raise ValueError("NaN detected in probs")
  543. return torch.ops._C.top_p_sampling_from_probs(
  544. probs, uniform_samples, *_to_tensor_scalar_tuple(top_p), deterministic)
  545. def top_k_sampling_from_probs(
  546. probs: torch.Tensor,
  547. uniform_samples: torch.Tensor,
  548. top_k: Union[torch.Tensor, int],
  549. deterministic: bool = True,
  550. check_nan: bool = False) -> Tuple[torch.Tensor, torch.Tensor]:
  551. if check_nan and torch.any(torch.isnan(probs)):
  552. raise ValueError("NaN detected in probs")
  553. return torch.ops._C.top_k_sampling_from_probs(
  554. probs, uniform_samples, *_to_tensor_scalar_tuple(top_k), deterministic)
  555. def min_p_sampling_from_probs(
  556. probs: torch.Tensor,
  557. uniform_samples: torch.Tensor,
  558. min_p: Union[torch.Tensor, float],
  559. deterministic: bool = True,
  560. check_nan: bool = False) -> Tuple[torch.Tensor, torch.Tensor]:
  561. if check_nan and torch.any(torch.isnan(probs)):
  562. raise ValueError("NaN detected in probs")
  563. return torch.ops._C.min_p_sampling_from_probs(
  564. probs, uniform_samples, *_to_tensor_scalar_tuple(min_p), deterministic)
  565. def top_k_mask_logits(
  566. logits: torch.Tensor,
  567. top_k: Union[torch.Tensor, int],
  568. ) -> torch.Tensor:
  569. return torch.ops._C.top_k_mask_logits(logits,
  570. *_to_tensor_scalar_tuple(top_k))
  571. def top_p_renorm_prob(
  572. probs: torch.Tensor,
  573. top_p: Union[torch.Tensor, float],
  574. ) -> torch.Tensor:
  575. return torch.ops._C.top_p_renorm_prob(probs,
  576. *_to_tensor_scalar_tuple(top_p))
  577. def top_k_renorm_prob(
  578. probs: torch.Tensor,
  579. top_k: Union[torch.Tensor, int],
  580. ) -> torch.Tensor:
  581. return torch.ops._C.top_k_renorm_prob(probs,
  582. *_to_tensor_scalar_tuple(top_k))
  583. def top_k_top_p_sampling_from_logits(
  584. probs: torch.Tensor,
  585. uniform_samples: torch.Tensor,
  586. top_k: Union[torch.Tensor, int],
  587. top_p: Union[torch.Tensor, float],
  588. filter_apply_order: str = "top_k_first",
  589. deterministic: bool = True,
  590. check_nan: bool = False,
  591. ) -> Tuple[torch.Tensor, torch.Tensor]:
  592. if filter_apply_order == "top_k_first":
  593. masked_logits = top_k_mask_logits(probs, top_k)
  594. probs = torch.softmax(masked_logits, dim=-1)
  595. return top_p_sampling_from_probs(probs, uniform_samples, top_p,
  596. deterministic, check_nan)
  597. elif filter_apply_order == "joint":
  598. probs = torch.softmax(probs, dim=-1)
  599. if check_nan and torch.any(torch.isnan(probs)):
  600. raise ValueError("NaN detected in probs")
  601. return torch.ops._C.top_k_top_p_sampling_from_logits(
  602. probs, uniform_samples, *_to_tensor_scalar_tuple(top_k),
  603. *_to_tensor_scalar_tuple(top_p), deterministic)
  604. else:
  605. raise ValueError(f"Invalid filter_apply_order: {filter_apply_order}")
  606. def top_k_top_p_sampling_from_probs(
  607. probs: torch.Tensor,
  608. uniform_samples: torch.Tensor,
  609. top_k: Union[torch.Tensor, int],
  610. top_p: Union[torch.Tensor, float],
  611. filter_apply_order: str = "top_k_first",
  612. deterministic: bool = True,
  613. check_nan: bool = False,
  614. ) -> Tuple[torch.Tensor, torch.Tensor]:
  615. if filter_apply_order == "top_k_first":
  616. renorm_probs = top_k_renorm_prob(probs, top_k)
  617. return top_p_sampling_from_probs(renorm_probs, uniform_samples, top_p,
  618. deterministic, check_nan)
  619. elif filter_apply_order == "joint":
  620. if check_nan and torch.any(torch.isnan(probs)):
  621. raise ValueError("NaN detected in probs")
  622. return torch.ops._C.top_k_top_p_sampling_from_probs(
  623. probs, uniform_samples, *_to_tensor_scalar_tuple(top_k),
  624. *_to_tensor_scalar_tuple(top_p), deterministic)
  625. else:
  626. raise ValueError(f"Invalid filter_apply_order: {filter_apply_order}")
  627. # hadamard
  628. # def fast_hadamard_transform(x: torch.Tensor, scale: float) -> torch.Tensor:
  629. # return torch.ops._C_hadamard.fast_hadamard_transform(x, scale)
  630. # def fast_hadamard_transform_12N(x: torch.Tensor, scale: float) -> torch.Tensor:
  631. # return torch.ops._C_hadamard.fast_hadamard_transform_12N(x, scale)
  632. # def fast_hadamard_transform_20N(x: torch.Tensor, scale: float) -> torch.Tensor:
  633. # return torch.ops._C_hadamard.fast_hadamard_transform_20N(x, scale)
  634. # def fast_hadamard_transform_28N(x: torch.Tensor, scale: float) -> torch.Tensor:
  635. # return torch.ops._C_hadamard.fast_hadamard_transform_28N(x, scale)
  636. # TODO: remove this later
  637. names_and_values = globals()
  638. names_and_values_to_update = {}
  639. # prepare variables to avoid dict size change during iteration
  640. k, v, arg = None, None, None
  641. fn_type = type(lambda x: x)
  642. for k, v in names_and_values.items():
  643. # find functions that are defined in this file and have torch.Tensor
  644. # in their annotations. `arg == "torch.Tensor"` is used to handle
  645. # the case when users use `import __annotations__` to turn type
  646. # hints into strings.
  647. if isinstance(v, fn_type) \
  648. and v.__code__.co_filename == __file__ \
  649. and any(arg is torch.Tensor or arg == "torch.Tensor"
  650. for arg in v.__annotations__.values()):
  651. names_and_values_to_update[k] = hint_on_error(v)
  652. names_and_values.update(names_and_values_to_update)
  653. del names_and_values_to_update, names_and_values, v, k, fn_type