
'''simple docstring'''

import unittest

from transformers import ErnieMConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

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 (
				    ErnieMForInformationExtraction,
				    ErnieMForMultipleChoice,
				    ErnieMForQuestionAnswering,
				    ErnieMForSequenceClassification,
				    ErnieMForTokenClassification,
				    ErnieMModel,
				)
				from transformers.models.ernie_m.modeling_ernie_m import ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST







class   UpperCamelCase__   :


		"""simple docstring"""

		def __init__(			self   ,      snake_case   ,      snake_case=1_3   ,      snake_case=7   ,      snake_case=True   ,      snake_case=True   ,      snake_case=True   ,      snake_case=9_9   ,      snake_case=3_2   ,      snake_case=5   ,      snake_case=4   ,      snake_case=3_7   ,      snake_case="gelu"   ,      snake_case=0.1   ,      snake_case=0.1   ,      snake_case=5_1_2   ,      snake_case=1_6   ,      snake_case=2   ,      snake_case=0.02   ,      snake_case=3   ,      snake_case=4   ,      snake_case=None   ,      ):


							'''simple docstring'''

							UpperCAmelCase		:							List[str]        =       parent
							UpperCAmelCase		:							List[str]        =       batch_size
							UpperCAmelCase		:							int        =       seq_length
							UpperCAmelCase		:							List[str]        =       is_training
							UpperCAmelCase		:							List[Any]        =       use_input_mask
							UpperCAmelCase		:							List[Any]        =       use_labels
							UpperCAmelCase		:							Union[str, Any]        =       vocab_size
							UpperCAmelCase		:							Tuple        =       hidden_size
							UpperCAmelCase		:							Optional[int]        =       num_hidden_layers
							UpperCAmelCase		:							Optional[Any]        =       num_attention_heads
							UpperCAmelCase		:							Optional[int]        =       intermediate_size
							UpperCAmelCase		:							Dict        =       hidden_act
							UpperCAmelCase		:							List[str]        =       hidden_dropout_prob
							UpperCAmelCase		:							List[str]        =       attention_probs_dropout_prob
							UpperCAmelCase		:							Optional[Any]        =       max_position_embeddings
							UpperCAmelCase		:							Dict        =       type_vocab_size
							UpperCAmelCase		:							List[str]        =       type_sequence_label_size
							UpperCAmelCase		:							Any        =       initializer_range
							UpperCAmelCase		:							Tuple        =       num_labels
							UpperCAmelCase		:							Optional[int]        =       num_choices
							UpperCAmelCase		:							Tuple        =       scope







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							str        =       ids_tensor([self.batch_size, self.seq_length]   ,      self.vocab_size      )

							UpperCAmelCase		:							int        =       None
							if self.use_input_mask:
												UpperCAmelCase		:							Optional[int]        =       random_attention_mask([self.batch_size, self.seq_length]      )

							UpperCAmelCase		:							Tuple        =       None
							UpperCAmelCase		:							Tuple        =       None
							UpperCAmelCase		:							Optional[int]        =       None
							if self.use_labels:
												UpperCAmelCase		:							Optional[Any]        =       ids_tensor([self.batch_size]   ,      self.type_sequence_label_size      )
												UpperCAmelCase		:							Dict        =       ids_tensor([self.batch_size, self.seq_length]   ,      self.num_labels      )
												UpperCAmelCase		:							str        =       ids_tensor([self.batch_size]   ,      self.num_choices      )

							UpperCAmelCase		:							Optional[Any]        =       self.get_config()

							return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							List[Any]        =       ids_tensor([self.batch_size, self.seq_length]   ,      self.vocab_size      )

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

							return config, input_ids, input_mask







		def 				A_	(			self      ):


							'''simple docstring'''

							return ErnieMConfig(
							    vocab_size=self.vocab_size   ,      hidden_size=self.hidden_size   ,      num_hidden_layers=self.num_hidden_layers   ,      num_attention_heads=self.num_attention_heads   ,      intermediate_size=self.intermediate_size   ,      hidden_act=self.hidden_act   ,      hidden_dropout_prob=self.hidden_dropout_prob   ,      attention_probs_dropout_prob=self.attention_probs_dropout_prob   ,      max_position_embeddings=self.max_position_embeddings   ,      type_vocab_size=self.type_vocab_size   ,      initializer_range=self.initializer_range   ,      )







		def 				A_	(			self   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case      ):


							'''simple docstring'''

							UpperCAmelCase		:							int        =       ErnieMModel(config=snake_case      )
							model.to(snake_case      )
							model.eval()
							UpperCAmelCase		:							Any        =       model(snake_case   ,      return_dict=snake_case      )
							self.parent.assertEqual(result.last_hidden_state.shape   ,      (self.batch_size, self.seq_length, self.hidden_size)      )







		def 				A_	(			self   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case      ):


							'''simple docstring'''

							UpperCAmelCase		:							Union[str, Any]        =       ErnieMForQuestionAnswering(config=snake_case      )
							model.to(snake_case      )
							model.eval()
							UpperCAmelCase		:							int        =       model(
							    snake_case   ,      attention_mask=snake_case   ,      start_positions=snake_case   ,      end_positions=snake_case   ,      )
							self.parent.assertEqual(result.start_logits.shape   ,      (self.batch_size, self.seq_length)      )
							self.parent.assertEqual(result.end_logits.shape   ,      (self.batch_size, self.seq_length)      )







		def 				A_	(			self   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case      ):


							'''simple docstring'''

							UpperCAmelCase		:							str        =       ErnieMForInformationExtraction(config=snake_case      )
							model.to(snake_case      )
							model.eval()
							UpperCAmelCase		:							Optional[Any]        =       torch.ones_like(snake_case   ,      dtype=torch.floataa      )
							UpperCAmelCase		:							Optional[int]        =       model(
							    snake_case   ,      attention_mask=snake_case   ,      start_positions=snake_case   ,      end_positions=snake_case   ,      )
							self.parent.assertEqual(result.start_logits.shape   ,      (self.batch_size, self.seq_length)      )
							self.parent.assertEqual(result.end_logits.shape   ,      (self.batch_size, self.seq_length)      )







		def 				A_	(			self   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case      ):


							'''simple docstring'''

							UpperCAmelCase		:							int        =       self.num_labels
							UpperCAmelCase		:							List[str]        =       ErnieMForSequenceClassification(snake_case      )
							model.to(snake_case      )
							model.eval()
							UpperCAmelCase		:							Union[str, Any]        =       model(snake_case   ,      attention_mask=snake_case   ,      labels=snake_case      )
							self.parent.assertEqual(result.logits.shape   ,      (self.batch_size, self.num_labels)      )







		def 				A_	(			self   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case      ):


							'''simple docstring'''

							UpperCAmelCase		:							List[Any]        =       self.num_labels
							UpperCAmelCase		:							Optional[Any]        =       ErnieMForTokenClassification(config=snake_case      )
							model.to(snake_case      )
							model.eval()
							input_ids.to(snake_case      )
							input_mask.to(snake_case      )
							token_labels.to(snake_case      )

							UpperCAmelCase		:							int        =       model(snake_case   ,      attention_mask=snake_case   ,      labels=snake_case      )

							self.parent.assertEqual(result.logits.shape   ,      (self.batch_size, self.seq_length, self.num_labels)      )







		def 				A_	(			self   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case      ):


							'''simple docstring'''

							UpperCAmelCase		:							Union[str, Any]        =       self.num_choices
							UpperCAmelCase		:							int        =       ErnieMForMultipleChoice(config=snake_case      )
							model.to(snake_case      )
							model.eval()
							UpperCAmelCase		:							Union[str, Any]        =       input_ids.unsqueeze(1      ).expand(-1   ,      self.num_choices   ,      -1      ).contiguous()
							UpperCAmelCase		:							int        =       input_mask.unsqueeze(1      ).expand(-1   ,      self.num_choices   ,      -1      ).contiguous()
							UpperCAmelCase		:							Any        =       model(
							    snake_case   ,      attention_mask=snake_case   ,      labels=snake_case   ,      )
							self.parent.assertEqual(result.logits.shape   ,      (self.batch_size, self.num_choices)      )







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							Optional[Any]        =       self.prepare_config_and_inputs()
							(
							    (
							    UpperCAmelCase   
							) ,			(
							    UpperCAmelCase   
							) ,			(
							    UpperCAmelCase   
							) ,			(
							    UpperCAmelCase   
							) ,			(
							    UpperCAmelCase   
							) ,			(
							    UpperCAmelCase   
							) ,			   
							)		:							int        =       config_and_inputs
							UpperCAmelCase		:							Optional[int]        =       {"input_ids": input_ids, "attention_mask": input_mask}
							return config, inputs_dict







@require_torch
class   UpperCamelCase__   (       lowercase__							,							lowercase__							,							unittest.TestCase       ):


		"""simple docstring"""

		SCREAMING_SNAKE_CASE__  :     Union[str, Any]       =							(
		    (
		        ErnieMModel,
		        ErnieMForMultipleChoice,
		        ErnieMForQuestionAnswering,
		        ErnieMForSequenceClassification,
		        ErnieMForTokenClassification,
		    )
		    if is_torch_available()
		    else ()
		)
		SCREAMING_SNAKE_CASE__  :     Optional[Any]       =							()
		SCREAMING_SNAKE_CASE__  :     Union[str, Any]       =							(
		    {
		        'feature-extraction': ErnieMModel,
		        'question-answering': ErnieMForQuestionAnswering,
		        'text-classification': ErnieMForSequenceClassification,
		        'token-classification': ErnieMForTokenClassification,
		        'zero-shot': ErnieMForSequenceClassification,
		    }
		    if is_torch_available()
		    else {}
		)
		SCREAMING_SNAKE_CASE__  :     Optional[Any]       =							False







		def 				A_	(			self   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case   ,      snake_case      ):


							'''simple docstring'''

							if pipeline_test_casse_name == "QAPipelineTests":
												return True

							return False







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							Any        =       ErnieMModelTester(self      )
							UpperCAmelCase		:							List[str]        =       ConfigTester(self   ,      config_class=snake_case   ,      hidden_size=3_7      )







		def 				A_	(			self      ):


							'''simple docstring'''

							self.config_tester.run_common_tests()







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							Dict        =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*snake_case      )







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							Dict        =       self.model_tester.prepare_config_and_inputs()
							for type in ["absolute", "relative_key", "relative_key_query"]:
												UpperCAmelCase		:							Union[str, Any]        =       type
												self.model_tester.create_and_check_model(*snake_case      )







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							List[Any]        =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_multiple_choice(*snake_case      )







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							int        =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_question_answering(*snake_case      )







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							str        =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_sequence_classification(*snake_case      )







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							List[str]        =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_information_extraction(*snake_case      )







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							int        =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_token_classification(*snake_case      )







		@slow
		def 				A_	(			self      ):


							'''simple docstring'''

							for model_name in ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												UpperCAmelCase		:							List[Any]        =       ErnieMModel.from_pretrained(snake_case      )
												self.assertIsNotNone(snake_case      )







@require_torch
class   UpperCamelCase__   (       unittest.TestCase       ):


		"""simple docstring"""

		@slow
		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							str        =       ErnieMModel.from_pretrained("susnato/ernie-m-base_pytorch"      )
							model.eval()
							UpperCAmelCase		:							Union[str, Any]        =       torch.tensor([[0, 1, 2, 3, 4, 5]]      )
							UpperCAmelCase		:							Optional[Any]        =       model(snake_case      )[0]

							# TODO Replace vocab size
							UpperCAmelCase		:							Optional[int]        =       7_6_8

							UpperCAmelCase		:							Optional[Any]        =       torch.Size((1, 6, hidden_size)      )
							self.assertEqual(output.shape   ,      snake_case      )

							UpperCAmelCase		:							List[Any]        =       torch.tensor(
							    [[[-0.0012, 0.1245, -0.0214], [-0.0742, 0.0244, -0.0771], [-0.0333, 0.1164, -0.1554]]]      )

							self.assertTrue(torch.allclose(output[:, :3, :3]   ,      snake_case   ,      atol=1e-3      )      )



'''simple docstring'''

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

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







class   UpperCamelCase__   (       lowercase__       ):


		"""simple docstring"""

		def __init__(			self   ,      snake_case   ,      snake_case = None   ,      snake_case = None   ,      snake_case = None   ,      snake_case = False   ,      snake_case = False   ,      snake_case = None   ,      **snake_case   ,      ):


							'''simple docstring'''

							super().__init__(
							    snake_case   ,      split=snake_case   ,      features=snake_case   ,      cache_dir=snake_case   ,      keep_in_memory=snake_case   ,      streaming=snake_case   ,      num_proc=snake_case   ,      **snake_case   ,      )
							UpperCAmelCase		:							str        =       path_or_paths if isinstance(snake_case   ,      snake_case      ) else {self.split: path_or_paths}
							UpperCAmelCase		:							int        =       Csv(
							    cache_dir=snake_case   ,      data_files=snake_case   ,      features=snake_case   ,      **snake_case   ,      )







		def 				A_	(			self      ):


							'''simple docstring'''

							if self.streaming:
												UpperCAmelCase		:							Optional[Any]        =       self.builder.as_streaming_dataset(split=self.split      )
							# Build regular (map-style) dataset
							else:
												UpperCAmelCase		:							Union[str, Any]        =       None
												UpperCAmelCase		:							str        =       None
												UpperCAmelCase		:							Union[str, Any]        =       None
												UpperCAmelCase		:							int        =       None

												self.builder.download_and_prepare(
												    download_config=snake_case   ,      download_mode=snake_case   ,      verification_mode=snake_case   ,      base_path=snake_case   ,      num_proc=self.num_proc   ,      )
												UpperCAmelCase		:							Tuple        =       self.builder.as_dataset(
												    split=self.split   ,      verification_mode=snake_case   ,      in_memory=self.keep_in_memory      )
							return dataset







class   UpperCamelCase__   :


		"""simple docstring"""

		def __init__(			self   ,      snake_case   ,      snake_case   ,      snake_case = None   ,      snake_case = None   ,      **snake_case   ,      ):


							'''simple docstring'''

							if num_proc is not None and num_proc <= 0:
												raise ValueError(f"num_proc {num_proc} must be an integer > 0."      )

							UpperCAmelCase		:							Tuple        =       dataset
							UpperCAmelCase		:							Dict        =       path_or_buf
							UpperCAmelCase		:							List[Any]        =       batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE
							UpperCAmelCase		:							str        =       num_proc
							UpperCAmelCase		:							List[Any]        =       "utf-8"
							UpperCAmelCase		:							Tuple        =       to_csv_kwargs







		def 				A_	(			self      ):


							'''simple docstring'''

							UpperCAmelCase		:							List[str]        =       self.to_csv_kwargs.pop("path_or_buf"   ,      snake_case      )
							UpperCAmelCase		:							Any        =       self.to_csv_kwargs.pop("header"   ,      snake_case      )
							UpperCAmelCase		:							Dict        =       self.to_csv_kwargs.pop("index"   ,      snake_case      )

							if isinstance(self.path_or_buf   ,      (str, bytes, os.PathLike)      ):
												with open(self.path_or_buf   ,      "wb+"      ) as buffer:
																	UpperCAmelCase		:							Tuple        =       self._write(file_obj=snake_case   ,      header=snake_case   ,      index=snake_case   ,      **self.to_csv_kwargs      )
							else:
												UpperCAmelCase		:							Any        =       self._write(file_obj=self.path_or_buf   ,      header=snake_case   ,      index=snake_case   ,      **self.to_csv_kwargs      )
							return written







		def 				A_	(			self   ,      snake_case      ):


							'''simple docstring'''

							UpperCAmelCase ,			UpperCAmelCase ,			UpperCAmelCase ,			UpperCAmelCase		:							Optional[int]        =       args

							UpperCAmelCase		:							List[str]        =       query_table(
							    table=self.dataset.data   ,      key=slice(snake_case   ,      offset + self.batch_size      )   ,      indices=self.dataset._indices   ,      )
							UpperCAmelCase		:							int        =       batch.to_pandas().to_csv(
							    path_or_buf=snake_case   ,      header=header if (offset == 0) else False   ,      index=snake_case   ,      **snake_case      )
							return csv_str.encode(self.encoding      )







		def 				A_	(			self   ,      snake_case   ,      snake_case   ,      snake_case   ,      **snake_case      ):


							'''simple docstring'''

							UpperCAmelCase		:							List[str]        =       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 CSV from Arrow format"   ,      ):
																	UpperCAmelCase		:							Any        =       self._batch_csv((offset, header, index, to_csv_kwargs)      )
																	written += file_obj.write(snake_case      )

							else:
												UpperCAmelCase ,			UpperCAmelCase		:							Union[str, Any]        =       len(self.dataset      ), self.batch_size
												with multiprocessing.Pool(self.num_proc      ) as pool:
																	for csv_str in logging.tqdm(
																	    pool.imap(
																	        self._batch_csv   ,      [(offset, header, index, to_csv_kwargs) for offset in range(0   ,      snake_case   ,      snake_case      )]   ,      )   ,      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 CSV from Arrow format"   ,      ):
																						written += file_obj.write(snake_case      )

							return written
