text
stringlengths
1
1.02k
class_index
int64
0
10.8k
source
stringlengths
85
188
conversation = [ { "role": "user", "content": [ {"type": "image", "image": "https://www.ilankelman.org/stopsigns/australia.jpg"}, {"type": "text", "text": "Please describe this image in detail."}, ], }, ...
123
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py
if chat_template is None: if self.chat_template is not None: chat_template = self.chat_template else: raise ValueError( "No chat template is set for this processor. Please either set the `chat_template` attribute, " "or prov...
123
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py
# Pop kwargs that should not be used by tokenizer's `apply_chat_template` tokenize = chat_template_kwargs.pop("tokenize") return_dict = chat_template_kwargs.pop("return_dict") num_frames = chat_template_kwargs.pop("num_frames") video_load_backend = chat_template_kwargs.pop("video_load_ba...
123
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py
# we will have to return all processed inputs in a dict if tokenize: images, videos = [], [] for message in conversation: visuals = [content for content in message["content"] if content["type"] in ["image", "video"]] for vision_info in visuals: ...
123
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py
out = self( text=prompt, images=images if images else None, videos=videos if videos else None, **kwargs, ) if return_dict: return out else: return out["input_ids"] return prompt ...
123
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py
class BatchFeature(BaseBatchFeature): r""" Holds the output of the image processor specific `__call__` methods. This class is derived from a python dictionary and can be used as a dictionary. Args: data (`dict`): Dictionary of lists/arrays/tensors returned by the __call__ method ('...
124
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
class ImageProcessingMixin(PushToHubMixin): """ This is an image processor mixin used to provide saving/loading functionality for sequential and image feature extractors. """ _auto_class = None def __init__(self, **kwargs): """Set elements of `kwargs` as attributes.""" # This k...
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
def _set_processor_class(self, processor_class: str): """Sets processor class as an attribute.""" self._processor_class = processor_class @classmethod def from_pretrained( cls: Type[ImageProcessorType], pretrained_model_name_or_path: Union[str, os.PathLike], cache_dir: O...
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
- a string, the *model id* of a pretrained image_processor hosted inside a model repo on huggingface.co. - a path to a *directory* containing a image processor file saved using the [`~image_processing_utils.ImageProcessingMixin.save_pretrained`] method, e.g., ...
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
Deprecated and ignored. All downloads are now resumed by default when possible. Will be removed in v5 of Transformers. proxies (`Dict[str, str]`, *optional*): A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128', 'http:/...
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
<Tip> To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>"`. </Tip>
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
return_unused_kwargs (`bool`, *optional*, defaults to `False`): If `False`, then this function returns just the final image processor object. If `True`, then this functions returns a `Tuple(image_processor, unused_kwargs)` where *unused_kwargs* is a dictionary consisting ...
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
loaded values. Behavior concerning key/value pairs whose keys are *not* image processor attributes is controlled by the `return_unused_kwargs` keyword parameter.
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
Returns: A image processor of type [`~image_processing_utils.ImageProcessingMixin`]. Examples:
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
```python # We can't instantiate directly the base class *ImageProcessingMixin* so let's show the examples on a # derived class: *CLIPImageProcessor* image_processor = CLIPImageProcessor.from_pretrained( "openai/clip-vit-base-patch32" ) # Download image_processing_config fro...
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
"openai/clip-vit-base-patch32", do_normalize=False, foo=False, return_unused_kwargs=True ) assert image_processor.do_normalize is False assert unused_kwargs == {"foo": False} ```""" kwargs["cache_dir"] = cache_dir kwargs["force_download"] = force_download kwargs["...
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
use_auth_token = kwargs.pop("use_auth_token", None) if use_auth_token is not None: warnings.warn( "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.", FutureWarning, ) if token is...
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
def save_pretrained(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs): """ Save an image processor object to the directory `save_directory`, so that it can be re-loaded using the [`~image_processing_utils.ImageProcessingMixin.from_pretrained`] class method.
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
Args: save_directory (`str` or `os.PathLike`): Directory where the image processor JSON file will be saved (will be created if it does not exist). push_to_hub (`bool`, *optional*, defaults to `False`): Whether or not to push your model to the Hugging Face model hu...
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
if use_auth_token is not None: warnings.warn( "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.", FutureWarning, ) if kwargs.get("token", None) is not None: raise ValueEr...
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
# If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be # loaded from the Hub. if self._auto_class is not None: custom_object_save(self, save_directory, config=self) # If we save using the predefined names, we can load using `from...
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
@classmethod def get_image_processor_dict( cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs ) -> Tuple[Dict[str, Any], Dict[str, Any]]: """ From a `pretrained_model_name_or_path`, resolve to a dictionary of parameters, to be used for instantiating a image pro...
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
Returns: `Tuple[Dict, Dict]`: The dictionary(ies) that will be used to instantiate the image processor object. """ cache_dir = kwargs.pop("cache_dir", None) force_download = kwargs.pop("force_download", False) resume_download = kwargs.pop("resume_download", None) prox...
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
if use_auth_token is not None: warnings.warn( "The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.", FutureWarning, ) if token is not None: raise ValueError( ...
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
pretrained_model_name_or_path = str(pretrained_model_name_or_path) is_local = os.path.isdir(pretrained_model_name_or_path) if os.path.isdir(pretrained_model_name_or_path): image_processor_file = os.path.join(pretrained_model_name_or_path, image_processor_filename) if os.path.isfile(p...
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
cache_dir=cache_dir, force_download=force_download, proxies=proxies, resume_download=resume_download, local_files_only=local_files_only, token=token, user_agent=user_agent, revisio...
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
f" same name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a" f" directory containing a {image_processor_filename} file" )
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
try: # Load image_processor dict with open(resolved_image_processor_file, "r", encoding="utf-8") as reader: text = reader.read() image_processor_dict = json.loads(text) except json.JSONDecodeError: raise EnvironmentError( f"It look...
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
if is_local: logger.info(f"loading configuration file {resolved_image_processor_file}") else: logger.info( f"loading configuration file {image_processor_file} from cache at {resolved_image_processor_file}" ) if "auto_map" in image_processor_dict: ...
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
@classmethod def from_dict(cls, image_processor_dict: Dict[str, Any], **kwargs): """ Instantiates a type of [`~image_processing_utils.ImageProcessingMixin`] from a Python dictionary of parameters. Args: image_processor_dict (`Dict[str, Any]`): Dictionary that wil...
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
# The `size` parameter is a dict and was previously an int or tuple in feature extractors. # We set `size` here directly to the `image_processor_dict` so that it is converted to the appropriate # dict within the image processor and isn't overwritten if `size` is passed in as a kwarg. if "size" i...
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
logger.info(f"Image processor {image_processor}") if return_unused_kwargs: return image_processor, kwargs else: return image_processor def to_dict(self) -> Dict[str, Any]: """ Serializes this instance to a Python dictionary. Returns: `Dic...
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
Returns: A image processor of type [`~image_processing_utils.ImageProcessingMixin`]: The image_processor object instantiated from that JSON file. """ with open(json_file, "r", encoding="utf-8") as reader: text = reader.read() image_processor_dict = json.loads(...
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
# make sure private name "_processor_class" is correctly # saved as "processor_class" _processor_class = dictionary.pop("_processor_class", None) if _processor_class is not None: dictionary["processor_class"] = _processor_class return json.dumps(dictionary, indent=2, sort_ke...
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
@classmethod def register_for_auto_class(cls, auto_class="AutoImageProcessor"): """ Register this class with a given auto class. This should only be used for custom image processors as the ones in the library are already mapped with `AutoImageProcessor `. <Tip warning={true}> ...
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
def fetch_images(self, image_url_or_urls: Union[str, List[str]]): """ Convert a single or a list of urls into the corresponding `PIL.Image` objects.
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
If a single url is passed, the return value will be a single object. If a list is passed a list of objects is returned. """ headers = { "User-Agent": ( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0" ...
125
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_base.py
class Seq2SeqTrainingArguments(TrainingArguments): """ Args: predict_with_generate (`bool`, *optional*, defaults to `False`): Whether to use generate to calculate generative metrics (ROUGE, BLEU). generation_max_length (`int`, *optional*): The `max_length` to use on each ...
126
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/training_args_seq2seq.py
- a string, the *model id* of a pretrained model configuration hosted inside a model repo on huggingface.co. - a path to a *directory* containing a configuration file saved using the [`~GenerationConfig.save_pretrained`] method, e.g., `./my_model_directory/`. - a [`~g...
126
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/training_args_seq2seq.py
sortish_sampler: bool = field(default=False, metadata={"help": "Whether to use SortishSampler or not."}) predict_with_generate: bool = field( default=False, metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) generation_max_length: Optional[int] = field( ...
126
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/training_args_seq2seq.py
default=None, metadata={ "help": "Model id, file path or url pointing to a GenerationConfig json file, to use during prediction." }, )
126
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/training_args_seq2seq.py
def to_dict(self): """ Serializes this instance while replace `Enum` by their values and `GenerationConfig` by dictionaries (for JSON serialization support). It obfuscates the token values by removing their value. """ # filter out fields that are defined as field(init=False) ...
126
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/training_args_seq2seq.py
class ModelCard: r""" Structured Model Card class. Store model card as well as methods for loading/downloading/saving model cards. Please read the following paper for details and explanation on the sections: "Model Cards for Model Reporting" by Margaret Mitchell, Simone Wu, Andrew Zaldivar, Parker Barn...
127
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modelcard.py
def __init__(self, **kwargs): warnings.warn( "The class `ModelCard` is deprecated and will be removed in version 5 of Transformers", FutureWarning ) # Recommended attributes from https://arxiv.org/abs/1810.03993 (see papers) self.model_details = kwargs.pop("model_details", {}...
127
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modelcard.py
# Open additional attributes for key, value in kwargs.items(): try: setattr(self, key, value) except AttributeError as err: logger.error(f"Can't set {key} with value {value} for {self}") raise err def save_pretrained(self, save_directo...
127
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modelcard.py
@classmethod def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): r""" Instantiate a [`ModelCard`] from a pre-trained model model card. Parameters: pretrained_model_name_or_path: either: - a string, the *model id* of a pretrained model card hosted ...
127
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modelcard.py
- The values in kwargs of any keys which are model card attributes will be used to override the loaded values. - Behavior concerning key/value pairs whose keys are *not* model card attributes is controlled by the *return_unused_kwargs* keyword parameter. ...
127
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modelcard.py
- If False, then this function returns just the final model card object. - If True, then this functions returns a tuple *(model card, unused_kwargs)* where *unused_kwargs* is a dictionary consisting of the key/value pairs whose keys are not model card attributes: ie the part of ...
127
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modelcard.py
```python # Download model card from huggingface.co and cache. modelcard = ModelCard.from_pretrained("google-bert/bert-base-uncased") # Model card was saved using *save_pretrained('./test/saved_model/')* modelcard = ModelCard.from_pretrained("./test/saved_model/") modelcard = Mod...
127
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modelcard.py
is_local = os.path.isdir(pretrained_model_name_or_path) if os.path.isfile(pretrained_model_name_or_path): resolved_model_card_file = pretrained_model_name_or_path is_local = True else: try: # Load from URL or cache if already cached res...
127
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modelcard.py
except (EnvironmentError, json.JSONDecodeError): # We fall back on creating an empty model card modelcard = cls() # Update model card with kwargs if needed to_remove = [] for key, value in kwargs.items(): if hasattr(modelcard, key): se...
127
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modelcard.py
@classmethod def from_json_file(cls, json_file): """Constructs a `ModelCard` from a json file of parameters.""" with open(json_file, "r", encoding="utf-8") as reader: text = reader.read() dict_obj = json.loads(text) return cls(**dict_obj) def __eq__(self, other): ...
127
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modelcard.py
class TrainingSummary: model_name: str language: Optional[Union[str, List[str]]] = None license: Optional[str] = None tags: Optional[Union[str, List[str]]] = None finetuned_from: Optional[str] = None tasks: Optional[Union[str, List[str]]] = None dataset: Optional[Union[str, List[str]]] = Non...
128
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modelcard.py
def __post_init__(self): # Infer default license from the checkpoint used, if possible. if ( self.license is None and not is_offline_mode() and self.finetuned_from is not None and len(self.finetuned_from) > 0 ): try: inf...
128
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modelcard.py
# Dataset mapping tag -> name dataset_names = _listify(self.dataset) dataset_tags = _listify(self.dataset_tags) dataset_args = _listify(self.dataset_args) dataset_metadata = _listify(self.dataset_metadata) if len(dataset_args) < len(dataset_tags): dataset_args = datas...
128
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modelcard.py
if len(task_mapping) == 0 and len(dataset_mapping) == 0: return [model_index] if len(task_mapping) == 0: task_mapping = {None: None} if len(dataset_mapping) == 0: dataset_mapping = {None: None} # One entry per dataset and per task all_possibilities = ...
128
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modelcard.py
if len(metric_mapping) > 0: result["metrics"] = [] for metric_tag, metric_name in metric_mapping.items(): result["metrics"].append( { "name": metric_name, "type": metric_tag, ...
128
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modelcard.py
metadata = {} metadata = _insert_value(metadata, "library_name", "transformers") metadata = _insert_values_as_list(metadata, "language", self.language) metadata = _insert_value(metadata, "license", self.license) if self.finetuned_from is not None and isinstance(self.finetuned_from, str) ...
128
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modelcard.py
# Now the model card for realsies. if self.source == "trainer": model_card += AUTOGENERATED_TRAINER_COMMENT else: model_card += AUTOGENERATED_KERAS_COMMENT model_card += f"\n# {self.model_name}\n\n" if self.finetuned_from is None: model_card += "This...
128
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modelcard.py
if self.dataset is None: model_card += "an unknown dataset." else: if isinstance(self.dataset, str): model_card += f"the {self.dataset} dataset." elif isinstance(self.dataset, (tuple, list)) and len(self.dataset) == 1: model_card += f"the {self...
128
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modelcard.py
model_card += "\n## Model description\n\nMore information needed\n" model_card += "\n## Intended uses & limitations\n\nMore information needed\n" model_card += "\n## Training and evaluation data\n\nMore information needed\n" model_card += "\n## Training procedure\n" model_card += "\n###...
128
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modelcard.py
if self.source == "trainer" and is_torch_available(): import torch model_card += f"- Pytorch {torch.__version__}\n" elif self.source == "keras" and is_tf_available(): import tensorflow as tf model_card += f"- TensorFlow {tf.__version__}\n" if is_datasets...
128
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modelcard.py
@classmethod def from_trainer( cls, trainer, language=None, license=None, tags=None, model_name=None, finetuned_from=None, tasks=None, dataset_tags=None, dataset_metadata=None, dataset=None, dataset_args=None, ): ...
128
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modelcard.py
dataset_tags = [default_tag] if dataset_args is None: dataset_args = [one_dataset.config_name]
128
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modelcard.py
if dataset is None and dataset_tags is not None: dataset = dataset_tags # Infer default finetuned_from if ( finetuned_from is None and hasattr(trainer.model.config, "_name_or_path") and not os.path.isdir(trainer.model.config._name_or_path) ): ...
128
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modelcard.py
# Add `generated_from_trainer` to the tags if tags is None: tags = ["generated_from_trainer"] elif isinstance(tags, str) and tags != "generated_from_trainer": tags = [tags, "generated_from_trainer"] elif "generated_from_trainer" not in tags: tags.append("gener...
128
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modelcard.py
@classmethod def from_keras( cls, model, model_name, keras_history=None, language=None, license=None, tags=None, finetuned_from=None, tasks=None, dataset_tags=None, dataset=None, dataset_args=None, ): # Infer...
128
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modelcard.py
# Infer default finetuned_from if ( finetuned_from is None and hasattr(model.config, "_name_or_path") and not os.path.isdir(model.config._name_or_path) ): finetuned_from = model.config._name_or_path # Infer default task tag: if tasks is No...
128
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modelcard.py
if keras_history is not None: _, eval_lines, eval_results = parse_keras_history(keras_history) else: eval_lines = [] eval_results = {} hyperparameters = extract_hyperparameters_from_keras(model) return cls( language=language, license=l...
128
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modelcard.py
class AdamW(Optimizer): """ Implements Adam algorithm with weight decay fix as introduced in [Decoupled Weight Decay Regularization](https://arxiv.org/abs/1711.05101).
129
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/optimization.py
Parameters: params (`Iterable[nn.parameter.Parameter]`): Iterable of parameters to optimize or dictionaries defining parameter groups. lr (`float`, *optional*, defaults to 0.001): The learning rate to use. betas (`Tuple[float,float]`, *optional*, defaults to `(0.9, 0.999)...
129
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/optimization.py
def __init__( self, params: Iterable[nn.parameter.Parameter], lr: float = 1e-3, betas: Tuple[float, float] = (0.9, 0.999), eps: float = 1e-6, weight_decay: float = 0.0, correct_bias: bool = True, no_deprecation_warning: bool = False, ): if not ...
129
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/optimization.py
raise ValueError(f"Invalid beta parameter: {betas[1]} - should be in [0.0, 1.0)") if not 0.0 <= eps: raise ValueError(f"Invalid epsilon value: {eps} - should be >= 0.0") defaults = {"lr": lr, "betas": betas, "eps": eps, "weight_decay": weight_decay, "correct_bias": correct_bias} supe...
129
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/optimization.py
@torch.no_grad() def step(self, closure: Callable = None): """ Performs a single optimization step. Arguments: closure (`Callable`, *optional*): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: ...
129
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/optimization.py
# State initialization if len(state) == 0: state["step"] = 0 # Exponential moving average of gradient values state["exp_avg"] = torch.zeros_like(p) # Exponential moving average of squared gradient values ...
129
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/optimization.py
step_size = group["lr"] if group["correct_bias"]: # No bias correction for Bert bias_correction1 = 1.0 - beta1 ** state["step"] bias_correction2 = 1.0 - beta2 ** state["step"] step_size = step_size * math.sqrt(bias_correction2) / bias_correcti...
129
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/optimization.py
# Just adding the square of the weights to the loss function is *not* # the correct way of using L2 regularization/weight decay with Adam, # since that will interact with the m and v parameters in strange ways. # # Instead we want to decay the weights in a...
129
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/optimization.py
class Adafactor(Optimizer): """ AdaFactor pytorch implementation can be used as a drop in replacement for Adam original fairseq code: https://github.com/pytorch/fairseq/blob/master/fairseq/optim/adafactor.py Paper: *Adafactor: Adaptive Learning Rates with Sublinear Memory Cost* https://arxiv.org/abs/18...
130
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/optimization.py
Arguments: params (`Iterable[nn.parameter.Parameter]`): Iterable of parameters to optimize or dictionaries defining parameter groups. lr (`float`, *optional*): The external learning rate. eps (`Tuple[float, float]`, *optional*, defaults to `(1e-30, 0.001)`): R...
130
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/optimization.py
relative_step (`bool`, *optional*, defaults to `True`): If True, time-dependent learning rate is computed instead of external learning rate warmup_init (`bool`, *optional*, defaults to `False`): Time-dependent learning rate computation depends on whether warm-up initialization is being u...
130
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/optimization.py
This implementation handles low-precision (FP16, bfloat) values, but we have not thoroughly tested. Recommended T5 finetuning settings (https://discuss.huggingface.co/t/t5-finetuning-tips/684/3): - Training without LR warmup or clip_threshold is not recommended. - use scheduled LR warm-up to f...
130
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/optimization.py
When using `lr=None` with [`Trainer`] you will most likely need to use [`~optimization.AdafactorSchedule`] scheduler as following: ```python from transformers.optimization import Adafactor, AdafactorSchedule optimizer = Adafactor(model.parameters(), scale_parameter=True, relative_step=True, warmup_ini...
130
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/optimization.py
def __init__( self, params, lr=None, eps=(1e-30, 1e-3), clip_threshold=1.0, decay_rate=-0.8, beta1=None, weight_decay=0.0, scale_parameter=True, relative_step=True, warmup_init=False, ): require_version("torch>=1.5.0") ...
130
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/optimization.py
@staticmethod def _get_lr(param_group, param_state): rel_step_sz = param_group["lr"] if param_group["relative_step"]: min_step = 1e-6 * param_state["step"] if param_group["warmup_init"] else 1e-2 rel_step_sz = min(min_step, 1.0 / math.sqrt(param_state["step"])) param_...
130
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/optimization.py
@staticmethod def _approx_sq_grad(exp_avg_sq_row, exp_avg_sq_col): # copy from fairseq's adafactor implementation: # https://github.com/huggingface/transformers/blob/8395f14de6068012787d83989c3627c3df6a252b/src/transformers/optimization.py#L505 r_factor = (exp_avg_sq_row / exp_avg_sq_row.mea...
130
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/optimization.py
for group in self.param_groups: for p in group["params"]: if p.grad is None: continue grad = p.grad if grad.dtype in {torch.float16, torch.bfloat16}: grad = grad.float() if grad.is_sparse: ...
130
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/optimization.py
if use_first_moment: # Exponential moving average of gradient values state["exp_avg"] = torch.zeros_like(grad) if factored: state["exp_avg_sq_row"] = torch.zeros(grad_shape[:-1]).to(grad) state["exp_avg_s...
130
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/optimization.py
p_data_fp32 = p if p.dtype in {torch.float16, torch.bfloat16}: p_data_fp32 = p_data_fp32.float() state["step"] += 1 state["RMS"] = self._rms(p_data_fp32) lr = self._get_lr(group, state) beta2t = 1.0 - math.pow(state["s...
130
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/optimization.py
# Approximation of exponential moving average of square of gradient update = self._approx_sq_grad(exp_avg_sq_row, exp_avg_sq_col) update.mul_(grad) else: exp_avg_sq = state["exp_avg_sq"] exp_avg_sq.mul_(beta2t).add_(update,...
130
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/optimization.py
if p.dtype in {torch.float16, torch.bfloat16}: p.copy_(p_data_fp32) return loss
130
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/optimization.py
class AdafactorSchedule(LambdaLR): """ Since [`~optimization.Adafactor`] performs its own scheduling, if the training loop relies on a scheduler (e.g., for logging), this class creates a proxy object that retrieves the current lr values from the optimizer. It returns `initial_lr` during startup and the...
131
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/optimization.py
class TFTrainingArguments(TrainingArguments): """ TrainingArguments is the subset of the arguments we use in our example scripts **which relate to the training loop itself**. Using [`HfArgumentParser`] we can turn this class into [argparse](https://docs.python.org/3/library/argparse#module-argparse...
132
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/training_args_tf.py
Parameters: output_dir (`str`): The output directory where the model predictions and checkpoints will be written. overwrite_output_dir (`bool`, *optional*, defaults to `False`): If `True`, overwrite the content of the output directory. Use this to continue training if `output_dir...
132
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/training_args_tf.py
training/evaluation scripts instead. See the [example scripts](https://github.com/huggingface/transformers/tree/main/examples) for more details. do_predict (`bool`, *optional*, defaults to `False`): Whether to run predictions on the test set or not. This argument is not directly used by ...
132
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/training_args_tf.py
- `"no"`: No evaluation is done during training. - `"steps"`: Evaluation is done (and logged) every `eval_steps`. - `"epoch"`: Evaluation is done at the end of each epoch. per_device_train_batch_size (`int`, *optional*, defaults to 8): The batch size per GPU/TPU core...
132
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/training_args_tf.py
learning_rate (`float`, *optional*, defaults to 5e-5): The initial learning rate for Adam. weight_decay (`float`, *optional*, defaults to 0): The weight decay to apply (if not zero). adam_beta1 (`float`, *optional*, defaults to 0.9): The beta1 hyperparameter for the A...
132
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/training_args_tf.py
For a finite dataset, training is reiterated through the dataset (if all data is exhausted) until `max_steps` is reached. warmup_ratio (`float`, *optional*, defaults to 0.0): Ratio of total training steps used for a linear warmup from 0 to `learning_rate`. warmup_steps (`int`, *o...
132
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/training_args_tf.py
- `"no"`: No logging is done during training. - `"epoch"`: Logging is done at the end of each epoch. - `"steps"`: Logging is done every `logging_steps`. logging_first_step (`bool`, *optional*, defaults to `False`): Whether to log and evaluate the first `global_step` ...
132
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/training_args_tf.py
save_steps (`int`, *optional*, defaults to 500): Number of updates steps before two checkpoint saves if `save_strategy="steps"`. save_total_limit (`int`, *optional*): If a value is passed, will limit the total amount of checkpoints. Deletes the older checkpoints in `output_di...
132
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/training_args_tf.py
local_rank (`int`, *optional*, defaults to -1): During distributed training, the rank of the process. tpu_num_cores (`int`, *optional*): When training on TPU, the number of TPU cores (automatically passed by launcher script). debug (`bool`, *optional*, defaults to `False`): ...
132
/Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/training_args_tf.py