






"""simple docstring"""



import math
from typing import Optional

import torch
import torch.utils.checkpoint as checkpoint
from torch import nn

from ....modeling_utils import PreTrainedModel
from ....utils import add_start_docstrings, logging
from ...bert.modeling_bert import BertModel
from .configuration_retribert import RetriBertConfig


__A		:	str      =		logging.get_logger(__name__)

__A		:	Union[str, Any]      =		[
    '''yjernite/retribert-base-uncased''',
    # See all RetriBert models at https://huggingface.co/models?filter=retribert
]





class  _UpperCAmelCase	(			_A							):
					SCREAMING_SNAKE_CASE_		:    Optional[int]							   =       RetriBertConfig
					SCREAMING_SNAKE_CASE_		:    Dict							   =       None
					SCREAMING_SNAKE_CASE_		:    Tuple							   =       "retribert"




					def   A  (    self					:						List[str]   ,						A					:						List[Any]       )  ->  str:
							if isinstance(A   ,						nn.Linear       ):
									module.weight.data.normal_(mean=0.0   ,						std=self.config.initializer_range       )
									if module.bias is not None:
											module.bias.data.zero_()
							elif isinstance(A   ,						nn.Embedding       ):
									module.weight.data.normal_(mean=0.0   ,						std=self.config.initializer_range       )
									if module.padding_idx is not None:
											module.weight.data[module.padding_idx].zero_()
							elif isinstance(A   ,						nn.LayerNorm       ):
									module.bias.data.zero_()
									module.weight.data.fill_(1.0       )
__A		:	Optional[int]      =		R'''

    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`RetriBertConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
'''





@add_start_docstrings(
    "Bert Based model to embed queries or document for document retrieval."       ,						_A       ,						)
class  _UpperCAmelCase	(			_A							):




					def __init__(    self					:						List[str]   ,						A					:						RetriBertConfig       )  ->  None:
							super().__init__(A       )
							lowercase_			:			List[str]								=       config.projection_dim

							lowercase_			:			str								=       BertModel(A       )
							lowercase_			:			Union[str, Any]								=       None if config.share_encoders else BertModel(A       )
							lowercase_			:			Optional[Any]								=       nn.Dropout(config.hidden_dropout_prob       )
							lowercase_			:			Optional[int]								=       nn.Linear(config.hidden_size   ,						config.projection_dim   ,						bias=A       )
							lowercase_			:			int								=       nn.Linear(config.hidden_size   ,						config.projection_dim   ,						bias=A       )

							lowercase_			:			Dict								=       nn.CrossEntropyLoss(reduction='''mean'''       )

							# Initialize weights and apply final processing
							self.post_init()




					def   A  (    self					:						List[str]   ,						A					:						Optional[Any]   ,						A					:						List[str]   ,						A					:						int   ,						A					:						Dict=-1   ,						)  ->  Optional[int]:
							# reproduces BERT forward pass with checkpointing
							if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size:
									return sent_encoder(A   ,						attention_mask=A       )[1]
							else:
									# prepare implicit variables
									lowercase_			:			List[str]								=       input_ids.device
									lowercase_			:			Dict								=       input_ids.size()
									lowercase_			:			Any								=       torch.zeros(A   ,						dtype=torch.long   ,						device=A       )
									lowercase_			:			str								=       [None] * sent_encoder.config.num_hidden_layers
									lowercase_			:			torch.Tensor								=       sent_encoder.get_extended_attention_mask(
									    A   ,						A       )

									# define function for checkpointing
									def partial_encode(*A					:						Optional[int]       ):
											lowercase_			:			Any								=       sent_encoder.encoder(
											    inputs[0]   ,						attention_mask=inputs[1]   ,						head_mask=A   ,						)
											lowercase_			:			Tuple								=       encoder_outputs[0]
											lowercase_			:			Dict								=       sent_encoder.pooler(A       )
											return pooled_output

									# run embedding layer on everything at once
									lowercase_			:			Union[str, Any]								=       sent_encoder.embeddings(
									    input_ids=A   ,						position_ids=A   ,						token_type_ids=A   ,						inputs_embeds=A       )
									# run encoding and pooling on one mini-batch at a time
									lowercase_			:			Any								=       []
									for b in range(math.ceil(input_ids.shape[0] / checkpoint_batch_size       )       ):
											lowercase_			:			Any								=       embedding_output[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
											lowercase_			:			str								=       extended_attention_mask[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
											lowercase_			:			int								=       checkpoint.checkpoint(A   ,						A   ,						A       )
											pooled_output_list.append(A       )
									return torch.cat(A   ,						dim=0       )




					def   A  (    self					:						Tuple   ,						A					:						Union[str, Any]   ,						A					:						Any=None   ,						A					:						str=-1   ,						)  ->  List[str]:
							lowercase_			:			List[Any]								=       self.embed_sentences_checkpointed(
							    A   ,						A   ,						self.bert_query   ,						A   ,						)
							return self.project_query(A       )




					def   A  (    self					:						str   ,						A					:						Union[str, Any]   ,						A					:						List[str]=None   ,						A					:						Union[str, Any]=-1   ,						)  ->  List[str]:
							lowercase_			:			Dict								=       self.embed_sentences_checkpointed(
							    A   ,						A   ,						self.bert_query if self.bert_doc is None else self.bert_doc   ,						A   ,						)
							return self.project_doc(A       )






					def   A  (    self					:						Union[str, Any]   ,						A					:						torch.LongTensor   ,						A					:						Optional[torch.FloatTensor]   ,						A					:						torch.LongTensor   ,						A					:						Optional[torch.FloatTensor]   ,						A					:						int = -1   ,						)  ->  torch.FloatTensor:
							lowercase_			:			Union[str, Any]								=       input_ids_query.device
							lowercase_			:			str								=       self.embed_questions(A   ,						A   ,						A       )
							lowercase_			:			int								=       self.embed_answers(A   ,						A   ,						A       )
							lowercase_			:			Any								=       torch.mm(A   ,						a_reps.t()       )
							lowercase_			:			str								=       self.ce_loss(A   ,						torch.arange(compare_scores.shape[1]       ).to(A       )       )
							lowercase_			:			Optional[Any]								=       self.ce_loss(compare_scores.t()   ,						torch.arange(compare_scores.shape[0]       ).to(A       )       )
							lowercase_			:			Tuple								=       (loss_qa + loss_aq) / 2
							return loss











"""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 						lowercase   (    ):
		lowercase_			:			Tuple								=       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"]:
				lowercase_			:			str								=       getattr(transformers.models.auto		, __snake_case		, __snake_case     )
				if module is None:
						continue
				# all mappings in a single auto modeling file
				lowercase_			:			Tuple								=       [
				    x
				    for x in dir(__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:
						lowercase_			:			Tuple								=       getattr(__snake_case		, __snake_case     )
						if mapping is not None:
								for v in mapping.values():
										if isinstance(__snake_case		, (list, tuple)     ):
												model_names.update(__snake_case     )
										elif isinstance(__snake_case		, __snake_case     ):
												model_names.add(__snake_case     )

		return sorted(__snake_case     )



def 						lowercase   (    ):
		# All model names defined in auto mappings
		lowercase_			:			Tuple								=       set(get_all_model_names()     )

		with open('''tests/utils/tiny_model_summary.json'''     ) as fp:
				lowercase_			:			Tuple								=       json.load(__snake_case     )
		lowercase_			:			Union[str, Any]								=       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.
		lowercase_			:			Union[str, Any]								=       model_names.difference(__snake_case     )
		for model_name in copy.copy(__snake_case     ):
				if not model_name.startswith('''TF'''     ) and F'''TF{model_name}''' in not_on_hub:
						tiny_models_names.remove(__snake_case     )
				elif model_name.startswith('''TF'''     ) and model_name[2:] in not_on_hub:
						tiny_models_names.remove(__snake_case     )

		return sorted(__snake_case     )



def 						lowercase   (    __snake_case    :			List[Any]     ):
		lowercase_			:			List[str]								=       COMPOSITE_MODELS.values()

		# All tiny model base names on Hub
		lowercase_			:			List[Any]								=       get_all_model_names()
		lowercase_			:			Tuple								=       hf_api.list_models(
		    filter=ModelFilter(
		        author='''hf-internal-testing'''		, )     )
		lowercase_			:			Tuple								=       set()
		for x in models:
				lowercase_			:			Tuple								=       x.modelId
				lowercase_	, lowercase_			:			Tuple								=       model.split('''/'''     )
				if not model.startswith('''tiny-random-'''     ):
						continue
				lowercase_			:			List[str]								=       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(__snake_case     )

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

				lowercase_			:			Dict								=       sorted(content['''tokenizer_classes''']     )
				lowercase_			:			Any								=       sorted(content['''processor_classes''']     )
				lowercase_			:			Union[str, Any]								=       sorted(content['''model_classes''']     )

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


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

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

						__A		:	List[str]      =		'''tiny_models'''
						__A		:	List[str]      =		True
						__A		:	int      =		None
						__A		:	Dict      =		get_tiny_model_names_from_repo()
						__A		:	Union[str, Any]      =		True
						__A		:	str      =		True
						__A		:	Optional[Any]      =		'''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,
						)



