





'''simple docstring'''






import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features


A__    :       Union[str, Any]              =logging.get_logger(__name__)

A__    :       Union[str, Any]              =list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
A__    :       Optional[Any]              =tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)




@dataclass
class 			UpperCAmelCase					:
      _lowercase:      str											=       field(
          default=snake_case_							,		metadata={'''help''': '''Model type selected in the list: ''' + ''', '''.join(snake_case_       )}       )
      _lowercase:      str											=       field(
          default=snake_case_							,		metadata={'''help''': '''The input data dir. Should contain the .json files for the SQuAD task.'''}       )
      _lowercase:      int											=       field(
          default=128							,		metadata={
              '''help''': (
                  '''The maximum total input sequence length after tokenization. Sequences longer '''
                  '''than this will be truncated, sequences shorter will be padded.'''
              )
          }							,		)
      _lowercase:      int											=       field(
          default=128							,		metadata={'''help''': '''When splitting up a long document into chunks, how much stride to take between chunks.'''}							,		)
      _lowercase:      int											=       field(
          default=64							,		metadata={
              '''help''': (
                  '''The maximum number of tokens for the question. Questions longer than this will '''
                  '''be truncated to this length.'''
              )
          }							,		)
      _lowercase:      int											=       field(
          default=30							,		metadata={
              '''help''': (
                  '''The maximum length of an answer that can be generated. This is needed because the start '''
                  '''and end predictions are not conditioned on one another.'''
              )
          }							,		)
      _lowercase:      bool											=       field(
          default=snake_case_							,		metadata={'''help''': '''Overwrite the cached training and evaluation sets'''}       )
      _lowercase:      bool											=       field(
          default=snake_case_							,		metadata={'''help''': '''If true, the SQuAD examples contain some that do not have an answer.'''}       )
      _lowercase:      float											=       field(
          default=0.0							,		metadata={'''help''': '''If null_score - best_non_null is greater than the threshold predict null.'''}       )
      _lowercase:      int											=       field(
          default=20							,		metadata={'''help''': '''If null_score - best_non_null is greater than the threshold predict null.'''}       )
      _lowercase:      int											=       field(
          default=0							,		metadata={
              '''help''': (
                  '''language id of input for language-specific xlm models (see'''
                  ''' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)'''
              )
          }							,		)
      _lowercase:      int											=       field(default=1							,		metadata={'''help''': '''multiple threads for converting example to features'''}       )




class 			UpperCAmelCase					(      snake_case_       ):
      _lowercase:      Dict											=       '''train'''
      _lowercase:      Tuple											=       '''dev'''




class 			UpperCAmelCase					(      snake_case_       ):
      _lowercase:      SquadDataTrainingArguments
      _lowercase:      List[SquadFeatures]
      _lowercase:      Split
      _lowercase:      bool




      def __init__(      self      :			Tuple      ,      __snake_case      :			SquadDataTrainingArguments      ,      __snake_case      :			PreTrainedTokenizer      ,      __snake_case      :			Optional[int] = None      ,      __snake_case      :			Union[str, Split] = Split.train      ,      __snake_case      :			Optional[bool] = False      ,      __snake_case      :			Optional[str] = None      ,      __snake_case      :			Optional[str] = "pt"      ,      )    ->				Optional[Any]:
            _lowerCAmelCase												=							args
            _lowerCAmelCase												=							is_language_sensitive
            _lowerCAmelCase												=							SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
            if isinstance(__snake_case      ,      __snake_case  ):
                  try:
                        _lowerCAmelCase												=							Split[mode]
                  except KeyError:
                        raise KeyError("""mode is not a valid split name"""  )
            _lowerCAmelCase												=							mode
            # Load data features from cache or dataset file
            _lowerCAmelCase												=							"""v2""" if args.version_2_with_negative else """v1"""
            _lowerCAmelCase												=							os.path.join(
                cache_dir if cache_dir is not None else args.data_dir      ,      f"cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}"      ,      )

            # Make sure only the first process in distributed training processes the dataset,
            # and the others will use the cache.
            _lowerCAmelCase												=							cached_features_file + """.lock"""
            with FileLock(__snake_case  ):
                  if os.path.exists(__snake_case  ) and not args.overwrite_cache:
                        _lowerCAmelCase												=							time.time()
                        _lowerCAmelCase												=							torch.load(__snake_case  )

                        # Legacy cache files have only features, while new cache files
                        # will have dataset and examples also.
                        _lowerCAmelCase												=							self.old_features["""features"""]
                        _lowerCAmelCase												=							self.old_features.get("""dataset"""      ,      __snake_case  )
                        _lowerCAmelCase												=							self.old_features.get("""examples"""      ,      __snake_case  )
                        logger.info(
                            f"Loading features from cached file {cached_features_file} [took %.3f s]"      ,      time.time() - start  )

                        if self.dataset is None or self.examples is None:
                              logger.warning(
                                  f"Deleting cached file {cached_features_file} will allow dataset and examples to be cached in"
                                  """ future run"""  )
                  else:
                        if mode == Split.dev:
                              _lowerCAmelCase												=							self.processor.get_dev_examples(args.data_dir  )
                        else:
                              _lowerCAmelCase												=							self.processor.get_train_examples(args.data_dir  )

                        _lowerCAmelCase					,							_lowerCAmelCase												=							squad_convert_examples_to_features(
                            examples=self.examples      ,      tokenizer=__snake_case      ,      max_seq_length=args.max_seq_length      ,      doc_stride=args.doc_stride      ,      max_query_length=args.max_query_length      ,      is_training=mode == Split.train      ,      threads=args.threads      ,      return_dataset=__snake_case      ,      )

                        _lowerCAmelCase												=							time.time()
                        torch.save(
                            {"""features""": self.features, """dataset""": self.dataset, """examples""": self.examples}      ,      __snake_case      ,      )
                        # ^ This seems to take a lot of time so I want to investigate why and how we can improve.
                        logger.info(
                            f"Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]"  )




      def __len__(      self      :			List[Any]  )    ->				Optional[int]:
            return len(self.features  )




      def __getitem__(      self      :			List[str]      ,      __snake_case      :			int  )    ->				Dict[str, torch.Tensor]:
            # Convert to Tensors and build dataset
            _lowerCAmelCase												=							self.features[i]

            _lowerCAmelCase												=							torch.tensor(feature.input_ids      ,      dtype=torch.long  )
            _lowerCAmelCase												=							torch.tensor(feature.attention_mask      ,      dtype=torch.long  )
            _lowerCAmelCase												=							torch.tensor(feature.token_type_ids      ,      dtype=torch.long  )
            _lowerCAmelCase												=							torch.tensor(feature.cls_index      ,      dtype=torch.long  )
            _lowerCAmelCase												=							torch.tensor(feature.p_mask      ,      dtype=torch.float  )
            _lowerCAmelCase												=							torch.tensor(feature.is_impossible      ,      dtype=torch.float  )

            _lowerCAmelCase												=							{
                """input_ids""": input_ids,
                """attention_mask""": attention_mask,
                """token_type_ids""": token_type_ids,
            }

            if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
                  del inputs["token_type_ids"]

            if self.args.model_type in ["xlnet", "xlm"]:
                  inputs.update({"""cls_index""": cls_index, """p_mask""": p_mask}  )
                  if self.args.version_2_with_negative:
                        inputs.update({"""is_impossible""": is_impossible}  )
                  if self.is_language_sensitive:
                        inputs.update({"""langs""": (torch.ones(input_ids.shape      ,      dtype=torch.intaa  ) * self.args.lang_id)}  )

            if self.mode == Split.train:
                  _lowerCAmelCase												=							torch.tensor(feature.start_position      ,      dtype=torch.long  )
                  _lowerCAmelCase												=							torch.tensor(feature.end_position      ,      dtype=torch.long  )
                  inputs.update({"""start_positions""": start_positions, """end_positions""": end_positions}  )

            return inputs













'''simple docstring'''






import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizer

from diffusers import (
    AltDiffusionImgaImgPipeline,
    AutoencoderKL,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()




class 			UpperCAmelCase					(      unittest.TestCase       ):




      def     lowercase__   (      self      :			Optional[int]  )    ->				Dict:
            # clean up the VRAM after each test
            super().tearDown()
            gc.collect()
            torch.cuda.empty_cache()




      @property
      def     lowercase__   (      self      :			List[Any]  )    ->				List[str]:
            _lowerCAmelCase												=							1
            _lowerCAmelCase												=							3
            _lowerCAmelCase												=							(32, 32)

            _lowerCAmelCase												=							floats_tensor((batch_size, num_channels) + sizes      ,      rng=random.Random(0  )  ).to(__snake_case  )
            return image




      @property
      def     lowercase__   (      self      :			int  )    ->				Union[str, Any]:
            torch.manual_seed(0  )
            _lowerCAmelCase												=							UNetaDConditionModel(
                block_out_channels=(32, 64)      ,      layers_per_block=2      ,      sample_size=32      ,      in_channels=4      ,      out_channels=4      ,      down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")      ,      up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")      ,      cross_attention_dim=32      ,      )
            return model




      @property
      def     lowercase__   (      self      :			Optional[int]  )    ->				List[str]:
            torch.manual_seed(0  )
            _lowerCAmelCase												=							AutoencoderKL(
                block_out_channels=[32, 64]      ,      in_channels=3      ,      out_channels=3      ,      down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]      ,      up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]      ,      latent_channels=4      ,      )
            return model




      @property
      def     lowercase__   (      self      :			Dict  )    ->				Optional[Any]:
            torch.manual_seed(0  )
            _lowerCAmelCase												=							RobertaSeriesConfig(
                hidden_size=32      ,      project_dim=32      ,      intermediate_size=37      ,      layer_norm_eps=1E-0_5      ,      num_attention_heads=4      ,      num_hidden_layers=5      ,      pad_token_id=1      ,      vocab_size=50_06      ,      )
            return RobertaSeriesModelWithTransformation(__snake_case  )




      @property
      def     lowercase__   (      self      :			Union[str, Any]  )    ->				str:
            def extract(*__snake_case      :			List[Any]      ,      **__snake_case      :			Any  ):




                  class 			UpperCAmelCase					:




                        def __init__(      self      :			Any  )    ->				Any:
                              _lowerCAmelCase												=							torch.ones([0]  )




                        def     lowercase__   (      self      :			Optional[Any]      ,      __snake_case      :			Tuple  )    ->				Dict:
                              self.pixel_values.to(__snake_case  )
                              return self




                  return Out()

            return extract




      def     lowercase__   (      self      :			List[str]  )    ->				Optional[int]:
            _lowerCAmelCase												=							"""cpu"""  # ensure determinism for the device-dependent torch.Generator
            _lowerCAmelCase												=							self.dummy_cond_unet
            _lowerCAmelCase												=							PNDMScheduler(skip_prk_steps=__snake_case  )
            _lowerCAmelCase												=							self.dummy_vae
            _lowerCAmelCase												=							self.dummy_text_encoder
            _lowerCAmelCase												=							XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""  )
            _lowerCAmelCase												=							77

            _lowerCAmelCase												=							self.dummy_image.to(__snake_case  )
            _lowerCAmelCase												=							init_image / 2 + 0.5

            # make sure here that pndm scheduler skips prk
            _lowerCAmelCase												=							AltDiffusionImgaImgPipeline(
                unet=__snake_case      ,      scheduler=__snake_case      ,      vae=__snake_case      ,      text_encoder=__snake_case      ,      tokenizer=__snake_case      ,      safety_checker=__snake_case      ,      feature_extractor=self.dummy_extractor      ,      )
            _lowerCAmelCase												=							VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor      ,      do_normalize=__snake_case  )
            _lowerCAmelCase												=							alt_pipe.to(__snake_case  )
            alt_pipe.set_progress_bar_config(disable=__snake_case  )

            _lowerCAmelCase												=							"""A painting of a squirrel eating a burger"""
            _lowerCAmelCase												=							torch.Generator(device=__snake_case  ).manual_seed(0  )
            _lowerCAmelCase												=							alt_pipe(
                [prompt]      ,      generator=__snake_case      ,      guidance_scale=6.0      ,      num_inference_steps=2      ,      output_type="""np"""      ,      image=__snake_case      ,      )

            _lowerCAmelCase												=							output.images

            _lowerCAmelCase												=							torch.Generator(device=__snake_case  ).manual_seed(0  )
            _lowerCAmelCase												=							alt_pipe(
                [prompt]      ,      generator=__snake_case      ,      guidance_scale=6.0      ,      num_inference_steps=2      ,      output_type="""np"""      ,      image=__snake_case      ,      return_dict=__snake_case      ,      )[0]

            _lowerCAmelCase												=							image[0, -3:, -3:, -1]
            _lowerCAmelCase												=							image_from_tuple[0, -3:, -3:, -1]

            assert image.shape == (1, 32, 32, 3)
            _lowerCAmelCase												=							np.array([0.44_27, 0.37_31, 0.42_49, 0.49_41, 0.45_46, 0.41_48, 0.41_93, 0.46_66, 0.44_99]  )

            assert np.abs(image_slice.flatten() - expected_slice  ).max() < 5E-3
            assert np.abs(image_from_tuple_slice.flatten() - expected_slice  ).max() < 5E-3




      @unittest.skipIf(torch_device != """cuda"""      ,      """This test requires a GPU"""  )
      def     lowercase__   (      self      :			Tuple  )    ->				str:
            _lowerCAmelCase												=							self.dummy_cond_unet
            _lowerCAmelCase												=							PNDMScheduler(skip_prk_steps=__snake_case  )
            _lowerCAmelCase												=							self.dummy_vae
            _lowerCAmelCase												=							self.dummy_text_encoder
            _lowerCAmelCase												=							XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""  )
            _lowerCAmelCase												=							77

            _lowerCAmelCase												=							self.dummy_image.to(__snake_case  )

            # put models in fp16
            _lowerCAmelCase												=							unet.half()
            _lowerCAmelCase												=							vae.half()
            _lowerCAmelCase												=							bert.half()

            # make sure here that pndm scheduler skips prk
            _lowerCAmelCase												=							AltDiffusionImgaImgPipeline(
                unet=__snake_case      ,      scheduler=__snake_case      ,      vae=__snake_case      ,      text_encoder=__snake_case      ,      tokenizer=__snake_case      ,      safety_checker=__snake_case      ,      feature_extractor=self.dummy_extractor      ,      )
            _lowerCAmelCase												=							VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor      ,      do_normalize=__snake_case  )
            _lowerCAmelCase												=							alt_pipe.to(__snake_case  )
            alt_pipe.set_progress_bar_config(disable=__snake_case  )

            _lowerCAmelCase												=							"""A painting of a squirrel eating a burger"""
            _lowerCAmelCase												=							torch.manual_seed(0  )
            _lowerCAmelCase												=							alt_pipe(
                [prompt]      ,      generator=__snake_case      ,      num_inference_steps=2      ,      output_type="""np"""      ,      image=__snake_case      ,      ).images

            assert image.shape == (1, 32, 32, 3)




      @unittest.skipIf(torch_device != """cuda"""      ,      """This test requires a GPU"""  )
      def     lowercase__   (      self      :			Optional[Any]  )    ->				Optional[Any]:
            _lowerCAmelCase												=							load_image(
                """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
                """/img2img/sketch-mountains-input.jpg"""  )
            # resize to resolution that is divisible by 8 but not 16 or 32
            _lowerCAmelCase												=							init_image.resize((7_60, 5_04)  )

            _lowerCAmelCase												=							"""BAAI/AltDiffusion"""
            _lowerCAmelCase												=							AltDiffusionImgaImgPipeline.from_pretrained(
                __snake_case      ,      safety_checker=__snake_case      ,      )
            pipe.to(__snake_case  )
            pipe.set_progress_bar_config(disable=__snake_case  )
            pipe.enable_attention_slicing()

            _lowerCAmelCase												=							"""A fantasy landscape, trending on artstation"""

            _lowerCAmelCase												=							torch.manual_seed(0  )
            _lowerCAmelCase												=							pipe(
                prompt=__snake_case      ,      image=__snake_case      ,      strength=0.75      ,      guidance_scale=7.5      ,      generator=__snake_case      ,      output_type="""np"""      ,      )
            _lowerCAmelCase												=							output.images[0]

            _lowerCAmelCase												=							image[2_55:2_58, 3_83:3_86, -1]

            assert image.shape == (5_04, 7_60, 3)
            _lowerCAmelCase												=							np.array([0.93_58, 0.93_97, 0.95_99, 0.99_01, 1.00_00, 1.00_00, 0.98_82, 1.00_00, 1.00_00]  )

            assert np.abs(image_slice.flatten() - expected_slice  ).max() < 1E-2




@slow
@require_torch_gpu
class 			UpperCAmelCase					(      unittest.TestCase       ):




      def     lowercase__   (      self      :			int  )    ->				Any:
            # clean up the VRAM after each test
            super().tearDown()
            gc.collect()
            torch.cuda.empty_cache()




      def     lowercase__   (      self      :			Dict  )    ->				Tuple:
            _lowerCAmelCase												=							load_image(
                """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
                """/img2img/sketch-mountains-input.jpg"""  )
            _lowerCAmelCase												=							init_image.resize((7_68, 5_12)  )
            _lowerCAmelCase												=							load_numpy(
                """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy"""  )

            _lowerCAmelCase												=							"""BAAI/AltDiffusion"""
            _lowerCAmelCase												=							AltDiffusionImgaImgPipeline.from_pretrained(
                __snake_case      ,      safety_checker=__snake_case      ,      )
            pipe.to(__snake_case  )
            pipe.set_progress_bar_config(disable=__snake_case  )
            pipe.enable_attention_slicing()

            _lowerCAmelCase												=							"""A fantasy landscape, trending on artstation"""

            _lowerCAmelCase												=							torch.manual_seed(0  )
            _lowerCAmelCase												=							pipe(
                prompt=__snake_case      ,      image=__snake_case      ,      strength=0.75      ,      guidance_scale=7.5      ,      generator=__snake_case      ,      output_type="""np"""      ,      )
            _lowerCAmelCase												=							output.images[0]

            assert image.shape == (5_12, 7_68, 3)
            # img2img is flaky across GPUs even in fp32, so using MAE here
            assert np.abs(expected_image - image  ).max() < 1E-2






