

"""simple docstring"""






import math
import os
import re
import sys
import unittest
from pathlib import Path
from typing import Tuple
from unittest.mock import patch

from parameterized import parameterized

from transformers.testing_utils import (
    CaptureStderr,
    ExtendSysPath,
    TestCasePlus,
    execute_subprocess_async,
    get_gpu_count,
    get_torch_dist_unique_port,
    require_apex,
    require_bitsandbytes,
    require_fairscale,
    require_torch,
    require_torch_gpu,
    require_torch_multi_gpu,
    require_torch_non_multi_gpu,
    slow,
)
from transformers.trainer_callback import TrainerState
from transformers.trainer_utils import set_seed


_lowerCAmelCase						=		os.path.abspath(os.path.dirname(__file__))
with ExtendSysPath(F'''{bindir}/../../examples/pytorch/translation'''):
 from run_translation import main  # noqa


set_seed(4_2)
_lowerCAmelCase						=		"""sshleifer/student_marian_en_ro_6_1"""
_lowerCAmelCase						=		"""sshleifer/tiny-mbart"""







@require_torch
class 	__UpperCamelCase    (    a__						):

  def __lowerCamelCase		(		self    ,_A=False    ,_A=None    ,_A=True    ,_A=True    ,_A=True    ,_A=True    ,):
      '''simple docstring'''

      _lowerCAmelCase       :   Any  =    self.run_trainer(
          eval_steps=1    ,max_len=12    ,model_name=_A    ,num_train_epochs=1    ,distributed=_A    ,extra_args_str=_A    ,predict_with_generate=_A    ,do_train=_A    ,do_eval=_A    ,do_predict=_A    ,)
      _lowerCAmelCase       :   Optional[Any]  =    TrainerState.load_from_json(os.path.join(_A    ,'trainer_state.json'      )      ).log_history

      if not do_eval:
          return

      _lowerCAmelCase       :   Tuple  =    [log for log in logs if 'eval_loss' in log.keys()]

      _lowerCAmelCase       :   Union[str, Any]  =    eval_metrics[0]
      if predict_with_generate:
          assert "eval_bleu" in first_step_stats

          _lowerCAmelCase       :   List[str]  =    eval_metrics[-1]
          assert isinstance(last_step_stats['eval_bleu']    ,_A      )
          assert not math.isnan(float(last_step_stats['eval_loss']      )      ), "eval_loss must not be `nan`"

  @require_torch_non_multi_gpu
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      self.run_seqaseq_quick()

  @require_torch_multi_gpu
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      self.run_seqaseq_quick(distributed=_A      )

  @require_torch_multi_gpu
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      self.run_seqaseq_quick(distributed=_A      )

  @unittest.skip('Requires an update of the env running those tests'      )
  @require_torch_multi_gpu
  @require_fairscale
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      self.run_seqaseq_quick(distributed=_A    ,extra_args_str='--sharded_ddp simple'      )

  @unittest.skip('Requires an update of the env running those tests'      )
  @require_torch_multi_gpu
  @require_fairscale
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      self.run_seqaseq_quick(distributed=_A    ,extra_args_str='--sharded_ddp simple --fp16'      )

  @unittest.skip('Requires an update of the env running those tests'      )
  @require_torch_multi_gpu
  @require_fairscale
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      self.run_seqaseq_quick(distributed=_A    ,extra_args_str='--sharded_ddp zero_dp_2'    ,predict_with_generate=_A      )

  @unittest.skip('Requires an update of the env running those tests'      )
  @require_torch_multi_gpu
  @require_fairscale
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      self.run_seqaseq_quick(
          distributed=_A    ,extra_args_str='--sharded_ddp zero_dp_2 --fp16'    ,predict_with_generate=_A      )

  @require_apex
  @require_torch_gpu
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      self.run_seqaseq_quick(distributed=_A    ,extra_args_str='--fp16 --fp16_backend=apex'      )
      # test 2nd time - was getting eval_loss': nan'
      # to reproduce the problem set distributed=False
      self.run_seqaseq_quick(distributed=_A    ,extra_args_str='--fp16 --fp16_backend=apex'      )

  @parameterized.expand(['base', 'low', 'high', 'mixed']      )
  @require_torch_multi_gpu
  def __lowerCamelCase		(		self    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[Any]  =    {
          # test with the default log_level - should be info and thus log info once
          'base': {'extra_args_str': '', 'n_matches': 1},
          # test with low log_level and log_level_replica - should be noisy on all processes
          # now the info string should appear twice on 2 processes
          'low': {'extra_args_str': '--log_level debug --log_level_replica debug', 'n_matches': 2},
          # test with high log_level and low log_level_replica
          # now the info string should appear once only on the replica
          'high': {'extra_args_str': '--log_level error --log_level_replica debug', 'n_matches': 1},
          # test with high log_level and log_level_replica - should be quiet on all processes
          'mixed': {'extra_args_str': '--log_level error --log_level_replica error', 'n_matches': 0},
      }

      _lowerCAmelCase       :   int  =    experiments[experiment_id]
      _lowerCAmelCase       :   List[Any]  =    {'distributed': True, 'predict_with_generate': False, 'do_eval': False, 'do_predict': False}
      _lowerCAmelCase       :   Tuple  =    'Running training'
      with CaptureStderr() as cl:
          self.run_seqaseq_quick(**_A    ,extra_args_str=data['extra_args_str']      )
      _lowerCAmelCase       :   int  =    len(re.findall(_A    ,cl.err      )      )
      self.assertEqual(_A    ,data['n_matches']      )

  @slow
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[Any]  =    self.run_trainer(
          eval_steps=2    ,max_len=128    ,model_name=_A    ,learning_rate=3E-4    ,num_train_epochs=10    ,distributed=_A    ,)

      # Check metrics
      _lowerCAmelCase       :   Tuple  =    TrainerState.load_from_json(os.path.join(_A    ,'trainer_state.json'      )      ).log_history
      _lowerCAmelCase       :   Union[str, Any]  =    [log for log in logs if 'eval_loss' in log.keys()]
      _lowerCAmelCase       :   int  =    eval_metrics[0]
      _lowerCAmelCase       :   List[str]  =    eval_metrics[-1]

      assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing"
      assert isinstance(last_step_stats['eval_bleu']    ,_A      )

      # test if do_predict saves generations and metrics
      _lowerCAmelCase       :   str  =    os.listdir(_A      )
      _lowerCAmelCase       :   Dict  =    {os.path.basename(_A      ) for p in contents}
      assert "generated_predictions.txt" in contents
      assert "predict_results.json" in contents

  @slow
  @require_bitsandbytes
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      from transformers.training_args import OptimizerNames

      def train_and_return_metrics(_A      ) -> Tuple[int, float]:
          _lowerCAmelCase       :   List[str]  =    '--skip_memory_metrics 0'

          _lowerCAmelCase       :   str  =    self.run_trainer(
              max_len=128    ,model_name=_A    ,learning_rate=3E-4    ,num_train_epochs=1    ,optim=_A    ,distributed=_A    ,extra_args_str=_A    ,do_eval=_A    ,do_predict=_A    ,n_gpus_to_use=1    ,)

          # Check metrics
          _lowerCAmelCase       :   str  =    TrainerState.load_from_json(Path(_A    ,'trainer_state.json'      )      ).log_history
          _lowerCAmelCase       :   List[Any]  =    int(logs[0]['train_mem_gpu_peaked_delta'] / 2**20      )
          _lowerCAmelCase       :   List[str]  =    int(logs[0]['train_mem_gpu_alloc_delta'] / 2**20      )

          _lowerCAmelCase       :   Optional[Any]  =    logs[0]['train_loss']
          return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss

      _lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase       :   Tuple  =    train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value      )
      _lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase       :   str  =    train_and_return_metrics(OptimizerNames.ADAMW_BNB.value      )

      _lowerCAmelCase       :   Union[str, Any]  =    gpu_alloc_mem_orig - gpu_alloc_mem_bnb

      _lowerCAmelCase       :   List[str]  =    gpu_peak_mem_orig + gpu_alloc_mem_orig
      _lowerCAmelCase       :   List[Any]  =    gpu_peak_mem_bnb + gpu_alloc_mem_bnb
      _lowerCAmelCase       :   List[str]  =    gpu_total_mem_orig - gpu_total_mem_bnb

      # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which
      # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized
      # in 2 bytes and the diff in optim memory usage is derived as so:
      #
      # - normal 25*8=~200MB (8 bytes per param)
      # - bnb    25*2= ~50MB (2 bytes per param)
      #
      # Thus we should expect ~150MB total memory saved.
      #
      # Peak memory should be the same - the total should be different by about that same margin
      #
      # After leaving a small margin to accommodate for differences between gpus let's check
      # that we have at least 120MB in savings
      _lowerCAmelCase       :   Any  =    120

      # uncomment the following if this test starts failing - requires py38 for a new print feature
      # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb
      # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB")
      # print(f" {gpu_alloc_mem_bnb=}MB  {gpu_peak_mem_bnb=}MB  {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB")
      # print(f"{gpu_alloc_mem_diff=}MB")
      # print(f"{gpu_peak_mem_diff=}MB")
      # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB")
      # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB")

      self.assertGreater(
          _A    ,_A    ,'should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got'
          F""" a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and"""
          F""" gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB"""    ,)

      self.assertGreater(
          _A    ,_A    ,'should use ~150MB less total gpu memory with BNB, compared to without it for this model but got'
          F""" a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and"""
          F""" gpu_total_mem_bnb={gpu_total_mem_bnb}MB"""    ,)

      self.assertEqual(
          _A    ,_A    ,F"""loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}"""      )







  def __lowerCamelCase		(		self    ,_A    ,_A    ,_A    ,_A = 3E-3    ,_A = "adafactor"    ,_A = False    ,_A = None    ,_A = 0    ,_A = True    ,_A = True    ,_A = True    ,_A = True    ,_A = None    ,):
      '''simple docstring'''

      _lowerCAmelCase       :   int  =    self.test_file_dir / '../fixtures/tests_samples/wmt_en_ro'
      _lowerCAmelCase       :   Optional[int]  =    self.get_auto_remove_tmp_dir()
      _lowerCAmelCase       :   Tuple  =    F"""
            --model_name_or_path {model_name}
            --train_file {data_dir}/train.json
            --validation_file {data_dir}/val.json
            --test_file {data_dir}/test.json
            --output_dir {output_dir}
            --overwrite_output_dir
            --max_train_samples 8
            --max_source_length {max_len}
            --max_target_length {max_len}
            --do_train
            --num_train_epochs {str(_A      )}
            --per_device_train_batch_size 4
            --learning_rate {learning_rate}
            --warmup_steps 8
            --logging_steps 0
            --logging_strategy no
            --save_steps {str(_A      )}
            --group_by_length
            --label_smoothing_factor 0.1
            --target_lang ro_RO
            --source_lang en_XX
        """.split()

      _lowerCAmelCase       :   Dict  =    F"""
            --do_eval
            --per_device_eval_batch_size 4
            --max_eval_samples 8
            --val_max_target_length {max_len}
            --evaluation_strategy steps
            --eval_steps {str(_A      )}
        """.split()

      _lowerCAmelCase       :   List[str]  =    '\n            --do_predict\n        '.split()

      _lowerCAmelCase       :   int  =    []
      if do_train:
          args += args_train

      if do_eval:
          args += args_eval

      if do_predict:
          args += args_predict

      if predict_with_generate:
          args += "--predict_with_generate".split()

      if do_train:
          if optim == "adafactor":
              args += "--adafactor".split()
          else:
              args += F"""--optim {optim}""".split()

      if extra_args_str is not None:
          args += extra_args_str.split()

      if distributed:
          if n_gpus_to_use is None:
              _lowerCAmelCase       :   List[Any]  =    get_gpu_count()
          _lowerCAmelCase       :   List[str]  =    get_torch_dist_unique_port()
          _lowerCAmelCase       :   Tuple  =    F"""
                -m torch.distributed.run
                --nproc_per_node={n_gpus_to_use}
                --master_port={master_port}
                {self.examples_dir_str}/pytorch/translation/run_translation.py
            """.split()
          _lowerCAmelCase       :   Optional[int]  =    [sys.executable] + distributed_args + args
          # keep for quick debug
          # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die
          execute_subprocess_async(_A    ,env=self.get_env()      )
      else:
          _lowerCAmelCase       :   Optional[Any]  =    ['run_translation.py'] + args
          with patch.object(_A    ,'argv'    ,_A      ):
              main()

      return output_dir








"""simple docstring"""






import argparse
import struct
import unittest







class 	__UpperCamelCase    :

  def __init__(		self    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[int]  =    data

      # Initialize hash values
      _lowerCAmelCase       :   Any  =    [
          0x6A09_E667,
          0xBB67_AE85,
          0x3C6E_F372,
          0xA54F_F53A,
          0x510E_527F,
          0x9B05_688C,
          0x1F83_D9AB,
          0x5BE0_CD19,
      ]

      # Initialize round constants
      _lowerCAmelCase       :   str  =    [
          0x428A_2F98,
          0x7137_4491,
          0xB5C0_FBCF,
          0xE9B5_DBA5,
          0x3956_C25B,
          0x59F1_11F1,
          0x923F_82A4,
          0xAB1C_5ED5,
          0xD807_AA98,
          0x1283_5B01,
          0x2431_85BE,
          0x550C_7DC3,
          0x72BE_5D74,
          0x80DE_B1FE,
          0x9BDC_06A7,
          0xC19B_F174,
          0xE49B_69C1,
          0xEFBE_4786,
          0x0FC1_9DC6,
          0x240C_A1CC,
          0x2DE9_2C6F,
          0x4A74_84AA,
          0x5CB0_A9DC,
          0x76F9_88DA,
          0x983E_5152,
          0xA831_C66D,
          0xB003_27C8,
          0xBF59_7FC7,
          0xC6E0_0BF3,
          0xD5A7_9147,
          0x06CA_6351,
          0x1429_2967,
          0x27B7_0A85,
          0x2E1B_2138,
          0x4D2C_6DFC,
          0x5338_0D13,
          0x650A_7354,
          0x766A_0ABB,
          0x81C2_C92E,
          0x9272_2C85,
          0xA2BF_E8A1,
          0xA81A_664B,
          0xC24B_8B70,
          0xC76C_51A3,
          0xD192_E819,
          0xD699_0624,
          0xF40E_3585,
          0x106A_A070,
          0x19A4_C116,
          0x1E37_6C08,
          0x2748_774C,
          0x34B0_BCB5,
          0x391C_0CB3,
          0x4ED8_AA4A,
          0x5B9C_CA4F,
          0x682E_6FF3,
          0x748F_82EE,
          0x78A5_636F,
          0x84C8_7814,
          0x8CC7_0208,
          0x90BE_FFFA,
          0xA450_6CEB,
          0xBEF9_A3F7,
          0xC671_78F2,
      ]

      _lowerCAmelCase       :   Any  =    self.preprocessing(self.data      )
      self.final_hash()

  @staticmethod
  def __lowerCamelCase		(		_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   int  =    b'\x80' + (b'\x00' * (63 - (len(_A      ) + 8) % 64))
      _lowerCAmelCase       :   Any  =    struct.pack('>Q'    ,(len(_A      ) * 8)      )
      return data + padding + big_endian_integer

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[Any]  =    [
          self.preprocessed_data[x : x + 64]
          for x in range(0    ,len(self.preprocessed_data      )    ,64      )
      ]

      for block in self.blocks:
          # Convert the given block into a list of 4 byte integers
          _lowerCAmelCase       :   int  =    list(struct.unpack('>16L'    ,_A      )      )
          # add 48 0-ed integers
          words += [0] * 48

          _lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase       :   Tuple  =    self.hashes

          for index in range(0    ,64      ):
              if index > 15:
                  # modify the zero-ed indexes at the end of the array
                  _lowerCAmelCase       :   List[str]  =    (
                      self.ror(words[index - 15]    ,7      )
                      ^ self.ror(words[index - 15]    ,18      )
                      ^ (words[index - 15] >> 3)
                  )
                  _lowerCAmelCase       :   Tuple  =    (
                      self.ror(words[index - 2]    ,17      )
                      ^ self.ror(words[index - 2]    ,19      )
                      ^ (words[index - 2] >> 10)
                  )

                  _lowerCAmelCase       :   str  =    (
                      words[index - 16] + sa + words[index - 7] + sa
                  ) % 0x1_0000_0000

              # Compression
              _lowerCAmelCase       :   Optional[Any]  =    self.ror(_A    ,6      ) ^ self.ror(_A    ,11      ) ^ self.ror(_A    ,25      )
              _lowerCAmelCase       :   int  =    (e & f) ^ ((~e & 0xFFFF_FFFF) & g)
              _lowerCAmelCase       :   int  =    (
                  h + sa + ch + self.round_constants[index] + words[index]
              ) % 0x1_0000_0000
              _lowerCAmelCase       :   Union[str, Any]  =    self.ror(_A    ,2      ) ^ self.ror(_A    ,13      ) ^ self.ror(_A    ,22      )
              _lowerCAmelCase       :   Any  =    (a & b) ^ (a & c) ^ (b & c)
              _lowerCAmelCase       :   Any  =    (sa + maj) % 0x1_0000_0000

              _lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase,					_lowerCAmelCase       :   Tuple  =    (
                  g,
                  f,
                  e,
                  ((d + tempa) % 0x1_0000_0000),
                  c,
                  b,
                  a,
                  ((tempa + tempa) % 0x1_0000_0000),
              )

          _lowerCAmelCase       :   Any  =    [a, b, c, d, e, f, g, h]

          # Modify final values
          _lowerCAmelCase       :   int  =    [
              ((element + mutated_hash_values[index]) % 0x1_0000_0000)
              for index, element in enumerate(self.hashes      )
          ]

      _lowerCAmelCase       :   List[str]  =    ''.join([hex(_A      )[2:].zfill(8      ) for value in self.hashes]      )







  def __lowerCamelCase		(		self    ,_A    ,_A      ):
      '''simple docstring'''

      return 0xFFFF_FFFF & (value << (32 - rotations)) | (value >> rotations)







class 	__UpperCamelCase    (    unittest.TestCase						):

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      import hashlib

      _lowerCAmelCase       :   Any  =    bytes('Test String'    ,'utf-8'      )
      self.assertEqual(SHAaaa(_A      ).hash    ,hashlib.shaaaa(_A      ).hexdigest()      )





def 		lowerCamelCase__		(					):

    '''simple docstring'''



    import doctest

    doctest.testmod()

    _lowerCAmelCase       :   Optional[Any]  =    argparse.ArgumentParser()
    parser.add_argument(
        '-s' ,   '--string' ,   dest='input_string' ,   default='Hello World!! Welcome to Cryptography' ,   help='Hash the string' ,   )
    parser.add_argument(
        '-f' ,   '--file' ,   dest='input_file' ,   help='Hash contents of a file'   )

    _lowerCAmelCase       :   Tuple  =    parser.parse_args()

    _lowerCAmelCase       :   List[str]  =    args.input_string

    # hash input should be a bytestring
    if args.input_file:
        with open(args.input_file ,   'rb'   ) as f:
            _lowerCAmelCase       :   int  =    f.read()
    else:
        _lowerCAmelCase       :   int  =    bytes(_lowerCamelCase ,   'utf-8'   )

    print(SHAaaa(_lowerCamelCase   ).hash   )


if __name__ == "__main__":
 main()





