






import argparse
import logging
import os

import datasets
import tensorflow as tf

from transformers import AutoTokenizer


__A      =				logging.getLogger(__name__)




def      __A					(     ):

					'''simple docstring'''







					_A								= argparse.ArgumentParser(
					    description='''Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.''' )
					parser.add_argument(
					    '''--dataset_name'''					,			type=_lowercase					,			default='''wikitext'''					,			help='''Name of the training. Explore datasets at: hf.co/datasets.'''					,			)
					parser.add_argument(
					    '''--dataset_config'''					,			type=_lowercase					,			default='''wikitext-103-raw-v1'''					,			help='''Configuration name of the dataset.''' )
					parser.add_argument(
					    '''--tokenizer_name_or_path'''					,			type=_lowercase					,			default='''sayakpaul/unigram-tokenizer-wikitext'''					,			help='''Tokenizer identifier. Can be a local filepath or a Hub identifier.'''					,			)
					parser.add_argument(
					    '''--shard_size'''					,			type=_lowercase					,			default=10_00					,			help='''Number of entries to go in a single shard.'''					,			)
					parser.add_argument('''--split'''					,			type=_lowercase					,			default='''train'''					,			choices=['''train''', '''test''', '''validation'''] )
					parser.add_argument(
					    '''--limit'''					,			default=_lowercase					,			type=_lowercase					,			help='''Limit the number of shards (used for debugging).'''					,			)
					parser.add_argument(
					    '''--max_length'''					,			type=_lowercase					,			default=5_12					,			help='''Maximum sequence length. For training on TPUs, it helps to have a maximum'''
					    ''' sequence length that is a multiple of 8.'''					,			)
					parser.add_argument(
					    '''--output_dir'''					,			default='''tf-tpu'''					,			type=_lowercase					,			help='''Output directory where the TFRecord shards will be saved. If the'''
					    ''' path is appended with `gs://` (\'gs://tf-tpu\', for example) then the TFRecord'''
					    ''' shards will be directly saved to a Google Cloud Storage bucket.'''					,			)

					_A								= parser.parse_args()
					return args




def      __A					(     _lowercase ):

					'''simple docstring'''







					def fn(_lowercase ):
										return tokenizer(examples['''text'''] )

					return fn




def      __A					(     _lowercase ):

					'''simple docstring'''







					_A								= []
					for i in range(len(tokenized_data['''input_ids'''] ) ):
										_A								= {
										    '''input_ids''': tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data['''input_ids'''][i] ) ),
										    '''attention_mask''': tf.train.Feature(
										        intaa_list=tf.train.IntaaList(value=tokenized_data['''attention_mask'''][i] ) ),
										}
										_A								= tf.train.Features(feature=_lowercase )
										_A								= tf.train.Example(features=_lowercase )
										_A								= example.SerializeToString()
										records.append(_lowercase )
					return records




def      __A					(     _lowercase ):

					'''simple docstring'''







					_A								= datasets.load_dataset(args.dataset_name					,			args.dataset_config					,			split=args.split )

					if args.limit is not None:
										_A								= min(len(_lowercase )					,			args.limit )
										_A								= dataset.select(range(_lowercase ) )
										print(f"""Limiting the dataset to {args.limit} entries.""" )

					_A								= AutoTokenizer.from_pretrained(args.tokenizer_name_or_path )

					# Handle output directory creation.
					# For serializing into a Google Cloud Storage Bucket, one needs to first
					# create a bucket.
					if "gs" not in args.output_dir:
										if not os.path.exists(args.output_dir ):
															os.makedirs(args.output_dir )
										_A								= os.path.join(args.output_dir					,			args.split )
										if not os.path.exists(_lowercase ):
															os.makedirs(_lowercase )
					else:
										_A								= os.path.join(args.output_dir					,			args.split )

					# Tokenize the whole dataset at once.
					_A								= tokenize_function(_lowercase )
					_A								= dataset.map(_lowercase					,			batched=_lowercase					,			num_proc=4					,			remove_columns=['''text'''] )

					# We need to concatenate all our texts together, and then split the result
					# into chunks of a fixed size, which we will call block_size. To do this, we
					# will use the map method again, with the option batched=True. When we use batched=True,
					# the function we pass to map() will be passed multiple inputs at once, allowing us
					# to group them into more or fewer examples than we had in the input.
					# This allows us to create our new fixed-length samples. The advantage of this
					# method is that we don't lose a whole lot of content from the dataset compared to the
					# case where we simply tokenize with a pre-defined max_length.

					def group_texts(_lowercase ):
										# Concatenate all texts.
										_A								= {k: sum(examples[k]					,			[] ) for k in examples.keys()}
										_A								= len(concatenated_examples[list(examples.keys() )[0]] )
										# We drop the small remainder, though you could add padding instead if the model supports it
										# In this, as in all things, we advise you to follow your heart 🫀
										_A								= (total_length // args.max_length) * args.max_length
										# Split by chunks of max_len.
										_A								= {
										    k: [t[i : i + args.max_length] for i in range(0					,			_lowercase					,			args.max_length )]
										    for k, t in concatenated_examples.items()
										}
										return result

					_A								= dataset_tokenized.map(_lowercase					,			batched=_lowercase					,			batch_size=10_00					,			num_proc=4 )

					_A								= 0
					_A								= 0
					for shard in range(0					,			len(_lowercase )					,			args.shard_size ):
										_A								= grouped_dataset[shard : shard + args.shard_size]
										_A								= len(dataset_snapshot['''input_ids'''] )
										_A								= os.path.join(_lowercase					,			f"""dataset-{shard_count}-{records_containing}.tfrecord""" )
										_A								= get_serialized_examples(_lowercase )

										with tf.io.TFRecordWriter(_lowercase ) as out_file:
															for i in range(len(_lowercase ) ):
																				_A								= serialized_examples[i]
																				out_file.write(_lowercase )
															print('''Wrote file {} containing {} records'''.format(_lowercase					,			_lowercase ) )

										shard_count += 1
										total_records += records_containing

					with open(f"""split-{args.split}-records-count.txt"""					,			'''w''' ) as f:
										print(f"""Total {args.split} records: {total_records}"""					,			file=_lowercase )


if __name__ == "__main__":
				__A      =				parse_args()
				main(args)











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 						SCREAMING_SNAKE_CASE				:





							"""simple docstring"""

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

							def       __A (  self:   Optional[int]   )    ->				Union[str, Any]:
												_A								= ids_tensor([self.batch_size, self.seq_length]		,     self.vocab_size   )

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

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

												_A								= None
												if self.use_mc_token_ids:
																	_A								= ids_tensor([self.batch_size, self.num_choices]		,     self.seq_length   )

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

												_A								= self.get_config()

												_A								= 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:   Optional[int]   )    ->				List[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:   Union[str, Any]		,     __A:   Union[str, Any]		,     __A:   Dict		,     __A:   Optional[int]		,     __A:   List[str]		,     __A:   List[str]		,     *__A:   Optional[int]   )    ->				Optional[Any]:
												_A								= CTRLModel(config=__A   )
												model.to(__A   )
												model.eval()

												model(__A		,     token_type_ids=__A		,     head_mask=__A   )
												model(__A		,     token_type_ids=__A   )
												_A								= model(__A   )
												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:   Optional[Any]		,     __A:   List[str]		,     __A:   Dict		,     __A:   List[Any]		,     __A:   List[Any]		,     __A:   Any		,     *__A:   Any   )    ->				str:
												_A								= CTRLLMHeadModel(__A   )
												model.to(__A   )
												model.eval()

												_A								= model(__A		,     token_type_ids=__A		,     labels=__A   )
												self.parent.assertEqual(result.loss.shape		,     ()   )
												self.parent.assertEqual(result.logits.shape		,     (self.batch_size, self.seq_length, self.vocab_size)   )

							def       __A (  self:   Optional[int]   )    ->				Dict:
												_A								= self.prepare_config_and_inputs()

												(
												    (
												    _A
												)							,(
												    _A
												)							,(
												    _A
												)							,(
												    _A
												)							,(
												    _A
												)							,(
												    _A
												)							,(
												    _A
												)							,(
												    _A
												)							,(
												    _A
												)							,
												)								= config_and_inputs

												_A								= {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''head_mask''': head_mask}

												return config, inputs_dict



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





@require_torch
class 						SCREAMING_SNAKE_CASE				( snake_case  ,	snake_case  ,	snake_case  ,	unittest.TestCase					):





							"""simple docstring"""

							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:   Any		,     __A:   List[Any]		,     __A:   int		,     __A:   Optional[Any]		,     __A:   Optional[int]		,     __A:   List[Any]   )    ->				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:   Any   )    ->				Union[str, Any]:
												_A								= CTRLModelTester(self   )
												_A								= ConfigTester(self		,     config_class=__A		,     n_embd=37   )

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

							def       __A (  self:   Dict   )    ->				Any:
												self.config_tester.run_common_tests()

							def       __A (  self:   str   )    ->				Optional[Any]:
												_A								= self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_ctrl_model(*__A   )

							def       __A (  self:   List[str]   )    ->				Any:
												_A								= self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_lm_head_model(*__A   )

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

							@slow
							def       __A (  self:   Tuple   )    ->				Dict:
												for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	_A								= CTRLModel.from_pretrained(__A   )
																	self.assertIsNotNone(__A   )



							@unittest.skip('''The model doesn\'t support left padding'''   )  # and it's not used enough to be worth fixing :)
							def       __A (  self:   Any   )    ->				Union[str, Any]:
												pass





@require_torch
class 						SCREAMING_SNAKE_CASE				( unittest.TestCase					):





							"""simple docstring"""

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



							@slow
							def       __A (  self:   Any   )    ->				Any:
												_A								= CTRLLMHeadModel.from_pretrained('''ctrl'''   )
												model.to(__A   )
												_A								= torch.tensor(
												    [[1_18_59, 0, 16_11, 8]]		,     dtype=torch.long		,     device=__A   )  # Legal the president is
												_A								= [
												    1_18_59,
												    0,
												    16_11,
												    8,
												    5,
												    1_50,
												    2_64_49,
												    2,
												    19,
												    3_48,
												    4_69,
												    3,
												    25_95,
												    48,
												    2_07_40,
												    24_65_33,
												    24_65_33,
												    19,
												    30,
												    5,
												]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

												_A								= model.generate(__A		,     do_sample=__A   )
												self.assertListEqual(output_ids[0].tolist()		,     __A   )



