本地部署 Qwen-Image 文生图:完整流程与避坑指南

目录

环境安装:

推理代码:

封装server:


环境安装:

bash 复制代码
pip install git+https://github.com/huggingface/diffusers

pip install accelerate

推理代码:

python 复制代码
import torch
from diffusers import QwenImage21Pipeline

pipe = QwenImage21Pipeline.from_pretrained(
    "/data/feature/0lbg/models/Qwen_Qwen-Image-2.1", 
    torch_dtype=torch.bfloat16
)

# 关键:用 offload 替代 .to("cuda")
pipe.enable_model_cpu_offload()

# 关键:VAE 解码阶段显存不够,必须开 tiling
pipe.vae.enable_tiling()

image = pipe(
    prompt='A neon shop sign that reads "QWEN IMAGE 2.1", rainy night, reflections on wet pavement',
    width=2048, height=2048,
    num_inference_steps=40,
    generator=torch.Generator("cuda").manual_seed(42),
).images[0]

image.save("t2i_example.png")

封装server:

python 复制代码
import io
import base64
import time
import uuid
from contextlib import asynccontextmanager

import torch
from fastapi import FastAPI, HTTPException
from fastapi.responses import Response
from pydantic import BaseModel, Field
from diffusers import QwenImage21Pipeline
import uvicorn

# ---------- 全局 pipeline ----------
pipe = None


@asynccontextmanager
async def lifespan(app: FastAPI):
    global pipe
    print("Loading Qwen-Image-2.1 pipeline ...")
    t0 = time.time()
    pipe = QwenImage21Pipeline.from_pretrained(
        "/data/feature/0lbg/models/Qwen_Qwen-Image-2.1",
        torch_dtype=torch.bfloat16,
    )
    pipe.enable_model_cpu_offload()
    pipe.vae.enable_tiling()
    print(f"Pipeline loaded in {time.time() - t0:.1f}s")
    yield
    # 关闭时释放
    del pipe
    torch.cuda.empty_cache()


app = FastAPI(title="Qwen-Image-2.1 T2I Server", lifespan=lifespan)


# ---------- 请求体 ----------
class T2IRequest(BaseModel):
    prompt: str = Field(..., description="正向提示词")
    negative_prompt: str = Field("", description="负向提示词")
    width: int = Field(2048, ge=256, le=2048)
    height: int = Field(2048, ge=256, le=2048)
    num_inference_steps: int = Field(40, ge=1, le=100)
    true_cfg_scale: float = Field(4.0, ge=0.0, le=20.0)
    seed: int | None = Field(None, description="不传则随机")


# ---------- 接口 ----------
@app.get("/health")
def health():
    return {"status": "ok", "model_loaded": pipe is not None}


@app.post("/generate")
def generate(req: T2IRequest):
    if pipe is None:
        raise HTTPException(status_code=503, detail="Model not loaded yet")

    # seed:不传则随机
    if req.seed is None:
        seed = torch.randint(0, 2**31 - 1, (1,)).item()
    else:
        seed = req.seed
    generator = torch.Generator("cuda").manual_seed(seed)

    try:
        image = pipe(
            prompt=req.prompt,
            negative_prompt=req.negative_prompt or None,
            width=req.width,
            height=req.height,
            num_inference_steps=req.num_inference_steps,
            true_cfg_scale=req.true_cfg_scale,
            generator=generator,
        ).images[0]
    except torch.cuda.OutOfMemoryError as e:
        torch.cuda.empty_cache()
        raise HTTPException(status_code=507, detail=f"CUDA OOM: {e}")

    # 返回 PNG 二进制
    buf = io.BytesIO()
    image.save(buf, format="PNG")
    buf.seek(0)

    return Response(
        content=buf.getvalue(),
        media_type="image/png",
        headers={
            "X-Seed": str(seed),
            "Content-Disposition": f'attachment; filename="{uuid.uuid4().hex}.png"',
        },
    )


@app.post("/generate_b64")
def generate_b64(req: T2IRequest):
    """返回 base64,方便前端直接展示。"""
    if pipe is None:
        raise HTTPException(status_code=503, detail="Model not loaded yet")

    seed = req.seed if req.seed is not None else torch.randint(0, 2**31 - 1, (1,)).item()
    generator = torch.Generator("cuda").manual_seed(seed)

    try:
        image = pipe(
            prompt=req.prompt,
            negative_prompt=req.negative_prompt or None,
            width=req.width,
            height=req.height,
            num_inference_steps=req.num_inference_steps,
            true_cfg_scale=req.true_cfg_scale,
            generator=generator,
        ).images[0]
    except torch.cuda.OutOfMemoryError as e:
        torch.cuda.empty_cache()
        raise HTTPException(status_code=507, detail=f"CUDA OOM: {e}")

    buf = io.BytesIO()
    image.save(buf, format="PNG")
    b64 = base64.b64encode(buf.getvalue()).decode("utf-8")
    return {"seed": seed, "format": "png", "image_base64": b64}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=7999)
相关推荐
aicat_cn8 小时前
90+测试点扒完腾讯混元Hy3D 3.6:单图带贴图约1.1美元、中位4分钟出,文档里还藏着这些坑
ai·大模型
香吧香9 小时前
彻底搞懂向量以及向量应用
大模型
神奇的代码在哪里1 天前
Thinking Machines 开源 Inkling 2 Mini:26.4B 总参、5.4B 有效激活,20GB 单文件本地可跑
大模型·transformer·模型部署·多模态·moe·开源模型
香吧香1 天前
Qdrant 实战学习指南
大模型
武雄(小星Ai)3 天前
大模型API逆向实战:用延迟指纹判断后端是不是换皮Qwen
ai·性能优化·大模型
AllData公司负责人5 天前
实战一:AllData大模型与AI数据底座-数据传输平台-DBSyncer,搭建 File 到 Doris 高效数据同步链路,批量文件离线入仓
数据库·人工智能·分布式·大模型·数据传输·数据同步·连接器
aicat_cn6 天前
AI Studio 做的安卓 App 有后端了,Gemini 密钥不用塞进 APK
ai·大模型
JonaHu6 天前
AceDataCloud Coding Plan 多模型编程:从 Chat Completions 迁移到 Responses API 与工具调用
python·大模型·api·ai编程·acedatacloud
吴名氏.7 天前
从零手写一个 AI Agent 框架(TypeScript 完整实现):Function Calling 循环、流式输出与错误恢复
人工智能·typescript·node.js·大模型·ai agent·functioncalling·llm 应用开发
深海鱼肝油ya7 天前
Agent工具系统——Tool Calling & Schema
人工智能·大模型·agent·schema·智能体·工具调用·toolcalling