Merged
fix(operation): Add viewshape check for GatherMask last axis #5626
Wang XuAdd on Aug 24
fix(operation): Add viewshape check for GatherMask last axis #5626
Merged
Total: 6 files changed+281-3
| @@ -1294,8 +1294,14 @@ Tensor View(const Tensor& operand, const std::vector<int64_t>& shapes, const std | |||
| 1294 | result.GetStorage()->UpdateDynValidShape(validShape); | 1294 | result.GetStorage()->UpdateDynValidShape(validShape); |
| 1295 | auto newOffsets = SymbolicScalar::FromConcrete(offsets); | 1295 | auto newOffsets = SymbolicScalar::FromConcrete(offsets); |
| 1296 | op.SetOpAttribute(std::make_shared<ViewOpAttribute>(offsets, newOffsets, validShape)); | 1296 | op.SetOpAttribute(std::make_shared<ViewOpAttribute>(offsets, newOffsets, validShape)); |
| 1297 | + result.GetStorage()->SetAttr("ORIGINAL_SHAPE", operand.GetShape()); | ||
| 1298 | + const auto& operandDynVS = operand.GetStorage()->GetDynValidShape(); | ||
| 1299 | + if (!operandDynVS.empty()) { | ||
| 1300 | + result.GetStorage()->SetAttr("ORIGINAL_DYN_VALID_SHAPE", operandDynVS); | ||
| 1301 | + } | ||
| 1297 | return result; | 1302 | return result; |
| 1298 | } | 1303 | } |
| 1304 | + | ||
| 1299 | bool isInteger(float num) | 1305 | bool isInteger(float num) |
| 1300 | { | 1306 | { |
| 1301 | const float epsilon = 1e-6f; | 1307 | const float epsilon = 1e-6f; |
| @@ -1399,6 +1405,11 @@ Tensor View(const Tensor& operand, const std::vector<int64_t>& shapes, const std | |||
| 1399 | result.GetStorage()->UpdateDynValidShape(validShape); | 1405 | result.GetStorage()->UpdateDynValidShape(validShape); |
| 1400 | std::vector<int64_t> newOffsetsConcrete = SymbolicScalar::Concrete(newOffsets, 0); | 1406 | std::vector<int64_t> newOffsetsConcrete = SymbolicScalar::Concrete(newOffsets, 0); |
| 1401 | op.SetOpAttribute(std::make_shared<ViewOpAttribute>(newOffsetsConcrete, newOffsets, validShape)); | 1407 | op.SetOpAttribute(std::make_shared<ViewOpAttribute>(newOffsetsConcrete, newOffsets, validShape)); |
| 1408 | + result.GetStorage()->SetAttr("ORIGINAL_SHAPE", operand.GetShape()); | ||
| 1409 | + const auto& operandDynVS2 = operand.GetStorage()->GetDynValidShape(); | ||
| 1410 | + if (!operandDynVS2.empty()) { | ||
| 1411 | + result.GetStorage()->SetAttr("ORIGINAL_DYN_VALID_SHAPE", operandDynVS2); | ||
| 1412 | + } | ||
| 1402 | return result; | 1413 | return result; |
| 1403 | } | 1414 | } |
| 1404 | 1415 | ||
| @@ -1429,6 +1440,11 @@ Tensor View(const Tensor& operand, const std::vector<int64_t>& shapes, | |||
| 1429 | std::vector<int64_t> newOffsetsConcrete = SymbolicScalar::Concrete(newOffsets, 0); | 1440 | std::vector<int64_t> newOffsetsConcrete = SymbolicScalar::Concrete(newOffsets, 0); |
| 1430 | op.SetOpAttribute(std::make_shared<ViewOpAttribute>(newOffsetsConcrete, newOffsets, newValidShapes)); | 1441 | op.SetOpAttribute(std::make_shared<ViewOpAttribute>(newOffsetsConcrete, newOffsets, newValidShapes)); |
| 1431 | result.GetStorage()->UpdateDynValidShape(newValidShapes); | 1442 | result.GetStorage()->UpdateDynValidShape(newValidShapes); |
| 1443 | + result.GetStorage()->SetAttr("ORIGINAL_SHAPE", operand.GetShape()); | ||
| 1444 | + const auto& operandDynVS3 = operand.GetStorage()->GetDynValidShape(); | ||
| 1445 | + if (!operandDynVS3.empty()) { | ||
| 1446 | + result.GetStorage()->SetAttr("ORIGINAL_DYN_VALID_SHAPE", operandDynVS3); | ||
| 1447 | + } | ||
| 1432 | return result; | 1448 | return result; |
| 1433 | } | 1449 | } |
| 1434 | 1450 | ||
| @@ -1865,6 +1865,16 @@ void GatherMaskBuildInOperationTileFunc(Function& function, const TileShape& til | |||
| 1865 | const std::vector<LogicalTensorPtr>& oOperand, const Operation& op) | 1865 | const std::vector<LogicalTensorPtr>& oOperand, const Operation& op) |
| 1866 | { | 1866 | { |
| 1867 | uint8_t patternMode = op.GetIntAttribute(OP_ATTR_PREFIX + "patternMode"); | 1867 | uint8_t patternMode = op.GetIntAttribute(OP_ATTR_PREFIX + "patternMode"); |
| 1868 | + if (patternMode >= 1 && patternMode <= 6) { | ||
| 1869 | + const auto& viewShape = iOperand[0]->GetShape(); | ||
| 1870 | + std::vector<int64_t> originalShape; | ||
| 1871 | + if (iOperand[0]->GetAttr("ORIGINAL_SHAPE", originalShape) && !originalShape.empty() && | ||
| 1872 | + originalShape.size() == viewShape.size() && originalShape.back() > 0 && viewShape.back() > 0) { | ||
| 1873 | + CHECK(VectorErrorCode::ERR_PARAM_INVALID, viewShape.back() >= originalShape.back()) | ||
| 1874 | + << "GatherMask requires the last axis of self.shape not to be split by view. " | ||
| 1875 | + << "self.shape last axis: " << originalShape.back() << ", viewshape last axis: " << viewShape.back(); | ||
| 1876 | + } | ||
| 1877 | + } | ||
| 1868 | TiledGatherMaskBuildIn(function, tileShape, iOperand[0], oOperand[0], patternMode); | 1878 | TiledGatherMaskBuildIn(function, tileShape, iOperand[0], oOperand[0], patternMode); |
| 1869 | } | 1879 | } |
| 1870 | 1880 | ||
| @@ -448,6 +448,12 @@ class JitCallableWrapper: | |||
| 448 | tensors, | 448 | tensors, |
| 449 | tensor_defs=None, | 449 | tensor_defs=None, |
| 450 | ) -> None: | 450 | ) -> None: |
| 451 | + from pypto.operation import _gathermask_checks, _view_input_ids, _view_input_names, _view_original_shapes | ||
| 452 | + _view_original_shapes.clear() | ||
| 453 | + _view_input_ids.clear() | ||
| 454 | + _view_input_names.clear() | ||
| 455 | + _gathermask_checks.clear() | ||
| 456 | + | ||
| 451 | if tensor_defs is not None: | 457 | if tensor_defs is not None: |
| 452 | self._check_input_defs_match_tensors(tensors, tensor_defs) | 458 | self._check_input_defs_match_tensors(tensors, tensor_defs) |
| 453 | pto_tensor = self._convert_tensors_with_metadata(tensors, tensor_defs) | 459 | pto_tensor = self._convert_tensors_with_metadata(tensors, tensor_defs) |
| @@ -463,6 +469,10 @@ class JitCallableWrapper: | |||
| 463 | **(self.kwargs or {}), | 469 | **(self.kwargs or {}), |
| 464 | ) | 470 | ) |
| 465 | 471 | ||
| 472 | + # Check GatherMask viewshape constraint with actual tensor shapes | ||
| 473 | + if tensor_defs is not None: | ||
| 474 | + self._check_gathermask_view_constraint(tensors, tensor_defs) | ||
| 475 | + | ||
| 466 | # Reset golden data after compilation | 476 | # Reset golden data after compilation |
| 467 | _pto_verify_datas.reset() | 477 | _pto_verify_datas.reset() |
| 468 | 478 | ||
| @@ -635,6 +645,40 @@ class JitCallableWrapper: | |||
| 635 | if key is not None: | 645 | if key is not None: |
| 636 | JitCallableWrapper._kernel_module_cache[key] = self.kmodule | 646 | JitCallableWrapper._kernel_module_cache[key] = self.kmodule |
| 637 | 647 | ||
| 648 | + def _check_gathermask_view_constraint( | ||
| 649 | + self, | ||
| 650 | + torch_tensors: list, | ||
| 651 | + tensor_defs: list, | ||
| 652 | + ) -> None: | ||
| 653 | + """Check GatherMask viewshape constraint with actual tensor shapes.""" | ||
| 654 | + from pypto.operation import _gathermask_checks | ||
| 655 | + if not _gathermask_checks: | ||
| 656 | + return | ||
| 657 | + | ||
| 658 | + name_to_shape = {} | ||
| 659 | + for tensor_def, torch_tensor in zip(tensor_defs, torch_tensors): | ||
| 660 | + try: | ||
| 661 | + base = tensor_def._base if hasattr(tensor_def, '_base') else tensor_def | ||
| 662 | + name = base.GetName() if hasattr(base, 'GetName') else '' | ||
| 663 | + if name: | ||
| 664 | + name_to_shape[name] = list(torch_tensor.shape) | ||
| 665 | + except (AttributeError, RuntimeError): | ||
| 666 | + pass | ||
| 667 | + | ||
| 668 | + for check in _gathermask_checks: | ||
| 669 | + input_name = check.get('input_tensor_name', '') | ||
| 670 | + viewshape_last = check['viewshape_last'] | ||
| 671 | + if input_name and input_name in name_to_shape and viewshape_last is not None: | ||
| 672 | + actual_shape = name_to_shape[input_name] | ||
| 673 | + actual_last = actual_shape[-1] | ||
| 674 | + if isinstance(actual_last, int) and isinstance(viewshape_last, int) and viewshape_last < actual_last: | ||
| 675 | + raise FeError( | ||
| 676 | + RuntimeError( | ||
| 677 | + f"GatherMask requires the last axis of self.shape not to be split by view. " | ||
| 678 | + f"self.shape last axis: {actual_last}, viewshape last axis: {viewshape_last}" | ||
| 679 | + ) | ||
| 680 | + ) | ||
| 681 | + | ||
| 638 | def _execute_kernel( | 682 | def _execute_kernel( |
| 639 | self, | 683 | self, |
| 640 | torch_tensors: list, | 684 | torch_tensors: list, |
| @@ -579,4 +579,19 @@ def gathermask(self: Tensor, pattern_mode: int) -> Tensor: | |||
| 579 | 579 | ||
| 580 | """ | 580 | """ |
| 581 | 581 | ||
| 582 | + if 1 <= pattern_mode <= 6: | ||
| 583 | + from ..operation import _gathermask_checks, _view_input_ids, _view_input_names, _view_original_shapes | ||
| 584 | + self_id = self.Id() if hasattr(self, 'Id') else self._base.Id() | ||
| 585 | + orig_view_shape = _view_original_shapes.get(self_id) | ||
| 586 | + orig_input_id = _view_input_ids.get(self_id) | ||
| 587 | + orig_input_name = _view_input_names.get(self_id) | ||
| 588 | + if orig_view_shape is not None: | ||
| 589 | + _gathermask_checks.append({ | ||
| 590 | + 'view_tensor_id': self_id, | ||
| 591 | + 'input_tensor_id': orig_input_id, | ||
| 592 | + 'input_tensor_name': orig_input_name, | ||
| 593 | + 'viewshape_last': orig_view_shape[-1] if orig_view_shape else None, | ||
| 594 | + 'pattern_mode': pattern_mode, | ||
| 595 | + }) | ||
| 596 | + | ||
| 582 | return pypto_impl.GatherMask(self, pattern_mode) | 597 | return pypto_impl.GatherMask(self, pattern_mode) |
| @@ -10,7 +10,7 @@ | |||
| 10 | # ----------------------------------------------------------------------------------------------------------- | 10 | # ----------------------------------------------------------------------------------------------------------- |
| 11 | """ """ | 11 | """ """ |
| 12 | 12 | ||
| 13 | -from typing import List, Optional, Sequence, Tuple, Union, overload | 13 | +from typing import Dict, List, Optional, Sequence, Tuple, Union, overload |
| 14 | 14 | ||
| 15 | from . import pypto_impl | 15 | from . import pypto_impl |
| 16 | from ._op_wrapper import op_wrapper | 16 | from ._op_wrapper import op_wrapper |
| @@ -20,6 +20,11 @@ from .error import FeError | |||
| 20 | from .symbolic_scalar import SymbolicScalar | 20 | from .symbolic_scalar import SymbolicScalar |
| 21 | from .tensor import Tensor | 21 | from .tensor import Tensor |
| 22 | 22 | ||
| 23 | +_view_original_shapes: Dict[int, list] = {} | ||
| 24 | +_view_input_ids: Dict[int, int] = {} | ||
| 25 | +_view_input_names: Dict[int, str] = {} | ||
| 26 | +_gathermask_checks: list = [] | ||
| 27 | + | ||
| 23 | 28 | ||
| 24 | @overload | 29 | @overload |
| 25 | def assemble( | 30 | def assemble( |
| @@ -375,6 +380,27 @@ def view( | |||
| 375 | if dtype is not None: | 380 | if dtype is not None: |
| 376 | return pypto_impl.View(input, dtype) | 381 | return pypto_impl.View(input, dtype) |
| 377 | elif valid_shape is None: | 382 | elif valid_shape is None: |
| 378 | - return pypto_impl.View(input, shape, offsets) | 383 | + result = pypto_impl.View(input, shape, offsets) |
| 379 | else: | 384 | else: |
| 380 | - return pypto_impl.View(input, shape, to_syms(valid_shape), to_syms(offsets)) | 385 | + result = pypto_impl.View(input, shape, to_syms(valid_shape), to_syms(offsets)) |
| 386 | + | ||
| 387 | + def _get_tensor_id(t): | ||
| 388 | + if hasattr(t, '_base'): | ||
| 389 | + return t._base.Id() | ||
| 390 | + if hasattr(t, 'Id'): | ||
| 391 | + return t.Id() | ||
| 392 | + return t.id() | ||
| 393 | + | ||
| 394 | + def _get_tensor_name(t): | ||
| 395 | + if hasattr(t, '_base'): | ||
| 396 | + base = t._base | ||
| 397 | + else: | ||
| 398 | + base = t | ||
| 399 | + if hasattr(base, 'GetName'): | ||
| 400 | + return base.GetName() | ||
| 401 | + return '' | ||
| 402 | + | ||
| 403 | + _view_original_shapes[result.Id()] = list(shape) | ||
| 404 | + _view_input_ids[result.Id()] = _get_tensor_id(input) | ||
| 405 | + _view_input_names[result.Id()] = _get_tensor_name(input) | ||
| 406 | + return result | ||
| @@ -0,0 +1,167 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# coding: utf-8 | ||
| 3 | +# Copyright (c) 2025 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software and you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 11 | +"""UT for GatherMask viewshape constraint check.""" | ||
| 12 | + | ||
| 13 | +import pytest | ||
| 14 | + | ||
| 15 | +import pypto | ||
| 16 | +from pypto.error import FeError | ||
| 17 | +from pypto.operation import ( | ||
| 18 | + _gathermask_checks, | ||
| 19 | + _view_input_ids, | ||
| 20 | + _view_input_names, | ||
| 21 | + _view_original_shapes, | ||
| 22 | +) | ||
| 23 | + | ||
| 24 | + | ||
| 25 | +def _init_tensor(shape, dtype=pypto.DT_FP32, name="input"): | ||
| 26 | + return pypto.tensor(shape, dtype, name) | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +def _get_id(t): | ||
| 30 | + if hasattr(t, 'Id'): | ||
| 31 | + return t.Id() | ||
| 32 | + return t._base.Id() | ||
| 33 | + | ||
| 34 | + | ||
| 35 | +def test_view_records_original_shape(): | ||
| 36 | + a = _init_tensor((8, 32), name="test_input") | ||
| 37 | + _view_original_shapes.clear() | ||
| 38 | + _view_input_ids.clear() | ||
| 39 | + _view_input_names.clear() | ||
| 40 | + with pypto.function("MAIN", a): | ||
| 41 | + result = pypto.view(a, [8, 16], [0, 0]) | ||
| 42 | + rid = _get_id(result) | ||
| 43 | + assert rid in _view_original_shapes | ||
| 44 | + assert _view_original_shapes[rid] == [8, 16] | ||
| 45 | + assert rid in _view_input_ids | ||
| 46 | + assert rid in _view_input_names | ||
| 47 | + | ||
| 48 | + | ||
| 49 | +def test_view_with_valid_shape_records(): | ||
| 50 | + a = _init_tensor((8, 32), name="vs_input") | ||
| 51 | + _view_original_shapes.clear() | ||
| 52 | + _view_input_ids.clear() | ||
| 53 | + _view_input_names.clear() | ||
| 54 | + with pypto.function("MAIN", a): | ||
| 55 | + result = pypto.view(a, [8, 16], valid_shape=[8, 16], offsets=[0, 0]) | ||
| 56 | + rid = _get_id(result) | ||
| 57 | + assert rid in _view_original_shapes | ||
| 58 | + assert _view_original_shapes[rid] == [8, 16] | ||
| 59 | + | ||
| 60 | + | ||
| 61 | +def test_gathermask_records_check(): | ||
| 62 | + a = _init_tensor((8, 32), name="gm_input") | ||
| 63 | + _view_original_shapes.clear() | ||
| 64 | + _view_input_ids.clear() | ||
| 65 | + _view_input_names.clear() | ||
| 66 | + _gathermask_checks.clear() | ||
| 67 | + with pypto.function("MAIN", a): | ||
| 68 | + view_result = pypto.view(a, [8, 32], [0, 0]) | ||
| 69 | + pypto.set_vec_tile_shapes(8, 32) | ||
| 70 | + pypto.gathermask(view_result, 1) | ||
| 71 | + assert len(_gathermask_checks) == 1 | ||
| 72 | + check = _gathermask_checks[0] | ||
| 73 | + assert check["viewshape_last"] == 32 | ||
| 74 | + assert check["pattern_mode"] == 1 | ||
| 75 | + | ||
| 76 | + | ||
| 77 | +def test_gathermask_mode7_no_check(): | ||
| 78 | + a = _init_tensor((8, 32), name="mode7_input") | ||
| 79 | + _view_original_shapes.clear() | ||
| 80 | + _view_input_ids.clear() | ||
| 81 | + _view_input_names.clear() | ||
| 82 | + _gathermask_checks.clear() | ||
| 83 | + with pypto.function("MAIN", a): | ||
| 84 | + view_result = pypto.view(a, [8, 16], [0, 0]) | ||
| 85 | + pypto.set_vec_tile_shapes(8, 16) | ||
| 86 | + pypto.gathermask(view_result, 7) | ||
| 87 | + assert len(_gathermask_checks) == 0 | ||
| 88 | + | ||
| 89 | + | ||
| 90 | +def test_gathermask_no_view_no_check(): | ||
| 91 | + a = _init_tensor((8, 32), name="noview_input") | ||
| 92 | + _view_original_shapes.clear() | ||
| 93 | + _view_input_ids.clear() | ||
| 94 | + _view_input_names.clear() | ||
| 95 | + _gathermask_checks.clear() | ||
| 96 | + with pypto.function("MAIN", a): | ||
| 97 | + pypto.set_vec_tile_shapes(8, 32) | ||
| 98 | + pypto.gathermask(a, 1) | ||
| 99 | + assert len(_gathermask_checks) == 0 | ||
| 100 | + | ||
| 101 | + | ||
| 102 | +def test_check_gathermask_view_constraint_blocks_violation(): | ||
| 103 | + from pypto.frontend.parser.entry import JitCallableWrapper | ||
| 104 | + | ||
| 105 | + class FakeTensorDef: | ||
| 106 | + def __init__(self, name, shape): | ||
| 107 | + self._base = type("FakeBase", (), {"GetName": lambda self: name, "Id": lambda self: 0})() | ||
| 108 | + | ||
| 109 | + class FakeWrapper: | ||
| 110 | + pass | ||
| 111 | + | ||
| 112 | + _gathermask_checks.clear() | ||
| 113 | + _gathermask_checks.append({ | ||
| 114 | + "view_tensor_id": 1, | ||
| 115 | + "input_tensor_id": 0, | ||
| 116 | + "input_tensor_name": "violation_input", | ||
| 117 | + "viewshape_last": 16, | ||
| 118 | + "pattern_mode": 1, | ||
| 119 | + }) | ||
| 120 | + | ||
| 121 | + tensor_defs = [FakeTensorDef("violation_input", (8, 32))] | ||
| 122 | + torch_tensors = [type("FakeTorch", (), {"shape": [8, 32]})()] | ||
| 123 | + | ||
| 124 | + wrapper = FakeWrapper() | ||
| 125 | + with pytest.raises(FeError, match="split by view"): | ||
| 126 | + JitCallableWrapper._check_gathermask_view_constraint( | ||
| 127 | + wrapper, torch_tensors, tensor_defs | ||
| 128 | + ) | ||
| 129 | + | ||
| 130 | + | ||
| 131 | +def test_check_gathermask_view_constraint_passes_normal(): | ||
| 132 | + from pypto.frontend.parser.entry import JitCallableWrapper | ||
| 133 | + | ||
| 134 | + class FakeTensorDef: | ||
| 135 | + def __init__(self, name, shape): | ||
| 136 | + self._base = type("FakeBase", (), {"GetName": lambda self: name, "Id": lambda self: 0})() | ||
| 137 | + | ||
| 138 | + class FakeWrapper: | ||
| 139 | + pass | ||
| 140 | + | ||
| 141 | + _gathermask_checks.clear() | ||
| 142 | + _gathermask_checks.append({ | ||
| 143 | + "view_tensor_id": 1, | ||
| 144 | + "input_tensor_id": 0, | ||
| 145 | + "input_tensor_name": "normal_input", | ||
| 146 | + "viewshape_last": 32, | ||
| 147 | + "pattern_mode": 1, | ||
| 148 | + }) | ||
| 149 | + | ||
| 150 | + tensor_defs = [FakeTensorDef("normal_input", (8, 32))] | ||
| 151 | + torch_tensors = [type("FakeTorch", (), {"shape": [8, 32]})()] | ||
| 152 | + | ||
| 153 | + wrapper = FakeWrapper() | ||
| 154 | + JitCallableWrapper._check_gathermask_view_constraint( | ||
| 155 | + wrapper, torch_tensors, tensor_defs | ||
| 156 | + ) | ||
| 157 | + | ||
| 158 | + | ||
| 159 | +def test_check_gathermask_view_constraint_empty_checks(): | ||
| 160 | + from pypto.frontend.parser.entry import JitCallableWrapper | ||
| 161 | + | ||
| 162 | + class FakeWrapper: | ||
| 163 | + pass | ||
| 164 | + | ||
| 165 | + _gathermask_checks.clear() | ||
| 166 | + wrapper = FakeWrapper() | ||
| 167 | + JitCallableWrapper._check_gathermask_view_constraint(wrapper, [], []) | ||