Merge remote-tracking branch 'origin/main' into qwen-image-2.1

# Conflicts:
#	vllm_omni/diffusion/executor/multiproc_executor.py
#	vllm_omni/diffusion/offloader/sequential_backend.py
This commit is contained in:
Isotr0py committed 2026-09-21 07:32:04 +00:00
commit 9174554e40
1332 files changed
+160051 -60504

No files matched your search

@@ -53,8 +53,7 @@ from .host_registration import (
HostRegistrationError,
register_host_mappings,
)
from .offload_plan import OffloadPlan
from .plan_resolver import ResolvedComponent, resolve_offload_plan
from .plan_resolver import BlockStack, ResolvedComponent, resolve_offload_plan
from .tensor_utils import (
clear_block_storage,
clear_tensor_storage,
@@ -111,7 +110,6 @@ def _forget_active_hwr_registration(
# use layerwise offload (streaming hooks) or be moved to GPU as a resident
# module. Submodules larger than this are offloaded to save HBM; smaller
# ones stay resident for lower latency.
_ON_DEMAND_THRESHOLD_MB = 1024
class DistributedLayerwiseOffloadHook(ModelHook):
@@ -1182,7 +1180,7 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
def _load_weights_via_mmap(
self,
pipeline: nn.Module,
modules,
dits: tuple[ResolvedComponent, ...],
plan: HostWeightPlan,
) -> None:
"""Load DiT checkpoint tensors as file-backed safetensors views.
@@ -1226,7 +1224,7 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
# converts the child's buffers too. So we must save ALL buffers
# from ALL DiT modules BEFORE any to_empty call.
saved_buffers: dict[int, dict[str, torch.Tensor]] = {}
for dit_module in modules.dits:
for dit_module in (component.module for component in dits):
bufs: dict[str, torch.Tensor] = {}
for name, buf in dit_module.named_buffers():
# Check if this buffer is non-persistent on its OWNING module
@@ -1246,7 +1244,7 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
# Skip modules that are already meta (happens when a parent DiT
# module contains a child DiT module — to_empty on the parent
# already converted the child).
for dit_module in modules.dits:
for dit_module in (component.module for component in dits):
if any(p.is_meta for p in dit_module.parameters()):
logger.info(
"%s already on meta device (skipping to_empty, %d buffers saved)",
@@ -1307,7 +1305,7 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
# assigning checkpoint tensors. The mmap path bypasses that loader, so
# preserve the same lifecycle for transforms such as Cosmos3's fp32
# timestep embedder.
for dit_name, dit_module in zip(modules.dit_names, modules.dits):
for dit_name, dit_module in ((component.path, component.module) for component in dits):
# Restore non-persistent buffers before post-load hooks and strict
# validation. They are constructor-derived and intentionally have
# no checkpoint binding.
@@ -1352,7 +1350,7 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
self._mmap_transforms_by_tensor_id[id(target)] = binding.transform
remaining_meta: list[str] = []
for dit_name, dit_module in zip(modules.dit_names, modules.dits):
for dit_name, dit_module in ((component.path, component.module) for component in dits):
remaining_meta.extend(
f"{dit_name}.{name}" for name, tensor in dit_module.named_parameters() if tensor.is_meta
)
@@ -1517,73 +1515,26 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
)
return True
def _try_layerwise_offload_submodule(self, module: nn.Module, name: str, plan: OffloadPlan | None = None) -> bool:
"""Try to apply layerwise offload to a large submodule's blocks.
Resolution order:
1. OffloadPlan.offload_submodules (declarative, if plan is provided)
2. Heuristic search for common block-list attributes
Returns True if layerwise offload was applied, False otherwise.
"""
from operator import attrgetter
blocks = None
blocks_attr = None
# 1. Check OffloadPlan first (declarative — no guessing)
if plan is not None and name in plan.offload_submodules:
attr_name = plan.offload_submodules[name]
try:
candidate = attrgetter(attr_name)(module)
if isinstance(candidate, nn.ModuleList) and len(candidate) > 1:
blocks = candidate
blocks_attr = attr_name
except AttributeError:
logger.warning(
"OffloadPlan declared block attr '%s' for submodule '%s' "
"but attribute not found — falling back to heuristic",
attr_name,
name,
)
# 2. Fallback: heuristic search
if blocks is None:
for attr_name in ("layers", "blocks", "h", "model.layers"):
try:
candidate = attrgetter(attr_name)(module)
except AttributeError:
continue
if isinstance(candidate, nn.ModuleList) and len(candidate) > 1:
blocks = candidate
blocks_attr = attr_name
break
if blocks is None:
return False
def _offload_nested_submodule(self, component: ResolvedComponent) -> None:
"""Stream one resolved DiT submodule through its own hook ring."""
stack = component.stacks[0]
logger.info(
"Distributed layerwise offload for submodule '%s.%s' (%d blocks, %.0f MB total, group_size=%d)",
name,
blocks_attr,
len(blocks),
sum(p.nelement() * p.element_size() for p in module.parameters()) / 1048576,
component.path,
stack.attrs[0],
len(stack.blocks),
sum(p.nelement() * p.element_size() for p in component.module.parameters()) / 1048576,
self._component_transport(DIT_COMPONENT)[1],
)
# Move non-block parts of the submodule to GPU (small: embeddings, norms)
for child_name, child in module.named_children():
if child_name != blocks_attr:
child.to(self.device)
self._install_hook_group(blocks, DIT_COMPONENT, use_dit_mmap=True)
return True
# Keep the submodule's own non-block state resident by block identity,
# so an attribute aliasing a streamed block is not placed with it.
move_non_block_state_to_device(component.module, (stack.blocks,), self.device)
self._install_hook_group(stack.blocks, DIT_COMPONENT, use_dit_mmap=True)
def _prepare_dit_non_block_modules(
self,
dit_module: nn.Module,
blocks_attr_names: list[str],
all_dit_modules: set[int],
plan: OffloadPlan | None,
component: ResolvedComponent,
stack: BlockStack,
) -> None:
"""Place or hook the DiT parts that are outside its repeated blocks.
@@ -1591,28 +1542,23 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
an all-resident stage skips placement for modules such as H3's token
refiner and enters the forward pass with CPU or meta tensors.
"""
dit_module = component.module
nested = {child.path.rsplit(".", 1)[-1]: child for child in component.children}
for name, module in dit_module.named_children():
if name in blocks_attr_names:
if name in stack.attrs:
logger.debug("Skipped blocks module %s", name)
continue
module_mb = (
sum(
param.nelement() * param.element_size() if not getattr(param, "is_meta", False) else 0
for param in module.parameters()
)
/ 1048576
)
explicitly_planned = plan is not None and name in plan.offload_submodules
if explicitly_planned or module_mb > _ON_DEMAND_THRESHOLD_MB:
if id(module) in all_dit_modules:
child = nested.get(name)
if child is not None:
if not child.selected:
logger.info("Submodule '%s' is already a DiT module, skipping layerwise offload", name)
elif self._try_layerwise_offload_submodule(module, name, plan):
pass
elif child.stacks:
self._offload_nested_submodule(child)
else:
prepare_component(
module,
name,
child.module,
child.path,
device=self.device,
stage_on_demand=True,
blockwise=False,
@@ -1715,7 +1661,7 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
elif host_weight_plan.backing_kind == "checkpoint_mmap":
self._load_weights_via_mmap(
pipeline,
resolved.modules,
resolved.dits,
host_weight_plan,
)
else:
@@ -1750,16 +1696,12 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
enable_encoder_blocks=self._try_layerwise_offload_encoder,
)
if self.config.offloads(DIT_COMPONENT):
if any(component.selected for component in resolved.dits):
logger.info(
"Applying distributed layer-wise offloading on %s",
[component.path for component in resolved.dits],
)
# Collect all DiT module objects to detect submodules that are
# already handled as a separate DiT module (avoids duplicate hooks).
all_dit_modules = set(id(component.module) for component in resolved.dits)
# Apply hooks for each DiT module
for component, stack in iter_streamable_dits(resolved, self.device):
streaming = list(stack.streaming)
@@ -1772,12 +1714,7 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
len(streaming),
)
self._prepare_dit_non_block_modules(
component.module,
list(stack.attrs),
all_dit_modules,
resolved.declaration,
)
self._prepare_dit_non_block_modules(component, stack)
if not streaming:
logger.info("All blocks for %s are resident; no streaming hooks required", component.path)
@@ -1804,11 +1741,6 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
self.enabled = bool(self._resident_blocks or self._encoder_modules or self._staged_components)
if self._using_mmap and not self.enabled:
self._release_mmap_handles()
if not self.enabled and not self.config.offloads(DIT_COMPONENT):
raise ValueError(
"None of the selected distributed layerwise offload components have "
"a model-declared streamable or on-demand plan"
)
return
# Unified allocation: 2 shared output buffers + 2 shared shard buffers
@@ -14,11 +14,6 @@ from vllm_omni.diffusion.hooks import HookRegistry, ModelHook
from vllm_omni.platforms import current_omni_platform
from .base import OffloadBackend, OffloadConfig, run_cleanup_steps
from .block_discovery import (
get_blocks_attr_names,
get_blocks_from_dit,
set_blocks_attr_names,
)
from .component_utils import (
clear_encoder_layerwise_state,
iter_streamable_dits,
@@ -26,7 +21,6 @@ from .component_utils import (
prepare_pipeline_components,
set_encoder_layerwise_state,
)
from .config import DIT_COMPONENT
from .plan_resolver import ResolvedComponent, resolve_offload_plan
from .tensor_utils import (
clear_block_storage,
@@ -433,9 +427,8 @@ class LayerWiseOffloadBackend(OffloadBackend):
return
resolved = resolve_offload_plan(pipeline, self.config)
if not resolved.dits and self.config.offloads(DIT_COMPONENT):
# An explicit selection already failed while resolving.
logger.warning("No DiT/transformer modules found for selected DiT layerwise offload")
if resolved.skip_reason is not None:
logger.warning("%s", resolved.skip_reason)
return
def enable_encoder_blocks(component: ResolvedComponent) -> bool:
@@ -458,15 +451,6 @@ class LayerWiseOffloadBackend(OffloadBackend):
enable_encoder_blocks=enable_encoder_blocks,
)
if not self.config.offloads(DIT_COMPONENT):
self.enabled = bool(self._encoder_modules or self._staged_components)
if not self.enabled:
raise ValueError(
"None of the selected layerwise offload components have "
"a model-declared streamable or on-demand plan"
)
return
logger.info("Applying layer-wise offloading on %s", [component.path for component in resolved.dits])
# Apply block-wise offloading hook for each of the blocks in DiT model(s)
@@ -475,22 +459,9 @@ class LayerWiseOffloadBackend(OffloadBackend):
dit_module = component.module
blocks = list(stack.blocks)
# Move non-block modules to GPU (they stay resident)
for name, m in dit_module.named_children():
if name not in stack.attrs:
m.to(self.device)
logger.debug(f"Moved {name} to device {self.device}")
else:
logger.debug(f"Skipped blocks module {name}")
# Move top-level params/buffers to GPU (dit_module's own, not sub-modules)
for param in dit_module._parameters.values():
if param is not None:
param.data = param.data.to(self.device, non_blocking=True)
for buffer in dit_module._buffers.values():
if buffer is not None:
buffer.data = buffer.data.to(self.device, non_blocking=True)
# Place the remainder by resolved block tensor identity, just as
# for encoders. Attribute aliases must not move streamed weights.
move_non_block_state_to_device(dit_module, (stack.blocks,), self.device)
block_hooks = _install_layerwise_hook_group(
blocks,
@@ -550,8 +521,3 @@ class LayerWiseOffloadBackend(OffloadBackend):
def disable(self) -> None:
self._disable(restore_weights=True)
# Compatibility aliases for existing model integrations.
get_blocks_attr_names = staticmethod(get_blocks_attr_names)
set_blocks_attr_names = staticmethod(set_blocks_attr_names)
get_blocks_from_dit = staticmethod(get_blocks_from_dit)
+121 -10
View File
@@ -17,6 +17,7 @@ from __future__ import annotations
from dataclasses import dataclass
from functools import cache
from operator import attrgetter
from typing import TYPE_CHECKING
from torch import nn
@@ -27,7 +28,7 @@ from vllm_omni.diffusion.models.interface import SupportsComponentDiscovery
from .block_discovery import get_blocks_from_dit
from .component_utils import get_encoder_block_groups, validate_on_demand_component
from .config import DIT_COMPONENT, TEXT_ENCODER_COMPONENT, OffloadStrategy
from .module_collector import ModuleDiscovery, PipelineModules
from .module_collector import ModuleDiscovery
from .offload_plan import OffloadPlan, get_offload_plan
if TYPE_CHECKING:
@@ -76,6 +77,9 @@ class ResolvedComponent:
selected: bool
stacks: tuple[BlockStack, ...] = ()
on_demand: bool = False
# Submodules of a DiT that are large enough to own their residency instead
# of staying resident with the rest of its non-block state.
children: tuple[ResolvedComponent, ...] = ()
@dataclass(frozen=True)
@@ -86,17 +90,33 @@ class ResolvedOffloadPlan:
encoders: tuple[ResolvedComponent, ...]
vaes: tuple[ResolvedComponent, ...]
residents: tuple[ResolvedComponent, ...]
# Raw discovery output and the model declaration remain reachable for the
# loader-owned mmap path and for DLO's nested-submodule staging, which
# still interpret topology themselves.
modules: PipelineModules
declaration: OffloadPlan | None = None
# Ordinary layerwise offload turns a legacy selection it cannot serve into
# a complete no-op, placement included. Distributed layerwise offload warns
# and keeps preparing its other components instead, so this stays scoped to
# the strategy that honors it.
skip_reason: str | None = None
@property
def components(self) -> tuple[ResolvedComponent, ...]:
return self.dits + self.encoders + self.vaes + self.residents
# A DiT submodule this large owns its residency even when no plan declares it.
_NESTED_OFFLOAD_THRESHOLD_MB = 1024
_NESTED_BLOCK_ATTRS = ("layers", "blocks", "h", "model.layers")
@cache
def _warn_nested_block_scan(module_class: str, attr: str) -> None:
"""Warn once per class that a nested block list was found by guessing."""
logger.warning(
"%s block list was discovered as %r by scanning well-known attribute names. "
"Declare it in OffloadPlan.offload_submodules; the attribute scan is deprecated.",
module_class,
attr,
)
@cache
def _warn_legacy_discovery(pipeline_class: str) -> None:
"""Warn once per pipeline class that component discovery guessed.
@@ -112,6 +132,77 @@ def _warn_legacy_discovery(pipeline_class: str) -> None:
)
def _nested_block_stack(module: nn.Module, declared_attr: str | None) -> BlockStack | None:
"""Resolve one DiT submodule's own block ring, if it has one."""
candidates = (declared_attr,) if declared_attr is not None else _NESTED_BLOCK_ATTRS
for attr in candidates:
try:
blocks = attrgetter(attr)(module)
except AttributeError:
continue
if isinstance(blocks, nn.ModuleList) and len(blocks) > 1:
if declared_attr is None:
_warn_nested_block_scan(type(module).__name__, attr)
return BlockStack(attrs=(attr,), blocks=tuple(blocks))
if declared_attr is not None:
logger.warning(
"OffloadPlan declared block attr %r for submodule %s but it is not a streamable block list",
declared_attr,
type(module).__name__,
)
return None
def _resolve_dit_children(
dit_module: nn.Module,
dit_path: str,
stack: BlockStack,
declaration: OffloadPlan | None,
dit_module_ids: set[int],
) -> tuple[ResolvedComponent, ...]:
"""Resolve the DiT submodules that own their residency.
A submodule qualifies when the model declares it or when it is large enough
that keeping it resident would defeat streaming. Submodules that are
themselves discovered DiTs are left to their own component.
"""
children: list[ResolvedComponent] = []
for name, module in dit_module.named_children():
if name in stack.attrs:
continue
declared_attr = None if declaration is None else declaration.offload_submodules.get(name)
if declared_attr is None and _module_size_mb(module) <= _NESTED_OFFLOAD_THRESHOLD_MB:
continue
path = f"{dit_path}.{name}"
if id(module) in dit_module_ids:
# Its own component owns this submodule; the parent must not place it.
children.append(ResolvedComponent(path=path, module=module, selected=False))
continue
nested_stack = _nested_block_stack(module, declared_attr)
if nested_stack is None:
# Without its own ring the submodule needs the pipeline lifecycle.
validate_on_demand_component(module, path)
children.append(
ResolvedComponent(
path=path,
module=module,
selected=True,
stacks=() if nested_stack is None else (nested_stack,),
on_demand=nested_stack is None,
)
)
return tuple(children)
def _module_size_mb(module: nn.Module) -> float:
"""Expected parameter bytes in MiB, including not-yet-loaded meta tensors.
Resolution precedes mmap materialization, so residency must depend on the
tensor metadata rather than whether the loader has allocated storage yet.
"""
return sum(parameter.nelement() * parameter.element_size() for parameter in module.parameters()) / 1048576
def _resolve_dit_stacks(
module: nn.Module,
path: str,
@@ -248,11 +339,25 @@ def resolve_offload_plan(pipeline: nn.Module, config: OffloadConfig) -> Resolved
vaes: list[ResolvedComponent] = []
residents: list[ResolvedComponent] = []
dit_module_ids = {id(module) for module in modules.dits}
for path, module in zip(modules.dit_names, modules.dits):
stacks: tuple[BlockStack, ...] = ()
children: tuple[ResolvedComponent, ...] = ()
if dit_selected and layerwise:
stacks = _resolve_dit_stacks(module, path, declaration, config, explicit=explicit)
dits.append(ResolvedComponent(path=path, module=module, selected=dit_selected, stacks=stacks))
# Only distributed layerwise offload streams or stages submodules;
# the ordinary backend keeps all non-block state resident.
if stacks and config.strategy is OffloadStrategy.DISTRIBUTED_LAYER_WISE:
children = _resolve_dit_children(module, path, stacks[0], declaration, dit_module_ids)
dits.append(
ResolvedComponent(
path=path,
module=module,
selected=dit_selected,
stacks=stacks,
children=children,
)
)
for path, module in zip(modules.encoder_names, modules.encoders):
selected = config.should_offload_encoder(path, declaration)
@@ -302,8 +407,11 @@ def resolve_offload_plan(pipeline: nn.Module, config: OffloadConfig) -> Resolved
encoders=tuple(encoders),
vaes=tuple(vaes),
residents=tuple(residents),
modules=modules,
declaration=declaration,
skip_reason=(
"No DiT/transformer modules found for selected DiT layerwise offload"
if config.strategy is OffloadStrategy.LAYER_WISE and dit_selected and not dits
else None
),
)
_validate_unique_ownership(resolved)
return resolved
@@ -312,7 +420,10 @@ def resolve_offload_plan(pipeline: nn.Module, config: OffloadConfig) -> Resolved
def _validate_unique_ownership(resolved: ResolvedOffloadPlan) -> None:
"""Reject topologies where two components would hook the same blocks."""
owner_by_block: dict[int, str] = {}
for component in resolved.components:
pending = list(reversed(resolved.components))
while pending:
component = pending.pop()
pending.extend(reversed(component.children))
for block in (block for stack in component.stacks for block in stack.blocks):
owner = owner_by_block.setdefault(id(block), component.path)
if owner != component.path:
@@ -13,7 +13,6 @@ from vllm_omni.diffusion.hooks import HookRegistry, ModelHook
from vllm_omni.platforms import current_omni_platform
from .base import OffloadBackend, OffloadConfig, SupportsModelCpuOffload
from .config import DIT_COMPONENT
from .module_residency import PinnedModuleStager
from .plan_resolver import resolve_offload_plan
@@ -385,6 +384,7 @@ class ModelLevelOffloadBackend(OffloadBackend):
encoders = [component.module for component in resolved.encoders]
vaes = [component.module for component in resolved.vaes]
residents = [component.module for component in resolved.residents]
selected_dits = [component.module for component in resolved.dits if component.selected]
selected_encoders = [component.module for component in resolved.encoders if component.selected]
all_modules = [*dits, *encoders, *vaes, *residents]
@@ -412,7 +412,7 @@ class ModelLevelOffloadBackend(OffloadBackend):
device=self.device,
pin_memory=self.config.pin_cpu_memory,
use_hsdp=self.config.use_hsdp,
offload_dit_modules=(dits if self.config.offloads(DIT_COMPONENT) else ()),
offload_dit_modules=selected_dits,
offload_encoder_modules=selected_encoders,
# Fixed DiT staging keeps decode-graph weight pointers valid;
# other platforms keep plain move semantics.