_custom_ops.py 30 KB

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