Skip to content

fix(offload): stop tracking mmap file descriptors in the weight loader - #6659

Merged
Qubitium merged 1 commit into
mainfrom
fix/olmo-offload-fd-leak
Dec 1, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/olmo-offload-fd-leak

Conversation

@Qubitium

@Qubitium Qubitium commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Fixes OSError: [Errno 24] Too many open files when a large MoE is quantized with the default offload_to_disk=True and the default soft RLIMIT_NOFILE of 1024. On allenai/OLMoE-1B-7B-0924 GPTQ (64 experts, 64x512 calibration) current main opens one file descriptor per offloaded expert projection and dies after a few layers; the same model also cannot be loaded back on CPU at 1024.

Root cause

file_back_module writes one safetensors file per offloaded module and keeps a zero-copy tensor view of it for the rest of the run (weight_loader/filebacked.py). read_tensors likewise keeps one mapping per module group when the tensors stay on CPU (weight_loader/reader.py). CPython's mmap.mmap duplicates the mapped file descriptor (dup(2)) unless the caller passes trackfd=False (Python 3.13+), and the duplicate lives until the mapping is closed. A 64-expert MoE with 16 layers has 3072 such projections, so the process needs thousands of descriptors and hits EMFILE at the default soft limit of 1024.

Bisect: pre-#6473 parent aff56aa1a completes OLMoE GPTQ at 1024 (max fd 355, no file-backed fds); #6473 (0043349bf) introduced the per-module file-backed offload and current main fails.

What Changed

  • New gptqmodel/utils/fd_limit.py:
    • map_file_window(fd, length, offset=0, access=ACCESS_COPY) asks mmap.mmap for an untracked mapping (trackfd=False) when the interpreter supports it. The mapping still keeps the file data alive after the caller closes the fd; only the duplicate descriptor is gone.
    • ensure_nofile_limit() is the Python 3.11/3.12 fallback where trackfd does not exist: it raises the soft RLIMIT_NOFILE to the hard limit (only ever raises, logs once at debug) and emits one warning naming ulimit -n when the hard limit is still below 4096.
  • Every mmap.mmap site in weight_loader/reader.py (3) and weight_loader/filebacked.py (1) now goes through map_file_window.
  • ensure_nofile_limit() is called once at the start of GPTQModel.load, GPTQModel.from_quantized and BaseQModel.quantize. On Python 3.13+ it is a no-op.
  • No mapping lifetime, read order, offload format, dtype or tensor value changes. close(), flush() and madvise() do not need the tracked fd; there are no size()/resize() calls on these mappings.

Why not bundle finalized modules per layer

The first revision of this PR bundled a finalized decoder layer into one file-backed safetensors file. That changes the offload design and was rejected for concrete costs:

  • it forces the finalize futures to drain synchronously before the layer bundle is written (the device pool gives no ordering guarantee against a still-queued layer-local task), losing the finalize/next-layer overlap;
  • measured host RSS peak regressed up to ~2x on Qwen2.5-0.5B (417 -> 809 MiB anonymous RSS over start) because a whole layer's tensors are alive while the bundle is written;
  • it still fails for a layer with more than ~1000 modules;
  • the descriptor is held by Python's mmap bookkeeping, not by the offload granularity, so the correct fix is one call-site helper rather than a new offload unit.

Tests

  • Unit tests have been executed and passed, or the reason they are not applicable is documented.
  • I added a new simple/fast unit test for this change, or documented why that is not applicable.

Red/green (tests/test_offload_fd_bound.py, Python 3.14, CPU, deterministic RLIMIT_NOFILE soft limit of 256 set inside the test):

# branch
CUDA_VISIBLE_DEVICES="" PYTHONPATH=$PWD python -P -m pytest -q -p no:cacheprovider tests/test_offload_fd_bound.py
# 4 passed in 21.98s

# main (same file copied into a worktree at 0127a0313)
# 3 failed, 1 deselected in 17.12s
#   test_offload_keeps_open_file_backed_mappings_bounded[gptq]  OSError: [Errno 24] Too many open files (filebacked.py:167)
#   test_offload_keeps_open_file_backed_mappings_bounded[rtn]   OSError: [Errno 24] Too many open files (filebacked.py:167)
#   test_checkpoint_load_keeps_open_mappings_bounded            OSError: [Errno 24] Too many open files (reader.py:331)

The two offload cases fail on main while writing the per-module file; the load case fails on main while mapping the quantized checkpoint back in (384 module groups). On the branch the same 64-expert model completes and the file-backed fd count stays at 0 after the run; the load case holds 0 checkpoint fds.

The real OLMoE GPTQ output from the A/B below (3.7 GB, 3,136 modules) also cannot be loaded back on CPU at ulimit -n 1024 on main:

# main (base worktree at 0127a0313), ulimit -n 1024
PYTHONPATH=$PWD python -P /tmp/load_ckpt_probe.py out_r4_olmo_load 1024
# OSError: [Errno 24] Too many open files
#   .../weight_loader/reader.py:331 in read_tensors
#   .../weight_loader/loader.py:304 in load

# branch, ulimit -n 1024
# LOAD_OK seconds=45.5 ckpt_fds=0 nparams=208275456

The fourth test (test_nofile_limit_fallback_raises_soft_limit) monkeypatches the trackfd capability off and asserts the fallback raises only the soft limit to the hard limit. It cannot exist on main because the helper module is new.

Other tests (CPU):

CUDA_VISIBLE_DEVICES="" PYTHONPATH=$PWD python -P -m pytest -q -p no:cacheprovider \
  tests/test_weight_only.py tests/test_weight_only_looper.py tests/test_weight_only_counterless_offload_6539.py \
  tests/test_offload_files.py tests/test_stage_modules.py tests/test_offload_fd_bound.py
# 204 passed, 43 skipped in 34.76s

CUDA_VISIBLE_DEVICES="" PYTHONPATH=$PWD python -P -m pytest -q -p no:cacheprovider \
  "tests/test_checkpoint_quantization.py::test_quantized_tensors_equal_after_subset_resume[llama-gptq]" \
  "tests/test_checkpoint_quantization.py::test_quantized_tensors_equal_after_subset_resume[qwen3_moe-gptq]" \
  "tests/test_checkpoint_quantization.py::test_quantized_tensors_equal_after_subset_resume[llama-rtn]" \
  "tests/test_checkpoint_quantization.py::test_quantized_tensors_equal_after_subset_resume[qwen3_moe-rtn]"
# 4 passed in 24.20s

CUDA_VISIBLE_DEVICES="" PYTHONPATH=$PWD python -P -m pytest -q -p no:cacheprovider \
  "tests/test_checkpoint_quantization.py::test_spilled_layer_inputs_are_bit_identical_and_resume[llama-cpu]" \
  "tests/test_checkpoint_quantization.py::test_spilled_layer_inputs_are_bit_identical_and_resume[qwen3_moe-cpu]"
# 2 passed in 16.68s

CUDA_VISIBLE_DEVICES="" PYTHONPATH=$PWD python -P -m pytest -q -p no:cacheprovider \
  tests/test_weight_loader.py tests/test_weight_loader_filebacked.py
# 79 passed, 10 skipped in 9.11s

CUDA_VISIBLE_DEVICES="" PYTHONPATH=$PWD python -P -m pytest -q -p no:cacheprovider \
  tests/test_offload_disk_container_5145.py tests/test_offload_run_cleanup_4368.py \
  tests/test_offload_base_modules_restored.py tests/test_offload_quantized_modules_restored_4450.py \
  tests/test_loader_offload_staging_4385.py tests/test_quantize_config_offload_tempdir.py
# 26 passed, 5 skipped in 7.65s

bash format/check.sh   # All checks passed! (ruff 0.14.2)

Measured Impact

GPU 4, BACKEND.TORCH, seed 0. "main-high" is current main 0127a0313 with ulimit -n 65536; "branch-low" is this branch at ulimit -n 1024. OLMoE-1B-7B-0924 64x512 batch 8; Qwen2.5-0.5B-Instruct 128x512 batch 8.

Metric Before (main-high) After (branch-low) Change
OLMoE GPTQ saved tensors - 12,627 bit-identical; jsons equal 0
OLMoE RTN saved tensors - 12,627 bit-identical; jsons equal 0
Qwen GPTQ saved tensors - 794 bit-identical; jsons equal 0
Qwen AWQ saved tensors - 626 bit-identical; jsons equal 0
OLMoE GPTQ max open fds 3,188 (65536 limit) 62 -3,126
OLMoE RTN max open fds 3,187 52 -3,135
OLMoE GPTQ checkpoint load on CPU at 1024 EMFILE 45.5 s, 0 checkpoint fds fixed

Host RSS peak is unchanged. Wall time stays inside the host's run-to-run variance: the same main revision measured 136 s and 296 s for OLMoE GPTQ in different runs, and the interleaved Qwen pair is slightly faster on the branch. Interleaved pairs on the same GPU:

Run pair main-high quantize branch-low quantize main-high host RSS peak branch-low host RSS peak
Qwen GPTQ #1 11.7 s 10.9 s 1108.7 MiB 1103.7 MiB
Qwen GPTQ #2 12.4 s 12.0 s 1073.1 MiB 1127.6 MiB
OLMoE GPTQ 131.0 s 144.6 s 1450.6 MiB 1459.9 MiB

The offload file set, tensor bytes and config jsons are identical, so there is no format or accuracy change.

Model Support / Module Plan

Not applicable: no model, alias, definition, or module tree changes.

AWQ onboarding safety

Not applicable: no AWQ grouping, search, replay or fold change. AWQ shares the checkpoint reader and offload path; the Qwen AWQ control above is bit-identical (626 tensors).

Logic Flow Documentation

  • This change alters the mapping lifecycle; the required diagram is included below. No docs page is added because the user-facing API and saved format are unchanged.
  • New-flow Mermaid diagram uses real symbol names.
  • The replaced mechanism is tabulated with file:line evidence.
  • Failure paths are marked.
flowchart TD
    A["GPTQModel.load / from_quantized / quantize"] --> B{"ensure_nofile_limit<br/>trackfd supported?"}
    B -- "yes (3.13+)" --> C["no-op"]
    B -- "no (3.11/3.12)" --> D["raise soft RLIMIT_NOFILE to hard<br/>warn once if hard < 4096"]
    C --> E["file_back_module / read_tensors"]
    D --> E
    E --> F["map_file_window(fd, length, offset, access)"]
    F --> G{"TRACKFD_SUPPORTED?"}
    G -- "yes" --> H["mmap.mmap(..., trackfd=False)<br/>no descriptor retained"]
    G -- "no" --> I["mmap.mmap(...)<br/>one descriptor per mapping"]
    H --> J["zero-copy tensor view<br/>mapping lives with the view"]
    I --> J
    J --> K{"more modules?"}
    K -- "yes" --> E
    K -- "no" --> L["done"]
    I -. "fd limit reached before the fallback ran" .-> X["OSError EMFILE"]
    style X fill:#ffe8e8,stroke:#cc3333
Loading
Decision Before (main) After
Mapping helper direct mmap.mmap at reader.py:226,308,331 and filebacked.py:167 map_file_window (utils/fd_limit.py)
Descriptor retained per mapping yes (CPython dup) no on 3.13+; one on 3.11/3.12
3.11/3.12 mitigation none, EMFILE soft RLIMIT_NOFILE raised to hard at load/quantize
Offload unit / format per module, unchanged per module, unchanged

Review Requirements

AI-assisted code is welcome. Open the PR as a draft. Mark it ready only after
review and after GitHub confirms the pushed head has no conflicts with the
current remote base.

I or an AI agent (such as Codex or Claude) have:

  • Reviewed this PR.
  • Checked that the code matches existing project structure, APIs, and conventions.
  • Avoided unnecessary monkeypatching and used the project's normal extension points where possible.
  • Minimized and compacted the impacted code surface.
  • Considered and eliminated potential regressions.

Kernel Accuracy Requirements

Not applicable: no kernel, packer or dispatch change.

Notes

  • trackfd is a Python 3.13+ keyword; the helper probes it once at import and falls back to the plain call on 3.11/3.12.
  • The 3.11/3.12 fallback is tested by monkeypatching the capability off; the host only has Python 3.14, so the real 3.11/3.12 rlimit path was not executed end to end. On those interpreters the loader still needs one descriptor per live mapping, so a hard limit below that count can still fail; the helper warns once when the hard limit is below 4096.
  • Windows: resource is optional in the helper and the test module; the mapping helper itself is portable. Not run on Windows.
  • Two-GPU and non-Linux /proc paths are untested.
  • The initial non-quantized base-module offload also uses file_back_module; it is a few dozen files per model, not per expert, and is covered by the same helper.

🤖 Generated with Claude Code

`file_back_module` keeps a zero-copy mapping of each offloaded module for the
rest of the run, and the checkpoint reader keeps one mapping per module group
for CPU-placed models. Python's `mmap` duplicates the mapped file descriptor
unless the caller passes `trackfd=False` (3.13+), and that duplicate stays open
until the mapping is closed, so a 64-expert MoE opens thousands of descriptors
and hits the default soft `RLIMIT_NOFILE` of 1024:

    OSError: [Errno 24] Too many open files
    .../weight_loader/reader.py:331

Bisect: the pre-#6473 parent (aff56aa) completes OLMoE GPTQ at 1024; #6473
(0043349) introduced the per-module file-backed offload.

Add `gptqmodel/utils/fd_limit.py`:

- `map_file_window(fd, length, offset=0, access=ACCESS_COPY)` asks `mmap` for
  an untracked mapping when the interpreter supports it. The mapping still
  keeps the file data alive after the caller closes the fd; only the duplicate
  descriptor is gone.
- `ensure_nofile_limit()` is the Python 3.11/3.12 fallback where `trackfd`
  does not exist: it raises the soft `RLIMIT_NOFILE` to the hard limit (only
  ever raises, logs once at debug) and warns once, naming `ulimit -n`, when the
  hard limit is still below 4096.

Use the helper at every `mmap.mmap` site in `weight_loader/reader.py` (3) and
`weight_loader/filebacked.py` (1), and call `ensure_nofile_limit()` once at
the start of `GPTQModel.load`, `GPTQModel.from_quantized` and
`BaseQModel.quantize` (a no-op on 3.13+).

The offload format, mapping lifetimes, read order and tensor values are
unchanged; `close()`, `flush()` and `madvise()` do not need the tracked fd and
there are no `size()`/`resize()` calls on these mappings.

This replaces the per-layer offload bundle from the first revision of the PR:
bundling forced a synchronous finalize drain, raised host RSS up to ~2x on
Qwen2.5-0.5B, and still failed for a layer with >~1000 modules.

Tests: `tests/test_offload_fd_bound.py` now exercises the offload write path
(GPTQ, RTN) and a quantized-checkpoint load at a deterministic soft limit of
256; all three fail with EMFILE on main and pass here. A fourth test disables
the trackfd capability and asserts the rlimit fallback raises only the soft
limit. GPU A/B on OLMoE-1B-7B (GPTQ, RTN) and Qwen2.5-0.5B (GPTQ, AWQ) is
bit-identical to main at 65536 with the branch at 1024, and host RSS peak is
unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Qubitium
Qubitium force-pushed the fix/olmo-offload-fd-leak branch from ffcc7fd to 98a6a3b Compare December 1, 2026 15:21
@Qubitium Qubitium changed the title fix(offload): bundle finalized modules per layer to bound open fds fix(offload): stop tracking mmap file descriptors in the weight loader Dec 1, 2026
Comment thread gptqmodel/utils/fd_limit.py Resolved
Comment thread gptqmodel/utils/fd_limit.py Resolved
@Qubitium
Qubitium marked this pull request as ready for review December 1, 2026 17:39
@Qubitium
Qubitium merged commit e4d7f76 into main Dec 1, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/olmo-offload-fd-leak branch December 1, 2026 17:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant