Repository navigation
Skip the per-layer RoPE stream sync unless the model spans several devices - #13609
Conversation
…vices The stream drain after RoPE (#3049, #3061) fired on every host with more than one visible GPU, so single-GPU training or one DDP rank on a multi-GPU machine paid one host-blocking synchronize per attention layer per forward and per gradient checkpoint recompute. inplace_rope_embedding synced even with one GPU. Keep the drain only once RoPE has run on a second device in the process (device_map / pipeline split), which is the case it was added for.
|
@codex review |
Codex Review SummaryThis 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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: de33b98c9d
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if len(_ROPE_DEVICES) > 1: | ||
| torch_device_stream(Q.device).synchronize() |
There was a problem hiding this comment.
Preserve synchronization for the first split-model shard
When a split model's first forward visits layers in device order (for example, cuda:0 layers followed by cuda:1 layers), every RoPE call on cuda:0 sees a one-element set and skips the synchronization; discovering cuda:1 only synchronizes cuda:1 and cannot retroactively drain cuda:0. Thus the first shard of the first forward loses the workaround that was retained specifically to prevent split-model NaNs, leaving that initial pass vulnerable to the original race. The split status needs to be known before execution or synchronization must remain enabled during device discovery.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in a7f8a84. Split models are now registered at load (register_split_model, called from _repair_dispatch_hooks, which every split load goes through), so the drain runs on every RoPE call from the first one, including the cuda:0 shard of the first forward. On 2 GPUs with Llama-3.2-1B split 8 + 8, the first forward + backward now drains 16 times on each device, the same as main. Covered by test_split_model_syncs_from_the_first_call.
| # Accelerator indices RoPE has run on in this process. The stream drain after RoPE was added for models | ||
| # split over several GPUs (device_map / pipeline, #3049, #3061). One model on one device of a multi-GPU | ||
| # host, or one DDP rank, launches every kernel on that device's current stream, so it skips the drain. | ||
| _ROPE_DEVICES = set() |
There was a problem hiding this comment.
Track RoPE devices per model instead of per process
Because _ROPE_DEVICES is process-global and never cleared, two independent single-device models that run on different GPUs—whether concurrently or sequentially—permanently make the set contain multiple indices. All later RoPE calls for both models then incur the per-layer host-blocking synchronization this change is intended to remove, even after one model is destroyed, so the claim that a single-device model skips the drain is false in long-lived multi-model processes. Split detection needs model-scoped state rather than an accumulating process-wide set.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in a7f8a84. The process-wide index set is gone. Only models whose hf_device_map spans two or more accelerators are registered, in a WeakSet, so two single-device models on different GPUs never turn the drain on, and freeing a split model turns it off again. Covered by test_independent_single_device_models_stay_unsynced and test_freed_split_model_stops_syncing.
…and only while one is alive
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a7f8a845b4
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if _SPLIT_MODELS or Q.get_device() != _current_device(): | ||
| torch_device_stream(Q.device).synchronize() |
There was a problem hiding this comment.
Preserve sync on current shards for hand-dispatched splits
When a user calls accelerate.dispatch_model() manually after loading—the fallback described here—_SPLIT_MODELS remains empty, so this condition synchronizes only layers away from the process's current device. For a map ordered across cuda:0 then cuda:1 while cuda:0 is current, every cuda:0 RoPE call, including the first shard, skips the split-model workaround even though the previous implementation synchronized every shard to avoid NaNs. Fresh evidence beyond the prior registered-loader report is the newly added unregistered-split path, whose test explicitly expects no synchronization for the first two cuda:0 calls; that path still needs to register the new device map or otherwise preserve synchronization for all shards.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in bfe789d. accelerate.dispatch_model is now wrapped to register the model it dispatches (and rebound where transformers imported it by name: modeling_utils on 4.x, integrations.accelerate / integrations.peft on 5.x), so a hand-dispatched split is registered before its first forward and every shard, including the one on the current device, drains from the first call. Checked on 2 GPUs with transformers 5.17.0 and 4.57.6, and covered by test_hand_dispatched_split_syncs_from_the_first_call. The off-current-device check stays only as a last fallback.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bfe789d50c
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| module = sys.modules.get(name) | ||
| if module is not None and getattr(module, "dispatch_model", None) is original: | ||
| module.dispatch_model = dispatch_model |
There was a problem hiding this comment.
Handle pre-bound dispatch aliases before skipping synchronization
When a caller binds dispatch_model before importing Unsloth (for example, from accelerate import dispatch_model), this loop cannot replace that local reference, so invoking it later can split the model without adding it to _SPLIT_MODELS. For a map whose first layers are on the current device, _sync_if_split then skips synchronization on that entire first shard and only catches the off-current shard, reopening the split-model NaN race. Fresh evidence beyond the earlier module-rebinding fix is that Python local aliases are not attributes of these sys.modules entries and therefore remain untouched; synchronization should stay conservative unless registration can be established independently of monkey-patching.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Addressed in c7d82d0. A local alias bound before Unsloth is imported cannot be rebound, so the fallback is now sticky: the first RoPE call on a device other than the current one turns the drain on for every later RoPE call in the process, on every device, as on main. What remains uncovered is only the current-device layers of the very first forward of a split made through such an alias, which needs both a hand dispatch and an import order Unsloth already warns about. Those layers launch on the current device's current stream, and their consumers run on that same stream. Covered by test_unregistered_split_syncs_once_seen.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c7d82d02be
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if len(_accelerator_indices(device_map)) < 2: | ||
| return False |
There was a problem hiding this comment.
Resolve index-less accelerator entries before classifying splits
When the current accelerator is not device 0, a valid hand-supplied map such as {"layers.0": "cuda", "layers.1": "cuda:0"} spans the current device and device 0, but _accelerator_indices converts the index-less torch.device("cuda") to index 0, so this check sees only one accelerator and declines registration. The first current-device shard then skips the required drain, and the fallback activates only after execution reaches cuda:0. Fresh evidence beyond the earlier hand-dispatch finding is that the patched dispatch wrapper does call this registration path, but the index-less entry is misclassified; resolve a missing index using the backend's current_device() before counting devices.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 7d50e11. The RoPE module now resolves an index-less accelerator entry ("cuda", torch.device("cuda")) to the current device before counting, so {"layers.0": "cuda", "layers.1": "cuda:0"} with cuda:1 current registers as a split. Covered by test_index_less_entries_mean_the_current_device.
| # Every split load passes here, so RoPE knows about the split before the first forward. | ||
| register_split_model(model) |
There was a problem hiding this comment.
Keep split registration from aborting dispatch-hook repair
For a supported custom or remote-code model that defines equality without a hash, WeakSet.add(model) raises TypeError: unhashable type here before any of _repair_dispatch_hooks' existing repair logic runs. Depending on the caller, this either aborts loading or is caught only outside the function, leaving the rebuilt embedding/output modules without their dispatch hooks and causing the documented cross-device failure. Treat split tracking as best-effort or otherwise store such models without allowing registration failure to prevent hook repair.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 7d50e11. register_split_model never raises now: if a split model cannot be tracked (for example an unhashable remote-code model), it turns the drain on for every RoPE call instead, so _repair_dispatch_hooks always runs its repair. Covered by test_unhashable_split_model_drains_instead_of_raising.
…r let split registration raise
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. 🎉 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Summary
_fast_rope_embedding_eagerdrains the current stream after every RoPE call whenDEVICE_COUNT > 1, andinplace_rope_embeddingdrains it unconditionally.DEVICE_COUNTis the number of visible devices, not the number the model uses, so single-GPU training on a multi-GPU machine (noCUDA_VISIBLE_DEVICES), and every DDP rank, pays one host-blockingsynchronize()per attention layer per forward, plus one per layer in each gradient checkpoint recompute, plus one per layer in everygenerate()prefill.This PR keeps the drain while a model split over several accelerators (the device_map / pipeline case it was added for in #3049 and #3061) is loaded. A model on one device skips it, whatever the visible device count.
Why the sync is not needed for a single-device model
printafterfast_rope_embeddingfixed NaNs after a few layers" on models split across GPUs), then fixup rope sync for everything #3061 moved it intofast_rope_embedding, then it was narrowed toDEVICE_COUNT > 1. Both were about split models.with torch_gpu_device(Q.device)(present since [3/N] Enable intel GPU for unsloth #2620), so it goes onQ.device's current stream. The torch ops that consume Q and K afterwards (torch.catwith the KV cache, SDPA / flash / xformers, the o_proj) run on that same stream, so they are stream-ordered after the kernel. With one device there is no second stream to race with.inplace_rope_embeddingis pure torch ops, so its unconditional sync never ordered anything.torch.ops.unsloth.rope_embedding*) already has no sync at all, on any number of devices.What changes
register_split_model(model)adds a model whosehf_device_mapspans two or more accelerators to aWeakSet. It is called from_repair_dispatch_hooks, which every split load inFastLanguageModelandFastModel(and the vocabulary resize) already goes through, so the split is known before the first forward._sync_if_split(Q)drainsQ.device's stream while any registered split model is alive, on every RoPE call including the first shard of the first forward, exactly as main does for split models. Once the split model is freed, other models stop paying for it.accelerate.dispatch_modelis wrapped (and rebound where transformers imported it by name:modeling_utilson 4.x,integrations.accelerate/integrations.pefton 5.x) so a model the user dispatches by hand after loading is registered too, before its first forward. Checked on 2 GPUs with transformers 5.17.0 and 4.57.6: a hand split registers, a single-device dispatch does not.dispatch_modelalias bound before Unsloth was imported), the first RoPE call on a device that is not the current device turns the drain on for every later call in the process, as on main. The only calls that can still skip it are the current-device layers of the very first forward of such a hand-dispatched split. A single-device model placed on a non-current card behaves as on main.DEVICE_COUNT <= 1returns immediately as before. Two independent single-device models on different GPUs of one process, each run with its own device current, do not drain.Engagement on 2 GPUs, Llama-3.2-1B-Instruct 4-bit, LoRA, first forward + backward with gradient checkpointing:
del modelMeasurements
Host: B200, heavily loaded CPU (load average 100 to 900 during the runs), so end-to-end step time is noisy. Same GPU for all arms, second GPU only visible. LoRA r=16 on 4-bit checkpoints,
packing=True, 8192 tokens per step, 25 steps, alpaca-cleaned,use_gradient_checkpointing="unsloth".Deterministic quantities (per training step, steps 3 to 22):
generate()Host time blocked inside those syncs on main with 2 visible GPUs (median over steps 3 to 22): Qwen3-0.6B 122.5 ms of a 568 ms step, Llama-3.2-1B 89.1 ms of a 274 ms step. That is time the host spends waiting for the GPU queue to drain instead of launching ahead.
Paired timing in one process (main, 2 GPUs visible, training on cuda:0). Each group of three consecutive steps runs sync, no sync, sync, so slow drift in host load cancels; 20 groups per model after 3 warmup steps. "No sync" here is exactly this PR's behaviour for a single-device model (0 RoPE syncs per step).
Separate processes, 3 runs per arm alternated, median of per-run step medians with [min, max] across runs (whole-step numbers on this host are noisy, the A/A spread is the min to max range):
Decode is unaffected by this sync except for the prefill: the single-token decode path does RoPE with torch ops and never calls
fast_rope_embedding. Decode tok/s on this host (Llama 30 to 37, Qwen3 16 to 19) moved inside the run-to-run spread for all arms.Correctness
Unit tests (
tests/test_rope_sync_single_device.py): no sync for a single device with 8 visible devices (index 0 and 3, the DDP rank case), none forinplace_rope_embeddingon a single device, none with one visible device, a registered split model syncs on every call from the first one, a handaccelerate.dispatch_modelsplit is registered and syncs from the first call, two single-device models on different GPUs never sync, a freed split model stops the syncs, an unregistered split syncs every call from the first one off the current device, and on CUDA the real kernels give bitwise identical Q and K with no stream sync. On main all 9 CPU tests fail; on this branch all 23 (with the existingtests/test_rope_zero_stride_grad.py) pass on torch 2.14 + transformers 5.x and on transformers 4.57.6.Split model repro, 2 GPUs: Llama-3.2-1B-Instruct (8 layers on cuda:0, 8 on cuda:1) and Qwen3-0.6B (14 + 14), LoRA + 4-bit, 24 iterations each, alternating three arms in one process (the first sync iteration is the reference): the existing sync, no sync, and no sync with a
torch.cuda._sleepqueued onQ.device's stream before every RoPE kernel (forward and backward) so that any consumer not ordered after the kernel would read unrotated data. Each iteration runs a packed training forward + backward (rope indices path), an unpacked one, and every fifth iteration a greedygenerate()with KV cache and scores. About 26 percent of RoPE calls ran withQon cuda:1 while the current device was cuda:0.The same holds on this branch. Logits, losses, generated ids and generation scores hash identically between main and this branch, for the single-device model with 2 GPUs visible and for the split model.
LoRA gradients are not bitwise reproducible run to run even within the sync arm on main (backward non-determinism), so they were compared by maximum absolute difference against the first run: the same order in every arm (Llama 4.5e-4 to 8.9e-4, Qwen3 3.9e-3 to 4.9e-3), with no NaN.
Not covered