



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


_snake_case						=    logging.get_logger(__name__)

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



@dataclass
class     UpperCAmelCase_       :
							lowerCamelCase__       =						field(
							    default=a  ,   metadata={'help': 'Model type selected in the list: ' + ', '.join(a)})
							lowerCamelCase__       =						field(
							    default=a  ,   metadata={'help': 'The input data dir. Should contain the .json files for the SQuAD task.'})
							lowerCamelCase__       =						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.'
							        )
							    }  ,   )
							lowerCamelCase__       =						field(
							    default=128  ,   metadata={'help': 'When splitting up a long document into chunks, how much stride to take between chunks.'}  ,   )
							lowerCamelCase__       =						field(
							    default=64  ,   metadata={
							        'help': (
							            'The maximum number of tokens for the question. Questions longer than this will '
							            'be truncated to this length.'
							        )
							    }  ,   )
							lowerCamelCase__       =						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.'
							        )
							    }  ,   )
							lowerCamelCase__       =						field(
							    default=a  ,   metadata={'help': 'Overwrite the cached training and evaluation sets'})
							lowerCamelCase__       =						field(
							    default=a  ,   metadata={'help': 'If true, the SQuAD examples contain some that do not have an answer.'})
							lowerCamelCase__       =						field(
							    default=0.0  ,   metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'})
							lowerCamelCase__       =						field(
							    default=20  ,   metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'})
							lowerCamelCase__       =						field(
							    default=0  ,   metadata={
							        'help': (
							            'language id of input for language-specific xlm models (see'
							            ' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)'
							        )
							    }  ,   )
							lowerCamelCase__       =						field(default=1  ,   metadata={'help': 'multiple threads for converting example to features'})



class     UpperCAmelCase_       (			a):
							lowerCamelCase__       =						'train'
							lowerCamelCase__       =						'dev'



class     UpperCAmelCase_       (			a):
							lowerCamelCase__       =						42
							lowerCamelCase__       =						42
							lowerCamelCase__       =						42
							lowerCamelCase__       =						42







							def __init__(  self,     __a,     __a,     __a = None,     __a = Split.train,     __a = False,     __a = None,     __a = "pt",     ):

														'''simple docstring'''

														_lowerCAmelCase	:				Any					  =       args
														_lowerCAmelCase	:				Any					  =       is_language_sensitive
														_lowerCAmelCase	:				List[str]					  =       SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
														if isinstance(__a,     __a):
																					try:
																												_lowerCAmelCase	:				str					  =       Split[mode]
																					except KeyError:
																												raise KeyError("mode is not a valid split name")
														_lowerCAmelCase	:				Union[str, Any]					  =       mode
														# Load data features from cache or dataset file
														_lowerCAmelCase	:				List[str]					  =       "v2" if args.version_2_with_negative else "v1"
														_lowerCAmelCase	:				List[Any]					  =       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.
														_lowerCAmelCase	:				Dict					  =       cached_features_file + ".lock"
														with FileLock(__a):
																					if os.path.exists(__a) and not args.overwrite_cache:
																												_lowerCAmelCase	:				str					  =       time.time()
																												_lowerCAmelCase	:				List[str]					  =       torch.load(__a)

																												# Legacy cache files have only features, while new cache files
																												# will have dataset and examples also.
																												_lowerCAmelCase	:				List[Any]					  =       self.old_features["features"]
																												_lowerCAmelCase	:				Tuple					  =       self.old_features.get("dataset",     __a)
																												_lowerCAmelCase	:				Any					  =       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:
																																			_lowerCAmelCase	:				int					  =       self.processor.get_dev_examples(args.data_dir)
																												else:
																																			_lowerCAmelCase	:				Optional[Any]					  =       self.processor.get_train_examples(args.data_dir)

																												_lowerCAmelCase  ,       _lowerCAmelCase	:				List[str]					  =       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,     )

																												_lowerCAmelCase	:				List[Any]					  =       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):

														'''simple docstring'''

														return len(self.features)







							def __getitem__(  self,     __a):

														'''simple docstring'''

														_lowerCAmelCase	:				int					  =       self.features[i]

														_lowerCAmelCase	:				List[Any]					  =       torch.tensor(feature.input_ids,     dtype=torch.long)
														_lowerCAmelCase	:				Any					  =       torch.tensor(feature.attention_mask,     dtype=torch.long)
														_lowerCAmelCase	:				Tuple					  =       torch.tensor(feature.token_type_ids,     dtype=torch.long)
														_lowerCAmelCase	:				List[str]					  =       torch.tensor(feature.cls_index,     dtype=torch.long)
														_lowerCAmelCase	:				str					  =       torch.tensor(feature.p_mask,     dtype=torch.float)
														_lowerCAmelCase	:				Tuple					  =       torch.tensor(feature.is_impossible,     dtype=torch.float)

														_lowerCAmelCase	:				int					  =       {
														    "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:
																					_lowerCAmelCase	:				Any					  =       torch.tensor(feature.start_position,     dtype=torch.long)
																					_lowerCAmelCase	:				Dict					  =       torch.tensor(feature.end_position,     dtype=torch.long)
																					inputs.update({"start_positions": start_positions, "end_positions": end_positions})

														return inputs





'''simple docstring'''





import inspect
import unittest

import torch
import torch.nn as nn

from accelerate.hooks import (
    AlignDevicesHook,
    ModelHook,
    SequentialHook,
    add_hook_to_module,
    attach_align_device_hook,
    remove_hook_from_module,
    remove_hook_from_submodules,
)
from accelerate.test_utils import require_multi_gpu






class __A     (    nn.Module		):



 '''simple docstring'''







 def __init__(self			)       ->	Dict:


      """simple docstring"""



      super().__init__()
      _a           =    nn.Linear(3					,  4			)
      _a           =    nn.BatchNormad(4			)
      _a           =    nn.Linear(4					,  5			)



 def    a__    (self					,  A			)       ->	Dict:


      """simple docstring"""



      return self.lineara(self.batchnorm(self.lineara(A			)			)			)






class __A     (    A		):



 '''simple docstring'''







 def    a__    (self					,  A					,  *A					,  **A			)       ->	Optional[Any]:


      """simple docstring"""



      return (args[0] + 1,) + args[1:], kwargs






class __A     (    A		):



 '''simple docstring'''







 def    a__    (self					,  A					,  A			)       ->	int:


      """simple docstring"""



      return output + 1






class __A     (    unittest.TestCase		):



 '''simple docstring'''







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


      """simple docstring"""



      _a           =    ModelForTest()
      _a           =    ModelHook()

      add_hook_to_module(A					,  A			)
      self.assertEqual(test_model._hf_hook					,  A			)
      self.assertTrue(hasattr(A					,  '''_old_forward'''			)			)

      # Check adding the hook did not change the name or the signature
      self.assertEqual(test_model.forward.__name__					,  '''forward'''			)
      self.assertListEqual(list(inspect.signature(test_model.forward			).parameters			)					,  ['''x''']			)

      remove_hook_from_module(A			)
      self.assertFalse(hasattr(A					,  '''_hf_hook'''			)			)
      self.assertFalse(hasattr(A					,  '''_old_forward'''			)			)



 def    a__    (self			)       ->	Any:


      """simple docstring"""



      _a           =    ModelForTest()
      _a           =    ModelHook()

      add_hook_to_module(A					,  A			)
      add_hook_to_module(A					,  A					,  append=A			)

      self.assertEqual(isinstance(test_model._hf_hook					,  A			)					,  A			)
      self.assertEqual(len(test_model._hf_hook.hooks			)					,  2			)
      self.assertTrue(hasattr(A					,  '''_old_forward'''			)			)

      # Check adding the hook did not change the name or the signature
      self.assertEqual(test_model.forward.__name__					,  '''forward'''			)
      self.assertListEqual(list(inspect.signature(test_model.forward			).parameters			)					,  ['''x''']			)

      remove_hook_from_module(A			)
      self.assertFalse(hasattr(A					,  '''_hf_hook'''			)			)
      self.assertFalse(hasattr(A					,  '''_old_forward'''			)			)



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


      """simple docstring"""



      _a           =    ModelForTest()
      _a           =    torch.randn(2					,  3			)
      _a           =    test_model(x + 1			)
      _a           =    test_model(x + 2			)

      _a           =    PreForwardHook()
      add_hook_to_module(A					,  A			)
      _a           =    test_model(A			)
      self.assertTrue(torch.allclose(A					,  A					,  atol=1E-5			)			)

      # Attaching a hook to a model when it already has one replaces, does not chain
      _a           =    PreForwardHook()
      add_hook_to_module(A					,  A			)
      _a           =    test_model(A			)
      self.assertTrue(torch.allclose(A					,  A					,  atol=1E-5			)			)

      # You need to use the sequential hook to chain two or more hooks
      _a           =    SequentialHook(PreForwardHook()					,  PreForwardHook()			)
      add_hook_to_module(A					,  A			)

      _a           =    test_model(A			)
      assert torch.allclose(A					,  A					,  atol=1E-5			)



 def    a__    (self			)       ->	str:


      """simple docstring"""



      _a           =    ModelForTest()
      _a           =    torch.randn(2					,  3			)
      _a           =    test_model(A			)

      _a           =    PostForwardHook()
      add_hook_to_module(A					,  A			)
      _a           =    test_model(A			)
      self.assertTrue(torch.allclose(A					,  output + 1					,  atol=1E-5			)			)

      # Attaching a hook to a model when it already has one replaces, does not chain
      _a           =    PostForwardHook()
      add_hook_to_module(A					,  A			)
      _a           =    test_model(A			)
      self.assertTrue(torch.allclose(A					,  output + 1					,  atol=1E-5			)			)

      # You need to use the sequential hook to chain two or more hooks
      _a           =    SequentialHook(PostForwardHook()					,  PostForwardHook()			)
      add_hook_to_module(A					,  A			)

      _a           =    test_model(A			)
      assert torch.allclose(A					,  output + 2					,  atol=1E-5			)



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


      """simple docstring"""



      _a           =    ModelForTest()
      _a           =    torch.randn(2					,  3			)
      _a           =    test_model(A			)

      _a           =    PostForwardHook()
      add_hook_to_module(A					,  A			)
      _a           =    test_model(A			)
      self.assertTrue(torch.allclose(A					,  output + 1			)			)
      self.assertTrue(outputa.requires_grad			)

      _a           =    True
      _a           =    test_model(A			)
      self.assertFalse(outputa.requires_grad			)



 @require_multi_gpu
 def    a__    (self			)       ->	List[Any]:


      """simple docstring"""



      _a           =    ModelForTest()
      # Everything is on CPU
      self.assertEqual(model.lineara.weight.device					,  torch.device('''cpu'''			)			)
      self.assertEqual(model.batchnorm.weight.device					,  torch.device('''cpu'''			)			)
      self.assertEqual(model.lineara.weight.device					,  torch.device('''cpu'''			)			)

      # This will move each submodule on different devices
      add_hook_to_module(model.lineara					,  AlignDevicesHook(execution_device=0			)			)
      add_hook_to_module(model.batchnorm					,  AlignDevicesHook(execution_device=0			)			)
      add_hook_to_module(model.lineara					,  AlignDevicesHook(execution_device=1			)			)

      self.assertEqual(model.lineara.weight.device					,  torch.device(0			)			)
      self.assertEqual(model.batchnorm.weight.device					,  torch.device(0			)			)
      self.assertEqual(model.batchnorm.running_mean.device					,  torch.device(0			)			)
      self.assertEqual(model.lineara.weight.device					,  torch.device(1			)			)

      # We can still make a forward pass. The input does not need to be on any particular device
      _a           =    torch.randn(2					,  3			)
      _a           =    model(A			)
      self.assertEqual(output.device					,  torch.device(1			)			)

      # We can add a general hook to put back output on same device as input.
      add_hook_to_module(A					,  AlignDevicesHook(io_same_device=A			)			)
      _a           =    torch.randn(2					,  3			).to(0			)
      _a           =    model(A			)
      self.assertEqual(output.device					,  torch.device(0			)			)



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


      """simple docstring"""



      _a           =    ModelForTest()

      # Everything is on CPU
      self.assertEqual(model.lineara.weight.device					,  torch.device('''cpu'''			)			)
      self.assertEqual(model.batchnorm.weight.device					,  torch.device('''cpu'''			)			)
      self.assertEqual(model.lineara.weight.device					,  torch.device('''cpu'''			)			)

      # This will move each submodule on different devices
      _a           =    {'''execution_device''': 0 if torch.cuda.is_available() else '''cpu''', '''offload''': True}

      add_hook_to_module(model.lineara					,  AlignDevicesHook(**A			)			)
      add_hook_to_module(model.batchnorm					,  AlignDevicesHook(**A			)			)
      add_hook_to_module(model.lineara					,  AlignDevicesHook(**A			)			)

      # Parameters have been offloaded, so on the meta device
      self.assertEqual(model.lineara.weight.device					,  torch.device('''meta'''			)			)
      self.assertEqual(model.batchnorm.weight.device					,  torch.device('''meta'''			)			)
      self.assertEqual(model.lineara.weight.device					,  torch.device('''meta'''			)			)
      # Buffers are not included in the offload by default, so are on the execution device
      _a           =    torch.device(hook_kwargs['''execution_device''']			)
      self.assertEqual(model.batchnorm.running_mean.device					,  A			)

      _a           =    torch.randn(2					,  3			)
      _a           =    model(A			)
      self.assertEqual(output.device					,  A			)

      # Removing hooks loads back the weights in the model.
      remove_hook_from_module(model.lineara			)
      remove_hook_from_module(model.batchnorm			)
      remove_hook_from_module(model.lineara			)
      self.assertEqual(model.lineara.weight.device					,  torch.device('''cpu'''			)			)
      self.assertEqual(model.batchnorm.weight.device					,  torch.device('''cpu'''			)			)
      self.assertEqual(model.lineara.weight.device					,  torch.device('''cpu'''			)			)

      # Now test with buffers included in the offload
      _a           =    {
          '''execution_device''': 0 if torch.cuda.is_available() else '''cpu''',
          '''offload''': True,
          '''offload_buffers''': True,
      }

      add_hook_to_module(model.lineara					,  AlignDevicesHook(**A			)			)
      add_hook_to_module(model.batchnorm					,  AlignDevicesHook(**A			)			)
      add_hook_to_module(model.lineara					,  AlignDevicesHook(**A			)			)

      # Parameters have been offloaded, so on the meta device, buffers included
      self.assertEqual(model.lineara.weight.device					,  torch.device('''meta'''			)			)
      self.assertEqual(model.batchnorm.weight.device					,  torch.device('''meta'''			)			)
      self.assertEqual(model.lineara.weight.device					,  torch.device('''meta'''			)			)
      self.assertEqual(model.batchnorm.running_mean.device					,  torch.device('''meta'''			)			)

      _a           =    torch.randn(2					,  3			)
      _a           =    model(A			)
      self.assertEqual(output.device					,  A			)

      # Removing hooks loads back the weights in the model.
      remove_hook_from_module(model.lineara			)
      remove_hook_from_module(model.batchnorm			)
      remove_hook_from_module(model.lineara			)
      self.assertEqual(model.lineara.weight.device					,  torch.device('''cpu'''			)			)
      self.assertEqual(model.batchnorm.weight.device					,  torch.device('''cpu'''			)			)
      self.assertEqual(model.lineara.weight.device					,  torch.device('''cpu'''			)			)



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


      """simple docstring"""



      _a           =    ModelForTest()

      # Everything is on CPU
      self.assertEqual(model.lineara.weight.device					,  torch.device('''cpu'''			)			)
      self.assertEqual(model.batchnorm.weight.device					,  torch.device('''cpu'''			)			)
      self.assertEqual(model.lineara.weight.device					,  torch.device('''cpu'''			)			)

      # This will move each submodule on different devices
      _a           =    0 if torch.cuda.is_available() else '''cpu'''
      attach_align_device_hook(A					,  execution_device=A					,  offload=A			)

      # Parameters have been offloaded, so on the meta device
      self.assertEqual(model.lineara.weight.device					,  torch.device('''meta'''			)			)
      self.assertEqual(model.batchnorm.weight.device					,  torch.device('''meta'''			)			)
      self.assertEqual(model.lineara.weight.device					,  torch.device('''meta'''			)			)
      # Buffers are not included in the offload by default, so are on the execution device
      _a           =    torch.device(A			)
      self.assertEqual(model.batchnorm.running_mean.device					,  A			)

      _a           =    torch.randn(2					,  3			)
      _a           =    model(A			)
      self.assertEqual(output.device					,  A			)

      # Removing hooks loads back the weights in the model.
      remove_hook_from_submodules(A			)
      self.assertEqual(model.lineara.weight.device					,  torch.device('''cpu'''			)			)
      self.assertEqual(model.batchnorm.weight.device					,  torch.device('''cpu'''			)			)
      self.assertEqual(model.lineara.weight.device					,  torch.device('''cpu'''			)			)

      # Now test with buffers included in the offload
      attach_align_device_hook(A					,  execution_device=A					,  offload=A					,  offload_buffers=A			)

      # Parameters have been offloaded, so on the meta device, buffers included
      self.assertEqual(model.lineara.weight.device					,  torch.device('''meta'''			)			)
      self.assertEqual(model.batchnorm.weight.device					,  torch.device('''meta'''			)			)
      self.assertEqual(model.lineara.weight.device					,  torch.device('''meta'''			)			)
      self.assertEqual(model.batchnorm.running_mean.device					,  torch.device('''meta'''			)			)

      _a           =    torch.randn(2					,  3			)
      _a           =    model(A			)
      self.assertEqual(output.device					,  A			)

      # Removing hooks loads back the weights in the model.
      remove_hook_from_submodules(A			)
      self.assertEqual(model.lineara.weight.device					,  torch.device('''cpu'''			)			)
      self.assertEqual(model.batchnorm.weight.device					,  torch.device('''cpu'''			)			)
      self.assertEqual(model.lineara.weight.device					,  torch.device('''cpu'''			)			)



 def    a__    (self			)       ->	Any:


      """simple docstring"""



      _a           =    ModelForTest()

      # Everything is on CPU
      self.assertEqual(model.lineara.weight.device					,  torch.device('''cpu'''			)			)
      self.assertEqual(model.batchnorm.weight.device					,  torch.device('''cpu'''			)			)
      self.assertEqual(model.lineara.weight.device					,  torch.device('''cpu'''			)			)

      # This will move each submodule on different devices
      _a           =    0 if torch.cuda.is_available() else '''cpu'''
      attach_align_device_hook(
          A					,  execution_device=A					,  offload=A					,  weights_map=model.state_dict()			)

      # Parameters have been offloaded, so on the meta device
      self.assertEqual(model.lineara.weight.device					,  torch.device('''meta'''			)			)
      self.assertEqual(model.batchnorm.weight.device					,  torch.device('''meta'''			)			)
      self.assertEqual(model.lineara.weight.device					,  torch.device('''meta'''			)			)
      # Buffers are not included in the offload by default, so are on the execution device
      _a           =    torch.device(A			)
      self.assertEqual(model.batchnorm.running_mean.device					,  A			)

      _a           =    torch.randn(2					,  3			)
      _a           =    model(A			)
      self.assertEqual(output.device					,  A			)

      # Removing hooks loads back the weights in the model.
      remove_hook_from_submodules(A			)
      self.assertEqual(model.lineara.weight.device					,  torch.device('''cpu'''			)			)
      self.assertEqual(model.batchnorm.weight.device					,  torch.device('''cpu'''			)			)
      self.assertEqual(model.lineara.weight.device					,  torch.device('''cpu'''			)			)

      # Now test with buffers included in the offload
      attach_align_device_hook(
          A					,  execution_device=A					,  offload=A					,  weights_map=model.state_dict()					,  offload_buffers=A					,  )

      # Parameters have been offloaded, so on the meta device, buffers included
      self.assertEqual(model.lineara.weight.device					,  torch.device('''meta'''			)			)
      self.assertEqual(model.batchnorm.weight.device					,  torch.device('''meta'''			)			)
      self.assertEqual(model.lineara.weight.device					,  torch.device('''meta'''			)			)
      self.assertEqual(model.batchnorm.running_mean.device					,  torch.device('''meta'''			)			)

      _a           =    torch.randn(2					,  3			)
      _a           =    model(A			)
      self.assertEqual(output.device					,  A			)

      # Removing hooks loads back the weights in the model.
      remove_hook_from_submodules(A			)
      self.assertEqual(model.lineara.weight.device					,  torch.device('''cpu'''			)			)
      self.assertEqual(model.batchnorm.weight.device					,  torch.device('''cpu'''			)			)
      self.assertEqual(model.lineara.weight.device					,  torch.device('''cpu'''			)			)



