
'''simple docstring'''






import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock

import torch

from ..state import AcceleratorState, PartialState
from ..utils import (
    gather,
    is_bnb_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_mps_available,
    is_safetensors_available,
    is_tensorboard_available,
    is_torch_version,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)







def 		A_							(						_lowerCAmelCase :     Optional[int]					,						_lowerCAmelCase :     List[str]=False				):



      """simple docstring"""




      try:
            _lowerCamelCase					: Tuple		    = os.environ[key]
      except KeyError:
            # KEY isn't set, default to `default`.
            _lowerCamelCase					: str		    = default
      else:
            # KEY is set, convert it to True or False.
            try:
                  _lowerCamelCase					: Optional[int]		    = strtobool(_lowerCAmelCase				)
            except ValueError:
                  # More values are supported, but let's keep the message simple.
                  raise ValueError(F'If set, {key} must be yes or no.'				)
      return _value


UpperCAmelCase_							: Any =							parse_flag_from_env('RUN_SLOW', default=False)







def 		A_							(						_lowerCAmelCase :     List[Any]				):



      """simple docstring"""




      return unittest.skip("Test was skipped"				)(_lowerCAmelCase				)







def 		A_							(						_lowerCAmelCase :     str				):



      """simple docstring"""




      return unittest.skipUnless(_run_slow_tests					,						"test is slow"				)(_lowerCAmelCase				)







def 		A_							(						_lowerCAmelCase :     Union[str, Any]				):



      """simple docstring"""




      return unittest.skipUnless(not torch.cuda.is_available()					,						"test requires only a CPU"				)(_lowerCAmelCase				)







def 		A_							(						_lowerCAmelCase :     Optional[Any]				):



      """simple docstring"""




      return unittest.skipUnless(torch.cuda.is_available()					,						"test requires a GPU"				)(_lowerCAmelCase				)







def 		A_							(						_lowerCAmelCase :     Optional[int]				):



      """simple docstring"""




      return unittest.skipUnless(is_xpu_available()					,						"test requires a XPU"				)(_lowerCAmelCase				)







def 		A_							(						_lowerCAmelCase :     Tuple				):



      """simple docstring"""




      return unittest.skipUnless(is_mps_available()					,						"test requires a `mps` backend support in `torch`"				)(_lowerCAmelCase				)







def 		A_							(						_lowerCAmelCase :     Tuple				):



      """simple docstring"""




      return unittest.skipUnless(
          is_transformers_available() and is_datasets_available()					,						"test requires the Hugging Face suite"				)(_lowerCAmelCase				)







def 		A_							(						_lowerCAmelCase :     Tuple				):



      """simple docstring"""




      return unittest.skipUnless(is_bnb_available()					,						"test requires the bitsandbytes library"				)(_lowerCAmelCase				)







def 		A_							(						_lowerCAmelCase :     Tuple				):



      """simple docstring"""




      return unittest.skipUnless(is_tpu_available()					,						"test requires TPU"				)(_lowerCAmelCase				)







def 		A_							(						_lowerCAmelCase :     Optional[Any]				):



      """simple docstring"""




      return unittest.skipUnless(torch.cuda.device_count() == 1					,						"test requires a GPU"				)(_lowerCAmelCase				)







def 		A_							(						_lowerCAmelCase :     Tuple				):



      """simple docstring"""




      return unittest.skipUnless(torch.xpu.device_count() == 1					,						"test requires a XPU"				)(_lowerCAmelCase				)







def 		A_							(						_lowerCAmelCase :     Optional[Any]				):



      """simple docstring"""




      return unittest.skipUnless(torch.cuda.device_count() > 1					,						"test requires multiple GPUs"				)(_lowerCAmelCase				)







def 		A_							(						_lowerCAmelCase :     Optional[int]				):



      """simple docstring"""




      return unittest.skipUnless(torch.xpu.device_count() > 1					,						"test requires multiple XPUs"				)(_lowerCAmelCase				)







def 		A_							(						_lowerCAmelCase :     Optional[Any]				):



      """simple docstring"""




      return unittest.skipUnless(is_safetensors_available()					,						"test requires safetensors"				)(_lowerCAmelCase				)







def 		A_							(						_lowerCAmelCase :     Optional[int]				):



      """simple docstring"""




      return unittest.skipUnless(is_deepspeed_available()					,						"test requires DeepSpeed"				)(_lowerCAmelCase				)







def 		A_							(						_lowerCAmelCase :     Optional[int]				):



      """simple docstring"""




      return unittest.skipUnless(is_torch_version(">="					,						"1.12.0"				)					,						"test requires torch version >= 1.12.0"				)(_lowerCAmelCase				)







def 		A_							(						_lowerCAmelCase :     List[Any]=None					,						_lowerCAmelCase :     Optional[int]=None				):



      """simple docstring"""




      if test_case is None:
            return partial(_lowerCAmelCase					,						version=_lowerCAmelCase				)
      return unittest.skipUnless(is_torch_version(">="					,						_lowerCAmelCase				)					,						F'test requires torch version >= {version}'				)(_lowerCAmelCase				)







def 		A_							(						_lowerCAmelCase :     List[str]				):



      """simple docstring"""




      return unittest.skipUnless(is_tensorboard_available()					,						"test requires Tensorboard"				)(_lowerCAmelCase				)







def 		A_							(						_lowerCAmelCase :     Optional[Any]				):



      """simple docstring"""




      return unittest.skipUnless(is_wandb_available()					,						"test requires wandb"				)(_lowerCAmelCase				)







def 		A_							(						_lowerCAmelCase :     Optional[int]				):



      """simple docstring"""




      return unittest.skipUnless(is_comet_ml_available()					,						"test requires comet_ml"				)(_lowerCAmelCase				)


UpperCAmelCase_							: Optional[Any] =							(
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)







def 		A_							(						_lowerCAmelCase :     Dict				):



      """simple docstring"""




      return unittest.skipUnless(
          _atleast_one_tracker_available					,						"test requires at least one tracker to be available and for `comet_ml` to not be installed"					,						)(_lowerCAmelCase				)

class 			UpperCAmelCase__    (							unittest.TestCase			):
    lowerCAmelCase_					     =		True



    @classmethod
    def 	lowerCamelCase_	(						cls   :							Any  ):
          _lowerCamelCase					: List[str]		    = tempfile.mkdtemp()



    @classmethod
    def 	lowerCamelCase_	(						cls   :							Tuple  ):
          if os.path.exists(cls.tmpdir  ):
                shutil.rmtree(cls.tmpdir  )



    def 	lowerCamelCase_	(						self   :							Optional[int]  ):
          if self.clear_on_setup:
                for path in Path(self.tmpdir  ).glob("**/*"  ):
                      if path.is_file():
                            path.unlink()
                      elif path.is_dir():
                            shutil.rmtree(__A  )


class 			UpperCAmelCase__    (							unittest.TestCase			):



    def 	lowerCamelCase_	(						self   :							Any  ):
          super().tearDown()
          # Reset the state of the AcceleratorState singleton.
          AcceleratorState._reset_state()
          PartialState._reset_state()


class 			UpperCAmelCase__    (							unittest.TestCase			):



    def 	lowerCamelCase_	(						self   :							int,__A   :							Union[mock.Mock, List[mock.Mock]]  ):
          _lowerCamelCase					: Tuple		    = mocks if isinstance(__A,(tuple, list)  ) else [mocks]
          for m in self.mocks:
                m.start()
                self.addCleanup(m.stop  )







def 		A_							(						_lowerCAmelCase :     Any				):



      """simple docstring"""




      _lowerCamelCase					: Tuple		    = AcceleratorState()
      _lowerCamelCase					: str		    = tensor[None].clone().to(state.device				)
      _lowerCamelCase					: List[Any]		    = gather(_lowerCAmelCase				).cpu()
      _lowerCamelCase					: Optional[Any]		    = tensor[0].cpu()
      for i in range(tensors.shape[0]				):
            if not torch.equal(tensors[i]					,						_lowerCAmelCase				):
                  return False
      return True

class 			UpperCAmelCase__    :



    def __init__(						self   :							int,__A   :							Any,__A   :							List[Any],__A   :							str  ):
          _lowerCamelCase					: Tuple		    = returncode
          _lowerCamelCase					: List[str]		    = stdout
          _lowerCamelCase					: Any		    = stderr







async def 		A_							(						_lowerCAmelCase :     Tuple					,						_lowerCAmelCase :     int				):



      """simple docstring"""




      while True:
            _lowerCamelCase					: Optional[Any]		    = await stream.readline()
            if line:
                  callback(_lowerCAmelCase				)
            else:
                  break







async def 		A_							(						_lowerCAmelCase :     Optional[Any]					,						_lowerCAmelCase :     Union[str, Any]=None					,						_lowerCAmelCase :     Dict=None					,						_lowerCAmelCase :     List[str]=None					,						_lowerCAmelCase :     List[Any]=False					,						_lowerCAmelCase :     Optional[int]=False				):



      """simple docstring"""




      if echo:
            print("\nRunning: "					,						" ".join(_lowerCAmelCase				)				)

      _lowerCamelCase					: List[str]		    = await asyncio.create_subprocess_exec(
          cmd[0]					,						*cmd[1:]					,						stdin=_lowerCAmelCase					,						stdout=asyncio.subprocess.PIPE					,						stderr=asyncio.subprocess.PIPE					,						env=_lowerCAmelCase					,						)

      # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
      # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
      #
      # If it starts hanging, will need to switch to the following code. The problem is that no data
      # will be seen until it's done and if it hangs for example there will be no debug info.
      # out, err = await p.communicate()
      # return _RunOutput(p.returncode, out, err)

      _lowerCamelCase					: List[Any]		    = []
      _lowerCamelCase					: List[str]		    = []

      def tee(_lowerCAmelCase :     int					,						_lowerCAmelCase :     Union[str, Any]					,						_lowerCAmelCase :     int					,						_lowerCAmelCase :     int=""				):
            _lowerCamelCase					: Optional[Any]		    = line.decode("utf-8"				).rstrip()
            sink.append(_lowerCAmelCase				)
            if not quiet:
                  print(_lowerCAmelCase					,						_lowerCAmelCase					,						file=_lowerCAmelCase				)

    # XXX: the timeout doesn't seem to make any difference here
      await asyncio.wait(
          [
              asyncio.create_task(_read_stream(p.stdout					,						lambda _lowerCAmelCase				: tee(_lowerCAmelCase					,						_lowerCAmelCase					,						sys.stdout					,						label="stdout:"				)				)				),
              asyncio.create_task(_read_stream(p.stderr					,						lambda _lowerCAmelCase				: tee(_lowerCAmelCase					,						_lowerCAmelCase					,						sys.stderr					,						label="stderr:"				)				)				),
          ]					,						timeout=_lowerCAmelCase					,						)
      return _RunOutput(await p.wait()					,						_lowerCAmelCase					,						_lowerCAmelCase				)







def 		A_							(						_lowerCAmelCase :     Tuple					,						_lowerCAmelCase :     int=None					,						_lowerCAmelCase :     int=None					,						_lowerCAmelCase :     List[Any]=180					,						_lowerCAmelCase :     Tuple=False					,						_lowerCAmelCase :     Optional[Any]=True				):



      """simple docstring"""




      _lowerCamelCase					: Dict		    = asyncio.get_event_loop()
      _lowerCamelCase					: List[Any]		    = loop.run_until_complete(
          _stream_subprocess(_lowerCAmelCase					,						env=_lowerCAmelCase					,						stdin=_lowerCAmelCase					,						timeout=_lowerCAmelCase					,						quiet=_lowerCAmelCase					,						echo=_lowerCAmelCase				)				)

      _lowerCamelCase					: List[str]		    = " ".join(_lowerCAmelCase				)
      if result.returncode > 0:
            _lowerCamelCase					: int		    = "\n".join(result.stderr				)
            raise RuntimeError(
                F'\'{cmd_str}\' failed with returncode {result.returncode}\n\n'
                F'The combined stderr from workers follows:\n{stderr}'				)

      return result

class 			UpperCAmelCase__    (							A			):
    pass







def 		A_							(						_lowerCAmelCase :     List[str]					,						_lowerCAmelCase :     Tuple=False				):



      """simple docstring"""




      try:
            _lowerCamelCase					: Optional[Any]		    = subprocess.check_output(_lowerCAmelCase					,						stderr=subprocess.STDOUT				)
            if return_stdout:
                  if hasattr(_lowerCAmelCase					,						"decode"				):
                        _lowerCamelCase					: List[str]		    = output.decode("utf-8"				)
                  return output
      except subprocess.CalledProcessError as e:
            raise SubprocessCallException(
                F'Command `{" ".join(_lowerCAmelCase				)}` failed with the following error:\n\n{e.output.decode()}'				) from e





"""simple docstring"""






from typing import Optional

import numpy as np
import torch
from torch import nn
from transformers import GPTaConfig, GPTaLMHeadModel
from transformers.modeling_utils import ModuleUtilsMixin

from ...configuration_utils import ConfigMixin, register_to_config
from ...models import ModelMixin






class lowerCAmelCase__      (	lowercase,      lowercase,      lowercase		):






			'''simple docstring'''



			lowerCamelCase__ =     [R"""h\.\d+\.attn\.bias""", R"""h\.\d+\.attn\.masked_bias"""]
			@register_to_config
			def __init__(    self    , lowercase    , lowercase    , lowercase = None    , lowercase = 50257    , lowercase = 1024    , lowercase = 768    , lowercase = 12    , lowercase = 12    , lowercase = None    , lowercase = "gelu_new"    , lowercase = 0.1    , lowercase = 0.1    , lowercase = 0.1    , lowercase = 1E-5    , lowercase = 0.02    , lowercase = True    , lowercase = True    , lowercase = False    , lowercase = False    , ):
							super().__init__()

							_lowerCamelCase	:     Tuple       =       prefix_length

							if prefix_inner_dim != n_embd and prefix_hidden_dim is None:
											raise ValueError(
											    F'''`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and'''
											    F''' `n_embd`: {n_embd} are not equal.'''    )

							_lowerCamelCase	:     Optional[Any]       =       prefix_inner_dim
							_lowerCamelCase	:     Tuple       =       prefix_hidden_dim

							_lowerCamelCase	:     Dict       =       (
							    nn.Linear(self.prefix_inner_dim    , self.prefix_hidden_dim    )
							    if self.prefix_hidden_dim is not None
							    else nn.Identity()
							)
							_lowerCamelCase	:     Tuple       =       (
							    nn.Linear(self.prefix_hidden_dim    , lowercase    ) if self.prefix_hidden_dim is not None else nn.Identity()
							)

							_lowerCamelCase	:     Any       =       GPTaConfig(
							    vocab_size=lowercase    , n_positions=lowercase    , n_embd=lowercase    , n_layer=lowercase    , n_head=lowercase    , n_inner=lowercase    , activation_function=lowercase    , resid_pdrop=lowercase    , embd_pdrop=lowercase    , attn_pdrop=lowercase    , layer_norm_epsilon=lowercase    , initializer_range=lowercase    , scale_attn_weights=lowercase    , use_cache=lowercase    , scale_attn_by_inverse_layer_idx=lowercase    , reorder_and_upcast_attn=lowercase    , )
							_lowerCamelCase	:     Dict       =       GPTaLMHeadModel(lowercase    )
			def    A_       (    self    , lowercase    , lowercase    , lowercase = None    , lowercase = None    , ):
							_lowerCamelCase	:     List[Any]       =       self.transformer.transformer.wte(lowercase    )
							_lowerCamelCase	:     str       =       self.encode_prefix(lowercase    )
							_lowerCamelCase	:     int       =       self.decode_prefix(lowercase    )
							_lowerCamelCase	:     Optional[int]       =       torch.cat((prefix_embeds, embedding_text)    , dim=1    )

							if labels is not None:
											_lowerCamelCase	:     Any       =       self.get_dummy_token(input_ids.shape[0]    , input_ids.device    )
											_lowerCamelCase	:     int       =       torch.cat((dummy_token, input_ids)    , dim=1    )
							_lowerCamelCase	:     List[Any]       =       self.transformer(inputs_embeds=lowercase    , labels=lowercase    , attention_mask=lowercase    )
							if self.prefix_hidden_dim is not None:
											return out, hidden
							else:
											return out
			def    A_       (    self    , lowercase    , lowercase    ):
							return torch.zeros(lowercase    , self.prefix_length    , dtype=torch.intaa    , device=lowercase    )
			def    A_       (    self    , lowercase    ):
							return self.encode_prefix(lowercase    )
			@torch.no_grad()
			def    A_       (    self    , lowercase    , lowercase    , lowercase    ):
							_lowerCamelCase	:     Dict       =       torch.split(lowercase    , 1    , dim=0    )
							_lowerCamelCase	:     Any       =       []
							_lowerCamelCase	:     str       =       []
							for feature in features:
											_lowerCamelCase	:     Any       =       self.decode_prefix(feature.to(lowercase    )    )  # back to the clip feature
											# Only support beam search for now
											_lowerCamelCase,					_lowerCamelCase	:     Dict       =       self.generate_beam(
											    input_embeds=lowercase    , device=lowercase    , eos_token_id=lowercase    )
											generated_tokens.append(output_tokens[0]    )
											generated_seq_lengths.append(seq_lengths[0]    )
							_lowerCamelCase	:     List[Any]       =       torch.stack(lowercase    )
							_lowerCamelCase	:     Optional[int]       =       torch.stack(lowercase    )
							return generated_tokens, generated_seq_lengths






			@torch.no_grad()
			def    A_       (    self    , lowercase=None    , lowercase=None    , lowercase=None    , lowercase = 5    , lowercase = 67    , lowercase = 1.0    , lowercase = None    , ):
							_lowerCamelCase	:     Any       =       eos_token_id
							_lowerCamelCase	:     List[str]       =       None
							_lowerCamelCase	:     List[Any]       =       None
							_lowerCamelCase	:     List[str]       =       torch.ones(lowercase    , device=lowercase    , dtype=torch.int    )
							_lowerCamelCase	:     Optional[int]       =       torch.zeros(lowercase    , device=lowercase    , dtype=torch.bool    )

							if input_embeds is not None:
											_lowerCamelCase	:     Optional[int]       =       input_embeds
							else:
											_lowerCamelCase	:     Union[str, Any]       =       self.transformer.transformer.wte(lowercase    )

							for i in range(lowercase    ):
											_lowerCamelCase	:     Any       =       self.transformer(inputs_embeds=lowercase    )
											_lowerCamelCase	:     Optional[Any]       =       outputs.logits
											_lowerCamelCase	:     List[Any]       =       logits[:, -1, :] / (temperature if temperature > 0 else 1.0)
											_lowerCamelCase	:     Optional[int]       =       logits.softmax(-1    ).log()

											if scores is None:
															_lowerCamelCase,					_lowerCamelCase	:     Union[str, Any]       =       logits.topk(lowercase    , -1    )
															_lowerCamelCase	:     Optional[int]       =       generated.expand(lowercase    , *generated.shape[1:]    )
															_lowerCamelCase,					_lowerCamelCase	:     Tuple       =       next_tokens.permute(1    , 0    ), scores.squeeze(0    )
															if tokens is None:
																			_lowerCamelCase	:     List[str]       =       next_tokens
															else:
																			_lowerCamelCase	:     Tuple       =       tokens.expand(lowercase    , *tokens.shape[1:]    )
																			_lowerCamelCase	:     int       =       torch.cat((tokens, next_tokens)    , dim=1    )
											else:
															_lowerCamelCase	:     Union[str, Any]       =       -float(np.inf    )
															_lowerCamelCase	:     Union[str, Any]       =       0
															_lowerCamelCase	:     List[Any]       =       scores[:, None] + logits
															seq_lengths[~is_stopped] += 1
															_lowerCamelCase	:     List[Any]       =       scores_sum / seq_lengths[:, None]
															_lowerCamelCase,					_lowerCamelCase	:     Optional[Any]       =       scores_sum_average.view(-1    ).topk(lowercase    , -1    )
															_lowerCamelCase	:     Union[str, Any]       =       next_tokens // scores_sum.shape[1]
															_lowerCamelCase	:     Optional[Any]       =       seq_lengths[next_tokens_source]
															_lowerCamelCase	:     Dict       =       next_tokens % scores_sum.shape[1]
															_lowerCamelCase	:     Optional[int]       =       next_tokens.unsqueeze(1    )
															_lowerCamelCase	:     Tuple       =       tokens[next_tokens_source]
															_lowerCamelCase	:     str       =       torch.cat((tokens, next_tokens)    , dim=1    )
															_lowerCamelCase	:     Optional[int]       =       generated[next_tokens_source]
															_lowerCamelCase	:     Dict       =       scores_sum_average * seq_lengths
															_lowerCamelCase	:     List[Any]       =       is_stopped[next_tokens_source]

											_lowerCamelCase	:     Union[str, Any]       =       self.transformer.transformer.wte(next_tokens.squeeze()    ).view(generated.shape[0]    , 1    , -1    )
											_lowerCamelCase	:     Union[str, Any]       =       torch.cat((generated, next_token_embed)    , dim=1    )
											_lowerCamelCase	:     Optional[Any]       =       is_stopped + next_tokens.eq(lowercase    ).squeeze()
											if is_stopped.all():
															break

							_lowerCamelCase	:     Optional[int]       =       scores / seq_lengths
							_lowerCamelCase	:     Optional[int]       =       scores.argsort(descending=lowercase    )
							# tokens tensors are already padded to max_seq_length
							_lowerCamelCase	:     List[Any]       =       [tokens[i] for i in order]
							_lowerCamelCase	:     Dict       =       torch.stack(lowercase    , dim=0    )
							_lowerCamelCase	:     Optional[int]       =       torch.tensor([seq_lengths[i] for i in order]    , dtype=seq_lengths.dtype    )
							return output_texts, seq_lengths