Skip to content

Tensor parallel sharded loading: allow init_lora_weights = "orthogonal" - #15218

Merged
danielhanchen merged 3 commits into
unslothai:mainfrom
lonexreb:fix/tp-sharded-loading-allows-orthogonal-lora-init
Nov 8, 2026
Merged

danielhanchen merged 3 commits into
unslothai:mainfrom
lonexreb:fix/tp-sharded-loading-allows-orthogonal-lora-init

Conversation

@lonexreb

@lonexreb lonexreb commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

What

_refuse_weight_dependent_lora_init in unsloth/models/tp_native.py (from #15174) rejects any init_lora_weights outside True / False / "gaussian" once load_tensor_parallel(...) has put sharded slices on the model, with the message "depends on the base weight". For "orthogonal" that is not true, so get_peft_model(model, LoraConfig(init_lora_weights = "orthogonal")) followed by apply_tensor_parallel at tp > 1 raises for no reason.

Why it is safe to allow

PEFT's LoraLayer.orthogonal_init (peft 0.21, tuners/lora/layer.py) builds both factors from torch.randn sized by self.in_features / self.out_features and reads only weight.dtype. Sharded loading keeps the nn.Linear at the full in / out features (the slice carries _unsloth_tp_full_shape), so the factors come out full-size, exactly the shape gaussian produces, and _sync_trainable then gives every rank rank 0's draw. PiSSA / OLoRA / CorDA / EVA / LoftQ / MiCA do read the weight (MiCA takes lora_B from the base weight's singular vectors) and stay refused.

How

Add "orthogonal" to the allowlist tuple; name it in the message and the docstring (which now also lists MiCA). Nothing else changes.

Verification

tests/test_tp_native_gloo.py::test_sharded_loading_refuses_weight_dependent_lora_init now also runs the orthogonal case on the 2-rank gloo mesh (tp = 2, r = 4, target_modules = "all-linear") and asserts it is allowed and the model ends up tensor parallel, next to the existing pissa (refused) and gaussian (allowed) cases.

pissa gaussian orthogonal
main (62fdd8fc79) refused allowed refused (extended test fails here)
this branch refused allowed allowed (1 passed)

CPU only, torch 2.13 + peft 0.21.2. ruff check, enforce_kwargs_spacing.py and the ruff-format-with-kwargs hook pass.

Follow-up

  • Merged current main.
  • PEFT's orthogonal init is identical in PEFT 0.18.0 and 0.21.2. It reads only r, in_features, out_features and the base weight's dtype, and draws from torch.randn, so the factors are full-size and never read weight values. It guarantees B @ A == 0 with both factors non-zero; the rows of A are not orthonormal.
  • New test_sharded_loading_random_lora_init_matches_one_process[orthogonal|gaussian|True] (2 gloo ranks, ranks seeded differently on purpose):
    • After the tp rank 0 broadcast, the LoRA factors are bit-identical to a one-process init from rank 0's seed, and identical on both ranks.
    • For orthogonal, B @ A == 0.
    • One forward / backward / AdamW step matches the unsharded run: logits, grads, loss, grad norm and the updated params.
  • With TPConfig(sync_trainable = False) the broadcast is skipped by design. The ranks agree when they are seeded alike and diverge otherwise, so the field's comment now says the caller then owns identical starting factors.
main this branch
orthogonal refused under sharded_loading refused allowed
..._random_lora_init_matches_one_process[orthogonal] fails passes
[gaussian], [True] pass pass
tests/test_tp_native_gloo.py 51 passed
floor (transformers 4.57.6, PEFT 0.18.0), -k sharded 10 passed

danielhanchen added a commit that referenced this pull request Oct 25, 2026
…ranks (#15250)

## Summary


`tests/test_float8_training_fsdp2_gloo.py::test_float8_linear_trains_under_native_fsdp2`
fails in the `Repo tests (CPU, rest)` shard on unrelated PRs (#15212,
#15217, #15218) and passes when run on its own:

```
Mismatched elements: 1 / 4:  Max relative difference: 6.84e-05
Index | Obtained          | Expected
3     | 5.603824138641357 | 5.603440761566162 ± 5.6e-05
```

The sharded run is the correct one. Training the same unsharded fp8
model in a clean process gives `5.603824139` at step 4, and the result
is identical with 1, 2, 4 and 8 threads. The value that moved is the
reference. The test trained it inside the pytest worker, so it inherited
whatever earlier tests in the shard had left in that process, while the
two gloo ranks start fresh under `spawn`. The tolerance is fine. The two
sides were simply not run under the same conditions.

## Change

- The unsharded reference trains in its own spawned process
(`_reference_worker`, `nprocs = 1`), so both sides of the comparison
start from a clean interpreter. The tolerance is unchanged (`rel = 1e-5,
abs = 1e-6`).
- The JSON reads and both writes name `encoding = "utf-8"`.

## Verification

- `tests/test_float8_training_fsdp2_gloo.py`: passes, and the clean
reference matches the sharded losses exactly.
- Sabotage 1 (the CI failure): a pytest plugin that changes only the
parent process (scales `F.cross_entropy` by `1 + 1e-4`, which `spawn`
children do not inherit). The old test fails with `Max relative
difference: 2.0e-04`. The new test passes.
- Sabotage 2 (the guard still bites): scaling the sharded ranks' losses
by `1 + 1e-4` makes the new test fail.

I did not pin down which earlier test leaves the state behind. With this
change, the comparison no longer depends on it.
danielhanchen added a commit that referenced this pull request Oct 25, 2026
…d copy (#15264)

`tests/test_tp_native_gloo.py::test_tp2_x_fsdp2_dp2_matches_one_process[llama-True-lora_kwargs4]`
fails now and then in `Repo tests (CPU, rest)` on unrelated PRs (#15159,
#15174, #15217, #15218, #15222, #15225) with only `AssertionError:
base_model.model.lm_head.weight`. Gradients, losses and norms all match
in those runs. Only the saved `lm_head` copy differs.

## Cause

The test, not the product. That case trains a full `lm_head` copy
(`modules_to_save`, 512000 entries) with AdamW at lr 1e-2 and the
default eps of 1e-8. At g = 0, Adam's `g / (sqrt(v) + eps)` has slope lr
/ eps = 1e6. Measured on main on this host:

| | value |
| --- | --- |
| median step-0 lm_head grad | 5.7e-6 |
| entries with step-0 grad below 1e-8 | 313 |
| step-0 grad of the 10 worst saved-weight entries | 4e-11 to 7e-9 |
| worst saved-weight diff / tolerance | 0.46 |

So reduction-order noise of about 1e-12 on a near-zero gradient becomes
about 5e-6 of weight. That is already half the `atol = 1e-5` here. A
runner whose CPU kernels sum in a different order goes over it.

## Fix

- Both arms use `AdamW(eps = 1e-6)`. The optimizer is still identical on
both sides, and 1e-6 is small next to the typical gradient, so the head
still trains. The worst entry drops to 0.0075 of the tolerance (60x
headroom).
- The saved-weight assert now keeps `assert_close`'s mismatch detail. It
used to print only the key, which is why the CI logs never showed how
far off the weight was.

## Verification

- `tests/test_tp_native_gloo.py`: 38 passed.
- Sabotage on the last step, after the norms are taken, so only the
saved weight can catch it:
- TP arm skips the lm_head update: fails, 511627 / 512000 mismatched,
max abs diff 1.0e-2.
- Each dp half's lm_head gradient scaled by +/-15% (a stand-in for a
missing dp reduction): fails, 493693 / 512000 mismatched, max abs diff
8.1e-4.
  - No sabotage: passes.
danielhanchen added a commit that referenced this pull request Oct 25, 2026
…ard (#15291)

`Repo tests (CPU, rest)` has been running out of time. Its pytest step
is capped at `timeout --signal=INT --kill-after=60 2100`.

- On most runs today pytest received SIGINT before finishing. Every run
I checked had a `KeyboardInterrupt` banner and a reported time of 2090
to 2097 s, stopping between 74% and 98% of the shard.
- The tail of the shard therefore never ran, and nothing said so. Those
runs were also red for other reasons, which hid it.
- Now that those reds are fixed on main, the shard fails on the timeout
alone (`Process completed with exit code 124`, at 75%), for example on
#15217, #15218 and #15226.
- The one complete run I found took 1920 s, already close to the cap.

## Cause

The shard is the catch-all. It has picked up the multi-rank gloo suites
added recently: tensor parallel, pipeline parallel, context parallel,
float8 and fp8 under FSDP2. Each spawns 2 to 4 ranks per test. This is
the same thing that happened with the FSDP2 gloo files, which is why
they already have their own `fsdp2` shard.

Measured locally at this job's shape (`-n 4 --dist loadgroup`, pinned to
4 cores, one selection per core set):

| selection | wall |
| --- | --- |
| the 7 non-FSDP2 gloo files | 578 s |
| the catch-all without them | 680 s |
| the existing `fsdp2` shard | 648 s |

So the gloo files are about 46% of the catch-all. Folding them into
`fsdp2` would push that shard to the cap instead; its jobs already run
17.5 to 29 minutes on CI.

## Fix

A `gloo` shard takes every `*gloo*` file except `test_fs*`, which are
`fsdp2`'s. It is written as two globs, `tests/test_[!f]*gloo*.py` and
`tests/test_f[!s]*gloo*.py`, because an explicit file root cannot be
filtered with `--ignore`, as the matrix notes already say. `rest`
ignores the same two globs. A new multi-rank gloo file lands in the new
shard without a workflow edit.

This adds a check, `Repo tests (CPU, gloo)`. No existing check name
changes.

## Verification

- `tests/studio/test_backend_ci_parallel_isolation.py` pins the number
of parallel pytest runs; it now expects eight, five of them
repo-cpu-tests shards (it failed at seven before that update). It and
`tests/test_ci_repo_cpu_shards.py` together: 54 passed.
- `tests/test_ci_repo_cpu_shards.py` on its own: 13 passed. It fails
both ways if the split is broken: drop the new shard and its files are
reported as dropped; drop the `rest` ignores and they are reported as
run twice.
- Collected ids at main (`--collect-only` with the same shell glob
expansion): the old `rest` has 17751. The new `rest` (17666) plus `gloo`
(85) is identical, with nothing in both and nothing shared with `fsdp2`.
- `test_gloo_spawn_cpu_guard.py` matches neither glob and stays in
`rest`. It is a guard, not a multi-rank suite.

## Not proven here

Runner timing is estimated by scaling: the catch-all is about 1258 s
locally against roughly 2800 s projected on CI. That puts the new `rest`
near 1500 s and `gloo` near 1270 s, both under 2100 s. This PR's own run
will show the real numbers.
_refuse_weight_dependent_lora_init (unslothai#15174) refuses every init_lora_weights outside True / False / "gaussian" as "depends on the base weight". PEFT's orthogonal init does not: it draws the factors from torch.randn sized by the layer's in_features / out_features, which sharded loading keeps at the full sizes, and reads only the weight's dtype. So the factors come out full-size, the same shape as gaussian's, and _sync_trainable gives every rank rank 0's draw. Add it to the allowlist; MiCA, which takes lora_B from the base weight's singular vectors, stays refused.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

Copy link
Copy Markdown
Member

Reviewed source faac391d56ce in mirror #766 at 777c7dd09910, replayed onto 4f4305ea10c4 with authorship preserved and merge-tree equivalence verified.

No actionable PR-specific findings; Codex review is clean at that mirror head. The two-rank CPU gloo regression passed: orthogonal/Gaussian initialization is accepted while PiSSA remains rejected. The same regression fails on the pinned base because orthogonal initialization is rejected.

Mirror CI finished with 34 passing checks, 5 skipped and 3 failures. All three failures are the external Zoo CPU MLX shim's missing BatchQuantizedKVCache at fe1bfc2bbb75, affecting the two padding-mask tests. GPU smoke was skipped; no GPU validation is claimed.

No fix commits were needed. Review complete; CI remains blocked by the external Zoo defect.

@danielhanchen danielhanchen self-assigned this Nov 7, 2026
…rocess

Orthogonal, gaussian and default inits on sharded_loading slices: full-size
factors bit-identical to a one-process init from tp rank 0's seed after the
broadcast (per-rank seeds), orthogonal B @ A == 0 with both factors non-zero,
and one forward / backward / AdamW step matching the unsharded run. Note on
TPConfig.sync_trainable that turning it off leaves equal factors to the caller.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 7, 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-07T14:52:52.097529Z 7d484b5 Manual request
ℹ️ 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 7d484b5105

ℹ️ 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".

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants