
import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCamelCase_						:     int	       =							logging.get_logger(__name__)

UpperCamelCase_						:     Optional[int]	       =							{
    """BAAI/AltCLIP""": """https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json""",
    # See all AltCLIP models at https://huggingface.co/models?filter=altclip
}




class   __lowercase						(						__snake_case       ):
	_A       =   "altclip_text_model"






	def __init__(self				: Optional[int]      ,	snake_case				: Any=25_0002      ,	snake_case				: Dict=1024      ,	snake_case				: List[str]=24      ,	snake_case				: List[Any]=16      ,	snake_case				: Optional[int]=4096      ,	snake_case				: Any="gelu"      ,	snake_case				: Optional[Any]=0.1      ,	snake_case				: Any=0.1      ,	snake_case				: List[str]=514      ,	snake_case				: int=1      ,	snake_case				: List[str]=0.02      ,	snake_case				: Union[str, Any]=0.02      ,	snake_case				: Optional[Any]=1e-05      ,	snake_case				: Any=1      ,	snake_case				: List[str]=0      ,	snake_case				: Optional[int]=2      ,	snake_case				: List[str]="absolute"      ,	snake_case				: Optional[Any]=True      ,	snake_case				: Optional[int]=768      ,	**snake_case				: Dict      ,	) ->			str:
							super().__init__(pad_token_id=snake_case      ,	bos_token_id=snake_case      ,	eos_token_id=snake_case      ,	**snake_case    )

							_lowercase       :	Union[str, Any]           =   vocab_size
							_lowercase       :	List[Any]           =   hidden_size
							_lowercase       :	List[Any]           =   num_hidden_layers
							_lowercase       :	str           =   num_attention_heads
							_lowercase       :	List[str]           =   hidden_act
							_lowercase       :	Tuple           =   intermediate_size
							_lowercase       :	str           =   hidden_dropout_prob
							_lowercase       :	Union[str, Any]           =   attention_probs_dropout_prob
							_lowercase       :	Union[str, Any]           =   max_position_embeddings
							_lowercase       :	Tuple           =   type_vocab_size
							_lowercase       :	Optional[Any]           =   initializer_range
							_lowercase       :	int           =   initializer_factor
							_lowercase       :	Optional[int]           =   layer_norm_eps
							_lowercase       :	str           =   position_embedding_type
							_lowercase       :	Optional[int]           =   use_cache
							_lowercase       :	List[Any]           =   project_dim




class   __lowercase						(						__snake_case       ):
	_A       =   "altclip_vision_model"






	def __init__(self				: Optional[Any]      ,	snake_case				: Dict=768      ,	snake_case				: Any=3072      ,	snake_case				: Tuple=512      ,	snake_case				: int=12      ,	snake_case				: Optional[int]=12      ,	snake_case				: Tuple=3      ,	snake_case				: List[Any]=224      ,	snake_case				: int=32      ,	snake_case				: Tuple="quick_gelu"      ,	snake_case				: Optional[Any]=1e-5      ,	snake_case				: Tuple=0.0      ,	snake_case				: List[Any]=0.02      ,	snake_case				: int=1.0      ,	**snake_case				: str      ,	) ->			int:
							super().__init__(**snake_case    )

							_lowercase       :	Tuple           =   hidden_size
							_lowercase       :	List[str]           =   intermediate_size
							_lowercase       :	Optional[Any]           =   projection_dim
							_lowercase       :	Optional[Any]           =   num_hidden_layers
							_lowercase       :	List[str]           =   num_attention_heads
							_lowercase       :	Optional[int]           =   num_channels
							_lowercase       :	Union[str, Any]           =   patch_size
							_lowercase       :	Any           =   image_size
							_lowercase       :	Optional[int]           =   initializer_range
							_lowercase       :	Tuple           =   initializer_factor
							_lowercase       :	Any           =   attention_dropout
							_lowercase       :	Optional[int]           =   layer_norm_eps
							_lowercase       :	List[Any]           =   hidden_act






	@classmethod
	def       _a(cls				: Dict      ,	snake_case				: Union[str, os.PathLike]      ,	**snake_case				: Any    ) ->			"PretrainedConfig":
							cls._set_token_in_kwargs(snake_case    )

							_lowercase      ,    _lowercase       :	Union[str, Any]           =   cls.get_config_dict(snake_case      ,	**snake_case    )

							# get the vision config dict if we are loading from AltCLIPConfig
							if config_dict.get("model_type"    ) == "altclip":
													_lowercase       :	List[str]           =   config_dict["vision_config"]

							if "model_type" in config_dict and hasattr(cls      ,	"model_type"    ) and config_dict["model_type"] != cls.model_type:
													logger.warning(
													    F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
													    F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""    )

							return cls.from_dict(snake_case      ,	**snake_case    )




class   __lowercase						(						__snake_case       ):
	_A       =   "altclip"
	_A       =   True






	def __init__(self				: List[Any]      ,	snake_case				: Dict=None      ,	snake_case				: int=None      ,	snake_case				: Optional[int]=768      ,	snake_case				: List[str]=2.65_92      ,	**snake_case				: List[str]    ) ->			Tuple:
							# If `_config_dict` exist, we use them for the backward compatibility.
							# We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot
							# of confusion!).
							_lowercase       :	str           =   kwargs.pop("text_config_dict"      ,	snake_case    )
							_lowercase       :	int           =   kwargs.pop("vision_config_dict"      ,	snake_case    )

							super().__init__(**snake_case    )

							# Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
							# `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
							# cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
							if text_config_dict is not None:
													if text_config is None:
																			_lowercase       :	Any           =   {}

													# This is the complete result when using `text_config_dict`.
													_lowercase       :	Optional[Any]           =   AltCLIPTextConfig(**snake_case    ).to_dict()

													# Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
													for key, value in _text_config_dict.items():
																			if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
																									# If specified in `text_config_dict`
																									if key in text_config_dict:
																															_lowercase       :	Optional[int]           =   (
																															    F"""`{key}` is found in both `text_config_dict` and `text_config` but with different values. """
																															    F"""The value `text_config_dict[\"{key}\"]` will be used instead."""
																															)
																									# If inferred from default argument values (just to be super careful)
																									else:
																															_lowercase       :	Any           =   (
																															    F"""`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The """
																															    F"""value `text_config[\"{key}\"]` will be overriden."""
																															)
																									logger.warning(snake_case    )

            # Update all values in `text_config` with the ones in `_text_config_dict`.
													text_config.update(_text_config_dict    )

							if vision_config_dict is not None:
													if vision_config is None:
																			_lowercase       :	str           =   {}

													# This is the complete result when using `vision_config_dict`.
													_lowercase       :	Union[str, Any]           =   AltCLIPVisionConfig(**snake_case    ).to_dict()
													# convert keys to string instead of integer
													if "id2label" in _vision_config_dict:
																			_lowercase       :	Optional[int]           =   {
																			    str(snake_case    ): value for key, value in _vision_config_dict["id2label"].items()
																			}

													# Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
													for key, value in _vision_config_dict.items():
																			if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
																									# If specified in `vision_config_dict`
																									if key in vision_config_dict:
																															_lowercase       :	Tuple           =   (
																															    F"""`{key}` is found in both `vision_config_dict` and `vision_config` but with different """
																															    F"""values. The value `vision_config_dict[\"{key}\"]` will be used instead."""
																															)
																									# If inferred from default argument values (just to be super careful)
																									else:
																															_lowercase       :	Tuple           =   (
																															    F"""`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. """
																															    F"""The value `vision_config[\"{key}\"]` will be overriden."""
																															)
																									logger.warning(snake_case    )

            # Update all values in `vision_config` with the ones in `_vision_config_dict`.
													vision_config.update(_vision_config_dict    )

							if text_config is None:
													_lowercase       :	Dict           =   {}
													logger.info("`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values."    )

							if vision_config is None:
													_lowercase       :	Tuple           =   {}
													logger.info("`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values."    )

							_lowercase       :	Any           =   AltCLIPTextConfig(**snake_case    )
							_lowercase       :	List[str]           =   AltCLIPVisionConfig(**snake_case    )

							_lowercase       :	Dict           =   projection_dim
							_lowercase       :	List[Any]           =   logit_scale_init_value
							_lowercase       :	List[Any]           =   1.0






	@classmethod
	def       _a(cls				: Optional[int]      ,	snake_case				: AltCLIPTextConfig      ,	snake_case				: AltCLIPVisionConfig      ,	**snake_case				: Tuple    ) ->			int:
							return cls(text_config=text_config.to_dict()      ,	vision_config=vision_config.to_dict()      ,	**snake_case    )






	def       _a(self				: int    ) ->			Optional[int]:
							_lowercase       :	Dict           =   copy.deepcopy(self.__dict__    )
							_lowercase       :	int           =   self.text_config.to_dict()
							_lowercase       :	Optional[int]           =   self.vision_config.to_dict()
							_lowercase       :	List[str]           =   self.__class__.model_type
							return output






from dataclasses import dataclass, field
from typing import Optional




@dataclass
class   __lowercase						:
	_A       =   field(
	    default="codeparrot/codeparrot"   , metadata={"help": "Model name or path of model to be trained."}       )
	_A       =   field(
	    default="./"   , metadata={"help": "Save dir where model repo is cloned and models updates are saved to."}       )
	_A       =   field(
	    default="codeparrot/codeparrot-clean-train"   , metadata={"help": "Name or path of training dataset."}       )
	_A       =   field(
	    default="codeparrot/codeparrot-clean-valid"   , metadata={"help": "Name or path of validation dataset."}       )
	_A       =   field(default=2   , metadata={"help": "Batch size for training."}       )
	_A       =   field(default=2   , metadata={"help": "Batch size for evaluation."}       )
	_A       =   field(default=0.1   , metadata={"help": "Value of weight decay."}       )
	_A       =   field(
	    default=10000   , metadata={"help": "Size of buffer used to shuffle streaming dataset."}       )
	_A       =   field(default=2e-4   , metadata={"help": "Learning rate fo training."}       )
	_A       =   field(default="cosine"   , metadata={"help": "Learning rate."}       )
	_A       =   field(
	    default=750   , metadata={"help": "Number of warmup steps in the learning rate schedule."}       )
	_A       =   field(
	    default=16   , metadata={"help": "Number of gradient accumulation steps."}       )
	_A       =   field(
	    default=__snake_case   , metadata={"help": "Use gradient checkpointing to reduce memory footprint."}       )
	_A       =   field(default=50000   , metadata={"help": "Maximum number of training steps."}       )
	_A       =   field(
	    default=-1   , metadata={"help": "Maximum number of evaluation steps. If -1 the full dataset is evaluated."}       )
	_A       =   field(default=1024   , metadata={"help": "Sequence lengths used for training."}       )
	_A       =   field(default=1   , metadata={"help": "Training seed."}       )
	_A       =   field(
	    default=1024   , metadata={"help": "Interval to save checkpoints. Measured as number of forward passes not training steps."}   , )
	_A       =   field(
	    default=__snake_case   , metadata={"help": "States path if the training should continue from a checkpoint folder."}       )
	_A       =   field(default=__snake_case   , metadata={"help": "If True the data is pretokenized."}       )




@dataclass
class   __lowercase						:
	_A       =   field(
	    default="codeparrot/codeparrot"   , metadata={"help": "Model name or path of model to be evaluated."}       )
	_A       =   field(
	    default="codeparrot/codeparrot-clean-valid"   , metadata={"help": "Name or path of validation dataset."}       )
	_A       =   field(default=2   , metadata={"help": "Batch size used for evaluation."}       )
	_A       =   field(
	    default=-1   , metadata={"help": "Maximum number of evaluation steps. If -1 the full dataset is evaluated."}       )
	_A       =   field(default=1024   , metadata={"help": "Length of sequences to be evaluated."}       )
	_A       =   field(default=1   , metadata={"help": "Random seed used for evaluation."}       )




@dataclass
class   __lowercase						:
	_A       =   field(
	    default="codeparrot/codeparrot"   , metadata={"help": "Model name or path of model to be evaluated."}       )
	_A       =   field(default=__snake_case   , metadata={"help": "Number of workers used for code evaluation."}       )
	_A       =   field(
	    default=__snake_case   , metadata={"help": "The number of human-eval tasks to run. If not included all tasks are evaluated."}   , )
	_A       =   field(
	    default=__snake_case   , metadata={"help": "Sample from the language model's output distribution."}       )
	_A       =   field(default=0.2   , metadata={"help": "Sampling temperature used for generation."}       )
	_A       =   field(default=256   , metadata={"help": "Maximum number of newly generated tokens."}       )
	_A       =   field(default=0   , metadata={"help": "Top-k parameter used for generation."}       )
	_A       =   field(default=0.95   , metadata={"help": "Top-p parameter used for nucleus sampling."}       )
	_A       =   field(default=10   , metadata={"help": "Number of generations to run in parallel."}       )
	_A       =   field(
	    default=200   , metadata={"help": "Number of completions to generate for each sample."}       )
	_A       =   field(default=1   , metadata={"help": "Random seed used for evaluation."}       )
	_A       =   field(
	    default="eval_results.json"   , metadata={"help": "Random seed used for evaluation."}       )
	_A       =   field(
	    default="0"   , metadata={"help": "Allow `code_eval` to execute Python code on machine"}       )
	_A       =   field(
	    default=-1   , metadata={
	        "help": (
	            "Determine which device to run the `text-generation` Pipeline on. -1 is CPU and any zero or positive"
	            " number corresponds to which GPU device id to run on."
	        )
	    }   , )




@dataclass
class   __lowercase						:
	_A       =   field(
	    default=__snake_case   , metadata={
	        "help": "The number of CPU cores to use for parallel preprocessing. Default uses the maximum available."
	    }   , )
	_A       =   field(
	    default="transformersbook/codeparrot"   , metadata={"help": "Folder or name of dataset to process."}       )
	_A       =   field(
	    default="codeparrot-clean"   , metadata={"help": "Folder to save processed processed dataset."}       )
	_A       =   field(
	    default=100000   , metadata={"help": "Number of files to save per JSON output file."}       )
	_A       =   field(default="content"   , metadata={"help": "Column containing text data to process."}       )
	_A       =   field(
	    default=1000   , metadata={"help": "Maximum line length in file, otherwise file is filtered."}       )
	_A       =   field(
	    default=100   , metadata={"help": "Maximum mean line length in file, otherwise file is filtered."}       )
	_A       =   field(
	    default=0.25   , metadata={"help": "Maximum fraction of non-alphanumeric characters, otherwise file is filtered."}       )
	_A       =   field(
	    default=1.5   , metadata={"help": "Minimum character token ratio for the file, otherwise file is filtered."}       )
	_A       =   field(
	    default=0.7   , metadata={"help": "Probability for filtering config, test and uncommon files."}       )
	_A       =   field(
	    default="codeparrot/codeparrot"   , metadata={"help": "Name or path to the tokenizer."}   , )
	_A       =   field(
	    default=__snake_case   , metadata={"help": "If True, near-duplicate samples are removed."}       )
	_A       =   field(
	    default=0.85   , metadata={"help": "Jaccard threshold for near-duplicate samples."}       )




@dataclass
class   __lowercase						:
	_A       =   field(
	    default="gpt2"   , metadata={"help": "Base tokenizer to build new tokenizer from."}       )
	_A       =   field(
	    default="transformersbook/codeparrot-train"   , metadata={"help": "Dataset to train tokenizer on."}       )
	_A       =   field(default="content"   , metadata={"help": "Column containing text data to process."}       )
	_A       =   field(default=200000   , metadata={"help": "Number of examples to train tokenizer on."}       )
	_A       =   field(
	    default=32768   , metadata={"help": "Number of examples to train the tokenizer on."}       )
	_A       =   field(default="codeparrot"   , metadata={"help": "Name of new tokenizer."}       )
	_A       =   field(default=__snake_case   , metadata={"help": "Push saved tokenizer to the hub."}       )




@dataclass
class   __lowercase						:
	_A       =   field(
	    default="codeparrot/codeparrot"   , metadata={"help": "Name or path to the tokenizer."}       )
	_A       =   field(
	    default="codeparrot/codeparrot-clean-train"   , metadata={"help": "Name or path to the dataset to pretokenize."}       )
	_A       =   field(
	    default="tokenized-codeparrot-train"   , metadata={"help": "Repo name of the pretokenized data."}       )
	_A       =   field(default=__snake_case   , metadata={"help": "Number of workers used for code evaluation."}       )




@dataclass
class   __lowercase						:
	_A       =   field(
	    default="gpt2-large"   , metadata={"help": "Configuration to use for model initialization."}       )
	_A       =   field(
	    default="codeparrot/codeparrot"   , metadata={"help": "Tokenizer attached to model."}       )
	_A       =   field(default="codeparrot"   , metadata={"help": "Name of the created model."}       )
	_A       =   field(default=__snake_case   , metadata={"help": "Push saved tokenizer to the hub."}       )




