Skip to content

fix(offload): clean up per-run offload directories - #4412

Closed
Qubitium wants to merge 1 commit into
mainfrom
fix/issue-4368-offload-run-cleanup
Closed

Qubitium wants to merge 1 commit into
mainfrom
fix/issue-4368-offload-run-cleanup

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

Every quantization run created a private <offload_to_disk_path>/run-<uuid16>
directory for bundle isolation (#4202) and nothing ever removed it. With an
explicit path, four runs of a 3-layer model left 1.3 GB of run-* trees; the
leak also grew across processes. EoRA generation allocated one more run
directory on top.

The run directory is now owned by the model that created it. It is removed when
that model is collected, when the quantization loop fails, before the same model
binds another run, after the EoRA adapter is written, and at interpreter exit
for anything still tracked. Per-run isolation is unchanged.

Fixes #4368

What Changed

  • gptqmodel/utils/offload.py
    • bind_private_offload_root() records the run root and a weakref.finalize
      callback on the model, plus the caller's base root so a second run on the
      same model stays a sibling instead of nesting inside the old run directory.
    • New release_private_offload_root() detaches the finalizer, clears the
      ownership attributes, and removes the directory. Removal is
      shutil.rmtree(..., ignore_errors=True) so it is safe from a finalizer
      thread and at shutdown.
    • A module-level atexit hook removes any run root this process still owns.
      This covers lightweight model doubles that cannot be weakly referenced and
      normal interpreter exit. The auto gptqmodel_* temp root keeps its existing
      exit cleanup.
  • gptqmodel/looper/module_looper.py, gptqmodel/looper/weight_only_looper.py:
    the existing failure branch releases the run directory next to
    _restore_offloaded_base_modules(strict=False).
  • gptqmodel/models/base.py: _eora_generate() releases its run directory
    after eora_save() completes.
  • tests/test_offload_run_cleanup_4368.py: new CPU-only regression coverage.
  • docs/offload-run-directories.md: reference page for the lifecycle, linked
    from README.md and docs/README.md.

API/behavior changes:

  • No public API change. A run-* directory under an explicit
    offload_to_disk_path no longer outlives its model.
  • save() deliberately keeps the directory: the quantized modules remain
    meta-backed with accelerate offload hooks, so an in-session forward after
    save() still reads those bundles (tests/test_planar_model_e2e.py does
    exactly this). The bundles are released at teardown, when the model can no
    longer use them.

Out of scope: a SIGKILLed process runs no Python cleanup hook, so its run
directory remains. Removing another process's directory at bind time would
break concurrent runs that share an explicit path.

Tests

New regression test (tests/test_offload_run_cleanup_4368.py, 6 tests):

Test Invariant
test_release_private_offload_root_removes_bundles explicit release deletes a populated run directory
test_run_directory_survives_save_and_is_removed_at_teardown save() resolves bundles from the run directory, the in-session module stays meta-backed, and teardown removes the directory
test_sequential_runs_share_path_without_accumulating two runs on one path stay isolated, each saved checkpoint has its own weights, and no run-* accumulates
test_run_directory_is_removed_when_weight_only_run_fails a real WeightOnlyLooper failure removes the bound run directory
test_run_directory_is_removed_when_module_looper_fails ModuleLooper.loop() removes the run directory when _loop_impl raises
test_rebinding_same_model_releases_previous_run a second run on the same model releases the first root and creates a sibling

Exact commands and results (CPU only: CUDA_VISIBLE_DEVICES="",
GPTQ_BYPASS_SAFETY_CHECKS=1, PYTHONPATH=/root/worktrees/issue-4368,
/root/gptqmodel-test-venv/bin/python):

# New regression test
python -m pytest tests/test_offload_run_cleanup_4368.py -q
# 6 passed

# Directly related offload / looper / writer tests
python -m pytest tests/test_offload_run_cleanup_4368.py tests/test_offload_run_namespace.py \
  tests/test_offload_base_modules_restored.py tests/test_quantize_config_offload_tempdir.py \
  tests/test_loader_offload_staging_4385.py tests/test_offload_files.py \
  tests/test_offload_autograd.py tests/test_marlin_cpu_offload_post_init.py \
  tests/test_ernie4_5_vl_moe_offload_hook.py tests/test_module_looper_quant_log_4321.py \
  tests/test_writer_quant_log.py -q
# 161 passed, 6 skipped

# Existing weight-only looper suite (two pre-existing failures also fail at 0b7582fea)
python -m pytest tests/test_weight_only_looper.py -q
# 18 passed, 2 failed
# FAILED test_weight_only_looper_quantizes_input_and_lm_head_embeddings_only
# FAILED test_weight_only_looper_respects_dense_and_moe_vram_strategy_devices

# Checkpoint resume / SIGTERM recovery (exercises the failure cleanup path)
python -m pytest tests/test_checkpoint_quantization.py -k "not subprocess_recovery" -q
# 12 passed, 28 deselected
python -m pytest tests/test_checkpoint_quantization.py -k "subprocess_recovery" -q
# 28 passed, 12 deselected

# Save-then-forward path that must keep the bundles alive
python -m pytest "tests/test_planar_model_e2e.py::test_planar_model_quantize_save_reload_inference[4]" -q
# 1 passed

# Lint
ruff check gptqmodel/utils/offload.py gptqmodel/looper/module_looper.py \
  gptqmodel/looper/weight_only_looper.py gptqmodel/models/base.py \
  tests/test_offload_run_cleanup_4368.py
# All checks passed!

The two test_weight_only_looper.py failures were reproduced on a clean
0b7582fea worktree with the same environment; they are not caused by this
change.

End-to-end check of the reported repro (two sequential runs, explicit path,
del model; gc.collect()):

run 0: run dirs while alive = ['run-8e714c2b475a4648']   after del = []
run 1: run dirs while alive = ['run-05254005f1944a36']   after del = []

Model Support / Module Plan

Not applicable: no model type, alias, definition, or module-plan change.

AWQ onboarding safety

Not applicable: no model/alias or AWQ grouping/search/replay/fold change.

Logic Flow Documentation

The change alters the offload scratch-directory lifecycle and adds a failure
path, so the diagrams are included here and committed in
docs/offload-run-directories.md, linked
from README.md.

New flow (shipped code):

flowchart TD
    A["bind_private_offload_root(model)"] --> B{"model already owns a run?"}
    B -- Yes --> C["release_private_offload_root(model)"]
    B -- No --> D["base = model._offload_run_base or configured root"]
    C --> D
    D --> E["makedirs base/run-uuid; add to _ACTIVE_RUN_ROOTS"]
    E --> F["weakref.finalize(model, _remove_offload_run_root, run_root)"]
    F --> G["private config copy points at run-uuid"]
    G --> H{"run outcome"}
    H -- "loop raises" --> I["looper except: release_private_offload_root"]
    H -- "eora_save completes" --> J["_eora_generate: release_private_offload_root"]
    H -- "save() completes" --> K["bundles retained: model still materializes from them"]
    H -- "model collected" --> L["finalizer: _remove_offload_run_root"]
    H -- "interpreter exit" --> M["atexit: _cleanup_active_offload_run_roots"]
    classDef failure fill:#ffe8e8,stroke:#b30000,color:#111;
    class I failure;
Loading

Before/after, with the old mechanism:

Mechanism Before (0b7582fea) After
Run directory creation bind_private_offload_root() created run-<uuid16> and stored the private config (gptqmodel/utils/offload.py:79-110) Same isolation, plus ownership attributes and weakref.finalize (gptqmodel/utils/offload.py:133)
Model teardown No cleanup; explicit root grew by one model per run Finalizer removes the run directory
Failed quantization No cleanup gptqmodel/looper/module_looper.py:1889, gptqmodel/looper/weight_only_looper.py:904
Same model, new run Second run nested inside the previous private path Previous root released, new sibling created
EoRA generation Extra run directory never removed Released after eora_save() (gptqmodel/models/base.py:2898)
Interpreter exit Auto temp root removed, explicit run dir leaked atexit removes any tracked run dir

Failure and ambiguity contract:

Situation Before After
Loop raises (including checkpoint stop) Run dir leaked Run dir deleted; checkpoint store owns published artifacts and resume recreates disposable indexes
save() raises Run dir leaked Run dir kept for retry; teardown removes it later
save() succeeds Run dir leaked Run dir kept because the live model still reads it
Model not weak-referenceable Run dir leaked atexit removes it at exit
SIGKILL Run dir leaked Unchanged; no Python hook runs (documented out of scope)

Kernel Accuracy Requirements

Not applicable: no kernel or numerical change.

Notes

  • The issue title says the directory should be removed "after save". This PR
    removes it at teardown instead, because save() does not materialize the
    quantized modules: they stay on meta with accelerate hooks pointing into
    the run directory, and tests/test_planar_model_e2e.py forwards from the
    same model after save(). Deleting at the end of save() would raise
    FileNotFoundError there. The regression test pins the retained-until-
    teardown behavior.
  • _RUN_BASE_ATTR is retained after a release so a retry/requantize on the
    same model creates a sibling of the original root rather than nesting inside
    the deleted path.
  • No environment-variable switches were added.

bind_private_offload_root() created run-<uuid16> under the configured
offload_to_disk_path for every quantization run and nothing removed it.
An explicit path therefore grew by one full model per run, including
EoRA generation's extra run.

The directory now belongs to the model that created it. It is removed
when the model is collected (weakref.finalize), when the quantization
loop fails, when the same model binds another run, and after the EoRA
adapter is written. The module-level atexit hook removes anything left
at interpreter exit, covering models that cannot be weakly referenced.

The bundles are not deleted at the end of save(): the quantized modules
stay meta-backed with accelerate offload hooks, so an in-session forward
after save() still reads them (test_planar_model_e2e.py). They are
released at teardown, when the model can no longer use them.

Fixes #4368
@Qubitium

Copy link
Copy Markdown
Collaborator Author

Superseded: #4368 was fixed and merged as #4409. This branch duplicates that change and now conflicts with main.

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