




def        __a							(  __UpperCAmelCase		:						int      ) ->					str:
							"""simple docstring"""




							lowerCamelCase_			:    Dict   						=      generate_pascal_triangle(lowerCamelCase__      )
							for row_idx in range(lowerCamelCase__      ):
														# Print left spaces
														for _ in range(num_rows - row_idx - 1      ):
																					print(end=" "      )
														# Print row values
														for col_idx in range(row_idx + 1      ):
																					if col_idx != row_idx:
																												print(triangle[row_idx][col_idx]   ,		end=" "      )
																					else:
																												print(triangle[row_idx][col_idx]   ,		end=""      )
														print()



def        __a							(  __UpperCAmelCase		:						int      ) ->					Tuple:
							"""simple docstring"""




							if not isinstance(lowerCamelCase__   ,		lowerCamelCase__      ):
														raise TypeError("The input value of 'num_rows' should be 'int'"      )

							if num_rows == 0:
														return []
							elif num_rows < 0:
														raise ValueError(
														    "The input value of 'num_rows' should be greater than or equal to 0"      )

							lowerCamelCase_			:    Union[str, Any]   						=      []
							for current_row_idx in range(lowerCamelCase__      ):
														lowerCamelCase_			:    str   						=      populate_current_row(lowerCamelCase__   ,		lowerCamelCase__      )
														triangle.append(lowerCamelCase__      )
							return triangle



def        __a							(  __UpperCAmelCase		:						list[list[int]]   ,		__UpperCAmelCase		:						int      ) ->					int:
							"""simple docstring"""




							lowerCamelCase_			:    Tuple   						=      [-1] * (current_row_idx + 1)
							# first and last elements of current row are equal to 1
							lowerCamelCase_						,						lowerCamelCase_			:    Dict   						=      1, 1
							for current_col_idx in range(1   ,		lowerCamelCase__      ):
														calculate_current_element(
														    lowerCamelCase__   ,		lowerCamelCase__   ,		lowerCamelCase__   ,		lowerCamelCase__      )
							return current_row



def        __a							(  __UpperCAmelCase		:						list[list[int]]   ,		__UpperCAmelCase		:						list[int]   ,		__UpperCAmelCase		:						int   ,		__UpperCAmelCase		:						int   ,		) ->					List[str]:
							"""simple docstring"""




							lowerCamelCase_			:    Dict   						=      triangle[current_row_idx - 1][current_col_idx - 1]
							lowerCamelCase_			:    List[str]   						=      triangle[current_row_idx - 1][current_col_idx]
							lowerCamelCase_			:    Union[str, Any]   						=      above_to_left_elt + above_to_right_elt



def        __a							(  __UpperCAmelCase		:						int      ) ->					Union[str, Any]:
							"""simple docstring"""




							if not isinstance(lowerCamelCase__   ,		lowerCamelCase__      ):
														raise TypeError("The input value of 'num_rows' should be 'int'"      )

							if num_rows == 0:
														return []
							elif num_rows < 0:
														raise ValueError(
														    "The input value of 'num_rows' should be greater than or equal to 0"      )

							lowerCamelCase_			:    Optional[int]   						=      [[1]]

							for row_index in range(1   ,		lowerCamelCase__      ):
														lowerCamelCase_			:    List[str]   						=      [0] + result[-1] + [0]
														lowerCamelCase_			:    Optional[int]   						=      row_index + 1
														# Calculate the number of distinct elements in a row
														lowerCamelCase_			:    Tuple   						=      sum(divmod(lowerCamelCase__   ,		2      )      )
														lowerCamelCase_			:    List[str]   						=      [
														    temp_row[i - 1] + temp_row[i] for i in range(1   ,		distinct_elements + 1      )
														]
														lowerCamelCase_			:    int   						=      row_first_half[: (row_index + 1) // 2]
														row_second_half.reverse()
														lowerCamelCase_			:    Dict   						=      row_first_half + row_second_half
														result.append(lowerCamelCase__      )

							return result



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




							from collections.abc import Callable
							from timeit import timeit

							def benchmark_a_function(__UpperCAmelCase		:						Callable   ,		__UpperCAmelCase		:						int      ) -> None:
														lowerCamelCase_			:    Optional[int]   						=      f"{func.__name__}({value})"
														lowerCamelCase_			:    Tuple   						=      timeit(f"__main__.{call}"   ,		setup="import __main__"      )
														# print(f"{call:38} = {func(value)} -- {timing:.4f} seconds")
														print(f"{call:38} -- {timing:.4f} seconds"      )

							for value in range(15      ):  # (1, 7, 14):
														for func in (generate_pascal_triangle, generate_pascal_triangle_optimized):
																					benchmark_a_function(lowerCamelCase__   ,		lowerCamelCase__      )
														print()


if __name__ == "__main__":
	import doctest

	doctest.testmod()
	benchmark()





import argparse
import logging
import os

import datasets
import tensorflow as tf

from transformers import AutoTokenizer


UpperCAmelCase   :    Any     =		logging.getLogger(__name__)






def 	__lowerCamelCase						(							):





			'''simple docstring'''




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






def 	__lowerCamelCase						(							lowerCamelCase__		:						Any      ):





			'''simple docstring'''




			def fn(lowerCamelCase__		:						Any      ):
						return tokenizer(examples["""text"""]      )

			return fn






def 	__lowerCamelCase						(							lowerCamelCase__		:						Optional[int]      ):





			'''simple docstring'''




			lowerCamelCase    		=  []
			for i in range(len(tokenized_data["""input_ids"""]      )      ):
						lowerCamelCase    		=  {
						    """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    		=  tf.train.Features(feature=lowerCamelCase__      )
						lowerCamelCase    		=  tf.train.Example(features=lowerCamelCase__      )
						lowerCamelCase    		=  example.SerializeToString()
						records.append(lowerCamelCase__      )
			return records






def 	__lowerCamelCase						(							lowerCamelCase__		:						str      ):





			'''simple docstring'''




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

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

			lowerCamelCase    		=  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    		=  os.path.join(args.output_dir  ,							args.split      )
						if not os.path.exists(lowerCamelCase__      ):
									os.makedirs(lowerCamelCase__      )
			else:
						lowerCamelCase    		=  os.path.join(args.output_dir  ,							args.split      )

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

			lowerCamelCase    		=  dataset_tokenized.map(lowerCamelCase__  ,							batched=lowerCamelCase__  ,							batch_size=1000  ,							num_proc=4      )

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

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

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


if __name__ == "__main__":
		UpperCAmelCase   :    Optional[int]     =		parse_args()
		main(args)

