





import copy
import fnmatch
import json
import os
import pickle as pkl
import shutil
import sys
import tarfile
import tempfile
from collections import OrderedDict
from contextlib import contextmanager
from functools import partial
from hashlib import shaaaa
from io import BytesIO
from pathlib import Path
from urllib.parse import urlparse
from zipfile import ZipFile, is_zipfile

import cva
import numpy as np
import requests
import wget
from filelock import FileLock
from PIL import Image
from tqdm.auto import tqdm
from yaml import Loader, dump, load


try:
			import torch

			_a     :    Dict         =						True
except ImportError:
			_a     :    Optional[int]         =						False


try:
			from torch.hub import _get_torch_home

			_a     :    Union[str, Any]         =						_get_torch_home()
except ImportError:
			_a     :    List[Any]         =						os.path.expanduser(
			    os.getenv('TORCH_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'torch'))
			)

_a     :    List[str]         =						os.path.join(torch_cache_home, 'transformers')

_a     :    Union[str, Any]         =						'https://cdn.huggingface.co'
_a     :    Any         =						'https://s3.amazonaws.com/models.huggingface.co/bert'
_a     :    Optional[int]         =						'/'.join(str(Path(__file__).resolve()).split('/')[:-1])
_a     :    List[str]         =						os.path.join(PATH, 'config.yaml')
_a     :    Optional[Any]         =						os.path.join(PATH, 'attributes.txt')
_a     :    int         =						os.path.join(PATH, 'objects.txt')
_a     :    Tuple         =						os.getenv('PYTORCH_PRETRAINED_BERT_CACHE', default_cache_path)
_a     :    Any         =						os.getenv('PYTORCH_TRANSFORMERS_CACHE', PYTORCH_PRETRAINED_BERT_CACHE)
_a     :    List[Any]         =						os.getenv('TRANSFORMERS_CACHE', PYTORCH_TRANSFORMERS_CACHE)
_a     :    List[Any]         =						'pytorch_model.bin'
_a     :    Optional[Any]         =						'config.yaml'
def 							a_	(    __magic_name__=OBJECTS		,     __magic_name__=ATTRIBUTES   )				->			Optional[int]:




				"""simple docstring"""






				snake_case   :					Tuple    						=				[]
				with open(_snake_case   ) as f:
								for object in f.readlines():
												vg_classes.append(object.split(''','''   )[0].lower().strip()   )

				snake_case   :					List[Any]    						=				[]
				with open(_snake_case   ) as f:
								for object in f.readlines():
												vg_attrs.append(object.split(''','''   )[0].lower().strip()   )
				return vg_classes, vg_attrs
def 							a_	(    __magic_name__   )				->			Union[str, Any]:




				"""simple docstring"""






				snake_case   :					List[str]    						=				OrderedDict()
				with open(_snake_case		,     '''rb'''   ) as f:
								snake_case   :					Optional[int]    						=				pkl.load(_snake_case   )['''model''']
				for k in copy.deepcopy(list(ckp.keys()   )   ):
								snake_case   :					Union[str, Any]    						=				ckp.pop(_snake_case   )
								if isinstance(_snake_case		,     np.ndarray   ):
												snake_case   :					Optional[Any]    						=				torch.tensor(_snake_case   )
								else:
												assert isinstance(_snake_case		,     torch.tensor   ), type(_snake_case   )
								snake_case   :					Any    						=				v
				return r
class   a_ :
			A__      :			Optional[int]       	=  {}

			def __init__(   self   :  int     , UpperCAmelCase__   :  Tuple     , UpperCAmelCase__   :  Optional[Any] = "root"     , UpperCAmelCase__   :  Optional[int]=0						):






							"""simple docstring"""
							snake_case   :					Optional[int]    						=				name
							snake_case   :					Dict    						=				level
							snake_case   :					List[str]    						=				{}
							for k, v in dictionary.items():
											if v is None:
															raise ValueError()
											snake_case   :					Tuple    						=				copy.deepcopy(UpperCAmelCase_						)
											snake_case   :					Optional[int]    						=				copy.deepcopy(UpperCAmelCase_						)
											if isinstance(UpperCAmelCase_     , UpperCAmelCase_						):
															snake_case   :					Any    						=				Config(UpperCAmelCase_     , name=UpperCAmelCase_     , level=level + 1						)
											snake_case   :					Any    						=				v
											setattr(self     , UpperCAmelCase_     , UpperCAmelCase_						)

							snake_case   :					Tuple    						=				d

			def __repr__(   self   :  Optional[int]						):






							"""simple docstring"""
							return str(list((self._pointer.keys())						)						)

			def __setattr__(   self   :  Any     , UpperCAmelCase__   :  Dict     , UpperCAmelCase__   :  Optional[int]						):






							"""simple docstring"""
							snake_case   :					str    						=				val
							snake_case   :					Union[str, Any]    						=				val
							snake_case   :					str    						=				key.split('''.'''						)
							snake_case   :					List[str]    						=				len(UpperCAmelCase_						) - 1
							snake_case   :					Any    						=				self._pointer
							if len(UpperCAmelCase_						) > 1:
											for i, l in enumerate(UpperCAmelCase_						):
															if hasattr(self     , UpperCAmelCase_						) and isinstance(getattr(self     , UpperCAmelCase_						)     , UpperCAmelCase_						):
																			setattr(getattr(self     , UpperCAmelCase_						)     , '''.'''.join(levels[i:]						)     , UpperCAmelCase_						)
															if l == last_level:
																			snake_case   :					Union[str, Any]    						=				val
															else:
																			snake_case   :					Optional[Any]    						=				pointer[l]

			def      lowerCAmelCase(   self   :  List[Any]						):






							"""simple docstring"""
							return self._pointer

			def      lowerCAmelCase(   self   :  int     , UpperCAmelCase__   :  List[str]     , UpperCAmelCase__   :  Any						):






							"""simple docstring"""
							with open(F"{file_name}"     , '''w'''						) as stream:
											dump(UpperCAmelCase_     , UpperCAmelCase_						)

			def      lowerCAmelCase(   self   :  str     , UpperCAmelCase__   :  Union[str, Any]     , UpperCAmelCase__   :  List[str]						):






							"""simple docstring"""
							with open(F"{file_name}"     , '''w'''						) as stream:
											json.dump(UpperCAmelCase_     , UpperCAmelCase_						)

			@staticmethod
			def      lowerCAmelCase(   UpperCAmelCase__   :  Any						):






							"""simple docstring"""
							with open(UpperCAmelCase_						) as stream:
											snake_case   :					int    						=				load(UpperCAmelCase_     , Loader=UpperCAmelCase_						)
							return data

			def __str__(   self   :  List[str]						):






							"""simple docstring"""
							snake_case   :					Optional[int]    						=				'''    '''
							if self._name != "root":
											snake_case   :					List[Any]    						=				F"{t * (self._level-1)}{self._name}:\n"
							else:
											snake_case   :					Dict    						=				''''''
							snake_case   :					int    						=				self._level
							for i, (k, v) in enumerate(self._pointer.items()						):
											if isinstance(UpperCAmelCase_     , UpperCAmelCase_						):
															r += F"{t * (self._level)}{v}\n"
															self._level += 1
											else:
															r += F"{t * (self._level)}{k}: {v} ({type(UpperCAmelCase_						).__name__})\n"
											snake_case   :					Tuple    						=				level
							return r[:-1]

			@classmethod
			def      lowerCAmelCase(   cls   :  int     , UpperCAmelCase__   :  int     , **UpperCAmelCase__   :  int						):






							"""simple docstring"""
							snake_case						,						snake_case   :					Union[str, Any]    						=				cls.get_config_dict(UpperCAmelCase_     , **UpperCAmelCase_						)
							return cls(UpperCAmelCase_						)



			@classmethod
			def      lowerCAmelCase(   cls   :  Union[str, Any]     , UpperCAmelCase__   :  Optional[Any]     , **UpperCAmelCase__   :  Dict						):






							"""simple docstring"""
							snake_case   :					int    						=				kwargs.pop('''cache_dir'''     , UpperCAmelCase_						)
							snake_case   :					Dict    						=				kwargs.pop('''force_download'''     , UpperCAmelCase_						)
							snake_case   :					Tuple    						=				kwargs.pop('''resume_download'''     , UpperCAmelCase_						)
							snake_case   :					List[str]    						=				kwargs.pop('''proxies'''     , UpperCAmelCase_						)
							snake_case   :					Dict    						=				kwargs.pop('''local_files_only'''     , UpperCAmelCase_						)

							if os.path.isdir(UpperCAmelCase_						):
											snake_case   :					Any    						=				os.path.join(UpperCAmelCase_     , UpperCAmelCase_						)
							elif os.path.isfile(UpperCAmelCase_						) or is_remote_url(UpperCAmelCase_						):
											snake_case   :					Optional[Any]    						=				pretrained_model_name_or_path
							else:
											snake_case   :					Optional[Any]    						=				hf_bucket_url(UpperCAmelCase_     , filename=UpperCAmelCase_     , use_cdn=UpperCAmelCase_						)

							try:
											# Load from URL or cache if already cached
											snake_case   :					int    						=				cached_path(
											    UpperCAmelCase_     , cache_dir=UpperCAmelCase_     , force_download=UpperCAmelCase_     , proxies=UpperCAmelCase_     , resume_download=UpperCAmelCase_     , local_files_only=UpperCAmelCase_     , )
											# Load config dict
											if resolved_config_file is None:
															raise EnvironmentError

											snake_case   :					Tuple    						=				Config.load_yaml(UpperCAmelCase_						)

							except EnvironmentError:
											snake_case   :					List[str]    						=				'''Can\'t load config for'''
											raise EnvironmentError(UpperCAmelCase_						)

							if resolved_config_file == config_file:
											print('''loading configuration file from path'''						)
							else:
											print('''loading configuration file cache'''						)

							return Config.load_yaml(UpperCAmelCase_						), kwargs
def 							a_	(    __magic_name__   )				->			List[Any]:




				"""simple docstring"""






				snake_case   :					int    						=				torch.load('''dump.pt'''		,     map_location=in_tensor.device   )
				snake_case   :					Optional[int]    						=				in_tensor.numpy()
				snake_case   :					Optional[int]    						=				out_tensor.numpy()[0]
				print(na.shape		,     na[0, 0, :5]   )
				print(na.shape		,     na[0, 0, :5]   )
				assert np.allclose(_snake_case		,     _snake_case		,     rtol=0.01		,     atol=0.1   ), (
				    F"{sum([1 for x in np.isclose(_snake_case		,     _snake_case		,     rtol=0.01		,     atol=0.1   ).flatten() if x is False]   )/len(na.flatten()   )*100:.4f} %"
				    " element-wise mismatch"
				)
				raise Exception('''tensors are all good'''   )

				# Hugging face functions below
def 							a_	(    __magic_name__   )				->			List[str]:




				"""simple docstring"""






				snake_case   :					int    						=				urlparse(_snake_case   )
				return parsed.scheme in ("http", "https")
def 							a_	(    __magic_name__		,     __magic_name__		,     __magic_name__=True   )				->			Tuple:




				"""simple docstring"""






				snake_case   :					Union[str, Any]    						=				CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
				snake_case   :					Dict    						=				'''/''' not in model_id
				if legacy_format:
								return F"{endpoint}/{model_id}-{filename}"
				else:
								return F"{endpoint}/{model_id}/{filename}"
def 							a_	(    __magic_name__		,     __magic_name__		,     __magic_name__=None		,     __magic_name__=0		,     __magic_name__=None		,     )				->			Optional[int]:




				"""simple docstring"""






				snake_case   :					Tuple    						=				'''python/{}'''.format(sys.version.split()[0]   )
				if _torch_available:
								ua += "; torch/{}".format(torch.__version__   )
				if isinstance(_snake_case		,     _snake_case   ):
								ua += "; " + "; ".join('''{}/{}'''.format(_snake_case		,     _snake_case   ) for k, v in user_agent.items()   )
				elif isinstance(_snake_case		,     _snake_case   ):
								ua += "; " + user_agent
				snake_case   :					Union[str, Any]    						=				{'''user-agent''': ua}
				if resume_size > 0:
								snake_case   :					Union[str, Any]    						=				'''bytes=%d-''' % (resume_size,)
				snake_case   :					str    						=				requests.get(_snake_case		,     stream=_snake_case		,     proxies=_snake_case		,     headers=_snake_case   )
				if response.status_code == 416:  # Range not satisfiable
								return
				snake_case   :					List[Any]    						=				response.headers.get('''Content-Length'''   )
				snake_case   :					Dict    						=				resume_size + int(_snake_case   ) if content_length is not None else None
				snake_case   :					Any    						=				tqdm(
				    unit='''B'''		,     unit_scale=_snake_case		,     total=_snake_case		,     initial=_snake_case		,     desc='''Downloading'''		,     )
				for chunk in response.iter_content(chunk_size=1_024   ):
								if chunk:  # filter out keep-alive new chunks
												progress.update(len(_snake_case   )   )
												temp_file.write(_snake_case   )
				progress.close()
def 							a_	(    __magic_name__		,     __magic_name__=None		,     __magic_name__=False		,     __magic_name__=None		,     __magic_name__=10		,     __magic_name__=False		,     __magic_name__=None		,     __magic_name__=False		,     )				->			List[str]:




				"""simple docstring"""






				if cache_dir is None:
								snake_case   :					Dict    						=				TRANSFORMERS_CACHE
				if isinstance(_snake_case		,     _snake_case   ):
								snake_case   :					List[str]    						=				str(_snake_case   )

				os.makedirs(_snake_case		,     exist_ok=_snake_case   )

				snake_case   :					Tuple    						=				None
				if not local_files_only:
								try:
												snake_case   :					Any    						=				requests.head(_snake_case		,     allow_redirects=_snake_case		,     proxies=_snake_case		,     timeout=_snake_case   )
												if response.status_code == 200:
																snake_case   :					Dict    						=				response.headers.get('''ETag'''   )
								except (EnvironmentError, requests.exceptions.Timeout):
												# etag is already None
												pass

				snake_case   :					Tuple    						=				url_to_filename(_snake_case		,     _snake_case   )

				# get cache path to put the file
				snake_case   :					Tuple    						=				os.path.join(_snake_case		,     _snake_case   )

				# etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible.
				# try to get the last downloaded one
				if etag is None:
								if os.path.exists(_snake_case   ):
												return cache_path
								else:
												snake_case   :					int    						=				[
												    file
												    for file in fnmatch.filter(os.listdir(_snake_case   )		,     filename + '''.*'''   )
												    if not file.endswith('''.json'''   ) and not file.endswith('''.lock'''   )
												]
												if len(_snake_case   ) > 0:
																return os.path.join(_snake_case		,     matching_files[-1]   )
												else:
																# If files cannot be found and local_files_only=True,
																# the models might've been found if local_files_only=False
																# Notify the user about that
																if local_files_only:
																				raise ValueError(
																				    '''Cannot find the requested files in the cached path and outgoing traffic has been'''
																				    ''' disabled. To enable model look-ups and downloads online, set \'local_files_only\''''
																				    ''' to False.'''   )
																return None

    # From now on, etag is not None.
				if os.path.exists(_snake_case   ) and not force_download:
								return cache_path

				# Prevent parallel downloads of the same file with a lock.
				snake_case   :					Tuple    						=				cache_path + '''.lock'''
				with FileLock(_snake_case   ):
								# If the download just completed while the lock was activated.
								if os.path.exists(_snake_case   ) and not force_download:
												# Even if returning early like here, the lock will be released.
												return cache_path

								if resume_download:
												snake_case   :					Union[str, Any]    						=				cache_path + '''.incomplete'''

												@contextmanager
												def _resumable_file_manager():
																with open(_snake_case		,     '''a+b'''   ) as f:
																				yield f

												snake_case   :					Optional[int]    						=				_resumable_file_manager
												if os.path.exists(_snake_case   ):
																snake_case   :					Tuple    						=				os.stat(_snake_case   ).st_size
												else:
																snake_case   :					Optional[Any]    						=				0
								else:
												snake_case   :					List[Any]    						=				partial(tempfile.NamedTemporaryFile		,     dir=_snake_case		,     delete=_snake_case   )
												snake_case   :					List[Any]    						=				0

								# Download to temporary file, then copy to cache dir once finished.
								# Otherwise you get corrupt cache entries if the download gets interrupted.
								with temp_file_manager() as temp_file:
												print(
												    '''%s not found in cache or force_download set to True, downloading to %s'''		,     _snake_case		,     temp_file.name		,     )

												http_get(
												    _snake_case		,     _snake_case		,     proxies=_snake_case		,     resume_size=_snake_case		,     user_agent=_snake_case		,     )

								os.replace(temp_file.name		,     _snake_case   )

								snake_case   :					Union[str, Any]    						=				{'''url''': url, '''etag''': etag}
								snake_case   :					int    						=				cache_path + '''.json'''
								with open(_snake_case		,     '''w'''   ) as meta_file:
												json.dump(_snake_case		,     _snake_case   )

				return cache_path
def 							a_	(    __magic_name__		,     __magic_name__=None   )				->			List[str]:




				"""simple docstring"""






				snake_case   :					List[str]    						=				url.encode('''utf-8'''   )
				snake_case   :					Optional[int]    						=				shaaaa(_snake_case   )
				snake_case   :					Tuple    						=				url_hash.hexdigest()

				if etag:
								snake_case   :					int    						=				etag.encode('''utf-8'''   )
								snake_case   :					List[Any]    						=				shaaaa(_snake_case   )
								filename += "." + etag_hash.hexdigest()

				if url.endswith('''.h5'''   ):
								filename += ".h5"

				return filename
def 							a_	(    __magic_name__		,     __magic_name__=None		,     __magic_name__=False		,     __magic_name__=None		,     __magic_name__=False		,     __magic_name__=None		,     __magic_name__=False		,     __magic_name__=False		,     __magic_name__=False		,     )				->			Optional[Any]:




				"""simple docstring"""






				if cache_dir is None:
								snake_case   :					str    						=				TRANSFORMERS_CACHE
				if isinstance(_snake_case		,     _snake_case   ):
								snake_case   :					Optional[int]    						=				str(_snake_case   )
				if isinstance(_snake_case		,     _snake_case   ):
								snake_case   :					Union[str, Any]    						=				str(_snake_case   )

				if is_remote_url(_snake_case   ):
								# URL, so get it from the cache (downloading if necessary)
								snake_case   :					Optional[Any]    						=				get_from_cache(
								    _snake_case		,     cache_dir=_snake_case		,     force_download=_snake_case		,     proxies=_snake_case		,     resume_download=_snake_case		,     user_agent=_snake_case		,     local_files_only=_snake_case		,     )
				elif os.path.exists(_snake_case   ):
								# File, and it exists.
								snake_case   :					Optional[Any]    						=				url_or_filename
				elif urlparse(_snake_case   ).scheme == "":
								# File, but it doesn't exist.
								raise EnvironmentError('''file {} not found'''.format(_snake_case   )   )
				else:
								# Something unknown
								raise ValueError('''unable to parse {} as a URL or as a local path'''.format(_snake_case   )   )

				if extract_compressed_file:
								if not is_zipfile(_snake_case   ) and not tarfile.is_tarfile(_snake_case   ):
												return output_path

								# Path where we extract compressed archives
								# We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/"
								snake_case						,						snake_case   :					Union[str, Any]    						=				os.path.split(_snake_case   )
								snake_case   :					Optional[Any]    						=				output_file.replace('''.'''		,     '''-'''   ) + '''-extracted'''
								snake_case   :					Optional[int]    						=				os.path.join(_snake_case		,     _snake_case   )

								if os.path.isdir(_snake_case   ) and os.listdir(_snake_case   ) and not force_extract:
												return output_path_extracted

								# Prevent parallel extractions
								snake_case   :					List[str]    						=				output_path + '''.lock'''
								with FileLock(_snake_case   ):
												shutil.rmtree(_snake_case		,     ignore_errors=_snake_case   )
												os.makedirs(_snake_case   )
												if is_zipfile(_snake_case   ):
																with ZipFile(_snake_case		,     '''r'''   ) as zip_file:
																				zip_file.extractall(_snake_case   )
																				zip_file.close()
												elif tarfile.is_tarfile(_snake_case   ):
																snake_case   :					Optional[int]    						=				tarfile.open(_snake_case   )
																tar_file.extractall(_snake_case   )
																tar_file.close()
												else:
																raise EnvironmentError('''Archive format of {} could not be identified'''.format(_snake_case   )   )

								return output_path_extracted

				return output_path
def 							a_	(    __magic_name__		,     __magic_name__=","   )				->			Optional[Any]:




				"""simple docstring"""






				assert isinstance(_snake_case		,     _snake_case   )
				if os.path.isfile(_snake_case   ):
								with open(_snake_case   ) as f:
												snake_case   :					List[str]    						=				eval(f.read()   )
				else:
								snake_case   :					List[str]    						=				requests.get(_snake_case   )
								try:
												snake_case   :					List[Any]    						=				requests.json()
								except Exception:
												snake_case   :					Optional[int]    						=				req.content.decode()
												assert data is not None, "could not connect"
												try:
																snake_case   :					Optional[int]    						=				eval(_snake_case   )
												except Exception:
																snake_case   :					Optional[Any]    						=				data.split('''\n'''   )
								req.close()
				return data
def 							a_	(    __magic_name__   )				->			Tuple:




				"""simple docstring"""






				snake_case   :					int    						=				requests.get(_snake_case   )
				snake_case   :					Union[str, Any]    						=				np.array(Image.open(BytesIO(response.content   )   )   )
				return img
def 							a_	(    __magic_name__   )				->			List[Any]:




				"""simple docstring"""






				snake_case   :					Tuple    						=				url.split('''/'''   )[-1]
				if fn not in os.listdir(os.getcwd()   ):
								wget.download(_snake_case   )
				with open(_snake_case		,     '''rb'''   ) as stream:
								snake_case   :					int    						=				pkl.load(_snake_case   )
				snake_case   :					int    						=				weights.pop('''model'''   )
				snake_case   :					Any    						=				{}
				for k, v in model.items():
								snake_case   :					Tuple    						=				torch.from_numpy(_snake_case   )
								if "running_var" in k:
												snake_case   :					str    						=				torch.tensor([0]   )
												snake_case   :					Optional[Any]    						=				k.replace('''running_var'''		,     '''num_batches_tracked'''   )
												snake_case   :					Optional[Any]    						=				zero
				return new
def 							a_	(    )				->			Dict:




				"""simple docstring"""






				print(F"{os.path.abspath(os.path.join(_snake_case		,     os.pardir   )   )}/demo.ipynb"   )
def 							a_	(    __magic_name__		,     __magic_name__="RGB"   )				->			Optional[Any]:




				"""simple docstring"""






				assert isinstance(_snake_case		,     _snake_case   )
				if os.path.isfile(_snake_case   ):
								snake_case   :					Optional[int]    						=				cva.imread(_snake_case   )
				else:
								snake_case   :					Optional[Any]    						=				get_image_from_url(_snake_case   )
								assert img is not None, F"could not connect to: {im}"
				snake_case   :					Tuple    						=				cva.cvtColor(_snake_case		,     cva.COLOR_BGR2RGB   )
				if input_format == "RGB":
								snake_case   :					List[str]    						=				img[:, :, ::-1]
				return img
def 							a_	(    __magic_name__		,     __magic_name__=1   )				->			List[Any]:




				"""simple docstring"""






				return (images[i : i + batch] for i in range(0		,     len(_snake_case   )		,     _snake_case   ))





'''simple docstring'''





import gc
import unittest

from transformers import CTRLConfig, 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, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import (
     CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
     CTRLForSequenceClassification,
     CTRLLMHeadModel,
     CTRLModel,
 )


class 					snake_case			:



       def __init__(					self  ,UpperCAmelCase_  ,UpperCAmelCase_=14  ,UpperCAmelCase_=7  ,UpperCAmelCase_=True  ,UpperCAmelCase_=True  ,UpperCAmelCase_=True  ,UpperCAmelCase_=True  ,UpperCAmelCase_=True  ,UpperCAmelCase_=99  ,UpperCAmelCase_=32  ,UpperCAmelCase_=5  ,UpperCAmelCase_=4  ,UpperCAmelCase_=37  ,UpperCAmelCase_="gelu"  ,UpperCAmelCase_=0.1  ,UpperCAmelCase_=0.1  ,UpperCAmelCase_=512  ,UpperCAmelCase_=16  ,UpperCAmelCase_=2  ,UpperCAmelCase_=0.02  ,UpperCAmelCase_=3  ,UpperCAmelCase_=4  ,UpperCAmelCase_=None  ,)	->				Dict:
           lowercase__									=    parent
           lowercase__									=    batch_size
           lowercase__									=    seq_length
           lowercase__									=    is_training
           lowercase__									=    use_token_type_ids
           lowercase__									=    use_input_mask
           lowercase__									=    use_labels
           lowercase__									=    use_mc_token_ids
           lowercase__									=    vocab_size
           lowercase__									=    hidden_size
           lowercase__									=    num_hidden_layers
           lowercase__									=    num_attention_heads
           lowercase__									=    intermediate_size
           lowercase__									=    hidden_act
           lowercase__									=    hidden_dropout_prob
           lowercase__									=    attention_probs_dropout_prob
           lowercase__									=    max_position_embeddings
           lowercase__									=    type_vocab_size
           lowercase__									=    type_sequence_label_size
           lowercase__									=    initializer_range
           lowercase__									=    num_labels
           lowercase__									=    num_choices
           lowercase__									=    scope
           lowercase__									=    self.vocab_size - 1



       def 				_a   (					self   )	->				Any:
           lowercase__									=    ids_tensor([self.batch_size, self.seq_length]  ,self.vocab_size   )

           lowercase__									=    None
           if self.use_input_mask:
               lowercase__									=    random_attention_mask([self.batch_size, self.seq_length]   )

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

           lowercase__									=    None
           if self.use_mc_token_ids:
               lowercase__									=    ids_tensor([self.batch_size, self.num_choices]  ,self.seq_length   )

           lowercase__									=    None
           lowercase__									=    None
           lowercase__									=    None
           if self.use_labels:
               lowercase__									=    ids_tensor([self.batch_size]  ,self.type_sequence_label_size   )
               lowercase__									=    ids_tensor([self.batch_size, self.seq_length]  ,self.num_labels   )
               lowercase__									=    ids_tensor([self.batch_size]  ,self.num_choices   )

           lowercase__									=    self.get_config()

           lowercase__									=    ids_tensor([self.num_hidden_layers, self.num_attention_heads]  ,2   )

           return (
               config,
               input_ids,
               input_mask,
               head_mask,
               token_type_ids,
               mc_token_ids,
               sequence_labels,
               token_labels,
               choice_labels,
           )



       def 				_a   (					self   )	->				Optional[int]:
           return CTRLConfig(
               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  ,)



       def 				_a   (					self  ,UpperCAmelCase_  ,UpperCAmelCase_  ,UpperCAmelCase_  ,UpperCAmelCase_  ,UpperCAmelCase_  ,*UpperCAmelCase_   )	->				List[Any]:
           lowercase__									=    CTRLModel(config=UpperCAmelCase_   )
           model.to(UpperCAmelCase_   )
           model.eval()

           model(UpperCAmelCase_  ,token_type_ids=UpperCAmelCase_  ,head_mask=UpperCAmelCase_   )
           model(UpperCAmelCase_  ,token_type_ids=UpperCAmelCase_   )
           lowercase__									=    model(UpperCAmelCase_   )
           self.parent.assertEqual(result.last_hidden_state.shape  ,(self.batch_size, self.seq_length, self.hidden_size)   )
           self.parent.assertEqual(len(result.past_key_values   )  ,config.n_layer   )



       def 				_a   (					self  ,UpperCAmelCase_  ,UpperCAmelCase_  ,UpperCAmelCase_  ,UpperCAmelCase_  ,UpperCAmelCase_  ,*UpperCAmelCase_   )	->				Optional[int]:
           lowercase__									=    CTRLLMHeadModel(UpperCAmelCase_   )
           model.to(UpperCAmelCase_   )
           model.eval()

           lowercase__									=    model(UpperCAmelCase_  ,token_type_ids=UpperCAmelCase_  ,labels=UpperCAmelCase_   )
           self.parent.assertEqual(result.loss.shape  ,()   )
           self.parent.assertEqual(result.logits.shape  ,(self.batch_size, self.seq_length, self.vocab_size)   )



       def 				_a   (					self   )	->				Union[str, Any]:
           lowercase__									=    self.prepare_config_and_inputs()

           (
               (
               lowercase__
           )							,							(
               lowercase__
           )							,							(
               lowercase__
           )							,							(
               lowercase__
           )							,							(
               lowercase__
           )							,							(
               lowercase__
           )							,							(
               lowercase__
           )							,							(
               lowercase__
           )							,							(
               lowercase__
           )							,							
           )									=    config_and_inputs

           lowercase__									=    {"input_ids": input_ids, "token_type_ids": token_type_ids, "head_mask": head_mask}

           return config, inputs_dict







       def 				_a   (					self  ,UpperCAmelCase_  ,UpperCAmelCase_  ,UpperCAmelCase_  ,UpperCAmelCase_  ,*UpperCAmelCase_   )	->				Optional[int]:
           lowercase__									=    self.num_labels
           lowercase__									=    CTRLForSequenceClassification(UpperCAmelCase_   )
           model.to(UpperCAmelCase_   )
           model.eval()
           lowercase__									=    ids_tensor([self.batch_size]  ,self.type_sequence_label_size   )
           lowercase__									=    model(UpperCAmelCase_  ,token_type_ids=UpperCAmelCase_  ,labels=UpperCAmelCase_   )
           self.parent.assertEqual(result.logits.shape  ,(self.batch_size, self.num_labels)   )





@require_torch
class 					snake_case			(UpperCamelCase		,   UpperCamelCase		,   UpperCamelCase		,   unittest.TestCase ):
       lowerCAmelCase__	:Union[str, Any]     =       (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else ()
       lowerCAmelCase__	:Dict     =       (CTRLLMHeadModel,) if is_torch_available() else ()
       lowerCAmelCase__	:int     =       (
           {
               "feature-extraction": CTRLModel,
               "text-classification": CTRLForSequenceClassification,
               "text-generation": CTRLLMHeadModel,
               "zero-shot": CTRLForSequenceClassification,
           }
           if is_torch_available()
           else {}
       )
       lowerCAmelCase__	:str     =       True
       lowerCAmelCase__	:Tuple     =       False
       lowerCAmelCase__	:List[Any]     =       False



       def 				_a   (					self  ,UpperCAmelCase_  ,UpperCAmelCase_  ,UpperCAmelCase_  ,UpperCAmelCase_  ,UpperCAmelCase_   )	->				Tuple:
           if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
               # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
               # `CTRLConfig` 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 				_a   (					self   )	->				str:
           lowercase__									=    CTRLModelTester(self   )
           lowercase__									=    ConfigTester(self  ,config_class=UpperCAmelCase_  ,n_embd=37   )



       def 				_a   (					self   )	->				List[Any]:
           super().tearDown()
           # clean-up as much as possible GPU memory occupied by PyTorch
           gc.collect()
           torch.cuda.empty_cache()



       def 				_a   (					self   )	->				Tuple:
           self.config_tester.run_common_tests()



       def 				_a   (					self   )	->				Any:
           lowercase__									=    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_ctrl_model(*UpperCAmelCase_   )



       def 				_a   (					self   )	->				Optional[Any]:
           lowercase__									=    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_lm_head_model(*UpperCAmelCase_   )



       @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."   )
       def 				_a   (					self   )	->				Tuple:
           pass



       @slow
       def 				_a   (					self   )	->				List[str]:
           for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               lowercase__									=    CTRLModel.from_pretrained(UpperCAmelCase_   )
               self.assertIsNotNone(UpperCAmelCase_   )







       @unittest.skip("The model doesn't support left padding"   )  # and it's not used enough to be worth fixing :)
       def 				_a   (					self   )	->				Tuple:
           pass





@require_torch
class 					snake_case			(unittest.TestCase ):



       def 				_a   (					self   )	->				int:
           super().tearDown()
           # clean-up as much as possible GPU memory occupied by PyTorch
           gc.collect()
           torch.cuda.empty_cache()







       @slow
       def 				_a   (					self   )	->				int:
           lowercase__									=    CTRLLMHeadModel.from_pretrained("ctrl"   )
           model.to(UpperCAmelCase_   )
           lowercase__									=    torch.tensor(
               [[11_859, 0, 1_611, 8]]  ,dtype=torch.long  ,device=UpperCAmelCase_   )  # Legal the president is
           lowercase__									=    [
               11_859,
               0,
               1_611,
               8,
               5,
               150,
               26_449,
               2,
               19,
               348,
               469,
               3,
               2_595,
               48,
               20_740,
               246_533,
               246_533,
               19,
               30,
               5,
           ]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

           lowercase__									=    model.generate(UpperCAmelCase_  ,do_sample=UpperCAmelCase_   )
           self.assertListEqual(output_ids[0].tolist()  ,UpperCAmelCase_   )




