
'''simple docstring'''







import numpy as np
import torch
from torch.nn import CrossEntropyLoss
from transformers import AutoModelForCausalLM, AutoTokenizer

import datasets
from datasets import logging


_lowercase :  Union[str, Any]    							=       '\\n\n'

_lowercase :  List[str]    							=       '\nPerplexity (PPL) is one of the most common metrics for evaluating language models.\nIt is defined as the exponentiated average negative log-likelihood of a sequence.\n\nFor more information, see https://huggingface.co/docs/transformers/perplexity\n'

_lowercase :  Union[str, Any]    							=       '\nArgs:\n    model_id (str): model used for calculating Perplexity\n            NOTE: Perplexity can only be calculated for causal language models.\n                    This includes models such as gpt2, causal variations of bert,\n                    causal versions of t5, and more (the full list can be found\n                    in the AutoModelForCausalLM documentation here:\n                    https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM )\n\n    input_texts (list of str): input text, each separate text snippet\n        is one list entry.\n    batch_size (int): the batch size to run texts through the model. Defaults to 16.\n    add_start_token (bool): whether to add the start token to the texts,\n        so the perplexity can include the probability of the first word. Defaults to True.\n    device (str): device to run on, defaults to \'cuda\' when available\nReturns:\n    perplexity: dictionary containing the perplexity scores for the texts\n        in the input list, as well as the mean perplexity. If one of the input texts is\n        longer than the max input length of the model, then it is truncated to the\n        max length for the perplexity computation.\nExamples:\n    Example 1:\n        >>> perplexity = datasets.load_metric("perplexity")\n        >>> input_texts = ["lorem ipsum", "Happy Birthday!", "Bienvenue"]\n        >>> results = perplexity.compute(model_id=\'gpt2\',\n        ...                              add_start_token=False,\n        ...                              input_texts=input_texts) # doctest:+ELLIPSIS\n        >>> print(list(results.keys()))\n        [\'perplexities\', \'mean_perplexity\']\n        >>> print(round(results["mean_perplexity"], 2))\n        78.22\n        >>> print(round(results["perplexities"][0], 2))\n        11.11\n\n    Example 2:\n        >>> perplexity = datasets.load_metric("perplexity")\n        >>> input_texts = datasets.load_dataset("wikitext",\n        ...                                     "wikitext-2-raw-v1",\n        ...                                     split="test")["text"][:50] # doctest:+ELLIPSIS\n        [...]\n        >>> input_texts = [s for s in input_texts if s!=\'\']\n        >>> results = perplexity.compute(model_id=\'gpt2\',\n        ...                              input_texts=input_texts) # doctest:+ELLIPSIS\n        >>> print(list(results.keys()))\n        [\'perplexities\', \'mean_perplexity\']\n        >>> print(round(results["mean_perplexity"], 2))\n        60.35\n        >>> print(round(results["perplexities"][0], 2))\n        81.12\n'






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION    ,						_KWARGS_DESCRIPTION     )
class  lowerCAmelCase__   (  datasets.Metric     ):






					def 	_snake_case    (   self		):


											"""simple docstring"""





											return datasets.MetricInfo(
											    description=_DESCRIPTION				,							citation=_CITATION				,							inputs_description=_KWARGS_DESCRIPTION				,							features=datasets.Features(
											        {
											            '''input_texts''': datasets.Value('''string'''		),
											        }		)				,							reference_urls=['''https://huggingface.co/docs/transformers/perplexity''']				,							)






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE = 16				,							__SCREAMING_SNAKE_CASE = True				,							__SCREAMING_SNAKE_CASE=None		):


											"""simple docstring"""





											if device is not None:
																	assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu."
																	if device == "gpu":
																							lowercase_	:     Any													=       "cuda"
											else:
																	lowercase_	:     str													=       "cuda" if torch.cuda.is_available() else "cpu"

											lowercase_	:     Optional[int]													=       AutoModelForCausalLM.from_pretrained(_SCREAMING_SNAKE_CASE		)
											lowercase_	:     Union[str, Any]													=       model.to(_SCREAMING_SNAKE_CASE		)

											lowercase_	:     Optional[Any]													=       AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE		)

											# if batch_size > 1 (which generally leads to padding being required), and
											# if there is not an already assigned pad_token, assign an existing
											# special token to also be the padding token
											if tokenizer.pad_token is None and batch_size > 1:
																	lowercase_	:     List[Any]													=       list(tokenizer.special_tokens_map_extended.values()		)
																	# check that the model already has at least one special token defined
																	assert (
																	    len(_SCREAMING_SNAKE_CASE		) > 0
																	), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1."
																	# assign one of the special tokens to also be the pad token
																	tokenizer.add_special_tokens({'''pad_token''': existing_special_tokens[0]}		)

											if add_start_token:
																	# leave room for <BOS> token to be added:
																	assert (
																	    tokenizer.bos_token is not None
																	), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False"
																	lowercase_	:     Optional[Any]													=       model.config.max_length - 1
											else:
																	lowercase_	:     List[str]													=       model.config.max_length

											lowercase_	:     List[str]													=       tokenizer(
											    _SCREAMING_SNAKE_CASE				,							add_special_tokens=_SCREAMING_SNAKE_CASE				,							padding=_SCREAMING_SNAKE_CASE				,							truncation=_SCREAMING_SNAKE_CASE				,							max_length=_SCREAMING_SNAKE_CASE				,							return_tensors='''pt'''				,							return_attention_mask=_SCREAMING_SNAKE_CASE				,							).to(_SCREAMING_SNAKE_CASE		)

											lowercase_	:     str													=       encodings["input_ids"]
											lowercase_	:     Union[str, Any]													=       encodings["attention_mask"]

											# check that each input is long enough:
											if add_start_token:
																	assert torch.all(torch.ge(attn_masks.sum(1		)				,							1		)		), "Each input text must be at least one token long."
											else:
																	assert torch.all(
																	    torch.ge(attn_masks.sum(1		)				,							2		)		), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings."

											lowercase_	:     str													=       []
											lowercase_	:     List[str]													=       CrossEntropyLoss(reduction='''none'''		)

											for start_index in logging.tqdm(range(0				,							len(_SCREAMING_SNAKE_CASE		)				,							_SCREAMING_SNAKE_CASE		)		):
																	lowercase_	:     Union[str, Any]													=       min(start_index + batch_size				,							len(_SCREAMING_SNAKE_CASE		)		)
																	lowercase_	:     Optional[Any]													=       encoded_texts[start_index:end_index]
																	lowercase_	:     Dict													=       attn_masks[start_index:end_index]

																	if add_start_token:
																							lowercase_	:     Tuple													=       torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0		)		).to(_SCREAMING_SNAKE_CASE		)
																							lowercase_	:     Dict													=       torch.cat([bos_tokens_tensor, encoded_batch]				,							dim=1		)
																							lowercase_	:     Tuple													=       torch.cat(
																							    [torch.ones(bos_tokens_tensor.size()				,							dtype=torch.intaa		).to(_SCREAMING_SNAKE_CASE		), attn_mask]				,							dim=1		)

																	lowercase_	:     List[Any]													=       encoded_batch

																	with torch.no_grad():
																							lowercase_	:     Any													=       model(_SCREAMING_SNAKE_CASE				,							attention_mask=_SCREAMING_SNAKE_CASE		).logits

																	lowercase_	:     List[str]													=       out_logits[..., :-1, :].contiguous()
																	lowercase_	:     int													=       labels[..., 1:].contiguous()
																	lowercase_	:     str													=       attn_mask[..., 1:].contiguous()

																	lowercase_	:     Union[str, Any]													=       torch.expa(
																	    (loss_fct(shift_logits.transpose(1				,							2		)				,							_SCREAMING_SNAKE_CASE		) * shift_attention_mask_batch).sum(1		)
																	    / shift_attention_mask_batch.sum(1		)		)

																	ppls += perplexity_batch.tolist()

											return {"perplexities": ppls, "mean_perplexity": np.mean(_SCREAMING_SNAKE_CASE		)}








"""simple docstring"""






from ....configuration_utils import PretrainedConfig
from ....utils import logging


__snake_case							:   List[Any]      =    logging.get_logger(__name__)

__snake_case							:   Any      =    {
    'speechbrain/m-ctc-t-large': 'https://huggingface.co/speechbrain/m-ctc-t-large/resolve/main/config.json',
    # See all M-CTC-T models at https://huggingface.co/models?filter=mctct
}



class 			A__   (  __SCREAMING_SNAKE_CASE							):




	'''simple docstring'''





	SCREAMING_SNAKE_CASE          =	'mctct'

	def __init__(     self:		Union[str, Any]       ,			_SCREAMING_SNAKE_CASE:		str=8065       ,			_SCREAMING_SNAKE_CASE:		str=1536       ,			_SCREAMING_SNAKE_CASE:		str=36       ,			_SCREAMING_SNAKE_CASE:		Optional[Any]=6144       ,			_SCREAMING_SNAKE_CASE:		Optional[Any]=4       ,			_SCREAMING_SNAKE_CASE:		Union[str, Any]=384       ,			_SCREAMING_SNAKE_CASE:		Optional[Any]=920       ,			_SCREAMING_SNAKE_CASE:		Union[str, Any]=1e-5       ,			_SCREAMING_SNAKE_CASE:		List[Any]=0.3       ,			_SCREAMING_SNAKE_CASE:		Optional[Any]="relu"       ,			_SCREAMING_SNAKE_CASE:		Optional[int]=0.02       ,			_SCREAMING_SNAKE_CASE:		Optional[Any]=0.3       ,			_SCREAMING_SNAKE_CASE:		Dict=0.3       ,			_SCREAMING_SNAKE_CASE:		List[Any]=1       ,			_SCREAMING_SNAKE_CASE:		Optional[Any]=0       ,			_SCREAMING_SNAKE_CASE:		List[str]=2       ,			_SCREAMING_SNAKE_CASE:		Union[str, Any]=1       ,			_SCREAMING_SNAKE_CASE:		Tuple=0.3       ,			_SCREAMING_SNAKE_CASE:		Dict=1       ,			_SCREAMING_SNAKE_CASE:		int=(7,)       ,			_SCREAMING_SNAKE_CASE:		str=(3,)       ,			_SCREAMING_SNAKE_CASE:		Union[str, Any]=80       ,			_SCREAMING_SNAKE_CASE:		Tuple=1       ,			_SCREAMING_SNAKE_CASE:		Dict=None       ,			_SCREAMING_SNAKE_CASE:		Tuple="sum"       ,			_SCREAMING_SNAKE_CASE:		List[str]=False       ,			**_SCREAMING_SNAKE_CASE:		Tuple       ,			)				->       Tuple:

				"""simple docstring"""

				super().__init__(**_SCREAMING_SNAKE_CASE       ,			pad_token_id=_SCREAMING_SNAKE_CASE       ,			bos_token_id=_SCREAMING_SNAKE_CASE       ,			eos_token_id=_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase      :  str												=       vocab_size
				__lowerCAmelCase      :  str												=       hidden_size
				__lowerCAmelCase      :  str												=       num_hidden_layers
				__lowerCAmelCase      :  str												=       intermediate_size
				__lowerCAmelCase      :  List[Any]												=       num_attention_heads
				__lowerCAmelCase      :  Dict												=       attention_head_dim
				__lowerCAmelCase      :  Optional[int]												=       max_position_embeddings
				__lowerCAmelCase      :  str												=       layer_norm_eps
				__lowerCAmelCase      :  Tuple												=       layerdrop
				__lowerCAmelCase      :  str												=       hidden_act
				__lowerCAmelCase      :  List[Any]												=       initializer_range
				__lowerCAmelCase      :  int												=       hidden_dropout_prob
				__lowerCAmelCase      :  Optional[Any]												=       attention_probs_dropout_prob
				__lowerCAmelCase      :  str												=       pad_token_id
				__lowerCAmelCase      :  Optional[int]												=       bos_token_id
				__lowerCAmelCase      :  Union[str, Any]												=       eos_token_id
				__lowerCAmelCase      :  Any												=       conv_glu_dim
				__lowerCAmelCase      :  Optional[int]												=       conv_dropout
				__lowerCAmelCase      :  Union[str, Any]												=       num_conv_layers
				__lowerCAmelCase      :  Optional[int]												=       input_feat_per_channel
				__lowerCAmelCase      :  Union[str, Any]												=       input_channels
				__lowerCAmelCase      :  Optional[Any]												=       conv_channels
				__lowerCAmelCase      :  Dict												=       ctc_loss_reduction
				__lowerCAmelCase      :  int												=       ctc_zero_infinity

				# prevents config testing fail with exporting to json
				__lowerCAmelCase      :  List[str]												=       list(_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase      :  Dict												=       list(_SCREAMING_SNAKE_CASE)

				if len(self.conv_kernel) != self.num_conv_layers:
							raise ValueError(
							    "Configuration for convolutional module is incorrect. "
							    "It is required that `len(config.conv_kernel)` == `config.num_conv_layers` "
							    F"""but is `len(config.conv_kernel) = {len(self.conv_kernel)}`, """
							    F"""`config.num_conv_layers = {self.num_conv_layers}`.""")