[Feature] Distributed layerwise offload with DP multi-concurrency + mmap weight… (#5397)
Signed-off-by: evanchueng <evanchueng@outlook.com> Signed-off-by: david6666666 <530634352@qq.com> Co-authored-by: david6666666 <530634352@qq.com>
This commit is contained in:
1 parent
b3f4fbf9e2
commit
744c65b730
23 files changed
+3586
-78
No files matched your search
@@ -8,24 +8,54 @@ from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
from .base import OffloadBackend, OffloadConfig, OffloadStrategy
|
||||
from .block_discovery import get_blocks_attr_names, get_blocks_from_dit, set_blocks_attr_names
|
||||
from .distributed_layerwise_backend import (
|
||||
DistributedLayerwiseOffloadBackend,
|
||||
DistributedLayerwiseOffloadHook,
|
||||
apply_distributed_block_hook,
|
||||
remove_distributed_block_hook,
|
||||
)
|
||||
from .layerwise_backend import LayerWiseOffloadBackend
|
||||
from .offload_plan import OffloadPlan, get_offload_plan, supports_mmap_loading
|
||||
from .sequential_backend import (
|
||||
ModelLevelOffloadBackend,
|
||||
apply_sequential_offload,
|
||||
remove_sequential_offload,
|
||||
)
|
||||
from .tensor_utils import (
|
||||
dtype_size,
|
||||
is_dtensor,
|
||||
is_materialized_tensor,
|
||||
make_offload_placeholder,
|
||||
set_tensor_storage,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
__all__ = [
|
||||
"OffloadBackend",
|
||||
"OffloadConfig",
|
||||
"OffloadPlan",
|
||||
"OffloadStrategy",
|
||||
"LayerWiseOffloadBackend",
|
||||
"DistributedLayerwiseOffloadBackend",
|
||||
"DistributedLayerwiseOffloadHook",
|
||||
"ModelLevelOffloadBackend",
|
||||
"apply_sequential_offload",
|
||||
"remove_sequential_offload",
|
||||
"apply_distributed_block_hook",
|
||||
"remove_distributed_block_hook",
|
||||
"get_offload_backend",
|
||||
"get_offload_plan",
|
||||
"supports_mmap_loading",
|
||||
"get_blocks_attr_names",
|
||||
"get_blocks_from_dit",
|
||||
"set_blocks_attr_names",
|
||||
"dtype_size",
|
||||
"is_dtensor",
|
||||
"is_materialized_tensor",
|
||||
"make_offload_placeholder",
|
||||
"set_tensor_storage",
|
||||
]
|
||||
|
||||
|
||||
@@ -75,6 +105,8 @@ def get_offload_backend(
|
||||
return ModelLevelOffloadBackend(config, device)
|
||||
elif config.strategy == OffloadStrategy.LAYER_WISE:
|
||||
return LayerWiseOffloadBackend(config, device)
|
||||
elif config.strategy == OffloadStrategy.DISTRIBUTED_LAYER_WISE:
|
||||
return DistributedLayerwiseOffloadBackend(config, device)
|
||||
else:
|
||||
logger.error("Unknown offload strategy: %s", config.strategy)
|
||||
return None
|
||||
@@ -18,6 +18,7 @@ class OffloadStrategy(Enum):
|
||||
NONE = "none"
|
||||
MODEL_LEVEL = "model_level" # Sequential offloading between DiT and encoders
|
||||
LAYER_WISE = "layer_wise" # Block-level
|
||||
DISTRIBUTED_LAYER_WISE = "distributed_layer_wise" # Block-level with DP sharding + H2D/AllGather overlap
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -25,13 +26,21 @@ class OffloadConfig:
|
||||
strategy: OffloadStrategy
|
||||
pin_cpu_memory: bool = True
|
||||
use_hsdp: bool = False
|
||||
dp_size: int = 1 # derived from parallel_config, not user-configurable
|
||||
dlo_use_allgather: bool = True # if True: shard + AllGather; if False: full weights H2D only
|
||||
model_path: str | None = None # checkpoint path for mmap weight loading
|
||||
|
||||
@classmethod
|
||||
def from_od_config(cls, od_config: OmniDiffusionConfig) -> "OffloadConfig":
|
||||
"""Extract and validate offload settings from OmniDiffusionConfig.
|
||||
|
||||
For now, enforces mutual exclusion between model-level and layer-wise offloading.
|
||||
Layer-wise takes priority if both are enabled.
|
||||
Enforces mutual exclusion among the three offload strategies.
|
||||
Distributed layer-wise takes the highest priority, then layer-wise,
|
||||
then model-level.
|
||||
|
||||
The ``dp_size`` is automatically derived from ``parallel_config`` —
|
||||
it is NOT a user-configurable parameter. The distributed layerwise
|
||||
offload works with whatever DP/SP parallelism is already set up.
|
||||
|
||||
Args:
|
||||
od_config: OmniDiffusionConfig with offload settings
|
||||
@@ -41,13 +50,39 @@ class OffloadConfig:
|
||||
"""
|
||||
enable_cpu_offload = getattr(od_config, "enable_cpu_offload", False)
|
||||
enable_layerwise_offload = getattr(od_config, "enable_layerwise_offload", False)
|
||||
enable_distributed_layerwise_offload = getattr(od_config, "enable_distributed_layerwise_offload", False)
|
||||
pin_cpu_memory = getattr(od_config, "pin_cpu_memory", True)
|
||||
|
||||
parallel_config = getattr(od_config, "parallel_config", None)
|
||||
use_hsdp = getattr(parallel_config, "use_hsdp", False) if parallel_config else False
|
||||
|
||||
# Determine strategy (mutual exclusion, layer-wise takes priority)
|
||||
if enable_layerwise_offload:
|
||||
# Derive dp_size from parallel_config — not user-configurable.
|
||||
# The offload adapts to whatever DP/SP is already configured.
|
||||
dp_size = 1
|
||||
if parallel_config is not None:
|
||||
dp_size = getattr(parallel_config, "data_parallel_size", 1)
|
||||
# HSDP's fully_shard_degree also contributes to effective DP
|
||||
hsdp_shard_size = getattr(parallel_config, "hsdp_shard_size", -1) if use_hsdp else -1
|
||||
hsdp_replicate_size = getattr(parallel_config, "hsdp_replicate_size", 1) if use_hsdp else 1
|
||||
if use_hsdp and hsdp_shard_size > 0:
|
||||
dp_size = hsdp_shard_size * hsdp_replicate_size
|
||||
|
||||
# When there is no DP but SP > 1, shard weights across SP ranks.
|
||||
# AllGather reconstructs full weights per layer; each rank then
|
||||
# computes on its SP portion of the sequence. This gives N×
|
||||
# compute parallelism with 1/N H2D transfer, reusing the exact
|
||||
# same AllGather code path — only the process group changes.
|
||||
if dp_size <= 1:
|
||||
sp_size = getattr(parallel_config, "sequence_parallel_size", 1)
|
||||
if sp_size and sp_size > 1:
|
||||
dp_size = sp_size
|
||||
|
||||
# Determine strategy (mutual exclusion, distributed layer-wise takes priority)
|
||||
if enable_distributed_layerwise_offload:
|
||||
strategy = OffloadStrategy.DISTRIBUTED_LAYER_WISE
|
||||
if enable_layerwise_offload or enable_cpu_offload:
|
||||
logger.info("Distributed layer-wise offloading takes priority, disabling other offloading strategies.")
|
||||
elif enable_layerwise_offload:
|
||||
strategy = OffloadStrategy.LAYER_WISE
|
||||
if enable_cpu_offload:
|
||||
logger.info(
|
||||
@@ -59,10 +94,37 @@ class OffloadConfig:
|
||||
else:
|
||||
strategy = OffloadStrategy.NONE
|
||||
|
||||
# When dlo_use_allgather=False, each rank loads full weights (no sharding,
|
||||
# no AllGather). This avoids AllGather synchronization requirements
|
||||
# (concurrent requests, dummy run skip) at the cost of N× CPU memory.
|
||||
dlo_use_allgather = getattr(od_config, "dlo_use_allgather", True)
|
||||
|
||||
# If dlo_use_allgather=False, force dp_size=1 (each rank independent)
|
||||
if enable_distributed_layerwise_offload and not dlo_use_allgather:
|
||||
dp_size = 1
|
||||
logger.info(
|
||||
"Distributed layerwise offload: dlo_use_allgather=False, "
|
||||
"each rank loads full weights (no shard, no AllGather)"
|
||||
)
|
||||
|
||||
# HSDP already shards parameters into DTensors. Running distributed
|
||||
# layerwise offload on top would shard each to_local() again, producing
|
||||
# incorrect reconstruction after AllGather. Reject this combination.
|
||||
if enable_distributed_layerwise_offload and use_hsdp and dlo_use_allgather:
|
||||
raise ValueError(
|
||||
"Distributed layerwise offload with AllGather is incompatible with "
|
||||
"HSDP: HSDP parameters are already sharded DTensors, and the offloader "
|
||||
"would double-shard them. Use --dlo-no-use-allgather (full weights per "
|
||||
"rank) or disable HSDP."
|
||||
)
|
||||
|
||||
return cls(
|
||||
strategy=strategy,
|
||||
pin_cpu_memory=pin_cpu_memory,
|
||||
use_hsdp=use_hsdp,
|
||||
dp_size=dp_size,
|
||||
dlo_use_allgather=dlo_use_allgather,
|
||||
model_path=getattr(od_config, "model", None),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Block discovery for layerwise offload.
|
||||
|
||||
Shared between LayerWiseOffloadBackend and DistributedLayerwiseOffloadBackend.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from torch import nn
|
||||
from vllm.logger import init_logger
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
def get_blocks_attr_names(model: nn.Module) -> list[str]:
|
||||
"""Get block attribute names from model class."""
|
||||
attrs: list[str] = getattr(model.__class__, "_layerwise_offload_blocks_attrs", [])
|
||||
|
||||
if not attrs:
|
||||
old_attr = getattr(model.__class__, "_layerwise_offload_blocks_attr", None)
|
||||
if old_attr is not None:
|
||||
logger.warning(
|
||||
"'_layerwise_offload_blocks_attr' is deprecated, "
|
||||
"please use '_layerwise_offload_blocks_attrs' instead. "
|
||||
"Example: _layerwise_offload_blocks_attrs = ['blocks']"
|
||||
)
|
||||
attrs = [old_attr] if isinstance(old_attr, str) else list(old_attr)
|
||||
|
||||
return attrs
|
||||
|
||||
|
||||
def set_blocks_attr_names(model: nn.Module, names: list[str]) -> None:
|
||||
if not hasattr(model.__class__, "_layerwise_offload_blocks_attrs"):
|
||||
setattr(model.__class__, "_layerwise_offload_blocks_attrs", names)
|
||||
|
||||
|
||||
def get_blocks_from_dit(model: nn.Module) -> tuple[list[str], list[nn.Module]]:
|
||||
"""Retrieve blocks and attribute names from provided DiT model."""
|
||||
blocks_attr_names = get_blocks_attr_names(model)
|
||||
if not blocks_attr_names:
|
||||
logger.warning(
|
||||
f"No _layerwise_offload_blocks_attrs defined for {model.__class__.__name__}, "
|
||||
"skipping distributed layerwise offloading"
|
||||
)
|
||||
return [], []
|
||||
|
||||
blocks: list[nn.Module] = []
|
||||
for name in blocks_attr_names:
|
||||
attr = getattr(model, name, None)
|
||||
if attr is None:
|
||||
raise AttributeError(
|
||||
f"Attribute '{name}' declared in _layerwise_offload_blocks_attrs "
|
||||
f"does not exist on model {model.__class__.__name__}"
|
||||
)
|
||||
try:
|
||||
attr_iter = iter(attr)
|
||||
except TypeError:
|
||||
if isinstance(attr, nn.Module):
|
||||
logger.warning(
|
||||
"Attribute '%s' on %s is not iterable; treating it as one block.",
|
||||
name,
|
||||
model.__class__.__name__,
|
||||
)
|
||||
blocks.append(attr)
|
||||
continue
|
||||
|
||||
logger.warning(
|
||||
"Attribute '%s' on %s is not iterable (got %s); skipping it.",
|
||||
name,
|
||||
model.__class__.__name__,
|
||||
type(attr).__name__,
|
||||
)
|
||||
else:
|
||||
blocks.extend(attr_iter)
|
||||
|
||||
if not blocks:
|
||||
logger.warning(
|
||||
"No blocks found in %s for %s, skipping distributed layerwise offloading",
|
||||
blocks_attr_names,
|
||||
model.__class__.__name__,
|
||||
)
|
||||
return [], []
|
||||
|
||||
return blocks_attr_names, blocks
|
||||
File diff suppressed because it is too large.
Load diff
@@ -80,11 +80,13 @@ class ModuleDiscovery:
|
||||
"text_encoder_2",
|
||||
"text_encoder_3",
|
||||
"image_encoder",
|
||||
"vision_encoder",
|
||||
"mllm",
|
||||
]
|
||||
_FALLBACK_VAE_ATTRS = [
|
||||
"vae",
|
||||
"audio_vae",
|
||||
"sound_tokenizer",
|
||||
]
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Declarative OffloadPlan for distributed layerwise offload.
|
||||
|
||||
Models declare this as a class attribute ``_offload_plan`` on the
|
||||
pipeline class. When present, the offloader uses it instead of
|
||||
heuristic block discovery.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from torch import nn
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OffloadPlan:
|
||||
"""Optional declarative metadata for distributed layerwise offload.
|
||||
|
||||
Models declare this as a class attribute ``_offload_plan`` on the
|
||||
pipeline class. When present, the offloader uses it instead of
|
||||
heuristic block discovery, making it easier to support new models
|
||||
without offload-specific logic in constructor or forward code.
|
||||
|
||||
If not declared, the offloader falls back to:
|
||||
1. ``_layerwise_offload_blocks_attrs`` on each DiT module class.
|
||||
2. Heuristic search for ``layers`` / ``blocks`` / ``h`` attributes.
|
||||
|
||||
Attributes:
|
||||
block_attrs: Maps DiT path → tuple of block-list attribute names.
|
||||
e.g. ``{"transformer": ("gen_layers",),
|
||||
"transformer.language_model": ("layers",)}``
|
||||
offload_submodules: Maps child name → block-list attribute name,
|
||||
for large non-DiT submodules within a DiT that should be
|
||||
independently offloaded with their own hooks.
|
||||
e.g. ``{"context_encoder": "layers"}``
|
||||
"""
|
||||
|
||||
block_attrs: dict[str, tuple[str, ...]] = field(default_factory=dict)
|
||||
offload_submodules: dict[str, str] = field(default_factory=dict)
|
||||
|
||||
|
||||
def get_offload_plan(pipeline: nn.Module) -> OffloadPlan | None:
|
||||
"""Retrieve the OffloadPlan declared by the pipeline, if any."""
|
||||
return getattr(pipeline, "_offload_plan", None)
|
||||
|
||||
|
||||
def supports_mmap_loading(pipeline: nn.Module) -> bool:
|
||||
"""Whether the pipeline supports mmap weight loading.
|
||||
|
||||
A pipeline supports mmap if any module defines ``_remap_ckpt_key``,
|
||||
which maps checkpoint keys to model parameter names. Models without
|
||||
this method must use the regular ``load_weights()`` path.
|
||||
|
||||
This check is shared between ``diffusers_loader.py`` (to decide whether
|
||||
to skip ``load_weights``) and ``DistributedLayerwiseOffloadBackend.enable()``
|
||||
(to decide whether to call ``_load_weights_via_mmap``), ensuring both
|
||||
paths use the same gate condition.
|
||||
"""
|
||||
return any(callable(getattr(type(m), "_remap_ckpt_key", None)) for m in pipeline.modules())
|
||||
@@ -0,0 +1,47 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""Shared tensor utilities for distributed layerwise offload.
|
||||
|
||||
These helpers are used by both DistributedLayerwiseOffloadHook and
|
||||
DistributedLayerwiseOffloadBackend, and can be reused by other
|
||||
offload backends.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import torch
|
||||
from torch.distributed.tensor import DTensor
|
||||
|
||||
|
||||
def dtype_size(dtype: torch.dtype) -> int:
|
||||
"""Return element size in bytes for a torch.dtype."""
|
||||
return torch.empty(1, dtype=dtype).element_size()
|
||||
|
||||
|
||||
def is_dtensor(t: torch.Tensor) -> bool:
|
||||
"""Check if tensor is a DTensor."""
|
||||
return isinstance(t, DTensor)
|
||||
|
||||
|
||||
def set_tensor_storage(target: torch.Tensor, value: torch.Tensor) -> None:
|
||||
"""Replace target's underlying storage with value (zero-copy)."""
|
||||
if is_dtensor(target):
|
||||
target._local_tensor = value
|
||||
else:
|
||||
target.data = value
|
||||
|
||||
|
||||
def make_offload_placeholder(tensor: torch.Tensor) -> torch.Tensor:
|
||||
"""Create a zero-element placeholder to free GPU memory."""
|
||||
if is_dtensor(tensor):
|
||||
local_shape = tuple(tensor.to_local().shape)
|
||||
return torch.empty(local_shape, device="meta", dtype=tensor.dtype)
|
||||
return torch.empty((0,), device=tensor.device, dtype=tensor.dtype)
|
||||
|
||||
|
||||
def is_materialized_tensor(t: torch.Tensor) -> bool:
|
||||
"""Check if tensor holds real data (not meta or empty placeholder)."""
|
||||
if is_dtensor(t):
|
||||
local_t = t.to_local()
|
||||
return not local_t.is_meta
|
||||
return not t.is_meta and t.data.numel() > 0
|
||||
Reference in new issue
Block a user