Files
TorchNPU/test/test_profiler_string_table.py
T
qq_65095566 8147ea812f test: Add tests for StringTable.default_factory
Co-authored-by: qq_65095566<1922937030@qq.com>



# message auto-generated for no-merge-commit merge:
!43213 merge test-string-table-default-factory-master into master

test: Add tests for StringTable.default_factory

Created-by: qq_65095566
Commit-by: qq_65095566
Merged-by: ascend-robot
Description: # 【合入来源】
## 关联社区 issue:[[Usage]: torch.autograd.profiler_util.StringTable.default_factory API适配补齐 #3444](https://gitcode.com/Ascend/pytorch/issues/3444)

## 关联社区 issue:[【社区任务】7月社区任务第二期-Ascend for PyTorch API 一致性开发(59) #2906](https://gitcode.com/Ascend/pytorch/issues/2906)


- [ ] 需求
- [ ] 问题单
- [x] issue/工单
- [ ] 重构优化
- [ ] 资料更新

# 【修改方案】

经检索 PyTorch 官方开发分支测试目录,未发现针对 `torch.autograd.profiler_util.StringTable.default_factory` 的直接测试用例。

现有 `StringTable` 测试主要覆盖 `popitem`,未直接覆盖 `default_factory` 的默认值、构造参数、属性修改、非法参数以及与 `StringTable.__missing__` 的交互行为,因此需要补充直接测试。

本次修改内容如下:

1. 扩展 master 分支已有测试文件:

   ```text
   test/test_profiler_string_table.py
   ```

2. 保留原有 `torch.autograd.profiler_util.StringTable.popitem` 测试。

3. 新增 `torch.autograd.profiler_util.StringTable.default_factory` 测试,覆盖:

   - 默认构造时 `default_factory` 为 `None`;
   - 显式传入 `None`;
   - 构造时传入可调用对象;
   - 读取和修改 `default_factory` 属性;
   - 构造时传入不可调用对象抛出 `TypeError`;
   - `StringTable.__missing__` 不调用 `default_factory`。

4. 本次仅补充单元测试,不修改 API 功能实现。

# 【资料变更】

不涉及

经检查,`docs/zh/api/native_api` 下 PyTorch 2.7.1、2.9.0、2.10.0、2.11.0 和 2.12.0 对应资料中均未收录 `torch.autograd.profiler_util.StringTable.default_factory`。

PyTorch 官方文档中也未提供该属性的独立公开文档条目。

`StringTable` 继承自 `collections.defaultdict`,`default_factory` 是继承获得的标准库属性,并非 PyTorch 在 `StringTable` 中单独实现的成员,因此本次不新增 torch-npu 原生 API 资料条目。

该属性属于非计算类属性,不涉及张量及数据类型。

# 【接口变更】

本次不修改 `torch.autograd.profiler_util.StringTable.default_factory` 的功能、参数或返回行为,仅补充单元测试,不涉及跨代码仓或客户可见接口变更。

# 【功能验证】

测试命令:

```bash
python test/test_profiler_string_table.py -v
```

测试结果:

```text
Ran 12 tests in 0.038s

OK
```

原有 7 个 `StringTable.popitem` 测试和新增 5 个 `StringTable.default_factory` 测试均执行通过。

本地使用现有环境完成冒烟验证,master 分支兼容性由 PR 持续集成流水线进一步验证。

测试过程中出现 CuTeDSL 可选依赖缺失警告,该警告与本次测试无关,不影响测试结果。

代码格式检查:

```bash
git diff --check
```

检查结果无异常。

# 【CheckList】

- [x] 代码注释完备,正确记录错误日志
- [x] 代码实现进行了返回值、空指针等校验
- [x] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等
- [x] PR持续集成流水线(CI)执行通过,代码检查无异常

See merge request: Ascend/pytorch!43213
2026-08-13 10:05:44 +08:00

161 lines
5.1 KiB
Python

# Copyright (c) 2026 Huawei Technologies Co., Ltd
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Add validation cases for torch.autograd.profiler_util.StringTable on NPU:
1. PyTorch community lacks sufficient and direct API validations for some
torch.autograd.profiler_util.StringTable APIs.
2. This file validates torch.autograd.profiler_util.StringTable.popitem and
torch.autograd.profiler_util.StringTable.default_factory (extendable).
"""
from torch.autograd.profiler_util import StringTable
from torch.testing._internal.common_utils import TestCase, run_tests
class TestStringTable(TestCase):
"""Test cases for torch.autograd.profiler_util.StringTable."""
def _populate_table(self, items):
"""Helper: populate StringTable with given key-value pairs."""
st = StringTable()
for k, v in items:
st[k] = v
return st
def test_popitem_returns_key_value(self):
st = self._populate_table([("a", "alpha"), ("b", "beta")])
initial_len = len(st)
k, v = st.popitem()
self.assertIsInstance(k, str)
self.assertIsInstance(v, str)
self.assertEqual(len(st), initial_len - 1)
self.assertNotIn(k, st)
def test_popitem_removes_item(self):
st = self._populate_table([("key1", "val1"), ("key2", "val2")])
k, _ = st.popitem()
self.assertNotIn(k, st)
def test_popitem_empty_raises_keyerror(self):
st = StringTable()
with self.assertRaises(KeyError):
st.popitem()
def test_popitem_exhausts_table(self):
items = [("a", "1"), ("b", "2"), ("c", "3")]
st = self._populate_table(items)
popped = []
while st:
popped.append(st.popitem())
self.assertEqual(len(st), 0)
self.assertEqual(len(popped), len(items))
self.assertRaises(KeyError, st.popitem)
def test_popitem_with_missing_demangle(self):
# Use a mangled C++ name that triggers __missing__ -> torch._C._demangle
st = StringTable()
mangled_key = "_Z3foov" # demangles to "foo()" when demangle is available
_ = st[mangled_key] # triggers __missing__, stores demangled value
self.assertGreater(len(st), 0)
k, v = st.popitem()
self.assertEqual(k, mangled_key)
self.assertIsInstance(v, str)
# __missing__ stores the demangled value, which must differ from the
# mangled key to prove the demangle path was actually exercised
self.assertNotEqual(v, mangled_key,
"demangle should produce different output from mangled input")
def test_popitem_does_not_trigger_default_factory(self):
# defaultdict's popitem should NOT call default_factory
call_count = [0]
def counting_factory():
call_count[0] += 1
return "default"
st = StringTable(counting_factory)
st["x"] = "explicit"
st.popitem()
# popitem on a table with only explicit items should not trigger factory
self.assertEqual(call_count[0], 0)
def test_multiple_popitems_consistent(self):
items = [("k1", "v1"), ("k2", "v2"), ("k3", "v3"), ("k4", "v4")]
st = self._populate_table(items)
popped_items = []
for _ in range(len(items)):
popped_items.append(st.popitem())
self.assertEqual(len(st), 0)
popped_keys = {k for k, v in popped_items}
expected_keys = {k for k, v in items}
self.assertEqual(popped_keys, expected_keys)
def test_default_factory_is_none_by_default(self):
self.assertIsNone(StringTable().default_factory)
self.assertIsNone(StringTable(None).default_factory)
def test_default_factory_preserves_callable(self):
def factory():
return "default"
table = StringTable(factory)
self.assertIs(table.default_factory, factory)
def test_default_factory_is_writable(self):
def factory():
return "default"
table = StringTable()
table.default_factory = factory
self.assertIs(table.default_factory, factory)
table.default_factory = None
self.assertIsNone(table.default_factory)
def test_default_factory_rejects_non_callable_at_construction(self):
with self.assertRaises(TypeError):
StringTable("invalid")
def test_default_factory_is_not_used_by_string_table_missing(self):
calls = []
def factory():
calls.append(True)
return "default"
table = StringTable(factory)
self.assertEqual(table["t"], "t")
self.assertEqual(calls, [])
if __name__ == "__main__":
run_tests()