Skip to content

[Fix] Pool pinned model and optimizer storage with checkpoint-safe DTensor views - #2277

Open
matrix72c wants to merge 4 commits into
InternLM:mainfrom
matrix72c:fix/pooled-pinned-storage
Open

matrix72c wants to merge 4 commits into
InternLM:mainfrom
matrix72c:fix/pooled-pinned-storage

Conversation

@matrix72c

@matrix72c matrix72c commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

CPU checks complete; CUDA/FSDP multi-rank and performance validation remain outstanding.

Root Cause

Allocating one pinned host tensor per optimizer moment or offloaded model tensor amplifies host allocator rounding. Pooling these destinations exposes two additional contracts: FSDP owns padded backing storage (which can be stale after HF leaf materialization), and PyTorch 2.10 DTensor wrappers with nonzero local offsets cannot be serialized normally even though their ordinary local views are valid.

Fix

This is one logical PR, combining the shared storage implementation and its consumers rather than stacking allocator/Adam/model PRs.

  • Share one bounded pinned allocator using deterministic indexed best-fit planning, preserve-format dense views, optional zero initialization, and per-slab nonblocking foreach copies. Slabs are capped at 1 GiB except individual oversized requests; small slabs allocate only their used bytes.
  • Add a checkpoint-only zero-offset DTensor wrapper retaining the exact local tensor and spec. No live tensor replacement or checkpoint data copy is needed. Full-state torch.save deduplicates shared storages; DCP compacts individual views. Raw torch.save of a single view still writes its entire slab unless the caller explicitly clones it.
  • Allocate SwapAdamW moments directly into pooled storage while preserving upstream [Fix] Load SwapAdamW state in place to keep pinned host residency #2225's canonical self.state, step path, and in-place loader helpers. Do not restore the old parameter/group or CPU-state maps. Checkpoint dictionaries are copied before wrapping offset DTensors so runtime state identity remains unchanged.
  • Offload model parameters, gradients and ordinary buffers through Module._apply, preserving move/FSDP hooks and fallback behavior for unsupported layouts/subclasses. Refresh FSDP sharded backing before planning, including HF-load-before-first-forward cases, and allocate the full padded backing rather than just a visible shard.
  • Wrap detached model checkpoint DTensors after ordinary hooks; preserve destination identity, metadata, prefix semantics and keep_vars=True behavior.
  • Extend existing regressions for FP32 parameter/buffer PrecisionPolicy declarations, offset checkpoint roundtrips, optimizer load hooks, and continued optimizer updates after save/reset/restore. Add an explicit CUDA/FSDP precision offload/HF-export roundtrip test, not executed in this CPU-only verification.

No HF-loader closure-lifetime fix, dependency changes, production pins, topic lists, integration history, or unrelated refactors are included.

Code Reference

  • Fixed base: d841a3feeba4565054ad773fce5335a4734def88
  • Topic: fix/pooled-pinned-storage
  • Head: bd23f5d27d6a51f550bf8cfd4ebed8485c3e14e0
  • Net diff: 9 files, 1,346 insertions, 12 deletions; 4 reviewable commits, no merge commits.
  • Source changes were adapted as net increments from a9e9c9ac, 3a03d9a0, and 4f3ad4fe; their historical merge chains were not cherry-picked.

Test Plan — Completed

Environment: existing sandbox-rl-dev, Python 3.12.12 at /opt/venv/bin/python, Torch 2.10.0, Ray 2.56.1, Transformers 5.17.0, FLA 0.5.2, LMDeploy 0.18.0. The actual XTuner import was verified as /workspace/.tools/worktrees/pr-pooled-20261109/xtuner/__init__.py. No environment installation or persistent PYTHONPATH change was made. Ray 2.56.1 differs from main's all-extra Ray 2.58.0 requirement; these tests do not initialize Ray and do not establish full environment compatibility.

All CPU invocations used the following call-local settings:

sudo -n -u jc -g docker docker exec \
  -e PYTHONPATH=/workspace/.tools/worktrees/pr-pooled-20261109 \
  -e OMP_NUM_THREADS=1 -e MKL_NUM_THREADS=1 -e OPENBLAS_NUM_THREADS=1 \
  -w /workspace/.tools/worktrees/pr-pooled-20261109 sandbox-rl-dev \
  /opt/venv/bin/python -m pytest -ra \
  -o cache_dir=/tmp/xtuner-unit-test/pr-pooled-20261109/pytest-cache \
  --junitxml=/workspace/.tools/pr-pooled-20261109-cpu-final.xml \
  tests/utils/test_pinned_memory.py \
  tests/utils/test_dtensor.py \
  tests/optim/test_swap_adamw_storage.py::TestPinnedSlabPlan \
  tests/optim/test_swap_adamw_storage.py::TestSwapAdamWStorageCPU \
  tests/model/test_pinned_model_offload.py::TestModelOffloadCPU
  • Collected exactly 31 CPU tests before running; no whole-file GPU selection.
  • Final head: 31 passed, 0 failed, 0 skipped, pytest exit 0, 0.57 s pytest execution time (not a performance benchmark).
  • Coverage includes layouts/zero-size shards, allocation accounting, DTensor metadata/serialization/aliasing, Adam math and checkpoint-resume parity, load/state-dict hooks, preserved state/group identity, DCP storage payload and restoration, model destination semantics, FP32 parameter/buffer checkpoint dtype preservation, and autograd fallback for differentiable buffers.
  • CPU allocation tests mock pinning/accelerator boundaries. They do not establish actual CUDA pinned-memory event ownership or FSDP behavior.
  • Ordinary tests/ files are outside the pre-commit filter: explicit python -m ruff check and python -m ruff format --check passed for all four changed test files.
  • Focused pre-commit on all five changed implementation files: exit 0, all applicable hooks passed, including mypy (432 source files) and pydantic-extra-check. Non-applicable YAML/requirements/Markdown hooks skipped. The cached mypy hook uses Torch 2.6.0 stubs, not the runtime Torch 2.10.0 environment.
  • git diff --check d841a3fe passed; final topic worktree is clean.

Full-hook failure disclosure

pre-commit run --all-files was executed and returned exit 1. It exposed:

  1. Existing unrelated formatting/import-order changes under seven autotest/ files. These automatic edits were inspected and reverted to the clean topic commit; they are not included in this PR.
  2. Two new utility module docstrings requiring docformatter wrapping; fixed in this PR.
  3. One missing private Tensor builtin in the Torch 2.6 type stubs (_make_wrapper_subclass); documented and narrowly annotated with type: ignore[attr-defined]. Runtime checkpoint tests exercise the builtin directly.
  4. Pydantic hook reported “files were modified” during that run, which overlapped a documentation edit; its subsequent focused rerun passed. Optional backend imports (NPU/cuDNN/DeepEP/vLLM/bitsandbytes) emit environment warnings and are not evidence of those backends being validated.

The final relevant-file hook run passes, but this is not a claim that the full repository hook baseline is clean. No unrelated formatting or dependency repair was folded into the PR.

Outstanding Validation

  • TestSwapAdamWStorageGPU and TestModelOffloadGPU, including real pinning, nondefault streams/event lifetime, uneven/empty FSDP shards, HF loading before first offload, and PrecisionPolicy CPU↔CUDA/checkpoint/HF-export behavior: not run.
  • Existing tests/engine/test_swap_adamw_engine_resume.py GPU/DCP resume tests: not run; require target GPU resources and model assets. The file remains upstream's implementation, not replaced with an older copy.
  • Target-device latency, peak device memory and pinned-host allocation before/after measurements: not run under this CPU-only/no-heavy-benchmark authorization. The metadata-only histogram regression checks allocator-rounding estimates, not measured CUDA memory or throughput. No end-to-end performance claim is made.
  • No training smoke, full test suite, Ray integration, dependency upgrade, image publication or production pin update.

Target CUDA/multi-rank checkpoint/continued-training checks and representative performance measurements remain outstanding.

@matrix72c
matrix72c marked this pull request as ready for review November 9, 2026 09:46
@matrix72c
matrix72c force-pushed the fix/pooled-pinned-storage branch from bd23f5d to df94de9 Compare November 23, 2026 03:54

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant