Diffusers 文档
创建服务器
并获取增强的文档体验
开始使用
创建服务器
Diffusers’ pipelines 可以用作服务器的推理引擎。它支持并发和多线程请求,以生成可能由多个用户同时请求的图像。
本指南将向您展示如何在服务器中使用 StableDiffusion3Pipeline,但您可以随意使用任何您想要的 pipeline。
首先导航到 examples/server
文件夹并安装所有依赖项。
pip install . pip install -f requirements.txt
使用以下命令启动服务器。
python server.py
服务器可通过 https://#:8000 访问。您可以使用以下命令 curl 此模型。
curl -X POST -H "Content-Type: application/json" --data '{"model": "something", "prompt": "a kitten in front of a fireplace"}' http://#:8000/v1/images/generations
如果您需要升级某些依赖项,您可以使用 pip-tools 或 uv。例如,使用以下命令通过 uv
升级依赖项。
uv pip compile requirements.in -o requirements.txt
该服务器使用 FastAPI 构建。下面显示了 v1/images/generations
的端点。
@app.post("/v1/images/generations")
async def generate_image(image_input: TextToImageInput):
try:
loop = asyncio.get_event_loop()
scheduler = shared_pipeline.pipeline.scheduler.from_config(shared_pipeline.pipeline.scheduler.config)
pipeline = StableDiffusion3Pipeline.from_pipe(shared_pipeline.pipeline, scheduler=scheduler)
generator = torch.Generator(device="cuda")
generator.manual_seed(random.randint(0, 10000000))
output = await loop.run_in_executor(None, lambda: pipeline(image_input.prompt, generator = generator))
logger.info(f"output: {output}")
image_url = save_image(output.images[0])
return {"data": [{"url": image_url}]}
except Exception as e:
if isinstance(e, HTTPException):
raise e
elif hasattr(e, 'message'):
raise HTTPException(status_code=500, detail=e.message + traceback.format_exc())
raise HTTPException(status_code=500, detail=str(e) + traceback.format_exc())
generate_image
函数被定义为异步函数,使用了 async 关键字,以便 FastAPI 知道此函数中发生的任何事情都不一定会立即返回结果。一旦它到达函数中需要等待其他 Task 的某个点,主线程就会返回以响应其他 HTTP 请求。这在下面的代码中通过 await 关键字显示。
output = await loop.run_in_executor(None, lambda: pipeline(image_input.prompt, generator = generator))
此时,pipeline 函数的执行被放置到一个 新线程 中,主线程执行其他操作,直到从 pipeline
返回结果。
此实现中的另一个重要方面是从 shared_pipeline
创建 pipeline
。这背后的目的是避免将底层模型多次加载到 GPU 上,同时仍然允许在单独线程上运行的每个新请求都拥有自己的生成器和调度器。特别是,调度器不是线程安全的,如果您尝试在多个线程中使用同一个调度器,则会导致错误,例如:IndexError: index 21 is out of bounds for dimension 0 with size 21
。