




import logging
import pathlib
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Set, Union

import datasets
import librosa
import numpy as np
import torch
from lang_trans import arabic
from packaging import version
from torch import nn

from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    trainer_utils,
)


if is_apex_available():
 from apex import amp

if version.parse(version.parse(torch.__version__).base_version) >= version.parse('''1.6'''):
 SCREAMING_SNAKE_CASE_    :       List[str]       =							True
 from torch.cuda.amp import autocast


SCREAMING_SNAKE_CASE_    :       Optional[int]       =							logging.getLogger(__name__)







@dataclass
class 		__UpperCAmelCase:





     """simple docstring"""



     __UpperCAmelCase						:			str							=     field(
         metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}			)
     __UpperCAmelCase						:			Optional[str]							=     field(
         default=lowercase__							,						metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}							,						)
     __UpperCAmelCase						:			Optional[bool]							=     field(
         default=lowercase__							,						metadata={"""help""": """Whether to freeze the feature extractor layers of the model."""}			)
     __UpperCAmelCase						:			Optional[bool]							=     field(
         default=lowercase__							,						metadata={"""help""": """Whether to log verbose messages or not."""}							,						)






def 							__lowerCAmelCase			(UpperCAmelCase_ ,     UpperCAmelCase_		):
    logging.basicConfig(
        format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" ,     datefmt="""%m/%d/%Y %H:%M:%S""" ,     handlers=[logging.StreamHandler(sys.stdout		)] ,     )
    a__  			=							logging.WARNING
    if model_args.verbose_logging:
        a__  			=							logging.DEBUG
    elif trainer_utils.is_main_process(training_args.local_rank		):
        a__  			=							logging.INFO
    logger.setLevel(UpperCAmelCase_		)







@dataclass
class 		__UpperCAmelCase:





     """simple docstring"""



     __UpperCAmelCase						:			str							=     field(
         default=lowercase__							,						metadata={"""help""": """The name of the dataset to use (via the datasets library)."""}			)
     __UpperCAmelCase						:			Optional[str]							=     field(
         default=lowercase__							,						metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""}			)
     __UpperCAmelCase						:			Optional[str]							=     field(
         default="""train"""							,						metadata={
             """help""": """The name of the training data set split to use (via the datasets library). Defaults to 'train'"""
         }							,						)
     __UpperCAmelCase						:			Optional[str]							=     field(
         default="""validation"""							,						metadata={
             """help""": (
                 """The name of the validation data set split to use (via the datasets library). Defaults to 'validation'"""
             )
         }							,						)
     __UpperCAmelCase						:			Optional[str]							=     field(
         default="""text"""							,						metadata={"""help""": """Column in the dataset that contains label (target text). Defaults to 'text'"""}							,						)
     __UpperCAmelCase						:			Optional[str]							=     field(
         default="""file"""							,						metadata={"""help""": """Column in the dataset that contains speech file path. Defaults to 'file'"""}							,						)
     __UpperCAmelCase						:			Optional[bool]							=     field(
         default=lowercase__							,						metadata={"""help""": """Resample loaded audio to target feature extractor's sampling rate or not."""}							,						)
     __UpperCAmelCase						:			Optional[float]							=     field(
         default=lowercase__							,						metadata={"""help""": """Filters out examples longer than specified. Defaults to no filtering."""}							,						)
     __UpperCAmelCase						:			Optional[str]							=     field(
         default="""librispeech"""							,						metadata={
             """help""": (
                 """Orthography used for normalization and tokenization: 'librispeech' (default), 'timit', or"""
                 """ 'buckwalter'."""
             )
         }							,						)
     __UpperCAmelCase						:			bool							=     field(
         default=lowercase__							,						metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""}			)
     __UpperCAmelCase						:			Optional[int]							=     field(
         default=lowercase__							,						metadata={"""help""": """The number of processes to use for the preprocessing."""}							,						)







@dataclass
class 		__UpperCAmelCase:





     """simple docstring"""



     __UpperCAmelCase						:			bool							=     False
     __UpperCAmelCase						:			Optional[str]							=     None
     __UpperCAmelCase						:			Optional[str]							=     "|"
     __UpperCAmelCase						:			Optional[Dict[str, str]]							=     field(default_factory=lowercase__			)
     __UpperCAmelCase						:			Optional[Set[str]]							=     field(default_factory=lowercase__			)
     __UpperCAmelCase						:			Optional[Callable[[str], str]]							=     None

     @classmethod
     def 					__SCREAMING_SNAKE_CASE		(   cls			:							Optional[int]    ,					A			:							str     )      ->      Union[str, Any]:






         """simple docstring"""
         if name == "librispeech":
             return cls()
         if name == "timit":
             return cls(
                 do_lower_case=A    ,					translation_table=str.maketrans({"""-""": """ """}     )    ,					)
         if name == "buckwalter":
             a__  			=							{
                 """-""": """ """,  # sometimes used to represent pauses
                 """^""": """v""",  # fixing "tha" in arabic_speech_corpus dataset
             }
             return cls(
                 vocab_file=pathlib.Path(A     ).parent.joinpath("""vocab/buckwalter.json"""     )    ,					word_delimiter_token="""/"""    ,					translation_table=str.maketrans(A     )    ,					words_to_remove={"""sil"""}    ,					untransliterator=arabic.buckwalter.untransliterate    ,					)
         raise ValueError(f"""Unsupported orthography: '{name}'."""     )

     def 					__SCREAMING_SNAKE_CASE		(   self			:							int    ,					A			:							str     )      ->      str:






         """simple docstring"""
         # TODO(elgeish) return a pipeline (e.g., from jiwer) instead? Or rely on branch predictor as is
         if len(self.translation_table     ) > 0:
             a__  			=							text.translate(self.translation_table     )
         if len(self.words_to_remove     ) == 0:
             a__  			=							""" """.join(text.split()     )  # clean up whitespaces
         else:
             a__  			=							""" """.join(w for w in text.split() if w not in self.words_to_remove     )  # and clean up whilespaces
         return text






     def 					__SCREAMING_SNAKE_CASE		(   self			:							str    ,					A			:							ModelArguments     )      ->      WavaVecaProcessor:






         """simple docstring"""
         a__  			=							WavaVecaFeatureExtractor.from_pretrained(
             model_args.model_name_or_path    ,					cache_dir=model_args.cache_dir     )
         if self.vocab_file:
             a__  			=							WavaVecaCTCTokenizer(
                 self.vocab_file    ,					cache_dir=model_args.cache_dir    ,					do_lower_case=self.do_lower_case    ,					word_delimiter_token=self.word_delimiter_token    ,					)
         else:
             a__  			=							WavaVecaCTCTokenizer.from_pretrained(
                 model_args.model_name_or_path    ,					cache_dir=model_args.cache_dir    ,					do_lower_case=self.do_lower_case    ,					word_delimiter_token=self.word_delimiter_token    ,					)
         return WavaVecaProcessor(A    ,					A     )







@dataclass
class 		__UpperCAmelCase:





     """simple docstring"""



     __UpperCAmelCase						:			WavaVecaProcessor
     __UpperCAmelCase						:			Union[bool, str]							=     True
     __UpperCAmelCase						:			Optional[int]							=     None
     __UpperCAmelCase						:			Optional[int]							=     None
     __UpperCAmelCase						:			Optional[int]							=     None
     __UpperCAmelCase						:			Optional[int]							=     None

     def __call__(   self			:							Dict    ,					A			:							List[Dict[str, Union[List[int], torch.Tensor]]]     )      ->      Dict[str, torch.Tensor]:






         """simple docstring"""
         # split inputs and labels since they have to be of different lenghts and need
         # different padding methods
         a__  			=							[{"""input_values""": feature["""input_values"""]} for feature in features]
         a__  			=							[{"""input_ids""": feature["""labels"""]} for feature in features]

         a__  			=							self.processor.pad(
             A    ,					padding=self.padding    ,					max_length=self.max_length    ,					pad_to_multiple_of=self.pad_to_multiple_of    ,					return_tensors="""pt"""    ,					)
         a__  			=							self.processor.pad(
             labels=A    ,					padding=self.padding    ,					max_length=self.max_length_labels    ,					pad_to_multiple_of=self.pad_to_multiple_of_labels    ,					return_tensors="""pt"""    ,					)

         # replace padding with -100 to ignore loss correctly
         a__  			=							labels_batch["""input_ids"""].masked_fill(labels_batch.attention_mask.ne(1     )    ,					-1_00     )

         a__  			=							labels

         return batch







class 		__UpperCAmelCase(		lowercase__			):





     """simple docstring"""



     def 					__SCREAMING_SNAKE_CASE		(   self			:							Tuple    ,					A			:							nn.Module    ,					A			:							Dict[str, Union[torch.Tensor, Any]]     )      ->      torch.Tensor:






         """simple docstring"""
         model.train()
         a__  			=							self._prepare_inputs(A     )

         if self.use_amp:
             with autocast():
                 a__  			=							self.compute_loss(A    ,					A     )
         else:
             a__  			=							self.compute_loss(A    ,					A     )

         if self.args.n_gpu > 1:
             if model.module.config.ctc_loss_reduction == "mean":
                 a__  			=							loss.mean()
             elif model.module.config.ctc_loss_reduction == "sum":
                 a__  			=							loss.sum() / (inputs["""labels"""] >= 0).sum()
             else:
                 raise ValueError(f"""{model.config.ctc_loss_reduction} is not valid. Choose one of ['mean', 'sum']"""     )

         if self.args.gradient_accumulation_steps > 1:
             a__  			=							loss / self.args.gradient_accumulation_steps

         if self.use_amp:
             self.scaler.scale(A     ).backward()
         elif self.use_apex:
             with amp.scale_loss(A    ,					self.optimizer     ) as scaled_loss:
                 scaled_loss.backward()
         elif self.deepspeed:
             self.deepspeed.backward(A     )
         else:
             loss.backward()

         return loss.detach()






def 							__lowerCAmelCase			():
    # See all possible arguments in src/transformers/training_args.py
    # or by passing the --help flag to this script.
    # We now keep distinct sets of args, for a cleaner separation of concerns.

    a__  			=							HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)		)

    a__			,		a__			,		a__  			=							parser.parse_args_into_dataclasses()
    configure_logger(UpperCAmelCase_ ,     UpperCAmelCase_		)

    a__  			=							Orthography.from_name(data_args.orthography.lower()		)
    a__  			=							orthography.create_processor(UpperCAmelCase_		)
    a__  			=							WavaVecaForCTC.from_pretrained(
        model_args.model_name_or_path ,     cache_dir=model_args.cache_dir ,     gradient_checkpointing=training_args.gradient_checkpointing ,     vocab_size=len(processor.tokenizer		) ,     )

    a__  			=							datasets.load_dataset(
        data_args.dataset_name ,     data_args.dataset_config_name ,     split=data_args.train_split_name		)
    a__  			=							datasets.load_dataset(
        data_args.dataset_name ,     data_args.dataset_config_name ,     split=data_args.validation_split_name		)

    a__  			=							datasets.load_metric("""wer"""		)
    a__  			=							processor.feature_extractor.sampling_rate if data_args.target_feature_extractor_sampling_rate else None
    a__  			=							"""""".join(t for t in processor.tokenizer.get_vocab().keys() if len(UpperCAmelCase_		) == 1		)
    a__  			=							re.compile(  # remove characters not in vocabulary
        rF"""[^\s{re.escape(UpperCAmelCase_		)}]""" ,     flags=re.IGNORECASE if processor.tokenizer.do_lower_case else 0 ,     )
    a__  			=							[]

    def prepare_example(UpperCAmelCase_		):  # TODO(elgeish) make use of multiprocessing?
        a__			,		a__  			=							librosa.load(example[data_args.speech_file_column] ,     sr=UpperCAmelCase_		)
        if data_args.max_duration_in_seconds is not None:
            a__  			=							len(example["""speech"""]		) / example["""sampling_rate"""]
        # Normalize and clean up text; order matters!
        a__  			=							orthography.preprocess_for_training(example[data_args.target_text_column]		)
        a__  			=							vocabulary_text_cleaner.sub("""""" ,     UpperCAmelCase_		)
        if updated_text != example[data_args.target_text_column]:
            text_updates.append((example[data_args.target_text_column], updated_text)		)
            a__  			=							updated_text
        return example

    a__  			=							train_dataset.map(UpperCAmelCase_ ,     remove_columns=[data_args.speech_file_column]		)
    a__  			=							val_dataset.map(UpperCAmelCase_ ,     remove_columns=[data_args.speech_file_column]		)

    if data_args.max_duration_in_seconds is not None:

        def filter_by_max_duration(UpperCAmelCase_		):
            return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

        a__  			=							len(UpperCAmelCase_		)
        a__  			=							len(UpperCAmelCase_		)
        a__  			=							train_dataset.filter(UpperCAmelCase_ ,     remove_columns=["""duration_in_seconds"""]		)
        a__  			=							val_dataset.filter(UpperCAmelCase_ ,     remove_columns=["""duration_in_seconds"""]		)
        if len(UpperCAmelCase_		) > old_train_size:
            logger.warning(
                F"""Filtered out {len(UpperCAmelCase_		) - old_train_size} train example(s) longer than"""
                F""" {data_args.max_duration_in_seconds} second(s)."""		)
        if len(UpperCAmelCase_		) > old_val_size:
            logger.warning(
                F"""Filtered out {len(UpperCAmelCase_		) - old_val_size} validation example(s) longer than"""
                F""" {data_args.max_duration_in_seconds} second(s)."""		)
    logger.info(F"""Split sizes: {len(UpperCAmelCase_		)} train and {len(UpperCAmelCase_		)} validation."""		)

    logger.warning(F"""Updated {len(UpperCAmelCase_		)} transcript(s) using '{data_args.orthography}' orthography rules."""		)
    if logger.isEnabledFor(logging.DEBUG		):
        for original_text, updated_text in text_updates:
            logger.debug(F"""Updated text: \"{original_text}\" -> \"{updated_text}\""""		)
    a__  			=							None

    def prepare_dataset(UpperCAmelCase_		):
        # check that all files have the correct sampling rate
        assert (
            len(set(batch["""sampling_rate"""]		)		) == 1
        ), F"""Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}."""

        a__  			=							processor(
            audio=batch["""speech"""] ,     text=batch[data_args.target_text_column] ,     sampling_rate=batch["""sampling_rate"""][0]		)
        batch.update(UpperCAmelCase_		)
        return batch

    a__  			=							train_dataset.map(
        UpperCAmelCase_ ,     batch_size=training_args.per_device_train_batch_size ,     batched=UpperCAmelCase_ ,     num_proc=data_args.preprocessing_num_workers ,     )
    a__  			=							val_dataset.map(
        UpperCAmelCase_ ,     batch_size=training_args.per_device_train_batch_size ,     batched=UpperCAmelCase_ ,     num_proc=data_args.preprocessing_num_workers ,     )

    a__  			=							DataCollatorCTCWithPadding(processor=UpperCAmelCase_ ,     padding=UpperCAmelCase_		)

    def compute_metrics(UpperCAmelCase_		):
        a__  			=							pred.predictions
        a__  			=							np.argmax(UpperCAmelCase_ ,     axis=-1		)

        a__  			=							processor.tokenizer.pad_token_id

        a__  			=							processor.batch_decode(UpperCAmelCase_		)
        # we do not want to group tokens when computing the metrics
        a__  			=							processor.batch_decode(pred.label_ids ,     group_tokens=UpperCAmelCase_		)
        if logger.isEnabledFor(logging.DEBUG		):
            for reference, predicted in zip(UpperCAmelCase_ ,     UpperCAmelCase_		):
                logger.debug(F"""reference: \"{reference}\""""		)
                logger.debug(F"""predicted: \"{predicted}\""""		)
                if orthography.untransliterator is not None:
                    logger.debug(F"""reference (untransliterated): \"{orthography.untransliterator(UpperCAmelCase_		)}\""""		)
                    logger.debug(F"""predicted (untransliterated): \"{orthography.untransliterator(UpperCAmelCase_		)}\""""		)

        a__  			=							wer_metric.compute(predictions=UpperCAmelCase_ ,     references=UpperCAmelCase_		)

        return {"wer": wer}

    if model_args.freeze_feature_extractor:
        model.freeze_feature_extractor()

    a__  			=							CTCTrainer(
        model=UpperCAmelCase_ ,     data_collator=UpperCAmelCase_ ,     args=UpperCAmelCase_ ,     compute_metrics=UpperCAmelCase_ ,     train_dataset=UpperCAmelCase_ ,     eval_dataset=UpperCAmelCase_ ,     tokenizer=processor.feature_extractor ,     )

    trainer.train()


if __name__ == "__main__":
 main()












import random
import unittest

import numpy as np
import torch
from PIL import Image
from torch import nn
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import KandinskyVaaPriorEmbaEmbPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import floats_tensor, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()







class 		__UpperCAmelCase(		lowercase__							,						unittest.TestCase			):





     """simple docstring"""



     __UpperCAmelCase						:			Optional[int]							=     KandinskyVaaPriorEmbaEmbPipeline
     __UpperCAmelCase						:			str							=     ["""prompt""", """image"""]
     __UpperCAmelCase						:			Dict							=     ["""prompt""", """image"""]
     __UpperCAmelCase						:			Optional[Any]							=     [
         """num_images_per_prompt""",
         """strength""",
         """generator""",
         """num_inference_steps""",
         """latents""",
         """negative_prompt""",
         """guidance_scale""",
         """output_type""",
         """return_dict""",
     ]
     __UpperCAmelCase						:			Dict							=     False

     @property
     def 					__SCREAMING_SNAKE_CASE		(   self			:							Any     )      ->      int:






         """simple docstring"""
         return 32

     @property
     def 					__SCREAMING_SNAKE_CASE		(   self			:							Optional[Any]     )      ->      Any:






         """simple docstring"""
         return 32

     @property
     def 					__SCREAMING_SNAKE_CASE		(   self			:							Tuple     )      ->      int:






         """simple docstring"""
         return self.time_input_dim

     @property
     def 					__SCREAMING_SNAKE_CASE		(   self			:							int     )      ->      List[Any]:






         """simple docstring"""
         return self.time_input_dim * 4

     @property
     def 					__SCREAMING_SNAKE_CASE		(   self			:							Optional[int]     )      ->      Tuple:






         """simple docstring"""
         return 1_00

     @property
     def 					__SCREAMING_SNAKE_CASE		(   self			:							Union[str, Any]     )      ->      List[str]:






         """simple docstring"""
         a__  			=							CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""     )
         return tokenizer

     @property
     def 					__SCREAMING_SNAKE_CASE		(   self			:							int     )      ->      Optional[int]:






         """simple docstring"""
         torch.manual_seed(0     )
         a__  			=							CLIPTextConfig(
             bos_token_id=0    ,					eos_token_id=2    ,					hidden_size=self.text_embedder_hidden_size    ,					projection_dim=self.text_embedder_hidden_size    ,					intermediate_size=37    ,					layer_norm_eps=1E-05    ,					num_attention_heads=4    ,					num_hidden_layers=5    ,					pad_token_id=1    ,					vocab_size=10_00    ,					)
         return CLIPTextModelWithProjection(A     )

     @property
     def 					__SCREAMING_SNAKE_CASE		(   self			:							Dict     )      ->      List[Any]:






         """simple docstring"""
         torch.manual_seed(0     )

         a__  			=							{
             """num_attention_heads""": 2,
             """attention_head_dim""": 12,
             """embedding_dim""": self.text_embedder_hidden_size,
             """num_layers""": 1,
         }

         a__  			=							PriorTransformer(**A     )
         # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
         a__  			=							nn.Parameter(torch.ones(model.clip_std.shape     )     )
         return model

     @property
     def 					__SCREAMING_SNAKE_CASE		(   self			:							Dict     )      ->      Optional[int]:






         """simple docstring"""
         torch.manual_seed(0     )
         a__  			=							CLIPVisionConfig(
             hidden_size=self.text_embedder_hidden_size    ,					image_size=2_24    ,					projection_dim=self.text_embedder_hidden_size    ,					intermediate_size=37    ,					num_attention_heads=4    ,					num_channels=3    ,					num_hidden_layers=5    ,					patch_size=14    ,					)

         a__  			=							CLIPVisionModelWithProjection(A     )
         return model

     @property
     def 					__SCREAMING_SNAKE_CASE		(   self			:							int     )      ->      List[str]:






         """simple docstring"""
         a__  			=							CLIPImageProcessor(
             crop_size=2_24    ,					do_center_crop=A    ,					do_normalize=A    ,					do_resize=A    ,					image_mean=[0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3]    ,					image_std=[0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1]    ,					resample=3    ,					size=2_24    ,					)

         return image_processor

     def 					__SCREAMING_SNAKE_CASE		(   self			:							List[Any]     )      ->      Tuple:






         """simple docstring"""
         a__  			=							self.dummy_prior
         a__  			=							self.dummy_image_encoder
         a__  			=							self.dummy_text_encoder
         a__  			=							self.dummy_tokenizer
         a__  			=							self.dummy_image_processor

         a__  			=							UnCLIPScheduler(
             variance_type="""fixed_small_log"""    ,					prediction_type="""sample"""    ,					num_train_timesteps=10_00    ,					clip_sample=A    ,					clip_sample_range=1_0.0    ,					)

         a__  			=							{
             """prior""": prior,
             """image_encoder""": image_encoder,
             """text_encoder""": text_encoder,
             """tokenizer""": tokenizer,
             """scheduler""": scheduler,
             """image_processor""": image_processor,
         }

         return components

     def 					__SCREAMING_SNAKE_CASE		(   self			:							Optional[int]    ,					A			:							Tuple    ,					A			:							Optional[Any]=0     )      ->      Any:






         """simple docstring"""
         if str(A     ).startswith("""mps"""     ):
             a__  			=							torch.manual_seed(A     )
         else:
             a__  			=							torch.Generator(device=A     ).manual_seed(A     )

         a__  			=							floats_tensor((1, 3, 64, 64)    ,					rng=random.Random(A     )     ).to(A     )
         a__  			=							image.cpu().permute(0    ,					2    ,					3    ,					1     )[0]
         a__  			=							Image.fromarray(np.uinta(A     )     ).convert("""RGB"""     ).resize((2_56, 2_56)     )

         a__  			=							{
             """prompt""": """horse""",
             """image""": init_image,
             """strength""": 0.5,
             """generator""": generator,
             """guidance_scale""": 4.0,
             """num_inference_steps""": 2,
             """output_type""": """np""",
         }
         return inputs

     def 					__SCREAMING_SNAKE_CASE		(   self			:							Dict     )      ->      Optional[int]:






         """simple docstring"""
         a__  			=							"""cpu"""

         a__  			=							self.get_dummy_components()

         a__  			=							self.pipeline_class(**A     )
         a__  			=							pipe.to(A     )

         pipe.set_progress_bar_config(disable=A     )

         a__  			=							pipe(**self.get_dummy_inputs(A     )     )
         a__  			=							output.image_embeds

         a__  			=							pipe(
             **self.get_dummy_inputs(A     )    ,					return_dict=A    ,					)[0]

         a__  			=							image[0, -10:]
         a__  			=							image_from_tuple[0, -10:]

         assert image.shape == (1, 32)

         a__  			=							np.array(
             [
                 0.1_0_7_1_2_8_4,
                 1.3_3_3_0_2_7_1,
                 0.6_1_2_6_0_2_2_3,
                 -0.6_6_9_1_0_6_5,
                 -0.3_8_4_6_8_5_2,
                 -1.0_3_0_3_6_6_1,
                 0.2_2_7_1_6_1_1_1,
                 0.0_3_3_4_8_9_0_1,
                 0.3_0_0_4_0_6_7_5,
                 -0.2_4_8_0_5_0_2_9,
             ]     )

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

     @skip_mps
     def 					__SCREAMING_SNAKE_CASE		(   self			:							str     )      ->      Optional[Any]:






         """simple docstring"""
         a__  			=							torch_device == """cpu"""
         a__  			=							True
         a__  			=							False

         self._test_inference_batch_single_identical(
             test_max_difference=A    ,					relax_max_difference=A    ,					test_mean_pixel_difference=A    ,					)






     @skip_mps
     def 					__SCREAMING_SNAKE_CASE		(   self			:							Tuple     )      ->      Union[str, Any]:






         """simple docstring"""
         a__  			=							torch_device == """cpu"""
         a__  			=							False

         self._test_attention_slicing_forward_pass(
             test_max_difference=A    ,					test_mean_pixel_difference=A    ,					)






