Merged
fix(operation): Add missing arch and format constraint checks for matmul/scaled_mm #5865
fix(operation): Add missing arch and format constraint checks for matmul/scaled_mm #5865
Merged
shi-dingkunAdd on Sep 2
Total: 4 files changed+306-67
@@ -106,7 +106,8 @@ void
106 106 
107- 多核切K约束107- 多核切K约束
108 108 
109- - 仅支持2维/3维/4维矩阵多核切K。109+ - `pypto.matmul`支持2维/3维/4维矩阵多核切K。
110+ - `pypto.scaled_mm`仅支持2维矩阵多核切K,3维/4维矩阵不支持。
110 - 多核切K场景只支持out\_dtype数据类型为DT\_FP32或DT\_INT32。111 - 多核切K场景只支持out\_dtype数据类型为DT\_FP32或DT\_INT32。
111 - Bias/FixPipe(包含ReLU)场景不支持叠加多核切K功能。112 - Bias/FixPipe(包含ReLU)场景不支持叠加多核切K功能。
112 113 
@@ -1,6 +1,6 @@
1#!/usr/bin/env python31#!/usr/bin/env python3
2# coding: utf-82# coding: utf-8
3-# Copyright (c) 2025 Huawei Technologies Co., Ltd.3+# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd.
4# This program is free software, you can redistribute it and/or modify it under the terms and conditions of4# This program is free software, 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").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.6# Please refer to the License for details. You may not use this file except in compliance with the License.
@@ -101,26 +101,26 @@ def matmul(input, mat2, out_dtype, *, a_trans=False, b_trans=False, c_matrix_nz=
101 b = pypto.tensor((32, 64), pypto.DT_FP16, "tensor_b")101 b = pypto.tensor((32, 64), pypto.DT_FP16, "tensor_b")
102 bias = pypto.tensor((1, 64), pypto.DT_FP16, "tensor_bias")102 bias = pypto.tensor((1, 64), pypto.DT_FP16, "tensor_bias")
103 extend_params = {'bias_tensor': bias}103 extend_params = {'bias_tensor': bias}
104- pypto.matmul(a, b, pypto.DT_BF16, extend_params=extend_params)104+ pypto.matmul(a, b, pypto.DT_FP16, extend_params=extend_params)
105 105 
106 # With dequantization (scale)106 # With dequantization (scale)
107 a = pypto.tensor((16, 32), pypto.DT_INT8, "tensor_a")107 a = pypto.tensor((16, 32), pypto.DT_INT8, "tensor_a")
108 b = pypto.tensor((32, 64), pypto.DT_INT8, "tensor_b")108 b = pypto.tensor((32, 64), pypto.DT_INT8, "tensor_b")
109 extend_params = {'scale': 0.2}109 extend_params = {'scale': 0.2}
110- pypto.matmul(a, b, pypto.DT_BF16, extend_params=extend_params)110+ pypto.matmul(a, b, pypto.DT_FP16, extend_params=extend_params)
111 111 
112 # With dequantization (scale & ReLU)112 # With dequantization (scale & ReLU)
113 a = pypto.tensor((16, 32), pypto.DT_INT8, "tensor_a")113 a = pypto.tensor((16, 32), pypto.DT_INT8, "tensor_a")
114 b = pypto.tensor((32, 64), pypto.DT_INT8, "tensor_b")114 b = pypto.tensor((32, 64), pypto.DT_INT8, "tensor_b")
115 extend_params = {'scale': 0.2, 'relu_type': pypto.ReLuType.RELU}115 extend_params = {'scale': 0.2, 'relu_type': pypto.ReLuType.RELU}
116- pypto.matmul(a, b, pypto.DT_BF16, extend_params=extend_params)116+ pypto.matmul(a, b, pypto.DT_FP16, extend_params=extend_params)
117 117 
118 # With dequantization (scale_tensor & ReLU)118 # With dequantization (scale_tensor & ReLU)
119 a = pypto.tensor((16, 32), pypto.DT_INT8, "tensor_a")119 a = pypto.tensor((16, 32), pypto.DT_INT8, "tensor_a")
120 b = pypto.tensor((32, 64), pypto.DT_INT8, "tensor_b")120 b = pypto.tensor((32, 64), pypto.DT_INT8, "tensor_b")
121 scale_tensor = pypto.tensor((1, 64), pypto.DT_UINT64, "tensor_scale")121 scale_tensor = pypto.tensor((1, 64), pypto.DT_UINT64, "tensor_scale")
122 extend_params = {'scale_tensor': scale_tensor, 'relu_type': pypto.ReLuType.RELU}122 extend_params = {'scale_tensor': scale_tensor, 'relu_type': pypto.ReLuType.RELU}
123- pypto.matmul(a, b, pypto.DT_BF16, extend_params=extend_params)123+ pypto.matmul(a, b, pypto.DT_FP16, extend_params=extend_params)
124 124 
125 # TF32 matrix multiplication125 # TF32 matrix multiplication
126 a = pypto.tensor((16, 32), pypto.DT_FP32, "tensor_a")126 a = pypto.tensor((16, 32), pypto.DT_FP32, "tensor_a")
@@ -128,7 +128,7 @@ def matmul(input, mat2, out_dtype, *, a_trans=False, b_trans=False, c_matrix_nz=
128 extend_params = {'trans_mode': pypto.TransMode.CAST_ROUND}128 extend_params = {'trans_mode': pypto.TransMode.CAST_ROUND}
129 pypto.matmul(a, b, pypto.DT_FP32, extend_params=extend_params)129 pypto.matmul(a, b, pypto.DT_FP32, extend_params=extend_params)
130 """130 """
131- __validate_inputs(input, mat2, out_dtype, [a_trans, b_trans, c_matrix_nz, extend_params])131+ __validate_inputs(input, mat2, out_dtype, [a_trans, b_trans, c_matrix_nz, extend_params], INPUT_COMBOS)
132 if input.Dim() == 2:132 if input.Dim() == 2:
133 if extend_params is not None:133 if extend_params is not None:
134 extend_params = pypto_impl.MatmulExtendParam(**__convert_matmul_extend_params(extend_params))134 extend_params = pypto_impl.MatmulExtendParam(**__convert_matmul_extend_params(extend_params))
@@ -260,9 +260,10 @@ def scaled_mm(
260 extend_params = {'bias_tensor': bias}260 extend_params = {'bias_tensor': bias}
261 pypto.scaled_mm(a, b, pypto.DT_FP16, a_scale, b_scale, extend_params=extend_params)261 pypto.scaled_mm(a, b, pypto.DT_FP16, a_scale, b_scale, extend_params=extend_params)
262 """262 """
263- __validate_inputs(mat_a, mat_b, out_dtype, [a_trans, b_trans, c_matrix_nz, extend_params])263+ __validate_inputs(mat_a, mat_b, out_dtype, [a_trans, b_trans, c_matrix_nz, extend_params], MX_INPUT_COMBOS)
264 __validate_scaled_inputs(mat_a, mat_b, scale_a, scale_b, extend_params)264 __validate_scaled_inputs(mat_a, mat_b, scale_a, scale_b, extend_params)
265 __validate_scaled_shape(mat_a, mat_b, scale_a, scale_b, [a_trans, b_trans, scale_a_trans, scale_b_trans])265 __validate_scaled_shape(mat_a, mat_b, scale_a, scale_b, [a_trans, b_trans, scale_a_trans, scale_b_trans])
266+ __validate_out_dtype(mat_a.GetDataType(), out_dtype, extend_params, MX_BASIC_OUT_DTYPES)
266 267 
267 if mat_a.Dim() == 2:268 if mat_a.Dim() == 2:
268 if extend_params is not None:269 if extend_params is not None:
@@ -306,6 +307,73 @@ def scaled_mm(
306 )307 )
307 308 
308 309 
310+A2A3_ARCHS = ("DAV_1001", "DAV_2201")
311+ 
312+# 封闭白名单:输入组合不在表内一律拒绝(来源:接口文档表3输入列)
313+INPUT_COMBOS = {
314+ (pypto_impl.DataType.DT_FP16, pypto_impl.DataType.DT_FP16),
315+ (pypto_impl.DataType.DT_BF16, pypto_impl.DataType.DT_BF16),
316+ (pypto_impl.DataType.DT_FP32, pypto_impl.DataType.DT_FP32),
317+ (pypto_impl.DataType.DT_INT8, pypto_impl.DataType.DT_INT8),
318+ (pypto_impl.DataType.DT_FP8E5M2, pypto_impl.DataType.DT_FP8E5M2),
319+ (pypto_impl.DataType.DT_FP8E5M2, pypto_impl.DataType.DT_FP8E4M3),
320+ (pypto_impl.DataType.DT_FP8E4M3, pypto_impl.DataType.DT_FP8E5M2),
321+ (pypto_impl.DataType.DT_FP8E4M3, pypto_impl.DataType.DT_FP8E4M3),
322+ (pypto_impl.DataType.DT_HF8, pypto_impl.DataType.DT_HF8),
323+}
324+ 
325+# 封闭白名单:输入组合不在表内一律拒绝(来源:scaled_mm文档表3输入列)
326+MX_INPUT_COMBOS = {
327+ (pypto_impl.DataType.DT_FP8E5M2, pypto_impl.DataType.DT_FP8E5M2),
328+ (pypto_impl.DataType.DT_FP8E5M2, pypto_impl.DataType.DT_FP8E4M3),
329+ (pypto_impl.DataType.DT_FP8E4M3, pypto_impl.DataType.DT_FP8E5M2),
330+ (pypto_impl.DataType.DT_FP8E4M3, pypto_impl.DataType.DT_FP8E4M3),
331+ (pypto_impl.DataType.DT_FP4_E2M1, pypto_impl.DataType.DT_FP4_E2M1),
332+}
333+ 
334+_FLOAT_OUT_DTYPES = (
335+ pypto_impl.DataType.DT_FP16,
336+ pypto_impl.DataType.DT_BF16,
337+ pypto_impl.DataType.DT_FP32,
338+)
339+ 
340+BASIC_OUT_DTYPES = {
341+ pypto_impl.DataType.DT_FP16: (pypto_impl.DataType.DT_FP16, pypto_impl.DataType.DT_FP32),
342+ pypto_impl.DataType.DT_BF16: (pypto_impl.DataType.DT_BF16, pypto_impl.DataType.DT_FP32),
343+ pypto_impl.DataType.DT_INT8: (pypto_impl.DataType.DT_INT32,),
344+ pypto_impl.DataType.DT_FP8E5M2: _FLOAT_OUT_DTYPES,
345+ pypto_impl.DataType.DT_FP8E4M3: _FLOAT_OUT_DTYPES,
346+ pypto_impl.DataType.DT_HF8: _FLOAT_OUT_DTYPES,
347+}
348+ 
349+MX_BASIC_OUT_DTYPES = {
350+ pypto_impl.DataType.DT_FP8E5M2: _FLOAT_OUT_DTYPES,
351+ pypto_impl.DataType.DT_FP8E4M3: _FLOAT_OUT_DTYPES,
352+ pypto_impl.DataType.DT_FP4_E2M1: _FLOAT_OUT_DTYPES,
353+}
354+ 
355+NZ_UNSUPPORTED_INPUT_DTYPES = {
356+ pypto_impl.DataType.DT_FP32,
357+ pypto_impl.DataType.DT_FP8E5M2,
358+ pypto_impl.DataType.DT_HF8,
359+}
360+ 
361+QUANT_OUT_DTYPES = {
362+ pypto_impl.DataType.DT_INT8: (pypto_impl.DataType.DT_FP16, pypto_impl.DataType.DT_INT8),
363+ pypto_impl.DataType.DT_BF16: (pypto_impl.DataType.DT_INT8,),
364+ pypto_impl.DataType.DT_FP16: (pypto_impl.DataType.DT_INT8,),
365+ pypto_impl.DataType.DT_FP32: (pypto_impl.DataType.DT_INT8,),
366+ pypto_impl.DataType.DT_FP8E5M2: (pypto_impl.DataType.DT_INT8,),
367+ pypto_impl.DataType.DT_FP8E4M3: (pypto_impl.DataType.DT_INT8,),
368+ pypto_impl.DataType.DT_HF8: (pypto_impl.DataType.DT_INT8,),
369+ pypto_impl.DataType.DT_FP4_E2M1: (pypto_impl.DataType.DT_INT8,),
370+}
371+ 
372+ 
373+def __is_a2a3_arch() -> bool:
374+ return pypto_impl.GetNPUArch() in A2A3_ARCHS
375+ 
376+ 
309def __validate_type(value: Any, expect_type: Type, arg_name: str = "input") -> None:377def __validate_type(value: Any, expect_type: Type, arg_name: str = "input") -> None:
310 if value is None:378 if value is None:
311 return379 return
@@ -379,7 +447,20 @@ def __validate_bias(input_tensor, extend_params) -> None:
379 )447 )
380 448 
381 449 
382-def __validate_inputs(input_tensor1, input_tensor2, out_dtype, optional_param) -> None:450+def __validate_nz_input(input_tensor1, input_tensor2) -> None:
451+ for tensor in (input_tensor1, input_tensor2):
452+ unsupported_dtype = tensor.GetDataType() in NZ_UNSUPPORTED_INPUT_DTYPES
453+ if unsupported_dtype and tensor.Format() == pypto_impl.TileOpFormat.TILEOP_NZ:
454+ raise PyptoError(
455+ 0xF00002,
456+ ValueError(
457+ f"Input tensor with {tensor.GetDataType().name} must use ND format, "
458+ "NZ format is not supported currently."
459+ ),
460+ )
461+ 
462+ 
463+def __validate_inputs(input_tensor1, input_tensor2, out_dtype, optional_param, input_combos) -> None:
383 a_trans, b_trans, is_out_nz, extend_params = optional_param464 a_trans, b_trans, is_out_nz, extend_params = optional_param
384 __validate_type(out_dtype, DataType, "out_dtype")465 __validate_type(out_dtype, DataType, "out_dtype")
385 __validate_type(a_trans, bool, "a_trans")466 __validate_type(a_trans, bool, "a_trans")
@@ -392,33 +473,43 @@ def __validate_inputs(input_tensor1, input_tensor2, out_dtype, optional_param) -
392 473 
393 input1_dtype = input_tensor1.GetDataType()474 input1_dtype = input_tensor1.GetDataType()
394 input2_dtype = input_tensor2.GetDataType()475 input2_dtype = input_tensor2.GetDataType()
395- input1_format = input_tensor1.Format()
396- input2_format = input_tensor2.Format()
397- fp8_dtype = (pypto_impl.DataType.DT_FP8E5M2, pypto_impl.DataType.DT_FP8E4M3)
398 if is_out_nz:476 if is_out_nz:
399 raise PyptoError(0xF00002, ValueError("Output tensor do not support NZ currently."))477 raise PyptoError(0xF00002, ValueError("Output tensor do not support NZ currently."))
400- input1_fp32_valid = (478+ if (input1_dtype == pypto_impl.DataType.DT_HF8 or input2_dtype == pypto_impl.DataType.DT_HF8) and __is_a2a3_arch():
dai-zhentao

这类与平台有关的校验建议外提一个专门子函数统一负责,否则后续难以避免散弹式修改,后续校验分为通用校验+平台特性校验两层。

likedislike
shi-dingkun
shi-dingkun
Sep 4 Comments:
likedislike
401- input1_dtype == pypto_impl.DataType.DT_FP32 and input1_format == pypto_impl.TileOpFormat.TILEOP_NZ
402- )
403- input2_fp32_valid = (
404- input2_dtype == pypto_impl.DataType.DT_FP32 and input2_format == pypto_impl.TileOpFormat.TILEOP_NZ
405- )
406- input1_fp8_valid = (
407- input1_dtype == pypto_impl.DataType.DT_FP8E5M2 and input1_format == pypto_impl.TileOpFormat.TILEOP_NZ
408- )
409- input2_fp8_valid = (
410- input2_dtype == pypto_impl.DataType.DT_FP8E5M2 and input2_format == pypto_impl.TileOpFormat.TILEOP_NZ
411- )
412- if input1_fp32_valid or input2_fp32_valid:
413 raise PyptoError(479 raise PyptoError(
414- 0xF00002, ValueError("Input tensor with DT_FP32 must use ND format, NZ format is not support currently.")480+ 0xF00002,
481+ ValueError("Input tensor with DT_HF8 is not supported on A2/A3 platforms, only supported on Ascend 950."),
415 )482 )
416- if input1_fp8_valid or input2_fp8_valid:483+ __validate_nz_input(input_tensor1, input_tensor2)
484+ if (input1_dtype, input2_dtype) not in input_combos:
417 raise PyptoError(485 raise PyptoError(
418- 0xF00002, ValueError("Input tensor with DT_FP8E5M2 must use ND format, NZ format is not support currently.")486+ 0xF00002,
487+ ValueError(
488+ f"Unsupported input dtype combination: (a={input1_dtype.name}, b={input2_dtype.name}). "
489+ "See the input dtype columns of the API docs."
490+ ),
491+ )
492+ __validate_out_dtype(input1_dtype, out_dtype, extend_params, BASIC_OUT_DTYPES)
493+ 
494+ 
495+def __has_quant_scale(extend_params) -> bool:
496+ if extend_params is None:
497+ return False
498+ return extend_params.get('scale_tensor') is not None or extend_params.get('scale', 0.0) != 0.0
dai-zhentao

这里应该用and吧

likedislike
shi-dingkun
shi-dingkun
Sep 4 Comments:
likedislike
499+ 
500+ 
501+def __validate_out_dtype(input_dtype, out_dtype, extend_params, basic_out_map) -> None:
502+ if input_dtype not in basic_out_map:
503+ return
504+ allowed_out = QUANT_OUT_DTYPES[input_dtype] if __has_quant_scale(extend_params) else basic_out_map[input_dtype]
505+ if out_dtype not in allowed_out:
506+ raise PyptoError(
507+ 0xF00002,
508+ ValueError(
509+ f"Unsupported out_dtype {out_dtype} for input dtype {input_dtype}. "
510+ f"Allowed out_dtype: {allowed_out} (see dtype support tables in the API docs)."
511+ ),
419 )512 )
420- if not ((input1_dtype in fp8_dtype and input2_dtype in fp8_dtype) or (input1_dtype == input2_dtype)):
421- raise PyptoError(0xF00002, ValueError("Non-FP8 inputs require identical dtypes."))
422 513 
423 514 
424def __validate_bias_dimension(input_dim, bias_tensor):515def __validate_bias_dimension(input_dim, bias_tensor):
@@ -464,6 +555,12 @@ def __validate_scaled_inputs(input_tensor1, input_tensor2, input_scale1, input_s
464 ):555 ):
465 raise PyptoError(0xF00003, RuntimeError("scaled_mm fp4 input only supports DT_FP4_E2M1."))556 raise PyptoError(0xF00003, RuntimeError("scaled_mm fp4 input only supports DT_FP4_E2M1."))
466 557 
558+ if (
559+ input_scale1.Format() == pypto_impl.TileOpFormat.TILEOP_NZ
560+ or input_scale2.Format() == pypto_impl.TileOpFormat.TILEOP_NZ
561+ ):
562+ raise PyptoError(0xF00002, ValueError("Scale tensor must use ND format, NZ format is not supported currently."))
563+ 
467 if input_dim not in supported_dims:564 if input_dim not in supported_dims:
468 raise PyptoError(565 raise PyptoError(
469 0xF00003,566 0xF00003,
@@ -561,9 +658,7 @@ def __validate_scale_k0_dimensions(k_a_scale0_dim, k_b_scale0_dim):
561def __validate_scale_k1_dimensions(k_a_scale1_dim, k_b_scale1_dim, shape_dim_2):658def __validate_scale_k1_dimensions(k_a_scale1_dim, k_b_scale1_dim, shape_dim_2):
562 is_value_concrete = k_a_scale1_dim.is_concrete() and k_b_scale1_dim.is_concrete()659 is_value_concrete = k_a_scale1_dim.is_concrete() and k_b_scale1_dim.is_concrete()
563 if is_value_concrete and (660 if is_value_concrete and (
564- k_a_scale1_dim != k_b_scale1_dim661+ k_a_scale1_dim != k_b_scale1_dim or k_a_scale1_dim != shape_dim_2 or k_b_scale1_dim != shape_dim_2
565- or k_a_scale1_dim != shape_dim_2
566- or k_b_scale1_dim != shape_dim_2
567 ):662 ):
568 raise PyptoError(663 raise PyptoError(
569 0xF00003,664 0xF00003,
@@ -615,7 +710,17 @@ def __validate_trans_mode(mat_a, mat_b, extend_params):
615 and mat_b.GetDataType() != pypto_impl.DataType.DT_FP32710 and mat_b.GetDataType() != pypto_impl.DataType.DT_FP32
616 ):711 ):
617 raise PyptoError(712 raise PyptoError(
618- 0xF00003, RuntimeError("The param of trans_mode is only supported when input data type is DT_FP32")713+ 0xF00003, RuntimeError("The trans_mode parameter is only supported when input data type is DT_FP32")
714+ )
715+ if (
716+ extend_params.get('trans_mode', pypto_impl.TransMode.CAST_NONE) != pypto_impl.TransMode.CAST_NONE
717+ and __is_a2a3_arch()
718+ ):
719+ raise PyptoError(
720+ 0xF00002,
721+ ValueError(
722+ "The trans_mode parameter is not supported on A2/A3 platforms, only supported on Ascend 950."
723+ ),
619 )724 )
620 725 
621 726 
@@ -1,7 +1,7 @@
1#!/usr/bin/env python31#!/usr/bin/env python3
2# coding: utf-82# coding: utf-8
3# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd.3# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd.
4-# This program is free software, you can redistribute it and/or modify it under the terms and conditions of4+# This program is free software; 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").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.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,7# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
@@ -19,8 +19,11 @@ import torch
19import pypto19import pypto
20 20 
21M = 6421M = 64
22+N = 64
22PACKED_K = 3223PACKED_K = 32
23LOGICAL_K = PACKED_K * 224LOGICAL_K = PACKED_K * 2
25+K_BLOCK_SIZE_64 = 64
26+SCALE_K = (LOGICAL_K + K_BLOCK_SIZE_64 - 1) // K_BLOCK_SIZE_64
24 27 
25 28 
26@contextmanager29@contextmanager
@@ -38,48 +41,30 @@ def npuarch(arch: str):
38)41)
39def fp4_kernel(42def fp4_kernel(
40 x: pypto.Tensor([], pypto.DT_FP4_E2M1),43 x: pypto.Tensor([], pypto.DT_FP4_E2M1),
41- out: pypto.Tensor([], pypto.DT_INT32),44+ y: pypto.Tensor([], pypto.DT_FP4_E2M1),
45+ out: pypto.Tensor([], pypto.DT_FP16),
46+ scale_a: pypto.Tensor([], pypto.DT_FP8E8M0),
47+ scale_b: pypto.Tensor([], pypto.DT_FP8E8M0),
42):48):
43 assert x.dtype == pypto.DT_FP4_E2M149 assert x.dtype == pypto.DT_FP4_E2M1
44 assert x.shape[-1] == PACKED_K * 250 assert x.shape[-1] == PACKED_K * 2
51+ assert y.shape[-1] == PACKED_K * 2
45 52 
46 pypto.set_vec_tile_shapes(32, 32)53 pypto.set_vec_tile_shapes(32, 32)
47- pypto.set_cube_tile_shapes([32, 32], [32, 32], [32, 32])54+ pypto.set_cube_tile_shapes([32, 32], [64, 64], [32, 32])
48- out.move(pypto.matmul(x, x, pypto.DT_INT32) + 1)55+ out.move(pypto.scaled_mm(x, y, pypto.DT_FP16, scale_a, scale_b) + 1)
49 56 
50 57 
51@npuarch("DAV_3510")58@npuarch("DAV_3510")
52def test_fp4x2_to_fp4_logical_shape():59def test_fp4x2_to_fp4_logical_shape():
53 packed_x = torch.zeros((M, PACKED_K), dtype=torch.uint8)60 packed_x = torch.zeros((M, PACKED_K), dtype=torch.uint8)
54- out = torch.zeros((M, M), dtype=torch.int32)61+ packed_y = torch.zeros((LOGICAL_K, N // 2), dtype=torch.uint8)
62+ out = torch.zeros((M, N), dtype=torch.float16)
63+ scale_a = torch.zeros((M, SCALE_K, 2), dtype=torch.float8_e8m0fnu)
64+ scale_b = torch.zeros((SCALE_K, N, 2), dtype=torch.float8_e8m0fnu)
55 65 
56- fp4_kernel(packed_x, out)66+ fp4_kernel(packed_x, packed_y, out, scale_a, scale_b)
57- 
58- 
59-@pypto.frontend.jit(
60- runtime_options={"run_mode": pypto.RunMode.SIM}, host_options={"compile_stage": pypto.CompStage.TENSOR_GRAPH}
61-)
62-def fp4x2_kernel(
63- x: pypto.Tensor([], pypto.DT_FP4_E2M1X2),
64- out: pypto.Tensor([], pypto.DT_INT32),
65-):
66- assert x.dtype == pypto.DT_FP4_E2M1X2
67- assert x.shape[-1] == PACKED_K
68- 
69- pypto.set_vec_tile_shapes(32, 32)
70- pypto.set_cube_tile_shapes([32, 32], [32, 32], [32, 32])
71- t = pypto.matmul(x, x, pypto.DT_INT32, b_trans=True)
72- out.move(t + 1)
73- 
74- 
75-@npuarch("DAV_3510")
76-def test_fp4x2_to_fp4x2_logical_shape():
77- packed_x = torch.zeros((M, PACKED_K), dtype=torch.uint8)
78- out = torch.zeros((M, M), dtype=torch.int32)
79- 
80- fp4x2_kernel(packed_x, out)
81 67 
82 68 
83if __name__ == "__main__":69if __name__ == "__main__":
84 test_fp4x2_to_fp4_logical_shape()70 test_fp4x2_to_fp4_logical_shape()
85- test_fp4x2_to_fp4x2_logical_shape()
Rpython/tests/ut/operation/test_matrix_op.py→python/tests/ut/operation/test_matmul_op.py+150-2
@@ -1,6 +1,6 @@
1#!/usr/bin/env python31#!/usr/bin/env python3
2# coding: utf-82# coding: utf-8
3-# Copyright (c) 2025 Huawei Technologies Co., Ltd.3+# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd.
4# This program is free software, you can redistribute it and/or modify it under the terms and conditions of4# This program is free software, 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").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.6# Please refer to the License for details. You may not use this file except in compliance with the License.
@@ -10,7 +10,22 @@
10# -----------------------------------------------------------------------------------------------------------10# -----------------------------------------------------------------------------------------------------------
11""" """11""" """
12 12 
13+from contextlib import contextmanager
14+ 
15+import pytest
16+ 
13import pypto17import pypto
18+from pypto.error import PyptoError
19+ 
20+ 
21+@contextmanager
22+def npuarch(arch: str):
23+ try:
24+ old_arch = pypto.platform.npuarch
25+ pypto.platform.npuarch = arch
26+ yield
27+ finally:
28+ pypto.platform.npuarch = old_arch
14 29 
15 30 
16def test_matrix_matmul():31def test_matrix_matmul():
@@ -80,6 +95,7 @@ def test_matrix_matmul_with_tensor_interface():
80 assert c.shape == [3, 32, 32]95 assert c.shape == [3, 32, 32]
81 96 
82 97 
98+@npuarch("DAV_3510")
83def test_matrix_matmul_with_trans_mode_cast_rint():99def test_matrix_matmul_with_trans_mode_cast_rint():
84 input_dtype = pypto.DT_FP32100 input_dtype = pypto.DT_FP32
85 out_dtype = pypto.DT_FP32101 out_dtype = pypto.DT_FP32
@@ -95,7 +111,8 @@ def test_matrix_matmul_with_trans_mode_cast_rint():
95 assert c.shape == [64, 64]111 assert c.shape == [64, 64]
96 112 
97 113 
98-def test_matrix_matmul_with_trans_mode_cast_rint(): # noqa: F811114+@npuarch("DAV_3510")
115+def test_matrix_matmul_with_trans_mode_cast_round():
99 input_dtype = pypto.DT_FP32116 input_dtype = pypto.DT_FP32
100 out_dtype = pypto.DT_FP32117 out_dtype = pypto.DT_FP32
101 a = pypto.tensor((64, 32), input_dtype, "A")118 a = pypto.tensor((64, 32), input_dtype, "A")
@@ -108,3 +125,134 @@ def test_matrix_matmul_with_trans_mode_cast_rint(): # noqa: F811
108 125 
109 assert isinstance(c, pypto.tensor)126 assert isinstance(c, pypto.tensor)
110 assert c.shape == [64, 64]127 assert c.shape == [64, 64]
128+ 
129+ 
130+@pytest.mark.parametrize("arch", ["DAV_1001", "DAV_2201"])
131+def test_matmul_rejects_hf8_input_on_a2a3(arch):
132+ a = pypto.tensor((16, 32), pypto.DT_HF8, "a")
133+ b = pypto.tensor((32, 64), pypto.DT_HF8, "b")
134+ 
135+ with npuarch(arch):
136+ with pytest.raises(PyptoError, match=r"DT_HF8.*not supported on A2/A3 platforms"):
137+ pypto.matmul(a, b, pypto.DT_FP16)
138+ 
139+ 
140+@npuarch("DAV_3510")
141+def test_matmul_rejects_hf8_nz_input():
142+ a = pypto.tensor((16, 32), pypto.DT_HF8, "a", pypto.TileOpFormat.TILEOP_NZ)
143+ b = pypto.tensor((32, 64), pypto.DT_HF8, "b")
144+ 
145+ with pytest.raises(PyptoError, match=r"Input tensor with DT_HF8 must use ND format"):
146+ pypto.matmul(a, b, pypto.DT_FP16)
147+ 
148+ 
149+@pytest.mark.parametrize("arch", ["DAV_1001", "DAV_2201"])
150+def test_matmul_rejects_trans_mode_on_a2a3(arch):
151+ a = pypto.tensor((16, 32), pypto.DT_FP32, "a")
152+ b = pypto.tensor((32, 64), pypto.DT_FP32, "b")
153+ extend_params = {'trans_mode': pypto.TransMode.CAST_RINT}
154+ 
155+ with npuarch(arch):
156+ with pytest.raises(PyptoError, match=r"trans_mode.*not supported on A2/A3 platforms"):
157+ pypto.matmul(a, b, pypto.DT_FP32, extend_params=extend_params)
158+ 
159+ 
160+@npuarch("DAV_3510")
161+def test_scaled_mm_rejects_nz_scale():
162+ mat_a = pypto.tensor((16, 128), pypto.DT_FP8E4M3, "mat_a")
163+ mat_b = pypto.tensor((128, 32), pypto.DT_FP8E4M3, "mat_b")
164+ scale_a = pypto.tensor((16, 32, 32), pypto.DT_FP8E8M0, "scale_a", pypto.TileOpFormat.TILEOP_NZ)
165+ scale_b = pypto.tensor((2, 32, 2), pypto.DT_FP8E8M0, "scale_b")
166+ 
167+ with pytest.raises(PyptoError, match=r"Scale tensor must use ND format"):
168+ pypto.scaled_mm(mat_a, mat_b, pypto.DT_FP16, scale_a, scale_b)
169+ 
170+ 
171+@pytest.mark.parametrize(
172+ "in_dtype,out_dtype",
173+ [
174+ (pypto.DT_FP16, pypto.DT_BF16),
175+ (pypto.DT_FP16, pypto.DT_INT32),
176+ (pypto.DT_BF16, pypto.DT_FP16),
177+ (pypto.DT_INT8, pypto.DT_FP16),
178+ ],
179+)
180+def test_matmul_rejects_unsupported_out_dtype(in_dtype, out_dtype):
181+ a = pypto.tensor((16, 32), in_dtype, "a")
182+ b = pypto.tensor((32, 64), in_dtype, "b")
183+ 
184+ with pytest.raises(PyptoError, match=r"Unsupported out_dtype"):
185+ pypto.matmul(a, b, out_dtype)
186+ 
187+ 
188+def test_matmul_rejects_unsupported_out_dtype_with_scale():
189+ a = pypto.tensor((16, 32), pypto.DT_FP16, "a")
190+ b = pypto.tensor((32, 64), pypto.DT_FP16, "b")
191+ extend_params = {'scale': 0.2}
192+ 
193+ with pytest.raises(PyptoError, match=r"Unsupported out_dtype"):
194+ pypto.matmul(a, b, pypto.DT_FP32, extend_params=extend_params)
195+ 
196+ 
197+@pytest.mark.parametrize(
198+ "in_dtype,out_dtype",
199+ [
200+ (pypto.DT_INT8, pypto.DT_FP16),
201+ (pypto.DT_INT8, pypto.DT_INT8),
202+ (pypto.DT_FP16, pypto.DT_INT8),
203+ (pypto.DT_BF16, pypto.DT_INT8),
204+ (pypto.DT_FP32, pypto.DT_INT8),
205+ ],
206+)
207+def test_matmul_accepts_quant_out_dtype_with_scale(in_dtype, out_dtype):
208+ a = pypto.tensor((16, 32), in_dtype, "a")
209+ b = pypto.tensor((32, 64), in_dtype, "b")
210+ extend_params = {'scale': 0.2}
211+ 
212+ with pypto.function("MATMUL_DEQUANT", a, b):
213+ pypto.set_cube_tile_shapes([32, 32], [32, 32], [32, 32])
214+ c = pypto.matmul(a, b, out_dtype, extend_params=extend_params)
215+ 
216+ assert isinstance(c, pypto.tensor)
217+ assert c.dtype == out_dtype
218+ 
219+ 
220+def test_matmul_dequant_int8_to_fp16():
221+ a = pypto.tensor((16, 32), pypto.DT_INT8, "a")
222+ b = pypto.tensor((32, 64), pypto.DT_INT8, "b")
223+ 
224+ with pypto.function("MATMUL_DEQUANT", a, b):
225+ pypto.set_cube_tile_shapes([64, 64], [64, 64], [64, 64])
226+ c = pypto.matmul(a, b, pypto.DT_FP16, extend_params={'scale': 0.2})
227+ 
228+ assert isinstance(c, pypto.tensor)
229+ assert c.shape == [16, 64]
230+ 
231+ 
232+@npuarch("DAV_3510")
233+def test_scaled_mm_rejects_unsupported_fp4_out_dtype():
234+ mat_a = pypto.tensor((16, 128), pypto.DT_FP4_E2M1, "mat_a")
235+ mat_b = pypto.tensor((128, 32), pypto.DT_FP4_E2M1, "mat_b")
236+ scale_a = pypto.tensor((16, 2, 2), pypto.DT_FP8E8M0, "scale_a")
237+ scale_b = pypto.tensor((2, 32, 2), pypto.DT_FP8E8M0, "scale_b")
238+ 
239+ with pytest.raises(PyptoError, match=r"Unsupported out_dtype"):
240+ pypto.scaled_mm(mat_a, mat_b, pypto.DT_INT32, scale_a, scale_b)
241+ 
242+ 
243+def test_matmul_rejects_input_outside_combos():
244+ a = pypto.tensor((16, 32), pypto.DT_FP4_E2M1, "a")
245+ b = pypto.tensor((32, 64), pypto.DT_FP4_E2M1, "b")
246+ 
247+ with pytest.raises(PyptoError, match=r"Unsupported input dtype combination"):
248+ pypto.matmul(a, b, pypto.DT_FP16)
249+ 
250+ 
251+def test_scaled_mm_rejects_input_outside_mx_combos():
252+ mat_a = pypto.tensor((16, 128), pypto.DT_FP16, "mat_a")
253+ mat_b = pypto.tensor((128, 32), pypto.DT_FP16, "mat_b")
254+ scale_a = pypto.tensor((16, 2, 2), pypto.DT_FP8E8M0, "scale_a")
255+ scale_b = pypto.tensor((2, 32, 2), pypto.DT_FP8E8M0, "scale_b")
256+ 
257+ with pytest.raises(PyptoError, match=r"Unsupported input dtype combination"):
258+ pypto.scaled_mm(mat_a, mat_b, pypto.DT_FP16, scale_a, scale_b)