Skip to content

Stable Diffusion

Stable Diffusion is a text-to-image latent diffusion model that can generate images from text prompts. RBLN NPUs can accelerate Stable Diffusion pipelines using RBLN Optimum.

Supported NPU

Diffusers pipelines run on ATOM™ only. Rebel100™ does not support them yet.

Supported Pipelines

RBLN Optimum supports several Stable Diffusion pipelines:

Pipeline Class Description
Text-to-Image RBLNStableDiffusionPipeline Generate images from text prompts.
Image-to-Image RBLNStableDiffusionImg2ImgPipeline Modify existing images based on text prompts.
Inpainting RBLNStableDiffusionInpaintPipeline Fill masked regions of an image guided by text prompts.

Important: Batch Size Configuration for Guidance Scale

Batch Size and Guidance Scale

When using Stable Diffusion with a guidance scale > 1.0 (the default is 7.5), the UNet's effective batch size is doubled during runtime because of the classifier-free guidance technique.

Because RBLN NPUs use static graph compilation, the UNet's batch size at compilation time must match its runtime batch size. Otherwise, the compiled graph cannot execute and inference fails.

Default Behavior

By default, if you do not explicitly specify the UNet's batch size, RBLN Optimum does the following:

  • Assumes you'll use the default guidance scale (7.5)
  • Automatically sets the UNet's batch size to 2× your pipeline's batch size

If you plan to use the default guidance scale (which is > 1.0), this automatic configuration works correctly. However, if you plan to use a different guidance scale or want more control, explicitly configure the UNet's batch size.

Example: Explicitly Setting the UNet Batch Size

from optimum.rbln import RBLNStableDiffusionPipelineConfig, RBLNStableDiffusionPipeline

# For inference with guidance_scale > 1.0 (default is 7.5)
# Set UNet's batch size to 2 * your desired inference batch size
config = RBLNStableDiffusionPipelineConfig(
    batch_size=2,  # Inference batch size
    height=512,
    width=512,
    # Configure UNet with doubled batch size
    unet=dict(batch_size=4),  # Double the batch size for UNet
)

pipe = RBLNStableDiffusionPipeline.from_pretrained(
    "runwayml/stable-diffusion-v1-5", export=True, rbln_config=config
)

# Normal inference with default guidance_scale=7.5
prompts = [
    "A photo of an astronaut riding a horse on Mars",
    "A portrait of a cat wearing a space suit",
]
images = pipe(prompts).images  # Batch size of 2

# Save the generated images
for i, image in enumerate(images):
    image.save(f"generated_image_{i}.png")
    print(f"Image {i} saved as generated_image_{i}.png")

Example: Using Guidance Scale = 1.0

If you plan to use a guidance scale of exactly 1.0 (which does not use classifier-free guidance), explicitly set the UNet batch size to match your inference batch size:

from optimum.rbln import RBLNStableDiffusionPipelineConfig, RBLNStableDiffusionPipeline

config = RBLNStableDiffusionPipelineConfig(
    height=512,
    width=512,
    # UNet batch size matches the inference batch size
    unet=dict(batch_size=1),
)

pipe = RBLNStableDiffusionPipeline.from_pretrained(
    "runwayml/stable-diffusion-v1-5", export=True, rbln_config=config
)

# Must use guidance_scale=1.0 during inference
prompt = "A photo of an astronaut riding a horse on Mars"
image = pipe(prompt, guidance_scale=1.0).images[0]

# Save the generated image
image.save("no_guidance_image.png")
print("Image saved as no_guidance_image.png")

Usage Example

from optimum.rbln import RBLNStableDiffusionPipeline, RBLNStableDiffusionPipelineConfig

# Create a configuration object with specific settings
config = RBLNStableDiffusionPipelineConfig(height=512, width=512)

# Load and compile the model for RBLN NPU
pipe = RBLNStableDiffusionPipeline.from_pretrained(
    "runwayml/stable-diffusion-v1-5", export=True, rbln_config=config
)

# Generate an image
prompt = "A photo of an astronaut riding a horse on Mars"
image = pipe(prompt).images[0]

# Save the generated image
image.save("astronaut_on_mars.png")
print("Image saved as astronaut_on_mars.png")

API Reference

RBLNStableDiffusionPipeline

Bases: RBLNDiffusionMixin, StableDiffusionPipeline

RBLN-accelerated implementation of Stable Diffusion pipeline for text-to-image generation.

This pipeline compiles Stable Diffusion models to run efficiently on RBLN NPUs, enabling high-performance inference for generating images from text prompts with optimized memory usage and throughput.

from_pretrained(model_id, *, export=None, model_save_dir=None, rbln_config=None, lora_ids=None, lora_weights_names=None, lora_scales=None, **kwargs) classmethod

Load a pretrained diffusion pipeline from a model checkpoint, with optional compilation for RBLN NPUs.

This method has two distinct operating modes
  • When export=True: Takes a PyTorch-based diffusion model, compiles it for RBLN NPUs, and loads the compiled model
  • When export=False: Loads an already compiled RBLN model from model_id without recompilation

It supports various diffusion pipelines including Stable Diffusion, Kandinsky, ControlNet, and other diffusers-based models.

Parameters:

Name Type Description Default
model_id `str`

The model ID or path to the pretrained model to load. Can be either:

  • A model ID from the HuggingFace Hub
  • A local path to a saved model directory
required
export bool | None

If True, takes a PyTorch model from model_id and compiles it for RBLN NPU execution. If False, loads an already compiled RBLN model from model_id without recompilation.

None
model_save_dir str | PathLike[str] | None

Directory to save the compiled model artifacts. Only used when export=True. If not provided and export=True, a temporary directory is used.

None
rbln_config dict[str, Any] | RBLNModelConfig | None

Configuration options for RBLN compilation. Can include settings for specific submodules such as text_encoder, unet, and vae. Configuration can be tailored to the specific pipeline being compiled.

None
lora_ids str | list[str] | None

LoRA adapter ID(s) to load and apply before compilation. LoRA weights are fused into the model weights during compilation. Only used when export=True.

None
lora_weights_names str | list[str] | None

Names of specific LoRA weight files to load, corresponding to lora_ids. Only used when export=True.

None
lora_scales float | list[float] | None

Scaling factor(s) to apply to the LoRA adapter(s). Only used when export=True.

None
kwargs Any

Additional arguments to pass to the underlying diffusion pipeline constructor or the RBLN compilation process. These may include parameters specific to individual submodules or the particular diffusion pipeline being used.

{}

Returns:

Type Description
Self

A compiled or loaded diffusion pipeline that can be used for inference on RBLN NPU. The returned object is an instance of the class that called this method, inheriting from RBLNDiffusionMixin.

RBLNStableDiffusionImg2ImgPipeline

Bases: RBLNDiffusionMixin, StableDiffusionImg2ImgPipeline

RBLN-accelerated implementation of Stable Diffusion pipeline for image-to-image generation.

This pipeline compiles Stable Diffusion models to run efficiently on RBLN NPUs, enabling high-performance inference for transforming input images based on text prompts with controlled strength and guidance.

from_pretrained(model_id, *, export=None, model_save_dir=None, rbln_config=None, lora_ids=None, lora_weights_names=None, lora_scales=None, **kwargs) classmethod

Load a pretrained diffusion pipeline from a model checkpoint, with optional compilation for RBLN NPUs.

This method has two distinct operating modes
  • When export=True: Takes a PyTorch-based diffusion model, compiles it for RBLN NPUs, and loads the compiled model
  • When export=False: Loads an already compiled RBLN model from model_id without recompilation

It supports various diffusion pipelines including Stable Diffusion, Kandinsky, ControlNet, and other diffusers-based models.

Parameters:

Name Type Description Default
model_id `str`

The model ID or path to the pretrained model to load. Can be either:

  • A model ID from the HuggingFace Hub
  • A local path to a saved model directory
required
export bool | None

If True, takes a PyTorch model from model_id and compiles it for RBLN NPU execution. If False, loads an already compiled RBLN model from model_id without recompilation.

None
model_save_dir str | PathLike[str] | None

Directory to save the compiled model artifacts. Only used when export=True. If not provided and export=True, a temporary directory is used.

None
rbln_config dict[str, Any] | RBLNModelConfig | None

Configuration options for RBLN compilation. Can include settings for specific submodules such as text_encoder, unet, and vae. Configuration can be tailored to the specific pipeline being compiled.

None
lora_ids str | list[str] | None

LoRA adapter ID(s) to load and apply before compilation. LoRA weights are fused into the model weights during compilation. Only used when export=True.

None
lora_weights_names str | list[str] | None

Names of specific LoRA weight files to load, corresponding to lora_ids. Only used when export=True.

None
lora_scales float | list[float] | None

Scaling factor(s) to apply to the LoRA adapter(s). Only used when export=True.

None
kwargs Any

Additional arguments to pass to the underlying diffusion pipeline constructor or the RBLN compilation process. These may include parameters specific to individual submodules or the particular diffusion pipeline being used.

{}

Returns:

Type Description
Self

A compiled or loaded diffusion pipeline that can be used for inference on RBLN NPU. The returned object is an instance of the class that called this method, inheriting from RBLNDiffusionMixin.

RBLNStableDiffusionInpaintPipeline

Bases: RBLNDiffusionMixin, StableDiffusionInpaintPipeline

RBLN-accelerated implementation of Stable Diffusion pipeline for image inpainting.

This pipeline compiles Stable Diffusion models to run efficiently on RBLN NPUs, enabling high-performance inference for filling masked regions of images based on text prompts with seamless integration.

from_pretrained(model_id, *, export=None, model_save_dir=None, rbln_config=None, lora_ids=None, lora_weights_names=None, lora_scales=None, **kwargs) classmethod

Load a pretrained diffusion pipeline from a model checkpoint, with optional compilation for RBLN NPUs.

This method has two distinct operating modes
  • When export=True: Takes a PyTorch-based diffusion model, compiles it for RBLN NPUs, and loads the compiled model
  • When export=False: Loads an already compiled RBLN model from model_id without recompilation

It supports various diffusion pipelines including Stable Diffusion, Kandinsky, ControlNet, and other diffusers-based models.

Parameters:

Name Type Description Default
model_id `str`

The model ID or path to the pretrained model to load. Can be either:

  • A model ID from the HuggingFace Hub
  • A local path to a saved model directory
required
export bool | None

If True, takes a PyTorch model from model_id and compiles it for RBLN NPU execution. If False, loads an already compiled RBLN model from model_id without recompilation.

None
model_save_dir str | PathLike[str] | None

Directory to save the compiled model artifacts. Only used when export=True. If not provided and export=True, a temporary directory is used.

None
rbln_config dict[str, Any] | RBLNModelConfig | None

Configuration options for RBLN compilation. Can include settings for specific submodules such as text_encoder, unet, and vae. Configuration can be tailored to the specific pipeline being compiled.

None
lora_ids str | list[str] | None

LoRA adapter ID(s) to load and apply before compilation. LoRA weights are fused into the model weights during compilation. Only used when export=True.

None
lora_weights_names str | list[str] | None

Names of specific LoRA weight files to load, corresponding to lora_ids. Only used when export=True.

None
lora_scales float | list[float] | None

Scaling factor(s) to apply to the LoRA adapter(s). Only used when export=True.

None
kwargs Any

Additional arguments to pass to the underlying diffusion pipeline constructor or the RBLN compilation process. These may include parameters specific to individual submodules or the particular diffusion pipeline being used.

{}

Returns:

Type Description
Self

A compiled or loaded diffusion pipeline that can be used for inference on RBLN NPU. The returned object is an instance of the class that called this method, inheriting from RBLNDiffusionMixin.

RBLNStableDiffusionPipelineBaseConfig

Bases: RBLNModelConfig

__init__(text_encoder=None, unet=None, vae=None, *, batch_size=None, img_height=None, img_width=None, height=None, width=None, sample_size=None, image_size=None, guidance_scale=None, **kwargs)

Parameters:

Name Type Description Default
text_encoder RBLNCLIPTextModelConfig | None

Configuration for the text encoder component. Initialized as RBLNCLIPTextModelConfig if not provided.

None
unet RBLNUNet2DConditionModelConfig | None

Configuration for the UNet model component. Initialized as RBLNUNet2DConditionModelConfig if not provided.

None
vae RBLNAutoencoderKLConfig | None

Configuration for the VAE model component. Initialized as RBLNAutoencoderKLConfig if not provided.

None
batch_size int | None

Batch size for inference, applied to all submodules.

None
img_height int | None

Height of the generated images.

None
img_width int | None

Width of the generated images.

None
height int | None

Height of the generated images.

None
width int | None

Width of the generated images.

None
sample_size tuple[int, int] | None

Spatial dimensions for the UNet model.

None
image_size tuple[int, int] | None

Alternative way to specify image dimensions. Cannot be used together with img_height/img_width.

None
guidance_scale float | None

Scale for classifier-free guidance.

None
kwargs Any

Additional arguments passed to the parent RBLNModelConfig.

{}

Raises:

Type Description
ValueError

If both image_size and img_height/img_width are provided.

Note

When guidance_scale > 1.0, the UNet batch size is automatically doubled to accommodate classifier-free guidance.

from_pretrained(path, rbln_config=None, return_unused_kwargs=False, **kwargs) classmethod

Load a RBLNModelConfig from a path.

Parameters:

Name Type Description Default
path str

Path to the RBLNModelConfig file or directory containing the config file.

required
rbln_config dict[str, Any] | None

Additional configuration to override.

None
return_unused_kwargs bool

Whether to return unused kwargs.

False
kwargs Any

Additional keyword arguments to override configuration values. Keys starting with 'rbln_' will have the prefix removed and be used to update the configuration.

{}

Returns:

Name Type Description
RBLNModelConfig Self | tuple[Self, dict[str, Any]]

The loaded configuration instance.

Note

This method loads the configuration from the specified path and applies any provided overrides. If the loaded configuration class doesn't match the expected class, a warning will be logged.

Examples:

config = RBLNResNetForImageClassificationConfig.from_pretrained("/path/to/model")

initialize_submodule_config(submodule_config=None, force_kwargs=False, **kwargs)

Build the config of a submodule from the parent's runtime options and kwargs.

Returns the submodule config instance when its class is known (an instance was passed, or cls_name was given), otherwise the merged kwargs dict for the model class to resolve later.

get_load_overrides()

Extract the options that must cross the load boundary, for passing to from_pretrained.

Returns the explicitly-set runtime options (device, device_map, create_runtimes, activate_profiler, timeout) and the subclass-specific non-save attributes (load-behavior flags such as _load_visual_runtime, which are never serialized so they can only travel with the caller), recursively including submodules. Compile-time attributes are not included: when loading a compiled model they come from the artifact's rbln_config.json, and this dict is merged on top of it.

Returns:

Type Description
dict[str, Any]

Dictionary of load overrides, keyed like the rbln_config dict accepted by from_pretrained.

RBLNStableDiffusionPipelineConfig

Bases: RBLNStableDiffusionPipelineBaseConfig

Configuration for Stable Diffusion pipeline.

initialize_submodule_config(submodule_config=None, force_kwargs=False, **kwargs)

Build the config of a submodule from the parent's runtime options and kwargs.

Returns the submodule config instance when its class is known (an instance was passed, or cls_name was given), otherwise the merged kwargs dict for the model class to resolve later.

__init__(text_encoder=None, unet=None, vae=None, *, batch_size=None, img_height=None, img_width=None, height=None, width=None, sample_size=None, image_size=None, guidance_scale=None, **kwargs)

Parameters:

Name Type Description Default
text_encoder RBLNCLIPTextModelConfig | None

Configuration for the text encoder component. Initialized as RBLNCLIPTextModelConfig if not provided.

None
unet RBLNUNet2DConditionModelConfig | None

Configuration for the UNet model component. Initialized as RBLNUNet2DConditionModelConfig if not provided.

None
vae RBLNAutoencoderKLConfig | None

Configuration for the VAE model component. Initialized as RBLNAutoencoderKLConfig if not provided.

None
batch_size int | None

Batch size for inference, applied to all submodules.

None
img_height int | None

Height of the generated images.

None
img_width int | None

Width of the generated images.

None
height int | None

Height of the generated images.

None
width int | None

Width of the generated images.

None
sample_size tuple[int, int] | None

Spatial dimensions for the UNet model.

None
image_size tuple[int, int] | None

Alternative way to specify image dimensions. Cannot be used together with img_height/img_width.

None
guidance_scale float | None

Scale for classifier-free guidance.

None
kwargs Any

Additional arguments passed to the parent RBLNModelConfig.

{}

Raises:

Type Description
ValueError

If both image_size and img_height/img_width are provided.

Note

When guidance_scale > 1.0, the UNet batch size is automatically doubled to accommodate classifier-free guidance.

get_load_overrides()

Extract the options that must cross the load boundary, for passing to from_pretrained.

Returns the explicitly-set runtime options (device, device_map, create_runtimes, activate_profiler, timeout) and the subclass-specific non-save attributes (load-behavior flags such as _load_visual_runtime, which are never serialized so they can only travel with the caller), recursively including submodules. Compile-time attributes are not included: when loading a compiled model they come from the artifact's rbln_config.json, and this dict is merged on top of it.

Returns:

Type Description
dict[str, Any]

Dictionary of load overrides, keyed like the rbln_config dict accepted by from_pretrained.

from_pretrained(path, rbln_config=None, return_unused_kwargs=False, **kwargs) classmethod

Load a RBLNModelConfig from a path.

Parameters:

Name Type Description Default
path str

Path to the RBLNModelConfig file or directory containing the config file.

required
rbln_config dict[str, Any] | None

Additional configuration to override.

None
return_unused_kwargs bool

Whether to return unused kwargs.

False
kwargs Any

Additional keyword arguments to override configuration values. Keys starting with 'rbln_' will have the prefix removed and be used to update the configuration.

{}

Returns:

Name Type Description
RBLNModelConfig Self | tuple[Self, dict[str, Any]]

The loaded configuration instance.

Note

This method loads the configuration from the specified path and applies any provided overrides. If the loaded configuration class doesn't match the expected class, a warning will be logged.

Examples:

config = RBLNResNetForImageClassificationConfig.from_pretrained("/path/to/model")

RBLNStableDiffusionImg2ImgPipelineConfig

Bases: RBLNStableDiffusionPipelineBaseConfig

Configuration for Stable Diffusion image-to-image pipeline.

initialize_submodule_config(submodule_config=None, force_kwargs=False, **kwargs)

Build the config of a submodule from the parent's runtime options and kwargs.

Returns the submodule config instance when its class is known (an instance was passed, or cls_name was given), otherwise the merged kwargs dict for the model class to resolve later.

__init__(text_encoder=None, unet=None, vae=None, *, batch_size=None, img_height=None, img_width=None, height=None, width=None, sample_size=None, image_size=None, guidance_scale=None, **kwargs)

Parameters:

Name Type Description Default
text_encoder RBLNCLIPTextModelConfig | None

Configuration for the text encoder component. Initialized as RBLNCLIPTextModelConfig if not provided.

None
unet RBLNUNet2DConditionModelConfig | None

Configuration for the UNet model component. Initialized as RBLNUNet2DConditionModelConfig if not provided.

None
vae RBLNAutoencoderKLConfig | None

Configuration for the VAE model component. Initialized as RBLNAutoencoderKLConfig if not provided.

None
batch_size int | None

Batch size for inference, applied to all submodules.

None
img_height int | None

Height of the generated images.

None
img_width int | None

Width of the generated images.

None
height int | None

Height of the generated images.

None
width int | None

Width of the generated images.

None
sample_size tuple[int, int] | None

Spatial dimensions for the UNet model.

None
image_size tuple[int, int] | None

Alternative way to specify image dimensions. Cannot be used together with img_height/img_width.

None
guidance_scale float | None

Scale for classifier-free guidance.

None
kwargs Any

Additional arguments passed to the parent RBLNModelConfig.

{}

Raises:

Type Description
ValueError

If both image_size and img_height/img_width are provided.

Note

When guidance_scale > 1.0, the UNet batch size is automatically doubled to accommodate classifier-free guidance.

get_load_overrides()

Extract the options that must cross the load boundary, for passing to from_pretrained.

Returns the explicitly-set runtime options (device, device_map, create_runtimes, activate_profiler, timeout) and the subclass-specific non-save attributes (load-behavior flags such as _load_visual_runtime, which are never serialized so they can only travel with the caller), recursively including submodules. Compile-time attributes are not included: when loading a compiled model they come from the artifact's rbln_config.json, and this dict is merged on top of it.

Returns:

Type Description
dict[str, Any]

Dictionary of load overrides, keyed like the rbln_config dict accepted by from_pretrained.

from_pretrained(path, rbln_config=None, return_unused_kwargs=False, **kwargs) classmethod

Load a RBLNModelConfig from a path.

Parameters:

Name Type Description Default
path str

Path to the RBLNModelConfig file or directory containing the config file.

required
rbln_config dict[str, Any] | None

Additional configuration to override.

None
return_unused_kwargs bool

Whether to return unused kwargs.

False
kwargs Any

Additional keyword arguments to override configuration values. Keys starting with 'rbln_' will have the prefix removed and be used to update the configuration.

{}

Returns:

Name Type Description
RBLNModelConfig Self | tuple[Self, dict[str, Any]]

The loaded configuration instance.

Note

This method loads the configuration from the specified path and applies any provided overrides. If the loaded configuration class doesn't match the expected class, a warning will be logged.

Examples:

config = RBLNResNetForImageClassificationConfig.from_pretrained("/path/to/model")

RBLNStableDiffusionInpaintPipelineConfig

Bases: RBLNStableDiffusionPipelineBaseConfig

Configuration for Stable Diffusion inpainting pipeline.

initialize_submodule_config(submodule_config=None, force_kwargs=False, **kwargs)

Build the config of a submodule from the parent's runtime options and kwargs.

Returns the submodule config instance when its class is known (an instance was passed, or cls_name was given), otherwise the merged kwargs dict for the model class to resolve later.

__init__(text_encoder=None, unet=None, vae=None, *, batch_size=None, img_height=None, img_width=None, height=None, width=None, sample_size=None, image_size=None, guidance_scale=None, **kwargs)

Parameters:

Name Type Description Default
text_encoder RBLNCLIPTextModelConfig | None

Configuration for the text encoder component. Initialized as RBLNCLIPTextModelConfig if not provided.

None
unet RBLNUNet2DConditionModelConfig | None

Configuration for the UNet model component. Initialized as RBLNUNet2DConditionModelConfig if not provided.

None
vae RBLNAutoencoderKLConfig | None

Configuration for the VAE model component. Initialized as RBLNAutoencoderKLConfig if not provided.

None
batch_size int | None

Batch size for inference, applied to all submodules.

None
img_height int | None

Height of the generated images.

None
img_width int | None

Width of the generated images.

None
height int | None

Height of the generated images.

None
width int | None

Width of the generated images.

None
sample_size tuple[int, int] | None

Spatial dimensions for the UNet model.

None
image_size tuple[int, int] | None

Alternative way to specify image dimensions. Cannot be used together with img_height/img_width.

None
guidance_scale float | None

Scale for classifier-free guidance.

None
kwargs Any

Additional arguments passed to the parent RBLNModelConfig.

{}

Raises:

Type Description
ValueError

If both image_size and img_height/img_width are provided.

Note

When guidance_scale > 1.0, the UNet batch size is automatically doubled to accommodate classifier-free guidance.

get_load_overrides()

Extract the options that must cross the load boundary, for passing to from_pretrained.

Returns the explicitly-set runtime options (device, device_map, create_runtimes, activate_profiler, timeout) and the subclass-specific non-save attributes (load-behavior flags such as _load_visual_runtime, which are never serialized so they can only travel with the caller), recursively including submodules. Compile-time attributes are not included: when loading a compiled model they come from the artifact's rbln_config.json, and this dict is merged on top of it.

Returns:

Type Description
dict[str, Any]

Dictionary of load overrides, keyed like the rbln_config dict accepted by from_pretrained.

from_pretrained(path, rbln_config=None, return_unused_kwargs=False, **kwargs) classmethod

Load a RBLNModelConfig from a path.

Parameters:

Name Type Description Default
path str

Path to the RBLNModelConfig file or directory containing the config file.

required
rbln_config dict[str, Any] | None

Additional configuration to override.

None
return_unused_kwargs bool

Whether to return unused kwargs.

False
kwargs Any

Additional keyword arguments to override configuration values. Keys starting with 'rbln_' will have the prefix removed and be used to update the configuration.

{}

Returns:

Name Type Description
RBLNModelConfig Self | tuple[Self, dict[str, Any]]

The loaded configuration instance.

Note

This method loads the configuration from the specified path and applies any provided overrides. If the loaded configuration class doesn't match the expected class, a warning will be logged.

Examples:

config = RBLNResNetForImageClassificationConfig.from_pretrained("/path/to/model")