


import logging

import torch
from torch import nn
from torch.nn import CrossEntropyLoss, MSELoss

from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward
from transformers.models.bert.modeling_bert import (
    BERT_INPUTS_DOCSTRING,
    BERT_START_DOCSTRING,
    BertEncoder,
    BertModel,
    BertPreTrainedModel,
)


SCREAMING_SNAKE_CASE							    =							logging.getLogger(__name__)


class     __UpperCAmelCase							(       __A							):


     """simple docstring"""


     def 	snake_case_  (	self  ,       __A  ,       __A  ,       __A=None  ,       __A=None    ):
        __a					=  self.layer[current_layer](__A  ,       __A  ,       head_mask[current_layer]    )

        __a					=  layer_outputs[0]

        return hidden_states







@add_start_docstrings(
    """The bare Bert Model transformer with PABEE outputting raw hidden-states without any specific head on top.""" ,					__A ,					)
class     __UpperCAmelCase							(       __A							):


     """simple docstring"""


     def __init__(	self  ,       __A    ):
        super().__init__(__A    )

        __a					=  BertEncoderWithPabee(__A    )

        self.init_weights()
        __a					=  0
        __a					=  0
        __a					=  0

        __a					=  0


     def 	snake_case_  (	self  ,       __A    ):
        __a					=  threshold


     def 	snake_case_  (	self  ,       __A    ):
        __a					=  patience


     def 	snake_case_  (	self    ):
        __a					=  0
        __a					=  0


     def 	snake_case_  (	self    ):
        __a					=  self.inference_layers_num / self.inference_instances_num
        __a					=  (
            f'''*** Patience = {self.patience} Avg. Inference Layers = {avg_inf_layers:.2f} Speed Up ='''
            f''' {1 - avg_inf_layers / self.config.num_hidden_layers:.2f} ***'''
        )
        print(__A    )


     @add_start_docstrings_to_model_forward(__A    )
     def 	snake_case_  (	self  ,       __A=None  ,       __A=None  ,       __A=None  ,       __A=None  ,       __A=None  ,       __A=None  ,       __A=None  ,       __A=None  ,       __A=None  ,       __A=None  ,       __A=False  ,       ):

        if input_ids is not None and inputs_embeds is not None:
           raise ValueError("""You cannot specify both input_ids and inputs_embeds at the same time"""    )
        elif input_ids is not None:
           __a					=  input_ids.size()
        elif inputs_embeds is not None:
           __a					=  inputs_embeds.size()[:-1]
        else:
           raise ValueError("""You have to specify either input_ids or inputs_embeds"""    )

        __a					=  input_ids.device if input_ids is not None else inputs_embeds.device

        if attention_mask is None:
           __a					=  torch.ones(__A  ,       device=__A    )
        if token_type_ids is None:
           __a					=  torch.zeros(__A  ,       dtype=torch.long  ,       device=__A    )

        # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
        # ourselves in which case we just need to make it broadcastable to all heads.
        __a					=  self.get_extended_attention_mask(__A  ,       __A  ,       __A    )

        # If a 2D ou 3D attention mask is provided for the cross-attention
        # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
        if self.config.is_decoder and encoder_hidden_states is not None:
           __a	,    __a	,    __a					=  encoder_hidden_states.size()
           __a					=  (encoder_batch_size, encoder_sequence_length)
           if encoder_attention_mask is None:
              __a					=  torch.ones(__A  ,       device=__A    )
           __a					=  self.invert_attention_mask(__A    )
        else:
           __a					=  None

        # Prepare head mask if needed
        # 1.0 in head_mask indicate we keep the head
        # attention_probs has shape bsz x n_heads x N x N
        # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
        # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
        __a					=  self.get_head_mask(__A  ,       self.config.num_hidden_layers    )

        __a					=  self.embeddings(
            input_ids=__A  ,       position_ids=__A  ,       token_type_ids=__A  ,       inputs_embeds=__A    )
        __a					=  embedding_output

        if self.training:
           __a					=  []
           for i in range(self.config.num_hidden_layers    ):
              __a					=  self.encoder.adaptive_forward(
                  __A  ,       current_layer=__A  ,       attention_mask=__A  ,       head_mask=__A    )

              __a					=  self.pooler(__A    )
              __a					=  output_layers[i](output_dropout(__A    )    )
              res.append(__A    )
        elif self.patience == 0:  # Use all layers for inference
           __a					=  self.encoder(
               __A  ,       attention_mask=__A  ,       head_mask=__A  ,       encoder_hidden_states=__A  ,       encoder_attention_mask=__A  ,       )
           __a					=  self.pooler(encoder_outputs[0]    )
           __a					=  [output_layers[self.config.num_hidden_layers - 1](__A    )]
        else:
           __a					=  0
           __a					=  None
           __a					=  0
           for i in range(self.config.num_hidden_layers    ):
              calculated_layer_num += 1
              __a					=  self.encoder.adaptive_forward(
                  __A  ,       current_layer=__A  ,       attention_mask=__A  ,       head_mask=__A    )

              __a					=  self.pooler(__A    )
              __a					=  output_layers[i](__A    )
              if regression:
                 __a					=  logits.detach()
                 if patient_result is not None:
                    __a					=  patient_result.detach()
                 if (patient_result is not None) and torch.abs(patient_result - labels    ) < self.regression_threshold:
                    patient_counter += 1
                 else:
                    __a					=  0
              else:
                 __a					=  logits.detach().argmax(dim=1    )
                 if patient_result is not None:
                    __a					=  patient_result.detach().argmax(dim=1    )
                 if (patient_result is not None) and torch.all(labels.eq(__A    )    ):
                    patient_counter += 1
                 else:
                    __a					=  0

              __a					=  logits
              if patient_counter == self.patience:
                 break
           __a					=  [patient_result]
           self.inference_layers_num += calculated_layer_num
           self.inference_instances_num += 1

        return res







@add_start_docstrings(
    """Bert Model transformer with PABEE and a sequence classification/regression head on top (a linear layer on top of
    the pooled output) e.g. for GLUE tasks. """ ,					__A ,					)
class     __UpperCAmelCase							(       __A							):


     """simple docstring"""


     def __init__(	self  ,       __A    ):
        super().__init__(__A    )
        __a					=  config.num_labels

        __a					=  BertModelWithPabee(__A    )
        __a					=  nn.Dropout(config.hidden_dropout_prob    )
        __a					=  nn.ModuleList(
            [nn.Linear(config.hidden_size  ,       self.config.num_labels    ) for _ in range(config.num_hidden_layers    )]    )

        self.init_weights()


     @add_start_docstrings_to_model_forward(__A    )
     def 	snake_case_  (	self  ,       __A=None  ,       __A=None  ,       __A=None  ,       __A=None  ,       __A=None  ,       __A=None  ,       __A=None  ,       ):
        __a					=  self.bert(
            input_ids=__A  ,       attention_mask=__A  ,       token_type_ids=__A  ,       position_ids=__A  ,       head_mask=__A  ,       inputs_embeds=__A  ,       output_dropout=self.dropout  ,       output_layers=self.classifiers  ,       regression=self.num_labels == 1  ,       )

        __a					=  (logits[-1],)

        if labels is not None:
           __a					=  None
           __a					=  0
           for ix, logits_item in enumerate(__A    ):
              if self.num_labels == 1:
                 #  We are doing regression
                 __a					=  MSELoss()
                 __a					=  loss_fct(logits_item.view(-1    )  ,       labels.view(-1    )    )
              else:
                 __a					=  CrossEntropyLoss()
                 __a					=  loss_fct(logits_item.view(-1  ,       self.num_labels    )  ,       labels.view(-1    )    )
              if total_loss is None:
                 __a					=  loss
              else:
                 total_loss += loss * (ix + 1)
              total_weights += ix + 1
           __a					=  (total_loss / total_weights,) + outputs

        return outputs







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

from packaging import version

from ..utils import is_torch_available, logging


if is_torch_available():
      import torch


snake_case__				:	int					       =					logging.get_logger(__name__)





@dataclass
class   SCREAMING_SNAKE_CASE_			:




       '''simple docstring'''



       def __init__(						self				:				int		,				__a				:				Optional[Any]=False		,				__a				:				Tuple=False		,				__a				:				Tuple=6.0		,				__a				:				str=None		,				__a				:				List[str]=False		,				__a				:				str=False		,				__a				:				Optional[Any]=None		,				__a				:				Dict="fp4"		,				__a				:				Optional[int]=False		,				**__a				:				Dict		,				)					->str:
          lowerCamelCase_						:   str		= load_in_abit
          lowerCamelCase_						:   Union[str, Any]		= load_in_abit
          lowerCamelCase_						:   Tuple		= llm_inta_threshold
          lowerCamelCase_						:   int		= llm_inta_skip_modules
          lowerCamelCase_						:   List[str]		= llm_inta_enable_fpaa_cpu_offload
          lowerCamelCase_						:   Optional[Any]		= llm_inta_has_fpaa_weight
          lowerCamelCase_						:   Dict		= bnb_abit_quant_type
          lowerCamelCase_						:   int		= bnb_abit_use_double_quant

          if bnb_abit_compute_dtype is None:
             lowerCamelCase_						:   int		= torch.floataa
          elif isinstance(__a		,				__a							):
             lowerCamelCase_						:   Tuple		= getattr(__a		,				__a							)
          elif isinstance(__a		,				torch.dtype							):
             lowerCamelCase_						:   List[str]		= bnb_abit_compute_dtype
          else:
             raise ValueError("""bnb_4bit_compute_dtype must be a string or a torch.dtype"""							)

          self.post_init()



       def 				_lowerCAmelCase							(						self				:				Any							)					->Union[str, Any]:
          if not isinstance(self.llm_inta_threshold		,				__a							):
             raise ValueError("""llm_int8_threshold must be a float"""							)

          if self.llm_inta_skip_modules is not None and not isinstance(self.llm_inta_skip_modules		,				__a							):
             raise ValueError("""llm_int8_skip_modules must be a list of strings"""							)
          if not isinstance(self.llm_inta_enable_fpaa_cpu_offload		,				__a							):
             raise ValueError("""llm_int8_enable_fp32_cpu_offload must be a boolean"""							)

          if not isinstance(self.llm_inta_has_fpaa_weight		,				__a							):
             raise ValueError("""llm_int8_has_fp16_weight must be a boolean"""							)

          if self.bnb_abit_compute_dtype is not None and not isinstance(self.bnb_abit_compute_dtype		,				torch.dtype							):
             raise ValueError("""bnb_4bit_compute_dtype must be torch.dtype"""							)

          if not isinstance(self.bnb_abit_quant_type		,				__a							):
             raise ValueError("""bnb_4bit_quant_type must be a string"""							)

          if not isinstance(self.bnb_abit_use_double_quant		,				__a							):
             raise ValueError("""bnb_4bit_use_double_quant must be a boolean"""							)

          if self.load_in_abit and not version.parse(importlib.metadata.version("""bitsandbytes"""							)							) >= version.parse(
              """0.39.0"""							):
             raise ValueError(
                 """4 bit quantization requires bitsandbytes>=0.39.0 - please upgrade your bitsandbytes version"""							)



       def 				_lowerCAmelCase							(						self				:				Optional[int]							)					->int:
          return self.load_in_abit or self.load_in_abit



       def 				_lowerCAmelCase							(						self				:				List[str]							)					->List[Any]:
          if self.load_in_abit:
             return "llm_int8"
          elif self.load_in_abit and self.bnb_abit_quant_type == "fp4":
             return "fp4"
          elif self.load_in_abit and self.bnb_abit_quant_type == "nf4":
             return "nf4"
          else:
             return None



       @classmethod
       def 				_lowerCAmelCase							(						cls				:				int		,				__a				:				Dict		,				__a				:				str		,				**__a				:				Any							)					->Optional[Any]:
          lowerCamelCase_						:   Optional[Any]		= cls(**__a							)

          lowerCamelCase_						:   List[Any]		= []
          for key, value in kwargs.items():
             if hasattr(__a		,				__a							):
                setattr(__a		,				__a		,				__a							)
                to_remove.append(__a							)
          for key in to_remove:
             kwargs.pop(__a		,				__a							)

          if return_unused_kwargs:
             return config, kwargs
          else:
             return config



       def 				_lowerCAmelCase							(						self				:				Optional[Any]		,				__a				:				Union[str, os.PathLike]							)					->Any:
          with open(__a		,				"""w"""		,				encoding="""utf-8"""							) as writer:
             lowerCamelCase_						:   List[Any]		= self.to_dict()
             lowerCamelCase_						:   Dict		= json.dumps(__a		,				indent=2		,				sort_keys=__a							) + """\n"""

             writer.write(__a							)



       def 				_lowerCAmelCase							(						self				:				Tuple							)					->Dict[str, Any]:
          lowerCamelCase_						:   Dict		= copy.deepcopy(self.__dict__							)
          lowerCamelCase_						:   Tuple		= str(output["""bnb_4bit_compute_dtype"""]							).split("""."""							)[1]

          return output



       def __repr__(						self				:				List[str]							)					->Any:
          return F'''{self.__class__.__name__} {self.to_json_string()}'''



       def 				_lowerCAmelCase							(						self				:				Optional[int]		,				__a				:				bool = True							)					->str:
          if use_diff is True:
             lowerCamelCase_						:   Dict		= self.to_diff_dict()
          else:
             lowerCamelCase_						:   Any		= self.to_dict()
          return json.dumps(__a		,				indent=2		,				sort_keys=__a							) + "\n"




       def 				_lowerCAmelCase							(						self				:				Optional[Any]							)					->Dict[str, Any]:
          lowerCamelCase_						:   Any		= self.to_dict()

          # get the default config dict
          lowerCamelCase_						:   List[str]		= BitsAndBytesConfig().to_dict()

          lowerCamelCase_						:   str		= {}

          # only serialize values that differ from the default config
          for key, value in config_dict.items():
             if value != default_config_dict[key]:
                lowerCamelCase_						:   List[Any]		= value

          return serializable_config_dict





