
"""simple docstring"""



import inspect
import unittest

from datasets import load_dataset
from packaging import version

from transformers import BeitConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch
 from torch import nn

 from transformers import (
     MODEL_MAPPING,
     BeitForImageClassification,
     BeitForMaskedImageModeling,
     BeitForSemanticSegmentation,
     BeitModel,
 )
 from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 import PIL
 from PIL import Image

 from transformers import BeitImageProcessor




class 		a_						:







    def __init__(			self			:       Optional[int]     ,					__UpperCamelCase			:       int     ,					__UpperCamelCase			:       str=1_00     ,					__UpperCamelCase			:       Union[str, Any]=13     ,					__UpperCamelCase			:       Optional[int]=30     ,					__UpperCamelCase			:       List[str]=2     ,					__UpperCamelCase			:       List[str]=3     ,					__UpperCamelCase			:       List[Any]=True     ,					__UpperCamelCase			:       Union[str, Any]=True     ,					__UpperCamelCase			:       Tuple=32     ,					__UpperCamelCase			:       List[Any]=4     ,					__UpperCamelCase			:       Optional[Any]=4     ,					__UpperCamelCase			:       Dict=37     ,					__UpperCamelCase			:       List[str]="gelu"     ,					__UpperCamelCase			:       int=0.1     ,					__UpperCamelCase			:       List[Any]=0.1     ,					__UpperCamelCase			:       str=10     ,					__UpperCamelCase			:       List[str]=0.0_2     ,					__UpperCamelCase			:       int=3     ,					__UpperCamelCase			:       List[str]=None     ,					__UpperCamelCase			:       Tuple=[0, 1, 2, 3]     ,					)		->List[str]:






        '''simple docstring'''






        _UpperCAmelCase          =   parent
        _UpperCAmelCase          =   1_00
        _UpperCAmelCase          =   batch_size
        _UpperCAmelCase          =   image_size
        _UpperCAmelCase          =   patch_size
        _UpperCAmelCase          =   num_channels
        _UpperCAmelCase          =   is_training
        _UpperCAmelCase          =   use_labels
        _UpperCAmelCase          =   hidden_size
        _UpperCAmelCase          =   num_hidden_layers
        _UpperCAmelCase          =   num_attention_heads
        _UpperCAmelCase          =   intermediate_size
        _UpperCAmelCase          =   hidden_act
        _UpperCAmelCase          =   hidden_dropout_prob
        _UpperCAmelCase          =   attention_probs_dropout_prob
        _UpperCAmelCase          =   type_sequence_label_size
        _UpperCAmelCase          =   initializer_range
        _UpperCAmelCase          =   scope
        _UpperCAmelCase          =   out_indices
        _UpperCAmelCase          =   num_labels

        # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
        _UpperCAmelCase          =   (image_size // patch_size) ** 2
        _UpperCAmelCase          =   num_patches + 1







    def      _snake_case					(			self			:       List[Any]     )		->Union[str, Any]:






        '''simple docstring'''






        _UpperCAmelCase          =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

        _UpperCAmelCase          =   None
        _UpperCAmelCase          =   None
        if self.use_labels:
            _UpperCAmelCase          =   ids_tensor([self.batch_size]     ,					self.type_sequence_label_size     )
            _UpperCAmelCase          =   ids_tensor([self.batch_size, self.image_size, self.image_size]     ,					self.num_labels     )

        _UpperCAmelCase          =   self.get_config()

        return config, pixel_values, labels, pixel_labels







    def      _snake_case					(			self			:       Tuple     )		->str:






        '''simple docstring'''






        return BeitConfig(
            vocab_size=self.vocab_size     ,					image_size=self.image_size     ,					patch_size=self.patch_size     ,					num_channels=self.num_channels     ,					hidden_size=self.hidden_size     ,					num_hidden_layers=self.num_hidden_layers     ,					num_attention_heads=self.num_attention_heads     ,					intermediate_size=self.intermediate_size     ,					hidden_act=self.hidden_act     ,					hidden_dropout_prob=self.hidden_dropout_prob     ,					attention_probs_dropout_prob=self.attention_probs_dropout_prob     ,					is_decoder=A_     ,					initializer_range=self.initializer_range     ,					out_indices=self.out_indices     ,					)







    def      _snake_case					(			self			:       List[str]     ,					__UpperCamelCase			:       Optional[int]     ,					__UpperCamelCase			:       Any     ,					__UpperCamelCase			:       Any     ,					__UpperCamelCase			:       Dict     )		->List[Any]:






        '''simple docstring'''






        _UpperCAmelCase          =   BeitModel(config=A_     )
        model.to(A_     )
        model.eval()
        _UpperCAmelCase          =   model(A_     )
        self.parent.assertEqual(result.last_hidden_state.shape     ,					(self.batch_size, self.seq_length, self.hidden_size)     )







    def      _snake_case					(			self			:       Optional[int]     ,					__UpperCamelCase			:       int     ,					__UpperCamelCase			:       int     ,					__UpperCamelCase			:       Union[str, Any]     ,					__UpperCamelCase			:       Dict     )		->Tuple:






        '''simple docstring'''






        _UpperCAmelCase          =   BeitForMaskedImageModeling(config=A_     )
        model.to(A_     )
        model.eval()
        _UpperCAmelCase          =   model(A_     )
        self.parent.assertEqual(result.logits.shape     ,					(self.batch_size, self.seq_length - 1, self.vocab_size)     )







    def      _snake_case					(			self			:       Any     ,					__UpperCamelCase			:       Union[str, Any]     ,					__UpperCamelCase			:       Optional[int]     ,					__UpperCamelCase			:       Dict     ,					__UpperCamelCase			:       Optional[Any]     )		->List[str]:






        '''simple docstring'''






        _UpperCAmelCase          =   self.type_sequence_label_size
        _UpperCAmelCase          =   BeitForImageClassification(A_     )
        model.to(A_     )
        model.eval()
        _UpperCAmelCase          =   model(A_     ,					labels=A_     )
        self.parent.assertEqual(result.logits.shape     ,					(self.batch_size, self.type_sequence_label_size)     )

        # test greyscale images
        _UpperCAmelCase          =   1
        _UpperCAmelCase          =   BeitForImageClassification(A_     )
        model.to(A_     )
        model.eval()

        _UpperCAmelCase          =   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]     )
        _UpperCAmelCase          =   model(A_     ,					labels=A_     )
        self.parent.assertEqual(result.logits.shape     ,					(self.batch_size, self.type_sequence_label_size)     )







    def      _snake_case					(			self			:       Any     ,					__UpperCamelCase			:       Optional[int]     ,					__UpperCamelCase			:       Union[str, Any]     ,					__UpperCamelCase			:       Tuple     ,					__UpperCamelCase			:       str     )		->List[Any]:






        '''simple docstring'''






        _UpperCAmelCase          =   self.num_labels
        _UpperCAmelCase          =   BeitForSemanticSegmentation(A_     )
        model.to(A_     )
        model.eval()
        _UpperCAmelCase          =   model(A_     )
        self.parent.assertEqual(
            result.logits.shape     ,					(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)     )
        _UpperCAmelCase          =   model(A_     ,					labels=A_     )
        self.parent.assertEqual(
            result.logits.shape     ,					(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)     )







    def      _snake_case					(			self			:       Optional[int]     )		->List[Any]:






        '''simple docstring'''






        _UpperCAmelCase          =   self.prepare_config_and_inputs()
        _UpperCAmelCase          =   config_and_inputs
        _UpperCAmelCase          =   {"pixel_values": pixel_values}
        return config, inputs_dict







@require_torch
class 		a_						( __snake_case     ,						__snake_case     ,						unittest.TestCase	):
    a      :				List[str]     =				(
        (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation)
        if is_torch_available()
        else ()
    )
    a      :				List[str]     =				(
        {
            'feature-extraction': BeitModel,
            'image-classification': BeitForImageClassification,
            'image-segmentation': BeitForSemanticSegmentation,
        }
        if is_torch_available()
        else {}
    )

    a      :				Optional[Any]     =				False
    a      :				str     =				False
    a      :				Optional[int]     =				False







    def      _snake_case					(			self			:       List[str]     )		->Optional[int]:






        '''simple docstring'''






        _UpperCAmelCase          =   BeitModelTester(self     )
        _UpperCAmelCase          =   ConfigTester(self     ,					config_class=A_     ,					has_text_modality=A_     ,					hidden_size=37     )







    def      _snake_case					(			self			:       Any     )		->Optional[Any]:






        '''simple docstring'''






        self.config_tester.run_common_tests()







    @unittest.skip(reason="""BEiT does not use inputs_embeds"""     )
    def      _snake_case					(			self			:       Optional[Any]     )		->str:






        '''simple docstring'''






        pass







    @require_torch_multi_gpu
    @unittest.skip(reason="""BEiT has some layers using `add_module` which doesn't work well with `nn.DataParallel`"""     )
    def      _snake_case					(			self			:       List[Any]     )		->int:






        '''simple docstring'''






        pass







    def      _snake_case					(			self			:       str     )		->List[str]:






        '''simple docstring'''






        _UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
            _UpperCAmelCase          =   model_class(A_     )
            self.assertIsInstance(model.get_input_embeddings()     ,					(nn.Module)     )
            _UpperCAmelCase          =   model.get_output_embeddings()
            self.assertTrue(x is None or isinstance(A_     ,					nn.Linear     )     )







    def      _snake_case					(			self			:       Optional[Any]     )		->Optional[Any]:






        '''simple docstring'''






        _UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
            _UpperCAmelCase          =   model_class(A_     )
            _UpperCAmelCase          =   inspect.signature(model.forward     )
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            _UpperCAmelCase          =   [*signature.parameters.keys()]

            _UpperCAmelCase          =   ["pixel_values"]
            self.assertListEqual(arg_names[:1]     ,					A_     )







    def      _snake_case					(			self			:       Tuple     )		->List[str]:






        '''simple docstring'''






        _UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*A_     )







    def      _snake_case					(			self			:       int     )		->str:






        '''simple docstring'''






        _UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_masked_lm(*A_     )







    def      _snake_case					(			self			:       Optional[int]     )		->Optional[Any]:






        '''simple docstring'''






        _UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*A_     )







    def      _snake_case					(			self			:       int     )		->Optional[int]:






        '''simple docstring'''






        _UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_semantic_segmentation(*A_     )







    def      _snake_case					(			self			:       str     )		->List[Any]:






        '''simple docstring'''






        if not self.model_tester.is_training:
            return

        _UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs_for_common()
        _UpperCAmelCase          =   True

        for model_class in self.all_model_classes:
            # we don't test BeitForMaskedImageModeling
            if model_class in [*get_values(A_     ), BeitForMaskedImageModeling]:
                continue

            _UpperCAmelCase          =   model_class(A_     )
            model.to(A_     )
            model.train()
            _UpperCAmelCase          =   self._prepare_for_class(A_     ,					A_     ,					return_labels=A_     )
            _UpperCAmelCase          =   model(**A_     ).loss
            loss.backward()







    def      _snake_case					(			self			:       Union[str, Any]     )		->Optional[Any]:






        '''simple docstring'''






        _UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs_for_common()
        if not self.model_tester.is_training:
            return

        _UpperCAmelCase          =   False
        _UpperCAmelCase          =   True

        for model_class in self.all_model_classes:
            # we don't test BeitForMaskedImageModeling
            if (
                model_class in [*get_values(A_     ), BeitForMaskedImageModeling]
                or not model_class.supports_gradient_checkpointing
            ):
                continue

            _UpperCAmelCase          =   model_class(A_     )
            model.gradient_checkpointing_enable()
            model.to(A_     )
            model.train()
            _UpperCAmelCase          =   self._prepare_for_class(A_     ,					A_     ,					return_labels=A_     )
            _UpperCAmelCase          =   model(**A_     ).loss
            loss.backward()







    def      _snake_case					(			self			:       Tuple     )		->Tuple:






        '''simple docstring'''






        _UpperCAmelCase          =   self.model_tester.prepare_config_and_inputs_for_common()

        _UpperCAmelCase          =   _config_zero_init(A_     )
        for model_class in self.all_model_classes:
            _UpperCAmelCase          =   model_class(config=A_     )
            for name, param in model.named_parameters():
                # we skip lambda parameters as these require special initial values
                # determined by config.layer_scale_init_value
                if "lambda" in name:
                    continue
                if param.requires_grad:
                    self.assertIn(
                        ((param.data.mean() * 1e9).round() / 1e9).item()     ,					[0.0, 1.0]     ,					msg=f"""Parameter {name} of model {model_class} seems not properly initialized"""     ,					)







    @slow
    def      _snake_case					(			self			:       Union[str, Any]     )		->Optional[Any]:






        '''simple docstring'''






        for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            _UpperCAmelCase          =   BeitModel.from_pretrained(A_     )
            self.assertIsNotNone(A_     )







def  _UpperCamelCase	(						)    ->  Optional[int]:





    """simple docstring"""

    _UpperCAmelCase          =   Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""      )
    return image






@require_torch
@require_vision
class 		a_						( unittest.TestCase	):







    @cached_property
    def      _snake_case					(			self			:       Dict     )		->str:






        '''simple docstring'''






        return BeitImageProcessor.from_pretrained("""microsoft/beit-base-patch16-224"""     ) if is_vision_available() else None







    @slow
    def      _snake_case					(			self			:       Optional[Any]     )		->Optional[Any]:






        '''simple docstring'''






        _UpperCAmelCase          =   BeitForMaskedImageModeling.from_pretrained("""microsoft/beit-base-patch16-224-pt22k"""     ).to(A_     )

        _UpperCAmelCase          =   self.default_image_processor
        _UpperCAmelCase          =   prepare_img()
        _UpperCAmelCase          =   image_processor(images=A_     ,					return_tensors="""pt"""     ).pixel_values.to(A_     )

        # prepare bool_masked_pos
        _UpperCAmelCase          =   torch.ones((1, 1_96)     ,					dtype=torch.bool     ).to(A_     )

        # forward pass
        with torch.no_grad():
            _UpperCAmelCase          =   model(pixel_values=A_     ,					bool_masked_pos=A_     )
        _UpperCAmelCase          =   outputs.logits

        # verify the logits
        _UpperCAmelCase          =   torch.Size((1, 1_96, 81_92)     )
        self.assertEqual(logits.shape     ,					A_     )

        _UpperCAmelCase          =   torch.tensor(
            [[-3.2_4_3_7, 0.5_0_7_2, -1_3.9_1_7_4], [-3.2_4_5_6, 0.4_9_4_8, -1_3.9_4_0_1], [-3.2_0_3_3, 0.5_1_2_1, -1_3.8_5_5_0]]     ).to(A_     )

        self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3]     ,					A_     ,					atol=1e-2     )     )







    @slow
    def      _snake_case					(			self			:       Dict     )		->List[Any]:






        '''simple docstring'''






        _UpperCAmelCase          =   BeitForImageClassification.from_pretrained("""microsoft/beit-base-patch16-224"""     ).to(A_     )

        _UpperCAmelCase          =   self.default_image_processor
        _UpperCAmelCase          =   prepare_img()
        _UpperCAmelCase          =   image_processor(images=A_     ,					return_tensors="""pt"""     ).to(A_     )

        # forward pass
        with torch.no_grad():
            _UpperCAmelCase          =   model(**A_     )
        _UpperCAmelCase          =   outputs.logits

        # verify the logits
        _UpperCAmelCase          =   torch.Size((1, 10_00)     )
        self.assertEqual(logits.shape     ,					A_     )

        _UpperCAmelCase          =   torch.tensor([-1.2_3_8_5, -1.0_9_8_7, -1.0_1_0_8]     ).to(A_     )

        self.assertTrue(torch.allclose(logits[0, :3]     ,					A_     ,					atol=1e-4     )     )

        _UpperCAmelCase          =   2_81
        self.assertEqual(logits.argmax(-1     ).item()     ,					A_     )







    @slow
    def      _snake_case					(			self			:       List[str]     )		->Union[str, Any]:






        '''simple docstring'''






        _UpperCAmelCase          =   BeitForImageClassification.from_pretrained("""microsoft/beit-large-patch16-224-pt22k-ft22k"""     ).to(
            A_     )

        _UpperCAmelCase          =   self.default_image_processor
        _UpperCAmelCase          =   prepare_img()
        _UpperCAmelCase          =   image_processor(images=A_     ,					return_tensors="""pt"""     ).to(A_     )

        # forward pass
        with torch.no_grad():
            _UpperCAmelCase          =   model(**A_     )
        _UpperCAmelCase          =   outputs.logits

        # verify the logits
        _UpperCAmelCase          =   torch.Size((1, 2_18_41)     )
        self.assertEqual(logits.shape     ,					A_     )

        _UpperCAmelCase          =   torch.tensor([1.6_8_8_1, -0.2_7_8_7, 0.5_9_0_1]     ).to(A_     )

        self.assertTrue(torch.allclose(logits[0, :3]     ,					A_     ,					atol=1e-4     )     )

        _UpperCAmelCase          =   23_96
        self.assertEqual(logits.argmax(-1     ).item()     ,					A_     )







    @slow
    def      _snake_case					(			self			:       List[Any]     )		->List[str]:






        '''simple docstring'''






        _UpperCAmelCase          =   BeitForSemanticSegmentation.from_pretrained("""microsoft/beit-base-finetuned-ade-640-640"""     )
        _UpperCAmelCase          =   model.to(A_     )

        _UpperCAmelCase          =   BeitImageProcessor(do_resize=A_     ,					size=6_40     ,					do_center_crop=A_     )

        _UpperCAmelCase          =   load_dataset("""hf-internal-testing/fixtures_ade20k"""     ,					split="""test"""     )
        _UpperCAmelCase          =   Image.open(ds[0]["""file"""]     )
        _UpperCAmelCase          =   image_processor(images=A_     ,					return_tensors="""pt"""     ).to(A_     )

        # forward pass
        with torch.no_grad():
            _UpperCAmelCase          =   model(**A_     )
        _UpperCAmelCase          =   outputs.logits

        # verify the logits
        _UpperCAmelCase          =   torch.Size((1, 1_50, 1_60, 1_60)     )
        self.assertEqual(logits.shape     ,					A_     )

        _UpperCAmelCase          =   version.parse(PIL.__version__     ) < version.parse("""9.0.0"""     )

        if is_pillow_less_than_a:
            _UpperCAmelCase          =   torch.tensor(
                [
                    [[-4.9_2_2_5, -2.3_9_5_4, -3.0_5_2_2], [-2.8_8_2_2, -1.0_0_4_6, -1.7_5_6_1], [-2.9_5_4_9, -1.3_2_2_8, -2.1_3_4_7]],
                    [[-5.8_1_6_8, -3.4_1_2_9, -4.0_7_7_8], [-3.8_6_5_1, -2.2_2_1_4, -3.0_2_7_7], [-3.8_3_5_6, -2.4_6_4_3, -3.3_5_3_5]],
                    [[-0.0_0_7_8, 3.9_9_5_2, 4.0_7_5_4], [2.9_8_5_6, 4.6_9_4_4, 5.0_0_3_5], [3.2_4_1_3, 4.7_8_1_3, 4.9_9_6_9]],
                ]     ,					device=A_     ,					)
        else:
            _UpperCAmelCase          =   torch.tensor(
                [
                    [[-4.8_9_6_0, -2.3_6_8_8, -3.0_3_5_5], [-2.8_4_7_8, -0.9_8_3_6, -1.7_4_1_8], [-2.9_4_4_9, -1.3_3_3_2, -2.1_4_5_6]],
                    [[-5.8_0_8_1, -3.4_1_2_4, -4.1_0_0_6], [-3.8_5_6_1, -2.2_0_8_1, -3.0_3_2_3], [-3.8_3_6_5, -2.4_6_0_1, -3.3_6_6_9]],
                    [[-0.0_3_0_9, 3.9_8_6_8, 4.0_5_4_0], [2.9_6_4_0, 4.6_8_7_7, 4.9_9_7_6], [3.2_0_8_1, 4.7_6_9_0, 4.9_9_4_2]],
                ]     ,					device=A_     ,					)

        self.assertTrue(torch.allclose(logits[0, :3, :3, :3]     ,					A_     ,					atol=1e-4     )     )







    @slow
    def      _snake_case					(			self			:       Dict     )		->List[str]:






        '''simple docstring'''






        _UpperCAmelCase          =   BeitForSemanticSegmentation.from_pretrained("""microsoft/beit-base-finetuned-ade-640-640"""     )
        _UpperCAmelCase          =   model.to(A_     )

        _UpperCAmelCase          =   BeitImageProcessor(do_resize=A_     ,					size=6_40     ,					do_center_crop=A_     )

        _UpperCAmelCase          =   load_dataset("""hf-internal-testing/fixtures_ade20k"""     ,					split="""test"""     )
        _UpperCAmelCase          =   Image.open(ds[0]["""file"""]     )
        _UpperCAmelCase          =   image_processor(images=A_     ,					return_tensors="""pt"""     ).to(A_     )

        # forward pass
        with torch.no_grad():
            _UpperCAmelCase          =   model(**A_     )

        _UpperCAmelCase          =   outputs.logits.detach().cpu()

        _UpperCAmelCase          =   image_processor.post_process_semantic_segmentation(outputs=A_     ,					target_sizes=[(5_00, 3_00)]     )
        _UpperCAmelCase          =   torch.Size((5_00, 3_00)     )
        self.assertEqual(segmentation[0].shape     ,					A_     )

        _UpperCAmelCase          =   image_processor.post_process_semantic_segmentation(outputs=A_     )
        _UpperCAmelCase          =   torch.Size((1_60, 1_60)     )
        self.assertEqual(segmentation[0].shape     ,					A_     )

"""simple docstring"""



# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING, Dict, Optional

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.logging import get_logger
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
 import jax
 import jaxlib

a					:	List[Any]							=		get_logger()

a					:	Optional[dict]							=		None




class 		a_						( TensorFormatter[Mapping, 'jax.Array', Mapping]	):







    def __init__(			self			:       int     ,					__UpperCamelCase			:       List[str]=None     ,					__UpperCamelCase			:       Optional[int]=None     ,					**__UpperCamelCase			:       int     )		->Tuple:






        '''simple docstring'''






        super().__init__(features=__UpperCamelCase     )
        import jax
        from jaxlib.xla_client import Device

        if isinstance(__UpperCamelCase     ,					__UpperCamelCase     ):
            raise ValueError(
                f"""Expected {device} to be a `str` not {type(__UpperCamelCase     )}, as `jaxlib.xla_extension.Device` """
                """is not serializable neither with `pickle` nor with `dill`. Instead you can surround """
                """the device with `str()` to get its string identifier that will be internally mapped """
                """to the actual `jaxlib.xla_extension.Device`."""     )
        _UpperCAmelCase          =   device if isinstance(__UpperCamelCase     ,					__UpperCamelCase     ) else str(jax.devices()[0]     )
        # using global variable since `jaxlib.xla_extension.Device` is not serializable neither
        # with `pickle` nor with `dill`, so we need to use a global variable instead
        global DEVICE_MAPPING
        if DEVICE_MAPPING is None:
            _UpperCAmelCase          =   self._map_devices_to_str()
        if self.device not in list(DEVICE_MAPPING.keys()     ):
            logger.warning(
                f"""Device with string identifier {self.device} not listed among the available """
                f"""devices: {list(DEVICE_MAPPING.keys()     )}, so falling back to the default """
                f"""device: {str(jax.devices()[0]     )}."""     )
            _UpperCAmelCase          =   str(jax.devices()[0]     )
        _UpperCAmelCase          =   jnp_array_kwargs







    @staticmethod
    def      _snake_case					(			)		->Dict[str, "jaxlib.xla_extension.Device"]:






        '''simple docstring'''






        import jax

        return {str(__UpperCamelCase     ): device for device in jax.devices()}







    def      _snake_case					(			self			:       Dict     ,					__UpperCamelCase			:       Any     )		->Union[str, Any]:






        '''simple docstring'''






        import jax
        import jax.numpy as jnp

        if isinstance(__UpperCamelCase     ,					__UpperCamelCase     ) and column:
            if all(
                isinstance(__UpperCamelCase     ,					jax.Array     ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column     ):
                return jnp.stack(__UpperCamelCase     ,					axis=0     )
        return column







    def      _snake_case					(			self			:       List[str]     ,					__UpperCamelCase			:       Any     )		->Optional[int]:






        '''simple docstring'''






        import jax
        import jax.numpy as jnp

        if isinstance(__UpperCamelCase     ,					(str, bytes, type(__UpperCamelCase     ))     ):
            return value
        elif isinstance(__UpperCamelCase     ,					(np.character, np.ndarray)     ) and np.issubdtype(value.dtype     ,					np.character     ):
            return value.tolist()

        _UpperCAmelCase          =   {}

        if isinstance(__UpperCamelCase     ,					(np.number, np.ndarray)     ) and np.issubdtype(value.dtype     ,					np.integer     ):
            # the default int precision depends on the jax config
            # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision
            if jax.config.jax_enable_xaa:
                _UpperCAmelCase          =   {"""dtype""": jnp.intaa}
            else:
                _UpperCAmelCase          =   {"""dtype""": jnp.intaa}
        elif isinstance(__UpperCamelCase     ,					(np.number, np.ndarray)     ) and np.issubdtype(value.dtype     ,					np.floating     ):
            _UpperCAmelCase          =   {"""dtype""": jnp.floataa}
        elif config.PIL_AVAILABLE and "PIL" in sys.modules:
            import PIL.Image

            if isinstance(__UpperCamelCase     ,					PIL.Image.Image     ):
                _UpperCAmelCase          =   np.asarray(__UpperCamelCase     )

        # using global variable since `jaxlib.xla_extension.Device` is not serializable neither
        # with `pickle` nor with `dill`, so we need to use a global variable instead
        global DEVICE_MAPPING
        if DEVICE_MAPPING is None:
            _UpperCAmelCase          =   self._map_devices_to_str()

        with jax.default_device(DEVICE_MAPPING[self.device]     ):
            # calling jnp.array on a np.ndarray does copy the data
            # see https://github.com/google/jax/issues/4486
            return jnp.array(__UpperCamelCase     ,					**{**default_dtype, **self.jnp_array_kwargs}     )







    def      _snake_case					(			self			:       Union[str, Any]     ,					__UpperCamelCase			:       List[str]     )		->Any:






        '''simple docstring'''






        import jax

        # support for torch, tf, jax etc.
        if config.TORCH_AVAILABLE and "torch" in sys.modules:
            import torch

            if isinstance(__UpperCamelCase     ,					torch.Tensor     ):
                return self._tensorize(data_struct.detach().cpu().numpy()[()]     )
        if hasattr(__UpperCamelCase     ,					"""__array__"""     ) and not isinstance(__UpperCamelCase     ,					jax.Array     ):
            _UpperCAmelCase          =   data_struct.__array__()
        # support for nested types like struct of list of struct
        if isinstance(__UpperCamelCase     ,					np.ndarray     ):
            if data_struct.dtype == object:  # jax arrays cannot be instantied from an array of objects
                return self._consolidate([self.recursive_tensorize(__UpperCamelCase     ) for substruct in data_struct]     )
        elif isinstance(__UpperCamelCase     ,					(list, tuple)     ):
            return self._consolidate([self.recursive_tensorize(__UpperCamelCase     ) for substruct in data_struct]     )
        return self._tensorize(__UpperCamelCase     )







    def      _snake_case					(			self			:       List[str]     ,					__UpperCamelCase			:       dict     )		->int:






        '''simple docstring'''






        return map_nested(self._recursive_tensorize     ,					__UpperCamelCase     ,					map_list=__UpperCamelCase     )







    def      _snake_case					(			self			:       Dict     ,					__UpperCamelCase			:       pa.Table     )		->Mapping:






        '''simple docstring'''






        _UpperCAmelCase          =   self.numpy_arrow_extractor().extract_row(__UpperCamelCase     )
        _UpperCAmelCase          =   self.python_features_decoder.decode_row(__UpperCamelCase     )
        return self.recursive_tensorize(__UpperCamelCase     )







    def      _snake_case					(			self			:       Optional[int]     ,					__UpperCamelCase			:       pa.Table     )		->"jax.Array":






        '''simple docstring'''






        _UpperCAmelCase          =   self.numpy_arrow_extractor().extract_column(__UpperCamelCase     )
        _UpperCAmelCase          =   self.python_features_decoder.decode_column(__UpperCamelCase     ,					pa_table.column_names[0]     )
        _UpperCAmelCase          =   self.recursive_tensorize(__UpperCamelCase     )
        _UpperCAmelCase          =   self._consolidate(__UpperCamelCase     )
        return column







    def      _snake_case					(			self			:       Optional[Any]     ,					__UpperCamelCase			:       pa.Table     )		->Mapping:






        '''simple docstring'''






        _UpperCAmelCase          =   self.numpy_arrow_extractor().extract_batch(__UpperCamelCase     )
        _UpperCAmelCase          =   self.python_features_decoder.decode_batch(__UpperCamelCase     )
        _UpperCAmelCase          =   self.recursive_tensorize(__UpperCamelCase     )
        for column_name in batch:
            _UpperCAmelCase          =   self._consolidate(batch[column_name]     )
        return batch