Skip to content

[BREAKING, perf] Compact controller state with partition-local rows - #249

Closed
ji-huazhong wants to merge 2 commits into
Ascend:mainfrom
ji-huazhong:refactor/compact-controller-state
Closed

ji-huazhong wants to merge 2 commits into
Ascend:mainfrom
ji-huazhong:refactor/compact-controller-state

Conversation

@ji-huazhong

@ji-huazhong ji-huazhong commented Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator

Problem and implementation

The Python controller indexes each partition's production and consumption tensors by global sample index. A partition containing only 4,096 samples starting at index 1,000,000 therefore allocates more than a million rows. Multiple partitions duplicate these unused rows, and partition statistics scan them.

Store those tensors in partition-local rows and reuse cleared slots. Consecutive indexes use a range instead of a per-sample dictionary. Full-range queries generate indexes on demand; subsets and irregular layouts cache sorted lookups until membership changes. Queries and updates translate global indexes at the boundary. Sampling order, KV keys, global-indexed query results, and SimpleStorage payload routing are preserved. Reserved rows and consumption retained by clear_consumption=False keep their existing semantics. Explicit global-indexed status views materialize dense tensors when needed.

Breaking change: Python checkpoint format

Python controller checkpoints now use format version 2. Convert existing unversioned checkpoints before loading them:

python scripts/convert_checkpoint.py /path/to/old_checkpoint /path/to/converted_checkpoint

The converter preserves the original directory, copies storage files unchanged, retains reserved rows and historical consumption, and validates the converted checkpoint before publishing the destination. Load the result with tq.load_checkpoint as usual.

Rust already stores partition-local rows. Its checkpoint format is unchanged; its Python snapshot adapter now constructs the compact representation. The converter does not convert between controller backends.

Performance

CPU microbenchmarks against ffde754: 4,096 samples, 16 fields, two consumer tasks, ARM64, PyTorch 2.6.0, one Torch thread. Queries use the median of 15 interleaved rounds of 50 calls (five calls for statistics); insert/clear measurements use 21 independently prepared partitions. All query caches are warmed where applicable.

Operation Before After
Scan ready samples, dense indexes 328.6 µs 230.9 µs
Query production status, dense indexes 291.2 µs 160.8 µs
Query consumption status, dense indexes 131.9 µs 12.8 µs
Mark 512 samples consumed 32.5 µs 21.8 µs
Pack force-fetch metadata, dense indexes 603.0 µs 613.6 µs
Insert a dense batch into a new partition 844.4 µs 915.3 µs
Rewrite an existing dense batch 690.0 µs 797.3 µs
Clear a dense partition 1,215.9 µs 1,283.4 µs
Clear one quarter of a dense partition 365.0 µs 459.6 µs
Partition statistics, indexes starting at 1,000,000 33.60 ms 0.237 ms

Dense writes and partial clears still cost more than the original implementation. Compared with the initial compact-state commit 0a0cf72, the range optimization improves batch insertion from 1.28 ms to 0.92 ms and reduces retained index storage, while consumption queries increase from 7.9 µs to 12.8 µs because their indexes are now generated per request. These CPU measurements do not imply the same speedup for end-to-end training.

Controller state memory

The comparison accounts for production/consumption tensor buffers, row mapping and free-list objects/integers, and unique query-index buffers. Unchanged metadata and small tensor/cache wrappers are excluded; shared small integers are counted conservatively. These are retained state-structure sizes, not process RSS or peak query/training memory.

Scenario Before After Change
One partition, 4,096 samples, global indexes starting at 0 72.00 KiB 72.18 KiB +184 bytes
One partition, 4,096 samples, global indexes starting at 1,000,000 17.24 MiB 72.18 KiB -99.6%
64 partitions, 1,024 samples each, consecutive disjoint global-index ranges 36.56 MiB 1.14 MiB -96.9%

For the 64-partition case, state tensors shrink from 38,338,560 to 1,179,648 bytes. Range descriptors and free lists add 12,028 bytes, giving 1,191,676 bytes in total. Complete contiguous ranges retain no query-index buffers; those tensors are created during a query and released afterward. Irregular layouts materialize the row dictionary, and partial ranges retain query caches. Explicit global-indexed status views still allocate dense tensors on demand. These figures apply to the Python controller; Rust already uses partition-local rows.

Validation

  • Final pre-commit checks (including mypy, formatting, license and docstrings) and compileall passed.
  • Controller partition/Rust snapshot tests, Python checkpoint tests and reruns of the two failing cases: 78 passed. Rust checkpoint tests: 15 passed, one Python-only conversion case skipped.
  • Full Python suite: 1,007 passed, 16 skipped, two failures and six errors. One failure and all six errors match the documented main baseline (worker-death test affected by suite order; Yuanrong datasystem fixtures). The additional failure was a Ray node heartbeat loss that cancelled the controller actor before it started; its targeted rerun passed.
  • Conversion of an actual checkpoint produced by unchanged main passed, with production, consumption and reserved indexes compared in both partitions.
  • Regression coverage adds one partial-clear/row-reuse scenario at zero and nonzero index offsets and extends the existing capacity-growth test for a gap appearing after contiguous insertion. Existing checkpoint and pre-allocation coverage is reused.
  • The earlier compact-state commit 0a0cf72 completed 20 Geo3K / Qwen3.5-35B-A3B steps using the Python controller and SimpleStorage, exit code 0, with matching input-sample multisets and process source hashes. Final critic/score/mean: 0.7144; last-five-step mean: 0.6334. The subsequent range/cache optimization has been validated by the tests above, without another training run.

Signed-off-by: ji-huazhong <hzji210@gmail.com>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-30T15:51:20.584911Z 0a0cf72 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@0oshowero0

Copy link
Copy Markdown
Collaborator

This issue has been tackled in the Rust controller. Maybe it's better to fix the python controller in next release so that not all controller backends introduces breaking changes related to ckpt?

@ji-huazhong
ji-huazhong marked this pull request as draft November 30, 2026 16:22
Signed-off-by: ji-huazhong <hzji210@gmail.com>
@0oshowero0

Copy link
Copy Markdown
Collaborator

Thanks for putting this together! Switching DataPartitionStatus to partition-local rows with free-list slot reuse cleanly addresses the sparse-index memory bloat and get_statistics() overhead, and I appreciate the transparent memory/microbenchmark breakdown in the PR description.

Before merging, there are a few design and edge-case issues I'd like to discuss:

1. Checkpoint compatibility & migration path

Following up on the earlier comment about avoiding another checkpoint breaking change in this release: this PR only changes DataPartitionStatus's internal representation — storage files, index_manager, and sampler formats are unchanged, and the core conversion logic in scripts/convert_checkpoint.py is ~20 lines of pure in-memory transformation.

  • Preferred option (non-breaking): Write format_version = 2 in save_checkpoint(), and transparently upgrade unversioned legacy partitions in memory during load_checkpoint() / validate_checkpoint() (or DataPartitionStatus.__setstate__) with a deprecation warning. That avoids breaking existing Python checkpoints and removes the need for scripts/convert_checkpoint.py and its extra docs/test scaffolding (legacy support can be dropped in a later release).
  • If we do want a breaking change + offline converter, three things should be addressed:
    1. tq.load_checkpoint() hides the migration hint: tq.load_checkpoint() calls validate_checkpoint() first, which catches the ValueError mentioning scripts/convert_checkpoint.py, logs a warning, and returns False. As a result, public API callers only see RuntimeError: Invalid controller checkpoint: ... instead of the actionable migration message. (The new E2E test only invokes controller.load_checkpoint.remote(...) directly, not tq.load_checkpoint().)
    2. validate_checkpoint() does not check v2 partition invariants: It currently only checks state.get("format_version") == 2, without verifying the new required attributes (_production_status, _consumption_status, row_mapping, _free_rows, _next_row, _global_capacity) or basic invariants (e.g., global_indexes | pre_allocated_global_indexes <= row_mapping.keys(), unique in-bounds row indices disjoint from _free_rows, matching consumption tensor lengths). Since tq.load_checkpoint() is non-transactional and convert_checkpoint.py relies on validate_checkpoint() as its pre-publish gate, validating these invariants is important.
    3. scripts/convert_checkpoint.py I/O and fail-fast checks: shutil.copytree(source, converted) byte-copies the entire simple_storage/ directory (potentially tens of GB of tensors and SSD .blobs/ on shared storage) and also copies the old controller_state.pkl only to overwrite it. Also, a missing metadata.json or a dangling symlink at destination (destination.exists() is False) isn't caught until after the full copy finishes. Checking metadata.json and destination.is_symlink() upfront, excluding controller_state.pkl from the copy, and considering hardlinks (when on the same filesystem) would make conversion much safer and faster.

2. Aliasing vs. copy inconsistency in _as_global_status() and property overhead

  • _as_global_status() returns the live internal tensor when status.shape[0] == self._global_capacity and all(index == row for index, row in self.row_mapping.items()), and a fresh copy otherwise (sparse indexes, or after any out-of-order row reuse via LIFO _free_rows.pop()):
    • This creates inconsistent mutation/aliasing semantics across production_status, consumption_status, and get_consumption_status(..., mask=False). For example, get_consumption_status(..., mask=False) clones partition_global_index to protect _index_cache, yet returns the live _consumption_status[task] tensor on the dense identity path — so an in-place mutation like status.zero_() silently corrupts live controller state when dense, while being a no-op when sparse. Similarly, subsequent mark_consumed() updates are visible through a previously fetched tensor when dense, but not when sparse.
    • Because consumption_status is now a @property that builds a new dict and materializes _as_global_status() for every registered task on each access, even len(partition.consumption_status) or accessing a single task allocates dense _global_capacity-sized tensors for all tasks, and dict assignments like partition.consumption_status[task] = ... silently mutate a throwaway dict instead of raising.
    • Every access also runs an O(N) Python check (all(index == row ...)) and requires persisting _global_capacity in the v2 checkpoint format solely to preserve legacy over-allocated view shapes.
  • Suggestion: Have _as_global_status() always return an isolated copy (updating the two legacy unit tests that rely on tensor object identity), and reconsider whether _global_capacity needs to be persisted in the checkpoint format at all.

3. Fragile _index_cache invalidation coupling & duplicate cache entries

  • Hidden invalidation dependency: In _allocate_partition_indexes(), if a global index previously cleared with clear_consumption=False (still present in row_mapping) is reused by index_manager:
    1. _allocate_partition_indexes() mutates partition.global_indexes.update(indexes) from outside DataPartitionStatus.
    2. partition._ensure_rows(indexes) returns early without clearing _index_cache because the index is already in row_mapping.
    3. A subsequent update_production_status() also skips clearing _index_cache because self.global_indexes.issuperset(global_indices) is already True.
      Right now this only avoids a stale cache because activate_pre_allocated_indexes() unconditionally calls self._index_cache.clear() even when pre_allocated_global_indexes is empty. If someone later adds an early return to activate_pre_allocated_indexes() when there are no reserved indexes, reused indexes will silently disappear from scan_data_status / status queries.
    • Suggestion: Move global_indexes.update + _ensure_rows + _index_cache.clear() into a dedicated method on DataPartitionStatus so membership mutations and cache invalidation live in one place.
  • Duplicate cache entries in the common case: Once pre_allocated_global_indexes is empty (the common steady state after the first insert with default TQ_PRE_ALLOC_SAMPLE_NUM=1), _indexed_rows(include_reserved=True) and _indexed_rows(include_reserved=False) sort and store two identical (global_indexes, rows) tensor pairs under True and False. Normalizing the key to include_reserved and bool(self.pre_allocated_global_indexes) shares one entry and halves cache memory/work.

4. Maintainability & minor edge cases (non-blocking)

  • Encapsulation: row_mapping is public while the other coupled row-management fields are private, and TransferQueueController (7 call sites) plus rust_controller.py reach directly into _production_status, _ensure_rows, and _rows_for. Making _row_mapping private and exposing a couple of focused helper methods on DataPartitionStatus would keep the invariants easier to maintain.
  • clear_data() invariant: When clear_consumption=True, clear_data() pops indexes from row_mapping and removes them from global_indexes, but not from pre_allocated_global_indexes. While current controller paths (clear_meta / clear_partition) don't hit this, calling DataPartitionStatus.clear_data() directly with a reserved index breaks the pre_allocated_global_indexes <= row_mapping.keys() invariant and causes a KeyError in _rows_for().

@ji-huazhong ji-huazhong closed this Dec 2, 2026
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.

2 participants