



import logging
import os
from typing import Dict, List, Optional, Union

import torch
import torch.nn as nn

from accelerate.utils.imports import (
    is_abit_bnb_available,
    is_abit_bnb_available,
    is_bnb_available,
)

from ..big_modeling import dispatch_model, init_empty_weights
from .dataclasses import BnbQuantizationConfig
from .modeling import (
    find_tied_parameters,
    get_balanced_memory,
    infer_auto_device_map,
    load_checkpoint_in_model,
    offload_weight,
    set_module_tensor_to_device,
)


if is_bnb_available():
				import bitsandbytes as bnb

from copy import deepcopy


__A   			=logging.getLogger(__name__)

def        a						(      _UpperCAmelCase							:					torch.nn.Module ,   _UpperCAmelCase							:					BnbQuantizationConfig ,   _UpperCAmelCase							:					Union[str, os.PathLike] = None ,   _UpperCAmelCase							:					Optional[Dict[str, Union[int, str, torch.device]]] = None ,   _UpperCAmelCase							:					Optional[List[str]] = None ,   _UpperCAmelCase							:					Optional[Dict[Union[int, str], Union[int, str]]] = None ,   _UpperCAmelCase							:					Optional[Union[str, os.PathLike]] = None ,   _UpperCAmelCase							:					bool = False ,   ):







		'''simple docstring'''





		__UpperCAmelCase    :     Optional[int]													=	bnb_quantization_config.load_in_abit
		__UpperCAmelCase    :     Any													=	bnb_quantization_config.load_in_abit

		if load_in_abit and not is_abit_bnb_available():
				raise ImportError(
				    '''You have a version of `bitsandbytes` that is not compatible with 8bit quantization,'''
				    ''' make sure you have the latest version of `bitsandbytes` installed.'''						)
		if load_in_abit and not is_abit_bnb_available():
				raise ValueError(
				    '''You have a version of `bitsandbytes` that is not compatible with 4bit quantization,'''
				    '''make sure you have the latest version of `bitsandbytes` installed.'''						)

		__UpperCAmelCase    :     List[Any]													=	[]
		# custom device map
		if isinstance(__A ,   __A						) and len(device_map.keys()						) > 1:
				__UpperCAmelCase    :     Optional[int]													=	[key for key, value in device_map.items() if value in ['disk', 'cpu']]

		# We keep some modules such as the lm_head in their original dtype for numerical stability reasons
		if bnb_quantization_config.skip_modules is None:
				__UpperCAmelCase    :     List[str]													=	get_keys_to_not_convert(__A						)

		# add cpu modules to skip modules only for 4-bit modules
		if load_in_abit:
				bnb_quantization_config.skip_modules.extend(__A						)
		__UpperCAmelCase    :     Union[str, Any]													=	bnb_quantization_config.skip_modules

		# We add the modules we want to keep in full precision
		if bnb_quantization_config.keep_in_fpaa_modules is None:
				__UpperCAmelCase    :     List[Any]													=	[]
		__UpperCAmelCase    :     str													=	bnb_quantization_config.keep_in_fpaa_modules
		modules_to_not_convert.extend(__A						)

		# compatibility with peft
		__UpperCAmelCase    :     Any													=	load_in_abit
		__UpperCAmelCase    :     List[Any]													=	load_in_abit

		__UpperCAmelCase    :     List[Any]													=	get_parameter_device(__A						)
		if model_device.type != "meta":
				# quantization of an already loaded model
				logger.warning(
				    '''It is not recommended to quantize a loaded model. '''
				    '''The model should be instantiated under the `init_empty_weights` context manager.'''						)
				__UpperCAmelCase    :     Any													=	replace_with_bnb_layers(__A ,   __A ,   modules_to_not_convert=__A						)
				# convert param to the right dtype
				__UpperCAmelCase    :     Union[str, Any]													=	bnb_quantization_config.torch_dtype
				for name, param in model.state_dict().items():
						if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules						):
								param.to(torch.floataa						)
								if param.dtype != torch.floataa:
										__UpperCAmelCase    :     int													=	name.replace('''.weight''' ,   ''''''						).replace('''.bias''' ,   ''''''						)
										__UpperCAmelCase    :     int													=	getattr(__A ,   __A ,   __A						)
										if param is not None:
												param.to(torch.floataa						)
						elif torch.is_floating_point(__A						):
								param.to(__A						)
				if model_device.type == "cuda":
						# move everything to cpu in the first place because we can't do quantization if the weights are already on cuda
						model.cuda(torch.cuda.current_device()						)
						torch.cuda.empty_cache()
				elif torch.cuda.is_available():
						model.to(torch.cuda.current_device()						)
				else:
						raise RuntimeError('''No GPU found. A GPU is needed for quantization.'''						)
				logger.info(
				    f'The model device type is {model_device.type}. However, cuda is needed for quantization.'
				    '''We move the model to cuda.'''						)
				return model

		elif weights_location is None:
				raise RuntimeError(
				    f'`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} '						)

		else:
				with init_empty_weights():
						__UpperCAmelCase    :     List[Any]													=	replace_with_bnb_layers(
						    __A ,   __A ,   modules_to_not_convert=__A						)

				__UpperCAmelCase    :     Any													=	get_quantized_model_device_map(
				    __A ,   __A ,   __A ,   max_memory=__A ,   no_split_module_classes=__A ,   )
				if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
						__UpperCAmelCase    :     Dict													=	True

				__UpperCAmelCase    :     Any													=	any(x in list(device_map.values()						) for x in ['''cpu''', '''disk''']						)

				load_checkpoint_in_model(
				    __A ,   __A ,   __A ,   dtype=bnb_quantization_config.torch_dtype ,   offload_folder=__A ,   offload_state_dict=__A ,   keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules ,   offload_abit_bnb=load_in_abit and offload ,   )
				return dispatch_model(__A ,   device_map=__A ,   offload_dir=__A						)

def        a						(      _UpperCAmelCase							:					List[str] ,   _UpperCAmelCase							:					Dict ,   _UpperCAmelCase							:					List[Any]=None ,   _UpperCAmelCase							:					Union[str, Any]=None ,   _UpperCAmelCase							:					Optional[Any]=None						):







		'''simple docstring'''





		if device_map is None:
				if torch.cuda.is_available():
						__UpperCAmelCase    :     Dict													=	{'': torch.cuda.current_device()}
				else:
						raise RuntimeError('''No GPU found. A GPU is needed for quantization.'''						)
				logger.info('''The device_map was not initialized.''' '''Setting device_map to `{\'\':torch.cuda.current_device()}`.'''						)

		if isinstance(__A ,   __A						):
				if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]:
						raise ValueError(
						    '''If passing a string for `device_map`, please choose \'auto\', \'balanced\', \'balanced_low_0\' or '''
						    '''\'sequential\'.'''						)

				__UpperCAmelCase    :     Any													=	{}
				special_dtypes.update(
				    {
				        name: bnb_quantization_config.torch_dtype
				        for name, _ in model.named_parameters()
				        if any(m in name for m in bnb_quantization_config.skip_modules						)
				    }						)
				special_dtypes.update(
				    {
				        name: torch.floataa
				        for name, _ in model.named_parameters()
				        if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules						)
				    }						)

				__UpperCAmelCase    :     Optional[Any]													=	{}
				__UpperCAmelCase    :     Union[str, Any]													=	special_dtypes
				__UpperCAmelCase    :     Optional[int]													=	no_split_module_classes
				__UpperCAmelCase    :     str													=	bnb_quantization_config.target_dtype

				# get max_memory for each device.
				if device_map != "sequential":
						__UpperCAmelCase    :     Optional[Any]													=	get_balanced_memory(
						    __A ,   low_zero=(device_map == '''balanced_low_0''') ,   max_memory=__A ,   **__A ,   )

				__UpperCAmelCase    :     int													=	max_memory
				__UpperCAmelCase    :     Optional[int]													=	infer_auto_device_map(__A ,   **__A						)

		if isinstance(__A ,   __A						):
				# check if don't have any quantized module on the cpu
				__UpperCAmelCase    :     str													=	bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules

				__UpperCAmelCase    :     Optional[Any]													=	{
				    key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert
				}
				for device in ["cpu", "disk"]:
						if device in device_map_without_some_modules.values():
								if bnb_quantization_config.load_in_abit:
										raise ValueError(
										    '''\n                        Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n                        the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n                        these modules in `torch_dtype`, you need to pass a custom `device_map` to\n                        `load_and_quantize_model`. Check\n                        https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n                        for more details.\n                        '''						)
								else:
										logger.info(
										    '''Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit'''						)
				del device_map_without_some_modules
		return device_map

def        a						(      _UpperCAmelCase							:					Tuple ,   _UpperCAmelCase							:					List[str] ,   _UpperCAmelCase							:					List[Any]=None ,   _UpperCAmelCase							:					List[Any]=None						):







		'''simple docstring'''





		if modules_to_not_convert is None:
				__UpperCAmelCase    :     Union[str, Any]													=	[]

		__UpperCAmelCase    :     List[str]													=	_replace_with_bnb_layers(
		    __A ,   __A ,   __A ,   __A						)
		if not has_been_replaced:
				logger.warning(
				    '''You are loading your model in 8bit or 4bit but no linear modules were found in your model.'''
				    ''' this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers.'''
				    ''' Please double check your model architecture, or submit an issue on github if you think this is'''
				    ''' a bug.'''						)
		return model

def        a						(      _UpperCAmelCase							:					int ,   _UpperCAmelCase							:					int ,   _UpperCAmelCase							:					Tuple=None ,   _UpperCAmelCase							:					Any=None ,   ):







		'''simple docstring'''





		__UpperCAmelCase    :     int													=	False
		for name, module in model.named_children():
				if current_key_name is None:
						__UpperCAmelCase    :     List[str]													=	[]
				current_key_name.append(__A						)
				if isinstance(__A ,   nn.Linear						) and name not in modules_to_not_convert:
						# Check if the current key is not in the `modules_to_not_convert`
						__UpperCAmelCase    :     Union[str, Any]													=	'.'.join(__A						)
						__UpperCAmelCase    :     Any													=	True
						for key in modules_to_not_convert:
								if (
								    (key in current_key_name_str) and (key + "." in current_key_name_str)
								) or key == current_key_name_str:
										__UpperCAmelCase    :     int													=	False
										break
						if proceed:
								# Load bnb module with empty weight and replace ``nn.Linear` module
								if bnb_quantization_config.load_in_abit:
										__UpperCAmelCase    :     Union[str, Any]													=	bnb.nn.LinearabitLt(
										    module.in_features ,   module.out_features ,   module.bias is not None ,   has_fpaa_weights=__A ,   threshold=bnb_quantization_config.llm_inta_threshold ,   )
								elif bnb_quantization_config.load_in_abit:
										__UpperCAmelCase    :     Optional[int]													=	bnb.nn.Linearabit(
										    module.in_features ,   module.out_features ,   module.bias is not None ,   bnb_quantization_config.bnb_abit_compute_dtype ,   compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant ,   quant_type=bnb_quantization_config.bnb_abit_quant_type ,   )
								else:
										raise ValueError('''load_in_8bit and load_in_4bit can\'t be both False'''						)
								__UpperCAmelCase    :     Union[str, Any]													=	module.weight.data
								if module.bias is not None:
										__UpperCAmelCase    :     str													=	module.bias.data
								bnb_module.requires_grad_(__A						)
								setattr(__A ,   __A ,   __A						)
								__UpperCAmelCase    :     int													=	True
				if len(list(module.children()						)						) > 0:
						__UpperCAmelCase    :     List[str]													=	_replace_with_bnb_layers(
						    __A ,   __A ,   __A ,   __A						)
						__UpperCAmelCase    :     List[str]													=	has_been_replaced | _has_been_replaced
				# Remove the last key for recursion
				current_key_name.pop(-1						)
		return model, has_been_replaced

def        a						(      _UpperCAmelCase							:					Tuple						):







		'''simple docstring'''





		with init_empty_weights():
				__UpperCAmelCase    :     List[str]													=	deepcopy(__A						)  # this has 0 cost since it is done inside `init_empty_weights` context manager`

		__UpperCAmelCase    :     List[str]													=	find_tied_parameters(__A						)
		# For compatibility with Accelerate < 0.18
		if isinstance(__A ,   __A						):
				__UpperCAmelCase    :     Union[str, Any]													=	sum(list(tied_params.values()						) ,   []						) + list(tied_params.keys()						)
		else:
				__UpperCAmelCase    :     Any													=	sum(__A ,   []						)
		__UpperCAmelCase    :     Optional[int]													=	len(__A						) > 0

		# Check if it is a base model
		__UpperCAmelCase    :     Union[str, Any]													=	False
		if hasattr(__A ,   '''base_model_prefix'''						):
				__UpperCAmelCase    :     Union[str, Any]													=	not hasattr(__A ,   model.base_model_prefix						)

		# Ignore this for base models (BertModel, GPT2Model, etc.)
		if (not has_tied_params) and is_base_model:
				return []

		# otherwise they have an attached head
		__UpperCAmelCase    :     Tuple													=	list(model.named_children()						)
		__UpperCAmelCase    :     str													=	[list_modules[-1][0]]

		# add last module together with tied weights
		__UpperCAmelCase    :     List[str]													=	set(__A						) - set(__A						)
		__UpperCAmelCase    :     Dict													=	list(set(__A						)						) + list(__A						)

		# remove ".weight" from the keys
		__UpperCAmelCase    :     List[str]													=	['.weight', '.bias']
		__UpperCAmelCase    :     List[Any]													=	[]
		for name in list_untouched:
				for name_to_remove in names_to_remove:
						if name_to_remove in name:
								__UpperCAmelCase    :     Dict													=	name.replace(__A ,   ''''''						)
				filtered_module_names.append(__A						)

		return filtered_module_names

def        a						(      _UpperCAmelCase							:					Any						):







		'''simple docstring'''





		for m in model.modules():
				if isinstance(__A ,   bnb.nn.Linearabit						):
						return True
		return False

def        a						(      _UpperCAmelCase							:					nn.Module						):







		'''simple docstring'''





		return next(parameter.parameters()						).device

def        a						(      _UpperCAmelCase							:					Optional[int] ,   _UpperCAmelCase							:					int ,   _UpperCAmelCase							:					Optional[Any] ,   _UpperCAmelCase							:					List[str] ,   _UpperCAmelCase							:					Dict ,   _UpperCAmelCase							:					Tuple ,   _UpperCAmelCase							:					Optional[Any]						):







		'''simple docstring'''





		if fpaa_statistics is None:
				set_module_tensor_to_device(__A ,   __A ,   0 ,   dtype=__A ,   value=__A						)
				__UpperCAmelCase    :     Optional[int]													=	param_name
				__UpperCAmelCase    :     List[str]													=	model
				if "." in tensor_name:
						__UpperCAmelCase    :     int													=	tensor_name.split('''.'''						)
						for split in splits[:-1]:
								__UpperCAmelCase    :     int													=	getattr(__A ,   __A						)
								if new_module is None:
										raise ValueError(f'{module} has no attribute {split}.'						)
								__UpperCAmelCase    :     Optional[Any]													=	new_module
						__UpperCAmelCase    :     List[str]													=	splits[-1]
				# offload weights
				__UpperCAmelCase    :     Union[str, Any]													=	False
				offload_weight(module._parameters[tensor_name] ,   __A ,   __A ,   index=__A						)
				if hasattr(module._parameters[tensor_name] ,   '''SCB'''						):
						offload_weight(
						    module._parameters[tensor_name].SCB ,   param_name.replace('''weight''' ,   '''SCB'''						) ,   __A ,   index=__A ,   )
		else:
				offload_weight(__A ,   __A ,   __A ,   index=__A						)
				offload_weight(__A ,   param_name.replace('''weight''' ,   '''SCB'''						) ,   __A ,   index=__A						)

		set_module_tensor_to_device(__A ,   __A ,   '''meta''' ,   dtype=__A ,   value=torch.empty(*param.size()						)						)









import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
   import torch

   from transformers import (
       OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
       OpenAIGPTConfig,
       OpenAIGPTDoubleHeadsModel,
       OpenAIGPTForSequenceClassification,
       OpenAIGPTLMHeadModel,
       OpenAIGPTModel,
   )
class  SCREAMING_SNAKE_CASE__  :
      def __init__(       self				:       List[str]     ,							SCREAMING_SNAKE_CASE__				:       Dict     ,							SCREAMING_SNAKE_CASE__				:       Tuple=1_3     ,							SCREAMING_SNAKE_CASE__				:       str=7     ,							SCREAMING_SNAKE_CASE__				:       List[str]=True     ,							SCREAMING_SNAKE_CASE__				:       Optional[Any]=True     ,							SCREAMING_SNAKE_CASE__				:       Union[str, Any]=True     ,							SCREAMING_SNAKE_CASE__				:       Optional[Any]=9_9     ,							SCREAMING_SNAKE_CASE__				:       Optional[Any]=3_2     ,							SCREAMING_SNAKE_CASE__				:       List[str]=5     ,							SCREAMING_SNAKE_CASE__				:       List[Any]=4     ,							SCREAMING_SNAKE_CASE__				:       Tuple=3_7     ,							SCREAMING_SNAKE_CASE__				:       Any="gelu"     ,							SCREAMING_SNAKE_CASE__				:       Dict=0.1     ,							SCREAMING_SNAKE_CASE__				:       Dict=0.1     ,							SCREAMING_SNAKE_CASE__				:       int=5_1_2     ,							SCREAMING_SNAKE_CASE__				:       int=1_6     ,							SCREAMING_SNAKE_CASE__				:       Optional[int]=2     ,							SCREAMING_SNAKE_CASE__				:       Any=0.02     ,							SCREAMING_SNAKE_CASE__				:       Union[str, Any]=3     ,							SCREAMING_SNAKE_CASE__				:       Optional[Any]=4     ,							SCREAMING_SNAKE_CASE__				:       Optional[int]=None     ,							)		->			Any:
             a_					:		Tuple							=  parent
             a_					:		int							=  batch_size
             a_					:		Tuple							=  seq_length
             a_					:		List[Any]							=  is_training
             a_					:		List[str]							=  use_token_type_ids
             a_					:		Dict							=  use_labels
             a_					:		Any							=  vocab_size
             a_					:		List[str]							=  hidden_size
             a_					:		Tuple							=  num_hidden_layers
             a_					:		List[Any]							=  num_attention_heads
             a_					:		Dict							=  intermediate_size
             a_					:		Any							=  hidden_act
             a_					:		List[str]							=  hidden_dropout_prob
             a_					:		Tuple							=  attention_probs_dropout_prob
             a_					:		Optional[Any]							=  max_position_embeddings
             a_					:		List[Any]							=  type_vocab_size
             a_					:		int							=  type_sequence_label_size
             a_					:		List[Any]							=  initializer_range
             a_					:		List[str]							=  num_labels
             a_					:		Union[str, Any]							=  num_choices
             a_					:		str							=  scope
             a_					:		Tuple							=  self.vocab_size - 1
      def        SCREAMING_SNAKE_CASE							(       self				:       Union[str, Any]     )		->			Any:
             a_					:		Optional[int]							=  ids_tensor([self.batch_size, self.seq_length]     ,							self.vocab_size     )

             a_					:		Any							=  None
             if self.use_token_type_ids:
                    a_					:		Tuple							=  ids_tensor([self.batch_size, self.seq_length]     ,							self.type_vocab_size     )

             a_					:		List[Any]							=  None
             a_					:		Union[str, Any]							=  None
             a_					:		List[Any]							=  None
             if self.use_labels:
                    a_					:		Tuple							=  ids_tensor([self.batch_size]     ,							self.type_sequence_label_size     )
                    a_					:		Any							=  ids_tensor([self.batch_size, self.seq_length]     ,							self.num_labels     )
                    a_					:		List[Any]							=  ids_tensor([self.batch_size]     ,							self.num_choices     )

             a_					:		Union[str, Any]							=  OpenAIGPTConfig(
                 vocab_size=self.vocab_size     ,							n_embd=self.hidden_size     ,							n_layer=self.num_hidden_layers     ,							n_head=self.num_attention_heads     ,							n_positions=self.max_position_embeddings     ,							pad_token_id=self.pad_token_id     ,							)

             a_					:		List[str]							=  ids_tensor([self.num_hidden_layers, self.num_attention_heads]     ,							2     )

             return (
                 config,
                 input_ids,
                 head_mask,
                 token_type_ids,
                 sequence_labels,
                 token_labels,
                 choice_labels,
             )
      def        SCREAMING_SNAKE_CASE							(       self				:       List[str]     ,							SCREAMING_SNAKE_CASE__				:       Any     ,							SCREAMING_SNAKE_CASE__				:       Union[str, Any]     ,							SCREAMING_SNAKE_CASE__				:       Any     ,							SCREAMING_SNAKE_CASE__				:       List[str]     ,							*SCREAMING_SNAKE_CASE__				:       Tuple     )		->			Union[str, Any]:
             a_					:		Dict							=  OpenAIGPTModel(config=SCREAMING_SNAKE_CASE__     )
             model.to(SCREAMING_SNAKE_CASE__     )
             model.eval()

             a_					:		str							=  model(SCREAMING_SNAKE_CASE__     ,							token_type_ids=SCREAMING_SNAKE_CASE__     ,							head_mask=SCREAMING_SNAKE_CASE__     )
             a_					:		Dict							=  model(SCREAMING_SNAKE_CASE__     ,							token_type_ids=SCREAMING_SNAKE_CASE__     )
             a_					:		Dict							=  model(SCREAMING_SNAKE_CASE__     )

             self.parent.assertEqual(result.last_hidden_state.shape     ,							(self.batch_size, self.seq_length, self.hidden_size)     )
      def        SCREAMING_SNAKE_CASE							(       self				:       Optional[int]     ,							SCREAMING_SNAKE_CASE__				:       List[str]     ,							SCREAMING_SNAKE_CASE__				:       Tuple     ,							SCREAMING_SNAKE_CASE__				:       Tuple     ,							SCREAMING_SNAKE_CASE__				:       Union[str, Any]     ,							*SCREAMING_SNAKE_CASE__				:       Optional[int]     )		->			Any:
             a_					:		str							=  OpenAIGPTLMHeadModel(SCREAMING_SNAKE_CASE__     )
             model.to(SCREAMING_SNAKE_CASE__     )
             model.eval()

             a_					:		Optional[int]							=  model(SCREAMING_SNAKE_CASE__     ,							token_type_ids=SCREAMING_SNAKE_CASE__     ,							labels=SCREAMING_SNAKE_CASE__     )
             self.parent.assertEqual(result.loss.shape     ,							()     )
             self.parent.assertEqual(result.logits.shape     ,							(self.batch_size, self.seq_length, self.vocab_size)     )
      def        SCREAMING_SNAKE_CASE							(       self				:       Optional[Any]     ,							SCREAMING_SNAKE_CASE__				:       Optional[Any]     ,							SCREAMING_SNAKE_CASE__				:       int     ,							SCREAMING_SNAKE_CASE__				:       Optional[int]     ,							SCREAMING_SNAKE_CASE__				:       Optional[Any]     ,							*SCREAMING_SNAKE_CASE__				:       Union[str, Any]     )		->			Dict:
             a_					:		int							=  OpenAIGPTDoubleHeadsModel(SCREAMING_SNAKE_CASE__     )
             model.to(SCREAMING_SNAKE_CASE__     )
             model.eval()

             a_					:		str							=  model(SCREAMING_SNAKE_CASE__     ,							token_type_ids=SCREAMING_SNAKE_CASE__     ,							labels=SCREAMING_SNAKE_CASE__     )
             self.parent.assertEqual(result.loss.shape     ,							()     )
             self.parent.assertEqual(result.logits.shape     ,							(self.batch_size, self.seq_length, self.vocab_size)     )
      def        SCREAMING_SNAKE_CASE							(       self				:       Tuple     ,							SCREAMING_SNAKE_CASE__				:       Dict     ,							SCREAMING_SNAKE_CASE__				:       Dict     ,							SCREAMING_SNAKE_CASE__				:       List[Any]     ,							SCREAMING_SNAKE_CASE__				:       Union[str, Any]     ,							*SCREAMING_SNAKE_CASE__				:       str     )		->			List[str]:
             a_					:		Any							=  self.num_labels
             a_					:		Dict							=  OpenAIGPTForSequenceClassification(SCREAMING_SNAKE_CASE__     )
             model.to(SCREAMING_SNAKE_CASE__     )
             model.eval()

             a_					:		Dict							=  ids_tensor([self.batch_size]     ,							self.type_sequence_label_size     )
             a_					:		Any							=  model(SCREAMING_SNAKE_CASE__     ,							token_type_ids=SCREAMING_SNAKE_CASE__     ,							labels=SCREAMING_SNAKE_CASE__     )
             self.parent.assertEqual(result.logits.shape     ,							(self.batch_size, self.num_labels)     )

      def        SCREAMING_SNAKE_CASE							(       self				:       Union[str, Any]     )		->			Tuple:
             a_					:		Optional[Any]							=  self.prepare_config_and_inputs()
             (
                 (
                 a_
             )							,		(
                 a_
             )							,		(
                 a_
             )							,		(
                 a_
             )							,		(
                 a_
             )							,		(
                 a_
             )							,		(
                 a_
             )							,		
             )					:		Optional[Any]							=  config_and_inputs
             a_					:		Optional[int]							=  {
                 'input_ids': input_ids,
                 'token_type_ids': token_type_ids,
                 'head_mask': head_mask,
             }

             return config, inputs_dict
@require_torch
class  SCREAMING_SNAKE_CASE__  (				lowercase__						,    lowercase__						,    lowercase__						,    unittest.TestCase			):
      snake_case__				:     Tuple        =						(
          (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
          if is_torch_available()
          else ()
      )
      snake_case__				:     List[str]        =						(
          (OpenAIGPTLMHeadModel,) if is_torch_available() else ()
      )  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
      snake_case__				:     Dict        =						(
          {
              '''feature-extraction''': OpenAIGPTModel,
              '''text-classification''': OpenAIGPTForSequenceClassification,
              '''text-generation''': OpenAIGPTLMHeadModel,
              '''zero-shot''': OpenAIGPTForSequenceClassification,
          }
          if is_torch_available()
          else {}
      )
      def        SCREAMING_SNAKE_CASE							(       self				:       List[str]     ,							SCREAMING_SNAKE_CASE__				:       Tuple     ,							SCREAMING_SNAKE_CASE__				:       Optional[Any]     ,							SCREAMING_SNAKE_CASE__				:       Tuple     ,							SCREAMING_SNAKE_CASE__				:       Dict     ,							SCREAMING_SNAKE_CASE__				:       List[str]     )		->			Dict:
             if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
                    # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
                    # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a
                    # tiny config could not be created.
                    return True

             return False
      def        SCREAMING_SNAKE_CASE							(       self				:       int     ,							SCREAMING_SNAKE_CASE__				:       Dict     ,							SCREAMING_SNAKE_CASE__				:       Dict     ,							SCREAMING_SNAKE_CASE__				:       Any=False     )		->			List[str]:
             a_					:		str							=  super()._prepare_for_class(SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     ,							return_labels=SCREAMING_SNAKE_CASE__     )

             if return_labels:
                    if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
                           a_					:		Optional[Any]							=  torch.zeros(
                               (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length)     ,							dtype=torch.long     ,							device=SCREAMING_SNAKE_CASE__     ,							)
                           a_					:		str							=  inputs_dict['labels']
                           a_					:		Optional[int]							=  inputs_dict['labels']
                           a_					:		Optional[int]							=  torch.zeros(
                               (self.model_tester.batch_size, self.model_tester.num_choices)     ,							dtype=torch.long     ,							device=SCREAMING_SNAKE_CASE__     ,							)
                           a_					:		Union[str, Any]							=  torch.zeros(
                               self.model_tester.batch_size     ,							dtype=torch.long     ,							device=SCREAMING_SNAKE_CASE__     )
             return inputs_dict
      def        SCREAMING_SNAKE_CASE							(       self				:       str     )		->			List[Any]:
             a_					:		str							=  OpenAIGPTModelTester(self     )
             a_					:		int							=  ConfigTester(self     ,							config_class=SCREAMING_SNAKE_CASE__     ,							n_embd=3_7     )
      def        SCREAMING_SNAKE_CASE							(       self				:       Tuple     )		->			Tuple:
             self.config_tester.run_common_tests()
      def        SCREAMING_SNAKE_CASE							(       self				:       List[Any]     )		->			Tuple:
             a_					:		Dict							=  self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_openai_gpt_model(*SCREAMING_SNAKE_CASE__     )
      def        SCREAMING_SNAKE_CASE							(       self				:       Optional[int]     )		->			Tuple:
             a_					:		Any							=  self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_lm_head_model(*SCREAMING_SNAKE_CASE__     )
      def        SCREAMING_SNAKE_CASE							(       self				:       Any     )		->			Optional[Any]:
             a_					:		Optional[int]							=  self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_double_lm_head_model(*SCREAMING_SNAKE_CASE__     )
      def        SCREAMING_SNAKE_CASE							(       self				:       Optional[Any]     )		->			Optional[Any]:
             a_					:		int							=  self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*SCREAMING_SNAKE_CASE__     )

      @slow
      def        SCREAMING_SNAKE_CASE							(       self				:       List[str]     )		->			str:
             for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    a_					:		str							=  OpenAIGPTModel.from_pretrained(SCREAMING_SNAKE_CASE__     )
                    self.assertIsNotNone(SCREAMING_SNAKE_CASE__     )
@require_torch
class  SCREAMING_SNAKE_CASE__  (				unittest.TestCase			):
      @slow
      def        SCREAMING_SNAKE_CASE							(       self				:       Dict     )		->			int:
             a_					:		Dict							=  OpenAIGPTLMHeadModel.from_pretrained('openai-gpt'     )
             model.to(SCREAMING_SNAKE_CASE__     )
             a_					:		List[Any]							=  torch.tensor([[4_8_1, 4_7_3_5, 5_4_4]]     ,							dtype=torch.long     ,							device=SCREAMING_SNAKE_CASE__     )  # the president is
             a_					:		Tuple							=  [
                 4_8_1,
                 4_7_3_5,
                 5_4_4,
                 2_4_6,
                 9_6_3,
                 8_7_0,
                 7_6_2,
                 2_3_9,
                 2_4_4,
                 4_0_4_7_7,
                 2_4_4,
                 2_4_9,
                 7_1_9,
                 8_8_1,
                 4_8_7,
                 5_4_4,
                 2_4_0,
                 2_4_4,
                 6_0_3,
                 4_8_1,
             ]  # the president is a very good man. " \n " i\'m sure he is, " said the

             a_					:		Dict							=  model.generate(SCREAMING_SNAKE_CASE__     ,							do_sample=SCREAMING_SNAKE_CASE__     )
             self.assertListEqual(output_ids[0].tolist()     ,							SCREAMING_SNAKE_CASE__     )


