






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  (       snake_case__     :   Optional[int]	,snake_case__     :   int	,snake_case__     :   Union[str, Any]	,snake_case__     :   List[str]  ):




					'''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  (       snake_case__     :   List[str]	,snake_case__     :   Union[str, Any]	,snake_case__     :   Optional[Any]	,snake_case__     :   Union[str, Any]	,snake_case__     :   int=True  ):




					'''simple docstring'''






					model.train()
					__snake_case			:Optional[int]          =						model(lowerCAmelCase_  )
					__snake_case			:Any          =						F.mse_loss(lowerCAmelCase_	,target.to(output.device  )  )
					if not do_backward:
										loss /= accelerator.gradient_accumulation_steps
										loss.backward()
					else:
										accelerator.backward(lowerCAmelCase_  )






def   UpperCamelCase  (       snake_case__     :   Tuple	,snake_case__     :   List[str]=False  ):




					'''simple docstring'''






					set_seed(42  )
					__snake_case			:Optional[Any]          =						RegressionModel()
					__snake_case			:Dict          =						deepcopy(lowerCAmelCase_  )
					__snake_case			:Union[str, Any]          =						RegressionDataset(length=80  )
					__snake_case			:List[Any]          =						DataLoader(lowerCAmelCase_	,batch_size=16  )
					model.to(accelerator.device  )
					if sched:
										__snake_case			:List[str]          =						AdamW(params=model.parameters()	,lr=1e-3  )
										__snake_case			:str          =						AdamW(params=ddp_model.parameters()	,lr=1e-3  )
										__snake_case			:str          =						LambdaLR(lowerCAmelCase_	,lr_lambda=lambda snake_case__  : epoch**0.6_5  )
										__snake_case			:Any          =						LambdaLR(lowerCAmelCase_	,lr_lambda=lambda snake_case__  : epoch**0.6_5  )
					# Make a copy of `model`
					if sched:
										__snake_case			:str          =						accelerator.prepare(lowerCAmelCase_	,lowerCAmelCase_	,lowerCAmelCase_	,lowerCAmelCase_  )
					else:
										__snake_case			:str          =						accelerator.prepare(lowerCAmelCase_	,lowerCAmelCase_  )
					if sched:
										return (model, opt, sched, dataloader, ddp_model, ddp_opt, ddp_sched)
					return model, ddp_model, dataloader






def   UpperCamelCase  (       snake_case__     :   List[str]  ):




					'''simple docstring'''






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

										# Since `no_sync` is a noop, `ddp_model` and `model` grads should always be in sync
										check_model_parameters(lowerCAmelCase_	,lowerCAmelCase_	,lowerCAmelCase_	,lowerCAmelCase_  )
										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(1337 + iteration  )
										__snake_case			:Dict          =						ddp_input[torch.randperm(len(lowerCAmelCase_  )  )]






def   UpperCamelCase  (       snake_case__     :   Optional[Any]  ):




					'''simple docstring'''






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

										# 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(1337 + iteration  )
										__snake_case			:List[Any]          =						ddp_input[torch.randperm(len(lowerCAmelCase_  )  )]






def   UpperCamelCase  (       snake_case__     :   int=False	,snake_case__     :   List[str]=False  ):




					'''simple docstring'''






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

										# 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(lowerCAmelCase_  ) - 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(1337 + iteration  )
										__snake_case			:str          =						ddp_input[torch.randperm(len(lowerCAmelCase_  )  )]
					GradientState._reset_state()






def   UpperCamelCase  (       snake_case__     :   Optional[Any]=False	,snake_case__     :   Tuple=False  ):




					'''simple docstring'''






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

										if ((iteration + 1) % 2 == 0) or ((iteration + 1) == len(lowerCAmelCase_  )):
															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(lowerCAmelCase_  ):
															step_model(lowerCAmelCase_	,lowerCAmelCase_	,lowerCAmelCase_	,lowerCAmelCase_  )
															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'''
										__snake_case			:Optional[Any]          =						(((iteration + 1) % 2) == 0) or ((iteration + 1) == len(lowerCAmelCase_  ))
										if accelerator.num_processes > 1:
															check_model_parameters(lowerCAmelCase_	,lowerCAmelCase_	,lowerCAmelCase_	,lowerCAmelCase_  )
										# Shuffle ddp_input on each iteration
										torch.manual_seed(1337 + iteration  )
					GradientState._reset_state()






def   UpperCamelCase  (       ):




					'''simple docstring'''






					__snake_case			:int          =						Accelerator()

					__snake_case			:Optional[int]          =						RegressionDataset(length=80  )
					__snake_case			:Tuple          =						DataLoader(lowerCAmelCase_	,batch_size=16  )
					__snake_case			:Optional[int]          =						RegressionDataset(length=96  )
					__snake_case			:Tuple          =						DataLoader(lowerCAmelCase_	,batch_size=16  )
					__snake_case			:Optional[int]          =						accelerator.prepare(lowerCAmelCase_	,lowerCAmelCase_  )
					assert accelerator.gradient_state.active_dataloader is None
					for iteration, _ in enumerate(lowerCAmelCase_  ):
										assert id(accelerator.gradient_state.active_dataloader  ) == id(lowerCAmelCase_  )
										if iteration < len(lowerCAmelCase_  ) - 1:
															assert not accelerator.gradient_state.end_of_dataloader
															if iteration == 1:
																				for batch_num, _ in enumerate(lowerCAmelCase_  ):
																									assert id(accelerator.gradient_state.active_dataloader  ) == id(lowerCAmelCase_  )
																									if batch_num < len(lowerCAmelCase_  ) - 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'''






					__snake_case			:Dict          =						Accelerator()
					__snake_case			:Optional[Any]          =						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(lowerCAmelCase_  )
					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(lowerCAmelCase_  )
					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(lowerCAmelCase_	,lowerCAmelCase_  )

    # 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(lowerCAmelCase_	,lowerCAmelCase_  )






def   UpperCamelCase  (       snake_case__     :   Dict  ):




					'''simple docstring'''






					main()


if __name__ == "__main__":
					main()










# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from packaging import version

from .. import __version__
from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD
from .doc import (
    add_code_sample_docstrings,
    add_end_docstrings,
    add_start_docstrings,
    add_start_docstrings_to_model_forward,
    copy_func,
    replace_return_docstrings,
)
from .generic import (
    ContextManagers,
    ExplicitEnum,
    ModelOutput,
    PaddingStrategy,
    TensorType,
    add_model_info_to_auto_map,
    cached_property,
    can_return_loss,
    expand_dims,
    find_labels,
    flatten_dict,
    infer_framework,
    is_jax_tensor,
    is_numpy_array,
    is_tensor,
    is_tf_symbolic_tensor,
    is_tf_tensor,
    is_torch_device,
    is_torch_dtype,
    is_torch_tensor,
    reshape,
    squeeze,
    strtobool,
    tensor_size,
    to_numpy,
    to_py_obj,
    transpose,
    working_or_temp_dir,
)
from .hub import (
    CLOUDFRONT_DISTRIB_PREFIX,
    DISABLE_TELEMETRY,
    HF_MODULES_CACHE,
    HUGGINGFACE_CO_PREFIX,
    HUGGINGFACE_CO_RESOLVE_ENDPOINT,
    PYTORCH_PRETRAINED_BERT_CACHE,
    PYTORCH_TRANSFORMERS_CACHE,
    S3_BUCKET_PREFIX,
    TRANSFORMERS_CACHE,
    TRANSFORMERS_DYNAMIC_MODULE_NAME,
    EntryNotFoundError,
    PushToHubMixin,
    RepositoryNotFoundError,
    RevisionNotFoundError,
    cached_file,
    default_cache_path,
    define_sagemaker_information,
    download_url,
    extract_commit_hash,
    get_cached_models,
    get_file_from_repo,
    get_full_repo_name,
    has_file,
    http_user_agent,
    is_offline_mode,
    is_remote_url,
    move_cache,
    send_example_telemetry,
    try_to_load_from_cache,
)
from .import_utils import (
    ENV_VARS_TRUE_AND_AUTO_VALUES,
    ENV_VARS_TRUE_VALUES,
    TORCH_FX_REQUIRED_VERSION,
    USE_JAX,
    USE_TF,
    USE_TORCH,
    DummyObject,
    OptionalDependencyNotAvailable,
    _LazyModule,
    ccl_version,
    direct_transformers_import,
    get_torch_version,
    is_accelerate_available,
    is_apex_available,
    is_bitsandbytes_available,
    is_bsa_available,
    is_coloredlogs_available,
    is_cython_available,
    is_datasets_available,
    is_decord_available,
    is_detectrona_available,
    is_faiss_available,
    is_flax_available,
    is_ftfy_available,
    is_in_notebook,
    is_ipex_available,
    is_jieba_available,
    is_jumanpp_available,
    is_kenlm_available,
    is_keras_nlp_available,
    is_librosa_available,
    is_natten_available,
    is_ninja_available,
    is_onnx_available,
    is_openai_available,
    is_optimum_available,
    is_pandas_available,
    is_peft_available,
    is_phonemizer_available,
    is_protobuf_available,
    is_psutil_available,
    is_pyanvml_available,
    is_pyctcdecode_available,
    is_pytesseract_available,
    is_pytest_available,
    is_pytorch_quantization_available,
    is_rjieba_available,
    is_sacremoses_available,
    is_safetensors_available,
    is_sagemaker_dp_enabled,
    is_sagemaker_mp_enabled,
    is_scipy_available,
    is_sentencepiece_available,
    is_seqio_available,
    is_sklearn_available,
    is_soundfile_availble,
    is_spacy_available,
    is_speech_available,
    is_sudachi_available,
    is_tensorflow_probability_available,
    is_tensorflow_text_available,
    is_tfaonnx_available,
    is_tf_available,
    is_timm_available,
    is_tokenizers_available,
    is_torch_available,
    is_torch_bfaa_available,
    is_torch_bfaa_cpu_available,
    is_torch_bfaa_gpu_available,
    is_torch_compile_available,
    is_torch_cuda_available,
    is_torch_fx_available,
    is_torch_fx_proxy,
    is_torch_mps_available,
    is_torch_neuroncore_available,
    is_torch_tensorrt_fx_available,
    is_torch_tfaa_available,
    is_torch_tpu_available,
    is_torchaudio_available,
    is_torchdistx_available,
    is_torchdynamo_available,
    is_torchvision_available,
    is_training_run_on_sagemaker,
    is_vision_available,
    requires_backends,
    torch_only_method,
)


lowerCamelCase__							=     """pytorch_model.bin"""
lowerCamelCase__							=     """pytorch_model.bin.index.json"""
lowerCamelCase__							=     """adapter_config.json"""
lowerCamelCase__							=     """adapter_model.bin"""
lowerCamelCase__							=     """adapter_model.safetensors"""
lowerCamelCase__							=     """tf_model.h5"""
lowerCamelCase__							=     """tf_model.h5.index.json"""
lowerCamelCase__							=     """model.ckpt"""
lowerCamelCase__							=     """flax_model.msgpack"""
lowerCamelCase__							=     """flax_model.msgpack.index.json"""
lowerCamelCase__							=     """model.safetensors"""
lowerCamelCase__							=     """model.safetensors.index.json"""
lowerCamelCase__							=     """config.json"""
lowerCamelCase__							=     """preprocessor_config.json"""
lowerCamelCase__							=     FEATURE_EXTRACTOR_NAME
lowerCamelCase__							=     """generation_config.json"""
lowerCamelCase__							=     """modelcard.json"""

lowerCamelCase__							=     """▁"""
lowerCamelCase__							=     SENTENCEPIECE_UNDERLINE  # Kept for backward compatibility

lowerCamelCase__							=     [
    [[0, 1, 0, 1], [1, 0, 0, 1]]
] * 2  # Needs to have 0s and 1s only since XLM uses it for langs too.
lowerCamelCase__							=     [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]]
lowerCamelCase__							=     [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]]






def   UpperCamelCase  (       snake_case__     :   Dict  ):




     '''simple docstring'''






     if version.parse(snake_case__  ) < version.parse(snake_case__  ):
          if "dev" in min_version:
               __snake_case			:Tuple          =						(
                   """This example requires a source install from HuggingFace Transformers (see """
                   """`https://huggingface.co/docs/transformers/installation#install-from-source`),"""
               )
          else:
               __snake_case			:List[str]          =						f'''This example requires a minimum version of {min_version},'''
          error_message += f''' but the version found is {__version__}.\n'''
          raise ImportError(
              error_message
              + """Check out https://github.com/huggingface/transformers/tree/main/examples#important-note for the examples corresponding to other """
              """versions of HuggingFace Transformers."""  )


