Merged
[feat]: 为本地 FileSystemReader 增加可选 mmap 加载 #1074
[feat]: 为本地 FileSystemReader 增加可选 mmap 加载 #1074
Merged
AWWOLFAdd on Oct 22
AWWOLF
AWWOLF
Oct 22

摘要

为 torchtitan-npu 固定的 PyTorch 2.14.0 回移植上游可选的本地 DCP mmap 读取能力。上游改动见 PyTorch PR https://github.com/pytorch/pytorch/pull/201621。

补丁增加的显式接口如下:

reader = torch.distributed.checkpoint.FileSystemReader(
    checkpoint_id,
    mmap=True,
)

torch.distributed.checkpoint.load(
    state_dict,
    storage_reader=reader,
)

mmap 默认关闭。

动机

一个 DCP .distcp 文件里可以包含多段独立的 torch.save ZIP。普通的 torch.load(..., mmap=True) 只能映射一份完整的独立 checkpoint 文件,不能直接映射其中某一段文件视图。

这个回移植对每个本地 .distcp 只做一次映射,再按 DCP 元数据里的偏移和有界 ZIP 视图读取请求的 tensor 存储区域。

实现

  • 给 FileSystemReader 增加可选参数 mmap。
  • mmap=False 时保持原来的读取路径。
  • 只对内置本地 FileSystem 使用 mmap。
  • 存在 storage transform 时回退到原 reader。
  • 每次 read_data 对同一个 backing file 最多映射一次。
  • ZIP 解析限制在当前选中的 DCP blob 内。
  • 压缩或加密的 tensor record 回退到 torch.load。
  • 保留 BYTE_IO、planner narrow、目标 copy_ 和 commit 行为。
  • 只 patch:
    • FileSystemReader.__init__
    • FileSystemReader.read_data

本 PR 不 patch torch.load、dcp.load、torch.serialization._load,也不 patch 全局 _ReaderView。

不修改 CheckpointManager.dcp_load(),也不增加会自动打开 mmap 的训练配置。

使用方式

创建 reader 之前先导入 torchtitan-npu,这样兼容补丁会执行 apply():

import torchtitan_npu
import torch.distributed.checkpoint as dcp

reader = dcp.FileSystemReader(
    checkpoint_id,
    mmap=True,
)

dcp.load(
    state_dict,
    storage_reader=reader,
)

原有路径不变:

dcp.load(
    state_dict,
    checkpoint_id=checkpoint_id,
)

这条路径不会自动开启 mmap。

范围

这是面向同一字节序下、由 PyTorch/TorchTitan 在本机正常生成的可信本地 DCP checkpoint 的最小回移植。

不包含:

  • 在 TorchTitan CheckpointManager 里自动开启 mmap;
  • 给顶层 dcp.load 增加 mmap 参数;
  • 远程或自定义 storage reader 的 mmap;
  • 改变 EMA、PEFT 或其他 CheckpointManager 的加载行为;
  • 用功能测试声称性能提升。

固定的 PyTorch 依赖包含上游实现后,应删除这个补丁。

验证

环境:

  • PyTorch:2.14.0+cpu
  • TorchTitan:该隔离环境未导入;仓库锁定版本仍是 0.3.0
  • 设备:CPU
  • 分布式进程组:未初始化

检查在容器 dcp-mmap-largeblob-20261021 的独立前缀 /work/venv214 中完成。该解释器里 FileSystemReader 的签名是 (path, _extension_registry=None),补丁生效前没有 mmap。容器预装的 2.14.0.dev20260701+cpu 没有用于这些结果。

测试:

/work/venv214/bin/python -m pytest tests/unit_tests/extensions/torchtitan/components/test_checkpoint.py -q -p no:cacheprovider --noconftest
13 passed, 1 warning in 9.92s

这条 warning 是该前缀缺少 NumPy,不是测试失败。

同一测试文件在本机隔离的 2.14.0+cpu 前缀上也通过:13 passed。

显式 mmap DCP 冒烟测试:

DCP save: PASS
FileSystemReader(..., mmap=True): PASS
dcp.load(..., storage_reader=reader): PASS
Tensor equality: PASS
_load_zip_region calls: 2

冒烟脚本直接加载 torchtitan_npu/patches/torchtitan/distributed/checkpoint/filesystem.py。在该容器中导入 torchtitan_npu 包会带入 torch_npu,并与这份 CPU libtorch 冲突。apply() 仍由该模块自身执行。加载后两个 tensor(1024x1024 fp32 和长度为 4097 的 bf16)与保存前一致。

静态检查:

git diff --check: PASS
global torch.load/dcp.load/serialization._load patch: none
FileSystemReader methods patched: 2

上游

likedislike
Pull Request has been successfully merged by CANN-robot.
(Thank you for AWWOLF's contribution.)
AWWOLFAWWOLF
Oct 22 Created pull request, commit b9d284df
atomgit-bot
atomgit-botCollaborators
Oct 22 Comments:

变更摘要

本 PR 以补丁形式为本地 DCP FileSystemReader 增加可选的 mmap 加载能力:在 torchtitan_npu/patches/torchtitan/distributed/checkpoint/filesystem.py 中按现有 apply() 方式替换 FileSystemReader.__init__ 与 read_data,为构造函数补上 keyword-only 的 mmap=False;显式开启后,符合条件的本地 tensor 请求会将 storage 关联到映射的 checkpoint 文件,并沿用 planner 选出的 narrow 与目标拷贝。默认 mmap=False 时完全走原有实现,上游 PyTorch 已提供 mmap 参数时 apply() 直接返回,避免重复替换。

主要改动

  • 新增可选 mmap 构造参数:_patched_init 在调用原 FileSystemReader.__init__ 后记录 self.mmap,使 dcp.FileSystemReader(path, mmap=True) 可用且不改变原有初始化行为。
  • read_data 增加映射分支:_patched_read_data 在关闭时直通 _ORIGINAL_READ_DATA;开启时按 relative_path 分组,用 torch.UntypedStorage.from_file 懒创建整文件私有映射,并对 offset/length 做越界校验后调用 _load_zip_region 复用 _load(overall_storage=...)。
  • 多段 ZIP 区域加载与回退策略:_load_zip_region 为 .distcp 中单段 ZIP 构造有界视图,校验 PK\x03\x04 头、record 范围与 record 大小/nbytes 一致性;压缩、加密、TorchScript 或需换字节序时抛出 _UnsupportedZipRegion,回退到原 torch.load。
  • _ReaderView 有界读取修正:替换 _ReaderView.seek、read、readinto,将读写限制在 offset/len 区间内,为映射区域提供正确的边界语义。
  • 补丁注册与导出:新增 torchtitan_npu/patches/torchtitan/distributed/checkpoint/__init__.py,并在 torchtitan_npu/patches/torchtitan/__init__.py 中导入 distributed.checkpoint.filesystem;apply() 同时把 _load_zip_region、_UnsupportedZipRegion 挂到 torch.serialization 上。
likedislike
Incorrect?
atomgit-bot
atomgit-botCollaborators
Oct 22 Comments:

代码审查

审查结论

逐文件确认

  • torchtitan_npu/patches/torchtitan/__init__.py:仅新增一行带 # noqa: F401 的副作用导入(from .distributed.checkpoint import filesystem),导入排序与相邻 checkpoint < flex_shard 一致,包路径 distributed/checkpoint/ 存在且父包 distributed/__init__.py 存在 —— 未发现问题。
  • torchtitan_npu/patches/torchtitan/distributed/checkpoint/__init__.py:仅导入子模块触发 apply(),导入是幂等的(模块缓存),无循环依赖 —— 未发现问题。
  • torchtitan_npu/patches/torchtitan/distributed/checkpoint/filesystem.py:发现 4 项问题(下述)。

发现清单(共 4 项)

优先级 位置 问题
P2 filesystem.py:171-172 _patched_init 无条件把 _extension_registry 位置参数透传给原 __init__,而 apply() 只校验 mmap;在不接受该参数的 torch 版本上,mmap=False 与所有 DCP 加载都会 TypeError
P2 filesystem.py:159-165 storage nbytes 与 record_sizes 做严格集合成员比较:粒度错(不是本 record 的 size)且忽略 zip record 的对齐补齐,失败时抛 RuntimeError 直接中止而非回退 torch.load
P3 filesystem.py:247 commit_tensor(req, target) 提交的是目标张量,原始路径提交的是加载出的 tensor,两条路径对 planner 契约不一致
P3 filesystem.py:45-47 _ORIGINAL_SEEK/_ORIGINAL_READ/_ORIGINAL_READINTO 备份后从未使用(死代码)

整体风险判断

默认路径(mmap=False)理论上应当零影响,但该保证依赖三个未经校验的前提:原始 __init__ 接受被透传的第二位置参数、_ReaderView 的 base_stream/offset/len 属性与语义未变、以及 storage 字节数与 record 大小严格相等。前两项一旦在目标 torch 版本上不成立,影响范围是全进程 DCP 加载而非可选特性;第三项会让 mmap=True 对部分合法 checkpoint 直接失败。中等风险,建议补充「mmap=False 与未打补丁行为一致」「mmap=True 在同一 checkpoint 上成功加载」两类回归验证后再合入。

类型 数量
🔴 阻塞 0
🟡 建议 2

💬 仅评论

likedislike
Incorrect?
CANN-robotCANN-robotCollaborators
Oct 22 Added label: cann-cla/yes
CANN-robot
CANN-robotCollaborators
Oct 22 Comments:

Thanks for your pull-request.
The full list of commands accepted by me can be found at here.
You can get sig-info at here.
You can self-configure the PR merge rules for this repository. For more details, please refer to Here.
For more, you also can visit HICANN.


PR Approval Progress

✅ Congratulations! All modules have met the lgtm and approve requirements.

Module Approval Details

module lgtm status approve status
repo-cann/torchtitan-npu ✅ hwcaifubi, xuyujun (2/2) ✅ hwcaifubi (1/1)

💡 Tip:

  • Committer can comment /approve or /lgtm
  • Commenting /approve implies both code review (lgtm) and intent to merge (approve)

CLA Signature Pass

ZHANGJIAOGOU, thanks for your pull request. All authors of the commits have signed the CLA. 👍

likedislike
192 messages are collapsed here。 See more
CANN-robotCANN-robotCollaborators
Oct 28 Added label: approved
xuyujun
xuyujunCollaborators
Oct 28 Comments:

/lgtm

likedislike
CANN-robotCANN-robotCollaborators
Oct 28 Added label: lgtm
CANN-robotCANN-robotCollaborators
Oct 28 Merged pull request
CANN-robot
CANN-robotCollaborators
Oct 28 Comments:

Pull Request 已合并或已关闭。

If you want to solve this problem, you can click here to do it in the FAQs.

likedislike