



"""simple docstring"""







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

import datasets
from datasets import logging


UpperCamelCase     =							"""\

"""

UpperCamelCase     =							"""
Perplexity (PPL) is one of the most common metrics for evaluating language models.
It is defined as the exponentiated average negative log-likelihood of a sequence.

For more information, see https://huggingface.co/docs/transformers/perplexity
"""

UpperCamelCase     =							"""
Args:
    model_id (str): model used for calculating Perplexity
            NOTE: Perplexity can only be calculated for causal language models.
                    This includes models such as gpt2, causal variations of bert,
                    causal versions of t5, and more (the full list can be found
                    in the AutoModelForCausalLM documentation here:
                    https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM )

    input_texts (list of str): input text, each separate text snippet
        is one list entry.
    batch_size (int): the batch size to run texts through the model. Defaults to 16.
    add_start_token (bool): whether to add the start token to the texts,
        so the perplexity can include the probability of the first word. Defaults to True.
    device (str): device to run on, defaults to 'cuda' when available
Returns:
    perplexity: dictionary containing the perplexity scores for the texts
        in the input list, as well as the mean perplexity. If one of the input texts is
        longer than the max input length of the model, then it is truncated to the
        max length for the perplexity computation.
Examples:
    Example 1:
        >>> perplexity = datasets.load_metric(\"perplexity\")
        >>> input_texts = [\"lorem ipsum\", \"Happy Birthday!\", \"Bienvenue\"]
        >>> results = perplexity.compute(model_id='gpt2',
        ...                              add_start_token=False,
        ...                              input_texts=input_texts) # doctest:+ELLIPSIS
        >>> print(list(results.keys()))
        ['perplexities', 'mean_perplexity']
        >>> print(round(results[\"mean_perplexity\"], 2))
        78.22
        >>> print(round(results[\"perplexities\"][0], 2))
        11.11

    Example 2:
        >>> perplexity = datasets.load_metric(\"perplexity\")
        >>> input_texts = datasets.load_dataset(\"wikitext\",
        ...                                     \"wikitext-2-raw-v1\",
        ...                                     split=\"test\")[\"text\"][:50] # doctest:+ELLIPSIS
        [...]
        >>> input_texts = [s for s in input_texts if s!='']
        >>> results = perplexity.compute(model_id='gpt2',
        ...                              input_texts=input_texts) # doctest:+ELLIPSIS
        >>> print(list(results.keys()))
        ['perplexities', 'mean_perplexity']
        >>> print(round(results[\"mean_perplexity\"], 2))
        60.35
        >>> print(round(results[\"perplexities\"][0], 2))
        81.12
"""






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

			"""simple docstring"""


			def   snake_case__	(      self		)      ->	Optional[Any]:
				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		)      ->	List[str]:
				if device is not None:
					assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu."
					if device == "gpu":
						A__											=					"cuda"
				else:
					A__											=					"cuda" if torch.cuda.is_available() else "cpu"

				A__											=					AutoModelForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE__		)
				A__											=					model.to(SCREAMING_SNAKE_CASE__		)

				A__											=					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:
					A__											=					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"
					A__											=					model.config.max_length - 1
				else:
					A__											=					model.config.max_length

				A__											=					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__		)

				A__											=					encodings["input_ids"]
				A__											=					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."

				A__											=					[]
				A__											=					CrossEntropyLoss(reduction="none"		)

				for start_index in logging.tqdm(range(0						,	len(SCREAMING_SNAKE_CASE__		)						,	SCREAMING_SNAKE_CASE__		)		):
					A__											=					min(start_index + batch_size						,	len(SCREAMING_SNAKE_CASE__		)		)
					A__											=					encoded_texts[start_index:end_index]
					A__											=					attn_masks[start_index:end_index]

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

					A__											=					encoded_batch

					with torch.no_grad():
						A__											=					model(SCREAMING_SNAKE_CASE__						,	attention_mask=SCREAMING_SNAKE_CASE__		).logits

					A__											=					out_logits[..., :-1, :].contiguous()
					A__											=					labels[..., 1:].contiguous()
					A__											=					attn_mask[..., 1:].contiguous()

					A__											=					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 collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import logging


if TYPE_CHECKING:
			from ...processing_utils import ProcessorMixin
			from ...utils import TensorType


UpperCamelCase     =							logging.get_logger(__name__)

UpperCamelCase     =							{
    """microsoft/layoutlmv3-base""": """https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json""",
}






class       UpperCamelCase__			(   _lowerCAmelCase      ):

			"""simple docstring"""


			A__	:					int							  =     "layoutlmv3"


			def __init__(      self						,	SCREAMING_SNAKE_CASE__=50265						,	SCREAMING_SNAKE_CASE__=768						,	SCREAMING_SNAKE_CASE__=12						,	SCREAMING_SNAKE_CASE__=12						,	SCREAMING_SNAKE_CASE__=3072						,	SCREAMING_SNAKE_CASE__="gelu"						,	SCREAMING_SNAKE_CASE__=0.1						,	SCREAMING_SNAKE_CASE__=0.1						,	SCREAMING_SNAKE_CASE__=512						,	SCREAMING_SNAKE_CASE__=2						,	SCREAMING_SNAKE_CASE__=0.0_2						,	SCREAMING_SNAKE_CASE__=1e-5						,	SCREAMING_SNAKE_CASE__=1						,	SCREAMING_SNAKE_CASE__=0						,	SCREAMING_SNAKE_CASE__=2						,	SCREAMING_SNAKE_CASE__=1024						,	SCREAMING_SNAKE_CASE__=128						,	SCREAMING_SNAKE_CASE__=128						,	SCREAMING_SNAKE_CASE__=True						,	SCREAMING_SNAKE_CASE__=32						,	SCREAMING_SNAKE_CASE__=128						,	SCREAMING_SNAKE_CASE__=64						,	SCREAMING_SNAKE_CASE__=256						,	SCREAMING_SNAKE_CASE__=True						,	SCREAMING_SNAKE_CASE__=True						,	SCREAMING_SNAKE_CASE__=True						,	SCREAMING_SNAKE_CASE__=224						,	SCREAMING_SNAKE_CASE__=3						,	SCREAMING_SNAKE_CASE__=16						,	SCREAMING_SNAKE_CASE__=None						,	**SCREAMING_SNAKE_CASE__						,	)      ->	Any:
				super().__init__(
				    vocab_size=SCREAMING_SNAKE_CASE__						,	hidden_size=SCREAMING_SNAKE_CASE__						,	num_hidden_layers=SCREAMING_SNAKE_CASE__						,	num_attention_heads=SCREAMING_SNAKE_CASE__						,	intermediate_size=SCREAMING_SNAKE_CASE__						,	hidden_act=SCREAMING_SNAKE_CASE__						,	hidden_dropout_prob=SCREAMING_SNAKE_CASE__						,	attention_probs_dropout_prob=SCREAMING_SNAKE_CASE__						,	max_position_embeddings=SCREAMING_SNAKE_CASE__						,	type_vocab_size=SCREAMING_SNAKE_CASE__						,	initializer_range=SCREAMING_SNAKE_CASE__						,	layer_norm_eps=SCREAMING_SNAKE_CASE__						,	pad_token_id=SCREAMING_SNAKE_CASE__						,	bos_token_id=SCREAMING_SNAKE_CASE__						,	eos_token_id=SCREAMING_SNAKE_CASE__						,	**SCREAMING_SNAKE_CASE__						,	)
				A__											=					max_ad_position_embeddings
				A__											=					coordinate_size
				A__											=					shape_size
				A__											=					has_relative_attention_bias
				A__											=					rel_pos_bins
				A__											=					max_rel_pos
				A__											=					has_spatial_attention_bias
				A__											=					rel_ad_pos_bins
				A__											=					max_rel_ad_pos
				A__											=					text_embed
				A__											=					visual_embed
				A__											=					input_size
				A__											=					num_channels
				A__											=					patch_size
				A__											=					classifier_dropout






class       UpperCamelCase__			(   _lowerCAmelCase      ):

			"""simple docstring"""


			A__	:					Union[str, Any]							  =     version.parse("1.12"      )


			@property
			def   snake_case__	(      self		)      ->	Mapping[str, Mapping[int, str]]:
				# The order of inputs is different for question answering and sequence classification
				if self.task in ["question-answering", "sequence-classification"]:
					return OrderedDict(
					    [
					        ("input_ids", {0: "batch", 1: "sequence"}),
					        ("attention_mask", {0: "batch", 1: "sequence"}),
					        ("bbox", {0: "batch", 1: "sequence"}),
					        ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
					    ]		)
				else:
					return OrderedDict(
					    [
					        ("input_ids", {0: "batch", 1: "sequence"}),
					        ("bbox", {0: "batch", 1: "sequence"}),
					        ("attention_mask", {0: "batch", 1: "sequence"}),
					        ("pixel_values", {0: "batch", 1: "num_channels"}),
					    ]		)


			@property
			def   snake_case__	(      self		)      ->	float:
				return 1e-5


			@property
			def   snake_case__	(      self		)      ->	int:
				return 12







			def   snake_case__	(      self						,	SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__ = -1						,	SCREAMING_SNAKE_CASE__ = -1						,	SCREAMING_SNAKE_CASE__ = False						,	SCREAMING_SNAKE_CASE__ = None						,	SCREAMING_SNAKE_CASE__ = 3						,	SCREAMING_SNAKE_CASE__ = 40						,	SCREAMING_SNAKE_CASE__ = 40						,	)      ->	Mapping[str, Any]:
				setattr(processor.image_processor						,	"apply_ocr"						,	SCREAMING_SNAKE_CASE__		)

				# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
				A__											=					compute_effective_axis_dimension(
				    SCREAMING_SNAKE_CASE__						,	fixed_dimension=OnnxConfig.default_fixed_batch						,	num_token_to_add=0		)
				# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
				A__											=					processor.tokenizer.num_special_tokens_to_add(SCREAMING_SNAKE_CASE__		)
				A__											=					compute_effective_axis_dimension(
				    SCREAMING_SNAKE_CASE__						,	fixed_dimension=OnnxConfig.default_fixed_sequence						,	num_token_to_add=SCREAMING_SNAKE_CASE__		)
				# Generate dummy inputs according to compute batch and sequence
				A__											=					[[" ".join([processor.tokenizer.unk_token]		) * seq_length]] * batch_size

				# Generate dummy bounding boxes
				A__											=					[[[48, 84, 73, 128]]] * batch_size

				# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
				# batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch)
				A__											=					self._generate_dummy_images(SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__		)

				A__											=					dict(
				    processor(
				        SCREAMING_SNAKE_CASE__						,	text=SCREAMING_SNAKE_CASE__						,	boxes=SCREAMING_SNAKE_CASE__						,	return_tensors=SCREAMING_SNAKE_CASE__						,	)		)

				return inputs




