

import gc
import importlib.metadata
import tempfile
import unittest

from packaging import version

from transformers import (
    AutoModel,
    AutoModelForCausalLM,
    AutoModelForSeqaSeqLM,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    BitsAndBytesConfig,
    pipeline,
)
from transformers.testing_utils import (
    is_torch_available,
    require_accelerate,
    require_bitsandbytes,
    require_torch,
    require_torch_gpu,
    require_torch_multi_gpu,
    slow,
)







def 						lowerCamelCase__      ( __A    :Tuple		):


       """simple docstring"""




       if model.config.model_type == "gpt2":
              return model.transformer.h[0].mlp.c_fc
       return model.transformer.h[0].mlp.dense_ah_to_h


if is_torch_available():
    import torch
    import torch.nn as nn

    class     __snake_case    (				nn.Module  ):
           """simple docstring"""







           def __init__(		self      , _UpperCamelCase      , _UpperCamelCase   )      ->							Tuple:






                  """simple docstring"""


                  super().__init__()
                  __snake_case       	=							module
                  __snake_case       	=							nn.Sequential(
                      nn.Linear(module.in_features      , _UpperCamelCase      , bias=_UpperCamelCase   )      , nn.Linear(_UpperCamelCase      , module.out_features      , bias=_UpperCamelCase   )      , )
                  __snake_case       	=							(2.0 / (5 * min(module.in_features      , module.out_features   ))) ** 0.5
                  nn.init.normal_(self.adapter[0].weight      , std=_UpperCamelCase   )
                  nn.init.zeros_(self.adapter[1].weight   )
                  self.adapter.to(module.weight.device   )






           def 			a		(		self      , _UpperCamelCase      , *_UpperCamelCase      , **_UpperCamelCase   )      ->							List[str]:






                  """simple docstring"""


                  return self.module(_UpperCamelCase      , *_UpperCamelCase      , **_UpperCamelCase   ) + self.adapter(_UpperCamelCase   )

@require_bitsandbytes
@require_accelerate
@require_torch
@require_torch_gpu
@slow
class     __snake_case    (				unittest.TestCase  ):
       """simple docstring"""







       __SCREAMING_SNAKE_CASE				    =							"bigscience/bloom-1b7"

       # Constant values
       __SCREAMING_SNAKE_CASE				    =							2.1_09_65_95_52_69_25_74

       __SCREAMING_SNAKE_CASE				    =							"Hello my name is"
       __SCREAMING_SNAKE_CASE				    =							set()
       EXPECTED_OUTPUTS.add("Hello my name is John and I am a professional photographer. I"  )
       EXPECTED_OUTPUTS.add("Hello my name is John.\nI am a friend of your father.\n"  )
       EXPECTED_OUTPUTS.add("Hello my name is John Doe, I am a student at the University"  )
       __SCREAMING_SNAKE_CASE				    =							10


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






              """simple docstring"""


              __snake_case       	=							AutoTokenizer.from_pretrained(self.model_name   )






class     __snake_case    (				snake_case__  ):
       """simple docstring"""







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






              """simple docstring"""


              super().setUp()

              # Models and tokenizer
              __snake_case       	=							AutoModelForCausalLM.from_pretrained(
                  self.model_name      , torch_dtype=torch.floataa      , device_map="""auto"""   )
              __snake_case       	=							AutoModelForCausalLM.from_pretrained(self.model_name      , load_in_abit=_UpperCamelCase      , device_map="""auto"""   )


       def 			a		(		self   )      ->							Any:






              """simple docstring"""


              del self.model_fpaa
              del self.model_abit

              gc.collect()
              torch.cuda.empty_cache()


       def 			a		(		self   )      ->							Tuple:






              """simple docstring"""


              __snake_case       	=							self.model_abit.config

              self.assertTrue(hasattr(_UpperCamelCase      , """quantization_config"""   )   )

              __snake_case       	=							config.to_dict()
              __snake_case       	=							config.to_diff_dict()

              __snake_case       	=							config.to_json_string()


       def 			a		(		self   )      ->							Dict:






              """simple docstring"""


              from bitsandbytes.nn import Paramsabit

              __snake_case       	=							self.model_fpaa.get_memory_footprint()
              __snake_case       	=							self.model_abit.get_memory_footprint()

              self.assertAlmostEqual(mem_fpaa / mem_abit      , self.EXPECTED_RELATIVE_DIFFERENCE   )
              __snake_case       	=							get_some_linear_layer(self.model_abit   )
              self.assertTrue(linear.weight.__class__ == Paramsabit   )


       def 			a		(		self   )      ->							Any:






              """simple docstring"""


              from transformers import TaPreTrainedModel

              self.model_fpaa.get_memory_footprint()
              self.model_abit.get_memory_footprint()

              for name, module in self.model_abit.named_modules():
                     if isinstance(_UpperCamelCase      , torch.nn.Linear   ):
                            if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules:
                                   # 4-bit parameters are packed in uint8 variables
                                   self.assertTrue(module.weight.dtype == torch.uinta   )


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






              """simple docstring"""


              __snake_case       	=							self.tokenizer(self.input_text      , return_tensors="""pt"""   )
              __snake_case       	=							self.model_abit.generate(input_ids=encoded_input["""input_ids"""].to(0   )      , max_new_tokens=10   )

              self.assertIn(self.tokenizer.decode(output_sequences[0]      , skip_special_tokens=_UpperCamelCase   )      , self.EXPECTED_OUTPUTS   )


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






              """simple docstring"""


              __snake_case       	=							BitsAndBytesConfig()
              __snake_case       	=							True

              __snake_case       	=							AutoModelForCausalLM.from_pretrained(
                  self.model_name      , quantization_config=_UpperCamelCase      , device_map="""auto"""   )

              __snake_case       	=							self.tokenizer(self.input_text      , return_tensors="""pt"""   )
              __snake_case       	=							model_abit_from_config.generate(
                  input_ids=encoded_input["""input_ids"""].to(0   )      , max_new_tokens=10   )

              self.assertIn(self.tokenizer.decode(output_sequences[0]      , skip_special_tokens=_UpperCamelCase   )      , self.EXPECTED_OUTPUTS   )


       def 			a		(		self   )      ->							int:






              """simple docstring"""


              with self.assertRaises(_UpperCamelCase   ), tempfile.TemporaryDirectory() as tmpdirname:
                     self.model_abit.save_pretrained(_UpperCamelCase   )


       def 			a		(		self   )      ->							Optional[Any]:






              """simple docstring"""


              __snake_case       	=							BitsAndBytesConfig()

              with self.assertRaises(_UpperCamelCase   ):
                     __snake_case       	=							AutoModelForCausalLM.from_pretrained(
                         self.model_name      , quantization_config=_UpperCamelCase      , load_in_abit=_UpperCamelCase      , device_map="""auto"""      , bnb_abit_quant_type="""nf4"""      , )


       def 			a		(		self   )      ->							List[Any]:






              """simple docstring"""


              with self.assertRaises(_UpperCamelCase   ):
                     # Tries with `str`
                     self.model_abit.to("""cpu"""   )

              with self.assertRaises(_UpperCamelCase   ):
                     # Tries with a `dtype``
                     self.model_abit.to(torch.floataa   )

              with self.assertRaises(_UpperCamelCase   ):
                     # Tries with a `device`
                     self.model_abit.to(torch.device("""cuda:0"""   )   )

              with self.assertRaises(_UpperCamelCase   ):
                     # Tries with a `device`
                     self.model_abit.float()

              with self.assertRaises(_UpperCamelCase   ):
                     # Tries with a `device`
                     self.model_abit.half()

              # Test if we did not break anything
              __snake_case       	=							self.tokenizer(self.input_text      , return_tensors="""pt"""   )

              __snake_case       	=							self.model_fpaa.to(torch.floataa   )
              __snake_case       	=							self.model_fpaa.generate(input_ids=encoded_input["""input_ids"""].to(0   )      , max_new_tokens=10   )

              # Check this does not throw an error
              __snake_case       	=							self.model_fpaa.to("""cpu"""   )

              # Check this does not throw an error
              __snake_case       	=							self.model_fpaa.half()

              # Check this does not throw an error
              __snake_case       	=							self.model_fpaa.float()






       def 			a		(		self   )      ->							Dict:






              """simple docstring"""


              __snake_case       	=							AutoModelForSeqaSeqLM.from_pretrained("""t5-small"""      , load_in_abit=_UpperCamelCase      , device_map="""auto"""   )
              self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa   )






@require_bitsandbytes
@require_accelerate
@require_torch
@require_torch_gpu
@slow
class     __snake_case    (				unittest.TestCase  ):
       """simple docstring"""







       @classmethod
       def 			a		(		cls   )      ->							List[str]:






              """simple docstring"""


              __snake_case       	=							"""t5-small"""
              __snake_case       	=							"""google/flan-t5-small"""  # flan-t5 uses dense-act instead of dense-relu-dense
              __snake_case       	=							AutoTokenizer.from_pretrained(cls.model_name   )
              __snake_case       	=							"""Translate in German: Hello, my dog is cute"""


       def 			a		(		self   )      ->							Tuple:






              """simple docstring"""


              gc.collect()
              torch.cuda.empty_cache()


       def 			a		(		self   )      ->							Dict:






              """simple docstring"""


              from transformers import TaForConditionalGeneration

              __snake_case       	=							TaForConditionalGeneration._keep_in_fpaa_modules
              __snake_case       	=							None

              # test with `t5-small`
              __snake_case       	=							TaForConditionalGeneration.from_pretrained(self.model_name      , load_in_abit=_UpperCamelCase      , device_map="""auto"""   )
              __snake_case       	=							self.tokenizer(self.input_text      , return_tensors="""pt"""   ).to(0   )
              __snake_case       	=							model.generate(**_UpperCamelCase   )

              # test with `flan-t5-small`
              __snake_case       	=							TaForConditionalGeneration.from_pretrained(
                  self.dense_act_model_name      , load_in_abit=_UpperCamelCase      , device_map="""auto"""   )
              __snake_case       	=							self.tokenizer(self.input_text      , return_tensors="""pt"""   ).to(0   )
              __snake_case       	=							model.generate(**_UpperCamelCase   )
              __snake_case       	=							modules






       def 			a		(		self   )      ->							Tuple:






              """simple docstring"""


              import bitsandbytes as bnb

              from transformers import TaForConditionalGeneration

              # test with `t5-small`
              __snake_case       	=							TaForConditionalGeneration.from_pretrained(self.model_name      , load_in_abit=_UpperCamelCase      , device_map="""auto"""   )

              # there was a bug with decoders - this test checks that it is fixed
              self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q      , bnb.nn.Linearabit   )   )

              __snake_case       	=							self.tokenizer(self.input_text      , return_tensors="""pt"""   ).to(0   )
              __snake_case       	=							model.generate(**_UpperCamelCase   )

              # test with `flan-t5-small`
              __snake_case       	=							TaForConditionalGeneration.from_pretrained(
                  self.dense_act_model_name      , load_in_abit=_UpperCamelCase      , device_map="""auto"""   )
              __snake_case       	=							self.tokenizer(self.input_text      , return_tensors="""pt"""   ).to(0   )
              __snake_case       	=							model.generate(**_UpperCamelCase   )






class     __snake_case    (				snake_case__  ):
       """simple docstring"""







       def 			a		(		self   )      ->							Optional[Any]:






              """simple docstring"""


              super().setUp()
              # model_name
              __snake_case       	=							"""bigscience/bloom-560m"""
              __snake_case       	=							"""t5-small"""

              # Different types of model

              __snake_case       	=							AutoModel.from_pretrained(self.model_name      , load_in_abit=_UpperCamelCase      , device_map="""auto"""   )
              # Sequence classification model
              __snake_case       	=							AutoModelForSequenceClassification.from_pretrained(
                  self.model_name      , load_in_abit=_UpperCamelCase      , device_map="""auto"""   )
              # CausalLM model
              __snake_case       	=							AutoModelForCausalLM.from_pretrained(self.model_name      , load_in_abit=_UpperCamelCase      , device_map="""auto"""   )
              # Seq2seq model
              __snake_case       	=							AutoModelForSeqaSeqLM.from_pretrained(
                  self.seq_to_seq_name      , load_in_abit=_UpperCamelCase      , device_map="""auto"""   )


       def 			a		(		self   )      ->							Dict:






              """simple docstring"""


              del self.base_model
              del self.sequence_model
              del self.model_abit
              del self.seq_to_seq_model

              gc.collect()
              torch.cuda.empty_cache()






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






              """simple docstring"""


              from bitsandbytes.nn import Paramsabit

              self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit   )

              # Other heads should be nn.Parameter
              self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter   )
              self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter   )
              self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter   )






class     __snake_case    (				snake_case__  ):
       """simple docstring"""







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






              """simple docstring"""


              super().setUp()


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






              """simple docstring"""


              del self.pipe

              gc.collect()
              torch.cuda.empty_cache()






       def 			a		(		self   )      ->							Tuple:






              """simple docstring"""


              __snake_case       	=							pipeline(
                  """text-generation"""      , model=self.model_name      , model_kwargs={"""device_map""": """auto""", """load_in_4bit""": True, """torch_dtype""": torch.floataa}      , max_new_tokens=self.MAX_NEW_TOKENS      , )

              # Real second forward pass
              __snake_case       	=							self.pipe(self.input_text   )
              self.assertIn(pipeline_output[0]["""generated_text"""]      , self.EXPECTED_OUTPUTS   )






@require_torch_multi_gpu
class     __snake_case    (				snake_case__  ):
       """simple docstring"""







       def 			a		(		self   )      ->							Tuple:






              """simple docstring"""


              super().setUp()






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






              """simple docstring"""


              __snake_case       	=							AutoModelForCausalLM.from_pretrained(
                  self.model_name      , load_in_abit=_UpperCamelCase      , device_map="""balanced"""   )

              # Check correct device map
              self.assertEqual(set(model_parallel.hf_device_map.values()   )      , {0, 1}   )

              # Check that inference pass works on the model
              __snake_case       	=							self.tokenizer(self.input_text      , return_tensors="""pt"""   )

              # Second real batch
              __snake_case       	=							model_parallel.generate(input_ids=encoded_input["""input_ids"""].to(0   )      , max_new_tokens=10   )
              self.assertIn(self.tokenizer.decode(output_parallel[0]      , skip_special_tokens=_UpperCamelCase   )      , self.EXPECTED_OUTPUTS   )






class     __snake_case    (				snake_case__  ):
       """simple docstring"""







       def 			a		(		self   )      ->							List[Any]:






              """simple docstring"""


              __snake_case       	=							"""facebook/opt-350m"""
              super().setUp()






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






              """simple docstring"""


              if version.parse(importlib.metadata.version("""bitsandbytes"""   )   ) < version.parse("""0.37.0"""   ):
                     return

              # Step 1: freeze all parameters
              __snake_case       	=							AutoModelForCausalLM.from_pretrained(self.model_name      , load_in_abit=_UpperCamelCase   )

              self.assertEqual(set(model.hf_device_map.values()   )      , {torch.cuda.current_device()}   )

              for param in model.parameters():
                     __snake_case       	=							False  # freeze the model - train adapters later
                     if param.ndim == 1:
                            # cast the small parameters (e.g. layernorm) to fp32 for stability
                            __snake_case       	=							param.data.to(torch.floataa   )

        # Step 2: add adapters
              for _, module in model.named_modules():
                     if "OPTAttention" in repr(type(_UpperCamelCase   )   ):
                            __snake_case       	=							LoRALayer(module.q_proj      , rank=16   )
                            __snake_case       	=							LoRALayer(module.k_proj      , rank=16   )
                            __snake_case       	=							LoRALayer(module.v_proj      , rank=16   )

        # Step 3: dummy batch
              __snake_case       	=							self.tokenizer("""Test batch """      , return_tensors="""pt"""   ).to(0   )

              # Step 4: Check if the gradient is not None
              with torch.cuda.amp.autocast():
                     __snake_case       	=							model.forward(**_UpperCamelCase   )
                     out.logits.norm().backward()

              for module in model.modules():
                     if isinstance(_UpperCamelCase      , _UpperCamelCase   ):
                            self.assertTrue(module.adapter[1].weight.grad is not None   )
                            self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0   )
                     elif isinstance(_UpperCamelCase      , nn.Embedding   ):
                            self.assertTrue(module.weight.grad is None   )






class     __snake_case    (				snake_case__  ):
       """simple docstring"""







       __SCREAMING_SNAKE_CASE				    =							"gpt2-xl"
       __SCREAMING_SNAKE_CASE				    =							3.31_91_85_48_54_15_21_87




# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from pathlib import Path

import torch

from ...utils import is_npu_available, is_xpu_available
from .config_args import ClusterConfig, default_json_config_file
from .config_utils import SubcommandHelpFormatter


UpperCamelCase__		 =     '''Create a default config file for Accelerate with only a few flags set.'''







def 						lowerCamelCase__      ( __A    :List[Any]="no"	,__A    :str = default_json_config_file	,__A    :bool = False		):


       """simple docstring"""




       __snake_case       	=							Path(__A		)
       path.parent.mkdir(parents=__A	,exist_ok=__A		)
       if path.exists():
              print(
                  F'Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.'		)
              return False
       __snake_case       	=							mixed_precision.lower()
       if mixed_precision not in ["no", "fp16", "bf16", "fp8"]:
              raise ValueError(
                  F'`mixed_precision` should be one of \'no\', \'fp16\', \'bf16\', or \'fp8\'. Received {mixed_precision}'		)
       __snake_case       	=							{
           """compute_environment""": """LOCAL_MACHINE""",
           """mixed_precision""": mixed_precision,
       }
       if torch.cuda.is_available():
              __snake_case       	=							torch.cuda.device_count()
              __snake_case       	=							num_gpus
              __snake_case       	=							False
              if num_gpus > 1:
                     __snake_case       	=							"""MULTI_GPU"""
              else:
                     __snake_case       	=							"""NO"""
       elif is_xpu_available() and use_xpu:
              __snake_case       	=							torch.xpu.device_count()
              __snake_case       	=							num_xpus
              __snake_case       	=							False
              if num_xpus > 1:
                     __snake_case       	=							"""MULTI_XPU"""
              else:
                     __snake_case       	=							"""NO"""
       elif is_npu_available():
              __snake_case       	=							torch.npu.device_count()
              __snake_case       	=							num_npus
              __snake_case       	=							False
              if num_npus > 1:
                     __snake_case       	=							"""MULTI_NPU"""
              else:
                     __snake_case       	=							"""NO"""
       else:
              __snake_case       	=							0
              __snake_case       	=							True
              __snake_case       	=							1
              __snake_case       	=							"""NO"""
       __snake_case       	=							ClusterConfig(**__A		)
       config.to_json_file(__A		)
       return path







def 						lowerCamelCase__      ( __A    :Dict	,__A    :List[Any]		):


       """simple docstring"""




       __snake_case       	=							parser.add_parser("""default"""	,parents=__A	,help=__A	,formatter_class=__A		)
       parser.add_argument(
           """--config_file"""	,default=__A	,help=(
               """The path to use to store the config file. Will default to a file named default_config.yaml in the cache """
               """location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have """
               """such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed """
               """with 'huggingface'."""
           )	,dest="""save_location"""	,)

       parser.add_argument(
           """--mixed_precision"""	,choices=["""no""", """fp16""", """bf16"""]	,type=__A	,help="""Whether or not to use mixed precision training. """
           """Choose between FP16 and BF16 (bfloat16) training. """
           """BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later."""	,default="""no"""	,)
       parser.set_defaults(func=__A		)
       return parser







def 						lowerCamelCase__      ( __A    :Optional[Any]		):


       """simple docstring"""




       __snake_case       	=							write_basic_config(args.mixed_precision	,args.save_location		)
       if config_file:
              print(F'accelerate configuration saved at {config_file}'		)

