# PR #31177 完整报告

- 仓库：`sgl-project/sglang`
- 标题：[Diffusion] Support fal Ideogram V4 Fast and Instant
- 合并时间：2026-07-14 19:51
- 原文链接：http://prhub.com.cn/sgl-project/sglang/pull/31177

---

# 执行摘要

- 一句话：支持 fal Ideogram V4 Fast/Instant 蒸馏模型
- 推荐动作：值得精读，特别是蒸馏流水线如何复用现有 pipeline 基础设施并通过简单的配置开关切换量化路径。对于负责多模态生成特性的开发者，可以学习如何扩展新的模型变体。钉住共享组件版本的策略值得关注，可避免意外上流 break。单分支 denoising 的修改很简洁。

# 功能与动机

fal Fast 和 Instant 版本是 gated、transformer-only 蒸馏检查点。现有 Ideogram 流水线预期同时包含 conditional 和 unconditional transformers，并默认使用官方 row-wise FP8 线性路径，导致这些检查点无法正确加载或执行。此变更重用原生 Ideogram 阶段，采用单一 denoiser 分支，选择正确的浮点线性实现，并仅下载模型卡片引用的共享组件。

# 实现拆解

1. **新增蒸馏组件下载与路径解析**：在 `ideogram.py` 中新增 `_resolve_ideogram4_distilled_components_path()` 函数，通过 `snapshot_download` 从 `ideogram-ai/ideogram-4-nf4-diffusers` 仓库下载 pin 版本的 scheduler、text encoder、tokenizer、VAE 等共享组件，排除 transformer 权重（由蒸馏模型自身提供）。
2. **定义蒸馏专用配置与采样参数**：在 `configs/models/dits/ideogram.py` 中添加 `Ideogram4DistilledDiTConfig`（继承 `Ideogram4DiTConfig`，设置 `use_weight_only_fp8_linears=False` 以使用未量化线性层）；在 `configs/sample/ideogram.py` 中添加 `Ideogram4FastSamplingParams` 和 `Ideogram4InstantSamplingParams`，分别预设 20 步和 8 步的采样计划；在 `configs/pipeline_configs/ideogram.py` 中添加 `Ideogram4DistilledPipelineConfig`。
3. **实现蒸馏流水线类**：在 `ideogram.py` 中新增 `Ideogram4DistilledPipeline` 及其子类 `Ideogram4FastPipeline`、`Ideogram4InstantPipeline`。`_load_config` 从共享组件仓库读取 `model_index.json`；`_resolve_distilled_transformer_path` 从模型路径下载 transformer 权重；`_resolve_component_path` 根据配置键返回对应组件的下载路径；`_create_denoising_stage` 创建单分支 denoising stage。
4. **调整 denoising stage 支持单分支**：在 `stages/model_specific_stages/ideogram.py` 中修改 `_run_denoising_step`，如果 `unconditional_transformer` 为 `None`，则跳过负向推理，velocity 直接等于正向输出，并修改 `_dual_transformer_execution_mode` 返回 `None`。
5. **注册新模型并更新测试与文档**：在 `registry.py` 中注册 `fal/ideogram-v4-fast` 和 `fal/ideogram-v4-instant` 到对应流水线；在 `test_ideogram4.py` 中添加 8 个新测试用例，覆盖流水线解析、组件下载、采样默认值、denoiser 使用单 transformer、线性层类型、attention 权重映射、以及 DiT 支持层间卸载。同时更新 cookbook 文档说明使用方式。

关键文件：
- `python/sglang/multimodal_gen/runtime/pipelines/ideogram.py`（模块 流水线；类别 source；类型 core-logic；符号 _resolve_ideogram4_distilled_components_path, Ideogram4DistilledPipeline, _load_config, _resolve_distilled_transformer_path）: 核心变更，新增蒸馏流水线类及路径解析函数，定义了蒸馏变体的加载和执行逻辑。
- `python/sglang/multimodal_gen/test/unit/test_ideogram4.py`（模块 测试；类别 test；类型 test-coverage；符号 test_ideogram_dit_supports_layerwise_offload, test_registry_resolves_fal_distilled_repos_to_native_pipelines, test_fal_distilled_pipeline_resolves_component_only_repo, test_fal_distilled_pipeline_downloads_pinned_shared_components）: 新增 8 个测试用例，覆盖蒸馏流水线的关键行为：仓库解析、组件下载、采样默认值、denoiser 单分支、线性层类型、attention 映射、层间卸载支持。
- `python/sglang/multimodal_gen/runtime/models/dits/ideogram.py`（模块 模型实现；类别 source；类型 data-contract；符号 Ideogram4Transformer2DModel）: 修改线性层构建函数以支持 `use_weight_only_fp8_linears` 参数，蒸馏模型需跳过 FP8 量化线性层。
- `python/sglang/multimodal_gen/configs/models/dits/ideogram.py`（模块 模型配置；类别 source；类型 data-contract；符号 Ideogram4DistilledDiTConfig）: 新增 `Ideogram4DistilledDiTConfig`，继承基础配置并设置 `use_weight_only_fp8_linears=False` 以指示蒸馏模型使用浮点线性。
- `python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/ideogram.py`（模块 Denoising 阶段；类别 source；类型 data-contract）: 修改 denoising 步骤以支持无条件 transformer 为 None 的单分支模式，蒸馏流水线不需要负向推理。
- `python/sglang/multimodal_gen/configs/sample/ideogram.py`（模块 采样参数；类别 source；类型 core-logic；符号 Ideogram4FastSamplingParams, Ideogram4InstantSamplingParams）: 新增 Fast 和 Instant 采样预设及对应的采样参数类。
- `python/sglang/multimodal_gen/configs/pipeline_configs/ideogram.py`（模块 流水线配置；类别 source；类型 core-logic；符号 Ideogram4DistilledPipelineConfig）: 新增蒸馏流水线配置类 `Ideogram4DistilledPipelineConfig`。
- `python/sglang/multimodal_gen/registry.py`（模块 注册中心；类别 source；类型 dependency-wiring）: 注册新模型 ID 到对应的流水线和配置。

关键符号：_resolve_ideogram4_distilled_components_path, Ideogram4DistilledPipeline._load_config, Ideogram4DistilledPipeline._resolve_distilled_transformer_path, Ideogram4DistilledPipeline._resolve_component_path, Ideogram4DistilledPipeline._create_denoising_stage, _linear, _merged_column_linear, _row_linear, Ideogram4DistilledDiTConfig, Ideogram4FastPipeline, Ideogram4InstantPipeline, Ideogram4FastSamplingParams, Ideogram4InstantSamplingParams, Ideogram4DistilledPipelineConfig

## 关键源码片段

### `python/sglang/multimodal_gen/runtime/pipelines/ideogram.py`

核心变更，新增蒸馏流水线类及路径解析函数，定义了蒸馏变体的加载和执行逻辑。

```python
import json
import os
from functools import lru_cache
from typing import Any, cast

from huggingface_hub import hf_hub_download, snapshot_download

# 蒸馏共享组件的固定仓库和版本
_IDEOGRAM4_DISTILLED_COMPONENTS_MODEL = 'ideogram-ai/ideogram-4-nf4-diffusers'
_IDEOGRAM4_DISTILLED_COMPONENTS_REVISION = '1874bc70267ba2c823a7239e1d70dd308c8d64dc'
# 仅下载共享组件，排除 transformer 权重
_IDEOGRAM4_DISTILLED_COMPONENT_PATTERNS = [
    'model_index.json',
    'scheduler/*',
    'text_encoder/*',
    'tokenizer/*',
    'vae/*',
]


@lru_cache(maxsize=1)
def _resolve_ideogram4_distilled_components_path() -> str:
    # fal 的模型卡片显式引用 NF4 Diffusers 仓库来获取这些共享组件。
    # 仅下载这些组件：其 conditional 和 unconditional base transformers 蒸馏变体未使用。
    return snapshot_download(
        repo_id=_IDEOGRAM4_DISTILLED_COMPONENTS_MODEL,
        revision=_IDEOGRAM4_DISTILLED_COMPONENTS_REVISION,
        allow_patterns=_IDEOGRAM4_DISTILLED_COMPONENT_PATTERNS,
        ignore_patterns=['*.onnx', '*.msgpack'],
        max_workers=8,
    )


class Ideogram4DistilledPipeline(Ideogram4Pipeline):
    _required_config_modules = [
        'text_encoder', 'tokenizer', 'vae', 'transformer', 'scheduler',
    ]
    _distilled_transformer_path: str | None = None

    def _load_config(self) -> dict[str, Any]:
        # 从共享组件仓库读取 model_index.json 作为配置
        logger.info(
            'Using %s for distilled config and non-transformer components',
            _IDEOGRAM4_DISTILLED_COMPONENTS_MODEL,
        )
        model_index_path = hf_hub_download(
            repo_id=_IDEOGRAM4_DISTILLED_COMPONENTS_MODEL,
            filename='model_index.json',
            revision=_IDEOGRAM4_DISTILLED_COMPONENTS_REVISION,
        )
        with open(model_index_path, encoding='utf-8') as f:
            return cast(dict[str, Any], json.load(f))

    def _resolve_distilled_transformer_path(self) -> str:
        # 如果未缓存，从模型仓库下载 transformer 子目录
        if self._distilled_transformer_path is None:
            model_path = (
                self.model_path
                if os.path.exists(self.model_path)
                else snapshot_download(
                    repo_id=self.model_path,
                    allow_patterns=['transformer/*'],
                    ignore_patterns=['*.onnx', '*.msgpack'],
                    max_workers=8,
                )
            )
            self._distilled_transformer_path = os.path.join(model_path, 'transformer')
        return self._distilled_transformer_path

```

### `python/sglang/multimodal_gen/runtime/models/dits/ideogram.py`

修改线性层构建函数以支持 `use_weight_only_fp8_linears` 参数，蒸馏模型需跳过 FP8 量化线性层。

```python
def _linear(
    in_features: int,
    out_features: int,
    bias: bool = True,
    quant_config: QuantizationConfig | None = None,
    prefix: str = '',
    gather_output: bool = True,
    use_weight_only_fp8_linears: bool = True,  # True 为 FP8 官方流水线，False 为蒸馏浮点流水线
) -> ...:
    tp_size = _tp_size()
    use_column_parallel = tp_size > 1 and out_features % tp_size == 0
    # 仅当无量化配置且启用 FP8 线性时使用 WeightOnlyFP8 类
    if quant_config is None and use_weight_only_fp8_linears:
        if use_column_parallel:
            return WeightOnlyFP8ColumnParallelLinear(...)
        return WeightOnlyFP8Linear(...)
    if use_column_parallel:
        return Ideogram4ColumnParallelLinear(...)
    return Ideogram4QuantizedLinear(...)

# 类似修改应用于 _merged_column_linear 和 _row_linear

```

# 评论区精华

该 PR 由作者直接合并，未产生实质性 review 讨论。PR body 中已详细说明动机和实现要点。

- 暂无高价值评论线程

# 风险与影响

- 风险：
 - **Gated 依赖风险**：fal/ideogram-v4-fast 和 fal/ideogram-v4-instant 是 gated 仓库，用户需要 Hugging Face 登录且有权限才能下载模型。若无权限，下载将失败，需在文档中提前说明。
 - **共享组件版本 pin**：`_IDEOGRAM4_DISTILLED_COMPONENTS_REVISION` 固定了组件仓库的 commit，若上游更新，需要手动更新 pin 值以获取最新组件。
 - **浮点线性路径切换**：蒸馏模型使用 `use_weight_only_fp8_linears=False`，选择非量化线性层。需要确保该路径与 TP、Ulysses 序列并行等策略兼容，测试覆盖了部分场景，但端到端测试缺失。
 - **继承基类风险**：`Ideogram4DistilledPipeline` 覆盖了 `_load_config` 等基类方法，如果基类 `Ideogram4Pipeline` 有行为变更，可能导致不一致。
 - **性能**：采样预设步数减少（Fast 20 步，Instant 8 步），速度更快，但生成质量可能有所下降，文档中提示了 Fast 的 NVFP4 质量 caveat。
- 影响：
 - **用户**：现在可以将 `fal/ideogram-v4-fast` 或 `fal/ideogram-v4-instant` 直接作为模型 ID 传递给 `sglang generate` 或 `sglang serve` 进行文本到图像生成。cookbook 提供了所需的 Python 依赖、结构化 caption 格式以及 TP2/Ulysses2 命令示例。
 - **系统**：引入额外的 Hugging Face Hub 下载请求（共享组件和 transformer 权重），但通过 `@lru_cache` 缓存路径。蒸馏模型仅下载 transformer 子目录，共享组件在所有蒸馏变体间复用。
 - **团队**：需要维护共享组件仓库的 revision 更新。但新增代码是继承现有架构的，与主模型流水线保持一致的编程模型。
 - 风险标记：Gated repository access required, Pinned component revision, Unquantized linear path switch, Inheritance from Ideogram4Pipeline with method overrides, Missing end-to-end integration test

# 关联脉络

- 暂无明显关联 PR