Repository navigation
[AffineIR] Move shared affine index and box geometry into affine_geometry - #9010
Merged
Merged
Conversation
jinyouzhi
force-pushed
the
affine-geometry-move
branch
from
November 9, 2026 04:56
e8034e1 to
8ea2326
Compare
jinyouzhi
marked this pull request as ready for review
November 9, 2026 04:57
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Row-major strides, products, coordinate/address conversion, range-to-box splitting and LogicalBox were duplicated across affine.py, affine_transfer.py and autoep_affine.py. Collect one copy in deepspeed/checkpoint/affine_geometry.py and import it under the old private names, so call sites and behavior are unchanged. This is the pure move that the planner complexity work builds on. Signed-off-by: Jin, Youzhi <youzhi.jin@intel.com>
delock
self-requested a review
November 10, 2026 09:00
This was referenced Nov 11, 2026
delock
approved these changes
Nov 11, 2026
delock
enabled auto-merge
November 11, 2026 15:29
Contributor
Author
|
@delock CI looks not normal, could you rerun? Thanks |
github-merge-queue
Bot
removed this pull request from the merge queue due to failed status checks
Nov 12, 2026
banxingmjj
pushed a commit
to openanolis/DeepSpeed
that referenced
this pull request
Nov 14, 2026
…omparisons (deepspeedai#9011) **Stacked on deepspeedai#9010** (only the last two commits are new here; I will rebase after deepspeedai#9010 merges). `_validate_holders` compared every piece with every other piece, `_sources` compared every source region with every other region, and `_shards_tile` compared each rank's pieces pairwise by shard address. Planning time therefore grew quadratically with the number of pieces, and a map with 1024 pieces already exceeded the default `max_pair_checks`. When no rank repeats a box and distinct boxes do not overlap, a rank covers a box exactly when it holds that very box, so the holders of each box can be read from a table. This PR adds `boxes_disjoint` to `affine_geometry`. It sweeps along the axis whose box origins vary most and compares each box only with the boxes still open where it starts. The same sweep proves that a rank's pieces tile its shard when they are disjoint by address and fill it (suggested by 0z5a in review). Maps that fail the fast checks fall back to the original pairwise walk, which names the offending piece, so error messages are unchanged, and maps that pass no longer hit the per-rank `len(held)**2` budget. The sweep counts its comparisons against `max_pair_checks` too (suggested by Achyuthan-S in review). A disjoint layout can keep every box open for the whole sweep: for example, h full-height one-column boxes plus 2h one-element boxes beside them. When the sweep runs out of budget it reports "not shown disjoint". It compares at most n·(n−1)/2 pairs, so running out implies n² > `max_pair_checks`, and the pairwise fallback refuses at once. With 4,095 such pieces, planning went from 19.2 s to a budget refusal in 0.6 s. Planning time (8 ranks with interleaved rows, re-sharded to 8 row shards, 64 columns; ms, single CPU process): | pieces | before | holders/sources only | + shard addresses (this PR) | |---|---|---|---| | 256 | 211 | 15 | 7 | | 512 | 827 | 46 | 15 | | 1024 | 3278 (refused by default budget) | 156 | 33 | | 2048 | 12926 | 569 | 76 | | 4096 | 50469 | 2227 | 235 | Tests: - Randomized oracle over 200 seeds: plans and errors match the pairwise walk, including replicas split at different points, overlapping pieces and wrong holder lists. - `boxes_disjoint` is checked against an all-pairs reference over 100 seeds. - Mutation check: the tests catch dropped intersections and wrong holder sets. - A rank holding 1024 pieces plans under the default `max_pair_checks` (refused before this change). - The always-open layout above plans correctly under the default budget and is refused with `max_pair_checks` just below its sweep cost. Without the sweep budget, that test plans instead of refusing. - `tests/unit/checkpoint -k affine` passes on 8× NVIDIA L20 (645 passed). At 12663c3 on CPU (`DS_ACCELERATOR=cpu`, 4 ranks): 642 passed, 5 skipped. The remaining near-quadratic steps, the source × target join and `_covers_union`, overlap with deepspeedai#8936 and will follow after it lands; segment merging in `_coalesce` has its own `max_merge_checks` budget and will follow separately. --------- Signed-off-by: Jin, Youzhi <youzhi.jin@intel.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Ma, Guokai <guokai.ma@gmail.com>
banxingmjj
pushed a commit
to openanolis/DeepSpeed
that referenced
this pull request
Nov 15, 2026
deepspeedai#9027) ## Why A replica policy (deepspeedai#8936) or cost model (deepspeedai#8252) needs to know what a batch will cost before running it: messages per peer, rounds, and staging memory. deepspeedai#8967 builds that report today by importing the executor's private `_packed_rounds` and `build_operations`. It then re-derives the in-place decision and the arena sizing, so its numbers would drift silently whenever the executor's staging changes. It asked for a public API instead. ## What `schedule_transfers(plans, endpoints, budget, element_size, process=None)` in `affine_transfer_executor` returns, for one process or for every process the endpoints name, the `ProcessSchedule` that `execute_transfers` would run. It uses no buffers and no communication: - the rounds per peer and direction (`ScheduledRound`: elements, chunks, and whether the round is sent or received in place); - the staging arena each peer direction allocates; - the local copies; - the round count that `TransferStats.rounds` reports. `execute_transfers` now builds its rounds and arenas from the same private computation, so the report and the run cannot disagree. The in-place decision is made from geometry rather than from the buffer. `_region` is an `as_strided` view of a packed shard, so it is contiguous exactly when `(chunk_shape, strides)` is row-major packed, ignoring extent-1 axes. Unchanged: - `plan_digest`, the batch fingerprint and `TransferStats`, so mixed versions still agree on the schedule; - `build_operations` and `_packed_rounds`, which keep their names and signatures until deepspeedai#8967 switches. ## Tests - `test_schedule_is_what_the_executor_runs` (2 and 4 ranks; mixed packed and strided regions with 16-element messages) checks: - rounds, sent, received and local-copy bytes against the executor's `TransferStats`; - that both sides of every message agree; - the arena sizes; - that the batch exercises both the in-place and the staged path. - `test_packed_regions_are_exactly_the_contiguous_views` compares the geometric rule with `Tensor.is_contiguous` over 2000 random shapes and strides, including extent-1 axes. - A single-process case covers local-only batches and the argument checks. - Forcing every round to be staged, or dropping the extent-1 exception, makes these tests fail. On macOS arm64 CPU (Python 3.12, torch 2.15.0): - The executor, external-group, planner and shard-map suites pass (263). - All other affine checkpoint tests pass, except the four `TestAffineUniversalCheckpointResume` cases, which fail the same way on master in this environment (uninstalled package version). - With deepspeedai#8967 merged on top, its analysis tests pass unchanged (59 together with the executor suite). - pre-commit is clean. This merges cleanly with deepspeedai#8936, deepspeedai#9010 and deepspeedai#9011. With deepspeedai#8966 and deepspeedai#8967 the only conflict is that both append a section to `affine-transfer.rst`. --------- Signed-off-by: 0z5a <dezhen.lu@student.uni-tuebingen.de> Co-authored-by: Ma, Guokai <guokai.ma@gmail.com>
banxingmjj
pushed a commit
to openanolis/DeepSpeed
that referenced
this pull request
Nov 18, 2026
…ons (deepspeedai#9039) **Rebased on master** (PRs deepspeedai#9010 and deepspeedai#9011 have merged; this branch is rebased on master at `5dc44e8`, so the diff contains only this PR's changes). `ParamAffineMap._validate_destinations` (added in deepspeedai#8922) checks the box-shaped pieces of a column split by comparing every box of a rank with every other one. `validate()` runs whenever a ZeRO, AutoEP or block-gather map is built and before every conversion, and this pass has no budget, so validation grows quadratically with the number of strided pieces per rank. This PR sweeps the boxes with `boxes_disjoint` from deepspeedai#9011 first. Only a rank that fails the sweep takes the pairwise walk, which names the shared shard address, so error messages are unchanged. The second commit moves the remaining hand-written geometry onto `affine_geometry`: `_dest_box` returns a `LogicalBox` built with `coordinate()`, the shared address comes from `intersection()` and `dot()`, and `address_range()` / `overlaps_itself()` move there from `affine.py`. The transfer executor reuses `address_range()` for its buffer-reach check and `dot()` for chunk offsets. No behavior or message changes. `validate()` of 8 ranks with interleaved columns (64 rows; ms, single CPU process): | pieces per rank | before | after | |---|---|---| | 128 | 29 | 4 | | 512 | 441 | 17 | | 2048 | 6654 | 68 | Tests: - Randomized check over 200 seeds: column blocks of row bands tiling a shard, half with one block shifted onto another. `validate()` refuses exactly the maps whose pieces write some shard address twice (enumerated independently in the test), and every refusal names an address that is written twice. The test checks this contract only, so it does not depend on which helper does the sweep. - Mutation checks: making the sweep always report "disjoint" fails 48 of the 200 cases. Forcing every rank through the pairwise walk still passes all 200. - All `tests/unit/checkpoint/test_*affine*` files: 839 passed, 1 skipped on 4× NVIDIA L20 at f6e1f6c. At ac3a329 on CPU (`DS_ACCELERATOR=cpu`, 4 ranks): 842 passed, 5 skipped. ## AI assistance Implementation, tests and this description were drafted with GitHub Copilot CLI and reviewed/validated by the author. --------- Signed-off-by: Jin, Youzhi <youzhi.jin@intel.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Ma, Guokai <guokai.ma@gmail.com>
banxingmjj
pushed a commit
to openanolis/DeepSpeed
that referenced
this pull request
Nov 23, 2026
…peedai#9052) Refs deepspeedai#9026 (open question 8), deepspeedai#9045. ### Why A rollout replica that changes placement can often keep a tensor-parallel shard that is still current, while the trainer's ZeRO-3 partitions hold the whole parameter. `plan_transfer` can read a block from any of its holders only if the source map's blocks are equal or disjoint and each block lists every holder. A map that simply lists both layouts' pieces breaks both rules, since a partition can start or end inside a row of the shard. So today the planner refuses it, and deepspeedai#9045 falls back to its own planner for these weights. ### What - `union_affine_maps(maps)` in `deepspeed/checkpoint/affine.py` returns one map of a parameter that several layouts hold at once. - Each piece is cut at the edges of every block held over it, in any layout (replicas within one layout may store a region whole or in parts), and each cut piece lists the holders from every layout. - A cut keeps the piece's strides and moves its offsets, so every location still stores exactly what it did. - Layouts use disjoint locations, one per buffer. `TransferEndpoints` already lets several locations map to one process. - More than two layouts are merged pairwise. - Blocks are taken in order of their first row, and each is compared only with the parts that still reach into its rows; a piece is cut against only the parts that start in its rows. That keeps the work close to linear in the number of partitions (see Cost). - Layouts that contradict each other raise `InvalidMapError`, and a piece that is not an axis-aligned block raises `UnsupportedLayoutError`: the planner's types for the same problems, so a caller that falls back on `AffineTransferError` catches these too. - `subtract` moves unchanged from `affine_transfer._subtract` into `affine_geometry`, the module deepspeedai#9010 added for shared box arithmetic. The planner imports it under its old name. - Spec §10.8 and a section in `affine-transfer.rst`, after the replica-policy section from deepspeedai#8936. ### Scope Cuts along rows and along columns are both planned. A ZeRO-3 block of several rows cut at a column edge keeps its row-major strides and its partition's offset, so it is not dense in its flat shard; the planner reads such shards since @0z5a's deepspeedai#9070. ### Cost @jinyouzhi measured the first version growing with the square of the number of ZeRO-3 partitions. `union_affine_maps` on a (4096, 4096) parameter's ZeRO-3 partitions plus another layout, macOS arm64 CPU (before = the previous version): | Other layout | 200 partitions | 1000 partitions | | --- | --- | --- | | 8-way row split | 1.93 s → 0.03 s | 48.0 s → 0.18 s | | 8-way column split | 11.0 s → 0.26 s | 1.3 s (34k pieces) | | whole replica | 1.91 s → 0.03 s | 0.18 s | A column split is the slowest case left, because each of its blocks spans every row. A union is cut at every layout's edges, so it can exceed the default `PlanBudget` (4,096 pieces per map). `plan_transfer` on the same unions, into a row-split and a column-split TP8 target (the same for both unless noted): | Partitions + other layout | Pieces | Default `PlanBudget()` | `max_pieces_per_map=1 << 16` | | --- | --- | --- | --- | | 200 + 8-way row | 1,196 | planned | planned | | 200 + 8-way column | 6,782 | refused (pieces) | planned | | 1000 + 8-way row | 5,996 | refused (pieces) | planned | | 1000 + 8-way column | 33,976 | refused (pieces) | into rows: planned (2.3 s); into columns: refused at `max_merge_checks` (262,144), planned (3.5 s) with `max_merge_checks` and `max_pair_checks` raised as well | The docs now show the budget next to the call (thanks @delock). ### Tests `test_affine_transfer_plan.py`: - A surviving row shard plus ZeRO-3 partitions, in 4 configurations (uneven TP sizes, one or two surviving ranks, 1 to 5 partitions), planned into a row-split and a column-split target. Checked: - each element's holders are exactly the union of both layouts' holders; - every location extracts what its own layout says; - every plan reproduces `extract` exactly; - the surviving shard is read. - Three layouts merged in all six orders: the same holders, and exact plans. - A column cut, in 3 configurations (one or two surviving column shards, 2 to 7 partitions): holders, and exact plans into a row-split and a column-split target that read the surviving shard. With deepspeedai#9070's planner change reverted, 2 of the 3 are refused. - A layout whose replicas store a block whole and in two halves, merged with ZeRO-3 partitions: holders, and an exact plan into a column-split target. - Refusals, with the planner's error types: no maps, a location in both layouts, different shapes, a transposed piece that is not a block, and a row-major run that wraps into the next row. `test_affine_transfer_executor.py`: on 2 ranks, one process holds a ZeRO-3 partition and a surviving row shard under two locations. The plan runs through `execute_transfer`, and every target shard equals `extract`. Not merging the holders, dropping the part of a block that a later block doesn't overlap, or leaving the destination offset unmoved makes 9 of these 11 tests fail. Setting a part aside one row too early, or ending the search for the parts under a piece one row short, makes 6 and 7 of them fail. ### Validation The fifth commit changes only the spec and `affine-transfer.rst`: the column cut is planned since deepspeedai#9070, and the example passes a `PlanBudget` sized for a union. Rebased on master c00a7f6, after deepspeedai#9070 and deepspeedai#9093 merged. The only conflict was in `test_affine_transfer_executor.py`, where this PR and deepspeedai#9093 added test classes at the same place; both are kept. The three earlier commits are otherwise unchanged (`git range-diff`), and a fourth extends the column-cut test to plan. macOS arm64 CPU, Python 3.9.6, torch 2.8.0, gloo (`DS_ACCELERATOR=cpu LOCAL_SIZE=4`): - All nine affine test files: 959 passed (master c00a7f6: 948 passed). - yapf 0.43.0 and flake8 5.0.4 pass on the changed files. - 300 random unions of ZeRO-3 partitions (1 to 8) and surviving column shards (2 to 4 way, random widths, any non-empty subset), each planned into a row split and a column split: all 600 plans are exact, and all read a surviving shard. On GPU: 4× A100-SXM4-40GB (NVLink), driver 595.71.05, torch 2.12.1+cu130, NCCL 2.29.7, Python 3.12.11, with `pytest --forked` over the six `test_affine_*.py` files and `test_zero_affine.py`: this branch 905 passed and 1 skipped (master c00a7f6: 894 passed and 1 skipped), so the 11 new tests also pass over NCCL. Earlier, rebased on master 97aa3c1, after deepspeedai#9039 renamed the geometry imports. The only conflicts were those imports and `affine_geometry.__all__`; `subtract` now sits with master's unaliased imports. macOS arm64 CPU, Python 3.9.6, torch 2.8.0, gloo (`DS_ACCELERATOR=cpu LOCAL_SIZE=4`): - All nine affine test files: 933 passed (master 97aa3c1: 924 passed). - yapf 0.43.0 and flake8 5.0.4 pass on the changed files. - Against the previous version, on 6,000 random unions of two or three layouts (ZeRO-3 partitions, row and column splits, replicas, any subset of surviving shards): identical pieces, the same holders for every element, the same shard at every location, and the same refusals. The runs below are from before that rebase and the cost change. Earlier, rebased on master 892ed83, which includes deepspeedai#9011. The code and test changes are the same as before the rebase; the only conflicts were additions next to deepspeedai#9011's (`subtract` next to `boxes_disjoint` in `affine_geometry.py`, and the imports). macOS arm64 CPU, Python 3.9.6, torch 2.8.0, gloo (`DS_ACCELERATOR=cpu LOCAL_SIZE=4`): - All eight affine test files: 715 passed (master 892ed83: 706 passed). - yapf and flake8 pass on the files the rebase touched. On master 988b2e3, before that rebase (with deepspeedai#9010 and deepspeedai#8936): - All eight affine test files, then including deepspeedai#8936's `test_affine_replica_policy.py`: 412 passed. - The four union configurations above, planned through deepspeedai#8936's `plan_transfers` with `local_first_least_loaded` and with `first_holder` into both targets: all 16 plans reproduce `extract` exactly. - Against the previous commit (110ff4b, before the two fixes from review), on random layouts: 300 unions with a row-split surviving shard, 300 with a column-split one, and 300 of three or four layouts. Every element has the same holders, and every plan into a row- or column-split target has the same outcome as before: exact, except 82 of the column-split cases, which both commits refuse (the column cut under Scope). - pre-commit passes on the changed files. Before the rebase, on f9fe4df with deepspeedai#9010 applied: - All seven affine test files: 346 passed. - With deepspeedai#9011 on top: 648 passed. The only conflicts were adjacent additions: import lines and appended definitions. - 300 random two-layout cases (uneven TP sizes, any subset of surviving ranks, 1 to 6 partitions): - holders and map-level exactness hold in every case; - cuts along rows: 137 of 137 planned and exact; - cuts along columns: 79 planned and exact, and 84 refused by the current planner. - 300 random unions of three or four layouts, merged in random order: all planned and exact. On GPU, also before the rebase: 4× A100-SXM4-40GB (NVLink), driver 595.71.05, torch 2.12.1+cu130, NCCL 2.29.7, Python 3.12.11, with `pytest --forked` over six of the affine test files (all but `test_autoep_affine_universal.py`): - master (8a6b53f): 317 passed, 1 skipped; - this branch: 325 passed, 1 skipped, so the 8 new tests also pass over NCCL, including the executor test. - The one skip is the external-group test that runs only on the CPU accelerator. cc @0z5a @LiRunGuo @jinyouzhi --------- Signed-off-by: Achyuthan Sivasankar <achyuthan.sivasankar@gmail.com> Co-authored-by: Ma, Guokai <guokai.ma@gmail.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Row-major strides, shape products, offset/coordinate/address conversion, row-major range-to-box splitting and
LogicalBoxwere each implemented two or three times acrossaffine.py,affine_transfer.pyandautoep_affine.py.This PR collects one copy of each in a new pure module,
deepspeed/checkpoint/affine_geometry.py, and imports it under the old private names. Call sites and behavior are unchanged.productaffine._product,affine_transfer._product,autoep_affine._productrow_major_stridesaffine,affine_transfer,autoep_affinecoordinateaffine_transfer._coordinatedot,strided_address,row_major_range_boxesaffineLogicalBoxaffine_transferThis is a pure move, kept separate so that the follow-up planner-complexity work, which replaces pairwise O(n²) checks with sweeps over these primitives, reviews as algorithm changes only. The first follow-up (holder/source validation) is stacked on this PR.
Test: existing
tests/unit/checkpoint -k affinepasses unchanged on CPU.