




'''simple docstring'''


import argparse
import collections

import numpy as np
import torch
from flax import traverse_util
from tax import checkpoints

from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration
from transformers.utils import logging


logging.set_verbosity_info()
def 	snake_case_					(UpperCamelCase :						Optional[int]				,		UpperCamelCase :						str				,		UpperCamelCase :						int   ):





							'''simple docstring'''


							return params[f'{prefix}/{prefix}/relpos_bias/rel_embedding'][:, i, :]
def 	snake_case_					(UpperCamelCase :						int				,		UpperCamelCase :						str				,		UpperCamelCase :						Tuple				,		UpperCamelCase :						Optional[int]="attention"   ):





							'''simple docstring'''


							_a			  =       np.ascontiguousarray(params[f'{prefix}/{prefix}/{layer_name}/key/kernel'][:, i, :, :]   )
							_a			  =       k_tmp.reshape(k_tmp.shape[0]				,		k_tmp.shape[1] * k_tmp.shape[2]   )
							_a			  =       np.ascontiguousarray(params[f'{prefix}/{prefix}/{layer_name}/out/kernel'][:, i, :, :]   )
							_a			  =       o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1]				,		o_tmp.shape[2]   )
							_a			  =       np.ascontiguousarray(params[f'{prefix}/{prefix}/{layer_name}/query/kernel'][:, i, :, :]   )
							_a			  =       q_tmp.reshape(q_tmp.shape[0]				,		q_tmp.shape[1] * q_tmp.shape[2]   )
							_a			  =       np.ascontiguousarray(params[f'{prefix}/{prefix}/{layer_name}/value/kernel'][:, i, :, :]   )
							_a			  =       v_tmp.reshape(v_tmp.shape[0]				,		v_tmp.shape[1] * v_tmp.shape[2]   )
							return k, o, q, v
def 	snake_case_					(UpperCamelCase :						Tuple				,		UpperCamelCase :						Tuple				,		UpperCamelCase :						Dict				,		UpperCamelCase :						str=False   ):





							'''simple docstring'''


							if split_mlp_wi:
														_a			  =       params[f'{prefix}/{prefix}/mlp/wi_0/kernel'][:, i, :]
														_a			  =       params[f'{prefix}/{prefix}/mlp/wi_1/kernel'][:, i, :]
														_a			  =       (wi_a, wi_a)
							else:
														_a			  =       params[f'{prefix}/{prefix}/mlp/wi/kernel'][:, i, :]

							_a			  =       params[f'{prefix}/{prefix}/mlp/wo/kernel'][:, i, :]
							return wi, wo
def 	snake_case_					(UpperCamelCase :						List[Any]				,		UpperCamelCase :						Union[str, Any]				,		UpperCamelCase :						Optional[Any]				,		UpperCamelCase :						Tuple   ):





							'''simple docstring'''


							return params[f'{prefix}/{prefix}/{layer_name}/scale'][:, i]
def 	snake_case_					(UpperCamelCase :						dict				,		*, UpperCamelCase :						int				,		UpperCamelCase :						bool				,		UpperCamelCase :						bool = False   ):





							'''simple docstring'''


							_a			  =       traverse_util.flatten_dict(variables['''target''']   )
							_a			  =       {'''/'''.join(UpperCamelCase   ): v for k, v in old.items()}

							# v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi
							_a			  =       '''encoder/encoder/mlp/wi_0/kernel''' in old
							print('''Split MLP:'''				,		UpperCamelCase   )

							_a			  =       collections.OrderedDict()

							# Shared embeddings.
							_a			  =       old['''token_embedder/embedding''']

							# Encoder.
							for i in range(UpperCamelCase   ):
														# Block i, layer 0 (Self Attention).
														_a			  =       tax_layer_norm_lookup(UpperCamelCase				,		UpperCamelCase				,		'''encoder'''				,		'''pre_attention_layer_norm'''   )
														_a			  =       tax_attention_lookup(UpperCamelCase				,		UpperCamelCase				,		'''encoder'''				,		'''attention'''   )
														_a			  =       layer_norm
														_a			  =       k.T
														_a			  =       o.T
														_a			  =       q.T
														_a			  =       v.T

														# Block i, layer 1 (MLP).
														_a			  =       tax_layer_norm_lookup(UpperCamelCase				,		UpperCamelCase				,		'''encoder'''				,		'''pre_mlp_layer_norm'''   )
														_a			  =       tax_mlp_lookup(UpperCamelCase				,		UpperCamelCase				,		'''encoder'''				,		UpperCamelCase   )
														_a			  =       layer_norm
														if split_mlp_wi:
																					_a			  =       wi[0].T
																					_a			  =       wi[1].T
														else:
																					_a			  =       wi.T
														_a			  =       wo.T
														if scalable_attention:
																					# convert the rel_embedding of each layer
																					_a			  =       tax_relpos_bias_lookup(
																					    UpperCamelCase				,		UpperCamelCase				,		'''encoder'''   ).T

							_a			  =       old['''encoder/encoder_norm/scale''']

							if not scalable_attention:
														_a			  =       tax_relpos_bias_lookup(
														    UpperCamelCase				,		0				,		'''encoder'''   ).T
														_a			  =       tax_relpos_bias_lookup(
														    UpperCamelCase				,		0				,		'''decoder'''   ).T

							if not is_encoder_only:
														# Decoder.
														for i in range(UpperCamelCase   ):
																					# Block i, layer 0 (Self Attention).
																					_a			  =       tax_layer_norm_lookup(UpperCamelCase				,		UpperCamelCase				,		'''decoder'''				,		'''pre_self_attention_layer_norm'''   )
																					_a			  =       tax_attention_lookup(UpperCamelCase				,		UpperCamelCase				,		'''decoder'''				,		'''self_attention'''   )
																					_a			  =       layer_norm
																					_a			  =       k.T
																					_a			  =       o.T
																					_a			  =       q.T
																					_a			  =       v.T

																					# Block i, layer 1 (Cross Attention).
																					_a			  =       tax_layer_norm_lookup(UpperCamelCase				,		UpperCamelCase				,		'''decoder'''				,		'''pre_cross_attention_layer_norm'''   )
																					_a			  =       tax_attention_lookup(UpperCamelCase				,		UpperCamelCase				,		'''decoder'''				,		'''encoder_decoder_attention'''   )
																					_a			  =       layer_norm
																					_a			  =       k.T
																					_a			  =       o.T
																					_a			  =       q.T
																					_a			  =       v.T

																					# Block i, layer 2 (MLP).
																					_a			  =       tax_layer_norm_lookup(UpperCamelCase				,		UpperCamelCase				,		'''decoder'''				,		'''pre_mlp_layer_norm'''   )
																					_a			  =       tax_mlp_lookup(UpperCamelCase				,		UpperCamelCase				,		'''decoder'''				,		UpperCamelCase   )
																					_a			  =       layer_norm
																					if split_mlp_wi:
																												_a			  =       wi[0].T
																												_a			  =       wi[1].T
																					else:
																												_a			  =       wi.T
																					_a			  =       wo.T

																					if scalable_attention:
																												# convert the rel_embedding of each layer
																												_a			  =       tax_relpos_bias_lookup(UpperCamelCase				,		UpperCamelCase				,		'''decoder'''   ).T

														_a			  =       old['''decoder/decoder_norm/scale''']

														# LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead)
														if "decoder/logits_dense/kernel" in old:
																					_a			  =       old['''decoder/logits_dense/kernel'''].T

							return new
def 	snake_case_					(UpperCamelCase :						Dict				,		UpperCamelCase :						bool   ):





							'''simple docstring'''


							_a			  =       collections.OrderedDict([(k, torch.from_numpy(v.copy()   )) for (k, v) in converted_params.items()]   )

							# Add what is missing.
							if "encoder.embed_tokens.weight" not in state_dict:
														_a			  =       state_dict['''shared.weight''']

							if not is_encoder_only:
														if "decoder.embed_tokens.weight" not in state_dict:
																					_a			  =       state_dict['''shared.weight''']

														if "lm_head.weight" not in state_dict:  # For old 1.0 models.
																					print('''Using shared word embeddings as lm_head.'''   )
																					_a			  =       state_dict['''shared.weight''']

							return state_dict
def 	snake_case_					(UpperCamelCase :						Union[str, Any]				,		UpperCamelCase :						Union[str, Any]				,		UpperCamelCase :						Any				,		UpperCamelCase :						Dict				,		UpperCamelCase :						Optional[int]   ):





							'''simple docstring'''


							_a			  =       checkpoints.load_tax_checkpoint(UpperCamelCase   )
							_a			  =       convert_tax_to_pytorch(
							    UpperCamelCase				,		num_layers=config.num_layers				,		is_encoder_only=UpperCamelCase				,		scalable_attention=UpperCamelCase   )
							_a			  =       make_state_dict(UpperCamelCase				,		UpperCamelCase   )
							model.load_state_dict(UpperCamelCase				,		strict=UpperCamelCase   )
def 	snake_case_					(UpperCamelCase :						Tuple				,		UpperCamelCase :						Tuple				,		UpperCamelCase :						str				,		UpperCamelCase :						bool = False				,		UpperCamelCase :						bool = False				,		):





							'''simple docstring'''


							_a			  =       MTaConfig.from_json_file(UpperCamelCase   )
							print(f'Building PyTorch model from configuration: {config}'   )
							# Non-v1.1 checkpoints could also use T5Model, but this works for all.
							# The v1.0 checkpoints will simply have an LM head that is the word embeddings.
							if is_encoder_only:
														_a			  =       UMTaEncoderModel(UpperCamelCase   )
							else:
														_a			  =       UMTaForConditionalGeneration(UpperCamelCase   )

							# Load weights from tf checkpoint
							load_tax_weights_in_ta(UpperCamelCase				,		UpperCamelCase				,		UpperCamelCase				,		UpperCamelCase				,		UpperCamelCase   )

							# Save pytorch-model
							print(f'Save PyTorch model to {pytorch_dump_path}'   )
							model.save_pretrained(UpperCamelCase   )

							# Verify that we can load the checkpoint.
							model.from_pretrained(UpperCamelCase   )
							print('''Done'''   )


if __name__ == "__main__":
				_snake_case   :   str     							=	argparse.ArgumentParser(description='Converts a native T5X checkpoint into a PyTorch checkpoint.')
				# Required parameters
				parser.add_argument(
				    '--t5x_checkpoint_path', default=None, type=str, required=True, help='Path to the T5X checkpoint.'
				)
				parser.add_argument(
				    '--config_file',
				    default=None,
				    type=str,
				    required=True,
				    help='The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.',
				)
				parser.add_argument(
				    '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
				)
				parser.add_argument(
				    '--is_encoder_only', action='store_true', help='Check if the model is encoder-decoder model', default=False
				)
				parser.add_argument(
				    '--scalable_attention',
				    action='store_true',
				    help='Whether the model uses scaled attention (umt5 model)',
				    default=False,
				)
				_snake_case   :   int     							=	parser.parse_args()
				convert_tax_checkpoint_to_pytorch(
				    args.tax_checkpoint_path,
				    args.config_file,
				    args.pytorch_dump_path,
				    args.is_encoder_only,
				    args.scalable_attention,
				)







'''simple docstring'''


import copy
import os
import tempfile
from unittest import TestCase
from unittest.mock import patch

import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
import pytest

from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence
from datasets.features import ArrayaD, ClassLabel, Features, Image, Value
from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects
from datasets.keyhash import DuplicatedKeysError, InvalidKeyError

from .utils import require_pil

class     A					(	_a					):







							def      __lowerCAmelCase    (						self :						List[Any]      )    ->							List[Any]:


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence([1, 2, 3]      )      )
														self.assertEqual(arr.type							,    pa.intaa()      )







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


														"""simple docstring"""


														with self.assertRaises(lowerCAmelCase_      ):
																					_a			  =       pa.array(TypedSequence([1, 2, 3]      )							,    type=pa.intaa()      )







							def      __lowerCAmelCase    (						self :						Dict      )    ->							Dict:


														"""simple docstring"""


														with self.assertRaises(lowerCAmelCase_      ):
																					_a			  =       pa.array(TypedSequence([1, 2, 3]							,    try_type=Value('''bool'''      )							,    type=Value('''int64'''      )      )      )







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


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence([1, 2, 3]							,    type=Value('''int32'''      )      )      )
														self.assertEqual(arr.type							,    pa.intaa()      )







							def      __lowerCAmelCase    (						self :						Any      )    ->							List[Any]:


														"""simple docstring"""


														with self.assertRaises((TypeError, pa.lib.ArrowInvalid)      ):
																					_a			  =       pa.array(TypedSequence(['''foo''', '''bar''']							,    type=Value('''int64'''      )      )      )







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


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence([1, 2, 3]							,    try_type=Value('''int32'''      )      )      )
														self.assertEqual(arr.type							,    pa.intaa()      )







							def      __lowerCAmelCase    (						self :						Any      )    ->							Tuple:


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence(['''foo''', '''bar''']							,    try_type=Value('''int64'''      )      )      )
														self.assertEqual(arr.type							,    pa.string()      )







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


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence([[[1, 2, 3]]]							,    type=ArrayaD((1, 3)							,    '''int64'''      )      )      )
														self.assertEqual(arr.type							,    ArrayaDExtensionType((1, 3)							,    '''int64'''      )      )







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


														"""simple docstring"""


														with self.assertRaises((TypeError, pa.lib.ArrowInvalid)      ):
																					_a			  =       pa.array(TypedSequence(['''foo''', '''bar''']							,    type=ArrayaD((1, 3)							,    '''int64'''      )      )      )







							def      __lowerCAmelCase    (						self :						Tuple      )    ->							Tuple:


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence([[[1, 2, 3]]]							,    try_type=ArrayaD((1, 3)							,    '''int64'''      )      )      )
														self.assertEqual(arr.type							,    ArrayaDExtensionType((1, 3)							,    '''int64'''      )      )







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


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence(['''foo''', '''bar''']							,    try_type=ArrayaD((1, 3)							,    '''int64'''      )      )      )
														self.assertEqual(arr.type							,    pa.string()      )







							@require_pil
							def      __lowerCAmelCase    (						self :						Tuple      )    ->							List[Any]:


														"""simple docstring"""


														import PIL.Image

														_a			  =       PIL.Image.fromarray(np.arange(10							,    dtype=np.uinta      ).reshape(2							,    5      )      )
														with patch(
														    '''datasets.arrow_writer.cast_to_python_objects'''							,    side_effect=lowerCAmelCase_      ) as mock_cast_to_python_objects:
																					_a			  =       pa.array(TypedSequence([{'''path''': None, '''bytes''': B'''image_bytes'''}, pil_image]							,    type=Image()      )      )
																					_a  ,							_a			  =       mock_cast_to_python_objects.call_args_list[-1]
																					self.assertIn('''optimize_list_casting'''							,    lowerCAmelCase_      )
																					self.assertFalse(kwargs['''optimize_list_casting''']      )



def 	snake_case_					(UpperCamelCase :						Union[str, Any]				,		UpperCamelCase :						int   ):





							'''simple docstring'''


							_a			  =       pa.BufferReader(UpperCamelCase   ) if isinstance(UpperCamelCase				,		pa.Buffer   ) else pa.memory_map(UpperCamelCase   )
							_a			  =       pa.ipc.open_stream(UpperCamelCase   )
							_a			  =       f.read_all()
							assert len(pa_table.to_batches()   ) == expected_num_chunks
							assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]}
							del pa_table
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 1, 10]   )
@pytest.mark.parametrize(
    '''fields'''				,		[None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]   )
def 	snake_case_					(UpperCamelCase :						Dict				,		UpperCamelCase :						str   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							_a			  =       pa.schema(UpperCamelCase   ) if fields else None
							with ArrowWriter(stream=UpperCamelCase				,		schema=UpperCamelCase				,		writer_batch_size=UpperCamelCase   ) as writer:
														writer.write({'''col_1''': '''foo''', '''col_2''': 1}   )
														writer.write({'''col_1''': '''bar''', '''col_2''': 2}   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							if not fields:
														_a			  =       {'''col_1''': pa.string(), '''col_2''': pa.intaa()}
							assert writer._schema == pa.schema(UpperCamelCase				,		metadata=writer._schema.metadata   )
							_check_output(output.getvalue()				,		expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )
def 	snake_case_					():





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							_a			  =       Features({'''labels''': ClassLabel(names=['''neg''', '''pos''']   )}   )
							with ArrowWriter(stream=UpperCamelCase				,		features=UpperCamelCase   ) as writer:
														writer.write({'''labels''': 0}   )
														writer.write({'''labels''': 1}   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							assert writer._schema == features.arrow_schema
							assert writer._schema.metadata == features.arrow_schema.metadata
							_a			  =       pa.BufferReader(output.getvalue()   )
							_a			  =       pa.ipc.open_stream(UpperCamelCase   )
							_a			  =       f.read_all()
							_a			  =       pa_table.schema
							assert pa_table.num_rows == 2
							assert schema == features.arrow_schema
							assert schema.metadata == features.arrow_schema.metadata
							assert features == Features.from_arrow_schema(UpperCamelCase   )
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 1, 10]   )
def 	snake_case_					(UpperCamelCase :						Any   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							with ArrowWriter(
							    stream=UpperCamelCase				,		writer_batch_size=UpperCamelCase				,		hash_salt='''split_name'''				,		check_duplicates=UpperCamelCase				,		) as writer:
														with pytest.raises(UpperCamelCase   ):
																					writer.write({'''col_1''': '''foo''', '''col_2''': 1}				,		key=[1, 2]   )
																					_a  ,							_a			  =       writer.finalize()
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 2, 10]   )
def 	snake_case_					(UpperCamelCase :						Any   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							with ArrowWriter(
							    stream=UpperCamelCase				,		writer_batch_size=UpperCamelCase				,		hash_salt='''split_name'''				,		check_duplicates=UpperCamelCase				,		) as writer:
														with pytest.raises(UpperCamelCase   ):
																					writer.write({'''col_1''': '''foo''', '''col_2''': 1}				,		key=10   )
																					writer.write({'''col_1''': '''bar''', '''col_2''': 2}				,		key=10   )
																					_a  ,							_a			  =       writer.finalize()
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 2, 10]   )
def 	snake_case_					(UpperCamelCase :						int   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							with ArrowWriter(
							    stream=UpperCamelCase				,		writer_batch_size=UpperCamelCase				,		hash_salt='''split_name'''				,		check_duplicates=UpperCamelCase				,		) as writer:
														writer.write({'''col_1''': '''foo''', '''col_2''': 1}				,		key=1   )
														writer.write({'''col_1''': '''bar''', '''col_2''': 2}				,		key=2   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							_check_output(output.getvalue()				,		expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 1, 10]   )
@pytest.mark.parametrize(
    '''fields'''				,		[None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]   )
def 	snake_case_					(UpperCamelCase :						Dict				,		UpperCamelCase :						List[str]   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							_a			  =       pa.schema(UpperCamelCase   ) if fields else None
							with ArrowWriter(stream=UpperCamelCase				,		schema=UpperCamelCase				,		writer_batch_size=UpperCamelCase   ) as writer:
														writer.write_batch({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]}   )
														writer.write_batch({'''col_1''': [], '''col_2''': []}   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							if not fields:
														_a			  =       {'''col_1''': pa.string(), '''col_2''': pa.intaa()}
							assert writer._schema == pa.schema(UpperCamelCase				,		metadata=writer._schema.metadata   )
							_check_output(output.getvalue()				,		expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 1, 10]   )
@pytest.mark.parametrize(
    '''fields'''				,		[None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]   )
def 	snake_case_					(UpperCamelCase :						Any				,		UpperCamelCase :						Any   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							_a			  =       pa.schema(UpperCamelCase   ) if fields else None
							with ArrowWriter(stream=UpperCamelCase				,		schema=UpperCamelCase				,		writer_batch_size=UpperCamelCase   ) as writer:
														writer.write_table(pa.Table.from_pydict({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]}   )   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							if not fields:
														_a			  =       {'''col_1''': pa.string(), '''col_2''': pa.intaa()}
							assert writer._schema == pa.schema(UpperCamelCase				,		metadata=writer._schema.metadata   )
							_check_output(output.getvalue()				,		expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 1, 10]   )
@pytest.mark.parametrize(
    '''fields'''				,		[None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]   )
def 	snake_case_					(UpperCamelCase :						int				,		UpperCamelCase :						Optional[int]   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							_a			  =       pa.schema(UpperCamelCase   ) if fields else None
							with ArrowWriter(stream=UpperCamelCase				,		schema=UpperCamelCase				,		writer_batch_size=UpperCamelCase   ) as writer:
														writer.write_row(pa.Table.from_pydict({'''col_1''': ['''foo'''], '''col_2''': [1]}   )   )
														writer.write_row(pa.Table.from_pydict({'''col_1''': ['''bar'''], '''col_2''': [2]}   )   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							if not fields:
														_a			  =       {'''col_1''': pa.string(), '''col_2''': pa.intaa()}
							assert writer._schema == pa.schema(UpperCamelCase				,		metadata=writer._schema.metadata   )
							_check_output(output.getvalue()				,		expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )
def 	snake_case_					():





							'''simple docstring'''


							with tempfile.TemporaryDirectory() as tmp_dir:
														_a			  =       {'''col_1''': pa.string(), '''col_2''': pa.intaa()}
														_a			  =       os.path.join(UpperCamelCase				,		'''test.arrow'''   )
														with ArrowWriter(path=UpperCamelCase				,		schema=pa.schema(UpperCamelCase   )   ) as writer:
																					writer.write_batch({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]}   )
																					_a  ,							_a			  =       writer.finalize()
														assert num_examples == 2
														assert num_bytes > 0
														assert writer._schema == pa.schema(UpperCamelCase				,		metadata=writer._schema.metadata   )
														_check_output(UpperCamelCase				,		1   )
def 	snake_case_					(UpperCamelCase :						List[str]   ):





							'''simple docstring'''


							if pa.types.is_list(UpperCamelCase   ):
														return get_base_dtype(arr_type.value_type   )
							else:
														return arr_type
def 	snake_case_					(UpperCamelCase :						Optional[int]				,		UpperCamelCase :						Any   ):





							'''simple docstring'''


							if isinstance(lst[0]				,		UpperCamelCase   ):
														change_first_primitive_element_in_list(lst[0]				,		UpperCamelCase   )
							else:
														_a			  =       value
@pytest.mark.parametrize('''optimized_int_type, expected_dtype'''				,		[(None, pa.intaa()), (Value('''int32'''   ), pa.intaa())]   )
@pytest.mark.parametrize('''sequence'''				,		[[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]]   )
def 	snake_case_					(UpperCamelCase :						int				,		UpperCamelCase :						Tuple				,		UpperCamelCase :						Optional[int]   ):





							'''simple docstring'''


							_a			  =       pa.array(TypedSequence(UpperCamelCase				,		optimized_int_type=UpperCamelCase   )   )
							assert get_base_dtype(arr.type   ) == expected_dtype
@pytest.mark.parametrize(
    '''col, expected_dtype'''				,		[
        ('''attention_mask''', pa.inta()),
        ('''special_tokens_mask''', pa.inta()),
        ('''token_type_ids''', pa.inta()),
        ('''input_ids''', pa.intaa()),
        ('''other''', pa.intaa()),
    ]				,		)
@pytest.mark.parametrize('''sequence'''				,		[[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]]   )
def 	snake_case_					(UpperCamelCase :						List[Any]				,		UpperCamelCase :						str				,		UpperCamelCase :						List[Any]   ):





							'''simple docstring'''


							_a			  =       pa.array(OptimizedTypedSequence(UpperCamelCase				,		col=UpperCamelCase   )   )
							assert get_base_dtype(arr.type   ) == expected_dtype

							# not in range
							if col != "other":
														# avoids errors due to in-place modifications
														_a			  =       copy.deepcopy(UpperCamelCase   )
														_a			  =       np.iinfo(expected_dtype.to_pandas_dtype()   ).max + 1
														change_first_primitive_element_in_list(UpperCamelCase				,		UpperCamelCase   )
														_a			  =       pa.array(OptimizedTypedSequence(UpperCamelCase				,		col=UpperCamelCase   )   )
														assert get_base_dtype(arr.type   ) == pa.intaa()
@pytest.mark.parametrize('''raise_exception'''				,		[False, True]   )
def 	snake_case_					(UpperCamelCase :						Optional[Any]				,		UpperCamelCase :						Optional[Any]   ):





							'''simple docstring'''


							_a			  =       str(tmp_path / '''dataset-train.arrow'''   )
							try:
														with ArrowWriter(path=UpperCamelCase   ) as writer:
																					if raise_exception:
																												raise pa.lib.ArrowInvalid()
																					else:
																												writer.stream.close()
							except pa.lib.ArrowInvalid:
														pass
							finally:
														assert writer.stream.closed
def 	snake_case_					(UpperCamelCase :						List[Any]   ):





							'''simple docstring'''


							_a			  =       '''mock://dataset-train.arrow'''
							with ArrowWriter(path=UpperCamelCase				,		storage_options=mockfs.storage_options   ) as writer:
														assert isinstance(writer._fs				,		type(UpperCamelCase   )   )
														assert writer._fs.storage_options == mockfs.storage_options
														writer.write({'''col_1''': '''foo''', '''col_2''': 1}   )
														writer.write({'''col_1''': '''bar''', '''col_2''': 2}   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							assert mockfs.exists(UpperCamelCase   )
def 	snake_case_					():





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							with ParquetWriter(stream=UpperCamelCase   ) as writer:
														writer.write({'''col_1''': '''foo''', '''col_2''': 1}   )
														writer.write({'''col_1''': '''bar''', '''col_2''': 2}   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							_a			  =       pa.BufferReader(output.getvalue()   )
							_a			  =       pq.read_table(UpperCamelCase   )
							assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]}
@require_pil
@pytest.mark.parametrize('''embed_local_files'''				,		[False, True]   )
def 	snake_case_					(UpperCamelCase :						List[Any]				,		UpperCamelCase :						List[Any]   ):





							'''simple docstring'''


							import PIL.Image

							_a			  =       str(tmp_path / '''test_image_rgb.jpg'''   )
							PIL.Image.fromarray(np.zeros((5, 5)				,		dtype=np.uinta   )   ).save(UpperCamelCase				,		format='''png'''   )
							_a			  =       pa.BufferOutputStream()
							with ParquetWriter(
							    stream=UpperCamelCase				,		features=Features({'''image''': Image()}   )				,		embed_local_files=UpperCamelCase   ) as writer:
														writer.write({'''image''': image_path}   )
														writer.finalize()
							_a			  =       pa.BufferReader(output.getvalue()   )
							_a			  =       pq.read_table(UpperCamelCase   )
							_a			  =       pa_table.to_pydict()
							if embed_local_files:
														assert isinstance(out['''image'''][0]['''path''']				,		UpperCamelCase   )
														with open(UpperCamelCase				,		'''rb'''   ) as f:
																					assert out["image"][0]["bytes"] == f.read()
							else:
														assert out["image"][0]["path"] == image_path
														assert out["image"][0]["bytes"] is None

def 	snake_case_					():





							'''simple docstring'''


							_a			  =       pa.schema([pa.field('''col_1'''				,		pa.string()				,		nullable=UpperCamelCase   )]   )
							_a			  =       pa.BufferOutputStream()
							with ArrowWriter(stream=UpperCamelCase   ) as writer:
														writer._build_writer(inferred_schema=UpperCamelCase   )
														assert writer._schema == pa.schema([pa.field('''col_1'''				,		pa.string()   )]   )

