



"""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     UpperCAmelCase    (	nn.Module  ):



   def __init__(       self    :	Union[str, Any]				):



     """simple docstring"""
     super().__init__()
     _snake_case   	=      nn.Linear(3							,       4				)
     _snake_case   	=      nn.BatchNormad(4				)
     _snake_case   	=      nn.Linear(4							,       5				)





   def    __UpperCAmelCase    (       self    :	List[str]							,       __lowerCamelCase    :	Union[str, Any]				):



     """simple docstring"""
     return self.lineara(self.batchnorm(self.lineara(__lowerCamelCase				)				)				)



class     UpperCAmelCase    (	__SCREAMING_SNAKE_CASE  ):



   def    __UpperCAmelCase    (       self    :	Optional[Any]							,       __lowerCamelCase    :	Optional[int]							,       *__lowerCamelCase    :	List[Any]							,       **__lowerCamelCase    :	Union[str, Any]				):



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



class     UpperCAmelCase    (	__SCREAMING_SNAKE_CASE  ):



   def    __UpperCAmelCase    (       self    :	int							,       __lowerCamelCase    :	Union[str, Any]							,       __lowerCamelCase    :	str				):



     """simple docstring"""
     return output + 1



class     UpperCAmelCase    (	unittest.TestCase  ):



   def    __UpperCAmelCase    (       self    :	Tuple				):



     """simple docstring"""
     _snake_case   	=      ModelForTest()
     _snake_case   	=      ModelHook()

     add_hook_to_module(__lowerCamelCase							,       __lowerCamelCase				)
     self.assertEqual(test_model._hf_hook							,       __lowerCamelCase				)
     self.assertTrue(hasattr(__lowerCamelCase							,       '''_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(__lowerCamelCase				)
     self.assertFalse(hasattr(__lowerCamelCase							,       '''_hf_hook'''				)				)
     self.assertFalse(hasattr(__lowerCamelCase							,       '''_old_forward'''				)				)



   def    __UpperCAmelCase    (       self    :	Tuple				):



     """simple docstring"""
     _snake_case   	=      ModelForTest()
     _snake_case   	=      ModelHook()

     add_hook_to_module(__lowerCamelCase							,       __lowerCamelCase				)
     add_hook_to_module(__lowerCamelCase							,       __lowerCamelCase							,       append=__lowerCamelCase				)

     self.assertEqual(isinstance(test_model._hf_hook							,       __lowerCamelCase				)							,       __lowerCamelCase				)
     self.assertEqual(len(test_model._hf_hook.hooks				)							,       2				)
     self.assertTrue(hasattr(__lowerCamelCase							,       '''_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(__lowerCamelCase				)
     self.assertFalse(hasattr(__lowerCamelCase							,       '''_hf_hook'''				)				)
     self.assertFalse(hasattr(__lowerCamelCase							,       '''_old_forward'''				)				)



   def    __UpperCAmelCase    (       self    :	Any				):



     """simple docstring"""
     _snake_case   	=      ModelForTest()
     _snake_case   	=      torch.randn(2							,       3				)
     _snake_case   	=      test_model(x + 1				)
     _snake_case   	=      test_model(x + 2				)

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

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

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

     _snake_case   	=      test_model(__lowerCamelCase				)
     assert torch.allclose(__lowerCamelCase							,       __lowerCamelCase							,       atol=1E-5				)



   def    __UpperCAmelCase    (       self    :	Union[str, Any]				):



     """simple docstring"""
     _snake_case   	=      ModelForTest()
     _snake_case   	=      torch.randn(2							,       3				)
     _snake_case   	=      test_model(__lowerCamelCase				)

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

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

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

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



   def    __UpperCAmelCase    (       self    :	Any				):



     """simple docstring"""
     _snake_case   	=      ModelForTest()
     _snake_case   	=      torch.randn(2							,       3				)
     _snake_case   	=      test_model(__lowerCamelCase				)

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

     _snake_case   	=      True
     _snake_case   	=      test_model(__lowerCamelCase				)
     self.assertFalse(outputa.requires_grad				)



   @require_multi_gpu
   def    __UpperCAmelCase    (       self    :	List[str]				):



     """simple docstring"""
     _snake_case   	=      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
     _snake_case   	=      torch.randn(2							,       3				)
     _snake_case   	=      model(__lowerCamelCase				)
     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(__lowerCamelCase							,       AlignDevicesHook(io_same_device=__lowerCamelCase				)				)
     _snake_case   	=      torch.randn(2							,       3				).to(0				)
     _snake_case   	=      model(__lowerCamelCase				)
     self.assertEqual(output.device							,       torch.device(0				)				)



   def    __UpperCAmelCase    (       self    :	Tuple				):



     """simple docstring"""
     _snake_case   	=      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
     _snake_case   	=      {'''execution_device''': 0 if torch.cuda.is_available() else '''cpu''', '''offload''': True}

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

     # 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
     _snake_case   	=      torch.device(hook_kwargs['''execution_device''']				)
     self.assertEqual(model.batchnorm.running_mean.device							,       __lowerCamelCase				)

     _snake_case   	=      torch.randn(2							,       3				)
     _snake_case   	=      model(__lowerCamelCase				)
     self.assertEqual(output.device							,       __lowerCamelCase				)

     # 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
     _snake_case   	=      {
         '''execution_device''': 0 if torch.cuda.is_available() else '''cpu''',
         '''offload''': True,
         '''offload_buffers''': True,
     }

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

     # 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'''				)				)

     _snake_case   	=      torch.randn(2							,       3				)
     _snake_case   	=      model(__lowerCamelCase				)
     self.assertEqual(output.device							,       __lowerCamelCase				)

     # 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    __UpperCAmelCase    (       self    :	List[Any]				):



     """simple docstring"""
     _snake_case   	=      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
     _snake_case   	=      0 if torch.cuda.is_available() else '''cpu'''
     attach_align_device_hook(__lowerCamelCase							,       execution_device=__lowerCamelCase							,       offload=__lowerCamelCase				)

     # 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
     _snake_case   	=      torch.device(__lowerCamelCase				)
     self.assertEqual(model.batchnorm.running_mean.device							,       __lowerCamelCase				)

     _snake_case   	=      torch.randn(2							,       3				)
     _snake_case   	=      model(__lowerCamelCase				)
     self.assertEqual(output.device							,       __lowerCamelCase				)

     # Removing hooks loads back the weights in the model.
     remove_hook_from_submodules(__lowerCamelCase				)
     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(__lowerCamelCase							,       execution_device=__lowerCamelCase							,       offload=__lowerCamelCase							,       offload_buffers=__lowerCamelCase				)

     # 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'''				)				)

     _snake_case   	=      torch.randn(2							,       3				)
     _snake_case   	=      model(__lowerCamelCase				)
     self.assertEqual(output.device							,       __lowerCamelCase				)

     # Removing hooks loads back the weights in the model.
     remove_hook_from_submodules(__lowerCamelCase				)
     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    __UpperCAmelCase    (       self    :	Dict				):



     """simple docstring"""
     _snake_case   	=      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
     _snake_case   	=      0 if torch.cuda.is_available() else '''cpu'''
     attach_align_device_hook(
         __lowerCamelCase							,       execution_device=__lowerCamelCase							,       offload=__lowerCamelCase							,       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
     _snake_case   	=      torch.device(__lowerCamelCase				)
     self.assertEqual(model.batchnorm.running_mean.device							,       __lowerCamelCase				)

     _snake_case   	=      torch.randn(2							,       3				)
     _snake_case   	=      model(__lowerCamelCase				)
     self.assertEqual(output.device							,       __lowerCamelCase				)

     # Removing hooks loads back the weights in the model.
     remove_hook_from_submodules(__lowerCamelCase				)
     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(
         __lowerCamelCase							,       execution_device=__lowerCamelCase							,       offload=__lowerCamelCase							,       weights_map=model.state_dict()							,       offload_buffers=__lowerCamelCase							,       )

     # 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'''				)				)

     _snake_case   	=      torch.randn(2							,       3				)
     _snake_case   	=      model(__lowerCamelCase				)
     self.assertEqual(output.device							,       __lowerCamelCase				)

     # Removing hooks loads back the weights in the model.
     remove_hook_from_submodules(__lowerCamelCase				)
     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'''				)				)










"""simple docstring"""






# This script creates a super tiny model that is useful inside tests, when we just want to test that
# the machinery works, without needing to the check the quality of the outcomes.
#
# This version creates a tiny vocab first, and then a tiny model - so the outcome is truly tiny -
# all files ~60KB. As compared to taking a full-size model, reducing to the minimum its layers and
# emb dimensions, but keeping the full vocab + merges files, leading to ~3MB in total for all files.
# The latter is done by `fsmt-make-super-tiny-model.py`.
#
# It will be used then as "stas/tiny-wmt19-en-ru"

from pathlib import Path
import json
import tempfile

from transformers import FSMTTokenizer, FSMTConfig, FSMTForConditionalGeneration
from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES

snake_case   					=				'''tiny-wmt19-en-ru'''

# Build

# borrowed from a test
snake_case   					=				[
    '''l''',
    '''o''',
    '''w''',
    '''e''',
    '''r''',
    '''s''',
    '''t''',
    '''i''',
    '''d''',
    '''n''',
    '''w</w>''',
    '''r</w>''',
    '''t</w>''',
    '''lo''',
    '''low''',
    '''er</w>''',
    '''low</w>''',
    '''lowest</w>''',
    '''newer</w>''',
    '''wider</w>''',
    '''<unk>''',
]
snake_case   					=				dict(zip(vocab, range(len(vocab))))
snake_case   					=				['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', '''''']

with tempfile.TemporaryDirectory() as tmpdirname:
     snake_case   					=				Path(tmpdirname)
     snake_case   					=				build_dir / VOCAB_FILES_NAMES['''src_vocab_file''']
     snake_case   					=				build_dir / VOCAB_FILES_NAMES['''tgt_vocab_file''']
     snake_case   					=				build_dir / VOCAB_FILES_NAMES['''merges_file''']
     with open(src_vocab_file, '''w''') as fp:
          fp.write(json.dumps(vocab_tokens))
     with open(tgt_vocab_file, '''w''') as fp:
          fp.write(json.dumps(vocab_tokens))
     with open(merges_file, '''w''') as fp:
          fp.write('''\n'''.join(merges))

     snake_case   					=				FSMTTokenizer(
         langs=['''en''', '''ru'''],
         src_vocab_size=len(vocab),
         tgt_vocab_size=len(vocab),
         src_vocab_file=src_vocab_file,
         tgt_vocab_file=tgt_vocab_file,
         merges_file=merges_file,
     )

snake_case   					=				FSMTConfig(
    langs=['''ru''', '''en'''],
    src_vocab_size=1_0_0_0,
    tgt_vocab_size=1_0_0_0,
    d_model=4,
    encoder_layers=1,
    decoder_layers=1,
    encoder_ffn_dim=4,
    decoder_ffn_dim=4,
    encoder_attention_heads=1,
    decoder_attention_heads=1,
)

snake_case   					=				FSMTForConditionalGeneration(config)
print(F"num of params {tiny_model.num_parameters()}")

# Test
snake_case   					=				tokenizer(['''Making tiny model'''], return_tensors='''pt''')
snake_case   					=				tiny_model(**batch)

print('''test output:''', len(outputs.logits[0]))

# Save
tiny_model.half()  # makes it smaller
tiny_model.save_pretrained(mname_tiny)
tokenizer.save_pretrained(mname_tiny)

print(F"Generated {mname_tiny}")

# Upload
# transformers-cli upload tiny-wmt19-en-ru





