Merged
fix(front): fix issue #3272 and #3274 add assemble parameter validation #6170
HuYiShengAdd on Sep 11
fix(front): fix issue #3272 and #3274 add assemble parameter validation #6170
Merged
Merged fromHuYiSheng01/Hys_pypto9.2.0-fix-3272-3274intocann/pypto9.2.0
Total: 4 files changed+114-5
| @@ -43,7 +43,7 @@ view(input: Tensor, shape: List[int] = None, offsets: List[Union[int, SymbolicSc | |||
| 43 | 43 | ||
| 44 | - **需要valid_shape时必须用pypto.view**:当需要指定`valid_shape`(动态有效数据大小)时,不能使用`[]`切片语法,必须使用显式的`pypto.view`接口 | 44 | - **需要valid_shape时必须用pypto.view**:当需要指定`valid_shape`(动态有效数据大小)时,不能使用`[]`切片语法,必须使用显式的`pypto.view`接口 |
| 45 | - 输入张量input和输入shape的维度数量需要一致。 | 45 | - 输入张量input和输入shape的维度数量需要一致。 |
| 46 | -- **view的写入与源input相互隔离**:对view的写入(含view[:] = ...)只作用于view自身,不会写回源input;而view的读取与源input保持联动,input后续被修改,读取view可感知修改。若需要将数据写回源Tensor(例如在循环中向persistent buffer分片累积写入的场景),请使用pypto.assemble(value, offsets, dest)。 | 46 | +- **view创建后与源input相互独立**:view创建后即成为独立的数据拷贝,对view的读写(含view[:] = ...)只作用于view自身,不会写回源input,也不会感知源input的后续修改。若需要将数据写回源Tensor(例如在循环中向persistent buffer分片累积写入的场景),请使用pypto.assemble(value, offsets, dest)。 |
| 47 | 47 | ||
| 48 | ## 调用示例 | 48 | ## 调用示例 |
| 49 | 49 | ||
| @@ -10,8 +10,10 @@ | |||
| 10 | # ----------------------------------------------------------------------------------------------------------- | 10 | # ----------------------------------------------------------------------------------------------------------- |
| 11 | """ """ | 11 | """ """ |
| 12 | 12 | ||
| 13 | +import collections.abc | ||
| 13 | import functools | 14 | import functools |
| 14 | import sys | 15 | import sys |
| 16 | +import typing | ||
| 15 | from typing import List, Sequence, Union | 17 | from typing import List, Sequence, Union |
| 16 | 18 | ||
| 17 | from . import pypto_impl | 19 | from . import pypto_impl |
| @@ -84,6 +86,34 @@ def to_syms(value: Union[Sequence[int], Sequence[SymbolicScalar]]) -> List[pypto | |||
| 84 | return [to_sym(v) for v in value] | 86 | return [to_sym(v) for v in value] |
| 85 | 87 | ||
| 86 | 88 | ||
| 89 | +def check_type(value, expect_type, arg_name, expect_len=None): | ||
| 90 | + origin = typing.get_origin(expect_type) | ||
| 91 | + if origin is None: | ||
| 92 | + origin_types = expect_type if isinstance(expect_type, tuple) else (expect_type,) | ||
| 93 | + elem_types = None | ||
| 94 | + else: | ||
| 95 | + origin_map = {list: (list,), collections.abc.Sequence: (list, tuple), tuple: (tuple,), dict: (dict,)} | ||
| 96 | + origin_types = origin_map.get(origin, (origin,)) | ||
| 97 | + elem_types = typing.get_args(expect_type) | ||
| 98 | + if not isinstance(value, origin_types): | ||
| 99 | + names = " or ".join(t.__name__ for t in origin_types) | ||
| 100 | + raise TypeError(f"{arg_name} must be {names}, got {type(value).__name__}") | ||
| 101 | + if expect_len is not None and len(value) != expect_len: | ||
| 102 | + raise TypeError(f"{arg_name} must have length {expect_len}, got {len(value)}") | ||
| 103 | + if not elem_types: | ||
| 104 | + return | ||
| 105 | + for i, item in enumerate(value): | ||
| 106 | + spec = elem_types[i] if len(elem_types) == 2 and origin_types == (tuple,) else elem_types[0] | ||
| 107 | + if typing.get_origin(spec) is typing.Union: | ||
| 108 | + allowed = typing.get_args(spec) | ||
| 109 | + if not isinstance(item, allowed): | ||
| 110 | + names = " or ".join(t.__name__ for t in allowed) | ||
| 111 | + raise TypeError(f"{arg_name}[{i}] must be {names}, got {type(item).__name__}") | ||
| 112 | + elif isinstance(spec, type) and typing.get_origin(spec) is None: | ||
| 113 | + if not isinstance(item, spec): | ||
| 114 | + raise TypeError(f"{arg_name}[{i}] must be {spec.__name__}, got {type(item).__name__}") | ||
| 115 | + | ||
| 116 | + | ||
| 87 | def ceildiv(a: SymInt, b: SymInt) -> SymInt: | 117 | def ceildiv(a: SymInt, b: SymInt) -> SymInt: |
| 88 | return (a + b - 1) // b | 118 | return (a + b - 1) // b |
| 89 | 119 | ||
| @@ -14,7 +14,7 @@ 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 |
| 17 | -from ._utils import to_syms | 17 | +from ._utils import check_type, source_location, to_syms |
| 18 | from .enum import AtomicRMWMode, DataType | 18 | from .enum import AtomicRMWMode, DataType |
| 19 | from .error import FeError | 19 | from .error import FeError |
| 20 | from .symbolic_scalar import SymbolicScalar | 20 | from .symbolic_scalar import SymbolicScalar |
| @@ -118,16 +118,35 @@ def assemble( | |||
| 118 | ... | 118 | ... |
| 119 | 119 | ||
| 120 | 120 | ||
| 121 | +@source_location | ||
| 121 | def assemble(*args, parallel: bool = False) -> None: | 122 | def assemble(*args, parallel: bool = False) -> None: |
| 122 | - if isinstance(args[0], Sequence): | 123 | + if len(args) == 3: |
| 124 | + src, offsets, dst = args | ||
| 125 | + check_type(src, Tensor, "assemble(): src") | ||
| 126 | + check_type(offsets, Sequence[Union[int, SymbolicScalar]], "assemble(): offsets") | ||
| 127 | + check_type(dst, Tensor, "assemble(): dst") | ||
| 128 | + pypto_impl.Assemble(src.base(), to_syms(offsets), dst.base(), parallel) | ||
| 129 | + elif len(args) == 2: | ||
| 123 | srcs, dst = args | 130 | srcs, dst = args |
| 131 | + if not isinstance(srcs, (list, tuple)): | ||
| 132 | + hint = " If you intend to use the single-source form (src, offsets, dst)," \ | ||
| 133 | + " you are missing the 'offsets' argument." if isinstance(srcs, Tensor) else "" | ||
| 134 | + raise TypeError(f"assemble(): srcs must be list or tuple, got {type(srcs).__name__}.{hint}") | ||
| 124 | if len(srcs) == 0: | 135 | if len(srcs) == 0: |
| 125 | return | 136 | return |
| 137 | + check_type(dst, Tensor, "assemble(): dst") | ||
| 138 | + for idx, item in enumerate(srcs): | ||
| 139 | + check_type(item, (list, tuple), f"assemble(): srcs[{idx}]", expect_len=2) | ||
| 140 | + src_item, offsets_item = item | ||
| 141 | + check_type(src_item, Tensor, f"assemble(): srcs[{idx}][0]") | ||
| 142 | + check_type(offsets_item, Sequence[Union[int, SymbolicScalar]], f"assemble(): srcs[{idx}][1]") | ||
| 126 | srcs = [(src.base(), to_syms(offsets)) for src, offsets in srcs] | 143 | srcs = [(src.base(), to_syms(offsets)) for src, offsets in srcs] |
| 127 | pypto_impl.Assemble(srcs, dst.base(), parallel) | 144 | pypto_impl.Assemble(srcs, dst.base(), parallel) |
| 128 | else: | 145 | else: |
| 129 | - src, offsets, dst = args | 146 | + raise TypeError( |
| 130 | - pypto_impl.Assemble(src.base(), to_syms(offsets), dst.base(), parallel) | 147 | + f"assemble() expects 3 positional arguments (src, offsets, dst) or " |
| 148 | + f"2 positional arguments (srcs, dst), but got {len(args)}." | ||
| 149 | + ) | ||
| 131 | 150 | ||
| 132 | 151 | ||
| 133 | def min(a: "SymbolicScalar | int", b: "SymbolicScalar | int") -> "SymbolicScalar": | 152 | def min(a: "SymbolicScalar | int", b: "SymbolicScalar | int") -> "SymbolicScalar": |
| @@ -11,11 +11,15 @@ | |||
| 11 | """Test pypto.frontend.jit kernel dynamic shape error behavior.""" | 11 | """Test pypto.frontend.jit kernel dynamic shape error behavior.""" |
| 12 | 12 | ||
| 13 | import logging | 13 | import logging |
| 14 | +from typing import Sequence, Union | ||
| 14 | 15 | ||
| 15 | import pytest | 16 | import pytest |
| 16 | import torch | 17 | import torch |
| 17 | 18 | ||
| 18 | import pypto | 19 | import pypto |
| 20 | +from pypto._utils import check_type | ||
| 21 | +from pypto.symbolic_scalar import SymbolicScalar | ||
| 22 | +from pypto.tensor import Tensor | ||
| 19 | 23 | ||
| 20 | logging.basicConfig(level=logging.INFO, format="", force=True) | 24 | logging.basicConfig(level=logging.INFO, format="", force=True) |
| 21 | SIM_RUNTIME_OPTIONS = {"run_mode": pypto.RunMode.SIM} | 25 | SIM_RUNTIME_OPTIONS = {"run_mode": pypto.RunMode.SIM} |
| @@ -151,6 +155,58 @@ def test_view_valid_shape_reshape_inplace_error(): | |||
| 151 | kernel_view_valid_shape_reshape_inplace_error(q, out) | 155 | kernel_view_valid_shape_reshape_inplace_error(q, out) |
| 152 | 156 | ||
| 153 | 157 | ||
| 158 | +def test_assemble_arg_count_and_hint(): | ||
| 159 | + src = pypto.Tensor([4, 16], pypto.DT_INT32) | ||
| 160 | + dst = pypto.Tensor([4, 32], pypto.DT_INT32) | ||
| 161 | + with pytest.raises(Exception, match="but got 0"): | ||
| 162 | + pypto.assemble() | ||
| 163 | + with pytest.raises(Exception, match="but got 4"): | ||
| 164 | + pypto.assemble(src, [0, 0], dst, True) | ||
| 165 | + with pytest.raises(Exception, match="missing the 'offsets' argument"): | ||
| 166 | + pypto.assemble(src, dst) | ||
| 167 | + | ||
| 168 | + | ||
| 169 | +def test_assemble_valid_calls_not_blocked(): | ||
| 170 | + @pypto.frontend.jit(runtime_options=SIM_RUNTIME_OPTIONS) | ||
| 171 | + def k_single(x: pypto.Tensor([pypto.STATIC, pypto.STATIC], pypto.DT_INT32), | ||
| 172 | + y: pypto.Tensor([pypto.STATIC, pypto.STATIC], pypto.DT_INT32)): | ||
| 173 | + pypto.set_vec_tile_shapes(32, 32) | ||
| 174 | + pypto.assemble(x, [0, 0], y) | ||
| 175 | + | ||
| 176 | + @pypto.frontend.jit(runtime_options=SIM_RUNTIME_OPTIONS) | ||
| 177 | + def k_multi(x: pypto.Tensor([pypto.STATIC, pypto.STATIC], pypto.DT_INT32), | ||
| 178 | + y: pypto.Tensor([pypto.STATIC, pypto.STATIC], pypto.DT_INT32)): | ||
| 179 | + pypto.set_vec_tile_shapes(32, 32) | ||
| 180 | + pypto.assemble([(x, [0, 0])], y, parallel=True) | ||
| 181 | + | ||
| 182 | + x = torch.ones(4, 16, dtype=torch.int32) | ||
| 183 | + y = torch.zeros(4, 32, dtype=torch.int32) | ||
| 184 | + k_single(x, y) | ||
| 185 | + k_multi(x, y) | ||
| 186 | + | ||
| 187 | + | ||
| 188 | +def test_check_type_pass(): | ||
| 189 | + check_type(pypto.Tensor([4, 16], pypto.DT_INT32), Tensor, "src") | ||
| 190 | + check_type([0, 1], (list, tuple), "offsets") | ||
| 191 | + check_type((0, 1), (list, tuple), "offsets") | ||
| 192 | + check_type([0, 1], Sequence[int], "offsets") | ||
| 193 | + check_type([0, SymbolicScalar(1)], Sequence[Union[int, SymbolicScalar]], "offsets") | ||
| 194 | + check_type([1, 2], (list, tuple), "pair", expect_len=2) | ||
| 195 | + | ||
| 196 | + | ||
| 197 | +def test_check_type_fail(): | ||
| 198 | + with pytest.raises(TypeError, match="src.*Tensor.*int"): | ||
| 199 | + check_type(42, Tensor, "src") | ||
| 200 | + with pytest.raises(TypeError, match="offsets.*list or tuple.*int"): | ||
| 201 | + check_type(42, (list, tuple), "offsets") | ||
| 202 | + with pytest.raises(TypeError, match="offsets.*list or tuple.*int"): | ||
| 203 | + check_type(42, Sequence[int], "offsets") | ||
| 204 | + with pytest.raises(TypeError, match="offsets\\[1\\].*int.*float"): | ||
| 205 | + check_type([0, 0.5], Sequence[int], "offsets") | ||
| 206 | + with pytest.raises(TypeError, match="pair.*length 2"): | ||
| 207 | + check_type([1, 2, 3], (list, tuple), "pair", expect_len=2) | ||
| 208 | + | ||
| 209 | + | ||
| 154 | # ------------------------------------------------------------------------------ | 210 | # ------------------------------------------------------------------------------ |
| 155 | # Entry point | 211 | # Entry point |
| 156 | # ------------------------------------------------------------------------------ | 212 | # ------------------------------------------------------------------------------ |
| @@ -162,5 +218,9 @@ if __name__ == "__main__": | |||
| 162 | test_assemble_dynamic_shape_error() | 218 | test_assemble_dynamic_shape_error() |
| 163 | test_dynamic_reshape_error() | 219 | test_dynamic_reshape_error() |
| 164 | test_view_valid_shape_reshape_inplace_error() | 220 | test_view_valid_shape_reshape_inplace_error() |
| 221 | + test_check_type_pass() | ||
| 222 | + test_check_type_fail() | ||
| 223 | + test_assemble_arg_count_and_hint() | ||
| 224 | + test_assemble_valid_calls_not_blocked() | ||
| 165 | 225 | ||
| 166 | logging.info("All dynamic shape error tests passed.") | 226 | logging.info("All dynamic shape error tests passed.") |