# 组件和配置

## ComponentSpec[[diffusers.ComponentSpec]]

#### diffusers.ComponentSpec[[diffusers.ComponentSpec]]

```python
diffusers.ComponentSpec(name: str | None = None, type_hint: typing.Optional[typing.Type] = None, description: str | None = None, config: diffusers.configuration_utils.FrozenDict | None = None, pretrained_model_name_or_path: str | list[str] | None = None, subfolder: str | None = '', variant: str | None = None, revision: str | None = None, default_creation_method: typing.Literal['from_config', 'from_pretrained'] = 'from_pretrained', repo: str | list[str] | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/modular_pipeline_utils.py#L98)

**参数：**

name : 组件的名称

type_hint : 组件的类型（例如 UNet2DConditionModel）

description : 组件的可选描述

config : 用于 __init__ 创建的可选配置字典

pretrained_model_name_or_path : 用于 from_pretrained 创建时可选的 pretrained_model_name_or_path 路径

subfolder : pretrained_model_name_or_path 中的可选子文件夹

variant : pretrained_model_name_or_path 中的可选变体

revision : pretrained_model_name_or_path 中可选的修订版本

default_creation_method : 首选创建方式 - "from_config" 或 "from_pretrained"

流水线组件的规范。

组件可以通过两种方式创建：
1. 使用配置字典通过 __init__ 从头开始
2. 使用 `from_pretrained`

#### 创建[[diffusers.ComponentSpec.create]]

```python
create(config: diffusers.configuration_utils.FrozenDict | dict[str, typing.Any] | None = None, **kwargs)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/modular_pipeline_utils.py#L267)

使用 from_config 和 config 创建组件。

#### decode_load_id[[diffusers.ComponentSpec.decode_load_id]]

```python
decode_load_id(load_id: str)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/modular_pipeline_utils.py#L228)

**参数：**

load_id : 要解码的 load_id 字符串，格式为："pretrained_model_name_or_path|subfolder|variant|revision"，其中 None 值表示为 "null"

**返回值：**

Dict mapping loading field names to their values. e.g. { "pretrained_model_name_or_path": "path/to/repo", "subfolder": "subfolder", "variant": "variant", "revision": "revision" } If a segment value is "null", it's replaced with None. Returns None if load_id is "null" (indicating component not created with `load` method).

将 load_id 字符串解码为包含加载字段及其值的字典。

#### from_component[[diffusers.ComponentSpec.from_component]]

```python
from_component(name: str, component: Any)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/modular_pipeline_utils.py#L149)

**参数：**

name : 组件的名称

component : 用于创建 spec 的组件对象

**返回值：**

ComponentSpec 对象

**引发：** ``ValueError``

- ``ValueError`` -- 如果组件不受支持（例如，没有 load_id 的 nn.Module，非 ConfigMixin）

从 Component 创建 ComponentSpec。

目前支持：
- 使用 `ComponentSpec.load()` 方法创建的组件
- ConfigMixin 的子类，但不是 nn.Module（例如调度器、引导器）

#### load[[diffusers.ComponentSpec.load]]

```python
load(**kwargs)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/modular_pipeline_utils.py#L295)

使用 from_pretrained 加载组件。

#### loading_fields[[diffusers.ComponentSpec.loading_fields]]

```python
loading_fields()
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/modular_pipeline_utils.py#L209)

返回所有与加载相关的字段名称（即那些 field.metadata["loading"] 为 True 的字段）。

## ConfigSpec[[diffusers.ConfigSpec]]

#### diffusers.ConfigSpec[[diffusers.ConfigSpec]]

```python
diffusers.ConfigSpec(name: str, default: Any, description: str | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/modular_pipeline_utils.py#L360)

流水线配置参数的规范。

## ComponentsManager[[diffusers.ComponentsManager]]

#### diffusers.ComponentsManager[[diffusers.ComponentsManager]]

```python
diffusers.ComponentsManager()
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/components_manager.py#L296)

一个用于跨多个流水线管理模型组件的中心注册和管理系统。

[ComponentsManager](/docs/diffusers/v0.43.0/zh/api/modular_diffusers/pipeline_components#diffusers.ComponentsManager) 提供了一种统一的方式，用于在不同的模块化流水线中注册、跟踪和复用模型组件（例如 UNet、VAE、文本编码器等）。它包含重复检测、内存管理和组件组织等功能。

> [!WARNING] > 这是一个实验性功能，未来可能会发生变化。

示例：
```python
from diffusers import ComponentsManager

# Create a components manager
cm = ComponentsManager()

# Add components
cm.add("unet", unet_model, collection="sdxl")
cm.add("vae", vae_model, collection="sdxl")

# Enable auto offloading
cm.enable_auto_cpu_offload()

# Retrieve components
unet = cm.get_one(name="unet", collection="sdxl")
```

#### 添加[[diffusers.ComponentsManager.add]]

```python
add(name: str, component: Any, collection: str | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/components_manager.py#L393)

**参数：**

name (str)：组件的名称

component (Any)：要添加的组件

collection (str | None) : 要添加组件的集合

**返回：** `str`

唯一的组件 ID，其生成格式为 "{name}_{id(component)}"，其中 id(component) 是 Python 内置的对象唯一标识符

向 ComponentsManager 添加一个组件。

#### disable_auto_cpu_offload[[diffusers.ComponentsManager.disable_auto_cpu_offload]]

```python
disable_auto_cpu_offload()
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/components_manager.py#L795)

禁用所有组件的自动 CPU 卸载。

#### enable_auto_cpu_offload[[diffusers.ComponentsManager.enable_auto_cpu_offload]]

```python
enable_auto_cpu_offload(device: str | int | torch.device = None, memory_reserve_margin = '3GB', offload_strategy = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/components_manager.py#L701)

**参数：**

device (str | int | torch.device) : 执行设备，模型将被移动至该设备以进行前向传播

memory_reserve_margin (str) : 要使用的内存预留余量，默认为 3GB。这是为避免在模型执行期间（例如，用于中间激活值、梯度等）耗尽内存而在设备上保留的空闲内存量。

offload_strategy : 任何具有签名 `(hooks, model_id, model, execution_device) -> hooks` 的可调用对象，用于返回在加载即将进入的模型之前需要卸载的驻留模型。默认为 `AutoOffloadStrategy`，它会释放最小的足够组合。

为所有组件启用自动 CPU 卸载。

该算法的工作流程如下：
1. 所有模型默认从 CPU 开始
2. 当调用模型的前向传播时，该模型会被移动到执行设备上
3. 如果内存不足，设备上的其他模型会被移回 CPU
4. 系统会尝试卸载能够释放足够内存的最小模型组合
5. 模型会一直保留在执行设备上，直到另一个模型需要内存并迫使它们被移出

参与此过程的组卸载模型会自行安排位置：它可以通过将其他模型移开来腾出空间，但永远不会被移开以为其他模型腾出空间。两种顺序均可——先进行组卸载，或先启用此功能。`AutoOffloadStrategy` 根据模型的内存占用大小来做出决策，而该占用大小并不描述模型一次只持有一个组的情况，因此请传入一个`offload_strategy`，使其基于工作流来做出决策。

#### get_components_by_ids[[diffusers.ComponentsManager.get_components_by_ids]]

```python
get_components_by_ids(ids: list[str], return_dict_with_names: bool | None = True)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/components_manager.py#L1104)

**参数：**

ids (list[str]) : 组件 ID 列表

return_dict_with_names (bool | None) : 是否返回一个以组件名称为键的字典：

**返回：** dict[str, Any]

组件字典。
- 如果 return_dict_with_names=True，则键为组件名称。
- If return_dict_with_names=False, keys are component IDs.

**引发：** ``ValueError``

- ``ValueError`` -- 当 return_dict_with_names=True 时，如果在搜索结果中发现重复的组件名称

通过 ID 列表获取组件。

#### get_components_by_names[[diffusers.ComponentsManager.get_components_by_names]]

```python
get_components_by_names(names: list[str], collection: str | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/components_manager.py#L1137)

**参数：**

names (list[str]) : 组件名称列表

collection (str | None) : 用于过滤的可选集合

**返回：** dict[str, Any]

以组件名称为键的组件字典

**引发：** ``ValueError``

- ``ValueError`` -- 如果在搜索结果中发现重复的组件名称

通过名称列表获取组件，可选按集合进行筛选。

#### get_ids[[diffusers.ComponentsManager.get_ids]]

```python
get_ids(names: str | list[str] = None, collection: str | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/components_manager.py#L1086)

**参数：**

names (str | list[str]) : 组件名称列表

collection (str | None) : 用于过滤的可选集合

**返回：** list[str]

组件 ID 列表

通过名称列表获取组件 ID，可选择按集合进行筛选。

#### get_model_info[[diffusers.ComponentsManager.get_model_info]]

```python
get_model_info(component_id: str, fields: str | list[str] | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/components_manager.py#L812)

**参数：**

component_id (str) ：要获取信息的组件名称

fields (str | list[str] | None) : 要返回的字段。可以是表示单个字段的字符串，也可以是字段列表。如果为 None，则使用 available_info_fields 设置。

**返回值：**

包含所请求组件元数据的字典。如果指定了 fields，则仅返回这些字段。否则，返回所有字段。

获取组件的详细信息。

#### get_one[[diffusers.ComponentsManager.get_one]]

```python
get_one(component_id: str | None = None, name: str | None = None, collection: str | None = None, load_id: str | None = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/components_manager.py#L1041)

**参数：**

component_id (str | None) : 要获取的可选组件 ID

name (str | None) : 组件名称或模式

collection (str | None) : 用于过滤的可选集合

load_id (str | None) : 可选的 load_id，用于按此进行过滤

**返回值：**

单个组件

**引发：** ``ValueError``

- ``ValueError`` -- 如果没有组件匹配或有多个组件匹配

通过以下任一方式获取单个组件：
- 搜索名称（模式匹配）、集合或 load_id。
- 传入 component_id
如果匹配到多个组件或未找到任何组件，则引发错误。

#### 移除[[diffusers.ComponentsManager.remove]]

```python
remove(component_id: str = None)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/components_manager.py#L485)

**参数：**

component_id (str)：要移除的组件的 ID

从 ComponentsManager 中移除一个组件。

#### remove_from_collection[[diffusers.ComponentsManager.remove_from_collection]]

```python
remove_from_collection(component_id: str, collection: str)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/components_manager.py#L467)

从集合中移除一个组件。

#### search_components[[diffusers.ComponentsManager.search_components]]

```python
search_components(names: str | None = None, collection: str | None = None, load_id: str | None = None, return_dict_with_names: bool = True)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/components_manager.py#L515)

**参数：**

names : 组件名称或模式 模式： - "unet" : 匹配基础名称为 "unet" 的任何组件（例如 unet_123abc） - "!unet" : 除基础名称为 "unet" 的组件外的所有组件 - "unet*" : 基础名称以 "unet" 开头的任何组件 - "!unet*" : 基础名称不以 "unet" 开头的任何组件 - "*unet*" : 基础名称包含 "unet" 的任何组件 - "!*unet*" : 基础名称不包含 "unet" 的任何组件 - "refiner|vae|unet" : 基础名称完全匹配 "refiner"、"vae" 或 "unet" 的任何组件 - "!refiner|vae|unet" : 基础名称不完全匹配 "refiner"、"vae" 或 "unet" 的任何组件 - "unet*|vae*" : 基础名称以 "unet" 开头或以 "vae" 开头的任何组件

collection : 可选的用于过滤的集合

load_id : 可选的 load_id，用于按此进行筛选

return_dict_with_names : 如果为 True，则返回一个以组件名称为键的字典，如果找到多个同名组件则抛出错误。如果为 False，则返回一个以组件 ID 为键的字典

**返回值：**

Dictionary mapping component names to components if return_dict_with_names=True, or a dictionary mapping component IDs to components if return_dict_with_names=False

通过简单的模式匹配按名称搜索组件。可选地按 collection 或 load_id 进行筛选。

#### set_offload_strategy[[diffusers.ComponentsManager.set_offload_strategy]]

```python
set_offload_strategy(offload_strategy)
```

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/components_manager.py#L779)

**参数：**

offload_strategy : 任何具有签名 `(hooks, model_id, model, execution_device) -> hooks` 的可调用对象：它接收当前位于设备上的模型的 hooks，并返回在加载传入模型之前需要卸载的 hooks。默认值为 `AutoOffloadStrategy`，它会释放最小的充分组合。

替换所有受管理模型上的 offload 策略。仅在启用自动 CPU offload 时有效。

## InsertableDict[[diffusers.modular_pipelines.InsertableDict]]

#### diffusers.modular_pipelines.InsertableDict[[diffusers.modular_pipelines.InsertableDict]]

[源代码](https://github.com/huggingface/diffusers/blob/v0.43.0/src/diffusers/modular_pipelines/modular_pipeline_utils.py#L60)

