





"""simple docstring"""






import argparse
import copy
import json
import multiprocessing
import os
import time

from create_dummy_models import COMPOSITE_MODELS, create_tiny_models
from huggingface_hub import ModelFilter, hf_api

import transformers
from transformers import AutoFeatureExtractor, AutoImageProcessor, AutoTokenizer
from transformers.image_processing_utils import BaseImageProcessor

def    __lowerCamelCase     (							)		->							Union[str, Any]:






       """simple docstring"""




       _UpperCAmelCase			     =  set()
       # Each auto modeling files contains multiple mappings. Let's get them in a dynamic way.
       for module_name in ["modeling_auto", "modeling_tf_auto", "modeling_flax_auto"]:
              _UpperCAmelCase			     =  getattr(transformers.models.auto,SCREAMING_SNAKE_CASE,SCREAMING_SNAKE_CASE				)
              if module is None:
                     continue
              # all mappings in a single auto modeling file
              _UpperCAmelCase			     =  [
                  x
                  for x in dir(SCREAMING_SNAKE_CASE				)
                  if x.endswith('_MAPPING_NAMES'				)
                  and (x.startswith('MODEL_'				) or x.startswith('TF_MODEL_'				) or x.startswith('FLAX_MODEL_'				))
              ]
              for name in mapping_names:
                     _UpperCAmelCase			     =  getattr(SCREAMING_SNAKE_CASE,SCREAMING_SNAKE_CASE				)
                     if mapping is not None:
                            for v in mapping.values():
                                   if isinstance(SCREAMING_SNAKE_CASE,(list, tuple)				):
                                          model_names.update(SCREAMING_SNAKE_CASE				)
                                   elif isinstance(SCREAMING_SNAKE_CASE,SCREAMING_SNAKE_CASE				):
                                          model_names.add(SCREAMING_SNAKE_CASE				)

       return sorted(SCREAMING_SNAKE_CASE				)

def    __lowerCamelCase     (							)		->							int:






       """simple docstring"""




       _UpperCAmelCase			     =  set(get_all_model_names()				)

       with open('tests/utils/tiny_model_summary.json'				) as fp:
              _UpperCAmelCase			     =  json.load(SCREAMING_SNAKE_CASE				)
       _UpperCAmelCase			     =  set()
       for model_base_name in tiny_model_info:
              tiny_models_names.update(tiny_model_info[model_base_name]['model_classes']				)

       # Remove a tiny model name if one of its framework implementation hasn't yet a tiny version on the Hub.
       _UpperCAmelCase			     =  model_names.difference(SCREAMING_SNAKE_CASE				)
       for model_name in copy.copy(SCREAMING_SNAKE_CASE				):
              if not model_name.startswith('TF'				) and F"""TF{model_name}""" in not_on_hub:
                     tiny_models_names.remove(SCREAMING_SNAKE_CASE				)
              elif model_name.startswith('TF'				) and model_name[2:] in not_on_hub:
                     tiny_models_names.remove(SCREAMING_SNAKE_CASE				)

       return sorted(SCREAMING_SNAKE_CASE				)

def    __lowerCamelCase     (							SCREAMING_SNAKE_CASE				)		->							List[Any]:






       """simple docstring"""




       _UpperCAmelCase			     =  COMPOSITE_MODELS.values()

       # All tiny model base names on Hub
       _UpperCAmelCase			     =  get_all_model_names()
       _UpperCAmelCase			     =  hf_api.list_models(
           filter=ModelFilter(
               author='hf-internal-testing',)				)
       _UpperCAmelCase			     =  set()
       for x in models:
              _UpperCAmelCase			     =  x.modelId
              _UpperCAmelCase			     =  model.split('/'				)
              if not model.startswith('tiny-random-'				):
                     continue
              _UpperCAmelCase			     =  model.replace('tiny-random-',''				)
              if not model[0].isupper():
                     continue
              if model not in model_names and model not in special_models:
                     continue
              _models.add(SCREAMING_SNAKE_CASE				)

       _UpperCAmelCase			     =  sorted(_models				)
       # All tiny model names on Hub
       _UpperCAmelCase			     =  {}
       for model in models:
              _UpperCAmelCase			     =  F"""hf-internal-testing/tiny-random-{model}"""
              _UpperCAmelCase			     =  model.split('-'				)[0]
              try:
                     _UpperCAmelCase			     =  hf_api.repo_info(SCREAMING_SNAKE_CASE				)
                     _UpperCAmelCase			     =  {
                         """tokenizer_classes""": set(),
                         """processor_classes""": set(),
                         """model_classes""": set(),
                         """sha""": repo_info.sha,
                     }
              except Exception:
                     continue
              try:
                     time.sleep(1				)
                     _UpperCAmelCase			     =  AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE				)
                     content["tokenizer_classes"].add(tokenizer_fast.__class__.__name__				)
              except Exception:
                     pass
              try:
                     time.sleep(1				)
                     _UpperCAmelCase			     =  AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE,use_fast=SCREAMING_SNAKE_CASE				)
                     content["tokenizer_classes"].add(tokenizer_slow.__class__.__name__				)
              except Exception:
                     pass
              try:
                     time.sleep(1				)
                     _UpperCAmelCase			     =  AutoImageProcessor.from_pretrained(SCREAMING_SNAKE_CASE				)
                     content["processor_classes"].add(img_p.__class__.__name__				)
              except Exception:
                     pass
              try:
                     time.sleep(1				)
                     _UpperCAmelCase			     =  AutoFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE				)
                     if not isinstance(SCREAMING_SNAKE_CASE,SCREAMING_SNAKE_CASE				):
                            content["processor_classes"].add(feat_p.__class__.__name__				)
              except Exception:
                     pass
              try:
                     time.sleep(1				)
                     _UpperCAmelCase			     =  getattr(SCREAMING_SNAKE_CASE,SCREAMING_SNAKE_CASE				)
                     _UpperCAmelCase			     =  model_class.from_pretrained(SCREAMING_SNAKE_CASE				)
                     content["model_classes"].add(m.__class__.__name__				)
              except Exception:
                     pass
              try:
                     time.sleep(1				)
                     _UpperCAmelCase			     =  getattr(SCREAMING_SNAKE_CASE,F"""TF{model}"""				)
                     _UpperCAmelCase			     =  model_class.from_pretrained(SCREAMING_SNAKE_CASE				)
                     content["model_classes"].add(m.__class__.__name__				)
              except Exception:
                     pass

              _UpperCAmelCase			     =  sorted(content['tokenizer_classes']				)
              _UpperCAmelCase			     =  sorted(content['processor_classes']				)
              _UpperCAmelCase			     =  sorted(content['model_classes']				)

              _UpperCAmelCase			     =  content
              with open(os.path.join(SCREAMING_SNAKE_CASE,'hub_tiny_model_summary.json'				),'w'				) as fp:
                     json.dump(SCREAMING_SNAKE_CASE,SCREAMING_SNAKE_CASE,ensure_ascii=SCREAMING_SNAKE_CASE,indent=4				)


if __name__ == "__main__":
    lowerCAmelCase_      =				argparse.ArgumentParser()
    parser.add_argument('''--num_workers''', default=1, type=int, help='''The number of workers to run.''')
    lowerCAmelCase_      =				parser.parse_args()

    # This has to be `spawn` to avoid hanging forever!
    multiprocessing.set_start_method('''spawn''')

    lowerCAmelCase_      =				'''tiny_models'''
    lowerCAmelCase_      =				True
    lowerCAmelCase_      =				None
    lowerCAmelCase_      =				get_tiny_model_names_from_repo()
    lowerCAmelCase_      =				True
    lowerCAmelCase_      =				True
    lowerCAmelCase_      =				'''hf-internal-testing'''

    create_tiny_models(
        output_path,
        all,
        model_types,
        models_to_skip,
        no_check,
        upload,
        organization,
        token=os.environ.get('''TOKEN''', None),
        num_workers=args.num_workers,
    )










'''simple docstring'''
import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device


if is_torch_available():
     import torch

     from transformers import XLMProphetNetForConditionalGeneration, XLMProphetNetTokenizer







@require_torch
class 					_A						(						unittest.TestCase							):



   '''simple docstring'''






   @slow
   def   __lowerCAmelCase						(	self	:					Tuple						)->	Optional[int]:
          snake_case__					:	Any          =					XLMProphetNetForConditionalGeneration.from_pretrained("""microsoft/xprophetnet-large-wiki100-cased"""						)
          model.to(lowerCamelCase						)

          # encoder-decoder outputs
          snake_case__					:	Optional[int]          =					torch.tensor([[17, 96_208, 103_471, 2]]						).to(lowerCamelCase						)
          snake_case__					:	Optional[Any]          =					torch.tensor(
              [[2, 250, 9_953, 34, 69_489, 1_620, 32, 118_424, 624, 210, 105, 2_913, 1_032, 351]]						).to(lowerCamelCase						)
          snake_case__					:	Optional[Any]          =					model(
              input_ids=lowerCamelCase					, attention_mask=lowerCamelCase					, encoder_outputs=lowerCamelCase					, decoder_input_ids=lowerCamelCase						)
          snake_case__					:	List[Any]          =					output[0]
          snake_case__					:	Any          =					torch.Size((1, 14, 250_012)						)
          self.assertEqual(output_predited_logis.shape					, lowerCamelCase						)
          snake_case__					:	Optional[int]          =					torch.tensor(
              [[[-6.3_986, -8.2_391, 12.5_189], [-6.3_289, -8.0_864, 12.6_211], [-6.2_418, -8.0_445, 12.7_968]]]						).to(lowerCamelCase						)
          self.assertTrue(torch.allclose(output_predited_logis[:, :3, :3]					, lowerCamelCase					, atol=1e-4						)						)

          # encoder outputs
          snake_case__					:	Dict          =					model.prophetnet.encoder(lowerCamelCase						)[0]
          snake_case__					:	Optional[Any]          =					torch.tensor(
              [[[-1.4_260, -0.7_628, 0.8_453], [-1.4_719, -0.1_391, 0.7_807], [-1.7_678, 0.0_114, 0.4_646]]]						).to(lowerCamelCase						)
          snake_case__					:	str          =					torch.Size((1, 4, 1_024)						)
          self.assertEqual(encoder_outputs.shape					, lowerCamelCase						)
          self.assertTrue(torch.allclose(encoder_outputs[:, :3, :3]					, lowerCamelCase					, atol=1e-4						)						)

          # decoder outputs
          snake_case__					:	int          =					model.prophetnet.decoder(
              lowerCamelCase					, encoder_hidden_states=lowerCamelCase					, )
          snake_case__					:	Any          =					decoder_outputs[1].view(1					, model.config.ngram					, 14					, -1						)
          snake_case__					:	Optional[Any]          =					model.lm_head(lowerCamelCase						)
          snake_case__					:	str          =					predicting_streams_logits[:, 0]
          self.assertTrue(torch.allclose(next_first_stream_logits[:, :3, :3]					, lowerCamelCase					, atol=1e-4						)						)




   @slow
   def   __lowerCAmelCase						(	self	:					Union[str, Any]						)->	Optional[Any]:
          snake_case__					:	Tuple          =					XLMProphetNetForConditionalGeneration.from_pretrained(
              """microsoft/xprophetnet-large-wiki100-cased-xglue-ntg"""						)
          model.to(lowerCamelCase						)

          snake_case__					:	str          =					torch.tensor([[17, 96_208, 103_471, 2]]						).to(lowerCamelCase						)
          snake_case__					:	Union[str, Any]          =					torch.tensor(
              [[2, 250, 9_953, 34, 69_489, 1_620, 32, 118_424, 624, 210, 105, 2_913, 1_032, 351]]						).to(lowerCamelCase						)
          snake_case__					:	List[Any]          =					model(
              input_ids=lowerCamelCase					, attention_mask=lowerCamelCase					, encoder_outputs=lowerCamelCase					, decoder_input_ids=lowerCamelCase						)
          snake_case__					:	List[str]          =					output[0]
          snake_case__					:	Any          =					torch.Size((1, 14, 250_012)						)
          self.assertEqual(output_predited_logis.shape					, lowerCamelCase						)
          # compare the actual values for a slice.
          snake_case__					:	List[str]          =					torch.tensor(
              [[[-9.2_253, -9.7_173, -6.3_529], [-7.6_701, -9.0_145, -1.9_382], [-8.0_195, -7.0_004, -0.1_523]]]						).to(lowerCamelCase						)

          self.assertTrue(torch.allclose(output_predited_logis[:, :3, :3]					, lowerCamelCase					, atol=1e-4						)						)




   @slow
   def   __lowerCAmelCase						(	self	:					str						)->	str:
          snake_case__					:	Dict          =					XLMProphetNetForConditionalGeneration.from_pretrained(
              """microsoft/xprophetnet-large-wiki100-cased-xglue-ntg"""						)
          model.to(lowerCamelCase						)
          snake_case__					:	Optional[int]          =					512

          snake_case__					:	Any          =					XLMProphetNetTokenizer.from_pretrained("""microsoft/xprophetnet-large-wiki100-cased-xglue-ntg"""						)

          snake_case__					:	Optional[int]          =					(
              """Microsoft Corporation intends to officially end free support for the Windows 7 operating system after"""
              """ January 14, 2020, according to the official portal of the organization. From that day, users of this"""
              """ system will not be able to receive security updates, which could make their computers vulnerable to"""
              """ cyber attacks."""
          )
          snake_case__					:	Union[str, Any]          =					(
              """орпорация Microsoft намерена официально прекратить бесплатную поддержку операционной системы Windows 7"""
              """ после 14 января 2020 года, сообщается на официальном портале организации . С указанного дня пользователи"""
              """ этой системы не смогут получать обновления безопасности, из-за чего их компьютеры могут стать уязвимыми"""
              """ к кибератакам."""
          )
          snake_case__					:	int          =					(
              """根据该组织的官方门户网站，微软公司打算在2020年1月14日之后正式终止对Windows 7操作系统的免费支持。从那时起，该系统的用户将无法接收安全更新，这可能会使他们的计算机容易受到网络攻击。"""
          )

          snake_case__					:	int          =					tokenizer(
              [EN_SENTENCE, RU_SENTENCE, ZH_SENTENCE]					, padding=lowerCamelCase					, max_length=255					, return_tensors="""pt"""						).input_ids
          snake_case__					:	Optional[int]          =					input_ids.to(lowerCamelCase						)

          snake_case__					:	Optional[Any]          =					model.generate(
              lowerCamelCase					, num_beams=10					, length_penalty=1.0					, no_repeat_ngram_size=3					, early_stopping=lowerCamelCase						)
          snake_case__					:	Union[str, Any]          =					[tokenizer.decode(lowerCamelCase					, skip_special_tokens=lowerCamelCase						) for g in summary_ids]
          snake_case__					:	Optional[Any]          =					"""Microsoft to end Windows 7 free support after January 14, 2020"""
          snake_case__					:	Dict          =					"""Microsoft намерена прекратить бесплатную поддержку Windows 7 после 14 января 2020 года"""
          snake_case__					:	Optional[int]          =					"""微软打算终止对Windows 7操作系统的免费支持"""
          self.assertListEqual(
              [EXPECTED_TITLE_EN, EXPECTED_TITLE_RU, EXPECTED_TITLE_ZH]					, lowerCamelCase					, )

          snake_case__					:	Optional[int]          =					model.generate(
              lowerCamelCase					, num_beams=1					, length_penalty=1.0					, no_repeat_ngram_size=3					, early_stopping=lowerCamelCase						)
          snake_case__					:	Tuple          =					[
              tokenizer.convert_ids_to_tokens(lowerCamelCase					, skip_special_tokens=lowerCamelCase						) for g in summary_ids_beama
          ]
          snake_case__					:	Any          =					"""▁Microsoft ▁to ▁end ▁free ▁support ▁for ▁Windows ▁7""".split(""" """						)
          snake_case__					:	Union[str, Any]          =					"""▁Microsoft ▁намерен а ▁прекрати ть ▁бес плат ную ▁поддержку ▁Windows ▁7 ▁после ▁14 ▁января ▁2020 ▁года""".split(
              """ """						)
          snake_case__					:	Tuple          =					"""微软 公司 打算 终止 对 Windows ▁7 操作 系统的 免费 支持""".split(""" """						)
          self.assertListEqual(
              [EXPECTED_TITLE_EN_BEAM1_TOK, EXPECTED_TITLE_RU_BEAM1_TOK, EXPECTED_TITLE_ZH_BEAM1_TOK]					, lowerCamelCase					, )




