已合并
[Task-99][v2.7.1] API Consistency: Tensor.ndim #41340
[Task-99][v2.7.1] API Consistency: Tensor.ndim #41340
已合并
Yhw050920创建于 7月11日
1 个文件变更+77-0
@@ -0,0 +1,77 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd
2+# All rights reserved.
3+# Licensed under the BSD 3-Clause License
4+# you may not use this file except in compliance with the License.
5+# You may obtain a copy of the License at
6+# https://opensource.org/licenses/BSD-3-Clause
7+# Unless required by applicable law or agreed to in writing, software
8+# distributed under the License is distributed on an "AS IS" BASIS,
9+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10+# See the License for the specific language governing permissions and
11+# limitations under the License.
12+ 
13+"""
14+Add validation cases for Tensor.ndim API on Ascend NPU:
15+ 
16+PyTorch community lacks sufficient and direct API validations for this API, so this file is added.
17+This file validates Tensor.ndim (extendable).
18+ 
19+Test command:
20+ python test/npu/test_tensor_ndim.py
21+"""
22+ 
23+import torch
24+from torch.testing._internal.common_utils import TestCase, run_tests
25+ 
26+import torch_npu
27+from torch_npu.testing.common_utils import SupportedDevices
28+ 
29+assert torch_npu is not None # NPU backend registration
30+ 
31+ 
32+class TestTensorNdim(TestCase):
33+ 
34+ @SupportedDevices(['Ascend910A', 'Ascend910B', 'Ascend910_93', 'Ascend950'])
35+ def test_ndim_0d_tensor(self):
36+ x = torch.tensor(5).npu()
37+ self.assertEqual(x.ndim, 0)
38+ 
39+ @SupportedDevices(['Ascend910A', 'Ascend910B', 'Ascend910_93', 'Ascend950'])
40+ def test_ndim_1d_tensor(self):
41+ x = torch.randn(5).npu()
42+ self.assertEqual(x.ndim, 1)
43+ 
44+ @SupportedDevices(['Ascend910A', 'Ascend910B', 'Ascend910_93', 'Ascend950'])
45+ def test_ndim_2d_tensor(self):
46+ x = torch.randn(3, 4).npu()
47+ self.assertEqual(x.ndim, 2)
48+ 
49+ @SupportedDevices(['Ascend910A', 'Ascend910B', 'Ascend910_93', 'Ascend950'])
50+ def test_ndim_3d_tensor(self):
51+ x = torch.randn(2, 3, 4).npu()
52+ self.assertEqual(x.ndim, 3)
53+ 
54+ @SupportedDevices(['Ascend910A', 'Ascend910B', 'Ascend910_93', 'Ascend950'])
55+ def test_ndim_4d_tensor(self):
56+ x = torch.randn(2, 3, 4, 5).npu()
57+ self.assertEqual(x.ndim, 4)
58+ 
59+ @SupportedDevices(['Ascend910A', 'Ascend910B', 'Ascend910_93', 'Ascend950'])
60+ def test_ndim_cpu_npu_consistency(self):
61+ for shape in [(5,), (3, 4), (2, 3, 4), (2, 3, 4, 5)]:
62+ cpu_tensor = torch.randn(*shape)
63+ npu_tensor = cpu_tensor.npu()
64+ self.assertEqual(cpu_tensor.ndim, npu_tensor.ndim)
65+ 
66+ @SupportedDevices(['Ascend910A', 'Ascend910B', 'Ascend910_93', 'Ascend950'])
67+ def test_ndim_after_operations(self):
68+ x = torch.randn(3, 4).npu()
69+ y = torch.randn(3, 4).npu()
70+ z = x + y
71+ self.assertEqual(z.ndim, 2)
72+ w = z.sum(dim=1)
73+ self.assertEqual(w.ndim, 1)
74+ 
75+ 
76+if __name__ == "__main__":
77+ run_tests()