





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 			UpperCAmelCase					(      snake_case_							,		snake_case_							,		snake_case_       ):
      _lowercase:      List[Any]											=       [r'''h\.\d+\.attn\.bias''', r'''h\.\d+\.attn\.masked_bias''']




      @register_to_config
      def __init__(      self      :			Optional[int]      ,      __snake_case      :			int      ,      __snake_case      :			int      ,      __snake_case      :			Optional[int] = None      ,      __snake_case      :			int = 5_02_57      ,      __snake_case      :			int = 10_24      ,      __snake_case      :			int = 7_68      ,      __snake_case      :			int = 12      ,      __snake_case      :			int = 12      ,      __snake_case      :			Optional[int] = None      ,      __snake_case      :			str = "gelu_new"      ,      __snake_case      :			float = 0.1      ,      __snake_case      :			float = 0.1      ,      __snake_case      :			float = 0.1      ,      __snake_case      :			float = 1E-5      ,      __snake_case      :			float = 0.02      ,      __snake_case      :			bool = True      ,      __snake_case      :			bool = True      ,      __snake_case      :			bool = False      ,      __snake_case      :			bool = False      ,      )    ->				int:
            super().__init__()

            _lowerCAmelCase												=							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												=							prefix_inner_dim
            _lowerCAmelCase												=							prefix_hidden_dim

            _lowerCAmelCase												=							(
                nn.Linear(self.prefix_inner_dim      ,      self.prefix_hidden_dim  )
                if self.prefix_hidden_dim is not None
                else nn.Identity()
            )
            _lowerCAmelCase												=							(
                nn.Linear(self.prefix_hidden_dim      ,      __snake_case  ) if self.prefix_hidden_dim is not None else nn.Identity()
            )

            _lowerCAmelCase												=							GPTaConfig(
                vocab_size=__snake_case      ,      n_positions=__snake_case      ,      n_embd=__snake_case      ,      n_layer=__snake_case      ,      n_head=__snake_case      ,      n_inner=__snake_case      ,      activation_function=__snake_case      ,      resid_pdrop=__snake_case      ,      embd_pdrop=__snake_case      ,      attn_pdrop=__snake_case      ,      layer_norm_epsilon=__snake_case      ,      initializer_range=__snake_case      ,      scale_attn_weights=__snake_case      ,      use_cache=__snake_case      ,      scale_attn_by_inverse_layer_idx=__snake_case      ,      reorder_and_upcast_attn=__snake_case      ,      )
            _lowerCAmelCase												=							GPTaLMHeadModel(__snake_case  )




      def     lowercase__   (      self      :			Optional[int]      ,      __snake_case      :			torch.Tensor      ,      __snake_case      :			torch.Tensor      ,      __snake_case      :			Optional[torch.Tensor] = None      ,      __snake_case      :			Optional[torch.Tensor] = None      ,      )    ->				Dict:
            _lowerCAmelCase												=							self.transformer.transformer.wte(__snake_case  )
            _lowerCAmelCase												=							self.encode_prefix(__snake_case  )
            _lowerCAmelCase												=							self.decode_prefix(__snake_case  )
            _lowerCAmelCase												=							torch.cat((prefix_embeds, embedding_text)      ,      dim=1  )

            if labels is not None:
                  _lowerCAmelCase												=							self.get_dummy_token(input_ids.shape[0]      ,      input_ids.device  )
                  _lowerCAmelCase												=							torch.cat((dummy_token, input_ids)      ,      dim=1  )
            _lowerCAmelCase												=							self.transformer(inputs_embeds=__snake_case      ,      labels=__snake_case      ,      attention_mask=__snake_case  )
            if self.prefix_hidden_dim is not None:
                  return out, hidden
            else:
                  return out




      def     lowercase__   (      self      :			Dict      ,      __snake_case      :			int      ,      __snake_case      :			torch.device  )    ->				torch.Tensor:
            return torch.zeros(__snake_case      ,      self.prefix_length      ,      dtype=torch.intaa      ,      device=__snake_case  )




      def     lowercase__   (      self      :			Optional[int]      ,      __snake_case      :			List[Any]  )    ->				Union[str, Any]:
            return self.encode_prefix(__snake_case  )




      @torch.no_grad()
      def     lowercase__   (      self      :			List[str]      ,      __snake_case      :			int      ,      __snake_case      :			List[Any]      ,      __snake_case      :			Dict  )    ->				List[str]:
            _lowerCAmelCase												=							torch.split(__snake_case      ,      1      ,      dim=0  )
            _lowerCAmelCase												=							[]
            _lowerCAmelCase												=							[]
            for feature in features:
                  _lowerCAmelCase												=							self.decode_prefix(feature.to(__snake_case  )  )  # back to the clip feature
                  # Only support beam search for now
                  _lowerCAmelCase					,							_lowerCAmelCase												=							self.generate_beam(
                      input_embeds=__snake_case      ,      device=__snake_case      ,      eos_token_id=__snake_case  )
                  generated_tokens.append(output_tokens[0]  )
                  generated_seq_lengths.append(seq_lengths[0]  )
            _lowerCAmelCase												=							torch.stack(__snake_case  )
            _lowerCAmelCase												=							torch.stack(__snake_case  )
            return generated_tokens, generated_seq_lengths




      @torch.no_grad()
      def     lowercase__   (      self      :			Optional[int]      ,      __snake_case      :			List[Any]=None      ,      __snake_case      :			str=None      ,      __snake_case      :			List[str]=None      ,      __snake_case      :			int = 5      ,      __snake_case      :			int = 67      ,      __snake_case      :			float = 1.0      ,      __snake_case      :			Optional[int] = None      ,      )    ->				Union[str, Any]:
            _lowerCAmelCase												=							eos_token_id
            _lowerCAmelCase												=							None
            _lowerCAmelCase												=							None
            _lowerCAmelCase												=							torch.ones(__snake_case      ,      device=__snake_case      ,      dtype=torch.int  )
            _lowerCAmelCase												=							torch.zeros(__snake_case      ,      device=__snake_case      ,      dtype=torch.bool  )

            if input_embeds is not None:
                  _lowerCAmelCase												=							input_embeds
            else:
                  _lowerCAmelCase												=							self.transformer.transformer.wte(__snake_case  )

            for i in range(__snake_case  ):
                  _lowerCAmelCase												=							self.transformer(inputs_embeds=__snake_case  )
                  _lowerCAmelCase												=							outputs.logits
                  _lowerCAmelCase												=							logits[:, -1, :] / (temperature if temperature > 0 else 1.0)
                  _lowerCAmelCase												=							logits.softmax(-1  ).log()

                  if scores is None:
                        _lowerCAmelCase					,							_lowerCAmelCase												=							logits.topk(__snake_case      ,      -1  )
                        _lowerCAmelCase												=							generated.expand(__snake_case      ,      *generated.shape[1:]  )
                        _lowerCAmelCase					,							_lowerCAmelCase												=							next_tokens.permute(1      ,      0  ), scores.squeeze(0  )
                        if tokens is None:
                              _lowerCAmelCase												=							next_tokens
                        else:
                              _lowerCAmelCase												=							tokens.expand(__snake_case      ,      *tokens.shape[1:]  )
                              _lowerCAmelCase												=							torch.cat((tokens, next_tokens)      ,      dim=1  )
                  else:
                        _lowerCAmelCase												=							-float(np.inf  )
                        _lowerCAmelCase												=							0
                        _lowerCAmelCase												=							scores[:, None] + logits
                        seq_lengths[~is_stopped] += 1
                        _lowerCAmelCase												=							scores_sum / seq_lengths[:, None]
                        _lowerCAmelCase					,							_lowerCAmelCase												=							scores_sum_average.view(-1  ).topk(__snake_case      ,      -1  )
                        _lowerCAmelCase												=							next_tokens // scores_sum.shape[1]
                        _lowerCAmelCase												=							seq_lengths[next_tokens_source]
                        _lowerCAmelCase												=							next_tokens % scores_sum.shape[1]
                        _lowerCAmelCase												=							next_tokens.unsqueeze(1  )
                        _lowerCAmelCase												=							tokens[next_tokens_source]
                        _lowerCAmelCase												=							torch.cat((tokens, next_tokens)      ,      dim=1  )
                        _lowerCAmelCase												=							generated[next_tokens_source]
                        _lowerCAmelCase												=							scores_sum_average * seq_lengths
                        _lowerCAmelCase												=							is_stopped[next_tokens_source]

                  _lowerCAmelCase												=							self.transformer.transformer.wte(next_tokens.squeeze()  ).view(generated.shape[0]      ,      1      ,      -1  )
                  _lowerCAmelCase												=							torch.cat((generated, next_token_embed)      ,      dim=1  )
                  _lowerCAmelCase												=							is_stopped + next_tokens.eq(__snake_case  ).squeeze()
                  if is_stopped.all():
                        break

            _lowerCAmelCase												=							scores / seq_lengths
            _lowerCAmelCase												=							scores.argsort(descending=__snake_case  )
            # tokens tensors are already padded to max_seq_length
            _lowerCAmelCase												=							[tokens[i] for i in order]
            _lowerCAmelCase												=							torch.stack(__snake_case      ,      dim=0  )
            _lowerCAmelCase												=							torch.tensor([seq_lengths[i] for i in order]      ,      dtype=seq_lengths.dtype  )
            return output_texts, seq_lengths













'''simple docstring'''






import logging
import os
import threading
import time


try:
      import warnings
except ImportError:
      A__    :       Tuple              =None

try:
      import msvcrt
except ImportError:
      A__    :       str              =None

try:
      import fcntl
except ImportError:
      A__    :       Dict              =None


# Backward compatibility
# ------------------------------------------------
try:
      TimeoutError
except NameError:
      A__    :       Tuple              =OSError


# Data
# ------------------------------------------------
A__    :       Optional[Any]              =[
    '''Timeout''',
    '''BaseFileLock''',
    '''WindowsFileLock''',
    '''UnixFileLock''',
    '''SoftFileLock''',
    '''FileLock''',
]

A__    :       Union[str, Any]              ='''3.0.12'''


A__    :       Optional[Any]              =None
def        UpperCamelCase__				(		):





      """simple docstring"""


      global _logger
      _lowerCAmelCase												=							_logger or logging.getLogger(__name__  )
      return _logger




class 			UpperCAmelCase					(      snake_case_       ):




      def __init__(      self      :			Optional[int]      ,      __snake_case      :			str  )    ->				Optional[Any]:
            _lowerCAmelCase												=							lock_file
            return None




      def __str__(      self      :			Union[str, Any]  )    ->				Any:
            _lowerCAmelCase												=							f"The file lock '{self.lock_file}' could not be acquired."
            return temp




class 			UpperCAmelCase					:




      def __init__(      self      :			str      ,      __snake_case      :			str  )    ->				Tuple:
            _lowerCAmelCase												=							lock
            return None




      def __enter__(      self      :			Union[str, Any]  )    ->				Union[str, Any]:
            return self.lock




      def __exit__(      self      :			Tuple      ,      __snake_case      :			List[Any]      ,      __snake_case      :			int      ,      __snake_case      :			Optional[int]  )    ->				Union[str, Any]:
            self.lock.release()
            return None




class 			UpperCAmelCase					:




      def __init__(      self      :			List[Any]      ,      __snake_case      :			str      ,      __snake_case      :			Tuple=-1      ,      __snake_case      :			List[str]=None  )    ->				Any:
            _lowerCAmelCase												=							max_filename_length if max_filename_length is not None else 2_55
            # Hash the filename if it's too long
            _lowerCAmelCase												=							self.hash_filename_if_too_long(__snake_case      ,      __snake_case  )
            # The path to the lock file.
            _lowerCAmelCase												=							lock_file

            # The file descriptor for the *_lock_file* as it is returned by the
            # os.open() function.
            # This file lock is only NOT None, if the object currently holds the
            # lock.
            _lowerCAmelCase												=							None

            # The default timeout value.
            _lowerCAmelCase												=							timeout

            # We use this lock primarily for the lock counter.
            _lowerCAmelCase												=							threading.Lock()

            # The lock counter is used for implementing the nested locking
            # mechanism. Whenever the lock is acquired, the counter is increased and
            # the lock is only released, when this value is 0 again.
            _lowerCAmelCase												=							0
            return None




      @property
      def     lowercase__   (      self      :			int  )    ->				List[str]:
            return self._lock_file




      @property
      def     lowercase__   (      self      :			Dict  )    ->				List[Any]:
            return self._timeout




      @timeout.setter
      def     lowercase__   (      self      :			Tuple      ,      __snake_case      :			int  )    ->				Optional[Any]:
            _lowerCAmelCase												=							float(__snake_case  )
            return None




      def     lowercase__   (      self      :			Optional[int]  )    ->				Union[str, Any]:
            raise NotImplementedError()




      def     lowercase__   (      self      :			Optional[Any]  )    ->				Any:
            raise NotImplementedError()




      @property
      def     lowercase__   (      self      :			str  )    ->				Dict:
            return self._lock_file_fd is not None




      def     lowercase__   (      self      :			Union[str, Any]      ,      __snake_case      :			Union[str, Any]=None      ,      __snake_case      :			List[str]=0.05  )    ->				List[str]:
            # Use the default timeout, if no timeout is provided.
            if timeout is None:
                  _lowerCAmelCase												=							self.timeout

            # Increment the number right at the beginning.
            # We can still undo it, if something fails.
            with self._thread_lock:
                  self._lock_counter += 1

            _lowerCAmelCase												=							id(self  )
            _lowerCAmelCase												=							self._lock_file
            _lowerCAmelCase												=							time.time()
            try:
                  while True:
                        with self._thread_lock:
                              if not self.is_locked:
                                    logger().debug(f"Attempting to acquire lock {lock_id} on {lock_filename}"  )
                                    self._acquire()

                        if self.is_locked:
                              logger().debug(f"Lock {lock_id} acquired on {lock_filename}"  )
                              break
                        elif timeout >= 0 and time.time() - start_time > timeout:
                              logger().debug(f"Timeout on acquiring lock {lock_id} on {lock_filename}"  )
                              raise Timeout(self._lock_file  )
                        else:
                              logger().debug(
                                  f"Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ..."  )
                              time.sleep(__snake_case  )
            except:  # noqa
                  # Something did go wrong, so decrement the counter.
                  with self._thread_lock:
                        _lowerCAmelCase												=							max(0      ,      self._lock_counter - 1  )

                  raise
            return _Acquire_ReturnProxy(lock=self  )




      def     lowercase__   (      self      :			Dict      ,      __snake_case      :			Optional[int]=False  )    ->				Union[str, Any]:
            with self._thread_lock:
                  if self.is_locked:
                        self._lock_counter -= 1

                        if self._lock_counter == 0 or force:
                              _lowerCAmelCase												=							id(self  )
                              _lowerCAmelCase												=							self._lock_file

                              logger().debug(f"Attempting to release lock {lock_id} on {lock_filename}"  )
                              self._release()
                              _lowerCAmelCase												=							0
                              logger().debug(f"Lock {lock_id} released on {lock_filename}"  )

            return None




      def __enter__(      self      :			List[str]  )    ->				Union[str, Any]:
            self.acquire()
            return self




      def __exit__(      self      :			Union[str, Any]      ,      __snake_case      :			str      ,      __snake_case      :			Tuple      ,      __snake_case      :			Any  )    ->				int:
            self.release()
            return None




      def __del__(      self      :			Optional[Any]  )    ->				Any:
            self.release(force=__snake_case  )
            return None




      def     lowercase__   (      self      :			Optional[Any]      ,      __snake_case      :			str      ,      __snake_case      :			int  )    ->				str:
            _lowerCAmelCase												=							os.path.basename(__snake_case  )
            if len(__snake_case  ) > max_length and max_length > 0:
                  _lowerCAmelCase												=							os.path.dirname(__snake_case  )
                  _lowerCAmelCase												=							str(hash(__snake_case  )  )
                  _lowerCAmelCase												=							filename[: max_length - len(__snake_case  ) - 8] + """...""" + hashed_filename + """.lock"""
                  return os.path.join(__snake_case      ,      __snake_case  )
            else:
                  return path




class 			UpperCAmelCase					(      snake_case_       ):




      def __init__(      self      :			str      ,      __snake_case      :			Union[str, Any]      ,      __snake_case      :			Optional[int]=-1      ,      __snake_case      :			str=None  )    ->				Dict:
            from .file_utils import relative_to_absolute_path

            super().__init__(__snake_case      ,      timeout=__snake_case      ,      max_filename_length=__snake_case  )
            _lowerCAmelCase												=							"""\\\\?\\""" + relative_to_absolute_path(self.lock_file  )




      def     lowercase__   (      self      :			List[str]  )    ->				Tuple:
            _lowerCAmelCase												=							os.O_RDWR | os.O_CREAT | os.O_TRUNC

            try:
                  _lowerCAmelCase												=							os.open(self._lock_file      ,      __snake_case  )
            except OSError:
                  pass
            else:
                  try:
                        msvcrt.locking(__snake_case      ,      msvcrt.LK_NBLCK      ,      1  )
                  except OSError:
                        os.close(__snake_case  )
                  else:
                        _lowerCAmelCase												=							fd
            return None




      def     lowercase__   (      self      :			List[str]  )    ->				List[str]:
            _lowerCAmelCase												=							self._lock_file_fd
            _lowerCAmelCase												=							None
            msvcrt.locking(__snake_case      ,      msvcrt.LK_UNLCK      ,      1  )
            os.close(__snake_case  )

            try:
                  os.remove(self._lock_file  )
            # Probably another instance of the application
            # that acquired the file lock.
            except OSError:
                  pass
            return None




class 			UpperCAmelCase					(      snake_case_       ):




      def __init__(      self      :			Dict      ,      __snake_case      :			List[Any]      ,      __snake_case      :			List[Any]=-1      ,      __snake_case      :			List[str]=None  )    ->				Dict:
            _lowerCAmelCase												=							os.statvfs(os.path.dirname(__snake_case  )  ).f_namemax
            super().__init__(__snake_case      ,      timeout=__snake_case      ,      max_filename_length=__snake_case  )




      def     lowercase__   (      self      :			Optional[int]  )    ->				List[Any]:
            _lowerCAmelCase												=							os.O_RDWR | os.O_CREAT | os.O_TRUNC
            _lowerCAmelCase												=							os.open(self._lock_file      ,      __snake_case  )

            try:
                  fcntl.flock(__snake_case      ,      fcntl.LOCK_EX | fcntl.LOCK_NB  )
            except OSError:
                  os.close(__snake_case  )
            else:
                  _lowerCAmelCase												=							fd
            return None




      def     lowercase__   (      self      :			Optional[int]  )    ->				Optional[int]:
            # Do not remove the lockfile:
            #
            #   https://github.com/benediktschmitt/py-filelock/issues/31
            #   https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition
            _lowerCAmelCase												=							self._lock_file_fd
            _lowerCAmelCase												=							None
            fcntl.flock(__snake_case      ,      fcntl.LOCK_UN  )
            os.close(__snake_case  )
            return None




class 			UpperCAmelCase					(      snake_case_       ):




      def     lowercase__   (      self      :			Union[str, Any]  )    ->				Dict:
            _lowerCAmelCase												=							os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC
            try:
                  _lowerCAmelCase												=							os.open(self._lock_file      ,      __snake_case  )
            except OSError:
                  pass
            else:
                  _lowerCAmelCase												=							fd
            return None




      def     lowercase__   (      self      :			Any  )    ->				Optional[Any]:
            os.close(self._lock_file_fd  )
            _lowerCAmelCase												=							None

            try:
                  os.remove(self._lock_file  )
            # The file is already deleted and that's what we want.
            except OSError:
                  pass
            return None




A__    :       Tuple              =None

if msvcrt:
      A__    :       List[Any]              =WindowsFileLock
elif fcntl:
      A__    :       Tuple              =UnixFileLock
else:
      A__    :       Tuple              =SoftFileLock

      if warnings is not None:
            warnings.warn('''only soft file lock is available''')






