






import unittest

from transformers import MobileBertConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
	import torch

	from transformers import (
	    MODEL_FOR_PRETRAINING_MAPPING,
	    MobileBertForMaskedLM,
	    MobileBertForMultipleChoice,
	    MobileBertForNextSentencePrediction,
	    MobileBertForPreTraining,
	    MobileBertForQuestionAnswering,
	    MobileBertForSequenceClassification,
	    MobileBertForTokenClassification,
	    MobileBertModel,
	)


class    _lowerCAmelCase			:



				"""simple docstring"""



				def __init__(      self    :    Dict			,		UpperCamelCase__    :    Tuple			,		UpperCamelCase__    :    Optional[int]=1_3			,		UpperCamelCase__    :    Dict=7			,		UpperCamelCase__    :    str=True			,		UpperCamelCase__    :    int=True			,		UpperCamelCase__    :    int=True			,		UpperCamelCase__    :    str=True			,		UpperCamelCase__    :    List[Any]=9_9			,		UpperCamelCase__    :    int=6_4			,		UpperCamelCase__    :    Optional[int]=3_2			,		UpperCamelCase__    :    Tuple=5			,		UpperCamelCase__    :    Tuple=4			,		UpperCamelCase__    :    List[Any]=3_7			,		UpperCamelCase__    :    str="gelu"			,		UpperCamelCase__    :    List[Any]=0.1			,		UpperCamelCase__    :    Optional[Any]=0.1			,		UpperCamelCase__    :    Dict=5_1_2			,		UpperCamelCase__    :    Union[str, Any]=1_6			,		UpperCamelCase__    :    int=2			,		UpperCamelCase__    :    Dict=0.02			,		UpperCamelCase__    :    List[str]=3			,		UpperCamelCase__    :    int=4			,		UpperCamelCase__    :    List[str]=None			,		):






											'''simple docstring'''







											snake_case__	  =       parent
											snake_case__	  =       batch_size
											snake_case__	  =       seq_length
											snake_case__	  =       is_training
											snake_case__	  =       use_input_mask
											snake_case__	  =       use_token_type_ids
											snake_case__	  =       use_labels
											snake_case__	  =       vocab_size
											snake_case__	  =       hidden_size
											snake_case__	  =       embedding_size
											snake_case__	  =       num_hidden_layers
											snake_case__	  =       num_attention_heads
											snake_case__	  =       intermediate_size
											snake_case__	  =       hidden_act
											snake_case__	  =       hidden_dropout_prob
											snake_case__	  =       attention_probs_dropout_prob
											snake_case__	  =       max_position_embeddings
											snake_case__	  =       type_vocab_size
											snake_case__	  =       type_sequence_label_size
											snake_case__	  =       initializer_range
											snake_case__	  =       num_labels
											snake_case__	  =       num_choices
											snake_case__	  =       scope



				def 					__magic_name__							(      self    :    Dict):






											'''simple docstring'''







											snake_case__	  =       ids_tensor([self.batch_size, self.seq_length]			,		self.vocab_size)

											snake_case__	  =       None
											if self.use_input_mask:
																		snake_case__	  =       random_attention_mask([self.batch_size, self.seq_length])

											snake_case__	  =       None
											if self.use_token_type_ids:
																		snake_case__	  =       ids_tensor([self.batch_size, self.seq_length]			,		self.type_vocab_size)

											snake_case__	  =       None
											snake_case__	  =       None
											snake_case__	  =       None
											if self.use_labels:
																		snake_case__	  =       ids_tensor([self.batch_size]			,		self.type_sequence_label_size)
																		snake_case__	  =       ids_tensor([self.batch_size, self.seq_length]			,		self.num_labels)
																		snake_case__	  =       ids_tensor([self.batch_size]			,		self.num_choices)

											snake_case__	  =       self.get_config()

											return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels



				def 					__magic_name__							(      self    :    Any):






											'''simple docstring'''







											return MobileBertConfig(
											    vocab_size=self.vocab_size			,		hidden_size=self.hidden_size			,		num_hidden_layers=self.num_hidden_layers			,		num_attention_heads=self.num_attention_heads			,		intermediate_size=self.intermediate_size			,		embedding_size=self.embedding_size			,		hidden_act=self.hidden_act			,		hidden_dropout_prob=self.hidden_dropout_prob			,		attention_probs_dropout_prob=self.attention_probs_dropout_prob			,		max_position_embeddings=self.max_position_embeddings			,		type_vocab_size=self.type_vocab_size			,		is_decoder=__UpperCamelCase			,		initializer_range=self.initializer_range			,		)



				def 					__magic_name__							(      self    :    str			,		UpperCamelCase__    :    str			,		UpperCamelCase__    :    str			,		UpperCamelCase__    :    Union[str, Any]			,		UpperCamelCase__    :    List[str]			,		UpperCamelCase__    :    str			,		UpperCamelCase__    :    Tuple			,		UpperCamelCase__    :    str):






											'''simple docstring'''







											snake_case__	  =       MobileBertModel(config=__UpperCamelCase)
											model.to(__UpperCamelCase)
											model.eval()
											snake_case__	  =       model(__UpperCamelCase			,		attention_mask=__UpperCamelCase			,		token_type_ids=__UpperCamelCase)
											snake_case__	  =       model(__UpperCamelCase			,		token_type_ids=__UpperCamelCase)
											snake_case__	  =       model(__UpperCamelCase)

											self.parent.assertEqual(result.last_hidden_state.shape			,		(self.batch_size, self.seq_length, self.hidden_size))
											self.parent.assertEqual(result.pooler_output.shape			,		(self.batch_size, self.hidden_size))



				def 					__magic_name__							(      self    :    Dict			,		UpperCamelCase__    :    List[Any]			,		UpperCamelCase__    :    List[Any]			,		UpperCamelCase__    :    Tuple			,		UpperCamelCase__    :    Optional[Any]			,		UpperCamelCase__    :    Dict			,		UpperCamelCase__    :    Optional[int]			,		UpperCamelCase__    :    str):






											'''simple docstring'''







											snake_case__	  =       MobileBertForMaskedLM(config=__UpperCamelCase)
											model.to(__UpperCamelCase)
											model.eval()
											snake_case__	  =       model(__UpperCamelCase			,		attention_mask=__UpperCamelCase			,		token_type_ids=__UpperCamelCase			,		labels=__UpperCamelCase)
											self.parent.assertEqual(result.logits.shape			,		(self.batch_size, self.seq_length, self.vocab_size))



				def 					__magic_name__							(      self    :    Dict			,		UpperCamelCase__    :    int			,		UpperCamelCase__    :    Dict			,		UpperCamelCase__    :    Dict			,		UpperCamelCase__    :    Tuple			,		UpperCamelCase__    :    List[str]			,		UpperCamelCase__    :    List[Any]			,		UpperCamelCase__    :    List[str]):






											'''simple docstring'''







											snake_case__	  =       MobileBertForNextSentencePrediction(config=__UpperCamelCase)
											model.to(__UpperCamelCase)
											model.eval()
											snake_case__	  =       model(
											    __UpperCamelCase			,		attention_mask=__UpperCamelCase			,		token_type_ids=__UpperCamelCase			,		labels=__UpperCamelCase			,		)
											self.parent.assertEqual(result.logits.shape			,		(self.batch_size, 2))



				def 					__magic_name__							(      self    :    List[Any]			,		UpperCamelCase__    :    Tuple			,		UpperCamelCase__    :    Tuple			,		UpperCamelCase__    :    List[str]			,		UpperCamelCase__    :    Tuple			,		UpperCamelCase__    :    Optional[Any]			,		UpperCamelCase__    :    Dict			,		UpperCamelCase__    :    Union[str, Any]):






											'''simple docstring'''







											snake_case__	  =       MobileBertForPreTraining(config=__UpperCamelCase)
											model.to(__UpperCamelCase)
											model.eval()
											snake_case__	  =       model(
											    __UpperCamelCase			,		attention_mask=__UpperCamelCase			,		token_type_ids=__UpperCamelCase			,		labels=__UpperCamelCase			,		next_sentence_label=__UpperCamelCase			,		)
											self.parent.assertEqual(result.prediction_logits.shape			,		(self.batch_size, self.seq_length, self.vocab_size))
											self.parent.assertEqual(result.seq_relationship_logits.shape			,		(self.batch_size, 2))



				def 					__magic_name__							(      self    :    List[Any]			,		UpperCamelCase__    :    Union[str, Any]			,		UpperCamelCase__    :    Optional[Any]			,		UpperCamelCase__    :    Optional[int]			,		UpperCamelCase__    :    Optional[int]			,		UpperCamelCase__    :    str			,		UpperCamelCase__    :    Dict			,		UpperCamelCase__    :    Optional[int]):






											'''simple docstring'''







											snake_case__	  =       MobileBertForQuestionAnswering(config=__UpperCamelCase)
											model.to(__UpperCamelCase)
											model.eval()
											snake_case__	  =       model(
											    __UpperCamelCase			,		attention_mask=__UpperCamelCase			,		token_type_ids=__UpperCamelCase			,		start_positions=__UpperCamelCase			,		end_positions=__UpperCamelCase			,		)
											self.parent.assertEqual(result.start_logits.shape			,		(self.batch_size, self.seq_length))
											self.parent.assertEqual(result.end_logits.shape			,		(self.batch_size, self.seq_length))



				def 					__magic_name__							(      self    :    int			,		UpperCamelCase__    :    Any			,		UpperCamelCase__    :    str			,		UpperCamelCase__    :    int			,		UpperCamelCase__    :    Union[str, Any]			,		UpperCamelCase__    :    List[Any]			,		UpperCamelCase__    :    List[Any]			,		UpperCamelCase__    :    Tuple):






											'''simple docstring'''







											snake_case__	  =       self.num_labels
											snake_case__	  =       MobileBertForSequenceClassification(__UpperCamelCase)
											model.to(__UpperCamelCase)
											model.eval()
											snake_case__	  =       model(__UpperCamelCase			,		attention_mask=__UpperCamelCase			,		token_type_ids=__UpperCamelCase			,		labels=__UpperCamelCase)
											self.parent.assertEqual(result.logits.shape			,		(self.batch_size, self.num_labels))



				def 					__magic_name__							(      self    :    Tuple			,		UpperCamelCase__    :    Optional[int]			,		UpperCamelCase__    :    Optional[int]			,		UpperCamelCase__    :    Optional[Any]			,		UpperCamelCase__    :    Dict			,		UpperCamelCase__    :    int			,		UpperCamelCase__    :    Tuple			,		UpperCamelCase__    :    Tuple):






											'''simple docstring'''







											snake_case__	  =       self.num_labels
											snake_case__	  =       MobileBertForTokenClassification(config=__UpperCamelCase)
											model.to(__UpperCamelCase)
											model.eval()
											snake_case__	  =       model(__UpperCamelCase			,		attention_mask=__UpperCamelCase			,		token_type_ids=__UpperCamelCase			,		labels=__UpperCamelCase)
											self.parent.assertEqual(result.logits.shape			,		(self.batch_size, self.seq_length, self.num_labels))



				def 					__magic_name__							(      self    :    Tuple			,		UpperCamelCase__    :    List[str]			,		UpperCamelCase__    :    List[Any]			,		UpperCamelCase__    :    Optional[int]			,		UpperCamelCase__    :    Union[str, Any]			,		UpperCamelCase__    :    str			,		UpperCamelCase__    :    List[Any]			,		UpperCamelCase__    :    Any):






											'''simple docstring'''







											snake_case__	  =       self.num_choices
											snake_case__	  =       MobileBertForMultipleChoice(config=__UpperCamelCase)
											model.to(__UpperCamelCase)
											model.eval()
											snake_case__	  =       input_ids.unsqueeze(1).expand(-1			,		self.num_choices			,		-1).contiguous()
											snake_case__	  =       token_type_ids.unsqueeze(1).expand(-1			,		self.num_choices			,		-1).contiguous()
											snake_case__	  =       input_mask.unsqueeze(1).expand(-1			,		self.num_choices			,		-1).contiguous()
											snake_case__	  =       model(
											    __UpperCamelCase			,		attention_mask=__UpperCamelCase			,		token_type_ids=__UpperCamelCase			,		labels=__UpperCamelCase			,		)
											self.parent.assertEqual(result.logits.shape			,		(self.batch_size, self.num_choices))



				def 					__magic_name__							(      self    :    int):






											'''simple docstring'''







											snake_case__	  =       self.prepare_config_and_inputs()
											(
											    (
											    snake_case__
											)  , (
											    snake_case__
											)  , (
											    snake_case__
											)  , (
											    snake_case__
											)  , (
											    snake_case__
											)  , (
											    snake_case__
											)  , (
											    snake_case__
											)  , 
											)	  =       config_and_inputs
											snake_case__	  =       {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
											return config, inputs_dict


@require_torch
class    _lowerCAmelCase			(		_UpperCAmelCase     ,      _UpperCAmelCase     ,      unittest.TestCase      ):



				"""simple docstring"""



				_lowercase				:   Optional[int]      =  (
				    (
				        MobileBertModel,
				        MobileBertForMaskedLM,
				        MobileBertForMultipleChoice,
				        MobileBertForNextSentencePrediction,
				        MobileBertForPreTraining,
				        MobileBertForQuestionAnswering,
				        MobileBertForSequenceClassification,
				        MobileBertForTokenClassification,
				    )
				    if is_torch_available()
				    else ()
				)
				_lowercase				:   Any      =  (
				    {
				        'feature-extraction': MobileBertModel,
				        'fill-mask': MobileBertForMaskedLM,
				        'question-answering': MobileBertForQuestionAnswering,
				        'text-classification': MobileBertForSequenceClassification,
				        'token-classification': MobileBertForTokenClassification,
				        'zero-shot': MobileBertForSequenceClassification,
				    }
				    if is_torch_available()
				    else {}
				)
				_lowercase				:   Optional[int]      =  True



				def 					__magic_name__							(      self    :    int			,		UpperCamelCase__    :    Any			,		UpperCamelCase__    :    Tuple			,		UpperCamelCase__    :    Union[str, Any]=False):






											'''simple docstring'''







											snake_case__	  =       super()._prepare_for_class(__UpperCamelCase			,		__UpperCamelCase			,		return_labels=__UpperCamelCase)

											if return_labels:
																		if model_class in get_values(__UpperCamelCase):
																									snake_case__	  =       torch.zeros(
																									    (self.model_tester.batch_size, self.model_tester.seq_length)			,		dtype=torch.long			,		device=__UpperCamelCase)
																									snake_case__	  =       torch.zeros(
																									    self.model_tester.batch_size			,		dtype=torch.long			,		device=__UpperCamelCase)
											return inputs_dict



				def 					__magic_name__							(      self    :    Tuple):






											'''simple docstring'''







											snake_case__	  =       MobileBertModelTester(self)
											snake_case__	  =       ConfigTester(self			,		config_class=__UpperCamelCase			,		hidden_size=3_7)



				def 					__magic_name__							(      self    :    List[str]):






											'''simple docstring'''







											self.config_tester.run_common_tests()



				def 					__magic_name__							(      self    :    Dict):






											'''simple docstring'''







											snake_case__	  =       self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_mobilebert_model(*__UpperCamelCase)



				def 					__magic_name__							(      self    :    Dict):






											'''simple docstring'''







											snake_case__	  =       self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_mobilebert_for_masked_lm(*__UpperCamelCase)



				def 					__magic_name__							(      self    :    List[str]):






											'''simple docstring'''







											snake_case__	  =       self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_mobilebert_for_multiple_choice(*__UpperCamelCase)



				def 					__magic_name__							(      self    :    Any):






											'''simple docstring'''







											snake_case__	  =       self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*__UpperCamelCase)



				def 					__magic_name__							(      self    :    List[str]):






											'''simple docstring'''







											snake_case__	  =       self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_mobilebert_for_pretraining(*__UpperCamelCase)



				def 					__magic_name__							(      self    :    Dict):






											'''simple docstring'''







											snake_case__	  =       self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_mobilebert_for_question_answering(*__UpperCamelCase)



				def 					__magic_name__							(      self    :    Any):






											'''simple docstring'''







											snake_case__	  =       self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_mobilebert_for_sequence_classification(*__UpperCamelCase)



				def 					__magic_name__							(      self    :    Union[str, Any]):






											'''simple docstring'''







											snake_case__	  =       self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_mobilebert_for_token_classification(*__UpperCamelCase)


def _UpperCAmelCase   (	a						:	List[Any] ):
							return torch.tensor(
							    _A  ,					dtype=torch.long  ,					device=_A  ,					)


a__       =     1e-3



@require_torch
@require_sentencepiece
@require_tokenizers
class    _lowerCAmelCase			(		unittest.TestCase      ):



				"""simple docstring"""



				@slow
				def 					__magic_name__							(      self    :    int):






											'''simple docstring'''







											snake_case__	  =       MobileBertModel.from_pretrained("""google/mobilebert-uncased""").to(__UpperCamelCase)
											snake_case__	  =       _long_tensor([[1_0_1, 7_1_1_0, 1_0_0_5, 1_0_5_6, 2_0_2_3, 1_1_3_3_3, 1_7_4_1_3, 1_0_2_9, 1_0_2]])
											with torch.no_grad():
																		snake_case__	  =       model(__UpperCamelCase)[0]
											snake_case__	  =       torch.Size((1, 9, 5_1_2))
											self.assertEqual(output.shape			,		__UpperCamelCase)
											snake_case__	  =       torch.tensor(
											    [
											        [
											            [-2.4_736_526E07, 8.2_691_656E04, 1.6_521_838E05],
											            [-5.7_541_704E-01, 3.9_056_022E00, 4.4_011_507E00],
											            [2.6_047_359E00, 1.5_677_652E00, -1.7_324_188E-01],
											        ]
											    ]			,		device=__UpperCamelCase			,		)

											# MobileBERT results range from 10e0 to 10e8. Even a 0.0000001% difference with a value of 10e8 results in a
											# ~1 difference, it's therefore not a good idea to measure using addition.
											# Here, we instead divide the expected result with the result in order to obtain ~1. We then check that the
											# result is held between bounds: 1 - TOLERANCE < expected_result / result < 1 + TOLERANCE
											snake_case__	  =       torch.all((expected_slice / output[..., :3, :3]) >= 1 - TOLERANCE)
											snake_case__	  =       torch.all((expected_slice / output[..., :3, :3]) <= 1 + TOLERANCE)

											self.assertTrue(lower_bound and upper_bound)








from typing import List, Optional, Union

import numpy as np
import tensorflow as tf

from .utils import logging


a__       =     logging.get_logger(__name__)

def _UpperCAmelCase   (	a						:	Union[tf.Tensor, np.ndarray] ):
							if isinstance(a  ,					np.ndarray ):
														return list(tensor.shape )

							snake_case__	  =       tf.shape(a )

							if tensor.shape == tf.TensorShape(a ):
														return dynamic

							snake_case__	  =       tensor.shape.as_list()

							return [dynamic[i] if s is None else s for i, s in enumerate(a )]

def _UpperCAmelCase   (	a						:	tf.Tensor  ,					a						:	Optional[int] = None  ,					a						:	Optional[str] = None ):
							return tf.nn.softmax(logits=logits + 1e-9  ,					axis=a  ,					name=a )

def _UpperCAmelCase   (	a						:	Optional[int]  ,					a						:	Union[str, Any]  ,					a						:	Dict  ,					a						:	int=1e-5  ,					a						:	Dict=-1 ):
							# This is a very simplified functional layernorm, designed to duplicate
							# the functionality of PyTorch nn.functional.layer_norm when this is needed to port
							# models in Transformers.

							if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(a  ,					a ):
														raise NotImplementedError("""Only 1D weight and bias tensors are supported for now, with only a single axis.""" )

							# Get mean and variance on the axis to be normalized
							snake_case__  , snake_case__	  =       tf.nn.moments(a  ,					axes=[axis]  ,					keepdims=a )

							if axis != -1:
														# Reshape scale and weight to have the same rank as inputs, but with 1 dimensions
														# on every dimension except axis
														snake_case__	  =       [1] * inputs.shape.rank
														snake_case__	  =       shape_list(a )[axis]
														snake_case__	  =       tf.reshape(a  ,					a )
														snake_case__	  =       tf.reshape(a  ,					a )

							# Compute layer normalization using the batch_normalization
							# function.
							snake_case__	  =       tf.nn.batch_normalization(
							    a  ,					a  ,					a  ,					offset=a  ,					scale=a  ,					variance_epsilon=a  ,					)
							return outputs

def _UpperCAmelCase   (	a						:	Optional[int]  ,					a						:	Dict=0  ,					a						:	List[Any]=-1 ):
							# Replicates the behavior of torch.flatten in TF

							# If end_dim or start_dim is negative, count them from the end
							if end_dim < 0:
														end_dim += input.shape.rank
							if start_dim < 0:
														start_dim += input.shape.rank

							if start_dim == end_dim:
														return input

							snake_case__	  =       tf.shape(a )
							snake_case__	  =       tf.math.reduce_prod(in_shape[start_dim : end_dim + 1] )
							snake_case__	  =       tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]]  ,					axis=0 )
							return tf.reshape(a  ,					a )

def _UpperCAmelCase   (	a						:	tf.Tensor ):
							if not isinstance(a  ,					tf.Tensor ):
														snake_case__	  =       tf.convert_to_tensor(a )  # Catches stray NumPy inputs
							if encoder_attention_mask.shape.rank == 3:
														snake_case__	  =       encoder_attention_mask[:, None, :, :]
							if encoder_attention_mask.shape.rank == 2:
														snake_case__	  =       encoder_attention_mask[:, None, None, :]
							# T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
							# Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow
							# /transformer/transformer_layers.py#L270
							# encoder_extended_attention_mask = (encoder_extended_attention_mask ==
							# encoder_extended_attention_mask.transpose(-1, -2))
							snake_case__	  =       (
							    tf.cast(1  ,					encoder_attention_mask.dtype ) - encoder_extended_attention_mask
							) * encoder_extended_attention_mask.dtype.min

							return encoder_extended_attention_mask

def _UpperCAmelCase   (	a						:	tf.Tensor  ,					a						:	int  ,					a						:	str = "input_ids" ):
							tf.debugging.assert_less(
							    a  ,					tf.cast(a  ,					dtype=tensor.dtype )  ,					message=(
							        F'''The maximum value of {tensor_name} ({tf.math.reduce_max(a )}) must be smaller than the embedding '''
							        F'''layer\'s input dimension ({embed_dim}). The likely cause is some problem at tokenization time.'''
							    )  ,					)

def _UpperCAmelCase   (	a						:	str  ,					a						:	Tuple  ,					a						:	Optional[int] ):
							snake_case__	  =       6_4512
							# Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT`
							# because in that case even chunking the array would not make the saving
							# possible.
							snake_case__	  =       [x for x in data if len(a ) > HDF5_OBJECT_HEADER_LIMIT]

							# Expecting this to never be true.
							if bad_attributes:
														raise RuntimeError(
														    """The following attributes cannot be saved to HDF5 file because """
														    F'''they are larger than {HDF5_OBJECT_HEADER_LIMIT} '''
														    F'''bytes: {bad_attributes}''' )

							snake_case__	  =       np.asarray(a )

							snake_case__	  =       1
							snake_case__	  =       np.array_split(a  ,					a )

							# This will never loop forever thanks to the test above.
							while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data ):
														num_chunks += 1
														snake_case__	  =       np.array_split(a  ,					a )

							if num_chunks > 1:
														for chunk_id, chunk_data in enumerate(a ):
																					snake_case__	  =       chunk_data
							else:
														snake_case__	  =       data

def _UpperCAmelCase   (	a						:	List[Any]  ,					a						:	Optional[int] ):
							if name in group.attrs:
														snake_case__	  =       [n.decode("""utf8""" ) if hasattr(a  ,					"""decode""" ) else n for n in group.attrs[name]]
							else:
														snake_case__	  =       []
														snake_case__	  =       0
														while "%s%d" % (name, chunk_id) in group.attrs:
																					data.extend(
																					    [n.decode("""utf8""" ) if hasattr(a  ,					"""decode""" ) else n for n in group.attrs["""%s%d""" % (name, chunk_id)]] )
																					chunk_id += 1
							return data



def _UpperCAmelCase   (	a						:	Optional[int] ):

							def _expand_single_ad_tensor(a						:	Any ):
														if isinstance(a  ,					tf.Tensor ) and t.shape.rank == 1:
																					return tf.expand_dims(a  ,					axis=-1 )
														return t

							return tf.nest.map_structure(_expand_single_ad_tensor  ,					a )
