已合并
test(nn): add test for UninitializedParameter.cls_to_become #31762
dinglaiping创建于 3月13日
test(nn): add test for UninitializedParameter.cls_to_become #31762
已合并
从已删除 :addtest-uninitialized-parameter-cls-to-become-2.8.0合入到Ascend/pytorchv2.8.0
共 1 个文件变更+36-0
| @@ -0,0 +1,36 @@ | |||
| 1 | +import torch | ||
| 2 | +from torch.testing._internal.common_utils import TestCase, run_tests | ||
| 3 | +import torch_npu | ||
| 4 | + | ||
| 5 | +# 关闭NPU JIT编译,减少CI耗时 | ||
| 6 | +torch_npu.npu.set_compile_mode(jit_compile=False) | ||
| 7 | + | ||
| 8 | + | ||
| 9 | +# 修复:将自定义属性设为类属性(确保实例化后必存在) | ||
| 10 | +class CustomParameter(torch.nn.Parameter): | ||
| 11 | + custom_attr = "custom_param" # 类属性,所有实例共享,无需__init__赋值 | ||
| 12 | + | ||
| 13 | + def __init__(self, data=None, requires_grad=True): | ||
| 14 | + super().__init__(data, requires_grad) | ||
| 15 | + | ||
| 16 | + | ||
| 17 | +class TestUninitializedParameterClsToBecome(TestCase): | ||
| 18 | + | ||
| 19 | + def test_core_functionality_npu(self): | ||
| 20 | + """极简验证NPU环境下cls_to_become+materialize核心功能""" | ||
| 21 | + # 1. 创建NPU未初始化参数 | ||
| 22 | + uninit_param = torch.nn.parameter.UninitializedParameter(device="npu") | ||
| 23 | + # 2. 绑定自定义类 | ||
| 24 | + uninit_param.cls_to_become = CustomParameter | ||
| 25 | + # 3. 实例化参数 | ||
| 26 | + uninit_param.materialize(shape=(3, 3)) | ||
| 27 | + | ||
| 28 | + # 核心断言(全部通过,无报错) | ||
| 29 | + self.assertEqual(uninit_param.shape, torch.Size((3, 3))) | ||
| 30 | + self.assertEqual(uninit_param.device.type, "npu") | ||
| 31 | + self.assertIsInstance(uninit_param, CustomParameter) | ||
| 32 | + self.assertEqual(uninit_param.custom_attr, "custom_param") # 现在能正常访问 | ||
| 33 | + | ||
| 34 | + | ||
| 35 | +if __name__ == "__main__": | ||
| 36 | + run_tests() | ||