


'''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   UpperCAmelCase_    (_UpperCAmelCase   ,						_UpperCAmelCase   ,						_UpperCAmelCase    ):





    """simple docstring"""






    lowerCamelCase    :   Any					=     [r'h\.\d+\.attn\.bias', r'h\.\d+\.attn\.masked_bias']







    @register_to_config
    def __init__(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_ = None     ,	SCREAMING_SNAKE_CASE_ = 5_02_57     ,	SCREAMING_SNAKE_CASE_ = 10_24     ,	SCREAMING_SNAKE_CASE_ = 7_68     ,	SCREAMING_SNAKE_CASE_ = 12     ,	SCREAMING_SNAKE_CASE_ = 12     ,	SCREAMING_SNAKE_CASE_ = None     ,	SCREAMING_SNAKE_CASE_ = "gelu_new"     ,	SCREAMING_SNAKE_CASE_ = 0.1     ,	SCREAMING_SNAKE_CASE_ = 0.1     ,	SCREAMING_SNAKE_CASE_ = 0.1     ,	SCREAMING_SNAKE_CASE_ = 1E-5     ,	SCREAMING_SNAKE_CASE_ = 0.0_2     ,	SCREAMING_SNAKE_CASE_ = True     ,	SCREAMING_SNAKE_CASE_ = True     ,	SCREAMING_SNAKE_CASE_ = False     ,	SCREAMING_SNAKE_CASE_ = False     ,	)							->	Tuple:
         super().__init__()

         __lowerCamelCase  :      int														=						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  :      List[Any]														=						prefix_inner_dim
         __lowerCamelCase  :      Any														=						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  :      Dict														=						(
             nn.Linear(self.prefix_hidden_dim     ,	SCREAMING_SNAKE_CASE_      ) if self.prefix_hidden_dim is not None else nn.Identity()
         )

         __lowerCamelCase  :      str														=						GPTaConfig(
             vocab_size=SCREAMING_SNAKE_CASE_     ,	n_positions=SCREAMING_SNAKE_CASE_     ,	n_embd=SCREAMING_SNAKE_CASE_     ,	n_layer=SCREAMING_SNAKE_CASE_     ,	n_head=SCREAMING_SNAKE_CASE_     ,	n_inner=SCREAMING_SNAKE_CASE_     ,	activation_function=SCREAMING_SNAKE_CASE_     ,	resid_pdrop=SCREAMING_SNAKE_CASE_     ,	embd_pdrop=SCREAMING_SNAKE_CASE_     ,	attn_pdrop=SCREAMING_SNAKE_CASE_     ,	layer_norm_epsilon=SCREAMING_SNAKE_CASE_     ,	initializer_range=SCREAMING_SNAKE_CASE_     ,	scale_attn_weights=SCREAMING_SNAKE_CASE_     ,	use_cache=SCREAMING_SNAKE_CASE_     ,	scale_attn_by_inverse_layer_idx=SCREAMING_SNAKE_CASE_     ,	reorder_and_upcast_attn=SCREAMING_SNAKE_CASE_     ,	)
         __lowerCamelCase  :      Dict														=						GPTaLMHeadModel(SCREAMING_SNAKE_CASE_      )







    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_ = None     ,	SCREAMING_SNAKE_CASE_ = None     ,	)							->	List[str]:
         __lowerCamelCase  :      Any														=						self.transformer.transformer.wte(SCREAMING_SNAKE_CASE_      )
         __lowerCamelCase  :      Tuple														=						self.encode_prefix(SCREAMING_SNAKE_CASE_      )
         __lowerCamelCase  :      List[str]														=						self.decode_prefix(SCREAMING_SNAKE_CASE_      )
         __lowerCamelCase  :      Any														=						torch.cat((prefix_embeds, embedding_text)     ,	dim=1      )

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







    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )							->	torch.Tensor:
         return torch.zeros(SCREAMING_SNAKE_CASE_     ,	self.prefix_length     ,	dtype=torch.intaa     ,	device=SCREAMING_SNAKE_CASE_      )







    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_      )							->	List[Any]:
         return self.encode_prefix(SCREAMING_SNAKE_CASE_      )







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







    @torch.no_grad()
    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_=None     ,	SCREAMING_SNAKE_CASE_=None     ,	SCREAMING_SNAKE_CASE_=None     ,	SCREAMING_SNAKE_CASE_ = 5     ,	SCREAMING_SNAKE_CASE_ = 67     ,	SCREAMING_SNAKE_CASE_ = 1.0     ,	SCREAMING_SNAKE_CASE_ = None     ,	)							->	Union[str, Any]:
         __lowerCamelCase  :      Dict														=						eos_token_id
         __lowerCamelCase  :      Dict														=						None
         __lowerCamelCase  :      List[str]														=						None
         __lowerCamelCase  :      Tuple														=						torch.ones(SCREAMING_SNAKE_CASE_     ,	device=SCREAMING_SNAKE_CASE_     ,	dtype=torch.int      )
         __lowerCamelCase  :      Dict														=						torch.zeros(SCREAMING_SNAKE_CASE_     ,	device=SCREAMING_SNAKE_CASE_     ,	dtype=torch.bool      )

         if input_embeds is not None:
              __lowerCamelCase  :      Any														=						input_embeds
         else:
              __lowerCamelCase  :      Dict														=						self.transformer.transformer.wte(SCREAMING_SNAKE_CASE_      )

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

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

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

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













import os

import torch

from ..logging import get_logger
from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME
from .versions import is_torch_version


if is_torch_version('>=', FSDP_PYTORCH_VERSION):
    import torch.distributed.checkpoint as dist_cp
    from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner
    from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict
    from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP
    from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType


UpperCamelCase_												=	get_logger(__name__)






def 				_UpperCAmelCase			(    A				,							A				,							A				,							A				,							A=0     ):




   '''simple docstring'''

   os.makedirs(A				,							exist_ok=A     )
   with FSDP.state_dict_type(
       A				,							fsdp_plugin.state_dict_type				,							fsdp_plugin.state_dict_config				,							fsdp_plugin.optim_state_dict_config     ):
      UpperCAmelCase__						=model.state_dict()
      if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
         UpperCAmelCase__						=F"""{MODEL_NAME}.bin""" if model_index == 0 else F"""{MODEL_NAME}_{model_index}.bin"""
         UpperCAmelCase__						=os.path.join(A				,							A     )
         if accelerator.process_index == 0:
            logger.info(F"""Saving model to {output_model_file}"""     )
            torch.save(A				,							A     )
            logger.info(F"""Model saved to {output_model_file}"""     )
      elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT:
         UpperCAmelCase__						=(
             F"""{MODEL_NAME}_rank{accelerator.process_index}.bin"""
             if model_index == 0
             else F"""{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin"""
         )
         UpperCAmelCase__						=os.path.join(A				,							A     )
         logger.info(F"""Saving model to {output_model_file}"""     )
         torch.save(A				,							A     )
         logger.info(F"""Model saved to {output_model_file}"""     )
      elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT:
         UpperCAmelCase__						=os.path.join(A				,							F"""{MODEL_NAME}_{model_index}"""     )
         os.makedirs(A				,							exist_ok=A     )
         logger.info(F"""Saving model to {ckpt_dir}"""     )
         UpperCAmelCase__						={"model": state_dict}

         dist_cp.save_state_dict(
             state_dict=A				,							storage_writer=dist_cp.FileSystemWriter(A     )				,							planner=DefaultSavePlanner()				,							)
         logger.info(F"""Model saved to {ckpt_dir}"""     )






def 				_UpperCAmelCase			(    A				,							A				,							A				,							A				,							A=0     ):




   '''simple docstring'''

   accelerator.wait_for_everyone()
   with FSDP.state_dict_type(
       A				,							fsdp_plugin.state_dict_type				,							fsdp_plugin.state_dict_config				,							fsdp_plugin.optim_state_dict_config     ):
      if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
         if type(A     ) != FSDP and accelerator.process_index != 0:
            if not fsdp_plugin.sync_module_states:
               raise ValueError(
                   "Set the `sync_module_states` flag to `True` so that model states are synced across processes when "
                   "initializing FSDP object"     )
            return
         UpperCAmelCase__						=F"""{MODEL_NAME}.bin""" if model_index == 0 else F"""{MODEL_NAME}_{model_index}.bin"""
         UpperCAmelCase__						=os.path.join(A				,							A     )
         logger.info(F"""Loading model from {input_model_file}"""     )
         UpperCAmelCase__						=torch.load(A     )
         logger.info(F"""Model loaded from {input_model_file}"""     )
      elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT:
         UpperCAmelCase__						=(
             F"""{MODEL_NAME}_rank{accelerator.process_index}.bin"""
             if model_index == 0
             else F"""{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin"""
         )
         UpperCAmelCase__						=os.path.join(A				,							A     )
         logger.info(F"""Loading model from {input_model_file}"""     )
         UpperCAmelCase__						=torch.load(A     )
         logger.info(F"""Model loaded from {input_model_file}"""     )
      elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT:
         UpperCAmelCase__						=(
             os.path.join(A				,							F"""{MODEL_NAME}_{model_index}"""     )
             if F"""{MODEL_NAME}""" not in input_dir
             else input_dir
         )
         logger.info(F"""Loading model from {ckpt_dir}"""     )
         UpperCAmelCase__						={"model": model.state_dict()}
         dist_cp.load_state_dict(
             state_dict=A				,							storage_reader=dist_cp.FileSystemReader(A     )				,							planner=DefaultLoadPlanner()				,							)
         UpperCAmelCase__						=state_dict["model"]
         logger.info(F"""Model loaded from {ckpt_dir}"""     )
      model.load_state_dict(A     )






def 				_UpperCAmelCase			(    A				,							A				,							A				,							A				,							A				,							A=0     ):




   '''simple docstring'''

   os.makedirs(A				,							exist_ok=A     )
   with FSDP.state_dict_type(
       A				,							fsdp_plugin.state_dict_type				,							fsdp_plugin.state_dict_config				,							fsdp_plugin.optim_state_dict_config     ):
      UpperCAmelCase__						=FSDP.optim_state_dict(A				,							A     )
      if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
         if accelerator.process_index == 0:
            UpperCAmelCase__						=(
                F"""{OPTIMIZER_NAME}.bin""" if optimizer_index == 0 else F"""{OPTIMIZER_NAME}_{optimizer_index}.bin"""
            )
            UpperCAmelCase__						=os.path.join(A				,							A     )
            logger.info(F"""Saving Optimizer state to {output_optimizer_file}"""     )
            torch.save(A				,							A     )
            logger.info(F"""Optimizer state saved in {output_optimizer_file}"""     )
      else:
         UpperCAmelCase__						=os.path.join(A				,							F"""{OPTIMIZER_NAME}_{optimizer_index}"""     )
         os.makedirs(A				,							exist_ok=A     )
         logger.info(F"""Saving Optimizer state to {ckpt_dir}"""     )
         dist_cp.save_state_dict(
             state_dict={"optimizer": optim_state}				,							storage_writer=dist_cp.FileSystemWriter(A     )				,							planner=DefaultSavePlanner()				,							)
         logger.info(F"""Optimizer state saved in {ckpt_dir}"""     )






def 				_UpperCAmelCase			(    A				,							A				,							A				,							A				,							A				,							A=0     ):




   '''simple docstring'''

   accelerator.wait_for_everyone()
   with FSDP.state_dict_type(
       A				,							fsdp_plugin.state_dict_type				,							fsdp_plugin.state_dict_config				,							fsdp_plugin.optim_state_dict_config     ):
      if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
         UpperCAmelCase__						=None
         # below check should work but currently it isn't working (mostly opytorch issue),
         # in the meantime disabling it at the cost of excess memory usage
         # if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only:
         UpperCAmelCase__						=(
             F"""{OPTIMIZER_NAME}.bin""" if optimizer_index == 0 else F"""{OPTIMIZER_NAME}_{optimizer_index}.bin"""
         )
         UpperCAmelCase__						=os.path.join(A				,							A     )
         logger.info(F"""Loading Optimizer state from {input_optimizer_file}"""     )
         UpperCAmelCase__						=torch.load(A     )
         logger.info(F"""Optimizer state loaded from {input_optimizer_file}"""     )
      else:
         UpperCAmelCase__						=(
             os.path.join(A				,							F"""{OPTIMIZER_NAME}_{optimizer_index}"""     )
             if F"""{OPTIMIZER_NAME}""" not in input_dir
             else input_dir
         )
         logger.info(F"""Loading Optimizer from {ckpt_dir}"""     )
         UpperCAmelCase__						=load_sharded_optimizer_state_dict(
             model_state_dict=model.state_dict()				,							optimizer_key="optimizer"				,							storage_reader=dist_cp.FileSystemReader(A     )				,							)
         UpperCAmelCase__						=optim_state["optimizer"]
         logger.info(F"""Optimizer loaded from {ckpt_dir}"""     )
      UpperCAmelCase__						=FSDP.optim_state_dict_to_load(A				,							A				,							A     )
      optimizer.load_state_dict(A     )



