Diffusers documentation
SequentialPipelineBlocks
SequentialPipelineBlocks
SequentialPipelineBlocks — это многоблочный тип, который объединяет другие ModularPipelineBlocks в последовательность. Данные линейно передаются от одного блока к следующему с помощью inputs и intermediate_outputs. Каждый блок в SequentialPipelineBlocks обычно представляет собой этап конвейера, и, комбинируя их, вы постепенно формируете конвейер.
В этом руководстве показано, как объединить два блока в SequentialPipelineBlocks.
Создайте два ModularPipelineBlocks. Первый блок, InputBlock, выводит значение batch_size, а второй блок, ImageEncoderBlock, использует batch_size в качестве inputs.
from diffusers.modular_pipelines import ModularPipelineBlocks, InputParam, OutputParam
class InputBlock(ModularPipelineBlocks):
@property
def inputs(self):
return [
InputParam(name="prompt", type_hint=list, description="list of text prompts"),
InputParam(name="num_images_per_prompt", type_hint=int, description="number of images per prompt"),
]
@property
def intermediate_outputs(self):
return [
OutputParam(name="batch_size", description="calculated batch size"),
]
@property
def description(self):
return "A block that determines batch_size based on the number of prompts and num_images_per_prompt argument."
def __call__(self, components, state):
block_state = self.get_block_state(state)
batch_size = len(block_state.prompt)
block_state.batch_size = batch_size * block_state.num_images_per_prompt
self.set_block_state(state, block_state)
return components, stateimport torch
from diffusers.modular_pipelines import ModularPipelineBlocks, InputParam, OutputParam
class ImageEncoderBlock(ModularPipelineBlocks):
@property
def inputs(self):
return [
InputParam(name="image", type_hint="PIL.Image", description="raw input image to process"),
InputParam(name="batch_size", type_hint=int),
]
@property
def intermediate_outputs(self):
return [
OutputParam(name="image_latents", description="latents representing the image"),
]
@property
def description(self):
return "Encode raw image into its latent presentation"
def __call__(self, components, state):
block_state = self.get_block_state(state)
# Simulate processing the image
# This will change the state of the image from a PIL image to a tensor for all blocks
block_state.image = torch.randn(1, 3, 512, 512)
block_state.batch_size = block_state.batch_size * 2
block_state.image_latents = torch.randn(1, 4, 64, 64)
self.set_block_state(state, block_state)
return components, stateСоедините два блока, определив SequentialPipelineBlocks. Перечислите экземпляры блоков в block_classes, а их соответствующие имена — в block_names. Блоки выполняются в том порядке, в котором они указаны в block_classes, а данные передаются от одного блока к следующему через PipelineState.
class ImageProcessingStep(SequentialPipelineBlocks):
"""
# auto_docstring
"""
model_name = "my_model"
block_classes = [InputBlock(), ImageEncoderBlock()]
block_names = ["input", "image_encoder"]
@property
def description(self):
return (
"Process text prompts and images for the pipeline. It:\n"
" - Determines the batch size from the prompts.\n"
" - Encodes the image into latent space."
)При создании SequentialPipelineBlocks свойства, такие как inputs, intermediate_outputs и expected_components, автоматически агрегируются из подблоков, поэтому их не нужно определять повторно.
Есть несколько свойств, которые вы должны задать:
description: Мы рекомендуем добавить описание для собранного блока, чтобы объяснить, что делает объединённый шаг.model_name: Это значение выводится автоматически из подблоков, но не всегда является корректным, поэтому может потребоваться его переопределение.outputs: по умолчанию совпадает сintermediate_outputs, но можно задать вручную, чтобы контролировать, какие значения отображаются в документации. Это полезно, если нужно показать только итоговые результаты, а не все промежуточные значения.
Эти свойства, вместе с агрегированными inputs, intermediate_outputs и expected_components, используются для автоматической генерации свойства doc.
Выведите блок ImageProcessingStep, чтобы просмотреть его подблоки, и используйте doc для полного обзора входных и выходных данных блока, а также его компонентов.
blocks = ImageProcessingStep()
print(blocks)
print(blocks.doc)