Skip to content

Inkling 2: checkpoint the Mini loop message residual, refuse TP / PP early, parity tests - #18959

Merged
danielhanchen merged 8 commits into
mainfrom
inkling2-mgpu
Nov 23, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
inkling2-mgpu

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

Follow-up to #18812 (Inkling 2 training support, merged). Companion unsloth-zoo PR unslothai/unsloth-zoo#2688: fused LM-head loss with Inkling's module softcap, and a bounded expert dequant scratch.

What this changes

  1. Inkling-2-Mini: the loop's message residual (24 calls per forward) ran between the checkpointed layers, so its fp32 norm, expanded queries, keys and values stayed alive for the whole step: 1.23 GB on the last card of a 2x T4 split at 1024 tokens. It now runs under torch.utils.checkpoint when gradient checkpointing is on and the model is training. The recompute runs the residual's math as plain tensor ops on inputs moved to the module's device instead of calling the module again: going back through the accelerate device hook and the compiled-module wrapper during recompute made two identical runs differ at step 1 on a two-card split (210 of 336 LoRA gradients). UNSLOTH_INKLING2_MESSAGE_CHECKPOINT=0 keeps the old behaviour.
  2. Tensor and pipeline parallel are refused for inkling2 and inkling2_loop from the config, before any weight loads. Tensor parallel has no sharding rule for the wrapped q / k / v / o projections or the per-head sink and relative position bias projections; a pipeline stage cut would split the block attention residual stack and the Mini loop. Before, UNSLOTH_PARALLEL="tp=2" loaded the whole model on every rank and failed after 101 s on Kaggle 2x T4 with transformers' weight conversion error; now it stops in 27 s with the reason and the alternatives (dp=N, fsdp=1, or device_map="balanced"). A matching row is added to the parallel capability table.
  3. CPU tests for the released NVFP4 / MXFP8 layout decode, the default LoRA targets against PEFT, and the adapter save / reload round trip, for both inkling2 and inkling2_loop.

Results (Kaggle 2x T4)

  • Mini QLoRA notebook, 4 x 1024 tokens, with the zoo companion: peak allocated 11.29 / 12.53 GB before, 10.04 / 9.87 GB after (card 0 / card 1); reserved 13.62 GB on card 1 before, 9.95 GB after. max_seq_length = 2048 now passes the whole notebook (30 steps); before, it ran out of memory. About 4.6% slower per step on the same machine, from the chunked expert dequant.

  • DDP and FSDP2 match a one GPU run with the same micro-batches on a fake shaped like Inkling-2-Small (48 layers, 384 experts) and on a looped Mini fake: fp32 LoRA gradients within 1e-6 relative, FSDP2 bit-identical in fp16, including FSDP2 with one unit per layer, where each looped layer is gathered three times per forward.

  • The real Mini does not fit DDP or FSDP2 on 15 GB cards: every rank loads the whole 4-bit model (14.3 GB) before sharding. It trains with the notebook's device_map split.

  • Inkling-2-Small needs about 310 GB of NF4 weights; it does not fit any free tier.

  • Determinism on the real Mini, two-card split (torch 2.11): repeated runs are bitwise identical (336 of 336 LoRA gradients, steps 1 to 3) with every change on, as on the base. The checkpointed residual alone against the base: 335 of 336 bitwise, worst tensor 4e-7. With the zoo fused loss the difference to the base is the fused CE rounding (1.6e-4 global).

Tests

  • tests/test_inkling2_parallel.py: 10 tests, all fail on the base commit and pass with the refusal.
  • tests/test_parallel_inkling2_gloo.py: two-process CPU DDP / FSDP2 parity on tiny Mini and Small configs, plus the refusals (8 tests).
  • tests/test_inkling2_lora_parity.py (6) and two new tests in tests/test_inkling2_support.py for the message residual checkpoint (fail on the base commit).
  • Together with tests/test_block_compile.py: 126 passed, 9 skipped on CPU, transformers 5.24.

Not covered

  • Real Inkling-2-Small weights (393 GB checkpoint).
  • FSDP2 from a checkpoint that is already 4-bit with sharded loading (none is published for Inkling 2).
  • Expert parallel: still refused by UNSLOTH_PARALLEL for every model.

GPU check

Kaggle 2x T4, tiny Mini-shaped fake split with device_map="balanced": the new message checkpoint runs (24 calls per step, 0 with its opt-out) and step-1 LoRA grads are bitwise equal across 3 runs; the merge base is also deterministic at this size, so this is no-regression evidence, not a flip. The balanced load works on both arms.

… vs PEFT, adapter round trip

Parametrized over inkling2 (Small) and inkling2_loop (Mini) on tiny in-test configs:
- released NVFP4 / MXFP8 experts load bit for bit equal to an independent decode of the packed bytes
- default targets (5 attention Linears + 2 expert parameters per layer) give one LoRA step equal to plain
  transformers + PEFT run in a subprocess that never imports unsloth
- save_pretrained writes every adapter tensor with its trained value and PEFT reloads it to the same logits
  and the same next step
…any weight loads

Tensor parallel stops at the first wrapper projection (q_proj holds the Linear beside an L2 clip) and pipeline
parallel at the block attention residual modules, both after a full load on every rank when quantizing on load.
Refuse UNSLOTH_TP_SIZE / UNSLOTH_PP_SIZE for inkling2 / inkling2_loop at the model type branch of
FastModel.from_pretrained with the reason and the data parallel alternatives (DDP, native FSDP2, device_map), and
add the matching capability table row. DDP and FSDP2 parity on a gloo world is covered by a new test.
…nkeypatch so no package state leaks into later tests
…heckpointing

The loop's message residual runs in the text model's forward between the checkpointed decoder layers, so everything
its fp32 attention saves for backward (norm, expanded queries, keys, values) stayed on the GPU for the whole step:
about 60 MB per call at 1024 tokens, 24 calls on Inkling-2-Mini, so 1.4 GB. Under gradient checkpointing it now
runs checkpointed as well (recomputed in backward, same values and gradients); outside training it is unchanged.
…tensor ops

Recomputing the loop message residual through the module (its accelerate device hook and compiled-module wrapper)
from the autograd engine gave run-to-run different first-step LoRA gradients for every layer up to the end of the
loop on Inkling-2-Mini split over two T4s (base runs are bit-exact), with the non-reentrant and the reentrant
checkpoint alike. The checkpoint now runs the module's eager math as plain tensor ops on inputs moved to the
module's device, bit for bit the module's values and gradients. UNSLOTH_INKLING2_MESSAGE_CHECKPOINT=0 keeps the
stock residual.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 22, 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-23T05:51:39.406248Z 761dc63 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

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 1f90c777b6

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

…keep accelerate offload hooks

- The message residual checkpoint now uses the use_reentrant the text model's layers were enabled with
  (transformers 5.24 defaults to False). It was hard-coded to True, so torch.autograd.grad and
  backward(inputs=...) raised inside a non-reentrant checkpointed model that handled them before.
- A residual whose weights accelerate offloads (query on meta until the hook's pre_forward, or a hook executing
  on another device) keeps its hooked forward. The checkpoint path skipped the hook and computed on meta.
- The gloo DDP / FSDP2 parity test gains Mini cases with gradient checkpointing and the message checkpoint
  installed, counting its recomputes. DDP with reentrant checkpointing stays out: the looped layers reuse their
  parameters, which stock DDP rejects with or without the message checkpoint.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: 621f2d39a8

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

…ollow deepcopy and pickle

- The checkpointed message residual normalized with an inline RMSNorm read from norm.eps, so a forward hook on
  message_input.norm, a replaced norm or a patched norm forward was skipped on the original forward and on the
  recomputation. The checkpointed math now calls the residual's own norm module, as transformers does; values and
  gradients stay bit for bit the stock residual's.
- The installed forward was a closure over the original residual: a deepcopied model ran the copy's residual with the
  original's query, and the residual no longer pickled. It is now a module-level callable that remaps the residual
  and its owner through the deepcopy memo and pickles them.
…ed or replaced one

Calling the norm module in the recompute brings back a module call from the
autograd engine, which 1f90c77 removed after run-to-run different gradients
on Mini split over two GPUs. Keep the stock unweighted RMSNorm as plain tensor
ops (bit for bit its forward) and call the norm module only when it carries
hooks, an instance or class forward override or parameters, so those still
apply on the original forward and the recomputation.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 761dc63867

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

@danielhanchen
danielhanchen merged commit c456427 into main Nov 23, 2026
@danielhanchen
danielhanchen deleted the inkling2-mgpu branch November 23, 2026 10:32
danielhanchen added a commit that referenced this pull request Nov 23, 2026
## Summary

`Repo tests (CPU, studio)` fails on `main` since #18959:

```
tests/python/test_accelerator_skip_guards.py::test_no_test_lets_a_loader_infer_the_device_from_a_spoofed_probe
E   AssertionError: these calls let the library pick the device, and it picks it off a probe tests/_zoo_aggressive_cuda_spoof.py patches to True process-wide. ...
E       test_inkling2_lora_parity.py:378: PeftModel.from_pretrained() with no torch_device=
```

## Root cause

The new test, not the guard. #18959 added
`tests/test_inkling2_lora_parity.py`, which builds the model on CPU and
then reloads the saved adapter with `PeftModel.from_pretrained(...)`
without `torch_device=`. PEFT then picks the device from
`torch.cuda.is_available()`, which the CPU runners' CUDA spoof patches
to `True`, so the reload can dispatch to a CUDA backend that is not
there. That is exactly what the guard is for.

## Fix

Pass `torch_device = "cpu"` on the reload, matching where the model
lives. `tests/test_inkling2_lora_parity.py` only.

## Testing

- `tests/python/test_accelerator_skip_guards.py` and
`tests/test_inkling2_lora_parity.py`: 24 passed, 1 skipped (the guard
failed on `main` without this change).
danielhanchen added a commit that referenced this pull request Nov 23, 2026
## Summary

`Repo tests (CPU, rest-2)` fails on `main`:

```
tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding
E   AssertionError: 1 file reads in the test trees touch a checked-in file with the platform default encoding, so they break on Windows as soon as that file gains a non-ASCII byte. Pass encoding = "utf-8": ['tests/test_inkling2_parallel.py:104: read_text()']
E   AssertionError: ... ['tests/test_rocm_skinny_linear.py:668: read_text()']
```

## Root cause

The new tests, not the guard. Two recent suites read a checked-in source
file with `read_text()` and no encoding, which on Windows decodes with
the locale code page:

| File | Added by |
|---|---|
| `tests/test_inkling2_parallel.py:104` (reads
`unsloth/models/loader.py`) | #18959 |
| `tests/test_rocm_skinny_linear.py:668` (reads
`unsloth/kernels/rocm_skinny_linear.py`) | #18874 |

## Fix

Pass `encoding = "utf-8"` on both reads. Tests only.

## Testing

- `tests/test_source_read_encoding.py`,
`tests/test_inkling2_parallel.py`, `tests/test_rocm_skinny_linear.py`:
60 passed, 51 skipped (GPU cases). The guard failed on `main` without
this change.
danielhanchen added a commit to danielhanchen/unsloth-zoo-staging that referenced this pull request Nov 23, 2026
…nded expert dequant scratch (unslothai#2688)

Two memory changes for Inkling 2 QLoRA, measured on the Inkling-2-Mini
notebook on Kaggle 2x T4. Companion to unslothai/unsloth#18959
(follow-up to unslothai/unsloth#18812).

## Fused LM-head loss with a module softcap

Inkling 2 applies its final logit softcap as a module call (`logits =
self.logit_softcap(logits)`, `tanh(x / 30) * 30`), so the forward
rewriter took the softcap module for the LM head and declined. The model
then built full fp32 logits over its 200058 token vocabulary: 2.29 GB
alive on the last card at 1024 tokens.

`inline_softcap_modules` rewrites that call into the expression form the
rewriter already understands, only when `__init__` builds the attribute
from a module whose whole forward is exactly `tanh(x / C) * C`; a
look-alike module is left alone. It runs on both the compiler route and
the import hook. The fused call no longer reads `logits.shape[-1]` for
`vocab_size` before `logits` exists in that branch.

Parity on fake models on a GPU: fp32 LoRA gradients fused vs unfused
within 6e-7 to 1.7e-6 relative, loss within 1e-6, with right padding,
prompt masks, and with and without `num_items_in_batch`. In fp16 the
fused loss equals an fp32 head reference to the printed digits.

## Bounded expert dequant scratch

Training dequantized each whole 4-bit expert stack per projection call:
1.27 GB for Mini's gate / up stack, and 16.3 GB per call for
Inkling-2-Small. An experts class can now declare
`_unsloth_dequant_scratch_fraction`; a stack larger than twice that
share of the card is dequantized in chunks of at most that share.
Inkling 2 declares 2.5% (Mini: 4 chunks of 36 experts on a T4, unchunked
on a 40 GB card; Small: chunked on every card).
`UNSLOTH_MOE_DEQUANT_MAX_MB` caps it for any model; an explicit
`UNSLOTH_MOE_DEQUANT_CHUNK_EXPERTS`, including 0, still wins. Chunks are
bit-exact: all 336 LoRA gradient tensors equal the unchunked run on T4
and A100.

## Results (Kaggle 2x T4, Mini QLoRA notebook shape, 4 x 1024 tokens)

| | card 0 | card 1 |
|---|---|---|
| peak allocated, before | 11.29 GB | 12.53 GB |
| peak allocated, after (with the unsloth companion) | 10.04 GB | 9.87
GB |
| fp32 logits + softcap | | 2.29 GB -> 0 |
| expert dequant scratch | 1.27 GB -> 0.18 GB | 0.18 GB |

`max_seq_length = 2048` now passes the whole notebook; before, it ran
out of memory. The chunked dequant costs about 4.6% per step on the same
machine (it adds a host sync per MoE call and turns off keeping
checkpoint base outputs).

## Tests

- `tests/test_inkling2_fused_softcap_ce.py`: 5 of 6 fail before, 6 pass
after (CPU); 6 of 6 pass on a GPU.
- `tests/test_moe_bnb4bit_selective_dequant.py`,
`tests/test_inkling2_moe_experts.py`: new cases for the scratch cap.
- Fused loss, compiler, MoE selective dequant, keep-base and Inkling
suites: 233 passed, 51 skipped (base 225 / 51; the 8 extra are new).

## Determinism

On the real Mini split over two Kaggle T4s (torch 2.11), repeated runs
with these changes and the unsloth companion are bitwise identical (336
of 336 LoRA gradients, steps 1 to 3), as on the base. Against the base
the only difference is the fused CE rounding (1.6e-4 global relative on
the LoRA gradients).

## Not covered

- Real Inkling-2-Small weights.
danielhanchen added a commit that referenced this pull request Nov 23, 2026
## Summary

`Repo tests (CPU, rest)` fails on `main`:

```
tests/test_loader_compile_disable_preserve.py::test_partial_is_written_only_inside_the_helper
E   assert False
E    +  where False = all(<generator object test_partial_is_written_only_inside_the_helper.<locals>.<genexpr> ...>)
```

## Root cause

The Inkling 2 branch, not the guard. #18773 added
`_set_partial_compile_disable()` to `unsloth/models/loader.py` and
routed every branch that partly disables compile through it, with a
guard that no other code writes `"partial"`. The Inkling 2 branch from
#18812 / #18959 landed alongside it with its own direct write:

```python
if os.environ.get("UNSLOTH_COMPILE_DISABLE", "0") == "0":
    os.environ["UNSLOTH_COMPILE_DISABLE"] = "partial"
```

Besides tripping the guard, that write keeps a value like `true` or
`yes` as it is, and unsloth_zoo only reads `"1"` and `"partial"` as off,
so `UNSLOTH_COMPILE_DISABLE=true` left Inkling 2 compiled. The helper
turns `1` / `true` / `yes` into `"1"` and everything else into
`"partial"`.

## Fix

- `unsloth/models/loader.py`: the Inkling 2 branch calls
`_set_partial_compile_disable()`. Unset or `0` still becomes `partial`,
and `1` still stays fully off.
- `tests/test_loader_compile_disable_preserve.py`: the helper-call count
goes from five branches to six, with Inkling 2 named.

## Testing

- `tests/test_loader_compile_disable_preserve.py` and
`tests/test_inkling2*.py`: 23 passed, 3 skipped.
- With `main`'s `loader.py`, the guard fails (both the direct write and
the helper count).
- Helper mapping checked directly: unset, `0`, `false` -> `partial`;
`1`, `true` -> `1`; `partial` -> `partial`.
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.

1 participant