o
    Gi                     @   s   d dl Z d dlZd dlmZ d dlmZ dddddd	d
dddddddddZddddZdd Zdd Z	e
dkr]e jddZejded d!d" ejd#ed d$d" e Ze	ejej dS dS )%    N)	load_file)Kandinsky3UNetztime_embedding.linear_1ztime_embedding.linear_2conv_inconv_norm_outconv_outdown_blocks	up_blocksz"encoder_hid_proj.projection_linearz encoder_hid_proj.projection_normadd_time_conditionto_qto_kto_vzto_out.0zattentions.0)zto_time_embed.1zto_time_embed.3in_layerzout_layer.0zout_layer.2down_samples
up_samplesprojection_linprojection_lnfeature_poolingto_queryto_keyto_valueoutput_layerself_attention_blockzresnets_in.*)zattentions.*   zresnets_out.*)zresnet_attn_blocks.*.0zresnet_attn_blocks.*.1zresnet_attn_blocks.*.2c                 C   s   i }| D ]m}|}t  D ]
\}}|||}qt D ]O\}}d}t|d| drj|sjt||dd d dd }	t|trP|	|d  }
|d }n|	}
|dt	|	}|dt	|
}|||}d	}q| | ||< q|S )
aR  
    Args:
    Convert the state dict of a U-Net model to match the key format expected by Kandinsky3UNet model.
        unet_model (torch.nn.Module): The original U-Net model. unet_kandi3_model (torch.nn.Module): The Kandinsky3UNet
        model to match keys with.

    Returns:
        OrderedDict: The converted state dictionary.
    Fz*.z.*.r   r   *T)
MAPPINGitemsreplaceDYNAMIC_MAPfnmatchintsplit
isinstancetuplestr)unet_state_dictconverted_state_dictkeynew_keypatternnew_patterndyn_patterndyn_new_patternhas_matchedstarnew_star r1   j/home/ubuntu/.local/lib/python3.10/site-packages/diffusers/pipelines/kandinsky3/convert_kandinsky3_unet.pyconvert_state_dict$   s(   &

r3   c                 C   sB   t | }i }t|}t|}|| || td|  d S )NzConverted model saved to )r   r3   r   load_state_dictsave_pretrainedprint)
model_pathoutput_pathr&   configr'   unetr1   r1   r2   mainK   s   

r;   __main__z4Convert U-Net PyTorch model to Kandinsky3UNet format)descriptionz--model_pathTz(Path to the original U-Net PyTorch model)typerequiredhelpz--output_pathz Path to save the converted model)argparser    safetensors.torchr   	diffusersr   r   r   r3   r;   __name__ArgumentParserparseradd_argumentr%   
parse_argsargsr7   r8   r1   r1   r1   r2   <module>   sB   '