






'''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     :      List[Any]   					=logging.getLogger(__name__)


def 			SCREAMING_SNAKE_CASE_	(UpperCamelCase=2    ,      UpperCamelCase=3    ,      UpperCamelCase=16    ,      UpperCamelCase = 10    ,      UpperCamelCase = 2				)				->	Tuple:

							def get_dataset(UpperCamelCase				):
														lowerCamelCase__ :     Optional[int]	  =	torch.randn(batch_size * n_batches    ,      1				)
														return TensorDataset(UpperCamelCase    ,      a * x + b + 0.1 * torch.randn(batch_size * n_batches    ,      1				)				)

							lowerCamelCase__ :     Optional[int]	  =	get_dataset(UpperCamelCase				)
							lowerCamelCase__ :     Optional[int]	  =	get_dataset(UpperCamelCase				)
							lowerCamelCase__ :     Tuple	  =	DataLoader(UpperCamelCase    ,      shuffle=UpperCamelCase    ,      batch_size=UpperCamelCase    ,      num_workers=4				)
							lowerCamelCase__ :     Tuple	  =	DataLoader(UpperCamelCase    ,      shuffle=UpperCamelCase    ,      batch_size=UpperCamelCase    ,      num_workers=4				)
							return (train_dataloader, valid_dataloader)


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

class _lowercase     (    nn.Module		):




							def __init__(							self:    List[str]					):
														super().__init__()
														lowerCamelCase__ :     List[Any]	  =	nn.Parameter(torch.randn(1					)					)
														lowerCamelCase__ :     int	  =	nn.Parameter(torch.randn(1					)					)




							def 		lowerCamelCase_    (							self:    Tuple      ,							UpperCamelCase__:    Optional[int]					):
														return x * self.a + self.b



class _lowercase     (    unittest.TestCase		):




							def 		lowerCamelCase_    (							self:    Optional[Any]					):
														with tempfile.TemporaryDirectory() as tmpdir:
																					set_seed(42					)
																					lowerCamelCase__ :     str	  =	DummyModel()
																					lowerCamelCase__ :     Union[str, Any]	  =	torch.optim.Adam(params=model.parameters()      ,							lr=1e-3					)
																					lowerCamelCase__ :     str	  =	dummy_dataloaders()
																					lowerCamelCase__ :     Any	  =	ProjectConfiguration(total_limit=1      ,							project_dir=UpperCamelCase__      ,							automatic_checkpoint_naming=UpperCamelCase__					)
																					# Train baseline
																					lowerCamelCase__ :     int	  =	Accelerator(project_config=UpperCamelCase__					)
																					lowerCamelCase__ :     Optional[int]	  =	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 		lowerCamelCase_    (							self:    Any					):
														with tempfile.TemporaryDirectory() as tmpdir:
																					set_seed(42					)
																					lowerCamelCase__ :     Union[str, Any]	  =	DummyModel()
																					lowerCamelCase__ :     Union[str, Any]	  =	torch.optim.Adam(params=model.parameters()      ,							lr=1e-3					)
																					lowerCamelCase__ :     Dict	  =	dummy_dataloaders()
																					# Train baseline
																					lowerCamelCase__ :     Union[str, Any]	  =	Accelerator()
																					lowerCamelCase__ :     Union[str, Any]	  =	accelerator.prepare(
																					    UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__					)
																					# Save initial
																					lowerCamelCase__ :     Optional[Any]	  =	os.path.join(UpperCamelCase__      ,							"""initial"""					)
																					accelerator.save_state(UpperCamelCase__					)
																					(lowerCamelCase__) :     str	  =	model.a.item(), model.b.item()
																					lowerCamelCase__ :     Union[str, Any]	  =	optimizer.state_dict()
																					lowerCamelCase__ :     Tuple	  =	train(3      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__					)
																					(lowerCamelCase__) :     List[Any]	  =	model.a.item(), model.b.item()
																					lowerCamelCase__ :     Any	  =	optimizer.state_dict()

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

																					lowerCamelCase__ :     Optional[int]	  =	train(2      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__					)
																					# Save everything
																					lowerCamelCase__ :     str	  =	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__					)
																					(lowerCamelCase__) :     Optional[int]	  =	model.a.item(), model.b.item()
																					lowerCamelCase__ :     Tuple	  =	optimizer.state_dict()
																					self.assertEqual(UpperCamelCase__      ,							UpperCamelCase__					)
																					self.assertEqual(UpperCamelCase__      ,							UpperCamelCase__					)
																					self.assertEqual(UpperCamelCase__      ,							UpperCamelCase__					)
																					self.assertEqual(UpperCamelCase__      ,							UpperCamelCase__					)




							def 		lowerCamelCase_    (							self:    int					):
														with tempfile.TemporaryDirectory() as tmpdir:
																					set_seed(42					)
																					lowerCamelCase__ :     Union[str, Any]	  =	DummyModel()
																					lowerCamelCase__ :     Union[str, Any]	  =	torch.optim.Adam(params=model.parameters()      ,							lr=1e-3					)
																					lowerCamelCase__ :     List[str]	  =	dummy_dataloaders()
																					lowerCamelCase__ :     Any	  =	ProjectConfiguration(automatic_checkpoint_naming=UpperCamelCase__					)

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

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

																					lowerCamelCase__ :     Tuple	  =	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__					)
																					(lowerCamelCase__) :     Any	  =	model.a.item(), model.b.item()
																					lowerCamelCase__ :     Any	  =	optimizer.state_dict()
																					self.assertEqual(UpperCamelCase__      ,							UpperCamelCase__					)
																					self.assertEqual(UpperCamelCase__      ,							UpperCamelCase__					)
																					self.assertEqual(UpperCamelCase__      ,							UpperCamelCase__					)
																					self.assertEqual(UpperCamelCase__      ,							UpperCamelCase__					)




							def 		lowerCamelCase_    (							self:    Optional[int]					):
														lowerCamelCase__ :     Tuple	  =	torch.tensor([1, 2, 3]					)
														lowerCamelCase__ :     List[str]	  =	torch.tensor([2, 3, 4]					)
														lowerCamelCase__ :     Tuple	  =	DummyModel()
														lowerCamelCase__ :     Optional[Any]	  =	torch.optim.Adam(net.parameters()					)
														lowerCamelCase__ :     Union[str, Any]	  =	Accelerator()
														with self.assertRaises(UpperCamelCase__					) as ve:
																					accelerator.register_for_checkpointing(UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__					)
														lowerCamelCase__ :     Any	  =	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 		lowerCamelCase_    (							self:    Optional[Any]					):
														with tempfile.TemporaryDirectory() as tmpdir:
																					set_seed(42					)
																					lowerCamelCase__ :     int	  =	DummyModel()
																					lowerCamelCase__ :     Optional[Any]	  =	torch.optim.Adam(params=model.parameters()      ,							lr=1e-3					)
																					lowerCamelCase__ :     int	  =	torch.optim.lr_scheduler.StepLR(UpperCamelCase__      ,							step_size=1      ,							gamma=0.99					)
																					lowerCamelCase__ :     Any	  =	dummy_dataloaders()
																					lowerCamelCase__ :     Tuple	  =	ProjectConfiguration(automatic_checkpoint_naming=UpperCamelCase__					)
																					# Train baseline
																					lowerCamelCase__ :     Dict	  =	Accelerator(project_dir=UpperCamelCase__      ,							project_config=UpperCamelCase__					)
																					lowerCamelCase__ :     Optional[Any]	  =	accelerator.prepare(
																					    UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__      ,							UpperCamelCase__					)
																					# Save initial
																					accelerator.save_state()
																					lowerCamelCase__ :     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 		lowerCamelCase_    (							self:    List[str]					):
														with tempfile.TemporaryDirectory() as tmpdir:
																					set_seed(42					)
																					lowerCamelCase__ :     Dict	  =	DummyModel()
																					lowerCamelCase__ :     Dict	  =	ProjectConfiguration(automatic_checkpoint_naming=UpperCamelCase__      ,							total_limit=2					)
																					# Train baseline
																					lowerCamelCase__ :     Dict	  =	Accelerator(project_dir=UpperCamelCase__      ,							project_config=UpperCamelCase__					)
																					lowerCamelCase__ :     Tuple	  =	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 		lowerCamelCase_    (							self:    List[Any]					):
														lowerCamelCase__ :     Optional[Any]	  =	["""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     :      Optional[Any]   					=DummyModel()
			_A     :      Optional[Any]   					=torch.optim.Adam(params=model.parameters(), lr=1e-3)
			_A     :      Any   					=torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99)
			_A     :      Any   					=dummy_dataloaders()
			_A     :      int   					=ProjectConfiguration(automatic_checkpoint_naming=True)
			# Train baseline
			_A     :      List[str]   					=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     :      str   					=accelerator.prepare(
			    model, optimizer, train_dataloader, valid_dataloader, scheduler
			)
			_A     :      Tuple   					=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[str]   					=group['''params'''][0].device
						break
			assert param_device.type == accelerator.device.type
			_A     :      int   					=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     :      Dict   					=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 Union

import numpy as np
import requests

from ..utils import (
    add_end_docstrings,
    logging,
)
from .audio_classification import ffmpeg_read
from .base import PIPELINE_INIT_ARGS, Pipeline


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

@add_end_docstrings(_lowercase		)
class _lowercase     (    _lowercase		):




							def __init__(							self:    Union[str, Any]      ,							**UpperCamelCase__:    str					):
														super().__init__(**UpperCamelCase__					)

														if self.framework != "pt":
																					raise ValueError(F'''The {self.__class__} is only available in PyTorch.'''					)
														# No specific FOR_XXX available yet




							def __call__(							self:    Optional[Any]      ,							UpperCamelCase__:    Union[np.ndarray, bytes, str]      ,							**UpperCamelCase__:    int					):
														return super().__call__(UpperCamelCase__      ,							**UpperCamelCase__					)




							def 		lowerCamelCase_    (							self:    Optional[Any]      ,							**UpperCamelCase__:    int					):
														lowerCamelCase__ :     Optional[Any]	  =	{}
														if "candidate_labels" in kwargs:
																					lowerCamelCase__ :     str	  =	kwargs["""candidate_labels"""]
														if "hypothesis_template" in kwargs:
																					lowerCamelCase__ :     int	  =	kwargs["""hypothesis_template"""]

														return preprocess_params, {}, {}




							def 		lowerCamelCase_    (							self:    Optional[Any]      ,							UpperCamelCase__:    int      ,							UpperCamelCase__:    List[str]=None      ,							UpperCamelCase__:    Dict="This is a sound of {}."					):
														if isinstance(UpperCamelCase__      ,							UpperCamelCase__					):
																					if audio.startswith("""http://"""					) or audio.startswith("""https://"""					):
																												# We need to actually check for a real protocol, otherwise it's impossible to use a local file
																												# like http_huggingface_co.png
																												lowerCamelCase__ :     int	  =	requests.get(UpperCamelCase__					).content
																					else:
																												with open(UpperCamelCase__      ,							"""rb"""					) as f:
																																			lowerCamelCase__ :     Dict	  =	f.read()

														if isinstance(UpperCamelCase__      ,							UpperCamelCase__					):
																					lowerCamelCase__ :     str	  =	ffmpeg_read(UpperCamelCase__      ,							self.feature_extractor.sampling_rate					)

														if not isinstance(UpperCamelCase__      ,							np.ndarray					):
																					raise ValueError("""We expect a numpy ndarray as input"""					)
														if len(audio.shape					) != 1:
																					raise ValueError("""We expect a single channel audio input for ZeroShotAudioClassificationPipeline"""					)

														lowerCamelCase__ :     Optional[Any]	  =	self.feature_extractor(
														    [audio]      ,							sampling_rate=self.feature_extractor.sampling_rate      ,							return_tensors="""pt"""					)
														lowerCamelCase__ :     Any	  =	candidate_labels
														lowerCamelCase__ :     Any	  =	[hypothesis_template.format(UpperCamelCase__					) for x in candidate_labels]
														lowerCamelCase__ :     int	  =	self.tokenizer(UpperCamelCase__      ,							return_tensors=self.framework      ,							padding=UpperCamelCase__					)
														lowerCamelCase__ :     Tuple	  =	[text_inputs]
														return inputs




							def 		lowerCamelCase_    (							self:    Tuple      ,							UpperCamelCase__:    Union[str, Any]					):
														lowerCamelCase__ :     Any	  =	model_inputs.pop("""candidate_labels"""					)
														lowerCamelCase__ :     Union[str, Any]	  =	model_inputs.pop("""text_inputs"""					)
														if isinstance(text_inputs[0]      ,							UpperCamelCase__					):
																					lowerCamelCase__ :     Optional[int]	  =	text_inputs[0]
														else:
																					# Batching case.
																					lowerCamelCase__ :     Tuple	  =	text_inputs[0][0]

														lowerCamelCase__ :     Tuple	  =	self.model(**UpperCamelCase__      ,							**UpperCamelCase__					)

														lowerCamelCase__ :     str	  =	{
														    """candidate_labels""": candidate_labels,
														    """logits""": outputs.logits_per_audio,
														}
														return model_outputs




							def 		lowerCamelCase_    (							self:    List[str]      ,							UpperCamelCase__:    Union[str, Any]					):
														lowerCamelCase__ :     List[str]	  =	model_outputs.pop("""candidate_labels"""					)
														lowerCamelCase__ :     int	  =	model_outputs["""logits"""][0]

														if self.framework == "pt":
																					lowerCamelCase__ :     Optional[int]	  =	logits.softmax(dim=0					)
																					lowerCamelCase__ :     Any	  =	probs.tolist()
														else:
																					raise ValueError("""`tf` framework not supported."""					)

														lowerCamelCase__ :     Tuple	  =	[
														    {"""score""": score, """label""": candidate_label}
														    for score, candidate_label in sorted(zip(UpperCamelCase__      ,							UpperCamelCase__					)      ,							key=lambda UpperCamelCase__					: -x[0]					)
														]
														return result

