from copy import deepcopy
from unittest.case import TestCase

import pytest

from datasets.arrow_dataset import Dataset
from datasets.features import Audio, ClassLabel, Features, Image, Sequence, Value
from datasets.info import DatasetInfo
from datasets.tasks import (
    AudioClassification,
    AutomaticSpeechRecognition,
    ImageClassification,
    LanguageModeling,
    QuestionAnsweringExtractive,
    Summarization,
    TextClassification,
    task_template_from_dict,
)
from datasets.utils.py_utils import asdict


UpperCamelCase      			=     {
    'id': '5733be284776f41900661182',
    'title': 'University_of_Notre_Dame',
    'context': 'Architecturally, the school has a Catholic character. Atop the Main Building\'s gold dome is a golden statue of the Virgin Mary. Immediately in front of the Main Building and facing it, is a copper statue of Christ with arms upraised with the legend "Venite Ad Me Omnes". Next to the Main Building is the Basilica of the Sacred Heart. Immediately behind the basilica is the Grotto, a Marian place of prayer and reflection. It is a replica of the grotto at Lourdes, France where the Virgin Mary reputedly appeared to Saint Bernadette Soubirous in 1858. At the end of the main drive (and in a direct line that connects through 3 statues and the Gold Dome), is a simple, modern stone statue of Mary.',
    'question': 'To whom did the Virgin Mary allegedly appear in 1858 in Lourdes France?',
    'answers': {'text': ['Saint Bernadette Soubirous'], 'answer_start': [515]},
}



@pytest.mark.parametrize(
    "task_cls" ,     [
        AudioClassification,
        AutomaticSpeechRecognition,
        ImageClassification,
        LanguageModeling,
        QuestionAnsweringExtractive,
        Summarization,
        TextClassification,
    ] ,     )
def    lowerCamelCase_   (  _lowercase    )							->	Optional[Any]:
		__A							:   Optional[int]	  =				task_cls()
		__A							:   List[str]	  =				asdict(_lowercase    )
		__A							:   Tuple	  =				task_template_from_dict(_lowercase    )
		assert task == reloaded


class _a       :

	'''simple docstring'''



	def 					__UpperCAmelCase(       self   ):
			__A							:   str	  =				LanguageModeling(text_column="input_text"   )
			assert {"input_text": "text"} == task.column_mapping







	def 					__UpperCAmelCase(       self   ):
			__A							:   List[str]	  =				Features({"text": Value("string"   )}   )
			__A							:   Tuple	  =				{"text_column": "input_text"}
			__A							:   Tuple	  =				LanguageModeling.from_dict(__UpperCAmelCase   )
			assert "language-modeling" == task.task
			assert input_schema == task.input_schema


class _a       (	lowerCAmelCase__ ):

	'''simple docstring'''



	def 					__UpperCAmelCase(       self   ):
			__A							:   Dict	  =				sorted(["pos", "neg"]   )

	def 					__UpperCAmelCase(       self   ):
			__A							:   int	  =				TextClassification(text_column="input_text"							,			label_column="input_label"   )
			self.assertDictEqual({"input_text": "text", "input_label": "labels"}							,			task.column_mapping   )

	def 					__UpperCAmelCase(       self   ):
			__A							:   List[str]	  =				Features({"text": Value("string"   )}   )
			# Labels are cast to tuple during `TextClassification.__post_init__`, so we do the same here
			__A							:   int	  =				Features({"labels": ClassLabel}   )
			__A							:   Tuple	  =				{"text_column": "input_text", "label_column": "input_labels"}
			__A							:   str	  =				TextClassification.from_dict(__UpperCAmelCase   )
			self.assertEqual("text-classification"							,			task.task   )
			self.assertEqual(__UpperCAmelCase							,			task.input_schema   )
			self.assertEqual(__UpperCAmelCase							,			task.label_schema   )







	def 					__UpperCAmelCase(       self   ):
			__A							:   Tuple	  =				TextClassification(text_column="input_text"							,			label_column="input_label"   )
			self.assertEqual(task.label_schema["labels"]							,			__UpperCAmelCase   )
			__A							:   Optional[Any]	  =				task.align_with_features(Features({"input_label": ClassLabel(names=self.labels   )}   )   )
			self.assertEqual(task.label_schema["labels"]							,			ClassLabel(names=self.labels   )   )


class _a       (	lowerCAmelCase__ ):

	'''simple docstring'''



	def 					__UpperCAmelCase(       self   ):
			__A							:   int	  =				QuestionAnsweringExtractive(
			    context_column="input_context"							,			question_column="input_question"							,			answers_column="input_answers"   )
			self.assertDictEqual(
			    {"input_context": "context", "input_question": "question", "input_answers": "answers"}							,			task.column_mapping   )







	def 					__UpperCAmelCase(       self   ):
			__A							:   Optional[Any]	  =				Features({"question": Value("string"   ), "context": Value("string"   )}   )
			__A							:   str	  =				Features(
			    {
			        "answers": Sequence(
			            {
			                "text": Value("string"   ),
			                "answer_start": Value("int32"   ),
			            }   )
			    }   )
			__A							:   str	  =				{
			    "context_column": "input_input_context",
			    "question_column": "input_question",
			    "answers_column": "input_answers",
			}
			__A							:   Union[str, Any]	  =				QuestionAnsweringExtractive.from_dict(__UpperCAmelCase   )
			self.assertEqual("question-answering-extractive"							,			task.task   )
			self.assertEqual(__UpperCAmelCase							,			task.input_schema   )
			self.assertEqual(__UpperCAmelCase							,			task.label_schema   )


class _a       (	lowerCAmelCase__ ):

	'''simple docstring'''



	def 					__UpperCAmelCase(       self   ):
			__A							:   int	  =				Summarization(text_column="input_text"							,			summary_column="input_summary"   )
			self.assertDictEqual({"input_text": "text", "input_summary": "summary"}							,			task.column_mapping   )







	def 					__UpperCAmelCase(       self   ):
			__A							:   Dict	  =				Features({"text": Value("string"   )}   )
			__A							:   Any	  =				Features({"summary": Value("string"   )}   )
			__A							:   Optional[Any]	  =				{"text_column": "input_text", "summary_column": "input_summary"}
			__A							:   str	  =				Summarization.from_dict(__UpperCAmelCase   )
			self.assertEqual("summarization"							,			task.task   )
			self.assertEqual(__UpperCAmelCase							,			task.input_schema   )
			self.assertEqual(__UpperCAmelCase							,			task.label_schema   )


class _a       (	lowerCAmelCase__ ):

	'''simple docstring'''



	def 					__UpperCAmelCase(       self   ):
			__A							:   Union[str, Any]	  =				AutomaticSpeechRecognition(audio_column="input_audio"							,			transcription_column="input_transcription"   )
			self.assertDictEqual({"input_audio": "audio", "input_transcription": "transcription"}							,			task.column_mapping   )







	def 					__UpperCAmelCase(       self   ):
			__A							:   Optional[Any]	  =				Features({"audio": Audio()}   )
			__A							:   str	  =				Features({"transcription": Value("string"   )}   )
			__A							:   Union[str, Any]	  =				{
			    "audio_column": "input_audio",
			    "transcription_column": "input_transcription",
			}
			__A							:   Optional[Any]	  =				AutomaticSpeechRecognition.from_dict(__UpperCAmelCase   )
			self.assertEqual("automatic-speech-recognition"							,			task.task   )
			self.assertEqual(__UpperCAmelCase							,			task.input_schema   )
			self.assertEqual(__UpperCAmelCase							,			task.label_schema   )


class _a       (	lowerCAmelCase__ ):

	'''simple docstring'''



	def 					__UpperCAmelCase(       self   ):
			__A							:   Tuple	  =				sorted(["pos", "neg"]   )

	def 					__UpperCAmelCase(       self   ):
			__A							:   Optional[int]	  =				AudioClassification(audio_column="input_audio"							,			label_column="input_label"   )
			self.assertDictEqual({"input_audio": "audio", "input_label": "labels"}							,			task.column_mapping   )

	def 					__UpperCAmelCase(       self   ):
			__A							:   Any	  =				Features({"audio": Audio()}   )
			__A							:   Union[str, Any]	  =				Features({"labels": ClassLabel}   )
			__A							:   int	  =				{
			    "audio_column": "input_image",
			    "label_column": "input_label",
			}
			__A							:   Any	  =				AudioClassification.from_dict(__UpperCAmelCase   )
			self.assertEqual("audio-classification"							,			task.task   )
			self.assertEqual(__UpperCAmelCase							,			task.input_schema   )
			self.assertEqual(__UpperCAmelCase							,			task.label_schema   )







	def 					__UpperCAmelCase(       self   ):
			__A							:   Union[str, Any]	  =				AudioClassification(audio_column="input_audio"							,			label_column="input_label"   )
			self.assertEqual(task.label_schema["labels"]							,			__UpperCAmelCase   )
			__A							:   int	  =				task.align_with_features(Features({"input_label": ClassLabel(names=self.labels   )}   )   )
			self.assertEqual(task.label_schema["labels"]							,			ClassLabel(names=self.labels   )   )


class _a       (	lowerCAmelCase__ ):

	'''simple docstring'''



	def 					__UpperCAmelCase(       self   ):
			__A							:   Optional[int]	  =				sorted(["pos", "neg"]   )

	def 					__UpperCAmelCase(       self   ):
			__A							:   str	  =				ImageClassification(image_column="input_image"							,			label_column="input_label"   )
			self.assertDictEqual({"input_image": "image", "input_label": "labels"}							,			task.column_mapping   )

	def 					__UpperCAmelCase(       self   ):
			__A							:   Optional[Any]	  =				Features({"image": Image()}   )
			__A							:   Any	  =				Features({"labels": ClassLabel}   )
			__A							:   int	  =				{
			    "image_column": "input_image",
			    "label_column": "input_label",
			}
			__A							:   Optional[Any]	  =				ImageClassification.from_dict(__UpperCAmelCase   )
			self.assertEqual("image-classification"							,			task.task   )
			self.assertEqual(__UpperCAmelCase							,			task.input_schema   )
			self.assertEqual(__UpperCAmelCase							,			task.label_schema   )







	def 					__UpperCAmelCase(       self   ):
			__A							:   Dict	  =				ImageClassification(image_column="input_image"							,			label_column="input_label"   )
			self.assertEqual(task.label_schema["labels"]							,			__UpperCAmelCase   )
			__A							:   Optional[Any]	  =				task.align_with_features(Features({"input_label": ClassLabel(names=self.labels   )}   )   )
			self.assertEqual(task.label_schema["labels"]							,			ClassLabel(names=self.labels   )   )


class _a       (	lowerCAmelCase__ ):

	'''simple docstring'''



	def 					__UpperCAmelCase(       self   ):
			__A							:   Any	  =				DatasetInfo(task_templates=QuestionAnsweringExtractive()   )
			__A							:   Optional[Any]	  =				Dataset.from_dict({k: [v] for k, v in SAMPLE_QUESTION_ANSWERING_EXTRACTIVE.items()}							,			info=__UpperCAmelCase   )
			assert isinstance(dataset.info.task_templates							,			__UpperCAmelCase   )
			assert len(dataset.info.task_templates   ) == 1

			def keep_task(__UpperCAmelCase   ):
					return x

			def dont_keep_task(__UpperCAmelCase   ):
					__A							:   Tuple	  =				deepcopy(__UpperCAmelCase   )
					__A							:   Optional[Any]	  =				0
					return out

			__A							:   Optional[int]	  =				dataset.map(__UpperCAmelCase   )
			assert mapped_dataset.info.task_templates == dataset.info.task_templates
			# reload from cache
			__A							:   Tuple	  =				dataset.map(__UpperCAmelCase   )
			assert mapped_dataset.info.task_templates == dataset.info.task_templates

			__A							:   int	  =				dataset.map(__UpperCAmelCase   )
			assert mapped_dataset.info.task_templates == []
			# reload from cache
			__A							:   str	  =				dataset.map(__UpperCAmelCase   )
			assert mapped_dataset.info.task_templates == []







	def 					__UpperCAmelCase(       self   ):
			__A							:   List[str]	  =				Features({"text": Value("string"   ), "label": ClassLabel(names=("pos", "neg")   )}   )
			__A							:   Tuple	  =				TextClassification(text_column="text"							,			label_column="label"   )
			__A							:   Dict	  =				DatasetInfo(features=__UpperCAmelCase							,			task_templates=__UpperCAmelCase   )
			__A							:   Union[str, Any]	  =				Dataset.from_dict({"text": ["A sentence."], "label": ["pos"]}							,			info=__UpperCAmelCase   )

			def process(__UpperCAmelCase   ):
					return example

			__A							:   Dict	  =				dataset.remove_columns("label"   )
			__A							:   Optional[int]	  =				modified_dataset.map(__UpperCAmelCase   )
			assert mapped_dataset.info.task_templates == []






import os
import pickle
import unittest
from collections import UserDict, namedtuple

import torch

from accelerate.test_utils.testing import require_cuda, require_torch_min_version
from accelerate.test_utils.training import RegressionModel
from accelerate.utils import (
    convert_outputs_to_fpaa,
    extract_model_from_parallel,
    find_device,
    listify,
    patch_environment,
    recursively_apply,
    send_to_device,
)


UpperCamelCase      			=     namedtuple('ExampleNamedTuple', 'a b c')


class _a       (	unittest.TestCase ):

	'''simple docstring'''



	def 					__UpperCAmelCase(       self   ):
			__A							:   List[str]	  =				torch.randn(5							,			2   )
			__A							:   Any	  =				torch.device("cuda"   ) if torch.cuda.is_available() else torch.device("cpu"   )

			__A							:   Union[str, Any]	  =				send_to_device(__UpperCAmelCase							,			__UpperCAmelCase   )
			self.assertTrue(torch.equal(resulta.cpu()							,			__UpperCAmelCase   )   )

			__A							:   Dict	  =				send_to_device((tensor, [tensor, tensor], 1)							,			__UpperCAmelCase   )
			self.assertIsInstance(__UpperCAmelCase							,			__UpperCAmelCase   )
			self.assertTrue(torch.equal(resulta[0].cpu()							,			__UpperCAmelCase   )   )
			self.assertIsInstance(resulta[1]							,			__UpperCAmelCase   )
			self.assertTrue(torch.equal(resulta[1][0].cpu()							,			__UpperCAmelCase   )   )
			self.assertTrue(torch.equal(resulta[1][1].cpu()							,			__UpperCAmelCase   )   )
			self.assertEqual(resulta[2]							,			1   )

			__A							:   Optional[Any]	  =				send_to_device({"a": tensor, "b": [tensor, tensor], "c": 1}							,			__UpperCAmelCase   )
			self.assertIsInstance(__UpperCAmelCase							,			__UpperCAmelCase   )
			self.assertTrue(torch.equal(resulta["a"].cpu()							,			__UpperCAmelCase   )   )
			self.assertIsInstance(resulta["b"]							,			__UpperCAmelCase   )
			self.assertTrue(torch.equal(resulta["b"][0].cpu()							,			__UpperCAmelCase   )   )
			self.assertTrue(torch.equal(resulta["b"][1].cpu()							,			__UpperCAmelCase   )   )
			self.assertEqual(resulta["c"]							,			1   )

			__A							:   Any	  =				send_to_device(ExampleNamedTuple(a=__UpperCAmelCase							,			b=[tensor, tensor]							,			c=1   )							,			__UpperCAmelCase   )
			self.assertIsInstance(__UpperCAmelCase							,			__UpperCAmelCase   )
			self.assertTrue(torch.equal(resulta.a.cpu()							,			__UpperCAmelCase   )   )
			self.assertIsInstance(resulta.b							,			__UpperCAmelCase   )
			self.assertTrue(torch.equal(resulta.b[0].cpu()							,			__UpperCAmelCase   )   )
			self.assertTrue(torch.equal(resulta.b[1].cpu()							,			__UpperCAmelCase   )   )
			self.assertEqual(resulta.c							,			1   )

			__A							:   List[Any]	  =				send_to_device(UserDict({"a": tensor, "b": [tensor, tensor], "c": 1}   )							,			__UpperCAmelCase   )
			self.assertIsInstance(__UpperCAmelCase							,			__UpperCAmelCase   )
			self.assertTrue(torch.equal(resulta["a"].cpu()							,			__UpperCAmelCase   )   )
			self.assertIsInstance(resulta["b"]							,			__UpperCAmelCase   )
			self.assertTrue(torch.equal(resulta["b"][0].cpu()							,			__UpperCAmelCase   )   )
			self.assertTrue(torch.equal(resulta["b"][1].cpu()							,			__UpperCAmelCase   )   )
			self.assertEqual(resulta["c"]							,			1   )

	def 					__UpperCAmelCase(       self   ):
			with self.assertRaises(__UpperCAmelCase   ) as cm:
					__A							:   List[Any]	  =				recursively_apply(torch.tensor							,			(torch.tensor(1   ), 1)							,			error_on_other_type=__UpperCAmelCase   )
			self.assertEqual(
			    str(cm.exception   )							,			"Unsupported types (<class 'int'>) passed to `tensor`. Only nested list/tuple/dicts of objects that are valid for `is_torch_tensor` should be passed."							,			)

	def 					__UpperCAmelCase(       self   ):
			__A							:   List[Any]	  =				torch.tensor([1, 2, 3, 4, 5]   )
			self.assertEqual(listify(__UpperCAmelCase   )							,			[1, 2, 3, 4, 5]   )

			__A							:   List[str]	  =				torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]   )
			self.assertEqual(listify(__UpperCAmelCase   )							,			[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]   )

			__A							:   Dict	  =				torch.tensor([[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]]   )
			self.assertEqual(
			    listify(__UpperCAmelCase   )							,			[[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]]   )

	def 					__UpperCAmelCase(       self   ):
			with patch_environment(aa=1							,			BB=2   ):
					self.assertEqual(os.environ.get("AA"   )							,			"1"   )
					self.assertEqual(os.environ.get("BB"   )							,			"2"   )

			self.assertNotIn("AA"							,			os.environ   )
			self.assertNotIn("BB"							,			os.environ   )

	def 					__UpperCAmelCase(       self   ):
			__A							:   str	  =				RegressionModel()
			__A							:   str	  =				model.forward
			__A							:   List[Any]	  =				convert_outputs_to_fpaa(model.forward   )
			__A							:   Optional[int]	  =				extract_model_from_parallel(__UpperCAmelCase							,			keep_fpaa_wrapper=__UpperCAmelCase   )
			__A							:   Any	  =				pickle.dumps(__UpperCAmelCase   )

	@require_cuda
	def 					__UpperCAmelCase(       self   ):
			__A							:   Any	  =				RegressionModel()
			__A							:   str	  =				model.forward
			__A							:   Tuple	  =				torch.cuda.amp.autocast(dtype=torch.floataa   )(model.forward   )
			__A							:   List[Any]	  =				convert_outputs_to_fpaa(model.forward   )
			__A							:   Optional[Any]	  =				extract_model_from_parallel(__UpperCAmelCase							,			keep_fpaa_wrapper=__UpperCAmelCase   )
			__A							:   Any	  =				pickle.dumps(__UpperCAmelCase   )

	@require_cuda
	@require_torch_min_version(version="2.0"   )
	def 					__UpperCAmelCase(       self   ):
			__A							:   Any	  =				RegressionModel()
			__A							:   Optional[int]	  =				model.forward
			__A							:   Union[str, Any]	  =				torch.cuda.amp.autocast(dtype=torch.floataa   )(model.forward   )
			__A							:   int	  =				convert_outputs_to_fpaa(model.forward   )
			__A							:   Optional[Any]	  =				torch.compile(model.forward							,			backend="inductor"   )
			__A							:   Tuple	  =				torch.randn(4							,			10   ).cuda()
			__A							:   Union[str, Any]	  =				model(__UpperCAmelCase   )

	def 					__UpperCAmelCase(       self   ):
			__A							:   Union[str, Any]	  =				RegressionModel()
			# could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
			__A							:   Dict	  =				torch.nn.parallel.DataParallel(__UpperCAmelCase   )
			__A							:   int	  =				extract_model_from_parallel(__UpperCAmelCase   )

			self.assertEqual(__UpperCAmelCase							,			__UpperCAmelCase   )

	@require_torch_min_version(version="2.0"   )
	def 					__UpperCAmelCase(       self   ):
			__A							:   Dict	  =				RegressionModel()
			__A							:   Dict	  =				torch.compile(__UpperCAmelCase   )

			# could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
			__A							:   Dict	  =				torch.nn.parallel.DataParallel(__UpperCAmelCase   )
			__A							:   Tuple	  =				torch.compile(__UpperCAmelCase   )
			__A							:   Any	  =				extract_model_from_parallel(__UpperCAmelCase   )

			self.assertEqual(compiled_model._orig_mod							,			compiled_model_unwrapped._orig_mod   )







	def 					__UpperCAmelCase(       self   ):
			self.assertEqual(find_device([1, "a", torch.tensor([1, 2, 3]   )]   )							,			torch.device("cpu"   )   )
			self.assertEqual(find_device({"a": 1, "b": torch.tensor([1, 2, 3]   )}   )							,			torch.device("cpu"   )   )
			self.assertIsNone(find_device([1, "a"]   )   )





