# Pipeline

## ModularPipeline[[diffusers.ModularPipeline]]

#### diffusers.ModularPipeline[[diffusers.ModularPipeline]]

```python
diffusers.ModularPipeline(blocks: diffusers.modular_pipelines.modular_pipeline.ModularPipelineBlocks | None = None, pretrained_model_name_or_path: str | os.PathLike | None = None, components_manager: diffusers.modular_pipelines.components_manager.ComponentsManager | None = None, collection: str | None = None, workflow: str | None = None, modular_config_dict: dict[str, typing.Any] | None = None, config_dict: dict[str, typing.Any] | None = None, **kwargs)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/modular_pipelines/modular_pipeline.py#L1697)

**매개변수:**

blocks : 파이프라인에서 사용할 블록인 ModularPipelineBlocks

모든 Modular 파이프라인의 베이스 클래스입니다.

#### from_pretrained[[diffusers.ModularPipeline.from_pretrained]]

```python
from_pretrained(pretrained_model_name_or_path: str | os.PathLike | None, trust_remote_code: bool | None = None, components_manager: diffusers.modular_pipelines.components_manager.ComponentsManager | None = None, collection: str | None = None, workflow: str | None = None, **kwargs)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/modular_pipelines/modular_pipeline.py#L1922)

**매개변수:**

pretrained_model_name_or_path (`str` 또는 `os.PathLike`, 선택 사항) : 사전 학습된 파이프라인 구성 파일의 경로입니다. 먼저 `modular_model_index.json`에서 구성을 로드하려고 시도한 후, 표준 비모듈형 저장소와의 호환성을 위해 `model_index.json`으로 폴백합니다. pretrained_model_name_or_path에 파이프라인 구성이 포함되지 않으면 초기화 시 None으로 설정됩니다.

trust_remote_code (`bool`, optional) : 파이프라인 로드 시 원격 코드를 신뢰할지 여부입니다. `pretrained_model_name_or_path`의 사용자 정의 코드를 기반으로 파이프라인 블록을 생성하려면 True로 설정해야 합니다.

components_manager (`ComponentsManager`, 선택 사항): 여러 파이프라인에 걸친 여러 컴포넌트를 관리하고 오프로딩 전략을 적용하기 위한 ComponentsManager 인스턴스.

collection (`str`, 선택 사항) -- ComponentsManager에서 구성 요소를 정리하기 위한 컬렉션 이름.

workflow (`str`, optional) : 파이프라인 블록에 의해 선언된 워크플로의 이름입니다. 값이 제공되면 블록은 해당 워크플로의 실행 블록으로 가지치기되어, 파이프라인은 해당 워크플로가 사용하는 컴포넌트만 기대하고 `load_components()`도 해당 컴포넌트만 로드합니다.

huggingface 허브 저장소에서 ModularPipeline를 로드합니다.

#### get_component_spec[[diffusers.ModularPipeline.get_component_spec]]

```python
get_component_spec(name: str)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/modular_pipelines/modular_pipeline.py#L2408)

**반환값:**

- ComponentSpec 객체의 복사본

#### load_components[[diffusers.ModularPipeline.load_components]]

```python
load_components(names: list[str] | str | None = None, workflow: str | None = None, **kwargs)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/modular_pipelines/modular_pipeline.py#L2496)

**매개변수:**

names : list of component names to load. If None, will load all components with default_creation_method == "from_pretrained". If provided as a list or string, will load only the specified components.

workflow : pipeline 블록에 의해 선언된 워크플로의 이름. 지정된 경우, 해당 워크플로의 실행 블록이 사용하는 컴포넌트만 로드됩니다. `names`와 함께 사용할 수 없습니다.

- ****kwargs** : `from_pretrained()`에 전달할 추가 kwargs입니다. 다음 중 하나일 수 있습니다: - 로드할 모든 구성 요소에 적용될 단일 값, 예: dtype=torch.bfloat16 - dict, 예: dtype={"unet": torch.bfloat16, "default": torch.float32} - kwargs에 다른 로딩 필드가 전달되면 ComponentSpec를 잠재적으로 오버라이드할 수 있습니다. 예: `pretrained_model_name_or_path`, `variant`, `revision` 등 - kwargs에 다른 로딩 필드가 전달되면 ComponentSpec를 잠재적으로 오버라이드할 수 있습니다. 예: `pretrained_model_name_or_path`, `variant`, `revision` 등

specs에서 선택된 컴포넌트를 로드합니다.

#### register_components[[diffusers.ModularPipeline.register_components]]

```python
register_components(**kwargs)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/modular_pipelines/modular_pipeline.py#L2193)

**매개변수:**

- ****kwargs** : 키가 컴포넌트 이름이고 값이 컴포넌트 객체인 키워드 인자. 예: register_components(unet=unet_model, text_encoder=encoder_model)

Register components with their corresponding specifications.

이 메서드는 다음을 담당합니다:
1. 로더에 컴포넌트 객체를 속성으로 설정합니다(예: self.unet = unet)
2. `save_pretrained` 시 `modular_model_index.json`로 저장되는 config dict를 업데이트합니다 (from_pretrained 컴포넌트에만 적용).
3. from_pretrained 컴포넌트의 경우, 컴포넌트 매니저가 연결되어 있으면 해당 컴포넌트를 추가합니다

이 메서드는 다음 경우에 호출됩니다:
- 컴포넌트는 __init__에서 먼저 초기화됩니다:
  - from_pretrained에서 __init__ 중에 로드되지 않은 구성 요소는 None으로 등록됩니다.
  - non from_pretrained 구성 요소는 __init__ 중에 생성되며 객체 자체로 등록됩니다
- 컴포넌트는 `update_components()` 메서드로 업데이트됩니다. 예를 들어, loader.update_components(unet=unet) 또는 loader.update_components(guider=guider_spec)
- (from_pretrained) 구성 요소는 `load_components()` 메서드로 로드됩니다. 예를 들어, loader.load_components(names=["unet"]) 또는 모든 기본 구성 요소를 로드하려면 loader.load_components()를 사용합니다.

참고:
- 컴포넌트에 대해 None을 등록하면 속성을 None으로 설정하지만, config dict와 specs를 계속 동기화합니다. 이 config dict는 `save_pretrained` 실행 시 `modular_model_index.json`으로 저장됩니다.
- component_specs are updated to match the new component outside of this method, e.g. in `update_components()` method

#### save_pretrained[[diffusers.ModularPipeline.save_pretrained]]

```python
save_pretrained(save_directory: str | os.PathLike, safe_serialization: bool = True, variant: str | None = None, max_shard_size: int | str | None = None, push_to_hub: bool = False, **kwargs)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/modular_pipelines/modular_pipeline.py#L2023)

**매개변수:**

save_directory (`str` 또는 `os.PathLike`) : 파이프라인을 저장할 디렉터리입니다. 존재하지 않으면 생성됩니다.

safe_serialization (`bool`, *선택 사항*, 기본값 `True`) : `safetensors` 또는 `pickle`를 사용한 전통적인 PyTorch 방식으로 모델을 저장할지 여부.

variant (`str`, *선택 사항*) : 지정된 경우, 가중치가 `pytorch_model.<variant>.bin` 형식으로 저장됩니다.

max_shard_size (`int` 또는 `str`, 기본값은 `None`) : 샤딩되기 전 체크포인트의 최대 크기입니다. 샤딩된 각 체크포인트의 크기는 이 크기보다 작아집니다. 문자열로 표현할 경우, 숫자 뒤에 단위(예: `"5GB"`)가 따라야 합니다. 정수로 표현할 경우, 단위는 바이트입니다.

push_to_hub (`bool`, *선택 사항*, 기본값 `False`) : 파이프라인을 저장한 후 Hugging Face 모델 허브에 푸시할지 여부.

- ****kwargs** : 추가 키워드 인자: - `overwrite_modular_index` (`bool`, *선택 사항*, 기본값 `True`): Hub에 푸시할 경우 `repo_id`로, 그렇지 않으면 `save_directory`로 각 저장된 구성 요소의 로딩 스펙이 가리키도록 `modular_model_index.json`을 업데이트할지 여부. 로드되지 않은 구성 요소는 저장되지 않으며 항상 기록된 로딩 스펙을 유지합니다. 저장되는 구성 요소의 기록된 스펙도 유지하려면 `False`를 전달하세요(예: 의도적으로 다른 저장소를 참조하는 인덱스). 로드 ID가 없는 구성 요소(`update_components`로 추가된 사용자 정의 모델 등)는 기록된 소스가 없으므로 여전히 다시 작성됩니다. - `repo_id` (`str`, *선택 사항*): 파이프라인을 푸시할 저장소 ID. 기본값은 `save_directory`의 마지막 구성 요소입니다. - `commit_message` (`str`, *선택 사항*): Hub 푸시 작업에 대한 커밋 메시지. - `private` (`bool`, *선택 사항*): 저장소를 비공개로 설정할지 여부. - `create_pr` (`bool`, *선택 사항*, 기본값 `False`): 직접 푸시하는 대신 pull request를 생성할지 여부. - `token` (`str`, *선택 사항*): 인증에 사용할 Hugging Face 토큰.

[from_pretrained()](/docs/diffusers/main/ko/api/modular_diffusers/pipeline#diffusers.ModularPipeline.from_pretrained) 클래스 메서드를 사용하여 다시 로드할 수 있도록 파이프라인과 모든 구성 요소를 디렉터리에 저장합니다.

#### (으)로[[diffusers.ModularPipeline.to]]

```python
to(*args, **kwargs)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/modular_pipelines/modular_pipeline.py#L2658)

**매개변수:**

dtype (`torch.dtype`, *선택 사항*) : 지정된 [`dtype`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.dtype)를 가진 파이프라인을 반환합니다

device (`torch.Device`, *선택 사항*) : 지정된 [`device`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.device)를 가진 파이프라인을 반환합니다

silence_dtype_warnings (`str`, *선택 사항*, 기본값 `False`) : 대상 `dtype`이 대상 `device`와 호환되지 않는 경우 경고를 생략할지 여부.

**반환값:** [DiffusionPipeline](/docs/diffusers/main/ko/api/pipelines/overview#diffusers.DiffusionPipeline)

파이프라인이 지정된 `dtype` 및/또는 `dtype`으로 변환되었습니다.

Performs Pipeline dtype and/or device conversion. A torch.dtype and torch.device are inferred from the arguments of `self.to(*args, **kwargs).`

> [!TIP] > 파이프라인에 이미 올바른 torch.dtype와 torch.device가 있는 경우, 그대로 반환됩니다.
그렇지 않은 경우, > 반환되는 pipeline은 원하는 torch.dtype과 torch.device를 가진 self의 복사본입니다.

`to`를 호출하는 방법은 다음과 같습니다:

- `to(dtype, silence_dtype_warnings=False) → DiffusionPipeline`를 사용하여 지정된 [`dtype`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.dtype)을 가진 파이프라인을 반환합니다
- `to(device, silence_dtype_warnings=False) → DiffusionPipeline`를 호출하여 지정된 [`device`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.device)를 가진 파이프라인을 반환합니다
- `to(device=None, dtype=None, silence_dtype_warnings=False) → DiffusionPipeline`는 지정된 [`device`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.device)와 [`dtype`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.dtype)를 가진 파이프라인을 반환합니다

#### unload_components[[diffusers.ModularPipeline.unload_components]]

```python
unload_components(names: list[str] | str)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/modular_pipelines/modular_pipeline.py#L2602)

**매개변수:**

names : 언로드할 컴포넌트 이름 또는 컴포넌트 이름 목록.

선택한 구성 요소를 언로드하여 해당 메모리를 해제합니다.

component 속성은 `None`으로 되돌려지며, ComponentsManager가 연결되어 있는 경우 해당 component가 그 안에서 제거됩니다. component spec은 변경되지 않으므로 나중에 `load_components()`를 사용하여 component를 다시 로드할 수 있습니다.

#### update_components[[diffusers.ModularPipeline.update_components]]

```python
update_components(**kwargs)
```

[소스](https://github.com/huggingface/diffusers/blob/main/src/diffusers/modular_pipelines/modular_pipeline.py#L2415)

**매개변수:**

- ****kwargs** : 업데이트할 구성 요소 객체 또는 구성 값: - 구성 요소 객체: `AutoModel.from_pretrained()` 또는 `ComponentSpec.load()`로 로드된 모델에는 로드 정보가 자동으로 태그됩니다. 가중치가 없는 ConfigMixin 객체(예: 스케줄러, 가이더)는 직접 전달할 수 있습니다. - 구성 값: 구성 설정을 업데이트하기 위한 단순 값(예: `requires_safety_checker=False`)

파이프라인 인스턴스화 후 구성 요소 및 구성 값과 스펙을 업데이트합니다.

이 메서드를 사용하면 다음을 수행할 수 있습니다:
1. 기존 구성 요소를 새 구성 요소로 교체합니다(예: `self.unet` 또는 `self.text_encoder` 업데이트)
2. 구성 값 업데이트(예: `self.requires_safety_checker` 플래그 변경)

파이프라인 속성으로 컴포넌트와 구성 값을 업데이트하는 것 외에도, 해당 메서드는 다음 항목들도 업데이트합니다:
- `_component_specs`와 `_config_specs`의 해당 스펙
- `save_pretrained` 시 `modular_model_index.json`으로 저장되는 `config` 딕셔너리

예:
```python
# Update pre-trained model
pipeline.update_components(unet=new_unet_model, text_encoder=new_text_encoder)

# Update configuration values
pipeline.update_components(requires_safety_checker=False)
```

참고:
- `AutoModel.from_pretrained()` 또는 `ComponentSpec.load()`로 로드된 Components에는
직렬화를 위해 유지되는 로딩 사양입니다. Hub 참조가 없는 사용자 정의 또는 로컬에서 로드된 컴포넌트는 `save_pretrained()` 실행 중에 `modular_model_index.json` 항목이 자동으로 업데이트됩니다.
- 가중치가 없는 ConfigMixin 객체(예: 스케줄러, 가이더)는 직접 전달할 수 있습니다.

