
import asyncio
import os
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
from copy import deepcopy
from distutils.util import strtobool
from enum import Enum
from importlib.util import find_spec
from pathlib import Path
from unittest.mock import patch

import pyarrow as pa
import pytest
import requests
from packaging import version

from datasets import config


if config.PY_VERSION < version.parse("3.8"):
						import importlib_metadata
else:
						import importlib.metadata as importlib_metadata

def  __snake_case							(	__magic_name__		,    __magic_name__=False						):







				'''simple docstring'''


				try:
								lowercase         =      os.environ[key]
				except KeyError:
								# KEY isn't set, default to `default`.
								lowercase         =      default
				else:
								# KEY is set, convert it to True or False.
								try:
												lowercase         =      strtobool(__magic_name__						)
								except ValueError:
												# More values are supported, but let's keep the message simple.
												raise ValueError(F'''If set, {key} must be yes or no.'''						)
				return _value


_snake_case      :							Any     	=    parse_flag_from_env("RUN_SLOW", default=False)
_snake_case      :							Dict     	=    parse_flag_from_env("RUN_REMOTE", default=False)
_snake_case      :							Any     	=    parse_flag_from_env("RUN_LOCAL", default=True)
_snake_case      :							str     	=    parse_flag_from_env("RUN_PACKAGED", default=True)

# Compression
_snake_case      :							Optional[Any]     	=    pytest.mark.skipif(not config.LZ4_AVAILABLE, reason="test requires lz4")
_snake_case      :							int     	=    pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason="test requires py7zr")
_snake_case      :							Union[str, Any]     	=    pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason="test requires zstandard")

# Audio
_snake_case      :							List[Any]     	=    pytest.mark.skipif(
    # On Windows and OS X, soundfile installs sndfile
    find_spec("soundfile") is None or version.parse(importlib_metadata.version("soundfile")) < version.parse("0.12.0"),
    reason="test requires sndfile>=0.12.1: 'pip install \"soundfile>=0.12.1\"'; ",
)

# Beam
_snake_case      :							Optional[Any]     	=    pytest.mark.skipif(
    not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse("0.3.2"),
    reason="test requires apache-beam and a compatible dill version",
)

# Dill-cloudpickle compatibility
_snake_case      :							Dict     	=    pytest.mark.skipif(
    config.DILL_VERSION <= version.parse("0.3.2"),
    reason="test requires dill>0.3.2 for cloudpickle compatibility",
)

# Windows
_snake_case      :							Any     	=    pytest.mark.skipif(
    sys.platform == "win32",
    reason="test should not be run on Windows",
)

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				try:
								import faiss  # noqa
				except ImportError:
								lowercase         =      unittest.skip("test requires faiss"						)(__magic_name__						)
				return test_case

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				try:
								import regex  # noqa
				except ImportError:
								lowercase         =      unittest.skip("test requires regex"						)(__magic_name__						)
				return test_case

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				try:
								import elasticsearch  # noqa
				except ImportError:
								lowercase         =      unittest.skip("test requires elasticsearch"						)(__magic_name__						)
				return test_case

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				try:
								import sqlalchemy  # noqa
				except ImportError:
								lowercase         =      unittest.skip("test requires sqlalchemy"						)(__magic_name__						)
				return test_case

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				if not config.TORCH_AVAILABLE:
								lowercase         =      unittest.skip("test requires PyTorch"						)(__magic_name__						)
				return test_case

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				if not config.TF_AVAILABLE:
								lowercase         =      unittest.skip("test requires TensorFlow"						)(__magic_name__						)
				return test_case

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				if not config.JAX_AVAILABLE:
								lowercase         =      unittest.skip("test requires JAX"						)(__magic_name__						)
				return test_case

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				if not config.PIL_AVAILABLE:
								lowercase         =      unittest.skip("test requires Pillow"						)(__magic_name__						)
				return test_case

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				try:
								import transformers  # noqa F401
				except ImportError:
								return unittest.skip("test requires transformers"						)(__magic_name__						)
				else:
								return test_case

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				try:
								import tiktoken  # noqa F401
				except ImportError:
								return unittest.skip("test requires tiktoken"						)(__magic_name__						)
				else:
								return test_case

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				try:
								import spacy  # noqa F401
				except ImportError:
								return unittest.skip("test requires spacy"						)(__magic_name__						)
				else:
								return test_case

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				def _require_spacy_model(__magic_name__						):
								try:
												import spacy  # noqa F401

												spacy.load(__magic_name__						)
								except ImportError:
												return unittest.skip("test requires spacy"						)(__magic_name__						)
								except OSError:
												return unittest.skip("test requires spacy model '{}'".format(__magic_name__						)						)(__magic_name__						)
								else:
												return test_case

				return _require_spacy_model

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				try:
								import pyspark  # noqa F401
				except ImportError:
								return unittest.skip("test requires pyspark"						)(__magic_name__						)
				else:
								return test_case

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				try:
								import joblibspark  # noqa F401
				except ImportError:
								return unittest.skip("test requires joblibspark"						)(__magic_name__						)
				else:
								return test_case

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				if not _run_slow_tests or _run_slow_tests == 0:
								lowercase         =      unittest.skip("test is slow"						)(__magic_name__						)
				return test_case

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				if not _run_local_tests or _run_local_tests == 0:
								lowercase         =      unittest.skip("test is local"						)(__magic_name__						)
				return test_case

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				if not _run_packaged_tests or _run_packaged_tests == 0:
								lowercase         =      unittest.skip("test is packaged"						)(__magic_name__						)
				return test_case

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				if not _run_remote_tests or _run_remote_tests == 0:
								lowercase         =      unittest.skip("test requires remote"						)(__magic_name__						)
				return test_case

def  __snake_case							(	*__magic_name__						):







				'''simple docstring'''


				def decorate(cls						):
								for name, fn in cls.__dict__.items():
												if callable(__magic_name__						) and name.startswith("test"						):
																for decorator in decorators:
																				lowercase         =      decorator(__magic_name__						)
																setattr(cls		,    __magic_name__		,    __magic_name__						)
								return cls

				return decorate





class   UpperCamelCase_      (      __a		):







						'''simple docstring'''



						pass





class   UpperCamelCase_      (      __a		):







						'''simple docstring'''



						UpperCamelCase      :  int				   =					0
						UpperCamelCase      :  str				   =					1
						UpperCamelCase      :  Optional[Any]				   =					2




@contextmanager
def  __snake_case							(	__magic_name__=OfflineSimulationMode.CONNECTION_FAILS		,    __magic_name__=1e-16						):







				'''simple docstring'''


				lowercase         =      requests.Session().request

				def timeout_request(__magic_name__		,    __magic_name__		,    __magic_name__		,    **__magic_name__						):
								# Change the url to an invalid url so that the connection hangs
								lowercase         =      "https://10.255.255.1"
								if kwargs.get("timeout"						) is None:
												raise RequestWouldHangIndefinitelyError(
												    F'''Tried a call to {url} in offline mode with no timeout set. Please set a timeout.'''						)
								lowercase         =      timeout
								try:
												return online_request(__magic_name__		,    __magic_name__		,    **__magic_name__						)
								except Exception as e:
												# The following changes in the error are just here to make the offline timeout error prettier
												lowercase         =      url
												lowercase         =      e.args[0]
												lowercase         =      (max_retry_error.args[0].replace("10.255.255.1"		,    F'''OfflineMock[{url}]'''						),)
												lowercase         =      (max_retry_error,)
												raise

				def raise_connection_error(__magic_name__		,    __magic_name__		,    **__magic_name__						):
								raise requests.ConnectionError("Offline mode is enabled."		,    request=__magic_name__						)

				if mode is OfflineSimulationMode.CONNECTION_FAILS:
								with patch("requests.Session.send"		,    __magic_name__						):
												yield
				elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
								# inspired from https://stackoverflow.com/a/904609
								with patch("requests.Session.request"		,    __magic_name__						):
												yield
				elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
								with patch("datasets.config.HF_DATASETS_OFFLINE"		,    __magic_name__						):
												yield
				else:
								raise ValueError("Please use a value from the OfflineSimulationMode enum."						)

@contextmanager
def  __snake_case							(	*__magic_name__		,    **__magic_name__						):







				'''simple docstring'''


				lowercase         =      str(Path().resolve()						)
				with tempfile.TemporaryDirectory(*__magic_name__		,    **__magic_name__						) as tmp_dir:
								try:
												os.chdir(__magic_name__						)
												yield
								finally:
												os.chdir(__magic_name__						)

@contextmanager
def  __snake_case							(	):







				'''simple docstring'''


				import gc

				gc.collect()
				lowercase         =      pa.total_allocated_bytes()
				yield
				assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."

@contextmanager
def  __snake_case							(	):







				'''simple docstring'''


				import gc

				gc.collect()
				lowercase         =      pa.total_allocated_bytes()
				yield
				assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."

def  __snake_case							(	__magic_name__		,    __magic_name__						):







				'''simple docstring'''


				return deepcopy(__magic_name__						).integers(0		,    100		,    10						).tolist() == deepcopy(__magic_name__						).integers(0		,    100		,    10						).tolist()

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				import decorator
				from requests.exceptions import HTTPError

				def _wrapper(__magic_name__		,    *__magic_name__		,    **__magic_name__						):
								try:
												return func(*__magic_name__		,    **__magic_name__						)
								except HTTPError as err:
												if str(__magic_name__						).startswith("500"						) or str(__magic_name__						).startswith("502"						):
																pytest.xfail(str(__magic_name__						)						)
												raise err

				return decorator.decorator(_wrapper		,    __magic_name__						)





class   UpperCamelCase_      :







						'''simple docstring'''



						def __init__(			self							:int		,    lowerCAmelCase__							:int		,    lowerCAmelCase__							:Optional[int]		,    lowerCAmelCase__							:List[str]     )  ->int:
										lowercase         =      returncode
										lowercase         =      stdout
										lowercase         =      stderr




async def  __snake_case							(	__magic_name__		,    __magic_name__						):







				'''simple docstring'''


				while True:
								lowercase         =      await stream.readline()
								if line:
												callback(__magic_name__						)
								else:
												break

async def  __snake_case							(	__magic_name__		,    __magic_name__=None		,    __magic_name__=None		,    __magic_name__=None		,    __magic_name__=False		,    __magic_name__=False						):







				'''simple docstring'''


				if echo:
								print("\nRunning: "		,    " ".join(__magic_name__						)						)

				lowercase         =      await asyncio.create_subprocess_exec(
				    cmd[0]		,    *cmd[1:]		,    stdin=__magic_name__		,    stdout=asyncio.subprocess.PIPE		,    stderr=asyncio.subprocess.PIPE		,    env=__magic_name__		,    )

				# note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
				# https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
				#
				# If it starts hanging, will need to switch to the following code. The problem is that no data
				# will be seen until it's done and if it hangs for example there will be no debug info.
				# out, err = await p.communicate()
				# return _RunOutput(p.returncode, out, err)

				lowercase         =      []
				lowercase         =      []

				def tee(__magic_name__		,    __magic_name__		,    __magic_name__		,    __magic_name__=""						):
								lowercase         =      line.decode("utf-8"						).rstrip()
								sink.append(__magic_name__						)
								if not quiet:
												print(__magic_name__		,    __magic_name__		,    file=__magic_name__						)

    # XXX: the timeout doesn't seem to make any difference here
				await asyncio.wait(
				    [
				        _read_stream(p.stdout		,    lambda __magic_name__						: tee(__magic_name__		,    __magic_name__		,    sys.stdout		,    label="stdout:"						)						),
				        _read_stream(p.stderr		,    lambda __magic_name__						: tee(__magic_name__		,    __magic_name__		,    sys.stderr		,    label="stderr:"						)						),
				    ]		,    timeout=__magic_name__		,    )
				return _RunOutput(await p.wait()		,    __magic_name__		,    __magic_name__						)

def  __snake_case							(	__magic_name__		,    __magic_name__=None		,    __magic_name__=None		,    __magic_name__=180		,    __magic_name__=False		,    __magic_name__=True						):







				'''simple docstring'''


				lowercase         =      asyncio.get_event_loop()
				lowercase         =      loop.run_until_complete(
				    _stream_subprocess(__magic_name__		,    env=__magic_name__		,    stdin=__magic_name__		,    timeout=__magic_name__		,    quiet=__magic_name__		,    echo=__magic_name__						)						)

				lowercase         =      " ".join(__magic_name__						)
				if result.returncode > 0:
								lowercase         =      "\n".join(result.stderr						)
								raise RuntimeError(
								    F'''\'{cmd_str}\' failed with returncode {result.returncode}\n\n'''
								    F'''The combined stderr from workers follows:\n{stderr}'''						)

				# check that the subprocess actually did run and produced some output, should the test rely on
				# the remote side to do the testing
				if not result.stdout and not result.stderr:
								raise RuntimeError(F'''\'{cmd_str}\' produced no output.'''						)

				return result

def  __snake_case							(	):







				'''simple docstring'''


				lowercase         =      os.environ.get("PYTEST_XDIST_WORKER"		,    "gw0"						)
				lowercase         =      re.sub(r"^gw"		,    ""		,    __magic_name__		,    0		,    re.M						)
				return int(__magic_name__						)




def  __snake_case							(	):







				'''simple docstring'''


				lowercase         =      29500
				lowercase         =      pytest_xdist_worker_id()
				return port + uniq_delta


import json
import os
import tempfile
from unittest.mock import patch

import torch
from torch.utils.data import DataLoader, TensorDataset

from accelerate import DistributedType, infer_auto_device_map, init_empty_weights
from accelerate.accelerator import Accelerator
from accelerate.state import GradientState, PartialState
from accelerate.test_utils import require_bnb, require_multi_gpu, slow
from accelerate.test_utils.testing import AccelerateTestCase, require_cuda
from accelerate.utils import patch_environment

def  __snake_case							(	):







				'''simple docstring'''


				lowercase         =      torch.nn.Linear(2		,    4						)
				lowercase         =      torch.optim.AdamW(model.parameters()		,    lr=1.0						)
				lowercase         =      torch.optim.lr_scheduler.OneCycleLR(__magic_name__		,    max_lr=0.0_1		,    steps_per_epoch=2		,    epochs=1						)
				lowercase         =      DataLoader(TensorDataset(torch.tensor([1, 2, 3]						)						)						)
				lowercase         =      DataLoader(TensorDataset(torch.tensor([4, 5, 6]						)						)						)

				return model, optimizer, scheduler, train_dl, valid_dl

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				return (model.weight.abs().sum() + model.bias.abs().sum()).item()

def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				lowercase         =      torch.nn.Linear(*tuple(model.weight.T.shape						)						).state_dict()
				model.load_state_dict(__magic_name__						)





class   UpperCamelCase_      (      __a		):







						'''simple docstring'''



						@require_cuda
						def        SCREAMING_SNAKE_CASE(			self							:Any     )  ->str:
										lowercase         =      Accelerator()
										assert PartialState._shared_state["_cpu"] is False
										assert PartialState._shared_state["device"].type == "cuda"
										with self.assertRaises(lowerCAmelCase__     ):
														lowercase         =      Accelerator(cpu=lowerCAmelCase__     )





						def        SCREAMING_SNAKE_CASE(			self							:Dict     )  ->Dict:
										lowercase         =      Accelerator()
										lowercase         =      GradientState()
										assert state.num_steps == 1
										lowercase         =      4
										assert state.num_steps == 4

										assert state.sync_gradients is True
										lowercase         =      False
										assert state.sync_gradients is False
										GradientState._reset_state()





						def        SCREAMING_SNAKE_CASE(			self							:int     )  ->Tuple:
										lowercase         =      Accelerator()
										lowercase     ,	lowercase     ,	lowercase     ,	lowercase     ,	lowercase         =      create_components()

										(
										    (
										    lowercase
										)     ,	(
										    lowercase
										)     ,	(
										    lowercase
										)     ,	(
										    lowercase
										)     ,	(
										    lowercase
										)     ,	
										)         =      accelerator.prepare(lowerCAmelCase__		,    lowerCAmelCase__		,    lowerCAmelCase__		,    lowerCAmelCase__		,    lowerCAmelCase__     )

										self.assertTrue(prepared_model in accelerator._models     )
										self.assertTrue(prepared_optimizer in accelerator._optimizers     )
										self.assertTrue(prepared_scheduler in accelerator._schedulers     )
										self.assertTrue(prepared_train_dl in accelerator._dataloaders     )
										self.assertTrue(prepared_valid_dl in accelerator._dataloaders     )





						def        SCREAMING_SNAKE_CASE(			self							:List[Any]     )  ->Tuple:
										lowercase         =      Accelerator()
										lowercase     ,	lowercase     ,	lowercase     ,	lowercase     ,	lowercase         =      create_components()
										accelerator.prepare(lowerCAmelCase__		,    lowerCAmelCase__		,    lowerCAmelCase__		,    lowerCAmelCase__		,    lowerCAmelCase__     )
										accelerator.free_memory()

										self.assertTrue(len(accelerator._models     ) == 0     )
										self.assertTrue(len(accelerator._optimizers     ) == 0     )
										self.assertTrue(len(accelerator._schedulers     ) == 0     )
										self.assertTrue(len(accelerator._dataloaders     ) == 0     )





						def        SCREAMING_SNAKE_CASE(			self							:List[str]     )  ->Optional[int]:
										PartialState._reset_state()

										# Mock torch.cuda.set_device to avoid an exception as the device doesn't exist
										def noop(*lowerCAmelCase__							:int		,    **lowerCAmelCase__							:Optional[Any]     ):
														pass

										with patch("torch.cuda.set_device"		,    lowerCAmelCase__     ), patch_environment(ACCELERATE_TORCH_DEVICE="cuda:64"     ):
														lowercase         =      Accelerator()
														self.assertEqual(str(accelerator.state.device     )		,    "cuda:64"     )





						def        SCREAMING_SNAKE_CASE(			self							:Union[str, Any]     )  ->Union[str, Any]:
										lowercase         =      Accelerator()
										lowercase     ,	lowercase     ,	lowercase     ,	lowercase     ,	lowercase         =      create_components()
										accelerator.prepare(lowerCAmelCase__		,    lowerCAmelCase__		,    lowerCAmelCase__		,    lowerCAmelCase__		,    lowerCAmelCase__     )

										lowercase         =      get_signature(lowerCAmelCase__     )

										with tempfile.TemporaryDirectory() as tmpdirname:
														accelerator.save_state(lowerCAmelCase__     )

														# make sure random weights don't match
														load_random_weights(lowerCAmelCase__     )
														self.assertTrue(abs(model_signature - get_signature(lowerCAmelCase__     )     ) > 1E-3     )

														# make sure loaded weights match
														accelerator.load_state(lowerCAmelCase__     )
														self.assertTrue(abs(model_signature - get_signature(lowerCAmelCase__     )     ) < 1E-3     )





						def        SCREAMING_SNAKE_CASE(			self							:List[str]     )  ->int:
										lowercase         =      Accelerator()
										lowercase     ,	lowercase     ,	lowercase     ,	lowercase     ,	lowercase         =      create_components()
										accelerator.prepare(lowerCAmelCase__		,    lowerCAmelCase__		,    lowerCAmelCase__		,    lowerCAmelCase__		,    lowerCAmelCase__     )

										lowercase         =      get_signature(lowerCAmelCase__     )

										# saving hook
										def save_config(lowerCAmelCase__							:Optional[Any]		,    lowerCAmelCase__							:Optional[int]		,    lowerCAmelCase__							:Optional[Any]     ):
														lowercase         =      {"class_name": models[0].__class__.__name__}

														with open(os.path.join(lowerCAmelCase__		,    "data.json"     )		,    "w"     ) as f:
																		json.dump(lowerCAmelCase__		,    lowerCAmelCase__     )

        # loading hook
										def load_config(lowerCAmelCase__							:Dict		,    lowerCAmelCase__							:List[str]     ):
														with open(os.path.join(lowerCAmelCase__		,    "data.json"     )		,    "r"     ) as f:
																		lowercase         =      json.load(lowerCAmelCase__     )

														lowercase         =      config["class_name"]

										lowercase         =      accelerator.register_save_state_pre_hook(lowerCAmelCase__     )
										lowercase         =      accelerator.register_load_state_pre_hook(lowerCAmelCase__     )

										with tempfile.TemporaryDirectory() as tmpdirname:
														accelerator.save_state(lowerCAmelCase__     )

														# make sure random weights don't match with hooks
														load_random_weights(lowerCAmelCase__     )
														self.assertTrue(abs(model_signature - get_signature(lowerCAmelCase__     )     ) > 1E-3     )

														# random class name to verify correct one is loaded
														lowercase         =      "random"

														# make sure loaded weights match with hooks
														accelerator.load_state(lowerCAmelCase__     )
														self.assertTrue(abs(model_signature - get_signature(lowerCAmelCase__     )     ) < 1E-3     )

														# mode.class_name is loaded from config
														self.assertTrue(model.class_name == model.__class__.__name__     )

										# remove hooks
										save_hook.remove()
										load_hook.remove()

										with tempfile.TemporaryDirectory() as tmpdirname:
														accelerator.save_state(lowerCAmelCase__     )

														# make sure random weights don't match with hooks removed
														load_random_weights(lowerCAmelCase__     )
														self.assertTrue(abs(model_signature - get_signature(lowerCAmelCase__     )     ) > 1E-3     )

														# random class name to verify correct one is loaded
														lowercase         =      "random"

														# make sure loaded weights match with hooks removed
														accelerator.load_state(lowerCAmelCase__     )
														self.assertTrue(abs(model_signature - get_signature(lowerCAmelCase__     )     ) < 1E-3     )

														# mode.class_name is NOT loaded from config
														self.assertTrue(model.class_name != model.__class__.__name__     )





						def        SCREAMING_SNAKE_CASE(			self							:Optional[int]     )  ->List[Any]:
										lowercase         =      Accelerator()
										lowercase     ,	lowercase     ,	lowercase     ,	lowercase     ,	lowercase         =      create_components()
										lowercase         =      None

										# This should work
										lowercase     ,	lowercase     ,	lowercase     ,	lowercase     ,	lowercase     ,	lowercase         =      accelerator.prepare(
										    lowerCAmelCase__		,    lowerCAmelCase__		,    lowerCAmelCase__		,    lowerCAmelCase__		,    lowerCAmelCase__		,    lowerCAmelCase__     )
										self.assertTrue(dummy_obj is None     )





						def        SCREAMING_SNAKE_CASE(			self							:Tuple     )  ->Optional[int]:
										lowercase         =      Accelerator()
										lowercase     ,	lowercase     ,	lowercase     ,	lowercase     ,	lowercase         =      create_components()
										lowercase         =      [1, 2, 3]

										# This should work
										lowercase     ,	lowercase     ,	lowercase     ,	lowercase     ,	lowercase     ,	lowercase         =      accelerator.prepare(
										    lowerCAmelCase__		,    lowerCAmelCase__		,    lowerCAmelCase__		,    lowerCAmelCase__		,    lowerCAmelCase__		,    lowerCAmelCase__     )
										self.assertEqual(
										    getattr(lowerCAmelCase__		,    "_is_accelerate_prepared"		,    lowerCAmelCase__     )		,    lowerCAmelCase__		,    "Dummy object should have `_is_accelerate_prepared` set to `True`"		,    )
										self.assertEqual(
										    getattr(lowerCAmelCase__		,    "_is_accelerate_prepared"		,    lowerCAmelCase__     )		,    lowerCAmelCase__		,    "Model is missing `_is_accelerator_prepared` or is set to `False`"		,    )
										self.assertEqual(
										    getattr(lowerCAmelCase__		,    "_is_accelerate_prepared"		,    lowerCAmelCase__     )		,    lowerCAmelCase__		,    "Optimizer is missing `_is_accelerator_prepared` or is set to `False`"		,    )
										self.assertEqual(
										    getattr(lowerCAmelCase__		,    "_is_accelerate_prepared"		,    lowerCAmelCase__     )		,    lowerCAmelCase__		,    "Scheduler is missing `_is_accelerator_prepared` or is set to `False`"		,    )
										self.assertEqual(
										    getattr(lowerCAmelCase__		,    "_is_accelerate_prepared"		,    lowerCAmelCase__     )		,    lowerCAmelCase__		,    "Train Dataloader is missing `_is_accelerator_prepared` or is set to `False`"		,    )
										self.assertEqual(
										    getattr(lowerCAmelCase__		,    "_is_accelerate_prepared"		,    lowerCAmelCase__     )		,    lowerCAmelCase__		,    "Valid Dataloader is missing `_is_accelerator_prepared` or is set to `False`"		,    )





						@slow
						@require_bnb
						def        SCREAMING_SNAKE_CASE(			self							:Union[str, Any]     )  ->Tuple:
										from transformers import AutoModelForCausalLM

										lowercase         =      AutoModelForCausalLM.from_pretrained(
										    "EleutherAI/gpt-neo-125m"		,    load_in_abit=lowerCAmelCase__		,    device_map={"": 0}		,    )
										lowercase         =      Accelerator()

										# This should work
										lowercase         =      accelerator.prepare(lowerCAmelCase__     )





						@slow
						@require_bnb
						def        SCREAMING_SNAKE_CASE(			self							:Tuple     )  ->List[str]:
										from transformers import AutoModelForCausalLM

										lowercase         =      Accelerator()

										with init_empty_weights():
														lowercase         =      AutoModelForCausalLM.from_pretrained(
														    "EleutherAI/gpt-neo-125m"		,    )
														model.tie_weights()
														lowercase         =      infer_auto_device_map(lowerCAmelCase__     )
														lowercase         =      "cpu"

										lowercase         =      AutoModelForCausalLM.from_pretrained(
										    "EleutherAI/gpt-neo-125m"		,    device_map=lowerCAmelCase__		,    load_in_abit=lowerCAmelCase__		,    llm_inta_enable_fpaa_cpu_offload=lowerCAmelCase__     )

										# This should not work and get value error
										with self.assertRaises(lowerCAmelCase__     ):
														lowercase         =      accelerator.prepare(lowerCAmelCase__     )





						@slow
						@require_bnb
						@require_multi_gpu
						def        SCREAMING_SNAKE_CASE(			self							:Tuple     )  ->int:
										from transformers import AutoModelForCausalLM

										lowercase         =      {"distributed_type": DistributedType.MULTI_GPU}

										with init_empty_weights():
														lowercase         =      AutoModelForCausalLM.from_pretrained(
														    "EleutherAI/gpt-neo-125m"		,    )
														model.tie_weights()
														lowercase         =      infer_auto_device_map(lowerCAmelCase__     )
														lowercase         =      1

										lowercase         =      AutoModelForCausalLM.from_pretrained(
										    "EleutherAI/gpt-neo-125m"		,    load_in_abit=lowerCAmelCase__		,    device_map=lowerCAmelCase__		,    )
										lowercase         =      Accelerator()

										# This should not work and get value error
										with self.assertRaises(lowerCAmelCase__     ):
														lowercase         =      accelerator.prepare(lowerCAmelCase__     )

										PartialState._reset_state()





						@slow
						@require_bnb
						@require_multi_gpu
						def        SCREAMING_SNAKE_CASE(			self							:List[str]     )  ->Tuple:
										from transformers import AutoModelForCausalLM

										with init_empty_weights():
														lowercase         =      AutoModelForCausalLM.from_pretrained(
														    "EleutherAI/gpt-neo-125m"		,    )
														lowercase         =      infer_auto_device_map(lowerCAmelCase__     )
														lowercase         =      1

										lowercase         =      AutoModelForCausalLM.from_pretrained(
										    "EleutherAI/gpt-neo-125m"		,    load_in_abit=lowerCAmelCase__		,    device_map=lowerCAmelCase__		,    )
										lowercase         =      Accelerator()

										# This should work
										lowercase         =      accelerator.prepare(lowerCAmelCase__     )





						@require_cuda
						def        SCREAMING_SNAKE_CASE(			self							:Optional[int]     )  ->Any:
										lowercase         =      torch.nn.Linear(10		,    10     )
										lowercase         =      torch.optim.SGD(model.parameters()		,    lr=0.01     )
										lowercase         =      Accelerator(cpu=lowerCAmelCase__     )
										lowercase         =      accelerator.prepare(lowerCAmelCase__     )
