1212# See the License for the specific language governing permissions and
1313# limitations under the License.
1414import inspect
15- from typing import List , Optional , Tuple , Union
15+ from typing import Callable , Dict , List , Optional , Tuple , Union
1616
1717import torch
1818from transformers import T5Tokenizer , UMT5EncoderModel
1919
20+ from ...callbacks import MultiPipelineCallbacks , PipelineCallback
2021from ...image_processor import VaeImageProcessor
2122from ...models import AuraFlowTransformer2DModel , AutoencoderKL
2223from ...models .attention_processor import AttnProcessor2_0 , FusedAttnProcessor2_0 , XFormersAttnProcessor
@@ -131,6 +132,10 @@ class AuraFlowPipeline(DiffusionPipeline):
131132
132133 _optional_components = []
133134 model_cpu_offload_seq = "text_encoder->transformer->vae"
135+ _callback_tensor_inputs = [
136+ "latents" ,
137+ "prompt_embeds" ,
138+ ]
134139
135140 def __init__ (
136141 self ,
@@ -159,12 +164,19 @@ def check_inputs(
159164 negative_prompt_embeds = None ,
160165 prompt_attention_mask = None ,
161166 negative_prompt_attention_mask = None ,
167+ callback_on_step_end_tensor_inputs = None ,
162168 ):
163169 if height % (self .vae_scale_factor * 2 ) != 0 or width % (self .vae_scale_factor * 2 ) != 0 :
164170 raise ValueError (
165171 f"`height` and `width` have to be divisible by { self .vae_scale_factor * 2 } but are { height } and { width } ."
166172 )
167173
174+ if callback_on_step_end_tensor_inputs is not None and not all (
175+ k in self ._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
176+ ):
177+ raise ValueError (
178+ f"`callback_on_step_end_tensor_inputs` has to be in { self ._callback_tensor_inputs } , but found { [k for k in callback_on_step_end_tensor_inputs if k not in self ._callback_tensor_inputs ]} "
179+ )
168180 if prompt is not None and prompt_embeds is not None :
169181 raise ValueError (
170182 f"Cannot forward both `prompt`: { prompt } and `prompt_embeds`: { prompt_embeds } . Please make sure to"
@@ -387,6 +399,14 @@ def upcast_vae(self):
387399 self .vae .decoder .conv_in .to (dtype )
388400 self .vae .decoder .mid_block .to (dtype )
389401
402+ @property
403+ def guidance_scale (self ):
404+ return self ._guidance_scale
405+
406+ @property
407+ def num_timesteps (self ):
408+ return self ._num_timesteps
409+
390410 @torch .no_grad ()
391411 @replace_example_docstring (EXAMPLE_DOC_STRING )
392412 def __call__ (
@@ -408,6 +428,10 @@ def __call__(
408428 max_sequence_length : int = 256 ,
409429 output_type : Optional [str ] = "pil" ,
410430 return_dict : bool = True ,
431+ callback_on_step_end : Optional [
432+ Union [Callable [[int , int , Dict ], None ], PipelineCallback , MultiPipelineCallbacks ]
433+ ] = None ,
434+ callback_on_step_end_tensor_inputs : List [str ] = ["latents" ],
411435 ) -> Union [ImagePipelineOutput , Tuple ]:
412436 r"""
413437 Function invoked when calling the pipeline for generation.
@@ -462,6 +486,15 @@ def __call__(
462486 return_dict (`bool`, *optional*, defaults to `True`):
463487 Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
464488 of a plain tuple.
489+ callback_on_step_end (`Callable`, *optional*):
490+ A function that calls at the end of each denoising steps during the inference. The function is called
491+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
492+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
493+ `callback_on_step_end_tensor_inputs`.
494+ callback_on_step_end_tensor_inputs (`List`, *optional*):
495+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
496+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
497+ `._callback_tensor_inputs` attribute of your pipeline class.
465498 max_sequence_length (`int` defaults to 256): Maximum sequence length to use with the `prompt`.
466499
467500 Examples:
@@ -483,8 +516,11 @@ def __call__(
483516 negative_prompt_embeds ,
484517 prompt_attention_mask ,
485518 negative_prompt_attention_mask ,
519+ callback_on_step_end_tensor_inputs = callback_on_step_end_tensor_inputs ,
486520 )
487521
522+ self ._guidance_scale = guidance_scale
523+
488524 # 2. Determine batch size.
489525 if prompt is not None and isinstance (prompt , str ):
490526 batch_size = 1
@@ -541,6 +577,7 @@ def __call__(
541577
542578 # 6. Denoising loop
543579 num_warmup_steps = max (len (timesteps ) - num_inference_steps * self .scheduler .order , 0 )
580+ self ._num_timesteps = len (timesteps )
544581 with self .progress_bar (total = num_inference_steps ) as progress_bar :
545582 for i , t in enumerate (timesteps ):
546583 # expand the latents if we are doing classifier free guidance
@@ -567,6 +604,15 @@ def __call__(
567604 # compute the previous noisy sample x_t -> x_t-1
568605 latents = self .scheduler .step (noise_pred , t , latents , return_dict = False )[0 ]
569606
607+ if callback_on_step_end is not None :
608+ callback_kwargs = {}
609+ for k in callback_on_step_end_tensor_inputs :
610+ callback_kwargs [k ] = locals ()[k ]
611+ callback_outputs = callback_on_step_end (self , i , t , callback_kwargs )
612+
613+ latents = callback_outputs .pop ("latents" , latents )
614+ prompt_embeds = callback_outputs .pop ("prompt_embeds" , prompt_embeds )
615+
570616 # call the callback, if provided
571617 if i == len (timesteps ) - 1 or ((i + 1 ) > num_warmup_steps and (i + 1 ) % self .scheduler .order == 0 ):
572618 progress_bar .update ()
0 commit comments