Diffusers 文件

建立伺服器

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

建立伺服器

Diffusers 的流水線可以作為伺服器的推理引擎。它支援併發和多執行緒請求,以生成可能同時被多個使用者請求的影像。

本指南將向您展示如何在伺服器中使用 StableDiffusion3Pipeline,但您可以隨意使用任何您想要的流水線。

首先導航到 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-toolsuv。例如,使用以下命令透過 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))

此時,流水線函式的執行被放置到 新執行緒 上,主執行緒執行其他操作,直到流水線返回結果。

此實現中的另一個重要方面是從 shared_pipeline 建立一個 pipeline。這樣做的目的是避免將底層模型多次載入到 GPU 上,同時仍然允許在單獨執行緒上執行的每個新請求擁有自己的生成器和排程器。特別是,排程器不是執行緒安全的,如果您嘗試在多個執行緒上使用同一個排程器,它將導致諸如 IndexError: index 21 is out of bounds for dimension 0 with size 21 之類的錯誤。

< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.