Merge origin/main into dev/rebase-v0.16.0.
Resolve arg_utils merge conflict and align CI base image tag to v0.16.0 for the vLLM rebase track. Co-authored-by: Cursor <cursoragent@cursor.com> Signed-off-by: Taichang Zhou <tzhouam@connect.ust.hk>
This commit is contained in:
commit
e2ced80d59
64 files changed
+5186
-1228
No files matched your search
@@ -298,11 +298,8 @@ class OmniDiffusionConfig:
|
||||
# - Text encoders run on GPU while DiT is on CPU
|
||||
# - DiT runs on GPU while encoders are on CPU
|
||||
enable_cpu_offload: bool = False
|
||||
|
||||
# Layer-wise offloading (block-level offloading) parameters
|
||||
enable_layerwise_offload: bool = False
|
||||
# Number of transformer blocks ready for computation to keep on GPU
|
||||
layerwise_num_gpu_layers: int = 1
|
||||
|
||||
use_fsdp_inference: bool = False
|
||||
pin_cpu_memory: bool = True # Use pinned memory for faster transfers when offloading
|
||||
@@ -335,6 +332,15 @@ class OmniDiffusionConfig:
|
||||
# TODO: do not hard code
|
||||
master_port: int | None = None
|
||||
|
||||
# Worker extension class for custom functionality
|
||||
worker_extension_cls: str | None = None
|
||||
|
||||
# Custom pipeline arguments for custom pipelines
|
||||
custom_pipeline_args: dict[str, Any] | None = None
|
||||
|
||||
# Diffusion model loading format
|
||||
diffusion_load_format: str = "default" # "default", "custom_pipeline", "dummy"
|
||||
|
||||
# http server endpoint config, would be ignored in local mode
|
||||
host: str | None = None
|
||||
port: int | None = None
|
||||
|
||||
@@ -77,6 +77,10 @@ class MultiprocDiffusionExecutor(DiffusionExecutor):
|
||||
mp.set_start_method("spawn", force=True)
|
||||
processes = []
|
||||
|
||||
# Extract worker_extension_cls and custom_pipeline_args from od_config
|
||||
worker_extension_cls = od_config.worker_extension_cls
|
||||
custom_pipeline_args = getattr(od_config, "custom_pipeline_args", None)
|
||||
|
||||
# Launch all worker processes
|
||||
scheduler_pipe_readers = []
|
||||
scheduler_pipe_writers = []
|
||||
@@ -91,6 +95,8 @@ class MultiprocDiffusionExecutor(DiffusionExecutor):
|
||||
od_config,
|
||||
writer,
|
||||
broadcast_handle,
|
||||
worker_extension_cls,
|
||||
custom_pipeline_args,
|
||||
),
|
||||
name=f"DiffusionWorker-{i}",
|
||||
daemon=True,
|
||||
|
||||
@@ -22,6 +22,7 @@ from vllm.model_executor.model_loader.weight_utils import (
|
||||
maybe_download_from_modelscope,
|
||||
safetensors_weights_iterator,
|
||||
)
|
||||
from vllm.utils.import_utils import resolve_obj_by_qualname
|
||||
from vllm.utils.torch_utils import set_default_torch_dtype
|
||||
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
@@ -208,13 +209,22 @@ class DiffusersPipelineLoader:
|
||||
allow_patterns_overrides=None,
|
||||
)
|
||||
|
||||
def load_model(self, od_config: OmniDiffusionConfig, load_device: str) -> nn.Module:
|
||||
def load_model(
|
||||
self,
|
||||
od_config: OmniDiffusionConfig,
|
||||
load_device: str,
|
||||
load_format: str = "default",
|
||||
custom_pipeline_name: str | None = None,
|
||||
) -> nn.Module:
|
||||
"""Load a model with the given configurations."""
|
||||
target_device = torch.device(load_device)
|
||||
with set_default_torch_dtype(od_config.dtype):
|
||||
with target_device:
|
||||
model = initialize_model(od_config)
|
||||
|
||||
if load_format == "default":
|
||||
model = initialize_model(od_config)
|
||||
elif load_format == "custom_pipeline":
|
||||
model_cls = resolve_obj_by_qualname(custom_pipeline_name)
|
||||
model = model_cls(od_config=od_config)
|
||||
logger.debug("Loading weights on %s ...", load_device)
|
||||
# Quantization does not happen in `load_weights` but after it
|
||||
self.load_weights(model)
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
import math
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
@@ -1251,6 +1250,39 @@ class Bagel(nn.Module):
|
||||
def prepare_vae_latent(self, curr_kvlens, curr_rope, image_sizes, new_token_ids):
|
||||
return self.prepare_input(curr_kvlens, curr_rope, image_sizes, new_token_ids)
|
||||
|
||||
def prepare_vae_latent_cfg(self, curr_kvlens, curr_rope, image_sizes):
|
||||
packed_position_ids, packed_indexes, packed_key_value_indexes = list(), list(), list()
|
||||
|
||||
query_curr = curr = 0
|
||||
for (H, W), curr_kvlen, curr_position_id in zip(image_sizes, curr_kvlens, curr_rope):
|
||||
packed_key_value_indexes.extend(range(curr, curr + curr_kvlen))
|
||||
curr += curr_kvlen
|
||||
|
||||
packed_indexes.append(curr)
|
||||
curr += 1
|
||||
query_curr += 1
|
||||
|
||||
h, w = H // self.latent_downsample, W // self.latent_downsample
|
||||
num_image_tokens = h * w
|
||||
packed_indexes.extend(range(curr, curr + num_image_tokens))
|
||||
curr += num_image_tokens
|
||||
query_curr += num_image_tokens
|
||||
|
||||
packed_indexes.append(curr)
|
||||
curr += 1
|
||||
query_curr += 1
|
||||
|
||||
packed_position_ids.extend([curr_position_id] * (num_image_tokens + 2))
|
||||
|
||||
generation_input = {
|
||||
"cfg_packed_position_ids": torch.tensor(packed_position_ids, dtype=torch.long),
|
||||
"cfg_key_values_lens": torch.tensor(curr_kvlens, dtype=torch.int),
|
||||
"cfg_packed_query_indexes": torch.tensor(packed_indexes, dtype=torch.long),
|
||||
"cfg_packed_key_value_indexes": torch.tensor(packed_key_value_indexes, dtype=torch.long),
|
||||
}
|
||||
|
||||
return generation_input
|
||||
|
||||
def generate_image(
|
||||
self,
|
||||
packed_text_ids: torch.LongTensor,
|
||||
@@ -1266,11 +1298,25 @@ class Bagel(nn.Module):
|
||||
packed_key_value_indexes: torch.LongTensor,
|
||||
num_timesteps: int = 24,
|
||||
timestep_shift: float = 1.0,
|
||||
cfg_renorm_min: float = 0.0,
|
||||
cfg_renorm_type: str = "global",
|
||||
cfg_interval: tuple[float, float] = [0, 1],
|
||||
# cfg_text
|
||||
cfg_text_scale: float = 1.0,
|
||||
cfg_text_packed_query_indexes: torch.LongTensor | None = None,
|
||||
cfg_text_packed_position_ids: torch.LongTensor | None = None,
|
||||
cfg_text_past_key_values: NaiveCache | None = None,
|
||||
cfg_text_key_values_lens: torch.IntTensor | None = None,
|
||||
cfg_text_packed_key_value_indexes: torch.LongTensor | None = None,
|
||||
# cfg_img
|
||||
cfg_img_scale: float = 1.0,
|
||||
cfg_img_packed_query_indexes: torch.LongTensor | None = None,
|
||||
cfg_img_packed_position_ids: torch.LongTensor | None = None,
|
||||
cfg_img_past_key_values: NaiveCache | None = None,
|
||||
cfg_img_key_values_lens: torch.IntTensor | None = None,
|
||||
cfg_img_packed_key_value_indexes: torch.LongTensor | None = None,
|
||||
cfg_type: str = "parallel",
|
||||
):
|
||||
model_pred_cache_dic, model_pred_current = None, None
|
||||
model_pred_text_cache_dic, model_pred_text_current = None, None
|
||||
model_pred_img_cache_dic, model_pred_img_current = None, None
|
||||
|
||||
x_t = packed_init_noises
|
||||
|
||||
timesteps = torch.linspace(1, 0, num_timesteps, device=x_t.device)
|
||||
@@ -1280,6 +1326,12 @@ class Bagel(nn.Module):
|
||||
|
||||
for i, t in enumerate(timesteps):
|
||||
timestep = torch.tensor([t] * x_t.shape[0], device=x_t.device)
|
||||
if t > cfg_interval[0] and t <= cfg_interval[1]:
|
||||
cfg_text_scale_ = cfg_text_scale
|
||||
cfg_img_scale_ = cfg_img_scale
|
||||
else:
|
||||
cfg_text_scale_ = 1.0
|
||||
cfg_img_scale_ = 1.0
|
||||
v_t = self._forward_flow(
|
||||
x_t=x_t,
|
||||
timestep=timestep,
|
||||
@@ -1293,17 +1345,26 @@ class Bagel(nn.Module):
|
||||
key_values_lens=key_values_lens,
|
||||
past_key_values=past_key_values,
|
||||
packed_key_value_indexes=packed_key_value_indexes,
|
||||
# cache
|
||||
model_pred_cache_dic=model_pred_cache_dic,
|
||||
model_pred_current=model_pred_current,
|
||||
model_pred_text_cache_dic=model_pred_text_cache_dic,
|
||||
model_pred_text_current=model_pred_text_current,
|
||||
model_pred_img_cache_dic=model_pred_img_cache_dic,
|
||||
model_pred_img_current=model_pred_img_current,
|
||||
cfg_renorm_min=cfg_renorm_min,
|
||||
cfg_renorm_type=cfg_renorm_type,
|
||||
# cfg_text
|
||||
cfg_text_scale=cfg_text_scale_,
|
||||
cfg_text_packed_position_ids=cfg_text_packed_position_ids,
|
||||
cfg_text_packed_query_indexes=cfg_text_packed_query_indexes,
|
||||
cfg_text_key_values_lens=cfg_text_key_values_lens,
|
||||
cfg_text_past_key_values=cfg_text_past_key_values,
|
||||
cfg_text_packed_key_value_indexes=cfg_text_packed_key_value_indexes,
|
||||
# cfg_img
|
||||
cfg_img_scale=cfg_img_scale_,
|
||||
cfg_img_packed_position_ids=cfg_img_packed_position_ids,
|
||||
cfg_img_packed_query_indexes=cfg_img_packed_query_indexes,
|
||||
cfg_img_key_values_lens=cfg_img_key_values_lens,
|
||||
cfg_img_past_key_values=cfg_img_past_key_values,
|
||||
cfg_img_packed_key_value_indexes=cfg_img_packed_key_value_indexes,
|
||||
cfg_type=cfg_type,
|
||||
)
|
||||
|
||||
x_t = x_t - v_t.to(x_t.device) * dts[i] # velocity pointing from data to noise
|
||||
|
||||
unpacked_latent = x_t.split((packed_seqlens - 2).tolist())
|
||||
return unpacked_latent
|
||||
|
||||
@@ -1321,13 +1382,23 @@ class Bagel(nn.Module):
|
||||
key_values_lens: torch.IntTensor,
|
||||
past_key_values: NaiveCache,
|
||||
packed_key_value_indexes: torch.LongTensor,
|
||||
# cache
|
||||
model_pred_cache_dic: dict[str, Any] | None = None,
|
||||
model_pred_current: int | None = None,
|
||||
model_pred_text_cache_dic: dict[str, Any] | None = None,
|
||||
model_pred_text_current: int | None = None,
|
||||
model_pred_img_cache_dic: dict[str, Any] | None = None,
|
||||
model_pred_img_current: int | None = None,
|
||||
cfg_renorm_min: float = 0.0,
|
||||
cfg_renorm_type: str = "global",
|
||||
# cfg_text
|
||||
cfg_text_scale: float = 1.0,
|
||||
cfg_text_packed_position_ids: torch.LongTensor | None = None,
|
||||
cfg_text_packed_query_indexes: torch.LongTensor | None = None,
|
||||
cfg_text_key_values_lens: torch.Tensor | None = None,
|
||||
cfg_text_past_key_values: NaiveCache | None = None,
|
||||
cfg_text_packed_key_value_indexes: torch.LongTensor | None = None,
|
||||
# cfg_img
|
||||
cfg_img_scale: float = 1.0,
|
||||
cfg_img_packed_position_ids: torch.LongTensor | None = None,
|
||||
cfg_img_packed_query_indexes: torch.LongTensor | None = None,
|
||||
cfg_img_key_values_lens: torch.Tensor | None = None,
|
||||
cfg_img_past_key_values: NaiveCache | None = None,
|
||||
cfg_img_packed_key_value_indexes: torch.LongTensor | None = None,
|
||||
cfg_type: str = "parallel",
|
||||
):
|
||||
packed_text_embedding = self.language_model.model.embed_tokens(packed_text_ids)
|
||||
packed_sequence = packed_text_embedding.new_zeros((sum(packed_seqlens), self.hidden_size))
|
||||
@@ -1364,4 +1435,70 @@ class Bagel(nn.Module):
|
||||
v_t = self.llm2vae(output.packed_query_sequence)
|
||||
v_t = v_t[packed_vae_token_indexes]
|
||||
|
||||
if cfg_text_scale > 1.0:
|
||||
cfg_text_output = self.language_model.forward(
|
||||
packed_query_sequence=packed_sequence,
|
||||
query_lens=packed_seqlens,
|
||||
packed_query_position_ids=cfg_text_packed_position_ids,
|
||||
packed_query_indexes=cfg_text_packed_query_indexes,
|
||||
past_key_values=cfg_text_past_key_values,
|
||||
key_values_lens=cfg_text_key_values_lens,
|
||||
packed_key_value_indexes=cfg_text_packed_key_value_indexes,
|
||||
update_past_key_values=False,
|
||||
is_causal=False,
|
||||
**extra_inputs,
|
||||
)
|
||||
cfg_text_v_t = self.llm2vae(cfg_text_output.packed_query_sequence)
|
||||
cfg_text_v_t = cfg_text_v_t[packed_vae_token_indexes]
|
||||
|
||||
if cfg_img_scale > 1.0:
|
||||
cfg_img_output = self.language_model.forward(
|
||||
packed_query_sequence=packed_sequence,
|
||||
query_lens=packed_seqlens,
|
||||
packed_query_position_ids=cfg_img_packed_position_ids,
|
||||
packed_query_indexes=cfg_img_packed_query_indexes,
|
||||
past_key_values=cfg_img_past_key_values,
|
||||
key_values_lens=cfg_img_key_values_lens,
|
||||
packed_key_value_indexes=cfg_img_packed_key_value_indexes,
|
||||
update_past_key_values=False,
|
||||
is_causal=False,
|
||||
**extra_inputs,
|
||||
)
|
||||
cfg_img_v_t = self.llm2vae(cfg_img_output.packed_query_sequence)
|
||||
cfg_img_v_t = cfg_img_v_t[packed_vae_token_indexes]
|
||||
|
||||
if cfg_text_scale > 1.0:
|
||||
if cfg_renorm_type == "text_channel":
|
||||
v_t_text_ = cfg_text_v_t + cfg_text_scale * (v_t - cfg_text_v_t)
|
||||
norm_v_t = torch.norm(v_t, dim=-1, keepdim=True)
|
||||
norm_v_t_text_ = torch.norm(v_t_text_, dim=-1, keepdim=True)
|
||||
scale = (norm_v_t / (norm_v_t_text_ + 1e-8)).clamp(min=cfg_renorm_min, max=1.0)
|
||||
v_t_text = v_t_text_ * scale
|
||||
if cfg_img_scale > 1.0:
|
||||
v_t = cfg_img_v_t + cfg_img_scale * (v_t_text - cfg_img_v_t)
|
||||
else:
|
||||
v_t = v_t_text
|
||||
else:
|
||||
v_t_text_ = cfg_text_v_t + cfg_text_scale * (v_t - cfg_text_v_t)
|
||||
|
||||
if cfg_img_scale > 1.0:
|
||||
v_t_ = cfg_img_v_t + cfg_img_scale * (v_t_text_ - cfg_img_v_t)
|
||||
else:
|
||||
v_t_ = v_t_text_
|
||||
|
||||
# NOTE norm is computed over all dimensions, thus currently only supports batch_size = 1 with navit
|
||||
if cfg_renorm_type == "global":
|
||||
norm_v_t = torch.norm(v_t)
|
||||
norm_v_t_ = torch.norm(v_t_)
|
||||
elif cfg_renorm_type == "channel":
|
||||
norm_v_t = torch.norm(v_t, dim=-1, keepdim=True)
|
||||
norm_v_t_ = torch.norm(v_t_, dim=-1, keepdim=True)
|
||||
else:
|
||||
raise NotImplementedError(f"{cfg_renorm_type} is not supported")
|
||||
scale = (norm_v_t / (norm_v_t_ + 1e-8)).clamp(min=cfg_renorm_min, max=1.0)
|
||||
v_t = v_t_ * scale
|
||||
else:
|
||||
# No CFG
|
||||
pass
|
||||
|
||||
return v_t
|
||||
@@ -9,6 +9,7 @@ from __future__ import annotations
|
||||
import json
|
||||
import os
|
||||
from collections.abc import Iterable
|
||||
from copy import deepcopy
|
||||
from dataclasses import dataclass
|
||||
from math import isqrt
|
||||
|
||||
@@ -37,7 +38,12 @@ logger = init_logger(__name__)
|
||||
@dataclass
|
||||
class BagelGenParams:
|
||||
num_timesteps: int = 50
|
||||
timestep_shift: float = 1.0
|
||||
timestep_shift: float = 3.0
|
||||
cfg_text_scale: float = 4.0
|
||||
cfg_img_scale: float = 1.5
|
||||
cfg_interval: tuple = (0.4, 1.0)
|
||||
cfg_renorm_min: float = 0.0
|
||||
cfg_renorm_type: str = "global"
|
||||
|
||||
|
||||
def add_special_tokens(tokenizer):
|
||||
@@ -296,10 +302,15 @@ class BagelPipeline(nn.Module):
|
||||
)
|
||||
image_shape = (height, width)
|
||||
|
||||
# Map request params to Bagel gen params (defaults follow Bagel inferencer)
|
||||
extra_args = getattr(req.sampling_params, "extra_args", {}) or {}
|
||||
cfg_text_scale = extra_args.get("cfg_text_scale", 4.0)
|
||||
cfg_img_scale = extra_args.get("cfg_img_scale", 1.5)
|
||||
|
||||
gen_params = BagelGenParams(
|
||||
num_timesteps=int(req.sampling_params.num_inference_steps or 50),
|
||||
timestep_shift=3.0,
|
||||
cfg_text_scale=cfg_text_scale,
|
||||
cfg_img_scale=cfg_img_scale,
|
||||
)
|
||||
|
||||
gen_context = {
|
||||
@@ -307,20 +318,26 @@ class BagelPipeline(nn.Module):
|
||||
"ropes": [0],
|
||||
"past_key_values": NaiveCache(self.bagel.config.llm_config.num_hidden_layers),
|
||||
}
|
||||
cfg_text_context = deepcopy(gen_context)
|
||||
cfg_img_context = deepcopy(gen_context)
|
||||
|
||||
# Add text prompt (prefill) on gen context.
|
||||
# [Omni] Check for injected KV Cache from remote transfer
|
||||
injected_kv = req.sampling_params.past_key_values
|
||||
if injected_kv is not None:
|
||||
logger.info("Using injected KV Cache (direct)")
|
||||
gen_context["past_key_values"] = injected_kv
|
||||
|
||||
# User requested: kv_lens and ropes set to [gen_context["past_key_values"].key_cache[0].shape[0]]
|
||||
# Assuming injected_kv is compatible and has key_cache[0]
|
||||
seq_len = injected_kv.key_cache[0].shape[0]
|
||||
gen_context["kv_lens"] = [seq_len]
|
||||
gen_context["ropes"] = [seq_len]
|
||||
|
||||
# Disable CFG: single KV cache cannot support 3-branch CFG
|
||||
logger.warning("CFG is disabled when using injected KV Cache")
|
||||
gen_params = BagelGenParams(
|
||||
num_timesteps=gen_params.num_timesteps,
|
||||
timestep_shift=gen_params.timestep_shift,
|
||||
cfg_text_scale=1.0,
|
||||
cfg_img_scale=1.0,
|
||||
)
|
||||
|
||||
else:
|
||||
image_input = (
|
||||
None if isinstance(first_prompt, str) else (first_prompt.get("multi_modal_data") or {}).get("image")
|
||||
@@ -335,9 +352,35 @@ class BagelPipeline(nn.Module):
|
||||
if self.image_processor and self.vae:
|
||||
|
||||
def vit_transforms(img):
|
||||
# SigLIP processor returns dict with pixel_values; we want the tensor
|
||||
return self.image_processor(images=img, return_tensors="pt").pixel_values[0]
|
||||
|
||||
stride = self.bagel.latent_downsample
|
||||
max_img_size = int(self.bagel.max_latent_size * stride)
|
||||
|
||||
def _resize_to_stride(img):
|
||||
if img.mode != "RGB":
|
||||
img = img.convert("RGB")
|
||||
w, h = img.size
|
||||
# Scale down if longest edge exceeds max
|
||||
scale = min(max_img_size / max(w, h), 1.0)
|
||||
# Scale up if shortest edge is too small (min 256)
|
||||
min_img_size = min(256, max_img_size)
|
||||
scale = max(scale, min_img_size / min(w, h))
|
||||
new_w = max(stride, int(round(w * scale / stride) * stride))
|
||||
new_h = max(stride, int(round(h * scale / stride) * stride))
|
||||
# Clamp to max
|
||||
new_w = min(new_w, max_img_size)
|
||||
new_h = min(new_h, max_img_size)
|
||||
if new_w != w or new_h != h:
|
||||
img = img.resize((new_w, new_h), Image.BICUBIC)
|
||||
return img
|
||||
|
||||
image_input = [_resize_to_stride(img) for img in image_input]
|
||||
|
||||
resized_w, resized_h = image_input[0].size
|
||||
image_shape = (resized_h, resized_w)
|
||||
logger.info(f"img2img: resized image to {resized_w}x{resized_h}")
|
||||
|
||||
def vae_transforms(img):
|
||||
if img.mode != "RGB":
|
||||
img = img.convert("RGB")
|
||||
@@ -345,7 +388,7 @@ class BagelPipeline(nn.Module):
|
||||
arr = torch.from_numpy(np.array(img)).float() / 127.5 - 1.0
|
||||
return arr.permute(2, 0, 1)
|
||||
|
||||
# 1. Update VAE
|
||||
# Update gen_context with image (VAE + ViT)
|
||||
gen_input_vae, newlens_vae, new_rope_vae = self.bagel.prepare_vae_images(
|
||||
curr_kvlens=gen_context["kv_lens"],
|
||||
curr_rope=gen_context["ropes"],
|
||||
@@ -353,12 +396,9 @@ class BagelPipeline(nn.Module):
|
||||
transforms=vae_transforms,
|
||||
new_token_ids=self.new_token_ids,
|
||||
)
|
||||
|
||||
for k, v in gen_input_vae.items():
|
||||
if torch.is_tensor(v):
|
||||
gen_input_vae[k] = v.to(self.device)
|
||||
|
||||
# VAE needs bfloat16 to match model strings usually, specifically encode
|
||||
with torch.autocast(
|
||||
device_type=self.device.type,
|
||||
enabled=self.device.type != "cpu",
|
||||
@@ -370,7 +410,6 @@ class BagelPipeline(nn.Module):
|
||||
gen_context["kv_lens"] = newlens_vae
|
||||
gen_context["ropes"] = new_rope_vae
|
||||
|
||||
# 2. Update ViT
|
||||
gen_input_img, newlens_img, new_rope_img = self.bagel.prepare_vit_images(
|
||||
curr_kvlens=gen_context["kv_lens"],
|
||||
curr_rope=gen_context["ropes"],
|
||||
@@ -378,11 +417,9 @@ class BagelPipeline(nn.Module):
|
||||
transforms=vit_transforms,
|
||||
new_token_ids=self.new_token_ids,
|
||||
)
|
||||
|
||||
for k, v in gen_input_img.items():
|
||||
if torch.is_tensor(v):
|
||||
gen_input_img[k] = v.to(self.device)
|
||||
|
||||
with torch.autocast(
|
||||
device_type=self.device.type,
|
||||
enabled=self.device.type != "cpu",
|
||||
@@ -393,6 +430,10 @@ class BagelPipeline(nn.Module):
|
||||
)
|
||||
gen_context["kv_lens"] = newlens_img
|
||||
gen_context["ropes"] = new_rope_img
|
||||
|
||||
cfg_text_context = deepcopy(gen_context)
|
||||
|
||||
# Update gen_context with text prompt
|
||||
generation_input, newlens, new_rope = self.bagel.prepare_prompts(
|
||||
curr_kvlens=gen_context["kv_lens"],
|
||||
curr_rope=gen_context["ropes"],
|
||||
@@ -424,12 +465,56 @@ class BagelPipeline(nn.Module):
|
||||
gen_context["kv_lens"] = newlens
|
||||
gen_context["ropes"] = new_rope
|
||||
|
||||
# cfg_text_context: update with negative prompt (no text condition)
|
||||
neg_prompt = extra_args.get("negative_prompt", "")
|
||||
neg_input, neg_newlens, neg_rope = self.bagel.prepare_prompts(
|
||||
curr_kvlens=cfg_text_context["kv_lens"],
|
||||
curr_rope=cfg_text_context["ropes"],
|
||||
prompts=[neg_prompt],
|
||||
tokenizer=self.tokenizer,
|
||||
new_token_ids=self.new_token_ids,
|
||||
)
|
||||
for k, v in neg_input.items():
|
||||
if torch.is_tensor(v):
|
||||
neg_input[k] = v.to(self.device)
|
||||
with torch.autocast(
|
||||
device_type=self.device.type,
|
||||
enabled=self.device.type != "cpu",
|
||||
dtype=self.od_config.dtype,
|
||||
):
|
||||
cfg_text_context["past_key_values"] = self.bagel.forward_cache_update_text(
|
||||
cfg_text_context["past_key_values"], **neg_input
|
||||
)
|
||||
cfg_text_context["kv_lens"] = neg_newlens
|
||||
cfg_text_context["ropes"] = neg_rope
|
||||
|
||||
# cfg_img_context: update with text prompt (no image condition)
|
||||
cfg_img_generation_input, cfg_img_newlens, cfg_img_new_rope = self.bagel.prepare_prompts(
|
||||
curr_kvlens=cfg_img_context["kv_lens"],
|
||||
curr_rope=cfg_img_context["ropes"],
|
||||
prompts=[prompt],
|
||||
tokenizer=self.tokenizer,
|
||||
new_token_ids=self.new_token_ids,
|
||||
)
|
||||
for k, v in cfg_img_generation_input.items():
|
||||
if torch.is_tensor(v):
|
||||
cfg_img_generation_input[k] = v.to(self.device)
|
||||
with torch.autocast(
|
||||
device_type=self.device.type,
|
||||
enabled=self.device.type != "cpu",
|
||||
dtype=self.od_config.dtype,
|
||||
):
|
||||
cfg_img_context["past_key_values"] = self.bagel.forward_cache_update_text(
|
||||
cfg_img_context["past_key_values"], **cfg_img_generation_input
|
||||
)
|
||||
cfg_img_context["kv_lens"] = cfg_img_newlens
|
||||
cfg_img_context["ropes"] = cfg_img_new_rope
|
||||
|
||||
if req.sampling_params.seed is not None:
|
||||
torch.manual_seed(req.sampling_params.seed)
|
||||
if self.device.type == "cuda":
|
||||
torch.cuda.manual_seed(req.sampling_params.seed)
|
||||
|
||||
# Prepare latent query and run flow
|
||||
generation_input = self.bagel.prepare_vae_latent(
|
||||
curr_kvlens=gen_context["kv_lens"],
|
||||
curr_rope=gen_context["ropes"],
|
||||
@@ -462,6 +547,25 @@ class BagelPipeline(nn.Module):
|
||||
if torch.is_tensor(v):
|
||||
generation_input[k] = v.to(self.device)
|
||||
|
||||
# text cfg
|
||||
generation_input_cfg_text = self.bagel.prepare_vae_latent_cfg(
|
||||
curr_kvlens=cfg_text_context["kv_lens"],
|
||||
curr_rope=cfg_text_context["ropes"],
|
||||
image_sizes=[image_shape],
|
||||
)
|
||||
# img cfg
|
||||
generation_input_cfg_img = self.bagel.prepare_vae_latent_cfg(
|
||||
curr_kvlens=cfg_img_context["kv_lens"],
|
||||
curr_rope=cfg_img_context["ropes"],
|
||||
image_sizes=[image_shape],
|
||||
)
|
||||
for k, v in generation_input_cfg_text.items():
|
||||
if torch.is_tensor(v):
|
||||
generation_input_cfg_text[k] = v.to(self.device)
|
||||
for k, v in generation_input_cfg_img.items():
|
||||
if torch.is_tensor(v):
|
||||
generation_input_cfg_img[k] = v.to(self.device)
|
||||
|
||||
with torch.autocast(
|
||||
device_type=self.device.type,
|
||||
enabled=self.device.type != "cpu",
|
||||
@@ -469,12 +573,26 @@ class BagelPipeline(nn.Module):
|
||||
):
|
||||
latents = self.bagel.generate_image(
|
||||
past_key_values=gen_context["past_key_values"],
|
||||
cfg_text_past_key_values=cfg_text_context["past_key_values"],
|
||||
cfg_img_past_key_values=cfg_img_context["past_key_values"],
|
||||
num_timesteps=gen_params.num_timesteps,
|
||||
timestep_shift=gen_params.timestep_shift,
|
||||
cfg_text_scale=gen_params.cfg_text_scale,
|
||||
cfg_img_scale=gen_params.cfg_img_scale,
|
||||
cfg_interval=gen_params.cfg_interval,
|
||||
cfg_renorm_min=gen_params.cfg_renorm_min,
|
||||
cfg_renorm_type=gen_params.cfg_renorm_type,
|
||||
**generation_input,
|
||||
cfg_text_packed_position_ids=generation_input_cfg_text["cfg_packed_position_ids"],
|
||||
cfg_text_packed_query_indexes=generation_input_cfg_text["cfg_packed_query_indexes"],
|
||||
cfg_text_key_values_lens=generation_input_cfg_text["cfg_key_values_lens"],
|
||||
cfg_text_packed_key_value_indexes=generation_input_cfg_text["cfg_packed_key_value_indexes"],
|
||||
cfg_img_packed_position_ids=generation_input_cfg_img["cfg_packed_position_ids"],
|
||||
cfg_img_packed_query_indexes=generation_input_cfg_img["cfg_packed_query_indexes"],
|
||||
cfg_img_key_values_lens=generation_input_cfg_img["cfg_key_values_lens"],
|
||||
cfg_img_packed_key_value_indexes=generation_input_cfg_img["cfg_packed_key_value_indexes"],
|
||||
)
|
||||
|
||||
# Decode first sample
|
||||
img = self._decode_image_from_latent(self.bagel, self.vae, latents[0], image_shape)
|
||||
return DiffusionOutput(output=img)
|
||||
|
||||
|
||||
@@ -2,14 +2,20 @@ from collections.abc import Iterable
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from diffusers.models.attention import FeedForward
|
||||
import torch.nn.functional as F
|
||||
|
||||
# TODO replace this with vLLM implementation
|
||||
from diffusers.models.embeddings import CombinedTimestepTextProjEmbeddings, PatchEmbed
|
||||
from diffusers.models.modeling_outputs import Transformer2DModelOutput
|
||||
from diffusers.models.normalization import AdaLayerNormContinuous, AdaLayerNormZero, RMSNorm, SD35AdaLayerNormZeroX
|
||||
from diffusers.models.normalization import AdaLayerNormContinuous, AdaLayerNormZero, SD35AdaLayerNormZeroX
|
||||
from vllm.logger import init_logger
|
||||
from vllm.model_executor.layers.linear import QKVParallelLinear, ReplicatedLinear
|
||||
from vllm.model_executor.layers.layernorm import RMSNorm
|
||||
from vllm.model_executor.layers.linear import (
|
||||
ColumnParallelLinear,
|
||||
QKVParallelLinear,
|
||||
ReplicatedLinear,
|
||||
RowParallelLinear,
|
||||
)
|
||||
from vllm.model_executor.model_loader.weight_utils import default_weight_loader
|
||||
|
||||
from vllm_omni.diffusion.attention.layer import Attention
|
||||
@@ -18,6 +24,54 @@ from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class GELU(nn.Module):
|
||||
def __init__(self, dim_in: int, dim_out: int, approximate: str = "none", bias: bool = True):
|
||||
super().__init__()
|
||||
self.proj = ColumnParallelLinear(dim_in, dim_out, bias=bias)
|
||||
self.approximate = approximate
|
||||
|
||||
def forward(self, hidden_states):
|
||||
hidden_states, _ = self.proj(hidden_states)
|
||||
hidden_states = F.gelu(hidden_states, approximate=self.approximate)
|
||||
return hidden_states
|
||||
|
||||
|
||||
class FeedForward(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
dim: int,
|
||||
dim_out: int | None = None,
|
||||
mult: int = 4,
|
||||
dropout: float = 0.0,
|
||||
activation_fn: str = "gelu-approximate",
|
||||
final_dropout: bool = False,
|
||||
inner_dim=None,
|
||||
bias: bool = True,
|
||||
):
|
||||
super().__init__()
|
||||
if inner_dim is None:
|
||||
inner_dim = int(dim * mult)
|
||||
dim_out = dim_out if dim_out is not None else dim
|
||||
|
||||
if activation_fn == "gelu-approximate":
|
||||
act_fn = GELU(dim, inner_dim, approximate="tanh", bias=bias)
|
||||
else:
|
||||
raise ValueError(f"Unsupported activation function type: {activation_fn}")
|
||||
|
||||
self.net = nn.ModuleList([])
|
||||
self.net.append(act_fn)
|
||||
self.net.append(nn.Dropout(dropout))
|
||||
self.net.append(RowParallelLinear(inner_dim, dim_out, bias=bias))
|
||||
if final_dropout:
|
||||
self.net.append(nn.Dropout(dropout))
|
||||
|
||||
def forward(self, hidden_states: torch.Tensor, *args, **kwargs) -> torch.Tensor:
|
||||
for layer in self.net:
|
||||
output = layer(hidden_states)
|
||||
hidden_states = output[0] if isinstance(output, tuple) else output
|
||||
return hidden_states
|
||||
|
||||
|
||||
class SD3PatchEmbed(nn.Module):
|
||||
"""
|
||||
2D Image to Patch Embedding with support for SD3.
|
||||
@@ -77,7 +131,6 @@ class SD3CrossAttention(nn.Module):
|
||||
hidden_size=dim,
|
||||
head_size=self.head_dim,
|
||||
total_num_heads=num_heads,
|
||||
disable_tp=True,
|
||||
)
|
||||
self.norm_q = RMSNorm(head_dim, eps=eps) if qk_norm else nn.Identity()
|
||||
self.norm_k = RMSNorm(head_dim, eps=eps) if qk_norm else nn.Identity()
|
||||
@@ -88,17 +141,18 @@ class SD3CrossAttention(nn.Module):
|
||||
added_kv_proj_dim,
|
||||
head_size=self.inner_kv_dim // self.num_heads,
|
||||
total_num_heads=self.num_heads,
|
||||
disable_tp=True,
|
||||
)
|
||||
else:
|
||||
self.add_kv_proj = None
|
||||
|
||||
if not context_pre_only:
|
||||
self.to_add_out = ReplicatedLinear(self.inner_dim, self.dim, bias=out_bias)
|
||||
self.to_add_out = RowParallelLinear(self.inner_dim, self.dim, bias=out_bias)
|
||||
else:
|
||||
self.to_add_out = None
|
||||
|
||||
if not pre_only:
|
||||
self.to_out = nn.ModuleList([])
|
||||
self.to_out.append(ReplicatedLinear(self.inner_dim, self.dim, bias=out_bias))
|
||||
self.to_out.append(RowParallelLinear(self.inner_dim, self.dim, bias=out_bias))
|
||||
else:
|
||||
self.to_out = None
|
||||
|
||||
@@ -106,7 +160,7 @@ class SD3CrossAttention(nn.Module):
|
||||
self.norm_added_k = RMSNorm(head_dim, eps=eps) if qk_norm else nn.Identity()
|
||||
|
||||
self.attn = Attention(
|
||||
num_heads=num_heads,
|
||||
num_heads=self.to_qkv.num_heads,
|
||||
head_size=self.head_dim,
|
||||
softmax_scale=1.0 / (self.head_dim**0.5),
|
||||
causal=False,
|
||||
@@ -118,13 +172,15 @@ class SD3CrossAttention(nn.Module):
|
||||
encoder_hidden_states: torch.Tensor | None = None,
|
||||
):
|
||||
# Compute QKV for image stream (sample projections)
|
||||
qkv, _ = self.to_qkv(hidden_states)
|
||||
qkv = self.to_qkv(hidden_states)
|
||||
qkv = qkv[0]
|
||||
img_query, img_key, img_value = qkv.chunk(3, dim=-1)
|
||||
|
||||
# Reshape for multi-head attention
|
||||
img_query = img_query.unflatten(-1, (self.num_heads, -1))
|
||||
img_key = img_key.unflatten(-1, (self.num_heads, -1))
|
||||
img_value = img_value.unflatten(-1, (self.num_heads, -1))
|
||||
local_num_heads = self.to_qkv.num_heads
|
||||
img_query = img_query.unflatten(-1, (local_num_heads, -1))
|
||||
img_key = img_key.unflatten(-1, (local_num_heads, -1))
|
||||
img_value = img_value.unflatten(-1, (local_num_heads, -1))
|
||||
|
||||
# Apply QK normalization
|
||||
img_query = self.norm_q(img_query)
|
||||
@@ -132,12 +188,13 @@ class SD3CrossAttention(nn.Module):
|
||||
|
||||
if encoder_hidden_states is not None:
|
||||
# Compute QKV for text stream (context projections)
|
||||
qkv, _ = self.add_kv_proj(encoder_hidden_states)
|
||||
txt_query, txt_key, txt_value = qkv.chunk(3, dim=-1)
|
||||
qkv_add = self.add_kv_proj(encoder_hidden_states)
|
||||
qkv_add = qkv_add[0]
|
||||
txt_query, txt_key, txt_value = qkv_add.chunk(3, dim=-1)
|
||||
|
||||
txt_query = txt_query.unflatten(-1, (self.num_heads, -1))
|
||||
txt_key = txt_key.unflatten(-1, (self.num_heads, -1))
|
||||
txt_value = txt_value.unflatten(-1, (self.num_heads, -1))
|
||||
txt_query = txt_query.unflatten(-1, (local_num_heads, -1))
|
||||
txt_key = txt_key.unflatten(-1, (local_num_heads, -1))
|
||||
txt_value = txt_value.unflatten(-1, (local_num_heads, -1))
|
||||
|
||||
txt_query = self.norm_added_q(txt_query)
|
||||
txt_key = self.norm_added_k(txt_key)
|
||||
@@ -265,6 +322,8 @@ class SD3TransformerBlock(nn.Module):
|
||||
encoder_hidden_states: torch.FloatTensor,
|
||||
temb: torch.FloatTensor,
|
||||
) -> tuple[torch.Tensor, torch.Tensor]:
|
||||
if isinstance(encoder_hidden_states, tuple):
|
||||
encoder_hidden_states = encoder_hidden_states[0]
|
||||
if self.use_dual_attention:
|
||||
norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp, norm_hidden_states2, gate_msa2 = self.norm1(
|
||||
hidden_states, emb=temb
|
||||
@@ -363,7 +422,7 @@ class SD3Transformer2DModel(nn.Module):
|
||||
self.time_text_embed = CombinedTimestepTextProjEmbeddings(
|
||||
embedding_dim=self.inner_dim, pooled_projection_dim=self.pooled_projection_dim
|
||||
)
|
||||
self.context_embedder = nn.Linear(self.joint_attention_dim, self.caption_projection_dim)
|
||||
self.context_embedder = ReplicatedLinear(self.joint_attention_dim, self.caption_projection_dim)
|
||||
|
||||
self.transformer_blocks = nn.ModuleList(
|
||||
[
|
||||
@@ -380,7 +439,9 @@ class SD3Transformer2DModel(nn.Module):
|
||||
)
|
||||
|
||||
self.norm_out = AdaLayerNormContinuous(self.inner_dim, self.inner_dim, elementwise_affine=False, eps=1e-6)
|
||||
self.proj_out = nn.Linear(self.inner_dim, self.patch_size * self.patch_size * self.out_channels, bias=True)
|
||||
self.proj_out = ReplicatedLinear(
|
||||
self.inner_dim, self.patch_size * self.patch_size * self.out_channels, bias=True
|
||||
)
|
||||
|
||||
def forward(
|
||||
self,
|
||||
@@ -427,6 +488,9 @@ class SD3Transformer2DModel(nn.Module):
|
||||
hidden_states = self.norm_out(hidden_states, temb)
|
||||
hidden_states = self.proj_out(hidden_states)
|
||||
|
||||
if isinstance(hidden_states, (tuple, list)):
|
||||
hidden_states = hidden_states[0]
|
||||
|
||||
# unpatchify
|
||||
patch_size = self.patch_size
|
||||
height = height // patch_size
|
||||
|
||||
@@ -1,535 +0,0 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
"""CPU offloading utilities for diffusion models.
|
||||
|
||||
This module provides mutual-exclusion CPU offloading between DiT and encoders.
|
||||
When enable_cpu_offload is enabled:
|
||||
- Text encoders run on GPU while DiT is on CPU
|
||||
- DiT runs on GPU while encoders are offloaded to CPU
|
||||
|
||||
This allows running large models on limited GPU memory.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import partial
|
||||
from itertools import chain
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class SequentialOffloader:
|
||||
"""Sequential offloader: DiT and encoders take turns on GPU.
|
||||
|
||||
Uses PyTorch's forward pre-hooks to automatically swap models:
|
||||
- Before encoder runs: move DiT modules to CPU, move encoder to GPU
|
||||
- Before DiT runs: move encoders to CPU, move active DiT to GPU
|
||||
|
||||
This ensures only one large model group is on GPU at a time.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
dits: list[nn.Module],
|
||||
encoders: list[nn.Module],
|
||||
device: torch.device,
|
||||
pin_memory: bool = True,
|
||||
):
|
||||
assert all(isinstance(m, nn.Module) for m in dits), "All dits must be nn.Module"
|
||||
assert all(isinstance(m, nn.Module) for m in encoders), "All encoders must be nn.Module"
|
||||
self.dits = dits
|
||||
self.encoders = encoders
|
||||
self.device = device
|
||||
self.pin_memory = pin_memory
|
||||
self._handles: list = []
|
||||
|
||||
def _to_cpu(self, module: nn.Module) -> None:
|
||||
"""Move module to CPU with optional memory pinning."""
|
||||
# Skip if already on CPU
|
||||
try:
|
||||
param = next(module.parameters())
|
||||
if param.device.type == "cpu":
|
||||
return
|
||||
except StopIteration:
|
||||
return
|
||||
|
||||
previous_device = param.device
|
||||
module.to("cpu", non_blocking=True)
|
||||
|
||||
# Release allocator blocks when tensors leave the GPU.
|
||||
if previous_device.type != "cpu":
|
||||
torch.cuda.empty_cache()
|
||||
|
||||
if self.pin_memory:
|
||||
for p in module.parameters():
|
||||
if p.data.device.type == "cpu" and not p.data.is_pinned():
|
||||
p.data = p.data.pin_memory()
|
||||
|
||||
def _to_gpu(self, module: nn.Module) -> None:
|
||||
"""Move module to GPU."""
|
||||
# Skip if already on target device
|
||||
try:
|
||||
if next(module.parameters()).device == self.device:
|
||||
return
|
||||
except StopIteration:
|
||||
return
|
||||
|
||||
module.to(self.device, non_blocking=True)
|
||||
|
||||
def _dit_pre_hook(self, module: nn.Module, args: tuple) -> None:
|
||||
"""Before DiT forward: offload encoders, load DiT."""
|
||||
for enc in self.encoders:
|
||||
self._to_cpu(enc)
|
||||
self._to_gpu(module)
|
||||
|
||||
current_omni_platform.synchronize()
|
||||
|
||||
logger.debug("Swapped: encoders -> CPU, DiT -> GPU")
|
||||
|
||||
def _encoder_pre_hook(self, module: nn.Module, args: tuple) -> None:
|
||||
"""Before encoder forward: offload DiT, load encoder."""
|
||||
for dit_mod in self.dits:
|
||||
self._to_cpu(dit_mod)
|
||||
self._to_gpu(module)
|
||||
|
||||
current_omni_platform.synchronize()
|
||||
|
||||
logger.debug("Swapped: DiT -> CPU, encoder -> GPU")
|
||||
|
||||
def register(self) -> None:
|
||||
"""Register forward pre-hooks on DiT and encoders."""
|
||||
# Hook on each DiT-like module
|
||||
for dit_mod in self.dits:
|
||||
h = dit_mod.register_forward_pre_hook(self._dit_pre_hook)
|
||||
self._handles.append(h)
|
||||
logger.debug("Registered offload hook for %s", dit_mod.__class__.__name__)
|
||||
|
||||
# Hook on each encoder
|
||||
for enc in self.encoders:
|
||||
h = enc.register_forward_pre_hook(self._encoder_pre_hook)
|
||||
self._handles.append(h)
|
||||
logger.debug("Registered offload hook for %s", enc.__class__.__name__)
|
||||
|
||||
def remove(self) -> None:
|
||||
"""Remove all hooks."""
|
||||
for h in self._handles:
|
||||
h.remove()
|
||||
self._handles = []
|
||||
|
||||
|
||||
class LayerwiseOffloader:
|
||||
"""Layer-wise CPU offloading for transformer blocks.
|
||||
|
||||
Keeps only a sliding window of layers (blocks), by default a single layer, on GPU,
|
||||
prefetching the next block while the current block computes to approach compute - memcpy overlap.
|
||||
Unused blocks are freed on GPU.
|
||||
|
||||
Based on implementations from:
|
||||
https://github.com/sgl-project/sglang/blob/v0.5.8/python/sglang/multimodal_gen/runtime/utils/layerwise_offload.py
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
blocks: list[nn.Module],
|
||||
device: torch.device,
|
||||
pin_memory: bool = True,
|
||||
num_gpu_layers: int = 1,
|
||||
):
|
||||
assert all(isinstance(m, nn.Module) for m in blocks), "All transformer blocks must be torch.nn.Module"
|
||||
assert current_omni_platform.is_cuda(), "Layerwise offloading is only supported on cuda devices for now"
|
||||
|
||||
self.blocks = blocks
|
||||
self.device = device
|
||||
self.pin_memory = pin_memory
|
||||
self.num_gpu_layers = num_gpu_layers
|
||||
self.num_blocks = len(self.blocks)
|
||||
if self.num_blocks == 0:
|
||||
raise ValueError("LayerwiseOffloader requires at least one block, but found 0.")
|
||||
if not (1 <= self.num_gpu_layers <= self.num_blocks):
|
||||
raise ValueError(f"Invalid num_gpu_layers {self.num_gpu_layers} with {self.num_blocks} blocks")
|
||||
|
||||
self._pre_hook_handles: list = []
|
||||
self._post_hook_handles: list = []
|
||||
|
||||
self._copy_stream = torch.cuda.Stream()
|
||||
|
||||
# Per-layer synchronization primitive: set after H2D copy completes.
|
||||
self._prefetch_done: list[torch.cuda.Event | None] = [None] * self.num_blocks
|
||||
|
||||
# Simple state to avoid redundant work.
|
||||
self._resident: list[bool] = [False] * self.num_blocks
|
||||
|
||||
# Pre-allocate gpu tensors
|
||||
# layer-id -> {dtype -> flattened aggregated cpu tensor}
|
||||
self.layer_cpu_weights: list[dict[torch.dtype, torch.Tensor]] = []
|
||||
self.layer_metadata: list[dict[torch.dtype, list[dict[str, Any]]]] = []
|
||||
|
||||
self.block_parameters: dict[int, dict[str, nn.Parameter]] = {}
|
||||
self.block_buffers: dict[int, dict[str, torch.Tensor]] = {}
|
||||
for layer_idx, block in enumerate(self.blocks):
|
||||
self.block_parameters[layer_idx] = dict(block.named_parameters())
|
||||
self.block_buffers[layer_idx] = dict(block.named_buffers())
|
||||
|
||||
dtype_cpu_flattened_weights, dtype_metadata = self._to_cpu(
|
||||
self.block_parameters[layer_idx], self.block_buffers[layer_idx]
|
||||
)
|
||||
self.layer_cpu_weights.append(dtype_cpu_flattened_weights)
|
||||
self.layer_metadata.append(dtype_metadata)
|
||||
|
||||
if self.num_blocks != len(self.layer_cpu_weights):
|
||||
logger.error(
|
||||
f"Inconsistent block layers happened: # of blocks: {self.num_blocks}; "
|
||||
f"# of layer cpu weights: {len(self.layer_cpu_weights)}"
|
||||
)
|
||||
|
||||
# Register pre and post forward hooks on each of the blocks
|
||||
self.register_block_hooks()
|
||||
|
||||
# Pre-fetch the first layer
|
||||
# For subsequent requests, the first layer/block will be pre-fetched
|
||||
# during the last layer compute of the previous request.
|
||||
self.prefetch_layer(0, non_blocking=False)
|
||||
|
||||
def _to_cpu(
|
||||
self, params: dict[str, nn.Parameter], bufs: dict[str, torch.Tensor]
|
||||
) -> tuple[dict[torch.dtype, torch.Tensor], dict[torch.dtype, list[dict[str, Any]]]]:
|
||||
"""Move block parameters and buffers to CPU, flattening by dtype.
|
||||
|
||||
Consolidates parameters and buffers into contiguous CPU tensors grouped by dtype
|
||||
for GPU transfers. Replaces original tensors with empty placeholders.
|
||||
|
||||
Returns:
|
||||
Tuple of
|
||||
flattened CPU tensors by dtype,
|
||||
metadata for reconstruction by dtype
|
||||
"""
|
||||
dtype_grouped_weights: dict[torch.dtype, dict[str, torch.Tensor]] = {}
|
||||
dtype_cpu_flattened_weights: dict[torch.dtype, torch.Tensor] = {}
|
||||
# order does matter
|
||||
dtype_metadata: dict[torch.dtype, list[dict[str, Any]]] = {}
|
||||
|
||||
for name, param_or_buf in chain(params.items(), bufs.items()):
|
||||
dtype = param_or_buf.dtype
|
||||
if dtype not in dtype_grouped_weights:
|
||||
dtype_grouped_weights[dtype] = {}
|
||||
dtype_grouped_weights[dtype][name] = param_or_buf
|
||||
|
||||
for dtype, name2weights in dtype_grouped_weights.items():
|
||||
# total # of parameters + buffers
|
||||
total_numel = sum(t.numel() for _, t in name2weights.items())
|
||||
cpu_tensor = torch.empty(total_numel, dtype=dtype, device="cpu", pin_memory=self.pin_memory)
|
||||
|
||||
current_offset = 0
|
||||
for name, param_or_buf in name2weights.items():
|
||||
numel = param_or_buf.numel()
|
||||
cpu_tensor[current_offset : current_offset + numel].copy_(param_or_buf.flatten())
|
||||
if dtype not in dtype_metadata:
|
||||
dtype_metadata[dtype] = []
|
||||
dtype_metadata[dtype].append(
|
||||
{
|
||||
"name": name,
|
||||
"offset": current_offset,
|
||||
"numel": numel,
|
||||
"shape": param_or_buf.shape,
|
||||
}
|
||||
)
|
||||
|
||||
param_or_buf.data = torch.empty((), device=self.device, dtype=dtype)
|
||||
current_offset += numel
|
||||
|
||||
dtype_cpu_flattened_weights[dtype] = cpu_tensor
|
||||
|
||||
return dtype_cpu_flattened_weights, dtype_metadata
|
||||
|
||||
def register_block_hooks(self) -> None:
|
||||
"""Register forward hooks on blocks for prefetching and offloading."""
|
||||
|
||||
def _pre_hook(module: nn.Module, args: tuple, *, layer_idx: int) -> None:
|
||||
# For the last block / layer, prefetch layer 0 (the first layer)
|
||||
next_id = (layer_idx + 1) % self.num_blocks
|
||||
self.prefetch_layer(next_id, non_blocking=True)
|
||||
|
||||
def _post_hook(module: nn.Module, args: tuple, output: tuple, *, layer_idx: int) -> None:
|
||||
self.offload_layer(layer_idx)
|
||||
self._resident[layer_idx] = False
|
||||
self._prefetch_done[layer_idx] = None
|
||||
|
||||
for i, layer in enumerate(self.blocks):
|
||||
pre_hook_fn = partial(_pre_hook, layer_idx=i)
|
||||
handle = layer.register_forward_pre_hook(pre_hook_fn)
|
||||
self._pre_hook_handles.append(handle)
|
||||
|
||||
post_hook_fn = partial(_post_hook, layer_idx=i)
|
||||
handle = layer.register_forward_hook(post_hook_fn)
|
||||
self._post_hook_handles.append(handle)
|
||||
|
||||
@torch.compiler.disable
|
||||
def prefetch_layer(self, layer_idx: int, non_blocking: bool = True) -> None:
|
||||
"""Copy layer weights from CPU -> GPU.
|
||||
|
||||
Pre-fetch target layer in an asynchronous way with compute - memory copy overlap,
|
||||
with non_blocking set to True.
|
||||
"""
|
||||
if layer_idx >= self.num_blocks or layer_idx < 0:
|
||||
logger.warning(f"Invalid layer id specified: {layer_idx}")
|
||||
return
|
||||
|
||||
self._copy_stream.wait_stream(torch.cuda.current_stream())
|
||||
|
||||
layers_to_fetch = [(layer_idx + i) % self.num_blocks for i in range(self.num_gpu_layers)]
|
||||
|
||||
for idx in layers_to_fetch:
|
||||
if self._resident[idx]:
|
||||
continue
|
||||
|
||||
layer_params = self.block_parameters[idx]
|
||||
layer_bufs = self.block_buffers[idx]
|
||||
|
||||
evt = torch.cuda.Event()
|
||||
gpu_weights: dict[torch.dtype, torch.Tensor] = {}
|
||||
|
||||
with torch.cuda.stream(self._copy_stream):
|
||||
for dtype, cpu_weight in self.layer_cpu_weights[idx].items():
|
||||
gpu_weight = torch.empty(cpu_weight.shape, dtype=dtype, device=self.device)
|
||||
gpu_weight.copy_(cpu_weight, non_blocking=non_blocking)
|
||||
gpu_weights[dtype] = gpu_weight
|
||||
|
||||
evt.record(self._copy_stream)
|
||||
|
||||
for dtype in self.layer_metadata[idx]:
|
||||
ordered_metadata: list[dict[str, Any]] = self.layer_metadata[idx][dtype]
|
||||
|
||||
gpu_weight = gpu_weights[dtype]
|
||||
|
||||
for metadata in ordered_metadata:
|
||||
target_name = metadata["name"]
|
||||
target_param_or_buf = (
|
||||
layer_params[target_name] if target_name in layer_params else layer_bufs[target_name]
|
||||
)
|
||||
|
||||
target_param_or_buf.data = gpu_weight[
|
||||
metadata["offset"] : metadata["offset"] + metadata["numel"]
|
||||
].view(metadata["shape"])
|
||||
|
||||
self._prefetch_done[idx] = evt
|
||||
self._resident[idx] = True
|
||||
|
||||
@torch.compiler.disable
|
||||
def offload_layer(self, layer_idx: int) -> None:
|
||||
"""Free GPU memory for layer by replacing tensors with empty placeholders."""
|
||||
if layer_idx >= self.num_blocks or layer_idx < 0:
|
||||
logger.warning(f"Invalid layer id specified: {layer_idx}")
|
||||
return
|
||||
if not self._resident[layer_idx]:
|
||||
logger.warning(f"{layer_idx} is not residing on GPU")
|
||||
return
|
||||
|
||||
evt = self._prefetch_done[layer_idx]
|
||||
if evt is not None:
|
||||
torch.cuda.current_stream().wait_event(evt)
|
||||
|
||||
# free GPU residency
|
||||
for _, param in self.block_parameters[layer_idx].items():
|
||||
param.data = torch.empty((), device=self.device, dtype=param.dtype)
|
||||
for _, buf in self.block_buffers[layer_idx].items():
|
||||
buf.data = torch.empty((), device=self.device, dtype=buf.dtype)
|
||||
|
||||
def remove_all_hooks(self) -> None:
|
||||
"""Remove all hooks."""
|
||||
for h in self._pre_hook_handles:
|
||||
h.remove()
|
||||
for h in self._post_hook_handles:
|
||||
h.remove()
|
||||
self._pre_hook_handles.clear()
|
||||
self._post_hook_handles.clear()
|
||||
|
||||
@staticmethod
|
||||
def get_blocks_attr_name(model: nn.Module) -> str | None:
|
||||
"""Retrieve blocks attribute name from provided DiT model"""
|
||||
return getattr(model.__class__, "_layerwise_offload_blocks_attr", None)
|
||||
|
||||
@staticmethod
|
||||
def get_blocks_from_dit(model: nn.Module) -> list[nn.Module]:
|
||||
"""
|
||||
Retrieve a list of blocks from provided DiT model. Blocks attribute name
|
||||
are found by `_layerwise_offload_blocks_attr` set to DiT models. For example,
|
||||
|
||||
```
|
||||
class WanTransformer3DModel(nn.Module):
|
||||
_layerwise_offload_blocks_attr = "blocks"
|
||||
```
|
||||
"""
|
||||
blocks_attr_name = LayerwiseOffloader.get_blocks_attr_name(model)
|
||||
if blocks_attr_name is None:
|
||||
logger.warning(
|
||||
f"No _layerwise_offload_blocks_attr defined for {model.__class__.__name__}, "
|
||||
"skipping layerwise offloading"
|
||||
)
|
||||
return []
|
||||
|
||||
_blocks = getattr(model, blocks_attr_name, None)
|
||||
if _blocks is None:
|
||||
logger.warning(
|
||||
f"Blocks (layers) '{blocks_attr_name}' not found on {model.__class__.__name__}, "
|
||||
"skipping layerwise offloading"
|
||||
)
|
||||
return []
|
||||
|
||||
return list(_blocks)
|
||||
|
||||
|
||||
def apply_offload_hooks(
|
||||
model: nn.Module,
|
||||
od_config: OmniDiffusionConfig,
|
||||
*,
|
||||
device: torch.device | None = None,
|
||||
) -> None:
|
||||
"""Apply mutual-exclusion offload hooks based on config.
|
||||
|
||||
When enable_cpu_offload is enabled, DiT and encoders swap GPU access:
|
||||
- Encoders (text_encoder, text_encoder_2, text_encoder_3, image_encoder)
|
||||
run on GPU while DiT is on CPU
|
||||
- DiT runs on GPU while encoders are on CPU
|
||||
|
||||
Args:
|
||||
model: Diffusion pipeline model
|
||||
od_config: OmniDiffusionConfig with offload settings
|
||||
"""
|
||||
enable_cpu_offload = getattr(od_config, "enable_cpu_offload", False)
|
||||
enable_layerwise_offload = getattr(od_config, "enable_layerwise_offload", False)
|
||||
pin_cpu_memory = getattr(od_config, "pin_cpu_memory", True)
|
||||
|
||||
if not enable_cpu_offload and not enable_layerwise_offload:
|
||||
return
|
||||
if enable_cpu_offload and enable_layerwise_offload:
|
||||
# NOTE: Model-wise and layerwise cpu offloading are not supported together at this moment,
|
||||
# consider layerwise offloading has higher priority than model-wise offloading
|
||||
enable_cpu_offload = False
|
||||
logger.info(
|
||||
"Model-wise and layer-wise CPU offloading are not supported together at this moment. "
|
||||
"Automatically disabled model-wise offloading."
|
||||
)
|
||||
# For now, model-wise and layer-wise (block-wise) offloading
|
||||
# are functioning as expected when cuda device is available
|
||||
if not current_omni_platform.is_cuda() or current_omni_platform.get_device_count() < 1:
|
||||
logger.info("CPU Offloading requires cuda devices available. Skipping for now...")
|
||||
return
|
||||
|
||||
# Find DiT/transformer modules
|
||||
dit_modules: list[nn.Module] = []
|
||||
dit_names: list[str] = []
|
||||
candidate_attrs = ["transformer", "transformer_2", "dit"]
|
||||
for attr in candidate_attrs:
|
||||
if not hasattr(model, attr):
|
||||
continue
|
||||
module_obj = getattr(model, attr)
|
||||
if module_obj is None:
|
||||
continue
|
||||
|
||||
assert isinstance(module_obj, nn.Module), f"Expected {attr} to be nn.Module, got {type(module_obj)!r}"
|
||||
|
||||
if module_obj in dit_modules:
|
||||
continue
|
||||
|
||||
dit_modules.append(module_obj)
|
||||
dit_names.append(attr)
|
||||
|
||||
if not dit_modules:
|
||||
logger.warning("enable_cpu_offload enabled but no transformer/dit/unet found")
|
||||
return
|
||||
if device is None:
|
||||
try:
|
||||
device = next(dit_modules[0].parameters()).device
|
||||
except StopIteration:
|
||||
try:
|
||||
device = current_omni_platform.get_torch_device()
|
||||
except (NotImplementedError, AttributeError):
|
||||
logger.error("Fail to get device of pipeline. Skipping applying offloading hooks")
|
||||
return
|
||||
|
||||
# Collect all encoders
|
||||
encoders: list[nn.Module] = []
|
||||
encoder_names: list[str] = []
|
||||
for attr in ["text_encoder", "text_encoder_2", "text_encoder_3", "image_encoder"]:
|
||||
if hasattr(model, attr) and getattr(model, attr) is not None:
|
||||
encoders.append(getattr(model, attr))
|
||||
encoder_names.append(attr)
|
||||
if not encoders and enable_cpu_offload:
|
||||
logger.warning("enable_cpu_offload enabled but no encoders found")
|
||||
return
|
||||
for enc in encoders:
|
||||
enc.to(device)
|
||||
|
||||
# Collect VAE
|
||||
for name in ["vae"]:
|
||||
module = getattr(model, name, None)
|
||||
if module is None:
|
||||
continue
|
||||
try:
|
||||
module.to(device, non_blocking=True)
|
||||
except Exception as exc:
|
||||
logger.debug("Failed to move %s to GPU: %s", name, exc)
|
||||
|
||||
if enable_cpu_offload:
|
||||
# Initial state: keep DiT modules on CPU (encoders typically run first)
|
||||
for dit_mod in dit_modules:
|
||||
dit_mod.to("cpu")
|
||||
|
||||
torch.cuda.empty_cache()
|
||||
|
||||
if pin_cpu_memory:
|
||||
for dit_mod in dit_modules:
|
||||
for p in dit_mod.parameters():
|
||||
if p.data.device.type == "cpu" and not p.data.is_pinned():
|
||||
p.data = p.data.pin_memory()
|
||||
|
||||
# Register sequential offload hooks
|
||||
SequentialOffloader(dit_modules, encoders, device, pin_cpu_memory).register()
|
||||
logger.info(
|
||||
"CPU offload enabled: %s <-> %s (mutual exclusion)",
|
||||
", ".join(dit_names),
|
||||
", ".join(encoder_names),
|
||||
)
|
||||
elif enable_layerwise_offload:
|
||||
logger.info(f"Applying offloading hooks on {dit_names}")
|
||||
|
||||
for i, dit_module in enumerate(dit_modules):
|
||||
logger.info(f"Applying hook on {dit_names[i]} ({dit_module.__class__.__name__})")
|
||||
blocks_attr_name = LayerwiseOffloader.get_blocks_attr_name(dit_module)
|
||||
blocks = LayerwiseOffloader.get_blocks_from_dit(dit_module)
|
||||
|
||||
if not blocks_attr_name or not blocks:
|
||||
logger.warning(
|
||||
"Target layers (blocks) are not found. "
|
||||
f"Skipping offloading on {dit_names[i]} ({dit_module.__class__.__name__})"
|
||||
)
|
||||
continue
|
||||
|
||||
# move modules other than blocks to gpu and keep them on gpu
|
||||
for name, m in dit_module.named_children():
|
||||
# Skip the blocks module (layers to be offloaded)
|
||||
if name == blocks_attr_name:
|
||||
logger.debug(f"Skipped module {name}")
|
||||
continue
|
||||
|
||||
m.to(device)
|
||||
logger.debug(f"Moved {name} to device {device}")
|
||||
|
||||
# set to the module (transformer)
|
||||
offloader = LayerwiseOffloader(blocks, device, pin_cpu_memory, od_config.layerwise_num_gpu_layers)
|
||||
setattr(dit_module, "_layerwise_offloader", offloader)
|
||||
|
||||
logger.info(
|
||||
f"Layerwise offloading enabled on {len(blocks)} layers (blocks), "
|
||||
f"with {od_config.layerwise_num_gpu_layers} kept on device"
|
||||
)
|
||||
@@ -0,0 +1,77 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import torch
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
from .base import OffloadBackend, OffloadConfig, OffloadStrategy
|
||||
from .layerwise_backend import LayerWiseOffloadBackend
|
||||
from .sequential_backend import (
|
||||
ModelLevelOffloadBackend,
|
||||
apply_sequential_offload,
|
||||
remove_sequential_offload,
|
||||
)
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
__all__ = [
|
||||
"OffloadBackend",
|
||||
"OffloadConfig",
|
||||
"OffloadStrategy",
|
||||
"LayerWiseOffloadBackend",
|
||||
"ModelLevelOffloadBackend",
|
||||
"apply_sequential_offload",
|
||||
"remove_sequential_offload",
|
||||
"get_offload_backend",
|
||||
]
|
||||
|
||||
|
||||
def get_offload_backend(
|
||||
od_config: OmniDiffusionConfig,
|
||||
device: torch.device | None = None,
|
||||
) -> OffloadBackend | None:
|
||||
"""Create appropriate offload backend based on configuration.
|
||||
|
||||
Args:
|
||||
od_config: OmniDiffusionConfig with offload settings
|
||||
device: Target device (auto-detected if None)
|
||||
|
||||
Returns:
|
||||
OffloadBackend instance or None if offloading disabled
|
||||
|
||||
Example:
|
||||
>>> backend = get_offload_backend(od_config, device=torch.device("cuda:0"))
|
||||
>>> if backend:
|
||||
... backend.enable(pipeline)
|
||||
"""
|
||||
# Extract and validate configuration
|
||||
config = OffloadConfig.from_od_config(od_config)
|
||||
|
||||
# Return None if no offloading requested
|
||||
if config.strategy == OffloadStrategy.NONE:
|
||||
return None
|
||||
|
||||
# Validate platform (CUDA required for now)
|
||||
if not current_omni_platform.is_cuda() or current_omni_platform.get_device_count() < 1:
|
||||
logger.warning("CPU offloading requires CUDA devices. Skipping offloading.")
|
||||
return None
|
||||
|
||||
# Detect device if not provided
|
||||
if device is None:
|
||||
try:
|
||||
device = current_omni_platform.get_torch_device()
|
||||
except (NotImplementedError, AttributeError) as exc:
|
||||
logger.error("Failed to detect device: %s. Skipping offloading.", exc)
|
||||
return None
|
||||
|
||||
# Create appropriate backend
|
||||
if config.strategy == OffloadStrategy.MODEL_LEVEL:
|
||||
return ModelLevelOffloadBackend(config, device)
|
||||
elif config.strategy == OffloadStrategy.LAYER_WISE:
|
||||
return LayerWiseOffloadBackend(config, device)
|
||||
else:
|
||||
logger.error("Unknown offload strategy: %s", config.strategy)
|
||||
return None
|
||||
@@ -0,0 +1,94 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.data import OmniDiffusionConfig
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class OffloadStrategy(Enum):
|
||||
NONE = "none"
|
||||
MODEL_LEVEL = "model_level" # Sequential offloading between DiT and encoders
|
||||
LAYER_WISE = "layer_wise" # Block-level
|
||||
|
||||
|
||||
@dataclass
|
||||
class OffloadConfig:
|
||||
strategy: OffloadStrategy
|
||||
pin_cpu_memory: bool = True
|
||||
|
||||
@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.
|
||||
|
||||
Args:
|
||||
od_config: OmniDiffusionConfig with offload settings
|
||||
|
||||
Returns:
|
||||
OffloadConfig with validated settings
|
||||
"""
|
||||
enable_cpu_offload = getattr(od_config, "enable_cpu_offload", False)
|
||||
enable_layerwise_offload = getattr(od_config, "enable_layerwise_offload", False)
|
||||
pin_cpu_memory = getattr(od_config, "pin_cpu_memory", True)
|
||||
|
||||
# Determine strategy (mutual exclusion, layer-wise takes priority)
|
||||
if enable_layerwise_offload:
|
||||
strategy = OffloadStrategy.LAYER_WISE
|
||||
if enable_cpu_offload:
|
||||
logger.info(
|
||||
"Both model-level and layer-wise offloading enabled. "
|
||||
"Layer-wise takes priority, disabling model-level offloading."
|
||||
)
|
||||
elif enable_cpu_offload:
|
||||
strategy = OffloadStrategy.MODEL_LEVEL
|
||||
else:
|
||||
strategy = OffloadStrategy.NONE
|
||||
|
||||
return cls(
|
||||
strategy=strategy,
|
||||
pin_cpu_memory=pin_cpu_memory,
|
||||
)
|
||||
|
||||
|
||||
class OffloadBackend(ABC):
|
||||
"""Base class for CPU offload backends"""
|
||||
|
||||
def __init__(self, config: OffloadConfig, device: torch.device):
|
||||
self.config = config
|
||||
self.device = device
|
||||
self.enabled = False
|
||||
|
||||
@abstractmethod
|
||||
def enable(self, pipeline: nn.Module) -> None:
|
||||
"""Enable offloading on the pipeline.
|
||||
|
||||
Discovers modules, moves them to appropriate devices, and
|
||||
registers forward hooks for swapping/prefetching.
|
||||
|
||||
Args:
|
||||
pipeline: Diffusion pipeline model (e.g., Wan22Pipeline)
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
def disable(self) -> None:
|
||||
"""Disable offloading and cleanup resources.
|
||||
|
||||
Removes all registered hooks. Does NOT move modules back to
|
||||
original devices (caller responsible for that).
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def is_enabled(self) -> bool:
|
||||
return self.enabled
|
||||
@@ -0,0 +1,362 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from itertools import chain
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.hooks import HookRegistry, ModelHook
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
from .base import OffloadBackend, OffloadConfig
|
||||
from .module_collector import ModuleDiscovery
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class LayerwiseOffloadHook(ModelHook):
|
||||
"""Hook for layerwise (transformer-block-wise) CPU offloading.
|
||||
|
||||
The hook instance retains parameters for both the current registered block
|
||||
module and those for the next block, as well as flattened CPU tensors which
|
||||
record the parameters of the current block module, so that these parameters
|
||||
could be re-materialized on device in an overlapping way.
|
||||
This hook should be registered to each of the transformer blocks in DiT
|
||||
module(s) of the target pipeline.
|
||||
|
||||
Based on implementations from:
|
||||
https://github.com/sgl-project/sglang/blob/v0.5.8/python/sglang/multimodal_gen/runtime/utils/layerwise_offload.py
|
||||
"""
|
||||
|
||||
_HOOK_NAME = "layerwise_offload"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
next_block: nn.Module,
|
||||
device: torch.device,
|
||||
stream: torch.cuda.Stream | None = None,
|
||||
pin_memory: bool = True,
|
||||
):
|
||||
assert isinstance(next_block, nn.Module), "transformer block must be type `torch.nn.Module`"
|
||||
assert current_omni_platform.is_cuda(), "Layerwise offloading is only supported on cuda devices for now"
|
||||
|
||||
self.next_block = next_block
|
||||
self.device = device
|
||||
self.copy_stream = stream or torch.cuda.current_stream()
|
||||
self.pin_memory = pin_memory
|
||||
|
||||
# Per-block synchronization primitive: set after H2D copy completes.
|
||||
self._prefetch_done: torch.cuda.Event | None = None
|
||||
|
||||
self.next_block_parameters: dict[str, nn.Parameter] = {}
|
||||
self.next_block_buffers: dict[str, torch.Tensor] = {}
|
||||
self.dtype_cpu_flattened_weights: dict[torch.dtype, torch.Tensor] = {}
|
||||
self.dtype_metadata: dict[torch.dtype, list[dict[str, Any]]] = {}
|
||||
|
||||
def initialize_hook(self, module: nn.Module) -> nn.Module:
|
||||
# This all happen during the hook instance being registered to hook registry;
|
||||
# the input module is kept intact
|
||||
module = super().initialize_hook(module)
|
||||
|
||||
self.block_parameters: dict[str, nn.Parameter] = dict(module.named_parameters())
|
||||
self.block_buffers: dict[str, torch.Tensor] = dict(module.named_buffers())
|
||||
|
||||
self.next_block_parameters: dict[str, nn.Parameter] = dict(self.next_block.named_parameters())
|
||||
self.next_block_buffers: dict[str, torch.Tensor] = dict(self.next_block.named_buffers())
|
||||
|
||||
# Pre-allocate gpu tensors in a flattened way
|
||||
self.dtype_cpu_flattened_weights, self.dtype_metadata = LayerwiseOffloadHook._to_cpu(
|
||||
self.next_block_parameters, self.next_block_buffers, self.device, self.pin_memory
|
||||
)
|
||||
|
||||
return module
|
||||
|
||||
@staticmethod
|
||||
def _to_cpu(
|
||||
params: dict[str, nn.Parameter],
|
||||
bufs: dict[str, torch.Tensor],
|
||||
device: torch.device,
|
||||
pin_memory: bool = True,
|
||||
) -> tuple[dict[torch.dtype, torch.Tensor], dict[torch.dtype, list[dict[str, Any]]]]:
|
||||
"""Helper method to move block parameters and buffers to CPU, flattening by dtype.
|
||||
|
||||
Consolidates parameters and buffers into contiguous CPU tensors grouped by dtype
|
||||
for GPU transfers. Replaces original tensors with empty placeholders.
|
||||
|
||||
Returns:
|
||||
Tuple of
|
||||
flattened CPU tensors by dtype,
|
||||
metadata for reconstruction by dtype
|
||||
"""
|
||||
dtype_grouped_weights: dict[torch.dtype, dict[str, torch.Tensor]] = {}
|
||||
dtype_cpu_flattened_weights: dict[torch.dtype, torch.Tensor] = {}
|
||||
# NOTE: order does matter
|
||||
dtype_metadata: dict[torch.dtype, list[dict[str, Any]]] = {}
|
||||
|
||||
for name, param_or_buf in chain(params.items(), bufs.items()):
|
||||
dtype = param_or_buf.dtype
|
||||
if dtype not in dtype_grouped_weights:
|
||||
dtype_grouped_weights[dtype] = {}
|
||||
dtype_grouped_weights[dtype][name] = param_or_buf
|
||||
|
||||
for dtype, name2weights in dtype_grouped_weights.items():
|
||||
# total # of parameters + buffers
|
||||
total_numel = sum(t.numel() for _, t in name2weights.items())
|
||||
cpu_tensor = torch.empty(total_numel, dtype=dtype, device="cpu", pin_memory=pin_memory)
|
||||
|
||||
current_offset = 0
|
||||
for name, param_or_buf in name2weights.items():
|
||||
numel = param_or_buf.numel()
|
||||
cpu_tensor[current_offset : current_offset + numel].copy_(param_or_buf.flatten())
|
||||
if dtype not in dtype_metadata:
|
||||
dtype_metadata[dtype] = []
|
||||
dtype_metadata[dtype].append(
|
||||
{
|
||||
"name": name,
|
||||
"offset": current_offset,
|
||||
"numel": numel,
|
||||
"shape": param_or_buf.shape,
|
||||
}
|
||||
)
|
||||
|
||||
param_or_buf.data = torch.empty((), device=device, dtype=dtype)
|
||||
current_offset += numel
|
||||
|
||||
dtype_cpu_flattened_weights[dtype] = cpu_tensor
|
||||
|
||||
return dtype_cpu_flattened_weights, dtype_metadata
|
||||
|
||||
@torch.compiler.disable
|
||||
def prefetch_layer(self, non_blocking: bool = True) -> None:
|
||||
"""Copy layer weights from CPU -> GPU.
|
||||
|
||||
Pre-fetch target block in an asynchronous way with compute - memory copy overlap,
|
||||
with non_blocking set to True.
|
||||
"""
|
||||
self.copy_stream.wait_stream(torch.cuda.current_stream())
|
||||
|
||||
layer_params = self.next_block_parameters
|
||||
layer_bufs = self.next_block_buffers
|
||||
|
||||
evt = torch.cuda.Event()
|
||||
gpu_weights: dict[torch.dtype, torch.Tensor] = {}
|
||||
|
||||
with torch.cuda.stream(self.copy_stream):
|
||||
for dtype, cpu_weight in self.dtype_cpu_flattened_weights.items():
|
||||
gpu_weight = torch.empty(cpu_weight.shape, dtype=dtype, device=self.device)
|
||||
gpu_weight.copy_(cpu_weight, non_blocking=non_blocking)
|
||||
gpu_weights[dtype] = gpu_weight
|
||||
|
||||
evt.record(self.copy_stream)
|
||||
|
||||
for dtype, ordered_metadata in self.dtype_metadata.items():
|
||||
# ordered_metadata: list[dict[str, Any]]
|
||||
gpu_weight = gpu_weights[dtype]
|
||||
|
||||
for metadata in ordered_metadata:
|
||||
target_name = metadata["name"]
|
||||
target_param_or_buf = (
|
||||
layer_params[target_name] if target_name in layer_params else layer_bufs[target_name]
|
||||
)
|
||||
|
||||
target_param_or_buf.data = gpu_weight[metadata["offset"] : metadata["offset"] + metadata["numel"]].view(
|
||||
metadata["shape"]
|
||||
)
|
||||
|
||||
self._prefetch_done = evt
|
||||
|
||||
@torch.compiler.disable
|
||||
def offload_layer(self) -> None:
|
||||
"""Free GPU memory for layer by replacing tensors with empty placeholders.
|
||||
This function does not actually offload weights from GPU back to CPU.
|
||||
"""
|
||||
evt = self._prefetch_done
|
||||
if evt is not None:
|
||||
torch.cuda.current_stream().wait_event(evt)
|
||||
|
||||
self._prefetch_done = None
|
||||
|
||||
# free GPU residency
|
||||
for _, param in self.block_parameters.items():
|
||||
param.data = torch.empty((), device=self.device, dtype=param.dtype)
|
||||
for _, buf in self.block_buffers.items():
|
||||
buf.data = torch.empty((), device=self.device, dtype=buf.dtype)
|
||||
|
||||
def pre_forward(self, module: nn.Module, *args: Any, **kwargs: Any) -> tuple[tuple, dict]:
|
||||
self.prefetch_layer(non_blocking=True)
|
||||
|
||||
return args, kwargs
|
||||
|
||||
def post_forward(self, module: nn.Module, output: Any) -> Any:
|
||||
self.offload_layer()
|
||||
|
||||
return output
|
||||
|
||||
|
||||
def apply_block_hook(
|
||||
module: nn.Module,
|
||||
next_block: nn.Module,
|
||||
device: torch.device,
|
||||
stream: torch.cuda.Stream | None = None,
|
||||
pin_memory: bool = True,
|
||||
) -> LayerwiseOffloadHook:
|
||||
registry = HookRegistry.get_or_create(module)
|
||||
hook = LayerwiseOffloadHook(next_block, device, stream, pin_memory)
|
||||
registry.register_hook(LayerwiseOffloadHook._HOOK_NAME, hook)
|
||||
|
||||
return hook
|
||||
|
||||
|
||||
def remove_block_hook(module: nn.Module) -> None:
|
||||
registry: HookRegistry | None = getattr(module, "_hook_registry", None)
|
||||
if registry is not None:
|
||||
registry.remove_hook(LayerwiseOffloadHook._HOOK_NAME)
|
||||
logger.debug("Removed offload hook from %s", module.__class__.__name__)
|
||||
|
||||
|
||||
class LayerWiseOffloadBackend(OffloadBackend):
|
||||
"""Layer-wise (block-level) offloading backend.
|
||||
|
||||
Implements sliding window offloading where only a small number of transformer
|
||||
blocks reside on GPU at a time. Blocks are prefetched asynchronously while
|
||||
previous blocks compute, and freed after use.
|
||||
"""
|
||||
|
||||
def __init__(self, config: OffloadConfig, device: torch.device):
|
||||
super().__init__(config, device)
|
||||
|
||||
self.copy_stream = torch.cuda.Stream()
|
||||
self._blocks: list[list[nn.Module]] = []
|
||||
|
||||
def enable(self, pipeline: nn.Module) -> None:
|
||||
if self.enabled:
|
||||
logger.warning("LayerWiseOffloadBackend already enabled")
|
||||
return
|
||||
|
||||
modules = ModuleDiscovery.discover(pipeline)
|
||||
if not modules.dits:
|
||||
logger.warning("No DiT/transformer modules found, skipping layer-wise offloading")
|
||||
return
|
||||
|
||||
# Move encoders to GPU (they stay resident)
|
||||
for enc in modules.encoders:
|
||||
enc.to(self.device)
|
||||
|
||||
# Move VAE to GPU if available
|
||||
if modules.vae is not None:
|
||||
try:
|
||||
modules.vae.to(self.device, non_blocking=True)
|
||||
except Exception as exc:
|
||||
logger.debug("Failed to move VAE to GPU: %s", exc)
|
||||
|
||||
logger.info("Applying layer-wise offloading on %s", modules.dit_names)
|
||||
|
||||
# Apply block-wise offloading hook for each of the blocks in DiT model(s)
|
||||
# Note that there might exist multiple DiT models in specific pipelines
|
||||
for i, dit_module in enumerate(modules.dits):
|
||||
dit_name = modules.dit_names[i]
|
||||
logger.info(f"Applying hooks on {dit_name} ({dit_module.__class__.__name__})")
|
||||
|
||||
blocks_attr_name = LayerWiseOffloadBackend.get_blocks_attr_name(dit_module)
|
||||
blocks = LayerWiseOffloadBackend.get_blocks_from_dit(dit_module)
|
||||
|
||||
if not blocks_attr_name or not blocks:
|
||||
logger.warning(
|
||||
"Target layers (blocks) not found. Skipping offloading on %s (%s)",
|
||||
dit_name,
|
||||
dit_module.__class__.__name__,
|
||||
)
|
||||
dit_module.to(self.device)
|
||||
continue
|
||||
|
||||
num_blocks = len(blocks)
|
||||
if num_blocks <= 1:
|
||||
logger.warning(
|
||||
"#Target layers (blocks) <= 1. Skipping offloading on %s (%s)",
|
||||
dit_name,
|
||||
dit_module.__class__.__name__,
|
||||
)
|
||||
dit_module.to(self.device)
|
||||
continue
|
||||
|
||||
# Move non-block modules to GPU (they stay resident)
|
||||
for name, m in dit_module.named_children():
|
||||
if name == blocks_attr_name:
|
||||
logger.debug(f"Skipped blocks module {name}")
|
||||
continue
|
||||
m.to(self.device)
|
||||
logger.debug(f"Moved {name} to device {self.device}")
|
||||
|
||||
# Pre-fetch the first layer by manually calling the hook function on the last layer;
|
||||
# For subsequent requests, the first layer/block will be pre-fetched
|
||||
# during the last layer compute of the previous request.
|
||||
last_block, first_block = blocks[-1], blocks[0]
|
||||
hook = apply_block_hook(last_block, first_block, self.device, self.copy_stream, self.config.pin_cpu_memory)
|
||||
hook.prefetch_layer(non_blocking=False)
|
||||
|
||||
# Register hook for each of blocks
|
||||
for i, block in enumerate(blocks[:-1]):
|
||||
next_block = blocks[(i + 1) % num_blocks]
|
||||
apply_block_hook(block, next_block, self.device, self.copy_stream, self.config.pin_cpu_memory)
|
||||
|
||||
logger.info(f"Layer-wise offloading enabled on {num_blocks} layers (blocks)")
|
||||
|
||||
# Track hooked blocks for cleanup
|
||||
self._blocks.append(blocks)
|
||||
|
||||
if len(self._blocks) > 0 and len(self._blocks[0]) > 0:
|
||||
self.enabled = True
|
||||
|
||||
def disable(self) -> None:
|
||||
if not self.enabled:
|
||||
return
|
||||
|
||||
for blocks in self._blocks:
|
||||
for block in blocks:
|
||||
remove_block_hook(block)
|
||||
|
||||
self._blocks.clear()
|
||||
self.enabled = False
|
||||
logger.info("Layer-wise offloading disabled")
|
||||
|
||||
@staticmethod
|
||||
def get_blocks_attr_name(model: nn.Module) -> str | None:
|
||||
"""Retrieve blocks attribute name from provided DiT model"""
|
||||
return getattr(model.__class__, "_layerwise_offload_blocks_attr", None)
|
||||
|
||||
@staticmethod
|
||||
def set_blocks_attr_name(model: nn.Module, name: str) -> None:
|
||||
if not hasattr(model.__class__, "_layerwise_offload_blocks_attr"):
|
||||
setattr(model.__class__, "_layerwise_offload_blocks_attr", name)
|
||||
|
||||
@staticmethod
|
||||
def get_blocks_from_dit(model: nn.Module) -> list[nn.Module]:
|
||||
"""
|
||||
Retrieve a list of blocks from provided DiT model. Blocks attribute name
|
||||
are found by `_layerwise_offload_blocks_attr` set to DiT models. For example,
|
||||
|
||||
```
|
||||
class WanTransformer3DModel(nn.Module):
|
||||
_layerwise_offload_blocks_attr = "blocks"
|
||||
```
|
||||
"""
|
||||
blocks_attr_name = LayerWiseOffloadBackend.get_blocks_attr_name(model)
|
||||
if blocks_attr_name is None:
|
||||
logger.warning(
|
||||
f"No _layerwise_offload_blocks_attr defined for {model.__class__.__name__}, "
|
||||
"skipping layerwise offloading"
|
||||
)
|
||||
return []
|
||||
|
||||
_blocks = getattr(model, blocks_attr_name, None)
|
||||
if _blocks is None:
|
||||
logger.warning(
|
||||
f"Blocks (layers) '{blocks_attr_name}' not found on {model.__class__.__name__}, "
|
||||
"skipping layerwise offloading"
|
||||
)
|
||||
return []
|
||||
|
||||
return list(_blocks)
|
||||
@@ -0,0 +1,80 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from torch import nn
|
||||
from vllm.logger import init_logger
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class PipelineModules:
|
||||
dits: list[nn.Module]
|
||||
dit_names: list[str]
|
||||
encoders: list[nn.Module]
|
||||
encoder_names: list[str]
|
||||
vae: nn.Module | None = None
|
||||
|
||||
|
||||
class ModuleDiscovery:
|
||||
"""Discovers pipeline components for offloading"""
|
||||
|
||||
DIT_ATTRS = ["transformer", "transformer_2", "dit", "language_model", "transformer_blocks"]
|
||||
ENCODER_ATTRS = ["text_encoder", "text_encoder_2", "text_encoder_3", "image_encoder"]
|
||||
VAE_ATTRS = ["vae"]
|
||||
|
||||
@staticmethod
|
||||
def discover(pipeline: nn.Module) -> PipelineModules:
|
||||
"""Discover DiT, encoder, and VAE modules from pipeline.
|
||||
|
||||
Args:
|
||||
pipeline: Diffusion pipeline model
|
||||
|
||||
Returns:
|
||||
PipelineModules with lists of discovered modules and names
|
||||
"""
|
||||
# Collect DiT/transformer modules
|
||||
dit_modules: list[nn.Module] = []
|
||||
dit_names: list[str] = []
|
||||
for attr in ModuleDiscovery.DIT_ATTRS:
|
||||
if not hasattr(pipeline, attr):
|
||||
continue
|
||||
module_obj = getattr(pipeline, attr)
|
||||
if module_obj is None:
|
||||
continue
|
||||
|
||||
if not isinstance(module_obj, nn.Module):
|
||||
logger.warning(f"Expected {attr} to be nn.Module, got {type(module_obj)!r}")
|
||||
continue
|
||||
|
||||
if module_obj in dit_modules:
|
||||
continue
|
||||
|
||||
dit_modules.append(module_obj)
|
||||
dit_names.append(attr)
|
||||
|
||||
# Collect all encoders
|
||||
encoders: list[nn.Module] = []
|
||||
encoder_names: list[str] = []
|
||||
for attr in ModuleDiscovery.ENCODER_ATTRS:
|
||||
if hasattr(pipeline, attr) and getattr(pipeline, attr) is not None:
|
||||
encoders.append(getattr(pipeline, attr))
|
||||
encoder_names.append(attr)
|
||||
|
||||
# Collect VAE
|
||||
vae = None
|
||||
for attr in ModuleDiscovery.VAE_ATTRS:
|
||||
module = getattr(pipeline, attr, None)
|
||||
if module is not None:
|
||||
vae = module
|
||||
break
|
||||
|
||||
return PipelineModules(
|
||||
dits=dit_modules,
|
||||
dit_names=dit_names,
|
||||
encoders=encoders,
|
||||
encoder_names=encoder_names,
|
||||
vae=vae,
|
||||
)
|
||||
@@ -0,0 +1,227 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.hooks import HookRegistry, ModelHook
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
from .base import OffloadBackend, OffloadConfig
|
||||
from .module_collector import ModuleDiscovery
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class SequentialOffloadHook(ModelHook):
|
||||
"""Hook for sequential offloading with mutual exclusion on encoder and DiT modules.
|
||||
|
||||
To be used as a model-level (or "component-level") of CPU offloading method;
|
||||
When a module's forward is called, this hook offloads target modules to CPU
|
||||
and loads the current module to GPU.
|
||||
"""
|
||||
|
||||
_HOOK_NAME = "sequential_offload"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
offload_targets: list[nn.Module],
|
||||
device: torch.device,
|
||||
pin_memory: bool = True,
|
||||
):
|
||||
# Modules to offload to CPU before this module runs
|
||||
self.offload_targets = offload_targets
|
||||
self.device = device
|
||||
self.pin_memory = pin_memory
|
||||
|
||||
def _to_cpu(self, module: nn.Module) -> None:
|
||||
"""Move module to CPU."""
|
||||
try:
|
||||
param = next(module.parameters())
|
||||
except StopIteration:
|
||||
return
|
||||
|
||||
previous_device = param.device
|
||||
# Skip if already on CPU
|
||||
if previous_device.type == "cpu":
|
||||
return
|
||||
|
||||
module.to("cpu")
|
||||
torch.cuda.empty_cache()
|
||||
|
||||
if self.pin_memory:
|
||||
for p in module.parameters():
|
||||
if p.data.device.type == "cpu" and not p.data.is_pinned():
|
||||
p.data = p.data.pin_memory()
|
||||
|
||||
def _to_gpu(self, module: nn.Module) -> None:
|
||||
"""Move module to GPU."""
|
||||
try:
|
||||
# Skip if already on target device
|
||||
if next(module.parameters()).device == self.device:
|
||||
return
|
||||
except StopIteration:
|
||||
return
|
||||
|
||||
module.to(self.device)
|
||||
|
||||
def pre_forward(self, module: nn.Module, *args, **kwargs) -> tuple[tuple, dict]:
|
||||
# Offload target modules to CPU
|
||||
for target in self.offload_targets:
|
||||
self._to_cpu(target)
|
||||
|
||||
# Load current module to GPU
|
||||
self._to_gpu(module)
|
||||
current_omni_platform.synchronize()
|
||||
|
||||
logger.debug(
|
||||
"Swapped: %s -> CPU, %s -> GPU",
|
||||
[t.__class__.__name__ for t in self.offload_targets],
|
||||
module.__class__.__name__,
|
||||
)
|
||||
|
||||
return args, kwargs
|
||||
|
||||
|
||||
def apply_sequential_offload(
|
||||
dit_modules: list[nn.Module],
|
||||
encoder_modules: list[nn.Module],
|
||||
device: torch.device,
|
||||
pin_memory: bool = True,
|
||||
) -> None:
|
||||
"""Apply sequential offloading hooks to DiT and encoder modules.
|
||||
|
||||
Registers hooks on modules to implement mutual-exclusion GPU allocation.
|
||||
- Before DiT runs, encoders are offloaded to CPU.
|
||||
- Before encoders run, DiT is offloaded to CPU.
|
||||
|
||||
Args:
|
||||
dit_modules: DiT/transformer modules to register hooks on
|
||||
encoder_modules: Encoder modules to register hooks on
|
||||
device: Target GPU device for loading
|
||||
pin_memory: Whether to pin CPU memory for faster transfers
|
||||
|
||||
Example:
|
||||
>>> apply_sequential_offload(
|
||||
... dit_modules=[pipeline.transformer],
|
||||
... encoder_modules=[pipeline.text_encoder, pipeline.vae],
|
||||
... device=torch.device("cuda:0"),
|
||||
... )
|
||||
>>> # Modules of pipeline now automatically swap between CPU and GPU
|
||||
"""
|
||||
# Register hooks on DiT modules (offload encoders when DiT runs)
|
||||
for dit_mod in dit_modules:
|
||||
registry = HookRegistry.get_or_create(dit_mod)
|
||||
hook = SequentialOffloadHook(
|
||||
offload_targets=encoder_modules,
|
||||
device=device,
|
||||
pin_memory=pin_memory,
|
||||
)
|
||||
registry.register_hook(SequentialOffloadHook._HOOK_NAME, hook)
|
||||
logger.debug("Registered offload hook for %s", dit_mod.__class__.__name__)
|
||||
|
||||
# Register hooks on encoders (offload DiTs when encoder runs)
|
||||
for enc in encoder_modules:
|
||||
registry = HookRegistry.get_or_create(enc)
|
||||
hook = SequentialOffloadHook(
|
||||
offload_targets=dit_modules,
|
||||
device=device,
|
||||
pin_memory=pin_memory,
|
||||
)
|
||||
registry.register_hook(SequentialOffloadHook._HOOK_NAME, hook)
|
||||
logger.debug("Registered offload hook for %s", enc.__class__.__name__)
|
||||
|
||||
|
||||
def remove_sequential_offload(modules: list[nn.Module]) -> None:
|
||||
"""Remove sequential offloading hooks from modules.
|
||||
|
||||
Args:
|
||||
modules: Modules to remove hooks from
|
||||
|
||||
Example:
|
||||
>>> all_modules = [*dit_modules, *encoder_modules]
|
||||
>>> remove_sequential_offload(all_modules)
|
||||
"""
|
||||
for module in modules:
|
||||
registry: HookRegistry | None = getattr(module, "_hook_registry", None)
|
||||
if registry is not None:
|
||||
registry.remove_hook(SequentialOffloadHook._HOOK_NAME)
|
||||
logger.debug("Removed offload hook from %s", module.__class__.__name__)
|
||||
|
||||
|
||||
class ModelLevelOffloadBackend(OffloadBackend):
|
||||
"""Model-level (sequential) offloading backend.
|
||||
|
||||
Uses SequentialOffloadHook registered via HookRegistry for automatic module swapping.
|
||||
"""
|
||||
|
||||
def __init__(self, config: OffloadConfig, device: torch.device):
|
||||
super().__init__(config, device)
|
||||
self._offload_modules: list[nn.Module] = [] # Track modules with hooks
|
||||
|
||||
def enable(self, pipeline: nn.Module) -> None:
|
||||
if self.enabled:
|
||||
logger.warning("ModelLevelOffloadBackend already enabled")
|
||||
return
|
||||
|
||||
modules = ModuleDiscovery.discover(pipeline)
|
||||
if not modules.dits:
|
||||
logger.warning("No DiT/transformer modules found, skipping model-level offloading")
|
||||
return
|
||||
if not modules.encoders:
|
||||
logger.warning("No encoder modules found, skipping model-level offloading")
|
||||
return
|
||||
|
||||
# Move encoders to GPU
|
||||
for enc in modules.encoders:
|
||||
enc.to(self.device)
|
||||
|
||||
# Move VAE to GPU if available
|
||||
if modules.vae is not None:
|
||||
try:
|
||||
modules.vae.to(self.device, non_blocking=True)
|
||||
except Exception as exc:
|
||||
logger.debug("Failed to move VAE to GPU: %s", exc)
|
||||
|
||||
# Initial state: keep DiT modules on CPU (encoders typically run first)
|
||||
# TODO: This part seems to be unnecessary, remove it after testing
|
||||
# for dit_mod in modules.dits:
|
||||
# dit_mod.to("cpu")
|
||||
|
||||
# torch.cuda.empty_cache()
|
||||
|
||||
# if self.config.pin_cpu_memory:
|
||||
# for dit_mod in modules.dits:
|
||||
# for p in dit_mod.parameters():
|
||||
# if p.data.device.type == "cpu" and not p.data.is_pinned():
|
||||
# p.data = p.data.pin_memory()
|
||||
|
||||
# Apply sequential offloading hooks
|
||||
apply_sequential_offload(
|
||||
dit_modules=modules.dits,
|
||||
encoder_modules=modules.encoders,
|
||||
device=self.device,
|
||||
pin_memory=self.config.pin_cpu_memory,
|
||||
)
|
||||
|
||||
# Track modules for cleanup
|
||||
self._offload_modules = [*modules.dits, *modules.encoders]
|
||||
|
||||
self.enabled = True
|
||||
|
||||
logger.info(
|
||||
"Model-level offloading enabled: %s <-> %s (mutual exclusion)",
|
||||
", ".join(modules.dit_names),
|
||||
", ".join(modules.encoder_names),
|
||||
)
|
||||
|
||||
def disable(self) -> None:
|
||||
if not self.enabled:
|
||||
return
|
||||
|
||||
remove_sequential_offload(self._offload_modules)
|
||||
|
||||
self._offload_modules.clear()
|
||||
self.enabled = False
|
||||
logger.info("Model-level offloading disabled")
|
||||
@@ -26,7 +26,7 @@ from vllm_omni.diffusion.compile import regionally_compile
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.forward_context import set_forward_context
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.offload import apply_offload_hooks
|
||||
from vllm_omni.diffusion.offloader import get_offload_backend
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.distributed.omni_connectors.kv_transfer_manager import OmniKVTransferManager
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
@@ -62,6 +62,7 @@ class DiffusionModelRunner:
|
||||
self.device = device
|
||||
self.pipeline = None
|
||||
self.cache_backend = None
|
||||
self.offload_backend = None
|
||||
|
||||
# Initialize KV cache manager for connector management
|
||||
self.kv_transfer_manager = OmniKVTransferManager.from_od_config(od_config)
|
||||
@@ -69,6 +70,8 @@ class DiffusionModelRunner:
|
||||
def load_model(
|
||||
self,
|
||||
memory_pool_context_fn: callable | None = None,
|
||||
load_format: str | None = None,
|
||||
custom_pipeline_name: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
Load the diffusion model, apply compilation and offloading.
|
||||
@@ -76,7 +79,17 @@ class DiffusionModelRunner:
|
||||
Args:
|
||||
memory_pool_context_fn: Optional function that returns a context manager
|
||||
for memory pool allocation (used for sleep mode).
|
||||
load_format: Format for loading model weights. Supported formats:
|
||||
- "default" (default): Automatically detect and use the default format based on configuration
|
||||
- "custom_pipeline": Init model from a custom pipeline class specified by `custom_pipeline_name`
|
||||
- "dummy": Skip actual weight loading, useful for testing and custom pipelines that
|
||||
don't require default weights.
|
||||
custom_pipeline_name: Optional custom pipeline class name to use.
|
||||
"""
|
||||
|
||||
if load_format == "dummy":
|
||||
return
|
||||
|
||||
load_device = (
|
||||
"cpu" if self.od_config.enable_cpu_offload or self.od_config.enable_layerwise_offload else str(self.device)
|
||||
)
|
||||
@@ -96,6 +109,8 @@ class DiffusionModelRunner:
|
||||
self.pipeline = model_loader.load_model(
|
||||
od_config=self.od_config,
|
||||
load_device=load_device,
|
||||
load_format=load_format,
|
||||
custom_pipeline_name=custom_pipeline_name,
|
||||
)
|
||||
time_after_load = time.perf_counter()
|
||||
|
||||
@@ -107,8 +122,10 @@ class DiffusionModelRunner:
|
||||
logger.info("Model runner: Model loaded successfully.")
|
||||
|
||||
# Apply CPU offloading
|
||||
if self.od_config.enable_cpu_offload or self.od_config.enable_layerwise_offload:
|
||||
apply_offload_hooks(self.pipeline, self.od_config, device=self.device)
|
||||
self.offload_backend = get_offload_backend(self.od_config, device=self.device)
|
||||
if self.offload_backend is not None:
|
||||
logger.info(f" Enabling offloader backend: {self.offload_backend.__class__.__name__}")
|
||||
self.offload_backend.enable(self.pipeline)
|
||||
|
||||
# Apply torch.compile if not in eager mode
|
||||
if not self.od_config.enforce_eager:
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
|
||||
"""
|
||||
Diffusion Worker for vLLM-Omni.
|
||||
|
||||
@@ -7,15 +8,19 @@ Handles GPU infrastructure initialization and delegates model operations
|
||||
to DiffusionModelRunner.
|
||||
"""
|
||||
|
||||
import gc
|
||||
import multiprocessing as mp
|
||||
import os
|
||||
from collections.abc import Iterable
|
||||
from contextlib import AbstractContextManager, nullcontext
|
||||
from typing import Any
|
||||
|
||||
import torch
|
||||
import zmq
|
||||
from vllm.config import CompilationConfig, VllmConfig, set_current_vllm_config
|
||||
from vllm.distributed.device_communicators.shm_broadcast import MessageQueue
|
||||
from vllm.logger import init_logger
|
||||
from vllm.utils.import_utils import resolve_obj_by_qualname
|
||||
from vllm.utils.mem_utils import GiB_bytes
|
||||
from vllm.v1.worker.workspace import init_workspace_manager
|
||||
|
||||
@@ -35,6 +40,7 @@ from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.diffusion.worker.diffusion_model_runner import DiffusionModelRunner
|
||||
from vllm_omni.lora.request import LoRARequest
|
||||
from vllm_omni.platforms import current_omni_platform
|
||||
from vllm_omni.worker.gpu_memory_utils import get_process_gpu_memory
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
@@ -67,6 +73,15 @@ class DiffusionWorker:
|
||||
self._sleep_saved_buffers: dict[str, torch.Tensor] = {}
|
||||
self.lora_manager: DiffusionLoRAManager | None = None
|
||||
self.init_device()
|
||||
# Create model runner
|
||||
self.model_runner = DiffusionModelRunner(
|
||||
vllm_config=self.vllm_config,
|
||||
od_config=self.od_config,
|
||||
device=self.device,
|
||||
)
|
||||
self.load_model(load_format=self.od_config.diffusion_load_format)
|
||||
self.init_lora_manager()
|
||||
logger.info(f"Worker {self.rank}: Initialization complete.")
|
||||
|
||||
def init_device(self) -> None:
|
||||
"""Initialize the device and distributed environment."""
|
||||
@@ -110,16 +125,30 @@ class DiffusionWorker:
|
||||
)
|
||||
init_workspace_manager(self.device)
|
||||
|
||||
# Create model runner and load model
|
||||
self.model_runner = DiffusionModelRunner(
|
||||
vllm_config=self.vllm_config,
|
||||
od_config=self.od_config,
|
||||
device=self.device,
|
||||
)
|
||||
def load_model(self, load_format: str = "default", custom_pipeline_name: str | None = None) -> None:
|
||||
"""Load the diffusion model using DiffusionModelRunner."""
|
||||
with (
|
||||
set_forward_context(vllm_config=self.vllm_config, omni_diffusion_config=self.od_config),
|
||||
set_current_vllm_config(self.vllm_config),
|
||||
):
|
||||
self.model_runner.load_model(
|
||||
memory_pool_context_fn=self._maybe_get_memory_pool_context,
|
||||
load_format=load_format,
|
||||
custom_pipeline_name=custom_pipeline_name,
|
||||
)
|
||||
process_memory = get_process_gpu_memory(self.local_rank)
|
||||
if process_memory is not None:
|
||||
logger.info(
|
||||
"Worker %d: Process-scoped GPU memory after model loading: %.2f GiB.",
|
||||
self.rank,
|
||||
process_memory / GiB_bytes,
|
||||
)
|
||||
assert self.model_runner.pipeline is not None
|
||||
|
||||
def init_lora_manager(self) -> None:
|
||||
"""Initialize the LoRA manager for this worker."""
|
||||
if self.model_runner.pipeline is None:
|
||||
return
|
||||
self.lora_manager = DiffusionLoRAManager(
|
||||
pipeline=self.model_runner.pipeline,
|
||||
device=self.device,
|
||||
@@ -128,7 +157,6 @@ class DiffusionWorker:
|
||||
lora_path=self.od_config.lora_path,
|
||||
lora_scale=self.od_config.lora_scale,
|
||||
)
|
||||
logger.info(f"Worker {self.rank}: Initialization complete.")
|
||||
|
||||
def generate(self, request: OmniDiffusionRequest) -> DiffusionOutput:
|
||||
"""Generate output for the given requests."""
|
||||
@@ -182,7 +210,10 @@ class DiffusionWorker:
|
||||
"""
|
||||
from vllm.device_allocator.cumem import CuMemAllocator
|
||||
|
||||
free_bytes_before_sleep = current_omni_platform.get_free_memory()
|
||||
process_memory_before_sleep = get_process_gpu_memory(self.local_rank)
|
||||
free_bytes_before_sleep = None
|
||||
if process_memory_before_sleep is None:
|
||||
free_bytes_before_sleep = current_omni_platform.get_free_memory()
|
||||
|
||||
# Save the buffers before level 2 sleep
|
||||
if level == 2 and self.model_runner is not None:
|
||||
@@ -191,14 +222,23 @@ class DiffusionWorker:
|
||||
|
||||
allocator = CuMemAllocator.get_instance()
|
||||
allocator.sleep(offload_tags=("weights",) if level == 1 else tuple())
|
||||
free_bytes_after_sleep = current_omni_platform.get_free_memory()
|
||||
device_id = self.device.index if self.device.index is not None else 0
|
||||
total = current_omni_platform.get_device_total_memory(device_id)
|
||||
freed_bytes = free_bytes_after_sleep - free_bytes_before_sleep
|
||||
used_bytes = total - free_bytes_after_sleep
|
||||
process_memory_after_sleep = get_process_gpu_memory(self.local_rank)
|
||||
if process_memory_before_sleep is not None and process_memory_after_sleep is not None:
|
||||
freed_bytes = process_memory_before_sleep - process_memory_after_sleep
|
||||
used_bytes = process_memory_after_sleep
|
||||
accounting_scope = "process-scoped"
|
||||
else:
|
||||
free_bytes_after_sleep = current_omni_platform.get_free_memory()
|
||||
assert free_bytes_before_sleep is not None
|
||||
device_id = self.device.index if self.device.index is not None else 0
|
||||
total = current_omni_platform.get_device_total_memory(device_id)
|
||||
freed_bytes = free_bytes_after_sleep - free_bytes_before_sleep
|
||||
used_bytes = total - free_bytes_after_sleep
|
||||
accounting_scope = "device-scoped fallback"
|
||||
assert freed_bytes >= 0, "Memory usage increased after sleeping."
|
||||
logger.info(
|
||||
"Sleep mode freed %.2f GiB memory, %.2f GiB memory is still in use.",
|
||||
"Sleep mode (%s) freed %.2f GiB memory, %.2f GiB memory is still in use.",
|
||||
accounting_scope,
|
||||
freed_bytes / GiB_bytes,
|
||||
used_bytes / GiB_bytes,
|
||||
)
|
||||
@@ -247,6 +287,32 @@ class DiffusionWorker:
|
||||
destroy_distributed_env()
|
||||
|
||||
|
||||
class CustomPipelineWorkerExtension:
|
||||
def re_init_pipeline(self, custom_pipeline_args: dict[str, Any]) -> None:
|
||||
"""
|
||||
Re-initialize the pipeline with custom arguments.
|
||||
|
||||
Args:
|
||||
custom_pipeline_args: Dictionary of arguments for custom pipeline initialization
|
||||
"""
|
||||
|
||||
# Clean up old pipeline
|
||||
if self.model_runner.pipeline is not None:
|
||||
del self.model_runner.pipeline
|
||||
gc.collect()
|
||||
torch.cuda.empty_cache()
|
||||
|
||||
# Get custom pipeline class name
|
||||
custom_pipeline_name = custom_pipeline_args["pipeline_class"]
|
||||
|
||||
# Use the DiffusionWorker's load_model method which handles the forward context
|
||||
self.load_model(
|
||||
load_format="custom_pipeline",
|
||||
custom_pipeline_name=custom_pipeline_name,
|
||||
)
|
||||
self.init_lora_manager()
|
||||
|
||||
|
||||
class WorkerProc:
|
||||
"""Wrapper that runs one Worker in a separate process."""
|
||||
|
||||
@@ -255,8 +321,11 @@ class WorkerProc:
|
||||
od_config: OmniDiffusionConfig,
|
||||
gpu_id: int,
|
||||
broadcast_handle,
|
||||
worker_extension_cls: str | None = None,
|
||||
custom_pipeline_args: dict[str, Any] | None = None,
|
||||
):
|
||||
self.od_config = od_config
|
||||
self.gpu_id = gpu_id
|
||||
|
||||
# Inter-process Communication
|
||||
self.context = zmq.Context(io_threads=2)
|
||||
@@ -274,17 +343,26 @@ class WorkerProc:
|
||||
logger.info(f"Worker {gpu_id} created result MessageQueue")
|
||||
|
||||
assert od_config.master_port is not None
|
||||
self.worker = self._create_worker(gpu_id, od_config)
|
||||
self.gpu_id = gpu_id
|
||||
|
||||
# Create worker using WorkerWrapperBase for extension support
|
||||
self.worker = self._create_worker(gpu_id, od_config, worker_extension_cls, custom_pipeline_args)
|
||||
self._running = True
|
||||
|
||||
def _create_worker(self, gpu_id: int, od_config: OmniDiffusionConfig) -> DiffusionWorker:
|
||||
def _create_worker(
|
||||
self,
|
||||
gpu_id: int,
|
||||
od_config: OmniDiffusionConfig,
|
||||
worker_extension_cls: str | None,
|
||||
custom_pipeline_args: dict[str, Any] | None = None,
|
||||
) -> DiffusionWorker:
|
||||
"""Create a worker instance. Override in subclasses for different worker types."""
|
||||
return DiffusionWorker(
|
||||
local_rank=gpu_id,
|
||||
rank=gpu_id,
|
||||
wrapper = WorkerWrapperBase(
|
||||
gpu_id=gpu_id,
|
||||
od_config=od_config,
|
||||
worker_extension_cls=worker_extension_cls,
|
||||
custom_pipeline_args=custom_pipeline_args,
|
||||
)
|
||||
return wrapper
|
||||
|
||||
def return_result(self, output: DiffusionOutput):
|
||||
"""Reply to client, only on rank 0."""
|
||||
@@ -310,11 +388,8 @@ class WorkerProc:
|
||||
return None, False
|
||||
|
||||
try:
|
||||
if isinstance(method, str):
|
||||
func = getattr(self.worker, method)
|
||||
result = func(*args, **kwargs)
|
||||
else:
|
||||
result = method(self.worker, *args, **kwargs)
|
||||
# Use execute_method from WorkerWrapperBase for consistent method resolution
|
||||
result = self.worker.execute_method(method, *args, **kwargs)
|
||||
return result, should_reply
|
||||
except Exception as e:
|
||||
logger.error(f"Error executing RPC: {e}", exc_info=True)
|
||||
@@ -385,6 +460,8 @@ class WorkerProc:
|
||||
od_config: OmniDiffusionConfig,
|
||||
pipe_writer: mp.connection.Connection,
|
||||
broadcast_handle,
|
||||
worker_extension_cls: str | None = None,
|
||||
custom_pipeline_args: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""Worker initialization and execution loops."""
|
||||
from vllm_omni.plugins import load_omni_general_plugins
|
||||
@@ -394,6 +471,8 @@ class WorkerProc:
|
||||
od_config,
|
||||
gpu_id=rank,
|
||||
broadcast_handle=broadcast_handle,
|
||||
worker_extension_cls=worker_extension_cls,
|
||||
custom_pipeline_args=custom_pipeline_args,
|
||||
)
|
||||
logger.info(f"Worker {rank}: Scheduler loop started.")
|
||||
pipe_writer.send(
|
||||
@@ -404,3 +483,201 @@ class WorkerProc:
|
||||
)
|
||||
worker_proc.worker_busy_loop()
|
||||
logger.info(f"Worker {rank}: Shutdown complete.")
|
||||
|
||||
|
||||
class WorkerWrapperBase:
|
||||
"""
|
||||
Wrapper base class that creates DiffusionWorker with optional worker_extension_cls support.
|
||||
This enables dynamic inheritance for DiffusionWorker to extend with custom functionality.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
gpu_id: int,
|
||||
od_config: OmniDiffusionConfig,
|
||||
base_worker_class: type = DiffusionWorker,
|
||||
worker_extension_cls: str | None = None,
|
||||
custom_pipeline_args: dict[str, Any] | None = None,
|
||||
):
|
||||
"""
|
||||
Initialize WorkerWrapperBase with support for worker extensions.
|
||||
|
||||
Args:
|
||||
gpu_id: GPU device ID
|
||||
od_config: OmniDiffusionConfig configuration
|
||||
worker_extension_cls: Optional qualified name of worker extension class
|
||||
custom_pipeline_args: Optional arguments for custom pipeline initialization
|
||||
"""
|
||||
self.gpu_id = gpu_id
|
||||
self.od_config = od_config
|
||||
self.base_worker_class = base_worker_class
|
||||
self.worker_extension_cls = worker_extension_cls
|
||||
self.custom_pipeline_args = custom_pipeline_args
|
||||
|
||||
# Prepare worker class with extension support
|
||||
worker_class = self._prepare_worker_class()
|
||||
|
||||
# Create the actual worker instance
|
||||
self.worker = worker_class(
|
||||
local_rank=gpu_id,
|
||||
rank=gpu_id,
|
||||
od_config=od_config,
|
||||
)
|
||||
|
||||
# Re-initialize pipeline with custom pipeline if provided
|
||||
if self.custom_pipeline_args is not None:
|
||||
self.worker.re_init_pipeline(self.custom_pipeline_args)
|
||||
|
||||
def _prepare_worker_class(self) -> type:
|
||||
"""
|
||||
Prepare the worker class with optional extension.
|
||||
Dynamically extends GPUWorker with worker_extension_cls if provided.
|
||||
|
||||
Returns:
|
||||
The worker class (potentially extended)
|
||||
"""
|
||||
worker_class = self.base_worker_class
|
||||
|
||||
# If custom_pipeline_args is provided, use CustomPipelineWorkerExtension
|
||||
if self.custom_pipeline_args is not None:
|
||||
# Set worker_extension_cls to CustomPipelineWorkerExtension if not already set
|
||||
if self.worker_extension_cls is None:
|
||||
self.worker_extension_cls = CustomPipelineWorkerExtension
|
||||
|
||||
if self.worker_extension_cls:
|
||||
if isinstance(self.worker_extension_cls, str):
|
||||
worker_extension_cls = resolve_obj_by_qualname(self.worker_extension_cls)
|
||||
else:
|
||||
worker_extension_cls = self.worker_extension_cls
|
||||
extended_calls = []
|
||||
|
||||
if worker_extension_cls not in worker_class.__bases__:
|
||||
# Check for conflicts between worker and extension
|
||||
for attr in dir(worker_extension_cls):
|
||||
if attr.startswith("__"):
|
||||
continue
|
||||
if hasattr(worker_class, attr):
|
||||
logger.warning(
|
||||
f"Worker class {worker_class} already has attribute "
|
||||
f"{attr}, which may conflict with worker extension "
|
||||
f"class {worker_extension_cls}."
|
||||
)
|
||||
if callable(getattr(worker_extension_cls, attr)):
|
||||
extended_calls.append(attr)
|
||||
|
||||
# Dynamically inherit the worker extension class
|
||||
class_name = f"{worker_class.__name__}With{worker_extension_cls.__name__}"
|
||||
worker_class = type(class_name, (worker_extension_cls, worker_class), {})
|
||||
logger.info(
|
||||
"Created extended worker class %s from %s for extended calls %s",
|
||||
class_name,
|
||||
worker_extension_cls,
|
||||
extended_calls,
|
||||
)
|
||||
|
||||
return worker_class
|
||||
|
||||
def generate(self, requests: list[OmniDiffusionRequest]) -> DiffusionOutput:
|
||||
"""
|
||||
Generate output for the given requests.
|
||||
|
||||
Args:
|
||||
requests: List of diffusion requests
|
||||
|
||||
Returns:
|
||||
DiffusionOutput with generated results
|
||||
"""
|
||||
return self.worker.generate(requests)
|
||||
|
||||
def execute_model(self, reqs: list[OmniDiffusionRequest], od_config: OmniDiffusionConfig) -> DiffusionOutput:
|
||||
"""
|
||||
Execute a forward pass.
|
||||
|
||||
Args:
|
||||
reqs: List of diffusion requests
|
||||
od_config: OmniDiffusionConfig configuration
|
||||
|
||||
Returns:
|
||||
DiffusionOutput with generated results
|
||||
"""
|
||||
return self.worker.execute_model(reqs, od_config)
|
||||
|
||||
def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
|
||||
"""
|
||||
Load model weights.
|
||||
|
||||
Args:
|
||||
weights: Iterable of (name, tensor) tuples
|
||||
|
||||
Returns:
|
||||
Set of loaded weight names
|
||||
"""
|
||||
return self.worker.load_weights(weights)
|
||||
|
||||
def sleep(self, level: int = 1) -> bool:
|
||||
"""
|
||||
Put the worker to sleep. The worker should not process any requests.
|
||||
The caller should guarantee that no requests are being processed
|
||||
during the sleep period, before `wake_up` is called.
|
||||
|
||||
Args:
|
||||
level: The sleep level. Level 1 sleep will offload the model
|
||||
weights and discard the kv cache.
|
||||
Currently only support level 1.
|
||||
|
||||
Returns:
|
||||
True on success
|
||||
"""
|
||||
return self.worker.sleep(level)
|
||||
|
||||
def wake_up(self, tags: list[str] | None = None) -> bool:
|
||||
"""
|
||||
Wake up the worker from sleep mode. See the sleep function
|
||||
method for more details.
|
||||
|
||||
Args:
|
||||
tags: An optional list of tags to reallocate the worker memory
|
||||
for specific memory allocations. Values must be in
|
||||
`("weights")`. If None, all memory is reallocated.
|
||||
wake_up should be called with all tags (or None) before the
|
||||
worker is used again.
|
||||
|
||||
Returns:
|
||||
True on success
|
||||
"""
|
||||
return self.worker.wake_up(tags)
|
||||
|
||||
def shutdown(self) -> None:
|
||||
"""Shutdown the worker and cleanup resources."""
|
||||
return self.worker.shutdown()
|
||||
|
||||
def execute_method(self, method: str | bytes, *args, **kwargs) -> Any:
|
||||
"""
|
||||
Execute a method on the worker.
|
||||
|
||||
Args:
|
||||
method: Method name (str) or serialized callable (bytes)
|
||||
|
||||
Returns:
|
||||
Result of the method execution (type depends on the method)
|
||||
|
||||
Raises:
|
||||
Exception: If method execution fails
|
||||
"""
|
||||
try:
|
||||
# Method resolution order:
|
||||
# 1. If method is defined in this class, it will be called directly
|
||||
# 2. Otherwise, since we define `__getattr__` and redirect attribute
|
||||
# query to `self.worker`, the method will be called on the worker
|
||||
assert isinstance(method, str), "Method must be str"
|
||||
func = getattr(self.worker, method)
|
||||
return func(*args, **kwargs)
|
||||
|
||||
except Exception as e:
|
||||
msg = f"Error executing method {method!r}. This might cause issues in distributed execution."
|
||||
logger.exception(msg)
|
||||
raise e
|
||||
|
||||
def __getattr__(self, attr: str):
|
||||
"""Delegate attribute access to the wrapped worker."""
|
||||
return getattr(self.worker, attr)
|
||||
Reference in new issue
Block a user