Skip to content

Fit Gemma 4 E2B on 8 GB cards on Windows and in Studio chat - #13425

Merged
danielhanchen merged 12 commits into
mainfrom
fix-13388-windows-embedding-offload
Oct 13, 2026
Merged

danielhanchen merged 12 commits into
mainfrom
fix-13388-windows-embedding-offload

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 12, 2026 •

Copy link
Copy Markdown
Member

Fixes #13388

Problem

Gemma 4 E2B in 4-bit is 8.1 GB, and 4.4 GB of that is one bf16 per-layer token table (embed_tokens_per_layer). On an 8 GB card it only fits if that table stays in host RAM. Two things stopped that:

  1. Embedding offload was switched off on Windows and WSL (_offload_embedding_unsupported_platform). The gate dates from the first offload (Dec 2025), which moved the table to the CPU with no hooks. Lookups now go through forward hooks with blocking copies from pageable memory, so there is nothing OS specific left in the path. With the gate, offload_layers = "auto" on Windows could only move decoder layers, and the planner gave up: Even with 34 of 35 decoder layers in host RAM the model does not fit.
  2. Studio chat loads never offload anything. A transformers chat load of E2B on an 8 GB card failed on every OS with does not fit in GPU memory ... bitsandbytes cannot quantize, which is the pop-up in the issue (the reporter loaded the model in chat).

Fix

  • Remove the Windows / WSL gate, so embedding offload runs the same on every OS.
  • Studio chat: before a single-GPU load, size the top-level safetensors of the repo the 4-bit mapper will read (local folder, then the HF cache, then the Hub). At 90% or more of free VRAM the load asks for offload_layers = "auto", the same planner Offload layers = Auto uses in training, which still loads everything onto the GPU if it fits after all. If the guess misses (unknown size, underestimate) and a single-GPU load still spills to the CPU, that attempt is released entirely (exception and traceback dropped, gc.collect(), CUDA cache emptied) and retried once with offload_layers = "auto". Smaller checkpoints, more than one visible GPU (transformers' sequential and Unsloth's balanced planner spread those over the cards, and neither loads into host RAM) and non-CUDA devices load exactly as before. Parameter-count estimates miss this case: E2B's table stays bf16 in the 4-bit checkpoint. A LoRA is sized from its base model, an exact-name load from the repo it reads, a 16-bit load of a *-bnb-4bit name from its full-precision repo, and a cached snapshot only counts when every shard in its index is present (else the Hub sizes it).

Evidence

An 8 GB card emulated on a B200: allocator capped at 7.3 GiB, mem_get_info and total_memory report 8 GiB with 7.3 GiB free. Windows is emulated by making the platform gate answer "Windows" (on this branch there is no gate left, so the code path is the same as Linux). Model unsloth/gemma-4-E2B-it, 4-bit.

Path main, Linux main, Windows this PR
Training, Offload layers = Auto, LoRA r=16, 5 steps trains, losses 1.8828, 2.1535, 1.4928, 1.598, 1.4552 DeviceMapInfeasible: Even with 34 of 35 decoder layers in host RAM the model does not fit trains, table on cpu, losses 1.8828, 2.1535, 1.4982, 1.6057, 1.4536, peak 5.74 GiB
Studio chat load (InferenceBackend.load_model) + generate does not fit in GPU memory (cuda:0 has 7.26 GB free) ... same error Checkpoint is 7.57 GiB with 7.26 GiB free; loading with offload_layers='auto', loads at 2.83 GiB, answers "4" to "What is 2+2?", peak 5.74 GiB
Studio chat, LoRA adapter on Gemma 4 E2B same CPU-spill error same error sized from the base (7.57 GiB), loads at 2.92 GiB, answers "4"
Studio chat, size guess forced to miss CPU-spill error same error first attempt released (0.04 GiB left), retry with offload_layers='auto' loads and answers "4"
Studio chat, E2B on 2 x 8 GB (no gpu_ids, sequential) loads across cuda:0 2.2 GiB + cuda:1 5.4 GiB same same split, no offload
Studio chat, E2B on 2 x 8 GB (unsloth_balanced) loads across cuda:0 4.42 GiB + cuda:1 3.18 GiB, no offload
Studio chat, unsloth/Qwen3-0.6B (0.54 GiB, fits) loads loads loads unchanged, no offload, same 0.603 GiB

Tests:

  • tests/test_offload_tied_autodisable.py::test_windows_and_wsl_offload_like_linux fails on main (assert False is True) and passes here; the removed tests asserted the gate itself. Offload and block swap suites: 210 passed, 13 skipped on CPU.
  • studio/backend/tests/test_inference_offload_fit.py: "auto" only for a single CUDA GPU whose checkpoint (sized from the mapped 4-bit repo) is at least 90% of free VRAM; exact-name loads size the repo they read; a partial snapshot is not sized locally; nothing with several visible cards, multi-GPU maps, no CUDA, or an unknown size.

Not covered

  • No Windows CUDA machine here, so the Windows rows are emulated. The reporter offered to try it on an RTX 4060 Ti.
  • The chat load uses the training reserve (about 3 GiB at 2048 tokens), so on E2B it also keeps 22 of 35 small decoder layers (1.0 GiB) in host RAM, which makes decoding slower. E4B in 4-bit still does not fit an 8 GB card for chat; the error now comes from the planner.

The platform gate dates from the first offload, which moved the table to the CPU
with no hooks. Lookups now run through forward hooks with blocking copies and
pageable memory, nothing OS specific, so offload_layers = 'auto' could not fit
Gemma 4 E2B on an 8 GB card on Windows while Linux could.
…uto'

Chat loads never offloaded anything, so a 4-bit Gemma 4 E2B (8.1 GB, 4.4 GB of it
one per-layer token table) failed on 8 GB cards on every OS. Only loads that fail
today take the retry.
@danielhanchen danielhanchen self-assigned this Oct 12, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-13T10:16:59.342469Z fce14a3 New commits
ℹ️ 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. Chef's kiss.

Reviewed commit: c614ac62aa

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

A single-GPU load whose top-level safetensors take 90% or more of free VRAM now
asks for offload_layers = 'auto' up front, sized from the repo the 4-bit mapper
loads. No failed first attempt, and loads with room are unchanged.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: abed0f8283

ℹ️ 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 device_map != "sequential" or not torch.cuda.is_available():
return {}
try:
free = sum(torch.cuda.mem_get_info(i)[0] for i in range(torch.cuda.device_count()))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Measure only the card used by sequential loading

When multiple CUDA devices are visible but gpu_ids is omitted, get_device_map() can still return "sequential", which fills the first card rather than pooling their memory; load_model_simple() uses exactly this path. Summing every device's free memory therefore makes an 8.1 GiB checkpoint appear to fit on a dual-8-GB host, suppresses offload_layers="auto", and leaves the load to fail on cuda:0. Compare against the free memory of the device selected by the sequential load instead.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

transformers' "sequential" does pool the visible cards: _get_device_map takes get_max_memory() over every GPU and infer_auto_device_map fills them in order, so two 8 GB cards hold an 8.1 GiB checkpoint without a CPU spill. Summing their free memory matches what that load does; and with more than one visible card block_swap_load_device returns None, so load-time offload could not apply there anyway.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: bb0abdd6e0

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

…edding-offload

# Conflicts:
#	studio/backend/core/inference/video.py
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4a960041f2

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

Comment on lines +118 to +120
else:
files = list(folder.glob("*.safetensors"))
return sum(f.stat().st_size for f in files) or None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject cached shard sets whose index is absent

When an interrupted Hub download has completed one or more files such as model-00001-of-00004.safetensors but has not cached model.safetensors.index.json, this branch treats those shards as a complete checkpoint and returns their partial size. The subsequent Hub metadata fallback is therefore skipped, so a partial size below the threshold suppresses automatic offloading even though the loader later downloads the remaining shards and may OOM. In the no-index branch, shard-pattern filenames should be treated as incomplete rather than as standalone checkpoints.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this one: it needs an interrupted download that finished shards but not the small index JSON. That only under-sizes the guess, so the load takes exactly today's path; no regression, and the index-present case (the usual partial download) is already handled.

except Exception:
return {}
# `mapped` = False: the loader reads `name` verbatim (use_exact_model_name).
size = _checkpoint_bytes(_loader_repo(name, load_in_4bit) if mapped else name, hf_token)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Size checkpoints from ModelScope when that loader is active

When loader.USE_MODELSCOPE is enabled, the actual model loader resolves non-local model IDs through modelscope.snapshot_download, but this sizing path still probes only the Hugging Face cache and HfApi. A ModelScope-only repository therefore produces an unknown size (or an unrelated Hugging Face repository with the same ID can produce the wrong size), so a checkpoint that needs host offloading still follows the old OOM path. Select the same repository service as the loader before deciding whether to pass offload_layers="auto".

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this one: with USE_MODELSCOPE a ModelScope-only id has no HF size, so the check returns unknown and the load runs exactly as it does today. Adding a second hub client just for the guess is out of scope for this fix.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 13, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 194f18dc11

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

total = sum(
s.size or 0
for s in info.siblings or ()
if s.rfilename.endswith(".safetensors") and "/" not in s.rfilename

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include indexed subdirectory shards in checkpoint sizing

For an uncached repository whose root model.safetensors.index.json points to files such as shards/model-00001-of-00002.safetensors, every actual weight is excluded by the "/" not in s.rfilename predicate. This is a valid layout already exercised by test_gate_allows_symlinked_sharded_safetensors, but _checkpoint_bytes() consequently returns None, _offload_kwargs_for_fit() skips automatic offloading, and a large single-GPU checkpoint can still fail with the OOM this change is intended to prevent. Size the shard paths referenced by the root index rather than restricting all weight files to the repository root.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this one: Hub checkpoints keep their shards at the repo root, and for a nested layout the size comes back unknown, so the load runs exactly as it does today. No regression, and not worth growing the guess for.

…oad_layers = 'auto'

The guess skips unknown or underestimated sizes. A single-GPU load that then
spills to the CPU is released entirely (exception and traceback dropped,
collected, CUDA cache emptied) and retried once with Offload layers = Auto.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: d4e1ea8abe

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

It is not yet possible to run Gemma4e2b on Windows.

1 participant