




import unittest

from transformers.utils.backbone_utils import (
    BackboneMixin,
    get_aligned_output_features_output_indices,
    verify_out_features_out_indices,
)




class     snake_case__							(unittest.TestCase   ):
				"""simple docstring"""



				def 							__UpperCAmelCase							(      self				:     List[str]							)					->     Dict:
							a    =			["a", "b", "c"]

							# Defaults to last layer if both are None
							a    ,		a    =			get_aligned_output_features_output_indices(__lowerCamelCase					,      __lowerCamelCase					,      __lowerCamelCase							)
							self.assertEqual(__lowerCamelCase					,      ["c"]							)
							self.assertEqual(__lowerCamelCase					,      [2]							)

							# Out indices set to match out features
							a    ,		a    =			get_aligned_output_features_output_indices(["a", "c"]					,      __lowerCamelCase					,      __lowerCamelCase							)
							self.assertEqual(__lowerCamelCase					,      ["a", "c"]							)
							self.assertEqual(__lowerCamelCase					,      [0, 2]							)

							# Out features set to match out indices
							a    ,		a    =			get_aligned_output_features_output_indices(__lowerCamelCase					,      [0, 2]					,      __lowerCamelCase							)
							self.assertEqual(__lowerCamelCase					,      ["a", "c"]							)
							self.assertEqual(__lowerCamelCase					,      [0, 2]							)

							# Out features selected from negative indices
							a    ,		a    =			get_aligned_output_features_output_indices(__lowerCamelCase					,      [-3, -1]					,      __lowerCamelCase							)
							self.assertEqual(__lowerCamelCase					,      ["a", "c"]							)
							self.assertEqual(__lowerCamelCase					,      [-3, -1]							)





				def 							__UpperCAmelCase							(      self				:     int							)					->     str:
							# Stage names must be set
							with self.assertRaises(__lowerCamelCase							):
										verify_out_features_out_indices(["a", "b"]					,      (0, 1)					,      __lowerCamelCase							)

							# Out features must be a list
							with self.assertRaises(__lowerCamelCase							):
										verify_out_features_out_indices(("a", "b")					,      (0, 1)					,      ["a", "b"]							)

							# Out features must be a subset of stage names
							with self.assertRaises(__lowerCamelCase							):
										verify_out_features_out_indices(["a", "b"]					,      (0, 1)					,      ["a"]							)

							# Out indices must be a list or tuple
							with self.assertRaises(__lowerCamelCase							):
										verify_out_features_out_indices(__lowerCamelCase					,      0					,      ["a", "b"]							)

							# Out indices must be a subset of stage names
							with self.assertRaises(__lowerCamelCase							):
										verify_out_features_out_indices(__lowerCamelCase					,      (0, 1)					,      ["a"]							)

							# Out features and out indices must be the same length
							with self.assertRaises(__lowerCamelCase							):
										verify_out_features_out_indices(["a", "b"]					,      (0,)					,      ["a", "b", "c"]							)

							# Out features should match out indices
							with self.assertRaises(__lowerCamelCase							):
										verify_out_features_out_indices(["a", "b"]					,      (0, 2)					,      ["a", "b", "c"]							)

							# Out features and out indices should be in order
							with self.assertRaises(__lowerCamelCase							):
										verify_out_features_out_indices(["b", "a"]					,      (0, 1)					,      ["a", "b"]							)

							# Check passes with valid inputs
							verify_out_features_out_indices(["a", "b", "d"]					,      (0, 1, -1)					,      ["a", "b", "c", "d"]							)





				def 							__UpperCAmelCase							(      self				:     Optional[int]							)					->     List[str]:
							a    =			BackboneMixin()

							a    =			["a", "b", "c"]
							a    =			["a", "c"]
							a    =			[0, 2]

							# Check that the output features and indices are set correctly
							self.assertEqual(backbone.out_features					,      ["a", "c"]							)
							self.assertEqual(backbone.out_indices					,      [0, 2]							)

							# Check out features and indices are updated correctly
							a    =			["a", "b"]
							self.assertEqual(backbone.out_features					,      ["a", "b"]							)
							self.assertEqual(backbone.out_indices					,      [0, 1]							)

							a    =			[-3, -1]
							self.assertEqual(backbone.out_features					,      ["a", "c"]							)
							self.assertEqual(backbone.out_indices					,      [-3, -1]							)












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

import numpy as np
import pyarrow as pa

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


if TYPE_CHECKING:
		import torch




class     snake_case__							(TensorFormatter[Mapping, """torch.Tensor""", Mapping]   ):
				"""simple docstring"""



				def __init__(      self				:     Tuple					,      __lowerCamelCase				:     Union[str, Any]=None					,      **__lowerCamelCase				:     Any							)					->     Optional[Any]:
							super().__init__(features=__lowerCamelCase							)
							a    =			torch_tensor_kwargs
							import torch  # noqa import torch at initialization





				def 							__UpperCAmelCase							(      self				:     List[str]					,      __lowerCamelCase				:     Dict							)					->     Dict:
							import torch

							if isinstance(__lowerCamelCase					,      __lowerCamelCase							) and column:
										if all(
										    isinstance(__lowerCamelCase					,      torch.Tensor							) and x.shape == column[0].shape and x.dtype == column[0].dtype
										    for x in column							):
													return torch.stack(__lowerCamelCase							)
							return column





				def 							__UpperCAmelCase							(      self				:     Optional[Any]					,      __lowerCamelCase				:     List[Any]							)					->     str:
							import torch

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

							a    =			{}

							if isinstance(__lowerCamelCase					,      (np.number, np.ndarray)							) and np.issubdtype(value.dtype					,      np.integer							):
										a    =			{"dtype": torch.intaa}
							elif isinstance(__lowerCamelCase					,      (np.number, np.ndarray)							) and np.issubdtype(value.dtype					,      np.floating							):
										a    =			{"dtype": torch.floataa}
							elif config.PIL_AVAILABLE and "PIL" in sys.modules:
										import PIL.Image

										if isinstance(__lowerCamelCase					,      PIL.Image.Image							):
													a    =			np.asarray(__lowerCamelCase							)
							return torch.tensor(__lowerCamelCase					,      **{**default_dtype, **self.torch_tensor_kwargs}							)





				def 							__UpperCAmelCase							(      self				:     List[str]					,      __lowerCamelCase				:     Tuple							)					->     List[str]:
							import torch

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





				def 							__UpperCAmelCase							(      self				:     int					,      __lowerCamelCase				:     dict							)					->     str:
							return map_nested(self._recursive_tensorize					,      __lowerCamelCase					,      map_list=__lowerCamelCase							)





				def 							__UpperCAmelCase							(      self				:     Optional[Any]					,      __lowerCamelCase				:     pa.Table							)					->     Mapping:
							a    =			self.numpy_arrow_extractor().extract_row(__lowerCamelCase							)
							a    =			self.python_features_decoder.decode_row(__lowerCamelCase							)
							return self.recursive_tensorize(__lowerCamelCase							)





				def 							__UpperCAmelCase							(      self				:     int					,      __lowerCamelCase				:     pa.Table							)					->     "torch.Tensor":
							a    =			self.numpy_arrow_extractor().extract_column(__lowerCamelCase							)
							a    =			self.python_features_decoder.decode_column(__lowerCamelCase					,      pa_table.column_names[0]							)
							a    =			self.recursive_tensorize(__lowerCamelCase							)
							a    =			self._consolidate(__lowerCamelCase							)
							return column





				def 							__UpperCAmelCase							(      self				:     Optional[Any]					,      __lowerCamelCase				:     pa.Table							)					->     Mapping:
							a    =			self.numpy_arrow_extractor().extract_batch(__lowerCamelCase							)
							a    =			self.python_features_decoder.decode_batch(__lowerCamelCase							)
							a    =			self.recursive_tensorize(__lowerCamelCase							)
							for column_name in batch:
										a    =			self._consolidate(batch[column_name]							)
							return batch






