[Feature]: Native GGUF Quantization Support for DiT (#1285)

Signed-off-by: David Chen <530634352@qq.com>
Signed-off-by: Isotr0py <mozf@mail2.sysu.edu.cn>
Signed-off-by: WeiQing Chen <40507679+david6666666@users.noreply.github.com>
Signed-off-by: Hongsheng Liu <liuhongsheng4@huawei.com>
Co-authored-by: Isotr0py <mozf@mail2.sysu.edu.cn>
Co-authored-by: Isotr0py <2037008807@qq.com>
Co-authored-by: Hongsheng Liu <liuhongsheng4@huawei.com>
This commit is contained in:
authored and GitHub committed 2026-02-27 11:39:14 +08:00
1 parent b19c227fb3
commit 0b884ebc6c
23 files changed
+1104 -67

No files matched your search

@@ -9,12 +9,14 @@ from pathlib import Path
from typing import cast
import torch
from huggingface_hub import hf_hub_download
from torch import nn
from vllm.config import ModelConfig
from vllm.config.load import LoadConfig
from vllm.logger import init_logger
from vllm.model_executor.layers.quantization.base_config import QuantizeMethodBase
from vllm.model_executor.model_loader.weight_utils import (
download_gguf,
download_safetensors_index_file_from_hf,
download_weights_from_hf,
filter_duplicate_safetensors_files,
@@ -27,6 +29,7 @@ from vllm.utils.torch_utils import set_default_torch_dtype
from vllm_omni.diffusion.data import OmniDiffusionConfig
from vllm_omni.diffusion.distributed.hsdp import HSDPInferenceConfig
from vllm_omni.diffusion.model_loader.gguf_adapters import get_gguf_adapter
from vllm_omni.diffusion.registry import initialize_model
logger = init_logger(__name__)
@@ -194,13 +197,36 @@ class DiffusersPipelineLoader:
self,
model: nn.Module,
) -> Generator[tuple[str, torch.Tensor], None, None]:
sources = cast(
Iterable[DiffusersPipelineLoader.ComponentSource],
getattr(model, "weights_sources", ()),
)
sources = self._get_weight_sources(model)
for source in sources:
yield from self._get_weights_iterator(source)
def _get_weight_sources(self, model: nn.Module) -> tuple["ComponentSource", ...]:
return tuple(
cast(
Iterable[DiffusersPipelineLoader.ComponentSource],
getattr(model, "weights_sources", ()),
)
)
def _get_expected_parameter_names(self, model: nn.Module) -> set[str]:
"""Return parameter names that should be covered by strict load checks."""
all_parameter_names = {name for name, _ in model.named_parameters()}
sources = self._get_weight_sources(model)
# Keep strict behavior if no source metadata exists.
if not sources:
return all_parameter_names
# Empty prefix means "root" source, i.e. entire model should be covered.
if any(source.prefix == "" for source in sources):
return all_parameter_names
source_prefixes = tuple(source.prefix for source in sources if source.prefix)
if not source_prefixes:
return all_parameter_names
return {name for name in all_parameter_names if name.startswith(source_prefixes)}
def download_model(self, model_config: ModelConfig) -> None:
self._prepare_weights(
model_name_or_path=model_config.model,
@@ -232,8 +258,11 @@ class DiffusersPipelineLoader:
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)
if self._is_gguf_quantization(od_config):
self._load_weights_with_gguf(model, od_config)
else:
# Quantization does not happen in `load_weights` but after it
self.load_weights(model)
# Process weights after loading for quantization (e.g., FP8 online quantization)
# This is needed for vLLM's quantization methods that need to transform weights
@@ -265,7 +294,7 @@ class DiffusersPipelineLoader:
module.to(module_device)
def load_weights(self, model: nn.Module) -> None:
weights_to_load = {name for name, _ in model.named_parameters()}
weights_to_load = self._get_expected_parameter_names(model)
loaded_weights = model.load_weights(self.get_all_weights(model))
self.counter_after_loading_weights = time.perf_counter()
@@ -278,12 +307,122 @@ class DiffusersPipelineLoader:
# We only enable strict check for non-quantized models
# that have loaded weights tracking currently.
if loaded_weights is not None:
_ = weights_to_load - loaded_weights
# if weights_not_loaded:
# raise ValueError(
# "Following weights were not initialized from "
# f"checkpoint: {weights_not_loaded}"
# )
weights_not_loaded = weights_to_load - loaded_weights
if weights_not_loaded:
raise ValueError(f"Following weights were not initialized from checkpoint: {weights_not_loaded}")
def _is_gguf_quantization(self, od_config: OmniDiffusionConfig) -> bool:
quant_config = od_config.quantization_config
if quant_config is None:
return False
# Fast path: mapping-style config (e.g., DictConfig)
if isinstance(quant_config, dict):
method = str(quant_config.get("method", "")).lower()
if method != "gguf":
return False
gguf_model = quant_config.get("gguf_model")
if not gguf_model:
raise ValueError("GGUF quantization requires quantization_config.gguf_model")
return True
# Normal path: DiffusionQuantizationConfig
if not hasattr(quant_config, "get_name"):
# Fallback: if it carries gguf_model, treat as GGUF
gguf_model = getattr(quant_config, "gguf_model", None)
return bool(gguf_model)
is_gguf = quant_config.get_name() == "gguf"
if not is_gguf:
return False
gguf_model = getattr(quant_config, "gguf_model", None)
if gguf_model is None:
raise ValueError("GGUF quantization requires quantization_config.gguf_model")
return True
def _is_transformer_source(self, source: "ComponentSource") -> bool:
if source.subfolder == "transformer":
return True
return source.prefix.startswith("transformer.")
def _get_model_loadable_names(self, model: nn.Module) -> set[str]:
# Avoid model.state_dict() here because GGUF uses UninitializedParameter
# which raises during detach(). Collect names directly.
names = {name for name, _ in model.named_parameters()}
names.update(name for name, _ in model.named_buffers())
return names
def _resolve_gguf_model_path(self, gguf_model: str, revision: str | None) -> str:
if os.path.isfile(gguf_model):
return gguf_model
# repo_id/filename.gguf
if "/" in gguf_model and gguf_model.endswith(".gguf"):
repo_id, filename = gguf_model.rsplit("/", 1)
return hf_hub_download(
repo_id=repo_id,
filename=filename,
revision=revision,
cache_dir=self.load_config.download_dir,
)
# repo_id:quant_type
if "/" in gguf_model and ":" in gguf_model:
repo_id, quant_type = gguf_model.rsplit(":", 1)
return download_gguf(
repo_id,
quant_type,
cache_dir=self.load_config.download_dir,
revision=revision,
ignore_patterns=self.load_config.ignore_patterns,
)
raise ValueError(
f"Unrecognized GGUF reference: {gguf_model!r} (expected local file, "
"<repo_id>/<filename>.gguf, or <repo_id>:<quant_type>)"
)
def _get_gguf_weights_iterator(
self,
source: "ComponentSource",
model: nn.Module,
od_config: OmniDiffusionConfig,
) -> Generator[tuple[str, torch.Tensor], None, None]:
quant_config = od_config.quantization_config
gguf_model = getattr(quant_config, "gguf_model", None)
if gguf_model is None:
raise ValueError("GGUF quantization requires quantization_config.gguf_model")
gguf_file = self._resolve_gguf_model_path(gguf_model, od_config.revision)
adapter = get_gguf_adapter(gguf_file, model, source, od_config)
weights_iter = adapter.weights_iterator()
return ((source.prefix + name, tensor) for (name, tensor) in weights_iter)
def _load_weights_with_gguf(self, model: nn.Module, od_config: OmniDiffusionConfig) -> set[str]:
sources = self._get_weight_sources(model)
loaded: set[str] = set()
loadable_names: set[str] | None = None
for source in sources:
if self._is_transformer_source(source):
loaded |= model.load_weights(self._get_gguf_weights_iterator(source, model, od_config))
# GGUF checkpoints can be transformer-only or partially quantized.
# Only fall back to HF if this source still has missing loadable weights.
loadable_names = loadable_names or self._get_model_loadable_names(model)
has_missing_for_source = any(
name.startswith(source.prefix) and name not in loaded for name in loadable_names
)
if not has_missing_for_source:
continue
hf_iter = self._get_weights_iterator(source)
hf_iter = (
(name, tensor) for (name, tensor) in hf_iter if name in loadable_names and name not in loaded
)
loaded |= model.load_weights(hf_iter)
else:
loaded |= model.load_weights(self._get_weights_iterator(source))
weights_to_load = self._get_expected_parameter_names(model)
weights_not_loaded = weights_to_load - loaded
if weights_not_loaded:
raise ValueError(f"Following weights were not initialized from checkpoint: {weights_not_loaded}")
return loaded
def _load_model_with_hsdp(
self,
@@ -0,0 +1,45 @@
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
from typing import TYPE_CHECKING
import torch
from .base import GGUFAdapter
from .flux2_klein import Flux2KleinGGUFAdapter
from .z_image import ZImageGGUFAdapter
if TYPE_CHECKING:
from vllm_omni.diffusion.data import OmniDiffusionConfig
from vllm_omni.diffusion.model_loader.diffusers_loader import (
DiffusersPipelineLoader,
)
def get_gguf_adapter(
gguf_file: str,
model: torch.nn.Module,
source: DiffusersPipelineLoader.ComponentSource,
od_config: OmniDiffusionConfig,
) -> GGUFAdapter:
adapter_classes = (ZImageGGUFAdapter, Flux2KleinGGUFAdapter)
for adapter_cls in adapter_classes:
if adapter_cls.is_compatible(od_config, model, source):
return adapter_cls(gguf_file, model, source, od_config)
model_type = None
if od_config.tf_model_config is not None:
model_type = od_config.tf_model_config.get("model_type")
supported = ", ".join(cls.__name__ for cls in adapter_classes)
raise ValueError(
"No GGUF adapter matched diffusion model "
f"(model_class_name={od_config.model_class_name!r}, model_type={model_type!r}). "
f"Supported adapters: {supported}."
)
__all__ = [
"GGUFAdapter",
"Flux2KleinGGUFAdapter",
"ZImageGGUFAdapter",
"get_gguf_adapter",
]
@@ -0,0 +1,245 @@
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
from abc import ABC, abstractmethod
from collections.abc import Generator
from dataclasses import dataclass
from typing import Any
import gguf
import numpy as np
import torch
@dataclass
class MappedTensor:
name: str
tensor: Any
tensor_type: Any
row_slice: slice | None = None
swap_scale_shift: bool = False
class GGUFAdapter(ABC):
"""Base class for model-specific GGUF adapters."""
_include_qkv_virtuals: bool = False
_include_add_kv_proj_virtuals: bool = False
_include_to_out_virtuals: bool = False
_include_w13_virtuals: bool = False
_shard_tokens: tuple[str, ...] = ()
_prefer_exact_qweight: bool = True
def __init__(self, gguf_file: str, model: torch.nn.Module, source, od_config) -> None:
self.gguf_file = gguf_file
self.model = model
self.source = source
self.od_config = od_config
@staticmethod
def is_compatible(od_config, model: torch.nn.Module, source) -> bool:
return False
@abstractmethod
def weights_iterator(self) -> Generator[tuple[str, torch.Tensor], None, None]:
raise NotImplementedError
def _get_target_module(self) -> torch.nn.Module:
prefix = getattr(self.source, "prefix", "")
return self.model.get_submodule(prefix.rstrip(".")) if prefix else self.model
def _build_allowed_names(self) -> set[str]:
target = self._get_target_module()
allowed = {name for name, _ in target.named_parameters()}
allowed.update(name for name, _ in target.named_buffers())
for name in list(allowed):
if name.endswith(".qweight"):
allowed.add(name.replace(".qweight", ".weight"))
elif name.endswith(".qweight_type"):
allowed.add(name.replace(".qweight_type", ".weight"))
virtual_names = set()
for name in allowed:
if self._include_qkv_virtuals and ".to_qkv." in name:
virtual_names.add(name.replace(".to_qkv.", ".to_q."))
virtual_names.add(name.replace(".to_qkv.", ".to_k."))
virtual_names.add(name.replace(".to_qkv.", ".to_v."))
if self._include_add_kv_proj_virtuals and ".add_kv_proj." in name:
virtual_names.add(name.replace(".add_kv_proj.", ".add_q_proj."))
virtual_names.add(name.replace(".add_kv_proj.", ".add_k_proj."))
virtual_names.add(name.replace(".add_kv_proj.", ".add_v_proj."))
if self._include_w13_virtuals and ".w13." in name:
virtual_names.add(name.replace(".w13.", ".w1."))
virtual_names.add(name.replace(".w13.", ".w3."))
if self._include_to_out_virtuals and ".to_out." in name:
virtual_names.add(name.replace(".to_out.", ".to_out.0."))
allowed.update(virtual_names)
return allowed
def _build_param_names(self) -> set[str]:
target = self._get_target_module()
return {name for name, _ in target.named_parameters()}
def _resolve_linear_qweight(self, name: str, param_names: set[str]) -> str | None:
if not name.endswith(".weight"):
return None
if self._prefer_exact_qweight:
candidate = name.replace(".weight", ".qweight")
if candidate in param_names:
return candidate
if ".to_out.0." in name:
alt_name = name.replace(".to_out.0.", ".to_out.")
candidate = alt_name.replace(".weight", ".qweight")
if candidate in param_names:
return candidate
name = alt_name
for shard_token in self._shard_tokens:
if shard_token in name:
return name.replace(".weight", ".qweight")
candidate = name.replace(".weight", ".qweight")
if candidate in param_names:
return candidate
return None
def _build_gguf_name_map(self) -> dict[str, str]:
def resolve_model_type() -> str:
cfg = self.od_config.tf_model_config
model_type = None
if cfg is not None:
model_type = cfg.get("model_type")
if model_type:
return model_type
model_class = self.od_config.model_class_name or ""
if model_class.startswith("QwenImage"):
return "qwen_image"
if model_class.startswith("Flux2"):
return "flux"
raise ValueError("Cannot infer gguf model_type for diffusion model.")
def resolve_arch(model_type: str):
for key, value in gguf.MODEL_ARCH_NAMES.items():
if value == model_type:
return key
raise RuntimeError(f"Unknown gguf model_type: {model_type}")
def resolve_num_layers(target_module: torch.nn.Module) -> int:
if hasattr(target_module, "transformer_blocks"):
return len(getattr(target_module, "transformer_blocks"))
if hasattr(target_module, "double_blocks"):
return len(getattr(target_module, "double_blocks"))
cfg = self.od_config.tf_model_config
if cfg is not None:
for key in ("num_hidden_layers", "num_layers", "n_layers"):
value = cfg.get(key)
if isinstance(value, int) and value > 0:
return value
raise ValueError("Cannot infer gguf num_layers for diffusion model.")
def get_target_module(root: torch.nn.Module, prefix: str) -> torch.nn.Module:
if not prefix:
return root
prefix = prefix.rstrip(".")
if hasattr(root, "get_submodule"):
return root.get_submodule(prefix)
current = root
for part in prefix.split("."):
current = getattr(current, part)
return current
def split_name(name: str) -> tuple[str, str]:
if name.endswith("_weight"):
return name[:-7], "weight"
if "." in name:
base, suffix = name.rsplit(".", 1)
return base, suffix
return name, ""
reader = gguf.GGUFReader(self.gguf_file)
gguf_tensor_names = {tensor.name for tensor in reader.tensors}
model_type = resolve_model_type()
arch = resolve_arch(model_type)
target_module = get_target_module(self.model, self.source.prefix)
num_layers = resolve_num_layers(target_module)
name_map = gguf.get_tensor_name_map(arch, num_layers)
gguf_to_model_map: dict[str, str] = {}
for name, _ in target_module.named_parameters():
base_name, suffix = split_name(name)
gguf_base = name_map.get_name(base_name)
if gguf_base is None:
continue
candidates = []
if suffix:
candidates.append(f"{gguf_base}.{suffix}")
if suffix == "weight":
candidates.append(f"{gguf_base}.scale")
else:
candidates.append(gguf_base)
gguf_name = next((c for c in candidates if c in gguf_tensor_names), None)
if gguf_name is None:
continue
gguf_to_model_map[gguf_name] = name
for name, _ in target_module.named_buffers():
base_name, suffix = split_name(name)
gguf_base = name_map.get_name(base_name)
if gguf_base is None:
continue
candidates = []
if suffix:
candidates.append(f"{gguf_base}.{suffix}")
if suffix == "weight":
candidates.append(f"{gguf_base}.scale")
else:
candidates.append(gguf_base)
gguf_name = next((c for c in candidates if c in gguf_tensor_names), None)
if gguf_name is None:
continue
gguf_to_model_map[gguf_name] = name
if not gguf_to_model_map:
raise RuntimeError(f"No GGUF tensors were mapped for model_class_name={self.od_config.model_class_name!r}.")
return gguf_to_model_map
# FIXME(Isotr0py): Sync implemnentation with upstream vLLM?
def gguf_quant_weights_iterator(gguf_file: str) -> Generator[tuple[str, torch.Tensor]]:
"""
Iterate over the quant weights in the model gguf files and convert
them to torch tensors.
Be careful of the order of yielding weight types and weights data,
we have to yield all weight types first before yielding any weights.
Otherwise it would cause issue when loading weights with for packed
layer with different quant types.
"""
reader = gguf.GGUFReader(gguf_file)
for tensor in reader.tensors:
weight_type = tensor.tensor_type
name = tensor.name
if weight_type.name not in ("F32", "F16"):
weight_type_name = name.replace("weight", "qweight_type")
weight_type = torch.tensor(weight_type)
yield weight_type_name, weight_type
for tensor in reader.tensors:
weight = tensor.data
weight_type = tensor.tensor_type
name = tensor.name
if weight_type.name not in ("F32", "F16"):
name = name.replace("weight", "qweight")
if weight_type.name == "BF16" and tensor.data.dtype == np.uint8:
# BF16 is currently the only "quantization" type that isn't
# actually quantized but is read as a raw byte tensor.
# Reinterpret as `torch.bfloat16` tensor.
weight = weight.view(np.uint16)
if reader.byte_order == "S":
# GGUF endianness != system endianness
weight = weight.byteswap()
param = torch.tensor(weight).view(torch.bfloat16)
else:
param = torch.tensor(weight)
yield name, param
@@ -0,0 +1,98 @@
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
from collections.abc import Iterable
import torch
from vllm.model_executor.models.utils import WeightsMapper
from .base import GGUFAdapter, gguf_quant_weights_iterator
FLUX2_TRANSFORMER_KEYS_RENAME_DICT = {
"single_blocks.": "single_transformer_blocks.",
# Image and text input projections
"img_in": "x_embedder",
"txt_in": "context_embedder",
# Timestep and guidance embeddings
"time_in.in_layer": "time_guidance_embed.timestep_embedder.linear_1",
"time_in.out_layer": "time_guidance_embed.timestep_embedder.linear_2",
"guidance_in.in_layer": "time_guidance_embed.guidance_embedder.linear_1",
"guidance_in.out_layer": "time_guidance_embed.guidance_embedder.linear_2",
# Modulation parameters
"double_stream_modulation_img.lin": "double_stream_modulation_img.linear",
"double_stream_modulation_txt.lin": "double_stream_modulation_txt.linear",
"single_stream_modulation.lin": "single_stream_modulation.linear",
# Final output layer
# "final_layer.adaLN_modulation.1": "norm_out.linear", # Handle separately since we need to swap mod params
"final_layer.linear": "proj_out",
}
FLUX2_TRANSFORMER_ADA_LAYER_NORM_KEY_MAP = {
"final_layer.adaLN_modulation.1": "norm_out.linear",
}
FLUX2_TRANSFORMER_DOUBLE_BLOCK_KEY_MAP = {
"double_blocks.": "transformer_blocks.",
# Handle fused QKV projections separately as we need to break into Q, K, V projections
"img_attn.norm.query_norm": "attn.norm_q",
"img_attn.norm.key_norm": "attn.norm_k",
"img_attn.proj": "attn.to_out.0",
"img_mlp.0": "ff.linear_in",
"img_mlp.2": "ff.linear_out",
"txt_attn.norm.query_norm": "attn.norm_added_q",
"txt_attn.norm.key_norm": "attn.norm_added_k",
"txt_attn.proj": "attn.to_add_out",
"txt_mlp.0": "ff_context.linear_in",
"txt_mlp.2": "ff_context.linear_out",
# Additional for fuse qkv
"img_attn.qkv": "attn.to_qkv",
"txt_attn.qkv": "attn.add_kv_proj",
}
FLUX2_TRANSFORMER_SINGLE_BLOCK_KEY_MAP = {
"linear1": "attn.to_qkv_mlp_proj",
"linear2": "attn.to_out",
"norm.query_norm": "attn.norm_q",
"norm.key_norm": "attn.norm_k",
}
class Flux2KleinGGUFAdapter(GGUFAdapter):
"""GGUF adapter for Flux2-Klein models with qkv splitting and adaLN swap."""
@staticmethod
def is_compatible(od_config, model: torch.nn.Module, source) -> bool:
model_class = od_config.model_class_name or ""
if model_class.startswith("Flux2"):
return True
cfg = od_config.tf_model_config
if cfg is not None:
model_type = str(cfg.get("model_type", "")).lower()
if model_type.startswith("flux"):
return True
return False
gguf_to_hf_mapper = WeightsMapper(
# double_stream_modulation
orig_to_new_prefix=FLUX2_TRANSFORMER_KEYS_RENAME_DICT | FLUX2_TRANSFORMER_ADA_LAYER_NORM_KEY_MAP,
orig_to_new_substr=FLUX2_TRANSFORMER_DOUBLE_BLOCK_KEY_MAP | FLUX2_TRANSFORMER_SINGLE_BLOCK_KEY_MAP,
)
def weights_iterator(self) -> Iterable[tuple[str, torch.Tensor]]:
def custom_weights_adapter(
weights: Iterable[tuple[str, torch.Tensor]],
) -> Iterable[tuple[str, torch.Tensor]]:
for name, weight in weights:
# Handle the special case for adaLN modulation parameters that require swapping shift and scale
if name.endswith(".scale"):
name = name.replace(".scale", ".weight")
if name == "norm_out.linear.weight":
shift, scale = weight.chunk(2, dim=0)
weight = torch.cat([scale, shift], dim=0)
yield name, weight
else:
yield name, weight
weights = gguf_quant_weights_iterator(self.gguf_file)
weights = self.gguf_to_hf_mapper.apply(weights)
yield from custom_weights_adapter(weights)
@@ -0,0 +1,43 @@
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
from collections.abc import Iterable
import torch
from vllm.model_executor.models.utils import WeightsMapper
from .base import GGUFAdapter, gguf_quant_weights_iterator
Z_IMAGE_KEYS_RENAME_DICT = {
"final_layer.": "all_final_layer.2-1.",
"x_embedder.": "all_x_embedder.2-1.",
".attention.qkv": ".attention.to_qkv",
".attention.k_norm": ".attention.norm_k",
".attention.q_norm": ".attention.norm_q",
".attention.out": ".attention.to_out.0",
"model.diffusion_model.": "",
}
class ZImageGGUFAdapter(GGUFAdapter):
"""GGUF adapter for Z-Image models with QKV/FFN shard support."""
@staticmethod
def is_compatible(od_config, model: torch.nn.Module, source) -> bool:
model_class = od_config.model_class_name or ""
if model_class.startswith("ZImage"):
return True
cfg = od_config.tf_model_config
if cfg is not None:
model_type = str(cfg.get("model_type", "")).lower()
if model_type in {"z_image", "zimage", "z-image"}:
return True
return False
gguf_to_hf_mapper = WeightsMapper(
orig_to_new_substr=Z_IMAGE_KEYS_RENAME_DICT,
)
def weights_iterator(self) -> Iterable[tuple[str, torch.Tensor]]:
weights = gguf_quant_weights_iterator(self.gguf_file)
yield from self.gguf_to_hf_mapper.apply(weights)