Closed
【API一致性任务】: torch.Generator.graphsafe_set_state NPU补齐任务 #3868
FlippedAdd on  Aug 10Closed at  Sep 30
Flipped
Flipped
Aug 10 Create

ISSUE来源:【社区任务】7月社区任务第三期-Ascend for PyTorch API 一致性开发(128)#3242

环境信息

操作系统:Ubuntu 22.04.5 LTS
机器架构:aarch64 / x86_64

昇腾硬件:
- A2:Ascend 910B3 NPU
- A3:Ascend910_9382 NPU
- A5:Ascend950PR NPU

CANN软件版本:9.1.0

验证环境:

- torch 2.7.1+cpu,torch-npu 2.7.1.post8
- torch 2.11.0+cpu,torch-npu 2.11.0
- torch 2.12.0+cpu,torch-npu 2.12.0

一、API功能说明

本任务涉及的 API 为:

torch.Generator.graphsafe_set_state

torch.Generator.graphsafe_set_state(state) 用于将当前 Generator 的随机数生成状态设置为指定 Generator 状态,以便在 Graph 捕获和回放场景中安全管理随机数状态。

该 API 的核心功能包括:

  • 接收一个 Generator 状态;
  • 将当前 Generator 切换到指定状态;
  • 支持在 Graph 捕获和回放场景中管理 RNG 状态;
  • 状态切换后正确维护 Generator offset;
  • 保证 eager 执行与 Graph replay 的随机结果一致。

该 API 属于 Generator 状态管理类接口,与 Tensor 的具体计算数据类型无关。

二、PyTorch官方用例检查

PyTorch 官方社区已提供直接覆盖该 API 的测试用例:

test/test_cuda.py::test_graphsafe_set_get_rng_state

各版本准确源码范围如下:

PyTorch版本 官方测试文件 源码范围
v2.7.1 test/test_cuda.py L1951-L2028
v2.11.0 test/test_cuda.py L2138-L2215
v2.12.0 test/test_cuda.py L2235-L2312
master test/test_cuda.py L2887-L2958

官方用例覆盖完整性

官方用例包含以下验证:

  1. 通过 graphsafe_get_state() 获取原 Generator 状态;
  2. 通过 clone_state() 创建新的 Generator 状态;
  3. 通过 graphsafe_set_state(new_state) 切换到新状态;
  4. 通过 graphsafe_set_state(old_state) 恢复原状态;
  5. 同时验证自定义 Generator 和默认设备 Generator;
  6. 将 Generator 状态注册到 Graph;
  7. 执行 Graph capture;
  8. 连续执行三次 Graph replay;
  9. 比较 eager Generator 与 Graph Generator 的 RNG offset;
  10. 比较 eager 执行与 Graph replay 的随机数结果。

官方用例不是仅间接调用目标 API,而是直接调用两次 graphsafe_set_state(),并通过 offset 和随机数结果验证状态切换产生的实际效果。因此,官方用例对该 API 的核心功能覆盖完整,无需新增测试用例。

三、官方用例需要NPU适配的源码依据

三个目标版本的官方用例结构一致,均使用 CUDA 专用条件、设备、Generator、Graph 和 Stream。

以下以 PyTorch v2.7.1 为例。

1. CUDA条件及设备硬编码

对应 test/test_cuda.py:L1951-L1959:

@unittest.skipIf(
    not TEST_CUDA_GRAPH,
    "CUDA >= 11.0 or ROCM >= 5.3 required for graphs",
)
def test_graphsafe_set_get_rng_state(self):
    def create_states(generator):
        """Initializes generator states and registers them with a CUDA graph if provided."""
        torch.rand(1, device="cuda")

该部分依赖:

TEST_CUDA_GRAPH
device="cuda"

无法直接在 NPU 环境执行。

2. 目标API及CUDA Tensor硬编码

对应 test/test_cuda.py:L1979-L1986:

generator.graphsafe_set_state(new_state)
random_values.append(
    torch.rand(5, device="cuda", generator=generator)
)

generator.graphsafe_set_state(old_state)
random_values.extend(
    [torch.rand(5, device="cuda", generator=generator) for _ in range(2)]
)

虽然 graphsafe_set_state() 本身与设备名称无关,但其后用于验证状态切换结果的随机 Tensor 被硬编码到 CUDA。

3. CUDA Generator、Graph及Stream硬编码

对应 test/test_cuda.py:L1998-L2011:

generator = torch.Generator(device="cuda")
generator_state = create_states(generator)

g = torch.cuda.CUDAGraph()
s = torch.cuda.Stream()
default_generator = torch.cuda.default_generators[0]
default_generator_state = create_states(default_generator)
register_states_to_graph(default_generator_state, g)

with torch.cuda.stream(s):
    g.capture_begin()

该部分依赖:

torch.Generator(device="cuda")
torch.cuda.CUDAGraph()
torch.cuda.Stream()
torch.cuda.default_generators
torch.cuda.stream()

因此,官方用例虽然覆盖完整,但存在明确的 CUDA 设备硬编码,需要进行 NPU 适配后才能验证 NPU 支持情况。

四、适配路线判断

根据最新《Torch-NPU API一致性说明文档》:

1.1 PyTorch官方社区有用例且用例覆盖完整

① 需要进行NPU适配:
不再新增patch,仅提交issue说明、运行截图,并给出相应源码片段说明用例需要进行NPU适配。
后续通过PyTorch社区用例硬件解耦任务跟踪实现。

本任务符合以下条件:

PyTorch官方已有直接测试用例
+ 官方用例核心功能覆盖完整
+ 官方用例存在CUDA设备硬编码
+ NPU映射验证执行通过

因此,本任务最终采用:

1.1①:PyTorch官方用例覆盖完整,但需要进行NPU适配

v2.9.0 和 v2.10.0 已进入维护阶段,本任务不作测试补齐。

五、NPU功能验证

为验证 torch.Generator.graphsafe_set_state 在NPU上的实际支持情况,本次在不修改PyTorch官方源码、不新增torch-npu测试文件和不提交patch的前提下,参考官方完整用例的执行逻辑编写临时NPU等价验证脚本。该脚本仅将CUDA专用对象替换为对应的NPU对象,用于验证接口功能,不属于PyTorch官方用例硬件解耦实现。验证脚本写入 /tmp,不会修改或提交到代码仓。
PyTorch官方用例仍包含 TEST_CUDA_GRAPH、device="cuda"、torch.cuda.CUDAGraph、torch.cuda.Stream 和torch.cuda.default_generators 等CUDA专用逻辑,因此仍需通过PyTorch社区用例硬件解耦任务进行统一适配。

5.1 验证方法

参考 PyTorch 官方用例:

test/test_cuda.py::test_graphsafe_set_get_rng_state

在不修改 torch-npu 源码的情况下,将官方用例中的 CUDA 专用对象映射为对应的 NPU 对象:

PyTorch 官方用例 NPU验证代码
device="cuda" device="npu:0"
torch.cuda.CUDAGraph() torch.npu.NPUGraph()
torch.cuda.Stream() torch.npu.Stream()
torch.cuda.default_generators[0] torch.npu.default_generators[0]
torch.cuda.stream() torch.npu.stream()
torch.cuda.current_stream() torch.npu.current_stream()

验证内容包括:

  1. torch.Generator.graphsafe_set_state 接口存在;
  2. 自定义 NPU Generator 和默认 NPU Generator 均可创建状态;
  3. graphsafe_get_state()、clone_state() 和 graphsafe_set_state() 可组合使用;
  4. Generator 状态可注册到 NPUGraph;
  5. NPUGraph 可以完成图捕获和三次图回放;
  6. 图外执行与图内执行产生的随机数一致;
  7. 图外 Generator 和图内 Generator 的状态偏移量一致。

验证脚本仅写入 /tmp,用于运行验证,不提交到代码仓。

5.2 创建可复现验证脚本

执行以下命令:

cd /workspace

tee /tmp/verify_graphsafe_set_state.py >/dev/null <<'PY'
import sys
from importlib.metadata import version

import torch
import torch_npu


API_NAME = "torch.Generator.graphsafe_set_state"
DEVICE = "npu:0"

target_version = sys.argv[1]
source_range = sys.argv[2]

print("=" * 70)
print(f"API: {API_NAME}")
print(f"Official test: test/test_cuda.py:{source_range}")
print(f"Target version: {target_version}")
print(f"torch version: {torch.__version__}")
print(f"torch-npu version: {version('torch-npu')}")
print(f"torch.npu available: {torch.npu.is_available()}")

assert torch.npu.is_available()
assert hasattr(torch.Generator, "graphsafe_set_state")
assert hasattr(torch.Generator, "graphsafe_get_state")
assert hasattr(torch.Generator, "clone_state")
assert hasattr(torch.npu.NPUGraph, "register_generator_state")

torch.npu.set_device(0)

probe = torch.rand(1, device=DEVICE)
assert probe.device.type == "npu"
print(f"[PASS] Required APIs exist; tensor device: {probe.device}")


def create_states(generator):
    # Initialize the NPU generator before obtaining its graph-safe states.
    torch.rand(1, device=DEVICE)
    generator.manual_seed(0)

    old_state = generator.graphsafe_get_state()
    new_state = generator.clone_state()

    assert old_state.device.type == "npu"
    assert new_state.device.type == "npu"
    return generator, old_state, new_state


def register_states_to_graph(generator_state, graph):
    _, old_state, new_state = generator_state
    graph.register_generator_state(old_state)
    graph.register_generator_state(new_state)


def perform_random_generation_steps(generator_state):
    generator, old_state, new_state = generator_state
    random_values = []

    generator.graphsafe_set_state(new_state)
    random_values.append(
        torch.rand(5, device=DEVICE, generator=generator)
    )

    generator.graphsafe_set_state(old_state)
    random_values.extend(
        [
            torch.rand(5, device=DEVICE, generator=generator)
            for _ in range(2)
        ]
    )

    return random_values


def get_final_offsets_of_states(generator_state):
    _, old_state, new_state = generator_state
    return old_state.get_offset(), new_state.get_offset()


# Generator used for graph-external reference execution.
generator = torch.Generator(device=DEVICE)
generator_state = create_states(generator)

# Default NPU Generator used during NPUGraph capture.
graph = torch.npu.NPUGraph()
stream = torch.npu.Stream()
default_generator = torch.npu.default_generators[0]
default_generator_state = create_states(default_generator)

register_states_to_graph(default_generator_state, graph)
print("[PASS] Generator states registered to NPUGraph")

with torch.npu.stream(stream):
    graph.capture_begin()
    graphed_random_values = perform_random_generation_steps(
        default_generator_state
    )
    graph.capture_end()

torch.npu.current_stream().wait_stream(stream)
torch.npu.synchronize()
print("[PASS] NPUGraph capture completed")

for replay_index in range(1, 4):
    random_values = perform_random_generation_steps(generator_state)

    graph.replay()
    torch.npu.synchronize()

    offsets = get_final_offsets_of_states(generator_state)
    graph_offsets = get_final_offsets_of_states(default_generator_state)

    assert offsets == graph_offsets, (
        f"offset mismatch: eager={offsets}, graph={graph_offsets}"
    )

    assert len(random_values) == len(graphed_random_values)

    for eager_value, graph_value in zip(
        random_values, graphed_random_values
    ):
        assert torch.equal(eager_value, graph_value)

    print(
        f"[PASS] replay {replay_index}: values and offsets consistent; "
        f"offsets={offsets}"
    )

print("=" * 70)
print(f"[PASS] {API_NAME} is supported on NPU")
print("Route: 1.1① - official test is complete but CUDA-specific")
print("=" * 70)
PY

python3 -m py_compile /tmp/verify_graphsafe_set_state.py &&
echo "[PASS] validation script syntax check passed"

说明:不校验 graphsafe_set_state() 的返回值为 None。该接口用于将当前 Generator 的状态设置为指定 Generator 状态,功能验证重点是状态切换后随机数及状态偏移量是否与图内执行一致。

5.3 PyTorch 2.7.1验证

官方用例范围:

pytorch-v2.7.1/test/test_cuda.py:L1951-L2028

运行命令:

deactivate 2>/dev/null || true
cd /workspace

source /workspace/envs/torch-npu-2.7.1/bin/activate
source /usr/local/Ascend/ascend-toolkit/set_env.sh

unset PYTHONPATH PIP_INDEX_URL PIP_EXTRA_INDEX_URL
export PYTHONNOUSERSITE=1
export PYTORCH_PRINT_REPRO_ON_FAILURE=0

python /tmp/verify_graphsafe_set_state.py \
    2.7.1 \
    L1951-L2028 \
    2>&1 | tee /workspace/graphsafe_set_state_v2.7.1.log

验证结果:

A2:

image.png

A3:

image.png

A5:

image.png

5.4 PyTorch 2.11.0验证

官方用例范围:

pytorch-v2.11.0/test/test_cuda.py:L2138-L2215

验证结果:

A2:

image.png

A3:

image.png

A5:

image.png

5.5 PyTorch 2.12.0验证

官方用例范围:

pytorch-v2.12.0/test/test_cuda.py:L2235-L2312

验证结果:

A2:

image.png

A3:

image.png

A5:

image.png

5.6 验证结论

版本 官方用例范围 NPU验证结果
PyTorch 2.7.1 L1951-L2028 通过
PyTorch 2.11.0 L2138-L2215 通过
PyTorch 2.12.0 L2235-L2312 通过

三个版本均完成以下验证:

  • graphsafe_set_state() 可以在NPU Generator上正常调用;
  • 自定义Generator与默认Generator的状态切换正常;
  • Generator状态可以注册到NPUGraph;
  • NPUGraph捕获及三次回放均成功;
  • 图外执行与图内执行的随机数结果一致;
  • Generator状态偏移量一致。

因此确认该API在NPU上已支持。官方用例功能覆盖完整,但依赖CUDA专用测试入口及对象,需要进行设备解耦适配,按照路线1.1①处理,不新增torch-npu测试Patch。

六、资料检查

补充 torch.Generator.graphsafe_set_state 的资料支持情况,涉及以下版本:

pytorch_2-7-1
pytorch_2-11-0
pytorch_2-12-0
pytorch_2-13-0

修改文件:

docs/zh/api/native_api/pytorch_2-7-1/torch.md
docs/zh/api/native_api/pytorch_2-11-0/torch.md
docs/zh/api/native_api/pytorch_2-12-0/torch.md
docs/zh/api/native_api/pytorch_2-13-0/torch.md

按照最新资料格式补充产品支持情况:

**产品支持情况**:

- <term>Atlas A2 训练系列产品</term>:支持
- <term>Atlas A3 训练系列产品</term>:支持
- <term>Ascend 950DT</term>:支持

该API属于Generator状态管理类API,与具体数据类型无关,无额外限制,因此不设置“限制与说明”。
master资料PR:docs(generator): add graphsafe_set_state support #44218

七、最终结论

  • torch.Generator.graphsafe_set_state 已有 PyTorch 官方直接测试用例;
  • 官方用例直接调用目标 API,并验证状态切换后的 offset 和随机结果;
  • 官方用例覆盖自定义 Generator、默认 Generator、Graph capture 和三次 replay,核心功能覆盖完整;
  • 官方用例存在 TEST_CUDA_GRAPH、device="cuda"、torch.cuda.CUDAGraph、torch.cuda.Stream 和 torch.cuda.default_generators 等 CUDA 硬编码;
  • v2.7.1、v2.11.0、v2.12.0 NPU 功能验证均通过;
  • 该 API 在当前 torch-npu 中已具备功能,无需修改底层实现;
  • 本任务最终采用 1.1① 路线;
  • 按照最新要求,不再新增或修改 patch,不再提交测试 PR;
  • 后续通过 PyTorch 社区用例硬件解耦任务跟踪官方用例的设备适配;
  • master 资料缺失,已通过资料 PR #44218 同步补齐 PyTorch 2.7.1、2.11.0、2.12.0 和 2.13.0 文档。

欢迎加入社区,感谢您对社区的贡献 🎉!

likedislike
FlippedFlipped
Aug 10 associated Kanban: FrameworkPTAdapter 版本issue看板
ascend-robotascend-robotCollaborators
Aug 10 Added label: usage
FlippedFlipped
Aug 10 Modify description of issue
TorchNPU-BotTorchNPU-BotCollaborators
Aug 10 Added label: bot-triaged
TorchNPU-Bot
TorchNPU-BotCollaborators
Aug 10 Comments:

检测到当前 issue 已关联 PR,自动添加标签:bot-triaged

likedislike
FlippedFlipped
Aug 11 Modify description of issue
FlippedFlipped
Aug 11 Modify description of issue
FlippedFlipped
Aug 13 Change title to "【API一致性任务】: torch.Generator.graphsafe_set_state NPU补齐任务", originally titled "[Usage]: torch.Generator.graphsafe_set_state NPU补齐任务".
TorchNPU-BotTorchNPU-BotCollaborators
Aug 13 Added label: event: api-consistency
TorchNPU-Bot
TorchNPU-BotCollaborators
Aug 13 Comments:

检测到社区任务相关 issue,自动添加标签:event: api-consistency

likedislike
FlippedFlipped
Aug 16 Modify description of issue
FlippedFlipped
Aug 16 Modify description of issue
FlippedFlipped
Aug 16 Modify description of issue
FlippedFlipped
Sep 10 Modify description of issue
TorchNPU-BotTorchNPU-BotCollaborators
Sep 10 Added label: help-wanted
TorchNPU-Bot
TorchNPU-BotCollaborators
Sep 10 Comments:

检测到社区任务相关 issue,自动添加标签:event: api-consistency、help-wanted

likedislike
TorchNPU-BotTorchNPU-BotCollaborators
Sep 10 Added label: event: accelerator-agnostic
TorchNPU-Bot
TorchNPU-BotCollaborators
Sep 10 Comments:

检测到社区任务相关 issue,自动添加标签:event: accelerator-agnostic、help-wanted

likedislike
FlippedFlipped
Sep 10 Modify description of issue
FlippedFlipped
Sep 10 Modify description of issue
群青世界群青世界Collaborators
Sep 30 changed custom state from TODO to DONE
群青世界群青世界Collaborators
Sep 30 Close issue
ascend-robotascend-robotCollaborators
Sep 30 Added label: resolved