|
| 1 | +# |
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved. |
| 3 | +# This file is a part of the vllm-ascend project. |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | +# mypy: ignore-errors |
| 17 | + |
| 18 | +from __future__ import annotations |
| 19 | + |
| 20 | +import math |
| 21 | + |
| 22 | +import torch |
| 23 | +import torch_npu |
| 24 | +from vllm.model_executor.layers.fla.ops.utils import tensor_cache |
| 25 | + |
| 26 | + |
| 27 | +@tensor_cache |
| 28 | +def _l2norm_unit_weight(dim: int, dtype: torch.dtype, device: torch.device) -> torch.Tensor: |
| 29 | + # RMSNorm with weight 1/sqrt(dim) matches L2 norm: x / sqrt(sum(x^2)). |
| 30 | + return torch.full((dim,), 1.0 / math.sqrt(dim), dtype=dtype, device=device) |
| 31 | + |
| 32 | + |
| 33 | +def l2norm_310p(x: torch.Tensor, eps: float = 1e-6) -> torch.Tensor: |
| 34 | + """L2-normalize the last dimension using the 310P NPU RMSNorm kernel.""" |
| 35 | + orig_shape = x.shape |
| 36 | + dim = x.shape[-1] |
| 37 | + x_2d = x.reshape(-1, dim).contiguous() |
| 38 | + weight = _l2norm_unit_weight(dim, x.dtype, x.device) |
| 39 | + # RMSNorm: y = x / sqrt(mean(x^2) + eps_rms) * weight |
| 40 | + # With weight=1/sqrt(dim), this equals x / sqrt(sum(x^2) + dim * eps_rms). |
| 41 | + # L2 norm needs y = x / sqrt(sum(x^2) + eps), so eps_rms = eps / dim. |
| 42 | + y, _ = torch_npu.npu_rms_norm(x_2d, weight, eps / dim) |
| 43 | + return y.reshape(orig_shape) |
0 commit comments