fix: derive staging from materializing offload scopes

This commit is contained in:
LLMsherpa authored and GitHub committed 2026-10-26 17:04:56 -04:00
1 parent 263854cb12
commit ba0404fc28
3 files changed
+142 -27

No files matched your search

+10 -17
View File
@@ -1918,9 +1918,9 @@ def _model_inventory(handle):
model = handle.model
modules = dict(model.named_modules())
dispatch = dev.uses_accelerate_dispatch(model)
resident, largest, expanded, owner_devices = {}, {}, {}, {}
scopes, disk_temporaries, dequantization = {}, {}, {}
offload_devices = {}
for path, owner in modules.items():
hook = getattr(owner, "_hf_hook", None)
if hook is None:
@@ -1947,6 +1947,7 @@ def _model_inventory(handle):
recurse=align.place_submodules, remove_non_persistent=True,
):
full_name = f"{path}.{relative}" if path else relative
offload_devices[full_name] = target
module_path, _, local_name = full_name.rpartition(".")
backing = (_cpu_offload_backing(modules, module_path, local_name)
if tensor.is_meta else None)
@@ -1963,26 +1964,21 @@ def _model_inventory(handle):
logical_sizes = {}
seen = set()
for name, owner in modules.items():
tensors = list(owner.parameters(recurse=False)) + list(owner.buffers(recurse=False))
tensors = (list(owner.named_parameters(recurse=False))
+ list(owner.named_buffers(recurse=False)))
if not tensors:
continue
execution = None
if dispatch:
path = name
while True:
execution = dev._hook_execution_device(
[modules[path]], require_supported_hooks=True
)
if execution is not None or not path:
break
path = path.rpartition(".")[0]
devices = set()
for tensor in tensors:
for local_name, tensor in tensors:
full_name = f"{name}.{local_name}" if name else local_name
execution = offload_devices.get(full_name)
if tensor.device.type == "meta" and execution is None:
raise ValueError(
f"meta tensor in {name or '<root>'} has no execution-device hook; "
f"meta tensor in {name or '<root>'} has no materializing offload hook; "
"set OBLITERATUS_PHASE_ADMISSION=off to explicitly bypass admission"
)
# IO hooks move inputs, not descendant weights. Only an offload
# scope materializes weights on a different device during forward.
target = _device_name(execution if execution is not None else tensor.device)
devices.add(target)
size = tensor.numel() * tensor.element_size()
@@ -1994,9 +1990,6 @@ def _model_inventory(handle):
staging_size = (max(size, logical) if packed
else size if transferred else 0)
if tensor.is_meta and target == "cpu" and not packed:
local_name = next(key for key, value in
(*owner._parameters.items(), *owner._buffers.items())
if value is tensor)
backing = _cpu_offload_backing(modules, name, local_name)
if (backing is not None and backing.shape == tensor.shape
and backing.dtype == tensor.dtype):
+17 -8
View File
@@ -9,7 +9,7 @@ from unittest.mock import Mock
import pytest
import re
import torch
from accelerate.hooks import AlignDevicesHook
from accelerate.hooks import AlignDevicesHook, add_hook_to_module
from transformers import GPT2Config, GPT2LMHeadModel
from obliteratus import phase_admission as admission
@@ -412,10 +412,13 @@ def test_embedding_only_device_is_admitted_using_accelerate_execution_hooks(tiny
"transformer.h": "cuda:1",
"lm_head": "cuda:1",
}
model.transformer.wte._hf_hook = AlignDevicesHook(execution_device="cuda:0")
model.lm_head._hf_hook = AlignDevicesHook(execution_device="cuda:1")
for layer in model.transformer.h:
layer._hf_hook = AlignDevicesHook(execution_device="cuda:1")
placements = [(model.transformer.wte, "cuda:0"), (model.lm_head, "cuda:1")]
placements.extend((layer, "cuda:1") for layer in model.transformer.h)
for owner, target in placements:
add_hook_to_module(owner, AlignDevicesHook(
execution_device="cpu", offload=True, place_submodules=True,
))
owner._hf_hook.execution_device = target
demand = model_phase_demand(tiny_handle, "probe", tokens=8)
embedding = demand.devices["cuda:0"]
assert embedding.kv_bytes == 0
@@ -574,15 +577,21 @@ def test_loader_rejects_summon_before_checkpoint_weight_load(tiny_config, monkey
load_weights.assert_not_called()
def test_output_head_inherits_ancestor_execution_hook(tiny_handle, monkeypatch):
def test_output_head_inherits_recursive_offload_scope(tiny_handle, monkeypatch):
model = tiny_handle.model
head = model.lm_head
del model.lm_head
model.output_holder = torch.nn.Module()
model.output_holder.head = head
model.output_holder._hf_hook = AlignDevicesHook(execution_device="cuda:1")
add_hook_to_module(model.output_holder, AlignDevicesHook(
execution_device="cpu", offload=True, place_submodules=True,
))
model.output_holder._hf_hook.execution_device = "cuda:1"
monkeypatch.setattr(model, "get_output_embeddings", lambda: head)
model.transformer.wte._hf_hook = AlignDevicesHook(execution_device="cuda:0")
add_hook_to_module(model.transformer.wte, AlignDevicesHook(
execution_device="cpu", offload=True,
))
model.transformer.wte._hf_hook.execution_device = "cuda:0"
demand = model_phase_demand(tiny_handle, "verify", tokens=8)
assert demand.devices["cuda:0"].output_bytes > 0
assert demand.devices["cuda:1"].output_bytes > 0
+115 -2
View File
@@ -1,10 +1,12 @@
"""Inference staging follows actual Accelerate hook scopes without CUDA allocation."""
from types import SimpleNamespace
from unittest.mock import Mock
from unittest.mock import Mock, patch
from accelerate import cpu_offload, disk_offload
from accelerate.hooks import AlignDevicesHook
from accelerate.hooks import (
AlignDevicesHook, SequentialHook, add_hook_to_module, set_module_tensor_to_device,
)
from accelerate.utils.offload import OffloadedWeightsLoader
import pytest
import torch
@@ -121,6 +123,117 @@ def test_offload_with_integer_execution_device_needs_no_cuda_runtime():
assert staging["cuda:0"] > 0
@pytest.mark.parametrize("nested_io", [False, True])
def test_io_only_hooks_do_not_stage_uncovered_cpu_tables(nested_io):
handle = tiny_handle()
largest = max(parameter.numel() * parameter.element_size()
for parameter in handle.model.parameters())
cpu_offload(handle.model, execution_device=torch.device("cpu"))
relocate_execution_hooks(handle.model)
handle.model._hf_hook.execution_device = "cuda:0"
resident_before = _model_inventory(handle)[0]["cpu"]
holder = torch.nn.Module()
holder.table = torch.nn.Embedding(2048, 32, dtype=torch.bfloat16)
if nested_io:
add_hook_to_module(holder, SequentialHook(
AlignDevicesHook(execution_device="cuda:1"),
AlignDevicesHook(execution_device="cuda:1", io_same_device=True),
))
handle.model.cpu_lookup = holder
resident, staging, expanded, _, _, _, _, _ = _model_inventory(handle)
table_bytes = holder.table.weight.numel() * holder.table.weight.element_size()
assert resident["cpu"] == resident_before + table_bytes
assert expanded["cpu"] == holder.table.weight.numel() * 4
assert staging["cpu"] == 0
assert staging["cuda:0"] == largest
assert staging.get("cuda:1", 0) == 0
assert holder.table.weight.device.type == "cpu"
transfer = Mock(side_effect=lambda value, *args, **kwargs: value)
with patch("accelerate.hooks.send_to_device", transfer), patch(
"accelerate.hooks.set_module_tensor_to_device",
side_effect=AssertionError("IO hook must not materialize weights"),
):
inputs = torch.tensor([[1, 2]])
handle.model._hf_hook.pre_forward(handle.model, inputs)
transfer.assert_any_call((inputs,), "cuda:0")
@pytest.mark.parametrize("recursive", [False, True])
@pytest.mark.parametrize("offload_buffers", [False, True])
def test_offload_scope_controls_cpu_parameter_and_buffer_transfers(recursive, offload_buffers):
handle = tiny_handle()
holder = torch.nn.Module()
holder.register_parameter("direct", torch.nn.Parameter(torch.zeros(32768)))
holder.register_buffer("persistent", torch.zeros(65536))
holder.table = torch.nn.Embedding(8192, 32)
handle.model.lookup = holder
add_hook_to_module(holder, AlignDevicesHook(
execution_device="cpu", offload=True,
place_submodules=recursive, offload_buffers=offload_buffers,
))
with patch("accelerate.hooks.set_module_tensor_to_device",
wraps=set_module_tensor_to_device) as materialize:
holder._hf_hook.pre_forward(holder)
names = {call.args[1] for call in materialize.call_args_list}
assert names == ({"direct"}
| ({"persistent"} if offload_buffers else set())
| ({"table.weight"} if recursive else set()))
holder._hf_hook.post_forward(holder, None)
holder._hf_hook.execution_device = "cuda:0"
_, staging, _, _, _, _, _, _ = _model_inventory(handle)
expected = holder.direct.numel() * 4
if offload_buffers:
expected += holder.persistent.numel() * 4
if recursive:
expected += holder.table.weight.numel() * 4
assert staging["cuda:0"] == expected
assert staging["cpu"] == 0
def test_quantized_cpu_storage_keeps_dequantization_on_cpu_under_io_hook():
handle = tiny_handle()
add_hook_to_module(handle.model, AlignDevicesHook(execution_device="cuda:0"))
packed = torch.nn.Parameter(torch.zeros(128, dtype=torch.uint8), requires_grad=False)
packed.quant_state = SimpleNamespace(shape=(32, 64))
handle.model.model.layers[0].register_parameter("packed_experts", packed)
_, staging, _, placement, _, _, _, _ = _model_inventory(handle)
assert staging["cpu"] == 32 * 64 * 4
assert staging.get("cuda:0", 0) == 0
assert placement == [["cpu"], ["cpu"]]
def test_quantized_offload_reserves_storage_and_dequantization_together():
handle = tiny_handle()
holder = torch.nn.Module()
holder.register_parameter("packed", torch.nn.Parameter(
torch.zeros(128, dtype=torch.uint8), requires_grad=False,
))
handle.model.packed_projection = holder
add_hook_to_module(holder, AlignDevicesHook(execution_device="cpu", offload=True))
holder.packed.quant_state = SimpleNamespace(shape=(32, 64))
holder._hf_hook.execution_device = "cuda:1"
_, staging, _, _, _, _, _, _ = _model_inventory(handle)
assert staging["cuda:1"] == 128 + 32 * 64 * 4
assert staging["cpu"] == 0
def test_io_only_ancestor_does_not_materialize_meta_parameters():
handle = tiny_handle()
add_hook_to_module(handle.model, AlignDevicesHook(execution_device="cuda:0"))
handle.model.table = torch.nn.Embedding(32, 32, device="meta")
with pytest.raises(ValueError, match="materializing offload hook"):
_model_inventory(handle)
def test_unmodelled_dispatch_hook_rejects_with_explicit_escape_hatch(monkeypatch):
handle = tiny_handle()
handle.model.model.rotary_emb._hf_hook = SimpleNamespace(execution_device="cpu")