





"""simple docstring"""


import unittest

from transformers.testing_utils import is_torch_available, require_torch, tooslow

from ...generation.test_utils import torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
   import torch

   from transformers import (
       CpmAntConfig,
       CpmAntForCausalLM,
       CpmAntModel,
       CpmAntTokenizer,
   )



@require_torch
class    lowercase_ :

       def __init__(	self      ,    __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE=2      ,    __SCREAMING_SNAKE_CASE=8      ,    __SCREAMING_SNAKE_CASE=True      ,    __SCREAMING_SNAKE_CASE=False      ,    __SCREAMING_SNAKE_CASE=False      ,    __SCREAMING_SNAKE_CASE=False      ,    __SCREAMING_SNAKE_CASE=False      ,    __SCREAMING_SNAKE_CASE=99      ,    __SCREAMING_SNAKE_CASE=32      ,    __SCREAMING_SNAKE_CASE=3      ,    __SCREAMING_SNAKE_CASE=4      ,    __SCREAMING_SNAKE_CASE=37      ,    __SCREAMING_SNAKE_CASE=32      ,    __SCREAMING_SNAKE_CASE=128      ,    __SCREAMING_SNAKE_CASE=8      ,    __SCREAMING_SNAKE_CASE=8      ,    __SCREAMING_SNAKE_CASE=8      ,    __SCREAMING_SNAKE_CASE=1.0      ,    __SCREAMING_SNAKE_CASE=True      ,    ):






        '''simple docstring'''

        snake_case__										= parent
        snake_case__										= batch_size
        snake_case__										= seq_length
        snake_case__										= is_training
        snake_case__										= use_token_type_ids
        snake_case__										= use_input_mask
        snake_case__										= use_labels
        snake_case__										= use_mc_token_ids
        snake_case__										= vocab_size
        snake_case__										= hidden_size
        snake_case__										= num_hidden_layers
        snake_case__										= num_attention_heads
        snake_case__										= intermediate_size
        snake_case__										= num_buckets
        snake_case__										= max_distance
        snake_case__										= prompt_length
        snake_case__										= prompt_types
        snake_case__										= segment_types
        snake_case__										= init_std
        snake_case__										= return_dict

       def 						_SCREAMING_SNAKE_CASE(	self   ):






        '''simple docstring'''

        snake_case__										= {}
        snake_case__										= ids_tensor([self.batch_size, self.seq_length]      ,    self.vocab_size   ).type(torch.intaa   )
        snake_case__										= False

        snake_case__										= self.get_config()

        return (config, input_ids)

       def 						_SCREAMING_SNAKE_CASE(	self   ):






        '''simple docstring'''

        return CpmAntConfig(
            vocab_size=self.vocab_size      ,    hidden_size=self.hidden_size      ,    num_hidden_layers=self.num_hidden_layers      ,    num_attention_heads=self.num_attention_heads      ,    dim_ff=self.intermediate_size      ,    position_bias_num_buckets=self.num_buckets      ,    position_bias_max_distance=self.max_distance      ,    prompt_types=self.prompt_types      ,    prompt_length=self.prompt_length      ,    segment_types=self.segment_types      ,    use_cache=__SCREAMING_SNAKE_CASE      ,    init_std=self.init_std      ,    return_dict=self.return_dict      ,    )

       def 						_SCREAMING_SNAKE_CASE(	self      ,    __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE      ,    *__SCREAMING_SNAKE_CASE   ):






        '''simple docstring'''

        snake_case__										= CpmAntModel(config=__SCREAMING_SNAKE_CASE   )
        model.to(__SCREAMING_SNAKE_CASE   )
        model.eval()

        snake_case__										= model(**__SCREAMING_SNAKE_CASE   ).last_hidden_state

        self.parent.assertEqual(hidden_states.shape      ,    (self.batch_size, self.seq_length, config.hidden_size)   )

       def 						_SCREAMING_SNAKE_CASE(	self      ,    __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE      ,    *__SCREAMING_SNAKE_CASE   ):






        '''simple docstring'''

        snake_case__										= CpmAntForCausalLM(__SCREAMING_SNAKE_CASE   )
        model.to(__SCREAMING_SNAKE_CASE   )
        snake_case__										= input_ids["input_ids"].to(__SCREAMING_SNAKE_CASE   )
        model.eval()

        snake_case__										= model(**__SCREAMING_SNAKE_CASE   )
        self.parent.assertEqual(
            model_output.logits.shape      ,    (self.batch_size, self.seq_length, config.vocab_size + config.prompt_types * config.prompt_length)      ,    )

       def 						_SCREAMING_SNAKE_CASE(	self   ):






        '''simple docstring'''

        snake_case__							,      snake_case__										= self.prepare_config_and_inputs()
        return config, inputs_dict



@require_torch
class    lowercase_ (   __lowerCAmelCase ,__lowerCAmelCase ,unittest.TestCase							):
       snake_case__ :							List[str] 							=   (CpmAntModel, CpmAntForCausalLM) if is_torch_available() else ()
       snake_case__ :							Optional[int] 							=   (
           {"""feature-extraction""": CpmAntModel, """text-generation""": CpmAntForCausalLM} if is_torch_available() else {}
       )

       snake_case__ :							Dict 							=   False
       snake_case__ :							Dict 							=   False
       snake_case__ :							str 							=   False
       snake_case__ :							int 							=   False
       snake_case__ :							int 							=   False

       def 						_SCREAMING_SNAKE_CASE(	self   ):






        '''simple docstring'''

        snake_case__										= CpmAntModelTester(self   )
        snake_case__										= ConfigTester(self      ,    config_class=__SCREAMING_SNAKE_CASE   )

       def 						_SCREAMING_SNAKE_CASE(	self   ):






        '''simple docstring'''

        self.config_tester.create_and_test_config_common_properties()
        self.config_tester.create_and_test_config_to_json_string()
        self.config_tester.create_and_test_config_to_json_file()
        self.config_tester.create_and_test_config_from_and_save_pretrained()
        self.config_tester.check_config_can_be_init_without_params()
        self.config_tester.check_config_arguments_init()

       def 						_SCREAMING_SNAKE_CASE(	self   ):






        '''simple docstring'''

        unittest.skip("CPMAnt doesn't support input_embeds."   )(self.test_inputs_embeds   )

       def 						_SCREAMING_SNAKE_CASE(	self   ):






        '''simple docstring'''

        unittest.skip(
            "CPMAnt doesn't support retain grad in hidden_states or attentions, because prompt management will peel off the output.hidden_states from graph.\
                 So is attentions. We strongly recommand you use loss to tune model."   )(self.test_retain_grad_hidden_states_attentions   )

       def 						_SCREAMING_SNAKE_CASE(	self   ):






        '''simple docstring'''

        snake_case__							,      snake_case__										= self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_cpmant_model(__SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE   )

       def 						_SCREAMING_SNAKE_CASE(	self   ):






        '''simple docstring'''

        snake_case__							,      snake_case__										= self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_lm_head_model(__SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE   )



@require_torch
class    lowercase_ (   unittest.TestCase							):

       @tooslow
       def 						_SCREAMING_SNAKE_CASE(	self   ):






        '''simple docstring'''

        snake_case__										= "今天天气真好！"
        snake_case__										= "openbmb/cpm-ant-10b"
        snake_case__										= CpmAntModel.from_pretrained(__SCREAMING_SNAKE_CASE   )
        snake_case__										= CpmAntTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE   )
        snake_case__										= tokenizer(__SCREAMING_SNAKE_CASE      ,    return_tensors="pt"   )
        snake_case__										= model(**__SCREAMING_SNAKE_CASE   ).last_hidden_state

        snake_case__										= torch.tensor(
            [[[6.1708, 5.9244, 1.0835], [6.5207, 6.2893, -11.3324], [-1.0107, -0.0576, -5.9577]]]      ,    )
        self.assertTrue(torch.allclose(hidden_states[:, :3, :3]      ,    __SCREAMING_SNAKE_CASE      ,    atol=1e-2   )   )



@require_torch
class    lowercase_ (   unittest.TestCase							):

       @tooslow
       def 						_SCREAMING_SNAKE_CASE(	self   ):






        '''simple docstring'''

        snake_case__										= "今天天气真好！"
        snake_case__										= "openbmb/cpm-ant-10b"
        snake_case__										= CpmAntForCausalLM.from_pretrained(__SCREAMING_SNAKE_CASE   )
        snake_case__										= CpmAntTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE   )
        snake_case__										= tokenizer(__SCREAMING_SNAKE_CASE      ,    return_tensors="pt"   )
        snake_case__										= model(**__SCREAMING_SNAKE_CASE   ).logits

        snake_case__										= torch.tensor(
            [[[-6.4267, -6.4083, -6.3958], [-5.8802, -5.9447, -5.7811], [-5.3896, -5.4820, -5.4295]]]      ,    )
        self.assertTrue(torch.allclose(hidden_states[:, :3, :3]      ,    __SCREAMING_SNAKE_CASE      ,    atol=1e-2   )   )

       @tooslow
       def 						_SCREAMING_SNAKE_CASE(	self   ):






        '''simple docstring'''

        snake_case__										= "openbmb/cpm-ant-10b"
        snake_case__										= CpmAntForCausalLM.from_pretrained(__SCREAMING_SNAKE_CASE   )
        snake_case__										= CpmAntTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE   )
        snake_case__										= "今天天气不错，"
        snake_case__										= "今天天气不错，阳光明媚，我和妈妈一起去超市买东西。\n在超市里，我看到了一个很好玩的玩具，它的名字叫“机器人”。它有一个圆圆的脑袋，两只圆圆的眼睛，还有一个圆圆的"
        snake_case__										= tokenizer(__SCREAMING_SNAKE_CASE      ,    return_tensors="pt"   )
        snake_case__										= model.generate(**__SCREAMING_SNAKE_CASE   )
        snake_case__										= tokenizer.batch_decode(__SCREAMING_SNAKE_CASE   )
        self.assertEqual(__SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE   )

       @tooslow
       def 						_SCREAMING_SNAKE_CASE(	self   ):






        '''simple docstring'''

        snake_case__										= "openbmb/cpm-ant-10b"
        snake_case__										= CpmAntForCausalLM.from_pretrained(__SCREAMING_SNAKE_CASE   )
        snake_case__										= CpmAntTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE   )
        snake_case__										= ["今天天气不错，", "新年快乐，万事如意！"]
        snake_case__										= [
            "今天天气不错，阳光明媚，我和妈妈一起去超市买东西。\n在超市里，我看到了一个很好玩的玩具，它的名字叫“机器人”。它有一个圆圆的脑袋，两只圆圆的眼睛，还有一个圆圆的",
            "新年快乐，万事如意！在这辞旧迎新的美好时刻，我谨代表《农村新技术》杂志社全体同仁，向一直以来关心、支持《农村新技术》杂志发展的各级领导、各界朋友和广大读者致以最诚挚的",
        ]
        snake_case__										= tokenizer(__SCREAMING_SNAKE_CASE      ,    return_tensors="pt"      ,    padding=__SCREAMING_SNAKE_CASE   )
        snake_case__										= model.generate(**__SCREAMING_SNAKE_CASE   )
        snake_case__										= tokenizer.batch_decode(__SCREAMING_SNAKE_CASE   )
        self.assertEqual(__SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE   )








"""simple docstring"""


import argparse
import json
import sys
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
from typing import List

import torch
import torch.nn as nn
from huggingface_hub import cached_download, hf_hub_download
from torch import Tensor

from transformers import AutoImageProcessor, VanConfig, VanForImageClassification
from transformers.models.deprecated.van.modeling_van import VanLayerScaling
from transformers.utils import logging


logging.set_verbosity_info()
a__    :   Any    						= logging.get_logger(__name__)



@dataclass
class    lowercase_ :
       snake_case__ :							nn.Module
       snake_case__ :							List[nn.Module] 							=   field(default_factory=__lowerCAmelCase							)
       snake_case__ :							list 							=   field(default_factory=__lowerCAmelCase							)

       def 						_SCREAMING_SNAKE_CASE(	self      ,    __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE   ):






        '''simple docstring'''

        snake_case__										= len(list(m.modules()   )   ) == 1 or isinstance(__SCREAMING_SNAKE_CASE      ,    nn.Convad   ) or isinstance(__SCREAMING_SNAKE_CASE      ,    nn.BatchNormad   )
        if has_not_submodules:
         if not isinstance(__SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE   ):
          self.traced.append(__SCREAMING_SNAKE_CASE   )

       def __call__(	self      ,    __SCREAMING_SNAKE_CASE   ):






        '''simple docstring'''

        for m in self.module.modules():
         self.handles.append(m.register_forward_hook(self._forward_hook   )   )
        self.module(__SCREAMING_SNAKE_CASE   )
        [x.remove() for x in self.handles]
        return self

       @property
       def 						_SCREAMING_SNAKE_CASE(	self   ):






        '''simple docstring'''

        return list(filter(lambda __SCREAMING_SNAKE_CASE   : len(list(x.state_dict().keys()   )   ) > 0      ,    self.traced   )   )



@dataclass
class    lowercase_ :
       snake_case__ :							nn.Module
       snake_case__ :							nn.Module
       snake_case__ :							int 							=   0
       snake_case__ :							List 							=   field(default_factory=__lowerCAmelCase							)
       snake_case__ :							List 							=   field(default_factory=__lowerCAmelCase							)

       def __call__(	self      ,    __SCREAMING_SNAKE_CASE   ):






        '''simple docstring'''

        snake_case__										= Tracker(self.dest   )(__SCREAMING_SNAKE_CASE   ).parametrized
        snake_case__										= Tracker(self.src   )(__SCREAMING_SNAKE_CASE   ).parametrized

        snake_case__										= list(filter(lambda __SCREAMING_SNAKE_CASE   : type(__SCREAMING_SNAKE_CASE   ) not in self.src_skip      ,    __SCREAMING_SNAKE_CASE   )   )
        snake_case__										= list(filter(lambda __SCREAMING_SNAKE_CASE   : type(__SCREAMING_SNAKE_CASE   ) not in self.dest_skip      ,    __SCREAMING_SNAKE_CASE   )   )

        if len(__SCREAMING_SNAKE_CASE   ) != len(__SCREAMING_SNAKE_CASE   ):
         raise Exception(
             F"Numbers of operations are different. Source module has {len(__SCREAMING_SNAKE_CASE   )} operations while"
             F" destination module has {len(__SCREAMING_SNAKE_CASE   )}."   )

        for dest_m, src_m in zip(__SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE   ):
         dest_m.load_state_dict(src_m.state_dict()   )
         if self.verbose == 1:
          print(F"Transfered from={src_m} to={dest_m}"   )





def 							a__	(     _UpperCAmelCase		,   _UpperCAmelCase		)			->     nn.Module:

 '''simple docstring'''






 snake_case__										= from_model.state_dict()
 snake_case__										= our_model.state_dict()
 snake_case__										= our_model.config
 snake_case__										= []
 for stage_idx in range(len(config.hidden_sizes		)		):
  for block_id in range(config.depths[stage_idx]		):
   snake_case__										= f"block{stage_idx + 1}.{block_id}.layer_scale_1"
   snake_case__										= f"van.encoder.stages.{stage_idx}.layers.{block_id}.attention_scaling.weight"

   all_keys.append((from_key, to_key)		)
   snake_case__										= f"block{stage_idx + 1}.{block_id}.layer_scale_2"
   snake_case__										= f"van.encoder.stages.{stage_idx}.layers.{block_id}.mlp_scaling.weight"

   all_keys.append((from_key, to_key)		)

 for from_key, to_key in all_keys:
  snake_case__										= from_state_dict.pop(_UpperCAmelCase		)

 our_model.load_state_dict(_UpperCAmelCase		)
 return our_model





def 							a__	(     _UpperCAmelCase		,   _UpperCAmelCase		,   _UpperCAmelCase		,   _UpperCAmelCase		,   _UpperCAmelCase		,   _UpperCAmelCase = True		,   )			->     Union[str, Any]:

 '''simple docstring'''






 print(f"Downloading weights for {name}..."		)
 snake_case__										= cached_download(_UpperCAmelCase		)
 print(f"Converting {name}..."		)
 snake_case__										= torch.load(_UpperCAmelCase		)["state_dict"]
 from_model.load_state_dict(_UpperCAmelCase		)
 from_model.eval()
 with torch.no_grad():
  snake_case__										= VanForImageClassification(_UpperCAmelCase		).eval()
  snake_case__										= ModuleTransfer(src=_UpperCAmelCase		,   dest=_UpperCAmelCase		)
  snake_case__										= torch.randn((1, 3, 2_2_4, 2_2_4)		)
  module_transfer(_UpperCAmelCase		)
  snake_case__										= copy_parameters(_UpperCAmelCase		,   _UpperCAmelCase		)

 if not torch.allclose(from_model(_UpperCAmelCase		)		,   our_model(_UpperCAmelCase		).logits		):
  raise ValueError("The model logits don't match the original one."		)

 snake_case__										= name
 print(_UpperCAmelCase		)

 if push_to_hub:
  our_model.push_to_hub(
      repo_path_or_name=save_directory / checkpoint_name		,   commit_message="Add model"		,   use_temp_dir=_UpperCAmelCase		,   )

  # we can use the convnext one
  snake_case__										= AutoImageProcessor.from_pretrained("facebook/convnext-base-224-22k-1k"		)
  image_processor.push_to_hub(
      repo_path_or_name=save_directory / checkpoint_name		,   commit_message="Add image processor"		,   use_temp_dir=_UpperCAmelCase		,   )

  print(f"Pushed {checkpoint_name}"		)





def 							a__	(     _UpperCAmelCase		,   _UpperCAmelCase = None		,   _UpperCAmelCase = True		)			->     Union[str, Any]:

 '''simple docstring'''






 snake_case__										= "imagenet-1k-id2label.json"
 snake_case__										= 1_0_0_0

 snake_case__										= "huggingface/label-files"
 snake_case__										= num_labels
 snake_case__										= json.load(open(hf_hub_download(_UpperCAmelCase		,   _UpperCAmelCase		,   repo_type="dataset"		)		,   "r"		)		)
 snake_case__										= {int(_UpperCAmelCase		): v for k, v in idalabel.items()}

 snake_case__										= idalabel
 snake_case__										= {v: k for k, v in idalabel.items()}

 snake_case__										= partial(_UpperCAmelCase		,   num_labels=_UpperCAmelCase		,   idalabel=_UpperCAmelCase		,   labelaid=_UpperCAmelCase		)

 snake_case__										= {
     "van-tiny": ImageNetPreTrainedConfig(
         hidden_sizes=[3_2, 6_4, 1_6_0, 2_5_6]		,   depths=[3, 3, 5, 2]		,   mlp_ratios=[8, 8, 4, 4]		,   ),
     "van-small": ImageNetPreTrainedConfig(
         hidden_sizes=[6_4, 1_2_8, 3_2_0, 5_1_2]		,   depths=[2, 2, 4, 2]		,   mlp_ratios=[8, 8, 4, 4]		,   ),
     "van-base": ImageNetPreTrainedConfig(
         hidden_sizes=[6_4, 1_2_8, 3_2_0, 5_1_2]		,   depths=[3, 3, 1_2, 3]		,   mlp_ratios=[8, 8, 4, 4]		,   ),
     "van-large": ImageNetPreTrainedConfig(
         hidden_sizes=[6_4, 1_2_8, 3_2_0, 5_1_2]		,   depths=[3, 5, 2_7, 3]		,   mlp_ratios=[8, 8, 4, 4]		,   ),
 }

 snake_case__										= {
     "van-tiny": van_tiny,
     "van-small": van_small,
     "van-base": van_base,
     "van-large": van_large,
 }

 snake_case__										= {
     "van-tiny": (
         "https://huggingface.co/Visual-Attention-Network/VAN-Tiny-original/resolve/main/van_tiny_754.pth.tar"
     ),
     "van-small": (
         "https://huggingface.co/Visual-Attention-Network/VAN-Small-original/resolve/main/van_small_811.pth.tar"
     ),
     "van-base": (
         "https://huggingface.co/Visual-Attention-Network/VAN-Base-original/resolve/main/van_base_828.pth.tar"
     ),
     "van-large": (
         "https://huggingface.co/Visual-Attention-Network/VAN-Large-original/resolve/main/van_large_839.pth.tar"
     ),
 }

 if model_name:
  convert_weight_and_push(
      _UpperCAmelCase		,   names_to_config[model_name]		,   checkpoint=names_to_original_checkpoints[model_name]		,   from_model=names_to_original_models[model_name]()		,   save_directory=_UpperCAmelCase		,   push_to_hub=_UpperCAmelCase		,   )
 else:
  for model_name, config in names_to_config.items():
   convert_weight_and_push(
       _UpperCAmelCase		,   _UpperCAmelCase		,   checkpoint=names_to_original_checkpoints[model_name]		,   from_model=names_to_original_models[model_name]()		,   save_directory=_UpperCAmelCase		,   push_to_hub=_UpperCAmelCase		,   )


if __name__ == "__main__":
   a__    :   Any    						= 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 resnet* architecture,"""
           """ currently: van-tiny/small/base/large. 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(
       """--van_dir""",
       required=True,
       type=Path,
       help=(
           """A path to VAN's original implementation directory. You can download from here:"""
           """ https://github.com/Visual-Attention-Network/VAN-Classification"""
       ),
   )
   parser.add_argument(
       """--push_to_hub""",
       default=True,
       type=bool,
       required=False,
       help="""If True, push model and image processor to the hub.""",
   )

   a__    :   Any    						= parser.parse_args()
   a__    :   Path    						= args.pytorch_dump_folder_path
   pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True)
   a__    :   int    						= args.van_dir
   # append the path to the parents to maskformer dir
   sys.path.append(str(van_dir.parent))
   from van.models.van import van_base, van_large, van_small, van_tiny

   convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)

