'''simple docstring'''

from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
 import tensorflow as tf

 from ..tf_utils import stable_softmax


if is_torch_available():
 import torch


_A			:      Dict					      =				logging.get_logger(__name__)







@add_end_docstrings(
    UpperCAmelCase__  ,							r"""
        top_k (`int`, defaults to 5):
            The number of predictions to return.
        targets (`str` or `List[str]`, *optional*):
            When passed, the model will limit the scores to the passed targets instead of looking up in the whole
            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
            token will be used (with a warning, and that might be slower).

    """  ,							)
class 				_lowercase     (				UpperCAmelCase__			):


 '''simple docstring'''






 def a					(      self   :	Optional[int]      ,       SCREAMING_SNAKE_CASE__   :	GenericTensor							)  ->    np.ndarray:
  if self.framework == "tf":
   __lowerCAmelCase											=						tf.where(input_ids == self.tokenizer.mask_token_id							).numpy()
  elif self.framework == "pt":
   __lowerCAmelCase											=						torch.nonzero(input_ids == self.tokenizer.mask_token_id      ,       as_tuple=SCREAMING_SNAKE_CASE__							)
  else:
   raise ValueError("""Unsupported framework"""							)
  return masked_index
 def a					(      self   :	int      ,       SCREAMING_SNAKE_CASE__   :	GenericTensor							)  ->    np.ndarray:
  __lowerCAmelCase											=						self.get_masked_index(SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase											=						np.prod(masked_index.shape							)
  if numel < 1:
   raise PipelineException(
       """fill-mask"""      ,       self.model.base_model_prefix      ,       f"""No mask_token ({self.tokenizer.mask_token}) found on the input"""      ,       )
 def a					(      self   :	str      ,       SCREAMING_SNAKE_CASE__   :	GenericTensor							)  ->    int:
  if isinstance(SCREAMING_SNAKE_CASE__      ,       SCREAMING_SNAKE_CASE__							):
   for model_input in model_inputs:
    self._ensure_exactly_one_mask_token(model_input["""input_ids"""][0]							)
  else:
   for input_ids in model_inputs["input_ids"]:
    self._ensure_exactly_one_mask_token(SCREAMING_SNAKE_CASE__							)
 def a					(      self   :	str      ,       SCREAMING_SNAKE_CASE__   :	List[Any]      ,       SCREAMING_SNAKE_CASE__   :	Optional[Any]=None      ,       **SCREAMING_SNAKE_CASE__   :	Optional[Any]							)  ->    Dict[str, GenericTensor]:
  if return_tensors is None:
   __lowerCAmelCase											=						self.framework
  __lowerCAmelCase											=						self.tokenizer(SCREAMING_SNAKE_CASE__      ,       return_tensors=SCREAMING_SNAKE_CASE__							)
  self.ensure_exactly_one_mask_token(SCREAMING_SNAKE_CASE__							)
  return model_inputs
 def a					(      self   :	Optional[int]      ,       SCREAMING_SNAKE_CASE__   :	int							)  ->    Tuple:
  __lowerCAmelCase											=						self.model(**SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase											=						model_inputs["""input_ids"""]
  return model_outputs
 def a					(      self   :	Tuple      ,       SCREAMING_SNAKE_CASE__   :	Union[str, Any]      ,       SCREAMING_SNAKE_CASE__   :	List[str]=5      ,       SCREAMING_SNAKE_CASE__   :	int=None							)  ->    Dict:
  # Cap top_k if there are targets
  if target_ids is not None and target_ids.shape[0] < top_k:
   __lowerCAmelCase											=						target_ids.shape[0]
  __lowerCAmelCase											=						model_outputs["""input_ids"""][0]
  __lowerCAmelCase											=						model_outputs["""logits"""]

  if self.framework == "tf":
   __lowerCAmelCase											=						tf.where(input_ids == self.tokenizer.mask_token_id							).numpy()[:, 0]

   __lowerCAmelCase											=						outputs.numpy()

   __lowerCAmelCase											=						outputs[0, masked_index, :]
   __lowerCAmelCase											=						stable_softmax(SCREAMING_SNAKE_CASE__      ,       axis=-1							)
   if target_ids is not None:
    __lowerCAmelCase											=						tf.gather_nd(tf.squeeze(SCREAMING_SNAKE_CASE__      ,       0							)      ,       target_ids.reshape(-1      ,       1							)							)
    __lowerCAmelCase											=						tf.expand_dims(SCREAMING_SNAKE_CASE__      ,       0							)

   __lowerCAmelCase											=						tf.math.top_k(SCREAMING_SNAKE_CASE__      ,       k=SCREAMING_SNAKE_CASE__							)
   __lowerCAmelCase							,       __lowerCAmelCase											=						topk.values.numpy(), topk.indices.numpy()
  else:
   __lowerCAmelCase											=						torch.nonzero(input_ids == self.tokenizer.mask_token_id      ,       as_tuple=SCREAMING_SNAKE_CASE__							).squeeze(-1							)
   # Fill mask pipeline supports only one ${mask_token} per sample

   __lowerCAmelCase											=						outputs[0, masked_index, :]
   __lowerCAmelCase											=						logits.softmax(dim=-1							)
   if target_ids is not None:
    __lowerCAmelCase											=						probs[..., target_ids]

   __lowerCAmelCase							,       __lowerCAmelCase											=						probs.topk(SCREAMING_SNAKE_CASE__							)

  __lowerCAmelCase											=						[]
  __lowerCAmelCase											=						values.shape[0] == 1
  for i, (_values, _predictions) in enumerate(zip(values.tolist()      ,       predictions.tolist()							)							):
   __lowerCAmelCase											=						[]
   for v, p in zip(_values      ,       _predictions							):
    # Copy is important since we're going to modify this array in place
    __lowerCAmelCase											=						input_ids.numpy().copy()
    if target_ids is not None:
     __lowerCAmelCase											=						target_ids[p].tolist()

    __lowerCAmelCase											=						p
    # Filter padding out:
    __lowerCAmelCase											=						tokens[np.where(tokens != self.tokenizer.pad_token_id							)]
    # Originally we skip special tokens to give readable output.
    # For multi masks though, the other [MASK] would be removed otherwise
    # making the output look odd, so we add them back
    __lowerCAmelCase											=						self.tokenizer.decode(SCREAMING_SNAKE_CASE__      ,       skip_special_tokens=SCREAMING_SNAKE_CASE__							)
    __lowerCAmelCase											=						{"""score""": v, """token""": p, """token_str""": self.tokenizer.decode([p]							), """sequence""": sequence}
    row.append(SCREAMING_SNAKE_CASE__							)
   result.append(SCREAMING_SNAKE_CASE__							)
  if single_mask:
   return result[0]
  return result
 def a					(      self   :	Union[str, Any]      ,       SCREAMING_SNAKE_CASE__   :	Dict      ,       SCREAMING_SNAKE_CASE__   :	Dict=None							)  ->    Any:
  if isinstance(SCREAMING_SNAKE_CASE__      ,       SCREAMING_SNAKE_CASE__							):
   __lowerCAmelCase											=						[targets]
  try:
   __lowerCAmelCase											=						self.tokenizer.get_vocab()
  except Exception:
   __lowerCAmelCase											=						{}
  __lowerCAmelCase											=						[]
  for target in targets:
   __lowerCAmelCase											=						vocab.get(SCREAMING_SNAKE_CASE__      ,       SCREAMING_SNAKE_CASE__							)
   if id_ is None:
    __lowerCAmelCase											=						self.tokenizer(
        SCREAMING_SNAKE_CASE__      ,       add_special_tokens=SCREAMING_SNAKE_CASE__      ,       return_attention_mask=SCREAMING_SNAKE_CASE__      ,       return_token_type_ids=SCREAMING_SNAKE_CASE__      ,       max_length=1      ,       truncation=SCREAMING_SNAKE_CASE__      ,       )["""input_ids"""]
    if len(SCREAMING_SNAKE_CASE__							) == 0:
     logger.warning(
         f"""The specified target token `{target}` does not exist in the model vocabulary. """
         """We cannot replace it with anything meaningful, ignoring it"""							)
     continue
    __lowerCAmelCase											=						input_ids[0]
    # XXX: If users encounter this pass
    # it becomes pretty slow, so let's make sure
    # The warning enables them to fix the input to
    # get faster performance.
    logger.warning(
        f"""The specified target token `{target}` does not exist in the model vocabulary. """
        f"""Replacing with `{self.tokenizer.convert_ids_to_tokens(id_							)}`."""							)
   target_ids.append(id_							)
  __lowerCAmelCase											=						list(set(SCREAMING_SNAKE_CASE__							)							)
  if len(SCREAMING_SNAKE_CASE__							) == 0:
   raise ValueError("""At least one target must be provided when passed."""							)
  __lowerCAmelCase											=						np.array(SCREAMING_SNAKE_CASE__							)
  return target_ids
 def a					(      self   :	Any      ,       SCREAMING_SNAKE_CASE__   :	Union[str, Any]=None      ,       SCREAMING_SNAKE_CASE__   :	Union[str, Any]=None							)  ->    Union[str, Any]:
  __lowerCAmelCase											=						{}

  if targets is not None:
   __lowerCAmelCase											=						self.get_target_ids(SCREAMING_SNAKE_CASE__      ,       SCREAMING_SNAKE_CASE__							)
   __lowerCAmelCase											=						target_ids

  if top_k is not None:
   __lowerCAmelCase											=						top_k

  if self.tokenizer.mask_token_id is None:
   raise PipelineException(
       """fill-mask"""      ,       self.model.base_model_prefix      ,       """The tokenizer does not define a `mask_token`."""							)
  return {}, {}, postprocess_params





 def __call__(      self   :	Optional[Any]      ,       SCREAMING_SNAKE_CASE__   :	List[Any]      ,       *SCREAMING_SNAKE_CASE__   :	Any      ,       **SCREAMING_SNAKE_CASE__   :	str							)  ->    Union[str, Any]:
  __lowerCAmelCase											=						super().__call__(SCREAMING_SNAKE_CASE__      ,       **SCREAMING_SNAKE_CASE__							)
  if isinstance(SCREAMING_SNAKE_CASE__      ,       SCREAMING_SNAKE_CASE__							) and len(SCREAMING_SNAKE_CASE__							) == 1:
   return outputs[0]
  return outputs







'''simple docstring'''

import argparse
import gc
import json
import os

import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed

from accelerate import Accelerator, DistributedType
from accelerate.utils.deepspeed import DummyOptim, DummyScheduler


_A			:      Optional[Any]					      =				16
_A			:      Union[str, Any]					      =				32







def      UpperCamelCase_						(					snake_case_       :       List[str]      )					->     str:






 '''simple docstring'''

 return int(x / 2**20      )







class 				_lowercase     :


 '''simple docstring'''






 def __enter__(      self   :	List[Any]							)  ->    int:
  gc.collect()
  torch.cuda.empty_cache()
  torch.cuda.reset_max_memory_allocated()  # reset the peak gauge to zero
  __lowerCAmelCase											=						torch.cuda.memory_allocated()
  return self





 def __exit__(      self   :	Tuple      ,       *SCREAMING_SNAKE_CASE__   :	List[Any]							)  ->    Optional[Any]:
  gc.collect()
  torch.cuda.empty_cache()
  __lowerCAmelCase											=						torch.cuda.memory_allocated()
  __lowerCAmelCase											=						torch.cuda.max_memory_allocated()
  __lowerCAmelCase											=						bamb(self.end - self.begin							)
  __lowerCAmelCase											=						bamb(self.peak - self.begin							)
  # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}")







def      UpperCamelCase_						(					snake_case_       :       Accelerator						,		snake_case_       :       int = 16						,		snake_case_       :       str = "bert-base-cased"						,		snake_case_       :       int = 3_20						,		snake_case_       :       int = 1_60						,		)					->     Optional[int]:






 '''simple docstring'''

 __lowerCAmelCase											=						AutoTokenizer.from_pretrained(snake_case_      )
 __lowerCAmelCase											=						load_dataset(
     """glue"""						,		"""mrpc"""						,		split={"""train""": f"""train[:{n_train}]""", """validation""": f"""validation[:{n_val}]"""}      )

 def tokenize_function(snake_case_       :       List[Any]      ):
  # max_length=None => use the model max length (it's actually the default)
  __lowerCAmelCase											=						tokenizer(examples["""sentence1"""]						,		examples["""sentence2"""]						,		truncation=snake_case_						,		max_length=snake_case_      )
  return outputs

 # Apply the method we just defined to all the examples in all the splits of the dataset
 __lowerCAmelCase											=						datasets.map(
     snake_case_						,		batched=snake_case_						,		remove_columns=["""idx""", """sentence1""", """sentence2"""]						,		load_from_cache_file=snake_case_      )

 # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
 # transformers library
 __lowerCAmelCase											=						tokenized_datasets.rename_column("""label"""						,		"""labels"""      )

 def collate_fn(snake_case_       :       List[Any]      ):
  # On TPU it's best to pad everything to the same length or training will be very slow.
  if accelerator.distributed_type == DistributedType.TPU:
   return tokenizer.pad(snake_case_						,		padding="""max_length"""						,		max_length=1_28						,		return_tensors="""pt"""      )
  return tokenizer.pad(snake_case_						,		padding="""longest"""						,		return_tensors="""pt"""      )

 # Instantiate dataloaders.
 __lowerCAmelCase											=						DataLoader(
     tokenized_datasets["""train"""]						,		shuffle=snake_case_						,		collate_fn=snake_case_						,		batch_size=snake_case_      )
 __lowerCAmelCase											=						DataLoader(
     tokenized_datasets["""validation"""]						,		shuffle=snake_case_						,		collate_fn=snake_case_						,		batch_size=snake_case_      )

 return train_dataloader, eval_dataloader







def      UpperCamelCase_						(					snake_case_       :       List[Any]						,		snake_case_       :       Tuple      )					->     Optional[int]:






 '''simple docstring'''

 __lowerCAmelCase											=						Accelerator()

 # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
 __lowerCAmelCase											=						config["""lr"""]
 __lowerCAmelCase											=						int(config["""num_epochs"""]      )
 __lowerCAmelCase											=						int(config["""seed"""]      )
 __lowerCAmelCase											=						int(config["""batch_size"""]      )
 __lowerCAmelCase											=						args.model_name_or_path

 set_seed(snake_case_      )
 __lowerCAmelCase							,       __lowerCAmelCase											=						get_dataloaders(snake_case_						,		snake_case_						,		snake_case_						,		args.n_train						,		args.n_val      )

 # Instantiate the model (we build the model here so that the seed also control new weights initialization)
 __lowerCAmelCase											=						AutoModelForSequenceClassification.from_pretrained(snake_case_						,		return_dict=snake_case_      )

 # Instantiate optimizer
 __lowerCAmelCase											=						(
     AdamW
     if accelerator.state.deepspeed_plugin is None
     or """optimizer""" not in accelerator.state.deepspeed_plugin.deepspeed_config
     else DummyOptim
 )
 __lowerCAmelCase											=						optimizer_cls(params=model.parameters()						,		lr=snake_case_      )

 if accelerator.state.deepspeed_plugin is not None:
  __lowerCAmelCase											=						accelerator.state.deepspeed_plugin.deepspeed_config[
      """gradient_accumulation_steps"""
  ]
 else:
  __lowerCAmelCase											=						1
 __lowerCAmelCase											=						(len(snake_case_      ) * num_epochs) // gradient_accumulation_steps

 # Instantiate scheduler
 if (
     accelerator.state.deepspeed_plugin is None
     or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config
 ):
  __lowerCAmelCase											=						get_linear_schedule_with_warmup(
      optimizer=snake_case_						,		num_warmup_steps=0						,		num_training_steps=snake_case_						,		)
 else:
  __lowerCAmelCase											=						DummyScheduler(snake_case_						,		total_num_steps=snake_case_						,		warmup_num_steps=0      )

 # Prepare everything
 # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
 # prepare method.
 __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase							,       __lowerCAmelCase											=						accelerator.prepare(
     snake_case_						,		snake_case_						,		snake_case_						,		snake_case_						,		snake_case_      )

 # We need to keep track of how many total steps we have iterated over
 __lowerCAmelCase											=						0
 # We also need to keep track of the stating epoch so files are named properly
 __lowerCAmelCase											=						0

 # Now we train the model
 __lowerCAmelCase											=						{}
 for epoch in range(snake_case_						,		snake_case_      ):
  with TorchTracemalloc() as tracemalloc:
   model.train()
   for step, batch in enumerate(snake_case_      ):
    __lowerCAmelCase											=						model(**snake_case_      )
    __lowerCAmelCase											=						outputs.loss
    __lowerCAmelCase											=						loss / gradient_accumulation_steps
    accelerator.backward(snake_case_      )
    if step % gradient_accumulation_steps == 0:
     optimizer.step()
     lr_scheduler.step()
     optimizer.zero_grad()

    overall_step += 1

        # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage
  accelerator.print("""Memory before entering the train : {}""".format(bamb(tracemalloc.begin      )      )      )
  accelerator.print("""Memory consumed at the end of the train (end-begin): {}""".format(tracemalloc.used      )      )
  accelerator.print("""Peak Memory consumed during the train (max-begin): {}""".format(tracemalloc.peaked      )      )
  accelerator.print(
      """Total Peak Memory consumed during the train (max): {}""".format(
          tracemalloc.peaked + bamb(tracemalloc.begin      )      )      )
  __lowerCAmelCase											=						tracemalloc.peaked + bamb(tracemalloc.begin      )
  if args.peak_memory_upper_bound is not None:
   assert (
       train_total_peak_memory[f"""epoch-{epoch}"""] <= args.peak_memory_upper_bound
   ), "Peak memory usage exceeded the upper bound"

 accelerator.wait_for_everyone()
 if accelerator.is_main_process:
  with open(os.path.join(args.output_dir						,		"""peak_memory_utilization.json"""      )						,		"""w"""      ) as f:
   json.dump(snake_case_						,		snake_case_      )







def      UpperCamelCase_						(					)					->     Any:






 '''simple docstring'''

 __lowerCAmelCase											=						argparse.ArgumentParser(description="""Simple example of training script tracking peak GPU memory usage."""      )
 parser.add_argument(
     """--model_name_or_path"""						,		type=snake_case_						,		default="""bert-base-cased"""						,		help="""Path to pretrained model or model identifier from huggingface.co/models."""						,		required=snake_case_						,		)
 parser.add_argument(
     """--output_dir"""						,		type=snake_case_						,		default="""."""						,		help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory."""						,		)
 parser.add_argument(
     """--peak_memory_upper_bound"""						,		type=snake_case_						,		default=snake_case_						,		help="""The upper bound of peak memory usage in MB. If set, the training will throw an error if the peak memory usage exceeds this value."""						,		)
 parser.add_argument(
     """--n_train"""						,		type=snake_case_						,		default=3_20						,		help="""Number of training examples to use."""						,		)
 parser.add_argument(
     """--n_val"""						,		type=snake_case_						,		default=1_60						,		help="""Number of validation examples to use."""						,		)
 parser.add_argument(
     """--num_epochs"""						,		type=snake_case_						,		default=1						,		help="""Number of train epochs."""						,		)
 __lowerCAmelCase											=						parser.parse_args()
 __lowerCAmelCase											=						{"""lr""": 2E-5, """num_epochs""": args.num_epochs, """seed""": 42, """batch_size""": 16}
 training_function(snake_case_						,		snake_case_      )


if __name__ == "__main__":
 main()






