"""simple docstring"""




from __future__ import annotations

import unittest

from transformers import AutoTokenizer, PegasusConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
				import tensorflow as tf

				from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel
@require_tf
class 			UpperCamelCase__:
						lowerCAmelCase__     :  Optional[int]  							=						PegasusConfig
						lowerCAmelCase__     :  List[str]  							=						{}
						lowerCAmelCase__     :  Dict  							=						'gelu'





						def __init__(				self						,__UpperCAmelCase						,__UpperCAmelCase=13						,__UpperCAmelCase=7						,__UpperCAmelCase=True						,__UpperCAmelCase=False						,__UpperCAmelCase=99						,__UpperCAmelCase=32						,__UpperCAmelCase=2						,__UpperCAmelCase=4						,__UpperCAmelCase=37						,__UpperCAmelCase=0.1						,__UpperCAmelCase=0.1						,__UpperCAmelCase=40						,__UpperCAmelCase=2						,__UpperCAmelCase=1						,__UpperCAmelCase=0						,)    -> str:
													A__		   =							parent
													A__		   =							batch_size
													A__		   =							seq_length
													A__		   =							is_training
													A__		   =							use_labels
													A__		   =							vocab_size
													A__		   =							hidden_size
													A__		   =							num_hidden_layers
													A__		   =							num_attention_heads
													A__		   =							intermediate_size

													A__		   =							hidden_dropout_prob
													A__		   =							attention_probs_dropout_prob
													A__		   =							max_position_embeddings
													A__		   =							eos_token_id
													A__		   =							pad_token_id
													A__		   =							bos_token_id





						def  snake_case__		(				self   )    -> str:
													A__		   =							ids_tensor([self.batch_size, self.seq_length - 1]						,self.vocab_size   )
													A__		   =							tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size   )						,1   )
													A__		   =							tf.concat([input_ids, eos_tensor]						,axis=1   )

													A__		   =							ids_tensor([self.batch_size, self.seq_length]						,self.vocab_size   )

													A__		   =							self.config_cls(
													    vocab_size=self.vocab_size						,d_model=self.hidden_size						,encoder_layers=self.num_hidden_layers						,decoder_layers=self.num_hidden_layers						,encoder_attention_heads=self.num_attention_heads						,decoder_attention_heads=self.num_attention_heads						,encoder_ffn_dim=self.intermediate_size						,decoder_ffn_dim=self.intermediate_size						,dropout=self.hidden_dropout_prob						,attention_dropout=self.attention_probs_dropout_prob						,max_position_embeddings=self.max_position_embeddings						,eos_token_ids=[2]						,bos_token_id=self.bos_token_id						,pad_token_id=self.pad_token_id						,decoder_start_token_id=self.pad_token_id						,**self.config_updates						,)
													A__		   =							prepare_pegasus_inputs_dict(__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase   )
													return config, inputs_dict





						def  snake_case__		(				self						,__UpperCAmelCase						,__UpperCAmelCase   )    -> List[str]:
													A__		   =							TFPegasusModel(config=__UpperCAmelCase   ).get_decoder()
													A__		   =							inputs_dict['input_ids']

													A__		   =							input_ids[:1, :]
													A__		   =							inputs_dict['attention_mask'][:1, :]
													A__		   =							inputs_dict['head_mask']
													A__		   =							1

													# first forward pass
													A__		   =							model(__UpperCAmelCase						,attention_mask=__UpperCAmelCase						,head_mask=__UpperCAmelCase						,use_cache=__UpperCAmelCase   )

													A__   ,     A__		   =							outputs.to_tuple()

													# create hypothetical next token and extent to next_input_ids
													A__		   =							ids_tensor((self.batch_size, 3)						,config.vocab_size   )
													A__		   =							tf.cast(ids_tensor((self.batch_size, 3)						,2   )						,tf.inta   )

													# append to next input_ids and
													A__		   =							tf.concat([input_ids, next_tokens]						,axis=-1   )
													A__		   =							tf.concat([attention_mask, next_attn_mask]						,axis=-1   )

													A__		   =							model(__UpperCAmelCase						,attention_mask=__UpperCAmelCase   )[0]
													A__		   =							model(__UpperCAmelCase						,attention_mask=__UpperCAmelCase						,past_key_values=__UpperCAmelCase   )[0]

													self.parent.assertEqual(next_tokens.shape[1]						,output_from_past.shape[1]   )

													# select random slice
													A__		   =							int(ids_tensor((1,)						,output_from_past.shape[-1]   )   )
													A__		   =							output_from_no_past[:, -3:, random_slice_idx]
													A__		   =							output_from_past[:, :, random_slice_idx]

													# test that outputs are equal for slice
													tf.debugging.assert_near(__UpperCAmelCase						,__UpperCAmelCase						,rtol=1e-3   )






def      UpperCAmelCase    (		UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__=None				,			UpperCamelCase__=None				,			UpperCamelCase__=None				,			UpperCamelCase__=None				,			UpperCamelCase__=None				,			):






							"""simple docstring"""





							if attention_mask is None:
														A__		   =							tf.cast(tf.math.not_equal(UpperCamelCase__				,			config.pad_token_id )				,			tf.inta )
							if decoder_attention_mask is None:
														A__		   =							tf.concat(
														    [
														        tf.ones(decoder_input_ids[:, :1].shape				,			dtype=tf.inta ),
														        tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:]				,			config.pad_token_id )				,			tf.inta ),
														    ]				,			axis=-1				,			)
							if head_mask is None:
														A__		   =							tf.ones((config.encoder_layers, config.encoder_attention_heads) )
							if decoder_head_mask is None:
														A__		   =							tf.ones((config.decoder_layers, config.decoder_attention_heads) )
							if cross_attn_head_mask is None:
														A__		   =							tf.ones((config.decoder_layers, config.decoder_attention_heads) )
							return {
							    "input_ids": input_ids,
							    "decoder_input_ids": decoder_input_ids,
							    "attention_mask": attention_mask,
							    "decoder_attention_mask": decoder_attention_mask,
							    "head_mask": head_mask,
							    "decoder_head_mask": decoder_head_mask,
							    "cross_attn_head_mask": cross_attn_head_mask,
							}
@require_tf
class 			UpperCamelCase__(	__A						,  __A						,  unittest.TestCase       ):
						lowerCAmelCase__     :  List[str]  							=						(TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else ()
						lowerCAmelCase__     :  Optional[Any]  							=						(TFPegasusForConditionalGeneration,) if is_tf_available() else ()
						lowerCAmelCase__     :  Any  							=						(
						    {
						        'conversational': TFPegasusForConditionalGeneration,
						        'feature-extraction': TFPegasusModel,
						        'summarization': TFPegasusForConditionalGeneration,
						        'text2text-generation': TFPegasusForConditionalGeneration,
						        'translation': TFPegasusForConditionalGeneration,
						    }
						    if is_tf_available()
						    else {}
						)
						lowerCAmelCase__     :  Any  							=						True
						lowerCAmelCase__     :  List[Any]  							=						False
						lowerCAmelCase__     :  Any  							=						False





						def  snake_case__		(				self   )    -> Dict:
													A__		   =							TFPegasusModelTester(self   )
													A__		   =							ConfigTester(self						,config_class=__UpperCAmelCase   )





						def  snake_case__		(				self   )    -> Tuple:
													self.config_tester.run_common_tests()





						def  snake_case__		(				self   )    -> Optional[Any]:
													A__		   =							self.model_tester.prepare_config_and_inputs_for_common()
													self.model_tester.check_decoder_model_past_large_inputs(*__UpperCAmelCase   )






@require_sentencepiece
@require_tokenizers
@require_tf
class 			UpperCamelCase__(	unittest.TestCase       ):
						lowerCAmelCase__     :  Any  							=						[
						    ' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.',
						    ' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a  re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ',
						]
						lowerCAmelCase__     :  int  							=						[
						    'California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to'
						    ' reduce the risk of wildfires.',
						    'N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.',
						]  # differs slightly from pytorch, likely due to numerical differences in linear layers
						lowerCAmelCase__     :  Optional[Any]  							=						'google/pegasus-xsum'





						@cached_property
						def  snake_case__		(				self   )    -> Any:
													return AutoTokenizer.from_pretrained(self.model_name   )





						@cached_property
						def  snake_case__		(				self   )    -> Any:
													A__		   =							TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name   )
													return model





						def  snake_case__		(				self						,**__UpperCAmelCase   )    -> Dict:
													A__		   =							self.translate_src_text(**__UpperCAmelCase   )
													assert self.expected_text == generated_words





						def  snake_case__		(				self						,**__UpperCAmelCase   )    -> Tuple:
													A__		   =							self.tokenizer(self.src_text						,**__UpperCAmelCase						,padding=__UpperCAmelCase						,return_tensors='tf'   )
													A__		   =							self.model.generate(
													    model_inputs.input_ids						,attention_mask=model_inputs.attention_mask						,num_beams=2						,use_cache=__UpperCAmelCase						,)
													A__		   =							self.tokenizer.batch_decode(generated_ids.numpy()						,skip_special_tokens=__UpperCAmelCase   )
													return generated_words





						@slow
						def  snake_case__		(				self   )    -> List[str]:
													self._assert_generated_batch_equal_expected()






"""simple docstring"""




from copy import deepcopy

import torch
import torch.nn.functional as F
from torch.optim import AdamW
from torch.optim.lr_scheduler import LambdaLR
from torch.utils.data import DataLoader

from accelerate.accelerator import Accelerator
from accelerate.state import GradientState
from accelerate.test_utils import RegressionDataset, RegressionModel
from accelerate.utils import DistributedType, is_torch_version, set_seed






def      UpperCAmelCase    (		UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ ):






							"""simple docstring"""





							for param, grad_param in zip(model_a.parameters()				,			model_b.parameters() ):
														if not param.requires_grad:
																					continue
														if not did_step:
																					# Grads should not be in sync
																					assert (
																					    torch.allclose(param.grad				,			grad_param.grad ) is False
																					), F'''Gradients in sync when they should not be at iteration {iteration}:\nmodel_a grad ({param.grad}) == model_b grad ({grad_param.grad})'''
														else:
																					# Grads should be in sync
																					assert (
																					    torch.allclose(param.grad				,			grad_param.grad ) is True
																					), F'''Gradients not in sync when they should be at iteration {iteration}:\nmodel_a grad ({param.grad}) != model_b grad ({grad_param.grad})'''






def      UpperCAmelCase    (		UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__=True ):






							"""simple docstring"""





							model.train()
							A__		   =							model(UpperCamelCase__ )
							A__		   =							F.mse_loss(UpperCamelCase__				,			target.to(output.device ) )
							if not do_backward:
														loss /= accelerator.gradient_accumulation_steps
														loss.backward()
							else:
														accelerator.backward(UpperCamelCase__ )






def      UpperCAmelCase    (		UpperCamelCase__				,			UpperCamelCase__=False ):






							"""simple docstring"""





							set_seed(42 )
							A__		   =							RegressionModel()
							A__		   =							deepcopy(UpperCamelCase__ )
							A__		   =							RegressionDataset(length=80 )
							A__		   =							DataLoader(UpperCamelCase__				,			batch_size=16 )
							model.to(accelerator.device )
							if sched:
														A__		   =							AdamW(params=model.parameters()				,			lr=1E-3 )
														A__		   =							AdamW(params=ddp_model.parameters()				,			lr=1E-3 )
														A__		   =							LambdaLR(UpperCamelCase__				,			lr_lambda=lambda UpperCamelCase__ : epoch**0.6_5 )
														A__		   =							LambdaLR(UpperCamelCase__				,			lr_lambda=lambda UpperCamelCase__ : epoch**0.6_5 )
							# Make a copy of `model`
							if sched:
														A__   ,     A__   ,     A__   ,     A__		   =							accelerator.prepare(UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ )
							else:
														A__   ,     A__		   =							accelerator.prepare(UpperCamelCase__				,			UpperCamelCase__ )
							if sched:
														return (model, opt, sched, dataloader, ddp_model, ddp_opt, ddp_sched)
							return model, ddp_model, dataloader






def      UpperCAmelCase    (		UpperCamelCase__ ):






							"""simple docstring"""





							A__   ,     A__   ,     A__		   =							get_training_setup(UpperCamelCase__ )
							# Use a single batch
							A__   ,     A__		   =							next(iter(UpperCamelCase__ ) ).values()
							for iteration in range(3 ):
														# Gather the distributed inputs and targs for the base model
														A__   ,     A__		   =							accelerator.gather((ddp_input, ddp_target) )
														A__   ,     A__		   =							input.to(accelerator.device ), target.to(accelerator.device )
														# Perform our initial ground truth step in non "DDP"
														step_model(UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ )
														# Do "gradient accumulation" (noop)
														if iteration % 2 == 0:
																					# Accumulate grads locally
																					with accelerator.no_sync(UpperCamelCase__ ):
																												step_model(UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ )
														else:
																					# Sync grads
																					step_model(UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ )

														# Since `no_sync` is a noop, `ddp_model` and `model` grads should always be in sync
														check_model_parameters(UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ )
														for param, ddp_param in zip(model.parameters()				,			ddp_model.parameters() ):
																					if not param.requires_grad:
																												continue
																					assert torch.allclose(
																					    param.grad				,			ddp_param.grad ), F'''Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})'''

														# Shuffle ddp_input on each iteration
														torch.manual_seed(1_337 + iteration )
														A__		   =							ddp_input[torch.randperm(len(UpperCamelCase__ ) )]






def      UpperCAmelCase    (		UpperCamelCase__ ):






							"""simple docstring"""





							A__   ,     A__   ,     A__		   =							get_training_setup(UpperCamelCase__ )
							# Use a single batch
							A__   ,     A__		   =							next(iter(UpperCamelCase__ ) ).values()
							for iteration in range(3 ):
														# Gather the distributed inputs and targs for the base model
														A__   ,     A__		   =							accelerator.gather((ddp_input, ddp_target) )
														A__   ,     A__		   =							input.to(accelerator.device ), target.to(accelerator.device )
														# Perform our initial ground truth step in non "DDP"
														step_model(UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ )
														# Do "gradient accumulation" (noop)
														if iteration % 2 == 0:
																					# Accumulate grads locally
																					with accelerator.no_sync(UpperCamelCase__ ):
																												step_model(UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ )
														else:
																					# Sync grads
																					step_model(UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ )

														# DDP model and model should only be in sync when not (iteration % 2 == 0)
														for param, ddp_param in zip(model.parameters()				,			ddp_model.parameters() ):
																					if not param.requires_grad:
																												continue
																					if iteration % 2 == 0:
																												# Grads should not be in sync
																												assert (
																												    torch.allclose(param.grad				,			ddp_param.grad ) is False
																												), F'''Gradients in sync when they should not be:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})'''
																					else:
																												# Grads should be in sync
																												assert (
																												    torch.allclose(param.grad				,			ddp_param.grad ) is True
																												), F'''Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})'''

        # Shuffle ddp_input on each iteration
														torch.manual_seed(1_337 + iteration )
														A__		   =							ddp_input[torch.randperm(len(UpperCamelCase__ ) )]






def      UpperCAmelCase    (		UpperCamelCase__=False				,			UpperCamelCase__=False ):






							"""simple docstring"""





							A__		   =							Accelerator(
							    split_batches=UpperCamelCase__				,			dispatch_batches=UpperCamelCase__				,			gradient_accumulation_steps=2 )
							# Test that context manager behaves properly
							A__   ,     A__   ,     A__		   =							get_training_setup(UpperCamelCase__ )
							for iteration, batch in enumerate(UpperCamelCase__ ):
														A__   ,     A__		   =							batch.values()
														# Gather the distributed inputs and targs for the base model
														A__   ,     A__		   =							accelerator.gather((ddp_input, ddp_target) )
														A__   ,     A__		   =							input.to(accelerator.device ), target.to(accelerator.device )
														# Perform our initial ground truth step in non "DDP"
														step_model(UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ )
														# Do "gradient accumulation" (noop)
														with accelerator.accumulate(UpperCamelCase__ ):
																					step_model(UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ )

														# DDP model and model should only be in sync when not (iteration % 2 == 0)
														for param, ddp_param in zip(model.parameters()				,			ddp_model.parameters() ):
																					if not param.requires_grad:
																												continue
																					if ((iteration + 1) % 2 == 0) or (iteration == len(UpperCamelCase__ ) - 1):
																												# Grads should be in sync
																												assert (
																												    torch.allclose(param.grad				,			ddp_param.grad ) is True
																												), F'''Gradients not in sync when they should be at iteration {iteration}:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})'''
																					else:
																												# Grads should not be in sync
																												assert (
																												    torch.allclose(param.grad				,			ddp_param.grad ) is False
																												), F'''Gradients in sync when they should not be at iteration {iteration}:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})'''

        # Shuffle ddp_input on each iteration
														torch.manual_seed(1_337 + iteration )
														A__		   =							ddp_input[torch.randperm(len(UpperCamelCase__ ) )]
							GradientState._reset_state()






def      UpperCAmelCase    (		UpperCamelCase__=False				,			UpperCamelCase__=False ):






							"""simple docstring"""





							A__		   =							Accelerator(
							    split_batches=UpperCamelCase__				,			dispatch_batches=UpperCamelCase__				,			gradient_accumulation_steps=2 )
							# Test that context manager behaves properly
							A__   ,     A__   ,     A__   ,     A__   ,     A__   ,     A__   ,     A__		   =							get_training_setup(UpperCamelCase__				,			UpperCamelCase__ )
							for iteration, batch in enumerate(UpperCamelCase__ ):
														A__   ,     A__		   =							batch.values()
														# Gather the distributed inputs and targs for the base model
														A__   ,     A__		   =							accelerator.gather((ddp_input, ddp_target) )
														A__   ,     A__		   =							input.to(accelerator.device ), target.to(accelerator.device )
														# Perform our initial ground truth step in non "DDP"
														model.train()
														ddp_model.train()
														step_model(UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ )
														opt.step()

														if ((iteration + 1) % 2 == 0) or ((iteration + 1) == len(UpperCamelCase__ )):
																					if split_batches:
																												sched.step()
																					else:
																												for _ in range(accelerator.num_processes ):
																																			sched.step()
														opt.zero_grad()
														# Perform gradient accumulation under wrapper
														with accelerator.accumulate(UpperCamelCase__ ):
																					step_model(UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ )
																					ddp_opt.step()
																					ddp_sched.step()
																					ddp_opt.zero_grad()

														# Learning rates should be the same
														assert (
														    opt.param_groups[0]["lr"] == ddp_opt.param_groups[0]["lr"]
														), F'''Learning rates found in each optimizer did not align\nopt: {opt.param_groups[0]["lr"]}\nDDP opt: {ddp_opt.param_groups[0]["lr"]}\n'''
														A__		   =							(((iteration + 1) % 2) == 0) or ((iteration + 1) == len(UpperCamelCase__ ))
														if accelerator.num_processes > 1:
																					check_model_parameters(UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ )
														# Shuffle ddp_input on each iteration
														torch.manual_seed(1_337 + iteration )
							GradientState._reset_state()






def      UpperCAmelCase    (		):






							"""simple docstring"""





							A__		   =							Accelerator()

							A__		   =							RegressionDataset(length=80 )
							A__		   =							DataLoader(UpperCamelCase__				,			batch_size=16 )
							A__		   =							RegressionDataset(length=96 )
							A__		   =							DataLoader(UpperCamelCase__				,			batch_size=16 )
							A__   ,     A__		   =							accelerator.prepare(UpperCamelCase__				,			UpperCamelCase__ )
							assert accelerator.gradient_state.active_dataloader is None
							for iteration, _ in enumerate(UpperCamelCase__ ):
														assert id(accelerator.gradient_state.active_dataloader ) == id(UpperCamelCase__ )
														if iteration < len(UpperCamelCase__ ) - 1:
																					assert not accelerator.gradient_state.end_of_dataloader
																					if iteration == 1:
																												for batch_num, _ in enumerate(UpperCamelCase__ ):
																																			assert id(accelerator.gradient_state.active_dataloader ) == id(UpperCamelCase__ )
																																			if batch_num < len(UpperCamelCase__ ) - 1:
																																										assert not accelerator.gradient_state.end_of_dataloader
																																			else:
																																										assert accelerator.gradient_state.end_of_dataloader
														else:
																					assert accelerator.gradient_state.end_of_dataloader
							assert accelerator.gradient_state.active_dataloader is None






def      UpperCAmelCase    (		):






							"""simple docstring"""





							A__		   =							Accelerator()
							A__		   =							accelerator.state
							if state.local_process_index == 0:
														print('**Test `accumulate` gradient accumulation with dataloader break**' )
							test_dataloader_break()
							if state.distributed_type == DistributedType.NO:
														if state.local_process_index == 0:
																					print('**Test NOOP `no_sync` context manager**' )
														test_noop_sync(UpperCamelCase__ )
							if state.distributed_type in (DistributedType.MULTI_GPU, DistributedType.MULTI_CPU):
														if state.local_process_index == 0:
																					print('**Test Distributed `no_sync` context manager**' )
														test_distributed_sync(UpperCamelCase__ )
							if state.distributed_type == DistributedType.MULTI_GPU:
														for split_batch in [True, False]:
																					for dispatch_batches in [True, False]:
																												if state.local_process_index == 0:
																																			print(
																																			    '**Test `accumulate` gradient accumulation, '				,			F'''`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**'''				,			)
																												test_gradient_accumulation(UpperCamelCase__				,			UpperCamelCase__ )

    # Currently will break on torch 2.0 +, need to investigate why
							if is_torch_version('<'				,			'2.0' ) or state.distributed_type == DistributedType.NO:
														if state.local_process_index == 0:
																					print(
																					    '**Test `accumulate` gradient accumulation with optimizer and scheduler, '				,			'`split_batches=False`, `dispatch_batches=False`**'				,			)
														test_gradient_accumulation_with_opt_and_scheduler()
														if state.distributed_type == DistributedType.MULTI_GPU:
																					for split_batch in [True, False]:
																												for dispatch_batches in [True, False]:
																																			if not split_batch and not dispatch_batches:
																																										continue
																																			if state.local_process_index == 0:
																																										print(
																																										    '**Test `accumulate` gradient accumulation with optimizer and scheduler, '				,			F'''`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**'''				,			)
																																			test_gradient_accumulation_with_opt_and_scheduler(UpperCamelCase__				,			UpperCamelCase__ )






def      UpperCAmelCase    (		UpperCamelCase__ ):






							"""simple docstring"""





							main()


if __name__ == "__main__":
				main()





