Flux.1をPythonで動かす方法

間違いなどがあったら指摘していただけるとうれしいです。質問もお待ちしています。

Nvidia関係のコマンド

nvidia-smi
nvcc -V

コマンド

1:

python -m venv venv

2:

.\venv\Scripts\activate

3:

pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu124

4:

コマンド4は必要ありません。飛ばしてください

5:

pip install --upgrade transformers diffusers

6:

pip install transformers accelerate optimum-quanto sentencepiece protobuf

プログラム

import torch
from diffusers import FluxPipeline

pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16)
pipe.enable_sequential_cpu_offload()
pipe.vae.enable_slicing()
pipe.vae.enable_tiling()

pipe.to(torch.float16)

prompt = "A cat holding a sign that says hello world"
out = pipe(
    prompt=prompt,
    guidance_scale=0.,
    height=768,
    width=1360,
    num_inference_steps=4,
    max_sequence_length=256,
).images[0]
out.save("image.png")

プログラム改良版

import torch
import datetime
from diffusers import FluxPipeline

now = datetime.datetime.now()
formatted_now = now.strftime("%Y%m%d_%H%M%S")

pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16)
pipe.enable_sequential_cpu_offload()
pipe.vae.enable_slicing()
pipe.vae.enable_tiling()

pipe.to(torch.float16)

prompt = input("prompt:")
out = pipe(
    prompt=prompt,
    guidance_scale=0.,
    height=768,
    width=1360,
    num_inference_steps=4,
    max_sequence_length=256,
).images[0]
out.save(f"{formatted_now}.png")

Gradio(おまけ)

pip install gradio
schnell-Download
dev-Download

※dev版の実行にはアクセストークンが必要です

リンクなど