

"""simple docstring"""





import unittest

from parameterized import parameterized

from transformers import LlamaConfig, is_torch_available, set_seed
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
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 LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer




class 					_lowerCAmelCase  :







 """simple docstring"""







 def __init__(			self							:			Union[str, Any],					UpperCAmelCase__							:			Any,					UpperCAmelCase__							:			Dict=1_3,					UpperCAmelCase__							:			List[Any]=7,					UpperCAmelCase__							:			List[Any]=True,					UpperCAmelCase__							:			Any=True,					UpperCAmelCase__							:			Optional[int]=False,					UpperCAmelCase__							:			Tuple=True,					UpperCAmelCase__							:			List[str]=9_9,					UpperCAmelCase__							:			Union[str, Any]=3_2,					UpperCAmelCase__							:			List[Any]=5,					UpperCAmelCase__							:			Dict=4,					UpperCAmelCase__							:			List[Any]=3_7,					UpperCAmelCase__							:			Any="gelu",					UpperCAmelCase__							:			Union[str, Any]=0.1,					UpperCAmelCase__							:			Tuple=0.1,					UpperCAmelCase__							:			List[Any]=5_1_2,					UpperCAmelCase__							:			Any=1_6,					UpperCAmelCase__							:			Optional[int]=2,					UpperCAmelCase__							:			Any=0.02,					UpperCAmelCase__							:			Dict=3,					UpperCAmelCase__							:			Union[str, Any]=4,					UpperCAmelCase__							:			Tuple=None,					):
    __lowercase								=						parent
    __lowercase								=						batch_size
    __lowercase								=						seq_length
    __lowercase								=						is_training
    __lowercase								=						use_input_mask
    __lowercase								=						use_token_type_ids
    __lowercase								=						use_labels
    __lowercase								=						vocab_size
    __lowercase								=						hidden_size
    __lowercase								=						num_hidden_layers
    __lowercase								=						num_attention_heads
    __lowercase								=						intermediate_size
    __lowercase								=						hidden_act
    __lowercase								=						hidden_dropout_prob
    __lowercase								=						attention_probs_dropout_prob
    __lowercase								=						max_position_embeddings
    __lowercase								=						type_vocab_size
    __lowercase								=						type_sequence_label_size
    __lowercase								=						initializer_range
    __lowercase								=						num_labels
    __lowercase								=						num_choices
    __lowercase								=						scope


 def 					_lowercase (			self							:			Dict	):
    __lowercase								=						ids_tensor([self.batch_size, self.seq_length],					self.vocab_size	)

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

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

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

    __lowercase								=						self.get_config()

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


 def 					_lowercase (			self							:			int	):
    return LlamaConfig(
        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,					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=lowercase_,					initializer_range=self.initializer_range,					)


 def 					_lowercase (			self							:			Tuple,					UpperCAmelCase__							:			Optional[int],					UpperCAmelCase__							:			Tuple,					UpperCAmelCase__							:			List[Any],					UpperCAmelCase__							:			str,					UpperCAmelCase__							:			Optional[Any],					UpperCAmelCase__							:			Optional[int],					UpperCAmelCase__							:			List[Any]	):
    __lowercase								=						LlamaModel(config=lowercase_	)
    model.to(lowercase_	)
    model.eval()
    __lowercase								=						model(lowercase_,					attention_mask=lowercase_	)
    __lowercase								=						model(lowercase_	)
    self.parent.assertEqual(result.last_hidden_state.shape,					(self.batch_size, self.seq_length, self.hidden_size)	)


 def 					_lowercase (			self							:			int,					UpperCAmelCase__							:			Tuple,					UpperCAmelCase__							:			Optional[int],					UpperCAmelCase__							:			int,					UpperCAmelCase__							:			List[str],					UpperCAmelCase__							:			Dict,					UpperCAmelCase__							:			Any,					UpperCAmelCase__							:			str,					UpperCAmelCase__							:			Dict,					UpperCAmelCase__							:			str,					):
    __lowercase								=						True
    __lowercase								=						LlamaModel(lowercase_	)
    model.to(lowercase_	)
    model.eval()
    __lowercase								=						model(
        lowercase_,					attention_mask=lowercase_,					encoder_hidden_states=lowercase_,					encoder_attention_mask=lowercase_,					)
    __lowercase								=						model(
        lowercase_,					attention_mask=lowercase_,					encoder_hidden_states=lowercase_,					)
    __lowercase								=						model(lowercase_,					attention_mask=lowercase_	)
    self.parent.assertEqual(result.last_hidden_state.shape,					(self.batch_size, self.seq_length, self.hidden_size)	)


 def 					_lowercase (			self							:			Dict,					UpperCAmelCase__							:			Dict,					UpperCAmelCase__							:			List[Any],					UpperCAmelCase__							:			Tuple,					UpperCAmelCase__							:			Dict,					UpperCAmelCase__							:			Tuple,					UpperCAmelCase__							:			str,					UpperCAmelCase__							:			List[Any],					UpperCAmelCase__							:			List[Any],					UpperCAmelCase__							:			Any,					):
    __lowercase								=						LlamaForCausalLM(config=lowercase_	)
    model.to(lowercase_	)
    model.eval()
    __lowercase								=						model(lowercase_,					attention_mask=lowercase_,					labels=lowercase_	)
    self.parent.assertEqual(result.logits.shape,					(self.batch_size, self.seq_length, self.vocab_size)	)


 def 					_lowercase (			self							:			int,					UpperCAmelCase__							:			str,					UpperCAmelCase__							:			Dict,					UpperCAmelCase__							:			str,					UpperCAmelCase__							:			Any,					UpperCAmelCase__							:			Optional[int],					UpperCAmelCase__							:			List[Any],					UpperCAmelCase__							:			str,					UpperCAmelCase__							:			Optional[int],					UpperCAmelCase__							:			Optional[Any],					):
    __lowercase								=						True
    __lowercase								=						True
    __lowercase								=						LlamaForCausalLM(config=lowercase_	)
    model.to(lowercase_	)
    model.eval()

    # first forward pass
    __lowercase								=						model(
        lowercase_,					attention_mask=lowercase_,					encoder_hidden_states=lowercase_,					encoder_attention_mask=lowercase_,					use_cache=lowercase_,					)
    __lowercase								=						outputs.past_key_values

    # create hypothetical multiple next token and extent to next_input_ids
    __lowercase								=						ids_tensor((self.batch_size, 3),					config.vocab_size	)
    __lowercase								=						ids_tensor((self.batch_size, 3),					vocab_size=2	)

    # append to next input_ids and
    __lowercase								=						torch.cat([input_ids, next_tokens],					dim=-1	)
    __lowercase								=						torch.cat([input_mask, next_mask],					dim=-1	)

    __lowercase								=						model(
        lowercase_,					attention_mask=lowercase_,					encoder_hidden_states=lowercase_,					encoder_attention_mask=lowercase_,					output_hidden_states=lowercase_,					)['hidden_states'][0]
    __lowercase								=						model(
        lowercase_,					attention_mask=lowercase_,					encoder_hidden_states=lowercase_,					encoder_attention_mask=lowercase_,					past_key_values=lowercase_,					output_hidden_states=lowercase_,					)['hidden_states'][0]

    # select random slice
    __lowercase								=						ids_tensor((1,),					output_from_past.shape[-1]	).item()
    __lowercase								=						output_from_no_past[:, -3:, random_slice_idx].detach()
    __lowercase								=						output_from_past[:, :, random_slice_idx].detach()

    self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]	)

    # test that outputs are equal for slice
    self.parent.assertTrue(torch.allclose(lowercase_,					lowercase_,					atol=1E-3	)	)



 def 					_lowercase (			self							:			Tuple	):
    __lowercase								=						self.prepare_config_and_inputs()
    (
        __lowercase     
    )								=						config_and_inputs
    __lowercase								=						{'input_ids': input_ids, 'attention_mask': input_mask}
    return config, inputs_dict







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







 """simple docstring"""







 __UpperCAmelCase	:					Optional[Any]   		=	(LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else ()
 __UpperCAmelCase	:					Union[str, Any]   		=	(LlamaForCausalLM,) if is_torch_available() else ()
 __UpperCAmelCase	:					List[Any]   		=	(
     {
         'feature-extraction': LlamaModel,
         'text-classification': LlamaForSequenceClassification,
         'text-generation': LlamaForCausalLM,
         'zero-shot': LlamaForSequenceClassification,
     }
     if is_torch_available()
     else {}
 )
 __UpperCAmelCase	:					Optional[Any]   		=	False
 __UpperCAmelCase	:					Tuple   		=	False


 def 					_lowercase (			self							:			Union[str, Any]	):
    __lowercase								=						LlamaModelTester(self	)
    __lowercase								=						ConfigTester(self,					config_class=lowercase_,					hidden_size=3_7	)


 def 					_lowercase (			self							:			List[str]	):
    self.config_tester.run_common_tests()


 def 					_lowercase (			self							:			Dict	):
    __lowercase								=						self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*lowercase_	)


 def 					_lowercase (			self							:			int	):
    __lowercase								=						self.model_tester.prepare_config_and_inputs()
    for type in ["absolute", "relative_key", "relative_key_query"]:
       __lowercase								=						type
       self.model_tester.create_and_check_model(*lowercase_	)


 def 					_lowercase (			self							:			Tuple	):
    __lowercase								=						self.model_tester.prepare_config_and_inputs_for_common()
    __lowercase								=						3
    __lowercase								=						input_dict['input_ids']
    __lowercase								=						input_ids.ne(1	).to(lowercase_	)
    __lowercase								=						ids_tensor([self.model_tester.batch_size],					self.model_tester.type_sequence_label_size	)
    __lowercase								=						LlamaForSequenceClassification(lowercase_	)
    model.to(lowercase_	)
    model.eval()
    __lowercase								=						model(lowercase_,					attention_mask=lowercase_,					labels=lowercase_	)
    self.assertEqual(result.logits.shape,					(self.model_tester.batch_size, self.model_tester.num_labels)	)


 def 					_lowercase (			self							:			Tuple	):
    __lowercase								=						self.model_tester.prepare_config_and_inputs_for_common()
    __lowercase								=						3
    __lowercase								=						'single_label_classification'
    __lowercase								=						input_dict['input_ids']
    __lowercase								=						input_ids.ne(1	).to(lowercase_	)
    __lowercase								=						ids_tensor([self.model_tester.batch_size],					self.model_tester.type_sequence_label_size	)
    __lowercase								=						LlamaForSequenceClassification(lowercase_	)
    model.to(lowercase_	)
    model.eval()
    __lowercase								=						model(lowercase_,					attention_mask=lowercase_,					labels=lowercase_	)
    self.assertEqual(result.logits.shape,					(self.model_tester.batch_size, self.model_tester.num_labels)	)


 def 					_lowercase (			self							:			Dict	):
    __lowercase								=						self.model_tester.prepare_config_and_inputs_for_common()
    __lowercase								=						3
    __lowercase								=						'multi_label_classification'
    __lowercase								=						input_dict['input_ids']
    __lowercase								=						input_ids.ne(1	).to(lowercase_	)
    __lowercase								=						ids_tensor(
        [self.model_tester.batch_size, config.num_labels],					self.model_tester.type_sequence_label_size	).to(torch.float	)
    __lowercase								=						LlamaForSequenceClassification(lowercase_	)
    model.to(lowercase_	)
    model.eval()
    __lowercase								=						model(lowercase_,					attention_mask=lowercase_,					labels=lowercase_	)
    self.assertEqual(result.logits.shape,					(self.model_tester.batch_size, self.model_tester.num_labels)	)


 @unittest.skip("LLaMA buffers include complex numbers, which breaks this test"	)
 def 					_lowercase (			self							:			int	):
    pass



 @parameterized.expand([("linear",), ("dynamic",)]	)
 def 					_lowercase (			self							:			Optional[int],					UpperCAmelCase__							:			List[Any]	):
    __lowercase								=						self.model_tester.prepare_config_and_inputs_for_common()
    __lowercase								=						ids_tensor([1, 1_0],					config.vocab_size	)
    __lowercase								=						ids_tensor([1, int(config.max_position_embeddings * 1.5	)],					config.vocab_size	)

    set_seed(4_2	)  # Fixed seed at init time so the two models get the same random weights
    __lowercase								=						LlamaModel(lowercase_	)
    original_model.to(lowercase_	)
    original_model.eval()
    __lowercase								=						original_model(lowercase_	).last_hidden_state
    __lowercase								=						original_model(lowercase_	).last_hidden_state

    set_seed(4_2	)  # Fixed seed at init time so the two models get the same random weights
    __lowercase								=						{'type': scaling_type, 'factor': 10.0}
    __lowercase								=						LlamaModel(lowercase_	)
    scaled_model.to(lowercase_	)
    scaled_model.eval()
    __lowercase								=						scaled_model(lowercase_	).last_hidden_state
    __lowercase								=						scaled_model(lowercase_	).last_hidden_state

    # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
    # maximum sequence length, so the outputs for the short input should match.
    if scaling_type == "dynamic":
       self.assertTrue(torch.allclose(lowercase_,					lowercase_,					atol=1E-5	)	)
    else:
       self.assertFalse(torch.allclose(lowercase_,					lowercase_,					atol=1E-5	)	)

    # The output should be different for long inputs
    self.assertFalse(torch.allclose(lowercase_,					lowercase_,					atol=1E-5	)	)







@require_torch
class 					_lowerCAmelCase  (	unittest.TestCase   ):







 """simple docstring"""







 @unittest.skip("Logits are not exactly the same, once we fix the instabalities somehow, will update!"	)
 @slow
 def 					_lowercase (			self							:			Tuple	):
    __lowercase								=						[1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8]
    __lowercase								=						LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf",					device_map="auto"	)
    __lowercase								=						model(torch.tensor([input_ids]	)	)
    # Expected mean on dim = -1
    __lowercase								=						torch.tensor([[-6.6_550, -4.1_227, -4.9_859, -3.2_406, 0.8_262, -3.0_033, 1.2_964, -3.3_699]]	)
    torch.testing.assert_close(out.mean(-1	),					lowercase_,					atol=1E-2,					rtol=1E-2	)
    # slicing logits[0, 0, 0:30]
    # fmt: off
    __lowercase								=						torch.tensor([-12.8_281, -7.4_453, -0.4_639, -8.0_625, -7.2_500, -8.0_000, -6.4_883, -7.7_695, -7.8_438, -7.0_312, -6.2_188, -7.1_328, -1.8_496, 1.9_961, -8.6_250, -6.7_227, -12.8_281, -6.9_492, -7.0_742, -7.7_852, -7.5_820, -7.9_062, -6.9_375, -7.9_805, -8.3_438, -8.1_562, -8.0_469, -7.6_250, -7.7_422, -7.3_398,]	)
    # fmt: on
    torch.testing.assert_close(out[0, 0, :3_0],					lowercase_,					atol=1E-5,					rtol=1E-5	)


 @unittest.skip("Logits are not exactly the same, once we fix the instabalities somehow, will update!"	)
 @slow
 def 					_lowercase (			self							:			int	):
    __lowercase								=						[1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8]
    __lowercase								=						LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-13b-hf",					device_map="auto"	)
    __lowercase								=						model(torch.tensor(lowercase_	)	)
    # Expected mean on dim = -1
    __lowercase								=						torch.tensor([[-2.0_622, -1.2_794, -1.1_638, -0.9_788, -1.4_603, -1.0_238, -1.7_893, -1.4_411]]	)
    torch.testing.assert_close(out.mean(-1	),					lowercase_,					atol=1E-2,					rtol=1E-2	)
    # slicing logits[0, 0, 0:30]
    # fmt: off
    __lowercase								=						torch.tensor([-8.1_406, -8.0_547, 2.7_461, -1.2_344, -0.1_448, -1.8_262, -1.0_020, -1.8_154, -1.6_895, -1.8_516, -2.3_574, -0.9_277, 3.7_598, 6.5_742, -1.2_998, -0.1_177, -8.1_406, -2.9_688, -2.9_199, -3.1_699, -3.5_254, -2.3_555, -2.7_988, -3.4_141, -2.8_262, -4.5_195, -3.3_379, -3.3_164, -2.7_832, -3.0_273]	)
    # fmt: on
    torch.testing.assert_close(out[0, 0, :3_0],					lowercase_,					atol=1E-5,					rtol=1E-5	)


 @unittest.skip("Logits are not exactly the same, once we fix the instabalities somehow, will update!"	)
 @slow
 def 					_lowercase (			self							:			List[Any]	):
    __lowercase								=						[1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8]
    __lowercase								=						LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-13b-chat-hf",					device_map="auto"	)
    __lowercase								=						model(torch.tensor(lowercase_	)	)
    # Expected mean on dim = -1
    __lowercase								=						torch.tensor([[-0.8_562, -1.8_520, -0.7_551, -0.4_162, -1.5_161, -1.2_038, -2.4_823, -2.3_254]]	)
    torch.testing.assert_close(out.mean(-1	),					lowercase_,					atol=1E-2,					rtol=1E-2	)
    # slicing logits[0, 0, 0:30]
    # fmt: off
    __lowercase								=						torch.tensor([-2.2_227, 4.8_828, 0.9_023, -0.4_578, -0.7_871, -0.1_033, -0.6_221, -0.5_786, -0.7_803, -1.0_674, -1.2_920, -0.1_570, 0.8_008, 2.0_723, -0.9_497, 0.2_771, -2.2_227, -0.7_612, -1.4_346, -1.2_061, -1.6_426, -0.3_000, -0.7_139, -1.1_934, -1.8_691, -1.6_973, -1.5_947, -1.2_705, -0.3_523, -0.5_513]	)
    # fmt: on
    torch.testing.assert_close(out.mean(-1	),					lowercase_,					atol=1E-2,					rtol=1E-2	)


 @unittest.skip(
     "Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test"	)
 @slow
 def 					_lowercase (			self							:			int	):
    __lowercase								=						[1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8]
    __lowercase								=						LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-70b-hf",					device_map="auto"	)
    __lowercase								=						model(torch.tensor(lowercase_	)	)

    __lowercase								=						torch.tensor(
        [[-4.2_327, -3.3_360, -4.6_665, -4.7_631, -1.8_180, -3.4_170, -1.4_211, -3.1_810]],					dtype=torch.floataa	)
    torch.testing.assert_close(out.mean(-1	),					lowercase_,					atol=1E-2,					rtol=1E-2	)
    # fmt: off
    __lowercase								=						torch.tensor([-9.4_922, -3.9_551, 1.7_998, -5.6_758, -5.1_055, -5.8_984, -4.8_320, -6.8_086, -6.5_391, -5.6_172, -5.5_820, -5.5_352, 1.7_881, 3.6_289, -6.5_117, -3.4_785, -9.5_000, -6.0_352, -6.8_125, -6.0_195, -6.6_836, -5.4_727, -6.2_812, -6.0_391, -7.3_398, -7.4_297, -7.4_844, -6.5_820, -5.8_789, -5.5_312]	)
    # fmt: on
    torch.testing.assert_close(out[0, 0, :3_0],					lowercase_,					atol=1E-5,					rtol=1E-5	)



 @unittest.skip("Model is curently gated"	)
 @slow
 def 					_lowercase (			self							:			str	):
    __lowercase								=						'Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi'
    __lowercase								=						'Simply put, the theory of relativity states that '
    __lowercase								=						LlamaTokenizer.from_pretrained("meta-llama/Llama-2-13b-chat-hf"	)
    __lowercase								=						tokenizer.encode(lowercase_,					return_tensors="pt"	)
    __lowercase								=						LlamaForCausalLM.from_pretrained(
        "meta-llama/Llama-2-13b-chat-hf",					device_map="sequential",					use_safetensors=lowercase_	)

    # greedy generation outputs
    __lowercase								=						model.generate(lowercase_,					max_new_tokens=6_4,					top_p=lowercase_,					temperature=1,					do_sample=lowercase_	)
    __lowercase								=						tokenizer.decode(generated_ids[0],					skip_special_tokens=lowercase_	)
    self.assertEqual(lowercase_,					lowercase_	)








import itertools
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Union

import pandas as pd
import pyarrow as pa

import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast
from datasets.utils.py_utils import Literal


lowerCamelCase											=       datasets.utils.logging.get_logger(__name__)

lowerCamelCase											=       ['names', 'prefix']
lowerCamelCase											=       ['warn_bad_lines', 'error_bad_lines', 'mangle_dupe_cols']
lowerCamelCase											=       ['encoding_errors', 'on_bad_lines']
lowerCamelCase											=       ['date_format']




@dataclass
class A  (   datasets.BuilderConfig     ):
      UpperCamelCase__							:  str      =","
      UpperCamelCase__							:  Optional[str]      =None
      UpperCamelCase__							:  Optional[Union[int, List[int], str]]      ="infer"
      UpperCamelCase__							:  Optional[List[str]]      =None
      UpperCamelCase__							:  Optional[List[str]]      =None
      UpperCamelCase__							:  Optional[Union[int, str, List[int], List[str]]]      =None
      UpperCamelCase__							:  Optional[Union[List[int], List[str]]]      =None
      UpperCamelCase__							:  Optional[str]      =None
      UpperCamelCase__							:  bool      =True
      UpperCamelCase__							:  Optional[Literal["c", "python", "pyarrow"]]      =None
      UpperCamelCase__							:  Dict[Union[int, str], Callable[[Any], Any]]      =None
      UpperCamelCase__							:  Optional[list]      =None
      UpperCamelCase__							:  Optional[list]      =None
      UpperCamelCase__							:  bool      =False
      UpperCamelCase__							:  Optional[Union[int, List[int]]]      =None
      UpperCamelCase__							:  Optional[int]      =None
      UpperCamelCase__							:  Optional[Union[str, List[str]]]      =None
      UpperCamelCase__							:  bool      =True
      UpperCamelCase__							:  bool      =True
      UpperCamelCase__							:  bool      =False
      UpperCamelCase__							:  bool      =True
      UpperCamelCase__							:  Optional[str]      =None
      UpperCamelCase__							:  str      ="."
      UpperCamelCase__							:  Optional[str]      =None
      UpperCamelCase__							:  str      ='"'
      UpperCamelCase__							:  int      =0
      UpperCamelCase__							:  Optional[str]      =None
      UpperCamelCase__							:  Optional[str]      =None
      UpperCamelCase__							:  Optional[str]      =None
      UpperCamelCase__							:  Optional[str]      =None
      UpperCamelCase__							:  bool      =True
      UpperCamelCase__							:  bool      =True
      UpperCamelCase__							:  int      =0
      UpperCamelCase__							:  bool      =True
      UpperCamelCase__							:  bool      =False
      UpperCamelCase__							:  Optional[str]      =None
      UpperCamelCase__							:  int      =10000
      UpperCamelCase__							:  Optional[datasets.Features]      =None
      UpperCamelCase__							:  Optional[str]      ="strict"
      UpperCamelCase__							:  Literal["error", "warn", "skip"]      ="error"
      UpperCamelCase__							:  Optional[str]      =None






      def        lowerCamelCase       (					self						:     List[str] )					->						str:
             """simple docstring"""




             if self.delimiter is not None:
                    _lowerCamelCase       :		Union[str, Any]		=self.delimiter
             if self.column_names is not None:
                    _lowerCamelCase       :		Dict		=self.column_names






      @property
      def        lowerCamelCase       (					self						:     int )					->						int:
             """simple docstring"""




             _lowerCamelCase       :		Any		={
                 'sep': self.sep,
                 'header': self.header,
                 'names': self.names,
                 'index_col': self.index_col,
                 'usecols': self.usecols,
                 'prefix': self.prefix,
                 'mangle_dupe_cols': self.mangle_dupe_cols,
                 'engine': self.engine,
                 'converters': self.converters,
                 'true_values': self.true_values,
                 'false_values': self.false_values,
                 'skipinitialspace': self.skipinitialspace,
                 'skiprows': self.skiprows,
                 'nrows': self.nrows,
                 'na_values': self.na_values,
                 'keep_default_na': self.keep_default_na,
                 'na_filter': self.na_filter,
                 'verbose': self.verbose,
                 'skip_blank_lines': self.skip_blank_lines,
                 'thousands': self.thousands,
                 'decimal': self.decimal,
                 'lineterminator': self.lineterminator,
                 'quotechar': self.quotechar,
                 'quoting': self.quoting,
                 'escapechar': self.escapechar,
                 'comment': self.comment,
                 'encoding': self.encoding,
                 'dialect': self.dialect,
                 'error_bad_lines': self.error_bad_lines,
                 'warn_bad_lines': self.warn_bad_lines,
                 'skipfooter': self.skipfooter,
                 'doublequote': self.doublequote,
                 'memory_map': self.memory_map,
                 'float_precision': self.float_precision,
                 'chunksize': self.chunksize,
                 'encoding_errors': self.encoding_errors,
                 'on_bad_lines': self.on_bad_lines,
                 'date_format': self.date_format,
             }

             # some kwargs must not be passed if they don't have a default value
             # some others are deprecated and we can also not pass them if they are the default value
             for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS:
                    if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig()			,   lowercase_ ):
                           del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 2.0 new arguments
             if not (datasets.config.PANDAS_VERSION.major >= 2):
                    for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS:
                           del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 1.3 new arguments
             if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3):
                    for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS:
                           del pd_read_csv_kwargs[pd_read_csv_parameter]

             return pd_read_csv_kwargs




class A  (   datasets.ArrowBasedBuilder     ):
      UpperCamelCase__							:  List[str]      =CsvConfig






      def        lowerCamelCase       (					self						:     Any )					->						Tuple:
             """simple docstring"""




             return datasets.DatasetInfo(features=self.config.features )






      def        lowerCamelCase       (					self						:     Tuple			,   lowercase_						:     Any )					->						List[Any]:
             """simple docstring"""




             if not self.config.data_files:
                    raise ValueError(F'''At least one data file must be specified, but got data_files={self.config.data_files}''' )
             _lowerCamelCase       :		int		=dl_manager.download_and_extract(self.config.data_files )
             if isinstance(lowercase_			,   (str, list, tuple) ):
                    _lowerCamelCase       :		List[Any]		=data_files
                    if isinstance(lowercase_			,   lowercase_ ):
                           _lowerCamelCase       :		Union[str, Any]		=[files]
                    _lowerCamelCase       :		Union[str, Any]		=[dl_manager.iter_files(lowercase_ ) for file in files]
                    return [datasets.SplitGenerator(name=datasets.Split.TRAIN			,   gen_kwargs={'files': files} )]
             _lowerCamelCase       :		Optional[int]		=[]
             for split_name, files in data_files.items():
                    if isinstance(lowercase_			,   lowercase_ ):
                           _lowerCamelCase       :		Dict		=[files]
                    _lowerCamelCase       :		Optional[int]		=[dl_manager.iter_files(lowercase_ ) for file in files]
                    splits.append(datasets.SplitGenerator(name=lowercase_			,   gen_kwargs={'files': files} ) )
             return splits






      def        lowerCamelCase       (					self						:     int			,   lowercase_						:     pa.Table )					->						pa.Table:
             """simple docstring"""




             if self.config.features is not None:
                    _lowerCamelCase       :		List[str]		=self.config.features.arrow_schema
                    if all(not require_storage_cast(lowercase_ ) for feature in self.config.features.values() ):
                           # cheaper cast
                           _lowerCamelCase       :		Optional[int]		=pa.Table.from_arrays([pa_table[field.name] for field in schema]			,   schema=lowercase_ )
                    else:
                           # more expensive cast; allows str <-> int/float or str to Audio for example
                           _lowerCamelCase       :		List[Any]		=table_cast(lowercase_			,   lowercase_ )
             return pa_table






      def        lowerCamelCase       (					self						:     Optional[Any]			,   lowercase_						:     List[Any] )					->						Any:
             """simple docstring"""




             _lowerCamelCase       :		str		=self.config.features.arrow_schema if self.config.features else None
             # dtype allows reading an int column as str
             _lowerCamelCase       :		Union[str, Any]		=(
                 {
                     name: dtype.to_pandas_dtype() if not require_storage_cast(lowercase_ ) else object
                     for name, dtype, feature in zip(schema.names			,   schema.types			,   self.config.features.values() )
                 }
                 if schema is not None
                 else None
             )
             for file_idx, file in enumerate(itertools.chain.from_iterable(lowercase_ ) ):
                    _lowerCamelCase       :		Union[str, Any]		=pd.read_csv(lowercase_			,   iterator=lowercase_			,   dtype=lowercase_			,   **self.config.pd_read_csv_kwargs )
                    try:
                           for batch_idx, df in enumerate(lowercase_ ):
                                  _lowerCamelCase       :		Tuple		=pa.Table.from_pandas(lowercase_ )
                                  # Uncomment for debugging (will print the Arrow table size and elements)
                                  # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
                                  # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
                                  yield (file_idx, batch_idx), self._cast_table(lowercase_ )
                    except ValueError as e:
                           logger.error(F'''Failed to read file \'{file}\' with error {type(lowercase_ )}: {e}''' )
                           raise


