


'''simple docstring'''
import argparse
import json
import os
import re
from collections import OrderedDict
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
from pprint import pprint
from typing import Dict, List, Tuple

import torch
import torch.nn as nn
from classy_vision.models.regnet import RegNet, RegNetParams
from huggingface_hub import cached_download, hf_hub_url
from torch import Tensor
from vissl.models.model_helpers import get_trunk_forward_outputs

from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel
from transformers.modeling_utils import PreTrainedModel
from transformers.utils import logging


logging.set_verbosity_info()
lowerCAmelCase__  =     logging.get_logger()







@dataclass
class 					_A						:



   '''simple docstring'''






   _lowercase    						= 42
   _lowercase    						= field(default_factory=UpperCAmelCase__							)
   _lowercase    						= field(default_factory=UpperCAmelCase__							)
   _lowercase    						= field(default_factory=UpperCAmelCase__							)




   def   __lowerCAmelCase						(	self	:					Dict					, lowerCamelCase	:					str					, lowerCamelCase	:					List[Any]					, lowerCamelCase	:					List[Any]					, lowerCamelCase	:					List[str]						)->	Tuple:
          snake_case__					:	List[str]          =					len(list(m.modules()						)						) == 1 or isinstance(__lowercase					, nn.Convad						) or isinstance(__lowercase					, nn.BatchNormad						)
          if has_not_submodules:
                 self.traced.append(__lowercase						)
                 snake_case__					:	Optional[int]          =					m




   def __call__(	self	:					Optional[int]					, lowerCamelCase	:					Optional[Any]						)->	Tuple:
          for name, m in self.module.named_modules():
                 self.handles.append(m.register_forward_hook(partial(self._forward_hook					, name=__lowercase						)						)						)
          self.module(__lowercase						)
          [x.remove() for x in self.handles]
          return self




   @property
   def   __lowerCAmelCase						(	self	:					Any						)->	str:
          # check the len of the state_dict keys to see if we have learnable params
          return {k: v for k, v in self.nameamodule.items() if len(list(v.state_dict().keys()						)						) > 0}







class 					_A						(						nn.Module							):



   '''simple docstring'''






   def __init__(	self	:					int					, lowerCamelCase	:					Optional[int]						)->	List[Any]:
          super().__init__()

          snake_case__					:	List[Tuple[str, nn.Module]]          =					[]
          # - get the stem
          feature_blocks.append(("""conv1""", model.stem)						)
          # - get all the feature blocks
          for k, v in model.trunk_output.named_children():
                 assert k.startswith("""block"""						), F"""Unexpected layer name {k}"""
                 snake_case__					:	List[str]          =					len(__lowercase						) + 1
                 feature_blocks.append((F"""res{block_index}""", v)						)

          snake_case__					:	Any          =					nn.ModuleDict(__lowercase						)




   def   __lowerCAmelCase						(	self	:					Tuple					, lowerCamelCase	:					Dict						)->	Optional[int]:
          return get_trunk_forward_outputs(
              __lowercase					, out_feat_keys=__lowercase					, feature_blocks=self._feature_blocks					, )







class 					_A						(						UpperCAmelCase__							):



   '''simple docstring'''






   def   __lowerCAmelCase						(	self	:					Dict						)->	Optional[Any]:
          return [(8, 2, 2, 8, 1.0), (8, 2, 7, 8, 1.0), (8, 2, 17, 8, 1.0), (8, 2, 1, 8, 1.0)]







def 				lowerCAmelCase__	(       UpperCAmelCase     ):






       """simple docstring"""





       snake_case__					:	Optional[int]          =					RegNetConfig(depths=[2, 7, 17, 1]    ,       hidden_sizes=[8, 8, 8, 8]    ,       groups_width=8     )
       if "in1k" in model_name:
              snake_case__					:	int          =					RegNetForImageClassification(lowerCAmelCase_     )
       else:
              snake_case__					:	Optional[Any]          =					RegNetModel(lowerCAmelCase_     )
       # create from model (with small weights)
       snake_case__					:	Tuple          =					FakeRegNetVisslWrapper(
           RegNet(FakeRegNetParams(depth=27    ,       group_width=1010    ,       w_a=1744    ,       w_a=6_2_0.8_3    ,       w_m=2.5_2     )     )     )

       with torch.no_grad():
              snake_case__					:	Union[str, Any]          =					from_model.eval()
              snake_case__					:	int          =					our_model.eval()

              snake_case__					:	Optional[int]          =					torch.randn((1, 3, 32, 32)     )
              # trace both
              snake_case__					:	str          =					Tracker(lowerCAmelCase_     )
              snake_case__					:	Union[str, Any]          =					dest_tracker(lowerCAmelCase_     ).parametrized

              pprint(dest_tracker.nameamodule     )
              snake_case__					:	str          =					Tracker(lowerCAmelCase_     )
              snake_case__					:	List[Any]          =					src_tracker(lowerCAmelCase_     ).parametrized

       # convert the keys -> module dict to keys -> params
       def to_params_dict(UpperCAmelCase     ):
              snake_case__					:	Tuple          =					OrderedDict()
              for name, module in dict_with_modules.items():
                     for param_name, param in module.state_dict().items():
                            snake_case__					:	Union[str, Any]          =					param
              return params_dict

       snake_case__					:	Any          =					{}

       snake_case__					:	str          =					to_params_dict(lowerCAmelCase_     )
       snake_case__					:	str          =					to_params_dict(lowerCAmelCase_     )

       for (src_key, src_param), (dest_key, dest_param) in zip(src_state_dict.items()    ,       dst_state_dict.items()     ):
              snake_case__					:	str          =					dest_key
              logger.info(f"""{src_key} -> {dest_key}"""     )
       # if "in1k" was in the model_name it means it must have a classification head (was finetuned)
       if "in1k" in model_name:
              snake_case__					:	Optional[int]          =					'''classifier.1.weight'''
              snake_case__					:	Tuple          =					'''classifier.1.bias'''

       return from_to_ours_keys



def 				lowerCAmelCase__	(       UpperCAmelCase    ,       UpperCAmelCase = None    ,       UpperCAmelCase = True     ):






       """simple docstring"""





       snake_case__					:	Optional[Any]          =					'''imagenet-1k-id2label.json'''
       snake_case__					:	List[Any]          =					1000

       snake_case__					:	List[Any]          =					'''huggingface/label-files'''
       snake_case__					:	Optional[Any]          =					num_labels
       snake_case__					:	Tuple          =					json.load(open(cached_download(hf_hub_url(lowerCAmelCase_    ,       lowerCAmelCase_    ,       repo_type="""dataset"""     )     )    ,       """r"""     )     )
       snake_case__					:	Union[str, Any]          =					{int(lowerCAmelCase_     ): v for k, v in idalabel.items()}

       snake_case__					:	List[str]          =					idalabel
       snake_case__					:	List[Any]          =					{v: k for k, v in idalabel.items()}

       snake_case__					:	Optional[Any]          =					partial(lowerCAmelCase_    ,       num_labels=lowerCAmelCase_    ,       idalabel=lowerCAmelCase_    ,       labelaid=lowerCAmelCase_     )

       snake_case__					:	Optional[int]          =					{
           '''regnet-y-10b-seer''': ImageNetPreTrainedConfig(
               depths=[2, 7, 17, 1]    ,       hidden_sizes=[2020, 4040, 1_1110, 2_8280]    ,       groups_width=1010     ),
           # finetuned on imagenet
           '''regnet-y-10b-seer-in1k''': ImageNetPreTrainedConfig(
               depths=[2, 7, 17, 1]    ,       hidden_sizes=[2020, 4040, 1_1110, 2_8280]    ,       groups_width=1010     ),
       }

       # add seer weights logic
       def load_using_classy_vision(UpperCAmelCase     ) -> Tuple[Dict, Dict]:
              snake_case__					:	Tuple          =					torch.hub.load_state_dict_from_url(lowerCAmelCase_    ,       model_dir=str(lowerCAmelCase_     )    ,       map_location="""cpu"""     )
              # check if we have a head, if yes add it
              snake_case__					:	Optional[Any]          =					files['''classy_state_dict''']['''base_model''']['''model''']
              return model_state_dict["trunk"], model_state_dict["heads"]

       snake_case__					:	Any          =					{
           '''regnet-y-10b-seer''': partial(
               lowerCAmelCase_    ,       """https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch"""    ,       ),
           '''regnet-y-10b-seer-in1k''': partial(
               lowerCAmelCase_    ,       """https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch"""    ,       ),
       }

       snake_case__					:	Any          =					get_from_to_our_keys(lowerCAmelCase_     )

       if not (save_directory / f"""{model_name}.pth""").exists():
              logger.info("""Loading original state_dict."""     )
              snake_case__					:	List[str]          =					names_to_from_model[model_name]()
              snake_case__					:	Dict          =					from_state_dict_trunk
              if "in1k" in model_name:
                     # add the head
                     snake_case__					:	Optional[int]          =					{**from_state_dict_trunk, **from_state_dict_head}
              logger.info("""Done!"""     )

              snake_case__					:	Optional[int]          =					{}

              snake_case__					:	Optional[int]          =					list(from_state_dict.keys()     )
              snake_case__					:	int          =					r'''\.block.-part.'''
              # this is "interesting", so the original checkpoints have `block[0,1]-part` in each key name, we remove it
              for key in from_state_dict.keys():
                     # remove the weird "block[0,1]-part" from the key
                     snake_case__					:	Optional[int]          =					re.sub(lowerCAmelCase_    ,       """"""    ,       lowerCAmelCase_     )
                     # now src_key from the model checkpoints is the one we got from the original model after tracing, so use it to get the correct destination key
                     snake_case__					:	List[str]          =					from_to_ours_keys[src_key]
                     # store the parameter with our key
                     snake_case__					:	List[str]          =					from_state_dict[key]
                     not_used_keys.remove(lowerCAmelCase_     )
              # check that all keys have been updated
              assert len(lowerCAmelCase_     ) == 0, f"""Some keys where not used {",".join(lowerCAmelCase_     )}"""

              logger.info(f"""The following keys were not used: {",".join(lowerCAmelCase_     )}"""     )

              # save our state dict to disk
              torch.save(lowerCAmelCase_    ,       save_directory / f"""{model_name}.pth"""     )

              del converted_state_dict
       else:
              logger.info("""The state_dict was already stored on disk."""     )
       if push_to_hub:
              logger.info(f"""Token is {os.environ["HF_TOKEN"]}"""     )
              logger.info("""Loading our model."""     )
              # create our model
              snake_case__					:	Union[str, Any]          =					names_to_config[model_name]
              snake_case__					:	Optional[Any]          =					RegNetModel
              if "in1k" in model_name:
                     snake_case__					:	int          =					RegNetForImageClassification
              snake_case__					:	List[str]          =					our_model_func(lowerCAmelCase_     )
              # place our model to the meta device (so remove all the weights)
              our_model.to(torch.device("""meta"""     )     )
              logger.info("""Loading state_dict in our model."""     )
              # load state dict
              snake_case__					:	Optional[int]          =					our_model.state_dict().keys()
              PreTrainedModel._load_pretrained_model_low_mem(
                  lowerCAmelCase_    ,       lowerCAmelCase_    ,       [save_directory / f"""{model_name}.pth"""]     )
              logger.info("""Finally, pushing!"""     )
              # push it to hub
              our_model.push_to_hub(
                  repo_path_or_name=save_directory / model_name    ,       commit_message="""Add model"""    ,       output_dir=save_directory / model_name    ,       )
              snake_case__					:	Union[str, Any]          =					384
              # we can use the convnext one
              snake_case__					:	str          =					AutoImageProcessor.from_pretrained("""facebook/convnext-base-224-22k-1k"""    ,       size=lowerCAmelCase_     )
              image_processor.push_to_hub(
                  repo_path_or_name=save_directory / model_name    ,       commit_message="""Add image processor"""    ,       output_dir=save_directory / model_name    ,       )


if __name__ == "__main__":
     lowerCAmelCase__  =     argparse.ArgumentParser()
     # Required parameters
     parser.add_argument(
         '--model_name',
         default=None,
         type=str,
         help=(
             'The name of the model you wish to convert, it must be one of the supported regnet* architecture,'
             ' currently: regnetx-*, regnety-*. If `None`, all of them will the converted.'
         ),
     )
     parser.add_argument(
         '--pytorch_dump_folder_path',
         default=None,
         type=Path,
         required=True,
         help='Path to the output PyTorch model directory.',
     )
     parser.add_argument(
         '--push_to_hub',
         default=True,
         type=bool,
         required=False,
         help='If True, push model and image processor to the hub.',
     )

     lowerCAmelCase__  =     parser.parse_args()

     lowerCAmelCase__  =     args.pytorch_dump_folder_path
     pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True)
     convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)








import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()







class 					snake_case__(				UpperCAmelCase__,    UpperCAmelCase__,    unittest.TestCase				):







						'''simple docstring'''




						SCREAMING_SNAKE_CASE__   :	str       =				StableDiffusionXLPipeline
						SCREAMING_SNAKE_CASE__   :	Dict       =				TEXT_TO_IMAGE_PARAMS
						SCREAMING_SNAKE_CASE__   :	Optional[int]       =				TEXT_TO_IMAGE_BATCH_PARAMS
						SCREAMING_SNAKE_CASE__   :	Optional[Any]       =				TEXT_TO_IMAGE_IMAGE_PARAMS
						SCREAMING_SNAKE_CASE__   :	int       =				TEXT_TO_IMAGE_IMAGE_PARAMS




						def     lowercase_			(					self				)       ->     int:
										torch.manual_seed(0				)
										lowerCAmelCase_			:   Tuple     					=					UNetaDConditionModel(
										    block_out_channels=(3_2, 6_4) ,    layers_per_block=2 ,    sample_size=3_2 ,    in_channels=4 ,    out_channels=4 ,    down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') ,    up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') ,    attention_head_dim=(2, 4) ,    use_linear_projection=__lowercase ,    addition_embed_type='''text_time''' ,    addition_time_embed_dim=8 ,    transformer_layers_per_block=(1, 2) ,    projection_class_embeddings_input_dim=8_0 ,    cross_attention_dim=6_4 ,    )
										lowerCAmelCase_			:   Any     					=					EulerDiscreteScheduler(
										    beta_start=0.0_00_85 ,    beta_end=0.0_12 ,    steps_offset=1 ,    beta_schedule='''scaled_linear''' ,    timestep_spacing='''leading''' ,    )
										torch.manual_seed(0				)
										lowerCAmelCase_			:   Any     					=					AutoencoderKL(
										    block_out_channels=[3_2, 6_4] ,    in_channels=3 ,    out_channels=3 ,    down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] ,    up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] ,    latent_channels=4 ,    sample_size=1_2_8 ,    )
										torch.manual_seed(0				)
										lowerCAmelCase_			:   Dict     					=					CLIPTextConfig(
										    bos_token_id=0 ,    eos_token_id=2 ,    hidden_size=3_2 ,    intermediate_size=3_7 ,    layer_norm_eps=1e-05 ,    num_attention_heads=4 ,    num_hidden_layers=5 ,    pad_token_id=1 ,    vocab_size=1_0_0_0 ,    hidden_act='''gelu''' ,    projection_dim=3_2 ,    )
										lowerCAmelCase_			:   str     					=					CLIPTextModel(__lowercase				)
										lowerCAmelCase_			:   List[str]     					=					CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ,    local_files_only=__lowercase				)

										lowerCAmelCase_			:   Tuple     					=					CLIPTextModelWithProjection(__lowercase				)
										lowerCAmelCase_			:   Optional[Any]     					=					CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ,    local_files_only=__lowercase				)

										lowerCAmelCase_			:   int     					=					{
										    '''unet''': unet,
										    '''scheduler''': scheduler,
										    '''vae''': vae,
										    '''text_encoder''': text_encoder,
										    '''tokenizer''': tokenizer,
										    '''text_encoder_2''': text_encoder_a,
										    '''tokenizer_2''': tokenizer_a,
										    # "safety_checker": None,
										    # "feature_extractor": None,
										}
										return components




						def     lowercase_			(					self ,    __lowercase ,    __lowercase=0				)       ->     Dict:
										if str(__lowercase				).startswith('''mps'''				):
														lowerCAmelCase_			:   Dict     					=					torch.manual_seed(__lowercase				)
										else:
														lowerCAmelCase_			:   Dict     					=					torch.Generator(device=__lowercase				).manual_seed(__lowercase				)
										lowerCAmelCase_			:   Dict     					=					{
										    '''prompt''': '''A painting of a squirrel eating a burger''',
										    '''generator''': generator,
										    '''num_inference_steps''': 2,
										    '''guidance_scale''': 5.0,
										    '''output_type''': '''numpy''',
										}
										return inputs




						def     lowercase_			(					self				)       ->     Optional[Any]:
										lowerCAmelCase_			:   Union[str, Any]     					=					'''cpu'''  # ensure determinism for the device-dependent torch.Generator
										lowerCAmelCase_			:   Any     					=					self.get_dummy_components()
										lowerCAmelCase_			:   Optional[int]     					=					StableDiffusionXLPipeline(**__lowercase				)
										lowerCAmelCase_			:   Optional[int]     					=					sd_pipe.to(__lowercase				)
										sd_pipe.set_progress_bar_config(disable=__lowercase				)

										lowerCAmelCase_			:   Dict     					=					self.get_dummy_inputs(__lowercase				)
										lowerCAmelCase_			:   str     					=					sd_pipe(**__lowercase				).images
										lowerCAmelCase_			:   Any     					=					image[0, -3:, -3:, -1]

										assert image.shape == (1, 6_4, 6_4, 3)
										lowerCAmelCase_			:   str     					=					np.array([0.58_73, 0.61_28, 0.47_97, 0.51_22, 0.56_74, 0.46_39, 0.52_27, 0.51_49, 0.47_47]				)

										assert np.abs(image_slice.flatten() - expected_slice				).max() < 1e-2




						def     lowercase_			(					self				)       ->     List[Any]:
										lowerCAmelCase_			:   Any     					=					self.get_dummy_components()
										lowerCAmelCase_			:   List[Any]     					=					StableDiffusionXLPipeline(**__lowercase				)
										lowerCAmelCase_			:   List[Any]     					=					sd_pipe.to(__lowercase				)
										lowerCAmelCase_			:   int     					=					sd_pipe.to(__lowercase				)
										sd_pipe.set_progress_bar_config(disable=__lowercase				)

										# forward without prompt embeds
										lowerCAmelCase_			:   Optional[Any]     					=					self.get_dummy_inputs(__lowercase				)
										lowerCAmelCase_			:   List[str]     					=					3 * ['''this is a negative prompt''']
										lowerCAmelCase_			:   Union[str, Any]     					=					negative_prompt
										lowerCAmelCase_			:   Union[str, Any]     					=					3 * [inputs['''prompt''']]

										lowerCAmelCase_			:   str     					=					sd_pipe(**__lowercase				)
										lowerCAmelCase_			:   Any     					=					output.images[0, -3:, -3:, -1]

										# forward with prompt embeds
										lowerCAmelCase_			:   Tuple     					=					self.get_dummy_inputs(__lowercase				)
										lowerCAmelCase_			:   Dict     					=					3 * ['''this is a negative prompt''']
										lowerCAmelCase_			:   Dict     					=					3 * [inputs.pop('''prompt'''				)]

										(
										    (
										    lowerCAmelCase_
										)					,	(
										    lowerCAmelCase_
										)					,	(
										    lowerCAmelCase_
										)					,	(
										    lowerCAmelCase_
										)					,	
										)			:   str     					=					sd_pipe.encode_prompt(__lowercase ,    negative_prompt=__lowercase				)

										lowerCAmelCase_			:   List[Any]     					=					sd_pipe(
										    **__lowercase ,    prompt_embeds=__lowercase ,    negative_prompt_embeds=__lowercase ,    pooled_prompt_embeds=__lowercase ,    negative_pooled_prompt_embeds=__lowercase ,    )
										lowerCAmelCase_			:   int     					=					output.images[0, -3:, -3:, -1]

										# make sure that it's equal
										assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()				).max() < 1e-4




						def     lowercase_			(					self				)       ->     List[str]:
										super().test_attention_slicing_forward_pass(expected_max_diff=3e-3				)




						def     lowercase_			(					self				)       ->     Tuple:
										super().test_inference_batch_single_identical(expected_max_diff=3e-3				)







@slow
@require_torch_gpu
class 					snake_case__(				unittest.TestCase				):







						'''simple docstring'''




						def     lowercase_			(					self				)       ->     int:
										super().tearDown()
										gc.collect()
										torch.cuda.empty_cache()




						def     lowercase_			(					self ,    __lowercase ,    __lowercase="cpu" ,    __lowercase=torch.floataa ,    __lowercase=0				)       ->     Dict:
										lowerCAmelCase_			:   Any     					=					torch.Generator(device=__lowercase				).manual_seed(__lowercase				)
										lowerCAmelCase_			:   str     					=					np.random.RandomState(__lowercase				).standard_normal((1, 4, 6_4, 6_4)				)
										lowerCAmelCase_			:   List[str]     					=					torch.from_numpy(__lowercase				).to(device=__lowercase ,    dtype=__lowercase				)
										lowerCAmelCase_			:   Optional[Any]     					=					{
										    '''prompt''': '''a photograph of an astronaut riding a horse''',
										    '''latents''': latents,
										    '''generator''': generator,
										    '''num_inference_steps''': 3,
										    '''guidance_scale''': 7.5,
										    '''output_type''': '''numpy''',
										}
										return inputs




						def     lowercase_			(					self				)       ->     List[str]:
										lowerCAmelCase_			:   Optional[int]     					=					DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base'''				)
										pipe.to(__lowercase				)
										pipe.set_progress_bar_config(disable=__lowercase				)

										lowerCAmelCase_			:   Any     					=					self.get_inputs(__lowercase				)
										lowerCAmelCase_			:   List[str]     					=					pipe(**__lowercase				).images
										lowerCAmelCase_			:   Dict     					=					image[0, -3:, -3:, -1].flatten()

										assert image.shape == (1, 5_1_2, 5_1_2, 3)
										lowerCAmelCase_			:   Optional[int]     					=					np.array([0.4_94_93, 0.4_78_96, 0.4_07_98, 0.5_42_14, 0.5_32_12, 0.4_82_02, 0.4_76_56, 0.4_63_29, 0.4_85_06]				)
										assert np.abs(image_slice - expected_slice				).max() < 7e-3