






"""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        lowerCAmelCase (      UpperCamelCase_:							int     , UpperCamelCase_:							str     , UpperCamelCase_:							List[Any]     , UpperCamelCase_:							int					)       ->							Tuple:







  '''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        lowerCAmelCase (      UpperCamelCase_:							List[str]     , UpperCamelCase_:							List[str]     , UpperCamelCase_:							List[Any]     , UpperCamelCase_:							List[Any]     , UpperCamelCase_:							Tuple=True					)       ->							int:







  '''simple docstring'''







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






def        lowerCAmelCase (      UpperCamelCase_:							Union[str, Any]     , UpperCamelCase_:							Optional[int]=False					)       ->							Any:







  '''simple docstring'''







  set_seed(42					)
  _a							=	RegressionModel()
  _a							=	deepcopy(_lowerCamelCase					)
  _a							=	RegressionDataset(length=80					)
  _a							=	DataLoader(_lowerCamelCase     , 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(_lowerCamelCase     , lr_lambda=lambda UpperCamelCase_					: epoch**0.65					)
    _a							=	LambdaLR(_lowerCamelCase     , lr_lambda=lambda UpperCamelCase_					: epoch**0.65					)
  # Make a copy of `model`
  if sched:
    _a			,	_a			,	_a			,	_a							=	accelerator.prepare(_lowerCamelCase     , _lowerCamelCase     , _lowerCamelCase     , _lowerCamelCase					)
  else:
    _a			,	_a							=	accelerator.prepare(_lowerCamelCase     , _lowerCamelCase					)
  if sched:
    return (model, opt, sched, dataloader, ddp_model, ddp_opt, ddp_sched)
  return model, ddp_model, dataloader






def        lowerCAmelCase (      UpperCamelCase_:							Any					)       ->							Any:







  '''simple docstring'''







  _a			,	_a			,	_a							=	get_training_setup(_lowerCamelCase					)
  # Use a single batch
  _a			,	_a							=	next(iter(_lowerCamelCase					)					).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(_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					)
    _a							=	ddp_input[torch.randperm(len(_lowerCamelCase					)					)]






def        lowerCAmelCase (      UpperCamelCase_:							Optional[int]					)       ->							Tuple:







  '''simple docstring'''







  _a			,	_a			,	_a							=	get_training_setup(_lowerCamelCase					)
  # Use a single batch
  _a			,	_a							=	next(iter(_lowerCamelCase					)					).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(_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					)
    _a							=	ddp_input[torch.randperm(len(_lowerCamelCase					)					)]






def        lowerCAmelCase (      UpperCamelCase_:							int=False     , UpperCamelCase_:							Optional[int]=False					)       ->							Optional[Any]:







  '''simple docstring'''







  _a							=	Accelerator(
      split_batches=_lowerCamelCase     , dispatch_batches=_lowerCamelCase     , gradient_accumulation_steps=2					)
  # Test that context manager behaves properly
  _a			,	_a			,	_a							=	get_training_setup(_lowerCamelCase					)
  for iteration, batch in enumerate(_lowerCamelCase					):
    _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(_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					)
    _a							=	ddp_input[torch.randperm(len(_lowerCamelCase					)					)]
  GradientState._reset_state()






def        lowerCAmelCase (      UpperCamelCase_:							Tuple=False     , UpperCamelCase_:							Any=False					)       ->							Tuple:







  '''simple docstring'''







  _a							=	Accelerator(
      split_batches=_lowerCamelCase     , dispatch_batches=_lowerCamelCase     , gradient_accumulation_steps=2					)
  # Test that context manager behaves properly
  _a			,	_a			,	_a			,	_a			,	_a			,	_a			,	_a							=	get_training_setup(_lowerCamelCase     , _lowerCamelCase					)
  for iteration, batch in enumerate(_lowerCamelCase					):
    _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(_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'''
    _a							=	(((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        lowerCAmelCase (      )       ->							Tuple:







  '''simple docstring'''







  _a							=	Accelerator()

  _a							=	RegressionDataset(length=80					)
  _a							=	DataLoader(_lowerCamelCase     , batch_size=16					)
  _a							=	RegressionDataset(length=96					)
  _a							=	DataLoader(_lowerCamelCase     , batch_size=16					)
  _a			,	_a							=	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        lowerCAmelCase (      )       ->							Union[str, Any]:







  '''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(_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        lowerCAmelCase (      UpperCamelCase_:							str					)       ->							Optional[int]:







  '''simple docstring'''







  main()


if __name__ == "__main__":
     main()










"""simple docstring"""




import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features


UpperCamelCase							       =    logging.get_logger(__name__)

UpperCamelCase							       =    list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
UpperCamelCase							       =    tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)




@dataclass
class    lowercase_    :
      A__	:		str       			=				field(
          default=_UpperCAmelCase,    metadata={'''help''': '''Model type selected in the list: ''' + ''', '''.join(_UpperCAmelCase     )}     )
      A__	:		str       			=				field(
          default=_UpperCAmelCase,    metadata={'''help''': '''The input data dir. Should contain the .json files for the SQuAD task.'''}     )
      A__	:		int       			=				field(
          default=128,    metadata={
              '''help''': (
                  '''The maximum total input sequence length after tokenization. Sequences longer '''
                  '''than this will be truncated, sequences shorter will be padded.'''
              )
          },    )
      A__	:		int       			=				field(
          default=128,    metadata={'''help''': '''When splitting up a long document into chunks, how much stride to take between chunks.'''},    )
      A__	:		int       			=				field(
          default=64,    metadata={
              '''help''': (
                  '''The maximum number of tokens for the question. Questions longer than this will '''
                  '''be truncated to this length.'''
              )
          },    )
      A__	:		int       			=				field(
          default=30,    metadata={
              '''help''': (
                  '''The maximum length of an answer that can be generated. This is needed because the start '''
                  '''and end predictions are not conditioned on one another.'''
              )
          },    )
      A__	:		bool       			=				field(
          default=_UpperCAmelCase,    metadata={'''help''': '''Overwrite the cached training and evaluation sets'''}     )
      A__	:		bool       			=				field(
          default=_UpperCAmelCase,    metadata={'''help''': '''If true, the SQuAD examples contain some that do not have an answer.'''}     )
      A__	:		float       			=				field(
          default=0.0,    metadata={'''help''': '''If null_score - best_non_null is greater than the threshold predict null.'''}     )
      A__	:		int       			=				field(
          default=20,    metadata={'''help''': '''If null_score - best_non_null is greater than the threshold predict null.'''}     )
      A__	:		int       			=				field(
          default=0,    metadata={
              '''help''': (
                  '''language id of input for language-specific xlm models (see'''
                  ''' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)'''
              )
          },    )
      A__	:		int       			=				field(default=1,    metadata={'''help''': '''multiple threads for converting example to features'''}     )







class    lowercase_    (_UpperCAmelCase     ):
      A__	:		Tuple       			=				'''train'''
      A__	:		List[Any]       			=				'''dev'''







class    lowercase_    (_UpperCAmelCase     ):
      A__	:		SquadDataTrainingArguments
      A__	:		List[SquadFeatures]
      A__	:		Split
      A__	:		bool






      def __init__(    self     ,     a_     ,     a_     ,     a_ = None     ,     a_ = Split.train     ,     a_ = False     ,     a_ = None     ,     a_ = "pt"     ,     )	->List[str]:







        '''simple docstring'''


        _a							=	args
        _a							=	is_language_sensitive
        _a							=	SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
        if isinstance(a_     ,     a_	):
          try:
            _a							=	Split[mode]
          except KeyError:
            raise KeyError("mode is not a valid split name"	)
        _a							=	mode
        # Load data features from cache or dataset file
        _a							=	"v2" if args.version_2_with_negative else "v1"
        _a							=	os.path.join(
            cache_dir if cache_dir is not None else args.data_dir     ,     f'''cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}'''     ,     )

        # Make sure only the first process in distributed training processes the dataset,
        # and the others will use the cache.
        _a							=	cached_features_file + ".lock"
        with FileLock(a_	):
          if os.path.exists(a_	) and not args.overwrite_cache:
            _a							=	time.time()
            _a							=	torch.load(a_	)

            # Legacy cache files have only features, while new cache files
            # will have dataset and examples also.
            _a							=	self.old_features["features"]
            _a							=	self.old_features.get("dataset"     ,     a_	)
            _a							=	self.old_features.get("examples"     ,     a_	)
            logger.info(
                f'''Loading features from cached file {cached_features_file} [took %.3f s]'''     ,     time.time() - start	)

            if self.dataset is None or self.examples is None:
              logger.warning(
                  f'''Deleting cached file {cached_features_file} will allow dataset and examples to be cached in'''
                  " future run"	)
          else:
            if mode == Split.dev:
              _a							=	self.processor.get_dev_examples(args.data_dir	)
            else:
              _a							=	self.processor.get_train_examples(args.data_dir	)

            _a			,	_a							=	squad_convert_examples_to_features(
                examples=self.examples     ,     tokenizer=a_     ,     max_seq_length=args.max_seq_length     ,     doc_stride=args.doc_stride     ,     max_query_length=args.max_query_length     ,     is_training=mode == Split.train     ,     threads=args.threads     ,     return_dataset=a_     ,     )

            _a							=	time.time()
            torch.save(
                {"features": self.features, "dataset": self.dataset, "examples": self.examples}     ,     a_     ,     )
            # ^ This seems to take a lot of time so I want to investigate why and how we can improve.
            logger.info(
                f'''Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]'''	)






      def __len__(    self	)	->Optional[int]:







        '''simple docstring'''


        return len(self.features	)






      def __getitem__(    self     ,     a_	)	->Dict[str, torch.Tensor]:







        '''simple docstring'''


        _a							=	self.features[i]

        _a							=	torch.tensor(feature.input_ids     ,     dtype=torch.long	)
        _a							=	torch.tensor(feature.attention_mask     ,     dtype=torch.long	)
        _a							=	torch.tensor(feature.token_type_ids     ,     dtype=torch.long	)
        _a							=	torch.tensor(feature.cls_index     ,     dtype=torch.long	)
        _a							=	torch.tensor(feature.p_mask     ,     dtype=torch.float	)
        _a							=	torch.tensor(feature.is_impossible     ,     dtype=torch.float	)

        _a							=	{
            "input_ids": input_ids,
            "attention_mask": attention_mask,
            "token_type_ids": token_type_ids,
        }

        if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
          del inputs["token_type_ids"]

        if self.args.model_type in ["xlnet", "xlm"]:
          inputs.update({"cls_index": cls_index, "p_mask": p_mask}	)
          if self.args.version_2_with_negative:
            inputs.update({"is_impossible": is_impossible}	)
          if self.is_language_sensitive:
            inputs.update({"langs": (torch.ones(input_ids.shape     ,     dtype=torch.intaa	) * self.args.lang_id)}	)

        if self.mode == Split.train:
          _a							=	torch.tensor(feature.start_position     ,     dtype=torch.long	)
          _a							=	torch.tensor(feature.end_position     ,     dtype=torch.long	)
          inputs.update({"start_positions": start_positions, "end_positions": end_positions}	)

        return inputs


