[Diffusion] Register HWR mmap for direct DLO H2D (#6591)

Signed-off-by: Hongsheng Liu <liuhongsheng4@huawei.com>
Signed-off-by: hsliuustc0106 <hsliuustc0106@users.noreply.github.com>
Co-authored-by: hsliuustc0106 <hsliuustc0106@users.noreply.github.com>
This commit is contained in:
Hongsheng Liuandhsliuustc0106 authored and GitHub committed 2026-08-25 23:30:11 +08:00
1 parent 5a8b81ebeb
commit c608910d20
28 files changed
+1869 -153

No files matched your search

+25
View File
@@ -113,6 +113,22 @@ def validate_host_weight_runtime_options(*, mode: object, root: object) -> None:
raise ValueError("enabled Host Weight Runtime requires host_weight_runtime_root")
def validate_dlo_host_registration_options(
*,
limit_gib: object,
enable_dlo: bool,
use_allgather: bool,
hwr_mode: object,
) -> float:
"""Validate the optional transport budget without probing CUDA or HWR."""
value = float(limit_gib)
if not math.isfinite(value) or value < 0:
raise ValueError("dlo_host_registration_limit_gib must be finite and >= 0")
if value and (not enable_dlo or use_allgather or hwr_mode == "disabled"):
raise ValueError("dlo_host_registration_limit_gib requires enabled no-AllGather DLO and Host Weight Runtime")
return value
def parse_kv_cache_skip_selector(
selector: str | list[int] | tuple[int, ...] | set[int] | None,
) -> set[int] | None:
@@ -784,6 +800,9 @@ class OmniDiffusionConfig:
# existing loader/storage path.
host_weight_runtime_mode: str = "disabled"
host_weight_runtime_root: str | None = None
# Optional per-worker ceiling for registering final-layout HWR mappings.
# Zero adds no ceiling; pin_cpu_memory controls whether registration is tried.
dlo_host_registration_limit_gib: float = 0.0
pin_cpu_memory: bool = True # Use pinned memory for faster transfers when offloading
@@ -1164,6 +1183,12 @@ class OmniDiffusionConfig:
mode=self.host_weight_runtime_mode,
root=self.host_weight_runtime_root,
)
self.dlo_host_registration_limit_gib = validate_dlo_host_registration_options(
limit_gib=self.dlo_host_registration_limit_gib,
enable_dlo=self.enable_distributed_layerwise_offload,
use_allgather=self.dlo_use_allgather,
hwr_mode=self.host_weight_runtime_mode,
)
if self.diffusion_load_format != "diffusers" and (self.diffusers_load_kwargs or self.diffusers_call_kwargs):
raise ValueError(
@@ -27,7 +27,10 @@ logger = init_logger(__name__)
if TYPE_CHECKING:
from vllm_omni.diffusion.model_loader.host_weights.identity_adapter import FinalLayoutIdentityContext
from vllm_omni.diffusion.model_loader.host_weights.source_identity import PreparedWeightSource
from vllm_omni.diffusion.model_loader.host_weights.source_identity import (
NodeSourceDigestCache,
PreparedWeightSource,
)
class _HWRCommitError(RuntimeError):
@@ -215,6 +218,7 @@ class HWRLoaderMixin:
*,
load_format: str,
sources: Sequence[object],
source_digest_cache: NodeSourceDigestCache | None = None,
) -> FinalLayoutIdentityContext:
from vllm.distributed.parallel_state import get_tensor_model_parallel_rank
@@ -293,6 +297,7 @@ class HWRLoaderMixin:
prepared_sources=prepared_sources,
request=request,
policy=FINAL_LAYOUT_BF16_POLICY,
source_digest_cache=source_digest_cache,
)
def _resolve_hwr(
@@ -306,7 +311,10 @@ class HWRLoaderMixin:
sources: Sequence[object],
) -> dict[str, object] | None:
"""Resolve an eligible no-AllGather final-layout HWR transaction."""
from vllm_omni.diffusion.model_loader.host_weights import FinalLayoutTensorRestorer
from vllm_omni.diffusion.model_loader.host_weights import (
FinalLayoutTensorRestorer,
NodeSourceDigestCache,
)
from vllm_omni.host_weight_runtime import (
HostWeightLeaseCarrier,
HostWeightRuntime,
@@ -347,7 +355,6 @@ class HWRLoaderMixin:
raise ValueError(f"required Host Weight Runtime path is ineligible: {message}")
logger.info("Host Weight Runtime is ineligible; using the canonical DLO path: %s", message)
return None
context = self._build_hwr_context(model, modules, load_format=load_format, sources=sources)
root_value = getattr(self.od_config, "host_weight_runtime_root", None)
if not isinstance(root_value, str) or not root_value.strip():
raise ValueError("enabled Host Weight Runtime requires host_weight_runtime_root")
@@ -362,6 +369,17 @@ class HWRLoaderMixin:
),
)
)
source_digest_cache = NodeSourceDigestCache(
root,
timeout_seconds=runtime.config.wait.coordination_timeout_seconds,
)
context = self._build_hwr_context(
model,
modules,
load_format=load_format,
sources=sources,
source_digest_cache=source_digest_cache,
)
resolution = runtime.resolve(context.identity)
state: dict[str, object] = {
"mode": mode,
@@ -19,7 +19,7 @@ from .producers import (
FinalLayoutBF16Producer,
)
from .restorer import FinalLayoutTensorRestorer
from .source_identity import PreparedWeightSource, WeightSourceKind
from .source_identity import NodeSourceDigestCache, PreparedWeightSource, WeightSourceKind
__all__ = [
"FINAL_LAYOUT_BF16_POLICY",
@@ -32,6 +32,7 @@ __all__ = [
"FinalLayoutRequest",
"FinalLayoutTensorRestorer",
"ImplementationIdentity",
"NodeSourceDigestCache",
"PreparedWeightSource",
"WeightSourceKind",
"build_final_layout_identity",
@@ -27,6 +27,7 @@ from .contracts import (
)
from .source_identity import (
FinalLayoutSourceContext,
NodeSourceDigestCache,
PreparedWeightSource,
resolve_final_layout_source_identity,
)
@@ -78,6 +79,7 @@ def build_final_layout_identity(
prepared_sources: Sequence[PreparedWeightSource],
request: FinalLayoutRequest,
policy: FinalLayoutTensorPolicy,
source_digest_cache: NodeSourceDigestCache | None = None,
) -> FinalLayoutIdentityContext:
"""Build exact source, representation, layout, and implementation identity."""
if not isinstance(request, FinalLayoutRequest):
@@ -99,6 +101,7 @@ def build_final_layout_identity(
prepared_sources,
model_id=request.model_id,
target_names=target_names,
digest_cache=source_digest_cache,
)
dit_names = tuple(name for name, _ in dit_modules)
model_contracts = tuple(binding.contract for binding in bindings)
@@ -286,7 +286,7 @@ class FinalLayoutBF16Producer:
for record in shard
)
file_name = f"model-{index:05d}-of-{shard_count:05d}.safetensors"
with writer.open_tensor_file(file_name, specs) as output:
with writer.open_tensor_file(file_name, specs, ordered=True) as output:
for record in shard:
output.write_tensor(record.name, record.tensor.detach())
@@ -5,9 +5,13 @@
from __future__ import annotations
import hashlib
import json
import os
import stat
import time
import uuid
from collections.abc import Sequence
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
@@ -15,6 +19,7 @@ from pathlib import Path
import regex as re
from vllm_omni.host_weight_runtime import CanonicalJson, WeightSourceIdentity
from vllm_omni.host_weight_runtime.filesystem.locks import FileLock, FileLockTimeoutError
from vllm_omni.host_weight_runtime.identity import canonical_json
from .contracts import (
@@ -101,6 +106,140 @@ class _FileSnapshot:
)
@dataclass(frozen=True)
class _FileState:
size: int
device: int
inode: int
mtime_ns: int
ctime_ns: int
symlink_target: str | None
def to_dict(self) -> dict[str, object]:
return {
"size": self.size,
"device": self.device,
"inode": self.inode,
"mtime_ns": self.mtime_ns,
"ctime_ns": self.ctime_ns,
"symlink_target": self.symlink_target,
}
def _observe(path: Path) -> _FileState:
try:
current = path.stat()
except OSError as exc:
raise ValueError(f"cannot stat canonical weight file {path}") from exc
if not stat.S_ISREG(current.st_mode):
raise ValueError(f"canonical weight source is not a regular file: {path}")
return _FileState(
size=current.st_size,
device=current.st_dev,
inode=current.st_ino,
mtime_ns=current.st_mtime_ns,
ctime_ns=current.st_ctime_ns,
symlink_target=os.readlink(path) if path.is_symlink() else None,
)
def _sha256_file(path: Path, expected: _FileState) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
before = os.fstat(handle.fileno())
while chunk := handle.read(_HASH_CHUNK_BYTES):
digest.update(chunk)
after = os.fstat(handle.fileno())
observed = (before.st_size, before.st_dev, before.st_ino, before.st_mtime_ns, before.st_ctime_ns)
completed = (after.st_size, after.st_dev, after.st_ino, after.st_mtime_ns, after.st_ctime_ns)
expected_stat = (expected.size, expected.device, expected.inode, expected.mtime_ns, expected.ctime_ns)
if observed != expected_stat or completed != expected_stat or _observe(path) != expected:
raise FinalLayoutContractError(
FinalLayoutContractCode.SOURCE_CHANGED,
f"canonical weight file changed while hashing: {path}",
)
return digest.hexdigest()
class NodeSourceDigestCache:
"""Share content-backed local-source fingerprints across node workers."""
def __init__(self, root: Path, *, timeout_seconds: float) -> None:
self.entries = root / "source-digests-v1" / "entries"
self.locks = root / "source-digests-v1" / "locks"
self.timeout_seconds = timeout_seconds
self._available = True
try:
self.entries.mkdir(parents=True, exist_ok=True, mode=0o700)
self.locks.mkdir(parents=True, exist_ok=True, mode=0o700)
except OSError:
self._available = False
@staticmethod
def _cached_content_id(entry: Path, path: Path, state: _FileState) -> str | None:
try:
cached = json.loads(entry.read_bytes())
if not isinstance(cached, dict):
return None
cached_state = cached["state"]
content_id = cached["content_id"]
record_sha256 = cached["record_sha256"]
except (FileNotFoundError, OSError, json.JSONDecodeError, KeyError, TypeError):
return None
record = {
"content_id": content_id,
"schema_version": cached.get("schema_version"),
"state": cached_state,
}
if (
record["schema_version"] != 1
or cached_state != state.to_dict()
or not isinstance(content_id, str)
or re.fullmatch(r"sha256:[0-9a-f]{64}", content_id) is None
or not isinstance(record_sha256, str)
or hashlib.sha256(canonical_json(record)).hexdigest() != record_sha256
or _observe(path) != state
):
return None
return content_id
def content_id(self, path: Path, state: _FileState) -> str:
if not self._available:
return f"sha256:{_sha256_file(path, state)}"
key = hashlib.sha256(os.fsencode(path.absolute())).hexdigest()
entry = self.entries / f"{key}.json"
content_id: str | None = None
try:
with FileLock(
self.locks / f"{key}.lock",
exclusive=True,
deadline=time.monotonic() + self.timeout_seconds,
):
if (cached := self._cached_content_id(entry, path, state)) is not None:
return cached
content_id = f"sha256:{_sha256_file(path, state)}"
record: dict[str, object] = {
"content_id": content_id,
"schema_version": 1,
"state": state.to_dict(),
}
record["record_sha256"] = hashlib.sha256(canonical_json(record)).hexdigest()
temporary = entry.with_name(f".{entry.name}.{os.getpid()}.{uuid.uuid4().hex}.tmp")
try:
temporary.write_bytes(canonical_json(record))
os.chmod(temporary, 0o600)
os.replace(temporary, entry)
finally:
temporary.unlink(missing_ok=True)
return content_id
except (FileLockTimeoutError, OSError):
# Digest sharing is an optimization. Coordination or cache I/O
# failures must not make a readable canonical source unavailable.
if content_id is not None and _observe(path) == state:
return content_id
return f"sha256:{_sha256_file(path, state)}"
@dataclass(frozen=True)
class _SourceSnapshot:
semantic: CanonicalJson
@@ -129,14 +268,6 @@ class FinalLayoutSourceContext:
)
def _sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
while chunk := handle.read(_HASH_CHUNK_BYTES):
digest.update(chunk)
return digest.hexdigest()
def _hf_blob_content_id(
path: Path,
*,
@@ -200,7 +331,10 @@ def _logical_model_id(value: str) -> str:
return value
def _snapshot_source(source: PreparedWeightSource) -> _SourceSnapshot:
def _snapshot_source(
source: PreparedWeightSource,
digest_cache: NodeSourceDigestCache | None,
) -> _SourceSnapshot:
root = source.resolved_root.expanduser().resolve()
if not root.is_dir():
raise ValueError(f"canonical source root is not a directory: {root}")
@@ -210,8 +344,7 @@ def _snapshot_source(source: PreparedWeightSource) -> _SourceSnapshot:
if _IMMUTABLE_REVISION_RE.fullmatch(requested) is not None:
immutable_revision = requested.lower()
files: list[_FileSnapshot] = []
for path in sorted(source.weight_files, key=lambda item: str(item)):
def snapshot_file(path: Path) -> _FileSnapshot:
candidate = path.expanduser()
if not candidate.is_absolute():
candidate = root / candidate
@@ -220,34 +353,34 @@ def _snapshot_source(source: PreparedWeightSource) -> _SourceSnapshot:
relative_name = candidate.relative_to(root).as_posix()
except ValueError as exc:
raise ValueError(f"weight file {candidate} is outside its canonical source root {root}") from exc
try:
current = candidate.stat()
except OSError as exc:
raise ValueError(f"cannot stat canonical weight file {candidate}") from exc
if not stat.S_ISREG(current.st_mode):
raise ValueError(f"canonical weight source is not a regular file: {candidate}")
symlink_target = os.readlink(candidate) if candidate.is_symlink() else None
current = _observe(candidate)
content_id = _hf_blob_content_id(
candidate,
source=source,
source_root=root,
)
if content_id is None:
content_id = f"sha256:{_sha256_file(candidate)}"
files.append(
_FileSnapshot(
path=candidate,
relative_name=relative_name,
size=current.st_size,
device=current.st_dev,
inode=current.st_ino,
mtime_ns=current.st_mtime_ns,
ctime_ns=current.st_ctime_ns,
symlink_target=symlink_target,
content_id=content_id,
content_id = (
digest_cache.content_id(candidate, current)
if digest_cache is not None
else f"sha256:{_sha256_file(candidate, current)}"
)
return _FileSnapshot(
path=candidate,
relative_name=relative_name,
size=current.size,
device=current.device,
inode=current.inode,
mtime_ns=current.mtime_ns,
ctime_ns=current.ctime_ns,
symlink_target=current.symlink_target,
content_id=content_id,
)
paths = sorted(source.weight_files, key=lambda item: str(item))
with ThreadPoolExecutor(max_workers=min(8, len(paths))) as executor:
files = list(executor.map(snapshot_file, paths))
file_semantics = [file.semantic_dict() for file in files]
file_fingerprint = hashlib.sha256(canonical_json(file_semantics)).hexdigest()
revision = immutable_revision or f"content-{file_fingerprint}"
@@ -306,11 +439,12 @@ def resolve_final_layout_source_identity(
*,
model_id: str,
target_names: frozenset[str],
digest_cache: NodeSourceDigestCache | None = None,
) -> FinalLayoutSourceContext:
"""Resolve exact source identity for files covering the owned tensors."""
bindings = _resolve_target_sources(prepared_sources, target_names)
selected_sources = frozenset(bindings.values())
snapshot_by_source = {source: _snapshot_source(source) for source in selected_sources}
snapshot_by_source = {source: _snapshot_source(source, digest_cache) for source in selected_sources}
snapshots = tuple(sorted(snapshot_by_source.values(), key=lambda snapshot: snapshot.semantic.encoded))
source_semantics = [snapshot.semantic.to_value() for snapshot in snapshots]
target_bindings = [
@@ -345,6 +479,7 @@ def resolve_final_layout_source_identity(
__all__ = [
"FinalLayoutSourceContext",
"NodeSourceDigestCache",
"PreparedWeightSource",
"WeightSourceKind",
"resolve_final_layout_source_identity",
+12 -2
View File
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
from abc import ABC, abstractmethod
from dataclasses import dataclass
@@ -10,7 +10,7 @@ import torch
from torch import nn
from vllm.logger import init_logger
from vllm_omni.diffusion.data import OmniDiffusionConfig
from vllm_omni.diffusion.data import OmniDiffusionConfig, validate_dlo_host_registration_options
logger = init_logger(__name__)
@@ -52,6 +52,9 @@ class OffloadConfig:
# blocks from the loader-selected host backing with H2D only.
dlo_use_allgather: bool = True
dlo_resident_layers: int = 0 # leading DiT layers kept on device
# Optional per-worker ceiling for registering an HWR mmap. Zero means no
# additional ceiling; pin_cpu_memory controls whether registration is tried.
dlo_host_registration_limit_gib: float = 0.0
@classmethod
def from_od_config(cls, od_config: OmniDiffusionConfig) -> "OffloadConfig":
@@ -122,6 +125,12 @@ class OffloadConfig:
# requirements (concurrent requests, dummy run skip).
dlo_use_allgather = getattr(od_config, "dlo_use_allgather", True)
dlo_resident_layers = int(getattr(od_config, "dlo_resident_layers", 0))
dlo_host_registration_limit_gib = validate_dlo_host_registration_options(
limit_gib=getattr(od_config, "dlo_host_registration_limit_gib", 0.0),
enable_dlo=enable_distributed_layerwise_offload,
use_allgather=dlo_use_allgather,
hwr_mode=getattr(od_config, "host_weight_runtime_mode", "disabled"),
)
if dlo_resident_layers < 0:
raise ValueError(f"dlo_resident_layers must be >= 0, got {dlo_resident_layers}")
if dlo_resident_layers and dlo_use_allgather:
@@ -157,6 +166,7 @@ class OffloadConfig:
dp_size=dp_size,
dlo_use_allgather=dlo_use_allgather,
dlo_resident_layers=dlo_resident_layers,
dlo_host_registration_limit_gib=dlo_host_registration_limit_gib,
)
@@ -0,0 +1,248 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""CUDA implementation of read-only host-mapping registration."""
from __future__ import annotations
import ctypes
import mmap
from collections import defaultdict
from collections.abc import Sequence
from dataclasses import dataclass
from typing import Protocol
import torch
from vllm_omni.host_weight_runtime import MappedHostRegion
from .host_registration import (
HostRegistrationBudgetError,
HostRegistrationCleanupError,
HostRegistrationError,
)
_CUDA_HOST_REGISTER_READ_ONLY = 0x08
_CUDA_DEVICE_ATTRIBUTE_HOST_REGISTER_READ_ONLY_SUPPORTED = 113
class _CudaRuntime(Protocol):
def cudaHostRegister(self, address: int, size: int, flags: int) -> int: ...
def cudaHostUnregister(self, address: int) -> int: ...
def cudaGetErrorString(self, error: int) -> str | bytes: ...
def cudaGetLastError(self) -> int: ...
@dataclass(frozen=True)
class _AddressRange:
start: int
end: int
@property
def size(self) -> int:
return self.end - self.start
def _coalesce_ranges(
ranges: Sequence[tuple[int, int]],
page_size: int = mmap.PAGESIZE,
) -> tuple[_AddressRange, ...]:
"""Page-align and merge overlapping ranges from one backing mapping."""
if page_size <= 0:
raise ValueError(f"page_size must be positive, got {page_size}")
aligned: list[_AddressRange] = []
for start, size in ranges:
if start <= 0 or size < 0:
raise ValueError(f"invalid host range start={start}, size={size}")
if size == 0:
continue
aligned_start = start - start % page_size
end = start + size
aligned_end = ((end + page_size - 1) // page_size) * page_size
aligned.append(_AddressRange(aligned_start, aligned_end))
merged: list[_AddressRange] = []
for region in sorted(aligned, key=lambda item: (item.start, item.end)):
if merged and region.start <= merged[-1].end:
previous = merged[-1]
merged[-1] = _AddressRange(previous.start, max(previous.end, region.end))
else:
merged.append(region)
return tuple(merged)
def _mapped_regions(regions: Sequence[MappedHostRegion]) -> tuple[_AddressRange, ...]:
"""Resolve page spans without merging unrelated artifact files."""
by_file: dict[str, list[tuple[int, int]]] = defaultdict(list)
for region in regions:
if not region.read_only:
raise HostRegistrationError(
f"CUDA direct H2D requires an immutable mapping, but {region.file_name!r} is writable"
)
by_file[region.file_name].append((region.address, region.length))
return tuple(span for ranges in by_file.values() for span in _coalesce_ranges(ranges))
def _error_message(runtime: _CudaRuntime, error: int) -> str:
try:
message = runtime.cudaGetErrorString(error)
except Exception:
return str(error)
if isinstance(message, bytes):
return message.decode(errors="replace")
return str(message)
def _consume_last_cuda_error(runtime: _CudaRuntime, expected_error: int) -> None:
"""Clear one handled CUDA Runtime error before returning to PyTorch."""
try:
get_last_error = getattr(runtime, "cudaGetLastError", None)
if get_last_error is None:
get_last_error = ctypes.CDLL(None).cudaGetLastError
get_last_error.argtypes = []
get_last_error.restype = ctypes.c_int
pending_error = int(get_last_error())
except (AttributeError, OSError, RuntimeError, TypeError, ValueError) as exc:
raise HostRegistrationError("cannot clear CUDA's pending error after host-registration failure") from exc
if pending_error not in (0, expected_error):
raise HostRegistrationError(
f"host registration returned CUDA error {expected_error}, but cudaGetLastError reported {pending_error}"
)
def _handled_error_message(runtime: _CudaRuntime, error: int) -> str:
error_code = int(error)
message = _error_message(runtime, error_code)
try:
_consume_last_cuda_error(runtime, error_code)
except HostRegistrationError as exc:
raise HostRegistrationError(f"{message}; {exc}") from exc
return message
def _supports_read_only_host_registration(runtime: _CudaRuntime) -> bool:
"""Query support required by immutable artifact mappings."""
try:
get_attribute = getattr(runtime, "cudaDeviceGetAttribute", None)
if get_attribute is None:
get_attribute = ctypes.CDLL(None).cudaDeviceGetAttribute
get_attribute.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.c_int, ctypes.c_int]
get_attribute.restype = ctypes.c_int
except (AttributeError, OSError) as exc:
raise HostRegistrationError("cannot query CUDA read-only host-registration support") from exc
supported = ctypes.c_int()
try:
error = get_attribute(
ctypes.byref(supported),
_CUDA_DEVICE_ATTRIBUTE_HOST_REGISTER_READ_ONLY_SUPPORTED,
torch.accelerator.current_device_index(),
)
except Exception as exc:
raise HostRegistrationError(f"cannot query CUDA read-only host-registration support: {exc}") from exc
if int(error) != 0:
raise HostRegistrationError(
f"cudaDeviceGetAttribute(read-only host registration) failed: {_handled_error_message(runtime, error)}"
)
return bool(supported.value)
class CudaHostRegistration:
"""Own CUDA registrations for immutable file-backed CPU regions."""
def __init__(self, runtime: _CudaRuntime, regions: tuple[_AddressRange, ...]) -> None:
self._runtime = runtime
self._regions = regions
@classmethod
def create(
cls,
regions: Sequence[MappedHostRegion],
*,
max_bytes: int | None,
) -> CudaHostRegistration:
mapped = _mapped_regions(regions)
total_bytes = sum(region.size for region in mapped)
if max_bytes is not None and total_bytes > max_bytes:
raise HostRegistrationBudgetError(
f"mapped host ranges need {total_bytes} bytes, exceeding the {max_bytes}-byte registration budget"
)
if not mapped:
raise HostRegistrationError("no non-empty host ranges were available for registration")
if not torch.cuda.is_available():
raise HostRegistrationError("CUDA is not available")
try:
runtime = torch.cuda.cudart()
except Exception as exc:
raise HostRegistrationError(f"cannot access the CUDA runtime: {exc}") from exc
if not _supports_read_only_host_registration(runtime):
raise HostRegistrationError(
"CUDA device does not support read-only host registration required by immutable HWR mappings"
)
registered: list[_AddressRange] = []
try:
for region in mapped:
error = runtime.cudaHostRegister(region.start, region.size, _CUDA_HOST_REGISTER_READ_ONLY)
if int(error) != 0:
raise HostRegistrationError(
"cudaHostRegister(read-only) failed for "
f"[{region.start:#x}, {region.end:#x}): {_handled_error_message(runtime, error)}"
)
registered.append(region)
except Exception as exc:
rollback_errors: list[str] = []
rollback_failed: list[_AddressRange] = []
for region in reversed(registered):
try:
error = runtime.cudaHostUnregister(region.start)
if int(error) != 0:
rollback_errors.append(
f"cudaHostUnregister({region.start:#x}) failed: {_handled_error_message(runtime, error)}"
)
rollback_failed.append(region)
except Exception as rollback_exc:
rollback_errors.append(f"cudaHostUnregister({region.start:#x}) raised: {rollback_exc}")
rollback_failed.append(region)
if rollback_errors:
active_registration = cls(runtime, tuple(reversed(rollback_failed)))
raise HostRegistrationCleanupError(
f"CUDA host registration failed ({exc}); rollback errors: {rollback_errors[:3]}",
active_registration=active_registration,
) from exc
if isinstance(exc, HostRegistrationError):
raise
raise HostRegistrationError(f"CUDA host registration raised: {exc}") from exc
return cls(runtime, mapped)
@property
def total_bytes(self) -> int:
return sum(region.size for region in self._regions)
@property
def region_count(self) -> int:
return len(self._regions)
def close(self) -> tuple[str, ...]:
"""Unregister every range and retain failures for a later retry."""
errors: list[str] = []
failed: list[_AddressRange] = []
for region in reversed(self._regions):
try:
error = self._runtime.cudaHostUnregister(region.start)
if int(error) != 0:
errors.append(
f"cudaHostUnregister({region.start:#x}) failed: {_handled_error_message(self._runtime, error)}"
)
failed.append(region)
except Exception as exc:
errors.append(f"cudaHostUnregister({region.start:#x}) raised: {exc}")
failed.append(region)
self._regions = tuple(reversed(failed))
return tuple(errors)
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Distributed Layerwise Offload backend with double-buffered H2D.
This module implements the RFC-1 "Distributed Layerwise Offload" mechanism that:
@@ -18,6 +18,8 @@ This module implements the RFC-1 "Distributed Layerwise Offload" mechanism that:
from __future__ import annotations
import threading
import time
from itertools import chain
from typing import Any
@@ -35,6 +37,12 @@ from vllm_omni.platforms import current_omni_platform
from .base import OffloadBackend, OffloadConfig
from .block_discovery import get_blocks_from_dit
from .host_registration import (
HostRegistration,
HostRegistrationCleanupError,
HostRegistrationError,
register_host_mappings,
)
from .module_collector import ModuleDiscovery
from .offload_plan import (
OffloadPlan,
@@ -51,6 +59,38 @@ from .tensor_utils import (
logger = init_logger(__name__)
# A backend normally owns both objects below. This process-lifetime safety
# owner prevents HostWeightLease.__del__ from unmapping storage when cleanup
# failure unwinds startup and the backend itself becomes unreachable. A clean
# retry removes the pair before closing the lease.
_ACTIVE_HWR_REGISTRATIONS: list[tuple[HostRegistration, HostWeightLease]] = []
_ACTIVE_HWR_REGISTRATIONS_LOCK = threading.Lock()
def _retain_active_hwr_registration(
registration: HostRegistration,
lease: HostWeightLease,
) -> None:
with _ACTIVE_HWR_REGISTRATIONS_LOCK:
if not any(
candidate is registration and candidate_lease is lease
for candidate, candidate_lease in _ACTIVE_HWR_REGISTRATIONS
):
_ACTIVE_HWR_REGISTRATIONS.append((registration, lease))
def _forget_active_hwr_registration(
registration: HostRegistration,
lease: HostWeightLease,
) -> None:
with _ACTIVE_HWR_REGISTRATIONS_LOCK:
_ACTIVE_HWR_REGISTRATIONS[:] = [
(candidate, candidate_lease)
for candidate, candidate_lease in _ACTIVE_HWR_REGISTRATIONS
if candidate is not registration or candidate_lease is not lease
]
# Threshold (in MB) for deciding whether a non-block DiT submodule should
# use layerwise offload (streaming hooks) or be moved to GPU as a resident
# module. Submodules larger than this are offloaded to save HBM; smaller
@@ -94,6 +134,7 @@ class DistributedLayerwiseOffloadHook(ModelHook):
self.rank = rank
self.pin_memory = pin_memory
self.rank_local_mmap = rank_local_mmap
self.registered_mmap = False
self.tensor_transforms = tensor_transforms or {}
self.copy_stream = copy_stream or current_omni_platform.Stream()
@@ -445,6 +486,26 @@ class DistributedLayerwiseOffloadHook(ModelHook):
# Prefetch: H2D + AllGather (overlapped on dedicated streams) #
# ------------------------------------------------------------------ #
@staticmethod
def _resolve_mmap_source(
source_info: dict[str, Any],
meta: dict[str, Any],
dtype: torch.dtype,
) -> torch.Tensor:
source = source_info["tensor"]
transform = source_info["transform"]
if callable(transform):
source = transform(source)
if source.dtype != dtype or source.shape != meta["shape"] or source.stride() != meta["stride"]:
raise ValueError(
"mmap weight transform changed tensor layout for "
f"{source_info['name']!r}: expected dtype={dtype}, "
f"shape={tuple(meta['shape'])}, stride={meta['stride']}; "
f"got dtype={source.dtype}, shape={tuple(source.shape)}, "
f"stride={source.stride()}"
)
return source
@staticmethod
def _pack_mmap_sources(
cpu_sources: dict[torch.dtype, list[dict[str, Any]]],
@@ -457,18 +518,7 @@ class DistributedLayerwiseOffloadHook(ModelHook):
destination = slot_buffers[dtype][:total_numel]
sources = cpu_sources[dtype]
for source_info, meta in zip(sources, metas, strict=True):
source = source_info["tensor"]
transform = source_info["transform"]
if callable(transform):
source = transform(source)
if source.dtype != dtype or source.shape != meta["shape"] or source.stride() != meta["stride"]:
raise ValueError(
"mmap weight transform changed tensor layout for "
f"{source_info['name']!r}: expected dtype={dtype}, "
f"shape={tuple(meta['shape'])}, stride={meta['stride']}; "
f"got dtype={source.dtype}, shape={tuple(source.shape)}, "
f"stride={source.stride()}"
)
source = DistributedLayerwiseOffloadHook._resolve_mmap_source(source_info, meta, dtype)
start = meta["offset"]
physical_storage = destination[start : start + meta["numel"]]
if source.is_contiguous():
@@ -500,6 +550,32 @@ class DistributedLayerwiseOffloadHook(ModelHook):
raise RuntimeError(f"cpu_staging_buffers[{slot}] was not allocated")
return self._pack_mmap_sources(self.cpu_sources, self.metadata, slot_buffers)
@staticmethod
def _copy_mmap_sources_to_device(
cpu_sources: dict[torch.dtype, list[dict[str, Any]]],
metadata: dict[torch.dtype, list[dict[str, Any]]],
gpu_buffers: dict[torch.dtype, torch.Tensor],
*,
non_blocking: bool,
) -> None:
"""Copy registered source views directly into flattened device buffers."""
for dtype, metas in metadata.items():
destination = gpu_buffers[dtype]
sources = cpu_sources[dtype]
for source_info, meta in zip(sources, metas, strict=True):
source = DistributedLayerwiseOffloadHook._resolve_mmap_source(source_info, meta, dtype)
start = meta["offset"]
physical_storage = destination[start : start + meta["numel"]]
async_copy = non_blocking and source.is_pinned()
if source.is_contiguous():
physical_storage.copy_(source.flatten(), non_blocking=async_copy)
else:
torch.as_strided(
physical_storage,
size=source.shape,
stride=source.stride(),
).copy_(source, non_blocking=async_copy)
@torch.compiler.disable
def prefetch_layer(self, slot: int, non_blocking: bool = True) -> None:
"""Prepare next block's weights into the shared device buffer for *slot*.
@@ -515,17 +591,27 @@ class DistributedLayerwiseOffloadHook(ModelHook):
assert gpu_weights is not None, f"gpu_buffers[{slot}] not allocated"
if self.dp_size <= 1 or self.dp_group is None:
cpu_weights = self._stage_mmap_sources(slot) if self.rank_local_mmap else self.cpu_shards
with current_omni_platform.stream(self.copy_stream):
for dtype, cpu_shard in cpu_weights.items():
gw = gpu_weights[dtype]
async_copy = non_blocking and cpu_shard.is_pinned()
gw[: cpu_shard.numel()].copy_(cpu_shard, non_blocking=async_copy)
evt.record(self.copy_stream)
if self.rank_local_mmap:
# The CPU slot may be overwritten only after this H2D copy has
# finished. The shared event protects reuse by another hook.
self.cpu_staging_events[slot] = evt
if self.rank_local_mmap and self.registered_mmap:
with current_omni_platform.stream(self.copy_stream):
self._copy_mmap_sources_to_device(
self.cpu_sources,
self.metadata,
gpu_weights,
non_blocking=non_blocking,
)
evt.record(self.copy_stream)
else:
cpu_weights = self._stage_mmap_sources(slot) if self.rank_local_mmap else self.cpu_shards
with current_omni_platform.stream(self.copy_stream):
for dtype, cpu_shard in cpu_weights.items():
gw = gpu_weights[dtype]
async_copy = non_blocking and cpu_shard.is_pinned()
gw[: cpu_shard.numel()].copy_(cpu_shard, non_blocking=async_copy)
evt.record(self.copy_stream)
if self.rank_local_mmap:
# The CPU slot may be overwritten only after this H2D copy has
# finished. The shared event protects reuse by another hook.
self.cpu_staging_events[slot] = evt
else:
gpu_shards: dict[torch.dtype, torch.Tensor] = {}
shard_bufs = self.gpu_shard_buffers[slot]
@@ -735,6 +821,7 @@ class PinnedResidentLayerGroup:
self.copy_stream = copy_stream
self.loaded = False
self.rank_local_mmap = rank_local_mmap
self.registered_mmap = False
self.pin_memory = pin_memory
self._states: list[dict[str, Any]] = []
self._gpu_buffers: list[dict[torch.dtype, torch.Tensor]] = []
@@ -805,6 +892,14 @@ class PinnedResidentLayerGroup:
ready = current_omni_platform.Event()
with current_omni_platform.stream(self.copy_stream):
for index, (state, block_buffers) in enumerate(zip(self._states, gpu_buffers)):
if self.rank_local_mmap and self.registered_mmap:
DistributedLayerwiseOffloadHook._copy_mmap_sources_to_device(
state["cpu_sources"],
state["metadata"],
block_buffers,
non_blocking=True,
)
continue
if self.rank_local_mmap:
slot = index % 2
previous_copy = self._cpu_staging_events[slot]
@@ -902,8 +997,10 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
self._resident_layer_group: PinnedResidentLayerGroup | None = None
self._using_mmap = False
self._using_rank_local_mmap = False
self._using_registered_mmap = False
self.host_weight_plan = host_weight_plan
self._host_weight_lease: HostWeightLease | None = None
self._host_registration: HostRegistration | None = None
self._mmap_transforms_by_tensor_id: dict[int, Any] = {}
def load_resident_layers(self) -> None:
@@ -916,6 +1013,136 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
if self._resident_layer_group is not None:
self._resident_layer_group.offload()
def _rank_local_source_tensors(
self,
hooks: list[DistributedLayerwiseOffloadHook],
) -> tuple[torch.Tensor, ...]:
"""Return the exact CPU sources that direct H2D would consume."""
tensors: list[torch.Tensor] = []
seen: set[int] = set()
def collect(cpu_sources: dict[torch.dtype, list[dict[str, Any]]]) -> None:
for sources in cpu_sources.values():
for source in sources:
tensor = source["tensor"]
if id(tensor) not in seen:
seen.add(id(tensor))
tensors.append(tensor)
for hook in hooks:
collect(hook.cpu_sources)
if self._resident_layer_group is not None:
for state in self._resident_layer_group._states:
collect(state["cpu_sources"])
return tuple(tensors)
def _try_register_hwr_mmap(self, source_tensors: tuple[torch.Tensor, ...]) -> bool:
"""Register the complete final-layout lease under pinned-memory policy."""
lease = self._host_weight_lease
if lease is None:
return False
if not self.config.pin_cpu_memory:
logger.info("HWR mmap registration disabled by pin_cpu_memory=False; using bounded host staging")
return False
if not lease.mapped_regions or not source_tensors:
logger.warning("HWR mmap registration found no mapped sources; using bounded host staging")
return False
limit_gib = self.config.dlo_host_registration_limit_gib
max_bytes = int(limit_gib * 1024**3) if limit_gib > 0 else None
started = time.perf_counter()
try:
registration = register_host_mappings(
lease.mapped_regions,
device=self.device,
max_bytes=max_bytes,
)
try:
unpinned = [tensor for tensor in source_tensors if tensor.numel() and not tensor.is_pinned()]
except Exception as exc:
errors = registration.close()
if errors:
self._host_registration = registration
_retain_active_hwr_registration(registration, lease)
raise HostRegistrationCleanupError(
"CUDA registration succeeded but pinned-source verification failed, "
f"and rollback failed: {errors[:3]}"
) from exc
raise HostRegistrationError(f"cannot verify registered HWR sources: {exc}") from exc
if unpinned:
errors = registration.close()
if errors:
self._host_registration = registration
_retain_active_hwr_registration(registration, lease)
raise HostRegistrationCleanupError(
"CUDA registration succeeded but PyTorch rejected mapped sources, "
f"and rollback failed: {errors[:3]}"
)
raise HostRegistrationError(
"CUDA registration succeeded but PyTorch did not recognize "
f"{len(unpinned)} mapped source(s) as pinned"
)
except HostRegistrationCleanupError as exc:
# Falling back could close a lease while the platform still owns
# one of its mappings. Fail startup and retain ownership for retry.
active_registration = exc.active_registration
if active_registration is not None:
self._host_registration = active_registration
_retain_active_hwr_registration(active_registration, lease)
logger.exception("HWR mmap registration rollback failed")
raise
except HostRegistrationError as exc:
logger.warning("HWR registered direct H2D unavailable (%s); using bounded host staging", exc)
return False
self._host_registration = registration
_retain_active_hwr_registration(registration, lease)
logger.info(
"Registered %.2f GiB of HWR mmap in %d range(s) for direct H2D in %.3f s",
registration.total_bytes / 1024**3,
registration.region_count,
time.perf_counter() - started,
)
return True
def _configure_hwr_transfer(self, hooks: list[DistributedLayerwiseOffloadHook]) -> None:
"""Select registered direct H2D or bounded staging once per backend."""
plan = self.host_weight_plan
if (
(not hooks and self._resident_layer_group is None)
or not self._using_rank_local_mmap
or plan is None
or plan.backing_kind != "host_weight_runtime"
):
return
source_tensors = self._rank_local_source_tensors(hooks)
self._using_registered_mmap = self._try_register_hwr_mmap(source_tensors)
for hook in hooks:
hook.registered_mmap = self._using_registered_mmap
if self._resident_layer_group is not None:
self._resident_layer_group.registered_mmap = self._using_registered_mmap
if self._using_registered_mmap:
self._resident_layer_group._cpu_staging_buffers.clear()
def _release_registered_mmap(self) -> None:
"""Release every platform registration before closing the HWR lease."""
registration = self._host_registration
if registration is None:
return
errors = registration.close()
if errors:
lease = self._host_weight_lease
if lease is not None and not lease.closed:
_retain_active_hwr_registration(registration, lease)
logger.error("HWR mmap unregistration failed; retaining lease mappings for retry: %s", errors[:3])
raise HostRegistrationCleanupError(f"failed to unregister {len(errors)} HWR mmap range(s)")
lease = self._host_weight_lease
if lease is not None:
_forget_active_hwr_registration(registration, lease)
self._host_registration = None
logger.info("Unregistered HWR mmap ranges")
def _load_weights_via_mmap(
self,
pipeline: nn.Module,
@@ -1465,11 +1692,11 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
raise RuntimeError("DLO received a closed Host Weight Runtime lease")
# The final-layout restorer has already rebound the model to
# immutable host tensors. Treat those tensors as mmap-like
# sources for the bounded two-slot rank-local staging path;
# do not reinitialize or rematerialize the restored model.
# sources; transport setup below selects registered direct
# H2D or the bounded two-slot staging fallback.
self._using_rank_local_mmap = True
logger.info(
"DLO consuming final-layout Host Weight Runtime lease %s with bounded rank-local staging",
"DLO consuming final-layout Host Weight Runtime lease %s",
self._host_weight_lease.provenance.resolution_id,
)
elif self.host_weight_plan.backing_kind == "checkpoint_mmap":
@@ -1483,7 +1710,7 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
if self._using_rank_local_mmap:
logger.info(
"DLO rank-local host storage enabled: source pages are "
"node-shared; each worker owns only two bounded host staging slots"
"node-shared; transfer setup will select registered direct H2D or bounded host staging"
)
else:
remaining_meta = [
@@ -1653,6 +1880,9 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
)
pipeline._dlo_residency_controller = self
all_hooks = [hook for group in self._all_hook_groups for hook in group]
self._configure_hwr_transfer(all_hooks)
if not self._all_hook_groups:
self.enabled = bool(self._resident_blocks)
if self._using_mmap and not self.enabled:
@@ -1662,17 +1892,13 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
# Unified allocation: 2 shared output buffers + 2 shared shard buffers
# sized to the max block across ALL module groups (gen_layers +
# language_model). Groups execute sequentially, so 2 buffers suffice.
all_hooks: list[DistributedLayerwiseOffloadHook] = []
for group in self._all_hook_groups:
all_hooks.extend(group)
unified_buffers = self._allocate_shared_buffers(all_hooks)
unified_shard_buffers = None
if self.dp_size > 1:
unified_shard_buffers = self._allocate_shared_shard_buffers(all_hooks)
unified_cpu_staging = None
cpu_staging_events = None
if self._using_rank_local_mmap:
if self._using_rank_local_mmap and not self._using_registered_mmap:
unified_cpu_staging = self._allocate_shared_cpu_staging_buffers(
all_hooks,
self._resident_layer_group,
@@ -1753,6 +1979,8 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
def _release_mmap_handles(self) -> None:
"""Release source handles and the transport-owned HWR lease."""
if self._host_registration is not None:
raise HostRegistrationCleanupError("cannot close HWR mappings while host registration is still active")
self._mmap_transforms_by_tensor_id.clear()
if hasattr(self, "_mmap_file_cache"):
self._mmap_file_cache.clear()
@@ -1781,6 +2009,7 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
def disable(self) -> None:
has_open_lease = self._host_weight_lease is not None and not self._host_weight_lease.closed
has_registration = self._host_registration is not None
has_carrier = (
self.host_weight_plan is not None
and self.host_weight_plan.lease_carrier is not None
@@ -1796,12 +2025,13 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
not self.enabled
and not hasattr(self, "_mmap_file_cache")
and not has_open_lease
and not has_registration
and not has_carrier
and not has_partial_hooks
):
return
if self._using_rank_local_mmap:
if self._using_rank_local_mmap or has_registration:
current_omni_platform.synchronize()
for blocks in self._blocks:
@@ -1818,9 +2048,11 @@ class DistributedLayerwiseOffloadBackend(OffloadBackend):
self._all_hook_groups.clear()
self._resident_blocks.clear()
self._resident_layer_group = None
self._release_registered_mmap()
self._release_mmap_handles()
self._using_mmap = False
self._using_rank_local_mmap = False
self._using_registered_mmap = False
self.enabled = False
logger.info("Distributed layer-wise offloading disabled")
@@ -0,0 +1,63 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""Platform-neutral lifecycle for registering existing host mappings."""
from __future__ import annotations
from collections.abc import Sequence
from typing import Protocol
import torch
from vllm_omni.host_weight_runtime import MappedHostRegion
class HostRegistrationError(RuntimeError):
"""Raised when existing host ranges cannot be registered safely."""
class HostRegistrationBudgetError(HostRegistrationError):
"""Raised before mutation when the complete mapping exceeds its budget."""
class HostRegistrationCleanupError(HostRegistrationError):
"""Raised when registered ranges cannot be released safely."""
def __init__(self, message: str, *, active_registration: HostRegistration | None = None) -> None:
super().__init__(message)
self.active_registration = active_registration
class HostRegistration(Protocol):
"""Transport-owned registration for one process-local host mapping."""
@property
def total_bytes(self) -> int: ...
@property
def region_count(self) -> int: ...
def close(self) -> tuple[str, ...]: ...
def register_host_mappings(
regions: Sequence[MappedHostRegion],
*,
device: torch.device,
max_bytes: int | None,
) -> HostRegistration:
"""Register immutable ranges with the active platform implementation."""
if device.type == "cuda":
from .cuda_host_registration import CudaHostRegistration
return CudaHostRegistration.create(regions, max_bytes=max_bytes)
raise HostRegistrationError(f"host-mapping registration is not supported on {device.type}")
__all__ = [
"HostRegistration",
"HostRegistrationBudgetError",
"HostRegistrationCleanupError",
"HostRegistrationError",
"register_host_mappings",
]
+13 -6
View File
@@ -1,5 +1,5 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# SPDX-FileCopyrightText: Copyright contributors to the vLLM-Omni project
"""
Diffusion Worker for vLLM-Omni.
@@ -897,11 +897,18 @@ class DiffusionWorker:
def shutdown(self) -> None:
"""Shutdown the worker and cleanup distributed environment."""
if self.model_runner is not None:
mgr = getattr(self.model_runner, "kv_transfer_manager", None)
if mgr is not None:
mgr.shutdown_prefetch()
destroy_distributed_env()
try:
if self.model_runner is not None:
mgr = getattr(self.model_runner, "kv_transfer_manager", None)
try:
offload_backend = getattr(self.model_runner, "offload_backend", None)
if offload_backend is not None:
offload_backend.disable()
finally:
if mgr is not None:
mgr.shutdown_prefetch()
finally:
destroy_distributed_env()
class CustomPipelineWorkerExtension: