# Stable Diffusion 3.5

Stability AI 的 Stable Diffusion 3.5 是一种多模态扩散变换器（MMDiT），为开源权重的图像生成树立了新标准。它有三个变体： **Large（大型）** （8B 参数）， **中等** （2.5B 参数），以及 **Large Turbo（大型涡轮）** （8B，蒸馏以实现 4 步推理）。其突出特点是准确的文本渲染——SD 3.5 能可靠地在生成图像中放置可读文本，这是多数早期模型难以做到的。

在 [Clore.ai](https://clore.ai/) 你可以以每天仅约 $0.30 的价格租用 SD 3.5 所需的 GPU 算力，并每小时生成数百张图片。

## 主要特性

* **三个变体** — Large（8B，最高质量），Medium（2.5B，快速且轻量），Large Turbo（8B，4 步蒸馏）。
* **准确的文本渲染** — 在图像中生成可读的文本、标牌、标签和排版。
* **MMDiT 架构** — 图像-文本联合注意力以实现更好的提示遵循性。
* **1024×1024 原生分辨率** — 无需放大技巧即可获得干净输出。
* **灵活的长宽比** — 处理非方形输出（768×1344、1344×768 等）而不损失质量。
* **原生 diffusers 支持** — `StableDiffusion3Pipeline` 于 `diffusers >= 0.30`.
* **开放权重** — Stability AI 社区许可证；对大多数商业用途免费。

## 要求

| 组件        | 最低            | 推荐                   |
| --------- | ------------- | -------------------- |
| GPU 显存    | 12 GB（Medium） | 24 GB（Large / Turbo） |
| 系统内存      | 16 GB         | 32 GB                |
| 磁盘        | 20 GB         | 40 GB                |
| Python    | 3.10+         | 3.11                 |
| CUDA      | 12.1+         | 12.4                 |
| diffusers | 0.30+         | 最新                   |

**Clore.ai 的 GPU 推荐：** 一台 **512x512** （24 GB，约 $0.5–2/天）可全速运行所有三个变体。对于 Medium 模型， **速度** （24 GB，约 $0.3–1/天）甚至 16 GB 卡就足够且更便宜。

## 快速开始

```bash
pip install torch torchvision --index-url https://download.pytorch.org/whl/cu124
pip install diffusers transformers accelerate sentencepiece protobuf

python -c "import torch; print(torch.cuda.get_device_name(0))"
```

## 使用示例

### SD 3.5 Large — 最高质量

```python
import torch
from diffusers import StableDiffusion3Pipeline

pipe = StableDiffusion3Pipeline.from_pretrained(
    "stabilityai/stable-diffusion-3.5-large",
    torch_dtype=torch.bfloat16,
)
pipe.to("cuda")

image = pipe(
    prompt=(
        "一块风化的木牌，上面写着 'OPEN 24 HOURS'，挂在"
        "霓虹灯照亮的餐馆外的一条生锈链条上，雨夜，"
        "湿润柏油路上的反射，电影摄影风格"
    ),
    negative_prompt="模糊、变形的文字、低质量",
    guidance_scale=3.5,
    num_inference_steps=28,
    width=1024,
    height=1024,
    generator=torch.Generator("cuda").manual_seed(42),
).images[0]

image.save("diner_sign.png")
print("Saved diner_sign.png")
```

### SD 3.5 Large Turbo — 4 步快速生成

```python
import torch
from diffusers import StableDiffusion3Pipeline

pipe = StableDiffusion3Pipeline.from_pretrained(
    "stabilityai/stable-diffusion-3.5-large-turbo",
    torch_dtype=torch.bfloat16,
).to("cuda")

# Turbo 变体：只需 4 步，guidance_scale=0（已蒸馏）
image = pipe(
    prompt="机械表机芯的微距照片，复杂齿轮，金色光线",
    guidance_scale=0.0,
    num_inference_steps=4,
    width=1024,
    height=1024,
).images[0]

image.save("watch_turbo.png")
```

### SD 3.5 Medium — 轻量选项

```python
import torch
from diffusers import StableDiffusion3Pipeline

pipe = StableDiffusion3Pipeline.from_pretrained(
    "stabilityai/stable-diffusion-3.5-medium",
    torch_dtype=torch.float16,
).to("cuda")

image = pipe(
    prompt="一间舒适咖啡馆内部的等角视图，像素艺术风格，温暖灯光",
    guidance_scale=4.0,
    num_inference_steps=28,
    width=1024,
    height=1024,
).images[0]

image.save("coffee_shop_medium.png")
```

### 不同长宽比的批量生成

```python
import torch
from diffusers import StableDiffusion3Pipeline

pipe = StableDiffusion3Pipeline.from_pretrained(
    "stabilityai/stable-diffusion-3.5-large",
    torch_dtype=torch.bfloat16,
).to("cuda")

jobs = [
    {"prompt": "一位宇航员在向日葵田的肖像", "w": 768, "h": 1344},
    {"prompt": "冰岛高地的全景风光，阴郁的天空", "w": 1344, "h": 768},
    {"prompt": "一瓶香水放在大理石表面上的产品照片", "w": 1024, "h": 1024},
]

for i, job in enumerate(jobs):
    img = pipe(
        prompt=job["prompt"],
        guidance_scale=3.5,
        num_inference_steps=28,
        width=job["w"],
        height=job["h"],
    ).images[0]
    img.save(f"batch_{i:03d}.png")
    print(f"[{i+1}/{len(jobs)}] {job['w']}x{job['h']} 完成")
```

## 给 Clore.ai 用户的提示

1. **用于迭代的 Turbo，用于最终稿的 Large** — 使用 4 步 Turbo 变体快速探索提示想法，然后切换到 Large（28 步）进行最终渲染。
2. **guidance\_scale=3.5** — SD 3.5 Large 在比旧版 Stable Diffusion 更低的 CFG 下表现最佳。超过 5.0 往往会导致颜色过饱和。
3. **Turbo 需要 guidance\_scale=0** — 蒸馏模型已将引导信息内建；再增加会降低输出质量。
4. **图像中的文本** — SD 3.5 的文本渲染能力很强但并不完美。对你想要的确切文本使用引号： `'OPEN 24 HOURS'`。保持简短（最多 3–5 个单词）。
5. **缓存权重** —— 设置 `HF_HOME=/workspace/hf_cache` 到持久存储。Large 在磁盘上约为 \~16 GB。
6. **Large 使用 bf16，Medium 使用 fp16** — 8B 模型在 bf16 下训练；2.5B 的 Medium 在 fp16 下运行良好。
7. **高效批量处理** — SD 3.5 Large 在 RTX 4090 上生成一张 1024×1024 图像约需 \~3 秒。夜间批量生成以大量产出。
8. **接受 HF 许可证** — 在下载之前，你必须在 HuggingFace 模型页面上接受模型许可证。使用登录 `huggingface-cli login`.

## # 使用固定种子以获得一致结果

| 问题                            | 修复                                                                                                     |
| ----------------------------- | ------------------------------------------------------------------------------------------------------ |
| `OutOfMemoryError` 使用 Large 时 | 使用 `pipe.enable_model_cpu_offload()`；或切换到 Medium 变体                                                    |
| 图像中出现乱码文本                     | 保持文本简短（3–5 个单词）；在提示中用引号括起；增加 `num_inference_steps` 到 35                                                |
| 颜色过度饱和                        | 降低 `guidance_scale` — 对 Large 试试 2.5–3.5；对 Turbo 使用 0.0                                                |
| 下载模型时 403 错误                  | 在以下页面接受许可： `https://huggingface.co/stabilityai/stable-diffusion-3.5-large` 并运行 `huggingface-cli login` |
| 第一次运行缓慢                       | Large 的初次下载约为 \~16 GB；后续运行使用缓存                                                                         |
| `KeyError: 'text_encoder_3'`  | 升级 diffusers： `pip install -U diffusers transformers`                                                  |
| 输出为黑图像                        | 确保已安装 `torch_dtype=torch.bfloat16` 对于 Large/Turbo；在某些显卡上，fp32 可能导致无声失败                                 |


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-zh/tu-xiang-sheng-cheng/stable-diffusion-3-5.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
