




import random
import unittest

import numpy as np

import transformers
from transformers import is_flax_available, is_torch_available
from transformers.testing_utils import is_pt_flax_cross_test, require_flax


if is_flax_available():
	import os

	import jax.numpy as jnp
	from jax import jit

	from transformers import AutoTokenizer, FlaxAutoModelForCausalLM
	from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model

	__lowerCamelCase   :						Tuple				=			'''0.12'''  # assumed parallelism: 8


if is_torch_available():
	import torch







def 		lowercase__   (		__A:	Any							,__A:	Dict							,__A:	str=None				):





					'''simple docstring'''






					if rng is None:
										__magic_name__							:	Optional[Any]    							=							random.Random()

					__magic_name__							:	Tuple    							=							1
					for dim in shape:
										total_dims *= dim

					__magic_name__							:	List[Any]    							=							[]
					for _ in range(__A				):
										values.append(rng.randint(0							,vocab_size - 1				)				)

					__magic_name__							:	Dict    							=							np.array(__A							,dtype=jnp.intaa				).reshape(__A				)

					return output







def 		lowercase__   (		__A:	List[Any]							,__A:	Any=None				):





					'''simple docstring'''






					__magic_name__							:	Optional[int]    							=							ids_tensor(__A							,vocab_size=2							,rng=__A				)
					# make sure that at least one token is attended to for each batch
					__magic_name__							:	List[str]    							=							1
					return attn_mask


@require_flax
class    lowerCamelCase    :






			'''simple docstring'''





			UpperCamelCase__								=None
			UpperCamelCase__								=()

			def 							UpperCAmelCase__       ( self			:   Dict  )						->   Optional[int]:
								__magic_name__							,    __magic_name__							:	Any    							=							self.model_tester.prepare_config_and_inputs_for_common()

								# cut to half length & take max batch_size 3
								__magic_name__							:	Union[str, Any]    							=							2
								__magic_name__							:	int    							=							inputs['''input_ids'''].shape[-1] // 2
								__magic_name__							:	Union[str, Any]    							=							inputs['''input_ids'''][:max_batch_size, :sequence_length]

								__magic_name__							:	Optional[Any]    							=							jnp.ones_like(lowerCamelCase_  )
								__magic_name__							:	List[str]    							=							attention_mask[:max_batch_size, :sequence_length]

								# generate max 5 tokens
								__magic_name__							:	Any    							=							input_ids.shape[-1] + 5
								if config.eos_token_id is not None and config.pad_token_id is None:
													# hack to allow generate for models such as GPT2 as is done in `generate()`
													__magic_name__							:	List[Any]    							=							config.eos_token_id
								return config, input_ids, attention_mask, max_length

			@is_pt_flax_cross_test
			def 							UpperCAmelCase__       ( self			:   Optional[Any]  )						->   Any:
								__magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							:	Optional[int]    							=							self._get_input_ids_and_config()
								__magic_name__							:	Dict    							=							False
								__magic_name__							:	str    							=							max_length
								__magic_name__							:	Tuple    							=							0

								for model_class in self.all_generative_model_classes:
													__magic_name__							:	Tuple    							=							model_class(lowerCamelCase_  )

													__magic_name__							:	Tuple    							=							model_class.__name__[4:]  # Skip the "Flax" at the beginning
													__magic_name__							:	Union[str, Any]    							=							getattr(lowerCamelCase_       ,						lowerCamelCase_  )
													__magic_name__							:	Any    							=							pt_model_class(lowerCamelCase_  ).eval()
													__magic_name__							:	str    							=							load_flax_weights_in_pytorch_model(lowerCamelCase_       ,						flax_model.params  )

													__magic_name__							:	Any    							=							flax_model.generate(lowerCamelCase_  ).sequences
													__magic_name__							:	Union[str, Any]    							=							pt_model.generate(torch.tensor(lowerCamelCase_       ,						dtype=torch.long  )  )

													if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]:
																		__magic_name__							:	Union[str, Any]    							=							flax_generation_outputs[:, : pt_generation_outputs.shape[-1]]

													self.assertListEqual(pt_generation_outputs.numpy().tolist()       ,						flax_generation_outputs.tolist()  )

			def 							UpperCAmelCase__       ( self			:   List[str]  )						->   List[str]:
								__magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							:	Dict    							=							self._get_input_ids_and_config()
								__magic_name__							:	Union[str, Any]    							=							False
								__magic_name__							:	List[Any]    							=							max_length

								for model_class in self.all_generative_model_classes:
													__magic_name__							:	str    							=							model_class(lowerCamelCase_  )

													__magic_name__							:	Any    							=							model.generate(lowerCamelCase_  ).sequences
													self.assertEqual(generation_outputs.shape[-1]       ,						lowerCamelCase_  )

													__magic_name__							:	Optional[int]    							=							jit(model.generate  )
													__magic_name__							:	Any    							=							jit_generate(lowerCamelCase_  ).sequences

													self.assertListEqual(generation_outputs.tolist()       ,						jit_generation_outputs.tolist()  )

			def 							UpperCAmelCase__       ( self			:   Union[str, Any]  )						->   Optional[int]:
								__magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							:	Optional[Any]    							=							self._get_input_ids_and_config()
								__magic_name__							:	Optional[int]    							=							True
								__magic_name__							:	List[Any]    							=							max_length

								for model_class in self.all_generative_model_classes:
													__magic_name__							:	Tuple    							=							model_class(lowerCamelCase_  )

													__magic_name__							:	Any    							=							model.generate(lowerCamelCase_  ).sequences
													self.assertEqual(generation_outputs.shape[-1]       ,						lowerCamelCase_  )

													__magic_name__							:	List[Any]    							=							jit(model.generate  )
													__magic_name__							:	List[str]    							=							jit_generate(lowerCamelCase_  ).sequences

													self.assertListEqual(generation_outputs.tolist()       ,						jit_generation_outputs.tolist()  )

			def 							UpperCAmelCase__       ( self			:   List[Any]  )						->   List[str]:
								__magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							:	Union[str, Any]    							=							self._get_input_ids_and_config()
								__magic_name__							:	int    							=							False
								__magic_name__							:	Any    							=							max_length
								__magic_name__							:	Optional[int]    							=							2

								for model_class in self.all_generative_model_classes:
													__magic_name__							:	Union[str, Any]    							=							model_class(lowerCamelCase_  )

													__magic_name__							:	Any    							=							model.generate(lowerCamelCase_  ).sequences
													self.assertEqual(generation_outputs.shape[-1]       ,						lowerCamelCase_  )

													__magic_name__							:	Optional[Any]    							=							jit(model.generate  )
													__magic_name__							:	Any    							=							jit_generate(lowerCamelCase_  ).sequences

													self.assertListEqual(generation_outputs.tolist()       ,						jit_generation_outputs.tolist()  )

			def 							UpperCAmelCase__       ( self			:   Union[str, Any]  )						->   Tuple:
								__magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							:	Union[str, Any]    							=							self._get_input_ids_and_config()
								__magic_name__							:	Dict    							=							False
								__magic_name__							:	int    							=							max_length
								__magic_name__							:	Optional[int]    							=							2
								__magic_name__							:	List[str]    							=							2

								for model_class in self.all_generative_model_classes:
													__magic_name__							:	Optional[Any]    							=							model_class(lowerCamelCase_  )

													__magic_name__							:	Union[str, Any]    							=							model.generate(lowerCamelCase_  ).sequences
													self.assertEqual(generation_outputs.shape[0]       ,						input_ids.shape[0] * config.num_return_sequences  )

			def 							UpperCAmelCase__       ( self			:   str  )						->   Optional[int]:
								__magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							:	str    							=							self._get_input_ids_and_config()
								__magic_name__							:	List[Any]    							=							True
								__magic_name__							:	Union[str, Any]    							=							max_length
								__magic_name__							:	List[str]    							=							0.8
								__magic_name__							:	Union[str, Any]    							=							10
								__magic_name__							:	Tuple    							=							0.3
								__magic_name__							:	Optional[Any]    							=							1
								__magic_name__							:	str    							=							8
								__magic_name__							:	Optional[Any]    							=							9

								for model_class in self.all_generative_model_classes:
													__magic_name__							:	Optional[Any]    							=							model_class(lowerCamelCase_  )

													__magic_name__							:	Optional[Any]    							=							model.generate(lowerCamelCase_  ).sequences
													self.assertEqual(generation_outputs.shape[-1]       ,						lowerCamelCase_  )

													__magic_name__							:	Tuple    							=							jit(model.generate  )
													__magic_name__							:	str    							=							jit_generate(lowerCamelCase_  ).sequences

													self.assertListEqual(generation_outputs.tolist()       ,						jit_generation_outputs.tolist()  )

			def 							UpperCAmelCase__       ( self			:   Tuple  )						->   Any:
								__magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							:	Any    							=							self._get_input_ids_and_config()
								__magic_name__							:	List[str]    							=							max_length
								__magic_name__							:	List[Any]    							=							1
								__magic_name__							:	str    							=							8
								__magic_name__							:	str    							=							9

								for model_class in self.all_generative_model_classes:
													__magic_name__							:	List[Any]    							=							model_class(lowerCamelCase_  )

													__magic_name__							:	List[Any]    							=							model.generate(lowerCamelCase_  ).sequences
													self.assertEqual(generation_outputs.shape[-1]       ,						lowerCamelCase_  )

													__magic_name__							:	Tuple    							=							jit(model.generate  )
													__magic_name__							:	Tuple    							=							jit_generate(lowerCamelCase_  ).sequences

													self.assertListEqual(generation_outputs.tolist()       ,						jit_generation_outputs.tolist()  )

			def 							UpperCAmelCase__       ( self			:   Dict  )						->   Optional[Any]:
								__magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							:	Any    							=							self._get_input_ids_and_config()
								__magic_name__							:	Any    							=							max_length
								__magic_name__							:	List[str]    							=							2
								__magic_name__							:	Any    							=							1
								__magic_name__							:	str    							=							8
								__magic_name__							:	Optional[Any]    							=							9

								for model_class in self.all_generative_model_classes:
													__magic_name__							:	int    							=							model_class(lowerCamelCase_  )

													__magic_name__							:	Tuple    							=							model.generate(lowerCamelCase_  ).sequences
													self.assertEqual(generation_outputs.shape[-1]       ,						lowerCamelCase_  )

													__magic_name__							:	Optional[int]    							=							jit(model.generate  )
													__magic_name__							:	int    							=							jit_generate(lowerCamelCase_  ).sequences

													self.assertListEqual(generation_outputs.tolist()       ,						jit_generation_outputs.tolist()  )

			def 							UpperCAmelCase__       ( self			:   Optional[int]  )						->   Optional[Any]:
								__magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							:	Union[str, Any]    							=							self._get_input_ids_and_config()

								# pad attention mask on the left
								__magic_name__							:	Any    							=							attention_mask.at[(0, 0)].set(0  )

								__magic_name__							:	Union[str, Any]    							=							False
								__magic_name__							:	Optional[Any]    							=							max_length

								for model_class in self.all_generative_model_classes:
													__magic_name__							:	Any    							=							model_class(lowerCamelCase_  )

													__magic_name__							:	Any    							=							model.generate(lowerCamelCase_       ,						attention_mask=lowerCamelCase_  ).sequences
													self.assertEqual(generation_outputs.shape[-1]       ,						lowerCamelCase_  )

													__magic_name__							:	List[Any]    							=							jit(model.generate  )
													__magic_name__							:	Any    							=							jit_generate(lowerCamelCase_       ,						attention_mask=lowerCamelCase_  ).sequences

													self.assertListEqual(generation_outputs.tolist()       ,						jit_generation_outputs.tolist()  )

			def 							UpperCAmelCase__       ( self			:   Optional[int]  )						->   Union[str, Any]:
								__magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							:	Optional[Any]    							=							self._get_input_ids_and_config()

								# pad attention mask on the left
								__magic_name__							:	Dict    							=							attention_mask.at[(0, 0)].set(0  )

								__magic_name__							:	str    							=							True
								__magic_name__							:	List[Any]    							=							max_length

								for model_class in self.all_generative_model_classes:
													__magic_name__							:	Optional[Any]    							=							model_class(lowerCamelCase_  )

													__magic_name__							:	Union[str, Any]    							=							model.generate(lowerCamelCase_       ,						attention_mask=lowerCamelCase_  ).sequences
													self.assertEqual(generation_outputs.shape[-1]       ,						lowerCamelCase_  )

													__magic_name__							:	Optional[int]    							=							jit(model.generate  )
													__magic_name__							:	Optional[Any]    							=							jit_generate(lowerCamelCase_       ,						attention_mask=lowerCamelCase_  ).sequences

													self.assertListEqual(generation_outputs.tolist()       ,						jit_generation_outputs.tolist()  )


			def 							UpperCAmelCase__       ( self			:   int  )						->   Optional[int]:
								__magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							:	Any    							=							self._get_input_ids_and_config()

								# pad attention mask on the left
								__magic_name__							:	str    							=							attention_mask.at[(0, 0)].set(0  )

								__magic_name__							:	List[Any]    							=							2
								__magic_name__							:	Optional[Any]    							=							max_length

								for model_class in self.all_generative_model_classes:
													__magic_name__							:	Optional[int]    							=							model_class(lowerCamelCase_  )

													__magic_name__							:	Union[str, Any]    							=							model.generate(lowerCamelCase_       ,						attention_mask=lowerCamelCase_  ).sequences
													self.assertEqual(generation_outputs.shape[-1]       ,						lowerCamelCase_  )

													__magic_name__							:	Dict    							=							jit(model.generate  )
													__magic_name__							:	List[str]    							=							jit_generate(lowerCamelCase_       ,						attention_mask=lowerCamelCase_  ).sequences

													self.assertListEqual(generation_outputs.tolist()       ,						jit_generation_outputs.tolist()  )






@require_flax
class    lowerCamelCase    (		unittest.TestCase						):






			'''simple docstring'''





			def 							UpperCAmelCase__       ( self			:   Any  )						->   Any:
								__magic_name__							:	Any    							=							AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-bert'''  )
								__magic_name__							:	List[Any]    							=							FlaxAutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-bert-flax-only'''  )

								__magic_name__							:	str    							=							'''Hello world'''
								__magic_name__							:	Any    							=							tokenizer(lowerCamelCase_       ,						return_tensors='''np'''  ).input_ids

								# typos are quickly detected (the correct argument is `do_sample`)
								with self.assertRaisesRegex(lowerCamelCase_       ,						'''do_samples'''  ):
													model.generate(lowerCamelCase_       ,						do_samples=lowerCamelCase_  )

								# arbitrary arguments that will not be used anywhere are also not accepted
								with self.assertRaisesRegex(lowerCamelCase_       ,						'''foo'''  ):
													__magic_name__							:	Any    							=							{'''foo''': '''bar'''}
													model.generate(lowerCamelCase_       ,						**lowerCamelCase_  )









import multiprocessing
import os
from typing import BinaryIO, Optional, Union

import fsspec

from .. import Dataset, Features, NamedSplit, config
from ..formatting import query_table
from ..packaged_modules.json.json import Json
from ..utils import logging
from ..utils.typing import NestedDataStructureLike, PathLike
from .abc import AbstractDatasetReader


class    lowerCamelCase    (		_lowerCamelCase						):






			'''simple docstring'''





			def __init__( self			:   List[Any]       ,						lowerCamelCase_			:   NestedDataStructureLike[PathLike]       ,						lowerCamelCase_			:   Optional[NamedSplit] = None       ,						lowerCamelCase_			:   Optional[Features] = None       ,						lowerCamelCase_			:   str = None       ,						lowerCamelCase_			:   bool = False       ,						lowerCamelCase_			:   bool = False       ,						lowerCamelCase_			:   Optional[str] = None       ,						lowerCamelCase_			:   Optional[int] = None       ,						**lowerCamelCase_			:   str       ,						)						->   Dict:
								super().__init__(
								    lowerCamelCase_       ,						split=lowerCamelCase_       ,						features=lowerCamelCase_       ,						cache_dir=lowerCamelCase_       ,						keep_in_memory=lowerCamelCase_       ,						streaming=lowerCamelCase_       ,						num_proc=lowerCamelCase_       ,						**lowerCamelCase_       ,						)
								__magic_name__							:	Optional[int]    							=							field
								__magic_name__							:	Optional[Any]    							=							path_or_paths if isinstance(lowerCamelCase_       ,						lowerCamelCase_  ) else {self.split: path_or_paths}
								__magic_name__							:	Optional[Any]    							=							Json(
								    cache_dir=lowerCamelCase_       ,						data_files=lowerCamelCase_       ,						features=lowerCamelCase_       ,						field=lowerCamelCase_       ,						**lowerCamelCase_       ,						)


			def 							UpperCAmelCase__       ( self			:   Optional[Any]  )						->   List[str]:
								# Build iterable dataset
								if self.streaming:
													__magic_name__							:	Optional[Any]    							=							self.builder.as_streaming_dataset(split=self.split  )
								# Build regular (map-style) dataset
								else:
													__magic_name__							:	int    							=							None
													__magic_name__							:	Tuple    							=							None
													__magic_name__							:	Tuple    							=							None
													__magic_name__							:	Optional[int]    							=							None

													self.builder.download_and_prepare(
													    download_config=lowerCamelCase_       ,						download_mode=lowerCamelCase_       ,						verification_mode=lowerCamelCase_       ,						base_path=lowerCamelCase_       ,						num_proc=self.num_proc       ,						)
													__magic_name__							:	Any    							=							self.builder.as_dataset(
													    split=self.split       ,						verification_mode=lowerCamelCase_       ,						in_memory=self.keep_in_memory  )
								return dataset






class    lowerCamelCase    :






			'''simple docstring'''





			def __init__( self			:   int       ,						lowerCamelCase_			:   Dataset       ,						lowerCamelCase_			:   Union[PathLike, BinaryIO]       ,						lowerCamelCase_			:   Optional[int] = None       ,						lowerCamelCase_			:   Optional[int] = None       ,						**lowerCamelCase_			:   List[Any]       ,						)						->   List[Any]:
								if num_proc is not None and num_proc <= 0:
													raise ValueError(F'''num_proc {num_proc} must be an integer > 0.'''  )

								__magic_name__							:	Optional[Any]    							=							dataset
								__magic_name__							:	Tuple    							=							path_or_buf
								__magic_name__							:	Dict    							=							batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE
								__magic_name__							:	Any    							=							num_proc
								__magic_name__							:	Tuple    							=							'''utf-8'''
								__magic_name__							:	Tuple    							=							to_json_kwargs

			def 							UpperCAmelCase__       ( self			:   Dict  )						->   int:
								__magic_name__							:	int    							=							self.to_json_kwargs.pop('''path_or_buf'''       ,						lowerCamelCase_  )
								__magic_name__							:	Any    							=							self.to_json_kwargs.pop('''orient'''       ,						'''records'''  )
								__magic_name__							:	List[Any]    							=							self.to_json_kwargs.pop('''lines'''       ,						True if orient == '''records''' else False  )
								__magic_name__							:	Optional[int]    							=							self.to_json_kwargs.pop('''index'''       ,						False if orient in ['''split''', '''table'''] else True  )
								__magic_name__							:	List[str]    							=							self.to_json_kwargs.pop('''compression'''       ,						lowerCamelCase_  )

								if compression not in [None, "infer", "gzip", "bz2", "xz"]:
													raise NotImplementedError(F'''`datasets` currently does not support {compression} compression'''  )

								if isinstance(self.path_or_buf       ,						(str, bytes, os.PathLike)  ):
													with fsspec.open(self.path_or_buf       ,						'''wb'''       ,						compression=lowerCamelCase_  ) as buffer:
																		__magic_name__							:	str    							=							self._write(file_obj=lowerCamelCase_       ,						orient=lowerCamelCase_       ,						lines=lowerCamelCase_       ,						index=lowerCamelCase_       ,						**self.to_json_kwargs  )
								else:
													if compression:
																		raise NotImplementedError(
																		    F'''The compression parameter is not supported when writing to a buffer, but compression={compression}'''
																		    ''' was passed. Please provide a local path instead.'''  )
													__magic_name__							:	List[str]    							=							self._write(
													    file_obj=self.path_or_buf       ,						orient=lowerCamelCase_       ,						lines=lowerCamelCase_       ,						index=lowerCamelCase_       ,						**self.to_json_kwargs  )
								return written

			def 							UpperCAmelCase__       ( self			:   Optional[Any]       ,						lowerCamelCase_			:   Dict  )						->   Optional[int]:
								__magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							:	Any    							=							args

								__magic_name__							:	List[Any]    							=							query_table(
								    table=self.dataset.data       ,						key=slice(lowerCamelCase_       ,						offset + self.batch_size  )       ,						indices=self.dataset._indices       ,						)
								__magic_name__							:	Optional[Any]    							=							batch.to_pandas().to_json(
								    path_or_buf=lowerCamelCase_       ,						orient=lowerCamelCase_       ,						lines=lowerCamelCase_       ,						index=lowerCamelCase_       ,						**lowerCamelCase_  )
								if not json_str.endswith('''\n'''  ):
													json_str += "\n"
								return json_str.encode(self.encoding  )


			def 							UpperCAmelCase__       ( self			:   int       ,						lowerCamelCase_			:   BinaryIO       ,						lowerCamelCase_			:   List[str]       ,						lowerCamelCase_			:   Union[str, Any]       ,						lowerCamelCase_			:   Any       ,						**lowerCamelCase_			:   Optional[Any]       ,						)						->   int:
								__magic_name__							:	Union[str, Any]    							=							0

								if self.num_proc is None or self.num_proc == 1:
													for offset in logging.tqdm(
													    range(0       ,						len(self.dataset  )       ,						self.batch_size  )       ,						unit='''ba'''       ,						disable=not logging.is_progress_bar_enabled()       ,						desc='''Creating json from Arrow format'''       ,						):
																		__magic_name__							:	List[str]    							=							self._batch_json((offset, orient, lines, index, to_json_kwargs)  )
																		written += file_obj.write(lowerCamelCase_  )
								else:
													__magic_name__							,    __magic_name__							:	Optional[Any]    							=							len(self.dataset  ), self.batch_size
													with multiprocessing.Pool(self.num_proc  ) as pool:
																		for json_str in logging.tqdm(
																		    pool.imap(
																		        self._batch_json       ,						[(offset, orient, lines, index, to_json_kwargs) for offset in range(0       ,						lowerCamelCase_       ,						lowerCamelCase_  )]       ,						)       ,						total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size       ,						unit='''ba'''       ,						disable=not logging.is_progress_bar_enabled()       ,						desc='''Creating json from Arrow format'''       ,						):
																							written += file_obj.write(lowerCamelCase_  )

								return written



