|
| 1 | +from typing import Any, Dict, List |
| 2 | + |
| 3 | +from .configuration_utils import ConfigMixin, register_to_config |
| 4 | +from .utils import CONFIG_NAME |
| 5 | + |
| 6 | + |
| 7 | +class PipelineCallback(ConfigMixin): |
| 8 | + """ |
| 9 | + Base class for all the official callbacks used in a pipeline. This class provides a structure for implementing |
| 10 | + custom callbacks and ensures that all callbacks have a consistent interface. |
| 11 | +
|
| 12 | + Please implement the following: |
| 13 | + `tensor_inputs`: This should return a list of tensor inputs specific to your callback. You will only be able to |
| 14 | + include |
| 15 | + variables listed in the `._callback_tensor_inputs` attribute of your pipeline class. |
| 16 | + `callback_fn`: This method defines the core functionality of your callback. |
| 17 | + """ |
| 18 | + |
| 19 | + config_name = CONFIG_NAME |
| 20 | + |
| 21 | + @register_to_config |
| 22 | + def __init__(self, cutoff_step_ratio=1.0, cutoff_step_index=None): |
| 23 | + super().__init__() |
| 24 | + |
| 25 | + if (cutoff_step_ratio is None and cutoff_step_index is None) or ( |
| 26 | + cutoff_step_ratio is not None and cutoff_step_index is not None |
| 27 | + ): |
| 28 | + raise ValueError("Either cutoff_step_ratio or cutoff_step_index should be provided, not both or none.") |
| 29 | + |
| 30 | + if cutoff_step_ratio is not None and ( |
| 31 | + not isinstance(cutoff_step_ratio, float) or not (0.0 <= cutoff_step_ratio <= 1.0) |
| 32 | + ): |
| 33 | + raise ValueError("cutoff_step_ratio must be a float between 0.0 and 1.0.") |
| 34 | + |
| 35 | + @property |
| 36 | + def tensor_inputs(self) -> List[str]: |
| 37 | + raise NotImplementedError(f"You need to set the attribute `tensor_inputs` for {self.__class__}") |
| 38 | + |
| 39 | + def callback_fn(self, pipeline, step_index, timesteps, callback_kwargs) -> Dict[str, Any]: |
| 40 | + raise NotImplementedError(f"You need to implement the method `callback_fn` for {self.__class__}") |
| 41 | + |
| 42 | + def __call__(self, pipeline, step_index, timestep, callback_kwargs) -> Dict[str, Any]: |
| 43 | + return self.callback_fn(pipeline, step_index, timestep, callback_kwargs) |
| 44 | + |
| 45 | + |
| 46 | +class MultiPipelineCallbacks: |
| 47 | + """ |
| 48 | + This class is designed to handle multiple pipeline callbacks. It accepts a list of PipelineCallback objects and |
| 49 | + provides a unified interface for calling all of them. |
| 50 | + """ |
| 51 | + |
| 52 | + def __init__(self, callbacks: List[PipelineCallback]): |
| 53 | + self.callbacks = callbacks |
| 54 | + |
| 55 | + @property |
| 56 | + def tensor_inputs(self) -> List[str]: |
| 57 | + return [input for callback in self.callbacks for input in callback.tensor_inputs] |
| 58 | + |
| 59 | + def __call__(self, pipeline, step_index, timestep, callback_kwargs) -> Dict[str, Any]: |
| 60 | + """ |
| 61 | + Calls all the callbacks in order with the given arguments and returns the final callback_kwargs. |
| 62 | + """ |
| 63 | + for callback in self.callbacks: |
| 64 | + callback_kwargs = callback(pipeline, step_index, timestep, callback_kwargs) |
| 65 | + |
| 66 | + return callback_kwargs |
| 67 | + |
| 68 | + |
| 69 | +class SDCFGCutoffCallback(PipelineCallback): |
| 70 | + """ |
| 71 | + Callback function for Stable Diffusion Pipelines. After certain number of steps (set by `cutoff_step_ratio` or |
| 72 | + `cutoff_step_index`), this callback will disable the CFG. |
| 73 | +
|
| 74 | + Note: This callback mutates the pipeline by changing the `_guidance_scale` attribute to 0.0 after the cutoff step. |
| 75 | + """ |
| 76 | + |
| 77 | + tensor_inputs = ["prompt_embeds"] |
| 78 | + |
| 79 | + def callback_fn(self, pipeline, step_index, timestep, callback_kwargs) -> Dict[str, Any]: |
| 80 | + cutoff_step_ratio = self.config.cutoff_step_ratio |
| 81 | + cutoff_step_index = self.config.cutoff_step_index |
| 82 | + |
| 83 | + # Use cutoff_step_index if it's not None, otherwise use cutoff_step_ratio |
| 84 | + cutoff_step = ( |
| 85 | + cutoff_step_index if cutoff_step_index is not None else int(pipeline.num_timesteps * cutoff_step_ratio) |
| 86 | + ) |
| 87 | + |
| 88 | + if step_index == cutoff_step: |
| 89 | + prompt_embeds = callback_kwargs[self.tensor_inputs[0]] |
| 90 | + prompt_embeds = prompt_embeds[-1:] # "-1" denotes the embeddings for conditional text tokens. |
| 91 | + |
| 92 | + pipeline._guidance_scale = 0.0 |
| 93 | + |
| 94 | + callback_kwargs[self.tensor_inputs[0]] = prompt_embeds |
| 95 | + return callback_kwargs |
| 96 | + |
| 97 | + |
| 98 | +class SDXLCFGCutoffCallback(PipelineCallback): |
| 99 | + """ |
| 100 | + Callback function for Stable Diffusion XL Pipelines. After certain number of steps (set by `cutoff_step_ratio` or |
| 101 | + `cutoff_step_index`), this callback will disable the CFG. |
| 102 | +
|
| 103 | + Note: This callback mutates the pipeline by changing the `_guidance_scale` attribute to 0.0 after the cutoff step. |
| 104 | + """ |
| 105 | + |
| 106 | + tensor_inputs = ["prompt_embeds", "add_text_embeds", "add_time_ids"] |
| 107 | + |
| 108 | + def callback_fn(self, pipeline, step_index, timestep, callback_kwargs) -> Dict[str, Any]: |
| 109 | + cutoff_step_ratio = self.config.cutoff_step_ratio |
| 110 | + cutoff_step_index = self.config.cutoff_step_index |
| 111 | + |
| 112 | + # Use cutoff_step_index if it's not None, otherwise use cutoff_step_ratio |
| 113 | + cutoff_step = ( |
| 114 | + cutoff_step_index if cutoff_step_index is not None else int(pipeline.num_timesteps * cutoff_step_ratio) |
| 115 | + ) |
| 116 | + |
| 117 | + if step_index == cutoff_step: |
| 118 | + prompt_embeds = callback_kwargs[self.tensor_inputs[0]] |
| 119 | + prompt_embeds = prompt_embeds[-1:] # "-1" denotes the embeddings for conditional text tokens. |
| 120 | + |
| 121 | + add_text_embeds = callback_kwargs[self.tensor_inputs[1]] |
| 122 | + add_text_embeds = add_text_embeds[-1:] # "-1" denotes the embeddings for conditional pooled text tokens |
| 123 | + |
| 124 | + add_time_ids = callback_kwargs[self.tensor_inputs[2]] |
| 125 | + add_time_ids = add_time_ids[-1:] # "-1" denotes the embeddings for conditional added time vector |
| 126 | + |
| 127 | + pipeline._guidance_scale = 0.0 |
| 128 | + |
| 129 | + callback_kwargs[self.tensor_inputs[0]] = prompt_embeds |
| 130 | + callback_kwargs[self.tensor_inputs[1]] = add_text_embeds |
| 131 | + callback_kwargs[self.tensor_inputs[2]] = add_time_ids |
| 132 | + return callback_kwargs |
| 133 | + |
| 134 | + |
| 135 | +class IPAdapterScaleCutoffCallback(PipelineCallback): |
| 136 | + """ |
| 137 | + Callback function for any pipeline that inherits `IPAdapterMixin`. After certain number of steps (set by |
| 138 | + `cutoff_step_ratio` or `cutoff_step_index`), this callback will set the IP Adapter scale to `0.0`. |
| 139 | +
|
| 140 | + Note: This callback mutates the IP Adapter attention processors by setting the scale to 0.0 after the cutoff step. |
| 141 | + """ |
| 142 | + |
| 143 | + tensor_inputs = [] |
| 144 | + |
| 145 | + def callback_fn(self, pipeline, step_index, timestep, callback_kwargs) -> Dict[str, Any]: |
| 146 | + cutoff_step_ratio = self.config.cutoff_step_ratio |
| 147 | + cutoff_step_index = self.config.cutoff_step_index |
| 148 | + |
| 149 | + # Use cutoff_step_index if it's not None, otherwise use cutoff_step_ratio |
| 150 | + cutoff_step = ( |
| 151 | + cutoff_step_index if cutoff_step_index is not None else int(pipeline.num_timesteps * cutoff_step_ratio) |
| 152 | + ) |
| 153 | + |
| 154 | + if step_index == cutoff_step: |
| 155 | + pipeline.set_ip_adapter_scale(0.0) |
| 156 | + return callback_kwargs |
0 commit comments