





# 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


UpperCamelCase__           =			logging.get_logger(__name__)

@dataclass
class 							__SCREAMING_SNAKE_CASE       :






							def __init__(    self	,			__lowerCAmelCase=False	,			__lowerCAmelCase=False	,			__lowerCAmelCase=6.0	,			__lowerCAmelCase=None	,			__lowerCAmelCase=False	,			__lowerCAmelCase=False	,			__lowerCAmelCase=None	,			__lowerCAmelCase="fp4"	,			__lowerCAmelCase=False	,			**__lowerCAmelCase	,			):
														UpperCamelCase__					  =      load_in_abit
														UpperCamelCase__					  =      load_in_abit
														UpperCamelCase__					  =      llm_inta_threshold
														UpperCamelCase__					  =      llm_inta_skip_modules
														UpperCamelCase__					  =      llm_inta_enable_fpaa_cpu_offload
														UpperCamelCase__					  =      llm_inta_has_fpaa_weight
														UpperCamelCase__					  =      bnb_abit_quant_type
														UpperCamelCase__					  =      bnb_abit_use_double_quant

														if bnb_abit_compute_dtype is None:
																					UpperCamelCase__					  =      torch.floataa
														elif isinstance(__lowerCAmelCase	,			__lowerCAmelCase	):
																					UpperCamelCase__					  =      getattr(__lowerCAmelCase	,			__lowerCAmelCase	)
														elif isinstance(__lowerCAmelCase	,			torch.dtype	):
																					UpperCamelCase__					  =      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	):
														if not isinstance(self.llm_inta_threshold	,			__lowerCAmelCase	):
																					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	,			__lowerCAmelCase	):
																					raise ValueError("""llm_int8_skip_modules must be a list of strings"""	)
														if not isinstance(self.llm_inta_enable_fpaa_cpu_offload	,			__lowerCAmelCase	):
																					raise ValueError("""llm_int8_enable_fp32_cpu_offload must be a boolean"""	)

														if not isinstance(self.llm_inta_has_fpaa_weight	,			__lowerCAmelCase	):
																					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	,			__lowerCAmelCase	):
																					raise ValueError("""bnb_4bit_quant_type must be a string"""	)

														if not isinstance(self.bnb_abit_use_double_quant	,			__lowerCAmelCase	):
																					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	):
														return self.load_in_abit or self.load_in_abit






							def 					_lowerCamelCase		(    self	):
														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	,			__lowerCAmelCase	,			__lowerCAmelCase	,			**__lowerCAmelCase	):
														UpperCamelCase__					  =      cls(**__lowerCAmelCase	)

														UpperCamelCase__					  =      []
														for key, value in kwargs.items():
																					if hasattr(__lowerCAmelCase	,			__lowerCAmelCase	):
																												setattr(__lowerCAmelCase	,			__lowerCAmelCase	,			__lowerCAmelCase	)
																												to_remove.append(__lowerCAmelCase	)
														for key in to_remove:
																					kwargs.pop(__lowerCAmelCase	,			__lowerCAmelCase	)

														if return_unused_kwargs:
																					return config, kwargs
														else:
																					return config






							def 					_lowerCamelCase		(    self	,			__lowerCAmelCase	):
														with open(__lowerCAmelCase	,			"""w"""	,			encoding="""utf-8"""	) as writer:
																					UpperCamelCase__					  =      self.to_dict()
																					UpperCamelCase__					  =      json.dumps(__lowerCAmelCase	,			indent=2	,			sort_keys=__lowerCAmelCase	) + """\n"""

																					writer.write(__lowerCAmelCase	)






							def 					_lowerCamelCase		(    self	):
														UpperCamelCase__					  =      copy.deepcopy(self.__dict__	)
														UpperCamelCase__					  =      str(output["""bnb_4bit_compute_dtype"""]	).split("""."""	)[1]

														return output






							def __repr__(    self	):
														return f"""{self.__class__.__name__} {self.to_json_string()}"""






							def 					_lowerCamelCase		(    self	,			__lowerCAmelCase = True	):
														if use_diff is True:
																					UpperCamelCase__					  =      self.to_diff_dict()
														else:
																					UpperCamelCase__					  =      self.to_dict()
														return json.dumps(__lowerCAmelCase	,			indent=2	,			sort_keys=__lowerCAmelCase	) + "\n"







							def 					_lowerCamelCase		(    self	):
														UpperCamelCase__					  =      self.to_dict()

														# get the default config dict
														UpperCamelCase__					  =      BitsAndBytesConfig().to_dict()

														UpperCamelCase__					  =      {}

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

														return serializable_config_dict











from dataclasses import dataclass
from typing import Optional, Tuple

import torch
from torch import nn
from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel
from transformers.utils import ModelOutput

@dataclass
class 							__SCREAMING_SNAKE_CASE       (  _a							):
							snake_case  :   Optional[torch.FloatTensor]      =							None
							snake_case  :   torch.FloatTensor      =							None
							snake_case  :   Optional[Tuple[torch.FloatTensor]]      =							None
							snake_case  :   Optional[Tuple[torch.FloatTensor]]      =							None






class 							__SCREAMING_SNAKE_CASE       (  _a							):






							def __init__(    self	,			__lowerCAmelCase=1	,			__lowerCAmelCase=0	,			__lowerCAmelCase=2	,			__lowerCAmelCase=512	,			__lowerCAmelCase="cls"	,			__lowerCAmelCase=False	,			__lowerCAmelCase=True	,			**__lowerCAmelCase	,			):
														super().__init__(pad_token_id=__lowerCAmelCase	,			bos_token_id=__lowerCAmelCase	,			eos_token_id=__lowerCAmelCase	,			**__lowerCAmelCase	)
														UpperCamelCase__					  =      project_dim
														UpperCamelCase__					  =      pooler_fn
														UpperCamelCase__					  =      learn_encoder
														UpperCamelCase__					  =      use_attention_mask






class 							__SCREAMING_SNAKE_CASE       (  _a							):
							snake_case  :   int      =							[r"""pooler""", r"""logit_scale"""]
							snake_case  :   Tuple      =							[r"""position_ids""", r"""predictions.decoder.bias"""]
							snake_case  :   str      =							"""roberta"""
							snake_case  :   Dict      =							RobertaSeriesConfig






							def __init__(    self	,			__lowerCAmelCase	):
														super().__init__(__lowerCAmelCase	)
														UpperCamelCase__					  =      XLMRobertaModel(__lowerCAmelCase	)
														UpperCamelCase__					  =      nn.Linear(config.hidden_size	,			config.project_dim	)
														UpperCamelCase__					  =      getattr(__lowerCAmelCase	,			"""has_pre_transformation"""	,			__lowerCAmelCase	)
														if self.has_pre_transformation:
																					UpperCamelCase__					  =      nn.Linear(config.hidden_size	,			config.project_dim	)
																					UpperCamelCase__					  =      nn.LayerNorm(config.hidden_size	,			eps=config.layer_norm_eps	)
														self.post_init()







							def 					_lowerCamelCase		(    self	,			__lowerCAmelCase = None	,			__lowerCAmelCase = None	,			__lowerCAmelCase = None	,			__lowerCAmelCase = None	,			__lowerCAmelCase = None	,			__lowerCAmelCase = None	,			__lowerCAmelCase = None	,			__lowerCAmelCase = None	,			__lowerCAmelCase = None	,			__lowerCAmelCase = None	,			__lowerCAmelCase = None	,			):
														UpperCamelCase__					  =      return_dict if return_dict is not None else self.config.use_return_dict

														UpperCamelCase__					  =      self.base_model(
														    input_ids=__lowerCAmelCase	,			attention_mask=__lowerCAmelCase	,			token_type_ids=__lowerCAmelCase	,			position_ids=__lowerCAmelCase	,			head_mask=__lowerCAmelCase	,			inputs_embeds=__lowerCAmelCase	,			encoder_hidden_states=__lowerCAmelCase	,			encoder_attention_mask=__lowerCAmelCase	,			output_attentions=__lowerCAmelCase	,			output_hidden_states=True if self.has_pre_transformation else output_hidden_states	,			return_dict=__lowerCAmelCase	,			)

														if self.has_pre_transformation:
																					UpperCamelCase__					  =      outputs["""hidden_states"""][-2]
																					UpperCamelCase__					  =      self.pre_LN(__lowerCAmelCase	)
																					UpperCamelCase__					  =      self.transformation_pre(__lowerCAmelCase	)

																					return TransformationModelOutput(
																					    projection_state=__lowerCAmelCase	,			last_hidden_state=outputs.last_hidden_state	,			hidden_states=outputs.hidden_states	,			attentions=outputs.attentions	,			)
														else:
																					UpperCamelCase__					  =      self.transformation(outputs.last_hidden_state	)
																					return TransformationModelOutput(
																					    projection_state=__lowerCAmelCase	,			last_hidden_state=outputs.last_hidden_state	,			hidden_states=outputs.hidden_states	,			attentions=outputs.attentions	,			)




