StreamDiffusion README

The project's README from github.com/cumulo-autumn/StreamDiffusion. As one markdown file: README.md.

StreamDiffusion

English | 日本語 | 한국어

StreamDiffusion: A Pipeline-Level Solution for Real-Time Interactive Generation

Authors: Akio Kodaira*, Chenfeng Xu*, Toshiki Hazama*, Takanori Yoshimoto, Kohei Ohno, Shogo Mitsuhori, Soichi Sugano, Hanying Cho, Zhijian Liu, Masayoshi Tomizuka, Kurt Keutzer

StreamDiffusion is an innovative diffusion pipeline designed for real-time interactive generation. It introduces significant performance enhancements to current diffusion-based image generation techniques.

arXiv Hugging Face Papers

We sincerely thank Taku Fujimoto and Radamés Ajna and Hugging Face team for their invaluable feedback, courteous support, and insightful discussions.

Key Features

  1. Stream Batch

    • Streamlined data processing through efficient batch operations.
  2. Residual Classifier-Free Guidance - Learn More

    • Improved guidance mechanism that minimizes computational redundancy.
  3. Stochastic Similarity Filter - Learn More

    • Improves GPU utilization efficiency through advanced filtering techniques.
  4. IO Queues

    • Efficiently manages input and output operations for smoother execution.
  5. Pre-Computation for KV-Caches

    • Optimizes caching strategies for accelerated processing.
  6. Model Acceleration Tools

    • Utilizes various tools for model optimization and performance boost.

When images are produced using our proposed StreamDiffusion pipeline in an environment with GPU: RTX 4090, CPU: Core i9-13900K, and OS: Ubuntu 22.04.3 LTS.

model Denoising Step fps on Txt2Img fps on Img2Img
SD-turbo 1 106.16 93.897
LCM-LoRA
+
KohakuV2
4 38.023 37.133

Feel free to explore each feature by following the provided links to learn more about StreamDiffusion's capabilities. If you find it helpful, please consider citing our work:

@article{kodaira2023streamdiffusion,
      title={StreamDiffusion: A Pipeline-level Solution for Real-time Interactive Generation},
      author={Akio Kodaira and Chenfeng Xu and Toshiki Hazama and Takanori Yoshimoto and Kohei Ohno and Shogo Mitsuhori and Soichi Sugano and Hanying Cho and Zhijian Liu and Kurt Keutzer},
      year={2023},
      eprint={2312.12491},
      archivePrefix={arXiv},
      primaryClass={cs.CV}
}

Installation

Step0: clone this repository

git clone https://github.com/cumulo-autumn/StreamDiffusion.git

Step1: Make Environment

You can install StreamDiffusion via pip, conda, or Docker(explanation below).

conda create -n streamdiffusion python=3.10
conda activate streamdiffusion

OR

python -m venv .venv
# Windows
.\.venv\Scripts\activate
# Linux
source .venv/bin/activate

Step2: Install PyTorch

Select the appropriate version for your system.

CUDA 11.8

pip3 install torch==2.1.0 torchvision==0.16.0 xformers --index-url https://download.pytorch.org/whl/cu118

CUDA 12.1

pip3 install torch==2.1.0 torchvision==0.16.0 xformers --index-url https://download.pytorch.org/whl/cu121

details: https://pytorch.org/

Step3: Install StreamDiffusion

For User

Install StreamDiffusion

#for Latest Version (recommended)
pip install git+https://github.com/cumulo-autumn/StreamDiffusion.git@main#egg=streamdiffusion[tensorrt]


#or


#for Stable Version
pip install streamdiffusion[tensorrt]

Install TensorRT extension

python -m streamdiffusion.tools.install-tensorrt

(Only for Windows) You may need to install pywin32 additionally, if you installed Stable Version(pip install streamdiffusion[tensorrt]).

pip install --force-reinstall pywin32

For Developer

python setup.py develop easy_install streamdiffusion[tensorrt]
python -m streamdiffusion.tools.install-tensorrt

Docker Installation (TensorRT Ready)

git clone https://github.com/cumulo-autumn/StreamDiffusion.git
cd StreamDiffusion
docker build -t stream-diffusion:latest -f Dockerfile .
docker run --gpus all -it -v $(pwd):/home/ubuntu/streamdiffusion stream-diffusion:latest

Quick Start

You can try StreamDiffusion in examples directory.

画像3 画像4
画像5 画像6

Real-Time Txt2Img Demo

There is an interactive txt2img demo in demo/realtime-txt2img directory!

Real-Time Img2Img Demo

There is a real time img2img demo with a live webcam feed or screen capture on a web browser in demo/realtime-img2img directory!

Usage Example

We provide a simple example of how to use StreamDiffusion. For more detailed examples, please refer to examples directory.

Image-to-Image

import torch
from diffusers import AutoencoderTiny, StableDiffusionPipeline
from diffusers.utils import load_image

from streamdiffusion import StreamDiffusion
from streamdiffusion.image_utils import postprocess_image

# You can load any models using diffuser's StableDiffusionPipeline
pipe = StableDiffusionPipeline.from_pretrained("KBlueLeaf/kohaku-v2.1").to(
    device=torch.device("cuda"),
    dtype=torch.float16,
)

# Wrap the pipeline in StreamDiffusion
stream = StreamDiffusion(
    pipe,
    t_index_list=[32, 45],
    torch_dtype=torch.float16,
)

# If the loaded model is not LCM, merge LCM
stream.load_lcm_lora()
stream.fuse_lora()
# Use Tiny VAE for further acceleration
stream.vae = AutoencoderTiny.from_pretrained("madebyollin/taesd").to(device=pipe.device, dtype=pipe.dtype)
# Enable acceleration
pipe.enable_xformers_memory_efficient_attention()


prompt = "1girl with dog hair, thick frame glasses"
# Prepare the stream
stream.prepare(prompt)

# Prepare image
init_image = load_image("assets/img2img_example.png").resize((512, 512))

# Warmup >= len(t_index_list) x frame_buffer_size
for _ in range(2):
    stream(init_image)

# Run the stream infinitely
while True:
    x_output = stream(init_image)
    postprocess_image(x_output, output_type="pil")[0].show()
    input_response = input("Press Enter to continue or type 'stop' to exit: ")
    if input_response == "stop":
        break

Text-to-Image

import torch
from diffusers import AutoencoderTiny, StableDiffusionPipeline

from streamdiffusion import StreamDiffusion
from streamdiffusion.image_utils import postprocess_image

# You can load any models using diffuser's StableDiffusionPipeline
pipe = StableDiffusionPipeline.from_pretrained("KBlueLeaf/kohaku-v2.1").to(
    device=torch.device("cuda"),
    dtype=torch.float16,
)

# Wrap the pipeline in StreamDiffusion
# Requires more long steps (len(t_index_list)) in text2image
# You recommend to use cfg_type="none" when text2image
stream = StreamDiffusion(
    pipe,
    t_index_list=[0, 16, 32, 45],
    torch_dtype=torch.float16,
    cfg_type="none",
)

# If the loaded model is not LCM, merge LCM
stream.load_lcm_lora()
stream.fuse_lora()
# Use Tiny VAE for further acceleration
stream.vae = AutoencoderTiny.from_pretrained("madebyollin/taesd").to(device=pipe.device, dtype=pipe.dtype)
# Enable acceleration
pipe.enable_xformers_memory_efficient_attention()


prompt = "1girl with dog hair, thick frame glasses"
# Prepare the stream
stream.prepare(prompt)

# Warmup >= len(t_index_list) x frame_buffer_size
for _ in range(4):
    stream()

# Run the stream infinitely
while True:
    x_output = stream.txt2img()
    postprocess_image(x_output, output_type="pil")[0].show()
    input_response = input("Press Enter to continue or type 'stop' to exit: ")
    if input_response == "stop":
        break

You can make it faster by using SD-Turbo.

Faster generation

Replace the following code in the above example.

pipe.enable_xformers_memory_efficient_attention()

To

from streamdiffusion.acceleration.tensorrt import accelerate_with_tensorrt

stream = accelerate_with_tensorrt(
    stream, "engines", max_batch_size=2,
)

It requires TensorRT extension and time to build the engine, but it will be faster than the above example.

Optionals

Stochastic Similarity Filter

demo

Stochastic Similarity Filter reduces processing during video input by minimizing conversion operations when there is little change from the previous frame, thereby alleviating GPU processing load, as shown by the red frame in the above GIF. The usage is as follows:

stream = StreamDiffusion(
    pipe,
    [32, 45],
    torch_dtype=torch.float16,
)
stream.enable_similar_image_filter(
    similar_image_filter_threshold,
    similar_image_filter_max_skip_frame,
)

There are the following parameters that can be set as arguments in the function:

similar_image_filter_threshold

similar_image_filter_max_skip_frame

Residual CFG (RCFG)

rcfg

RCFG is a method for approximately realizing CFG with competitive computational complexity compared to cases where CFG is not used. It can be specified through the cfg_type argument in the StreamDiffusion. There are two types of RCFG: one with no specified items for negative prompts RCFG Self-Negative and one where negative prompts can be specified RCFG Onetime-Negative. In terms of computational complexity, denoting the complexity without CFG as N and the complexity with a regular CFG as 2N, RCFG Self-Negative can be computed in N steps, while RCFG Onetime-Negative can be computed in N+1 steps.

The usage is as follows:

# w/0 CFG
cfg_type = "none"
# CFG
cfg_type = "full"
# RCFG Self-Negative
cfg_type = "self"
# RCFG Onetime-Negative
cfg_type = "initialize"
stream = StreamDiffusion(
    pipe,
    [32, 45],
    torch_dtype=torch.float16,
    cfg_type=cfg_type,
)
stream.prepare(
    prompt="1girl, purple hair",
    guidance_scale=guidance_scale,
    delta=delta,
)

The delta has a moderating effect on the effectiveness of RCFG.

Development Team

Aki, Ararat, Chenfeng Xu, ddPn08, kizamimi, ramune, teftef, Tonimono, Verb,

(*alphabetical order)

Acknowledgements

The video and image demos in this GitHub repository were generated using LCM-LoRA + KohakuV2 and SD-Turbo.

Special thanks to LCM-LoRA authors for providing the LCM-LoRA and Kohaku BlueLeaf (@KBlueleaf) for providing the KohakuV2 model and ,to Stability AI for SD-Turbo.

KohakuV2 Models can be downloaded from Civitai and Hugging Face.

SD-Turbo is also available on Hugging Face Space.

Contributors

StreamDiffusion (cumulo-autumn/StreamDiffusion)

Searching Database…

这是什么?StreamDiffusion 是一个流水线级别的库,用于实时、交互式的扩散模型图像生成。你可以用文字提示词,或者用实时摄像头、屏幕画面作为输入,以较高的帧率生成图像。
这是独立应用,还是我可以接入自己代码的库?它是一个 Python 库或流水线,封装了 SD-Turbo、LCM-LoRA 等扩散模型,可以通过 pip、conda 或 Docker 安装。你可以在自己的 Python 脚本中调用它,也可以直接运行提供的演示程序。
我该怎么让它跑起来?克隆代码仓库,创建环境,安装与你的 CUDA 版本匹配的 PyTorch 版本,然后再安装 StreamDiffusion 本身。项目还提供了已经配置好 TensorRT 的 Docker 镜像。
我需要先配置特定的 CUDA 和 PyTorch 环境吗?需要。在安装 StreamDiffusion 之前,你必须选择与 CUDA 11.8 或 CUDA 12.1 对应的 PyTorch 版本。如果你使用 Windows,还需要额外安装 TensorRT 扩展和 pywin32。
使用 TensorRT 加速,开箱即用吗?不是。TensorRT 扩展需要额外安装,构建引擎也需要一些时间,不过最终速度比默认流水线更快。在 Windows 上,还需要安装 pywin32。
它同时支持 Linux 和 Windows 吗?支持,两个系统都可以使用。README 中专门为 Windows 用户说明了 TensorRT 扩展的安装步骤。
要达到较好的帧率,我需要什么样的 GPU?基准测试是在 Ubuntu 22.04 系统上完成的,使用的是 RTX 4090 显卡和 Core i9-13900K 处理器。使用 SD-Turbo 进行 Txt2Img 时,帧率超过 100 fps。性能较低的显卡速度会更慢。
什么是 Stochastic Similarity Filter?它会跳过与上一帧非常相似的画面,不再重复处理,从而在视频或摄像头输入时降低 GPU 负载。它的判断依据是可配置的相似度阈值和最大跳帧数设置。
什么是 Residual CFG(RCFG)?RCFG 以更低的计算成本近似实现无分类器引导(classifier-free guidance)。Self-Negative 模式只需 N 步,普通 CFG 需要 2N 步,但它不支持负面提示词。Onetime-Negative 模式需要 N+1 步,并允许使用负面提示词。
StreamDiffusion 可以使用哪些模型?演示程序使用 SD-Turbo,以及搭配 KohakuV2 模型的 LCM-LoRA。两者都可以从 Civitai 或 Hugging Face 下载。SD-Turbo 也可以直接在 Hugging Face Space 中使用。
我应该先试哪个演示,配置最快?示例目录中的 realtime-txt2img 和 realtime-img2img 演示是最快的体验方式。其中 img2img 演示支持在浏览器中接入实时摄像头或屏幕捕获。
Size
121.7 MB
Stars
10.8K
Age
2y
Commits · 90 Days