_custom_ops.py 23 KB

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