Inplace Optimization allows you to optimize model components (like converting them to TensorRT) within a Python pipeline without modifying the original pipeline code.
To use this, you must wrap specific modules of your pipeline (e.g., text encoder, UNet, VAE) using nav.Module. You can also provide an output_mapping to ensure the optimized module's output is compatible with the original pipeline's expected types (e.g., HuggingFace classes).
Workflow:
- Wrap pipeline modules with
nav.Module. - Prepare a dataloader where each element is a tuple:
(batch_size, data_sample). - Call
nav.optimize(pipeline, dataloader). - Call
nav.load_optimized() to switch the pipeline to use the optimized modules directly in Python.
import model_navigator as nav
from transformers.modeling_outputs import BaseModelOutputWithPooling
from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline
def get_pipeline():
pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1")
pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
pipe = pipe.to("cuda")
# Wrap modules for optimization
pipe.text_encoder = nav.Module(
pipe.text_encoder,
name="clip",
output_mapping=lambda output: BaseModelOutputWithPooling(**output),
)
pipe.unet = nav.Module(pipe.unet, name="unet")
pipe.vae.decoder = nav.Module(pipe.vae.decoder, name="vae")
return pipe
# Dataloader: first element in tuple must be batch size
def get_dataloader():
return [(1, "a photo of an astronaut riding a horse on mars")]
pipe = get_pipeline()
dataloader = get_dataloader()
# Execute optimization
nav.optimize(pipe, dataloader)
# Load optimized modules for direct Python execution
nav.load_optimized()