
import gc
import unittest

from transformers import CTRLConfig, is_torch_available
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 (
							    CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
							    CTRLForSequenceClassification,
							    CTRLLMHeadModel,
							    CTRLModel,
							)




class   __lowercase						:






	def __init__(self				: Any      ,	snake_case				: Tuple      ,	snake_case				: int=14      ,	snake_case				: Tuple=7      ,	snake_case				: Any=True      ,	snake_case				: str=True      ,	snake_case				: Union[str, Any]=True      ,	snake_case				: str=True      ,	snake_case				: str=True      ,	snake_case				: Union[str, Any]=99      ,	snake_case				: List[str]=32      ,	snake_case				: List[Any]=5      ,	snake_case				: Optional[Any]=4      ,	snake_case				: Dict=37      ,	snake_case				: List[Any]="gelu"      ,	snake_case				: List[str]=0.1      ,	snake_case				: Optional[int]=0.1      ,	snake_case				: str=512      ,	snake_case				: Optional[Any]=16      ,	snake_case				: str=2      ,	snake_case				: Tuple=0.02      ,	snake_case				: int=3      ,	snake_case				: str=4      ,	snake_case				: Dict=None      ,	) ->			Tuple:
							_lowercase       :	List[str]           =   parent
							_lowercase       :	Any           =   batch_size
							_lowercase       :	Union[str, Any]           =   seq_length
							_lowercase       :	str           =   is_training
							_lowercase       :	Any           =   use_token_type_ids
							_lowercase       :	List[Any]           =   use_input_mask
							_lowercase       :	Optional[int]           =   use_labels
							_lowercase       :	str           =   use_mc_token_ids
							_lowercase       :	int           =   vocab_size
							_lowercase       :	int           =   hidden_size
							_lowercase       :	Union[str, Any]           =   num_hidden_layers
							_lowercase       :	Union[str, Any]           =   num_attention_heads
							_lowercase       :	List[str]           =   intermediate_size
							_lowercase       :	List[Any]           =   hidden_act
							_lowercase       :	List[Any]           =   hidden_dropout_prob
							_lowercase       :	List[Any]           =   attention_probs_dropout_prob
							_lowercase       :	Tuple           =   max_position_embeddings
							_lowercase       :	Union[str, Any]           =   type_vocab_size
							_lowercase       :	List[Any]           =   type_sequence_label_size
							_lowercase       :	Dict           =   initializer_range
							_lowercase       :	List[str]           =   num_labels
							_lowercase       :	int           =   num_choices
							_lowercase       :	Tuple           =   scope
							_lowercase       :	List[str]           =   self.vocab_size - 1






	def       _a(self				: Optional[int]    ) ->			Dict:
							_lowercase       :	Optional[int]           =   ids_tensor([self.batch_size, self.seq_length]      ,	self.vocab_size    )

							_lowercase       :	List[Any]           =   None
							if self.use_input_mask:
													_lowercase       :	Tuple           =   random_attention_mask([self.batch_size, self.seq_length]    )

							_lowercase       :	List[str]           =   None
							if self.use_token_type_ids:
													_lowercase       :	int           =   ids_tensor([self.batch_size, self.seq_length]      ,	self.type_vocab_size    )

							_lowercase       :	Optional[int]           =   None
							if self.use_mc_token_ids:
													_lowercase       :	Any           =   ids_tensor([self.batch_size, self.num_choices]      ,	self.seq_length    )

							_lowercase       :	Union[str, Any]           =   None
							_lowercase       :	List[str]           =   None
							_lowercase       :	Any           =   None
							if self.use_labels:
													_lowercase       :	Optional[Any]           =   ids_tensor([self.batch_size]      ,	self.type_sequence_label_size    )
													_lowercase       :	int           =   ids_tensor([self.batch_size, self.seq_length]      ,	self.num_labels    )
													_lowercase       :	Optional[int]           =   ids_tensor([self.batch_size]      ,	self.num_choices    )

							_lowercase       :	List[Any]           =   self.get_config()

							_lowercase       :	str           =   ids_tensor([self.num_hidden_layers, self.num_attention_heads]      ,	2    )

							return (
							    config,
							    input_ids,
							    input_mask,
							    head_mask,
							    token_type_ids,
							    mc_token_ids,
							    sequence_labels,
							    token_labels,
							    choice_labels,
							)






	def       _a(self				: int    ) ->			Any:
							return CTRLConfig(
							    vocab_size=self.vocab_size      ,	n_embd=self.hidden_size      ,	n_layer=self.num_hidden_layers      ,	n_head=self.num_attention_heads      ,	n_positions=self.max_position_embeddings      ,	pad_token_id=self.pad_token_id      ,	)






	def       _a(self				: Dict      ,	snake_case				: str      ,	snake_case				: int      ,	snake_case				: str      ,	snake_case				: Optional[Any]      ,	snake_case				: int      ,	*snake_case				: str    ) ->			int:
							_lowercase       :	Union[str, Any]           =   CTRLModel(config=snake_case    )
							model.to(snake_case    )
							model.eval()

							model(snake_case      ,	token_type_ids=snake_case      ,	head_mask=snake_case    )
							model(snake_case      ,	token_type_ids=snake_case    )
							_lowercase       :	Optional[Any]           =   model(snake_case    )
							self.parent.assertEqual(result.last_hidden_state.shape      ,	(self.batch_size, self.seq_length, self.hidden_size)    )
							self.parent.assertEqual(len(result.past_key_values    )      ,	config.n_layer    )






	def       _a(self				: List[str]      ,	snake_case				: Optional[Any]      ,	snake_case				: Tuple      ,	snake_case				: Union[str, Any]      ,	snake_case				: Optional[Any]      ,	snake_case				: Optional[int]      ,	*snake_case				: Tuple    ) ->			Tuple:
							_lowercase       :	Dict           =   CTRLLMHeadModel(snake_case    )
							model.to(snake_case    )
							model.eval()

							_lowercase       :	Dict           =   model(snake_case      ,	token_type_ids=snake_case      ,	labels=snake_case    )
							self.parent.assertEqual(result.loss.shape      ,	()    )
							self.parent.assertEqual(result.logits.shape      ,	(self.batch_size, self.seq_length, self.vocab_size)    )






	def       _a(self				: List[str]    ) ->			List[Any]:
							_lowercase       :	Optional[int]           =   self.prepare_config_and_inputs()

							(
							    (
							    _lowercase
							)      ,    (
							    _lowercase
							)      ,    (
							    _lowercase
							)      ,    (
							    _lowercase
							)      ,    (
							    _lowercase
							)      ,    (
							    _lowercase
							)      ,    (
							    _lowercase
							)      ,    (
							    _lowercase
							)      ,    (
							    _lowercase
							)      ,    
							)       :	List[Any]           =   config_and_inputs

							_lowercase       :	int           =   {"input_ids": input_ids, "token_type_ids": token_type_ids, "head_mask": head_mask}

							return config, inputs_dict






	def       _a(self				: Union[str, Any]      ,	snake_case				: Union[str, Any]      ,	snake_case				: Dict      ,	snake_case				: Optional[int]      ,	snake_case				: int      ,	*snake_case				: Union[str, Any]    ) ->			int:
							_lowercase       :	Union[str, Any]           =   self.num_labels
							_lowercase       :	Union[str, Any]           =   CTRLForSequenceClassification(snake_case    )
							model.to(snake_case    )
							model.eval()
							_lowercase       :	Tuple           =   ids_tensor([self.batch_size]      ,	self.type_sequence_label_size    )
							_lowercase       :	Union[str, Any]           =   model(snake_case      ,	token_type_ids=snake_case      ,	labels=snake_case    )
							self.parent.assertEqual(result.logits.shape      ,	(self.batch_size, self.num_labels)    )




@require_torch
class   __lowercase						(						__snake_case   , __snake_case   , __snake_case   , unittest.TestCase       ):
	_A       =   (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else ()
	_A       =   (CTRLLMHeadModel,) if is_torch_available() else ()
	_A       =   (
	    {
	        "feature-extraction": CTRLModel,
	        "text-classification": CTRLForSequenceClassification,
	        "text-generation": CTRLLMHeadModel,
	        "zero-shot": CTRLForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)
	_A       =   True
	_A       =   False
	_A       =   False






	def       _a(self				: Tuple      ,	snake_case				: List[str]      ,	snake_case				: List[str]      ,	snake_case				: Dict      ,	snake_case				: List[Any]      ,	snake_case				: str    ) ->			List[str]:
							if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
													# Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
													# `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny
													# config could not be created.
													return True

							return False






	def       _a(self				: int    ) ->			int:
							_lowercase       :	str           =   CTRLModelTester(self    )
							_lowercase       :	List[Any]           =   ConfigTester(self      ,	config_class=snake_case      ,	n_embd=37    )






	def       _a(self				: str    ) ->			Optional[Any]:
							super().tearDown()
							# clean-up as much as possible GPU memory occupied by PyTorch
							gc.collect()
							torch.cuda.empty_cache()






	def       _a(self				: List[Any]    ) ->			int:
							self.config_tester.run_common_tests()






	def       _a(self				: List[str]    ) ->			Union[str, Any]:
							_lowercase       :	List[Any]           =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_ctrl_model(*snake_case    )






	def       _a(self				: Optional[Any]    ) ->			Dict:
							_lowercase       :	List[Any]           =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_lm_head_model(*snake_case    )






	@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."    )
	def       _a(self				: Optional[Any]    ) ->			Tuple:
							pass






	@slow
	def       _a(self				: Optional[Any]    ) ->			Optional[Any]:
							for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													_lowercase       :	Optional[int]           =   CTRLModel.from_pretrained(snake_case    )
													self.assertIsNotNone(snake_case    )






	@unittest.skip("The model doesn't support left padding"    )  # and it's not used enough to be worth fixing :)
	def       _a(self				: int    ) ->			Dict:
							pass




@require_torch
class   __lowercase						(						unittest.TestCase       ):






	def       _a(self				: Optional[int]    ) ->			Optional[Any]:
							super().tearDown()
							# clean-up as much as possible GPU memory occupied by PyTorch
							gc.collect()
							torch.cuda.empty_cache()






	@slow
	def       _a(self				: List[Any]    ) ->			Dict:
							_lowercase       :	Tuple           =   CTRLLMHeadModel.from_pretrained("ctrl"    )
							model.to(snake_case    )
							_lowercase       :	Tuple           =   torch.tensor(
							    [[1_1859, 0, 1611, 8]]      ,	dtype=torch.long      ,	device=snake_case    )  # Legal the president is
							_lowercase       :	Optional[Any]           =   [
							    1_1859,
							    0,
							    1611,
							    8,
							    5,
							    150,
							    2_6449,
							    2,
							    19,
							    348,
							    469,
							    3,
							    2595,
							    48,
							    2_0740,
							    24_6533,
							    24_6533,
							    19,
							    30,
							    5,
							]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

							_lowercase       :	Optional[Any]           =   model.generate(snake_case      ,	do_sample=snake_case    )
							self.assertListEqual(output_ids[0].tolist()      ,	snake_case    )






import io
import itertools
import json
from dataclasses import dataclass
from typing import Optional

import pyarrow as pa
import pyarrow.json as paj

import datasets
from datasets.table import table_cast
from datasets.utils.file_utils import readline


UpperCamelCase_						:     Union[str, Any]	       =							datasets.utils.logging.get_logger(__name__)




@dataclass
class   __lowercase						(						datasets.BuilderConfig       ):
	_A       =   None
	_A       =   "utf-8"
	_A       =   None
	_A       =   None
	_A       =   True  # deprecated
	_A       =   None  # deprecated
	_A       =   10 << 20  # 10MB
	_A       =   None




class   __lowercase						(						datasets.ArrowBasedBuilder       ):
	_A       =   JsonConfig






	def       _a(self				: List[Any]    ) ->			Dict:
							if self.config.block_size is not None:
													logger.warning("The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead"    )
													_lowercase       :	Union[str, Any]           =   self.config.block_size
							if self.config.use_threads is not True:
													logger.warning(
													    "The JSON loader parameter `use_threads` is deprecated and doesn't have any effect anymore."    )
							if self.config.newlines_in_values is not None:
													raise ValueError("The JSON loader parameter `newlines_in_values` is no longer supported"    )
							return datasets.DatasetInfo(features=self.config.features    )






	def       _a(self				: Any      ,	snake_case				: Union[str, Any]    ) ->			List[str]:
							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}"""    )
							_lowercase       :	str           =   dl_manager.download_and_extract(self.config.data_files    )
							if isinstance(snake_case      ,	(str, list, tuple)    ):
													_lowercase       :	int           =   data_files
													if isinstance(snake_case      ,	snake_case    ):
																			_lowercase       :	Union[str, Any]           =   [files]
													_lowercase       :	Union[str, Any]           =   [dl_manager.iter_files(snake_case    ) for file in files]
													return [datasets.SplitGenerator(name=datasets.Split.TRAIN      ,	gen_kwargs={"files": files}    )]
							_lowercase       :	Union[str, Any]           =   []
							for split_name, files in data_files.items():
													if isinstance(snake_case      ,	snake_case    ):
																			_lowercase       :	List[Any]           =   [files]
													_lowercase       :	Optional[Any]           =   [dl_manager.iter_files(snake_case    ) for file in files]
													splits.append(datasets.SplitGenerator(name=snake_case      ,	gen_kwargs={"files": files}    )    )
							return splits






	def       _a(self				: List[Any]      ,	snake_case				: pa.Table    ) ->			pa.Table:
							if self.config.features is not None:
													# adding missing columns
													for column_name in set(self.config.features    ) - set(pa_table.column_names    ):
																			_lowercase       :	Any           =   self.config.features.arrow_schema.field(snake_case    ).type
																			_lowercase       :	Optional[Any]           =   pa_table.append_column(snake_case      ,	pa.array([None] * len(snake_case    )      ,	type=snake_case    )    )
													# more expensive cast to support nested structures with keys in a different order
													# allows str <-> int/float or str to Audio for example
													_lowercase       :	str           =   table_cast(snake_case      ,	self.config.features.arrow_schema    )
							return pa_table






	def       _a(self				: str      ,	snake_case				: Tuple    ) ->			Tuple:
							for file_idx, file in enumerate(itertools.chain.from_iterable(snake_case    )    ):
													# If the file is one json object and if we need to look at the list of items in one specific field
													if self.config.field is not None:
																			with open(snake_case      ,	encoding=self.config.encoding      ,	errors=self.config.encoding_errors    ) as f:
																									_lowercase       :	Any           =   json.load(snake_case    )

																			# We keep only the field we are interested in
																			_lowercase       :	List[Any]           =   dataset[self.config.field]

																			# We accept two format: a list of dicts or a dict of lists
																			if isinstance(snake_case      ,	(list, tuple)    ):
																									_lowercase       :	Optional[int]           =   set().union(*[row.keys() for row in dataset]    )
																									_lowercase       :	Union[str, Any]           =   {col: [row.get(snake_case    ) for row in dataset] for col in keys}
																			else:
																									_lowercase       :	List[Any]           =   dataset
																			_lowercase       :	int           =   pa.Table.from_pydict(snake_case    )
																			yield file_idx, self._cast_table(snake_case    )

													# If the file has one json object per line
													else:
																			with open(snake_case      ,	"rb"    ) as f:
																									_lowercase       :	Union[str, Any]           =   0
																									# Use block_size equal to the chunk size divided by 32 to leverage multithreading
																									# Set a default minimum value of 16kB if the chunk size is really small
																									_lowercase       :	Dict           =   max(self.config.chunksize // 32      ,	16 << 10    )
																									_lowercase       :	int           =   (
																									    self.config.encoding_errors if self.config.encoding_errors is not None else "strict"
																									)
																									while True:
																															_lowercase       :	Tuple           =   f.read(self.config.chunksize    )
																															if not batch:
																																					break
																															# Finish current line
																															try:
																																					batch += f.readline()
																															except (AttributeError, io.UnsupportedOperation):
																																					batch += readline(snake_case    )
																															# PyArrow only accepts utf-8 encoded bytes
																															if self.config.encoding != "utf-8":
																																					_lowercase       :	Union[str, Any]           =   batch.decode(self.config.encoding      ,	errors=snake_case    ).encode("utf-8"    )
																															try:
																																					while True:
																																											try:
																																																	_lowercase       :	Optional[Any]           =   paj.read_json(
																																																	    io.BytesIO(snake_case    )      ,	read_options=paj.ReadOptions(block_size=snake_case    )    )
																																																	break
																																											except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e:
																																																	if (
																																																	    isinstance(snake_case      ,	pa.ArrowInvalid    )
																																																	    and "straddling" not in str(snake_case    )
																																																	    or block_size > len(snake_case    )
																																																	):
																																																							raise
																																																	else:
																																																							# Increase the block size in case it was too small.
																																																							# The block size will be reset for the next file.
																																																							logger.debug(
																																																							    F"""Batch of {len(snake_case    )} bytes couldn't be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}."""    )
																																																							block_size *= 2
																															except pa.ArrowInvalid as e:
																																					try:
																																											with open(
																																											    snake_case      ,	encoding=self.config.encoding      ,	errors=self.config.encoding_errors    ) as f:
																																																	_lowercase       :	Any           =   json.load(snake_case    )
																																					except json.JSONDecodeError:
																																											logger.error(F"""Failed to read file '{file}' with error {type(snake_case    )}: {e}"""    )
																																											raise e
																																					# If possible, parse the file as a list of json objects and exit the loop
																																					if isinstance(snake_case      ,	snake_case    ):  # list is the only sequence type supported in JSON
																																											try:
																																																	_lowercase       :	int           =   set().union(*[row.keys() for row in dataset]    )
																																																	_lowercase       :	Dict           =   {col: [row.get(snake_case    ) for row in dataset] for col in keys}
																																																	_lowercase       :	str           =   pa.Table.from_pydict(snake_case    )
																																											except (pa.ArrowInvalid, AttributeError) as e:
																																																	logger.error(F"""Failed to read file '{file}' with error {type(snake_case    )}: {e}"""    )
																																																	raise ValueError(F"""Not able to read records in the JSON file at {file}."""    ) from None
																																											yield file_idx, self._cast_table(snake_case    )
																																											break
																																					else:
																																											logger.error(F"""Failed to read file '{file}' with error {type(snake_case    )}: {e}"""    )
																																											raise ValueError(
																																											    F"""Not able to read records in the JSON file at {file}. """
																																											    F"""You should probably indicate the field of the JSON file containing your records. """
																																											    F"""This JSON file contain the following fields: {str(list(dataset.keys()    )    )}. """
																																											    F"""Select the correct one and provide it as `field='XXX'` to the dataset loading method. """    ) from None
                        # 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(snake_case    )
																															batch_idx += 1




