



import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer
from ...utils import logging


SCREAMING_SNAKE_CASE_:Any					=						logging.get_logger(__name__)

SCREAMING_SNAKE_CASE_:Optional[int]					=						"""▁"""

SCREAMING_SNAKE_CASE_:Tuple					=						{"""vocab_file""": """sentencepiece.bpe.model"""}

SCREAMING_SNAKE_CASE_:Optional[Any]					=						{
    """vocab_file""": {
        """facebook/mbart-large-en-ro""": (
            """https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model"""
        ),
        """facebook/mbart-large-cc25""": (
            """https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model"""
        ),
    }
}

SCREAMING_SNAKE_CASE_:Optional[Any]					=						{
    """facebook/mbart-large-en-ro""": 1_024,
    """facebook/mbart-large-cc25""": 1_024,
}

# fmt: off
SCREAMING_SNAKE_CASE_:Any					=						["""ar_AR""", """cs_CZ""", """de_DE""", """en_XX""", """es_XX""", """et_EE""", """fi_FI""", """fr_XX""", """gu_IN""", """hi_IN""", """it_IT""", """ja_XX""", """kk_KZ""", """ko_KR""", """lt_LT""", """lv_LV""", """my_MM""", """ne_NP""", """nl_XX""", """ro_RO""", """ru_RU""", """si_LK""", """tr_TR""", """vi_VN""", """zh_CN"""]






class SCREAMING_SNAKE_CASE__					(		SCREAMING_SNAKE_CASE__   ):




    '''simple docstring'''






    __lowerCamelCase      :			int =				VOCAB_FILES_NAMES
    __lowerCamelCase      :			Any =				PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    __lowerCamelCase      :			Optional[int] =				PRETRAINED_VOCAB_FILES_MAP
    __lowerCamelCase      :			Union[str, Any] =				["input_ids", "attention_mask"]

    __lowerCamelCase      :			List[int] =				[]
    __lowerCamelCase      :			List[int] =				[]






    def __init__(	self,		lowerCamelCase__,		lowerCamelCase__="<s>",		lowerCamelCase__="</s>",		lowerCamelCase__="</s>",		lowerCamelCase__="<s>",		lowerCamelCase__="<unk>",		lowerCamelCase__="<pad>",		lowerCamelCase__="<mask>",		lowerCamelCase__=None,		lowerCamelCase__=None,		lowerCamelCase__=None,		lowerCamelCase__ = None,		lowerCamelCase__=None,		**lowerCamelCase__,		):
        # Mask token behave like a normal word, i.e. include the space before it
        A			:	List[str]										=       AddedToken(lowerCamelCase__,		lstrip=lowerCamelCase__,		rstrip=lowerCamelCase__		) if isinstance(lowerCamelCase__,		lowerCamelCase__		) else mask_token

        A			:	int										=       {} if sp_model_kwargs is None else sp_model_kwargs

        super().__init__(
            bos_token=lowerCamelCase__,		eos_token=lowerCamelCase__,		unk_token=lowerCamelCase__,		sep_token=lowerCamelCase__,		cls_token=lowerCamelCase__,		pad_token=lowerCamelCase__,		mask_token=lowerCamelCase__,		tokenizer_file=lowerCamelCase__,		src_lang=lowerCamelCase__,		tgt_lang=lowerCamelCase__,		additional_special_tokens=lowerCamelCase__,		sp_model_kwargs=self.sp_model_kwargs,		**lowerCamelCase__,		)

        A			:	List[str]										=       spm.SentencePieceProcessor(**self.sp_model_kwargs		)
        self.sp_model.Load(str(lowerCamelCase__		)		)
        A			:	Dict										=       vocab_file

        # Original fairseq vocab and spm vocab must be "aligned":
        # Vocab    |    0    |    1    |   2    |    3    |  4  |  5  |  6  |   7   |   8   |  9
        # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
        # fairseq  | '<s>'   | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's'   | '▁de' | '-'
        # spm      | '<unk>' | '<s>'   | '</s>' | ','     | '.' | '▁' | 's' | '▁de' | '-'   | '▁a'

        # Mimic fairseq token-to-id alignment for the first 4 token
        A			:	Dict										=       {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3}

        # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
        A			:	List[Any]										=       1

        A			:	Optional[Any]										=       len(self.sp_model		)
        A			:	int										=       {
            code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(lowerCamelCase__		)
        }
        A			:	int										=       {v: k for k, v in self.lang_code_to_id.items()}
        A			:	List[Any]										=       len(self.sp_model		) + len(self.lang_code_to_id		) + self.fairseq_offset

        self.fairseq_tokens_to_ids.update(self.lang_code_to_id		)
        A			:	Union[str, Any]										=       {v: k for k, v in self.fairseq_tokens_to_ids.items()}
        A			:	Union[str, Any]										=       list(self.lang_code_to_id.keys()		)

        if additional_special_tokens is not None:
            # Only add those special tokens if they are not already there.
            self._additional_special_tokens.extend(
                [t for t in additional_special_tokens if t not in self._additional_special_tokens]		)

        A			:	List[Any]										=       src_lang if src_lang is not None else """en_XX"""
        A			:	Tuple										=       self.lang_code_to_id[self._src_lang]
        A			:	List[str]										=       tgt_lang
        self.set_src_lang_special_tokens(self._src_lang		)






    def __getstate__(	self		):
        A			:	Dict										=       self.__dict__.copy()
        A			:	Any										=       None
        A			:	Tuple										=       self.sp_model.serialized_model_proto()
        return state






    def __setstate__(	self,		lowerCamelCase__		):
        A			:	Any										=       d

        # for backward compatibility
        if not hasattr(self,		"""sp_model_kwargs"""		):
            A			:	int										=       {}

        A			:	Dict										=       spm.SentencePieceProcessor(**self.sp_model_kwargs		)
        self.sp_model.LoadFromSerializedProto(self.sp_model_proto		)






    @property
    def       _lowerCAmelCase (	self		):
        return len(self.sp_model		) + len(self.lang_code_to_id		) + self.fairseq_offset + 1  # Plus 1 for the mask token






    @property
    def       _lowerCAmelCase (	self		):
        return self._src_lang






    @src_lang.setter
    def       _lowerCAmelCase (	self,		lowerCamelCase__		):
        A			:	Any										=       new_src_lang
        self.set_src_lang_special_tokens(self._src_lang		)






    def       _lowerCAmelCase (	self,		lowerCamelCase__,		lowerCamelCase__ = None,		lowerCamelCase__ = False		):

        if already_has_special_tokens:
            return super().get_special_tokens_mask(
                token_ids_a=lowerCamelCase__,		token_ids_a=lowerCamelCase__,		already_has_special_tokens=lowerCamelCase__		)

        A			:	int										=       [1] * len(self.prefix_tokens		)
        A			:	Tuple										=       [1] * len(self.suffix_tokens		)
        if token_ids_a is None:
            return prefix_ones + ([0] * len(lowerCamelCase__		)) + suffix_ones
        return prefix_ones + ([0] * len(lowerCamelCase__		)) + ([0] * len(lowerCamelCase__		)) + suffix_ones






    def       _lowerCAmelCase (	self,		lowerCamelCase__,		lowerCamelCase__ = None		):
        if token_ids_a is None:
            return self.prefix_tokens + token_ids_a + self.suffix_tokens
        # We don't expect to process pairs, but leave the pair logic for API consistency
        return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens






    def       _lowerCAmelCase (	self,		lowerCamelCase__,		lowerCamelCase__ = None		):
        A			:	Optional[Any]										=       [self.sep_token_id]
        A			:	Optional[Any]										=       [self.cls_token_id]

        if token_ids_a is None:
            return len(cls + token_ids_a + sep		) * [0]
        return len(cls + token_ids_a + sep + sep + token_ids_a + sep		) * [0]






    def       _lowerCAmelCase (	self,		lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__,		lowerCamelCase__,		**lowerCamelCase__		):
        if src_lang is None or tgt_lang is None:
            raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model"""		)
        A			:	List[str]										=       src_lang
        A			:	Optional[Any]										=       self(lowerCamelCase__,		add_special_tokens=lowerCamelCase__,		return_tensors=lowerCamelCase__,		**lowerCamelCase__		)
        A			:	Tuple										=       self.convert_tokens_to_ids(lowerCamelCase__		)
        A			:	int										=       tgt_lang_id
        return inputs






    def       _lowerCAmelCase (	self		):
        A			:	Optional[Any]										=       {self.convert_ids_to_tokens(lowerCamelCase__		): i for i in range(self.vocab_size		)}
        vocab.update(self.added_tokens_encoder		)
        return vocab






    def       _lowerCAmelCase (	self,		lowerCamelCase__		):
        return self.sp_model.encode(lowerCamelCase__,		out_type=lowerCamelCase__		)






    def       _lowerCAmelCase (	self,		lowerCamelCase__		):
        if token in self.fairseq_tokens_to_ids:
            return self.fairseq_tokens_to_ids[token]
        A			:	Optional[int]										=       self.sp_model.PieceToId(lowerCamelCase__		)

        # Need to return unknown token if the SP model returned 0
        return spm_id + self.fairseq_offset if spm_id else self.unk_token_id






    def       _lowerCAmelCase (	self,		lowerCamelCase__		):
        if index in self.fairseq_ids_to_tokens:
            return self.fairseq_ids_to_tokens[index]
        return self.sp_model.IdToPiece(index - self.fairseq_offset		)






    def       _lowerCAmelCase (	self,		lowerCamelCase__		):
        A			:	int										=       """""".join(lowerCamelCase__		).replace(lowerCamelCase__,		""" """		).strip()
        return out_string






    def       _lowerCAmelCase (	self,		lowerCamelCase__,		lowerCamelCase__ = None		):
        if not os.path.isdir(lowerCamelCase__		):
            logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''		)
            return
        A			:	Union[str, Any]										=       os.path.join(
            lowerCamelCase__,		(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]		)

        if os.path.abspath(self.vocab_file		) != os.path.abspath(lowerCamelCase__		) and os.path.isfile(self.vocab_file		):
            copyfile(self.vocab_file,		lowerCamelCase__		)
        elif not os.path.isfile(self.vocab_file		):
            with open(lowerCamelCase__,		"""wb"""		) as fi:
                A			:	Tuple										=       self.sp_model.serialized_model_proto()
                fi.write(lowerCamelCase__		)

        return (out_vocab_file,)






    def       _lowerCAmelCase (	self,		lowerCamelCase__,		lowerCamelCase__ = "en_XX",		lowerCamelCase__ = None,		lowerCamelCase__ = "ro_RO",		**lowerCamelCase__,		):
        A			:	int										=       src_lang
        A			:	Optional[int]										=       tgt_lang
        return super().prepare_seqaseq_batch(lowerCamelCase__,		lowerCamelCase__,		**lowerCamelCase__		)






    def       _lowerCAmelCase (	self		):
        return self.set_src_lang_special_tokens(self.src_lang		)






    def       _lowerCAmelCase (	self		):
        return self.set_tgt_lang_special_tokens(self.tgt_lang		)






    def       _lowerCAmelCase (	self,		lowerCamelCase__		):
        A			:	Any										=       self.lang_code_to_id[src_lang]
        A			:	str										=       []
        A			:	Optional[Any]										=       [self.eos_token_id, self.cur_lang_code]






    def       _lowerCAmelCase (	self,		lowerCamelCase__		):
        A			:	int										=       self.lang_code_to_id[lang]
        A			:	Tuple										=       []
        A			:	List[Any]										=       [self.eos_token_id, self.cur_lang_code]







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




    '''simple docstring'''






    def __init__(	self		):
        super().__init__()
        A			:	Union[str, Any]										=       nn.Linear(3,		4		)
        A			:	Union[str, Any]										=       nn.BatchNormad(4		)
        A			:	Optional[Any]										=       nn.Linear(4,		5		)






    def       _lowerCAmelCase (	self,		lowerCamelCase__		):
        return self.lineara(self.batchnorm(self.lineara(lowerCamelCase__		)		)		)






class SCREAMING_SNAKE_CASE__					(		SCREAMING_SNAKE_CASE__   ):




    '''simple docstring'''






    def       _lowerCAmelCase (	self,		lowerCamelCase__,		*lowerCamelCase__,		**lowerCamelCase__		):
        return (args[0] + 1,) + args[1:], kwargs






class SCREAMING_SNAKE_CASE__					(		SCREAMING_SNAKE_CASE__   ):




    '''simple docstring'''






    def       _lowerCAmelCase (	self,		lowerCamelCase__,		lowerCamelCase__		):
        return output + 1






class SCREAMING_SNAKE_CASE__					(		unittest.TestCase   ):




    '''simple docstring'''






    def       _lowerCAmelCase (	self		):
        A			:	Tuple										=       ModelForTest()
        A			:	Any										=       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       _lowerCAmelCase (	self		):
        A			:	Tuple										=       ModelForTest()
        A			:	Optional[int]										=       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       _lowerCAmelCase (	self		):
        A			:	Any										=       ModelForTest()
        A			:	Tuple										=       torch.randn(2,		3		)
        A			:	Optional[int]										=       test_model(x + 1		)
        A			:	List[str]										=       test_model(x + 2		)

        A			:	List[str]										=       PreForwardHook()
        add_hook_to_module(lowerCamelCase__,		lowerCamelCase__		)
        A			:	List[str]										=       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
        A			:	Optional[Any]										=       PreForwardHook()
        add_hook_to_module(lowerCamelCase__,		lowerCamelCase__		)
        A			:	Tuple										=       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
        A			:	Any										=       SequentialHook(PreForwardHook(),		PreForwardHook()		)
        add_hook_to_module(lowerCamelCase__,		lowerCamelCase__		)

        A			:	Optional[Any]										=       test_model(lowerCamelCase__		)
        assert torch.allclose(lowerCamelCase__,		lowerCamelCase__,		atol=1e-5		)






    def       _lowerCAmelCase (	self		):
        A			:	Tuple										=       ModelForTest()
        A			:	Any										=       torch.randn(2,		3		)
        A			:	Any										=       test_model(lowerCamelCase__		)

        A			:	List[Any]										=       PostForwardHook()
        add_hook_to_module(lowerCamelCase__,		lowerCamelCase__		)
        A			:	str										=       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
        A			:	Tuple										=       PostForwardHook()
        add_hook_to_module(lowerCamelCase__,		lowerCamelCase__		)
        A			:	Optional[int]										=       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
        A			:	Dict										=       SequentialHook(PostForwardHook(),		PostForwardHook()		)
        add_hook_to_module(lowerCamelCase__,		lowerCamelCase__		)

        A			:	List[str]										=       test_model(lowerCamelCase__		)
        assert torch.allclose(lowerCamelCase__,		output + 2,		atol=1e-5		)






    def       _lowerCAmelCase (	self		):
        A			:	List[Any]										=       ModelForTest()
        A			:	Tuple										=       torch.randn(2,		3		)
        A			:	Union[str, Any]										=       test_model(lowerCamelCase__		)

        A			:	List[Any]										=       PostForwardHook()
        add_hook_to_module(lowerCamelCase__,		lowerCamelCase__		)
        A			:	List[Any]										=       test_model(lowerCamelCase__		)
        self.assertTrue(torch.allclose(lowerCamelCase__,		output + 1		)		)
        self.assertTrue(outputa.requires_grad		)

        A			:	int										=       True
        A			:	Tuple										=       test_model(lowerCamelCase__		)
        self.assertFalse(outputa.requires_grad		)






    @require_multi_gpu
    def       _lowerCAmelCase (	self		):
        A			:	int										=       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			:	str										=       torch.randn(2,		3		)
        A			:	int										=       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__		)		)
        A			:	int										=       torch.randn(2,		3		).to(0		)
        A			:	str										=       model(lowerCamelCase__		)
        self.assertEqual(output.device,		torch.device(0		)		)






    def       _lowerCAmelCase (	self		):
        A			:	List[str]										=       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			:	int										=       {"""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
        A			:	Dict										=       torch.device(hook_kwargs["""execution_device"""]		)
        self.assertEqual(model.batchnorm.running_mean.device,		lowerCamelCase__		)

        A			:	int										=       torch.randn(2,		3		)
        A			:	List[Any]										=       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
        A			:	int										=       {
            """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"""		)		)

        A			:	int										=       torch.randn(2,		3		)
        A			:	str										=       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       _lowerCAmelCase (	self		):
        A			:	Any										=       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			:	Tuple										=       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
        A			:	Optional[int]										=       torch.device(lowerCamelCase__		)
        self.assertEqual(model.batchnorm.running_mean.device,		lowerCamelCase__		)

        A			:	List[str]										=       torch.randn(2,		3		)
        A			:	Optional[int]										=       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"""		)		)

        A			:	List[str]										=       torch.randn(2,		3		)
        A			:	List[str]										=       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       _lowerCAmelCase (	self		):
        A			:	int										=       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			:	List[str]										=       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
        A			:	Any										=       torch.device(lowerCamelCase__		)
        self.assertEqual(model.batchnorm.running_mean.device,		lowerCamelCase__		)

        A			:	Optional[Any]										=       torch.randn(2,		3		)
        A			:	Tuple										=       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"""		)		)

        A			:	List[Any]										=       torch.randn(2,		3		)
        A			:	Dict										=       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"""		)		)


