新闻详情

新闻详情

首页 / 资讯中心 / 详情

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

发布时间:2026/10/1 8:31:54来源:尧图网络
本地部署 Qwen-Image 文生图:完整流程与避坑指南
目录环境安装推理代码封装server环境安装pip install githttps://github.com/huggingface/diffusers pip install accelerate推理代码import torch from diffusers import QwenImage21Pipeline pipe QwenImage21Pipeline.from_pretrained( /data/feature/0lbg/models/Qwen_Qwen-Image-2.1, torch_dtypetorch.bfloat16 ) # 关键用 offload 替代 .to(cuda) pipe.enable_model_cpu_offload() # 关键VAE 解码阶段显存不够必须开 tiling pipe.vae.enable_tiling() image pipe( promptA neon shop sign that reads QWEN IMAGE 2.1, rainy night, reflections on wet pavement, width2048, height2048, num_inference_steps40, generatortorch.Generator(cuda).manual_seed(42), ).images[0] image.save(t2i_example.png)封装serverimport 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_dtypetorch.bfloat16, ) pipe.enable_model_cpu_offload() pipe.vae.enable_tiling() print(fPipeline loaded in {time.time() - t0:.1f}s) yield # 关闭时释放 del pipe torch.cuda.empty_cache() app FastAPI(titleQwen-Image-2.1 T2I Server, lifespanlifespan) # ---------- 请求体 ---------- class T2IRequest(BaseModel): prompt: str Field(..., description正向提示词) negative_prompt: str Field(, description负向提示词) width: int Field(2048, ge256, le2048) height: int Field(2048, ge256, le2048) num_inference_steps: int Field(40, ge1, le100) true_cfg_scale: float Field(4.0, ge0.0, le20.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_code503, detailModel 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( promptreq.prompt, negative_promptreq.negative_prompt or None, widthreq.width, heightreq.height, num_inference_stepsreq.num_inference_steps, true_cfg_scalereq.true_cfg_scale, generatorgenerator, ).images[0] except torch.cuda.OutOfMemoryError as e: torch.cuda.empty_cache() raise HTTPException(status_code507, detailfCUDA OOM: {e}) # 返回 PNG 二进制 buf io.BytesIO() image.save(buf, formatPNG) buf.seek(0) return Response( contentbuf.getvalue(), media_typeimage/png, headers{ X-Seed: str(seed), Content-Disposition: fattachment; filename{uuid.uuid4().hex}.png, }, ) app.post(/generate_b64) def generate_b64(req: T2IRequest): 返回 base64方便前端直接展示。 if pipe is None: raise HTTPException(status_code503, detailModel 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( promptreq.prompt, negative_promptreq.negative_prompt or None, widthreq.width, heightreq.height, num_inference_stepsreq.num_inference_steps, true_cfg_scalereq.true_cfg_scale, generatorgenerator, ).images[0] except torch.cuda.OutOfMemoryError as e: torch.cuda.empty_cache() raise HTTPException(status_code507, detailfCUDA OOM: {e}) buf io.BytesIO() image.save(buf, formatPNG) b64 base64.b64encode(buf.getvalue()).decode(utf-8) return {seed: seed, format: png, image_base64: b64} if __name__ __main__: uvicorn.run(app, host0.0.0.0, port7999)
网站建设高端定制企业官网
RELATED

相关资讯

更多精彩内容,欢迎继续阅读

较早相关资讯

最新相关资讯

ESXi定制ISO指南:用ESXi-Customizer-PS集成网卡驱动解决No Network Adapters 2026/10/1 9:27:08

ESXi定制ISO指南:用ESXi-Customizer-PS集成网卡驱动解决No Network Adapters

如果你玩过ESXi,大概率遇到过这种尴尬:镜像已经写进U盘,安装界面跑完引导,结果弹出一句No Network Adapters Found,整个流程直接卡死。我上个月给一台二手工作站装ESXi 8.0就撞上了——板载的Realtek R8125B完全不认&a…

阅读更多 →
PermissionError 报错根治:pip 权限不足与虚拟环境解决方案 2026/10/1 9:27:08

PermissionError 报错根治:pip 权限不足与虚拟环境解决方案

兄弟,看到PermissionError: [Errno 13] Permission denied这一行,是不是瞬间头皮发麻?别急,这基本上是每个玩 Python 的人都会碰到的一道坎,尤其是当你满心欢喜地 clone 了一个开源项目,准备用pip install …

阅读更多 →
理解Linux基础命令设计逻辑,掌握文件、进程与网络排查实战 2026/10/1 9:27:08

理解Linux基础命令设计逻辑,掌握文件、进程与网络排查实战

1. 先理解Linux命令的底层设计,再谈记忆命令很多刚接触Linux的朋友,包括我当年刚入职做运维的时候,都走入过一个误区:把Linux命令当成单词表去背。ls是列目录,cd是切换目录,cp是复制,mv是移动&a…

阅读更多 →
MongoDB固定集合(Capped Collection)原理、容量设计与Tailable游标实战指南 2026/10/1 9:26:55

MongoDB固定集合(Capped Collection)原理、容量设计与Tailable游标实战指南

固定集合这个名字,听起来像是 MongoDB 新手阶段练手才会碰的东西,但我个人觉得它恰恰是很多后端老手也会忽略的宝藏特性。最早我是做访问日志模块时真正领会到它的价值:一天上千万条日志,全量保存不可能,定期清理又会让…

阅读更多 →
火电厂DCS改造中控制逻辑组态迁移的实战方法论与避坑指南 2026/10/1 9:26:55

火电厂DCS改造中控制逻辑组态迁移的实战方法论与避坑指南

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

阅读更多 →
Windows分体工控越跑越卡?嵌入式一体化架构根治机器视觉量产稳定性 2026/10/1 9:26:54

Windows分体工控越跑越卡?嵌入式一体化架构根治机器视觉量产稳定性

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

阅读更多 →

今日资讯

本周资讯

本月资讯

看完文章仍有疑问?

联系尧图顾问,获取一对一建站咨询

立即免费咨询 📞 400-888-8888
📞 ✉