Merged
torch extension整改成分布式 #9712
huangbolinAdd on Aug 6
torch extension整改成分布式 #9712
Merged
Total: 160 files changed+2662-1613
| @@ -0,0 +1,4 @@ | |||
| 1 | +__all__ = ["compressor"] | ||
| 2 | + | ||
| 3 | +from .compressor import compressor | ||
| 4 | +from . import graph_convert_compressor | ||
Rtorch_extension/cann_ops_transformer/ops/compressor.py→attention/compressor/torch_extension/compressor.py+4-4
| @@ -11,17 +11,16 @@ from typing import Optional, Tuple | |||
| 11 | 11 | ||
| 12 | import torch | 12 | import torch |
| 13 | from torch.library import impl | 13 | from torch.library import impl |
| 14 | - | 14 | +from cann_ops_transformer.op_builder import OpBuilder |
| 15 | -from cann_ops_transformer.op_builder.builder import AS_LIBRARY, OpBuilder | ||
| 16 | 15 | ||
| 17 | 16 | ||
| 18 | class CompressorOpBuilder(OpBuilder): | 17 | class CompressorOpBuilder(OpBuilder): |
| 19 | def __init__(self): | 18 | def __init__(self): |
| 20 | - super(CompressorOpBuilder, self).__init__("compressor") | 19 | + super(CompressorOpBuilder, self).__init__("compressor", category="attention") |
| 21 | 20 | ||
| 22 | def sources(self): | 21 | def sources(self): |
| 23 | """Path to C++ source code.""" | 22 | """Path to C++ source code.""" |
| 24 | - return ["ops/csrc/compressor.cpp"] | 23 | + return ["csrc/attention/compressor.cpp"] |
| 25 | 24 | ||
| 26 | def schema(self): | 25 | def schema(self): |
| 27 | """PyTorch operator signature.""" | 26 | """PyTorch operator signature.""" |
| @@ -36,6 +35,7 @@ class CompressorOpBuilder(OpBuilder): | |||
| 36 | 35 | ||
| 37 | 36 | ||
| 38 | compressor_op_builder = CompressorOpBuilder() | 37 | compressor_op_builder = CompressorOpBuilder() |
| 38 | +compressor_op_builder._ensure_initialized() | ||
| 39 | 39 | ||
| 40 | 40 | ||
| 41 | # =========================================================================== | 41 | # =========================================================================== |
Rtorch_extension/cann_ops_transformer/ops/csrc/compressor.cpp→attention/compressor/torch_extension/csrc/compressor.cpp+17-22
| @@ -47,8 +47,8 @@ std::vector<bool> IsContiguousAxes(const at::Tensor &tensor) | |||
| 47 | } | 47 | } |
| 48 | 48 | ||
| 49 | std::tuple<at::Tensor, at::Tensor, at::Tensor> ConstructCompressorOutputTensor( | 49 | std::tuple<at::Tensor, at::Tensor, at::Tensor> ConstructCompressorOutputTensor( |
| 50 | - const at::Tensor &x, const at::Tensor &wkv, const at::Tensor &ape, | 50 | + const at::Tensor &x, const at::Tensor &wkv, const at::Tensor &ape, const c10::optional<at::Tensor> &cuSeqlens, |
| 51 | - const c10::optional<at::Tensor> &cuSeqlens, int64_t cmpRatio, int64_t coff) | 51 | + int64_t cmpRatio, int64_t coff) |
| 52 | { | 52 | { |
| 53 | auto xDim = x.dim(); | 53 | auto xDim = x.dim(); |
| 54 | at::SmallVector<int64_t, MAX_DIM_SIZE> cmpKvSize; | 54 | at::SmallVector<int64_t, MAX_DIM_SIZE> cmpKvSize; |
| @@ -87,12 +87,10 @@ std::tuple<at::Tensor, at::Tensor, at::Tensor> ConstructCompressorOutputTensor( | |||
| 87 | } | 87 | } |
| 88 | 88 | ||
| 89 | std::tuple<at::Tensor, at::Tensor, at::Tensor> Compressor( | 89 | std::tuple<at::Tensor, at::Tensor, at::Tensor> Compressor( |
| 90 | - const at::Tensor &x, const at::Tensor &wkv, const at::Tensor &wgate, | 90 | + const at::Tensor &x, const at::Tensor &wkv, const at::Tensor &wgate, at::Tensor &stateCache, const at::Tensor &ape, |
| 91 | - at::Tensor &stateCache, const at::Tensor &ape, int64_t cmpRatio, | 91 | + int64_t cmpRatio, const c10::optional<at::Tensor> &stateBlockTable, const c10::optional<at::Tensor> &cuSeqlens, |
| 92 | - const c10::optional<at::Tensor> &stateBlockTable, | 92 | + const c10::optional<at::Tensor> &seqused, const c10::optional<at::Tensor> &startPos, int64_t coff, |
| 93 | - const c10::optional<at::Tensor> &cuSeqlens, | 93 | + int64_t cacheMode, bool gradEnabled) |
| 94 | - const c10::optional<at::Tensor> &seqused, const c10::optional<at::Tensor> &startPos, | ||
| 95 | - int64_t coff, int64_t cacheMode, bool gradEnabled) | ||
| 96 | { | 94 | { |
| 97 | TORCH_CHECK(x.defined(), "Check x != nullptr failed"); | 95 | TORCH_CHECK(x.defined(), "Check x != nullptr failed"); |
| 98 | auto xDim = x.dim(); | 96 | auto xDim = x.dim(); |
| @@ -107,16 +105,15 @@ std::tuple<at::Tensor, at::Tensor, at::Tensor> Compressor( | |||
| 107 | int64_t stateCacheStrideDim0 = stateCache.stride(0); | 105 | int64_t stateCacheStrideDim0 = stateCache.stride(0); |
| 108 | 106 | ||
| 109 | ACLNN_CMD(aclnnCompressor, x, wkv, wgate, stateCache, ape, stateBlockTable, cuSeqlens, seqused, startPos, cmpRatio, | 107 | ACLNN_CMD(aclnnCompressor, x, wkv, wgate, stateCache, ape, stateBlockTable, cuSeqlens, seqused, startPos, cmpRatio, |
| 110 | - coff, cacheMode, stateCacheStrideDim0, gradEnabled, cmpKv, softmaxScore, kv); | 108 | + coff, cacheMode, stateCacheStrideDim0, gradEnabled, cmpKv, softmaxScore, kv); |
| 111 | 109 | ||
| 112 | return std::tuple<at::Tensor, at::Tensor, at::Tensor>(cmpKv, softmaxScore, kv); | 110 | return std::tuple<at::Tensor, at::Tensor, at::Tensor>(cmpKv, softmaxScore, kv); |
| 113 | } | 111 | } |
| 114 | 112 | ||
| 115 | std::tuple<at::Tensor, at::Tensor, at::Tensor, at::Tensor> CompressorBackward( | 113 | std::tuple<at::Tensor, at::Tensor, at::Tensor, at::Tensor> CompressorBackward( |
| 116 | - at::Tensor &dCmpKv, const at::Tensor &x, const at::Tensor &wkv, | 114 | + at::Tensor &dCmpKv, const at::Tensor &x, const at::Tensor &wkv, const at::Tensor &wgate, |
| 117 | - const at::Tensor &wgate, const at::Tensor &softmaxScore, const at::Tensor &kv, | 115 | + const at::Tensor &softmaxScore, const at::Tensor &kv, const c10::optional<at::Tensor> &cuSeqlens, |
| 118 | - const c10::optional<at::Tensor> &cuSeqlens, const c10::optional<at::Tensor> &seqused, | 116 | + const c10::optional<at::Tensor> &seqused, const c10::optional<at::Tensor> &startPos, int64_t cmpRatio, int64_t coff) |
| 119 | - const c10::optional<at::Tensor> &startPos, int64_t cmpRatio, int64_t coff) | ||
| 120 | { | 117 | { |
| 121 | auto xDim = x.dim(); | 118 | auto xDim = x.dim(); |
| 122 | at::SmallVector<int64_t, MAX_DIM_SIZE> dxSize; | 119 | at::SmallVector<int64_t, MAX_DIM_SIZE> dxSize; |
| @@ -132,7 +129,7 @@ std::tuple<at::Tensor, at::Tensor, at::Tensor, at::Tensor> CompressorBackward( | |||
| 132 | TORCH_CHECK(xDim == DIM_TWO || xDim == DIM_THREE, "x dim num[", xDim, "] should be 2 or 3"); | 129 | TORCH_CHECK(xDim == DIM_TWO || xDim == DIM_THREE, "x dim num[", xDim, "] should be 2 or 3"); |
| 133 | 130 | ||
| 134 | TORCH_CHECK(cmpRatio > VALUE_0, "cmp_ratio should be greater than 0"); | 131 | TORCH_CHECK(cmpRatio > VALUE_0, "cmp_ratio should be greater than 0"); |
| 135 | - | 132 | + |
| 136 | dxSize = x.sizes().vec(); | 133 | dxSize = x.sizes().vec(); |
| 137 | dx = at::empty(dxSize, x.options().dtype(x.dtype())); | 134 | dx = at::empty(dxSize, x.options().dtype(x.dtype())); |
| 138 | dWkvSize = wkv.sizes().vec(); | 135 | dWkvSize = wkv.sizes().vec(); |
| @@ -142,19 +139,17 @@ std::tuple<at::Tensor, at::Tensor, at::Tensor, at::Tensor> CompressorBackward( | |||
| 142 | dApeSize = {cmpRatio, wkv.size(0)}; | 139 | dApeSize = {cmpRatio, wkv.size(0)}; |
| 143 | dApe = at::empty(dApeSize, kv.options().dtype(kv.dtype())); | 140 | dApe = at::empty(dApeSize, kv.options().dtype(kv.dtype())); |
| 144 | 141 | ||
| 145 | - ACLNN_CMD(aclnnCompressorGrad, x, wkv, wgate, dCmpKv, softmaxScore, kv, cuSeqlens, seqused, | 142 | + ACLNN_CMD(aclnnCompressorGrad, x, wkv, wgate, dCmpKv, softmaxScore, kv, cuSeqlens, seqused, startPos, cmpRatio, |
| 146 | - startPos, cmpRatio, coff, dx, dWkv, dWgate, dApe); | 143 | + coff, dx, dWkv, dWgate, dApe); |
| 147 | 144 | ||
| 148 | return std::tuple<at::Tensor, at::Tensor, at::Tensor, at::Tensor>(dx, dWkv, dWgate, dApe); | 145 | return std::tuple<at::Tensor, at::Tensor, at::Tensor, at::Tensor>(dx, dWkv, dWgate, dApe); |
| 149 | } | 146 | } |
| 150 | 147 | ||
| 151 | std::tuple<at::Tensor, at::Tensor, at::Tensor> CompressorMeta( | 148 | std::tuple<at::Tensor, at::Tensor, at::Tensor> CompressorMeta( |
| 152 | - const at::Tensor &x, const at::Tensor &wkv, const at::Tensor &wgate, | 149 | + const at::Tensor &x, const at::Tensor &wkv, const at::Tensor &wgate, at::Tensor &stateCache, const at::Tensor &ape, |
| 153 | - at::Tensor &stateCache, const at::Tensor &ape, int64_t cmpRatio, | 150 | + int64_t cmpRatio, const c10::optional<at::Tensor> &stateBlockTable, const c10::optional<at::Tensor> &cuSeqlens, |
| 154 | - const c10::optional<at::Tensor> &stateBlockTable, | 151 | + const c10::optional<at::Tensor> &seqused, const c10::optional<at::Tensor> &startPos, int64_t coff, |
| 155 | - const c10::optional<at::Tensor> &cuSeqlens, | 152 | + int64_t cacheMode) |
| 156 | - const c10::optional<at::Tensor> &seqused, const c10::optional<at::Tensor> &startPos, | ||
| 157 | - int64_t coff, int64_t cacheMode) | ||
| 158 | { | 153 | { |
| 159 | TORCH_CHECK(x.defined(), "Check x != nullptr failed"); | 154 | TORCH_CHECK(x.defined(), "Check x != nullptr failed"); |
| 160 | auto xDim = x.dim(); | 155 | auto xDim = x.dim(); |
Rtorch_extension/cann_ops_transformer/ops/graph_convert/graph_convert_compressor.py→attention/compressor/torch_extension/graph_convert_compressor.py+3-1
| @@ -67,7 +67,9 @@ if _TORCHAIR_AVAILABLE: | |||
| 67 | result = x.new_empty(x.size()) | 67 | result = x.new_empty(x.size()) |
| 68 | return result | 68 | return result |
| 69 | 69 | ||
| 70 | - @register_fx_node_ge_converter(torch.ops.cann_ops_transformer._compressor_forward.default) | 70 | + @register_fx_node_ge_converter( |
| 71 | + torch.ops.cann_ops_transformer._compressor_forward.default | ||
| 72 | + ) | ||
| 71 | def convert_compressor( | 73 | def convert_compressor( |
| 72 | x: Tensor, | 74 | x: Tensor, |
| 73 | wkv: Tensor, | 75 | wkv: Tensor, |
| @@ -0,0 +1,9 @@ | |||
| 1 | +__all__ = [ | ||
| 2 | + "dense_lightning_indexer_kl_loss_grad", | ||
| 3 | + "dense_lightning_indexer_kl_loss_grad_metadata", | ||
| 4 | +] | ||
| 5 | + | ||
| 6 | +from .dense_lightning_indexer_kl_loss_grad import ( | ||
| 7 | + dense_lightning_indexer_kl_loss_grad, | ||
| 8 | + dense_lightning_indexer_kl_loss_grad_metadata, | ||
| 9 | +) | ||
Rtorch_extension/cann_ops_transformer/ops/csrc/dense_lightning_indexer_kl_loss_grad.cpp→attention/dense_lightning_indexer_kl_loss_grad/torch_extension/csrc/dense_lightning_indexer_kl_loss_grad.cpp+0-0
File renamed without changes.
Rtorch_extension/cann_ops_transformer/ops/dense_lightning_indexer_kl_loss_grad.py→attention/dense_lightning_indexer_kl_loss_grad/torch_extension/dense_lightning_indexer_kl_loss_grad.py+11-7
| @@ -11,8 +11,7 @@ from typing import Optional | |||
| 11 | import torch | 11 | import torch |
| 12 | from torch.library import impl | 12 | from torch.library import impl |
| 13 | 13 | ||
| 14 | -from cann_ops_transformer.op_builder.builder import AS_LIBRARY | 14 | +from cann_ops_transformer.op_builder import OpBuilder, get_as_library |
| 15 | -from cann_ops_transformer.op_builder.builder import OpBuilder | ||
| 16 | 15 | ||
| 17 | 16 | ||
| 18 | DLI_KL_LOSS_GRAD_METADATA_SIZE = 64 | 17 | DLI_KL_LOSS_GRAD_METADATA_SIZE = 64 |
| @@ -23,11 +22,11 @@ DLI_KL_LOSS_GRAD_METADATA_OP_NAME = "dense_lightning_indexer_kl_loss_grad_metada | |||
| 23 | class DenseLightningIndexerKLLossGradOpBuilder(OpBuilder): | 22 | class DenseLightningIndexerKLLossGradOpBuilder(OpBuilder): |
| 24 | def __init__(self): | 23 | def __init__(self): |
| 25 | super(DenseLightningIndexerKLLossGradOpBuilder, self).__init__( | 24 | super(DenseLightningIndexerKLLossGradOpBuilder, self).__init__( |
| 26 | - "dense_lightning_indexer_kl_loss_grad" | 25 | + "dense_lightning_indexer_kl_loss_grad", category="attention" |
| 27 | ) | 26 | ) |
| 28 | 27 | ||
| 29 | def sources(self): | 28 | def sources(self): |
| 30 | - return ["ops/csrc/dense_lightning_indexer_kl_loss_grad.cpp"] | 29 | + return ["csrc/attention/dense_lightning_indexer_kl_loss_grad.cpp"] |
| 31 | 30 | ||
| 32 | def schema(self) -> str: | 31 | def schema(self) -> str: |
| 33 | return [ | 32 | return [ |
| @@ -72,7 +71,7 @@ class DenseLightningIndexerKLLossGradOpBuilder(OpBuilder): | |||
| 72 | (DLI_KL_LOSS_GRAD_METADATA_SIZE,), dtype=torch.int32, device="meta" | 71 | (DLI_KL_LOSS_GRAD_METADATA_SIZE,), dtype=torch.int32, device="meta" |
| 73 | ) | 72 | ) |
| 74 | 73 | ||
| 75 | - @impl(AS_LIBRARY, self.name, "Meta") | 74 | + @impl(get_as_library(), self.name, "Meta") |
| 76 | def dense_lightning_indexer_kl_loss_grad_meta( | 75 | def dense_lightning_indexer_kl_loss_grad_meta( |
| 77 | q, | 76 | q, |
| 78 | k, | 77 | k, |
| @@ -105,9 +104,10 @@ class DenseLightningIndexerKLLossGradOpBuilder(OpBuilder): | |||
| 105 | dense_lightning_indexer_kl_loss_grad_op_builder = ( | 104 | dense_lightning_indexer_kl_loss_grad_op_builder = ( |
| 106 | DenseLightningIndexerKLLossGradOpBuilder() | 105 | DenseLightningIndexerKLLossGradOpBuilder() |
| 107 | ) | 106 | ) |
| 107 | +dense_lightning_indexer_kl_loss_grad_op_builder._ensure_initialized() | ||
| 108 | 108 | ||
| 109 | 109 | ||
| 110 | -@impl(AS_LIBRARY, DLI_KL_LOSS_GRAD_METADATA_OP_NAME, "PrivateUse1") | 110 | +@impl(get_as_library(), DLI_KL_LOSS_GRAD_METADATA_OP_NAME, "PrivateUse1") |
| 111 | def dense_lightning_indexer_kl_loss_grad_metadata( | 111 | def dense_lightning_indexer_kl_loss_grad_metadata( |
| 112 | num_heads_q, | 112 | num_heads_q, |
| 113 | num_heads_k, | 113 | num_heads_k, |
| @@ -197,7 +197,11 @@ def dense_lightning_indexer_kl_loss_grad_metadata_fallback( | |||
| 197 | torch.compiler.allow_in_graph(dense_lightning_indexer_kl_loss_grad_metadata) | 197 | torch.compiler.allow_in_graph(dense_lightning_indexer_kl_loss_grad_metadata) |
| 198 | 198 | ||
| 199 | 199 | ||
| 200 | -@impl(AS_LIBRARY, dense_lightning_indexer_kl_loss_grad_op_builder.name, "PrivateUse1") | 200 | +@impl( |
| 201 | + get_as_library(), | ||
| 202 | + dense_lightning_indexer_kl_loss_grad_op_builder.name, | ||
| 203 | + "PrivateUse1", | ||
| 204 | +) | ||
| 201 | def dense_lightning_indexer_kl_loss_grad( | 205 | def dense_lightning_indexer_kl_loss_grad( |
| 202 | q, | 206 | q, |
| 203 | k, | 207 | k, |
| @@ -0,0 +1,9 @@ | |||
| 1 | +__all__ = [ | ||
| 2 | + "dense_lightning_indexer_softmax_lse", | ||
| 3 | + "dense_lightning_indexer_softmax_lse_metadata", | ||
| 4 | +] | ||
| 5 | + | ||
| 6 | +from .dense_lightning_indexer_softmax_lse import ( | ||
| 7 | + dense_lightning_indexer_softmax_lse, | ||
| 8 | + dense_lightning_indexer_softmax_lse_metadata, | ||
| 9 | +) | ||
Rtorch_extension/cann_ops_transformer/ops/csrc/dense_lightning_indexer_softmax_lse.cpp→attention/dense_lightning_indexer_softmax_lse_v2/torch_extension/csrc/dense_lightning_indexer_softmax_lse.cpp+0-0
File renamed without changes.
Rtorch_extension/cann_ops_transformer/ops/dense_lightning_indexer_softmax_lse.py→attention/dense_lightning_indexer_softmax_lse_v2/torch_extension/dense_lightning_indexer_softmax_lse.py+12-7
| @@ -14,8 +14,7 @@ import torch | |||
| 14 | import torch_npu | 14 | import torch_npu |
| 15 | from torch.library import impl | 15 | from torch.library import impl |
| 16 | 16 | ||
| 17 | -from cann_ops_transformer.op_builder.builder import AS_LIBRARY | 17 | +from cann_ops_transformer.op_builder import OpBuilder, get_as_library |
| 18 | -from cann_ops_transformer.op_builder.builder import OpBuilder | ||
| 19 | 18 | ||
| 20 | 19 | ||
| 21 | DLI_METADATA_SIZE = 64 | 20 | DLI_METADATA_SIZE = 64 |
| @@ -26,11 +25,11 @@ DLI_OP_NAME = "dense_lightning_indexer_softmax_lse" | |||
| 26 | class DenseLightningIndexerSoftmaxLseOpBuilder(OpBuilder): | 25 | class DenseLightningIndexerSoftmaxLseOpBuilder(OpBuilder): |
| 27 | def __init__(self): | 26 | def __init__(self): |
| 28 | super(DenseLightningIndexerSoftmaxLseOpBuilder, self).__init__( | 27 | super(DenseLightningIndexerSoftmaxLseOpBuilder, self).__init__( |
| 29 | - "dense_lightning_indexer_softmax_lse" | 28 | + "dense_lightning_indexer_softmax_lse", category="attention" |
| 30 | ) | 29 | ) |
| 31 | 30 | ||
| 32 | def sources(self): | 31 | def sources(self): |
| 33 | - return ["ops/csrc/dense_lightning_indexer_softmax_lse.cpp"] | 32 | + return ["csrc/attention/dense_lightning_indexer_softmax_lse.cpp"] |
| 34 | 33 | ||
| 35 | def schema(self) -> str: | 34 | def schema(self) -> str: |
| 36 | return [ | 35 | return [ |
| @@ -71,7 +70,7 @@ class DenseLightningIndexerSoftmaxLseOpBuilder(OpBuilder): | |||
| 71 | ): | 70 | ): |
| 72 | return torch.empty((DLI_METADATA_SIZE,), dtype=torch.int32, device="meta") | 71 | return torch.empty((DLI_METADATA_SIZE,), dtype=torch.int32, device="meta") |
| 73 | 72 | ||
| 74 | - @impl(AS_LIBRARY, self.name, "Meta") | 73 | + @impl(get_as_library(), self.name, "Meta") |
| 75 | def dense_lightning_indexer_softmax_lse_meta( | 74 | def dense_lightning_indexer_softmax_lse_meta( |
| 76 | query_index, | 75 | query_index, |
| 77 | key_index, | 76 | key_index, |
| @@ -104,7 +103,7 @@ dense_lightning_indexer_softmax_lse_op_builder = ( | |||
| 104 | ) | 103 | ) |
| 105 | 104 | ||
| 106 | 105 | ||
| 107 | -@impl(AS_LIBRARY, DLI_METADATA_OP_NAME, "PrivateUse1") | 106 | +@impl(get_as_library(), DLI_METADATA_OP_NAME, "PrivateUse1") |
| 108 | def dense_lightning_indexer_softmax_lse_metadata( | 107 | def dense_lightning_indexer_softmax_lse_metadata( |
| 109 | num_heads_q, | 108 | num_heads_q, |
| 110 | num_heads_k, | 109 | num_heads_k, |
| @@ -217,7 +216,7 @@ def dense_lightning_indexer_softmax_lse_metadata_fallback( | |||
| 217 | torch.compiler.allow_in_graph(dense_lightning_indexer_softmax_lse_metadata) | 216 | torch.compiler.allow_in_graph(dense_lightning_indexer_softmax_lse_metadata) |
| 218 | 217 | ||
| 219 | 218 | ||
| 220 | -@impl(AS_LIBRARY, DLI_OP_NAME, "PrivateUse1") | 219 | +@impl(get_as_library(), DLI_OP_NAME, "PrivateUse1") |
| 221 | def dense_lightning_indexer_softmax_lse( | 220 | def dense_lightning_indexer_softmax_lse( |
| 222 | query_index: torch.Tensor, | 221 | query_index: torch.Tensor, |
| 223 | key_index: torch.Tensor, | 222 | key_index: torch.Tensor, |
| @@ -312,3 +311,9 @@ def dense_lightning_indexer_softmax_lse_fallback( | |||
| 312 | 311 | ||
| 313 | 312 | ||
| 314 | torch.compiler.allow_in_graph(dense_lightning_indexer_softmax_lse) | 313 | torch.compiler.allow_in_graph(dense_lightning_indexer_softmax_lse) |
| 314 | + | ||
| 315 | + | ||
| 316 | +dense_lightning_indexer_softmax_lse_op_builder = ( | ||
| 317 | + DenseLightningIndexerSoftmaxLseOpBuilder() | ||
| 318 | +) | ||
| 319 | +dense_lightning_indexer_softmax_lse_op_builder._ensure_initialized() | ||
| @@ -0,0 +1,4 @@ | |||
| 1 | +__all__ = ["flash_attn", "flash_attn_metadata"] | ||
| 2 | + | ||
| 3 | +from .flash_attn import flash_attn, flash_attn_metadata | ||
| 4 | +from . import graph_convert_flash_attn | ||
Rtorch_extension/cann_ops_transformer/ops/csrc/flash_attn.cpp→attention/flash_attn/torch_extension/csrc/flash_attn.cpp+8-8
| @@ -34,14 +34,14 @@ at::Tensor FlashAttnMetadata(const c10::optional<at::Tensor> &cuSeqlensQ, const | |||
| 34 | return output; | 34 | return output; |
| 35 | } | 35 | } |
| 36 | 36 | ||
| 37 | -std::tuple<at::Tensor, at::Tensor> | 37 | +std::tuple<at::Tensor, at::Tensor> FlashAttn( |
| 38 | -FlashAttn(const at::Tensor &q, const at::Tensor &k, const at::Tensor &v, const c10::optional<at::Tensor> &blockTable, | 38 | + const at::Tensor &q, const at::Tensor &k, const at::Tensor &v, const c10::optional<at::Tensor> &blockTable, |
| 39 | - const c10::optional<at::Tensor> &cuSeqlensQ, const c10::optional<at::Tensor> &cuSeqlensKv, | 39 | + const c10::optional<at::Tensor> &cuSeqlensQ, const c10::optional<at::Tensor> &cuSeqlensKv, |
| 40 | - const c10::optional<at::Tensor> &sequsedQ, const c10::optional<at::Tensor> &sequsedKv, | 40 | + const c10::optional<at::Tensor> &sequsedQ, const c10::optional<at::Tensor> &sequsedKv, |
| 41 | - const c10::optional<at::Tensor> &sinks, const c10::optional<at::Tensor> &attnMask, | 41 | + const c10::optional<at::Tensor> &sinks, const c10::optional<at::Tensor> &attnMask, |
| 42 | - const c10::optional<at::Tensor> &metadata, double softmaxScale, int64_t maskMode, int64_t winLeft, | 42 | + const c10::optional<at::Tensor> &metadata, double softmaxScale, int64_t maskMode, int64_t winLeft, int64_t winRight, |
| 43 | - int64_t winRight, int64_t maxSeqlenQ, int64_t maxSeqlenKv, string layoutQ, string layoutKv, string layoutOut, | 43 | + int64_t maxSeqlenQ, int64_t maxSeqlenKv, string layoutQ, string layoutKv, string layoutOut, |
| 44 | - int64_t returnSoftmaxLse) | 44 | + int64_t returnSoftmaxLse) |
| 45 | { | 45 | { |
| 46 | int64_t tSize = 0; | 46 | int64_t tSize = 0; |
| 47 | int64_t nSize = 0; | 47 | int64_t nSize = 0; |
Rtorch_extension/cann_ops_transformer/ops/flash_attn.py→attention/flash_attn/torch_extension/flash_attn.py+7-8
| @@ -10,8 +10,7 @@ | |||
| 10 | from typing import Optional | 10 | from typing import Optional |
| 11 | import torch | 11 | import torch |
| 12 | from torch.library import impl | 12 | from torch.library import impl |
| 13 | -from cann_ops_transformer.op_builder.builder import OpBuilder | 13 | +from cann_ops_transformer.op_builder import OpBuilder, get_as_library |
| 14 | -from cann_ops_transformer.op_builder.builder import AS_LIBRARY | ||
| 15 | 14 | ||
| 16 | FA_METADATA_SIZE = 1024 | 15 | FA_METADATA_SIZE = 1024 |
| 17 | FA_METADATA_OP_NAME = "flash_attn_metadata" | 16 | FA_METADATA_OP_NAME = "flash_attn_metadata" |
| @@ -43,11 +42,11 @@ def _calculate_metadata_size(batch_size, num_heads_kv): | |||
| 43 | 42 | ||
| 44 | class FlashAttenOpBuilder(OpBuilder): | 43 | class FlashAttenOpBuilder(OpBuilder): |
| 45 | def __init__(self): | 44 | def __init__(self): |
| 46 | - super(FlashAttenOpBuilder, self).__init__("flash_attn") | 45 | + super(FlashAttenOpBuilder, self).__init__("flash_attn", category="attention") |
| 47 | 46 | ||
| 48 | def sources(self): | 47 | def sources(self): |
| 49 | """Path to C++ source code.""" | 48 | """Path to C++ source code.""" |
| 50 | - return ["ops/csrc/flash_attn.cpp"] | 49 | + return ["csrc/attention/flash_attn.cpp"] |
| 51 | 50 | ||
| 52 | def schema(self) -> str: | 51 | def schema(self) -> str: |
| 53 | """PyTorch operator signature.""" | 52 | """PyTorch operator signature.""" |
| @@ -82,7 +81,7 @@ class FlashAttenOpBuilder(OpBuilder): | |||
| 82 | cu_seqlens_kv: Optional[torch.Tensor] = None, | 81 | cu_seqlens_kv: Optional[torch.Tensor] = None, |
| 83 | seqused_q: Optional[torch.Tensor] = None, | 82 | seqused_q: Optional[torch.Tensor] = None, |
| 84 | seqused_kv: Optional[torch.Tensor] = None, | 83 | seqused_kv: Optional[torch.Tensor] = None, |
| 85 | - batch_size: Optional[int] = None, | 84 | + batch_size: Optional[int] = -1, |
| 86 | max_seqlen_q: Optional[int] = None, | 85 | max_seqlen_q: Optional[int] = None, |
| 87 | max_seqlen_kv: Optional[int] = None, | 86 | max_seqlen_kv: Optional[int] = None, |
| 88 | mask_mode: Optional[int] = None, | 87 | mask_mode: Optional[int] = None, |
| @@ -165,9 +164,10 @@ class FlashAttenOpBuilder(OpBuilder): | |||
| 165 | 164 | ||
| 166 | # Instantiate the builder | 165 | # Instantiate the builder |
| 167 | flash_attn_op_builder = FlashAttenOpBuilder() | 166 | flash_attn_op_builder = FlashAttenOpBuilder() |
| 167 | +flash_attn_op_builder._ensure_initialized() | ||
| 168 | 168 | ||
| 169 | 169 | ||
| 170 | -@impl(AS_LIBRARY, FA_METADATA_OP_NAME, "PrivateUse1") | 170 | +@impl(get_as_library(), FA_METADATA_OP_NAME, "PrivateUse1") |
| 171 | def flash_attn_metadata( | 171 | def flash_attn_metadata( |
| 172 | num_heads_q: int, | 172 | num_heads_q: int, |
| 173 | num_heads_kv: int, | 173 | num_heads_kv: int, |
| @@ -193,7 +193,6 @@ def flash_attn_metadata( | |||
| 193 | b_size = _calculate_batch_size(batch_size, cu_seqlens_q, seqused_q) | 193 | b_size = _calculate_batch_size(batch_size, cu_seqlens_q, seqused_q) |
| 194 | 194 | ||
| 195 | batch_size = -1 if batch_size is None else batch_size | 195 | batch_size = -1 if batch_size is None else batch_size |
| 196 | - max_seqlen_q = -1 if max_seqlen_q is None else max_seqlen_q | ||
| 197 | max_seqlen_kv = -1 if max_seqlen_kv is None else max_seqlen_kv | 196 | max_seqlen_kv = -1 if max_seqlen_kv is None else max_seqlen_kv |
| 198 | mask_mode = 1 if mask_mode is None else mask_mode | 197 | mask_mode = 1 if mask_mode is None else mask_mode |
| 199 | win_left = -1 if win_left is None else win_left | 198 | win_left = -1 if win_left is None else win_left |
| @@ -270,7 +269,7 @@ def flash_attn_metadata_fallback( | |||
| 270 | ) | 269 | ) |
| 271 | 270 | ||
| 272 | 271 | ||
| 273 | -@impl(AS_LIBRARY, flash_attn_op_builder.name, "PrivateUse1") | 272 | +@impl(get_as_library(), flash_attn_op_builder.name, "PrivateUse1") |
| 274 | def flash_attn( | 273 | def flash_attn( |
| 275 | q: torch.Tensor, | 274 | q: torch.Tensor, |
| 276 | k: torch.Tensor, | 275 | k: torch.Tensor, |
Rtorch_extension/cann_ops_transformer/ops/graph_convert/graph_convert_flash_attn.py→attention/flash_attn/torch_extension/graph_convert_flash_attn.py+0-0
File renamed without changes.
| @@ -0,0 +1,4 @@ | |||
| 1 | +__all__ = ["indexer_quant_cache"] | ||
| 2 | + | ||
| 3 | +from .indexer_quant_cache import indexer_quant_cache | ||
| 4 | +from . import graph_convert_indexer_quant_cache | ||
Rtorch_extension/cann_ops_transformer/ops/csrc/indexer_quant_cache.cpp→attention/indexer_quant_cache/torch_extension/csrc/indexer_quant_cache.cpp+1-4
| @@ -50,8 +50,5 @@ void IndexerQuantCache(at::Tensor &cache, at::Tensor &cacheScale, const at::Tens | |||
| 50 | } | 50 | } |
| 51 | 51 | ||
| 52 | // Bind the C++ function to Python module | 52 | // Bind the C++ function to Python module |
| 53 | -PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) | 53 | +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("indexer_quant_cache", &IndexerQuantCache, "indexer_quant_cache"); } |
| 54 | -{ | ||
| 55 | - m.def("indexer_quant_cache", &IndexerQuantCache, "indexer_quant_cache"); | ||
| 56 | -} | ||
| 57 | } // namespace op_api | 54 | } // namespace op_api |
Rtorch_extension/cann_ops_transformer/ops/graph_convert/graph_convert_indexer_quant_cache.py→attention/indexer_quant_cache/torch_extension/graph_convert_indexer_quant_cache.py+1-1
| @@ -123,7 +123,7 @@ if _TORCHAIR_AVAILABLE: | |||
| 123 | meta_outputs: TensorSpec = None, | 123 | meta_outputs: TensorSpec = None, |
| 124 | ): | 124 | ): |
| 125 | # 对外 str quant_mode → 算子侧 int(与 eager 路径共用同一映射) | 125 | # 对外 str quant_mode → 算子侧 int(与 eager 路径共用同一映射) |
| 126 | - from cann_ops_transformer.ops.indexer_quant_cache import _resolve_quant_mode | 126 | + from .indexer_quant_cache import _resolve_quant_mode |
| 127 | 127 | ||
| 128 | out = IndexerQuantCache( | 128 | out = IndexerQuantCache( |
| 129 | cache=cache, | 129 | cache=cache, |
Rtorch_extension/cann_ops_transformer/ops/indexer_quant_cache.py→attention/indexer_quant_cache/torch_extension/indexer_quant_cache.py+8-6
| @@ -11,8 +11,7 @@ from enum import IntEnum | |||
| 11 | from typing import Union | 11 | from typing import Union |
| 12 | import torch | 12 | import torch |
| 13 | from torch.library import impl | 13 | from torch.library import impl |
| 14 | -from cann_ops_transformer.op_builder.builder import OpBuilder | 14 | +from cann_ops_transformer.op_builder import OpBuilder, get_as_library |
| 15 | -from cann_ops_transformer.op_builder.builder import AS_LIBRARY | ||
| 16 | 15 | ||
| 17 | 16 | ||
| 18 | class IndexerQuantMode(IntEnum): | 17 | class IndexerQuantMode(IntEnum): |
| @@ -42,11 +41,13 @@ def _resolve_quant_mode(quant_mode: Union[str, int]) -> int: | |||
| 42 | 41 | ||
| 43 | class IndexerQuantCacheOpBuilder(OpBuilder): | 42 | class IndexerQuantCacheOpBuilder(OpBuilder): |
| 44 | def __init__(self): | 43 | def __init__(self): |
| 45 | - super(IndexerQuantCacheOpBuilder, self).__init__("indexer_quant_cache") | 44 | + super(IndexerQuantCacheOpBuilder, self).__init__( |
| 45 | + "indexer_quant_cache", category="attention" | ||
| 46 | + ) | ||
| 46 | 47 | ||
| 47 | def sources(self): | 48 | def sources(self): |
| 48 | """Path to C++ source code.""" | 49 | """Path to C++ source code.""" |
| 49 | - return ["ops/csrc/indexer_quant_cache.cpp"] | 50 | + return ["csrc/attention/indexer_quant_cache.cpp"] |
| 50 | 51 | ||
| 51 | def schema(self) -> str: | 52 | def schema(self) -> str: |
| 52 | """PyTorch operator signature.""" | 53 | """PyTorch operator signature.""" |
| @@ -61,7 +62,7 @@ class IndexerQuantCacheOpBuilder(OpBuilder): | |||
| 61 | Registers the Meta implementation. | 62 | Registers the Meta implementation. |
| 62 | """ | 63 | """ |
| 63 | 64 | ||
| 64 | - @impl(AS_LIBRARY, self.name, "Meta") | 65 | + @impl(get_as_library(), self.name, "Meta") |
| 65 | def indexer_quant_cache_meta( | 66 | def indexer_quant_cache_meta( |
| 66 | cache, | 67 | cache, |
| 67 | cache_scale, | 68 | cache_scale, |
| @@ -77,9 +78,10 @@ class IndexerQuantCacheOpBuilder(OpBuilder): | |||
| 77 | 78 | ||
| 78 | # Instantiate the builder | 79 | # Instantiate the builder |
| 79 | indexer_quant_cache_op_builder = IndexerQuantCacheOpBuilder() | 80 | indexer_quant_cache_op_builder = IndexerQuantCacheOpBuilder() |
| 81 | +indexer_quant_cache_op_builder._ensure_initialized() | ||
| 80 | 82 | ||
| 81 | 83 | ||
| 82 | -@impl(AS_LIBRARY, indexer_quant_cache_op_builder.name, "PrivateUse1") | 84 | +@impl(get_as_library(), indexer_quant_cache_op_builder.name, "PrivateUse1") |
| 83 | def _indexer_quant_cache( | 85 | def _indexer_quant_cache( |
| 84 | cache: torch.Tensor, | 86 | cache: torch.Tensor, |
| 85 | cache_scale: torch.Tensor, | 87 | cache_scale: torch.Tensor, |
| @@ -0,0 +1,4 @@ | |||
| 1 | +__all__ = ["kv_compress_epilog"] | ||
| 2 | + | ||
| 3 | +from .kv_compress_epilog import kv_compress_epilog | ||
| 4 | +from . import graph_convert_kv_compress_epilog | ||
Rtorch_extension/cann_ops_transformer/ops/csrc/kv_compress_epilog.cpp→attention/kv_compress_epilog/torch_extension/csrc/kv_compress_epilog.cpp+1-4
| @@ -49,8 +49,5 @@ void KvCompressEpilog(at::Tensor &cache, const at::Tensor &x, const at::Tensor & | |||
| 49 | xScaleF); | 49 | xScaleF); |
| 50 | } | 50 | } |
| 51 | 51 | ||
| 52 | -PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) | 52 | +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("kv_compress_epilog", &KvCompressEpilog, "kv_compress_epilog"); } |
| 53 | -{ | ||
| 54 | - m.def("kv_compress_epilog", &KvCompressEpilog, "kv_compress_epilog"); | ||
| 55 | -} | ||
| 56 | } // namespace op_api | 53 | } // namespace op_api |
Rtorch_extension/cann_ops_transformer/ops/graph_convert/graph_convert_kv_compress_epilog.py→attention/kv_compress_epilog/torch_extension/graph_convert_kv_compress_epilog.py+1-1
| @@ -114,7 +114,7 @@ if _TORCHAIR_AVAILABLE: | |||
| 114 | meta_outputs: TensorSpec = None, | 114 | meta_outputs: TensorSpec = None, |
| 115 | ): | 115 | ): |
| 116 | # 对外 str quant_mode → 算子侧 int(与 eager 路径共用同一映射) | 116 | # 对外 str quant_mode → 算子侧 int(与 eager 路径共用同一映射) |
| 117 | - from cann_ops_transformer.ops.kv_compress_epilog import _resolve_quant_mode | 117 | + from .kv_compress_epilog import _resolve_quant_mode |
| 118 | 118 | ||
| 119 | return KvCompressEpilog( | 119 | return KvCompressEpilog( |
| 120 | cache=cache, | 120 | cache=cache, |
Rtorch_extension/cann_ops_transformer/ops/kv_compress_epilog.py→attention/kv_compress_epilog/torch_extension/kv_compress_epilog.py+8-6
| @@ -11,8 +11,7 @@ from enum import IntEnum | |||
| 11 | from typing import Union | 11 | from typing import Union |
| 12 | import torch | 12 | import torch |
| 13 | from torch.library import impl | 13 | from torch.library import impl |
| 14 | -from cann_ops_transformer.op_builder.builder import OpBuilder | 14 | +from cann_ops_transformer.op_builder import OpBuilder, get_as_library |
| 15 | -from cann_ops_transformer.op_builder.builder import AS_LIBRARY | ||
| 16 | 15 | ||
| 17 | 16 | ||
| 18 | class KvCompressQuantMode(IntEnum): | 17 | class KvCompressQuantMode(IntEnum): |
| @@ -43,11 +42,13 @@ def _resolve_quant_mode(quant_mode: Union[str, int]) -> int: | |||
| 43 | 42 | ||
| 44 | class KvCompressEpilogOpBuilder(OpBuilder): | 43 | class KvCompressEpilogOpBuilder(OpBuilder): |
| 45 | def __init__(self): | 44 | def __init__(self): |
| 46 | - super(KvCompressEpilogOpBuilder, self).__init__("kv_compress_epilog") | 45 | + super(KvCompressEpilogOpBuilder, self).__init__( |
| 46 | + "kv_compress_epilog", category="attention" | ||
| 47 | + ) | ||
| 47 | 48 | ||
| 48 | def sources(self): | 49 | def sources(self): |
| 49 | """Path to C++ source code.""" | 50 | """Path to C++ source code.""" |
| 50 | - return ["ops/csrc/kv_compress_epilog.cpp"] | 51 | + return ["csrc/attention/kv_compress_epilog.cpp"] |
| 51 | 52 | ||
| 52 | def schema(self) -> str: | 53 | def schema(self) -> str: |
| 53 | """PyTorch operator signature.""" | 54 | """PyTorch operator signature.""" |
| @@ -62,7 +63,7 @@ class KvCompressEpilogOpBuilder(OpBuilder): | |||
| 62 | Registers the Meta implementation. | 63 | Registers the Meta implementation. |
| 63 | """ | 64 | """ |
| 64 | 65 | ||
| 65 | - @impl(AS_LIBRARY, self.name, "Meta") | 66 | + @impl(get_as_library(), self.name, "Meta") |
| 66 | def kv_compress_epilog_meta( | 67 | def kv_compress_epilog_meta( |
| 67 | cache, | 68 | cache, |
| 68 | x, | 69 | x, |
| @@ -78,9 +79,10 @@ class KvCompressEpilogOpBuilder(OpBuilder): | |||
| 78 | 79 | ||
| 79 | # Instantiate the builder | 80 | # Instantiate the builder |
| 80 | kv_compress_epilog_op_builder = KvCompressEpilogOpBuilder() | 81 | kv_compress_epilog_op_builder = KvCompressEpilogOpBuilder() |
| 82 | +kv_compress_epilog_op_builder._ensure_initialized() | ||
| 81 | 83 | ||
| 82 | 84 | ||
| 83 | -@impl(AS_LIBRARY, kv_compress_epilog_op_builder.name, "PrivateUse1") | 85 | +@impl(get_as_library(), kv_compress_epilog_op_builder.name, "PrivateUse1") |
| 84 | def _kv_compress_epilog( | 86 | def _kv_compress_epilog( |
| 85 | cache: torch.Tensor, | 87 | cache: torch.Tensor, |
| 86 | x: torch.Tensor, | 88 | x: torch.Tensor, |
| @@ -0,0 +1,3 @@ | |||
| 1 | +__all__ = ["lightning_indexer_kl_loss"] | ||
| 2 | + | ||
| 3 | +from .lightning_indexer_kl_loss import lightning_indexer_kl_loss | ||
Rtorch_extension/cann_ops_transformer/ops/csrc/lightning_indexer_kl_loss.cpp→attention/lightning_indexer_kl_loss/torch_extension/csrc/lightning_indexer_kl_loss.cpp+0-0
File renamed without changes.
Rtorch_extension/cann_ops_transformer/ops/lightning_indexer_kl_loss.py→attention/lightning_indexer_kl_loss/torch_extension/lightning_indexer_kl_loss.py+7-7
| @@ -12,24 +12,23 @@ import torch | |||
| 12 | import torch_npu | 12 | import torch_npu |
| 13 | from torch.library import impl | 13 | from torch.library import impl |
| 14 | 14 | ||
| 15 | -from cann_ops_transformer.op_builder.builder import AS_LIBRARY | 15 | +from cann_ops_transformer.op_builder import OpBuilder, get_as_library |
| 16 | -from cann_ops_transformer.op_builder.builder import OpBuilder | ||
| 17 | 16 | ||
| 18 | 17 | ||
| 19 | class LightningIndexerKLLossOpBuilder(OpBuilder): | 18 | class LightningIndexerKLLossOpBuilder(OpBuilder): |
| 20 | def __init__(self): | 19 | def __init__(self): |
| 21 | super(LightningIndexerKLLossOpBuilder, self).__init__( | 20 | super(LightningIndexerKLLossOpBuilder, self).__init__( |
| 22 | - "lightning_indexer_kl_loss" | 21 | + "lightning_indexer_kl_loss", category="attention" |
| 23 | ) | 22 | ) |
| 24 | 23 | ||
| 25 | def sources(self): | 24 | def sources(self): |
| 26 | - return ["ops/csrc/lightning_indexer_kl_loss.cpp"] | 25 | + return ["csrc/attention/lightning_indexer_kl_loss.cpp"] |
| 27 | 26 | ||
| 28 | def schema(self) -> str: | 27 | def schema(self) -> str: |
| 29 | return "lightning_indexer_kl_loss(Tensor target_score, Tensor index_probs, float eps=1e-9, str weight_type='logits') -> Tensor" | 28 | return "lightning_indexer_kl_loss(Tensor target_score, Tensor index_probs, float eps=1e-9, str weight_type='logits') -> Tensor" |
| 30 | 29 | ||
| 31 | def register_meta(self): | 30 | def register_meta(self): |
| 32 | - @impl(AS_LIBRARY, self.name, "Meta") | 31 | + @impl(get_as_library(), self.name, "Meta") |
| 33 | def lightning_indexer_kl_loss_meta( | 32 | def lightning_indexer_kl_loss_meta( |
| 34 | target_score, index_probs, eps=1e-9, weight_type="logits" | 33 | target_score, index_probs, eps=1e-9, weight_type="logits" |
| 35 | ): | 34 | ): |
| @@ -37,10 +36,10 @@ class LightningIndexerKLLossOpBuilder(OpBuilder): | |||
| 37 | 36 | ||
| 38 | 37 | ||
| 39 | lightning_indexer_kl_loss_op_builder = LightningIndexerKLLossOpBuilder() | 38 | lightning_indexer_kl_loss_op_builder = LightningIndexerKLLossOpBuilder() |
| 40 | -op_module = lightning_indexer_kl_loss_op_builder.load() | 39 | +lightning_indexer_kl_loss_op_builder._ensure_initialized() |
| 41 | 40 | ||
| 42 | 41 | ||
| 43 | -@impl(AS_LIBRARY, lightning_indexer_kl_loss_op_builder.name, "PrivateUse1") | 42 | +@impl(get_as_library(), lightning_indexer_kl_loss_op_builder.name, "PrivateUse1") |
| 44 | def lightning_indexer_kl_loss( | 43 | def lightning_indexer_kl_loss( |
| 45 | target_score, index_probs, eps=1e-9, weight_type="logits" | 44 | target_score, index_probs, eps=1e-9, weight_type="logits" |
| 46 | ): | 45 | ): |
| @@ -82,6 +81,7 @@ def lightning_indexer_kl_loss( | |||
| 82 | >>> index_probs = torch.softmax(torch.randn(4, 10, 128), dim=-1).npu() | 81 | >>> index_probs = torch.softmax(torch.randn(4, 10, 128), dim=-1).npu() |
| 83 | >>> loss = lightning_indexer_kl_loss(target_score, index_probs) | 82 | >>> loss = lightning_indexer_kl_loss(target_score, index_probs) |
| 84 | """ | 83 | """ |
| 84 | + op_module = lightning_indexer_kl_loss_op_builder.load() | ||
| 85 | return op_module.lightning_indexer_kl_loss( | 85 | return op_module.lightning_indexer_kl_loss( |
| 86 | target_score, index_probs, eps, weight_type | 86 | target_score, index_probs, eps, weight_type |
| 87 | ) | 87 | ) |
| @@ -0,0 +1,4 @@ | |||
| 1 | +__all__ = ["lightning_indexer", "lightning_indexer_metadata"] | ||
| 2 | + | ||
| 3 | +from .lightning_indexer import lightning_indexer, lightning_indexer_metadata | ||
| 4 | +from . import graph_convert_lightning_indexer | ||
Rtorch_extension/cann_ops_transformer/ops/csrc/lightning_indexer.cpp→attention/lightning_indexer_v2/torch_extension/csrc/lightning_indexer.cpp+7-8
| @@ -106,14 +106,13 @@ std::tuple<at::Tensor, at::Tensor> ConstructLightningIndexerOutputTensor(const a | |||
| 106 | return std::tuple<at::Tensor, at::Tensor>(sparseIndicesOut, sparseValuesOut); | 106 | return std::tuple<at::Tensor, at::Tensor>(sparseIndicesOut, sparseValuesOut); |
| 107 | } | 107 | } |
| 108 | 108 | ||
| 109 | -std::tuple<at::Tensor, at::Tensor> | 109 | +std::tuple<at::Tensor, at::Tensor> LightningIndexer( |
| 110 | -LightningIndexer(const at::Tensor &q, const at::Tensor &k, const at::Tensor &w, int64_t topk, | 110 | + const at::Tensor &q, const at::Tensor &k, const at::Tensor &w, int64_t topk, |
| 111 | - const c10::optional<at::Tensor> &cuSeqlensQ, const c10::optional<at::Tensor> &cuSeqlensK, | 111 | + const c10::optional<at::Tensor> &cuSeqlensQ, const c10::optional<at::Tensor> &cuSeqlensK, |
| 112 | - const c10::optional<at::Tensor> &sequsedQ, const c10::optional<at::Tensor> &sequsedK, | 112 | + const c10::optional<at::Tensor> &sequsedQ, const c10::optional<at::Tensor> &sequsedK, |
| 113 | - const c10::optional<at::Tensor> &cmpResidualK, const c10::optional<at::Tensor> &blockTable, | 113 | + const c10::optional<at::Tensor> &cmpResidualK, const c10::optional<at::Tensor> &blockTable, |
| 114 | - const c10::optional<at::Tensor> &outputIdxOffset, const c10::optional<at::Tensor> &metadata, | 114 | + const c10::optional<at::Tensor> &outputIdxOffset, const c10::optional<at::Tensor> &metadata, int64_t maxSeqlenQ, |
| 115 | - int64_t maxSeqlenQ, c10::string_view layoutQ, c10::string_view layoutK, int64_t maskMode, | 115 | + c10::string_view layoutQ, c10::string_view layoutK, int64_t maskMode, int64_t cmpRatio, int64_t returnValue) |
| 116 | - int64_t cmpRatio, int64_t returnValue) | ||
| 117 | { | 116 | { |
| 118 | TORCH_CHECK(q.numel() > 0, "Tensor q is empty.") | 117 | TORCH_CHECK(q.numel() > 0, "Tensor q is empty.") |
| 119 | TORCH_CHECK(k.numel() > 0, "Tensor k is empty.") | 118 | TORCH_CHECK(k.numel() > 0, "Tensor k is empty.") |
Rtorch_extension/cann_ops_transformer/ops/graph_convert/graph_convert_lightning_indexer.py→attention/lightning_indexer_v2/torch_extension/graph_convert_lightning_indexer.py+0-0
File renamed without changes.
Rtorch_extension/cann_ops_transformer/ops/lightning_indexer.py→attention/lightning_indexer_v2/torch_extension/lightning_indexer.py+9-7
| @@ -10,8 +10,7 @@ | |||
| 10 | from typing import Optional | 10 | from typing import Optional |
| 11 | import torch | 11 | import torch |
| 12 | from torch.library import impl | 12 | from torch.library import impl |
| 13 | -from cann_ops_transformer.op_builder.builder import OpBuilder | 13 | +from cann_ops_transformer.op_builder import OpBuilder, get_as_library |
| 14 | -from cann_ops_transformer.op_builder.builder import AS_LIBRARY | ||
| 15 | 14 | ||
| 16 | LI_METADATA_SIZE = 1024 | 15 | LI_METADATA_SIZE = 1024 |
| 17 | LI_METADATA_OP_NAME = "lightning_indexer_metadata" | 16 | LI_METADATA_OP_NAME = "lightning_indexer_metadata" |
| @@ -19,11 +18,13 @@ LI_METADATA_OP_NAME = "lightning_indexer_metadata" | |||
| 19 | 18 | ||
| 20 | class LightningIndexerOpBuilder(OpBuilder): | 19 | class LightningIndexerOpBuilder(OpBuilder): |
| 21 | def __init__(self): | 20 | def __init__(self): |
| 22 | - super(LightningIndexerOpBuilder, self).__init__("lightning_indexer") | 21 | + super(LightningIndexerOpBuilder, self).__init__( |
| 22 | + "lightning_indexer", category="attention" | ||
| 23 | + ) | ||
| 23 | 24 | ||
| 24 | def sources(self): | 25 | def sources(self): |
| 25 | """Path to C++ source code.""" | 26 | """Path to C++ source code.""" |
| 26 | - return ["ops/csrc/lightning_indexer.cpp"] | 27 | + return ["csrc/attention/lightning_indexer.cpp"] |
| 27 | 28 | ||
| 28 | def schema(self) -> str: | 29 | def schema(self) -> str: |
| 29 | """PyTorch operator signature.""" | 30 | """PyTorch operator signature.""" |
| @@ -69,7 +70,7 @@ class LightningIndexerOpBuilder(OpBuilder): | |||
| 69 | ): | 70 | ): |
| 70 | return torch.empty((LI_METADATA_SIZE), dtype=torch.int32, device="npu") | 71 | return torch.empty((LI_METADATA_SIZE), dtype=torch.int32, device="npu") |
| 71 | 72 | ||
| 72 | - @impl(AS_LIBRARY, self.name, "Meta") | 73 | + @impl(get_as_library(), self.name, "Meta") |
| 73 | def lightning_indexer_meta( | 74 | def lightning_indexer_meta( |
| 74 | q, | 75 | q, |
| 75 | k, | 76 | k, |
| @@ -123,9 +124,10 @@ class LightningIndexerOpBuilder(OpBuilder): | |||
| 123 | 124 | ||
| 124 | # Instantiate the builder | 125 | # Instantiate the builder |
| 125 | lightning_indexer_op_builder = LightningIndexerOpBuilder() | 126 | lightning_indexer_op_builder = LightningIndexerOpBuilder() |
| 127 | +lightning_indexer_op_builder._ensure_initialized() | ||
| 126 | 128 | ||
| 127 | 129 | ||
| 128 | -@impl(AS_LIBRARY, LI_METADATA_OP_NAME, "PrivateUse1") | 130 | +@impl(get_as_library(), LI_METADATA_OP_NAME, "PrivateUse1") |
| 129 | def lightning_indexer_metadata( | 131 | def lightning_indexer_metadata( |
| 130 | num_heads_q: int, | 132 | num_heads_q: int, |
| 131 | num_heads_k: int, | 133 | num_heads_k: int, |
| @@ -221,7 +223,7 @@ def lightning_indexer_metadata_fallback( | |||
| 221 | torch.compiler.allow_in_graph(lightning_indexer_metadata) | 223 | torch.compiler.allow_in_graph(lightning_indexer_metadata) |
| 222 | 224 | ||
| 223 | 225 | ||
| 224 | -@impl(AS_LIBRARY, lightning_indexer_op_builder.name, "PrivateUse1") | 226 | +@impl(get_as_library(), lightning_indexer_op_builder.name, "PrivateUse1") |
| 225 | def lightning_indexer( | 227 | def lightning_indexer( |
| 226 | q, | 228 | q, |
| 227 | k, | 229 | k, |
| @@ -0,0 +1,7 @@ | |||
| 1 | +__all__ = ["mixed_quant_sparse_flash_mla", "mixed_quant_sparse_flash_mla_metadata"] | ||
| 2 | + | ||
| 3 | +from .mixed_quant_sparse_flash_mla import ( | ||
| 4 | + mixed_quant_sparse_flash_mla, | ||
| 5 | + mixed_quant_sparse_flash_mla_metadata, | ||
| 6 | +) | ||
| 7 | +from . import graph_convert_mixed_quant_sparse_flash_mla | ||
Rtorch_extension/cann_ops_transformer/ops/csrc/mixed_quant_sparse_flash_mla.cpp→attention/mixed_quant_sparse_flash_mla/torch_extension/csrc/mixed_quant_sparse_flash_mla.cpp+3-4
| @@ -84,10 +84,9 @@ at::Tensor MixedQuantSparseFlashMlaMetadata( | |||
| 84 | return output; | 84 | return output; |
| 85 | } | 85 | } |
| 86 | 86 | ||
| 87 | -std::tuple<at::Tensor, at::Tensor> | 87 | +std::tuple<at::Tensor, at::Tensor> ConstructMixedQuantSparseFlashMlaAttenOutTensor( |
| 88 | -ConstructMixedQuantSparseFlashMlaAttenOutTensor(const at::Tensor &q, const at::Tensor &oriKv, std::string layoutQStr, | 88 | + const at::Tensor &q, const at::Tensor &oriKv, std::string layoutQStr, std::string layoutKvStr, |
| 89 | - std::string layoutKvStr, const uint64_t &ropeHeadDim, | 89 | + const uint64_t &ropeHeadDim, bool returnSoftmaxLse) |
| 90 | - bool returnSoftmaxLse) | ||
| 91 | { | 90 | { |
| 92 | TORCH_CHECK(layoutQStr == "BSND" || layoutQStr == "TND", "The layout of query only support BSND and TND, but got ", | 91 | TORCH_CHECK(layoutQStr == "BSND" || layoutQStr == "TND", "The layout of query only support BSND and TND, but got ", |
| 93 | layoutQStr); | 92 | layoutQStr); |
Rtorch_extension/cann_ops_transformer/ops/graph_convert/graph_convert_mixed_quant_sparse_flash_mla.py→attention/mixed_quant_sparse_flash_mla/torch_extension/graph_convert_mixed_quant_sparse_flash_mla.py+0-0
File renamed without changes.
Rtorch_extension/cann_ops_transformer/ops/mixed_quant_sparse_flash_mla.py→attention/mixed_quant_sparse_flash_mla/torch_extension/mixed_quant_sparse_flash_mla.py+7-7
| @@ -9,8 +9,7 @@ | |||
| 9 | from typing import Optional | 9 | from typing import Optional |
| 10 | import torch | 10 | import torch |
| 11 | from torch.library import impl | 11 | from torch.library import impl |
| 12 | -from cann_ops_transformer.op_builder.builder import OpBuilder | 12 | +from cann_ops_transformer.op_builder import OpBuilder, get_as_library |
| 13 | -from cann_ops_transformer.op_builder.builder import AS_LIBRARY | ||
| 14 | 13 | ||
| 15 | MQSMLA_METADATA_SIZE = 1024 | 14 | MQSMLA_METADATA_SIZE = 1024 |
| 16 | MQSMLA_METADATA_OP_NAME = "mixed_quant_sparse_flash_mla_metadata" | 15 | MQSMLA_METADATA_OP_NAME = "mixed_quant_sparse_flash_mla_metadata" |
| @@ -19,12 +18,12 @@ MQSMLA_METADATA_OP_NAME = "mixed_quant_sparse_flash_mla_metadata" | |||
| 19 | class MixedQuantSparseFlashMlaOpBuilder(OpBuilder): | 18 | class MixedQuantSparseFlashMlaOpBuilder(OpBuilder): |
| 20 | def __init__(self): | 19 | def __init__(self): |
| 21 | super(MixedQuantSparseFlashMlaOpBuilder, self).__init__( | 20 | super(MixedQuantSparseFlashMlaOpBuilder, self).__init__( |
| 22 | - "mixed_quant_sparse_flash_mla" | 21 | + "mixed_quant_sparse_flash_mla", category="attention" |
| 23 | ) | 22 | ) |
| 24 | 23 | ||
| 25 | def sources(self): | 24 | def sources(self): |
| 26 | """Path to C++ source code.""" | 25 | """Path to C++ source code.""" |
| 27 | - return ["ops/csrc/mixed_quant_sparse_flash_mla.cpp"] | 26 | + return ["csrc/attention/mixed_quant_sparse_flash_mla.cpp"] |
| 28 | 27 | ||
| 29 | def schema(self) -> str: | 28 | def schema(self) -> str: |
| 30 | """PyTorch operator signature.""" | 29 | """PyTorch operator signature.""" |
| @@ -97,7 +96,7 @@ class MixedQuantSparseFlashMlaOpBuilder(OpBuilder): | |||
| 97 | ): | 96 | ): |
| 98 | return torch.empty((MQSMLA_METADATA_SIZE), dtype=torch.int32, device="npu") | 97 | return torch.empty((MQSMLA_METADATA_SIZE), dtype=torch.int32, device="npu") |
| 99 | 98 | ||
| 100 | - @impl(AS_LIBRARY, self.name, "Meta") | 99 | + @impl(get_as_library(), self.name, "Meta") |
| 101 | def mixed_quant_sparse_flash_mla_meta( | 100 | def mixed_quant_sparse_flash_mla_meta( |
| 102 | q, | 101 | q, |
| 103 | ori_kv=None, | 102 | ori_kv=None, |
| @@ -177,9 +176,10 @@ class MixedQuantSparseFlashMlaOpBuilder(OpBuilder): | |||
| 177 | 176 | ||
| 178 | # Instantiate the builder | 177 | # Instantiate the builder |
| 179 | mixed_quant_sparse_flash_mla_op_builder = MixedQuantSparseFlashMlaOpBuilder() | 178 | mixed_quant_sparse_flash_mla_op_builder = MixedQuantSparseFlashMlaOpBuilder() |
| 179 | +mixed_quant_sparse_flash_mla_op_builder._ensure_initialized() | ||
| 180 | 180 | ||
| 181 | 181 | ||
| 182 | -@impl(AS_LIBRARY, MQSMLA_METADATA_OP_NAME, "PrivateUse1") | 182 | +@impl(get_as_library(), MQSMLA_METADATA_OP_NAME, "PrivateUse1") |
| 183 | def mixed_quant_sparse_flash_mla_metadata( | 183 | def mixed_quant_sparse_flash_mla_metadata( |
| 184 | num_heads_q: int, | 184 | num_heads_q: int, |
| 185 | num_heads_kv: int, | 185 | num_heads_kv: int, |
| @@ -336,7 +336,7 @@ def mixed_quant_sparse_flash_mla_metadata_fallback( | |||
| 336 | torch.compiler.allow_in_graph(mixed_quant_sparse_flash_mla_metadata) | 336 | torch.compiler.allow_in_graph(mixed_quant_sparse_flash_mla_metadata) |
| 337 | 337 | ||
| 338 | 338 | ||
| 339 | -@impl(AS_LIBRARY, mixed_quant_sparse_flash_mla_op_builder.name, "PrivateUse1") | 339 | +@impl(get_as_library(), mixed_quant_sparse_flash_mla_op_builder.name, "PrivateUse1") |
| 340 | def mixed_quant_sparse_flash_mla( | 340 | def mixed_quant_sparse_flash_mla( |
| 341 | q, | 341 | q, |
| 342 | ori_kv=None, | 342 | ori_kv=None, |
| @@ -0,0 +1,4 @@ | |||
| 1 | +__all__ = ["msa_index_score"] | ||
| 2 | + | ||
| 3 | +from .msa_index_score import msa_index_score | ||
| 4 | +from . import graph_convert_msa_index_score | ||
Rtorch_extension/cann_ops_transformer/ops/csrc/msa_index_score.cpp→attention/msa_index_score/torch_extension/csrc/msa_index_score.cpp+0-0
File renamed without changes.
Rtorch_extension/cann_ops_transformer/ops/graph_convert/graph_convert_msa_index_score.py→attention/msa_index_score/torch_extension/graph_convert_msa_index_score.py+0-0
File renamed without changes.
Rtorch_extension/cann_ops_transformer/ops/msa_index_score.py→attention/msa_index_score/torch_extension/msa_index_score.py+10-15
| @@ -11,8 +11,7 @@ from typing import Optional | |||
| 11 | 11 | ||
| 12 | import torch | 12 | import torch |
| 13 | from torch.library import impl | 13 | from torch.library import impl |
| 14 | -from cann_ops_transformer.op_builder.builder import OpBuilder | 14 | +from cann_ops_transformer.op_builder import OpBuilder, get_as_library |
| 15 | -from cann_ops_transformer.op_builder.builder import AS_LIBRARY | ||
| 16 | 15 | ||
| 17 | SCORE_STRIDE_ALIGN = 16 | 16 | SCORE_STRIDE_ALIGN = 16 |
| 18 | DEFAULT_SPARSE_MODE = 3 | 17 | DEFAULT_SPARSE_MODE = 3 |
| @@ -39,10 +38,12 @@ def _normalize_layout_key(layout_key: Optional[str]) -> str: | |||
| 39 | 38 | ||
| 40 | class MsaIndexScoreOpBuilder(OpBuilder): | 39 | class MsaIndexScoreOpBuilder(OpBuilder): |
| 41 | def __init__(self): | 40 | def __init__(self): |
| 42 | - super(MsaIndexScoreOpBuilder, self).__init__("msa_index_score") | 41 | + super(MsaIndexScoreOpBuilder, self).__init__( |
| 42 | + "msa_index_score", category="attention" | ||
| 43 | + ) | ||
| 43 | 44 | ||
| 44 | def sources(self): | 45 | def sources(self): |
| 45 | - return ["ops/csrc/msa_index_score.cpp"] | 46 | + return ["csrc/attention/msa_index_score.cpp"] |
| 46 | 47 | ||
| 47 | def schema(self) -> str: | 48 | def schema(self) -> str: |
| 48 | return ( | 49 | return ( |
| @@ -53,7 +54,7 @@ class MsaIndexScoreOpBuilder(OpBuilder): | |||
| 53 | ) | 54 | ) |
| 54 | 55 | ||
| 55 | def register_meta(self): | 56 | def register_meta(self): |
| 56 | - @impl(AS_LIBRARY, self.name, "Meta") | 57 | + @impl(get_as_library(), self.name, "Meta") |
| 57 | def msa_index_score_meta( | 58 | def msa_index_score_meta( |
| 58 | query: torch.Tensor, | 59 | query: torch.Tensor, |
| 59 | key: torch.Tensor, | 60 | key: torch.Tensor, |
| @@ -104,17 +105,10 @@ class MsaIndexScoreOpBuilder(OpBuilder): | |||
| 104 | 105 | ||
| 105 | 106 | ||
| 106 | _msa_index_score_op_builder = MsaIndexScoreOpBuilder() | 107 | _msa_index_score_op_builder = MsaIndexScoreOpBuilder() |
| 107 | -_op_module = None | 108 | +_msa_index_score_op_builder._ensure_initialized() |
| 108 | 109 | ||
| 109 | 110 | ||
| 110 | -def _get_op_module(): | 111 | +@impl(get_as_library(), _msa_index_score_op_builder.name, "PrivateUse1") |
| 111 | - global _op_module | ||
| 112 | - if _op_module is None: | ||
| 113 | - _op_module = _msa_index_score_op_builder.load() | ||
| 114 | - return _op_module | ||
| 115 | - | ||
| 116 | - | ||
| 117 | -@impl(AS_LIBRARY, _msa_index_score_op_builder.name, "PrivateUse1") | ||
| 118 | def _msa_index_score( | 112 | def _msa_index_score( |
| 119 | query: torch.Tensor, | 113 | query: torch.Tensor, |
| 120 | key: torch.Tensor, | 114 | key: torch.Tensor, |
| @@ -130,7 +124,8 @@ def _msa_index_score( | |||
| 130 | init_blocks: int = DEFAULT_INIT_BLOCKS, | 124 | init_blocks: int = DEFAULT_INIT_BLOCKS, |
| 131 | local_blocks: int = DEFAULT_LOCAL_BLOCKS, | 125 | local_blocks: int = DEFAULT_LOCAL_BLOCKS, |
| 132 | ) -> torch.Tensor: | 126 | ) -> torch.Tensor: |
| 133 | - return _get_op_module().msa_index_score( | 127 | + op_module = _msa_index_score_op_builder.load() |
| 128 | + return op_module.msa_index_score( | ||
| 134 | query, | 129 | query, |
| 135 | key, | 130 | key, |
| 136 | block_table, | 131 | block_table, |
| @@ -0,0 +1,4 @@ | |||
| 1 | +__all__ = ["quant_compressor"] | ||
| 2 | + | ||
| 3 | +from .quant_compressor import quant_compressor | ||
| 4 | +from . import graph_convert_quant_compressor | ||
Rtorch_extension/cann_ops_transformer/ops/csrc/quant_compressor.cpp→attention/quant_compressor/torch_extension/csrc/quant_compressor.cpp+0-0
File renamed without changes.
Rtorch_extension/cann_ops_transformer/ops/graph_convert/graph_convert_quant_compressor.py→attention/quant_compressor/torch_extension/graph_convert_quant_compressor.py+0-0
File renamed without changes.
Rtorch_extension/cann_ops_transformer/ops/quant_compressor.py→attention/quant_compressor/torch_extension/quant_compressor.py+8-6
| @@ -11,8 +11,7 @@ from enum import IntEnum | |||
| 11 | from typing import Optional | 11 | from typing import Optional |
| 12 | import torch | 12 | import torch |
| 13 | from torch.library import impl | 13 | from torch.library import impl |
| 14 | -from cann_ops_transformer.op_builder.builder import OpBuilder | 14 | +from cann_ops_transformer.op_builder import OpBuilder, get_as_library |
| 15 | -from cann_ops_transformer.op_builder.builder import AS_LIBRARY | ||
| 16 | 15 | ||
| 17 | 16 | ||
| 18 | class QuantMode(IntEnum): | 17 | class QuantMode(IntEnum): |
| @@ -26,11 +25,13 @@ class CacheMode(IntEnum): | |||
| 26 | 25 | ||
| 27 | class QuantCompressorOpBuilder(OpBuilder): | 26 | class QuantCompressorOpBuilder(OpBuilder): |
| 28 | def __init__(self): | 27 | def __init__(self): |
| 29 | - super(QuantCompressorOpBuilder, self).__init__("quant_compressor") | 28 | + super(QuantCompressorOpBuilder, self).__init__( |
| 29 | + "quant_compressor", category="attention" | ||
| 30 | + ) | ||
| 30 | 31 | ||
| 31 | def sources(self): | 32 | def sources(self): |
| 32 | """Path to C++ source code.""" | 33 | """Path to C++ source code.""" |
| 33 | - return ["ops/csrc/quant_compressor.cpp"] | 34 | + return ["csrc/attention/quant_compressor.cpp"] |
| 34 | 35 | ||
| 35 | def schema(self): | 36 | def schema(self): |
| 36 | """PyTorch operator signature.""" | 37 | """PyTorch operator signature.""" |
| @@ -50,7 +51,7 @@ class QuantCompressorOpBuilder(OpBuilder): | |||
| 50 | Essential for Autograd and FakeTensor support. | 51 | Essential for Autograd and FakeTensor support. |
| 51 | """ | 52 | """ |
| 52 | 53 | ||
| 53 | - @impl(AS_LIBRARY, self.name, "Meta") | 54 | + @impl(get_as_library(), self.name, "Meta") |
| 54 | def quant_compressor_meta( | 55 | def quant_compressor_meta( |
| 55 | x, | 56 | x, |
| 56 | wkv, | 57 | wkv, |
| @@ -86,9 +87,10 @@ class QuantCompressorOpBuilder(OpBuilder): | |||
| 86 | 87 | ||
| 87 | 88 | ||
| 88 | quant_compressor_op_builder = QuantCompressorOpBuilder() | 89 | quant_compressor_op_builder = QuantCompressorOpBuilder() |
| 90 | +quant_compressor_op_builder._ensure_initialized() | ||
| 89 | 91 | ||
| 90 | 92 | ||
| 91 | -@impl(AS_LIBRARY, quant_compressor_op_builder.name, "PrivateUse1") | 93 | +@impl(get_as_library(), quant_compressor_op_builder.name, "PrivateUse1") |
| 92 | def quant_compressor( | 94 | def quant_compressor( |
| 93 | x: torch.Tensor, | 95 | x: torch.Tensor, |
| 94 | wkv: torch.Tensor, | 96 | wkv: torch.Tensor, |
| @@ -0,0 +1,4 @@ | |||
| 1 | +__all__ = ["quant_flash_attn", "quant_flash_attn_metadata"] | ||
| 2 | + | ||
| 3 | +from .quant_flash_attn import quant_flash_attn, quant_flash_attn_metadata | ||
| 4 | +from . import graph_convert_quant_flash_attn | ||
Rtorch_extension/cann_ops_transformer/ops/csrc/quant_flash_attn.cpp→attention/quant_flash_attn/torch_extension/csrc/quant_flash_attn.cpp+17-19
| @@ -23,7 +23,6 @@ const int64_t QUANT_MODE_MXFP4 = 5; | |||
| 23 | const int64_t FLOAT4_E2M1 = 296; | 23 | const int64_t FLOAT4_E2M1 = 296; |
| 24 | const int64_t FLOAT8_E8M0 = 293; | 24 | const int64_t FLOAT8_E8M0 = 293; |
| 25 | 25 | ||
| 26 | - | ||
| 27 | inline int64_t GetQkvDtypeRatio(int64_t quant_mode) | 26 | inline int64_t GetQkvDtypeRatio(int64_t quant_mode) |
| 28 | { | 27 | { |
| 29 | // mxfp4 时 q/k/v 在 Python 端被 pack 成 uint8(每 byte 2 个 fp4 元素), | 28 | // mxfp4 时 q/k/v 在 Python 端被 pack 成 uint8(每 byte 2 个 fp4 元素), |
| @@ -50,14 +49,13 @@ TensorWrapper make_wrapper(const at::Tensor &tensor, const int64_t real_dtype) | |||
| 50 | return wrapper; | 49 | return wrapper; |
| 51 | } | 50 | } |
| 52 | 51 | ||
| 53 | -at::Tensor | 52 | +at::Tensor quant_flash_attn_metadata( |
| 54 | -quant_flash_attn_metadata(const c10::optional<at::Tensor> &cu_seqlens_q, const c10::optional<at::Tensor> &cu_seqlens_kv, | 53 | + const c10::optional<at::Tensor> &cu_seqlens_q, const c10::optional<at::Tensor> &cu_seqlens_kv, |
| 55 | - const c10::optional<at::Tensor> &seqused_q, const c10::optional<at::Tensor> &seqused_kv, | 54 | + const c10::optional<at::Tensor> &seqused_q, const c10::optional<at::Tensor> &seqused_kv, |
| 56 | - const c10::optional<at::Tensor> &v_descale, int64_t batch_size, int64_t max_seqlen_q, | 55 | + const c10::optional<at::Tensor> &v_descale, int64_t batch_size, int64_t max_seqlen_q, int64_t max_seqlen_kv, |
| 57 | - int64_t max_seqlen_kv, int64_t num_heads_q, int64_t num_heads_kv, int64_t head_dim, | 56 | + int64_t num_heads_q, int64_t num_heads_kv, int64_t head_dim, int64_t quant_mode, int64_t mask_mode, |
| 58 | - int64_t quant_mode, int64_t mask_mode, int64_t win_left, int64_t win_right, | 57 | + int64_t win_left, int64_t win_right, std::string layout_q, std::string layout_q_descale, std::string layout_kv, |
| 59 | - std::string layout_q, std::string layout_q_descale, std::string layout_kv, | 58 | + std::string layout_out, const at::Tensor &output) |
| 60 | - std::string layout_out, const at::Tensor &output) | ||
| 61 | { | 59 | { |
| 62 | ACLNN_CMD(aclnnQuantFlashAttnMetadata, cu_seqlens_q, cu_seqlens_kv, seqused_q, seqused_kv, v_descale, batch_size, | 60 | ACLNN_CMD(aclnnQuantFlashAttnMetadata, cu_seqlens_q, cu_seqlens_kv, seqused_q, seqused_kv, v_descale, batch_size, |
| 63 | max_seqlen_q, max_seqlen_kv, num_heads_q, num_heads_kv, head_dim, quant_mode, mask_mode, win_left, | 61 | max_seqlen_q, max_seqlen_kv, num_heads_q, num_heads_kv, head_dim, quant_mode, mask_mode, win_left, |
| @@ -65,16 +63,16 @@ quant_flash_attn_metadata(const c10::optional<at::Tensor> &cu_seqlens_q, const c | |||
| 65 | return output; | 63 | return output; |
| 66 | } | 64 | } |
| 67 | 65 | ||
| 68 | -std::tuple<at::Tensor, at::Tensor> | 66 | +std::tuple<at::Tensor, at::Tensor> quant_flash_attn( |
| 69 | -quant_flash_attn(const at::Tensor &q, const at::Tensor &k, const at::Tensor &v, const at::Tensor &q_descale, | 67 | + const at::Tensor &q, const at::Tensor &k, const at::Tensor &v, const at::Tensor &q_descale, |
| 70 | - const at::Tensor &k_descale, const at::Tensor &v_descale, int64_t quant_mode, | 68 | + const at::Tensor &k_descale, const at::Tensor &v_descale, int64_t quant_mode, |
| 71 | - const c10::optional<at::Tensor> &block_table, const c10::optional<at::Tensor> &p_scale, | 69 | + const c10::optional<at::Tensor> &block_table, const c10::optional<at::Tensor> &p_scale, |
| 72 | - const c10::optional<at::Tensor> &cu_seqlens_q, const c10::optional<at::Tensor> &cu_seqlens_kv, | 70 | + const c10::optional<at::Tensor> &cu_seqlens_q, const c10::optional<at::Tensor> &cu_seqlens_kv, |
| 73 | - const c10::optional<at::Tensor> &seqused_q, const c10::optional<at::Tensor> &seqused_kv, | 71 | + const c10::optional<at::Tensor> &seqused_q, const c10::optional<at::Tensor> &seqused_kv, |
| 74 | - const c10::optional<at::Tensor> &sinks, const c10::optional<at::Tensor> &attn_mask, | 72 | + const c10::optional<at::Tensor> &sinks, const c10::optional<at::Tensor> &attn_mask, |
| 75 | - const c10::optional<at::Tensor> &metadata, double softmax_scale, int64_t mask_mode, int64_t win_left, | 73 | + const c10::optional<at::Tensor> &metadata, double softmax_scale, int64_t mask_mode, int64_t win_left, |
| 76 | - int64_t win_right, int64_t max_seqlen_q, int64_t max_seqlen_kv, std::string layout_q, | 74 | + int64_t win_right, int64_t max_seqlen_q, int64_t max_seqlen_kv, std::string layout_q, std::string layout_q_descale, |
| 77 | - std::string layout_q_descale, std::string layout_kv, std::string layout_out, bool return_softmax_lse) | 75 | + std::string layout_kv, std::string layout_out, bool return_softmax_lse) |
| 78 | { | 76 | { |
| 79 | const c10::string_view device = "npu"; | 77 | const c10::string_view device = "npu"; |
| 80 | at::Device outputDevice = at::Device(std::string(device)); | 78 | at::Device outputDevice = at::Device(std::string(device)); |
Rtorch_extension/cann_ops_transformer/ops/graph_convert/graph_convert_quant_flash_attn.py→attention/quant_flash_attn/torch_extension/graph_convert_quant_flash_attn.py+51-10
| @@ -5,10 +5,18 @@ try: | |||
| 5 | from torch.library import impl | 5 | from torch.library import impl |
| 6 | from torchair._ge_concrete_graph import ge_apis as ge | 6 | from torchair._ge_concrete_graph import ge_apis as ge |
| 7 | from torchair.ge._ge_graph import Tensor, TensorSpec | 7 | from torchair.ge._ge_graph import Tensor, TensorSpec |
| 8 | - from torchair._ge_concrete_graph.fx2ge_converter import declare_supported, register_fx_node_ge_converter | 8 | + from torchair._ge_concrete_graph.fx2ge_converter import ( |
| 9 | + declare_supported, | ||
| 10 | + register_fx_node_ge_converter, | ||
| 11 | + ) | ||
| 9 | from torchair._ge_concrete_graph.supported_declaration import Support | 12 | from torchair._ge_concrete_graph.supported_declaration import Support |
| 10 | from typing import Any, Dict, List, Tuple, Union, Callable, Optional | 13 | from typing import Any, Dict, List, Tuple, Union, Callable, Optional |
| 11 | - from torchair._ge_concrete_graph.ge_ir_pb2 import GraphDef, OpDef, TensorDescriptor, TensorDef | 14 | + from torchair._ge_concrete_graph.ge_ir_pb2 import ( |
| 15 | + GraphDef, | ||
| 16 | + OpDef, | ||
| 17 | + TensorDescriptor, | ||
| 18 | + TensorDef, | ||
| 19 | + ) | ||
| 12 | from torchair.ge._ge_graph import get_default_ge_graph, next_unique_name | 20 | from torchair.ge._ge_graph import get_default_ge_graph, next_unique_name |
| 13 | from torchair.ge._ge_graph import auto_convert_to_tensor | 21 | from torchair.ge._ge_graph import auto_convert_to_tensor |
| 14 | from torchair.ge._ge_graph import Tensor, TensorSpec, DataType, TensorType | 22 | from torchair.ge._ge_graph import Tensor, TensorSpec, DataType, TensorType |
| @@ -17,14 +25,45 @@ try: | |||
| 17 | from torchair.ge._ge_graph import get_invalid_desc | 25 | from torchair.ge._ge_graph import get_invalid_desc |
| 18 | from torchair._ge_concrete_graph.compat_ir import ge_op, IrDef | 26 | from torchair._ge_concrete_graph.compat_ir import ge_op, IrDef |
| 19 | from torchair.ge import attr | 27 | from torchair.ge import attr |
| 28 | + | ||
| 20 | _TORCHAIR_AVAILABLE = True | 29 | _TORCHAIR_AVAILABLE = True |
| 21 | except ImportError: | 30 | except ImportError: |
| 22 | _TORCHAIR_AVAILABLE = False | 31 | _TORCHAIR_AVAILABLE = False |
| 23 | 32 | ||
| 24 | if _TORCHAIR_AVAILABLE: | 33 | if _TORCHAIR_AVAILABLE: |
| 34 | + | ||
| 25 | @auto_convert_to_tensor( | 35 | @auto_convert_to_tensor( |
| 26 | - [False, False, False, False, False, False, False, False, False, False, False, False, False], | 36 | + [ |
| 27 | - [False, False, False, True, True, True, True, True, True, True, True, True, True]) | 37 | + False, |
| 38 | + False, | ||
| 39 | + False, | ||
| 40 | + False, | ||
| 41 | + False, | ||
| 42 | + False, | ||
| 43 | + False, | ||
| 44 | + False, | ||
| 45 | + False, | ||
| 46 | + False, | ||
| 47 | + False, | ||
| 48 | + False, | ||
| 49 | + False, | ||
| 50 | + ], | ||
| 51 | + [ | ||
| 52 | + False, | ||
| 53 | + False, | ||
| 54 | + False, | ||
| 55 | + True, | ||
| 56 | + True, | ||
| 57 | + True, | ||
| 58 | + True, | ||
| 59 | + True, | ||
| 60 | + True, | ||
| 61 | + True, | ||
| 62 | + True, | ||
| 63 | + True, | ||
| 64 | + True, | ||
| 65 | + ], | ||
| 66 | + ) | ||
| 28 | def QuantFlashAttn( | 67 | def QuantFlashAttn( |
| 29 | q: Tensor, | 68 | q: Tensor, |
| 30 | k: Tensor, | 69 | k: Tensor, |
| @@ -51,12 +90,14 @@ if _TORCHAIR_AVAILABLE: | |||
| 51 | layout_q: str = "BSND", | 90 | layout_q: str = "BSND", |
| 52 | layout_kv: str = "BSND", | 91 | layout_kv: str = "BSND", |
| 53 | layout_out: str = "BSND", | 92 | layout_out: str = "BSND", |
| 54 | - return_softmax_lse: bool = False): | 93 | + return_softmax_lse: bool = False, |
| 55 | - | 94 | + ): |
| 56 | result = q.new_empty(q.size()) | 95 | result = q.new_empty(q.size()) |
| 57 | return result | 96 | return result |
| 58 | 97 | ||
| 59 | - @register_fx_node_ge_converter(torch.ops.cann_ops_transformer.quant_flash_attn.default) | 98 | + @register_fx_node_ge_converter( |
| 99 | + torch.ops.cann_ops_transformer.quant_flash_attn.default | ||
| 100 | + ) | ||
| 60 | def convert_quant_flash_attn( | 101 | def convert_quant_flash_attn( |
| 61 | q: Tensor, | 102 | q: Tensor, |
| 62 | k: Tensor, | 103 | k: Tensor, |
| @@ -83,6 +124,6 @@ if _TORCHAIR_AVAILABLE: | |||
| 83 | layout_q: str = "BSND", | 124 | layout_q: str = "BSND", |
| 84 | layout_kv: str = "BSND", | 125 | layout_kv: str = "BSND", |
| 85 | layout_out: str = "BSND", | 126 | layout_out: str = "BSND", |
| 86 | - return_softmax_lse: bool = False): | 127 | + return_softmax_lse: bool = False, |
| 87 | - | 128 | + ): |
| 88 | - raise AssertionError(f"GE not supported!") | 129 | + raise AssertionError("GE not supported!") |
Rtorch_extension/cann_ops_transformer/ops/quant_flash_attn.py→attention/quant_flash_attn/torch_extension/quant_flash_attn.py+10-7
| @@ -12,8 +12,7 @@ from enum import IntEnum | |||
| 12 | import torch | 12 | import torch |
| 13 | import torch_npu | 13 | import torch_npu |
| 14 | from torch.library import impl | 14 | from torch.library import impl |
| 15 | -from cann_ops_transformer.op_builder.builder import OpBuilder | 15 | +from cann_ops_transformer.op_builder import OpBuilder, get_as_library |
| 16 | -from cann_ops_transformer.op_builder.builder import AS_LIBRARY | ||
| 17 | 16 | ||
| 18 | QFA_METADATA_OP_NAME = "quant_flash_attn_metadata" | 17 | QFA_METADATA_OP_NAME = "quant_flash_attn_metadata" |
| 19 | 18 | ||
| @@ -85,11 +84,13 @@ def _calculate_metadata_size(): | |||
| 85 | 84 | ||
| 86 | class QuantFlashAttnOpBuilder(OpBuilder): | 85 | class QuantFlashAttnOpBuilder(OpBuilder): |
| 87 | def __init__(self): | 86 | def __init__(self): |
| 88 | - super(QuantFlashAttnOpBuilder, self).__init__("quant_flash_attn") | 87 | + super(QuantFlashAttnOpBuilder, self).__init__( |
| 88 | + "quant_flash_attn", category="attention" | ||
| 89 | + ) | ||
| 89 | 90 | ||
| 90 | def sources(self): | 91 | def sources(self): |
| 91 | """Path to C++ source code.""" | 92 | """Path to C++ source code.""" |
| 92 | - return ["ops/csrc/quant_flash_attn.cpp"] | 93 | + return ["csrc/attention/quant_flash_attn.cpp"] |
| 93 | 94 | ||
| 94 | def schema(self) -> str: | 95 | def schema(self) -> str: |
| 95 | """PyTorch operator signature.""" | 96 | """PyTorch operator signature.""" |
| @@ -144,7 +145,7 @@ class QuantFlashAttnOpBuilder(OpBuilder): | |||
| 144 | metadata_size = _calculate_metadata_size() | 145 | metadata_size = _calculate_metadata_size() |
| 145 | return torch.empty((metadata_size,), dtype=torch.int32, device="npu") | 146 | return torch.empty((metadata_size,), dtype=torch.int32, device="npu") |
| 146 | 147 | ||
| 147 | - @impl(AS_LIBRARY, self.name, "Meta") | 148 | + @impl(get_as_library(), self.name, "Meta") |
| 148 | def quant_flash_attn_meta( | 149 | def quant_flash_attn_meta( |
| 149 | q: torch.Tensor, | 150 | q: torch.Tensor, |
| 150 | k: torch.Tensor, | 151 | k: torch.Tensor, |
| @@ -224,9 +225,11 @@ class QuantFlashAttnOpBuilder(OpBuilder): | |||
| 224 | 225 | ||
| 225 | # Instantiate the builder | 226 | # Instantiate the builder |
| 226 | quant_flash_attn_op_builder = QuantFlashAttnOpBuilder() | 227 | quant_flash_attn_op_builder = QuantFlashAttnOpBuilder() |
| 228 | +quant_flash_attn_op_builder._ensure_initialized() | ||
| 229 | +op_module = quant_flash_attn_op_builder.load() | ||
| 227 | 230 | ||
| 228 | 231 | ||
| 229 | -@impl(AS_LIBRARY, QFA_METADATA_OP_NAME, "PrivateUse1") | 232 | +@impl(get_as_library(), QFA_METADATA_OP_NAME, "PrivateUse1") |
| 230 | def quant_flash_attn_metadata( | 233 | def quant_flash_attn_metadata( |
| 231 | num_heads_q: int, | 234 | num_heads_q: int, |
| 232 | num_heads_kv: int, | 235 | num_heads_kv: int, |
| @@ -344,7 +347,7 @@ def quant_flash_attn_metadata_fallback( | |||
| 344 | ) | 347 | ) |
| 345 | 348 | ||
| 346 | 349 | ||
| 347 | -@impl(AS_LIBRARY, quant_flash_attn_op_builder.name, "PrivateUse1") | 350 | +@impl(get_as_library(), quant_flash_attn_op_builder.name, "PrivateUse1") |
| 348 | def quant_flash_attn( | 351 | def quant_flash_attn( |
| 349 | q: torch.Tensor, | 352 | q: torch.Tensor, |
| 350 | k: torch.Tensor, | 353 | k: torch.Tensor, |
| @@ -0,0 +1,7 @@ | |||
| 1 | +__all__ = ["quant_lightning_indexer", "quant_lightning_indexer_metadata"] | ||
| 2 | + | ||
| 3 | +from .quant_lightning_indexer import ( | ||
| 4 | + quant_lightning_indexer, | ||
| 5 | + quant_lightning_indexer_metadata, | ||
| 6 | +) | ||
| 7 | +from . import graph_convert_quant_lightning_indexer | ||
Rtorch_extension/cann_ops_transformer/ops/csrc/quant_lightning_indexer.cpp→attention/quant_lightning_indexer_v2/torch_extension/csrc/quant_lightning_indexer.cpp+0-0
File renamed without changes.
Rtorch_extension/cann_ops_transformer/ops/graph_convert/graph_convert_quant_lightning_indexer.py→attention/quant_lightning_indexer_v2/torch_extension/graph_convert_quant_lightning_indexer.py+0-0
File renamed without changes.
Rtorch_extension/cann_ops_transformer/ops/quant_lightning_indexer.py→attention/quant_lightning_indexer_v2/torch_extension/quant_lightning_indexer.py+9-7
| @@ -10,8 +10,7 @@ | |||
| 10 | from typing import Optional | 10 | from typing import Optional |
| 11 | import torch | 11 | import torch |
| 12 | from torch.library import impl | 12 | from torch.library import impl |
| 13 | -from cann_ops_transformer.op_builder.builder import OpBuilder | 13 | +from cann_ops_transformer.op_builder import OpBuilder, get_as_library |
| 14 | -from cann_ops_transformer.op_builder.builder import AS_LIBRARY | ||
| 15 | 14 | ||
| 16 | QLI_METADATA_SIZE = 1024 | 15 | QLI_METADATA_SIZE = 1024 |
| 17 | QLI_METADATA_OP_NAME = "quant_lightning_indexer_metadata" | 16 | QLI_METADATA_OP_NAME = "quant_lightning_indexer_metadata" |
| @@ -19,11 +18,13 @@ QLI_METADATA_OP_NAME = "quant_lightning_indexer_metadata" | |||
| 19 | 18 | ||
| 20 | class QuantLightningIndexerOpBuilder(OpBuilder): | 19 | class QuantLightningIndexerOpBuilder(OpBuilder): |
| 21 | def __init__(self): | 20 | def __init__(self): |
| 22 | - super(QuantLightningIndexerOpBuilder, self).__init__("quant_lightning_indexer") | 21 | + super(QuantLightningIndexerOpBuilder, self).__init__( |
| 22 | + "quant_lightning_indexer", category="attention" | ||
| 23 | + ) | ||
| 23 | 24 | ||
| 24 | def sources(self): | 25 | def sources(self): |
| 25 | """Path to C++ source code.""" | 26 | """Path to C++ source code.""" |
| 26 | - return ["ops/csrc/quant_lightning_indexer.cpp"] | 27 | + return ["csrc/attention/quant_lightning_indexer.cpp"] |
| 27 | 28 | ||
| 28 | def schema(self) -> str: | 29 | def schema(self) -> str: |
| 29 | """PyTorch operator signature.""" | 30 | """PyTorch operator signature.""" |
| @@ -69,7 +70,7 @@ class QuantLightningIndexerOpBuilder(OpBuilder): | |||
| 69 | ): | 70 | ): |
| 70 | return torch.empty((QLI_METADATA_SIZE), dtype=torch.int32, device="npu") | 71 | return torch.empty((QLI_METADATA_SIZE), dtype=torch.int32, device="npu") |
| 71 | 72 | ||
| 72 | - @impl(AS_LIBRARY, self.name, "Meta") | 73 | + @impl(get_as_library(), self.name, "Meta") |
| 73 | def quant_lightning_indexer_meta( | 74 | def quant_lightning_indexer_meta( |
| 74 | query, | 75 | query, |
| 75 | key, | 76 | key, |
| @@ -130,9 +131,10 @@ class QuantLightningIndexerOpBuilder(OpBuilder): | |||
| 130 | 131 | ||
| 131 | # Instantiate the builder | 132 | # Instantiate the builder |
| 132 | quant_lightning_indexer_op_builder = QuantLightningIndexerOpBuilder() | 133 | quant_lightning_indexer_op_builder = QuantLightningIndexerOpBuilder() |
| 134 | +quant_lightning_indexer_op_builder._ensure_initialized() | ||
| 133 | 135 | ||
| 134 | 136 | ||
| 135 | -@impl(AS_LIBRARY, QLI_METADATA_OP_NAME, "PrivateUse1") | 137 | +@impl(get_as_library(), QLI_METADATA_OP_NAME, "PrivateUse1") |
| 136 | def quant_lightning_indexer_metadata( | 138 | def quant_lightning_indexer_metadata( |
| 137 | num_heads_q: int, | 139 | num_heads_q: int, |
| 138 | num_heads_k: int, | 140 | num_heads_k: int, |
| @@ -232,7 +234,7 @@ def quant_lightning_indexer_metadata_fallback( | |||
| 232 | torch.compiler.allow_in_graph(quant_lightning_indexer_metadata) | 234 | torch.compiler.allow_in_graph(quant_lightning_indexer_metadata) |
| 233 | 235 | ||
| 234 | 236 | ||
| 235 | -@impl(AS_LIBRARY, quant_lightning_indexer_op_builder.name, "PrivateUse1") | 237 | +@impl(get_as_library(), quant_lightning_indexer_op_builder.name, "PrivateUse1") |
| 236 | def quant_lightning_indexer( | 238 | def quant_lightning_indexer( |
| 237 | query, | 239 | query, |
| 238 | key, | 240 | key, |
| @@ -0,0 +1,6 @@ | |||
| 1 | +__all__ = ["quant_sparse_flash_mla", "quant_sparse_flash_mla_metadata"] | ||
| 2 | + | ||
| 3 | +from .quant_sparse_flash_mla import ( | ||
| 4 | + quant_sparse_flash_mla, | ||
| 5 | + quant_sparse_flash_mla_metadata, | ||
| 6 | +) | ||
Rtorch_extension/cann_ops_transformer/ops/csrc/quant_sparse_flash_mla.cpp→attention/quant_sparse_flash_mla/torch_extension/csrc/quant_sparse_flash_mla.cpp+31-30
| @@ -39,10 +39,10 @@ at::Tensor QuantSparseFlashMlaMetadata( | |||
| 39 | const c10::optional<at::Tensor> &cuSeqlensCmpKv, const c10::optional<at::Tensor> &sequsedQ, | 39 | const c10::optional<at::Tensor> &cuSeqlensCmpKv, const c10::optional<at::Tensor> &sequsedQ, |
| 40 | const c10::optional<at::Tensor> &sequsedOriKv, const c10::optional<at::Tensor> &sequsedCmpKv, | 40 | const c10::optional<at::Tensor> &sequsedOriKv, const c10::optional<at::Tensor> &sequsedCmpKv, |
| 41 | const c10::optional<at::Tensor> &cmpResidualKv, const c10::optional<at::Tensor> &oriTopkLength, | 41 | const c10::optional<at::Tensor> &cmpResidualKv, const c10::optional<at::Tensor> &oriTopkLength, |
| 42 | - const c10::optional<at::Tensor> &cmpTopkLength, int64_t batchSize, int64_t maxSeqlenQ, | 42 | + const c10::optional<at::Tensor> &cmpTopkLength, int64_t batchSize, int64_t maxSeqlenQ, int64_t maxSeqlenOriKv, |
| 43 | - int64_t maxSeqlenOriKv, int64_t maxSeqlenCmpKv, int64_t oriTopk, int64_t cmpTopk, | 43 | + int64_t maxSeqlenCmpKv, int64_t oriTopk, int64_t cmpTopk, int64_t cmpRatio, int64_t oriMaskMode, |
| 44 | - int64_t cmpRatio, int64_t oriMaskMode, int64_t cmpMaskMode, int64_t oriWinLeft, int64_t oriWinRight, | 44 | + int64_t cmpMaskMode, int64_t oriWinLeft, int64_t oriWinRight, c10::string_view layoutQ, c10::string_view layoutKv, |
| 45 | - c10::string_view layoutQ, c10::string_view layoutKv, bool hasOriKv, bool hasCmpKv) | 45 | + bool hasOriKv, bool hasCmpKv) |
| 46 | { | 46 | { |
| 47 | at::Device outputDevice = at::Device(std::string("npu")); | 47 | at::Device outputDevice = at::Device(std::string("npu")); |
| 48 | if (cuSeqlensQ.has_value()) { | 48 | if (cuSeqlensQ.has_value()) { |
| @@ -82,34 +82,37 @@ at::Tensor QuantSparseFlashMlaMetadata( | |||
| 82 | char *layoutQPtr = const_cast<char *>(layoutQStr.c_str()); | 82 | char *layoutQPtr = const_cast<char *>(layoutQStr.c_str()); |
| 83 | char *layoutKvPtr = const_cast<char *>(layoutKvStr.c_str()); | 83 | char *layoutKvPtr = const_cast<char *>(layoutKvStr.c_str()); |
| 84 | 84 | ||
| 85 | - ACLNN_CMD(aclnnQuantSparseFlashMlaMetadata, cuSeqlensQVal, cuSeqlensOriKvVal, cuSeqlensCmpKvVal, | 85 | + ACLNN_CMD(aclnnQuantSparseFlashMlaMetadata, cuSeqlensQVal, cuSeqlensOriKvVal, cuSeqlensCmpKvVal, sequsedQVal, |
| 86 | - sequsedQVal, sequsedOriKvVal, sequsedCmpKvVal, cmpResidualKvVal, oriTopkLengthVal, | 86 | + sequsedOriKvVal, sequsedCmpKvVal, cmpResidualKvVal, oriTopkLengthVal, cmpTopkLengthVal, numHeadsQ, |
| 87 | - cmpTopkLengthVal, numHeadsQ, numHeadsKv, headDim, quantMode, batchSize, maxSeqlenQ, | 87 | + numHeadsKv, headDim, quantMode, batchSize, maxSeqlenQ, maxSeqlenOriKv, maxSeqlenCmpKv, oriTopk, cmpTopk, |
| 88 | - maxSeqlenOriKv, maxSeqlenCmpKv, oriTopk, cmpTopk, cmpRatio, oriMaskMode, | 88 | + cmpRatio, oriMaskMode, cmpMaskMode, oriWinLeft, oriWinRight, layoutQPtr, layoutKvPtr, hasOriKv, hasCmpKv, |
| 89 | - cmpMaskMode, oriWinLeft, oriWinRight, layoutQPtr, layoutKvPtr, hasOriKv, hasCmpKv, | ||
| 90 | output); | 89 | output); |
| 91 | return output; | 90 | return output; |
| 92 | } | 91 | } |
| 93 | 92 | ||
| 94 | -std::tuple<at::Tensor, at::Tensor> | 93 | +std::tuple<at::Tensor, at::Tensor> ConstructQuantSparseFlashMlaAttenOutTensor(const at::Tensor &q, |
| 95 | -ConstructQuantSparseFlashMlaAttenOutTensor(const at::Tensor &q, const at::Tensor &oriKv, std::string layoutQStr, | 94 | + const at::Tensor &oriKv, |
| 96 | - std::string layoutKvStr, bool returnSoftmaxLse) | 95 | + std::string layoutQStr, |
| 96 | + std::string layoutKvStr, | ||
| 97 | + bool returnSoftmaxLse) | ||
| 97 | { | 98 | { |
| 98 | - TORCH_CHECK(layoutQStr == "BSND" || layoutQStr == "TND", | 99 | + TORCH_CHECK(layoutQStr == "BSND" || layoutQStr == "TND", "The layout of query only support BSND and TND, but got ", |
| 99 | - "The layout of query only support BSND and TND, but got ", layoutQStr); | 100 | + layoutQStr); |
| 100 | for (auto i = 0; i < q.sizes().size(); i++) { | 101 | for (auto i = 0; i < q.sizes().size(); i++) { |
| 101 | - TORCH_CHECK(q.size(i) > 0, "All values within query's shape should be greater " | 102 | + TORCH_CHECK(q.size(i) > 0, |
| 102 | - "than 0, but shape[", i, "] is ", q.size(i)); | 103 | + "All values within query's shape should be greater " |
| 104 | + "than 0, but shape[", | ||
| 105 | + i, "] is ", q.size(i)); | ||
| 103 | } | 106 | } |
| 104 | at::SmallVector<int64_t, SIZE> attenOutSize; | 107 | at::SmallVector<int64_t, SIZE> attenOutSize; |
| 105 | at::SmallVector<int64_t, SIZE> softmaxLseSize; | 108 | at::SmallVector<int64_t, SIZE> softmaxLseSize; |
| 106 | if (layoutQStr == "BSND") { | 109 | if (layoutQStr == "BSND") { |
| 107 | - TORCH_CHECK(q.dim() == DIM_4, | 110 | + TORCH_CHECK(q.dim() == DIM_4, "When the layout of query is BSND, the query dimension must be 4, but got ", |
| 108 | - "When the layout of query is BSND, the query dimension must be 4, but got ", q.dim()); | 111 | + q.dim()); |
| 109 | attenOutSize = {q.size(DIM_0), q.size(DIM_1), q.size(DIM_2), q.size(DIM_3)}; | 112 | attenOutSize = {q.size(DIM_0), q.size(DIM_1), q.size(DIM_2), q.size(DIM_3)}; |
| 110 | } else { | 113 | } else { |
| 111 | - TORCH_CHECK(q.dim() == DIM_3, | 114 | + TORCH_CHECK(q.dim() == DIM_3, "When the layout of query is TND, the query dimension must be 3, but got ", |
| 112 | - "When the layout of query is TND, the query dimension must be 3, but got ", q.dim()); | 115 | + q.dim()); |
| 113 | attenOutSize = {q.size(DIM_0), q.size(DIM_1), q.size(DIM_2)}; | 116 | attenOutSize = {q.size(DIM_0), q.size(DIM_1), q.size(DIM_2)}; |
| 114 | } | 117 | } |
| 115 | at::Tensor attenOut = at::empty(attenOutSize, q.options().dtype(torch::kBFloat16)); | 118 | at::Tensor attenOut = at::empty(attenOutSize, q.options().dtype(torch::kBFloat16)); |
| @@ -164,7 +167,7 @@ std::tuple<at::Tensor, at::Tensor> QuantSparseFlashMla( | |||
| 164 | 167 | ||
| 165 | std::string layoutQStr = std::string(layoutQ); | 168 | std::string layoutQStr = std::string(layoutQ); |
| 166 | std::string layoutKvStr = std::string(layoutKv); | 169 | std::string layoutKvStr = std::string(layoutKv); |
| 167 | - const at::Tensor& oriKvVal = *oriKv; | 170 | + const at::Tensor &oriKvVal = *oriKv; |
| 168 | // convert str | 171 | // convert str |
| 169 | char *layoutQPtr = const_cast<char *>(layoutQStr.c_str()); | 172 | char *layoutQPtr = const_cast<char *>(layoutQStr.c_str()); |
| 170 | char *layoutKvPtr = const_cast<char *>(layoutKvStr.c_str()); | 173 | char *layoutKvPtr = const_cast<char *>(layoutKvStr.c_str()); |
| @@ -174,7 +177,7 @@ std::tuple<at::Tensor, at::Tensor> QuantSparseFlashMla( | |||
| 174 | op_api::ConstructQuantSparseFlashMlaAttenOutTensor(q, oriKvVal, layoutQStr, layoutKvStr, returnSoftmaxLse); | 177 | op_api::ConstructQuantSparseFlashMlaAttenOutTensor(q, oriKvVal, layoutQStr, layoutKvStr, returnSoftmaxLse); |
| 175 | at::Tensor attenOut = std::get<0>(quantSparseFlashMlaAttenOut); | 178 | at::Tensor attenOut = std::get<0>(quantSparseFlashMlaAttenOut); |
| 176 | at::Tensor softmaxLse = std::get<1>(quantSparseFlashMlaAttenOut); | 179 | at::Tensor softmaxLse = std::get<1>(quantSparseFlashMlaAttenOut); |
| 177 | - | 180 | + |
| 178 | if (quantMode == 1) { // HIFLOAT8 FULL QUANT | 181 | if (quantMode == 1) { // HIFLOAT8 FULL QUANT |
| 179 | at::Tensor nullTensor; | 182 | at::Tensor nullTensor; |
| 180 | auto oriKvValue = oriKv.has_value() ? oriKv.value() : nullTensor; | 183 | auto oriKvValue = oriKv.has_value() ? oriKv.value() : nullTensor; |
| @@ -182,20 +185,18 @@ std::tuple<at::Tensor, at::Tensor> QuantSparseFlashMla( | |||
| 182 | TensorWrapper qWrapper = QsmlaMakeWrapper(q, ACL_HIFLOAT8); | 185 | TensorWrapper qWrapper = QsmlaMakeWrapper(q, ACL_HIFLOAT8); |
| 183 | TensorWrapper oriKvWrapper = QsmlaMakeWrapper(oriKvValue, ACL_HIFLOAT8); | 186 | TensorWrapper oriKvWrapper = QsmlaMakeWrapper(oriKvValue, ACL_HIFLOAT8); |
| 184 | TensorWrapper cmpKvWrapper = QsmlaMakeWrapper(cmpKvValue, ACL_HIFLOAT8); | 187 | TensorWrapper cmpKvWrapper = QsmlaMakeWrapper(cmpKvValue, ACL_HIFLOAT8); |
| 185 | - ACLNN_CMD(aclnnQuantSparseFlashMla, qWrapper, oriKvWrapper, cmpKvWrapper, qDescale, oriKvDescale, | 188 | + ACLNN_CMD(aclnnQuantSparseFlashMla, qWrapper, oriKvWrapper, cmpKvWrapper, qDescale, oriKvDescale, cmpKvDescale, |
| 186 | - cmpKvDescale, oriSparseIndices, cmpSparseIndices, oriBlockTable, cmpBlockTable, | 189 | + oriSparseIndices, cmpSparseIndices, oriBlockTable, cmpBlockTable, cuSeqlensQ, cuSeqlensOriKv, |
| 187 | - cuSeqlensQ, cuSeqlensOriKv, cuSeqlensCmpKv, sequsedQ, sequsedOriKv, sequsedCmpKv, | 190 | + cuSeqlensCmpKv, sequsedQ, sequsedOriKv, sequsedCmpKv, cmpResidualKv, oriTopkLength, cmpTopkLength, |
| 188 | - cmpResidualKv, oriTopkLength, cmpTopkLength, sinks, metadata, quantMode, softmaxScale, | 191 | + sinks, metadata, quantMode, softmaxScale, cmpRatio, oriMaskMode, cmpMaskMode, oriWinLeft, oriWinRight, |
| 189 | - cmpRatio, oriMaskMode, cmpMaskMode, oriWinLeft, oriWinRight, layoutQPtr, layoutKvPtr, | 192 | + layoutQPtr, layoutKvPtr, topkValueMode, returnSoftmaxLse, attenOut, softmaxLse); |
| 190 | - topkValueMode, returnSoftmaxLse, attenOut, softmaxLse); | ||
| 191 | } | 193 | } |
| 192 | return std::tuple<at::Tensor, at::Tensor>(attenOut, softmaxLse); | 194 | return std::tuple<at::Tensor, at::Tensor>(attenOut, softmaxLse); |
| 193 | } | 195 | } |
| 194 | 196 | ||
| 195 | PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) | 197 | PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) |
| 196 | { | 198 | { |
| 197 | - m.def("quant_sparse_flash_mla_metadata", &QuantSparseFlashMlaMetadata, | 199 | + m.def("quant_sparse_flash_mla_metadata", &QuantSparseFlashMlaMetadata, "quant_sparse_flash_mla_metadata"); |
| 198 | - "quant_sparse_flash_mla_metadata"); | ||
| 199 | m.def("quant_sparse_flash_mla", &QuantSparseFlashMla, "quant_sparse_flash_mla"); | 200 | m.def("quant_sparse_flash_mla", &QuantSparseFlashMla, "quant_sparse_flash_mla"); |
| 200 | } | 201 | } |
| 201 | } // namespace op_api | 202 | } // namespace op_api |
Rtorch_extension/cann_ops_transformer/ops/quant_sparse_flash_mla.py→attention/quant_sparse_flash_mla/torch_extension/quant_sparse_flash_mla.py+9-7
| @@ -10,8 +10,7 @@ from typing import Optional | |||
| 10 | import torch | 10 | import torch |
| 11 | import torch_npu | 11 | import torch_npu |
| 12 | from torch.library import impl | 12 | from torch.library import impl |
| 13 | -from cann_ops_transformer.op_builder.builder import OpBuilder | 13 | +from cann_ops_transformer.op_builder import OpBuilder, get_as_library |
| 14 | -from cann_ops_transformer.op_builder.builder import AS_LIBRARY | ||
| 15 | 14 | ||
| 16 | QSMLA_METADATA_SIZE = 1024 | 15 | QSMLA_METADATA_SIZE = 1024 |
| 17 | QSMLA_METADATA_OP_NAME = "quant_sparse_flash_mla_metadata" | 16 | QSMLA_METADATA_OP_NAME = "quant_sparse_flash_mla_metadata" |
| @@ -19,11 +18,13 @@ QSMLA_METADATA_OP_NAME = "quant_sparse_flash_mla_metadata" | |||
| 19 | 18 | ||
| 20 | class QuantSparseFlashMlaOpBuilder(OpBuilder): | 19 | class QuantSparseFlashMlaOpBuilder(OpBuilder): |
| 21 | def __init__(self): | 20 | def __init__(self): |
| 22 | - super(QuantSparseFlashMlaOpBuilder, self).__init__("quant_sparse_flash_mla") | 21 | + super(QuantSparseFlashMlaOpBuilder, self).__init__( |
| 22 | + "quant_sparse_flash_mla", category="attention" | ||
| 23 | + ) | ||
| 23 | 24 | ||
| 24 | def sources(self): | 25 | def sources(self): |
| 25 | """Path to C++ source code.""" | 26 | """Path to C++ source code.""" |
| 26 | - return ["ops/csrc/quant_sparse_flash_mla.cpp"] | 27 | + return ["csrc/attention/quant_sparse_flash_mla.cpp"] |
| 27 | 28 | ||
| 28 | def schema(self) -> str: | 29 | def schema(self) -> str: |
| 29 | """PyTorch operator signature.""" | 30 | """PyTorch operator signature.""" |
| @@ -96,7 +97,7 @@ class QuantSparseFlashMlaOpBuilder(OpBuilder): | |||
| 96 | ): | 97 | ): |
| 97 | return torch.empty((QSMLA_METADATA_SIZE), dtype=torch.int32, device="npu") | 98 | return torch.empty((QSMLA_METADATA_SIZE), dtype=torch.int32, device="npu") |
| 98 | 99 | ||
| 99 | - @impl(AS_LIBRARY, self.name, "Meta") | 100 | + @impl(get_as_library(), self.name, "Meta") |
| 100 | def quant_sparse_flash_mla_meta( | 101 | def quant_sparse_flash_mla_meta( |
| 101 | q, | 102 | q, |
| 102 | ori_kv=None, | 103 | ori_kv=None, |
| @@ -178,9 +179,10 @@ class QuantSparseFlashMlaOpBuilder(OpBuilder): | |||
| 178 | 179 | ||
| 179 | # Instantiate the builder | 180 | # Instantiate the builder |
| 180 | quant_sparse_flash_mla_op_builder = QuantSparseFlashMlaOpBuilder() | 181 | quant_sparse_flash_mla_op_builder = QuantSparseFlashMlaOpBuilder() |
| 182 | +quant_sparse_flash_mla_op_builder._ensure_initialized() | ||
| 181 | 183 | ||
| 182 | 184 | ||
| 183 | -@impl(AS_LIBRARY, QSMLA_METADATA_OP_NAME, "PrivateUse1") | 185 | +@impl(get_as_library(), QSMLA_METADATA_OP_NAME, "PrivateUse1") |
| 184 | def quant_sparse_flash_mla_metadata( | 186 | def quant_sparse_flash_mla_metadata( |
| 185 | num_heads_q: int, | 187 | num_heads_q: int, |
| 186 | num_heads_kv: int, | 188 | num_heads_kv: int, |
| @@ -332,7 +334,7 @@ def quant_sparse_flash_mla_metadata_fallback( | |||
| 332 | torch.compiler.allow_in_graph(quant_sparse_flash_mla_metadata) | 334 | torch.compiler.allow_in_graph(quant_sparse_flash_mla_metadata) |
| 333 | 335 | ||
| 334 | 336 | ||
| 335 | -@impl(AS_LIBRARY, quant_sparse_flash_mla_op_builder.name, "PrivateUse1") | 337 | +@impl(get_as_library(), quant_sparse_flash_mla_op_builder.name, "PrivateUse1") |
| 336 | def quant_sparse_flash_mla( | 338 | def quant_sparse_flash_mla( |
| 337 | q, | 339 | q, |
| 338 | ori_kv=None, | 340 | ori_kv=None, |
| @@ -0,0 +1,4 @@ | |||
| 1 | +__all__ = ["scatter_pa_kv_cache_with_k_scale"] | ||
| 2 | + | ||
| 3 | +from .scatter_pa_kv_cache_with_k_scale import scatter_pa_kv_cache_with_k_scale | ||
| 4 | +from . import graph_convert_scatter_pa_kv_cache_with_k_scale | ||
Rtorch_extension/cann_ops_transformer/ops/csrc/scatter_pa_kv_cache_with_k_scale.cpp→attention/scatter_pa_kv_cache_with_k_scale/torch_extension/csrc/scatter_pa_kv_cache_with_k_scale.cpp+2-2
| @@ -60,8 +60,8 @@ void ScatterPaKvCacheWithKScale(const at::Tensor &key, const at::Tensor &value, | |||
| 60 | char *cacheLayoutPtr = const_cast<char *>(cacheLayout.c_str()); | 60 | char *cacheLayoutPtr = const_cast<char *>(cacheLayout.c_str()); |
| 61 | 61 | ||
| 62 | // 调用ACLNN算子(inplace更新输入cache) | 62 | // 调用ACLNN算子(inplace更新输入cache) |
| 63 | - ACLNN_CMD(aclnnScatterPaKvCacheWithKScale, key, value, keyCache, valueCache, slotMapping, keyScale, | 63 | + ACLNN_CMD(aclnnScatterPaKvCacheWithKScale, key, value, keyCache, valueCache, slotMapping, keyScale, keyScaleCache, |
| 64 | - keyScaleCache, cacheLayoutPtr); | 64 | + cacheLayoutPtr); |
| 65 | } | 65 | } |
| 66 | 66 | ||
| 67 | // 绑定C++函数到Python模块 | 67 | // 绑定C++函数到Python模块 |
Rtorch_extension/cann_ops_transformer/ops/graph_convert/graph_convert_scatter_pa_kv_cache_with_k_scale.py→attention/scatter_pa_kv_cache_with_k_scale/torch_extension/graph_convert_scatter_pa_kv_cache_with_k_scale.py+0-0
File renamed without changes.
Rtorch_extension/cann_ops_transformer/ops/scatter_pa_kv_cache_with_k_scale.py→attention/scatter_pa_kv_cache_with_k_scale/torch_extension/scatter_pa_kv_cache_with_k_scale.py+6-6
| @@ -12,8 +12,7 @@ from typing import Optional | |||
| 12 | 12 | ||
| 13 | import torch | 13 | import torch |
| 14 | from torch.library import impl | 14 | from torch.library import impl |
| 15 | -from cann_ops_transformer.op_builder.builder import OpBuilder | 15 | +from cann_ops_transformer.op_builder import OpBuilder, get_as_library |
| 16 | -from cann_ops_transformer.op_builder.builder import AS_LIBRARY | ||
| 17 | 16 | ||
| 18 | 17 | ||
| 19 | class ScatterPaKvCacheWithKScaleOpBuilder(OpBuilder): | 18 | class ScatterPaKvCacheWithKScaleOpBuilder(OpBuilder): |
| @@ -37,12 +36,12 @@ class ScatterPaKvCacheWithKScaleOpBuilder(OpBuilder): | |||
| 37 | 36 | ||
| 38 | def __init__(self): | 37 | def __init__(self): |
| 39 | super(ScatterPaKvCacheWithKScaleOpBuilder, self).__init__( | 38 | super(ScatterPaKvCacheWithKScaleOpBuilder, self).__init__( |
| 40 | - "scatter_pa_kv_cache_with_k_scale" | 39 | + "scatter_pa_kv_cache_with_k_scale", category="attention" |
| 41 | ) | 40 | ) |
| 42 | 41 | ||
| 43 | def sources(self): | 42 | def sources(self): |
| 44 | """C++源代码路径""" | 43 | """C++源代码路径""" |
| 45 | - return ["ops/csrc/scatter_pa_kv_cache_with_k_scale.cpp"] | 44 | + return ["csrc/attention/scatter_pa_kv_cache_with_k_scale.cpp"] |
| 46 | 45 | ||
| 47 | def schema(self) -> str: | 46 | def schema(self) -> str: |
| 48 | """PyTorch算子签名""" | 47 | """PyTorch算子签名""" |
| @@ -60,7 +59,7 @@ class ScatterPaKvCacheWithKScaleOpBuilder(OpBuilder): | |||
| 60 | 原地更新key_cache、value_cache、key_scale_cache,无返回值 | 59 | 原地更新key_cache、value_cache、key_scale_cache,无返回值 |
| 61 | """ | 60 | """ |
| 62 | 61 | ||
| 63 | - @impl(AS_LIBRARY, self.name, "Meta") | 62 | + @impl(get_as_library(), self.name, "Meta") |
| 64 | def scatter_pa_kv_cache_with_k_scale_meta( | 63 | def scatter_pa_kv_cache_with_k_scale_meta( |
| 65 | key, | 64 | key, |
| 66 | value, | 65 | value, |
| @@ -77,9 +76,10 @@ class ScatterPaKvCacheWithKScaleOpBuilder(OpBuilder): | |||
| 77 | 76 | ||
| 78 | # 实例化OpBuilder | 77 | # 实例化OpBuilder |
| 79 | scatter_pa_kv_cache_with_k_scale_op_builder = ScatterPaKvCacheWithKScaleOpBuilder() | 78 | scatter_pa_kv_cache_with_k_scale_op_builder = ScatterPaKvCacheWithKScaleOpBuilder() |
| 79 | +scatter_pa_kv_cache_with_k_scale_op_builder._ensure_initialized() | ||
| 80 | 80 | ||
| 81 | 81 | ||
| 82 | -@impl(AS_LIBRARY, scatter_pa_kv_cache_with_k_scale_op_builder.name, "PrivateUse1") | 82 | +@impl(get_as_library(), scatter_pa_kv_cache_with_k_scale_op_builder.name, "PrivateUse1") |
| 83 | def scatter_pa_kv_cache_with_k_scale( | 83 | def scatter_pa_kv_cache_with_k_scale( |
| 84 | key: torch.Tensor, | 84 | key: torch.Tensor, |
| 85 | value: torch.Tensor, | 85 | value: torch.Tensor, |
| @@ -0,0 +1,4 @@ | |||
| 1 | +__all__ = ["sparse_flash_mla", "sparse_flash_mla_metadata"] | ||
| 2 | + | ||
| 3 | +from .sparse_flash_mla import sparse_flash_mla, sparse_flash_mla_metadata | ||
| 4 | +from . import graph_convert_sparse_flash_mla | ||
Rtorch_extension/cann_ops_transformer/ops/csrc/sparse_flash_mla.cpp→attention/sparse_flash_mla/torch_extension/csrc/sparse_flash_mla.cpp+12-12
| @@ -137,18 +137,18 @@ std::tuple<at::Tensor, at::Tensor> MakeSparseFlashMlaOutputs(const at::Tensor &q | |||
| 137 | return {attenOut, softmaxLse}; | 137 | return {attenOut, softmaxLse}; |
| 138 | } | 138 | } |
| 139 | 139 | ||
| 140 | -std::tuple<at::Tensor, at::Tensor> | 140 | +std::tuple<at::Tensor, at::Tensor> SparseFlashMla( |
| 141 | -SparseFlashMla(const at::Tensor &q, const c10::optional<at::Tensor> &oriKv, const c10::optional<at::Tensor> &cmpKv, | 141 | + const at::Tensor &q, const c10::optional<at::Tensor> &oriKv, const c10::optional<at::Tensor> &cmpKv, |
| 142 | - const c10::optional<at::Tensor> &oriSparseIndices, const c10::optional<at::Tensor> &cmpSparseIndices, | 142 | + const c10::optional<at::Tensor> &oriSparseIndices, const c10::optional<at::Tensor> &cmpSparseIndices, |
| 143 | - const c10::optional<at::Tensor> &oriBlockTable, const c10::optional<at::Tensor> &cmpBlockTable, | 143 | + const c10::optional<at::Tensor> &oriBlockTable, const c10::optional<at::Tensor> &cmpBlockTable, |
| 144 | - const c10::optional<at::Tensor> &cuSeqlensQ, const c10::optional<at::Tensor> &cuSeqlensOriKv, | 144 | + const c10::optional<at::Tensor> &cuSeqlensQ, const c10::optional<at::Tensor> &cuSeqlensOriKv, |
| 145 | - const c10::optional<at::Tensor> &cuSeqlensCmpKv, const c10::optional<at::Tensor> &sequsedQ, | 145 | + const c10::optional<at::Tensor> &cuSeqlensCmpKv, const c10::optional<at::Tensor> &sequsedQ, |
| 146 | - const c10::optional<at::Tensor> &sequsedOriKv, const c10::optional<at::Tensor> &sequsedCmpKv, | 146 | + const c10::optional<at::Tensor> &sequsedOriKv, const c10::optional<at::Tensor> &sequsedCmpKv, |
| 147 | - const c10::optional<at::Tensor> &cmpResidualKv, const c10::optional<at::Tensor> &oriTopkLength, | 147 | + const c10::optional<at::Tensor> &cmpResidualKv, const c10::optional<at::Tensor> &oriTopkLength, |
| 148 | - const c10::optional<at::Tensor> &cmpTopkLength, const c10::optional<at::Tensor> &sinks, | 148 | + const c10::optional<at::Tensor> &cmpTopkLength, const c10::optional<at::Tensor> &sinks, |
| 149 | - const c10::optional<at::Tensor> &metadata, double softmaxScale, int64_t cmpRatio, int64_t oriMaskMode, | 149 | + const c10::optional<at::Tensor> &metadata, double softmaxScale, int64_t cmpRatio, int64_t oriMaskMode, |
| 150 | - int64_t cmpMaskMode, int64_t oriWinLeft, int64_t oriWinRight, c10::string_view layoutQ, | 150 | + int64_t cmpMaskMode, int64_t oriWinLeft, int64_t oriWinRight, c10::string_view layoutQ, c10::string_view layoutKv, |
| 151 | - c10::string_view layoutKv, int64_t topkValueMode, bool returnSoftmaxLse) | 151 | + int64_t topkValueMode, bool returnSoftmaxLse) |
| 152 | { | 152 | { |
| 153 | std::string layoutQStr = std::string(layoutQ); | 153 | std::string layoutQStr = std::string(layoutQ); |
| 154 | std::string layoutKvStr = std::string(layoutKv); | 154 | std::string layoutKvStr = std::string(layoutKv); |
Rtorch_extension/cann_ops_transformer/ops/graph_convert/graph_convert_sparse_flash_mla.py→attention/sparse_flash_mla/torch_extension/graph_convert_sparse_flash_mla.py+0-0
File renamed without changes.
Rtorch_extension/cann_ops_transformer/ops/sparse_flash_mla.py→attention/sparse_flash_mla/torch_extension/sparse_flash_mla.py+12-11
| @@ -11,8 +11,7 @@ | |||
| 11 | from typing import Optional | 11 | from typing import Optional |
| 12 | import torch | 12 | import torch |
| 13 | from torch.library import impl | 13 | from torch.library import impl |
| 14 | -from cann_ops_transformer.op_builder.builder import OpBuilder | 14 | +from cann_ops_transformer.op_builder import OpBuilder, get_as_library |
| 15 | -from cann_ops_transformer.op_builder.builder import AS_LIBRARY | ||
| 16 | 15 | ||
| 17 | SMLA_METADATA_SIZE = 1024 | 16 | SMLA_METADATA_SIZE = 1024 |
| 18 | SMLA_METADATA_OP_NAME = "sparse_flash_mla_metadata" | 17 | SMLA_METADATA_OP_NAME = "sparse_flash_mla_metadata" |
| @@ -20,11 +19,13 @@ SMLA_METADATA_OP_NAME = "sparse_flash_mla_metadata" | |||
| 20 | 19 | ||
| 21 | class SparseFlashMlaOpBuilder(OpBuilder): | 20 | class SparseFlashMlaOpBuilder(OpBuilder): |
| 22 | def __init__(self): | 21 | def __init__(self): |
| 23 | - super(SparseFlashMlaOpBuilder, self).__init__("sparse_flash_mla") | 22 | + super(SparseFlashMlaOpBuilder, self).__init__( |
| 23 | + "sparse_flash_mla", category="attention" | ||
| 24 | + ) | ||
| 24 | 25 | ||
| 25 | def sources(self): | 26 | def sources(self): |
| 26 | """Path to C++ source code.""" | 27 | """Path to C++ source code.""" |
| 27 | - return ["ops/csrc/sparse_flash_mla.cpp"] | 28 | + return ["csrc/attention/sparse_flash_mla.cpp"] |
| 28 | 29 | ||
| 29 | def schema(self) -> str: | 30 | def schema(self) -> str: |
| 30 | """PyTorch operator signature.""" | 31 | """PyTorch operator signature.""" |
| @@ -92,7 +93,7 @@ class SparseFlashMlaOpBuilder(OpBuilder): | |||
| 92 | ): | 93 | ): |
| 93 | return torch.empty((SMLA_METADATA_SIZE), dtype=torch.int32, device="npu") | 94 | return torch.empty((SMLA_METADATA_SIZE), dtype=torch.int32, device="npu") |
| 94 | 95 | ||
| 95 | - @impl(AS_LIBRARY, self.name, "Meta") | 96 | + @impl(get_as_library(), self.name, "Meta") |
| 96 | def sparse_flash_mla_meta( | 97 | def sparse_flash_mla_meta( |
| 97 | q, | 98 | q, |
| 98 | ori_kv=None, | 99 | ori_kv=None, |
| @@ -143,7 +144,7 @@ class SparseFlashMlaOpBuilder(OpBuilder): | |||
| 143 | device="meta", | 144 | device="meta", |
| 144 | ) | 145 | ) |
| 145 | else: | 146 | else: |
| 146 | - # 给一个空的合法张量,不能是 nullptr | 147 | + # 给一个空的合法张量,不能�?nullptr |
| 147 | softmax_lse = torch.empty([], dtype=torch.float32, device="meta") | 148 | softmax_lse = torch.empty([], dtype=torch.float32, device="meta") |
| 148 | else: | 149 | else: |
| 149 | attn_out = torch.empty(q.shape, dtype=q.dtype, device="meta") | 150 | attn_out = torch.empty(q.shape, dtype=q.dtype, device="meta") |
| @@ -154,16 +155,17 @@ class SparseFlashMlaOpBuilder(OpBuilder): | |||
| 154 | device="meta", | 155 | device="meta", |
| 155 | ) | 156 | ) |
| 156 | else: | 157 | else: |
| 157 | - # 给一个空的合法张量,不能是 nullptr | 158 | + # 给一个空的合法张量,不能�?nullptr |
| 158 | softmax_lse = torch.empty([], dtype=torch.float32, device="meta") | 159 | softmax_lse = torch.empty([], dtype=torch.float32, device="meta") |
| 159 | return (attn_out, softmax_lse) | 160 | return (attn_out, softmax_lse) |
| 160 | 161 | ||
| 161 | 162 | ||
| 162 | # Instantiate the builder | 163 | # Instantiate the builder |
| 163 | sparse_flash_mla_op_builder = SparseFlashMlaOpBuilder() | 164 | sparse_flash_mla_op_builder = SparseFlashMlaOpBuilder() |
| 165 | +sparse_flash_mla_op_builder._ensure_initialized() | ||
| 164 | 166 | ||
| 165 | 167 | ||
| 166 | -@impl(AS_LIBRARY, SMLA_METADATA_OP_NAME, "PrivateUse1") | 168 | +@impl(get_as_library(), SMLA_METADATA_OP_NAME, "PrivateUse1") |
| 167 | def sparse_flash_mla_metadata( | 169 | def sparse_flash_mla_metadata( |
| 168 | num_heads_q: int, | 170 | num_heads_q: int, |
| 169 | num_heads_kv: int, | 171 | num_heads_kv: int, |
| @@ -275,8 +277,7 @@ def sparse_flash_mla_metadata_fallback( | |||
| 275 | has_ori_kv: Optional[bool] = None, | 277 | has_ori_kv: Optional[bool] = None, |
| 276 | has_cmp_kv: Optional[bool] = None, | 278 | has_cmp_kv: Optional[bool] = None, |
| 277 | ): | 279 | ): |
| 278 | - # 处理所有 tensor 都为 None 的情况 | 280 | + # 处理所�?tensor 都为 None 的情�? # 调用 NPU 实现 |
| 279 | - # 调用 NPU 实现 | ||
| 280 | return sparse_flash_mla_metadata( | 281 | return sparse_flash_mla_metadata( |
| 281 | num_heads_q, | 282 | num_heads_q, |
| 282 | num_heads_kv, | 283 | num_heads_kv, |
| @@ -311,7 +312,7 @@ def sparse_flash_mla_metadata_fallback( | |||
| 311 | torch.compiler.allow_in_graph(sparse_flash_mla_metadata) | 312 | torch.compiler.allow_in_graph(sparse_flash_mla_metadata) |
| 312 | 313 | ||
| 313 | 314 | ||
| 314 | -@impl(AS_LIBRARY, sparse_flash_mla_op_builder.name, "PrivateUse1") | 315 | +@impl(get_as_library(), sparse_flash_mla_op_builder.name, "PrivateUse1") |
| 315 | def sparse_flash_mla( | 316 | def sparse_flash_mla( |
| 316 | q, | 317 | q, |
| 317 | ori_kv=None, | 318 | ori_kv=None, |
| @@ -0,0 +1,3 @@ | |||
| 1 | +__all__ = ["sparse_flash_mla_grad", "sparse_flash_mla_grad_metadata"] | ||
| 2 | + | ||
| 3 | +from .sparse_flash_mla_grad import sparse_flash_mla_grad, sparse_flash_mla_grad_metadata | ||
Rtorch_extension/cann_ops_transformer/ops/csrc/sparse_flash_mla_grad.cpp→attention/sparse_flash_mla_grad/torch_extension/csrc/sparse_flash_mla_grad.cpp+13-14
| @@ -86,20 +86,19 @@ at::Tensor SparseFlashMlaGradMetadata( | |||
| 86 | return output; | 86 | return output; |
| 87 | } | 87 | } |
| 88 | 88 | ||
| 89 | -std::tuple<at::Tensor, at::Tensor, at::Tensor, at::Tensor, at::Tensor, at::Tensor> | 89 | +std::tuple<at::Tensor, at::Tensor, at::Tensor, at::Tensor, at::Tensor, at::Tensor> SparseFlashMlaGrad( |
| 90 | -SparseFlashMlaGrad(const at::Tensor &q, const at::Tensor &dout, const at::Tensor &attnOut, const at::Tensor &softmaxLse, | 90 | + const at::Tensor &q, const at::Tensor &dout, const at::Tensor &attnOut, const at::Tensor &softmaxLse, |
| 91 | - const c10::optional<at::Tensor> &oriKv, const c10::optional<at::Tensor> &cmpKv, | 91 | + const c10::optional<at::Tensor> &oriKv, const c10::optional<at::Tensor> &cmpKv, |
| 92 | - const c10::optional<at::Tensor> &oriSparseIndices, const c10::optional<at::Tensor> &cmpSparseIndices, | 92 | + const c10::optional<at::Tensor> &oriSparseIndices, const c10::optional<at::Tensor> &cmpSparseIndices, |
| 93 | - const c10::optional<at::Tensor> &cuSeqlensQ, const c10::optional<at::Tensor> &cuSeqlensOriKv, | 93 | + const c10::optional<at::Tensor> &cuSeqlensQ, const c10::optional<at::Tensor> &cuSeqlensOriKv, |
| 94 | - const c10::optional<at::Tensor> &cuSeqlensCmpKv, const c10::optional<at::Tensor> &sequsedQ, | 94 | + const c10::optional<at::Tensor> &cuSeqlensCmpKv, const c10::optional<at::Tensor> &sequsedQ, |
| 95 | - const c10::optional<at::Tensor> &sequsedOriKv, const c10::optional<at::Tensor> &sequsedCmpKv, | 95 | + const c10::optional<at::Tensor> &sequsedOriKv, const c10::optional<at::Tensor> &sequsedCmpKv, |
| 96 | - const c10::optional<at::Tensor> &cmpResidualKv, const c10::optional<at::Tensor> &oriTopkLength, | 96 | + const c10::optional<at::Tensor> &cmpResidualKv, const c10::optional<at::Tensor> &oriTopkLength, |
| 97 | - const c10::optional<at::Tensor> &cmpTopkLength, const c10::optional<at::Tensor> &sinks, | 97 | + const c10::optional<at::Tensor> &cmpTopkLength, const c10::optional<at::Tensor> &sinks, |
| 98 | - const c10::optional<at::Tensor> &metadata, c10::optional<double> softmaxScale, | 98 | + const c10::optional<at::Tensor> &metadata, c10::optional<double> softmaxScale, c10::optional<int64_t> cmpRatio, |
| 99 | - c10::optional<int64_t> cmpRatio, c10::optional<int64_t> oriMaskMode, | 99 | + c10::optional<int64_t> oriMaskMode, c10::optional<int64_t> cmpMaskMode, c10::optional<int64_t> oriWinLeft, |
| 100 | - c10::optional<int64_t> cmpMaskMode, c10::optional<int64_t> oriWinLeft, | 100 | + c10::optional<int64_t> oriWinRight, c10::optional<c10::string_view> layoutQ, |
| 101 | - c10::optional<int64_t> oriWinRight, c10::optional<c10::string_view> layoutQ, | 101 | + c10::optional<c10::string_view> layoutKv) |
| 102 | - c10::optional<c10::string_view> layoutKv) | ||
| 103 | { | 102 | { |
| 104 | const at::Tensor &oriKvConst = oriKv.value_or(at::Tensor()); | 103 | const at::Tensor &oriKvConst = oriKv.value_or(at::Tensor()); |
| 105 | const at::Tensor &cmpKvConst = cmpKv.value_or(at::Tensor()); | 104 | const at::Tensor &cmpKvConst = cmpKv.value_or(at::Tensor()); |
Rtorch_extension/cann_ops_transformer/ops/sparse_flash_mla_grad.py→attention/sparse_flash_mla_grad/torch_extension/sparse_flash_mla_grad.py+9-7
| @@ -10,8 +10,7 @@ | |||
| 10 | from typing import Optional | 10 | from typing import Optional |
| 11 | import torch | 11 | import torch |
| 12 | from torch.library import impl | 12 | from torch.library import impl |
| 13 | -from cann_ops_transformer.op_builder.builder import OpBuilder | 13 | +from cann_ops_transformer.op_builder import OpBuilder, get_as_library |
| 14 | -from cann_ops_transformer.op_builder.builder import AS_LIBRARY | ||
| 15 | 14 | ||
| 16 | SMLAG_METADATA_SIZE = 1024 | 15 | SMLAG_METADATA_SIZE = 1024 |
| 17 | SMLAG_METADATA_OP_NAME = "sparse_flash_mla_grad_metadata" | 16 | SMLAG_METADATA_OP_NAME = "sparse_flash_mla_grad_metadata" |
| @@ -26,11 +25,13 @@ def _is_ascend950(): | |||
| 26 | 25 | ||
| 27 | class SparseFlashMlaGradOpBuilder(OpBuilder): | 26 | class SparseFlashMlaGradOpBuilder(OpBuilder): |
| 28 | def __init__(self): | 27 | def __init__(self): |
| 29 | - super(SparseFlashMlaGradOpBuilder, self).__init__("sparse_flash_mla_grad") | 28 | + super(SparseFlashMlaGradOpBuilder, self).__init__( |
| 29 | + "sparse_flash_mla_grad", category="attention" | ||
| 30 | + ) | ||
| 30 | 31 | ||
| 31 | def sources(self): | 32 | def sources(self): |
| 32 | """Path to C++ source code.""" | 33 | """Path to C++ source code.""" |
| 33 | - return ["ops/csrc/sparse_flash_mla_grad.cpp"] | 34 | + return ["csrc/attention/sparse_flash_mla_grad.cpp"] |
| 34 | 35 | ||
| 35 | def schema(self) -> str: | 36 | def schema(self) -> str: |
| 36 | """PyTorch operator signature.""" | 37 | """PyTorch operator signature.""" |
| @@ -94,7 +95,7 @@ class SparseFlashMlaGradOpBuilder(OpBuilder): | |||
| 94 | ): | 95 | ): |
| 95 | return torch.empty((SMLAG_METADATA_SIZE), dtype=torch.int32, device="npu") | 96 | return torch.empty((SMLAG_METADATA_SIZE), dtype=torch.int32, device="npu") |
| 96 | 97 | ||
| 97 | - @impl(AS_LIBRARY, self.name, "Meta") | 98 | + @impl(get_as_library(), self.name, "Meta") |
| 98 | def sparse_flash_mla_grad_meta( | 99 | def sparse_flash_mla_grad_meta( |
| 99 | q, | 100 | q, |
| 100 | dout, | 101 | dout, |
| @@ -171,9 +172,10 @@ class SparseFlashMlaGradOpBuilder(OpBuilder): | |||
| 171 | 172 | ||
| 172 | # Instantiate the builder | 173 | # Instantiate the builder |
| 173 | smlag_op_builder = SparseFlashMlaGradOpBuilder() | 174 | smlag_op_builder = SparseFlashMlaGradOpBuilder() |
| 175 | +smlag_op_builder._ensure_initialized() | ||
| 174 | 176 | ||
| 175 | 177 | ||
| 176 | -@impl(AS_LIBRARY, SMLAG_METADATA_OP_NAME, "PrivateUse1") | 178 | +@impl(get_as_library(), SMLAG_METADATA_OP_NAME, "PrivateUse1") |
| 177 | def sparse_flash_mla_grad_metadata( | 179 | def sparse_flash_mla_grad_metadata( |
| 178 | num_heads_q: int, | 180 | num_heads_q: int, |
| 179 | num_heads_kv: int, | 181 | num_heads_kv: int, |
| @@ -323,7 +325,7 @@ def sparse_flash_mla_grad_metadata_fallback( | |||
| 323 | torch.compiler.allow_in_graph(sparse_flash_mla_grad_metadata) | 325 | torch.compiler.allow_in_graph(sparse_flash_mla_grad_metadata) |
| 324 | 326 | ||
| 325 | 327 | ||
| 326 | -@impl(AS_LIBRARY, smlag_op_builder.name, "PrivateUse1") | 328 | +@impl(get_as_library(), smlag_op_builder.name, "PrivateUse1") |
| 327 | def sparse_flash_mla_grad( | 329 | def sparse_flash_mla_grad( |
| 328 | q, | 330 | q, |
| 329 | dout, | 331 | dout, |
| @@ -0,0 +1,9 @@ | |||
| 1 | +__all__ = [ | ||
| 2 | + "sparse_flash_mla_softmax_l1_norm", | ||
| 3 | + "sparse_flash_mla_softmax_l1_norm_metadata", | ||
| 4 | +] | ||
| 5 | + | ||
| 6 | +from .sparse_flash_mla_softmax_l1_norm import ( | ||
| 7 | + sparse_flash_mla_softmax_l1_norm, | ||
| 8 | + sparse_flash_mla_softmax_l1_norm_metadata, | ||
| 9 | +) | ||
Rtorch_extension/cann_ops_transformer/ops/csrc/sparse_flash_mla_softmax_l1_norm.cpp→attention/sparse_flash_mla_softmax_l1_norm/torch_extension/csrc/sparse_flash_mla_softmax_l1_norm.cpp+0-0
File renamed without changes.
Rtorch_extension/cann_ops_transformer/ops/sparse_flash_mla_softmax_l1_norm.py→attention/sparse_flash_mla_softmax_l1_norm/torch_extension/sparse_flash_mla_softmax_l1_norm.py+7-7
| @@ -13,8 +13,7 @@ from typing import Optional | |||
| 13 | import torch | 13 | import torch |
| 14 | from torch.library import impl | 14 | from torch.library import impl |
| 15 | 15 | ||
| 16 | -from cann_ops_transformer.op_builder.builder import AS_LIBRARY | 16 | +from cann_ops_transformer.op_builder import OpBuilder, get_as_library |
| 17 | -from cann_ops_transformer.op_builder.builder import OpBuilder | ||
| 18 | 17 | ||
| 19 | 18 | ||
| 20 | SMLA_METADATA_SIZE = 64 | 19 | SMLA_METADATA_SIZE = 64 |
| @@ -25,11 +24,11 @@ SMLA_OP_NAME = "sparse_flash_mla_softmax_l1_norm" | |||
| 25 | class SparseFlashMlaSoftmaxL1NormOpBuilder(OpBuilder): | 24 | class SparseFlashMlaSoftmaxL1NormOpBuilder(OpBuilder): |
| 26 | def __init__(self): | 25 | def __init__(self): |
| 27 | super(SparseFlashMlaSoftmaxL1NormOpBuilder, self).__init__( | 26 | super(SparseFlashMlaSoftmaxL1NormOpBuilder, self).__init__( |
| 28 | - "sparse_flash_mla_softmax_l1_norm" | 27 | + "sparse_flash_mla_softmax_l1_norm", category="attention" |
| 29 | ) | 28 | ) |
| 30 | 29 | ||
| 31 | def sources(self): | 30 | def sources(self): |
| 32 | - return ["ops/csrc/sparse_flash_mla_softmax_l1_norm.cpp"] | 31 | + return ["csrc/attention/sparse_flash_mla_softmax_l1_norm.cpp"] |
| 33 | 32 | ||
| 34 | def schema(self) -> list: | 33 | def schema(self) -> list: |
| 35 | return [ | 34 | return [ |
| @@ -73,7 +72,7 @@ class SparseFlashMlaSoftmaxL1NormOpBuilder(OpBuilder): | |||
| 73 | ): | 72 | ): |
| 74 | return torch.empty((SMLA_METADATA_SIZE,), dtype=torch.int32, device="meta") | 73 | return torch.empty((SMLA_METADATA_SIZE,), dtype=torch.int32, device="meta") |
| 75 | 74 | ||
| 76 | - @impl(AS_LIBRARY, self.name, "Meta") | 75 | + @impl(get_as_library(), self.name, "Meta") |
| 77 | def sparse_flash_mla_softmax_l1_norm_meta( | 76 | def sparse_flash_mla_softmax_l1_norm_meta( |
| 78 | q, | 77 | q, |
| 79 | k, | 78 | k, |
| @@ -107,9 +106,10 @@ class SparseFlashMlaSoftmaxL1NormOpBuilder(OpBuilder): | |||
| 107 | 106 | ||
| 108 | 107 | ||
| 109 | sparse_flash_mla_softmax_l1_norm_op_builder = SparseFlashMlaSoftmaxL1NormOpBuilder() | 108 | sparse_flash_mla_softmax_l1_norm_op_builder = SparseFlashMlaSoftmaxL1NormOpBuilder() |
| 109 | +sparse_flash_mla_softmax_l1_norm_op_builder._ensure_initialized() | ||
| 110 | 110 | ||
| 111 | 111 | ||
| 112 | -@impl(AS_LIBRARY, SMLA_METADATA_OP_NAME, "PrivateUse1") | 112 | +@impl(get_as_library(), SMLA_METADATA_OP_NAME, "PrivateUse1") |
| 113 | def sparse_flash_mla_softmax_l1_norm_metadata( | 113 | def sparse_flash_mla_softmax_l1_norm_metadata( |
| 114 | num_heads_q, | 114 | num_heads_q, |
| 115 | num_heads_k, | 115 | num_heads_k, |
| @@ -233,7 +233,7 @@ def sparse_flash_mla_softmax_l1_norm_metadata_fallback( | |||
| 233 | torch.compiler.allow_in_graph(sparse_flash_mla_softmax_l1_norm_metadata) | 233 | torch.compiler.allow_in_graph(sparse_flash_mla_softmax_l1_norm_metadata) |
| 234 | 234 | ||
| 235 | 235 | ||
| 236 | -@impl(AS_LIBRARY, SMLA_OP_NAME, "PrivateUse1") | 236 | +@impl(get_as_library(), SMLA_OP_NAME, "PrivateUse1") |
| 237 | def sparse_flash_mla_softmax_l1_norm( | 237 | def sparse_flash_mla_softmax_l1_norm( |
| 238 | q: torch.Tensor, | 238 | q: torch.Tensor, |
| 239 | k: torch.Tensor, | 239 | k: torch.Tensor, |
| @@ -36,9 +36,6 @@ def find_repo_root(): | |||
| 36 | 36 | ||
| 37 | 37 | ||
| 38 | REPO_ROOT = find_repo_root() | 38 | REPO_ROOT = find_repo_root() |
| 39 | -TORCH_EXTENSION_PATH = REPO_ROOT / "torch_extension" | ||
| 40 | -if TORCH_EXTENSION_PATH.exists(): | ||
| 41 | - sys.path.insert(0, str(TORCH_EXTENSION_PATH)) | ||
| 42 | 39 | ||
| 43 | MINDSPEED_PATH = REPO_ROOT / "MindSpeed" | 40 | MINDSPEED_PATH = REPO_ROOT / "MindSpeed" |
| 44 | if MINDSPEED_PATH.exists(): | 41 | if MINDSPEED_PATH.exists(): |
| @@ -0,0 +1,9 @@ | |||
| 1 | +__all__ = [ | ||
| 2 | + "sparse_lightning_indexer_kl_loss_grad", | ||
| 3 | + "sparse_lightning_indexer_kl_loss_grad_metadata", | ||
| 4 | +] | ||
| 5 | + | ||
| 6 | +from .sparse_lightning_indexer_kl_loss_grad import ( | ||
| 7 | + sparse_lightning_indexer_kl_loss_grad, | ||
| 8 | + sparse_lightning_indexer_kl_loss_grad_metadata, | ||
| 9 | +) | ||
Rtorch_extension/cann_ops_transformer/ops/csrc/sparse_lightning_indexer_kl_loss_grad.cpp→attention/sparse_lightning_indexer_kl_loss_grad/torch_extension/csrc/sparse_lightning_indexer_kl_loss_grad.cpp+0-0
File renamed without changes.
Rtorch_extension/cann_ops_transformer/ops/sparse_lightning_indexer_kl_loss_grad.py→attention/sparse_lightning_indexer_kl_loss_grad/torch_extension/sparse_lightning_indexer_kl_loss_grad.py+11-7
| @@ -11,8 +11,7 @@ from typing import Optional | |||
| 11 | import torch | 11 | import torch |
| 12 | from torch.library import impl | 12 | from torch.library import impl |
| 13 | 13 | ||
| 14 | -from cann_ops_transformer.op_builder.builder import AS_LIBRARY | 14 | +from cann_ops_transformer.op_builder import OpBuilder, get_as_library |
| 15 | -from cann_ops_transformer.op_builder.builder import OpBuilder | ||
| 16 | 15 | ||
| 17 | 16 | ||
| 18 | SLI_KL_LOSS_GRAD_METADATA_SIZE = 64 | 17 | SLI_KL_LOSS_GRAD_METADATA_SIZE = 64 |
| @@ -23,11 +22,11 @@ SLI_KL_LOSS_GRAD_METADATA_OP_NAME = "sparse_lightning_indexer_kl_loss_grad_metad | |||
| 23 | class SparseLightningIndexerKLLossGradOpBuilder(OpBuilder): | 22 | class SparseLightningIndexerKLLossGradOpBuilder(OpBuilder): |
| 24 | def __init__(self): | 23 | def __init__(self): |
| 25 | super(SparseLightningIndexerKLLossGradOpBuilder, self).__init__( | 24 | super(SparseLightningIndexerKLLossGradOpBuilder, self).__init__( |
| 26 | - "sparse_lightning_indexer_kl_loss_grad" | 25 | + "sparse_lightning_indexer_kl_loss_grad", category="attention" |
| 27 | ) | 26 | ) |
| 28 | 27 | ||
| 29 | def sources(self): | 28 | def sources(self): |
| 30 | - return ["ops/csrc/sparse_lightning_indexer_kl_loss_grad.cpp"] | 29 | + return ["csrc/attention/sparse_lightning_indexer_kl_loss_grad.cpp"] |
| 31 | 30 | ||
| 32 | def schema(self) -> str: | 31 | def schema(self) -> str: |
| 33 | return [ | 32 | return [ |
| @@ -73,7 +72,7 @@ class SparseLightningIndexerKLLossGradOpBuilder(OpBuilder): | |||
| 73 | (SLI_KL_LOSS_GRAD_METADATA_SIZE,), dtype=torch.int32, device="npu" | 72 | (SLI_KL_LOSS_GRAD_METADATA_SIZE,), dtype=torch.int32, device="npu" |
| 74 | ) | 73 | ) |
| 75 | 74 | ||
| 76 | - @impl(AS_LIBRARY, self.name, "Meta") | 75 | + @impl(get_as_library(), self.name, "Meta") |
| 77 | def sparse_lightning_indexer_kl_loss_grad_meta( | 76 | def sparse_lightning_indexer_kl_loss_grad_meta( |
| 78 | q, | 77 | q, |
| 79 | k, | 78 | k, |
| @@ -106,9 +105,10 @@ class SparseLightningIndexerKLLossGradOpBuilder(OpBuilder): | |||
| 106 | sparse_lightning_indexer_kl_loss_grad_op_builder = ( | 105 | sparse_lightning_indexer_kl_loss_grad_op_builder = ( |
| 107 | SparseLightningIndexerKLLossGradOpBuilder() | 106 | SparseLightningIndexerKLLossGradOpBuilder() |
| 108 | ) | 107 | ) |
| 108 | +sparse_lightning_indexer_kl_loss_grad_op_builder._ensure_initialized() | ||
| 109 | 109 | ||
| 110 | 110 | ||
| 111 | -@impl(AS_LIBRARY, SLI_KL_LOSS_GRAD_METADATA_OP_NAME, "PrivateUse1") | 111 | +@impl(get_as_library(), SLI_KL_LOSS_GRAD_METADATA_OP_NAME, "PrivateUse1") |
| 112 | def sparse_lightning_indexer_kl_loss_grad_metadata( | 112 | def sparse_lightning_indexer_kl_loss_grad_metadata( |
| 113 | num_heads_q, | 113 | num_heads_q, |
| 114 | num_heads_k, | 114 | num_heads_k, |
| @@ -203,7 +203,11 @@ def sparse_lightning_indexer_kl_loss_grad_metadata_fallback( | |||
| 203 | torch.compiler.allow_in_graph(sparse_lightning_indexer_kl_loss_grad_metadata) | 203 | torch.compiler.allow_in_graph(sparse_lightning_indexer_kl_loss_grad_metadata) |
| 204 | 204 | ||
| 205 | 205 | ||
| 206 | -@impl(AS_LIBRARY, sparse_lightning_indexer_kl_loss_grad_op_builder.name, "PrivateUse1") | 206 | +@impl( |
| 207 | + get_as_library(), | ||
| 208 | + sparse_lightning_indexer_kl_loss_grad_op_builder.name, | ||
| 209 | + "PrivateUse1", | ||
| 210 | +) | ||
| 207 | def sparse_lightning_indexer_kl_loss_grad( | 211 | def sparse_lightning_indexer_kl_loss_grad( |
| 208 | q, | 212 | q, |
| 209 | k, | 213 | k, |
| @@ -0,0 +1,4 @@ | |||
| 1 | +__all__ = ["stem_oam_prep_paged_kv"] | ||
| 2 | + | ||
| 3 | +from .stem_oam_prep_paged_kv import stem_oam_prep_paged_kv | ||
| 4 | +from . import graph_convert_stem_oam_prep_paged_kv | ||
Rtorch_extension/cann_ops_transformer/ops/csrc/stem_oam_prep_paged_kv.cpp→attention/stem_oam_prep_paged_kv/torch_extension/csrc/stem_oam_prep_paged_kv.cpp+5-6
| @@ -20,9 +20,9 @@ const int64_t DIM_QK = 128; | |||
| 20 | std::tuple<at::Tensor, at::Tensor> StemOamPrepPagedKv(const at::Tensor &kCache, const at::Tensor &vCache, | 20 | std::tuple<at::Tensor, at::Tensor> StemOamPrepPagedKv(const at::Tensor &kCache, const at::Tensor &vCache, |
| 21 | const at::Tensor &kvIndices, at::IntArrayRef kvSeqLens, | 21 | const at::Tensor &kvIndices, at::IntArrayRef kvSeqLens, |
| 22 | const c10::optional<at::Tensor> &kScaleCacheOpt, | 22 | const c10::optional<at::Tensor> &kScaleCacheOpt, |
| 23 | - const c10::optional<at::Tensor> &vScaleOpt, | 23 | + const c10::optional<at::Tensor> &vScaleOpt, double lambdaMag, |
| 24 | - double lambdaMag, const std::string &kvLayout, | 24 | + const std::string &kvLayout, int64_t stemBlockSize, |
| 25 | - int64_t stemBlockSize, int64_t stemStride) | 25 | + int64_t stemStride) |
| 26 | { | 26 | { |
| 27 | TORCH_CHECK(kCache.numel() > 0, "kCache is empty"); | 27 | TORCH_CHECK(kCache.numel() > 0, "kCache is empty"); |
| 28 | TORCH_CHECK(vCache.numel() > 0, "vCache is empty"); | 28 | TORCH_CHECK(vCache.numel() > 0, "vCache is empty"); |
| @@ -63,9 +63,8 @@ std::tuple<at::Tensor, at::Tensor> StemOamPrepPagedKv(const at::Tensor &kCache, | |||
| 63 | StorageShapeTensor kFlatWrapped{kFlat}; | 63 | StorageShapeTensor kFlatWrapped{kFlat}; |
| 64 | StorageShapeTensor vBiasWrapped{vBias}; | 64 | StorageShapeTensor vBiasWrapped{vBias}; |
| 65 | const char *kvLayoutPtr = kvLayout.c_str(); | 65 | const char *kvLayoutPtr = kvLayout.c_str(); |
| 66 | - ACLNN_CMD(aclnnStemOamPrepPagedKv, kCacheWrapped, vCacheWrapped, kvIndicesWrapped, kvSeqLens, | 66 | + ACLNN_CMD(aclnnStemOamPrepPagedKv, kCacheWrapped, vCacheWrapped, kvIndicesWrapped, kvSeqLens, kScaleCacheWrapped, |
| 67 | - kScaleCacheWrapped, vScale, lambdaMag, kvLayoutPtr, stemBlockSize, stemStride, | 67 | + vScale, lambdaMag, kvLayoutPtr, stemBlockSize, stemStride, kFlatWrapped, vBiasWrapped); |
| 68 | - kFlatWrapped, vBiasWrapped); | ||
| 69 | 68 | ||
| 70 | return std::tuple<at::Tensor, at::Tensor>(kFlat, vBias); | 69 | return std::tuple<at::Tensor, at::Tensor>(kFlat, vBias); |
| 71 | } | 70 | } |
Rtorch_extension/cann_ops_transformer/ops/graph_convert/graph_convert_stem_oam_prep_paged_kv.py→attention/stem_oam_prep_paged_kv/torch_extension/graph_convert_stem_oam_prep_paged_kv.py+0-0
File renamed without changes.
Rtorch_extension/cann_ops_transformer/ops/stem_oam_prep_paged_kv.py→attention/stem_oam_prep_paged_kv/torch_extension/stem_oam_prep_paged_kv.py+8-6
| @@ -10,18 +10,19 @@ | |||
| 10 | import torch | 10 | import torch |
| 11 | import torch_npu | 11 | import torch_npu |
| 12 | from torch.library import impl | 12 | from torch.library import impl |
| 13 | -from cann_ops_transformer.op_builder.builder import OpBuilder | 13 | +from cann_ops_transformer.op_builder import OpBuilder, get_as_library |
| 14 | -from cann_ops_transformer.op_builder.builder import AS_LIBRARY | ||
| 15 | 14 | ||
| 16 | DIM_QK = 128 | 15 | DIM_QK = 128 |
| 17 | 16 | ||
| 18 | 17 | ||
| 19 | class StemOamPrepPagedKvOpBuilder(OpBuilder): | 18 | class StemOamPrepPagedKvOpBuilder(OpBuilder): |
| 20 | def __init__(self): | 19 | def __init__(self): |
| 21 | - super(StemOamPrepPagedKvOpBuilder, self).__init__("stem_oam_prep_paged_kv") | 20 | + super(StemOamPrepPagedKvOpBuilder, self).__init__( |
| 21 | + "stem_oam_prep_paged_kv", category="attention" | ||
| 22 | + ) | ||
| 22 | 23 | ||
| 23 | def sources(self): | 24 | def sources(self): |
| 24 | - return ["ops/csrc/stem_oam_prep_paged_kv.cpp"] | 25 | + return ["csrc/attention/stem_oam_prep_paged_kv.cpp"] |
| 25 | 26 | ||
| 26 | def schema(self) -> str: | 27 | def schema(self) -> str: |
| 27 | return [ | 28 | return [ |
| @@ -32,7 +33,7 @@ class StemOamPrepPagedKvOpBuilder(OpBuilder): | |||
| 32 | ] | 33 | ] |
| 33 | 34 | ||
| 34 | def register_meta(self): | 35 | def register_meta(self): |
| 35 | - @impl(AS_LIBRARY, self.name, "Meta") | 36 | + @impl(get_as_library(), self.name, "Meta") |
| 36 | def stem_oam_prep_paged_kv_meta( | 37 | def stem_oam_prep_paged_kv_meta( |
| 37 | k_cache, | 38 | k_cache, |
| 38 | v_cache, | 39 | v_cache, |
| @@ -64,9 +65,10 @@ class StemOamPrepPagedKvOpBuilder(OpBuilder): | |||
| 64 | 65 | ||
| 65 | 66 | ||
| 66 | stem_oam_prep_paged_kv_op_builder = StemOamPrepPagedKvOpBuilder() | 67 | stem_oam_prep_paged_kv_op_builder = StemOamPrepPagedKvOpBuilder() |
| 68 | +stem_oam_prep_paged_kv_op_builder._ensure_initialized() | ||
| 67 | 69 | ||
| 68 | 70 | ||
| 69 | -@impl(AS_LIBRARY, "stem_oam_prep_paged_kv", "PrivateUse1") | 71 | +@impl(get_as_library(), "stem_oam_prep_paged_kv", "PrivateUse1") |
| 70 | def stem_oam_prep_paged_kv( | 72 | def stem_oam_prep_paged_kv( |
| 71 | k_cache, | 73 | k_cache, |
| 72 | v_cache, | 74 | v_cache, |
| @@ -0,0 +1,4 @@ | |||
| 1 | +__all__ = ["stem_oam_prep_varlen_q"] | ||
| 2 | + | ||
| 3 | +from .stem_oam_prep_varlen_q import stem_oam_prep_varlen_q | ||
| 4 | +from . import graph_convert_stem_oam_prep_varlen_q | ||
Rtorch_extension/cann_ops_transformer/ops/csrc/stem_oam_prep_varlen_q.cpp→attention/stem_oam_prep_varlen_q/torch_extension/csrc/stem_oam_prep_varlen_q.cpp+0-0
File renamed without changes.
Rtorch_extension/cann_ops_transformer/ops/graph_convert/graph_convert_stem_oam_prep_varlen_q.py→attention/stem_oam_prep_varlen_q/torch_extension/graph_convert_stem_oam_prep_varlen_q.py+0-0
File renamed without changes.
Rtorch_extension/cann_ops_transformer/ops/stem_oam_prep_varlen_q.py→attention/stem_oam_prep_varlen_q/torch_extension/stem_oam_prep_varlen_q.py+8-6
| @@ -9,16 +9,17 @@ | |||
| 9 | # ----------------------------------------------------------------------------------------------------------- | 9 | # ----------------------------------------------------------------------------------------------------------- |
| 10 | import torch | 10 | import torch |
| 11 | from torch.library import impl | 11 | from torch.library import impl |
| 12 | -from cann_ops_transformer.op_builder.builder import OpBuilder | 12 | +from cann_ops_transformer.op_builder import OpBuilder, get_as_library |
| 13 | -from cann_ops_transformer.op_builder.builder import AS_LIBRARY | ||
| 14 | 13 | ||
| 15 | 14 | ||
| 16 | class StemOamPrepVarlenQOpBuilder(OpBuilder): | 15 | class StemOamPrepVarlenQOpBuilder(OpBuilder): |
| 17 | def __init__(self): | 16 | def __init__(self): |
| 18 | - super(StemOamPrepVarlenQOpBuilder, self).__init__("stem_oam_prep_varlen_q") | 17 | + super(StemOamPrepVarlenQOpBuilder, self).__init__( |
| 18 | + "stem_oam_prep_varlen_q", category="attention" | ||
| 19 | + ) | ||
| 19 | 20 | ||
| 20 | def sources(self): | 21 | def sources(self): |
| 21 | - return ["ops/csrc/stem_oam_prep_varlen_q.cpp"] | 22 | + return ["csrc/attention/stem_oam_prep_varlen_q.cpp"] |
| 22 | 23 | ||
| 23 | def schema(self) -> str: | 24 | def schema(self) -> str: |
| 24 | return ( | 25 | return ( |
| @@ -28,7 +29,7 @@ class StemOamPrepVarlenQOpBuilder(OpBuilder): | |||
| 28 | ) | 29 | ) |
| 29 | 30 | ||
| 30 | def register_meta(self): | 31 | def register_meta(self): |
| 31 | - @impl(AS_LIBRARY, self.name, "Meta") | 32 | + @impl(get_as_library(), self.name, "Meta") |
| 32 | def stem_oam_prep_varlen_q_meta( | 33 | def stem_oam_prep_varlen_q_meta( |
| 33 | q, | 34 | q, |
| 34 | q_seq_lens, | 35 | q_seq_lens, |
| @@ -52,9 +53,10 @@ class StemOamPrepVarlenQOpBuilder(OpBuilder): | |||
| 52 | 53 | ||
| 53 | 54 | ||
| 54 | stem_oam_prep_varlen_q_op_builder = StemOamPrepVarlenQOpBuilder() | 55 | stem_oam_prep_varlen_q_op_builder = StemOamPrepVarlenQOpBuilder() |
| 56 | +stem_oam_prep_varlen_q_op_builder._ensure_initialized() | ||
| 55 | 57 | ||
| 56 | 58 | ||
| 57 | -@impl(AS_LIBRARY, stem_oam_prep_varlen_q_op_builder.name, "PrivateUse1") | 59 | +@impl(get_as_library(), stem_oam_prep_varlen_q_op_builder.name, "PrivateUse1") |
| 58 | def stem_oam_prep_varlen_q( | 60 | def stem_oam_prep_varlen_q( |
| 59 | q, q_seq_lens, cu_seq_lens_q, *, q_scale=None, stem_block_size=128, stem_stride=16 | 61 | q, q_seq_lens, cu_seq_lens_q, *, q_scale=None, stem_block_size=128, stem_stride=16 |
| 60 | ): | 62 | ): |
| @@ -370,6 +370,7 @@ function help_info() { | |||
| 370 | echo " --jit build run package without kernel bin" | 370 | echo " --jit build run package without kernel bin" |
| 371 | echo " --pkg build run package with kernel bin" | 371 | echo " --pkg build run package with kernel bin" |
| 372 | echo " --pkg-type=<TYPE> Specify package type(TYPE options: run/rpm/deb/all), Default: run" | 372 | echo " --pkg-type=<TYPE> Specify package type(TYPE options: run/rpm/deb/all), Default: run" |
| 373 | + echo " --torch_extension Build torch_extension whl only, support --ops for single op packaging" | ||
| 373 | echo " --torch_extension_only Build torch_extension whl package only" | 374 | echo " --torch_extension_only Build torch_extension whl package only" |
| 374 | echo " --experimental build experimental version" | 375 | echo " --experimental build experimental version" |
| 375 | echo " --opkernel_aicpu build aicpu kernel" | 376 | echo " --opkernel_aicpu build aicpu kernel" |
| @@ -844,6 +845,19 @@ function build_torch_extension_whl() { | |||
| 844 | return 0 | 845 | return 0 |
| 845 | fi | 846 | fi |
| 846 | 847 | ||
| 848 | + if [[ -n "${ascend_op_name}" ]]; then | ||
| 849 | + export TORCH_EXTENSION_OPS="${ascend_op_name}" | ||
| 850 | + if [[ -n "${vendor_name}" ]]; then | ||
| 851 | + export TORCH_EXTENSION_VENDOR="${vendor_name}" | ||
| 852 | + else | ||
| 853 | + export TORCH_EXTENSION_VENDOR="custom" | ||
| 854 | + fi | ||
| 855 | + log "[INFO] Building torch_extension whl with ops: ${ascend_op_name}, vendor: ${TORCH_EXTENSION_VENDOR}" | ||
| 856 | + else | ||
| 857 | + unset TORCH_EXTENSION_OPS | ||
| 858 | + unset TORCH_EXTENSION_VENDOR | ||
| 859 | + fi | ||
| 860 | + | ||
| 847 | python3 -m build --wheel -n 2>&1 || { | 861 | python3 -m build --wheel -n 2>&1 || { |
| 848 | log "[ERROR] Failed to build torch_extension whl package" | 862 | log "[ERROR] Failed to build torch_extension whl package" |
| 849 | cd "${original_dir}" | 863 | cd "${original_dir}" |
| @@ -1235,7 +1249,7 @@ set_example_opt() { | |||
| 1235 | # 所有支持的长选项(不含值),用于参数合法性校验 | 1249 | # 所有支持的长选项(不含值),用于参数合法性校验 |
| 1236 | SUPPORTED_LONG_OPTS=( | 1250 | SUPPORTED_LONG_OPTS=( |
| 1237 | "help" "list_soc" "pkg" "pkg-type=" "static" "jit" "noaicpu" "opkernel_aicpu" "opkernel" | 1251 | "help" "list_soc" "pkg" "pkg-type=" "static" "jit" "noaicpu" "opkernel_aicpu" "opkernel" |
| 1238 | - "experimental" "noexec" "torch_extension_only" "oom" "make_clean" | 1252 | + "experimental" "noexec" "torch_extension" "torch_extension_only" "oom" "make_clean" |
| 1239 | "mssanitizer" "dump_cce" | 1253 | "mssanitizer" "dump_cce" |
| 1240 | "ophost" "opapi" "opgraph" "onnxplugin" | 1254 | "ophost" "opapi" "opgraph" "onnxplugin" |
| 1241 | "ophost_test" "opapi_test" "opgraph_test" "opkernel_test" | 1255 | "ophost_test" "opapi_test" "opgraph_test" "opkernel_test" |
| @@ -1895,6 +1909,10 @@ while [[ $# -gt 0 ]]; do | |||
| 1895 | ENABLE_UT_EXEC=FALSE | 1909 | ENABLE_UT_EXEC=FALSE |
| 1896 | shift | 1910 | shift |
| 1897 | ;; | 1911 | ;; |
| 1912 | + --torch_extension) | ||
| 1913 | + ENABLE_TORCH_EXTENSION_ONLY=TRUE | ||
| 1914 | + shift | ||
| 1915 | + ;; | ||
| 1898 | --torch_extension_only) | 1916 | --torch_extension_only) |
| 1899 | ENABLE_TORCH_EXTENSION_ONLY=TRUE | 1917 | ENABLE_TORCH_EXTENSION_ONLY=TRUE |
| 1900 | shift | 1918 | shift |
| @@ -0,0 +1,3 @@ | |||
| 1 | +__all__ = ["grouped_matmul_activation_quant"] | ||
| 2 | + | ||
| 3 | +from .grouped_matmul_activation_quant import grouped_matmul_activation_quant | ||
Rtorch_extension/cann_ops_transformer/ops/csrc/grouped_matmul_activation_quant.cpp→gmm/grouped_matmul_activation_quant/torch_extension/csrc/grouped_matmul_activation_quant.cpp+2-6
| @@ -104,8 +104,7 @@ at::ScalarType GetYScalarType(int64_t yDtype) | |||
| 104 | if (geDtype == GE_DTYPE_FLOAT8_E5M2) { | 104 | if (geDtype == GE_DTYPE_FLOAT8_E5M2) { |
| 105 | return at::ScalarType::Float8_e5m2; | 105 | return at::ScalarType::Float8_e5m2; |
| 106 | } | 106 | } |
| 107 | - TORCH_CHECK(false, "y_dtype only supports FLOAT8_E4M3FN or FLOAT8_E5M2, but got ", | 107 | + TORCH_CHECK(false, "y_dtype only supports FLOAT8_E4M3FN or FLOAT8_E5M2, but got ", GetDtypeName(yDtype), "."); |
| 108 | - GetDtypeName(yDtype), "."); | ||
| 109 | } | 108 | } |
| 110 | 109 | ||
| 111 | int64_t ResolveYGeDtype(const c10::optional<int64_t> &yDtype, aclDataType xAclDtype) | 110 | int64_t ResolveYGeDtype(const c10::optional<int64_t> &yDtype, aclDataType xAclDtype) |
| @@ -122,10 +121,7 @@ int64_t ResolveYGeDtype(const c10::optional<int64_t> &yDtype, aclDataType xAclDt | |||
| 122 | TORCH_CHECK(false, "y_dtype is None only supports inferring from FP8 x dtype."); | 121 | TORCH_CHECK(false, "y_dtype is None only supports inferring from FP8 x dtype."); |
| 123 | } | 122 | } |
| 124 | 123 | ||
| 125 | -int64_t CeilDiv(int64_t value, int64_t factor) | 124 | +int64_t CeilDiv(int64_t value, int64_t factor) { return (value + factor - 1) / factor; } |
| 126 | -{ | ||
| 127 | - return (value + factor - 1) / factor; | ||
| 128 | -} | ||
| 129 | 125 | ||
| 130 | int64_t InferNzLogicalN(const at::Tensor &weightScaleTensor) | 126 | int64_t InferNzLogicalN(const at::Tensor &weightScaleTensor) |
| 131 | { | 127 | { |
Rtorch_extension/cann_ops_transformer/ops/grouped_matmul_activation_quant.py→gmm/grouped_matmul_activation_quant/torch_extension/grouped_matmul_activation_quant.py+6-6
| @@ -14,8 +14,7 @@ from typing import List, Optional, Tuple | |||
| 14 | import torch | 14 | import torch |
| 15 | import torch_npu | 15 | import torch_npu |
| 16 | from torch.library import impl | 16 | from torch.library import impl |
| 17 | -from cann_ops_transformer.op_builder.builder import AS_LIBRARY | 17 | +from cann_ops_transformer.op_builder import OpBuilder, get_as_library |
| 18 | -from cann_ops_transformer.op_builder.builder import OpBuilder | ||
| 19 | 18 | ||
| 20 | 19 | ||
| 21 | GE_DTYPE_FLOAT = 0 | 20 | GE_DTYPE_FLOAT = 0 |
| @@ -137,11 +136,11 @@ def _infer_nz_logical_n(weight_scale): | |||
| 137 | class GroupedMatmulActivationQuantOpBuilder(OpBuilder): | 136 | class GroupedMatmulActivationQuantOpBuilder(OpBuilder): |
| 138 | def __init__(self): | 137 | def __init__(self): |
| 139 | super(GroupedMatmulActivationQuantOpBuilder, self).__init__( | 138 | super(GroupedMatmulActivationQuantOpBuilder, self).__init__( |
| 140 | - "grouped_matmul_activation_quant" | 139 | + "grouped_matmul_activation_quant", category="gmm" |
| 141 | ) | 140 | ) |
| 142 | 141 | ||
| 143 | def sources(self): | 142 | def sources(self): |
| 144 | - return ["ops/csrc/grouped_matmul_activation_quant.cpp"] | 143 | + return ["csrc/gmm/grouped_matmul_activation_quant.cpp"] |
| 145 | 144 | ||
| 146 | def schema(self) -> str: | 145 | def schema(self) -> str: |
| 147 | return ( | 146 | return ( |
| @@ -155,7 +154,7 @@ class GroupedMatmulActivationQuantOpBuilder(OpBuilder): | |||
| 155 | ) | 154 | ) |
| 156 | 155 | ||
| 157 | def register_meta(self): | 156 | def register_meta(self): |
| 158 | - @impl(AS_LIBRARY, self.name, "Meta") | 157 | + @impl(get_as_library(), self.name, "Meta") |
| 159 | def grouped_matmul_activation_quant_meta( | 158 | def grouped_matmul_activation_quant_meta( |
| 160 | x, | 159 | x, |
| 161 | group_list, | 160 | group_list, |
| @@ -207,9 +206,10 @@ class GroupedMatmulActivationQuantOpBuilder(OpBuilder): | |||
| 207 | 206 | ||
| 208 | 207 | ||
| 209 | _grouped_matmul_activation_quant_op_builder = GroupedMatmulActivationQuantOpBuilder() | 208 | _grouped_matmul_activation_quant_op_builder = GroupedMatmulActivationQuantOpBuilder() |
| 209 | +_grouped_matmul_activation_quant_op_builder._ensure_initialized() | ||
| 210 | 210 | ||
| 211 | 211 | ||
| 212 | -@impl(AS_LIBRARY, _grouped_matmul_activation_quant_op_builder.name, "PrivateUse1") | 212 | +@impl(get_as_library(), _grouped_matmul_activation_quant_op_builder.name, "PrivateUse1") |
| 213 | def _grouped_matmul_activation_quant( | 213 | def _grouped_matmul_activation_quant( |
| 214 | x, | 214 | x, |
| 215 | group_list, | 215 | group_list, |
| @@ -0,0 +1,13 @@ | |||
| 1 | +__all__ = [ | ||
| 2 | + "causal_conv1d_fn", | ||
| 3 | + "causal_conv1d_update", | ||
| 4 | + "convert_causal_conv1d_fn", | ||
| 5 | + "convert_causal_conv1d_update", | ||
| 6 | +] | ||
| 7 | + | ||
| 8 | +from .causal_conv1d_fn import causal_conv1d_fn | ||
| 9 | +from .causal_conv1d_update import causal_conv1d_update | ||
| 10 | +from .graph_convert_causal_conv1d import ( | ||
| 11 | + convert_causal_conv1d_fn, | ||
| 12 | + convert_causal_conv1d_update, | ||
| 13 | +) | ||
Rtorch_extension/cann_ops_transformer/ops/causal_conv1d_fn.py→mamba/causal_conv1d/torch_extension/causal_conv1d_fn.py+8-6
| @@ -11,17 +11,18 @@ from typing import Optional | |||
| 11 | 11 | ||
| 12 | import torch | 12 | import torch |
| 13 | from torch.library import impl | 13 | from torch.library import impl |
| 14 | -from cann_ops_transformer.op_builder.builder import OpBuilder | 14 | +from cann_ops_transformer.op_builder import OpBuilder, get_as_library |
| 15 | -from cann_ops_transformer.op_builder.builder import AS_LIBRARY | ||
| 16 | 15 | ||
| 17 | 16 | ||
| 18 | class CausalConv1dFnOpBuilder(OpBuilder): | 17 | class CausalConv1dFnOpBuilder(OpBuilder): |
| 19 | def __init__(self): | 18 | def __init__(self): |
| 20 | - super(CausalConv1dFnOpBuilder, self).__init__("causal_conv1d_fn") | 19 | + super(CausalConv1dFnOpBuilder, self).__init__( |
| 20 | + "causal_conv1d_fn", category="mamba" | ||
| 21 | + ) | ||
| 21 | 22 | ||
| 22 | def sources(self): | 23 | def sources(self): |
| 23 | """Path to C++ source code.""" | 24 | """Path to C++ source code.""" |
| 24 | - return ["ops/csrc/causal_conv1d_fn.cpp"] | 25 | + return ["csrc/mamba/causal_conv1d_fn.cpp"] |
| 25 | 26 | ||
| 26 | def schema(self) -> str: | 27 | def schema(self) -> str: |
| 27 | """PyTorch operator schema.""" | 28 | """PyTorch operator schema.""" |
| @@ -47,7 +48,7 @@ class CausalConv1dFnOpBuilder(OpBuilder): | |||
| 47 | def register_meta(self): | 48 | def register_meta(self): |
| 48 | """Register Meta implementation for shape/dtype inference.""" | 49 | """Register Meta implementation for shape/dtype inference.""" |
| 49 | 50 | ||
| 50 | - @impl(AS_LIBRARY, self.name, "Meta") | 51 | + @impl(get_as_library(), self.name, "Meta") |
| 51 | def causal_conv1d_fn_meta( | 52 | def causal_conv1d_fn_meta( |
| 52 | x: torch.Tensor, | 53 | x: torch.Tensor, |
| 53 | weight: torch.Tensor, | 54 | weight: torch.Tensor, |
| @@ -71,9 +72,10 @@ class CausalConv1dFnOpBuilder(OpBuilder): | |||
| 71 | 72 | ||
| 72 | 73 | ||
| 73 | _causal_conv1d_fn_op_builder = CausalConv1dFnOpBuilder() | 74 | _causal_conv1d_fn_op_builder = CausalConv1dFnOpBuilder() |
| 75 | +_causal_conv1d_fn_op_builder._ensure_initialized() | ||
| 74 | 76 | ||
| 75 | 77 | ||
| 76 | -@impl(AS_LIBRARY, _causal_conv1d_fn_op_builder.name, "PrivateUse1") | 78 | +@impl(get_as_library(), _causal_conv1d_fn_op_builder.name, "PrivateUse1") |
| 77 | def _causal_conv1d_fn( | 79 | def _causal_conv1d_fn( |
| 78 | x: torch.Tensor, | 80 | x: torch.Tensor, |
| 79 | weight: torch.Tensor, | 81 | weight: torch.Tensor, |
Rtorch_extension/cann_ops_transformer/ops/causal_conv1d_update.py→mamba/causal_conv1d/torch_extension/causal_conv1d_update.py+8-6
| @@ -11,17 +11,18 @@ from typing import Optional | |||
| 11 | 11 | ||
| 12 | import torch | 12 | import torch |
| 13 | from torch.library import impl | 13 | from torch.library import impl |
| 14 | -from cann_ops_transformer.op_builder.builder import OpBuilder | 14 | +from cann_ops_transformer.op_builder import OpBuilder, get_as_library |
| 15 | -from cann_ops_transformer.op_builder.builder import AS_LIBRARY | ||
| 16 | 15 | ||
| 17 | 16 | ||
| 18 | class CausalConv1dUpdateOpBuilder(OpBuilder): | 17 | class CausalConv1dUpdateOpBuilder(OpBuilder): |
| 19 | def __init__(self): | 18 | def __init__(self): |
| 20 | - super(CausalConv1dUpdateOpBuilder, self).__init__("causal_conv1d_update") | 19 | + super(CausalConv1dUpdateOpBuilder, self).__init__( |
| 20 | + "causal_conv1d_update", category="mamba" | ||
| 21 | + ) | ||
| 21 | 22 | ||
| 22 | def sources(self): | 23 | def sources(self): |
| 23 | """Path to C++ source code.""" | 24 | """Path to C++ source code.""" |
| 24 | - return ["ops/csrc/causal_conv1d_update.cpp"] | 25 | + return ["csrc/mamba/causal_conv1d_update.cpp"] |
| 25 | 26 | ||
| 26 | def schema(self) -> str: | 27 | def schema(self) -> str: |
| 27 | """PyTorch operator schema.""" | 28 | """PyTorch operator schema.""" |
| @@ -44,7 +45,7 @@ class CausalConv1dUpdateOpBuilder(OpBuilder): | |||
| 44 | def register_meta(self): | 45 | def register_meta(self): |
| 45 | """Register Meta implementation for shape/dtype inference.""" | 46 | """Register Meta implementation for shape/dtype inference.""" |
| 46 | 47 | ||
| 47 | - @impl(AS_LIBRARY, self.name, "Meta") | 48 | + @impl(get_as_library(), self.name, "Meta") |
| 48 | def causal_conv1d_update_meta( | 49 | def causal_conv1d_update_meta( |
| 49 | x: torch.Tensor, | 50 | x: torch.Tensor, |
| 50 | conv_state: torch.Tensor, | 51 | conv_state: torch.Tensor, |
| @@ -65,9 +66,10 @@ class CausalConv1dUpdateOpBuilder(OpBuilder): | |||
| 65 | 66 | ||
| 66 | 67 | ||
| 67 | _causal_conv1d_update_op_builder = CausalConv1dUpdateOpBuilder() | 68 | _causal_conv1d_update_op_builder = CausalConv1dUpdateOpBuilder() |
| 69 | +_causal_conv1d_update_op_builder._ensure_initialized() | ||
| 68 | 70 | ||
| 69 | 71 | ||
| 70 | -@impl(AS_LIBRARY, _causal_conv1d_update_op_builder.name, "PrivateUse1") | 72 | +@impl(get_as_library(), _causal_conv1d_update_op_builder.name, "PrivateUse1") |
| 71 | def _causal_conv1d_update( | 73 | def _causal_conv1d_update( |
| 72 | x: torch.Tensor, | 74 | x: torch.Tensor, |
| 73 | conv_state: torch.Tensor, | 75 | conv_state: torch.Tensor, |
Rtorch_extension/cann_ops_transformer/ops/csrc/causal_conv1d_fn.cpp→mamba/causal_conv1d/torch_extension/csrc/causal_conv1d_fn.cpp+1-4
| @@ -45,9 +45,6 @@ at::Tensor CausalConv1dFn(const at::Tensor &x, const at::Tensor &weight, const c | |||
| 45 | return y; | 45 | return y; |
| 46 | } | 46 | } |
| 47 | 47 | ||
| 48 | -PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) | 48 | +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("causal_conv1d_fn", &CausalConv1dFn, "causal_conv1d prefill"); } |
| 49 | -{ | ||
| 50 | - m.def("causal_conv1d_fn", &CausalConv1dFn, "causal_conv1d prefill"); | ||
| 51 | -} | ||
| 52 | 49 | ||
| 53 | } // namespace op_api | 50 | } // namespace op_api |
Rtorch_extension/cann_ops_transformer/ops/csrc/causal_conv1d_update.cpp→mamba/causal_conv1d/torch_extension/csrc/causal_conv1d_update.cpp+0-0
File renamed without changes.
Rtorch_extension/cann_ops_transformer/ops/graph_convert/graph_convert_causal_conv1d.py→mamba/causal_conv1d/torch_extension/graph_convert_causal_conv1d.py+0-0
File renamed without changes.
| @@ -0,0 +1,14 @@ | |||
| 1 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 10 | +__all__ = ["CommContextManager", "MoeDistributeBuffer", "ElasticBuffer", "EPHandle"] | ||
| 11 | + | ||
| 12 | +from .comm_context import CommContextManager | ||
| 13 | +from .moe_distribute_buffer import MoeDistributeBuffer | ||
| 14 | +from .elastic_buffer import ElasticBuffer, EPHandle | ||
Rtorch_extension/cann_ops_transformer/ops/comm_context.py→mc2/common/torch_extension/comm_context.py+4-3
| @@ -7,15 +7,15 @@ | |||
| 7 | # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | 7 | # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. |
| 8 | # See LICENSE in the root of the software repository for the full text of the License. | 8 | # See LICENSE in the root of the software repository for the full text of the License. |
| 9 | # ----------------------------------------------------------------------------------------------------------- | 9 | # ----------------------------------------------------------------------------------------------------------- |
| 10 | -from cann_ops_transformer.op_builder.builder import OpBuilder | 10 | +from cann_ops_transformer.op_builder import OpBuilder, get_as_library |
| 11 | 11 | ||
| 12 | 12 | ||
| 13 | class CommContextOpBuilder(OpBuilder): | 13 | class CommContextOpBuilder(OpBuilder): |
| 14 | def __init__(self): | 14 | def __init__(self): |
| 15 | - super(CommContextOpBuilder, self).__init__("comm_context") | 15 | + super(CommContextOpBuilder, self).__init__("comm_context", category="mc2") |
| 16 | 16 | ||
| 17 | def sources(self): | 17 | def sources(self): |
| 18 | - return ["ops/csrc/comm_context.cpp"] | 18 | + return ["csrc/mc2/comm_context.cpp"] |
| 19 | 19 | ||
| 20 | def schema(self): | 20 | def schema(self): |
| 21 | return None | 21 | return None |
| @@ -25,6 +25,7 @@ class CommContextOpBuilder(OpBuilder): | |||
| 25 | 25 | ||
| 26 | 26 | ||
| 27 | comm_context_op_builder = CommContextOpBuilder() | 27 | comm_context_op_builder = CommContextOpBuilder() |
| 28 | +comm_context_op_builder._ensure_initialized() | ||
| 28 | 29 | ||
| 29 | 30 | ||
| 30 | class _LazyClassProxy: | 31 | class _LazyClassProxy: |
Rtorch_extension/cann_ops_transformer/ops/csrc/comm_context.cpp→mc2/common/torch_extension/csrc/comm_context.cpp+37-52
| @@ -30,6 +30,7 @@ constexpr uint32_t HCCL_CONTEXT_TAG_MAX_LEN = 255; | |||
| 30 | constexpr uint32_t HCCL_COMM_LAYERS_MTE_CCU = 1; | 30 | constexpr uint32_t HCCL_COMM_LAYERS_MTE_CCU = 1; |
| 31 | constexpr uint32_t HCCL_COMM_LAYERS_UB_MEM = 0; | 31 | constexpr uint32_t HCCL_COMM_LAYERS_UB_MEM = 0; |
| 32 | constexpr uint32_t GET_LOCAL_SERVER_RANK_SIZE_LAYER = 0; | 32 | constexpr uint32_t GET_LOCAL_SERVER_RANK_SIZE_LAYER = 0; |
| 33 | +constexpr int64_t DEFAULT_RANK_NUM_PER_SERVER = 2; | ||
| 33 | 34 | ||
| 34 | enum class TopoType : uint32_t { | 35 | enum class TopoType : uint32_t { |
| 35 | INTRA_SUPER_NODE = 0, // 超节点内通信(默认) | 36 | INTRA_SUPER_NODE = 0, // 超节点内通信(默认) |
| @@ -240,9 +241,8 @@ public: | |||
| 240 | const CommProtocol &protocol, CommContext &commContextStruct, int64_t &cclBufferSize) | 241 | const CommProtocol &protocol, CommContext &commContextStruct, int64_t &cclBufferSize) |
| 241 | { | 242 | { |
| 242 | std::string mc2ContextTag = std::string(group) + opName; | 243 | std::string mc2ContextTag = std::string(group) + opName; |
| 243 | - TORCH_CHECK(mc2ContextTag.size() <= HCCL_CONTEXT_TAG_MAX_LEN, | 244 | + TORCH_CHECK(mc2ContextTag.size() <= HCCL_CONTEXT_TAG_MAX_LEN, "Mc2ContextTag is too long, max size is ", |
| 244 | - "Mc2ContextTag is too long, max size is ", HCCL_CONTEXT_TAG_MAX_LEN, | 245 | + HCCL_CONTEXT_TAG_MAX_LEN, ", got ", mc2ContextTag.size()); |
| 245 | - ", got ", mc2ContextTag.size()); | ||
| 246 | 246 | ||
| 247 | CommEngine engine = CommEngine::COMM_ENGINE_AIV; | 247 | CommEngine engine = CommEngine::COMM_ENGINE_AIV; |
| 248 | void *ctx = nullptr; | 248 | void *ctx = nullptr; |
| @@ -529,9 +529,8 @@ public: | |||
| 529 | ASCEND_LOGI("Get rank size success, rankSize is: %u", rankSize); | 529 | ASCEND_LOGI("Get rank size success, rankSize is: %u", rankSize); |
| 530 | 530 | ||
| 531 | std::string memBufferTag = mc2ContextTag + "_buffer"; | 531 | std::string memBufferTag = mc2ContextTag + "_buffer"; |
| 532 | - TORCH_CHECK(memBufferTag.size() <= HCCL_CONTEXT_TAG_MAX_LEN, | 532 | + TORCH_CHECK(memBufferTag.size() <= HCCL_CONTEXT_TAG_MAX_LEN, "MemBufferTag is too long, max size is ", |
| 533 | - "MemBufferTag is too long, max size is ", HCCL_CONTEXT_TAG_MAX_LEN, | 533 | + HCCL_CONTEXT_TAG_MAX_LEN, ", got ", memBufferTag.size()); |
| 534 | - ", got ", memBufferTag.size()); | ||
| 535 | AllocateAndRegisterDeviceBuffer(commHandle, memBufferTag); | 534 | AllocateAndRegisterDeviceBuffer(commHandle, memBufferTag); |
| 536 | 535 | ||
| 537 | GetHcclCommResource(commHandle, engine, protocol, commContextStruct, rankSize, hcclBuffSize, memBufferTag); | 536 | GetHcclCommResource(commHandle, engine, protocol, commContextStruct, rankSize, hcclBuffSize, memBufferTag); |
| @@ -604,20 +603,14 @@ public: | |||
| 604 | static_cast<int>(protocol)); | 603 | static_cast<int>(protocol)); |
| 605 | } | 604 | } |
| 606 | 605 | ||
| 607 | - TopoType GetTopoType() const | 606 | + TopoType GetTopoType() const { return topoType_; } |
| 608 | - { | 607 | + int64_t GetRankNumPerServer() const { return rankNumPerServer_; } |
| 609 | - return topoType_; | ||
| 610 | - } | ||
| 611 | - int64_t GetRankNumPerServer() const | ||
| 612 | - { | ||
| 613 | - return rankNumPerServer_; | ||
| 614 | - } | ||
| 615 | 608 | ||
| 616 | // 记录本卡与其他卡的通信层数,key为其他卡的rankId,value为通信层数 | 609 | // 记录本卡与其他卡的通信层数,key为其他卡的rankId,value为通信层数 |
| 617 | std::unordered_map<uint32_t, uint32_t> layerMap_; | 610 | std::unordered_map<uint32_t, uint32_t> layerMap_; |
| 618 | uint32_t rankNumPerUbDomain_ = 0; | 611 | uint32_t rankNumPerUbDomain_ = 0; |
| 619 | TopoType topoType_ = TopoType::INTRA_SUPER_NODE; | 612 | TopoType topoType_ = TopoType::INTRA_SUPER_NODE; |
| 620 | - int64_t rankNumPerServer_ = 2; | 613 | + int64_t rankNumPerServer_ = DEFAULT_RANK_NUM_PER_SERVER; |
| 621 | int64_t customCclBufferSize_ = 0; | 614 | int64_t customCclBufferSize_ = 0; |
| 622 | void **customDeviceBuffer_ = nullptr; | 615 | void **customDeviceBuffer_ = nullptr; |
| 623 | HcclMemHandle *customMemHandle_ = nullptr; | 616 | HcclMemHandle *customMemHandle_ = nullptr; |
| @@ -630,11 +623,17 @@ public: | |||
| 630 | CommContextManager(const std::string &group, int64_t worldSize, const py::object &backend = py::str("kfc"), | 623 | CommContextManager(const std::string &group, int64_t worldSize, const py::object &backend = py::str("kfc"), |
| 631 | const std::string &commAlg = "ub-mem", const std::string &opName = "moe_dispatch_ffn_combine", | 624 | const std::string &commAlg = "ub-mem", const std::string &opName = "moe_dispatch_ffn_combine", |
| 632 | int64_t customCclBufferSize = 0) | 625 | int64_t customCclBufferSize = 0) |
| 633 | - : group_(group), worldSize_(worldSize), commAlg_(commAlg), opName_(opName), backend_(backend), | 626 | + : group_(group), |
| 634 | - mode_(BackendMode::UNINITIALIZED), cclBufferSize_(0), topoType_(TopoType::INTRA_SUPER_NODE), | 627 | + worldSize_(worldSize), |
| 635 | - rankNumPerServer_(2), customCclBufferSize_(customCclBufferSize) | 628 | + commAlg_(commAlg), |
| 636 | - { | 629 | + opName_(opName), |
| 637 | - } | 630 | + backend_(backend), |
| 631 | + mode_(BackendMode::UNINITIALIZED), | ||
| 632 | + cclBufferSize_(0), | ||
| 633 | + topoType_(TopoType::INTRA_SUPER_NODE), | ||
| 634 | + rankNumPerServer_(DEFAULT_RANK_NUM_PER_SERVER), | ||
| 635 | + customCclBufferSize_(customCclBufferSize) | ||
| 636 | + {} | ||
| 638 | 637 | ||
| 639 | ~CommContextManager() | 638 | ~CommContextManager() |
| 640 | { | 639 | { |
| @@ -680,24 +679,12 @@ public: | |||
| 680 | } | 679 | } |
| 681 | } | 680 | } |
| 682 | 681 | ||
| 683 | - int64_t CclBufferSize() const | 682 | + int64_t CclBufferSize() const { return cclBufferSize_; } |
| 684 | - { | 683 | + int64_t GetTopoType() const { return static_cast<int64_t>(topoType_); } |
| 685 | - return cclBufferSize_; | 684 | + int64_t GetRankNumPerServer() const { return static_cast<int64_t>(rankNumPerServer_); } |
| 686 | - } | ||
| 687 | - int64_t GetTopoType() const | ||
| 688 | - { | ||
| 689 | - return static_cast<int64_t>(topoType_); | ||
| 690 | - } | ||
| 691 | - int64_t GetRankNumPerServer() const | ||
| 692 | - { | ||
| 693 | - return static_cast<int64_t>(rankNumPerServer_); | ||
| 694 | - } | ||
| 695 | 685 | ||
| 696 | private: | 686 | private: |
| 697 | - static int64_t ContextTensorSize() | 687 | + static int64_t ContextTensorSize() { return (sizeof(CommContext) + sizeof(int32_t) - 1) / sizeof(int32_t); } |
| 698 | - { | ||
| 699 | - return (sizeof(CommContext) + sizeof(int32_t) - 1) / sizeof(int32_t); | ||
| 700 | - } | ||
| 701 | 688 | ||
| 702 | void EnsureResolved() | 689 | void EnsureResolved() |
| 703 | { | 690 | { |
| @@ -709,21 +696,19 @@ private: | |||
| 709 | void DispatchBuild(at::Tensor &tensor) | 696 | void DispatchBuild(at::Tensor &tensor) |
| 710 | { | 697 | { |
| 711 | switch (mode_) { | 698 | switch (mode_) { |
| 712 | - case BackendMode::KFC: | 699 | + case BackendMode::KFC: { |
| 713 | - { | 700 | + KfcContextBuilder builder; |
| 714 | - KfcContextBuilder builder; | 701 | + builder.Build(group_, worldSize_, cclBufferSize_, tensor); |
| 715 | - builder.Build(group_, worldSize_, cclBufferSize_, tensor); | 702 | + return; |
| 716 | - return; | 703 | + } |
| 717 | - } | 704 | + case BackendMode::CHANNEL: { |
| 718 | - case BackendMode::CHANNEL: | 705 | + HcclChannelContextBuilder builder; |
| 719 | - { | 706 | + builder.Build(group_, worldSize_, cclBufferSize_, tensor, commAlg_, opName_, customCclBufferSize_, |
| 720 | - HcclChannelContextBuilder builder; | 707 | + &customDeviceBuffer_, &customMemHandle_); |
| 721 | - builder.Build(group_, worldSize_, cclBufferSize_, tensor, commAlg_, opName_, | 708 | + topoType_ = builder.GetTopoType(); |
| 722 | - customCclBufferSize_, &customDeviceBuffer_, &customMemHandle_); | 709 | + rankNumPerServer_ = builder.GetRankNumPerServer(); |
| 723 | - topoType_ = builder.GetTopoType(); | 710 | + return; |
| 724 | - rankNumPerServer_ = builder.GetRankNumPerServer(); | 711 | + } |
| 725 | - return; | ||
| 726 | - } | ||
| 727 | default: | 712 | default: |
| 728 | TORCH_CHECK(false, "Unknown backend mode: ", static_cast<int>(mode_)); | 713 | TORCH_CHECK(false, "Unknown backend mode: ", static_cast<int>(mode_)); |
| 729 | } | 714 | } |
| @@ -737,7 +722,7 @@ private: | |||
| 737 | BackendMode mode_; | 722 | BackendMode mode_; |
| 738 | int64_t cclBufferSize_ = 0; | 723 | int64_t cclBufferSize_ = 0; |
| 739 | TopoType topoType_ = TopoType::INTRA_SUPER_NODE; | 724 | TopoType topoType_ = TopoType::INTRA_SUPER_NODE; |
| 740 | - int64_t rankNumPerServer_ = 2; | 725 | + int64_t rankNumPerServer_ = DEFAULT_RANK_NUM_PER_SERVER; |
| 741 | int64_t customCclBufferSize_ = 0; | 726 | int64_t customCclBufferSize_ = 0; |
| 742 | void *customDeviceBuffer_ = nullptr; | 727 | void *customDeviceBuffer_ = nullptr; |
| 743 | HcclMemHandle customMemHandle_ = nullptr; | 728 | HcclMemHandle customMemHandle_ = nullptr; |
Rtorch_extension/cann_ops_transformer/ops/csrc/elastic_buffer.cpp→mc2/common/torch_extension/csrc/elastic_buffer.cpp+0-0
File renamed without changes.
Rtorch_extension/cann_ops_transformer/ops/elastic_buffer.py→mc2/common/torch_extension/elastic_buffer.py+13-11
| @@ -16,8 +16,7 @@ import torch.distributed as dist | |||
| 16 | from torch.library import impl | 16 | from torch.library import impl |
| 17 | from torch import _check as _torch_check | 17 | from torch import _check as _torch_check |
| 18 | 18 | ||
| 19 | -from cann_ops_transformer.op_builder.builder import OpBuilder | 19 | +from cann_ops_transformer.op_builder import OpBuilder, get_as_library |
| 20 | -from cann_ops_transformer.op_builder.builder import AS_LIBRARY | ||
| 21 | 20 | ||
| 22 | 21 | ||
| 23 | _ENGRAM_DTYPE_TO_INT = { | 22 | _ENGRAM_DTYPE_TO_INT = { |
| @@ -54,11 +53,13 @@ class ElasticBufferOpBuilder(OpBuilder): | |||
| 54 | """OpBuilder for ElasticBuffer operations""" | 53 | """OpBuilder for ElasticBuffer operations""" |
| 55 | 54 | ||
| 56 | def __init__(self): | 55 | def __init__(self): |
| 57 | - super(ElasticBufferOpBuilder, self).__init__("npu_elastic_buffer") | 56 | + super(ElasticBufferOpBuilder, self).__init__( |
| 57 | + "npu_elastic_buffer", category="mc2" | ||
| 58 | + ) | ||
| 58 | 59 | ||
| 59 | def sources(self): | 60 | def sources(self): |
| 60 | """Path to C++ source code.""" | 61 | """Path to C++ source code.""" |
| 61 | - return ["ops/csrc/elastic_buffer.cpp"] | 62 | + return ["csrc/mc2/elastic_buffer.cpp"] |
| 62 | 63 | ||
| 63 | def schema(self): | 64 | def schema(self): |
| 64 | """PyTorch operator signature.""" | 65 | """PyTorch operator signature.""" |
| @@ -75,7 +76,7 @@ class ElasticBufferOpBuilder(OpBuilder): | |||
| 75 | def register_meta(self): | 76 | def register_meta(self): |
| 76 | """Meta implementation for FakeTensor / torch.compile graph tracing.""" | 77 | """Meta implementation for FakeTensor / torch.compile graph tracing.""" |
| 77 | 78 | ||
| 78 | - @impl(AS_LIBRARY, "engram_fetch", "Meta") | 79 | + @impl(get_as_library(), "engram_fetch", "Meta") |
| 79 | def engram_fetch_meta(context, indices, hidden_size, num_entries, dtype): | 80 | def engram_fetch_meta(context, indices, hidden_size, num_entries, dtype): |
| 80 | return torch.empty( | 81 | return torch.empty( |
| 81 | (indices.size(0), hidden_size), | 82 | (indices.size(0), hidden_size), |
| @@ -83,7 +84,7 @@ class ElasticBufferOpBuilder(OpBuilder): | |||
| 83 | device="meta", | 84 | device="meta", |
| 84 | ) | 85 | ) |
| 85 | 86 | ||
| 86 | - @impl(AS_LIBRARY, "engram_fetch_train", "Meta") | 87 | + @impl(get_as_library(), "engram_fetch_train", "Meta") |
| 87 | def engram_fetch_train_meta(*args): | 88 | def engram_fetch_train_meta(*args): |
| 88 | ( | 89 | ( |
| 89 | _context, | 90 | _context, |
| @@ -119,7 +120,7 @@ class ElasticBufferOpBuilder(OpBuilder): | |||
| 119 | ) | 120 | ) |
| 120 | return fetch_result | 121 | return fetch_result |
| 121 | 122 | ||
| 122 | - @impl(AS_LIBRARY, "engram_fetch_wait", "Meta") | 123 | + @impl(get_as_library(), "engram_fetch_wait", "Meta") |
| 123 | def engram_fetch_wait_meta(context, fetched): | 124 | def engram_fetch_wait_meta(context, fetched): |
| 124 | return torch.empty_like(fetched, device="meta") | 125 | return torch.empty_like(fetched, device="meta") |
| 125 | 126 | ||
| @@ -138,14 +139,15 @@ class ElasticBufferOpBuilder(OpBuilder): | |||
| 138 | os.path.join(self._torch_npu_path, "include"), | 139 | os.path.join(self._torch_npu_path, "include"), |
| 139 | os.path.join(self._torch_npu_path, "include/third_party/hccl/inc"), | 140 | os.path.join(self._torch_npu_path, "include/third_party/hccl/inc"), |
| 140 | os.path.join(self._torch_npu_path, "include/third_party/acl/inc"), | 141 | os.path.join(self._torch_npu_path, "include/third_party/acl/inc"), |
| 141 | - os.path.join(self._package_path, "common/inc"), | 142 | + os.path.join(self._package_path, "common"), |
| 142 | ] | 143 | ] |
| 143 | 144 | ||
| 144 | 145 | ||
| 145 | _elastic_buffer_op_builder = ElasticBufferOpBuilder() | 146 | _elastic_buffer_op_builder = ElasticBufferOpBuilder() |
| 147 | +_elastic_buffer_op_builder._ensure_initialized() | ||
| 146 | 148 | ||
| 147 | 149 | ||
| 148 | -@impl(AS_LIBRARY, "engram_fetch", "PrivateUse1") | 150 | +@impl(get_as_library(), "engram_fetch", "PrivateUse1") |
| 149 | def engram_fetch(context, indices, hidden_size, num_entries, dtype): | 151 | def engram_fetch(context, indices, hidden_size, num_entries, dtype): |
| 150 | op_module = _elastic_buffer_op_builder.load() | 152 | op_module = _elastic_buffer_op_builder.load() |
| 151 | return op_module.ElasticBuffer.engram_fetch( | 153 | return op_module.ElasticBuffer.engram_fetch( |
| @@ -153,13 +155,13 @@ def engram_fetch(context, indices, hidden_size, num_entries, dtype): | |||
| 153 | ) | 155 | ) |
| 154 | 156 | ||
| 155 | 157 | ||
| 156 | -@impl(AS_LIBRARY, "engram_fetch_train", "PrivateUse1") | 158 | +@impl(get_as_library(), "engram_fetch_train", "PrivateUse1") |
| 157 | def engram_fetch_train(*args): | 159 | def engram_fetch_train(*args): |
| 158 | op_module = _elastic_buffer_op_builder.load() | 160 | op_module = _elastic_buffer_op_builder.load() |
| 159 | return op_module.ElasticBuffer.engram_fetch_train(*args) | 161 | return op_module.ElasticBuffer.engram_fetch_train(*args) |
| 160 | 162 | ||
| 161 | 163 | ||
| 162 | -@impl(AS_LIBRARY, "engram_fetch_wait", "PrivateUse1") | 164 | +@impl(get_as_library(), "engram_fetch_wait", "PrivateUse1") |
| 163 | def engram_fetch_wait(context, fetched): | 165 | def engram_fetch_wait(context, fetched): |
| 164 | op_module = _elastic_buffer_op_builder.load() | 166 | op_module = _elastic_buffer_op_builder.load() |
| 165 | return op_module.ElasticBuffer.engram_fetch_wait(context, fetched) | 167 | return op_module.ElasticBuffer.engram_fetch_wait(context, fetched) |
| @@ -0,0 +1,328 @@ | |||
| 1 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 2025 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 10 | +import torch | ||
| 11 | +import torch_npu | ||
| 12 | +from torch_npu.utils._error_code import ErrCode, ops_error | ||
| 13 | +from .comm_context import CommContextManager | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +def _empty_topk_weights_like(tensor): | ||
| 17 | + return tensor.new_empty((0,), dtype=torch.float32) | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +def _get_hccl_comm_name(group, rank_id): | ||
| 21 | + if hasattr(group, "get_hccl_comm_name"): | ||
| 22 | + return group.get_hccl_comm_name(rank_id, init_comm=False) | ||
| 23 | + get_backend = getattr(group, "".join(["_get", "_backend"])) | ||
| 24 | + return get_backend(torch.device("npu")).get_hccl_comm_name(rank_id, init_comm=False) | ||
| 25 | + | ||
| 26 | + | ||
| 27 | +class MoeDistributeBuffer: | ||
| 28 | + def __init__(self, group, ccl_buffer_size: int = 0, comm_alg: int = 0): | ||
| 29 | + self.group = group | ||
| 30 | + self.rank_id = torch.distributed.get_rank(group) | ||
| 31 | + self.world_size = torch.distributed.get_world_size(group) | ||
| 32 | + self.group_name = _get_hccl_comm_name(group, self.rank_id) | ||
| 33 | + self._ctx_manager = CommContextManager( | ||
| 34 | + self.group_name, | ||
| 35 | + self.world_size, | ||
| 36 | + backend={ | ||
| 37 | + "Ascend910B": "kfc", | ||
| 38 | + "Ascend910_93": "kfc", | ||
| 39 | + "Ascend950": "channel", | ||
| 40 | + }, | ||
| 41 | + customCclBufferSize=ccl_buffer_size, | ||
| 42 | + ) | ||
| 43 | + self.context = self._ctx_manager.create_context() | ||
| 44 | + self.ccl_buffer_size = self._ctx_manager.ccl_buffer_size | ||
| 45 | + | ||
| 46 | + self.ccl_buffer_size = self._ctx_manager.ccl_buffer_size | ||
| 47 | + | ||
| 48 | + @staticmethod | ||
| 49 | + def get_low_latency_ccl_buffer_size( | ||
| 50 | + world_size: int, | ||
| 51 | + num_max_dispatch_tokens_per_rank: int, | ||
| 52 | + hidden: int, | ||
| 53 | + num_moe_expert: int, | ||
| 54 | + topk: int, | ||
| 55 | + num_shared_expert: int = 0, | ||
| 56 | + num_shared_expert_ranks: int = 0, | ||
| 57 | + comm_alg: str = "", | ||
| 58 | + ) -> int: | ||
| 59 | + def inline_align(value, base): | ||
| 60 | + return (value + base - 1) // base * base | ||
| 61 | + | ||
| 62 | + torch._check( | ||
| 63 | + ((world_size >= 2) and (world_size <= 768)), # world_size当前仅支持[2,768] | ||
| 64 | + lambda: (f"world_size only support in [2, 768], but got {world_size=}."), | ||
| 65 | + ) | ||
| 66 | + torch._check( | ||
| 67 | + ((hidden >= 1024) and (hidden <= 8192)), # hidden当前仅支持[1024,8192] | ||
| 68 | + lambda: (f"hidden only support in [1024, 8192], but got {hidden=}."), | ||
| 69 | + ) | ||
| 70 | + # num_max_dispatch_tokens_per_rank当前仅支持[1,512] | ||
| 71 | + torch._check( | ||
| 72 | + ( | ||
| 73 | + (num_max_dispatch_tokens_per_rank >= 1) | ||
| 74 | + and (num_max_dispatch_tokens_per_rank <= 512) | ||
| 75 | + ), | ||
| 76 | + lambda: ( | ||
| 77 | + f"num_max_dispatch_tokens_per_rank only support in [1, 512], " | ||
| 78 | + f"but got {num_max_dispatch_tokens_per_rank=}." | ||
| 79 | + ), | ||
| 80 | + ) | ||
| 81 | + torch._check( | ||
| 82 | + ( | ||
| 83 | + (num_moe_expert >= 1) and (num_moe_expert <= 1024) | ||
| 84 | + ), # num_moe_expert当前仅支持[1,1024] | ||
| 85 | + lambda: ( | ||
| 86 | + f"num_moe_expert only support in [1, 1024], but got {num_moe_expert=}." | ||
| 87 | + ), | ||
| 88 | + ) | ||
| 89 | + torch._check( | ||
| 90 | + ((topk >= 1) and (topk <= 16)), # topk当前仅支持[1,16] | ||
| 91 | + lambda: (f"topk only support in [1, 16], but got {topk=}."), | ||
| 92 | + ) | ||
| 93 | + torch._check( | ||
| 94 | + ( | ||
| 95 | + (num_shared_expert >= 0) and (num_shared_expert <= 4) | ||
| 96 | + ), # num_shared_expert当前仅支持[0,4] | ||
| 97 | + lambda: ( | ||
| 98 | + f"num_shared_expert only support in [0, 4], but got {num_shared_expert=}." | ||
| 99 | + ), | ||
| 100 | + ) | ||
| 101 | + torch._check( | ||
| 102 | + (world_size - num_shared_expert_ranks > 0), # 至少存在一张moe专家卡 | ||
| 103 | + lambda: ( | ||
| 104 | + f"world_size - num_shared_expert_ranks must be greater than 0, " | ||
| 105 | + f"but got {world_size=} {num_shared_expert_ranks=}." | ||
| 106 | + ), | ||
| 107 | + ) | ||
| 108 | + # local_moe_expert_num*world_size仅支持(0,2048] | ||
| 109 | + local_moe_expert_num = num_moe_expert // (world_size - num_shared_expert_ranks) | ||
| 110 | + torch._check( | ||
| 111 | + ( | ||
| 112 | + (local_moe_expert_num * world_size > 0) | ||
| 113 | + and (local_moe_expert_num * world_size <= 2048) | ||
| 114 | + ), | ||
| 115 | + lambda: ( | ||
| 116 | + f"local_moe_expert_num * world_size only support in (0, 2048], " | ||
| 117 | + f"but got {world_size=} {num_shared_expert_ranks=}, " | ||
| 118 | + f"local_moe_expert_num = num_moe_expert // (world_size - num_shared_expert_ranks), " | ||
| 119 | + f"{local_moe_expert_num=}" | ||
| 120 | + ), | ||
| 121 | + ) | ||
| 122 | + | ||
| 123 | + max_out_dtype_size = 2 # sizeof(int32) | ||
| 124 | + mb_conversion = 1024 * 1024 | ||
| 125 | + ub_align = 32 # 32B | ||
| 126 | + scale_expand_index_buffer = 44 # scale 32B + 3 * 4 expand_idx | ||
| 127 | + full_mesh_data_align = 480 | ||
| 128 | + win_addr_align = 512 | ||
| 129 | + | ||
| 130 | + comm_alg_support_list = ["fullmesh_v1", "fullmesh_v2", ""] | ||
| 131 | + torch._check( | ||
| 132 | + comm_alg in comm_alg_support_list, | ||
| 133 | + lambda: ( | ||
| 134 | + f"comm_alg only support {comm_alg_support_list=}, but got {comm_alg=}." | ||
| 135 | + ), | ||
| 136 | + ) | ||
| 137 | + | ||
| 138 | + token_actual_len = ( | ||
| 139 | + inline_align(hidden * max_out_dtype_size, ub_align) | ||
| 140 | + + scale_expand_index_buffer | ||
| 141 | + ) | ||
| 142 | + if comm_alg == "fullmesh_v2": | ||
| 143 | + token_need_size_dispatch = ( | ||
| 144 | + inline_align(token_actual_len, full_mesh_data_align) | ||
| 145 | + // full_mesh_data_align | ||
| 146 | + * win_addr_align | ||
| 147 | + ) | ||
| 148 | + else: | ||
| 149 | + token_need_size_dispatch = inline_align(token_actual_len, win_addr_align) | ||
| 150 | + token_need_size_combine = inline_align( | ||
| 151 | + hidden * max_out_dtype_size, win_addr_align | ||
| 152 | + ) | ||
| 153 | + minimum_buffer_size = ( | ||
| 154 | + 2 | ||
| 155 | + * ( | ||
| 156 | + ( | ||
| 157 | + num_max_dispatch_tokens_per_rank | ||
| 158 | + * token_need_size_dispatch | ||
| 159 | + * world_size | ||
| 160 | + * local_moe_expert_num | ||
| 161 | + ) | ||
| 162 | + + ( | ||
| 163 | + num_max_dispatch_tokens_per_rank | ||
| 164 | + * token_need_size_combine | ||
| 165 | + * (topk + num_shared_expert) | ||
| 166 | + ) | ||
| 167 | + ) | ||
| 168 | + + mb_conversion | ||
| 169 | + ) | ||
| 170 | + ## hccl按照2*bufferSize大小开设 | ||
| 171 | + ccl_buffer_size = ( | ||
| 172 | + inline_align( | ||
| 173 | + inline_align(minimum_buffer_size, mb_conversion) // mb_conversion, 2 | ||
| 174 | + ) | ||
| 175 | + // 2 | ||
| 176 | + ) | ||
| 177 | + return ccl_buffer_size | ||
| 178 | + | ||
| 179 | + def update_ctx(self, new_group) -> bool: | ||
| 180 | + self.group = new_group | ||
| 181 | + self.rank_id = torch.distributed.get_rank(new_group) | ||
| 182 | + self.group_name = _get_hccl_comm_name(new_group, self.rank_id) | ||
| 183 | + new_world_size = torch.distributed.get_world_size(new_group) | ||
| 184 | + torch._check( | ||
| 185 | + new_world_size == self.world_size, | ||
| 186 | + lambda: ( | ||
| 187 | + f"New world size should be the same as orginal world size, " | ||
| 188 | + f"but got {new_world_size=}, orginial={self.world_size}" | ||
| 189 | + f"{ops_error(ErrCode.VALUE)}." | ||
| 190 | + ), | ||
| 191 | + ) | ||
| 192 | + self._ctx_manager.update_group(self.group_name, self.context) | ||
| 193 | + self.ccl_buffer_size = self._ctx_manager.ccl_buffer_size | ||
| 194 | + return True | ||
| 195 | + | ||
| 196 | + def low_latency_dispatch( | ||
| 197 | + self, | ||
| 198 | + x, | ||
| 199 | + topk_idx, | ||
| 200 | + num_experts: int, | ||
| 201 | + *, | ||
| 202 | + quant_mode=0, | ||
| 203 | + comm_alg="", | ||
| 204 | + x_smooth_scale=None, | ||
| 205 | + x_active_mask=None, | ||
| 206 | + topk_weights=None, | ||
| 207 | + zero_expert_num=0, | ||
| 208 | + copy_expert_num=0, | ||
| 209 | + const_expert_num=0, | ||
| 210 | + elastic_info=None, | ||
| 211 | + expert_shard_type=0, | ||
| 212 | + shared_expert_num=1, | ||
| 213 | + shared_expert_rank_num=0, | ||
| 214 | + expert_token_nums_type=1, | ||
| 215 | + num_max_dispatch_tokens_per_rank=0, | ||
| 216 | + y_dtype=None, | ||
| 217 | + x_dtype=None, | ||
| 218 | + x_smooth_scales_dtype=None, | ||
| 219 | + ): | ||
| 220 | + ( | ||
| 221 | + expand_x, | ||
| 222 | + dynamic_scales, | ||
| 223 | + expand_idx, | ||
| 224 | + expert_token_nums, | ||
| 225 | + ep_recv_counts, | ||
| 226 | + tp_recv_counts, | ||
| 227 | + expand_scales, | ||
| 228 | + ) = torch.ops.cann_ops_transformer.npu_moe_distribute_dispatch( | ||
| 229 | + context=self.context, | ||
| 230 | + x=x, | ||
| 231 | + expert_ids=topk_idx, | ||
| 232 | + ep_world_size=self.world_size, | ||
| 233 | + ep_rank_id=self.rank_id, | ||
| 234 | + moe_expert_num=num_experts, | ||
| 235 | + ccl_buffer_size=self.ccl_buffer_size, | ||
| 236 | + scales=x_smooth_scale, | ||
| 237 | + x_active_mask=x_active_mask, | ||
| 238 | + expert_scales=topk_weights, | ||
| 239 | + elastic_info=elastic_info, | ||
| 240 | + performance_info=None, | ||
| 241 | + expert_shard_type=expert_shard_type, | ||
| 242 | + shared_expert_num=shared_expert_num, | ||
| 243 | + shared_expert_rank_num=shared_expert_rank_num, | ||
| 244 | + quant_mode=quant_mode, | ||
| 245 | + expert_token_nums_type=expert_token_nums_type, | ||
| 246 | + global_bs=num_max_dispatch_tokens_per_rank * self.world_size, | ||
| 247 | + comm_alg=comm_alg, | ||
| 248 | + zero_expert_num=zero_expert_num, | ||
| 249 | + copy_expert_num=copy_expert_num, | ||
| 250 | + const_expert_num=const_expert_num, | ||
| 251 | + y_dtype=y_dtype, | ||
| 252 | + x_dtype=x_dtype, | ||
| 253 | + x_smooth_scales_dtype=x_smooth_scales_dtype, | ||
| 254 | + ) | ||
| 255 | + return ( | ||
| 256 | + expand_x, | ||
| 257 | + dynamic_scales, | ||
| 258 | + expand_idx, | ||
| 259 | + expert_token_nums, | ||
| 260 | + ep_recv_counts, | ||
| 261 | + expand_scales, | ||
| 262 | + ) | ||
| 263 | + | ||
| 264 | + def low_latency_combine( | ||
| 265 | + self, | ||
| 266 | + x, | ||
| 267 | + topk_idx, | ||
| 268 | + topk_weights, | ||
| 269 | + assist_info_for_combine, | ||
| 270 | + ep_send_counts, | ||
| 271 | + *, | ||
| 272 | + num_experts=0, | ||
| 273 | + comm_alg="", | ||
| 274 | + comm_quant_mode=0, | ||
| 275 | + x_active_mask=None, | ||
| 276 | + expand_scales=None, | ||
| 277 | + shared_expert_x=None, | ||
| 278 | + elastic_info=None, | ||
| 279 | + ori_x=None, | ||
| 280 | + const_expert_alpha_1=None, | ||
| 281 | + const_expert_alpha_2=None, | ||
| 282 | + const_expert_v=None, | ||
| 283 | + zero_expert_num=0, | ||
| 284 | + copy_expert_num=0, | ||
| 285 | + const_expert_num=0, | ||
| 286 | + expert_shared_type=0, | ||
| 287 | + shared_expert_num=1, | ||
| 288 | + shared_expert_rank_num=0, | ||
| 289 | + num_max_dispatch_tokens_per_rank=0, | ||
| 290 | + ): | ||
| 291 | + if assist_info_for_combine is None: | ||
| 292 | + raise ValueError("assist_info_for_combine must be provided.") | ||
| 293 | + if ep_send_counts is None: | ||
| 294 | + raise ValueError("ep_send_counts must be provided.") | ||
| 295 | + topk_weights = ( | ||
| 296 | + _empty_topk_weights_like(x) if topk_weights is None else topk_weights | ||
| 297 | + ) | ||
| 298 | + return torch.ops.cann_ops_transformer.npu_moe_distribute_combine( | ||
| 299 | + context=self.context, | ||
| 300 | + expand_x=x, | ||
| 301 | + expert_ids=topk_idx, | ||
| 302 | + assist_info_for_combine=assist_info_for_combine, | ||
| 303 | + ep_send_counts=ep_send_counts, | ||
| 304 | + expert_scales=topk_weights, | ||
| 305 | + ep_world_size=self.world_size, | ||
| 306 | + ep_rank_id=self.rank_id, | ||
| 307 | + moe_expert_num=num_experts, | ||
| 308 | + ccl_buffer_size=self.ccl_buffer_size, | ||
| 309 | + tp_send_counts=None, | ||
| 310 | + x_active_mask=x_active_mask, | ||
| 311 | + expand_scales=expand_scales, | ||
| 312 | + shared_expert_x=shared_expert_x, | ||
| 313 | + elastic_info=elastic_info, | ||
| 314 | + ori_x=ori_x, | ||
| 315 | + const_expert_alpha_1=const_expert_alpha_1, | ||
| 316 | + const_expert_alpha_2=const_expert_alpha_2, | ||
| 317 | + const_expert_v=const_expert_v, | ||
| 318 | + performance_info=None, | ||
| 319 | + expert_shard_type=expert_shared_type, | ||
| 320 | + shared_expert_num=shared_expert_num, | ||
| 321 | + shared_expert_rank_num=shared_expert_rank_num, | ||
| 322 | + copy_expert_num=copy_expert_num, | ||
| 323 | + zero_expert_num=zero_expert_num, | ||
| 324 | + const_expert_num=const_expert_num, | ||
| 325 | + comm_alg=comm_alg, | ||
| 326 | + comm_quant_mode=comm_quant_mode, | ||
| 327 | + global_bs=num_max_dispatch_tokens_per_rank * self.world_size, | ||
| 328 | + ) | ||
| @@ -0,0 +1,4 @@ | |||
| 1 | +__all__ = ["mega_moe", "get_symm_buffer_for_mega_moe"] | ||
| 2 | + | ||
| 3 | +from .mega_moe import mega_moe, get_symm_buffer_for_mega_moe | ||
| 4 | +from . import graph_convert_mega_moe | ||
Rtorch_extension/cann_ops_transformer/ops/csrc/mega_moe.cpp→mc2/mega_moe/torch_extension/csrc/mega_moe.cpp+20-24
| @@ -16,29 +16,28 @@ namespace op_api { | |||
| 16 | using npu_utils = at_npu::native::NpuUtils; | 16 | using npu_utils = at_npu::native::NpuUtils; |
| 17 | const int DIM_TWO = 2; | 17 | const int DIM_TWO = 2; |
| 18 | 18 | ||
| 19 | -std::tuple<at::Tensor, at::Tensor> | 19 | +std::tuple<at::Tensor, at::Tensor> NpuMegaMoe( |
| 20 | -NpuMegaMoe(const at::Tensor &context, const at::Tensor &x, const at::Tensor &topkIds, const at::Tensor &topkWeights, | 20 | + const at::Tensor &context, const at::Tensor &x, const at::Tensor &topkIds, const at::Tensor &topkWeights, |
| 21 | - const std::vector<at::Tensor> &weight1, const std::vector<at::Tensor> &weight2, int64_t moeExpertNum, | 21 | + const std::vector<at::Tensor> &weight1, const std::vector<at::Tensor> &weight2, int64_t moeExpertNum, |
| 22 | - int64_t epWorldSize, int64_t cclBufferSize, const c10::optional<std::vector<at::Tensor>> &weightScales1, | 22 | + int64_t epWorldSize, int64_t cclBufferSize, const c10::optional<std::vector<at::Tensor>> &weightScales1, |
| 23 | - const c10::optional<std::vector<at::Tensor>> &weightScales2, | 23 | + const c10::optional<std::vector<at::Tensor>> &weightScales2, const c10::optional<std::vector<at::Tensor>> &bias1, |
| 24 | - const c10::optional<std::vector<at::Tensor>> &bias1, const c10::optional<std::vector<at::Tensor>> &bias2, | 24 | + const c10::optional<std::vector<at::Tensor>> &bias2, const c10::optional<at::Tensor> &xActiveMask, |
| 25 | - const c10::optional<at::Tensor> &xActiveMask, const c10::optional<std::vector<at::Tensor>> &sharedWeight1, | 25 | + const c10::optional<std::vector<at::Tensor>> &sharedWeight1, |
| 26 | - const c10::optional<std::vector<at::Tensor>> &sharedWeight2, | 26 | + const c10::optional<std::vector<at::Tensor>> &sharedWeight2, |
| 27 | - const c10::optional<std::vector<at::Tensor>> &sharedWeightScales1, | 27 | + const c10::optional<std::vector<at::Tensor>> &sharedWeightScales1, |
| 28 | - const c10::optional<std::vector<at::Tensor>> &sharedWeightScales2, | 28 | + const c10::optional<std::vector<at::Tensor>> &sharedWeightScales2, |
| 29 | - const c10::optional<std::vector<at::Tensor>> &sharedBias1, | 29 | + const c10::optional<std::vector<at::Tensor>> &sharedBias1, |
| 30 | - const c10::optional<std::vector<at::Tensor>> &sharedBias2, int64_t maxRecvTokenNum, | 30 | + const c10::optional<std::vector<at::Tensor>> &sharedBias2, int64_t maxRecvTokenNum, int64_t dispatchQuantMode, |
| 31 | - int64_t dispatchQuantMode, int64_t combineQuantMode, std::string commAlg, int64_t numMaxTokensPerRank, | 31 | + int64_t combineQuantMode, std::string commAlg, int64_t numMaxTokensPerRank, std::string activation, |
| 32 | - std::string activation, std::vector<float> activationParams, | 32 | + std::vector<float> activationParams, c10::optional<int64_t> dispatchQuantOutDtype, |
| 33 | - c10::optional<int64_t> dispatchQuantOutDtype, c10::optional<int64_t> weight1Type, | 33 | + c10::optional<int64_t> weight1Type, c10::optional<int64_t> weight2Type, c10::optional<int64_t> topoType, |
| 34 | - c10::optional<int64_t> weight2Type, c10::optional<int64_t> topoType, c10::optional<int64_t> rankNumPerServer, | 34 | + c10::optional<int64_t> rankNumPerServer, int64_t topkWeightsType) |
| 35 | - int64_t topkWeightsType) | ||
| 36 | { | 35 | { |
| 37 | TORCH_CHECK((epWorldSize > 0), "The ep_world_sizes should be greater than 0, current is: ", epWorldSize); | 36 | TORCH_CHECK((epWorldSize > 0), "The ep_world_sizes should be greater than 0, current is: ", epWorldSize); |
| 38 | TORCH_CHECK((x.dim() == DIM_TWO) && (topkIds.dim() == DIM_TWO), "The x and topk_ids should be 2D"); | 37 | TORCH_CHECK((x.dim() == DIM_TWO) && (topkIds.dim() == DIM_TWO), "The x and topk_ids should be 2D"); |
| 39 | - TORCH_CHECK(((x.scalar_type() == at::kBFloat16) || (x.scalar_type() == at::kHalf)) && | 38 | + TORCH_CHECK( |
| 40 | - (topkIds.scalar_type() == at::kInt), | 39 | + ((x.scalar_type() == at::kBFloat16) || (x.scalar_type() == at::kHalf)) && (topkIds.scalar_type() == at::kInt), |
| 41 | - "dtype of x should be bfloat16, float16, dtype of topk_ids should be int."); | 40 | + "dtype of x should be bfloat16, float16, dtype of topk_ids should be int."); |
| 42 | 41 | ||
| 43 | at::TensorList weight1Ref = weight1; | 42 | at::TensorList weight1Ref = weight1; |
| 44 | at::TensorList weight2Ref = weight2; | 43 | at::TensorList weight2Ref = weight2; |
| @@ -143,10 +142,7 @@ constexpr int64_t RESERVED_SPACE_SIZE = 10LL * 1024 * 1024; | |||
| 143 | constexpr int64_t MAX_EXPERTS_PER_RANK_A2A3 = 128LL; | 142 | constexpr int64_t MAX_EXPERTS_PER_RANK_A2A3 = 128LL; |
| 144 | constexpr int64_t SYNC_STATE_RESERVED_SIZE = 512LL * 1024; | 143 | constexpr int64_t SYNC_STATE_RESERVED_SIZE = 512LL * 1024; |
| 145 | 144 | ||
| 146 | -int64_t CeilAlign(int64_t val, int64_t align) | 145 | +int64_t CeilAlign(int64_t val, int64_t align) { return (val + align - 1) / align * align; } |
| 147 | -{ | ||
| 148 | - return (val + align - 1) / align * align; | ||
| 149 | -} | ||
| 150 | 146 | ||
| 151 | // A2 minimum buffer size (MB). | 147 | // A2 minimum buffer size (MB). |
| 152 | // Matches tiling_arch22.cpp CalcLeastCclBufferSize with isA3=false. | 148 | // Matches tiling_arch22.cpp CalcLeastCclBufferSize with isA3=false. |
Rtorch_extension/cann_ops_transformer/ops/graph_convert/graph_convert_mega_moe.py→mc2/mega_moe/torch_extension/graph_convert_mega_moe.py+1-1
| @@ -41,7 +41,7 @@ try: | |||
| 41 | except ImportError: | 41 | except ImportError: |
| 42 | _TORCHAIR_AVAILABLE = False | 42 | _TORCHAIR_AVAILABLE = False |
| 43 | 43 | ||
| 44 | -from cann_ops_transformer.ops.mega_moe import _normalize_activation_params | 44 | +from .mega_moe import _normalize_activation_params |
| 45 | 45 | ||
| 46 | if _TORCHAIR_AVAILABLE: | 46 | if _TORCHAIR_AVAILABLE: |
| 47 | 47 | ||
| @@ -12,9 +12,8 @@ from typing import Dict, List, Optional | |||
| 12 | import torch | 12 | import torch |
| 13 | from torch.library import impl | 13 | from torch.library import impl |
| 14 | from torch_npu.utils._error_code import ErrCode, ops_error | 14 | from torch_npu.utils._error_code import ErrCode, ops_error |
| 15 | -from cann_ops_transformer.op_builder.builder import OpBuilder | 15 | +from cann_ops_transformer.op_builder import OpBuilder, get_as_library |
| 16 | -from cann_ops_transformer.op_builder.builder import AS_LIBRARY | 16 | +from ..common import CommContextManager |
| 17 | -from .comm_context import CommContextManager | ||
| 18 | 17 | ||
| 19 | 18 | ||
| 20 | _CLAMP_DEFAULT = 3.4028234663852886e38 | 19 | _CLAMP_DEFAULT = 3.4028234663852886e38 |
| @@ -68,10 +67,10 @@ def _normalize_activation_params( | |||
| 68 | 67 | ||
| 69 | class _MegaMoeOpBuilder(OpBuilder): | 68 | class _MegaMoeOpBuilder(OpBuilder): |
| 70 | def __init__(self): | 69 | def __init__(self): |
| 71 | - super(_MegaMoeOpBuilder, self).__init__("npu_mega_moe") | 70 | + super(_MegaMoeOpBuilder, self).__init__("npu_mega_moe", category="mc2") |
| 72 | 71 | ||
| 73 | def sources(self): | 72 | def sources(self): |
| 74 | - return ["ops/csrc/mega_moe.cpp"] | 73 | + return ["csrc/mc2/mega_moe.cpp"] |
| 75 | 74 | ||
| 76 | def schema(self) -> str: | 75 | def schema(self) -> str: |
| 77 | return ( | 76 | return ( |
| @@ -93,7 +92,7 @@ class _MegaMoeOpBuilder(OpBuilder): | |||
| 93 | ) | 92 | ) |
| 94 | 93 | ||
| 95 | def register_meta(self): | 94 | def register_meta(self): |
| 96 | - @impl(AS_LIBRARY, self.name, "Meta") | 95 | + @impl(get_as_library(), self.name, "Meta") |
| 97 | def npu_mega_moe_meta( | 96 | def npu_mega_moe_meta( |
| 98 | context, | 97 | context, |
| 99 | x, | 98 | x, |
| @@ -143,9 +142,10 @@ class _MegaMoeOpBuilder(OpBuilder): | |||
| 143 | 142 | ||
| 144 | 143 | ||
| 145 | _mega_moe_op_builder = _MegaMoeOpBuilder() | 144 | _mega_moe_op_builder = _MegaMoeOpBuilder() |
| 145 | +_mega_moe_op_builder._ensure_initialized() | ||
| 146 | 146 | ||
| 147 | 147 | ||
| 148 | -@impl(AS_LIBRARY, _mega_moe_op_builder.name, "PrivateUse1") | 148 | +@impl(get_as_library(), _mega_moe_op_builder.name, "PrivateUse1") |
| 149 | def _npu_mega_moe( | 149 | def _npu_mega_moe( |
| 150 | context, | 150 | context, |
| 151 | x, | 151 | x, |
| @@ -0,0 +1,6 @@ | |||
| 1 | +__all__ = ["moe_distribute_combine"] | ||
| 2 | + | ||
| 3 | +from .moe_distribute_combine import ( | ||
| 4 | + moe_distribute_combine_op_builder as moe_distribute_combine, | ||
| 5 | +) | ||
| 6 | +from . import graph_convert_moe_distribute_combine | ||
Rtorch_extension/cann_ops_transformer/ops/csrc/moe_distribute_combine.cpp→mc2/moe_distribute_combine/torch_extension/csrc/moe_distribute_combine.cpp+12-13
| @@ -24,19 +24,18 @@ const int DIM_TWO = 2; | |||
| 24 | /** | 24 | /** |
| 25 | * @brief Warpper for moe_distribute_combine | 25 | * @brief Warpper for moe_distribute_combine |
| 26 | */ | 26 | */ |
| 27 | -at::Tensor | 27 | +at::Tensor NpuMoeDistributeCombine( |
| 28 | -NpuMoeDistributeCombine(const at::Tensor &context, const at::Tensor &expandX, const at::Tensor &expertIds, | 28 | + const at::Tensor &context, const at::Tensor &expandX, const at::Tensor &expertIds, |
| 29 | - const at::Tensor &assistInfoForCombine, const at::Tensor &epSendCounts, | 29 | + const at::Tensor &assistInfoForCombine, const at::Tensor &epSendCounts, const at::Tensor &expertScales, |
| 30 | - const at::Tensor &expertScales, int64_t epWorldSize, int64_t epRankId, int64_t moeExpertNum, | 30 | + int64_t epWorldSize, int64_t epRankId, int64_t moeExpertNum, int64_t cclBufferSize, |
| 31 | - int64_t cclBufferSize, const c10::optional<at::Tensor> &tpSendCounts, | 31 | + const c10::optional<at::Tensor> &tpSendCounts, const c10::optional<at::Tensor> &xActiveMask, |
| 32 | - const c10::optional<at::Tensor> &xActiveMask, const c10::optional<at::Tensor> &expandScales, | 32 | + const c10::optional<at::Tensor> &expandScales, const c10::optional<at::Tensor> &sharedExpertX, |
| 33 | - const c10::optional<at::Tensor> &sharedExpertX, const c10::optional<at::Tensor> &elasticInfo, | 33 | + const c10::optional<at::Tensor> &elasticInfo, const c10::optional<at::Tensor> &oriX, |
| 34 | - const c10::optional<at::Tensor> &oriX, const c10::optional<at::Tensor> &constExpertAlpha1, | 34 | + const c10::optional<at::Tensor> &constExpertAlpha1, const c10::optional<at::Tensor> &constExpertAlpha2, |
| 35 | - const c10::optional<at::Tensor> &constExpertAlpha2, | 35 | + const c10::optional<at::Tensor> &constExpertV, const c10::optional<at::Tensor> &performanceInfo, |
| 36 | - const c10::optional<at::Tensor> &constExpertV, const c10::optional<at::Tensor> &performanceInfo, | 36 | + int64_t tpWorldSize, int64_t tpRankId, int64_t expertShardType, int64_t sharedExpertNum, |
| 37 | - int64_t tpWorldSize, int64_t tpRankId, int64_t expertShardType, int64_t sharedExpertNum, | 37 | + int64_t sharedExpertRankNum, int64_t globalBs, int64_t commQuantMode, std::string commAlg, int64_t zeroExpertNum, |
| 38 | - int64_t sharedExpertRankNum, int64_t globalBs, int64_t commQuantMode, std::string commAlg, | 38 | + int64_t copyExpertNum, int64_t constExpertNum) |
| 39 | - int64_t zeroExpertNum, int64_t copyExpertNum, int64_t constExpertNum) | ||
| 40 | { | 39 | { |
| 41 | TORCH_CHECK((expandX.dim() == DIM_TWO) && (expertIds.dim() == DIM_TWO), "The x and expert_ids should be 2D"); | 40 | TORCH_CHECK((expandX.dim() == DIM_TWO) && (expertIds.dim() == DIM_TWO), "The x and expert_ids should be 2D"); |
| 42 | TORCH_CHECK((expandX.scalar_type() == at::kBFloat16) || (expandX.scalar_type() == at::kHalf) || | 41 | TORCH_CHECK((expandX.scalar_type() == at::kBFloat16) || (expandX.scalar_type() == at::kHalf) || |
Rtorch_extension/cann_ops_transformer/ops/graph_convert/graph_convert_moe_distribute_combine.py→mc2/moe_distribute_combine/torch_extension/graph_convert_moe_distribute_combine.py+0-0
File renamed without changes.
Rtorch_extension/cann_ops_transformer/ops/csrc/moe_distribute_dispatch.cpp→mc2/moe_distribute_dispatch/torch_extension/csrc/moe_distribute_dispatch.cpp+14-17
Rtorch_extension/cann_ops_transformer/ops/graph_convert/graph_convert_moe_distribute_dispatch.py→mc2/moe_distribute_dispatch/torch_extension/graph_convert_moe_distribute_dispatch.py+79-52
Rtorch_extension/cann_ops_transformer/ops/deep_ep.py→mc2/moe_distribute_dispatch/torch_extension/moe_distribute_dispatch.py+111-405
Rtorch_extension/cann_ops_transformer/ops/csrc/mhc_post.cpp→mhc/mhc_post/torch_extension/csrc/mhc_post.cpp+1-4
Rtorch_extension/cann_ops_transformer/ops/csrc/mhc_post_backward.cpp→mhc/mhc_post_backward/torch_extension/csrc/mhc_post_backward.cpp+1-4
Rtorch_extension/cann_ops_transformer/ops/mhc_post_backward.py→mhc/mhc_post_backward/torch_extension/mhc_post_backward.py+8-6
Rtorch_extension/cann_ops_transformer/ops/csrc/mhc_pre_sinkhorn.cpp→mhc/mhc_pre_sinkhorn/torch_extension/csrc/mhc_pre_sinkhorn.cpp+1-4
Rtorch_extension/cann_ops_transformer/ops/graph_convert/graph_convert_mhc_pre_sinkhorn.py→mhc/mhc_pre_sinkhorn/torch_extension/graph_convert_mhc_pre_sinkhorn.py+63-36
Rtorch_extension/cann_ops_transformer/ops/mhc_pre_sinkhorn.py→mhc/mhc_pre_sinkhorn/torch_extension/mhc_pre_sinkhorn.py+9-7
Rtorch_extension/cann_ops_transformer/ops/csrc/mhc_pre_sinkhorn_backward.cpp→mhc/mhc_pre_sinkhorn_backward/torch_extension/csrc/mhc_pre_sinkhorn_backward.cpp+5-5
Rtorch_extension/cann_ops_transformer/ops/graph_convert/graph_convert_mhc_pre_sinkhorn_backward.py→mhc/mhc_pre_sinkhorn_backward/torch_extension/graph_convert_mhc_pre_sinkhorn_backward.py+100-43
Rtorch_extension/cann_ops_transformer/ops/mhc_pre_sinkhorn_backward.py→mhc/mhc_pre_sinkhorn_backward/torch_extension/mhc_pre_sinkhorn_backward.py+6-6
Rtorch_extension/cann_ops_transformer/ops/csrc/moe_finalize_routing.cpp→moe/moe_finalize_routing_v2/torch_extension/csrc/moe_finalize_routing.cpp+10-17
Rtorch_extension/cann_ops_transformer/ops/graph_convert/graph_convert_moe_finalize_routing.py→moe/moe_finalize_routing_v2/torch_extension/graph_convert_moe_finalize_routing.py+0-0
Rtorch_extension/cann_ops_transformer/ops/moe_finalize_routing.py→moe/moe_finalize_routing_v2/torch_extension/moe_finalize_routing.py+9-6
Rtorch_extension/cann_ops_transformer/ops/csrc/moe_init_routing.cpp→moe/moe_init_routing_v4/torch_extension/csrc/moe_init_routing.cpp+38-64
Rtorch_extension/cann_ops_transformer/ops/graph_convert/graph_convert_moe_init_routing.py→moe/moe_init_routing_v4/torch_extension/graph_convert_moe_init_routing.py+67-36
Rtorch_extension/cann_ops_transformer/ops/moe_init_routing.py→moe/moe_init_routing_v4/torch_extension/moe_init_routing.py+53-106
Rtorch_extension/cann_ops_transformer/ops/csrc/moe_re_routing.cpp→moe/moe_re_routing_v2/torch_extension/csrc/moe_re_routing.cpp+16-26
Rtorch_extension/cann_ops_transformer/ops/graph_convert/graph_convert_moe_re_routing.py→moe/moe_re_routing_v2/torch_extension/graph_convert_moe_re_routing.py+78-32
Rtorch_extension/cann_ops_transformer/ops/moe_re_routing.py→moe/moe_re_routing_v2/torch_extension/moe_re_routing.py+14-22
Rtorch_extension/cann_ops_transformer/ops/csrc/moe_token_permute.cpp→moe/moe_token_permute/torch_extension/csrc/moe_token_permute.cpp+3-12
Rtorch_extension/cann_ops_transformer/ops/moe_token_permute.py→moe/moe_token_permute/torch_extension/moe_token_permute.py+8-6
Rtorch_extension/cann_ops_transformer/ops/csrc/inplace_partial_rotary_mul.cpp→posembedding/inplace_partial_rotary_mul/torch_extension/csrc/inplace_partial_rotary_mul.cpp+0-0
Rtorch_extension/cann_ops_transformer/ops/graph_convert/graph_convert_inplace_partial_rotary_mul.py→posembedding/inplace_partial_rotary_mul/torch_extension/graph_convert_inplace_partial_rotary_mul.py+0-0
Rtorch_extension/cann_ops_transformer/ops/inplace_partial_rotary_mul.py→posembedding/inplace_partial_rotary_mul/torch_extension/inplace_partial_rotary_mul.py+10-6
Rtorch_extension/cann_ops_transformer/ops/csrc/inplace_partial_rotary_mul_backward.cpp→posembedding/inplace_partial_rotary_mul_grad/torch_extension/csrc/inplace_partial_rotary_mul_backward.cpp+0-0
Rtorch_extension/cann_ops_transformer/ops/graph_convert/graph_convert_inplace_partial_rotary_mul_backward.py→posembedding/inplace_partial_rotary_mul_grad/torch_extension/graph_convert_inplace_partial_rotary_mul_backward.py+0-0
Rtorch_extension/cann_ops_transformer/ops/inplace_partial_rotary_mul_backward.py→posembedding/inplace_partial_rotary_mul_grad/torch_extension/inplace_partial_rotary_mul_backward.py+13-6
Rtorch_extension/cann_ops_transformer/ops/csrc/qkv_rms_norm_rope_cache_with_k_scale.cpp→posembedding/qkv_rms_norm_rope_cache_with_k_scale/torch_extension/csrc/qkv_rms_norm_rope_cache_with_k_scale.cpp+0-0
Rtorch_extension/cann_ops_transformer/ops/qkv_rms_norm_rope_cache_with_k_scale.py→posembedding/qkv_rms_norm_rope_cache_with_k_scale/torch_extension/qkv_rms_norm_rope_cache_with_k_scale.py+7-7
Rtorch_extension/cann_ops_transformer/ops/csrc/und_gen_qkv_rms_norm_rope_cache.cpp→posembedding/und_gen_qkv_rms_norm_rope_cache/torch_extension/csrc/und_gen_qkv_rms_norm_rope_cache.cpp+6-8
Rtorch_extension/cann_ops_transformer/ops/graph_convert/graph_convert_und_gen_qkv_rms_norm_rope_cache.py→posembedding/und_gen_qkv_rms_norm_rope_cache/torch_extension/graph_convert_und_gen_qkv_rms_norm_rope_cache.py+0-0
Rtorch_extension/cann_ops_transformer/ops/und_gen_qkv_rms_norm_rope_cache.py→posembedding/und_gen_qkv_rms_norm_rope_cache/torch_extension/und_gen_qkv_rms_norm_rope_cache.py+8-6
Rtorch_extension/cann_ops_transformer/common/inc/aclnn_common.h→torch_extension/cann_ops_transformer/common/aclnn_common.h+0-0
Rtorch_extension/cann_ops_transformer/common/inc/hccl_common.h→torch_extension/cann_ops_transformer/common/hccl_common.h+2-8
Rtorch_extension/cann_ops_transformer/ops/graph_convert/__init__.py→torch_extension/cann_ops_transformer/op_builder/__init__.py+2-5