




from typing import Dict, List, Optional, Tuple, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    flip_channel_order,
    get_resize_output_image_size,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_torch_available, is_torch_tensor, is_vision_available, logging


if is_vision_available():
				import PIL

if is_torch_available():
				import torch


UpperCamelCase__         =      logging.get_logger(__name__)
class       a__   ( UpperCAmelCase_				):
						_a							:   Dict =   ["""pixel_values"""]






						def __init__(       self		,      _A = True		,      _A = None		,      _A = PILImageResampling.BILINEAR		,      _A = True		,      _A = 1 / 2_5_5		,      _A = True		,      _A = None		,      _A = True		,      **_A		,      ):




											"""simple docstring"""



											super().__init__(**__lowercase      )
											__lowerCAmelCase           =	size if size is not None else {'''shortest_edge''': 2_2_4}
											__lowerCAmelCase           =	get_size_dict(__lowercase		,      default_to_square=__lowercase      )
											__lowerCAmelCase           =	crop_size if crop_size is not None else {'''height''': 2_5_6, '''width''': 2_5_6}
											__lowerCAmelCase           =	get_size_dict(__lowercase		,      param_name="crop_size"      )

											__lowerCAmelCase           =	do_resize
											__lowerCAmelCase           =	size
											__lowerCAmelCase           =	resample
											__lowerCAmelCase           =	do_rescale
											__lowerCAmelCase           =	rescale_factor
											__lowerCAmelCase           =	do_center_crop
											__lowerCAmelCase           =	crop_size
											__lowerCAmelCase           =	do_flip_channel_order






						def     __SCREAMING_SNAKE_CASE(       self		,      _A		,      _A		,      _A = PIL.Image.BILINEAR		,      _A = None		,      **_A		,      ):




											"""simple docstring"""



											__lowerCAmelCase           =	get_size_dict(__lowercase		,      default_to_square=__lowercase      )
											if "shortest_edge" not in size:
																raise ValueError(f"""The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}"""      )
											__lowerCAmelCase           =	get_resize_output_image_size(__lowercase		,      size=size["shortest_edge"]		,      default_to_square=__lowercase      )
											return resize(__lowercase		,      size=__lowercase		,      resample=__lowercase		,      data_format=__lowercase		,      **__lowercase      )






						def     __SCREAMING_SNAKE_CASE(       self		,      _A		,      _A		,      _A = None		,      **_A		,      ):




											"""simple docstring"""



											__lowerCAmelCase           =	get_size_dict(__lowercase      )
											if "height" not in size or "width" not in size:
																raise ValueError(f"""The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}"""      )
											return center_crop(__lowercase		,      size=(size["height"], size["width"])		,      data_format=__lowercase		,      **__lowercase      )






						def     __SCREAMING_SNAKE_CASE(       self		,      _A		,      _A		,      _A = None		,      **_A		,      ):




											"""simple docstring"""



											return rescale(__lowercase		,      scale=__lowercase		,      data_format=__lowercase		,      **__lowercase      )






						def     __SCREAMING_SNAKE_CASE(       self		,      _A		,      _A = None      ):




											"""simple docstring"""



											return flip_channel_order(__lowercase		,      data_format=__lowercase      )






						def     __SCREAMING_SNAKE_CASE(       self		,      _A		,      _A = None		,      _A = None		,      _A = None		,      _A = None		,      _A = None		,      _A = None		,      _A = None		,      _A = None		,      _A = None		,      _A = ChannelDimension.FIRST		,      **_A		,      ):




											"""simple docstring"""



											__lowerCAmelCase           =	do_resize if do_resize is not None else self.do_resize
											__lowerCAmelCase           =	resample if resample is not None else self.resample
											__lowerCAmelCase           =	do_rescale if do_rescale is not None else self.do_rescale
											__lowerCAmelCase           =	rescale_factor if rescale_factor is not None else self.rescale_factor
											__lowerCAmelCase           =	do_center_crop if do_center_crop is not None else self.do_center_crop
											__lowerCAmelCase           =	(
											    do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order
											)

											__lowerCAmelCase           =	size if size is not None else self.size
											__lowerCAmelCase           =	get_size_dict(__lowercase		,      default_to_square=__lowercase      )
											__lowerCAmelCase           =	crop_size if crop_size is not None else self.crop_size
											__lowerCAmelCase           =	get_size_dict(__lowercase		,      param_name="crop_size"      )

											__lowerCAmelCase           =	make_list_of_images(__lowercase      )

											if not valid_images(__lowercase      ):
																raise ValueError(
																    "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
																    "torch.Tensor, tf.Tensor or jax.ndarray."      )

											if do_resize and size is None:
																raise ValueError("Size must be specified if do_resize is True."      )

											if do_rescale and rescale_factor is None:
																raise ValueError("Rescale factor must be specified if do_rescale is True."      )

											if do_center_crop and crop_size is None:
																raise ValueError("Crop size must be specified if do_center_crop is True."      )

											# All transformations expect numpy arrays.
											__lowerCAmelCase           =	[to_numpy_array(__lowercase      ) for image in images]

											if do_resize:
																__lowerCAmelCase           =	[self.resize(image=__lowercase		,      size=__lowercase		,      resample=__lowercase      ) for image in images]

											if do_center_crop:
																__lowerCAmelCase           =	[self.center_crop(image=__lowercase		,      size=__lowercase      ) for image in images]

											if do_rescale:
																__lowerCAmelCase           =	[self.rescale(image=__lowercase		,      scale=__lowercase      ) for image in images]

											# the pretrained checkpoints assume images are BGR, not RGB
											if do_flip_channel_order:
																__lowerCAmelCase           =	[self.flip_channel_order(image=__lowercase      ) for image in images]

											__lowerCAmelCase           =	[to_channel_dimension_format(__lowercase		,      __lowercase      ) for image in images]

											__lowerCAmelCase           =	{'''pixel_values''': images}
											return BatchFeature(data=__lowercase		,      tensor_type=__lowercase      )






						def     __SCREAMING_SNAKE_CASE(       self		,      _A		,      _A = None      ):




											"""simple docstring"""



											__lowerCAmelCase           =	outputs.logits

											# Resize logits and compute semantic segmentation maps
											if target_sizes is not None:
																if len(__lowercase      ) != len(__lowercase      ):
																					raise ValueError(
																					    "Make sure that you pass in as many target sizes as the batch dimension of the logits"      )

																if is_torch_tensor(__lowercase      ):
																					__lowerCAmelCase           =	target_sizes.numpy()

																__lowerCAmelCase           =	[]

																for idx in range(len(__lowercase      )      ):
																					__lowerCAmelCase           =	torch.nn.functional.interpolate(
																					    logits[idx].unsqueeze(dim=0      )		,      size=target_sizes[idx]		,      mode="bilinear"		,      align_corners=__lowercase      )
																					__lowerCAmelCase           =	resized_logits[0].argmax(dim=0      )
																					semantic_segmentation.append(__lowercase      )
											else:
																__lowerCAmelCase           =	logits.argmax(dim=1      )
																__lowerCAmelCase           =	[semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]      )]

											return semantic_segmentation










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       a__   ( datasets.Metric				):






						def     __SCREAMING_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     __SCREAMING_SNAKE_CASE(       self		,      _A		,      _A		,      _A = 1_6		,      _A = True		,      _A=None      ):




											"""simple docstring"""



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

											__lowerCAmelCase           =	AutoModelForCausalLM.from_pretrained(_A      )
											__lowerCAmelCase           =	model.to(_A      )

											__lowerCAmelCase           =	AutoTokenizer.from_pretrained(_A      )

											# 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:
																__lowerCAmelCase           =	list(tokenizer.special_tokens_map_extended.values()      )
																# check that the model already has at least one special token defined
																assert (
																    len(_A      ) > 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"
																__lowerCAmelCase           =	model.config.max_length - 1
											else:
																__lowerCAmelCase           =	model.config.max_length

											__lowerCAmelCase           =	tokenizer(
											    _A		,      add_special_tokens=_A		,      padding=_A		,      truncation=_A		,      max_length=_A		,      return_tensors="pt"		,      return_attention_mask=_A		,      ).to(_A      )

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

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

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

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

																__lowerCAmelCase           =	encoded_batch

																with torch.no_grad():
																					__lowerCAmelCase           =	model(_A		,      attention_mask=_A      ).logits

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

																__lowerCAmelCase           =	torch.expa(
																    (loss_fct(shift_logits.transpose(1		,      2      )		,      _A      ) * shift_attention_mask_batch).sum(1      )
																    / shift_attention_mask_batch.sum(1      )      )

																ppls += perplexity_batch.tolist()

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




