


'''simple docstring'''




import tempfile

import torch

from diffusers import (
    DEISMultistepScheduler,
    DPMSolverMultistepScheduler,
    DPMSolverSinglestepScheduler,
    UniPCMultistepScheduler,
)

from .test_schedulers import SchedulerCommonTest



class  lowerCAmelCase				(				a							):
	_lowerCamelCase   :					str			      = (UniPCMultistepScheduler,)
	_lowerCamelCase   :					int			      = (("""num_inference_steps""", 25),)



	def 				lowercase     (					self ,					**snake_case__    ):
		lowerCAmelCase					:    List[Any]      							= {
		    'num_train_timesteps': 1000,
		    'beta_start': 0.0_0_0_1,
		    'beta_end': 0.0_2,
		    'beta_schedule': 'linear',
		    'solver_order': 2,
		    'solver_type': 'bh2',
		}

		config.update(**snake_case__    )
		return config



	def 				lowercase     (					self ,					snake_case__=0 ,					**snake_case__    ):
		lowerCAmelCase					:    Dict      							= dict(self.forward_default_kwargs    )
		lowerCAmelCase					:    Dict      							= kwargs.pop('num_inference_steps' ,					snake_case__    )
		lowerCAmelCase					:    List[str]      							= self.dummy_sample
		lowerCAmelCase					:    Optional[int]      							= 0.1 * sample
		lowerCAmelCase					:    Tuple      							= [residual + 0.2, residual + 0.1_5, residual + 0.1_0]

		for scheduler_class in self.scheduler_classes:
			lowerCAmelCase					:    List[Any]      							= self.get_scheduler_config(**snake_case__    )
			lowerCAmelCase					:    Optional[Any]      							= scheduler_class(**snake_case__    )
			scheduler.set_timesteps(snake_case__    )
			# copy over dummy past residuals
			lowerCAmelCase					:    List[Any]      							= dummy_past_residuals[: scheduler.config.solver_order]

			with tempfile.TemporaryDirectory() as tmpdirname:
				scheduler.save_config(snake_case__    )
				lowerCAmelCase					:    Any      							= scheduler_class.from_pretrained(snake_case__    )
				new_scheduler.set_timesteps(snake_case__    )
				# copy over dummy past residuals
				lowerCAmelCase					:    str      							= dummy_past_residuals[: new_scheduler.config.solver_order]

			lowerCAmelCase							,   lowerCAmelCase					:    Optional[Any]      							= sample, sample
			for t in range(snake_case__ ,					time_step + scheduler.config.solver_order + 1    ):
				lowerCAmelCase					:    List[str]      							= scheduler.step(snake_case__ ,					snake_case__ ,					snake_case__ ,					**snake_case__    ).prev_sample
				lowerCAmelCase					:    Tuple      							= new_scheduler.step(snake_case__ ,					snake_case__ ,					snake_case__ ,					**snake_case__    ).prev_sample

				assert torch.sum(torch.abs(output - new_output    )    ) < 1e-5, "Scheduler outputs are not identical"



	def 				lowercase     (					self ,					snake_case__=0 ,					**snake_case__    ):
		lowerCAmelCase					:    Tuple      							= dict(self.forward_default_kwargs    )
		lowerCAmelCase					:    Any      							= kwargs.pop('num_inference_steps' ,					snake_case__    )
		lowerCAmelCase					:    Optional[Any]      							= self.dummy_sample
		lowerCAmelCase					:    Dict      							= 0.1 * sample
		lowerCAmelCase					:    Optional[Any]      							= [residual + 0.2, residual + 0.1_5, residual + 0.1_0]

		for scheduler_class in self.scheduler_classes:
			lowerCAmelCase					:    List[Any]      							= self.get_scheduler_config()
			lowerCAmelCase					:    List[str]      							= scheduler_class(**snake_case__    )
			scheduler.set_timesteps(snake_case__    )

			# copy over dummy past residuals (must be after setting timesteps)
			lowerCAmelCase					:    Dict      							= dummy_past_residuals[: scheduler.config.solver_order]

			with tempfile.TemporaryDirectory() as tmpdirname:
				scheduler.save_config(snake_case__    )
				lowerCAmelCase					:    Optional[int]      							= scheduler_class.from_pretrained(snake_case__    )
				# copy over dummy past residuals
				new_scheduler.set_timesteps(snake_case__    )

				# copy over dummy past residual (must be after setting timesteps)
				lowerCAmelCase					:    Union[str, Any]      							= dummy_past_residuals[: new_scheduler.config.solver_order]

			lowerCAmelCase					:    Optional[int]      							= scheduler.step(snake_case__ ,					snake_case__ ,					snake_case__ ,					**snake_case__    ).prev_sample
			lowerCAmelCase					:    int      							= new_scheduler.step(snake_case__ ,					snake_case__ ,					snake_case__ ,					**snake_case__    ).prev_sample

			assert torch.sum(torch.abs(output - new_output    )    ) < 1e-5, "Scheduler outputs are not identical"



	def 				lowercase     (					self ,					snake_case__=None ,					**snake_case__    ):
		if scheduler is None:
			lowerCAmelCase					:    Union[str, Any]      							= self.scheduler_classes[0]
			lowerCAmelCase					:    Any      							= self.get_scheduler_config(**snake_case__    )
			lowerCAmelCase					:    Optional[int]      							= scheduler_class(**snake_case__    )

		lowerCAmelCase					:    Optional[Any]      							= self.scheduler_classes[0]
		lowerCAmelCase					:    Optional[int]      							= self.get_scheduler_config(**snake_case__    )
		lowerCAmelCase					:    Optional[int]      							= scheduler_class(**snake_case__    )

		lowerCAmelCase					:    List[Any]      							= 10
		lowerCAmelCase					:    Tuple      							= self.dummy_model()
		lowerCAmelCase					:    List[Any]      							= self.dummy_sample_deter
		scheduler.set_timesteps(snake_case__    )

		for i, t in enumerate(scheduler.timesteps    ):
			lowerCAmelCase					:    List[str]      							= model(snake_case__ ,					snake_case__    )
			lowerCAmelCase					:    Optional[int]      							= scheduler.step(snake_case__ ,					snake_case__ ,					snake_case__    ).prev_sample

		return sample



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    List[str]      							= dict(self.forward_default_kwargs    )

		lowerCAmelCase					:    str      							= kwargs.pop('num_inference_steps' ,					snake_case__    )

		for scheduler_class in self.scheduler_classes:
			lowerCAmelCase					:    Dict      							= self.get_scheduler_config()
			lowerCAmelCase					:    Dict      							= scheduler_class(**snake_case__    )

			lowerCAmelCase					:    Optional[Any]      							= self.dummy_sample
			lowerCAmelCase					:    Optional[Any]      							= 0.1 * sample

			if num_inference_steps is not None and hasattr(snake_case__ ,					'set_timesteps'    ):
				scheduler.set_timesteps(snake_case__    )
			elif num_inference_steps is not None and not hasattr(snake_case__ ,					'set_timesteps'    ):
				lowerCAmelCase					:    Optional[Any]      							= num_inference_steps

			# copy over dummy past residuals (must be done after set_timesteps)
			lowerCAmelCase					:    Any      							= [residual + 0.2, residual + 0.1_5, residual + 0.1_0]
			lowerCAmelCase					:    Any      							= dummy_past_residuals[: scheduler.config.solver_order]

			lowerCAmelCase					:    int      							= scheduler.timesteps[5]
			lowerCAmelCase					:    str      							= scheduler.timesteps[6]

			lowerCAmelCase					:    List[str]      							= scheduler.step(snake_case__ ,					snake_case__ ,					snake_case__ ,					**snake_case__    ).prev_sample
			lowerCAmelCase					:    Any      							= scheduler.step(snake_case__ ,					snake_case__ ,					snake_case__ ,					**snake_case__    ).prev_sample

			self.assertEqual(output_a.shape ,					sample.shape    )
			self.assertEqual(output_a.shape ,					output_a.shape    )



	def 				lowercase     (					self    ):
		# make sure that iterating over schedulers with same config names gives same results
		# for defaults
		lowerCAmelCase					:    str      							= UniPCMultistepScheduler(**self.get_scheduler_config()    )
		lowerCAmelCase					:    Dict      							= self.full_loop(scheduler=snake_case__    )
		lowerCAmelCase					:    Union[str, Any]      							= torch.mean(torch.abs(snake_case__    )    )

		assert abs(result_mean.item() - 0.2_4_6_4    ) < 1e-3

		lowerCAmelCase					:    Tuple      							= DPMSolverSinglestepScheduler.from_config(scheduler.config    )
		lowerCAmelCase					:    Optional[int]      							= DEISMultistepScheduler.from_config(scheduler.config    )
		lowerCAmelCase					:    Any      							= DPMSolverMultistepScheduler.from_config(scheduler.config    )
		lowerCAmelCase					:    int      							= UniPCMultistepScheduler.from_config(scheduler.config    )

		lowerCAmelCase					:    str      							= self.full_loop(scheduler=snake_case__    )
		lowerCAmelCase					:    Optional[int]      							= torch.mean(torch.abs(snake_case__    )    )

		assert abs(result_mean.item() - 0.2_4_6_4    ) < 1e-3



	def 				lowercase     (					self    ):
		for timesteps in [25, 50, 100, 999, 1000]:
			self.check_over_configs(num_train_timesteps=snake_case__    )



	def 				lowercase     (					self    ):
		self.check_over_configs(thresholding=snake_case__    )
		for order in [1, 2, 3]:
			for solver_type in ["bh1", "bh2"]:
				for threshold in [0.5, 1.0, 2.0]:
					for prediction_type in ["epsilon", "sample"]:
						self.check_over_configs(
						    thresholding=snake_case__ ,					prediction_type=snake_case__ ,					sample_max_value=snake_case__ ,					solver_order=snake_case__ ,					solver_type=snake_case__ ,					)



	def 				lowercase     (					self    ):
		for prediction_type in ["epsilon", "v_prediction"]:
			self.check_over_configs(prediction_type=snake_case__    )



	def 				lowercase     (					self    ):
		for solver_type in ["bh1", "bh2"]:
			for order in [1, 2, 3]:
				for prediction_type in ["epsilon", "sample"]:
					self.check_over_configs(
					    solver_order=snake_case__ ,					solver_type=snake_case__ ,					prediction_type=snake_case__ ,					)
					lowerCAmelCase					:    Any      							= self.full_loop(
					    solver_order=snake_case__ ,					solver_type=snake_case__ ,					prediction_type=snake_case__ ,					)
					assert not torch.isnan(snake_case__    ).any(), "Samples have nan numbers"



	def 				lowercase     (					self    ):
		self.check_over_configs(lower_order_final=snake_case__    )
		self.check_over_configs(lower_order_final=snake_case__    )



	def 				lowercase     (					self    ):
		for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1000]:
			self.check_over_forward(num_inference_steps=snake_case__ ,					time_step=0    )



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    Dict      							= self.full_loop()
		lowerCAmelCase					:    Dict      							= torch.mean(torch.abs(snake_case__    )    )

		assert abs(result_mean.item() - 0.2_4_6_4    ) < 1e-3



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    int      							= self.full_loop(prediction_type='v_prediction'    )
		lowerCAmelCase					:    str      							= torch.mean(torch.abs(snake_case__    )    )

		assert abs(result_mean.item() - 0.1_0_1_4    ) < 1e-3



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    Dict      							= self.scheduler_classes[0]
		lowerCAmelCase					:    str      							= self.get_scheduler_config(thresholding=snake_case__ ,					dynamic_thresholding_ratio=0    )
		lowerCAmelCase					:    Dict      							= scheduler_class(**snake_case__    )

		lowerCAmelCase					:    Optional[int]      							= 10
		lowerCAmelCase					:    str      							= self.dummy_model()
		lowerCAmelCase					:    Tuple      							= self.dummy_sample_deter.half()
		scheduler.set_timesteps(snake_case__    )

		for i, t in enumerate(scheduler.timesteps    ):
			lowerCAmelCase					:    str      							= model(snake_case__ ,					snake_case__    )
			lowerCAmelCase					:    List[Any]      							= scheduler.step(snake_case__ ,					snake_case__ ,					snake_case__    ).prev_sample

		assert sample.dtype == torch.floataa



	def 				lowercase     (					self ,					**snake_case__    ):
		for scheduler_class in self.scheduler_classes:
			lowerCAmelCase					:    List[str]      							= self.get_scheduler_config(**snake_case__    )
			lowerCAmelCase					:    Optional[int]      							= scheduler_class(**snake_case__    )

			scheduler.set_timesteps(scheduler.config.num_train_timesteps    )
			assert len(scheduler.timesteps.unique()    ) == scheduler.num_inference_steps




'''simple docstring'''




import argparse
import logging
import os

import datasets
import tensorflow as tf

from transformers import AutoTokenizer


_lowerCAmelCase  :		List[Any]		     =	logging.getLogger(__name__)

def 			__UpperCamelCase    (    )    ->      Any:




	"""simple docstring"""





	lowerCAmelCase					:    str      							= argparse.ArgumentParser(
	    description='Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.'				)
	parser.add_argument(
	    '--dataset_name'					,   type=_A					,   default='wikitext'					,   help='Name of the training. Explore datasets at: hf.co/datasets.'					,   )
	parser.add_argument(
	    '--dataset_config'					,   type=_A					,   default='wikitext-103-raw-v1'					,   help='Configuration name of the dataset.'				)
	parser.add_argument(
	    '--tokenizer_name_or_path'					,   type=_A					,   default='sayakpaul/unigram-tokenizer-wikitext'					,   help='Tokenizer identifier. Can be a local filepath or a Hub identifier.'					,   )
	parser.add_argument(
	    '--shard_size'					,   type=_A					,   default=10_00					,   help='Number of entries to go in a single shard.'					,   )
	parser.add_argument('--split'					,   type=_A					,   default='train'					,   choices=['train', 'test', 'validation']				)
	parser.add_argument(
	    '--limit'					,   default=_A					,   type=_A					,   help='Limit the number of shards (used for debugging).'					,   )
	parser.add_argument(
	    '--max_length'					,   type=_A					,   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=_A					,   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.'					,   )

	lowerCAmelCase					:    Any      							= parser.parse_args()
	return args

def 			__UpperCamelCase    (    _A    :				Optional[int]				)    ->      int:




	"""simple docstring"""





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

	return fn

def 			__UpperCamelCase    (    _A    :				int				)    ->      int:




	"""simple docstring"""





	lowerCAmelCase					:    Tuple      							= []
	for i in range(len(tokenized_data['input_ids']				)				):
		lowerCAmelCase					:    Optional[Any]      							= {
		    '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]				)				),
		}
		lowerCAmelCase					:    Any      							= tf.train.Features(feature=_A				)
		lowerCAmelCase					:    List[str]      							= tf.train.Example(features=_A				)
		lowerCAmelCase					:    Tuple      							= example.SerializeToString()
		records.append(_A				)
	return records

def 			__UpperCamelCase    (    _A    :				int				)    ->      Union[str, Any]:




	"""simple docstring"""





	lowerCAmelCase					:    Union[str, Any]      							= datasets.load_dataset(args.dataset_name					,   args.dataset_config					,   split=args.split				)

	if args.limit is not None:
		lowerCAmelCase					:    Optional[Any]      							= min(len(_A				)					,   args.limit				)
		lowerCAmelCase					:    Dict      							= dataset.select(range(_A				)				)
		print(F"Limiting the dataset to {args.limit} entries."				)

	lowerCAmelCase					:    str      							= 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				)
		lowerCAmelCase					:    Any      							= os.path.join(args.output_dir					,   args.split				)
		if not os.path.exists(_A				):
			os.makedirs(_A				)
	else:
		lowerCAmelCase					:    List[Any]      							= os.path.join(args.output_dir					,   args.split				)

	# Tokenize the whole dataset at once.
	lowerCAmelCase					:    Any      							= tokenize_function(_A				)
	lowerCAmelCase					:    Optional[int]      							= dataset.map(_A					,   batched=_A					,   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(_A    :				str				):
		# Concatenate all texts.
		lowerCAmelCase					:    Optional[int]      							= {k: sum(examples[k]					,   []				) for k in examples.keys()}
		lowerCAmelCase					:    str      							= 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 🫀
		lowerCAmelCase					:    List[Any]      							= (total_length // args.max_length) * args.max_length
		# Split by chunks of max_len.
		lowerCAmelCase					:    str      							= {
		    k: [t[i : i + args.max_length] for i in range(0					,   _A					,   args.max_length				)]
		    for k, t in concatenated_examples.items()
		}
		return result

	lowerCAmelCase					:    List[Any]      							= dataset_tokenized.map(_A					,   batched=_A					,   batch_size=10_00					,   num_proc=4				)

	lowerCAmelCase					:    Union[str, Any]      							= 0
	lowerCAmelCase					:    Tuple      							= 0
	for shard in range(0					,   len(_A				)					,   args.shard_size				):
		lowerCAmelCase					:    Optional[Any]      							= grouped_dataset[shard : shard + args.shard_size]
		lowerCAmelCase					:    List[str]      							= len(dataset_snapshot['input_ids']				)
		lowerCAmelCase					:    Union[str, Any]      							= os.path.join(_A					,   F"dataset-{shard_count}-{records_containing}.tfrecord"				)
		lowerCAmelCase					:    List[Any]      							= get_serialized_examples(_A				)

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

		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=_A				)


if __name__ == "__main__":
				_lowerCAmelCase  :		List[Any]		     =	parse_args()
				main(args)
