[Core] Unified quantization framework (#1764)

This commit is contained in:
SYLAR authored and GitHub committed 2026-03-24 18:56:55 +08:00
1 parent 2a630313ce
commit 6b93459826
40 files changed
+3306 -605

No files matched your search

@@ -0,0 +1,129 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
"""Compute LPIPS between pairs of BF16 (baseline) and FP8 (quantized) images.
Reads image pairs from a directory, computes LPIPS perceptual distance,
and prints a Markdown results table.
Usage:
python compute_lpips.py --image-dir ./test_quant_outputs
Expects files named: <model>_bf16.png and <model>_fp8.png
e.g. zimage_bf16.png / zimage_fp8.png, qwen_bf16.png / qwen_fp8.png
Requirements:
pip install lpips Pillow torchvision
"""
import argparse
import sys
from pathlib import Path
def compute_lpips(img_baseline, img_quantized, net="alex"):
"""Compute LPIPS between two PIL images."""
import lpips
import torch
from torchvision import transforms
loss_fn = lpips.LPIPS(net=net).eval()
if torch.cuda.is_available():
loss_fn = loss_fn.cuda()
transform = transforms.Compose(
[
transforms.Resize((256, 256)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5]),
]
)
t_bl = transform(img_baseline.convert("RGB")).unsqueeze(0)
t_qt = transform(img_quantized.convert("RGB")).unsqueeze(0)
if torch.cuda.is_available():
t_bl, t_qt = t_bl.cuda(), t_qt.cuda()
with torch.no_grad():
score = loss_fn(t_bl, t_qt).item()
return score
def main():
parser = argparse.ArgumentParser(description="Compute LPIPS for BF16 vs FP8 image pairs.")
parser.add_argument(
"--image-dir", type=str, required=True, help="Directory containing *_bf16.png and *_fp8.png pairs."
)
parser.add_argument("--threshold", type=float, default=0.1, help="LPIPS threshold for PASS/FAIL (default: 0.1).")
parser.add_argument(
"--net", type=str, default="alex", choices=["alex", "vgg", "squeeze"], help="LPIPS backbone (default: alex)."
)
args = parser.parse_args()
from PIL import Image
image_dir = Path(args.image_dir)
if not image_dir.exists():
print(f"ERROR: directory {image_dir} does not exist")
sys.exit(1)
# Find all *_bf16.png files and look for matching *_fp8.png
bf16_files = sorted(image_dir.glob("*_bf16.png"))
if not bf16_files:
print(f"No *_bf16.png files found in {image_dir}")
sys.exit(0)
results = []
all_pass = True
for bf16_path in bf16_files:
model_name = bf16_path.stem.replace("_bf16", "")
fp8_path = image_dir / f"{model_name}_fp8.png"
if not fp8_path.exists():
print(f" SKIP {model_name}: no matching {fp8_path.name}")
continue
img_bl = Image.open(bf16_path)
img_fp8 = Image.open(fp8_path)
score = compute_lpips(img_bl, img_fp8, net=args.net)
status = "PASS" if score < args.threshold else "FAIL"
if score >= args.threshold:
all_pass = False
results.append(
(model_name, score, status, f"{img_bl.width}x{img_bl.height}", f"{img_fp8.width}x{img_fp8.height}")
)
# Print results table
print("")
print("=" * 70)
print(f" LPIPS Results (net={args.net}, threshold={args.threshold})")
print("=" * 70)
print(f" {'Model':<20} {'LPIPS':>8} {'Status':>8} {'BF16 size':>12} {'FP8 size':>12}")
print(f" {'-' * 20} {'-' * 8} {'-' * 8} {'-' * 12} {'-' * 12}")
for model_name, score, status, sz_bl, sz_fp8 in results:
print(f" {model_name:<20} {score:>8.4f} {status:>8} {sz_bl:>12} {sz_fp8:>12}")
print("")
print(" LPIPS < 0.01 = imperceptible")
print(" LPIPS < 0.05 = minor differences")
print(" LPIPS < 0.10 = noticeable but acceptable")
print(" LPIPS > 0.10 = clearly different")
print("=" * 70)
# Markdown table for PR
md_path = image_dir / "lpips_results.md"
with open(md_path, "w") as f:
f.write("## LPIPS Quality Benchmark (BF16 vs FP8)\n\n")
f.write(f"LPIPS backbone: `{args.net}` | threshold: `{args.threshold}`\n\n")
f.write("| Model | LPIPS | Status | BF16 Size | FP8 Size |\n")
f.write("|-------|-------|--------|-----------|----------|\n")
for model_name, score, status, sz_bl, sz_fp8 in results:
emoji = "✅" if status == "PASS" else "❌"
f.write(f"| {model_name} | {score:.4f} | {emoji} {status} | {sz_bl} | {sz_fp8} |\n")
f.write(f"\n> LPIPS < {args.threshold} = PASS\n")
print(f" Markdown saved to: {md_path}")
if not all_pass:
sys.exit(1)
if __name__ == "__main__":
main()
@@ -0,0 +1,200 @@
#!/bin/bash
# End-to-end test script for unified quantization framework (PR #1764).
#
# Tests FP8 quantization for:
# 1. Z-Image-Turbo (single-stage, ~20GB VRAM)
# 2. Qwen-Image (single-stage, ~20GB VRAM)
# 3. FLUX.1-dev (single-stage, ~25GB VRAM with fp8)
# 4. BAGEL (multi-stage LLM+DiT, ~55GB VRAM)
#
# Usage:
# bash tests/e2e/offline_inference/run_quantization_e2e.sh [--skip-flux] [--skip-bagel]
#
# Expected: all runs produce images without errors.
# Key check for BAGEL: FP8 only applies to diffusion stage, NOT the LLM stage.
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"
OUTPUT_DIR="${REPO_ROOT}/test_quant_outputs"
mkdir -p "$OUTPUT_DIR"
SKIP_FLUX=false
SKIP_BAGEL=false
for arg in "$@"; do
case "$arg" in
--skip-flux) SKIP_FLUX=true ;;
--skip-bagel) SKIP_BAGEL=true ;;
esac
done
PASS=0
FAIL=0
SKIP=0
run_test() {
local name="$1"
shift
echo ""
echo "============================================================"
echo " TEST: $name"
echo "============================================================"
if "$@"; then
echo " PASS: $name"
PASS=$((PASS + 1))
else
echo " FAIL: $name (exit code $?)"
FAIL=$((FAIL + 1))
fi
}
# ─── 1. Z-Image-Turbo ────────────────────────────────────────────────────────
# Defaults from README: 1024x1024, 50 steps, cfg-scale 4.0, seed 42
run_test "Z-Image-Turbo BF16 (baseline)" \
python "$REPO_ROOT/examples/offline_inference/text_to_image/text_to_image.py" \
--model Tongyi-MAI/Z-Image-Turbo \
--prompt "a cup of coffee on the table" \
--seed 42 --num-inference-steps 50 \
--height 1024 --width 1024 \
--cfg-scale 4.0 \
--output "$OUTPUT_DIR/zimage_bf16.png"
run_test "Z-Image-Turbo FP8" \
python "$REPO_ROOT/examples/offline_inference/text_to_image/text_to_image.py" \
--model Tongyi-MAI/Z-Image-Turbo \
--prompt "a cup of coffee on the table" \
--seed 42 --num-inference-steps 50 \
--height 1024 --width 1024 \
--cfg-scale 4.0 \
--quantization fp8 \
--output "$OUTPUT_DIR/zimage_fp8.png"
# ─── 2. Qwen-Image ───────────────────────────────────────────────────────────
# Defaults from README: 1024x1024, 50 steps, cfg-scale 4.0, seed 142
run_test "Qwen-Image BF16 (baseline)" \
python "$REPO_ROOT/examples/offline_inference/text_to_image/text_to_image.py" \
--model Qwen/Qwen-Image \
--prompt "a cup of coffee on the table" \
--seed 142 --num-inference-steps 50 \
--height 1024 --width 1024 \
--cfg-scale 4.0 \
--output "$OUTPUT_DIR/qwen_bf16.png"
run_test "Qwen-Image FP8" \
python "$REPO_ROOT/examples/offline_inference/text_to_image/text_to_image.py" \
--model Qwen/Qwen-Image \
--prompt "a cup of coffee on the table" \
--seed 142 --num-inference-steps 50 \
--height 1024 --width 1024 \
--cfg-scale 4.0 \
--quantization fp8 \
--output "$OUTPUT_DIR/qwen_fp8.png"
# ─── 3. FLUX.1-dev ───────────────────────────────────────────────────────────
# Defaults from first test run: 1024x1024, 20 steps, guidance-scale 3.5
if [ "$SKIP_FLUX" = true ]; then
echo ""
echo " SKIP: FLUX.1-dev (--skip-flux)"
SKIP=$((SKIP + 1))
SKIP=$((SKIP + 1))
else
run_test "FLUX.1-dev BF16 (baseline)" \
python "$REPO_ROOT/examples/offline_inference/text_to_image/text_to_image.py" \
--model black-forest-labs/FLUX.1-dev \
--prompt "a cup of coffee on the table" \
--seed 42 --num-inference-steps 20 \
--height 1024 --width 1024 \
--guidance-scale 3.5 --cfg-scale 1.0 \
--output "$OUTPUT_DIR/flux_bf16.png"
run_test "FLUX.1-dev FP8" \
python "$REPO_ROOT/examples/offline_inference/text_to_image/text_to_image.py" \
--model black-forest-labs/FLUX.1-dev \
--prompt "a cup of coffee on the table" \
--seed 42 --num-inference-steps 20 \
--height 1024 --width 1024 \
--guidance-scale 3.5 --cfg-scale 1.0 \
--quantization fp8 \
--output "$OUTPUT_DIR/flux_fp8.png"
fi
# ─── 4. BAGEL (multi-stage) ──────────────────────────────────────────────────
# Defaults from README: 50 steps, cfg-text-scale 4.0, cfg-img-scale 1.5
# BAGEL end2end.py saves images as output_1_stage_None_0.png in cwd.
# We copy them to OUTPUT_DIR with proper names for LPIPS comparison.
if [ "$SKIP_BAGEL" = true ]; then
echo ""
echo " SKIP: BAGEL (--skip-bagel)"
SKIP=$((SKIP + 1))
SKIP=$((SKIP + 1))
else
BAGEL_WORKDIR=$(mktemp -d)
run_test "BAGEL BF16 (baseline)" \
bash -c "cd '$BAGEL_WORKDIR' && python '$REPO_ROOT/examples/offline_inference/bagel/end2end.py' \
--model ByteDance-Seed/BAGEL-7B-MoT \
--modality text2img \
--prompts 'A cute cat' \
--steps 50 \
--cfg-text-scale 4.0 \
--cfg-img-scale 1.5 \
--seed 52 \
&& cp -f output_1_stage_None_0.png '$OUTPUT_DIR/bagel_bf16.png'"
run_test "BAGEL FP8 (diffusion-only quantization)" \
bash -c "cd '$BAGEL_WORKDIR' && python '$REPO_ROOT/examples/offline_inference/bagel/end2end.py' \
--model ByteDance-Seed/BAGEL-7B-MoT \
--modality text2img \
--prompts 'A cute cat' \
--steps 50 \
--cfg-text-scale 4.0 \
--cfg-img-scale 1.5 \
--seed 52 \
--quantization fp8 \
&& cp -f output_1_stage_None_0.png '$OUTPUT_DIR/bagel_fp8.png'"
rm -rf "$BAGEL_WORKDIR"
fi
# ─── 5. LPIPS quality comparison ─────────────────────────────────────────────
# Compares each BF16/FP8 image pair using perceptual LPIPS distance.
# Requires: pip install lpips torchvision
echo ""
echo "============================================================"
echo " LPIPS Quality Comparison"
echo "============================================================"
if python -c "import lpips" 2>/dev/null; then
run_test "LPIPS BF16-vs-FP8 quality check" \
python "$SCRIPT_DIR/compute_lpips.py" \
--image-dir "$OUTPUT_DIR" \
--threshold 0.1
else
echo " SKIP: lpips not installed (pip install lpips torchvision)"
SKIP=$((SKIP + 1))
fi
# ─── Summary ─────────────────────────────────────────────────────────────────
echo ""
echo "============================================================"
echo " SUMMARY"
echo "============================================================"
echo " PASS: $PASS"
echo " FAIL: $FAIL"
echo " SKIP: $SKIP"
echo " Output images: $OUTPUT_DIR/"
if [ -f "$OUTPUT_DIR/lpips_results.md" ]; then
echo " LPIPS report: $OUTPUT_DIR/lpips_results.md"
fi
echo "============================================================"
if [ "$FAIL" -gt 0 ]; then
exit 1
fi
@@ -0,0 +1,323 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""
End-to-end tests for the unified quantization framework (PR #1764).
Validates FP8 quantization works correctly for all supported model types:
- Single-stage diffusion models (FLUX.1-dev, Qwen-Image, Z-Image-Turbo)
- Multi-stage models (BAGEL: LLM + Diffusion)
Tests verify:
1. FP8 quantization produces valid images
2. Memory usage is lower than BF16 baseline
3. Multi-stage models only quantize the diffusion stage (not the LLM stage)
Usage:
# Run all FP8 quantization tests
pytest tests/e2e/offline_inference/test_quantization_fp8.py -v
# Run single-stage tests only (faster, needs ~25GB VRAM)
pytest tests/e2e/offline_inference/test_quantization_fp8.py -v -k "single_stage"
# Run BAGEL multi-stage test (needs ~55GB VRAM, H100 recommended)
pytest tests/e2e/offline_inference/test_quantization_fp8.py -v -k "bagel"
# Run FLUX test only
pytest tests/e2e/offline_inference/test_quantization_fp8.py -v -k "flux"
"""
import os
os.environ["VLLM_WORKER_MULTIPROC_METHOD"] = "spawn"
os.environ["VLLM_TEST_CLEAN_GPU_MEMORY"] = "1"
from pathlib import Path
from typing import Any
import pytest
import torch
from tests.utils import hardware_test
from vllm_omni.entrypoints.omni import Omni
from vllm_omni.inputs.data import OmniDiffusionSamplingParams
from vllm_omni.outputs import OmniRequestOutput
from vllm_omni.platforms import current_omni_platform
pytestmark = [pytest.mark.core_model, pytest.mark.diffusion]
# ─── helpers ──────────────────────────────────────────────────────────────────
def _generate_single_stage_image(
model: str,
quantization: str | None = None,
height: int = 256,
width: int = 256,
num_inference_steps: int = 2,
seed: int = 42,
**extra_omni_kwargs: Any,
) -> tuple[list, float]:
"""Generate an image with a single-stage diffusion model.
Returns (images, peak_memory_gib).
"""
omni_kwargs: dict[str, Any] = {"model": model, **extra_omni_kwargs}
if quantization:
omni_kwargs["quantization"] = quantization
omni = Omni(**omni_kwargs)
try:
torch.cuda.reset_peak_memory_stats()
generator = torch.Generator(device=current_omni_platform.device_type).manual_seed(seed)
outputs = omni.generate(
"a photo of a cat sitting on a laptop keyboard",
OmniDiffusionSamplingParams(
height=height,
width=width,
num_inference_steps=num_inference_steps,
guidance_scale=0.0,
generator=generator,
),
)
peak_mem = torch.cuda.max_memory_allocated() / (1024**3)
first_output = outputs[0]
assert first_output.final_output_type == "image"
assert hasattr(first_output, "request_output") and first_output.request_output
req_out = first_output.request_output[0]
assert isinstance(req_out, OmniRequestOutput) and hasattr(req_out, "images")
images = req_out.images
assert len(images) >= 1
assert images[0].width == width
assert images[0].height == height
return images, peak_mem
finally:
omni.close()
def _generate_bagel_image(
quantization_config: str | None = None,
num_inference_steps: int = 15,
) -> tuple[Any, float]:
"""Generate an image with BAGEL (multi-stage: LLM + Diffusion).
Returns (generated_image, peak_memory_gib).
"""
config_path = str(Path(__file__).parent / "stage_configs" / "bagel_sharedmemory_ci.yaml")
omni_kwargs: dict[str, Any] = {
"model": "ByteDance-Seed/BAGEL-7B-MoT",
"stage_configs_path": config_path,
"stage_init_timeout": 300,
}
if quantization_config:
omni_kwargs["quantization_config"] = quantization_config
omni = Omni(**omni_kwargs)
try:
torch.cuda.reset_peak_memory_stats()
params_list = omni.default_sampling_params_list
params_list[0].max_tokens = 1 # type: ignore
if len(params_list) > 1:
params_list[1].num_inference_steps = num_inference_steps # type: ignore
params_list[1].extra_args = { # type: ignore
"cfg_text_scale": 4.0,
"cfg_img_scale": 1.5,
}
prompt = "<|im_start|>A futuristic city skyline at twilight, cyberpunk style<|im_end|>"
omni_outputs = list(
omni.generate(
prompts=[{"prompt": prompt, "modalities": ["image"]}],
sampling_params_list=params_list,
)
)
peak_mem = torch.cuda.max_memory_allocated() / (1024**3)
# Extract image
generated_image = None
for req_output in omni_outputs:
if images := getattr(req_output, "images", None):
generated_image = images[0]
break
if hasattr(req_output, "request_output") and req_output.request_output:
for stage_out in req_output.request_output:
if hasattr(stage_out, "images") and stage_out.images:
generated_image = stage_out.images[0]
break
if generated_image:
break
assert generated_image is not None, "No images generated from BAGEL"
assert generated_image.size == (1024, 1024), f"Expected 1024x1024, got {generated_image.size}"
# Check LLM stage output — should have finish_reason=stop (not length)
for req_output in omni_outputs:
if hasattr(req_output, "request_output"):
for stage_out in req_output.request_output:
if hasattr(stage_out, "outputs"):
for comp_out in stage_out.outputs:
if hasattr(comp_out, "finish_reason"):
assert comp_out.finish_reason == "stop", (
f"LLM stage finish_reason={comp_out.finish_reason}, "
f"text={comp_out.text!r}. "
"FP8 may have leaked to the LLM stage."
)
return generated_image, peak_mem
finally:
omni.close()
# ─── Single-stage diffusion model tests ──────────────────────────────────────
@hardware_test(res={"cuda": "L4"})
def test_single_stage_zimage_fp8():
"""Z-Image-Turbo with FP8 generates valid images."""
images, _ = _generate_single_stage_image(
model="Tongyi-MAI/Z-Image-Turbo",
quantization="fp8",
)
assert len(images) >= 1
images[0].save("test_zimage_fp8.png")
@hardware_test(res={"cuda": "L4"})
def test_single_stage_zimage_fp8_uses_less_memory():
"""FP8 should use less peak memory than BF16 for Z-Image-Turbo."""
_, mem_bf16 = _generate_single_stage_image(
model="Tongyi-MAI/Z-Image-Turbo",
quantization=None,
)
torch.cuda.empty_cache()
_, mem_fp8 = _generate_single_stage_image(
model="Tongyi-MAI/Z-Image-Turbo",
quantization="fp8",
)
print(f"Z-Image BF16 peak memory: {mem_bf16:.2f} GiB")
print(f"Z-Image FP8 peak memory: {mem_fp8:.2f} GiB")
assert mem_fp8 < mem_bf16, f"FP8 ({mem_fp8:.2f} GiB) should use less memory than BF16 ({mem_bf16:.2f} GiB)"
@hardware_test(res={"cuda": "L4"})
def test_single_stage_qwen_image_fp8():
"""Qwen-Image (random weights) with FP8 generates valid images."""
model = "riverclouds/qwen_image_random"
if current_omni_platform.is_npu() or current_omni_platform.is_rocm():
pytest.skip("qwen_image_random not available on this platform")
images, _ = _generate_single_stage_image(
model=model,
quantization="fp8",
)
assert len(images) >= 1
images[0].save("test_qwen_image_fp8.png")
@hardware_test(res={"cuda": "H100"})
def test_single_stage_flux_fp8():
"""FLUX.1-dev with FP8 generates valid images."""
images, _ = _generate_single_stage_image(
model="black-forest-labs/FLUX.1-dev",
quantization="fp8",
height=512,
width=512,
num_inference_steps=4,
)
assert len(images) >= 1
images[0].save("test_flux_fp8.png")
@hardware_test(res={"cuda": "H100"})
def test_single_stage_flux_fp8_uses_less_memory():
"""FP8 should use less peak memory than BF16 for FLUX.1-dev."""
_, mem_bf16 = _generate_single_stage_image(
model="black-forest-labs/FLUX.1-dev",
quantization=None,
height=512,
width=512,
num_inference_steps=4,
)
torch.cuda.empty_cache()
_, mem_fp8 = _generate_single_stage_image(
model="black-forest-labs/FLUX.1-dev",
quantization="fp8",
height=512,
width=512,
num_inference_steps=4,
)
print(f"FLUX BF16 peak memory: {mem_bf16:.2f} GiB")
print(f"FLUX FP8 peak memory: {mem_fp8:.2f} GiB")
assert mem_fp8 < mem_bf16, f"FP8 ({mem_fp8:.2f} GiB) should use less memory than BF16 ({mem_bf16:.2f} GiB)"
# ─── Multi-stage model tests (BAGEL) ─────────────────────────────────────────
@hardware_test(res={"cuda": "H100"})
def test_bagel_fp8_generates_image():
"""BAGEL with FP8 quantization_config generates a valid image.
FP8 should only apply to the diffusion stage (Stage-1), not the
LLM stage (Stage-0). We verify this by checking:
1. Image is generated successfully
2. LLM stage finish_reason is 'stop' (not 'length' from garbled output)
"""
image, _ = _generate_bagel_image(quantization_config="fp8")
image.save("test_bagel_fp8.png")
@hardware_test(res={"cuda": "H100"})
def test_bagel_bf16_generates_image():
"""BAGEL without quantization generates a valid image (baseline)."""
image, _ = _generate_bagel_image(quantization_config=None)
image.save("test_bagel_bf16.png")
# ─── Quantization config routing tests ────────────────────────────────────────
@hardware_test(res={"cuda": "L4"})
def test_quantization_key_maps_to_quantization_config():
"""The old 'quantization' kwarg should map to 'quantization_config'
in OmniDiffusionConfig.from_kwargs for backwards compatibility."""
from vllm_omni.diffusion.data import OmniDiffusionConfig
config = OmniDiffusionConfig.from_kwargs(model="test", quantization="fp8")
assert config.quantization_config is not None
assert config.quantization_config.get_name() == "fp8"
@hardware_test(res={"cuda": "L4"})
def test_quantization_config_key_takes_priority():
"""When both 'quantization' and 'quantization_config' are set,
'quantization_config' takes priority."""
from vllm_omni.diffusion.data import OmniDiffusionConfig
config = OmniDiffusionConfig.from_kwargs(
model="test",
quantization="fp8",
quantization_config={"method": "fp8", "activation_scheme": "static"},
)
assert config.quantization_config is not None
assert config.quantization_config.activation_scheme == "static"
@hardware_test(res={"cuda": "L4"})
def test_single_stage_quantization_config_key():
"""Single-stage model using quantization_config (dict) key generates images."""
images, _ = _generate_single_stage_image(
model="Tongyi-MAI/Z-Image-Turbo",
quantization=None,
quantization_config="fp8",
)
assert len(images) >= 1