Merged
feat(mla): 接入 PR436 最新 DSL 实现与 Torch 适配 #16332
liqingsong16Add on 10 days ago
feat(mla): 接入 PR436 最新 DSL 实现与 Torch 适配 #16332
Merged
Total: 10 files changed+27526-0
| @@ -0,0 +1,14 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +add_op_to_compiled_list() | ||
| 10 | + | ||
| 11 | + | ||
| 12 | +if(BUILD_OPEN_PROJECT) | ||
| 13 | + enable_cannbotdsl_kernel(mla_prolog_v4 "${CMAKE_CURRENT_LIST_DIR}") | ||
| 14 | +endif() | ||
| @@ -0,0 +1,14 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +from .mla_prolog_v2 import mla_prolog_v2 | ||
| 10 | + | ||
| 11 | +# The repository wheel discovery key is the operator directory name. | ||
| 12 | +mla_prolog_v4 = mla_prolog_v2 | ||
| 13 | + | ||
| 14 | +__all__ = ["mla_prolog_v2"] | ||
| @@ -0,0 +1,219 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +from enum import Enum | ||
| 10 | +from typing import Optional, Tuple | ||
| 11 | + | ||
| 12 | +import torch | ||
| 13 | +from torch.library import impl | ||
| 14 | + | ||
| 15 | +from cann_ops_transformer.op_builder import get_as_library | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +class CacheMode(Enum): | ||
| 19 | + PA_BSND = 0 | ||
| 20 | + PA_NZ = 1 | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +class QkvQuantMode(Enum): | ||
| 24 | + A16C16 = 0 | ||
| 25 | + A16C8_KV_NOPE_FP8_E4M3_PER_TOKEN_GROUP_GROUP_SIZE_128_ROPE_BF16_SCALE_FLOAT_KV_CACHE_LAYOUT_N_NOPE_ROPE_SCALE = 1 | ||
| 26 | + A8C8_Q_FP8_E4M3_PER_TOKEN_HEAD_KV_FP8_E4M3_PER_TENSOR = 2 | ||
| 27 | + A8C8_QKV_HIFLOAT8_PER_TENSOR = 3 | ||
| 28 | + | ||
| 29 | + | ||
| 30 | +class RopeMode(Enum): | ||
| 31 | + NO_ROPE = 0 | ||
| 32 | + ROPE_INTERLEAVE_HALF = 1 | ||
| 33 | + ROPE_HALF = 2 | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +_QKV_QUANT_MODE_VALUES = tuple((_m.value for _m in QkvQuantMode)) | ||
| 37 | +_CACHE_MODE_VALUES = tuple((_m.value for _m in CacheMode)) | ||
| 38 | +_ROPE_MODE_VALUES = tuple((_m.value for _m in RopeMode)) | ||
| 39 | + | ||
| 40 | + | ||
| 41 | +def _validate_mode_enums(qkv_quant_mode, cache_mode, rope_mode): | ||
| 42 | + for name, value, enum_type in ( | ||
| 43 | + ("qkv_quant_mode", qkv_quant_mode, QkvQuantMode), | ||
| 44 | + ("cache_mode", cache_mode, CacheMode), | ||
| 45 | + ("rope_mode", rope_mode, RopeMode), | ||
| 46 | + ): | ||
| 47 | + if type(value) is not enum_type: | ||
| 48 | + raise TypeError(f"{name} must be a {enum_type.__name__} enum") | ||
| 49 | + | ||
| 50 | + | ||
| 51 | +def _validate_scalar_types(norm_eps, qr_scale, kvr_scale): | ||
| 52 | + for name, value in ( | ||
| 53 | + ("norm_eps", norm_eps), | ||
| 54 | + ("qr_scale", qr_scale), | ||
| 55 | + ("kvr_scale", kvr_scale), | ||
| 56 | + ): | ||
| 57 | + if isinstance(value, bool) or not isinstance(value, (int, float)): | ||
| 58 | + raise TypeError(f"{name} must be a finite float") | ||
| 59 | + | ||
| 60 | + | ||
| 61 | +_TORCH_SCHEMA = "mla_prolog_v2(Tensor x, Tensor wqa, Tensor wqb, Tensor wkva, Tensor wkb, Tensor norm_weight_qa, Tensor norm_weight_kva, Tensor(a!) kv_cache, Tensor cache_index, int qkv_quant_mode, *, Tensor? quant_scale_kv=None, Tensor? rope_sin=None, Tensor? rope_cos=None, float norm_eps=1e-5, int cache_mode=0, float qr_scale=1.0, float kvr_scale=1.0, int rope_mode=1, bool return_qr=False) -> (Tensor, Tensor, Tensor)" | ||
| 62 | + | ||
| 63 | + | ||
| 64 | +def _validate_schema_modes(qkv_quant_mode, cache_mode, rope_mode): | ||
| 65 | + for name, value, allowed in ( | ||
| 66 | + ("qkv_quant_mode", qkv_quant_mode, _QKV_QUANT_MODE_VALUES), | ||
| 67 | + ("cache_mode", cache_mode, _CACHE_MODE_VALUES), | ||
| 68 | + ("rope_mode", rope_mode, _ROPE_MODE_VALUES), | ||
| 69 | + ): | ||
| 70 | + if type(value) is not int: | ||
| 71 | + raise TypeError(f"{name} schema value must be int") | ||
| 72 | + if value not in allowed: | ||
| 73 | + raise ValueError(f"{name} has unsupported schema value {value}") | ||
| 74 | + | ||
| 75 | + | ||
| 76 | +def mla_prolog_v2_fake( | ||
| 77 | + x: torch.Tensor, | ||
| 78 | + wqa: torch.Tensor, | ||
| 79 | + wqb: torch.Tensor, | ||
| 80 | + wkva: torch.Tensor, | ||
| 81 | + wkb: torch.Tensor, | ||
| 82 | + norm_weight_qa: torch.Tensor, | ||
| 83 | + norm_weight_kva: torch.Tensor, | ||
| 84 | + kv_cache: torch.Tensor, | ||
| 85 | + cache_index: torch.Tensor, | ||
| 86 | + qkv_quant_mode: int, | ||
| 87 | + *, | ||
| 88 | + quant_scale_kv: Optional[torch.Tensor] = None, | ||
| 89 | + rope_sin: Optional[torch.Tensor] = None, | ||
| 90 | + rope_cos: Optional[torch.Tensor] = None, | ||
| 91 | + norm_eps: float = 1e-05, | ||
| 92 | + cache_mode: int = 0, | ||
| 93 | + qr_scale: float = 1.0, | ||
| 94 | + kvr_scale: float = 1.0, | ||
| 95 | + rope_mode: int = 1, | ||
| 96 | + return_qr: bool = False, | ||
| 97 | +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: | ||
| 98 | + """Describe fixed output slots without reading device data or launching DSL.""" | ||
| 99 | + _validate_schema_modes(qkv_quant_mode, cache_mode, rope_mode) | ||
| 100 | + (t, heads, dr) = (x.shape[0], wkb.shape[0], 0 if wkb.shape[1] == 256 else 64) | ||
| 101 | + q_dtype = ( | ||
| 102 | + torch.bfloat16 | ||
| 103 | + if qkv_quant_mode < 2 | ||
| 104 | + else torch.float8_e4m3fn | ||
| 105 | + if qkv_quant_mode == 2 | ||
| 106 | + else torch.uint8 | ||
| 107 | + ) | ||
| 108 | + scale_shape = ( | ||
| 109 | + (0,) | ||
| 110 | + if qkv_quant_mode < 2 or (t == 0 and qkv_quant_mode == 3) | ||
| 111 | + else (t, heads, 1) | ||
| 112 | + if qkv_quant_mode == 2 | ||
| 113 | + else (1,) | ||
| 114 | + ) | ||
| 115 | + return ( | ||
| 116 | + x.new_empty((t, heads, 512 + dr), dtype=q_dtype), | ||
| 117 | + x.new_empty(scale_shape, dtype=torch.float32), | ||
| 118 | + x.new_empty( | ||
| 119 | + (t, norm_weight_qa.shape[0]) if return_qr else (0,), dtype=torch.bfloat16 | ||
| 120 | + ), | ||
| 121 | + ) | ||
| 122 | + | ||
| 123 | + | ||
| 124 | +def mla_prolog_v2( | ||
| 125 | + x: torch.Tensor, | ||
| 126 | + wqa: torch.Tensor, | ||
| 127 | + wqb: torch.Tensor, | ||
| 128 | + wkva: torch.Tensor, | ||
| 129 | + wkb: torch.Tensor, | ||
| 130 | + norm_weight_qa: torch.Tensor, | ||
| 131 | + norm_weight_kva: torch.Tensor, | ||
| 132 | + kv_cache: torch.Tensor, | ||
| 133 | + cache_index: torch.Tensor, | ||
| 134 | + qkv_quant_mode: QkvQuantMode, | ||
| 135 | + *, | ||
| 136 | + quant_scale_kv: Optional[torch.Tensor] = None, | ||
| 137 | + rope_sin: Optional[torch.Tensor] = None, | ||
| 138 | + rope_cos: Optional[torch.Tensor] = None, | ||
| 139 | + norm_eps: float = 1e-05, | ||
| 140 | + cache_mode: CacheMode = CacheMode.PA_BSND, | ||
| 141 | + qr_scale: float = 1.0, | ||
| 142 | + kvr_scale: float = 1.0, | ||
| 143 | + rope_mode: RopeMode = RopeMode.ROPE_INTERLEAVE_HALF, | ||
| 144 | + return_qr: bool = False, | ||
| 145 | +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: | ||
| 146 | + """Project BF16 MLA inputs, apply RMSNorm/RoPE and update ``kv_cache``. | ||
| 147 | + | ||
| 148 | + ``x`` has shape ``(T, dim)``; weights use the selected ND/NZ layout. | ||
| 149 | + ``norm_weight_qa`` and ``norm_weight_kva`` are FP32 | ||
| 150 | + RMSNorm weights; ``cache_index`` selects the slots updated in ``kv_cache``. | ||
| 151 | + Optional quantization scale and RoPE tensors are keyword arguments. | ||
| 152 | + Mode attributes use the enums attached to this function. ``norm_eps``, | ||
| 153 | + ``qr_scale`` and ``kvr_scale`` control normalization and output scaling. | ||
| 154 | + | ||
| 155 | + Returns ``(q, descale_q, qr)``. ``return_qr`` controls whether ``qr`` is empty. | ||
| 156 | + Cache is updated in place and is not included in the return values. | ||
| 157 | + """ | ||
| 158 | + _validate_mode_enums(qkv_quant_mode, cache_mode, rope_mode) | ||
| 159 | + if type(return_qr) is not bool: | ||
| 160 | + raise TypeError("return_qr must be bool") | ||
| 161 | + _validate_scalar_types(norm_eps, qr_scale, kvr_scale) | ||
| 162 | + dispatch = ( | ||
| 163 | + torch.ops.cann_ops_transformer._mla_prolog_v2_graph.default | ||
| 164 | + if torch.compiler.is_compiling() | ||
| 165 | + or ( | ||
| 166 | + isinstance(x, torch.Tensor) | ||
| 167 | + and x.device.type in ("npu", "privateuseone") | ||
| 168 | + and torch.npu.is_current_stream_capturing() | ||
| 169 | + ) | ||
| 170 | + else torch.ops.cann_ops_transformer.mla_prolog_v2.default | ||
| 171 | + ) | ||
| 172 | + return dispatch( | ||
| 173 | + x, | ||
| 174 | + wqa, | ||
| 175 | + wqb, | ||
| 176 | + wkva, | ||
| 177 | + wkb, | ||
| 178 | + norm_weight_qa, | ||
| 179 | + norm_weight_kva, | ||
| 180 | + kv_cache, | ||
| 181 | + cache_index, | ||
| 182 | + quant_scale_kv=quant_scale_kv, | ||
| 183 | + rope_sin=rope_sin, | ||
| 184 | + rope_cos=rope_cos, | ||
| 185 | + norm_eps=norm_eps, | ||
| 186 | + qkv_quant_mode=qkv_quant_mode.value, | ||
| 187 | + cache_mode=cache_mode.value, | ||
| 188 | + qr_scale=qr_scale, | ||
| 189 | + kvr_scale=kvr_scale, | ||
| 190 | + rope_mode=rope_mode.value, | ||
| 191 | + return_qr=return_qr, | ||
| 192 | + ) | ||
| 193 | + | ||
| 194 | + | ||
| 195 | +get_as_library().define(_TORCH_SCHEMA) | ||
| 196 | +get_as_library().define( | ||
| 197 | + _TORCH_SCHEMA.replace("mla_prolog_v2(", "_mla_prolog_v2_graph(", 1) | ||
| 198 | +) | ||
| 199 | +impl(get_as_library(), "mla_prolog_v2", "Meta")(mla_prolog_v2_fake) | ||
| 200 | +impl(get_as_library(), "_mla_prolog_v2_graph", "Meta")(mla_prolog_v2_fake) | ||
| 201 | + | ||
| 202 | + | ||
| 203 | +@impl(get_as_library(), "mla_prolog_v2", "PrivateUse1") | ||
| 204 | +def _dispatch_eager(*values, **attributes): | ||
| 205 | + from .op_dsl import mla_prolog_v4 as implementation | ||
| 206 | + | ||
| 207 | + return implementation.mla_prolog_v2_npu(*values, **attributes) | ||
| 208 | + | ||
| 209 | + | ||
| 210 | +@impl(get_as_library(), "_mla_prolog_v2_graph", "PrivateUse1") | ||
| 211 | +def _dispatch_graph(*values, **attributes): | ||
| 212 | + from .op_dsl import mla_prolog_v4 as implementation | ||
| 213 | + | ||
| 214 | + return implementation.mla_prolog_v2_graph_npu(*values, **attributes) | ||
| 215 | + | ||
| 216 | + | ||
| 217 | +mla_prolog_v2.QkvQuantMode = QkvQuantMode | ||
| 218 | +mla_prolog_v2.CacheMode = CacheMode | ||
| 219 | +mla_prolog_v2.RopeMode = RopeMode | ||
| @@ -0,0 +1,14 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +add_op_to_compiled_list() | ||
| 10 | + | ||
| 11 | + | ||
| 12 | +if(BUILD_OPEN_PROJECT) | ||
| 13 | + enable_cannbotdsl_kernel(quant_mla_prolog "${CMAKE_CURRENT_LIST_DIR}") | ||
| 14 | +endif() | ||
This file has too many line changes or character changes, you can directly View source code
| @@ -0,0 +1,11 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +from .quant_mla_prolog import quant_mla_prolog | ||
| 10 | + | ||
| 11 | +__all__ = ["quant_mla_prolog"] | ||
| @@ -0,0 +1,431 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | + | ||
| 9 | +from enum import Enum as _Enum | ||
| 10 | +import math as _math | ||
| 11 | +import struct as _struct | ||
| 12 | + | ||
| 13 | +import torch as _torch | ||
| 14 | +from torch.library import impl | ||
| 15 | + | ||
| 16 | +from cann_ops_transformer.op_builder import get_as_library | ||
| 17 | + | ||
| 18 | + | ||
| 19 | +KV_ELEMENTS = 512 | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +class WQrQuantMode(_Enum): | ||
| 23 | + A8W8_MXFP8 = 1 | ||
| 24 | + A8W8_HIFLOAT8_PER_TENSOR = 2 | ||
| 25 | + A4W4_HIFLOAT4 = 3 | ||
| 26 | + | ||
| 27 | + | ||
| 28 | +class QkvQuantMode(_Enum): | ||
| 29 | + A16C16 = 0 | ||
| 30 | + A16C8_KV_NOPE_FP8_E4M3_PER_TOKEN_GROUP_GROUP_SIZE_128_ROPE_BF16_SCALE_FLOAT_KV_CACHE_LAYOUT_N_NOPE_ROPE_SCALE = 1 | ||
| 31 | + A8C8_Q_FP8_E4M3_PER_TOKEN_HEAD_KV_FP8_E4M3_PER_TENSOR = 2 | ||
| 32 | + A8C8_QKV_HIFLOAT8_PER_TENSOR = 3 | ||
| 33 | + | ||
| 34 | + | ||
| 35 | +class CacheMode(_Enum): | ||
| 36 | + PA_BSND = 0 | ||
| 37 | + PA_NZ = 1 | ||
| 38 | + | ||
| 39 | + | ||
| 40 | +class RopeMode(_Enum): | ||
| 41 | + NO_ROPE = 0 | ||
| 42 | + ROPE_INTERLEAVE_HALF = 1 | ||
| 43 | + ROPE_HALF = 2 | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +_W_QR_QUANT_MODE_VALUES = tuple((_m.value for _m in WQrQuantMode)) | ||
| 47 | +_QKV_QUANT_MODE_VALUES = tuple((_m.value for _m in QkvQuantMode)) | ||
| 48 | +_CACHE_MODE_VALUES = tuple((_m.value for _m in CacheMode)) | ||
| 49 | +_ROPE_MODE_VALUES = tuple((_m.value for _m in RopeMode)) | ||
| 50 | +_VALID_PAIRS = {(0, 1), (0, 2), (1, 1), (2, 1), (3, 2)} | ||
| 51 | +_E4 = _torch.float8_e4m3fn | ||
| 52 | +_E8 = _torch.float8_e8m0fnu | ||
| 53 | + | ||
| 54 | + | ||
| 55 | +def _require(condition, message): | ||
| 56 | + if not condition: | ||
| 57 | + raise ValueError(message) | ||
| 58 | + | ||
| 59 | + | ||
| 60 | +def _mode_value(name, value, enum_type): | ||
| 61 | + if type(value) is not enum_type: | ||
| 62 | + raise TypeError(f"{name} must be a {enum_type.__name__} enum") | ||
| 63 | + return value.value | ||
| 64 | + | ||
| 65 | + | ||
| 66 | +def _validate_modes(w_qr_quant_mode, qkv_quant_mode, cache_mode, rope_mode): | ||
| 67 | + for name, value, allowed in ( | ||
| 68 | + ("w_qr_quant_mode", w_qr_quant_mode, _W_QR_QUANT_MODE_VALUES), | ||
| 69 | + ("qkv_quant_mode", qkv_quant_mode, _QKV_QUANT_MODE_VALUES), | ||
| 70 | + ("cache_mode", cache_mode, _CACHE_MODE_VALUES), | ||
| 71 | + ("rope_mode", rope_mode, _ROPE_MODE_VALUES), | ||
| 72 | + ): | ||
| 73 | + if type(value) is not int: | ||
| 74 | + raise TypeError(f"{name} schema value must be int") | ||
| 75 | + if value not in allowed: | ||
| 76 | + raise ValueError(f"{name} has unsupported schema value {value}") | ||
| 77 | + if w_qr_quant_mode == WQrQuantMode.A4W4_HIFLOAT4.value: | ||
| 78 | + raise NotImplementedError("A4W4_HIFLOAT4 is not implemented") | ||
| 79 | + _require( | ||
| 80 | + (qkv_quant_mode, w_qr_quant_mode) in _VALID_PAIRS, | ||
| 81 | + "unsupported qkv_quant_mode/w_qr_quant_mode combination", | ||
| 82 | + ) | ||
| 83 | + _require( | ||
| 84 | + not ( | ||
| 85 | + cache_mode == CacheMode.PA_NZ.value | ||
| 86 | + and qkv_quant_mode | ||
| 87 | + == QkvQuantMode.A16C8_KV_NOPE_FP8_E4M3_PER_TOKEN_GROUP_GROUP_SIZE_128_ROPE_BF16_SCALE_FLOAT_KV_CACHE_LAYOUT_N_NOPE_ROPE_SCALE.value | ||
| 88 | + ), | ||
| 89 | + "qkv_quant_mode=1 does not support PA_NZ", | ||
| 90 | + ) | ||
| 91 | + | ||
| 92 | + | ||
| 93 | +def _output_specs(T, N, q_lora, Dr, w_qr_quant_mode, qkv_quant_mode, return_qr): | ||
| 94 | + q_dtype = ( | ||
| 95 | + _torch.bfloat16 | ||
| 96 | + if qkv_quant_mode in (0, 1) | ||
| 97 | + else _E4 | ||
| 98 | + if qkv_quant_mode == 2 | ||
| 99 | + else _torch.uint8 | ||
| 100 | + ) | ||
| 101 | + qr_dtype = _E4 if w_qr_quant_mode == 1 else _torch.uint8 | ||
| 102 | + descale_qr_dtype = _E8 if w_qr_quant_mode == 1 else _torch.float32 | ||
| 103 | + descale_q_shape = ( | ||
| 104 | + (T, N, 1) | ||
| 105 | + if qkv_quant_mode == 2 | ||
| 106 | + else (int(T != 0),) | ||
| 107 | + if qkv_quant_mode == 3 | ||
| 108 | + else (0,) | ||
| 109 | + ) | ||
| 110 | + qr_shape = (T, q_lora) if return_qr else (0,) | ||
| 111 | + descale_qr_shape = ( | ||
| 112 | + ((T, q_lora // 32) if w_qr_quant_mode == 1 else (int(T != 0),)) | ||
| 113 | + if return_qr | ||
| 114 | + else (0,) | ||
| 115 | + ) | ||
| 116 | + return ( | ||
| 117 | + ((T, N, KV_ELEMENTS + Dr), q_dtype), | ||
| 118 | + (descale_q_shape, _torch.float32), | ||
| 119 | + (qr_shape, qr_dtype), | ||
| 120 | + (descale_qr_shape, descale_qr_dtype), | ||
| 121 | + ) | ||
| 122 | + | ||
| 123 | + | ||
| 124 | +def _validate_scalars(norm_eps, qr_scale, kvr_scale): | ||
| 125 | + for name, value in ( | ||
| 126 | + ("norm_eps", norm_eps), | ||
| 127 | + ("qr_scale", qr_scale), | ||
| 128 | + ("kvr_scale", kvr_scale), | ||
| 129 | + ): | ||
| 130 | + if isinstance(value, bool) or not isinstance(value, (int, float)): | ||
| 131 | + raise TypeError(f"{name} must be a Python float or int, not bool or Tensor") | ||
| 132 | + try: | ||
| 133 | + fp32_value = _struct.unpack("f", _struct.pack("f", float(value)))[0] | ||
| 134 | + except (OverflowError, _struct.error) as error: | ||
| 135 | + raise ValueError(f"{name} must be finite in FP32") from error | ||
| 136 | + _require(_math.isfinite(fp32_value), f"{name} must be finite in FP32") | ||
| 137 | + if name == "norm_eps": | ||
| 138 | + _require(fp32_value > 0, f"{name} must be strictly positive in FP32") | ||
| 139 | + | ||
| 140 | + | ||
| 141 | +def _validate_rope_inputs(rope_sin, rope_cos, T, Dr, rope_mode, device, *, fake=False): | ||
| 142 | + if rope_sin is None and rope_cos is None: | ||
| 143 | + _require( | ||
| 144 | + not (Dr and rope_mode), "rope_sin/rope_cos are required for active RoPE" | ||
| 145 | + ) | ||
| 146 | + return | ||
| 147 | + _require( | ||
| 148 | + rope_sin is not None and rope_cos is not None, | ||
| 149 | + "rope_sin/rope_cos must be supplied together", | ||
| 150 | + ) | ||
| 151 | + for name, value in (("rope_sin", rope_sin), ("rope_cos", rope_cos)): | ||
| 152 | + _require(isinstance(value, _torch.Tensor), f"{name} must be a Tensor") | ||
| 153 | + _require(tuple(value.shape) == (T, Dr), f"{name} shape must be {(T, Dr)}") | ||
| 154 | + _require(value.dtype == _torch.bfloat16, f"{name} must be BF16") | ||
| 155 | + _require(value.device == device, f"{name} must be on {device}") | ||
| 156 | + _require(value.is_contiguous(), f"{name} must be contiguous") | ||
| 157 | + | ||
| 158 | + | ||
| 159 | +_TORCH_SCHEMA = "quant_mla_prolog(Tensor x, Tensor wqa, Tensor wqb, Tensor wkva, Tensor wkb, Tensor descale_x, Tensor descale_wqa, Tensor descale_wqb, Tensor descale_wkva, Tensor norm_weight_qa, Tensor norm_weight_kva, Tensor(a!) kv_cache, Tensor cache_index, int w_qr_quant_mode, int qkv_quant_mode, *, Tensor? quant_scale_kv=None, Tensor? rope_sin=None, Tensor? rope_cos=None, float norm_eps=1e-5, int cache_mode=0, float qr_scale=1., float kvr_scale=1., int rope_mode=1, bool return_qr=False) -> (Tensor, Tensor, Tensor, Tensor)" | ||
| 160 | + | ||
| 161 | + | ||
| 162 | +def _fake( | ||
| 163 | + x, | ||
| 164 | + wqa, | ||
| 165 | + wqb, | ||
| 166 | + wkva, | ||
| 167 | + wkb, | ||
| 168 | + descale_x, | ||
| 169 | + descale_wqa, | ||
| 170 | + descale_wqb, | ||
| 171 | + descale_wkva, | ||
| 172 | + norm_weight_qa, | ||
| 173 | + norm_weight_kva, | ||
| 174 | + kv_cache, | ||
| 175 | + cache_index, | ||
| 176 | + w_qr_quant_mode, | ||
| 177 | + qkv_quant_mode, | ||
| 178 | + *, | ||
| 179 | + quant_scale_kv=None, | ||
| 180 | + rope_sin=None, | ||
| 181 | + rope_cos=None, | ||
| 182 | + norm_eps=1e-05, | ||
| 183 | + cache_mode=0, | ||
| 184 | + qr_scale=1.0, | ||
| 185 | + kvr_scale=1.0, | ||
| 186 | + rope_mode=1, | ||
| 187 | + return_qr=False, | ||
| 188 | +): | ||
| 189 | + _validate_modes(w_qr_quant_mode, qkv_quant_mode, cache_mode, rope_mode) | ||
| 190 | + _require(type(return_qr) is bool, "return_qr must be bool") | ||
| 191 | + _validate_scalars(norm_eps, qr_scale, kvr_scale) | ||
| 192 | + T = x.shape[0] | ||
| 193 | + N = wkb.shape[0] | ||
| 194 | + Dr = 0 if wkb.shape[1] == 256 else 64 | ||
| 195 | + q_lora = norm_weight_qa.shape[0] | ||
| 196 | + _require( | ||
| 197 | + Dr != 0 or rope_mode == RopeMode.NO_ROPE.value, "Dr=0 requires rope_mode=0" | ||
| 198 | + ) | ||
| 199 | + _validate_rope_inputs(rope_sin, rope_cos, T, Dr, rope_mode, x.device, fake=True) | ||
| 200 | + return tuple( | ||
| 201 | + ( | ||
| 202 | + x.new_empty(shape, dtype=dtype) | ||
| 203 | + for (shape, dtype) in _output_specs( | ||
| 204 | + T, N, q_lora, Dr, w_qr_quant_mode, qkv_quant_mode, return_qr | ||
| 205 | + ) | ||
| 206 | + ) | ||
| 207 | + ) | ||
| 208 | + | ||
| 209 | + | ||
| 210 | +def _reject_functionalization(*args, **kwargs): | ||
| 211 | + raise RuntimeError( | ||
| 212 | + "quant_mla_prolog requires a backend preserving the mutable cache op; functionalization with cache clone/copy-back is disabled" | ||
| 213 | + ) | ||
| 214 | + | ||
| 215 | + | ||
| 216 | +def _graph_fake(*args, **attrs): | ||
| 217 | + (q, descale_q, qr, descale_qr) = _fake(*args, **attrs) | ||
| 218 | + weight_mode = args[13] if len(args) > 13 else attrs["w_qr_quant_mode"] | ||
| 219 | + if weight_mode == WQrQuantMode.A8W8_MXFP8.value: | ||
| 220 | + descale_qr = descale_qr.view(_torch.uint8) | ||
| 221 | + return (q, descale_q, qr, descale_qr) | ||
| 222 | + | ||
| 223 | + | ||
| 224 | +def quant_mla_prolog( | ||
| 225 | + x: _torch.Tensor, | ||
| 226 | + wqa: _torch.Tensor, | ||
| 227 | + wqb: _torch.Tensor, | ||
| 228 | + wkva: _torch.Tensor, | ||
| 229 | + wkb: _torch.Tensor, | ||
| 230 | + descale_x: _torch.Tensor, | ||
| 231 | + descale_wqa: _torch.Tensor, | ||
| 232 | + descale_wqb: _torch.Tensor, | ||
| 233 | + descale_wkva: _torch.Tensor, | ||
| 234 | + norm_weight_qa: _torch.Tensor, | ||
| 235 | + norm_weight_kva: _torch.Tensor, | ||
| 236 | + kv_cache: _torch.Tensor, | ||
| 237 | + cache_index: _torch.Tensor, | ||
| 238 | + w_qr_quant_mode: WQrQuantMode, | ||
| 239 | + qkv_quant_mode: QkvQuantMode, | ||
| 240 | + *, | ||
| 241 | + quant_scale_kv: _torch.Tensor | None = None, | ||
| 242 | + rope_sin: _torch.Tensor | None = None, | ||
| 243 | + rope_cos: _torch.Tensor | None = None, | ||
| 244 | + norm_eps: float = 1e-05, | ||
| 245 | + cache_mode: CacheMode = CacheMode.PA_BSND, | ||
| 246 | + qr_scale: float = 1.0, | ||
| 247 | + kvr_scale: float = 1.0, | ||
| 248 | + rope_mode: RopeMode = RopeMode.ROPE_INTERLEAVE_HALF, | ||
| 249 | + return_qr: bool = False, | ||
| 250 | +) -> tuple[_torch.Tensor, _torch.Tensor, _torch.Tensor, _torch.Tensor]: | ||
| 251 | + """Run quantized MLA projection, normalization, RoPE and cache update. | ||
| 252 | + | ||
| 253 | + ``x``, weights and their descales use the selected MXFP8/HiF8 layout. | ||
| 254 | + FP32 normalization weights and | ||
| 255 | + ``cache_index`` describe normalization and the slots updated in ``kv_cache``. | ||
| 256 | + Optional scale and RoPE tensors are keyword arguments. Mode attributes use | ||
| 257 | + the enums attached to this function; scalar attributes control epsilon and | ||
| 258 | + output scaling. ``precheck`` validates scale contents before graph capture. | ||
| 259 | + | ||
| 260 | + Returns ``(q, descale_q, qr, descale_qr)``; the QR slots are empty when | ||
| 261 | + ``return_qr`` is false. Cache is updated in place and is not returned. | ||
| 262 | + """ | ||
| 263 | + if type(return_qr) is not bool: | ||
| 264 | + raise TypeError("return_qr must be bool") | ||
| 265 | + _validate_scalars(norm_eps, qr_scale, kvr_scale) | ||
| 266 | + w_qr_quant_mode = _mode_value("w_qr_quant_mode", w_qr_quant_mode, WQrQuantMode) | ||
| 267 | + qkv_quant_mode = _mode_value("qkv_quant_mode", qkv_quant_mode, QkvQuantMode) | ||
| 268 | + cache_mode = _mode_value("cache_mode", cache_mode, CacheMode) | ||
| 269 | + rope_mode = _mode_value("rope_mode", rope_mode, RopeMode) | ||
| 270 | + _validate_modes(w_qr_quant_mode, qkv_quant_mode, cache_mode, rope_mode) | ||
| 271 | + graph_execution = _torch.compiler.is_compiling() or ( | ||
| 272 | + isinstance(x, _torch.Tensor) | ||
| 273 | + and x.device.type in ("npu", "privateuseone") | ||
| 274 | + and (x.shape[0] != 0) | ||
| 275 | + and _torch.npu.is_current_stream_capturing() | ||
| 276 | + ) | ||
| 277 | + if graph_execution and w_qr_quant_mode == WQrQuantMode.A8W8_MXFP8.value: | ||
| 278 | + if not isinstance(descale_x, _torch.Tensor) or descale_x.dtype != _E8: | ||
| 279 | + raise TypeError("descale_x must be an E8M0 Tensor") | ||
| 280 | + for name, value, weight in ( | ||
| 281 | + ("descale_wqa", descale_wqa, wqa), | ||
| 282 | + ("descale_wqb", descale_wqb, wqb), | ||
| 283 | + ("descale_wkva", descale_wkva, wkva), | ||
| 284 | + ): | ||
| 285 | + if not isinstance(value, _torch.Tensor): | ||
| 286 | + raise TypeError(f"{name} must be a Tensor") | ||
| 287 | + byte_weight_scale = value.dtype == _torch.uint8 and tuple(value.shape) == ( | ||
| 288 | + weight.shape[0] // 64, | ||
| 289 | + weight.shape[1], | ||
| 290 | + 2, | ||
| 291 | + ) | ||
| 292 | + if value.dtype != _E8 and (not byte_weight_scale): | ||
| 293 | + raise TypeError(f"{name} must be E8M0 or a UINT8 NZ weight scale") | ||
| 294 | + (descale_x, descale_wqa, descale_wqb, descale_wkva) = ( | ||
| 295 | + value.view(_torch.uint8) | ||
| 296 | + for value in (descale_x, descale_wqa, descale_wqb, descale_wkva) | ||
| 297 | + ) | ||
| 298 | + args = ( | ||
| 299 | + x, | ||
| 300 | + wqa, | ||
| 301 | + wqb, | ||
| 302 | + wkva, | ||
| 303 | + wkb, | ||
| 304 | + descale_x, | ||
| 305 | + descale_wqa, | ||
| 306 | + descale_wqb, | ||
| 307 | + descale_wkva, | ||
| 308 | + norm_weight_qa, | ||
| 309 | + norm_weight_kva, | ||
| 310 | + kv_cache, | ||
| 311 | + cache_index, | ||
| 312 | + ) | ||
| 313 | + attrs = dict( | ||
| 314 | + quant_scale_kv=quant_scale_kv, | ||
| 315 | + rope_sin=rope_sin, | ||
| 316 | + rope_cos=rope_cos, | ||
| 317 | + norm_eps=norm_eps, | ||
| 318 | + w_qr_quant_mode=w_qr_quant_mode, | ||
| 319 | + qkv_quant_mode=qkv_quant_mode, | ||
| 320 | + cache_mode=cache_mode, | ||
| 321 | + qr_scale=qr_scale, | ||
| 322 | + kvr_scale=kvr_scale, | ||
| 323 | + rope_mode=rope_mode, | ||
| 324 | + return_qr=return_qr, | ||
| 325 | + ) | ||
| 326 | + dispatch = ( | ||
| 327 | + _torch.ops.cann_ops_transformer._quant_mla_prolog_graph.default | ||
| 328 | + if graph_execution | ||
| 329 | + else _torch.ops.cann_ops_transformer.quant_mla_prolog.default | ||
| 330 | + ) | ||
| 331 | + result = dispatch(*args, **attrs) | ||
| 332 | + if graph_execution and w_qr_quant_mode == WQrQuantMode.A8W8_MXFP8.value: | ||
| 333 | + return (result[0], result[1], result[2], result[3].view(_E8)) | ||
| 334 | + return result | ||
| 335 | + | ||
| 336 | + | ||
| 337 | +get_as_library().define(_TORCH_SCHEMA) | ||
| 338 | +get_as_library().define( | ||
| 339 | + _TORCH_SCHEMA.replace("quant_mla_prolog(", "_quant_mla_prolog_graph(", 1) | ||
| 340 | +) | ||
| 341 | +impl(get_as_library(), "quant_mla_prolog", "Meta")(_fake) | ||
| 342 | +impl(get_as_library(), "_quant_mla_prolog_graph", "Meta")(_graph_fake) | ||
| 343 | + | ||
| 344 | + | ||
| 345 | +@impl(get_as_library(), "quant_mla_prolog", "PrivateUse1") | ||
| 346 | +def _dispatch_eager(*values, **attributes): | ||
| 347 | + from .op_dsl import quant_mla_prolog as implementation | ||
| 348 | + | ||
| 349 | + return implementation.execute_async(*values, **attributes) | ||
| 350 | + | ||
| 351 | + | ||
| 352 | +@impl(get_as_library(), "_quant_mla_prolog_graph", "PrivateUse1") | ||
| 353 | +def _dispatch_graph(*values, **attributes): | ||
| 354 | + from .op_dsl import quant_mla_prolog as implementation | ||
| 355 | + | ||
| 356 | + return implementation.execute_graph(*values, **attributes) | ||
| 357 | + | ||
| 358 | + | ||
| 359 | +def _mode(name, value, enum_type, implementation): | ||
| 360 | + if type(value) is not enum_type: | ||
| 361 | + raise TypeError(f"{name} must be {enum_type.__name__}") | ||
| 362 | + return getattr(implementation, enum_type.__name__)(value.value) | ||
| 363 | + | ||
| 364 | + | ||
| 365 | +def quant_mla_prolog_precheck( | ||
| 366 | + x: _torch.Tensor, | ||
| 367 | + wqa: _torch.Tensor, | ||
| 368 | + wqb: _torch.Tensor, | ||
| 369 | + wkva: _torch.Tensor, | ||
| 370 | + wkb: _torch.Tensor, | ||
| 371 | + descale_x: _torch.Tensor, | ||
| 372 | + descale_wqa: _torch.Tensor, | ||
| 373 | + descale_wqb: _torch.Tensor, | ||
| 374 | + descale_wkva: _torch.Tensor, | ||
| 375 | + norm_weight_qa: _torch.Tensor, | ||
| 376 | + norm_weight_kva: _torch.Tensor, | ||
| 377 | + kv_cache: _torch.Tensor, | ||
| 378 | + cache_index: _torch.Tensor, | ||
| 379 | + w_qr_quant_mode: WQrQuantMode, | ||
| 380 | + qkv_quant_mode: QkvQuantMode, | ||
| 381 | + *, | ||
| 382 | + quant_scale_kv: _torch.Tensor | None = None, | ||
| 383 | + rope_sin: _torch.Tensor | None = None, | ||
| 384 | + rope_cos: _torch.Tensor | None = None, | ||
| 385 | + norm_eps: float = 1e-05, | ||
| 386 | + cache_mode: CacheMode = CacheMode.PA_BSND, | ||
| 387 | + qr_scale: float = 1.0, | ||
| 388 | + kvr_scale: float = 1.0, | ||
| 389 | + rope_mode: RopeMode = RopeMode.ROPE_INTERLEAVE_HALF, | ||
| 390 | + return_qr: bool = False, | ||
| 391 | +) -> None: | ||
| 392 | + from .op_dsl import quant_mla_prolog as implementation | ||
| 393 | + | ||
| 394 | + return implementation.quant_mla_prolog_precheck( | ||
| 395 | + x, | ||
| 396 | + wqa, | ||
| 397 | + wqb, | ||
| 398 | + wkva, | ||
| 399 | + wkb, | ||
| 400 | + descale_x, | ||
| 401 | + descale_wqa, | ||
| 402 | + descale_wqb, | ||
| 403 | + descale_wkva, | ||
| 404 | + norm_weight_qa, | ||
| 405 | + norm_weight_kva, | ||
| 406 | + kv_cache, | ||
| 407 | + cache_index, | ||
| 408 | + quant_scale_kv=quant_scale_kv, | ||
| 409 | + rope_sin=rope_sin, | ||
| 410 | + rope_cos=rope_cos, | ||
| 411 | + norm_eps=norm_eps, | ||
| 412 | + w_qr_quant_mode=_mode( | ||
| 413 | + "w_qr_quant_mode", w_qr_quant_mode, WQrQuantMode, implementation | ||
| 414 | + ), | ||
| 415 | + qkv_quant_mode=_mode( | ||
| 416 | + "qkv_quant_mode", qkv_quant_mode, QkvQuantMode, implementation | ||
| 417 | + ), | ||
| 418 | + cache_mode=_mode("cache_mode", cache_mode, CacheMode, implementation), | ||
| 419 | + qr_scale=qr_scale, | ||
| 420 | + kvr_scale=kvr_scale, | ||
| 421 | + rope_mode=_mode("rope_mode", rope_mode, RopeMode, implementation), | ||
| 422 | + return_qr=return_qr, | ||
| 423 | + ) | ||
| 424 | + | ||
| 425 | + | ||
| 426 | +impl(get_as_library(), "quant_mla_prolog", "Functionalize")(_reject_functionalization) | ||
| 427 | +quant_mla_prolog.QkvQuantMode = QkvQuantMode | ||
| 428 | +quant_mla_prolog.CacheMode = CacheMode | ||
| 429 | +quant_mla_prolog.RopeMode = RopeMode | ||
| 430 | +quant_mla_prolog.WQrQuantMode = WQrQuantMode | ||
| 431 | +quant_mla_prolog.precheck = quant_mla_prolog_precheck | ||