
    bi                    D   d dl Z d dlZd dlZd dlZd dlZd dlmZ d dlmZ d dl	m
Z
mZ d dlmZmZmZmZmZmZ d dlZd dlmZ d dlmZ d dlmZ d d	lmZ d
dlmZmZ d
dlm Z m!Z! d
dl"m#Z#m$Z$m%Z% d
dl&m'Z'm(Z( d
dl)m*Z*m+Z+ ddl,m-Z- ddl.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6  e$       rd dl7Z7 e%jp                  e9      Z: eg d      Z; eg d      Z<e
 G d d             Z=e
 G d d             Z> G d dee#      Z? G d de?      Z@ G d de?      ZA G d d e?      ZB G d! d"ee#      ZCy)#    N)OrderedDict)deepcopy)	dataclassfield)AnyDictListOptionalTupleUnion)create_repo)validate_hf_hub_args)tqdm)Self   )ConfigMixin
FrozenDict)_fetch_class_library_tuplesimple_get_class_obj)PushToHubMixinis_accelerate_availablelogging)get_class_from_dynamic_moduleresolve_trust_remote_code)load_or_create_model_cardpopulate_model_card   )ComponentsManager)ComponentSpec
ConfigSpec
InputParamInsertableDictOutputParamformat_componentsformat_configsmake_doc_string))zstable-diffusion-xl StableDiffusionXLModularPipeline)wanWanModularPipeline)fluxFluxModularPipeline))r'   StableDiffusionXLAutoBlocks)r)   WanAutoBlocks)r+   FluxAutoBlocksc                       e Zd ZU dZ ee      Zeee	f   e
d<    ee      Zeeee   f   e
d<   ddede	defd	Zdd
eeee   f   de	dee	eee	f   f   fdZdedeee	f   fdZdeee	f   fdZd Zy)PipelineStatezl
    [`PipelineState`] stores the state of a pipeline. It is used to pass data between pipeline blocks.
    )default_factoryvalueskwargs_mappingNkeyvaluekwargs_typec                     || j                   |<   |>|| j                  vr|g| j                  |<   y| j                  |   j                  |       yy)z
        Add a value to the pipeline state.

        Args:
            key (str): The key for the value
            value (Any): The value to store
            kwargs_type (str): The kwargs_type with which the value is associated
        N)r2   r3   append)selfr4   r5   r6   s       g/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/modular_pipelines/modular_pipeline.pysetzPipelineState.setP   sV     !C"$"5"55475##K0##K077<	 #    keysdefaultreturnc                     t        |t              r| j                  j                  ||      S |D ci c]  }|| j                  j                  ||      ! c}S c c}w )aa  
        Get one or multiple values from the pipeline state.

        Args:
            keys (Union[str, List[str]]): Key or list of keys for the values
            default (Any): The default value to return if not found

        Returns:
            Union[Any, Dict[str, Any]]: Single value if keys is str, dictionary of values if keys is list
        )
isinstancestrr2   get)r9   r=   r>   r4   s       r:   rC   zPipelineState.geta   sK     dC ;;??411>BCsT[[__S'22CCCs   $Ac                 \    | j                   j                  |g       }| j                  |      S )z
        Get all values with matching kwargs_type.

        Args:
            kwargs_type (str): The kwargs_type to filter by

        Returns:
            Dict[str, Any]: Dictionary of values with matching kwargs_type
        )r3   rC   )r9   r6   value_namess      r:   get_by_kwargszPipelineState.get_by_kwargsp   s+     ))--k2>xx$$r<   c                     i | j                   S )z8
        Convert PipelineState to a dictionary.
        )__dict__r9   s    r:   to_dictzPipelineState.to_dict}   s     !$--  r<   c                     d dj                  fd| j                  j                         D              }dj                  d | j                  j                         D              }d| d| dS )Nc                 @   t        | d      r)t        | d      rd| j                   d| j                   dS t        | t              rOt        |       dkD  rAt        | d   d      r2t        | d   d      r#d| d   j                   d| d   j                   dS t        |       S )	NshapedtypeTensor(dtype=, shape=)r   z[Tensor(dtype=z), ...])hasattrrN   rM   rA   listlenrepr)vs    r:   format_valuez,PipelineState.__repr__.<locals>.format_value   s    q'"wq'':&qwwixyBBAt$Q!!g8NSZ[\]^[_ahSi'!

|8AaDJJ<wOOAwr<   
c              3   @   K   | ]  \  }}d | d |         ywz    z: N .0krV   rW   s      r:   	<genexpr>z)PipelineState.__repr__.<locals>.<genexpr>   s'     ]AaS<?*;<]   c              3   2   K   | ]  \  }}d | d|   ywrZ   r[   )r]   r^   rV   s      r:   r_   z)PipelineState.__repr__.<locals>.<genexpr>   s      &_41aaS1#&_   zPipelineState(
  values={
z
  },
  kwargs_mapping={
z
  }
))joinr2   itemsr3   )r9   
values_strkwargs_mapping_strrW   s      @r:   __repr__zPipelineState.__repr__   sh    	 YY]IZIZI\]]
!YY&_4CVCVC\C\C^&__.zl:XYkXlluvvr<   N)__name__
__module____qualname____doc__r   dictr2   r   rB   r   __annotations__r3   r	   r;   r   rC   rF   rJ   rg   r[   r<   r:   r0   r0   G   s     #48FDcN8+0+FNDd3i(F=s =3 =S ="Dc49n- D DuSRVWZ\_W_R`M`Ga D% %c3h %!c3h !wr<   r0   c                   >    e Zd ZdZd ZdefdZdedefdZd Z	d Z
y	)

BlockStatez\
    Container for block state data with attribute access and formatted representation.
    c                 N    |j                         D ]  \  }}t        | ||        y rh   )rd   setattr)r9   kwargsr4   r5   s       r:   __init__zBlockState.__init__   s'     ,,. 	&JCD#u%	&r<   r4   c                     t        | |d       S rh   )getattr)r9   r4   s     r:   __getitem__zBlockState.__getitem__   s    tS$''r<   r5   c                     t        | ||       y rh   )rr   )r9   r4   r5   s      r:   __setitem__zBlockState.__setitem__   s    c5!r<   c                 H    t        | j                  j                               S )z
        Convert BlockState to a dictionary.

        Returns:
            Dict[str, Any]: Dictionary containing all attributes of the BlockState
        )rm   rH   rd   rI   s    r:   as_dictzBlockState.as_dict   s     DMM'')**r<   c                 z    d dj                  fd| j                  j                         D              }d| dS )Nc                    t        | d      r)t        | d      rd| j                   d| j                   dS t        | t              rat        |       dkD  rHt        | d   d      r9t        | d   d      r*| D cg c]  }|j                   }}dt        |        d| S t        |       S t        | t              rat        |       dkD  rHt        | d   d      r9t        | d   d      r*| D cg c]  }|j                   }}d	t        |        d| S t        |       S t        | t              ri }| j                         D ]  \  }}t        |d      r-t        |d      r!d
|j                   d|j                   d||<   ?t        |t              rZt        |      dkD  rLt        |d   d      r=t        |d   d      r.|D cg c]  }|j                   }}dt        |       d| ||<   t        |      ||<    |S t        |       S c c}w c c}w c c}w )NrM   rN   rO   rP   rQ   r   zList[z] of Tensors with shapes zTuple[zTensor(shape=z, dtype=)
rR   rN   rM   rA   rS   rT   rU   tuplerm   rd   )rV   tshapesformatted_dictr^   vals         r:   rW   z)BlockState.__repr__.<locals>.format_value   s   q'"wq'':&qwwixyBB At$q6A:'!A$"8WQqT7=S/01!agg1F1"3q6(*CF8LLAw Au%q6A:'!A$"8WQqT7=S/01!agg1F1#CF8+DVHMMAw At$!#ggi 6FAssG,g1F.;CII;hsyykYZ,[q)"3-HqL#CFG4#CFG436!7a!''!7!7.3CH:=VW]V^,_q),0Iq)6 &% 7N= 2 2  "8s   6H 'H9H
rX   c              3   @   K   | ]  \  }}d | d |         ywrZ   r[   r\   s      r:   r_   z&BlockState.__repr__.<locals>.<genexpr>   s'     _AaS<?*;<_r`   zBlockState(
z
))rc   rH   rd   )r9   
attributesrW   s     @r:   rg   zBlockState.__repr__   s;    &	P YY_I\I\I^__
zl#..r<   N)ri   rj   rk   rl   rt   rB   rw   r   ry   r{   rg   r[   r<   r:   rp   rp      s5    &(s ("s "3 "+*/r<   rp   c            	       d   e Zd ZdZdZdZed        Zd Ze	de
fd       Ze	dee   fd       Ze	dee   fd	       Ze	dee   fd
       Zd Ze	dee   fd       Ze	dee   fd       Zd Ze	dee   fd       Ze	 d$de
dee   fd       Zd%dZ	 	 	 d&deee
ej>                  f      dee    dee
   ddfdZ!de"de#fdZ$de"de%fdZ&e'dee(e
ee   f      dee   fd       Z)e'dee(e
ee   f      dee   fd       Z*e	dee
   fd        Z+e	dee
   fd!       Z,e	dee
   fd"       Z-e	d#        Z.y)'ModularPipelineBlocksad  
    Base class for all Pipeline Blocks: PipelineBlock, AutoPipelineBlocks, SequentialPipelineBlocks,
    LoopSequentialPipelineBlocks

    [`ModularPipelineBlocks`] provides method to load and save the defination of pipeline blocks.

    <Tip warning={true}>

        This is an experimental feature and is likely to change in the future.

    </Tip>
    zmodular_config.jsonNc                    t        j                  |j                        j                  }|j	                         D ci c]&  \  }}|j
                  t         j                  k(  s$||( }}}t        |j	                         D ch c]%  \  }}|j
                  t         j                  k7  s$|' c}}      }t        |j                               dhz
  }||fS c c}}w c c}}w )Nr9   )	inspect	signaturert   
parametersrd   r>   _emptyr;   r=   )clsobjr   r^   rV   required_parametersoptional_parametersexpected_moduless           r:   _get_signature_keysz)ModularPipelineBlocks._get_signature_keys   s    &&s||4??
0:0@0@0Bb1aiiSZSaSaFaq!tbb!1A1A1C"cAqyyT[TbTbGb1"cd2779:fXE!444	 c"cs   %C#C%C
)C
c                 "    t               | _        y rh   )r"   
sub_blocksrI   s    r:   rt   zModularPipelineBlocks.__init__   s    (*r<   r?   c                      y)<Description of the block. Must be implemented by subclasses. r[   rI   s    r:   descriptionz!ModularPipelineBlocks.description   s     r<   c                     g S rh   r[   rI   s    r:   expected_componentsz)ModularPipelineBlocks.expected_components       	r<   c                     g S rh   r[   rI   s    r:   expected_configsz&ModularPipelineBlocks.expected_configs   r   r<   c                     g S z<List of input parameters. Must be implemented by subclasses.r[   rI   s    r:   inputszModularPipelineBlocks.inputs  	     	r<   c                 |    g }| j                   D ]*  }|j                  s|j                  |j                         , |S rh   )r   requiredr8   namer9   input_namesinput_params      r:   _get_required_inputsz*ModularPipelineBlocks._get_required_inputs	  s?    ;; 	5K##"";#3#34	5 r<   c                 "    | j                         S rh   )r   rI   s    r:   required_inputsz%ModularPipelineBlocks.required_inputs  s    ((**r<   c                     g S zJList of intermediate output parameters. Must be implemented by subclasses.r[   rI   s    r:   intermediate_outputsz*ModularPipelineBlocks.intermediate_outputs  r   r<   c                     | j                   S rh   r   rI   s    r:   _get_outputsz"ModularPipelineBlocks._get_outputs  s    (((r<   c                 "    | j                         S rh   )r   rI   s    r:   outputszModularPipelineBlocks.outputs  s      ""r<   pretrained_model_name_or_pathtrust_remote_codec                    g d}|D ci c]  }||v s||j                  |       }}| j                  |      }d|v xr | j                  |d   v }t        |||      }|r|st	        d      |d   | j                     }	|	j                  d      \  }
}|
dz   }
t        |f|
|d||}|j                  |      \  }}|D ci c]  }||v s||v s||j                  |       }} |di |S c c}w c c}w )N)	cache_dirforce_downloadlocal_files_onlyproxiesresume_downloadrevision	subfoldertokenauto_mapzoSelected model repository does not happear to have any custom code or does not have a valid `config.json` file..z.py)module_file
class_namer[   )popload_configri   r   
ValueErrorsplitr   r   )r   r   r   rs   hub_kwargs_namesr   
hub_kwargsconfighas_remote_code	class_refr   r   	block_clsexpected_kwargsoptional_kwargsblock_kwargss                   r:   from_pretrainedz%ModularPipelineBlocks.from_pretrained!  sW   	
 :J\TU[^dFJJt,,\
\!>?$.U3<<6*CU3U5<o
  $5 B  :&s||4	"+//#"6Z!E)1)
#!
 	

 
	 ,5+H+H+S(/5
'+9PTX\kTkD&**T""
 
 (<((7 ].
s   	C-C-C2C2c                    | j                   j                  }t        |       j                  }|j	                  dd      d   j                  dd      }| j                  j                  j                  j                  dd      d   }| | d| i}| j                  |        | j                  d	||d| t        | j                        }	t        |	      | _        y )
Nr   r   __dynamic__r   r   )r   )save_directorypush_to_hubr[   )	__class__ri   typerj   rsplitreplacesave_pretrained__func__rk   r   register_to_configsave_configrm   r   r   _internal_dict)
r9   r   r   rs   cls_namefull_modmoduleparent_moduler   r   s
             r:   r   z%ModularPipelineBlocks.save_pretrainedO  s    >>**:((a(,44]BG,,55BBHHaPQRS$o6(!H:(>?2ZKZSYZdkk"(0r<   components_manager
collectionModularPipelinec                     t         j                  | j                  t        j                        }t        j                  d      }t        ||      } |t        |       |||      }|S )z\
        create a ModularPipeline, optionally accept modular_repo to load from hub.
        	diffusersblocksr   r   r   )	MODULAR_PIPELINE_MAPPINGrC   
model_namer   ri   	importlibimport_modulerv   r   )r9   r   r   r   pipeline_class_namediffusers_modulepipeline_classmodular_pipelines           r:   init_pipelinez#ModularPipelineBlocks.init_pipeline]  sc     7::4??OLdLde$22;? !13FG)D>*G1!	
  r<   statec                    i }| j                   }|D ]  }|j                  rf|j                  |j                        }|j                  r|t	        d|j                   d      ||V|j                  |vse|||j                  <   u|j
                  s|j
                  |vri ||j
                  <   |j                  |j
                        }|s|j                         D ]  \  }}|	|||<   |||j
                     |<   !  t        di |S )z2Get all inputs and intermediates in one dictionaryzRequired input 'z' is missingr[   )	r   r   rC   r   r   r6   rF   rd   rp   )	r9   r   datastate_inputsr   r5   inputs_kwargsr^   rV   s	            r:   get_block_statez%ModularPipelineBlocks.get_block_stater  s"   {{ ( 	AK		+"2"23''EM$'78H8H7I%VWW&5=[=M=MUY=Y-2D))*((**$646D001 % 3 3K4K4K L  - 3 3 5 A1=&'DG?@D!8!89!<A	A& !D!!r<   block_statec                     | j                   D ]n  }t        ||j                        st        d|j                   d      t	        ||j                        }|j                  |j                  ||j                         p | j                  D ]  }|j                  rtt        ||j                        r^t	        ||j                        }|j                  |j                        }||us\|j                  |j                  ||j                         |j                  s|j                  |j                        }|j                         D ]C  \  }}|	t        ||      st	        ||      }||us'|j                  |||j                         E  y )NzIntermediate output 'z' is missing in block state)r   rR   r   r   rv   r;   r6   r   rC   rF   rd   )	r9   r   r   output_paramparamr   current_valueintermediate_kwargs
param_names	            r:   set_block_statez%ModularPipelineBlocks.set_block_state  sn    55 	JL;(9(9: #89J9J8KKf!ghhK):):;EIIl''0H0HI		J  ;; 	NKGK9I9I$J[-=-=> %		+*:*: ; -IIk..{7N7NO(( ',&9&9+:Q:Q&R#1D1J1J1L 	N-J!) ";
; #K<E$E1		*e[5L5LM	N	Nr<   named_input_listsc                  *   i }i }| D ]  \  }}|D ]  }|j                   |j                  d|j                  z   }n|j                   }||v r||   }|j                  n|j                  b|j                  |j                  k7  rIt        j                  d| d|j                   d||    d|j                   d| d|j                   d       |j                  |j                  |||<   |||<   |||<   |||<     t        |j                               S )a  
        Combines multiple lists of InputParam objects from different blocks. For duplicate inputs, updates only if
        current default value is None and new default value is not None. Warns if multiple non-None default values
        exist for the same input.

        Args:
            named_input_lists: List of tuples containing (block_name, input_param_list) pairs

        Returns:
            List[InputParam]: Combined list of unique InputParam objects
        z*_z3Multiple different default values found for input '': z (from block 'z') and z
'). Using r   )r   r6   r>   warningswarnrS   r2   )r   combined_dictvalue_sources
block_namer   r   
input_namecurrent_params           r:   combine_inputsz$ModularPipelineBlocks.combine_inputs  sU    "3 	;J% ;##+0G0G0S!%(?(?!?J!,!1!1J.$1*$=M%--9'//;)11[5H5HH QR\Q]]`,445^MR\D]C^^e*223>*ZXeXmXmWnnoq
 %,,49L9L9X4?j14>j10;M*-0:M*--;	;2 M((*++r<   named_output_listsc                      i }| D ]P  \  }}|D ]F  }|j                   |vs'||j                      j                  +|j                  8|||j                   <   H R t        |j                               S )ar  
        Combines multiple lists of OutputParam objects from different blocks. For duplicate outputs, keeps the first
        occurrence of each output name.

        Args:
            named_output_lists: List of tuples containing (block_name, output_param_list) pairs

        Returns:
            List[OutputParam]: Combined list of unique OutputParam objects
        )r   r6   rS   r2   )r
  r  r  r   r   s        r:   combine_outputsz%ModularPipelineBlocks.combine_outputs  s     #5 	DJ ' D %%]:!,"3"34@@H\MeMeMq7CM,"3"34	D	D M((*++r<   c                 T    | j                   D cg c]  }|j                   c}S c c}w rh   )r   r   )r9   r   s     r:   r   z!ModularPipelineBlocks.input_names  s     48KK@[  @@@   %c                 T    | j                   D cg c]  }|j                   c}S c c}w rh   )r   r   r9   r   s     r:   intermediate_output_namesz/ModularPipelineBlocks.intermediate_output_names  s"    6:6O6OPl!!PPPr  c                 T    | j                   D cg c]  }|j                   c}S c c}w rh   )r   r   r  s     r:   output_namesz"ModularPipelineBlocks.output_names  s     6:llCl!!CCCr  c                     t        | j                  | j                  | j                  | j                  j
                  | j                  | j                        S N)r   r   r   r&   r   r   r   r   ri   r   r   rI   s    r:   doczModularPipelineBlocks.doc  E    KKLL~~.. $ 8 8!22
 	
r<   rh   FNNN)/ri   rj   rk   rl   config_namer   classmethodr   rt   propertyrB   r   r	   r   r   r    r   r!   r   r   r   r#   r   r   r   r
   boolr   r   r   osPathLiker   r   r0   rm   r   rp   r   staticmethodr   r	  r  r   r  r  r  r[   r<   r:   r   r      s    (KJ5 5+ S   T-%8   $z"2   Z(   +j!1 + + d;&7  ) #k* # #  -1+)'*+) $D>+) +)Z1  LP:>$(	 '/c2;;6F0G'H  %%67  SM	 
 
 *"] "t "6N] N N< (,4c4
;K6K0L+M (,RVWaRb (, (,T ,T%T+=N8N2O-P ,UYZeUf , ,, AT#Y A A Q49 Q Q Dd3i D D 
 
r<   r   c                   @   e Zd ZdZg Zg Zg Zd Zed        Z	ed        Z
ed        Zed        Zedee   fd       Zedeeeef      fd	       Zedee   fd
       Zedee   fd       Z ej,                         dedefd       Zd Zed        Zd Zed        Zy)AutoPipelineBlocksa  
    A Pipeline Blocks that automatically selects a block to run based on the inputs.

    This class inherits from [`ModularPipelineBlocks`]. Check the superclass documentation for the generic methods the
    library implements for all the pipeline blocks (such as loading or saving etc.)

    <Tip warning={true}>

        This is an experimental feature and is likely to change in the future.

    </Tip>

    Attributes:
        block_classes: List of block classes to be used
        block_names: List of prefixes for each block
        block_trigger_inputs: List of input names that trigger specific blocks, with None for default
    c                    t               }t        | j                  | j                        D ]  \  }} |       ||<    || _        t        | j                        t        | j                        cxk(  rt        | j                        k(  s%n t        d| j                  j                   d      | j                  D cg c]  }||	 }}t        |      dkD  st        |      dk(  r2| j                  d   #t        d| j                  j                   d      t        t        | j                  | j                  j                                     | _        t        t        | j                  | j                  j                                     | _        t        t        | j                  j                         | j                              | _        y c c}w )NzIn zV, the number of block_classes, block_names, and block_trigger_inputs must be the same.r   r   zQ, exactly one None must be specified as the last element in block_trigger_inputs.)r"   zipblock_namesblock_classesr   rT   block_trigger_inputsr   r   ri   rm   r2   trigger_to_block_mapr=   trigger_to_block_name_mapblock_to_trigger_map)r9   r   r  r   r   default_blockss         r:   rt   zAutoPipelineBlocks.__init__  s   #%
%()9)94;M;M%N 	1!J	%.[Jz"	1$D&&'3t/?/?+@bCHaHaDbbdnn--.  /E  F  &*%>%>L!)!LL
 ~"s>':a'?DD]D]^`DaDmdnn--. /+ +  %)T-F-FH^H^H`)a$b!)-c$2K2KT__MaMaMc.d)e&$(T__-A-A-CTE^E^)_$`! Ms   ;GGc                 n    t        t        | j                  j                                     j                  S rh   )nextiterr   r2   r   rI   s    r:   r   zAutoPipelineBlocks.model_name5  s%    D//123>>>r<   c                      yNr   r[   rI   s    r:   r   zAutoPipelineBlocks.description9      r<   c                     g }| j                   j                         D ])  }|j                  D ]  }||vs|j                  |        + |S rh   r   r2   r   r8   r9   r   block	components       r:   r   z&AutoPipelineBlocks.expected_components=  X     __++- 	:E"66 :	$77'..y9:	: #"r<   c                     g }| j                   j                         D ])  }|j                  D ]  }||vs|j                  |        + |S rh   r   r2   r   r8   r9   r   r6  r   s       r:   r   z#AutoPipelineBlocks.expected_configsF  X    __++- 	4E00 4!11$++F34	4  r<   r?   c           	         d | j                   vrg S t        t        | j                  j	                                     }t        t        |dt                           }t        | j                  j	                               dd  D ]1  }t        t        |dt                           }|j                  |       3 t        |      S Nr   r   )	r(  r.  r/  r   r2   r;   rv   rS   intersection_update)r9   first_blockrequired_by_allr6  block_requireds        r:   r   z"AutoPipelineBlocks.required_inputsO  s    t000I4 6 6 89:gk3DceLM $//0023AB7 	@E 0A35!IJN//?	@ O$$r<   c                     | j                   j                         D cg c]  \  }}||j                  f }}} | j                  | }|D ])  }|j                  | j
                  v rd|_        #d|_        + |S c c}}w )NTF)r   rd   r   r	  r   r   r   )r9   r   r6  named_inputscombined_inputsr   s         r:   r   zAutoPipelineBlocks.inputs^  s    @D@U@U@WXuu||,XX-$--|<* 	-K4#7#77'+$',$		-
  Ys   A8c                     | j                   j                         D cg c]  \  }}||j                  f }}} | j                  | }|S c c}}w rh   )r   rd   r   r  r9   r   r6  named_outputscombined_outputss        r:   r   z'AutoPipelineBlocks.intermediate_outputsj  sP    OSOdOdOfge$ : :;gg/4//? h   A
c                     | j                   j                         D cg c]  \  }}||j                  f }}} | j                  | }|S c c}}w rh   )r   rd   r   r  rG  s        r:   r   zAutoPipelineBlocks.outputsp  sN    BF//BWBWBYZ;4$.ZZ/4//? [rJ  r   c                 <   | j                   j                  d       }| j                  D ]'  }||j                  |      | j                   |   } n |0t        j	                  d| j
                  j                          ||fS 	 t        j                  d|j
                  j                   d         |||      S # t        $ rU}d|j
                  j                   dt        |       dt        j                          }t        j                  |        d }~ww xY w)Nzskipping auto block: zRunning block: z, trigger: z
Error in block: z
Error details: 
Traceback:
)r)  rC   r(  loggerwarningr   ri   info	ExceptionrB   	traceback
format_excerror)r9   pipeliner   r6  r  e	error_msgs          r:   __call__zAutoPipelineBlocks.__call__v  s    ))--d333 	J%%))J*?*K11*=	
 =NN24>>3J3J2KLMU?"
	KK/%//*B*B)C;zl[\5)) 	$U__%=%=$> ?""%a& *(33568 
 LL#	s   7B= =	DADDc                 ~    fdt        | j                        }|j                   | j                               |S )
        Returns a set of all unique trigger input values found in the blocks. Returns: Set[str] containing all unique
        block_trigger_inputs values
        c                 $   t               }| | j                         D ]o  \  }}t        |d      r.|j                  "|j	                  d |j                  D               |j
                  sM |j
                        }|j	                  |       q |S )Nr(  c              3   &   K   | ]	  }||  y wrh   r[   r]   r   s     r:   r_   z[AutoPipelineBlocks._get_trigger_inputs.<locals>.fn_recursive_get_trigger.<locals>.<genexpr>       -eAWXWda-e   r;   rd   rR   r(  updater   r   trigger_valuesr   r6  nested_triggersfn_recursive_get_triggers        r:   re  zHAutoPipelineBlocks._get_trigger_inputs.<locals>.fn_recursive_get_trigger       UN!#)<<> 	?KD%u&<=%B\B\Bh&---e9S9S-ee ''*B5CSCS*T&--o>	? "!r<   )r;   r(  ra  r   )r9   trigger_inputsre  s     @r:   _get_trigger_inputsz&AutoPipelineBlocks._get_trigger_inputs  s8    	"" T6676tGHr<   c                 "    | j                         S rh   rh  rI   s    r:   rg  z!AutoPipelineBlocks.trigger_inputs      ''))r<   c           	      p   | j                   j                  }| j                   j                  d   j                  }|r|dk7  r| d| dn| d}| j                  r8|dz  }|dz  }|dz  }|d| j                  D cg c]  }||	 c} dz  }|d	z  }| j                  j                  d      }g }|j                  d
|d           t        |      dkD  r|j                  d |dd  D               dj                  |      dz   }t        | dg       }t        |dd      }t        | dg       }	t        |	dd      }
d}t        | j                  j                               D ]  \  }\  }}d }t!        | d      r}| j"                  j%                  |      }|d}n9t'        |t(        t*        f      rddj                  d |D               d}nd| d}|d| d| d|j                   j                   dz  }n#|d| d| d|j                   j                   dz  }|j                  j                  d      }|d   }t        |      dkD  r!|ddj                  d |dd  D              z   z  }|d | d!z  } | d| }|j-                         r|d!| z  }|
j-                         r|d!|
 z  }|d!| d"z  }|S c c}w )#Nr   object(
  Class: rX   (
g  ====================================================================================================
N  This pipeline contains blocks that are selected at runtime based on inputs.
  Trigger Inputs: h  ====================================================================================================

  Description: r   c              3   &   K   | ]	  }d |   ywz      Nr[   r]   lines     r:   r_   z.AutoPipelineBlocks.__repr__.<locals>.<genexpr>       CD&C   r   r   Findent_leveladd_empty_linesr     Sub-Blocks:
r+  	[default]
[trigger: , c              3   2   K   | ]  }t        |        y wrh   rB   r]  s     r:   r_   z.AutoPipelineBlocks.__repr__.<locals>.<genexpr>       8QAQ8Qrb   ]       •   ()
    [] c              3   &   K   | ]	  }d |z     ywz                   Nr[   rw  s     r:   r_   z.AutoPipelineBlocks.__repr__.<locals>.<genexpr>       1jSW2G$2N1jrz         Description: 

rQ   )r   ri   	__bases__rg  r   r   r8   rT   extendrc   rv   r$   r%   	enumerater   rd   rR   r+  rC   rA   rS   r~   strip)r9   r   
base_classheaderinp
desc_linesdescr   components_strr   configs_str
blocks_strir   r6  triggertrigger_strindented_descresults                      r:   rg   zAutoPipelineBlocks.__repr__  s6   ^^,,
^^--a099
9C
V^H^zl,zl"5gqfrrudv 	 dNF--FggF*4;N;N+bCRURaC+b*cceffF//F %%++D1
ojm_56z?QKKCJqrNCCyy% &d,A2F*+>Q`ef #4);R@$%5AW\] '
 )$//*?*?*A B 	EA}eGt343377=?"-K$7$.tyy8Q8Q/Q.RRS"TK$.wiq"9Ka}Bu?W?W>XX[\\
 aS4&5??3K3K2LCPP
 **006J&qMM:"		1j[efgfh[i1j(j!jj0tDDJ/	E4 82dV$ !^,--F [M**F 	DA&&} ,cs   9J3J3c                     t        | j                  | j                  | j                  | j                  j
                  | j                  | j                        S r  r  rI   s    r:   r  zAutoPipelineBlocks.doc  r  r<   N)ri   rj   rk   rl   r'  r&  r(  rt   r  r   r   r   r   r	   rB   r   r   r   r   r   r   torchno_gradr0   rX  rh  rg  rg   r  r[   r<   r:   r#  r#    sR   $ MKa2 ? ?   # #     %c % % 	U38_- 	 	  d3i    
  c    
 U]]_ -  28 * *IV 
 
r<   r#  c                   r   e Zd ZdZg Zg Zed        Zed        Zed        Z	ed        Z
edeeef   dd fd       Zd	 Zd
 Zedeeeef      fd       Zedee   fd       Zedee   fd       Zedee   fd       Z ej2                         dedefd       Zd Zed        Zd Zd Zd Z ed        Z!y)SequentialPipelineBlocksaI  
    A Pipeline Blocks that combines multiple pipeline block classes into one. When called, it will call each block in
    sequence.

    This class inherits from [`ModularPipelineBlocks`]. Check the superclass documentation for the generic methods the
    library implements for all the pipeline blocks (such as loading or saving etc.)

    <Tip warning={true}>

        This is an experimental feature and is likely to change in the future.

    </Tip>

    Attributes:
        block_classes: List of block classes to be used
        block_names: List of prefixes for each block
    c                      yr1  r[   rI   s    r:   r   z$SequentialPipelineBlocks.description  r2  r<   c                 X    t        d | j                  j                         D        d       S )Nc              3   N   K   | ]  }|j                   |j                     y wrh   )r   )r]   r6  s     r:   r_   z6SequentialPipelineBlocks.model_name.<locals>.<genexpr>#  s!     l%uO_O_OkU%%ls   %%)r.  r   r2   rI   s    r:   r   z#SequentialPipelineBlocks.model_name!  s#    l4??3I3I3Klnrssr<   c                     g }| j                   j                         D ])  }|j                  D ]  }||vs|j                  |        + |S rh   r4  r5  s       r:   r   z,SequentialPipelineBlocks.expected_components%  r8  r<   c                     g }| j                   j                         D ])  }|j                  D ]  }||vs|j                  |        + |S rh   r:  r;  s       r:   r   z)SequentialPipelineBlocks.expected_configs.  r<  r<   blocks_dictr?   c                 P    |        }t               }|j                         D ]*  \  }}t        j                  |      r |       ||<   &|||<   , |j	                         D cg c]  }|j
                   c}|_        t        |j                               |_	        ||_
        |S c c}w )zCreates a SequentialPipelineBlocks instance from a dictionary of blocks.

        Args:
            blocks_dict: Dictionary mapping block names to block classes or instances

        Returns:
            A new SequentialPipelineBlocks instance
        r"   rd   r   isclassr2   r   r'  rS   r=   r&  r   r   r  instancer   r   r6  s         r:   from_blocks_dictz)SequentialPipelineBlocks.from_blocks_dict7  s     5 $%
&,,. 	)KD%u%#(7
4 #(
4 		) @J?P?P?R!Se%//!S#JOO$56( "T   !B#c                     t               }t        | j                  | j                        D ]  \  }} |       ||<    || _        y rh   r"   r%  r&  r'  r   r9   r   r  r   s       r:   rt   z!SequentialPipelineBlocks.__init__P  D    #%
%()9)94;M;M%N 	1!J	%.[Jz"	1$r<   c                    g }t               }| j                  j                         D ]  }|j                  D ]I  }|j                  |vs|j                  |D ch c]  }|j                   c}vs9|j                  |       K d}t        |d      rd |j                  vrd}|s||j                  D cg c]  }|j                   }}|j                  |        |S c c}w c c}w NTr(  F)
r;   r   r2   r   r   r8   rR   r(  r   ra  )	r9   r   r   r6  r  inputshould_add_outputsoutblock_intermediate_outputss	            r:   _get_inputsz$SequentialPipelineBlocks._get_inputsV  s    % __++- 	;E|| '887*sxxX^?_u

?_/_MM#&'
 "&u45$eF`F`:`%*"!BGB\B\-]3chh-]*-]9:	;   @` .^s   C
1C c                 "    | j                         S rh   r  rI   s    r:   r   zSequentialPipelineBlocks.inputsn  s    !!r<   c           	      `   t        t        | j                  j                                     }t	        t        |dt	                           }t        | j                  j                               dd  D ]1  }t	        t        |dt	                           }|j                  |       3 t        |      S r>  )r.  r/  r   r2   r;   rv   rS   ra  )r9   r@  required_by_anyr6  rB  s        r:   r   z(SequentialPipelineBlocks.required_inputsr  s     4 6 6 89:gk3DceLM $//0023AB7 	3E 0A35!IJN"">2	3 O$$r<   c                     g }| j                   j                         D ]J  \  }}|j                  D ch c]  }|j                   }}||vs.|j	                  ||j
                  f       L  | j                  | }|S c c}w rh   )r   rd   r   r   r8   r   r  )r9   rH  r   r6  r  	inp_namesrI  s          r:   r   z-SequentialPipelineBlocks.intermediate_outputs  s    ??002 	IKD%-2\\:c:I: 9$$$dE,F,F%GH	I 04//? ;s   A;c                     | j                   S rh   r   rI   s    r:   r   z SequentialPipelineBlocks.outputs  s     (((r<   r   c                 0   | j                   j                         D ]  \  }}	  |||      \  }} ||fS # t        $ rX}d| d|j                  j                   dt        |       dt        j                          }t        j                  |        d }~ww xY wNz
Error in block: (r  z)
Error details: rM  
r   rd   rQ  r   ri   rB   rR  rS  rN  rT  )r9   rU  r   r  r6  rV  rW  s          r:   rX  z!SequentialPipelineBlocks.__call__  s    !%!6!6!8 
	J	"'%"8%
	   )*R8P8P7Q R&&)!fX .##,#7#7#9":< 
 Y's   4	BABBc                 2    fd | j                         S )rZ  c                 $   t               }| | j                         D ]o  \  }}t        |d      r.|j                  "|j	                  d |j                  D               |j
                  sM |j
                        }|j	                  |       q |S )Nr(  c              3   &   K   | ]	  }||  y wrh   r[   r]  s     r:   r_   zaSequentialPipelineBlocks._get_trigger_inputs.<locals>.fn_recursive_get_trigger.<locals>.<genexpr>  r^  r_  r`  rb  s        r:   re  zNSequentialPipelineBlocks._get_trigger_inputs.<locals>.fn_recursive_get_trigger  rf  r<   )r   )r9   re  s    @r:   rh  z,SequentialPipelineBlocks._get_trigger_inputs  s    	"" (88r<   c                 "    | j                         S rh   rj  rI   s    r:   rg  z'SequentialPipelineBlocks.trigger_inputs  rk  r<   c                     t        |      }fdt               }| j                  j                         D ]   \  }} |||      }|j	                  |       " |S )Nc                    t               }t        | d      s| j                  rq| j                  j                         D ]R  \  }} |||      } |||      }|j                         D ci c]  \  }}| d| | }}}|j	                  |       T |S | ||<   t        | d      r"|j	                  d | j
                  D               |S d }	| j                  D ]  }
|
|
|v s| j                  |
   }	 n |	d | j                  v r| j                  d    }	|	Z|	j                  r|j	                   |	||             |S |	||<   t        |	d      r"|j	                  d |	j
                  D               |S c c}}w )Nr(  r   r   c              3   4   K   | ]  }|j                     y wrh   r   r]   r  s     r:   r_   zcSequentialPipelineBlocks._traverse_trigger_blocks.<locals>.fn_recursive_traverse.<locals>.<genexpr>  s     .QCsxx.Q   c              3   4   K   | ]  }|j                     y wrh   r  r  s     r:   r_   zcSequentialPipelineBlocks._traverse_trigger_blocks.<locals>.fn_recursive_traverse.<locals>.<genexpr>  s     2Z3882Zr  )r   rR   r   rd   ra  r   r(  r)  )r6  r  active_triggersresult_blockssub_block_name	sub_blockblocks_to_updater^   rV   
this_blocktrigger_inputfn_recursive_traverses              r:   r  zPSequentialPipelineBlocks._traverse_trigger_blocks.<locals>.fn_recursive_traverse  s   'MM 5"89##5:5E5E5K5K5M ?1	+@N\k+l(+@N\k+l(O_OeOeOg+htq!zl!A3,?,B+h(+h%,,-=>	? %$	 16M*-ui0'...Q5==.QQ$$
 "
%*%?%? M$0]o5U%*%?%?%N
 %$%2L2L*L!&!;!;D!AJ)!,,%,,-B:z[j-kl !  5?j1 #:y9+222ZzGYGY2ZZ  G ,is   +E2)r;   r   r   rd   ra  )r9   rg  r  
all_blocksr  r6  r  r  s          @r:   _traverse_trigger_blocksz1SequentialPipelineBlocks._traverse_trigger_blocks  sc    n--	!^ !]
!%!6!6!8 	0J4UJX./	0 r<   c                 ^   | j                   }|`t        |t        t        t        f      s|g}|D cg c]	  }||vs| }}|r,t
        j                  d|        |D cg c]	  }||v s| }}|d |v rd g}n|d   g}| j                  |      }t        j                  |      S c c}w c c}w )NzHThe following trigger inputs will be ignored as they are not supported: r   )
rg  rA   rS   r~   r;   rN  rO  r  r  r  )r9   rg  trigger_inputs_allxinvalid_inputsblocks_triggereds         r:   get_execution_blocksz-SequentialPipelineBlocks.get_execution_blocks  s    !00%ntUC.@A"0!1)7WA1DV;VaWNW^_m^no .<!WqDV?V!!W!W!))"&"4Q"7!888H'889IJJ X
 "Xs   	B%B%	B*)B*c           	         | j                   j                  }| j                   j                  d   j                  }|r|dk7  r| d| dn| d}| j                  r]|dz  }|dz  }|dz  }|d| j                  D cg c]  }||	 c} dz  }t	        d	 | j                  D              }|d
| dz  }|dz  }| j
                  j                  d      }g }|j                  d|d           t        |      dkD  r|j                  d |dd  D               dj                  |      dz   }t        | dg       }t        |dd      }	t        | dg       }
t        |
dd      }d}t        | j                  j!                               D ]  \  }\  }}d }t#        | d      r}| j$                  j'                  |      }|d}n9t)        |t*        t,        f      rddj                  d |D               d}nd| d}|d| d| d|j                   j                   dz  }n#|d | d!| d|j                   j                   dz  }|j
                  j                  d      }|d   }t        |      dkD  r!|ddj                  d" |dd  D              z   z  }|d#| d$z  } | d| }|	j/                         r|d$|	 z  }|j/                         r|d$| z  }|d$| d%z  }|S c c}w )&Nr   rm  rn  rX   ro  rp  rq  rr  c              3   &   K   | ]	  }||  y wrh   r[   r]  s     r:   r_   z4SequentialPipelineBlocks.__repr__.<locals>.<genexpr>  s      Qq1= Qr_  zd  Use `get_execution_blocks()` with input names to see selected blocks (e.g. `get_execution_blocks('z')`).
rs  rt  r   c              3   &   K   | ]	  }d |   ywrv  r[   rw  s     r:   r_   z4SequentialPipelineBlocks.__repr__.<locals>.<genexpr>#  ry  rz  r   r   Fr{  r   r~  r+  r  r  r  c              3   2   K   | ]  }t        |        y wrh   r  r]  s     r:   r_   z4SequentialPipelineBlocks.__repr__.<locals>.<genexpr>9  r  rb   r  r  r  r  r  r  r  c              3   &   K   | ]	  }d |z     ywr  r[   rw  s     r:   r_   z4SequentialPipelineBlocks.__repr__.<locals>.<genexpr>F  r  rz  r  r  rQ   )r   ri   r  rg  r.  r   r   r8   rT   r  rc   rv   r$   r%   r  r   rd   rR   r+  rC   rA   rS   r~   r  )r9   r   r  r  r  example_inputr  r  r   r  r   r  r  r  r   r6  r  r  r  r  s                       r:   rg   z!SequentialPipelineBlocks.__repr__  su   ^^,,
^^--a099
9C
V^H^zl,zl"5gqfrrudv 	 dNF--FggF*4;N;N+bCRURaC+b*cceffF  QD,?,? QQM|  ~K  }L  LS  T  TF//F %%++D1
ojm_56z?QKKCJqrNCCyy% &d,A2F*+>Q`ef #4);R@$%5AW\] '
 )$//*?*?*A B 	EA}eGt343377=?"-K$7$.tyy8Q8Q/Q.RRS"TK$.wiq"9Ka}Bu?W?W>XX[\\
 aS4&5??3K3K2LCPP
 **006J&qMM:"		1j[efgfh[i1j(j!jj0tDDJ/	E4 82dV$ !^,--F [M**F 	DA&&C ,cs   9KKc                     t        | j                  | j                  | j                  | j                  j
                  | j                  | j                        S r  r  rI   s    r:   r  zSequentialPipelineBlocks.docY  r  r<   N)"ri   rj   rk   rl   r'  r&  r  r   r   r   r   r  r   rB   r   r  rt   r  r	   r   r   r   r   r   r  r  r0   rX  rh  rg  r  r  rg   r  r[   r<   r:   r  r    s   $ MK  t t # #     4S> >X  0%0 "U38_- " " 
%c 
% 
% 	 d3i 	  	  )c ) ) U]]_ -  92 * *7rK*L\ 
 
r<   r  c                      e Zd ZdZdZg Zg Zedefd       Z	ede
e   fd       Zede
e   fd       Zede
e   fd       Zede
e   fd       Zede
e   fd	       Zed
        Zed        Zd Zed        Zede
e   fd       Zede
e   fd       Zede
e   fd       Zd Zedeeef   dd fd       Zde fdZ!de de fdZ"ed        Z#d Z$e%jL                  jN                  dd       Z(d Z)y)LoopSequentialPipelineBlocksaP  
    A Pipeline blocks that combines multiple pipeline block classes into a For Loop. When called, it will call each
    block in sequence.

    This class inherits from [`ModularPipelineBlocks`]. Check the superclass documentation for the generic methods the
    library implements for all the pipeline blocks (such as loading or saving etc.)

    <Tip warning={true}>

        This is an experimental feature and is likely to change in the future.

    </Tip>

    Attributes:
        block_classes: List of block classes to be used
        block_names: List of prefixes for each block
    Nr?   c                     t        d      )r   z4description method must be implemented in subclassesNotImplementedErrorrI   s    r:   r   z(LoopSequentialPipelineBlocks.description|  s     ""XYYr<   c                     g S rh   r[   rI   s    r:   loop_expected_componentsz5LoopSequentialPipelineBlocks.loop_expected_components  r   r<   c                     g S rh   r[   rI   s    r:   loop_expected_configsz2LoopSequentialPipelineBlocks.loop_expected_configs  r   r<   c                     g S r   r[   rI   s    r:   loop_inputsz(LoopSequentialPipelineBlocks.loop_inputs  r   r<   c                 |    g }| j                   D ]*  }|j                  s|j                  |j                         , |S rh   )r  r   r8   r   r   s      r:   loop_required_inputsz1LoopSequentialPipelineBlocks.loop_required_inputs  sA    ++ 	5K##"";#3#34	5 r<   c                     g S r   r[   rI   s    r:   loop_intermediate_outputsz6LoopSequentialPipelineBlocks.loop_intermediate_outputs  r   r<   c                     g }| j                   j                         D ])  }|j                  D ]  }||vs|j                  |        + | j                  D ]  }||vs|j                  |        |S rh   )r   r2   r   r8   r  r5  s       r:   r   z0LoopSequentialPipelineBlocks.expected_components  s     __++- 	:E"66 :	$77'..y9:	: 66 	6I 33#**95	6 #"r<   c                     g }| j                   j                         D ])  }|j                  D ]  }||vs|j                  |        + | j                  D ]  }||vs|j                  |        |S rh   )r   r2   r   r8   r  r;  s       r:   r   z-LoopSequentialPipelineBlocks.expected_configs  s    __++- 	4E00 4!11$++F34	4 00 	0F-- ''/	0  r<   c                    g }|j                  | j                         t               }| j                  j	                         D ]  \  }}|j
                  D ]'  }|j                  |vs||vs|j                  |       ) d}t        |d      rd |j                  vrd}|s]|j                  D cg c]  }|j                   }}|j                  |        |D ])  }	|	j                  | j                  v rd|	_        #d|	_        + |S c c}w r  )r  r  r;   r   rd   r   r   r8   rR   r(  r   ra  r   r   )
r9   r   r   r   r6  r  r  r  r  r   s
             r:   r  z(LoopSequentialPipelineBlocks._get_inputs  s   d&&'%??002 	;KD%|| '887*s&/@MM#&'
 "&u45$eF`F`:`%*"!BGB\B\-]3chh-]*-]9:	;  " 	-K4#7#77'+$',$		-  .^s   -Dc                 "    | j                         S rh   r  rI   s    r:   r   z#LoopSequentialPipelineBlocks.inputs  s     !!r<   c           	         t        t        | j                  j                                     }t	        t        |dt	                           }t	        t        | dt	                           }|j                  |       t        | j                  j                               dd  D ]1  }t	        t        |dt	                           }|j                  |       3 t        |      S )Nr   r  r   )r.  r/  r   r2   r;   rv   ra  rS   )r9   r@  r  required_by_loopr6  rB  s         r:   r   z,LoopSequentialPipelineBlocks.required_inputs  s     4 6 6 89:gk3DceLMwt-CSUKL/0 $//0023AB7 	3E 0A35!IJN"">2	3 O$$r<   c                 <   | j                   j                         D cg c]  \  }}||j                  f }}} | j                  | }| j                  D ]:  }|j
                  |D ch c]  }|j
                   c}vs*|j                         < |S c c}}w c c}w rh   )r   rd   r   r  r  r   r8   )r9   r   r6  rH  rI  outputs         r:   r   z1LoopSequentialPipelineBlocks.intermediate_outputs  s    OSOdOdOfge$ : :;gg/4//?44 	0F{{=M"N66;;"NN ''/	0   h #Os   B&Bc                 n    t        t        | j                  j                                     j                  S rh   )r.  reversedr   r2   r   rI   s    r:   r   z$LoopSequentialPipelineBlocks.outputs  s%    HT__33567LLLr<   c                     t               }t        | j                  | j                        D ]  \  }} |       ||<    || _        y rh   r  r  s       r:   rt   z%LoopSequentialPipelineBlocks.__init__  r  r<   r  c                 P    |        }t               }|j                         D ]*  \  }}t        j                  |      r |       ||<   &|||<   , |j	                         D cg c]  }|j
                   c}|_        t        |j                               |_	        ||_
        |S c c}w )a  
        Creates a LoopSequentialPipelineBlocks instance from a dictionary of blocks.

        Args:
            blocks_dict: Dictionary mapping block names to block instances

        Returns:
            A new LoopSequentialPipelineBlocks instance
        r  r  s         r:   r  z-LoopSequentialPipelineBlocks.from_blocks_dict  s     5 $%
&,,. 	)KD%u%#(7
4 #(
4 		) @K?Q?Q?S!Te%//!T#K$4$4$67) "Ur  r   c                 2   | j                   j                         D ]  \  }}	  |||fi |\  }} ||fS # t        $ rX}d| d|j                  j                   dt        |       dt        j                          }t        j                  |        d }~ww xY wr  r  )r9   
componentsr   rs   r  r6  rV  rW  s           r:   	loop_stepz&LoopSequentialPipelineBlocks.loop_step  s    !%!6!6!8 
	J	$)*e$Fv$F!
E
	 5    )*R8P8P7Q R&&)!fX .##,#7#7#9":< 
 Y's   5	BABBc                     t        d      )Nz9`__call__` method needs to be implemented by the subclassr  )r9   r  r   s      r:   rX  z%LoopSequentialPipelineBlocks.__call__&  s    !"]^^r<   c                     t        | j                  | j                  | j                  | j                  j
                  | j                  | j                        S r  r  rI   s    r:   r  z LoopSequentialPipelineBlocks.doc)  r  r<   c           	         | j                   j                  }| j                   j                  d   j                  }|r|dk7  r| d| dn| d}| j                  j	                  d      }g }|j                  d|d           t        |      dkD  r|j                  d |dd  D               dj                  |      dz   }t        | d	g       }t        |d
d      }t        | dg       }t        |d
d      }	d}
t        | j                  j                               D ]  \  }\  }}|
d| d| d|j                   j                   dz  }
|j                  j	                  d      }|d   }t        |      dkD  r!|ddj                  d |dd  D              z   z  }|
d| dz  }
 | d| }|j                         r|d| z  }|	j                         r|d|	 z  }|d|
 dz  }|S )Nr   rm  rn  rX   ro  rt  r   c              3   &   K   | ]	  }d |   ywrv  r[   rw  s     r:   r_   z8LoopSequentialPipelineBlocks.__repr__.<locals>.<genexpr>E  ry  rz  r   r   Fr{  r   r~  r  r  r  r  c              3   &   K   | ]	  }d |z     ywr  r[   rw  s     r:   r_   z8LoopSequentialPipelineBlocks.__repr__.<locals>.<genexpr>Z  r  rz  r  r  rQ   )r   ri   r  r   r   r8   rT   r  rc   rv   r$   r%   r  r   rd   r  )r9   r   r  r  r  r  r   r  r   r  r  r  r   r6  r  r  s                   r:   rg   z%LoopSequentialPipelineBlocks.__repr__7  s5   ^^,,
^^--a099
9C
V^H^zl,zl"5gqfrrudv 	
 %%++D1
ojm_56z?QKKCJqrNCCyy% &d,A2F*+>Q`ef #4);R@$%5AW\] '
 )$//*?*?*A B 		EA}eE!BtfBu/G/G.HLLJ **006J&qMM:"		1j[efgfh[i1j(j!jj0tDDJ		E 82dV$ !^,--F [M**F 	DA&&r<   c                    t        | d      si | _        n<t        | j                  t              s"t	        dt        | j                         d      |t        |fi | j                  S |t        dd|i| j                  S t	        d      )N_progress_bar_configz=`self._progress_bar_config` should be of type `dict`, but is r   totalz/Either `total` or `iterable` has to be defined.r[   )rR   r  rA   rm   r   r   r   )r9   iterabler  s      r:   progress_barz)LoopSequentialPipelineBlocks.progress_barm  s    t34(*D%D55t<OPTUYUnUnPoOppqr  >D$=$=>>AeAt'@'@AANOOr<   c                     || _         y rh   )r  )r9   rs   s     r:   set_progress_bar_configz4LoopSequentialPipelineBlocks.set_progress_bar_config}  s
    $*!r<   NN)*ri   rj   rk   rl   r   r'  r&  r  rB   r   r	   r   r  r    r  r!   r  r  r#   r  r   r   r  r   r   r   r   rt   r  r   r   r  r0   r  rX  r  rg   r  compilerdisabler  r  r[   r<   r:   r  r  e  s   $ JMKZS Z Z $}*=   tJ'7   T*-   d3i   4+<  
 	# 	# 	  	 : " " %c % %"  d3i     Mc M M% 4S> >\  2!= !_- _M _ 
 
4l ^^P P+r<   r  c                   (   e Zd ZdZdZdZ	 	 	 	 d,dee   deee	e
j                  f      dee   dee	   fdZed	ee	ef   fd
       Zd Zee	 	 	 d-deee	e
j                  f      dee   dee   dee	   fd              Zd.dee	e
j                  f   defdZed        Zd Zed	ej6                  fd       Zed        Zed	ej:                  fd       Zed	ee	   fd       Zed	ee	   fd       Z ed	ee	   fd       Z!ed	ee	   fd       Z"ed	ee	ef   fd       Z#de	d	e$fdZ%d Z&deee	   e	f   fdZ'	 d/d ed!eejP                  jR                     d	efd"Z*d	e+fd#Z,e-d$e$d	efd%       Z.e-de	d&ee	ef   d	e$fd'       Z/d( Z0d0d)e1d*ee	ee	   f   fd+Z2y)1r   z
    Base class for all Modular pipelines.

    <Tip warning={true}>

        This is an experimental feature and is likely to change in the future.

    </Tip>

    Args:
        blocks: ModularPipelineBlocks, the blocks to be used in the pipeline
    zmodular_model_index.jsonNr   r   r   r   c                 h   |t         j                  | j                  j                        }|)t	        j
                  d      }t        ||      } |       }n,t        j                  d| j                  j                          || _	        || _
        || _        | j                  j                  D 	ci c]  }	|	j                  t        |	       c}	| _        | j                  j                   D 	ci c]  }	|	j                  t        |	       c}	| _        | | j$                  |fi |}
|
j'                         D ]  \  }}|| j                  v rSt)        |t*        t,        f      r=t/        |      dk(  r/|\  }}}| j1                  ||      }d|_        || j                  |<   g|| j"                  v sv|| j"                  |   _         i }| j                  j'                         D ],  \  }}|j2                  dk(  r|j7                         }nd}|||<   .  | j8                  di | i }| j"                  j'                         D ]  \  }}|j4                  ||<     | j:                  di | | j;                  | j                  &| j                  j                  j                         yd       yc c}	w c c}	w )	a  
        Initialize a ModularPipeline instance.

        This method sets up the pipeline by:
        - creating default pipeline blocks if not provided
        - gather component and config specifications based on the pipeline blocks's requirement (e.g.
           expected_components, expected_configs)
        - update the loading specs of from_pretrained components based on the modular_model_index.json file from
           huggingface hub if `pretrained_model_name_or_path` is provided
        - create defaultfrom_config components and register everything

        Args:
            blocks: `ModularPipelineBlocks` instance. If None, will attempt to load
                   default blocks based on the pipeline class name.
            pretrained_model_name_or_path: Path to a pretrained pipeline configuration. If provided,
                    will load component specs (only for from_pretrained components) and config values from the saved
                    modular_model_index.json file.
            components_manager:
                Optional ComponentsManager for managing multiple component cross different pipelines and apply
                offloading strategies.
            collection: Optional collection name for organizing components in the ComponentsManager.
            **kwargs: Additional arguments passed to `load_config()` when loading pretrained configuration.

        Examples:
            ```python
            # Initialize with custom blocks
            pipeline = ModularPipeline(blocks=my_custom_blocks)

            # Initialize from pretrained configuration
            pipeline = ModularPipeline(blocks=my_blocks, pretrained_model_name_or_path="my-repo/modular-pipeline")

            # Initialize with components manager
            pipeline = ModularPipeline(
                blocks=my_blocks, components_manager=ComponentsManager(), collection="my_collection"
            )
            ```

        Notes:
            - If blocks is None, the method will try to find default blocks based on the pipeline class name
            - Components with default_creation_method="from_config" are created immediately, its specs are not included
              in config dict and will not be saved in `modular_model_index.json`
            - Components with default_creation_method="from_pretrained" are set to None and can be loaded later with
              `load_default_components()`/`load_components()`
            - The pipeline's config dict is populated with component specs (only for from_pretrained components) and
              config values, which will be saved as `modular_model_index.json` during `save_pretrained`
            - The pipeline's config dict is also used to store the pipeline blocks's class name, which will be saved as
              `_blocks_class_name` in the config dict
        Nr   z6`blocks` is `None`, no default blocks class found for    r   from_config)_blocks_class_namer[   )MODULAR_PIPELINE_BLOCKS_MAPPINGrC   r   ri   r   r   rv   rN  rO  r   _components_manager_collectionr   r   r   _component_specsr   _config_specsr   rd   rA   r~   rS   rT   _dict_to_component_specdefault_creation_methodr>   createregister_componentsr   )r9   r   r   r   r   rs   blocks_class_namer   blocks_classspecconfig_dictr   r5   libraryr   component_spec_dictcomponent_specregister_components_dictr7  default_configsconfig_specs                        r:   rt   zModularPipeline.__init__  s   p > ? C CDNND[D[ \ ,#,#:#:;#G &'79JK%!WX\XfXfXoXoWpqr#5 %GK{{GfGf gtHTN!: gDHKKD`D`aDdii$7a )4*$**+HSFSK*002 	=e4000Zt}5UZ]^cZdhiZi?D<GZ)<%)%A%A$H[%\N=NN:2@D))$/T///7<D&&t,4	= $& $($9$9$?$?$A 	7 D.55F*113	 	-6$T*	7 	!  <#;<!%!3!3!9!9!; 	8D+$/$7$7OD!	82/2UYU`U`Ul4;;3H3H3Q3QwrvwA !has   0J*-J/r?   c                 r    i }| j                   j                  D ]  }|j                  ||j                  <    |S )z_
        Returns:
            - Dictionary mapping input names to their default values
        )r   r   r>   r   )r9   paramsr   s      r:   default_call_parametersz'ModularPipeline.default_call_parameters  s=     ;;-- 	;K'2':':F;##$	;r<   c                     | j                   j                         D cg c]   }| j                   |   j                  dk(  r|" }} | j                  dd|i| yc c}w )z
        Load from_pretrained components using the loading specs in the config dict.

        Args:
            **kwargs: Additional arguments passed to `from_pretrained` method, e.g. torch_dtype, cache_dir, etc.
        r   namesNr[   )r   r=   r#  load_components)r9   rs   r   r4  s       r:   load_default_componentsz'ModularPipeline.load_default_components  si     --224
$$T*BBFWW 
 

 	353F3
s   %Ar   c                    ddl m} 	 t        j                  |fd|i|}|j                  dd      }|j                  dd      }	|j                  dd      }
|j                  d	d      }|j                  d
d      }|j                  dd      }||	|
|||d}	  | j                  |fi |} || |      } |d||||d|}|S # t        $ r d}Y w xY w# t        $ r | }d}Y /w xY w)a  
        Load a ModularPipeline from a huggingface hub repo.

        Args:
            pretrained_model_name_or_path (`str` or `os.PathLike`, optional):
                Path to a pretrained pipeline configuration. If provided, will load component specs (only for
                from_pretrained components) and config values from the modular_model_index.json file.
            trust_remote_code (`bool`, optional):
                Whether to trust remote code when loading the pipeline, need to be set to True if you want to create
                pipeline blocks based on the custom code in `pretrained_model_name_or_path`
            components_manager (`ComponentsManager`, optional):
                ComponentsManager instance for managing multiple component cross different pipelines and apply
                offloading strategies.
            collection (`str`, optional):`
                Collection name for organizing components in the ComponentsManager.
        r   )_get_pipeline_classr   Nr   r   Fr   r   r   r   )r   r   r   r   r   r   )r   r   r[   ) pipelines.pipeline_loading_utilsr8  r   r   EnvironmentErrorr   r   )r   r   r   r   r   rs   r8  r   r   r   r   r   r   r   load_config_kwargsr)  r   rU  s                     r:   r   zModularPipeline.from_pretrained  s9   4 	K	*::-ARV\F JJ{D1	$4e<**Y-

7D)!::&8%@::j$/ #, 0 
	1)#//*G^K]^K0[IN
 " 
*G1!	

 
 C   	F	,   	1 N,0)	1s#   C C CCC#"C#r   r   c                 (   |r|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  d|j                  t        j                  j                        d         }t        |d	||
      j                  }t        ||d	      }	t        |	      }	|	j                  t        j                  j                  |d             | j                  |       |r| j                  |       yy)a  
        Save the pipeline to a directory. It does not save components, you need to save them separately.

        Args:
            save_directory (`str` or `os.PathLike`):
                Path to the directory where the pipeline will be saved.
            push_to_hub (`bool`, optional):
                Whether to push the pipeline to the huggingface hub.
            **kwargs: Additional arguments passed to `save_config()` method
        commit_messageNprivate	create_prFr   repo_idr   T)exist_okr>  r   )r   is_pipelinez	README.md)r   )r   r=  r?  )r   r   r  pathsepr   r@  r   r   saverc   r   _upload_folder)
r9   r   r   rs   r=  r>  r?  r   r@  
model_cards
             r:   r   zModularPipeline.save_pretrainedY  s     #ZZ(8$?NjjD1G

;6IJJw-EjjN,@,@,Mb,QRG!'D'QVW__G 37%UYZJ,Z8JOOBGGLLEF 	7-#    r<   c                 .    | j                   j                  S )zM
        Returns:
            - The docstring of the pipeline blocks
        )r   r  rI   s    r:   r  zModularPipeline.doc}  s     {{r<   c           	         |j                         D ]  \  }}| j                  j                  |      }|t        j	                  d| d       >t        | |      }|j                  dk(  }|t        |      \  }}nd\  }}| j                  |      }	||||	fi}
|sY|r | j                  di |
 t        | ||       |5|r3| j                  '| j                  j                  ||| j                         t        | |d      }||u rt        j                  d| d       |3|1t        j                  d| d	|j                   j"                   d
       nN|L|Jt%        ||j                         r4||k7  r/t        j'                  d| dt)        |      j"                   d       |r | j                  di |
 t        | ||       ||s| j                  | j                  j                  ||| j                          y)a  
        Register components with their corresponding specifications.

        This method is responsible for:
        1. Sets component objects as attributes on the loader (e.g., self.unet = unet)
        2. Updates the config dict, which will be saved as `modular_model_index.json` during `save_pretrained` (only
           for from_pretrained components)
        3. Adds components to the component manager if one is attached (only for from_pretrained components)

        This method is called when:
        - Components are first initialized in __init__:
           - from_pretrained components not loaded during __init__ so they are registered as None;
           - non from_pretrained components are created during __init__ and registered as the object itself
        - Components are updated with the `update_components()` method: e.g. loader.update_components(unet=unet) or
          loader.update_components(guider=guider_spec)
        - (from_pretrained) Components are loaded with the `load_default_components()` method: e.g.
          loader.load_default_components(names=["unet"])

        Args:
            **kwargs: Keyword arguments where keys are component names and values are component objects.
                      E.g., register_components(unet=unet_model, text_encoder=encoder_model)

        Notes:
            - When registering None for a component, it sets attribute to None but still syncs specs with the config
              dict, which will be saved as `modular_model_index.json` during `save_pretrained`
            - component_specs are updated to match the new component outside of this method, e.g. in
              `update_components()` method
        NzAModularPipeline.register_components: skipping unknown component ''r   r  z%ModularPipeline.register_components: z1 is already registered with same object, skippingz.ModularPipeline.register_components: setting 'z' to None (was rQ   z9ModularPipeline.register_components: replacing existing 'z' (same type z, new instance)r[   )rd   r   rC   rN  rO  rR   r#  r   _component_spec_to_dictr   rr   r  addr  rv   rP  r   ri   rA   debugr   )r9   rs   r   r   r,  is_registeredis_from_pretrainedr*  r   r+  register_dictcurrent_modules               r:   r%  z#ModularPipeline.register_components  s>   : #LLN I	MLD&!2266t<N%!bcgbhhijk $D$/M!/!G!GK\!\!&@&H#
 '1# #'">">~"N!GZ9L#MNM !%+D++<m<dF+%*<AYAYAe,,00vt?O?OP$T46N';D6Ars  )fnDTF K*44==>aA *&v~'?'?@"f,OPTv V""&~"6"?"?!@Q "'''8-8D$'!&8T=U=U=a((,,T64;K;KLSI	Mr<   c                     | j                   j                         }|D cg c])  }t        |t        j                  j
                        s(|+ }}|D ]  }|j                  c S  t        j                  d      S c c}w )zi
        Returns:
            `torch.device`: The torch device on which the pipeline is located.
        cpu)r  r2   rA   r  nnModuledevicer9   modulesmr   s       r:   rV  zModularPipeline.device  sj     //((*%HAuxx)G1HH 	!F== 	! ||E"" Is   )A8	A8c                    | j                   j                         D ]  \  }}t        |t        j                  j
                        s+t        |d      s| j                  c S |j                         D ]i  }t        |d      st        |j                  d      s'|j                  j                  >t        j                  |j                  j                        c c S   | j                  S )z
        Returns the device on which the pipeline's models will be executed. After calling
        [`~DiffusionPipeline.enable_sequential_cpu_offload`] the execution device can only be inferred from
        Accelerate's module hooks.
        _hf_hookexecution_device)r  rd   rA   r  rT  rU  rR   rV  rX  r[  r\  )r9   r   modelr   s       r:   _execution_devicez!ModularPipeline._execution_device  s      ??002 	JKD%eUXX__55*-{{"--/ JFJ/1CD88D <<(H(HIIJ	J {{r<   c                     | j                   j                         }|D cg c])  }t        |t        j                  j
                        s(|+ }}|D ]  }|j                  c S  t        j                  S c c}w )zg
        Returns:
            `torch.dtype`: The torch dtype on which the pipeline is located.
        )r  r2   rA   r  rT  rU  rN   float32rW  s       r:   rN   zModularPipeline.dtype  se     //((*%HAuxx)G1HH 	 F<<	  }} Is   )A3	A3c                     | j                   j                         D cg c]  }t        | |      st        | |      |  c}S c c}w )z]
        Returns:
            - List of names for components that needs to be loaded
        r   r=   rR   rv   r9   r   s     r:   null_component_namesz$ModularPipeline.null_component_names   s?     "&!6!6!;!;!=utATY`aegkYlYtuuus   AAAc                 H    t        | j                  j                               S )zI
        Returns:
            - List of names for all components
        )rS   r  r=   rI   s    r:   component_nameszModularPipeline.component_names(  s     DOO((*++r<   c                     | j                   j                         D cg c]   }| j                   |   j                  dk(  r|" c}S c c}w )zU
        Returns:
            - List of names for from_pretrained components
        r   r   r=   r#  rc  s     r:   pretrained_component_namesz*ModularPipeline.pretrained_component_names0  sM     --224
$$T*BBFWW 
 	
 
   %Ac                     | j                   j                         D cg c]   }| j                   |   j                  dk(  r|" c}S c c}w )zQ
        Returns:
            - List of names for from_config components
        r  rh  rc  s     r:   config_component_namesz&ModularPipeline.config_component_names<  sL     --224
$$T*BBmS 
 	
 
rj  c                     | j                   j                         D ci c]  }t        | |      s|t        | |       c}S c c}w )z
        Returns:
            - Dictionary mapping component names to their objects (include both from_pretrained and from_config
              components)
        rb  rc  s     r:   r  zModularPipeline.componentsH  s?     7;6K6K6P6P6RjdV]^bdhVigdD))jjjs
   AAr   c                 2    t        | j                  |         S )zh
        Returns:
            - a copy of the ComponentSpec object for the given component name
        )r   r   rc  s     r:   get_component_specz"ModularPipeline.get_component_specR  s    
 --d344r<   c           
      F   | j                   D ci c]-  }||v st        ||   t              s||j                  |      / }}| j                   D ci c]-  }||v st        ||   t              r||j                  |      / }}| j                  D ci c]  }||v s||j                  |       }}|j                         D ]  \  }}| j                   |   }|j                  \t        ||j                        sFt        j                  d| d|j                  j                   d|j                  j                          t        j                  ||      }	|	j                  |j                  k7  r3t        j                  d| d|j                   d|	j                   d       |	| j                   |<    t        |      d	kD  r&t        j                  d
|j                                 i }
|j                         D ]  \  }}|j                  dk(  rt        d      |j!                         |
|<   | j                   |   }|j                  bt        |
|   |j                        sIt        j                  d| d|
|   j                  j                   d|j                  j                          || j                   |<     | j"                  di ||
 i }|j                         D ]  \  }}|| j                  |   _        |||<      | j&                  di | yc c}w c c}w c c}w )ae  
        Update components and configuration values and specs after the pipeline has been instantiated.

        This method allows you to:
        1. Replace existing components with new ones (e.g., updating `self.unet` or `self.text_encoder`)
        2. Update configuration values (e.g., changing `self.requires_safety_checker` flag)

        In addition to updating the components and configuration values as pipeline attributes, the method also
        updates:
        - the corresponding specs in `_component_specs` and `_config_specs`
        - the `config` dict, which will be saved as `modular_model_index.json` during `save_pretrained`

        Args:
            **kwargs: Component objects, ComponentSpec objects, or configuration values to update:
                - Component objects: Only supports components we can extract specs using
                  `ComponentSpec.from_component()` method i.e. components created with ComponentSpec.load() or
                  ConfigMixin subclasses that aren't nn.Modules (e.g., `unet=new_unet, text_encoder=new_encoder`)
                - ComponentSpec objects: Only supports default_creation_method == "from_config", will call create()
                  method to create a new component (e.g., `guider=ComponentSpec(name="guider",
                  type_hint=ClassifierFreeGuidance, config={...}, default_creation_method="from_config")`)
                - Configuration values: Simple values to update configuration settings (e.g.,
                  `requires_safety_checker=False`)

        Raises:
            ValueError: If a component object is not supported in ComponentSpec.from_component() method:
                - nn.Module components without a valid `_diffusers_load_id` attribute
                - Non-ConfigMixin components without a valid `_diffusers_load_id` attribute

        Examples:
            ```python
            # Update multiple components at once
            pipeline.update_components(unet=new_unet_model, text_encoder=new_text_encoder)

            # Update configuration values
            pipeline.update_components(requires_safety_checker=False)

            # Update both components and configs together
            pipeline.update_components(unet=new_unet_model, requires_safety_checker=False)

            # Update with ComponentSpec objects (from_config only)
            pipeline.update_components(
                guider=ComponentSpec(
                    name="guider",
                    type_hint=ClassifierFreeGuidance,
                    config={"guidance_scale": 5.0},
                    default_creation_method="from_config",
                )
            )
            ```

        Notes:
            - Components with trained weights must be created using ComponentSpec.load(). If the component has not been
              shared in huggingface hub and you don't have loading specs, you can upload it using `push_to_hub()`
            - ConfigMixin objects without weights (e.g., schedulers, guiders) can be passed directly
            - ComponentSpec objects with default_creation_method="from_pretrained" are not supported in
              update_components()
        Nz*ModularPipeline.update_components: adding z with new type: z, previous type: zKModularPipeline.update_components: changing the default_creation_method of z from z to r   r   z/Unexpected keyword arguments, will be ignored: r   zuComponentSpec object with default_creation_method == 'from_pretrained' is not supported in update_components() methodr[   )r   rA   r   r   r!  rd   	type_hintrN  rO  r   ri   from_componentr#  rT   r=   r   r$  r%  r>   r   )r9   rs   r^   passed_component_specspassed_componentspassed_config_valuesr   r7  current_component_specnew_component_speccreated_componentsr,  config_to_register	new_values                 r:   update_componentsz!ModularPipeline.update_componentsY  s   z '+&;&;"
!"qF{zZ`abZcerOsAvzz!}"
 "
 '+&;&;
!"qF{S]^def^givSwAvzz!}
 
 ;?:L:L\QPQU[P[6::a= 0\\0668 	=OD)%)%:%:4%@" &//;J1;;E @FVW`WjWjWsWsVt  uF  G]  Gg  Gg  Gp  Gp  Fq  r "/!=!=dI!N!99=S=k=kkabfaggm  oE  o]  o]  n^  ^b  cu  cM  cM  bN  NO  P +=D!!$'#	=& v;?NNLV[[]O\]$:$@$@$B 	9 D.559JJ  L  (6'<'<'>t$%)%:%:4%@"%//;J"4(*@*J*JE @FVWijnWoWyWy  XC  XC  WD  DU  Vl  Vv  Vv  V  V  U@  A +9D!!$'	9  	!  K#4K8JK399; 	1OD)/8Dt$,'0t$	1 	 5"45m"

  ]s-   	LLL	LL/L	LLr4  c                    t        |t              r|g}n't        |t              st        dt	        |             |D ch c]  }|| j
                  v s| }}|D ch c]  }|| j
                  vs| }}t        |      dkD  rt        j                  d|        i }|D ]q  }| j
                  |   }i }|j                         D ]5  \  }	}
t        |
t              s|
||	<   ||
v r	|
|   ||	<   )d|
v s.|
d   ||	<   7 	  |j                  di |||<   s  | j                  di | yc c}w c c}w # t        $ r%}t        j                  d| d|        Y d}~d}~ww xY w)	aX  
        Load selected components from specs.

        Args:
            names: List of component names to load; by default will not load any components
            **kwargs: additional kwargs to be passed to `from_pretrained()`.Can be:
             - a single value to be applied to all components to be loaded, e.g. torch_dtype=torch.bfloat16
             - a dict, e.g. torch_dtype={"unet": torch.bfloat16, "default": torch.float32}
             - if potentially override ComponentSpec if passed a different loading field in kwargs, e.g. `repo`,
               `variant`, `revision`, etc.
        zInvalid type for names: r   z$Unknown components will be ignored: r>   zFailed to create component 'r  Nr[   )rA   rB   rS   r   r   r   rT   rN  rO  rd   rm   loadrQ  r%  )r9   r4  rs   r   components_to_loadunknown_namescomponents_to_registerr(  component_load_kwargsr4   r5   rV  s               r:   r5  zModularPipeline.load_components  s    eS!GEE4(7U}EFF/4Vt@U@U8UdVV*/U$4t?T?T3TUU}!NNA-QR!#& 	LD((.D$&!$lln 
F
U!%.16)#.u}5:4[-c2"e+5:95E-c2
FL/8tyy/Q;P/Q&t,	L( 	!  :#9:5 WU*  L!=dV3qcJKKLs0    D)D)D.2D.?D33	E!<EE!raise_errorr   c                     ddl m} || j                  j                         n|g}|D cg c])  }t	        |t
        j                  j                        s(|+ }}|D ]  } ||      s|rt        d       y yc c}w )Nr   )_is_group_offload_enabledzYou are trying to apply model/sequential CPU offloading to a pipeline that contains components with group offloading enabled. This is not supported. Please disable group offloading for components of the pipeline to use other offloading methods.TF)	hooks.group_offloadingr  r  r2   rA   r  rT  rU  r   )r9   r  r   r  r  r7  s         r:   *_maybe_raise_error_if_group_offload_activez:ModularPipeline._maybe_raise_error_if_group_offload_active  s     	G17T__++-fX
1;fIz)UZU]U]UdUd?eif
f# 	I(3$V 
 	  gs   )A9A9c                 &
   ddl m ddlmmm}m} |j                  dd      }|j                  dd      }|j                  dd      }d}d}	t        |      d	k(  rCt        |d
   t        j                        r|d
   }n|d
   t        j                  |d
         nd}	ntt        |      dk(  rMt        |d
   t        j                        rt        d      |d
   t        j                  |d
         nd}	|d	   }nt        |      dkD  rt        d      ||t        d      |xs |}||	t        d      |xs |	}|t        j                  |      j                  nd}
t        fd| j                   j#                         D              }fdfdt        fd| j                   j#                         D              }| j$                  duxr t        | j$                        d	kD  }|rt        d      |
dv r%|r|st        d      |r dd      rt        d      t        fd| j                   j#                         D              }|rD|
dv r@t&        j)                  ddj+                  | j                   j-                                d       |
dk(  r|j                  dd      r |       rd t.        j0                  d!<   t&        j3                  d"       d
dl}t7        t        d      rt        j8                  j;                         st        d#      d t.        j0                  d$<   t&        j3                  d%       | j                   j=                         }|D cg c])  }t        |t        j>                  j@                        s(|+ }}|xs |}|D ]n  } |      \  }}}| jC                  |&      }|s|r@|>t&        j)                  d'|jD                  jF                   d(|rd)nd* d+| d,|rd)nd* d-	       |r?|=t&        j)                  d'|jD                  jF                   d.| d/|j                   d0       | jC                  d|1      r2|0t&        j)                  d'|jD                  jF                   d2| d3       |r| |d4d5      r|jI                  |6       n|s|s|s|jI                  ||       |j                  t        jJ                  k(  sCtM        |      d7v sR|rV|rZt&        j)                  d8       q | S c c}w )9ug  
        Performs Pipeline dtype and/or device conversion. A torch.dtype and torch.device are inferred from the
        arguments of `self.to(*args, **kwargs).`

        <Tip>

            If the pipeline already has the correct torch.dtype and torch.device, then it is returned as is. Otherwise,
            the returned pipeline is a copy of self with the desired torch.dtype and torch.device.

        </Tip>


        Here are the ways to call `to`:

        - `to(dtype, silence_dtype_warnings=False) → DiffusionPipeline` to return a pipeline with the specified
          [`dtype`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.dtype)
        - `to(device, silence_dtype_warnings=False) → DiffusionPipeline` to return a pipeline with the specified
          [`device`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.device)
        - `to(device=None, dtype=None, silence_dtype_warnings=False) → DiffusionPipeline` to return a pipeline with the
          specified [`device`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.device) and
          [`dtype`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.dtype)

        Arguments:
            dtype (`torch.dtype`, *optional*):
                Returns a pipeline with the specified
                [`dtype`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.dtype)
            device (`torch.Device`, *optional*):
                Returns a pipeline with the specified
                [`device`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.device)
            silence_dtype_warnings (`str`, *optional*, defaults to `False`):
                Whether to omit warnings if the target `dtype` is not compatible with the target `device`.

        Returns:
            [`DiffusionPipeline`]: The pipeline converted to specified `dtype` and/or `dtype`.
        r   )_check_bnb_status)r   is_accelerate_versionis_hpu_availableis_transformers_versionrN   NrV  silence_dtype_warningsFr   r   zbWhen passing two arguments, make sure the first corresponds to `device` and the second to `dtype`.zPPlease make sure to pass at most two arguments (`device` and `dtype`) `.to(...)`zgYou have passed `dtype` both as an argument and as a keyword argument. Please only pass one of the two.zhYou have passed `device` both as an argument and as a keyword argument. Please only pass one of the two.c              3   F   K   | ]  \  }}t         |              y wrh   )any)r]   _r   r  s      r:   r_   z%ModularPipeline.to.<locals>.<genexpr>[  s      iIAvs$5f$=?is   !c                 f           r	 dd      ry |       \  }}}|ryt        | d      xr t        | j                  t        j                  j
                        xsS t        | j                  d      xr; t        | j                  j                  d   t        j                  j
                        S )N<z0.14.0Fr[  hooksr   )rR   rA   r[  
accelerater  AlignDevicesHook)r   r  is_loaded_in_8bit_bnbr  r   r  s      r:    module_is_sequentially_offloadedz<ModularPipeline.to.<locals>.module_is_sequentially_offloaded^  s    *,0Ec80T*;F*C'Aq'$6:. 6??J,<,<,M,MN \6??G4 \v44Q79I9I9Z9Z[r<   c                             r	 dd      ryt        | d      xr. t        | j                  t        j                  j
                        S )Nr  z0.17.0.dev0Fr[  )rR   rA   r[  r  r  
CpuOffload)r   r   r  s    r:   module_is_offloadedz/ModularPipeline.to.<locals>.module_is_offloadedm  s?    *,0Ec=0Y6:.k:foozO_O_OjOj3kkr<   c              3   4   K   | ]  \  }} |        y wrh   r[   )r]   r  r   r  s      r:   r_   z%ModularPipeline.to.<locals>.<genexpr>t  s       1
9BF,V41
   zIt seems like you have activated a device mapping strategy on the pipeline which doesn't allow explicit device placement using `to()`. You can call `reset_device_map()` to remove the existing device map from the pipeline.)cudaxpua7  It seems like you have activated sequential model offloading by calling `enable_sequential_cpu_offload`, but are now attempting to move the pipeline to GPU. This is not compatible with offloading. Please, move your pipeline `.to('cpu')` or consider removing the move altogether if you use sequential offloading.r  z
1.1.0.dev0zYou are trying to call `.to('cuda')` on a pipeline that has models quantized with `bitsandbytes`. Your current `accelerate` installation does not support it. Please upgrade the installation.c              3   4   K   | ]  \  }} |        y wrh   r[   )r]   r  r   r  s      r:   r_   z%ModularPipeline.to.<locals>.<genexpr>  s     #iIAv$7$?#ir  a5  It seems like you have activated model offloading by calling `enable_model_cpu_offload`, but are now manually moving the pipeline to GPU. It is strongly recommended against doing so as memory gains from offloading are likely to be lost. Offloading automatically takes care of moving the individual components r  z to GPU when needed. To make sure offloading works as expected, you should consider moving the pipeline back to CPU: `pipeline.to('cpu')` or removing the move altogether if you use offloading.hpuhpu_migrationT1PT_HPU_GPU_MIGRATIONz0Environment variable set: PT_HPU_GPU_MIGRATION=1zBYou are trying to call `.to('hpu')` but HPU device is unavailable.PT_HPU_MAX_COMPOUND_OP_SIZEz7Environment variable set: PT_HPU_MAX_COMPOUND_OP_SIZE=1)r   zThe module 'z$' has been loaded in `bitsandbytes` 4bit8bitz and conversion to z& is not supported. Module is still in z precision.z:' has been loaded in `bitsandbytes` 8bit and moving it to z2 via `.to()` is not supported. Module is still on r   )r  r   z&' is group offloaded and moving it to z via `.to()` is not supported.>z4.44.0)rV  )rS  a  Pipelines loaded with `dtype=torch.float16` cannot run with `cpu` device. It is not recommended to move them to `cpu` as running them will fail. Please make sure to use an accelerator to run the pipeline in inference, due to the lack of support for`float16` operations on this device in PyTorch. Please, remove the `torch_dtype=torch.float16` argument, or use another device for inference.)'pipelines.pipeline_utilsr  utilsr   r  r  r  r   rT   rA   r  rN   rV  r   r   r  r  rd   hf_device_maprN  rO  rc   r=   r  environrM  habana_frameworks.torchrR   r  is_availabler2   rT  rU  r  r   ri   tofloat16rB   )r9   argsrs   r  r  rN   rV  r  	dtype_arg
device_argdevice_typepipeline_has_bnb"pipeline_is_sequentially_offloadedis_pipeline_device_mappedpipeline_is_offloadedhabana_frameworksrX  rY  is_offloadedr   r  is_loaded_in_4bit_bnbr  is_group_offloadedr  r   r  r  r  s                           @@@@@r:   r  zModularPipeline.to  s   H 	Auu

7D)Hd+!',De!L	
t9>$q'5;;/ G	6:1g6IU\\$q'2t
Y!^$q'5;;/ x  37q'2Ed1g.4JQIY]opp!6y  "*"8z  %:393Eell6*//4iQUQ`Q`QfQfQhii		l .1 1
FJooF[F[F]1
 .
* %)$6$6d$B$bs4K]K]G^abGb!$ p  /)1:J  N  "&;C&N  U 
 !$#iQUQ`Q`QfQfQh#i i [O%CNN H  IM  IR  IR  SW  Sb  Sb  Sg  Sg  Si  Ij  Hk  kk  l
 %FJJ$EJZJ\14BJJ-.LLKL* E5)eii.D.D.F !eff8;BJJ45LLRS//((*%HAuxx)G1HH,R0R +	F>OPV>W;A$&;!%!P!PX^!P!_%)>EDU"6#3#3#<#<"==a  mBbh  HN  bO  Ob  ch  bi  iO  Zo  PV  u{  O|  |G  H %);"6#3#3#<#<"==wx~w  @r  sy  s@  s@  rA  AB  C ??EZ`?a&"6#3#3#<#<"==cdjck  lJ  K %);@WX[]e@f			(*3HQc		&%( -K7*.$bK+	X _ Is   ")TTr,  c                     | j                   dk7  ry| j                  t        | j                        \  }}nd}d}| j                         D ci c]  }|t	        | |       }}d||fi|S c c}w )uo  
        Convert a ComponentSpec into a JSON‐serializable dict for saving as an entry in `modular_model_index.json`. If
        the `default_creation_method` is not `from_pretrained`, return None.

        This dict contains:
          - "type_hint": Tuple[str, str]
              Library name and class name of the component. (e.g. ("diffusers", "UNet2DConditionModel"))
          - All loading fields defined by `component_spec.loading_fields()`, typically:
              - "repo": Optional[str]
                  The model repository (e.g., "stabilityai/stable-diffusion-xl").
              - "subfolder": Optional[str]
                  A subfolder within the repo where this component lives.
              - "variant": Optional[str]
                  An optional variant identifier for the model.
              - "revision": Optional[str]
                  A specific git revision (commit hash, tag, or branch).
              - ... any other loading fields defined on the spec.

        Args:
            component_spec (ComponentSpec):
                The spec object describing one pipeline component.

        Returns:
            Dict[str, Any]: A mapping suitable for JSON serialization.

        Example:
            >>> from diffusers.pipelines.modular_pipeline_utils import ComponentSpec >>> from diffusers import
            UNet2DConditionModel >>> spec = ComponentSpec(
                ... name="unet", ... type_hint=UNet2DConditionModel, ... config=None, ... repo="path/to/repo", ...
                subfolder="subfolder", ... variant=None, ... revision=None, ...
                default_creation_method="from_pretrained",
            ... ) >>> ModularPipeline._component_spec_to_dict(spec) {
                "type_hint": ("diffusers", "UNet2DConditionModel"), "repo": "path/to/repo", "subfolder": "subfolder",
                "variant": None, "revision": None,
            }
        r   Nrq  )r#  rq  r   loading_fieldsrv   )r,  lib_namer   r^   load_spec_dicts        r:   rK  z'ModularPipeline._component_spec_to_dict  s    L 115FF##/!;N<T<T!UHhHHAOA^A^A`aA!W^Q77aa(H-

 	
 bs   A*	spec_dictc                     |j                         }|j                  d      \  }}||t        ||      }nd}t        d| |d|S )a  
        Reconstruct a ComponentSpec from a loading specdict.

        This method converts a dictionary representation back into a ComponentSpec object. The dict should contain:
          - "type_hint": Tuple[str, str]
              Library name and class name of the component. (e.g. ("diffusers", "UNet2DConditionModel"))
          - All loading fields defined by `component_spec.loading_fields()`, typically:
              - "repo": Optional[str]
                  The model repository (e.g., "stabilityai/stable-diffusion-xl").
              - "subfolder": Optional[str]
                  A subfolder within the repo where this component lives.
              - "variant": Optional[str]
                  An optional variant identifier for the model.
              - "revision": Optional[str]
                  A specific git revision (commit hash, tag, or branch).
              - ... any other loading fields defined on the spec.

        Args:
            name (str):
                The name of the component.
            specdict (Dict[str, Any]):
                A dictionary containing the component specification data.

        Returns:
            ComponentSpec: A reconstructed ComponentSpec object.

        Example:
            >>> spec_dict = { ... "type_hint": ("diffusers", "UNet2DConditionModel"), ... "repo":
            "stabilityai/stable-diffusion-xl", ... "subfolder": "unet", ... "variant": None, ... "revision": None, ...
            } >>> ModularPipeline._dict_to_component_spec("unet", spec_dict) ComponentSpec(
                name="unet", type_hint=UNet2DConditionModel, config=None, repo="stabilityai/stable-diffusion-xl",
                subfolder="unet", variant=None, revision=None, default_creation_method="from_pretrained"
            )
        rq  N)r   rq  r[   )copyr   r   r   )r   r  r  r   rq  s        r:   r"  z'ModularPipeline._dict_to_component_spec	  sd    P NN$	&]];7(H$8,Xx@II  

 
 	
r<   c                     | j                   j                  j                         D ]$  \  }}t        |d      s |j                  di | & y )Nr  r[   )r   r   rd   rR   r  )r9   rs   r  r  s       r:   r  z'ModularPipeline.set_progress_bar_config;	  sG    )-)?)?)E)E)G 	<%NIy";<1	11;F;	<r<   r   r  c                 x   |
t               }|j                         }| j                  j                  D ]o  }|j                  }|j
                  }|j                  }||v r#|j                  ||j                  |      |       N||j                  vs]|j                  |||       q t        |      dkD  r't        j                  d|j                          d       t        j                         5  	 | j                  | |      \  }	}	 ddd       ||S t+        |t,              r|j/                  |      S t+        |t0        t2        f      r|j/                  |      S t5        d| d      # t         $ r; d| j                  j"                  j$                   d}
t&        j)                  |
        w xY w# 1 sw Y   xY w)	a  
        Execute the pipeline by running the pipeline blocks with the given inputs.

        Args:
            state (`PipelineState`, optional):
                PipelineState instance contains inputs and intermediate values. If None, a new `PipelineState` will be
                created based on the user inputs and the pipeline blocks's requirement.
            output (`str` or `List[str]`, optional):
                Optional specification of what to return:
                   - None: Returns the complete `PipelineState` with all inputs and intermediates (default)
                   - str: Returns a specific intermediate value from the state (e.g. `output="image"`)
                   - List[str]: Returns a dictionary of specific intermediate values (e.g. `output=["image",
                     "latents"]`)


        Examples:
            ```python
            # Get complete pipeline state
            state = pipeline(prompt="A beautiful sunset", num_inference_steps=20)
            print(state.intermediates)  # All intermediate outputs

            # Get specific output
            image = pipeline(prompt="A beautiful sunset", output="image")

            # Get multiple specific outputs
            results = pipeline(prompt="A beautiful sunset", output=["image", "latents"])
            image, latents = results["image"], results["latents"]

            # Continue from previous state
            state = pipeline(prompt="A beautiful sunset")
            new_state = pipeline(state=state, output="image")  # Continue processing
            ```

        Returns:
            - If `output` is None: Complete `PipelineState` containing all inputs and intermediates
            - If `output` is str: The specific intermediate value from the state (e.g. `output="image"`)
            - If `output` is List[str]: Dictionary mapping output names to their values from the state (e.g.
              `output=["image", "latents"]`)
        Nr   zUnexpected input 'z'' provided. This input will be ignored.zError in block: (z):
zOutput 'z' is not a valid output type)r0   r  r   r   r   r>   r6   r;   r   r2   rT   r  r  r=   r  r  rQ  r   ri   rN  rT  rA   rB   rC   rS   r~   r   )r9   r   r  rs   passed_kwargsexpected_input_paramr   r>   r6   r  rW  s              r:   rX  zModularPipeline.__call__@	  s   P =!OE  %)KK$6$6 	6 ',,D*22G.::K}$		$ 1 1$ 7EU\\)		$5	6 }!MM.}/A/A/C.DDklm]]_ 	;;tU35	 >Lfc"99V$$u.99V$$xx/KLMM  /0E0E0N0N/OtT	Y'	 	s   .F00E))AF--F00F9)NNNNr  r  )FNr  )3ri   rj   rk   rl   r  r  r
   r   r   rB   r  r   r   rt   r  r   r   r2  r6  r  r   r  r   r   r  r%  r  rV  r^  rN   r	   rd  rf  ri  rl  r  r   ro  r{  r5  rT  rU  r  r   r  r!  rK  r"  r  r0   rX  r[   r<   r:   r   r     s@    -KM
 37KO:>$(dx./dx (0c2;;6F0G'Hdx %%67	dx
 SMdxL c3h  4  -1:>$(?'/c2;;6F0G'H? $D>? %%67	?
 SM?  ?B"eC4D.E "TX "H  fMP # # #  * u{{   vd3i v v ,c , , 	
DI 	
 	
 	
S	 	
 	
 kDcN k k5s 5} 5r6l,;U49c>%: ,;` NR19%((//1J	&}T }~ 1
 1
# 1
 1
f 4
4
S>4
 
4
 4
l<
NNm NNE#tCy.<Q NNr<   r   )Dr   r   r  rR  r  collectionsr   r  r   dataclassesr   r   typingr   r   r	   r
   r   r   r  huggingface_hubr   huggingface_hub.utilsr   	tqdm.autor   typing_extensionsr   configuration_utilsr   r   r9  r   r   r  r   r   r   utils.dynamic_modules_utilsr   r   utils.hub_utilsr   r   r   r   modular_pipeline_utilsr   r    r!   r"   r#   r$   r%   r&   r  
get_loggerri   rN  r   r  r0   rp   r   r#  r  r  r   r[   r<   r:   <module>r     s)     	   #  ( : :  ' 6  " 9 _ D D b L 1	 	 	 			H	% '  #.#  Gw Gw GwT D/ D/ D/Nh
K h
V	
. 
D[
4 [
|
Y+#8 Y+@	INk> INr<   