Merge branch 'main' into codex-vae-spatial-decode-auto
This commit is contained in:
186 files changed
+10814
-1165
No files matched your search
@@ -60,7 +60,10 @@ def regionally_compile(
|
||||
for name, submod in model.named_modules():
|
||||
if _matches_repeated_block(name, submod, repeated_blocks, repeated_block_attrs):
|
||||
# Compile the block compute while keeping nn.Module.__call__ hooks
|
||||
# outside the compiled graph.
|
||||
# outside the compiled graph. NOTE: anything that wraps this
|
||||
# callable must stay signature-transparent — cache-dit's
|
||||
# BlockAdapter matches blocks by inspecting forward's parameter
|
||||
# names and return annotation, which torch.compile preserves.
|
||||
compiled_forwards.append(
|
||||
(
|
||||
submod,
|
||||
|
||||
@@ -27,6 +27,7 @@ from vllm_omni.diffusion.diffusion_kv.config import (
|
||||
DiffusionKVCacheMode,
|
||||
parse_diffusion_kv_cache_mode,
|
||||
)
|
||||
from vllm_omni.diffusion.lora.manager import LoRABackend
|
||||
from vllm_omni.diffusion.model_metadata import get_diffusion_model_metadata
|
||||
from vllm_omni.diffusion.utils.network_utils import is_port_available
|
||||
from vllm_omni.errors import client_error_metadata
|
||||
@@ -686,8 +687,9 @@ class OmniDiffusionConfig:
|
||||
# pipeline_config: PipelineConfig = field(default_factory=PipelineConfig, repr=False)
|
||||
|
||||
# LoRA parameters
|
||||
lora_path: str | None = None
|
||||
lora_scale: float = 1.0
|
||||
lora_path: str | list[str] | None = None
|
||||
lora_scale: float | list[float] = 1.0
|
||||
lora_backend: LoRABackend = LoRABackend.PEFT # available choices: ["peft", "distill"]
|
||||
max_cpu_loras: int | None = None
|
||||
|
||||
output_type: str = "pil"
|
||||
|
||||
@@ -208,8 +208,17 @@ def reshard_from_trimmed_extent(
|
||||
return x
|
||||
|
||||
dim = _spatial_dim(split_dim)
|
||||
ctx = _SPATIAL_SHARD_CONTEXT.get()
|
||||
if ctx is not None and ctx.rank != rank:
|
||||
raise RuntimeError(
|
||||
"Wan VAE spatial-shard rank mismatch while resharding: "
|
||||
f"group_rank={rank}, context_rank={ctx.rank}, split_dim={split_dim!r}."
|
||||
)
|
||||
|
||||
valid_extent = _local_valid_extent(local_extent)
|
||||
start = rank * local_extent
|
||||
actual_extent = x.shape[dim]
|
||||
start = min(rank * local_extent, actual_extent)
|
||||
valid_extent = min(valid_extent, actual_extent - start)
|
||||
local = _narrow_along_dim(x, dim, start, valid_extent).contiguous()
|
||||
if valid_extent < local_extent:
|
||||
local = _pad_along_dim(local, local_extent - valid_extent, dim=dim)
|
||||
@@ -659,10 +668,22 @@ def _patch_attention_block(module: nn.Module, group: dist.ProcessGroup) -> None:
|
||||
dim = _spatial_dim(split_dim)
|
||||
local_extent = x.shape[dim]
|
||||
gathered = all_gather_along_dim(x, group=group, dim=dim).contiguous()
|
||||
gathered_extent = gathered.shape[dim]
|
||||
full_extent = _current_full_extent(local_extent)
|
||||
if full_extent is not None:
|
||||
gathered = _narrow_along_dim(gathered, dim, 0, full_extent).contiguous()
|
||||
trim_extent = min(full_extent, gathered_extent)
|
||||
gathered = _narrow_along_dim(gathered, dim, 0, trim_extent).contiguous()
|
||||
else:
|
||||
trim_extent = gathered_extent
|
||||
out = orig_forward(gathered, *args, **kwargs)
|
||||
if out.shape[dim] != trim_extent:
|
||||
raise RuntimeError(
|
||||
"Wan VAE attention changed the spatial extent during global gather: "
|
||||
f"rank={_rank_world(group)[0]}, split_dim={split_dim!r}, "
|
||||
f"local_extent={local_extent}, gathered_extent={gathered_extent}, "
|
||||
f"trimmed_extent={trim_extent}, output_extent={out.shape[dim]}, "
|
||||
f"context={_SPATIAL_SHARD_CONTEXT.get()!r}."
|
||||
)
|
||||
return reshard_from_trimmed_extent(out, local_extent=local_extent, split_dim=split_dim, group=group)
|
||||
|
||||
module.forward = MethodType(_forward, module)
|
||||
|
||||
@@ -28,6 +28,8 @@ If you only need to use the distributed environment without model parallelism,
|
||||
you can skip the model parallel initialization and destruction steps.
|
||||
"""
|
||||
|
||||
import inspect
|
||||
|
||||
import torch
|
||||
import torch.distributed
|
||||
import vllm.distributed.parallel_state as vllm_parallel_state
|
||||
@@ -524,13 +526,23 @@ def init_vllm_model_parallel_group(
|
||||
local_rank: int,
|
||||
backend: str,
|
||||
group_name: str,
|
||||
use_all2all: bool = False,
|
||||
) -> vllm_parallel_state.GroupCoordinator:
|
||||
# vLLM 0.27's MoE oracle (make_unquantized_moe_kernel ->
|
||||
# get_ep_all2all_manager) asserts that the EP group's device communicator
|
||||
# carries an all2all_manager, and vLLM only builds one when the group is
|
||||
# created with use_all2all=True. Older vLLM has neither the kwarg nor the
|
||||
# requirement, so forward it only when supported.
|
||||
kwargs = {}
|
||||
if use_all2all and "use_all2all" in inspect.signature(vllm_parallel_state.init_model_parallel_group).parameters:
|
||||
kwargs["use_all2all"] = True
|
||||
return vllm_parallel_state.init_model_parallel_group(
|
||||
group_ranks=group_ranks,
|
||||
local_rank=local_rank,
|
||||
backend=backend,
|
||||
group_name=group_name,
|
||||
use_device_communicator=True,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
|
||||
@@ -954,6 +966,7 @@ def initialize_model_parallel(
|
||||
local_rank=get_world_group().local_rank,
|
||||
backend=backend,
|
||||
group_name="ep",
|
||||
use_all2all=True,
|
||||
)
|
||||
|
||||
init_dit_group(dit_parallel_size, backend)
|
||||
|
||||
@@ -75,7 +75,7 @@ class FusedMoE:
|
||||
# Current vLLM FusedMoE handles output reduction internally.
|
||||
kwargs.pop("reduce_results", None)
|
||||
# FusedMoE is now a factory function; call it to get a MoERunner.
|
||||
from vllm.model_executor.layers.fused_moe import FusedMoE as _FusedMoE
|
||||
from vllm.model_executor.layers.fused_moe import FusedMoEFactory as _FusedMoE
|
||||
|
||||
moe_runner = _FusedMoE(prefix=prefix, **kwargs)
|
||||
|
||||
|
||||
@@ -65,9 +65,10 @@ class LayerNorm(nn.LayerNorm, CustomOp):
|
||||
|
||||
|
||||
class RMSNorm(CustomOp):
|
||||
def __init__(self, hidden_size: int, eps: float = 1e-6, dtype: torch.dtype = torch.float32) -> None:
|
||||
def __init__(self, hidden_size: int, eps: float = 1e-6, dtype: torch.dtype | None = None) -> None:
|
||||
super().__init__()
|
||||
self.weight = nn.Parameter(torch.ones(hidden_size, dtype=dtype))
|
||||
weight_dtype = dtype or torch.get_default_dtype()
|
||||
self.weight = nn.Parameter(torch.ones(hidden_size, dtype=weight_dtype))
|
||||
self.hidden_size = hidden_size
|
||||
self.variance_epsilon = eps
|
||||
|
||||
|
||||
@@ -0,0 +1,461 @@
|
||||
import os
|
||||
from collections import OrderedDict, defaultdict
|
||||
from collections.abc import Callable
|
||||
|
||||
import torch
|
||||
from diffusers.loaders.lora_conversion_utils import (
|
||||
_convert_non_diffusers_qwen_lora_to_diffusers,
|
||||
_convert_non_diffusers_wan_lora_to_diffusers,
|
||||
)
|
||||
from huggingface_hub import hf_hub_download
|
||||
from safetensors.torch import load_file
|
||||
from vllm.logger import init_logger
|
||||
|
||||
from vllm_omni.diffusion.utils.tf_utils import get_transformer_from_pipeline
|
||||
|
||||
logger = init_logger(__name__)
|
||||
|
||||
lora_convert_mapping: dict[str, Callable] = {
|
||||
"QwenImagePipeline": _convert_non_diffusers_qwen_lora_to_diffusers,
|
||||
"QwenImageEditPipeline": _convert_non_diffusers_qwen_lora_to_diffusers,
|
||||
"QwenImageEditPlusPipeline": _convert_non_diffusers_qwen_lora_to_diffusers,
|
||||
"Wan22Pipeline": _convert_non_diffusers_wan_lora_to_diffusers,
|
||||
"Wan22I2VPipeline": _convert_non_diffusers_wan_lora_to_diffusers,
|
||||
}
|
||||
|
||||
|
||||
def get_converter_by_pipeline(pipeline):
|
||||
for pipeline_cls in pipeline.__class__.__mro__:
|
||||
converter = lora_convert_mapping.get(pipeline_cls.__name__)
|
||||
if converter is not None:
|
||||
return converter
|
||||
return None
|
||||
|
||||
|
||||
def _prepare_lora_delta(
|
||||
lora_state_dict,
|
||||
base_key: str,
|
||||
param_to_weight_names: dict[str, list[str]] | None = None,
|
||||
is_bias: bool = False,
|
||||
lora_a_suffix: str = "lora_A.weight",
|
||||
lora_b_suffix: str = "lora_B.weight",
|
||||
lora_bias_suffix: str = "bias",
|
||||
):
|
||||
used_keys = set()
|
||||
# stacked_params_mapping param_to_weight_names
|
||||
# [(".to_qkv", ".to_q.", "q")
|
||||
# (".to_qkv", ".to_k.", "k") ========> {".to_qkv": [".to_q", ".to_k", ".to_v"]}
|
||||
# (".to_qkv", ".to_v.", "v")]
|
||||
|
||||
# stacked_sd is to store packed parameter deltas (format: [str, list[torch.Tensor]])
|
||||
# example: {".to_qkv": [delta_q, delta_k, delta_v]}
|
||||
stacked_deltas = []
|
||||
is_stacked_param = False
|
||||
if param_to_weight_names is None:
|
||||
param_to_weight_names = defaultdict(list)
|
||||
for param_name, weight_names in param_to_weight_names.items():
|
||||
if param_name not in base_key:
|
||||
continue
|
||||
is_stacked_param = True
|
||||
# handle lora_a_key and lora_b_key together
|
||||
if is_bias:
|
||||
for weight_name in weight_names:
|
||||
lora_bias_key = f"{base_key.replace(param_name, weight_name)}.{lora_bias_suffix}"
|
||||
if lora_bias_key not in lora_state_dict:
|
||||
return None, used_keys
|
||||
delta = lora_state_dict[lora_bias_key]
|
||||
stacked_deltas.append(delta)
|
||||
used_keys.add(lora_bias_key)
|
||||
else:
|
||||
for weight_name in weight_names:
|
||||
lora_a_key = f"{base_key.replace(param_name, weight_name)}.{lora_a_suffix}"
|
||||
lora_b_key = lora_a_key.replace(lora_a_suffix, lora_b_suffix)
|
||||
if lora_a_key not in lora_state_dict or lora_b_key not in lora_state_dict:
|
||||
return None, used_keys
|
||||
a = lora_state_dict[lora_a_key]
|
||||
b = lora_state_dict[lora_b_key]
|
||||
delta = torch.matmul(b, a)
|
||||
stacked_deltas.append(delta)
|
||||
used_keys.add(lora_a_key)
|
||||
used_keys.add(lora_b_key)
|
||||
continue
|
||||
|
||||
if is_stacked_param:
|
||||
return torch.concat(stacked_deltas), used_keys
|
||||
|
||||
if is_bias:
|
||||
lora_bias_key = f"{base_key}.{lora_bias_suffix}"
|
||||
if lora_bias_key not in lora_state_dict:
|
||||
return None, used_keys
|
||||
used_keys.add(lora_bias_key)
|
||||
return lora_state_dict[lora_bias_key], used_keys
|
||||
|
||||
lora_a_key = f"{base_key}.{lora_a_suffix}"
|
||||
lora_b_key = f"{base_key}.{lora_b_suffix}"
|
||||
if lora_a_key not in lora_state_dict or lora_b_key not in lora_state_dict:
|
||||
return None, used_keys
|
||||
a = lora_state_dict[lora_a_key]
|
||||
b = lora_state_dict[lora_b_key]
|
||||
used_keys.add(lora_a_key)
|
||||
used_keys.add(lora_b_key)
|
||||
return torch.matmul(b, a), used_keys
|
||||
|
||||
|
||||
def _load_lora_state_dict(
|
||||
pretrained_model_name_or_path: str,
|
||||
weights_name: str | None = None,
|
||||
use_safetensors: bool = True,
|
||||
subfolder: str | None = None,
|
||||
cache_dir: str | None = None,
|
||||
force_download: bool = False,
|
||||
local_files_only: bool | None = None,
|
||||
):
|
||||
# first we try to load it from local disk
|
||||
if use_safetensors and pretrained_model_name_or_path.endswith(".safetensors"):
|
||||
return load_file(pretrained_model_name_or_path)
|
||||
|
||||
if os.path.isdir(pretrained_model_name_or_path):
|
||||
model_file = pretrained_model_name_or_path
|
||||
if subfolder:
|
||||
model_file = os.path.join(model_file, subfolder)
|
||||
if weights_name is None:
|
||||
raise ValueError("weights_name is required when loading from a directory")
|
||||
model_file = os.path.join(model_file, weights_name)
|
||||
return load_file(model_file)
|
||||
|
||||
# finally, we try to load it from the internet
|
||||
try:
|
||||
model_file = hf_hub_download(
|
||||
pretrained_model_name_or_path,
|
||||
filename=weights_name,
|
||||
subfolder=subfolder,
|
||||
cache_dir=cache_dir,
|
||||
force_download=force_download,
|
||||
local_files_only=local_files_only,
|
||||
)
|
||||
return load_file(model_file)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to download {weights_name} from {pretrained_model_name_or_path}: {e}")
|
||||
raise e
|
||||
|
||||
|
||||
def _remap_state_dict_keys(sd, rules):
|
||||
"""
|
||||
Remap keys in a state_dict by sequentially applying a list of substring substitution rules.
|
||||
|
||||
This utility function transforms parameter names by applying a sequence of
|
||||
(old_substring, new_substring) pairs. For each key in the input dictionary,
|
||||
**all rules are evaluated in the given order**, and every rule whose
|
||||
`old_substring` is found within the current key triggers a replacement.
|
||||
Substitutions are cumulative: the key is updated after each match, and
|
||||
subsequent rules operate on the result of previous replacements.
|
||||
|
||||
The order of rules matters; users are responsible for arranging them to
|
||||
achieve the desired final key. Keys that do not match any rule are copied
|
||||
unchanged.
|
||||
|
||||
Args:
|
||||
sd (dict[str, Any]): Original state_dict mapping parameter names to tensors.
|
||||
rules (List[Tuple[str, str]]): A list of (old_substring, new_substring) pairs.
|
||||
Rules are applied sequentially, and **all matching rules are executed**.
|
||||
|
||||
Returns:
|
||||
dict[str, Any]: A new state_dict with remapped keys. Values are unchanged.
|
||||
"""
|
||||
new_sd = OrderedDict()
|
||||
for k, v in sd.items():
|
||||
new_key = k
|
||||
matched = False
|
||||
for p1, p2 in rules:
|
||||
if p1 not in k:
|
||||
continue
|
||||
new_key = new_key.replace(p1, p2)
|
||||
matched = True
|
||||
if matched:
|
||||
new_sd[new_key] = v
|
||||
else:
|
||||
new_sd[k] = v
|
||||
return new_sd
|
||||
|
||||
|
||||
def _apply_diffusers_lora_alpha_scaling(state_dict: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
|
||||
"""Fold Diffusers-format LoRA alpha values into their B matrices."""
|
||||
scaled_state_dict = dict(state_dict)
|
||||
for alpha_key in (key for key in state_dict if key.endswith(".alpha")):
|
||||
base_key = alpha_key[: -len(".alpha")]
|
||||
lora_a_key = f"{base_key}.lora_A.weight"
|
||||
lora_b_key = f"{base_key}.lora_B.weight"
|
||||
if lora_a_key not in state_dict or lora_b_key not in state_dict:
|
||||
raise ValueError(f"LoRA alpha key {alpha_key!r} does not have matching lora_A and lora_B weights.")
|
||||
|
||||
rank = state_dict[lora_a_key].shape[0]
|
||||
alpha = state_dict[alpha_key]
|
||||
|
||||
scaled_state_dict[lora_b_key] = state_dict[lora_b_key] * (alpha.item() / rank)
|
||||
scaled_state_dict.pop(alpha_key)
|
||||
|
||||
return scaled_state_dict
|
||||
|
||||
|
||||
class LoraLoaderMixin:
|
||||
transformer_name = "transformer"
|
||||
|
||||
# Lazy initialization to avoid MRO issues: __init__ may not be called
|
||||
# when mixin with nn.Module
|
||||
@property
|
||||
def lora_loaded(self):
|
||||
if not hasattr(self, "_lora_loaded"):
|
||||
self._lora_loaded = {}
|
||||
return self._lora_loaded
|
||||
|
||||
@lora_loaded.setter
|
||||
def lora_loaded(self, value):
|
||||
self._lora_loaded = value
|
||||
|
||||
@classmethod
|
||||
def load_lora_into_module(
|
||||
cls,
|
||||
state_dict,
|
||||
module,
|
||||
prefix: str = "transformer",
|
||||
lora_a_suffix: str = "lora_A.weight",
|
||||
lora_b_suffix: str = "lora_B.weight",
|
||||
lora_bias_suffix: str = "bias",
|
||||
):
|
||||
lora_loaded_keys = set()
|
||||
|
||||
# prepare stacked parameters mapping for later use
|
||||
# stacked_params_mapping param_to_weight_names
|
||||
# [(".to_qkv", ".to_q.", "q")
|
||||
# (".to_qkv", ".to_k.", "k") ========> {".to_qkv": [".to_q", ".to_k", ".to_v"]}
|
||||
# (".to_qkv", ".to_v.", "v")]
|
||||
param_to_weight_names = defaultdict(list)
|
||||
if hasattr(module, "stacked_params_mapping"):
|
||||
for param_name, weight_name, _ in module.stacked_params_mapping:
|
||||
param_to_weight_names[param_name].append(weight_name)
|
||||
|
||||
for name, params in module.named_parameters(prefix):
|
||||
is_bias = False
|
||||
if name.endswith(".bias"):
|
||||
base_key = name[: -len(".bias")]
|
||||
is_bias = True
|
||||
elif name.endswith(".weight"):
|
||||
base_key = name[: -len(".weight")]
|
||||
else:
|
||||
continue
|
||||
|
||||
delta, used_keys = _prepare_lora_delta(
|
||||
state_dict,
|
||||
base_key,
|
||||
param_to_weight_names,
|
||||
is_bias,
|
||||
lora_a_suffix,
|
||||
lora_b_suffix,
|
||||
lora_bias_suffix,
|
||||
)
|
||||
if delta is None:
|
||||
continue
|
||||
lora_loaded_keys.update(used_keys)
|
||||
|
||||
delta = delta.to(device=params.device, dtype=params.dtype)
|
||||
with torch.no_grad():
|
||||
params.add_(delta)
|
||||
del delta
|
||||
|
||||
missing_keys = set(state_dict.keys()) - lora_loaded_keys
|
||||
for k in missing_keys:
|
||||
logger.warning(f"Missing loading lora key: {k}")
|
||||
|
||||
logger.info(f"{len(lora_loaded_keys)} lora keys loaded into {module.__class__.__name__}.")
|
||||
return lora_loaded_keys
|
||||
|
||||
@classmethod
|
||||
def unload_module_lora(
|
||||
cls,
|
||||
state_dict,
|
||||
module,
|
||||
prefix: str = "transformer",
|
||||
lora_a_suffix: str = "lora_A.weight",
|
||||
lora_b_suffix: str = "lora_B.weight",
|
||||
lora_bias_suffix: str = "bias",
|
||||
):
|
||||
lora_unloaded_keys = set()
|
||||
|
||||
param_to_weight_names = defaultdict(list)
|
||||
if hasattr(module, "stacked_params_mapping"):
|
||||
for param_name, weight_name, _ in module.stacked_params_mapping:
|
||||
param_to_weight_names[param_name].append(weight_name)
|
||||
|
||||
for name, param in module.named_parameters(prefix):
|
||||
is_bias = False
|
||||
if name.endswith(".bias"):
|
||||
base_key = name[: -len(".bias")]
|
||||
is_bias = True
|
||||
elif name.endswith(".weight"):
|
||||
base_key = name[: -len(".weight")]
|
||||
else:
|
||||
continue
|
||||
|
||||
delta, used_keys = _prepare_lora_delta(
|
||||
state_dict,
|
||||
base_key,
|
||||
param_to_weight_names,
|
||||
is_bias,
|
||||
lora_a_suffix,
|
||||
lora_b_suffix,
|
||||
lora_bias_suffix,
|
||||
)
|
||||
if delta is None:
|
||||
continue
|
||||
lora_unloaded_keys.update(used_keys)
|
||||
|
||||
delta = delta.to(device=param.device, dtype=param.dtype)
|
||||
with torch.no_grad():
|
||||
param.sub_(delta)
|
||||
del delta
|
||||
|
||||
missing_keys = set(state_dict.keys()) - lora_unloaded_keys
|
||||
for k in missing_keys:
|
||||
logger.warning(f"Missing unloading lora key: {k}")
|
||||
|
||||
logger.info(f"{len(lora_unloaded_keys)} lora keys unloaded from {module.__class__.__name__}.")
|
||||
return lora_unloaded_keys
|
||||
|
||||
|
||||
class QwenImageLoraLoaderMixin(LoraLoaderMixin):
|
||||
def load_lora_weights(
|
||||
self,
|
||||
pretrained_model_name_or_path_or_dict: str | dict[str, torch.Tensor],
|
||||
adapter_name: str | None = None,
|
||||
):
|
||||
if adapter_name in self.lora_loaded:
|
||||
return
|
||||
|
||||
if isinstance(pretrained_model_name_or_path_or_dict, dict):
|
||||
state_dict = pretrained_model_name_or_path_or_dict
|
||||
else:
|
||||
state_dict = _load_lora_state_dict(pretrained_model_name_or_path_or_dict)
|
||||
|
||||
has_alpha = any(k.endswith(".alpha") for k in state_dict)
|
||||
is_non_diffusers_format = any(k.startswith("diffusion_model.") for k in state_dict)
|
||||
is_diffusers_lora_format = any(k.endswith(".lora_A.weight") for k in state_dict)
|
||||
if has_alpha and is_diffusers_lora_format:
|
||||
state_dict = _apply_diffusers_lora_alpha_scaling(state_dict)
|
||||
|
||||
if has_alpha or is_non_diffusers_format:
|
||||
converter = get_converter_by_pipeline(self)
|
||||
if converter is None:
|
||||
raise ValueError(f"Converter for Lora weights not found for {self.__class__.__name__}")
|
||||
|
||||
state_dict = converter(state_dict)
|
||||
|
||||
state_dict = _remap_state_dict_keys(state_dict, [(".to_out.0.", ".to_out.")])
|
||||
|
||||
self.load_lora_into_module(
|
||||
state_dict,
|
||||
self.transformer,
|
||||
prefix=self.transformer_name,
|
||||
)
|
||||
|
||||
self.lora_loaded[adapter_name] = state_dict
|
||||
|
||||
def unload_lora_weights(self, adapter_name: str):
|
||||
if adapter_name not in self.lora_loaded:
|
||||
return
|
||||
|
||||
state_dict = self.lora_loaded[adapter_name]
|
||||
|
||||
transformer = get_transformer_from_pipeline(self)
|
||||
self.unload_module_lora(state_dict, transformer, prefix=self.transformer_name)
|
||||
|
||||
del self.lora_loaded[adapter_name]
|
||||
|
||||
|
||||
class WanLoraLoaderMixin(LoraLoaderMixin):
|
||||
transformer_2_name = "transformer_2"
|
||||
|
||||
def load_lora_weights(
|
||||
self,
|
||||
pretrained_model_name_or_path: str | list[str],
|
||||
adapter_name: str | None = None,
|
||||
):
|
||||
"""Load LoRA weights into the pipeline's transformer(s).
|
||||
|
||||
Args:
|
||||
pretrained_model_name_or_path: Path(s) to concrete .safetensors LoRA files.
|
||||
- str: a single .safetensors file. Only valid for Wan2.1
|
||||
(single-transformer pipelines).
|
||||
- list[str]: one file per transformer, matched **by position** to
|
||||
[transformer, transformer_2]. Required for Wan2.2 MoE.
|
||||
adapter_name: Name to register the adapter under.
|
||||
"""
|
||||
if adapter_name in self.lora_loaded:
|
||||
return
|
||||
|
||||
# Normalize to list[(lora_path, target_module_name)].
|
||||
lora_paths = None
|
||||
if isinstance(pretrained_model_name_or_path, str):
|
||||
lora_paths = [pretrained_model_name_or_path]
|
||||
else:
|
||||
lora_paths = list(pretrained_model_name_or_path)
|
||||
|
||||
target_modules = (
|
||||
[self.transformer_name, self.transformer_2_name] if self.has_transformer_2 else [self.transformer_name]
|
||||
)
|
||||
if len(lora_paths) != len(target_modules):
|
||||
raise ValueError(
|
||||
f"{self.__class__.__name__} expects {len(target_modules)} LoRA file(s) "
|
||||
f"(target_modules={target_modules}, paths={lora_paths}), got {len(lora_paths)}. Pass a list of concrete " # noqa
|
||||
f".safetensors files, one per transformer."
|
||||
)
|
||||
|
||||
module_to_lora_sd = dict()
|
||||
for lora_path, target_module_name in zip(lora_paths, target_modules):
|
||||
state_dict = _load_lora_state_dict(lora_path)
|
||||
is_non_diffusers_format = any(k.startswith("diffusion_model.") for k in state_dict)
|
||||
if is_non_diffusers_format:
|
||||
converter = get_converter_by_pipeline(self)
|
||||
if converter is None:
|
||||
raise ValueError(f"Converter for Lora weights not found for {self.__class__.__name__}")
|
||||
|
||||
state_dict = converter(state_dict)
|
||||
|
||||
state_dict = _remap_state_dict_keys(
|
||||
state_dict,
|
||||
[
|
||||
(".ffn.net.0.", ".ffn.net_0."),
|
||||
(".ffn.net.2.", ".ffn.net_2."),
|
||||
(
|
||||
".to_out.0.",
|
||||
".to_out.",
|
||||
),
|
||||
# '.bias_B.bias' is a horrible name in diffuser's.
|
||||
# So we remap it to '.bias'
|
||||
(".lora_B.bias", ".bias"),
|
||||
],
|
||||
)
|
||||
|
||||
module = get_transformer_from_pipeline(self, transformer_name=target_module_name)
|
||||
if module is None:
|
||||
logger.warning(
|
||||
f"Skip LoRA {lora_path}: target module '{target_module_name}' "
|
||||
f"is not loaded in pipeline {self.__class__.__name__} "
|
||||
f"(e.g. disabled by boundary_ratio)."
|
||||
)
|
||||
continue
|
||||
|
||||
self.load_lora_into_module(state_dict, module, prefix=self.transformer_name, lora_bias_suffix="bias")
|
||||
module_to_lora_sd[target_module_name] = state_dict
|
||||
|
||||
self.lora_loaded[adapter_name] = module_to_lora_sd
|
||||
|
||||
def unload_lora_weights(self, adapter_name: str):
|
||||
if adapter_name not in self.lora_loaded:
|
||||
return
|
||||
|
||||
module_to_lora_sd = self.lora_loaded[adapter_name]
|
||||
for module_name, lora_sd in module_to_lora_sd.items():
|
||||
module = get_transformer_from_pipeline(self, transformer_name=module_name)
|
||||
self.unload_module_lora(lora_sd, module, prefix=self.transformer_name)
|
||||
|
||||
del self.lora_loaded[adapter_name]
|
||||
@@ -4,6 +4,7 @@
|
||||
import math
|
||||
import time
|
||||
from collections import OrderedDict
|
||||
from enum import Enum
|
||||
from typing import get_args
|
||||
|
||||
import torch
|
||||
@@ -33,6 +34,11 @@ from vllm_omni.lora.utils import stable_lora_int_id
|
||||
logger = init_logger(__name__)
|
||||
|
||||
|
||||
class LoRABackend(str, Enum):
|
||||
PEFT = "peft"
|
||||
DISTILL = "distill"
|
||||
|
||||
|
||||
class DiffusionLoRAManager:
|
||||
"""Manager for LoRA adapters in diffusion models.
|
||||
|
||||
|
||||
@@ -36,6 +36,22 @@ from vllm_omni.platforms import current_omni_platform
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Preference chain for CUDA flash attention in diffusers, best first. Shared
|
||||
# with the accuracy tests' diffusers reference runs so both sides of a
|
||||
# similarity comparison resolve to the same backend on any given image
|
||||
# (hub kernels may lack a build variant for the image's torch).
|
||||
CUDA_FLASH_ATTENTION_BACKEND_ATTEMPTS: list[str] = [
|
||||
"_flash_3_hub",
|
||||
"_flash_3_varlen_hub",
|
||||
"_flash_3",
|
||||
"_flash_varlen_3",
|
||||
"flash_hub",
|
||||
"flash_varlen_hub",
|
||||
"flash",
|
||||
"flash_varlen",
|
||||
"_native_flash",
|
||||
]
|
||||
|
||||
_DIFFUSERS_CONFIG_LOAD_KWARGS = {
|
||||
"cache_dir",
|
||||
"dduf_entries",
|
||||
@@ -279,19 +295,7 @@ class DiffusersAdapterPipeline(nn.Module, DiffusionPipelineProfilerMixin):
|
||||
)
|
||||
attention_backend_attempts.append("native")
|
||||
else:
|
||||
attention_backend_attempts.extend(
|
||||
[
|
||||
"_flash_3_hub",
|
||||
"_flash_3_varlen_hub",
|
||||
"_flash_3",
|
||||
"_flash_varlen_3",
|
||||
"flash_hub",
|
||||
"flash_varlen_hub",
|
||||
"flash",
|
||||
"flash_varlen",
|
||||
"_native_flash",
|
||||
]
|
||||
)
|
||||
attention_backend_attempts.extend(CUDA_FLASH_ATTENTION_BACKEND_ATTEMPTS)
|
||||
case "SAGE_ATTN":
|
||||
attention_backend_attempts.extend(["sage_hub", "sage", "sage", "sage_varlen"])
|
||||
case "ASCEND":
|
||||
|
||||
@@ -299,16 +299,21 @@ def resolve_lingbot_output_dimensions(
|
||||
sampling_width: Any = None,
|
||||
sampling_height: Any = None,
|
||||
prompt_fields: Mapping[str, Any] | None = None,
|
||||
extra_fields: Mapping[str, Any] | None = None,
|
||||
default_width: int = 480,
|
||||
default_height: int = 480,
|
||||
) -> tuple[int, int]:
|
||||
"""Resolve the ``(width, height)`` that LingBot will use for generation."""
|
||||
prompt_fields = prompt_fields or {}
|
||||
requested_width = _pick(prompt_fields, "width")
|
||||
requested_height = _pick(prompt_fields, "height")
|
||||
size = _pick(prompt_fields, "size")
|
||||
resolution = _pick(prompt_fields, "resolution")
|
||||
ratio = _pick(prompt_fields, "ratio")
|
||||
extra_fields = extra_fields or {}
|
||||
# Online requests deliver `extra_params` through sampling.extra_args; the
|
||||
# offline path embeds the same fields in the prompt dict. Consult both,
|
||||
# extra_args first — the same precedence fps and num_frames use.
|
||||
requested_width = _first_not_none(_pick(extra_fields, "width"), _pick(prompt_fields, "width"))
|
||||
requested_height = _first_not_none(_pick(extra_fields, "height"), _pick(prompt_fields, "height"))
|
||||
size = _first_not_none(_pick(extra_fields, "size"), _pick(prompt_fields, "size"))
|
||||
resolution = _first_not_none(_pick(extra_fields, "resolution"), _pick(prompt_fields, "resolution"))
|
||||
ratio = _first_not_none(_pick(extra_fields, "ratio"), _pick(prompt_fields, "ratio"))
|
||||
if requested_width is not None or requested_height is not None:
|
||||
width, height = requested_width, requested_height
|
||||
elif size is not None or resolution is not None or ratio is not None:
|
||||
@@ -414,6 +419,7 @@ def normalize_lingbot_request(
|
||||
sampling_width=sampling.width,
|
||||
sampling_height=sampling.height,
|
||||
prompt_fields=prompt_fields,
|
||||
extra_fields=extra_args,
|
||||
default_width=default_width,
|
||||
default_height=default_height,
|
||||
)
|
||||
|
||||
@@ -25,6 +25,7 @@ from vllm.model_executor.models.utils import AutoWeightsLoader
|
||||
from vllm_omni.diffusion.data import DiffusionOutput, OmniDiffusionConfig
|
||||
from vllm_omni.diffusion.distributed.autoencoders.autoencoder_kl_qwenimage import DistributedAutoencoderKLQwenImage
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.lora.loader import QwenImageLoraLoaderMixin
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.model_loader.hub_prefetch import from_pretrained_with_prefetch, prefetch_subfolders
|
||||
from vllm_omni.diffusion.models.dmd2 import DMD2PipelineMixin
|
||||
@@ -264,7 +265,11 @@ def apply_rotary_emb_qwen(
|
||||
|
||||
|
||||
class QwenImagePipeline(
|
||||
nn.Module, QwenImageCFGParallelMixin, DiffusionPipelineProfilerMixin, SupportsComponentDiscovery
|
||||
nn.Module,
|
||||
QwenImageCFGParallelMixin,
|
||||
DiffusionPipelineProfilerMixin,
|
||||
SupportsComponentDiscovery,
|
||||
QwenImageLoraLoaderMixin,
|
||||
):
|
||||
supports_request_batch = True
|
||||
_dit_modules: ClassVar[list[str]] = ["transformer"]
|
||||
|
||||
@@ -25,6 +25,7 @@ from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
|
||||
from vllm_omni.diffusion.distributed.pipeline_parallel import AsyncLatents, PipelineParallelMixin
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.forward_context import DenoiseProgressMixin
|
||||
from vllm_omni.diffusion.lora.loader import WanLoraLoaderMixin
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.model_loader.hub_prefetch import from_pretrained_with_prefetch, prefetch_subfolders
|
||||
from vllm_omni.diffusion.models.dmd2 import DMD2PipelineMixin
|
||||
@@ -285,6 +286,7 @@ class Wan22Pipeline(
|
||||
DenoiseProgressMixin,
|
||||
DiffusionPipelineProfilerMixin,
|
||||
SupportsComponentDiscovery,
|
||||
WanLoraLoaderMixin,
|
||||
):
|
||||
_dit_modules: ClassVar[list[str]] = ["transformer", "transformer_2"]
|
||||
_encoder_modules: ClassVar[list[str]] = ["text_encoder"]
|
||||
|
||||
@@ -25,6 +25,7 @@ from vllm_omni.diffusion.distributed.cfg_parallel import CFGParallelMixin
|
||||
from vllm_omni.diffusion.distributed.pipeline_parallel import AsyncLatents, PipelineParallelMixin
|
||||
from vllm_omni.diffusion.distributed.utils import get_local_device
|
||||
from vllm_omni.diffusion.forward_context import DenoiseProgressMixin
|
||||
from vllm_omni.diffusion.lora.loader import WanLoraLoaderMixin
|
||||
from vllm_omni.diffusion.model_loader.diffusers_loader import DiffusersPipelineLoader
|
||||
from vllm_omni.diffusion.model_loader.hub_prefetch import from_pretrained_with_prefetch, prefetch_subfolders
|
||||
from vllm_omni.diffusion.models.dmd2 import DMD2PipelineMixin
|
||||
@@ -147,6 +148,7 @@ class Wan22I2VPipeline(
|
||||
DiffusionPipelineProfilerMixin,
|
||||
DenoiseProgressMixin,
|
||||
SupportsComponentDiscovery,
|
||||
WanLoraLoaderMixin,
|
||||
):
|
||||
"""
|
||||
Wan2.2 Image-to-Video Pipeline.
|
||||
|
||||
@@ -70,9 +70,10 @@ def find_module_with_attr(model, attr_name="transformer"):
|
||||
return None
|
||||
|
||||
|
||||
def get_transformer_from_pipeline(pipeline: Any):
|
||||
pipe = find_module_with_attr(pipeline, attr_name="transformer")
|
||||
def get_transformer_from_pipeline(pipeline: Any, transformer_name: str = "transformer"):
|
||||
"""Return a named transformer from a pipeline or pipeline wrapper."""
|
||||
pipe = find_module_with_attr(pipeline, attr_name=transformer_name)
|
||||
|
||||
if pipe is not None:
|
||||
return pipe.transformer
|
||||
return getattr(pipe, transformer_name)
|
||||
return None
|
||||
@@ -49,7 +49,7 @@ from vllm_omni.diffusion.distributed.parallel_state import (
|
||||
)
|
||||
from vllm_omni.diffusion.forward_context import set_forward_context
|
||||
from vllm_omni.diffusion.ipc import DIFFUSION_RPC_RESULT_ENVELOPE, pack_diffusion_output_shm
|
||||
from vllm_omni.diffusion.lora.manager import DiffusionLoRAManager
|
||||
from vllm_omni.diffusion.lora.manager import DiffusionLoRAManager, LoRABackend
|
||||
from vllm_omni.diffusion.registry import get_diffusion_ir_op_priority_func
|
||||
from vllm_omni.diffusion.request import OmniDiffusionRequest
|
||||
from vllm_omni.diffusion.sched.interface import DiffusionSchedulerOutput, KVPrefetchJob
|
||||
@@ -388,14 +388,31 @@ class DiffusionWorker:
|
||||
"""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,
|
||||
dtype=self.od_config.dtype,
|
||||
max_cached_adapters=self.od_config.max_cpu_loras,
|
||||
lora_path=self.od_config.lora_path,
|
||||
lora_scale=self.od_config.lora_scale,
|
||||
)
|
||||
|
||||
lora_path = self.od_config.lora_path
|
||||
if isinstance(lora_path, list) and len(lora_path) == 1:
|
||||
lora_path = lora_path[0]
|
||||
|
||||
lora_backend = self.od_config.lora_backend
|
||||
if lora_backend == LoRABackend.PEFT:
|
||||
self.lora_manager = DiffusionLoRAManager(
|
||||
pipeline=self.model_runner.pipeline,
|
||||
device=self.device,
|
||||
dtype=self.od_config.dtype,
|
||||
max_cached_adapters=self.od_config.max_cpu_loras,
|
||||
lora_path=lora_path,
|
||||
lora_scale=self.od_config.lora_scale,
|
||||
)
|
||||
elif lora_backend == LoRABackend.DISTILL:
|
||||
pipeline = self.model_runner.pipeline
|
||||
if hasattr(pipeline, "load_lora_weights"):
|
||||
if self.od_config.lora_scale > 1.0:
|
||||
logger.warning("lora_scale > 1.0 may not take any effect when using distilled LoRA backend.")
|
||||
pipeline.load_lora_weights(lora_path)
|
||||
else:
|
||||
logger.warning("Pipeline does not support loading distilled LoRA weights for now.")
|
||||
else:
|
||||
raise ValueError(f"Unknown LoRA backend: {lora_backend}. Available choices: {LoRABackend.__members__}")
|
||||
|
||||
def profile(self, is_start: bool = True, profile_prefix: str | None = None) -> None:
|
||||
"""Start or stop profiling for this GPU worker.
|
||||
|
||||
Reference in new issue
Block a user