Merged
fix(gmm): 修复 A5 golden 权重解码与图输入布局 #17527
zhoushaolongAdd on 1 day ago
fix(gmm): 修复 A5 golden 权重解码与图输入布局 #17527
Merged
Total: 4 files changed+140-7
| @@ -599,14 +599,23 @@ def _with_transposed_storage(tensor, dim0, dim1): | |||
| 599 | """Give a dense CSV tensor transposed strides without changing logical values.""" | 599 | """Give a dense CSV tensor transposed strides without changing logical values.""" |
| 600 | import torch | 600 | import torch |
| 601 | 601 | ||
| 602 | - if tensor.stride(dim0) < tensor.stride(dim1): | 602 | + first, second = sorted((dim0 % tensor.ndim, dim1 % tensor.ndim)) |
| 603 | + if tensor.stride(first) < tensor.stride(second): | ||
| 603 | return tensor | 604 | return tensor |
| 604 | source = tensor.transpose(dim0, dim1).clone(memory_format=torch.contiguous_format) | 605 | source = tensor.transpose(dim0, dim1).clone(memory_format=torch.contiguous_format) |
| 605 | return source.transpose(dim0, dim1) | 606 | return source.transpose(dim0, dim1) |
| 606 | 607 | ||
| 607 | 608 | ||
| 608 | def _hook_preprocess(*args, **meta): | 609 | def _hook_preprocess(*args, **meta): |
| 609 | - trans = meta["f_trans"] and not meta.get("f_graph_source") | 610 | + routing_graph = ( |
| 611 | + meta["f_family"] == "routing" | ||
| 612 | + and meta.get("f_graph_source") | ||
| 613 | + and meta["f_trans"] | ||
| 614 | + and meta["f_format"] == "FRACTAL_NZ_C0_32" | ||
| 615 | + and meta["f_types"][0] == "float8_e4m3fn" | ||
| 616 | + and meta["f_types"][1] == "float4_e2m1" | ||
| 617 | + ) | ||
| 618 | + trans = meta["f_trans"] and (routing_graph or not meta.get("f_graph_source")) | ||
| 610 | nd = meta["f_format"] == "ND" | 619 | nd = meta["f_format"] == "ND" |
| 611 | swiglu_trans = trans and meta["f_family"] == "swiglu" | 620 | swiglu_trans = trans and meta["f_family"] == "swiglu" |
| 612 | if nd and not swiglu_trans: | 621 | if nd and not swiglu_trans: |
| @@ -619,6 +628,10 @@ def _hook_preprocess(*args, **meta): | |||
| 619 | scales = args[meta["f_ports"]["ws"]] | 628 | scales = args[meta["f_ports"]["ws"]] |
| 620 | for i, scale in enumerate(scales): | 629 | for i, scale in enumerate(scales): |
| 621 | scales[i] = _with_transposed_storage(scale, -3, -2) | 630 | scales[i] = _with_transposed_storage(scale, -3, -2) |
| 631 | + if routing_graph: | ||
| 632 | + # Graph CSVs carry the packed source layout; eager needs API views. | ||
| 633 | + scale = args[meta["f_ports"]["ws"]] | ||
| 634 | + scale.data = scale.transpose(-3, -2) | ||
| 622 | port = meta["f_ports"]["w"] | 635 | port = meta["f_ports"]["w"] |
| 623 | value = args[port] | 636 | value = args[port] |
| 624 | listed = isinstance(value, (list, tuple)) | 637 | listed = isinstance(value, (list, tuple)) |
| @@ -629,7 +642,11 @@ def _hook_preprocess(*args, **meta): | |||
| 629 | if nd: | 642 | if nd: |
| 630 | results.append(_with_transposed_storage(tensor, -1, -2)) | 643 | results.append(_with_transposed_storage(tensor, -1, -2)) |
| 631 | continue | 644 | continue |
| 632 | - source = tensor.transpose(-1, -2).contiguous() if trans else tensor | 645 | + source = ( |
| 646 | + tensor.transpose(-1, -2).contiguous() | ||
| 647 | + if trans and not routing_graph | ||
| 648 | + else tensor | ||
| 649 | + ) | ||
| 633 | if wd.startswith("float4") and meta["f_format"] == "FRACTAL_NZ_C0_32": | 650 | if wd.startswith("float4") and meta["f_format"] == "FRACTAL_NZ_C0_32": |
| 634 | hint = 296 if wd == "float4_e2m1" else 297 | 651 | hint = 296 if wd == "float4_e2m1" else 297 |
| 635 | converted = torch_npu.npu_format_cast( | 652 | converted = torch_npu.npu_format_cast( |
| @@ -695,8 +712,8 @@ def _hook_golden(*args, _routing_trace=None, **meta): | |||
| 695 | meta["f_trans"], | 712 | meta["f_trans"], |
| 696 | c0, | 713 | c0, |
| 697 | "int4" if wd == "int4" else "", | 714 | "int4" if wd == "int4" else "", |
| 698 | - meta["f_shape"][1], | 715 | + meta["f_shape"][-2], |
| 699 | - meta["f_shape"][2], | 716 | + meta["f_shape"][-1], |
| 700 | ) | 717 | ) |
| 701 | w = np.stack(decoded) if len(decoded) > 1 else decoded[0] | 718 | w = np.stack(decoded) if len(decoded) > 1 else decoded[0] |
| 702 | else: | 719 | else: |
| @@ -21,8 +21,37 @@ finally: | |||
| 21 | sys.path.pop(0) | 21 | sys.path.pop(0) |
| 22 | 22 | ||
| 23 | 23 | ||
| 24 | +class PreparedRoutingGraph(RoutingGraph): | ||
| 25 | + """Keep packed NZ graph inputs contiguous and trace transposes in forward. | ||
| 26 | + | ||
| 27 | + The eager preprocessor exposes transposed API views. Restore their source | ||
| 28 | + layout before tracing so TorchAir does not clone a discontiguous NZ input. | ||
| 29 | + """ | ||
| 30 | + | ||
| 31 | + def __init__(self, w, scale=None, w_dtype=None, x_dtype=None): | ||
| 32 | + super().__init__() | ||
| 33 | + self._w_dtype = w_dtype | ||
| 34 | + self._x_dtype = x_dtype | ||
| 35 | + if w_dtype == self._fp4_e2m1 and x_dtype != self._fp4_e2m1: | ||
| 36 | + w = w.transpose(-1, -2) | ||
| 37 | + scale = scale.transpose(-3, -2) | ||
| 38 | + self.register_buffer("weight", w, persistent=False) | ||
| 39 | + self.register_buffer("weight_scale", scale, persistent=False) | ||
| 40 | + | ||
| 41 | + def forward(self, x, group_list, **kwargs): | ||
| 42 | + return super().forward( | ||
| 43 | + x, | ||
| 44 | + self.weight, | ||
| 45 | + group_list, | ||
| 46 | + scale=self.weight_scale, | ||
| 47 | + w_dtype=self._w_dtype, | ||
| 48 | + x_dtype=self._x_dtype, | ||
| 49 | + **kwargs, | ||
| 50 | + ) | ||
| 51 | + | ||
| 52 | + | ||
| 24 | E2ESpec = _make_spec("routing", "e2e") | 53 | E2ESpec = _make_spec("routing", "e2e") |
| 25 | -E2ESpec.torch_graph = RoutingGraph | 54 | +E2ESpec.torch_graph = PreparedRoutingGraph |
| 26 | 55 | ||
| 27 | 56 | ||
| 28 | __spec__ = { | 57 | __spec__ = { |
| @@ -0,0 +1,34 @@ | |||
| 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 | +from pathlib import Path | ||
| 9 | +from runpy import run_path | ||
| 10 | + | ||
| 11 | +import numpy as np | ||
| 12 | +import torch | ||
| 13 | + | ||
| 14 | +_REFERENCE = run_path( | ||
| 15 | + str(Path(__file__).resolve().parents[4] / "common/tests/ttk/fused_spec.py") | ||
| 16 | +) | ||
| 17 | + | ||
| 18 | + | ||
| 19 | +def test_transposed_storage_keeps_values_for_either_axis_order(): | ||
| 20 | + original = torch.arange(24).reshape(2, 3, 4) | ||
| 21 | + for axes in ((-1, -2), (-2, -1)): | ||
| 22 | + view = _REFERENCE["_with_transposed_storage"](original, *axes) | ||
| 23 | + torch.testing.assert_close(view, original) | ||
| 24 | + assert view.stride(-2) == 1 | ||
| 25 | + assert view.stride(-1) == 3 | ||
| 26 | + assert _REFERENCE["_with_transposed_storage"](view, *axes) is view | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +def test_fp4_transposed_carrier_unpacks_k_axis(): | ||
| 30 | + packed = torch.full((1, 2, 3), 0x21, dtype=torch.uint8) | ||
| 31 | + view = _REFERENCE["_with_transposed_storage"](packed, -1, -2) | ||
| 32 | + actual = _REFERENCE["_decode"](view, "float4_e2m1") | ||
| 33 | + expected = np.array([[[0.5] * 3, [1.0] * 3, [0.5] * 3, [1.0] * 3]]) | ||
| 34 | + np.testing.assert_array_equal(actual, expected) | ||
| @@ -92,8 +92,61 @@ finally: | |||
| 92 | sys.path.pop(0) | 92 | sys.path.pop(0) |
| 93 | 93 | ||
| 94 | 94 | ||
| 95 | +class PreparedInplaceGraph(InplaceGraph): | ||
| 96 | + """Bind logical inputs before Dynamo traces the graph-side transposes. | ||
| 97 | + | ||
| 98 | + The eager leg consumes API views, materialized by npu_preprocess below. | ||
| 99 | + Restoring the logical layout in __init__ keeps that eager-only adaptation | ||
| 100 | + outside the traced forward and preserves the documented MX scale transpose. | ||
| 101 | + """ | ||
| 102 | + | ||
| 103 | + def __init__(self, x1, x1_scale=None): | ||
| 104 | + super().__init__() | ||
| 105 | + self.register_buffer("x1", x1.transpose(0, 1), persistent=False) | ||
| 106 | + logical_scale = ( | ||
| 107 | + x1_scale.transpose(0, 1) | ||
| 108 | + if x1_scale is not None and x1_scale.ndim == 3 | ||
| 109 | + else x1_scale | ||
| 110 | + ) | ||
| 111 | + self.register_buffer("x1_scale", logical_scale, persistent=False) | ||
| 112 | + | ||
| 113 | + def forward(self, input, x2, x2_scale, group_list, **kwargs): | ||
| 114 | + return super().forward( | ||
| 115 | + input, | ||
| 116 | + self.x1, | ||
| 117 | + x2, | ||
| 118 | + x2_scale, | ||
| 119 | + group_list, | ||
| 120 | + x1_scale=self.x1_scale, | ||
| 121 | + **kwargs, | ||
| 122 | + ) | ||
| 123 | + | ||
| 124 | + | ||
| 95 | class GraphSpec(E2eSpec): | 125 | class GraphSpec(E2eSpec): |
| 96 | - torch_graph = InplaceGraph | 126 | + torch_graph = PreparedInplaceGraph |
| 127 | + | ||
| 128 | + @staticmethod | ||
| 129 | + def npu_preprocess( | ||
| 130 | + input, | ||
| 131 | + x1, | ||
| 132 | + x2, | ||
| 133 | + x2_scale, | ||
| 134 | + group_list, | ||
| 135 | + *, | ||
| 136 | + x1_scale=None, | ||
| 137 | + ttk_graph_counts=None, | ||
| 138 | + **kwargs, | ||
| 139 | + ): | ||
| 140 | + """Expose API views without copying or changing low precision values.""" | ||
| 141 | + if ttk_graph_counts is not None: | ||
| 142 | + if x1.stride(0) > x1.stride(1): | ||
| 143 | + x1.data = x1.transpose(0, 1).detach() | ||
| 144 | + if ( | ||
| 145 | + x1_scale is not None | ||
| 146 | + and x1_scale.ndim == 3 | ||
| 147 | + and x1_scale.stride(0) > x1_scale.stride(1) | ||
| 148 | + ): | ||
| 149 | + x1_scale.data = x1_scale.transpose(0, 1).detach() | ||
| 97 | 150 | ||
| 98 | 151 | ||
| 99 | __spec__ = { | 152 | __spec__ = { |