text stringlengths 1 1.02k | class_index int64 0 10.8k | source stringlengths 85 188 |
|---|---|---|
class FSDPOption(ExplicitEnum):
FULL_SHARD = "full_shard"
SHARD_GRAD_OP = "shard_grad_op"
NO_SHARD = "no_shard"
HYBRID_SHARD = "hybrid_shard"
HYBRID_SHARD_ZERO2 = "hybrid_shard_zero2"
OFFLOAD = "offload"
AUTO_WRAP = "auto_wrap" | 112 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
class RemoveColumnsCollator:
"""Wrap the data collator to remove unused columns before they are passed to the collator."""
def __init__(
self,
data_collator,
signature_columns,
logger=None,
model_name: Optional[str] = None,
description: Optional[str] = None,
... | 113 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
def _remove_columns(self, feature: dict) -> dict:
if not isinstance(feature, dict):
return feature
if not self.message_logged and self.logger and self.model_name:
ignored_columns = list(set(feature.keys()) - set(self.signature_columns))
if len(ignored_columns) > 0:
... | 113 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
def __call__(self, features: List[dict]):
features = [self._remove_columns(feature) for feature in features]
return self.data_collator(features) | 113 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
class HfArgumentParser(ArgumentParser):
"""
This subclass of `argparse.ArgumentParser` uses type hints on dataclasses to generate arguments.
The class is designed to play well with the native argparse. In particular, you can add more (non-dataclass backed)
arguments to the parser after initialization a... | 114 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/hf_argparser.py |
def __init__(self, dataclass_types: Union[DataClassType, Iterable[DataClassType]], **kwargs):
"""
Args:
dataclass_types:
Dataclass type, or list of dataclass types for which we will "fill" instances with the parsed args.
kwargs (`Dict[str, Any]`, *optional*):
... | 114 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/hf_argparser.py |
@staticmethod
def _parse_dataclass_field(parser: ArgumentParser, field: dataclasses.Field):
# Long-option strings are conventionlly separated by hyphens rather
# than underscores, e.g., "--long-format" rather than "--long_format".
# Argparse converts hyphens to underscores so that the destin... | 114 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/hf_argparser.py |
aliases = kwargs.pop("aliases", [])
if isinstance(aliases, str):
aliases = [aliases] | 114 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/hf_argparser.py |
origin_type = getattr(field.type, "__origin__", field.type)
if origin_type is Union or (hasattr(types, "UnionType") and isinstance(origin_type, types.UnionType)):
if str not in field.type.__args__ and (
len(field.type.__args__) != 2 or type(None) not in field.type.__args__
... | 114 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/hf_argparser.py |
# filter `NoneType` in Union (except for `Union[bool, NoneType]`)
field.type = (
field.type.__args__[0] if isinstance(None, field.type.__args__[1]) else field.type.__args__[1]
)
origin_type = getattr(field.type, "__origin__", field.type) | 114 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/hf_argparser.py |
# A variable to store kwargs for a boolean field, if needed
# so that we can init a `no_*` complement argument (see below)
bool_kwargs = {}
if origin_type is Literal or (isinstance(field.type, type) and issubclass(field.type, Enum)):
if origin_type is Literal:
kwargs[... | 114 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/hf_argparser.py |
# Hack because type=bool in argparse does not behave as we want.
kwargs["type"] = string_to_bool
if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING):
# Default value is False if we have no default when of type bool.
de... | 114 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/hf_argparser.py |
if field.default_factory is not dataclasses.MISSING:
kwargs["default"] = field.default_factory()
elif field.default is dataclasses.MISSING:
kwargs["required"] = True
else:
kwargs["type"] = field.type
if field.default is not dataclasses.MISSING:... | 114 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/hf_argparser.py |
# Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added.
# Order is important for arguments with the same destination!
# We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down
# here and we do not need tho... | 114 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/hf_argparser.py |
try:
type_hints: Dict[str, type] = get_type_hints(dtype)
except NameError:
raise RuntimeError(
f"Type resolution failed for {dtype}. Try declaring the class in global scope or "
"removing line of `from __future__ import annotations` which opts in Postponed... | 114 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/hf_argparser.py |
"support Python versions that lower than 3.10, you need to use "
"`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of "
"`X | None`."
) from ex
raise | 114 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/hf_argparser.py |
for field in dataclasses.fields(dtype):
if not field.init:
continue
field.type = type_hints[field.name]
self._parse_dataclass_field(parser, field)
def parse_args_into_dataclasses(
self,
args=None,
return_remaining_strings=False,
lo... | 114 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/hf_argparser.py |
Args:
args:
List of strings to parse. The default is taken from sys.argv. (same as argparse.ArgumentParser)
return_remaining_strings:
If true, also return a list of remaining argument strings.
look_for_args_file:
If true, will look for ... | 114 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/hf_argparser.py |
- the dataclass instances in the same order as they were passed to the initializer.abspath
- if applicable, an additional namespace for more (non-dataclass backed) arguments added to the parser
after initialization.
- The potential list of remaining argument strings. (s... | 114 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/hf_argparser.py |
# args files specified via command line flag should overwrite default args files so we add them last
if args_file_flag:
# Create special parser just to extract the args_file_flag values
args_file_parser = ArgumentParser()
args_file_parser.add_argument(args_fil... | 114 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/hf_argparser.py |
# in case of duplicate arguments the last one has precedence
# args specified via the command line should overwrite args from files, so we add them last
args = file_args + args if args is not None else file_args + sys.argv[1:]
namespace, remaining_args = self.parse_known_args(args=args)
... | 114 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/hf_argparser.py |
raise ValueError(f"Some specified arguments are not used by the HfArgumentParser: {remaining_args}") | 114 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/hf_argparser.py |
return (*outputs,)
def parse_dict(self, args: Dict[str, Any], allow_extra_keys: bool = False) -> Tuple[DataClass, ...]:
"""
Alternative helper method that does not use `argparse` at all, instead uses a dict and populating the dataclass
types.
Args:
args (`dict`):
... | 114 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/hf_argparser.py |
- the dataclass instances in the same order as they were passed to the initializer.
"""
unused_keys = set(args.keys())
outputs = []
for dtype in self.dataclass_types:
keys = {f.name for f in dataclasses.fields(dtype) if f.init}
inputs = {k: v for k, v in args.item... | 114 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/hf_argparser.py |
Args:
json_file (`str` or `os.PathLike`):
File name of the json file to parse
allow_extra_keys (`bool`, *optional*, defaults to `False`):
Defaults to False. If False, will raise an exception if the json file contains keys that are not
parsed.
... | 114 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/hf_argparser.py |
Args:
yaml_file (`str` or `os.PathLike`):
File name of the yaml file to parse
allow_extra_keys (`bool`, *optional*, defaults to `False`):
Defaults to False. If False, will raise an exception if the json file contains keys that are not
parsed.
... | 114 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/hf_argparser.py |
class TextKwargs(TypedDict, total=False):
"""
Keyword arguments for text processing. For extended documentation, check out tokenization_utils_base methods and
docstrings associated. | 115 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
Attributes:
add_special_tokens (`bool`, *optional*)
Whether or not to add special tokens when encoding the sequences.
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*)
Activates and controls padding.
truncation (`bool`, `str` or [`~tokenization_utils_base.... | 115 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
return_attention_mask (`bool`, *optional*):
Whether to return the attention mask.
return_overflowing_tokens (`bool`, *optional*):
Whether or not to return overflowing token sequences.
return_special_tokens_mask (`bool`, *optional*):
Whether or not to return special to... | 115 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
text_pair: Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]]
text_target: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]
text_pair_target: Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]]
add_special_... | 115 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
class ImagesKwargs(TypedDict, total=False):
"""
Keyword arguments for image processing. For extended documentation, check the appropriate ImageProcessor
class methods and docstrings. | 116 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
Attributes:
do_resize (`bool`, *optional*):
Whether to resize the image.
size (`Dict[str, int]`, *optional*):
Resize the shorter side of the input to `size["shortest_edge"]`.
size_divisor (`int`, *optional*):
The size by which to make sure both the height and ... | 116 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
image_std (`float` or `List[float]`, *optional*):
Standard deviation to use if normalizing the image.
do_pad (`bool`, *optional*):
Whether to pad the image to the `(max_height, max_width)` of the images in the batch.
pad_size (`Dict[str, int]`, *optional*):
The size `... | 116 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
do_resize: Optional[bool]
size: Optional[Dict[str, int]]
size_divisor: Optional[int]
crop_size: Optional[Dict[str, int]]
resample: Optional[Union["PILImageResampling", int]]
do_rescale: Optional[bool]
rescale_factor: Optional[float]
do_normalize: Optional[bool]
image_mean: Optional[Union... | 116 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
class VideosKwargs(TypedDict, total=False):
"""
Keyword arguments for video processing. | 117 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
Attributes:
do_resize (`bool`):
Whether to resize the image.
size (`Dict[str, int]`, *optional*):
Resize the shorter side of the input to `size["shortest_edge"]`.
size_divisor (`int`, *optional*):
The size by which to make sure both the height and width can be... | 117 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
do_pad (`bool`, *optional*):
Whether to pad the image to the `(max_height, max_width)` of the images in the batch.
do_center_crop (`bool`, *optional*):
Whether to center crop the image.
data_format (`ChannelDimension` or `str`, *optional*):
The channel dimension forma... | 117 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
do_resize: Optional[bool]
size: Optional[Dict[str, int]]
size_divisor: Optional[int]
resample: Optional["PILImageResampling"]
do_rescale: Optional[bool]
rescale_factor: Optional[float]
do_normalize: Optional[bool]
image_mean: Optional[Union[float, List[float]]]
image_std: Optional[Union[... | 117 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
class AudioKwargs(TypedDict, total=False):
"""
Keyword arguments for audio processing.
Attributes:
sampling_rate (`int`, *optional*):
The sampling rate at which the `raw_speech` input was sampled.
raw_speech (`np.ndarray`, `List[float]`, `List[np.ndarray]`, `List[List[float]]`):... | 118 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
sequence if provided).
- `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
acceptable input length for the model if that argument... | 118 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
sampling_rate: Optional[int]
raw_speech: Optional[Union["np.ndarray", List[float], List["np.ndarray"], List[List[float]]]]
padding: Optional[Union[bool, str, PaddingStrategy]]
max_length: Optional[int]
truncation: Optional[bool]
pad_to_multiple_of: Optional[int]
return_attention_mask: Optional[b... | 118 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
class CommonKwargs(TypedDict, total=False):
return_tensors: Optional[Union[str, TensorType]] | 119 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
class ProcessingKwargs(TextKwargs, ImagesKwargs, VideosKwargs, AudioKwargs, CommonKwargs, total=False):
"""
Base class for kwargs passing to processors.
A model should have its own `ModelProcessorKwargs` class that inherits from `ProcessingKwargs` to provide:
1) Additional typed keys and that this m... | 120 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
For Python 3.8 compatibility, when inheriting from this class and overriding one of the kwargs,
you need to manually update the __annotations__ dictionary. This can be done as follows:
```python
class CustomProcessorKwargs(ProcessingKwargs, total=False):
images_kwargs: CustomImagesKwargs
Custo... | 120 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
class ChatTemplateKwargs(TypedDict, total=False):
"""
Keyword arguments for processor chat templates. | 121 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
tokenize (`bool`, *optional*, defaults to `False`):
Whether to tokenize the output or not.
return_dict (`bool`, defaults to `False`):
Whether to return a dictionary with named outputs. Has no effect if tokenize is `False`.
tools (`List[Dict]`, *optional*):
A list of tools (callable funct... | 121 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
effect. We recommend that each document should be a dict containing "title" and "text" keys. Please
see the RAG section of the [chat templating guide](https://huggingface.co/docs/transformers/main/en/chat_templating#arguments-for-RAG)
for examples of passing documents with chat templates.
add_genera... | 121 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
rather than starting a new one. This allows you to "prefill" part of
the model's response for it. Cannot be used at the same time as `add_generation_prompt`.
return_assistant_tokens_mask (`bool`, defaults to `False`):
Whether to return a mask of the assistant generated tokens. For tokens generated b... | 121 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
that supports all types of sources to load from.
""" | 121 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
tokenize: Optional[bool] = False
return_dict: Optional[bool] = False
tools: Optional[List[Dict]] = None
documents: Optional[List[Dict[str, str]]] = None
add_generation_prompt: Optional[bool] = False
continue_final_message: Optional[bool] = False
return_assistant_tokens_mask: Optional[bool] = Fal... | 121 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
class AllKwargsForChatTemplate(
TextKwargs, ImagesKwargs, VideosKwargs, AudioKwargs, CommonKwargs, ChatTemplateKwargs
): ... | 122 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
class ProcessorMixin(PushToHubMixin):
"""
This is a mixin used to provide saving/loading functionality for all processor classes.
"""
attributes = ["feature_extractor", "tokenizer"]
optional_attributes = ["chat_template"]
optional_call_args: List[str] = []
# Names need to be attr_class for ... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
# args have to match the attributes class attribute
def __init__(self, *args, **kwargs):
# First, extract optional attributes from kwargs if present
# Optional attributes can never be positional arguments
for optional_attribute in self.optional_attributes:
setattr(self, optional_... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
if len(kwargs) != len(self.attributes):
raise ValueError(
f"This processor requires {len(self.attributes)} arguments: {', '.join(self.attributes)}. Got "
f"{len(args)} arguments instead."
)
# Check each arg is of the proper class (this will also catch a u... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
if not isinstance(arg, proper_class):
raise TypeError(
f"Received a {type(arg).__name__} for argument {attribute_name}, but a {class_name} was expected."
)
setattr(self, attribute_name, arg)
def to_dict(self) -> Dict[str, Any]:
"""
Se... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
output = {k: v for k, v in output.items() if k in attrs_to_save}
output["processor_class"] = self.__class__.__name__
if "tokenizer" in output:
del output["tokenizer"]
if "image_processor" in output:
del output["image_processor"]
if "feature_extractor" in output:... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
Returns:
`str`: String containing all the attributes that make up this feature_extractor instance in JSON format.
"""
dictionary = self.to_dict()
return json.dumps(dictionary, indent=2, sort_keys=True) + "\n"
def to_json_file(self, json_file_path: Union[str, os.PathLike]):
... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
def save_pretrained(self, save_directory, push_to_hub: bool = False, **kwargs):
"""
Saves the attributes of this processor (feature extractor, tokenizer...) in the specified directory so that it
can be reloaded using the [`~ProcessorMixin.from_pretrained`] method.
<Tip>
This cl... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
Args:
save_directory (`str` or `os.PathLike`):
Directory where the feature extractor JSON file and the tokenizer files will be saved (directory will
be created if it does not exist).
push_to_hub (`bool`, *optional*, defaults to `False`):
Whether or... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.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... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
if push_to_hub:
commit_message = kwargs.pop("commit_message", None)
repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
repo_id = self._create_repo(repo_id, **kwargs)
files_timestamps = self._get_files_timestamps(save_directory)
# If we have a c... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
for attribute_name in self.attributes:
attribute = getattr(self, attribute_name)
# Include the processor class in the attribute config so this processor can then be reloaded with the
# `AutoProcessor` API.
if hasattr(attribute, "_set_processor_class"):
att... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
# If we save using the predefined names, we can load using `from_pretrained`
# plus we save chat_template in its own file
output_processor_file = os.path.join(save_directory, PROCESSOR_NAME)
output_raw_chat_template_file = os.path.join(save_directory, "chat_template.jinja")
output_chat_t... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
processor_dict = self.to_dict()
# Save `chat_template` in its own file. We can't get it from `processor_dict` as we popped it in `to_dict`
# to avoid serializing chat template in json config file. So let's get it from `self` directly
if self.chat_template is not None:
if kwargs.get("... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
# For now, let's not save to `processor_config.json` if the processor doesn't have extra attributes and
# `auto_map` is not specified.
if set(processor_dict.keys()) != {"processor_class"}:
self.to_json_file(output_processor_file)
logger.info(f"processor saved in {output_processor... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
@classmethod
def get_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
processor of ty... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
Returns:
`Tuple[Dict, Dict]`: The dictionary(ies) that will be used to instantiate the processor object.
"""
cache_dir = kwargs.pop("cache_dir", None)
force_download = kwargs.pop("force_download", False)
resume_download = kwargs.pop("resume_download", None)
proxies = ... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.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):
processor_file = os.path.join(pretrained_model_name_or_path, PROCESSOR_NAME) | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
if os.path.isfile(pretrained_model_name_or_path):
resolved_processor_file = pretrained_model_name_or_path
# cant't load chat-template when given a file as pretrained_model_name_or_path
resolved_chat_template_file = None
resolved_raw_chat_template_file = None
i... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
resolved_processor_file = cached_file(
pretrained_model_name_or_path,
processor_file,
cache_dir=cache_dir,
force_download=force_download,
proxies=proxies,
resume_download=resume_download,
... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
# Load chat template from a separate json if exists
# because making it part of processor-config break BC.
# Processors in older version do not accept any kwargs
resolved_chat_template_file = cached_file(
pretrained_model_name_or_path,
... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
resolved_raw_chat_template_file = cached_file(
pretrained_model_name_or_path,
raw_chat_template_file,
cache_dir=cache_dir,
force_download=force_download,
proxies=proxies,
resume_download=resume_downlo... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
f"Can't load processor for '{pretrained_model_name_or_path}'. If you were trying to load"
" it from 'https://huggingface.co/models', make sure you don't have a local directory with the"
f" same name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a"... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
# Add chat template as kwarg before returning because most models don't have processor config
if resolved_raw_chat_template_file is not None:
with open(resolved_raw_chat_template_file, "r", encoding="utf-8") as reader:
chat_template = reader.read()
kwargs["chat_template"]... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
# Existing processors on the Hub created before #27761 being merged don't have `processor_config.json` (if not
# updated afterward), and we need to keep `from_pretrained` work. So here it fallbacks to the empty dict.
# (`cached_file` called using `_raise_exceptions_for_missing_entries=False` to avoid ex... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
if is_local:
logger.info(f"loading configuration file {resolved_processor_file}")
else:
logger.info(f"loading configuration file {processor_file} from cache at {resolved_processor_file}")
if "chat_template" in processor_dict and processor_dict["chat_template"] is not None:
... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
if not is_local:
if "auto_map" in processor_dict:
processor_dict["auto_map"] = add_model_info_to_auto_map(
processor_dict["auto_map"], pretrained_model_name_or_path
)
if "custom_pipelines" in processor_dict:
processor_dict["cust... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
Args:
processor_dict (`Dict[str, Any]`):
Dictionary that will be used to instantiate the processor object. Such a dictionary can be
retrieved from a pretrained checkpoint by leveraging the
[`~processing_utils.ProcessingMixin.to_dict`] method.
kwarg... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
# We have to pop up some unused (but specific) kwargs and then validate that it doesn't contain unused kwargs
# If we don't pop, some specific kwargs will raise a warning
if "processor_class" in processor_dict:
del processor_dict["processor_class"]
if "auto_map" in processor_dict:
... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
def _merge_kwargs(
self,
ModelProcessorKwargs: ProcessingKwargs,
tokenizer_init_kwargs: Optional[Dict] = None,
**kwargs,
) -> Dict[str, Dict]:
"""
Method to merge dictionaries of kwargs cleanly separated by modality within a Processor instance.
The order of op... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
```python
tokenizer = tokenizer_class(..., {"padding": "max_length"})
image_processor = image_processor_class(...)
processor(tokenizer, image_processor) # will pass max_length unless overriden by kwargs at call
```
4) defaults kwargs specified ... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
Dictionary of kwargs the tokenizer was instantiated with and need to take precedence over defaults. | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
Returns:
output_kwargs (`Dict`):
Dictionary of per-modality kwargs to be passed to each modality-specific processor.
"""
# Initialize dictionaries
output_kwargs = {
"text_kwargs": {},
"images_kwargs": {},
"audio_kwargs": {},
... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
# get defaults from set model processor kwargs if they exist
for modality in default_kwargs:
default_kwargs[modality] = ModelProcessorKwargs._defaults.get(modality, {}).copy()
# update defaults with arguments from tokenizer init
for modality_key in ModelProcessorKwargs.__anno... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
# update modality kwargs with passed kwargs
non_modality_kwargs = set(kwargs) - set(output_kwargs)
for modality in output_kwargs:
for modality_key in ModelProcessorKwargs.__annotations__[modality].__annotations__.keys():
# check if we received a structured kwarg dict or not t... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
# can have overlapping kwargs
kwarg_value = kwargs.get(modality_key, "__empty__")
else:
kwarg_value = "__empty__"
if kwarg_value != "__empty__":
output_kwargs[modality][modality_key] = kwarg_value
used_keys.a... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
# Determine if kwargs is a flat dictionary or contains nested dictionaries
if any(key in default_kwargs for key in kwargs):
# kwargs is dictionary-based, and some keys match modality names
for modality, subdict in kwargs.items():
if modality in default_kwargs:
... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
f"Keyword argument `{key}` is not a valid argument for this processor and will be ignored."
) | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
# all modality-specific kwargs are updated with common kwargs
for modality in output_kwargs:
output_kwargs[modality].update(output_kwargs["common_kwargs"])
return output_kwargs
@classmethod
def from_pretrained(
cls,
pretrained_model_name_or_path: Union[str, os.PathLi... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
This class method is simply calling the feature extractor
[`~feature_extraction_utils.FeatureExtractionMixin.from_pretrained`], image processor
[`~image_processing_utils.ImageProcessingMixin`] and the tokenizer
[`~tokenization_utils_base.PreTrainedTokenizer.from_pretrained`] methods. Please refe... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
- a string, the *model id* of a pretrained feature_extractor hosted inside a model repo on
huggingface.co.
- a path to a *directory* containing a feature extractor file saved using the
[`~SequenceFeatureExtractor.save_pretrained`] method, e.g., `./my_model_directory/`... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.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... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
@classmethod
def register_for_auto_class(cls, auto_class="AutoProcessor"):
"""
Register this class with a given auto class. This should only be used for custom feature extractors as the ones
in the library are already mapped with `AutoProcessor`.
<Tip warning={true}>
This A... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
@classmethod
def _get_arguments_from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
args = []
for attribute_name in cls.attributes:
class_name = getattr(cls, f"{attribute_name}_class")
if isinstance(class_name, tuple):
classes = tuple(getattr(transf... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
@staticmethod
def validate_init_kwargs(processor_config, valid_kwargs):
kwargs_from_config = processor_config.keys()
unused_kwargs = {}
unused_keys = set(kwargs_from_config) - set(valid_kwargs)
if unused_keys:
unused_key_str = ", ".join(unused_keys)
logger.war... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
Note that this should only be used in the `__call__` method of the processors with special
arguments. Special arguments are arguments that aren't `text`, `images`, `audio`, nor `videos`
but also aren't passed to the tokenizer, image processor, etc. Examples of such processors are:
- `CLIPSeg... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
Then, if we call the processor as:
```python
images = [...]
processor("What is common in these images?", images, arg_value_1, arg_value_2)
``` | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
Then, this method will return:
```python
{
"arg_name_1": arg_value_1,
"arg_name_2": arg_value_2,
}
```
which we could then pass as kwargs to `self._merge_kwargs`
"""
if len(args):
warnings.warn(
... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
"Please pass all arguments as keyword arguments instead (e.g. `processor(arg_name_1=..., arg_name_2=...))`."
)
return {arg_name: arg_value for arg_value, arg_name in zip(args, self.optional_call_args)} | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
def apply_chat_template(
self,
conversation: Union[List[Dict[str, str]]],
chat_template: Optional[str] = None,
**kwargs: Unpack[AllKwargsForChatTemplate],
) -> str:
"""
Similar to the `apply_chat_template` method on tokenizers, this method applies a Jinja template to ... | 123 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/processing_utils.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.