



'''simple docstring'''

import inspect
import logging
import os
import random
import shutil
import tempfile
import unittest

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

from accelerate import Accelerator
from accelerate.test_utils import execute_subprocess_async, require_cuda
from accelerate.utils import ProjectConfiguration, set_seed


_A				:    Dict     						=logging.getLogger(__name__)







def 						__UpperCamelCase				(							_lowercase=2,				_lowercase=3,				_lowercase=16,				_lowercase = 10,				_lowercase = 2					) ->			Tuple:

	def get_dataset(_lowercase					):
		_lowercase					:       int       =		torch.randn(batch_size * n_batches,				1					)
		return TensorDataset(_lowercase,				a * x + b + 0.1 * torch.randn(batch_size * n_batches,				1					)					)

	_lowercase					:       Dict       =		get_dataset(_lowercase					)
	_lowercase					:       Dict       =		get_dataset(_lowercase					)
	_lowercase					:       str       =		DataLoader(_lowercase,				shuffle=_lowercase,				batch_size=_lowercase,				num_workers=4					)
	_lowercase					:       Any       =		DataLoader(_lowercase,				shuffle=_lowercase,				batch_size=_lowercase,				num_workers=4					)
	return (train_dataloader, valid_dataloader)







def 						__UpperCamelCase				(							_lowercase,				_lowercase,				_lowercase,				_lowercase,				_lowercase,				_lowercase=None					) ->			Dict:
	_lowercase					:       Any       =		[]
	for epoch in range(_lowercase					):
		# Train quickly
		model.train()
		for batch in dataloader:
			_lowercase					:       List[Any]       =		batch
			_lowercase					:       Dict       =		model(_lowercase					)
			_lowercase					:       Any       =		torch.nn.functional.mse_loss(_lowercase,				_lowercase					)
			accelerator.backward(_lowercase					)
			optimizer.step()
			optimizer.zero_grad()
		rands.append(random.random()					)  # Introduce some randomness
		if scheduler is not None:
			scheduler.step()
	return rands



class 		lowerCamelCase__		(						nn.Module     ):




					'''simple docstring'''



					def __init__(  self				:	Optional[int]					)  ->       List[str]:



						'''simple docstring'''





						super().__init__()
						_lowercase					:       Any       =		nn.Parameter(torch.randn(1					)					)
						_lowercase					:       Optional[Any]       =		nn.Parameter(torch.randn(1					)					)




					def 						__UpperCAmelCase     (  self				:	str     ,  UpperCamelCase_				:	List[Any]					)  ->       Optional[int]:



						'''simple docstring'''





						return x * self.a + self.b






class 		lowerCamelCase__		(						unittest.TestCase     ):




					'''simple docstring'''



					def 						__UpperCAmelCase     (  self				:	str					)  ->       int:



						'''simple docstring'''





						with tempfile.TemporaryDirectory() as tmpdir:
							set_seed(42					)
							_lowercase					:       Union[str, Any]       =		DummyModel()
							_lowercase					:       List[Any]       =		torch.optim.Adam(params=model.parameters()     ,  lr=1E-3					)
							_lowercase					:       Union[str, Any]       =		dummy_dataloaders()
							_lowercase					:       List[Any]       =		ProjectConfiguration(total_limit=1     ,  project_dir=UpperCamelCase_     ,  automatic_checkpoint_naming=UpperCamelCase_					)
							# Train baseline
							_lowercase					:       List[Any]       =		Accelerator(project_config=UpperCamelCase_					)
							_lowercase					:       Union[str, Any]       =		accelerator.prepare(
							    UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_					)
							# Save initial
							accelerator.save_state()

							# Save second state
							accelerator.save_state()
							self.assertEqual(len(os.listdir(accelerator.project_dir					)					)     ,  1					)




					def 						__UpperCAmelCase     (  self				:	Union[str, Any]					)  ->       Optional[int]:



						'''simple docstring'''





						with tempfile.TemporaryDirectory() as tmpdir:
							set_seed(42					)
							_lowercase					:       Any       =		DummyModel()
							_lowercase					:       Union[str, Any]       =		torch.optim.Adam(params=model.parameters()     ,  lr=1E-3					)
							_lowercase					:       Dict       =		dummy_dataloaders()
							# Train baseline
							_lowercase					:       List[Any]       =		Accelerator()
							_lowercase					:       Dict       =		accelerator.prepare(
							    UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_					)
							# Save initial
							_lowercase					:       Any       =		os.path.join(UpperCamelCase_     ,  'initial'					)
							accelerator.save_state(UpperCamelCase_					)
							(_lowercase)					:       Union[str, Any]       =		model.a.item(), model.b.item()
							_lowercase					:       Optional[Any]       =		optimizer.state_dict()
							_lowercase					:       int       =		train(3     ,  UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_					)
							(_lowercase)					:       str       =		model.a.item(), model.b.item()
							_lowercase					:       Union[str, Any]       =		optimizer.state_dict()

							# Train partially
							set_seed(42					)
							_lowercase					:       int       =		DummyModel()
							_lowercase					:       int       =		torch.optim.Adam(params=model.parameters()     ,  lr=1E-3					)
							_lowercase					:       Any       =		dummy_dataloaders()
							_lowercase					:       List[str]       =		Accelerator()
							_lowercase					:       List[str]       =		accelerator.prepare(
							    UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_					)
							accelerator.load_state(UpperCamelCase_					)
							(_lowercase)					:       List[Any]       =		model.a.item(), model.b.item()
							_lowercase					:       int       =		optimizer.state_dict()
							self.assertEqual(UpperCamelCase_     ,  UpperCamelCase_					)
							self.assertEqual(UpperCamelCase_     ,  UpperCamelCase_					)
							self.assertEqual(UpperCamelCase_     ,  UpperCamelCase_					)

							_lowercase					:       str       =		train(2     ,  UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_					)
							# Save everything
							_lowercase					:       Tuple       =		os.path.join(UpperCamelCase_     ,  'checkpoint'					)
							accelerator.save_state(UpperCamelCase_					)

							# Load everything back in and make sure all states work
							accelerator.load_state(UpperCamelCase_					)
							test_rands += train(1     ,  UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_					)
							(_lowercase)					:       str       =		model.a.item(), model.b.item()
							_lowercase					:       int       =		optimizer.state_dict()
							self.assertEqual(UpperCamelCase_     ,  UpperCamelCase_					)
							self.assertEqual(UpperCamelCase_     ,  UpperCamelCase_					)
							self.assertEqual(UpperCamelCase_     ,  UpperCamelCase_					)
							self.assertEqual(UpperCamelCase_     ,  UpperCamelCase_					)




					def 						__UpperCAmelCase     (  self				:	Optional[Any]					)  ->       Union[str, Any]:



						'''simple docstring'''





						with tempfile.TemporaryDirectory() as tmpdir:
							set_seed(42					)
							_lowercase					:       Optional[Any]       =		DummyModel()
							_lowercase					:       List[str]       =		torch.optim.Adam(params=model.parameters()     ,  lr=1E-3					)
							_lowercase					:       Dict       =		dummy_dataloaders()
							_lowercase					:       Union[str, Any]       =		ProjectConfiguration(automatic_checkpoint_naming=UpperCamelCase_					)

							# Train baseline
							_lowercase					:       Optional[Any]       =		Accelerator(project_dir=UpperCamelCase_     ,  project_config=UpperCamelCase_					)
							_lowercase					:       int       =		accelerator.prepare(
							    UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_					)
							# Save initial
							accelerator.save_state()
							(_lowercase)					:       int       =		model.a.item(), model.b.item()
							_lowercase					:       Dict       =		optimizer.state_dict()
							_lowercase					:       Optional[int]       =		train(3     ,  UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_					)
							(_lowercase)					:       Optional[int]       =		model.a.item(), model.b.item()
							_lowercase					:       List[str]       =		optimizer.state_dict()

							# Train partially
							set_seed(42					)
							_lowercase					:       Tuple       =		DummyModel()
							_lowercase					:       List[Any]       =		torch.optim.Adam(params=model.parameters()     ,  lr=1E-3					)
							_lowercase					:       List[Any]       =		dummy_dataloaders()
							_lowercase					:       Optional[Any]       =		ProjectConfiguration(iteration=1     ,  automatic_checkpoint_naming=UpperCamelCase_					)
							_lowercase					:       Optional[int]       =		Accelerator(project_dir=UpperCamelCase_     ,  project_config=UpperCamelCase_					)
							_lowercase					:       Dict       =		accelerator.prepare(
							    UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_					)
							accelerator.load_state(os.path.join(UpperCamelCase_     ,  'checkpoints'     ,  'checkpoint_0'					)					)
							(_lowercase)					:       str       =		model.a.item(), model.b.item()
							_lowercase					:       Tuple       =		optimizer.state_dict()
							self.assertEqual(UpperCamelCase_     ,  UpperCamelCase_					)
							self.assertEqual(UpperCamelCase_     ,  UpperCamelCase_					)
							self.assertEqual(UpperCamelCase_     ,  UpperCamelCase_					)

							_lowercase					:       List[str]       =		train(2     ,  UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_					)
							# Save everything
							accelerator.save_state()

							# Load everything back in and make sure all states work
							accelerator.load_state(os.path.join(UpperCamelCase_     ,  'checkpoints'     ,  'checkpoint_1'					)					)
							test_rands += train(1     ,  UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_					)
							(_lowercase)					:       Any       =		model.a.item(), model.b.item()
							_lowercase					:       List[Any]       =		optimizer.state_dict()
							self.assertEqual(UpperCamelCase_     ,  UpperCamelCase_					)
							self.assertEqual(UpperCamelCase_     ,  UpperCamelCase_					)
							self.assertEqual(UpperCamelCase_     ,  UpperCamelCase_					)
							self.assertEqual(UpperCamelCase_     ,  UpperCamelCase_					)




					def 						__UpperCAmelCase     (  self				:	str					)  ->       List[str]:



						'''simple docstring'''





						_lowercase					:       str       =		torch.tensor([1, 2, 3]					)
						_lowercase					:       Union[str, Any]       =		torch.tensor([2, 3, 4]					)
						_lowercase					:       Union[str, Any]       =		DummyModel()
						_lowercase					:       Union[str, Any]       =		torch.optim.Adam(net.parameters()					)
						_lowercase					:       int       =		Accelerator()
						with self.assertRaises(UpperCamelCase_					) as ve:
							accelerator.register_for_checkpointing(UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_					)
						_lowercase					:       int       =		str(ve.exception					)
						self.assertTrue('Item at index 0' in message					)
						self.assertTrue('Item at index 1' in message					)
						self.assertFalse('Item at index 2' in message					)
						self.assertFalse('Item at index 3' in message					)




					def 						__UpperCAmelCase     (  self				:	Tuple					)  ->       Any:



						'''simple docstring'''





						with tempfile.TemporaryDirectory() as tmpdir:
							set_seed(42					)
							_lowercase					:       Dict       =		DummyModel()
							_lowercase					:       List[str]       =		torch.optim.Adam(params=model.parameters()     ,  lr=1E-3					)
							_lowercase					:       List[str]       =		torch.optim.lr_scheduler.StepLR(UpperCamelCase_     ,  step_size=1     ,  gamma=0.99					)
							_lowercase					:       str       =		dummy_dataloaders()
							_lowercase					:       Any       =		ProjectConfiguration(automatic_checkpoint_naming=UpperCamelCase_					)
							# Train baseline
							_lowercase					:       List[str]       =		Accelerator(project_dir=UpperCamelCase_     ,  project_config=UpperCamelCase_					)
							_lowercase					:       List[str]       =		accelerator.prepare(
							    UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_					)
							# Save initial
							accelerator.save_state()
							_lowercase					:       str       =		scheduler.state_dict()
							train(3     ,  UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_     ,  UpperCamelCase_					)
							self.assertNotEqual(UpperCamelCase_     ,  scheduler.state_dict()					)

							# Load everything back in and make sure all states work
							accelerator.load_state(os.path.join(UpperCamelCase_     ,  'checkpoints'     ,  'checkpoint_0'					)					)
							self.assertEqual(UpperCamelCase_     ,  scheduler.state_dict()					)




					def 						__UpperCAmelCase     (  self				:	Optional[Any]					)  ->       Any:



						'''simple docstring'''





						with tempfile.TemporaryDirectory() as tmpdir:
							set_seed(42					)
							_lowercase					:       Optional[Any]       =		DummyModel()
							_lowercase					:       List[str]       =		ProjectConfiguration(automatic_checkpoint_naming=UpperCamelCase_     ,  total_limit=2					)
							# Train baseline
							_lowercase					:       List[str]       =		Accelerator(project_dir=UpperCamelCase_     ,  project_config=UpperCamelCase_					)
							_lowercase					:       List[Any]       =		accelerator.prepare(UpperCamelCase_					)
							# Save 3 states:
							for _ in range(11					):
								accelerator.save_state()
							self.assertTrue(not os.path.exists(os.path.join(UpperCamelCase_     ,  'checkpoints'     ,  'checkpoint_0'					)					)					)
							self.assertTrue(os.path.exists(os.path.join(UpperCamelCase_     ,  'checkpoints'     ,  'checkpoint_9'					)					)					)
							self.assertTrue(os.path.exists(os.path.join(UpperCamelCase_     ,  'checkpoints'     ,  'checkpoint_10'					)					)					)




					@require_cuda
					def 						__UpperCAmelCase     (  self				:	Optional[Any]					)  ->       int:



						'''simple docstring'''





						_lowercase					:       List[str]       =		['torchrun', F'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__					)]
						execute_subprocess_async(UpperCamelCase_     ,  env=os.environ.copy()					)


if __name__ == "__main__":
		_A				:    Union[str, Any]     						='''/tmp/accelerate/state_checkpointing'''
		_A				:    Any     						=DummyModel()
		_A				:    int     						=torch.optim.Adam(params=model.parameters(), lr=1e-3)
		_A				:    str     						=torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99)
		_A				:    int     						=dummy_dataloaders()
		_A				:    Dict     						=ProjectConfiguration(automatic_checkpoint_naming=True)
		# Train baseline
		_A				:    Optional[Any]     						=Accelerator(project_dir=savedir, project_config=project_config, mixed_precision='''no''')
		if accelerator.process_index == 0:
				if os.path.exists(savedir):
						shutil.rmtree(savedir)
				os.makedirs(savedir)
		_A				:    Optional[Any]     						=accelerator.prepare(
		    model, optimizer, train_dataloader, valid_dataloader, scheduler
		)
		_A				:    Any     						=accelerator.prepare(model, optimizer)
		train(3, model, train_dataloader, optimizer, accelerator, scheduler)
		# Check that the intial optimizer is loaded on the GPU
		for group in optimizer.param_groups:
				_A				:    List[Any]     						=group['''params'''][0].device
				break
		assert param_device.type == accelerator.device.type
		_A				:    Optional[Any]     						=model.cpu()
		accelerator.wait_for_everyone()
		accelerator.save_state()
		accelerator.wait_for_everyone()

		# Check CPU state
		accelerator.load_state(os.path.join(savedir, '''checkpoints''', '''checkpoint_0'''), map_location='''cpu''')
		for group in optimizer.param_groups:
				_A				:    Tuple     						=group['''params'''][0].device
				break
		assert (
		    param_device.type == torch.device('''cpu''').type
		), F"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}"

		# Check device state
		model.to(accelerator.device)
		accelerator.load_state(os.path.join(savedir, '''checkpoints''', '''checkpoint_0'''), map_location='''on_device''')
		for group in optimizer.param_groups:
				_A				:    Optional[int]     						=group['''params'''][0].device
				break
		assert (
		    param_device.type == accelerator.device.type
		), F"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}"

		# Check error
		with pytest.raises(TypeError, match='''Unsupported optimizer map location passed'''):
				accelerator.load_state(os.path.join(savedir, '''checkpoints''', '''checkpoint_0'''), map_location='''invalid''')
		accelerator.wait_for_everyone()
		if accelerator.process_index == 0:
				shutil.rmtree(savedir)
		accelerator.wait_for_everyone()





'''simple docstring'''

from collections import UserDict
from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
		from PIL import Image

		from ..image_utils import load_image

if is_torch_available():
		from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING

if is_tf_available():
		from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
		from ..tf_utils import stable_softmax

_A				:    Optional[int]     						=logging.get_logger(__name__)



@add_end_docstrings(A     )
class 		lowerCamelCase__      (						A     ):




					'''simple docstring'''



					def __init__(  self				:	Tuple     ,  **UpperCamelCase_				:	List[str]					)  ->       int:



						'''simple docstring'''





						super().__init__(**UpperCamelCase_					)

						requires_backends(self     ,  'vision'					)
						self.check_model_type(
						    TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
						    if self.framework == 'tf'
						    else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING					)




					def __call__(  self				:	int     ,  UpperCamelCase_				:	Union[str, List[str], "Image", List["Image"]]     ,  **UpperCamelCase_				:	Tuple					)  ->       List[Any]:



						'''simple docstring'''





						return super().__call__(UpperCamelCase_     ,  **UpperCamelCase_					)




					def 						__UpperCAmelCase     (  self				:	List[Any]     ,  **UpperCamelCase_				:	str					)  ->       List[str]:



						'''simple docstring'''





						_lowercase					:       Optional[int]       =		{}
						if "candidate_labels" in kwargs:
							_lowercase					:       Union[str, Any]       =		kwargs['candidate_labels']
						if "hypothesis_template" in kwargs:
							_lowercase					:       int       =		kwargs['hypothesis_template']

						return preprocess_params, {}, {}




					def 						__UpperCAmelCase     (  self				:	Tuple     ,  UpperCamelCase_				:	Dict     ,  UpperCamelCase_				:	Optional[Any]=None     ,  UpperCamelCase_				:	str="This is a photo of {}."					)  ->       Union[str, Any]:



						'''simple docstring'''





						_lowercase					:       Dict       =		load_image(UpperCamelCase_					)
						_lowercase					:       List[str]       =		self.image_processor(images=[image]     ,  return_tensors=self.framework					)
						_lowercase					:       Optional[Any]       =		candidate_labels
						_lowercase					:       List[Any]       =		[hypothesis_template.format(UpperCamelCase_					) for x in candidate_labels]
						_lowercase					:       Union[str, Any]       =		self.tokenizer(UpperCamelCase_     ,  return_tensors=self.framework     ,  padding=UpperCamelCase_					)
						_lowercase					:       Any       =		[text_inputs]
						return inputs




					def 						__UpperCAmelCase     (  self				:	str     ,  UpperCamelCase_				:	Union[str, Any]					)  ->       Optional[Any]:



						'''simple docstring'''





						_lowercase					:       Optional[Any]       =		model_inputs.pop('candidate_labels'					)
						_lowercase					:       List[str]       =		model_inputs.pop('text_inputs'					)
						if isinstance(text_inputs[0]     ,  UpperCamelCase_					):
							_lowercase					:       Optional[int]       =		text_inputs[0]
						else:
							# Batching case.
							_lowercase					:       List[str]       =		text_inputs[0][0]

						_lowercase					:       Optional[Any]       =		self.model(**UpperCamelCase_     ,  **UpperCamelCase_					)

						_lowercase					:       Optional[Any]       =		{
						    'candidate_labels': candidate_labels,
						    'logits': outputs.logits_per_image,
						}
						return model_outputs




					def 						__UpperCAmelCase     (  self				:	Optional[int]     ,  UpperCamelCase_				:	int					)  ->       List[str]:



						'''simple docstring'''





						_lowercase					:       Optional[int]       =		model_outputs.pop('candidate_labels'					)
						_lowercase					:       Optional[int]       =		model_outputs['logits'][0]
						if self.framework == "pt":
							_lowercase					:       List[Any]       =		logits.softmax(dim=-1					).squeeze(-1					)
							_lowercase					:       Tuple       =		probs.tolist()
							if not isinstance(UpperCamelCase_     ,  UpperCamelCase_					):
								_lowercase					:       List[Any]       =		[scores]
						elif self.framework == "tf":
							_lowercase					:       Optional[int]       =		stable_softmax(UpperCamelCase_     ,  axis=-1					)
							_lowercase					:       List[Any]       =		probs.numpy().tolist()
						else:
							raise ValueError(F'''Unsupported framework: {self.framework}'''					)

						_lowercase					:       List[Any]       =		[
						    {'score': score, 'label': candidate_label}
						    for score, candidate_label in sorted(zip(UpperCamelCase_     ,  UpperCamelCase_					)     ,  key=lambda UpperCamelCase_					: -x[0]					)
						]
						return result
