


import json
import os
import tempfile
from unittest.mock import patch

import torch
from torch.utils.data import DataLoader, TensorDataset

from accelerate import DistributedType, infer_auto_device_map, init_empty_weights
from accelerate.accelerator import Accelerator
from accelerate.state import GradientState, PartialState
from accelerate.test_utils import require_bnb, require_multi_gpu, slow
from accelerate.test_utils.testing import AccelerateTestCase, require_cuda
from accelerate.utils import patch_environment





def __UpperCAmelCase       (		)						->					List[Any]:



       '''simple docstring'''





       UpperCAmelCase__										=     torch.nn.Linear(2 ,						4			)
       UpperCAmelCase__										=     torch.optim.AdamW(model.parameters() ,						lr=1.0			)
       UpperCAmelCase__										=     torch.optim.lr_scheduler.OneCycleLR(__A ,						max_lr=0.01 ,						steps_per_epoch=2 ,						epochs=1			)
       UpperCAmelCase__										=     DataLoader(TensorDataset(torch.tensor([1, 2, 3]			)			)			)
       UpperCAmelCase__										=     DataLoader(TensorDataset(torch.tensor([4, 5, 6]			)			)			)

       return model, optimizer, scheduler, train_dl, valid_dl





def __UpperCAmelCase       (		__A			)						->					Union[str, Any]:



       '''simple docstring'''





       return (model.weight.abs().sum() + model.bias.abs().sum()).item()





def __UpperCAmelCase       (		__A			)						->					List[str]:



       '''simple docstring'''





       UpperCAmelCase__										=     torch.nn.Linear(*tuple(model.weight.T.shape			)			).state_dict()
       model.load_state_dict(__A			)




class     lowercase__  (					__SCREAMING_SNAKE_CASE		):






  @require_cuda
  def 			_UpperCAmelCase  (					self      :					List[Any] ):




         """simple docstring"""







         UpperCAmelCase__										=     Accelerator()
         assert PartialState._shared_state["_cpu"] is False
         assert PartialState._shared_state["device"].type == "cuda"
         with self.assertRaises(_lowercase ):
                UpperCAmelCase__										=     Accelerator(cpu=_lowercase )






  def 			_UpperCAmelCase  (					self      :					Optional[int] ):




         """simple docstring"""







         UpperCAmelCase__										=     Accelerator()
         UpperCAmelCase__										=     GradientState()
         assert state.num_steps == 1
         UpperCAmelCase__										=     4
         assert state.num_steps == 4

         assert state.sync_gradients is True
         UpperCAmelCase__										=     False
         assert state.sync_gradients is False
         GradientState._reset_state()






  def 			_UpperCAmelCase  (					self      :					Any ):




         """simple docstring"""







         UpperCAmelCase__										=     Accelerator()
         UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__										=     create_components()

         (
             (
             UpperCAmelCase__
         )						,			(
             UpperCAmelCase__
         )						,			(
             UpperCAmelCase__
         )						,			(
             UpperCAmelCase__
         )						,			(
             UpperCAmelCase__
         )						,			
         )										=     accelerator.prepare(_lowercase		,						_lowercase		,						_lowercase		,						_lowercase		,						_lowercase )

         self.assertTrue(prepared_model in accelerator._models )
         self.assertTrue(prepared_optimizer in accelerator._optimizers )
         self.assertTrue(prepared_scheduler in accelerator._schedulers )
         self.assertTrue(prepared_train_dl in accelerator._dataloaders )
         self.assertTrue(prepared_valid_dl in accelerator._dataloaders )






  def 			_UpperCAmelCase  (					self      :					Dict ):




         """simple docstring"""







         UpperCAmelCase__										=     Accelerator()
         UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__										=     create_components()
         accelerator.prepare(_lowercase		,						_lowercase		,						_lowercase		,						_lowercase		,						_lowercase )
         accelerator.free_memory()

         self.assertTrue(len(accelerator._models ) == 0 )
         self.assertTrue(len(accelerator._optimizers ) == 0 )
         self.assertTrue(len(accelerator._schedulers ) == 0 )
         self.assertTrue(len(accelerator._dataloaders ) == 0 )






  def 			_UpperCAmelCase  (					self      :					int ):




         """simple docstring"""







         PartialState._reset_state()

         # Mock torch.cuda.set_device to avoid an exception as the device doesn't exist
         def noop(*_lowercase      :					Dict		,						**_lowercase      :					Any ):
                pass

         with patch("torch.cuda.set_device"		,						_lowercase ), patch_environment(ACCELERATE_TORCH_DEVICE="cuda:64" ):
                UpperCAmelCase__										=     Accelerator()
                self.assertEqual(str(accelerator.state.device )		,						"cuda:64" )






  def 			_UpperCAmelCase  (					self      :					str ):




         """simple docstring"""







         UpperCAmelCase__										=     Accelerator()
         UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__										=     create_components()
         accelerator.prepare(_lowercase		,						_lowercase		,						_lowercase		,						_lowercase		,						_lowercase )

         UpperCAmelCase__										=     get_signature(_lowercase )

         with tempfile.TemporaryDirectory() as tmpdirname:
                accelerator.save_state(_lowercase )

                # make sure random weights don't match
                load_random_weights(_lowercase )
                self.assertTrue(abs(model_signature - get_signature(_lowercase ) ) > 1E-3 )

                # make sure loaded weights match
                accelerator.load_state(_lowercase )
                self.assertTrue(abs(model_signature - get_signature(_lowercase ) ) < 1E-3 )






  def 			_UpperCAmelCase  (					self      :					Dict ):




         """simple docstring"""







         UpperCAmelCase__										=     Accelerator()
         UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__										=     create_components()
         accelerator.prepare(_lowercase		,						_lowercase		,						_lowercase		,						_lowercase		,						_lowercase )

         UpperCAmelCase__										=     get_signature(_lowercase )

         # saving hook
         def save_config(_lowercase      :					Optional[Any]		,						_lowercase      :					Tuple		,						_lowercase      :					int ):
                UpperCAmelCase__										=     {"class_name": models[0].__class__.__name__}

                with open(os.path.join(_lowercase		,						"data.json" )		,						"w" ) as f:
                       json.dump(_lowercase		,						_lowercase )

        # loading hook
         def load_config(_lowercase      :					List[str]		,						_lowercase      :					Optional[Any] ):
                with open(os.path.join(_lowercase		,						"data.json" )		,						"r" ) as f:
                       UpperCAmelCase__										=     json.load(_lowercase )

                UpperCAmelCase__										=     config["class_name"]

         UpperCAmelCase__										=     accelerator.register_save_state_pre_hook(_lowercase )
         UpperCAmelCase__										=     accelerator.register_load_state_pre_hook(_lowercase )

         with tempfile.TemporaryDirectory() as tmpdirname:
                accelerator.save_state(_lowercase )

                # make sure random weights don't match with hooks
                load_random_weights(_lowercase )
                self.assertTrue(abs(model_signature - get_signature(_lowercase ) ) > 1E-3 )

                # random class name to verify correct one is loaded
                UpperCAmelCase__										=     "random"

                # make sure loaded weights match with hooks
                accelerator.load_state(_lowercase )
                self.assertTrue(abs(model_signature - get_signature(_lowercase ) ) < 1E-3 )

                # mode.class_name is loaded from config
                self.assertTrue(model.class_name == model.__class__.__name__ )

         # remove hooks
         save_hook.remove()
         load_hook.remove()

         with tempfile.TemporaryDirectory() as tmpdirname:
                accelerator.save_state(_lowercase )

                # make sure random weights don't match with hooks removed
                load_random_weights(_lowercase )
                self.assertTrue(abs(model_signature - get_signature(_lowercase ) ) > 1E-3 )

                # random class name to verify correct one is loaded
                UpperCAmelCase__										=     "random"

                # make sure loaded weights match with hooks removed
                accelerator.load_state(_lowercase )
                self.assertTrue(abs(model_signature - get_signature(_lowercase ) ) < 1E-3 )

                # mode.class_name is NOT loaded from config
                self.assertTrue(model.class_name != model.__class__.__name__ )






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




         """simple docstring"""







         UpperCAmelCase__										=     Accelerator()
         UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__										=     create_components()
         UpperCAmelCase__										=     None

         # This should work
         UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__										=     accelerator.prepare(
             _lowercase		,						_lowercase		,						_lowercase		,						_lowercase		,						_lowercase		,						_lowercase )
         self.assertTrue(dummy_obj is None )






  def 			_UpperCAmelCase  (					self      :					Tuple ):




         """simple docstring"""







         UpperCAmelCase__										=     Accelerator()
         UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__										=     create_components()
         UpperCAmelCase__										=     [1, 2, 3]

         # This should work
         UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__						,			UpperCAmelCase__										=     accelerator.prepare(
             _lowercase		,						_lowercase		,						_lowercase		,						_lowercase		,						_lowercase		,						_lowercase )
         self.assertEqual(
             getattr(_lowercase		,						"_is_accelerate_prepared"		,						_lowercase )		,						_lowercase		,						"Dummy object should have `_is_accelerate_prepared` set to `True`"		,						)
         self.assertEqual(
             getattr(_lowercase		,						"_is_accelerate_prepared"		,						_lowercase )		,						_lowercase		,						"Model is missing `_is_accelerator_prepared` or is set to `False`"		,						)
         self.assertEqual(
             getattr(_lowercase		,						"_is_accelerate_prepared"		,						_lowercase )		,						_lowercase		,						"Optimizer is missing `_is_accelerator_prepared` or is set to `False`"		,						)
         self.assertEqual(
             getattr(_lowercase		,						"_is_accelerate_prepared"		,						_lowercase )		,						_lowercase		,						"Scheduler is missing `_is_accelerator_prepared` or is set to `False`"		,						)
         self.assertEqual(
             getattr(_lowercase		,						"_is_accelerate_prepared"		,						_lowercase )		,						_lowercase		,						"Train Dataloader is missing `_is_accelerator_prepared` or is set to `False`"		,						)
         self.assertEqual(
             getattr(_lowercase		,						"_is_accelerate_prepared"		,						_lowercase )		,						_lowercase		,						"Valid Dataloader is missing `_is_accelerator_prepared` or is set to `False`"		,						)






  @slow
  @require_bnb
  def 			_UpperCAmelCase  (					self      :					Optional[int] ):




         """simple docstring"""







         from transformers import AutoModelForCausalLM

         UpperCAmelCase__										=     AutoModelForCausalLM.from_pretrained(
             "EleutherAI/gpt-neo-125m"		,						load_in_abit=_lowercase		,						device_map={"": 0}		,						)
         UpperCAmelCase__										=     Accelerator()

         # This should work
         UpperCAmelCase__										=     accelerator.prepare(_lowercase )






  @slow
  @require_bnb
  def 			_UpperCAmelCase  (					self      :					List[Any] ):




         """simple docstring"""







         from transformers import AutoModelForCausalLM

         UpperCAmelCase__										=     Accelerator()

         with init_empty_weights():
                UpperCAmelCase__										=     AutoModelForCausalLM.from_pretrained(
                    "EleutherAI/gpt-neo-125m"		,						)
                model.tie_weights()
                UpperCAmelCase__										=     infer_auto_device_map(_lowercase )
                UpperCAmelCase__										=     "cpu"

         UpperCAmelCase__										=     AutoModelForCausalLM.from_pretrained(
             "EleutherAI/gpt-neo-125m"		,						device_map=_lowercase		,						load_in_abit=_lowercase		,						llm_inta_enable_fpaa_cpu_offload=_lowercase )

         # This should not work and get value error
         with self.assertRaises(_lowercase ):
                UpperCAmelCase__										=     accelerator.prepare(_lowercase )






  @slow
  @require_bnb
  @require_multi_gpu
  def 			_UpperCAmelCase  (					self      :					int ):




         """simple docstring"""







         from transformers import AutoModelForCausalLM

         UpperCAmelCase__										=     {"distributed_type": DistributedType.MULTI_GPU}

         with init_empty_weights():
                UpperCAmelCase__										=     AutoModelForCausalLM.from_pretrained(
                    "EleutherAI/gpt-neo-125m"		,						)
                model.tie_weights()
                UpperCAmelCase__										=     infer_auto_device_map(_lowercase )
                UpperCAmelCase__										=     1

         UpperCAmelCase__										=     AutoModelForCausalLM.from_pretrained(
             "EleutherAI/gpt-neo-125m"		,						load_in_abit=_lowercase		,						device_map=_lowercase		,						)
         UpperCAmelCase__										=     Accelerator()

         # This should not work and get value error
         with self.assertRaises(_lowercase ):
                UpperCAmelCase__										=     accelerator.prepare(_lowercase )

         PartialState._reset_state()






  @slow
  @require_bnb
  @require_multi_gpu
  def 			_UpperCAmelCase  (					self      :					Any ):




         """simple docstring"""







         from transformers import AutoModelForCausalLM

         with init_empty_weights():
                UpperCAmelCase__										=     AutoModelForCausalLM.from_pretrained(
                    "EleutherAI/gpt-neo-125m"		,						)
                UpperCAmelCase__										=     infer_auto_device_map(_lowercase )
                UpperCAmelCase__										=     1

         UpperCAmelCase__										=     AutoModelForCausalLM.from_pretrained(
             "EleutherAI/gpt-neo-125m"		,						load_in_abit=_lowercase		,						device_map=_lowercase		,						)
         UpperCAmelCase__										=     Accelerator()

         # This should work
         UpperCAmelCase__										=     accelerator.prepare(_lowercase )






  @require_cuda
  def 			_UpperCAmelCase  (					self      :					Optional[int] ):




         """simple docstring"""







         UpperCAmelCase__										=     torch.nn.Linear(10		,						10 )
         UpperCAmelCase__										=     torch.optim.SGD(model.parameters()		,						lr=0.0_1 )
         UpperCAmelCase__										=     Accelerator(cpu=_lowercase )
         UpperCAmelCase__										=     accelerator.prepare(_lowercase )









import uuid
from typing import Any, Dict, List, Optional, Union

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


if is_tf_available():
    import tensorflow as tf

if is_torch_available():
    import torch


A      = logging.get_logger(__name__)


class     lowercase__  :






  def __init__(					self      :					List[str]		,						_lowercase      :					str = None		,						_lowercase      :					uuid.UUID = None		,						_lowercase      :					Dict=None		,						_lowercase      :					Any=None ):




         """simple docstring"""







         if not conversation_id:
                UpperCAmelCase__										=     uuid.uuida()
         if past_user_inputs is None:
                UpperCAmelCase__										=     []
         if generated_responses is None:
                UpperCAmelCase__										=     []

         UpperCAmelCase__										=     conversation_id
         UpperCAmelCase__										=     past_user_inputs
         UpperCAmelCase__										=     generated_responses
         UpperCAmelCase__										=     text






  def __eq__(					self      :					Any		,						_lowercase      :					str ):




         """simple docstring"""







         if not isinstance(_lowercase		,						_lowercase ):
                return False
         if self.uuid == other.uuid:
                return True
         return (
             self.new_user_input == other.new_user_input
             and self.past_user_inputs == other.past_user_inputs
             and self.generated_responses == other.generated_responses
         )






  def 			_UpperCAmelCase  (					self      :					Any		,						_lowercase      :					str		,						_lowercase      :					bool = False ):




         """simple docstring"""







         if self.new_user_input:
                if overwrite:
                       logger.warning(
                           F"""User input added while unprocessed input was existing: \"{self.new_user_input}\" was overwritten """
                           F"""with: \"{text}\".""" )
                       UpperCAmelCase__										=     text
                else:
                       logger.warning(
                           F"""User input added while unprocessed input was existing: \"{self.new_user_input}\" new input """
                           F"""ignored: \"{text}\". Set `overwrite` to True to overwrite unprocessed user input""" )
         else:
                UpperCAmelCase__										=     text






  def 			_UpperCAmelCase  (					self      :					int ):




         """simple docstring"""







         if self.new_user_input:
                self.past_user_inputs.append(self.new_user_input )
         UpperCAmelCase__										=     None






  def 			_UpperCAmelCase  (					self      :					List[str]		,						_lowercase      :					str ):




         """simple docstring"""







         self.generated_responses.append(_lowercase )






  def 			_UpperCAmelCase  (					self      :					List[str] ):




         """simple docstring"""







         for user_input, generated_response in zip(self.past_user_inputs		,						self.generated_responses ):
                yield True, user_input
                yield False, generated_response
         if self.new_user_input:
                yield True, self.new_user_input






  def __repr__(					self      :					List[Any] ):




         """simple docstring"""







         UpperCAmelCase__										=     F"""Conversation id: {self.uuid} \n"""
         for is_user, text in self.iter_texts():
                UpperCAmelCase__										=     "user" if is_user else "bot"
                output += F"""{name} >> {text} \n"""
         return output




@add_end_docstrings(
    __SCREAMING_SNAKE_CASE					,							R'\n        min_length_for_response (`int`, *optional*, defaults to 32):\n            The minimum length (in number of tokens) for a response.\n        minimum_tokens (`int`, *optional*, defaults to 10):\n            The minimum length of tokens to leave for a response.\n    '					,							)
class     lowercase__  (					__SCREAMING_SNAKE_CASE		):






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




         """simple docstring"""







         super().__init__(*_lowercase		,						**_lowercase )
         if self.tokenizer.pad_token_id is None:
                UpperCAmelCase__										=     self.tokenizer.eos_token






  def 			_UpperCAmelCase  (					self      :					List[str]		,						_lowercase      :					int=None		,						_lowercase      :					Any=None		,						_lowercase      :					List[str]=None		,						**_lowercase      :					Dict ):




         """simple docstring"""







         UpperCAmelCase__										=     {}
         UpperCAmelCase__										=     {}
         UpperCAmelCase__										=     {}

         if min_length_for_response is not None:
                UpperCAmelCase__										=     min_length_for_response
         if minimum_tokens is not None:
                UpperCAmelCase__										=     minimum_tokens

         if "max_length" in generate_kwargs:
                UpperCAmelCase__										=     generate_kwargs["max_length"]
                # self.max_length = generate_kwargs.get("max_length", self.model.config.max_length)
         if clean_up_tokenization_spaces is not None:
                UpperCAmelCase__										=     clean_up_tokenization_spaces

         if generate_kwargs:
                forward_params.update(_lowercase )
         return preprocess_params, forward_params, postprocess_params






  def __call__(					self      :					Dict		,						_lowercase      :					Union[Conversation, List[Conversation]]		,						_lowercase      :					List[str]=0		,						**_lowercase      :					Optional[int] ):




         """simple docstring"""







         UpperCAmelCase__										=     super().__call__(_lowercase		,						num_workers=_lowercase		,						**_lowercase )
         if isinstance(_lowercase		,						_lowercase ) and len(_lowercase ) == 1:
                return outputs[0]
         return outputs






  def 			_UpperCAmelCase  (					self      :					Optional[Any]		,						_lowercase      :					Conversation		,						_lowercase      :					List[Any]=32 ):




         """simple docstring"""







         if not isinstance(_lowercase		,						_lowercase ):
                raise ValueError("ConversationalPipeline, expects Conversation as inputs" )
         if conversation.new_user_input is None:
                raise ValueError(
                    F"""Conversation with UUID {type(conversation.uuid )} does not contain new user input to process. """
                    "Add user inputs with the conversation's `add_user_input` method" )
         if hasattr(self.tokenizer		,						"_build_conversation_input_ids" ):
                UpperCAmelCase__										=     self.tokenizer._build_conversation_input_ids(_lowercase )
         else:
                # If the tokenizer cannot handle conversations, we default to only the old version
                UpperCAmelCase__										=     self._legacy_parse_and_tokenize(_lowercase )

         if self.framework == "pt":
                UpperCAmelCase__										=     torch.LongTensor([input_ids] )
         elif self.framework == "tf":
                UpperCAmelCase__										=     tf.constant([input_ids] )
         return {"input_ids": input_ids, "conversation": conversation}






  def 			_UpperCAmelCase  (					self      :					Optional[Any]		,						_lowercase      :					List[Any]		,						_lowercase      :					List[Any]=10		,						**_lowercase      :					Optional[Any] ):




         """simple docstring"""







         UpperCAmelCase__										=     generate_kwargs.get("max_length"		,						self.model.config.max_length )

         UpperCAmelCase__										=     model_inputs["input_ids"].shape[1]
         if max_length - minimum_tokens < n:
                logger.warning(F"""Conversation input is to long ({n}), trimming it to ({max_length} - {minimum_tokens})""" )
                UpperCAmelCase__										=     max_length - minimum_tokens
                UpperCAmelCase__										=     model_inputs["input_ids"][:, -trim:]
                if "attention_mask" in model_inputs:
                       UpperCAmelCase__										=     model_inputs["attention_mask"][:, -trim:]
         UpperCAmelCase__										=     model_inputs.pop("conversation" )
         UpperCAmelCase__										=     max_length
         UpperCAmelCase__										=     self.model.generate(**_lowercase		,						**_lowercase )
         if self.model.config.is_encoder_decoder:
                UpperCAmelCase__										=     1
         else:
                UpperCAmelCase__										=     n
         return {"output_ids": output_ids[:, start_position:], "conversation": conversation}






  def 			_UpperCAmelCase  (					self      :					Tuple		,						_lowercase      :					Union[str, Any]		,						_lowercase      :					Optional[Any]=True ):




         """simple docstring"""







         UpperCAmelCase__										=     model_outputs["output_ids"]
         UpperCAmelCase__										=     self.tokenizer.decode(
             output_ids[0]		,						skip_special_tokens=_lowercase		,						clean_up_tokenization_spaces=_lowercase		,						)
         UpperCAmelCase__										=     model_outputs["conversation"]
         conversation.mark_processed()
         conversation.append_response(_lowercase )
         return conversation






  def 			_UpperCAmelCase  (					self      :					List[str]		,						_lowercase      :					Conversation ):




         """simple docstring"""







         UpperCAmelCase__										=     self.tokenizer.eos_token_id
         UpperCAmelCase__										=     []
         for is_user, text in conversation.iter_texts():
                if eos_token_id is not None:
                       input_ids.extend(self.tokenizer.encode(_lowercase		,						add_special_tokens=_lowercase ) + [eos_token_id] )
                else:
                       input_ids.extend(self.tokenizer.encode(_lowercase		,						add_special_tokens=_lowercase ) )

         if len(_lowercase ) > self.tokenizer.model_max_length:
                UpperCAmelCase__										=     input_ids[-self.tokenizer.model_max_length :]
         return input_ids





