





'''simple docstring'''







import os
from shutil import copyfile
from typing import List, Optional, Tuple

from tokenizers import processors

from ...tokenization_utils import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
   from .tokenization_nllb import NllbTokenizer
else:
   _lowercase												=			None


_lowercase												=			logging.get_logger(__name__)


_lowercase												=			{'vocab_file': 'sentencepiece.bpe.model', 'tokenizer_file': 'tokenizer.json'}

_lowercase												=			{
    'vocab_file': {
        'facebook/nllb-200-distilled-600M': (
            'https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/sentencepiece.bpe.model'
        ),
    },
    'tokenizer_file': {
        'facebook/nllb-200-distilled-600M': (
            'https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/tokenizer.json'
        ),
    },
}

_lowercase												=			{
    'facebook/nllb-large-en-ro': 1_024,
    'facebook/nllb-200-distilled-600M': 1_024,
}

# fmt: off
_lowercase												=			['ace_Arab', 'ace_Latn', 'acm_Arab', 'acq_Arab', 'aeb_Arab', 'afr_Latn', 'ajp_Arab', 'aka_Latn', 'amh_Ethi', 'apc_Arab', 'arb_Arab', 'ars_Arab', 'ary_Arab', 'arz_Arab', 'asm_Beng', 'ast_Latn', 'awa_Deva', 'ayr_Latn', 'azb_Arab', 'azj_Latn', 'bak_Cyrl', 'bam_Latn', 'ban_Latn', 'bel_Cyrl', 'bem_Latn', 'ben_Beng', 'bho_Deva', 'bjn_Arab', 'bjn_Latn', 'bod_Tibt', 'bos_Latn', 'bug_Latn', 'bul_Cyrl', 'cat_Latn', 'ceb_Latn', 'ces_Latn', 'cjk_Latn', 'ckb_Arab', 'crh_Latn', 'cym_Latn', 'dan_Latn', 'deu_Latn', 'dik_Latn', 'dyu_Latn', 'dzo_Tibt', 'ell_Grek', 'eng_Latn', 'epo_Latn', 'est_Latn', 'eus_Latn', 'ewe_Latn', 'fao_Latn', 'pes_Arab', 'fij_Latn', 'fin_Latn', 'fon_Latn', 'fra_Latn', 'fur_Latn', 'fuv_Latn', 'gla_Latn', 'gle_Latn', 'glg_Latn', 'grn_Latn', 'guj_Gujr', 'hat_Latn', 'hau_Latn', 'heb_Hebr', 'hin_Deva', 'hne_Deva', 'hrv_Latn', 'hun_Latn', 'hye_Armn', 'ibo_Latn', 'ilo_Latn', 'ind_Latn', 'isl_Latn', 'ita_Latn', 'jav_Latn', 'jpn_Jpan', 'kab_Latn', 'kac_Latn', 'kam_Latn', 'kan_Knda', 'kas_Arab', 'kas_Deva', 'kat_Geor', 'knc_Arab', 'knc_Latn', 'kaz_Cyrl', 'kbp_Latn', 'kea_Latn', 'khm_Khmr', 'kik_Latn', 'kin_Latn', 'kir_Cyrl', 'kmb_Latn', 'kon_Latn', 'kor_Hang', 'kmr_Latn', 'lao_Laoo', 'lvs_Latn', 'lij_Latn', 'lim_Latn', 'lin_Latn', 'lit_Latn', 'lmo_Latn', 'ltg_Latn', 'ltz_Latn', 'lua_Latn', 'lug_Latn', 'luo_Latn', 'lus_Latn', 'mag_Deva', 'mai_Deva', 'mal_Mlym', 'mar_Deva', 'min_Latn', 'mkd_Cyrl', 'plt_Latn', 'mlt_Latn', 'mni_Beng', 'khk_Cyrl', 'mos_Latn', 'mri_Latn', 'zsm_Latn', 'mya_Mymr', 'nld_Latn', 'nno_Latn', 'nob_Latn', 'npi_Deva', 'nso_Latn', 'nus_Latn', 'nya_Latn', 'oci_Latn', 'gaz_Latn', 'ory_Orya', 'pag_Latn', 'pan_Guru', 'pap_Latn', 'pol_Latn', 'por_Latn', 'prs_Arab', 'pbt_Arab', 'quy_Latn', 'ron_Latn', 'run_Latn', 'rus_Cyrl', 'sag_Latn', 'san_Deva', 'sat_Beng', 'scn_Latn', 'shn_Mymr', 'sin_Sinh', 'slk_Latn', 'slv_Latn', 'smo_Latn', 'sna_Latn', 'snd_Arab', 'som_Latn', 'sot_Latn', 'spa_Latn', 'als_Latn', 'srd_Latn', 'srp_Cyrl', 'ssw_Latn', 'sun_Latn', 'swe_Latn', 'swh_Latn', 'szl_Latn', 'tam_Taml', 'tat_Cyrl', 'tel_Telu', 'tgk_Cyrl', 'tgl_Latn', 'tha_Thai', 'tir_Ethi', 'taq_Latn', 'taq_Tfng', 'tpi_Latn', 'tsn_Latn', 'tso_Latn', 'tuk_Latn', 'tum_Latn', 'tur_Latn', 'twi_Latn', 'tzm_Tfng', 'uig_Arab', 'ukr_Cyrl', 'umb_Latn', 'urd_Arab', 'uzn_Latn', 'vec_Latn', 'vie_Latn', 'war_Latn', 'wol_Latn', 'xho_Latn', 'ydd_Hebr', 'yor_Latn', 'yue_Hant', 'zho_Hans', 'zho_Hant', 'zul_Latn']
class 			_lowercase						(       __a					):
     _UpperCAmelCase										=					VOCAB_FILES_NAMES
     _UpperCAmelCase										=					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     _UpperCAmelCase										=					PRETRAINED_VOCAB_FILES_MAP
     _UpperCAmelCase										=					['''input_ids''', '''attention_mask''']
     _UpperCAmelCase										=					NllbTokenizer

     _UpperCAmelCase										=					[]
     _UpperCAmelCase										=					[]







     def __init__( self    ,   A__=None    ,   A__=None    ,   A__="<s>"    ,   A__="</s>"    ,   A__="</s>"    ,   A__="<s>"    ,   A__="<unk>"    ,   A__="<pad>"    ,   A__="<mask>"    ,   A__=None    ,   A__=None    ,   A__=None    ,   A__=False    ,   **A__    ,   ) ->	List[Any]:
      # Mask token behave like a normal word, i.e. include the space before it
      snake_case				=			AddedToken(A__    ,   lstrip=A__    ,   rstrip=A__    ) if isinstance(A__    ,   A__    ) else mask_token
      snake_case				=			legacy_behaviour
      super().__init__(
          vocab_file=A__    ,   tokenizer_file=A__    ,   bos_token=A__    ,   eos_token=A__    ,   sep_token=A__    ,   cls_token=A__    ,   unk_token=A__    ,   pad_token=A__    ,   mask_token=A__    ,   src_lang=A__    ,   tgt_lang=A__    ,   additional_special_tokens=A__    ,   legacy_behaviour=A__    ,   **A__    ,   )

      snake_case				=			vocab_file
      snake_case				=			False if not self.vocab_file else True

      snake_case				=			FAIRSEQ_LANGUAGE_CODES.copy()

      if additional_special_tokens is not None:
       # Only add those special tokens if they are not already there.
       _additional_special_tokens.extend(
           [t for t in additional_special_tokens if t not in _additional_special_tokens]    )

      self.add_special_tokens({'''additional_special_tokens''': _additional_special_tokens}    )
      snake_case				=			{
          lang_code: self.convert_tokens_to_ids(A__    ) for lang_code in FAIRSEQ_LANGUAGE_CODES
      }

      snake_case				=			src_lang if src_lang is not None else '''eng_Latn'''
      snake_case				=			self.convert_tokens_to_ids(self._src_lang    )
      snake_case				=			tgt_lang
      self.set_src_lang_special_tokens(self._src_lang    )







     @property
     def     UpperCamelCase			( self    ) ->	str:
      return self._src_lang







     @src_lang.setter
     def     UpperCamelCase			( self    ,   A__    ) ->	None:
      snake_case				=			new_src_lang
      self.set_src_lang_special_tokens(self._src_lang    )







     def     UpperCamelCase			( self    ,   A__    ,   A__ = None    ) ->	List[int]:
      if token_ids_a is None:
       return self.prefix_tokens + token_ids_a + self.suffix_tokens
      # We don't expect to process pairs, but leave the pair logic for API consistency
      return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens







     def     UpperCamelCase			( self    ,   A__    ,   A__ = None    ) ->	List[int]:
      snake_case				=			[self.sep_token_id]
      snake_case				=			[self.cls_token_id]

      if token_ids_a is None:
       return len(cls + token_ids_a + sep    ) * [0]
      return len(cls + token_ids_a + sep + sep + token_ids_a + sep    ) * [0]







     def     UpperCamelCase			( self    ,   A__    ,   A__    ,   A__    ,   A__    ,   **A__    ) ->	Union[str, Any]:
      if src_lang is None or tgt_lang is None:
       raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model'''    )
      snake_case				=			src_lang
      snake_case				=			self(A__    ,   add_special_tokens=A__    ,   return_tensors=A__    ,   **A__    )
      snake_case				=			self.convert_tokens_to_ids(A__    )
      snake_case				=			tgt_lang_id
      return inputs







     def     UpperCamelCase			( self    ,   A__    ,   A__ = "eng_Latn"    ,   A__ = None    ,   A__ = "fra_Latn"    ,   **A__    ,   ) ->	BatchEncoding:
      snake_case				=			src_lang
      snake_case				=			tgt_lang
      return super().prepare_seqaseq_batch(A__    ,   A__    ,   **A__    )







     def     UpperCamelCase			( self    ) ->	List[Any]:
      return self.set_src_lang_special_tokens(self.src_lang    )







     def     UpperCamelCase			( self    ) ->	Optional[Any]:
      return self.set_tgt_lang_special_tokens(self.tgt_lang    )







     def     UpperCamelCase			( self    ,   A__    ) ->	None:
      snake_case				=			self.convert_tokens_to_ids(A__    )

      if self.legacy_behaviour:
       snake_case				=			[]
       snake_case				=			[self.eos_token_id, self.cur_lang_code]
      else:
       snake_case				=			[self.cur_lang_code]
       snake_case				=			[self.eos_token_id]

      snake_case				=			self.convert_ids_to_tokens(self.prefix_tokens    )
      snake_case				=			self.convert_ids_to_tokens(self.suffix_tokens    )

      snake_case				=			processors.TemplateProcessing(
          single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str    ,   pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str    ,   special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str    ,   self.prefix_tokens + self.suffix_tokens    )    )    ,   )







     def     UpperCamelCase			( self    ,   A__    ) ->	None:
      snake_case				=			self.convert_tokens_to_ids(A__    )
      if self.legacy_behaviour:
       snake_case				=			[]
       snake_case				=			[self.eos_token_id, self.cur_lang_code]
      else:
       snake_case				=			[self.cur_lang_code]
       snake_case				=			[self.eos_token_id]

      snake_case				=			self.convert_ids_to_tokens(self.prefix_tokens    )
      snake_case				=			self.convert_ids_to_tokens(self.suffix_tokens    )

      snake_case				=			processors.TemplateProcessing(
          single=prefix_tokens_str + ['''$A'''] + suffix_tokens_str    ,   pair=prefix_tokens_str + ['''$A''', '''$B'''] + suffix_tokens_str    ,   special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str    ,   self.prefix_tokens + self.suffix_tokens    )    )    ,   )







     def     UpperCamelCase			( self    ,   A__    ,   A__ = None    ) ->	Tuple[str]:
      if not self.can_save_slow_tokenizer:
       raise ValueError(
           '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow '''
           '''tokenizer.'''    )

      if not os.path.isdir(A__    ):
       logger.error(F"""Vocabulary path ({save_directory}) should be a directory."""    )
       return
      snake_case				=			os.path.join(
          A__    ,   (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']    )

      if os.path.abspath(self.vocab_file    ) != os.path.abspath(A__    ):
       copyfile(self.vocab_file    ,   A__    )

      return (out_vocab_file,)








'''simple docstring'''







import argparse
import json
from collections import OrderedDict
from pathlib import Path

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor
from transformers.utils import logging


logging.set_verbosity_info()
_lowercase       						=			logging.get_logger(__name__)

def    __UpperCamelCase	(	a    : Dict					,   a    : Optional[int]					,   a    : Dict					,   a    : Dict     ) ->Union[str, Any]:
 snake_case				=			original_name.split('''.'''     )[0]
 snake_case				=			key.split('''.'''     )
 snake_case				=			int(key_list[key_list.index(a     ) - 2]     )
 snake_case				=			int(key_list[key_list.index(a     ) - 1]     )
 snake_case				=			orig_block_num - offset

 snake_case				=			key.replace(f"""{orig_block_num}.{layer_num}.{original_name}"""					,   f"""block.{new_block_num}.{layer_num}.{new_name}"""     )
 return key

def    __UpperCamelCase	(	a    : Tuple     ) ->Dict:
 snake_case				=			OrderedDict()
 snake_case				,		snake_case				=			0, 0
 for key, value in state_dict.items():
  if key.startswith('''network'''     ):
   snake_case				=			key.replace('''network'''					,   '''poolformer.encoder'''     )
  if "proj" in key:
   # Works for the first embedding as well as the internal embedding layers
   if key.endswith('''bias'''     ) and "patch_embed" not in key:
    patch_emb_offset += 1
   snake_case				=			key[: key.find('''proj'''     )]
   snake_case				=			key.replace(a					,   f"""patch_embeddings.{total_embed_found}."""     )
   snake_case				=			key.replace('''proj'''					,   '''projection'''     )
   if key.endswith('''bias'''     ):
    total_embed_found += 1
  if "patch_embeddings" in key:
   snake_case				=			'''poolformer.encoder.''' + key
  if "mlp.fc1" in key:
   snake_case				=			replace_key_with_offset(a					,   a					,   '''mlp.fc1'''					,   '''output.conv1'''     )
  if "mlp.fc2" in key:
   snake_case				=			replace_key_with_offset(a					,   a					,   '''mlp.fc2'''					,   '''output.conv2'''     )
  if "norm1" in key:
   snake_case				=			replace_key_with_offset(a					,   a					,   '''norm1'''					,   '''before_norm'''     )
  if "norm2" in key:
   snake_case				=			replace_key_with_offset(a					,   a					,   '''norm2'''					,   '''after_norm'''     )
  if "layer_scale_1" in key:
   snake_case				=			replace_key_with_offset(a					,   a					,   '''layer_scale_1'''					,   '''layer_scale_1'''     )
  if "layer_scale_2" in key:
   snake_case				=			replace_key_with_offset(a					,   a					,   '''layer_scale_2'''					,   '''layer_scale_2'''     )
  if "head" in key:
   snake_case				=			key.replace('''head'''					,   '''classifier'''     )
  snake_case				=			value
 return new_state_dict

def    __UpperCamelCase	(	) ->Optional[int]:
 snake_case				=			'''http://images.cocodataset.org/val2017/000000039769.jpg'''
 snake_case				=			Image.open(requests.get(a					,   stream=a     ).raw     )

 return image

@torch.no_grad()
def    __UpperCamelCase	(	a    : Dict					,   a    : Optional[Any]					,   a    : Tuple     ) ->List[str]:
 snake_case				=			PoolFormerConfig()

 # set attributes based on model_name
 snake_case				=			'''huggingface/label-files'''
 snake_case				=			model_name[-3:]
 snake_case				=			1000
 snake_case				=			'''imagenet-1k-id2label.json'''
 snake_case				=			(1, 1000)

 # set config attributes
 snake_case				=			json.load(open(hf_hub_download(a					,   a					,   repo_type='''dataset'''     )					,   '''r'''     )     )
 snake_case				=			{int(a     ): v for k, v in idalabel.items()}
 snake_case				=			idalabel
 snake_case				=			{v: k for k, v in idalabel.items()}
 if size == "s12":
  snake_case				=			[2, 2, 6, 2]
  snake_case				=			[64, 128, 320, 512]
  snake_case				=			4.0
  snake_case				=			0.9
 elif size == "s24":
  snake_case				=			[4, 4, 12, 4]
  snake_case				=			[64, 128, 320, 512]
  snake_case				=			4.0
  snake_case				=			0.9
 elif size == "s36":
  snake_case				=			[6, 6, 18, 6]
  snake_case				=			[64, 128, 320, 512]
  snake_case				=			4.0
  snake_case				=			1e-6
  snake_case				=			0.9
 elif size == "m36":
  snake_case				=			[6, 6, 18, 6]
  snake_case				=			[96, 192, 384, 768]
  snake_case				=			4.0
  snake_case				=			1e-6
  snake_case				=			0.95
 elif size == "m48":
  snake_case				=			[8, 8, 24, 8]
  snake_case				=			[96, 192, 384, 768]
  snake_case				=			4.0
  snake_case				=			1e-6
  snake_case				=			0.95
 else:
  raise ValueError(f"""Size {size} not supported"""     )

 # load image processor
 snake_case				=			PoolFormerImageProcessor(crop_pct=a     )

 # Prepare image
 snake_case				=			prepare_img()
 snake_case				=			image_processor(images=a					,   return_tensors='''pt'''     ).pixel_values

 logger.info(f"""Converting model {model_name}..."""     )

 # load original state dict
 snake_case				=			torch.load(a					,   map_location=torch.device('''cpu'''     )     )

 # rename keys
 snake_case				=			rename_keys(a     )

 # create HuggingFace model and load state dict
 snake_case				=			PoolFormerForImageClassification(a     )
 model.load_state_dict(a     )
 model.eval()

 # Define image processor
 snake_case				=			PoolFormerImageProcessor(crop_pct=a     )
 snake_case				=			image_processor(images=prepare_img()					,   return_tensors='''pt'''     ).pixel_values

 # forward pass
 snake_case				=			model(a     )
 snake_case				=			outputs.logits

 # define expected logit slices for different models
 if size == "s12":
  snake_case				=			torch.tensor([-0.3045, -0.6758, -0.4869]     )
 elif size == "s24":
  snake_case				=			torch.tensor([0.4402, -0.1374, -0.8045]     )
 elif size == "s36":
  snake_case				=			torch.tensor([-0.6080, -0.5133, -0.5898]     )
 elif size == "m36":
  snake_case				=			torch.tensor([0.3952, 0.2263, -1.2668]     )
 elif size == "m48":
  snake_case				=			torch.tensor([0.1167, -0.0656, -0.3423]     )
 else:
  raise ValueError(f"""Size {size} not supported"""     )

 # verify logits
 assert logits.shape == expected_shape
 assert torch.allclose(logits[0, :3]					,   a					,   atol=1e-2     )

 # finally, save model and image processor
 logger.info(f"""Saving PyTorch model and image processor to {pytorch_dump_folder_path}..."""     )
 Path(a     ).mkdir(exist_ok=a     )
 model.save_pretrained(a     )
 print(f"""Saving image processor to {pytorch_dump_folder_path}"""     )
 image_processor.save_pretrained(a     )


if __name__ == "__main__":
   _lowercase       						=			argparse.ArgumentParser()

   parser.add_argument(
       '--model_name',
       default='poolformer_s12',
       type=str,
       help='Name of the model you\'d like to convert.',
   )
   parser.add_argument(
       '--checkpoint_path', default=None, type=str, help='Path to the original PyTorch checkpoint (.pth file).'
   )
   parser.add_argument(
       '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.'
   )
   _lowercase       						=			parser.parse_args()
   convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)

