text stringlengths 1 1.02k | class_index int64 0 10.8k | source stringlengths 85 188 |
|---|---|---|
@property
def num_labels(self) -> int:
"""
`int`: The number of labels for classification models.
"""
return len(self.id2label)
@num_labels.setter
def num_labels(self, num_labels: int):
if not hasattr(self, "id2label") or self.id2label is None or len(self.id2label) !... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
@property
def _attn_implementation(self):
# This property is made private for now (as it cannot be changed and a PreTrainedModel.use_attn_implementation method needs to be implemented.)
if hasattr(self, "_attn_implementation_internal"):
if self._attn_implementation_internal is None:
... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
Args:
save_directory (`str` or `os.PathLike`):
Directory where the configuration 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 hub ... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
non_default_generation_parameters = self._get_non_default_generation_parameters()
if len(non_default_generation_parameters) > 0:
# TODO (joao): this should be an exception if the user has modified the loaded config. See #33886
warnings.warn(
"Some non-default generation p... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_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 ... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
if push_to_hub:
self._upload_modified_files(
save_directory,
repo_id,
files_timestamps,
commit_message=commit_message,
token=kwargs.get("token"),
)
@staticmethod
def _set_token_in_kwargs(kwargs, token=None):... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_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 token is not None:
raise ValueError(
... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
@classmethod
def from_pretrained(
cls,
pretrained_model_name_or_path: Union[str, os.PathLike],
cache_dir: Optional[Union[str, os.PathLike]] = None,
force_download: bool = False,
local_files_only: bool = False,
token: Optional[Union[str, bool]] = None,
revision... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.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
[`~PretrainedConfig.save_pretrained`] method, e.g., `./my_model_directory/`.
... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
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://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
token (`str` or ... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
<Tip>
To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>"`.
</Tip>
return_unused_kwargs (`bool`, *optional*, defaults to `False`):
If `False`, then this function returns just the final configuration object. | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
If `True`, then this functions returns a `Tuple(config, unused_kwargs)` where *unused_kwargs* is a
dictionary consisting of the key/value pairs whose keys are not configuration attributes: i.e., the
part of `kwargs` which has not been used to update `config` and is otherwise ignored.
... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
Returns:
[`PretrainedConfig`]: The configuration object instantiated from this pretrained model.
Examples: | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
```python
# We can't instantiate directly the base class *PretrainedConfig* so let's show the examples on a
# derived class: BertConfig
config = BertConfig.from_pretrained(
"google-bert/bert-base-uncased"
) # Download configuration from huggingface.co and cache.
conf... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
kwargs["cache_dir"] = cache_dir
kwargs["force_download"] = force_download
kwargs["local_files_only"] = local_files_only
kwargs["revision"] = revision | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
cls._set_token_in_kwargs(kwargs, token)
config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
if cls.base_config_key and cls.base_config_key in config_dict:
config_dict = config_dict[cls.base_config_key]
if "model_type" in config_dict and hasattr(cls, "... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
# raise warning only if we still can't see a match in `model_type`
if 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 ... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
Returns:
`Tuple[Dict, Dict]`: The dictionary(ies) that will be used to instantiate the configuration object.
"""
cls._set_token_in_kwargs(kwargs)
original_kwargs = copy.deepcopy(kwargs)
# Get config dict associated with the base config file
config_dict, kwargs = cls... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
@classmethod
def _get_config_dict(
cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
cache_dir = kwargs.pop("cache_dir", None)
force_download = kwargs.pop("force_download", False)
resume_download = kwargs.pop("resume... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
if trust_remote_code is True:
logger.warning(
"The argument `trust_remote_code` is to be used with Auto classes. It has no effect here and is"
" ignored."
)
user_agent = {"file_type": "config", "from_auto_class": from_auto_class}
if from_pipeline ... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
is_local = os.path.isdir(pretrained_model_name_or_path)
if os.path.isfile(os.path.join(subfolder, pretrained_model_name_or_path)):
# Special case when pretrained_model_name_or_path is a local file
resolved_config_file = pretrained_model_name_or_path
is_local = True
el... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
try:
# Load from local folder or from cache or download from model Hub and cache
resolved_config_file = cached_file(
pretrained_model_name_or_path,
configuration_file,
cache_dir=cache_dir,
force_download=forc... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
# Raise any environment error raise by `cached_file`. It will have a helpful error message adapted to
# the original exception.
raise
except Exception:
# For any other exception, we throw a generic error.
raise EnvironmentError(
... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
try:
if gguf_file:
config_dict = load_gguf_checkpoint(resolved_config_file, return_tensors=False)["config"]
else:
# Load config dict
config_dict = cls._dict_from_json_file(resolved_config_file)
config_dict["_commit_hash"] = commit_hash... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
if "auto_map" in config_dict and not is_local:
config_dict["auto_map"] = add_model_info_to_auto_map(
config_dict["auto_map"], pretrained_model_name_or_path
)
if "custom_pipelines" in config_dict and not is_local:
config_dict["custom_pipelines"] = add_model_inf... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
Args:
config_dict (`Dict[str, Any]`):
Dictionary that will be used to instantiate the configuration object. Such a dictionary can be
retrieved from a pretrained checkpoint by leveraging the [`~PretrainedConfig.get_config_dict`] method.
kwargs (`Dict[str, Any]`):
... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
Returns:
[`PretrainedConfig`]: The configuration object instantiated from those parameters.
"""
return_unused_kwargs = kwargs.pop("return_unused_kwargs", False)
# Those arguments may be passed along for our internal telemetry.
# We remove them so they don't appear in `return_... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
if hasattr(config, "pruned_heads"):
config.pruned_heads = {int(key): value for key, value in config.pruned_heads.items()} | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
# Update config with kwargs if needed
if "num_labels" in kwargs and "id2label" in kwargs:
num_labels = kwargs["num_labels"]
id2label = kwargs["id2label"] if kwargs["id2label"] is not None else []
if len(id2label) != num_labels:
raise ValueError(
... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
setattr(config, key, value)
if key != "torch_dtype":
to_remove.append(key)
for key in to_remove:
kwargs.pop(key, None) | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
logger.info(f"Model config {config}")
if return_unused_kwargs:
return config, kwargs
else:
return config
@classmethod
def from_json_file(cls, json_file: Union[str, os.PathLike]) -> "PretrainedConfig":
"""
Instantiates a [`PretrainedConfig`] from the path ... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
def __eq__(self, other):
return isinstance(other, PretrainedConfig) and (self.__dict__ == other.__dict__)
def __repr__(self):
return f"{self.__class__.__name__} {self.to_json_string()}"
def __iter__(self):
for attr in self.__dict__:
yield attr
def to_diff_dict(self) ->... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
# only serialize values that differ from the default config
for key, value in config_dict.items():
if (
isinstance(getattr(self, key, None), PretrainedConfig)
and key in class_config_dict
and isinstance(class_config_dict[key], dict)
):
... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
):
serializable_config_dict[key] = value | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
if hasattr(self, "quantization_config"):
serializable_config_dict["quantization_config"] = (
self.quantization_config.to_dict()
if not isinstance(self.quantization_config, dict)
else self.quantization_config
)
# pop the `_pre_quantizat... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
Returns:
`Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
"""
output = copy.deepcopy(self.__dict__)
if hasattr(self.__class__, "model_type"):
output["model_type"] = self.__class__.model_type
if "_auto_class" in output:
... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
for key, value in output.items():
# Deal with nested configs like CLIP
if isinstance(value, PretrainedConfig):
value = value.to_dict()
del value["transformers_version"]
output[key] = value
if hasattr(self, "quantization_config"):
... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
Args:
use_diff (`bool`, *optional*, defaults to `True`):
If set to `True`, only the difference between the config instance and the default `PretrainedConfig()`
is serialized to JSON string.
Returns:
`str`: String containing all the attributes that make up... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
Args:
json_file_path (`str` or `os.PathLike`):
Path to the JSON file in which this configuration instance's parameters will be saved.
use_diff (`bool`, *optional*, defaults to `True`):
If set to `True`, only the difference between the config instance and the defau... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
def update_from_string(self, update_str: str):
"""
Updates attributes of this class with attributes from `update_str`.
The expected format is ints, floats and strings as is, and for booleans use `true` or `false`. For example:
"n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
old_v = getattr(self, k)
if isinstance(old_v, bool):
if v.lower() in ["true", "1", "y", "yes"]:
v = True
elif v.lower() in ["false", "0", "n", "no"]:
v = False
else:
raise ValueError(f"can't derive tr... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
def dict_torch_dtype_to_str(self, d: Dict[str, Any]) -> None:
"""
Checks whether the passed dictionary and its nested dicts have a *torch_dtype* key and if it's not None,
converts torch.dtype to a string of just the type. For example, `torch.float32` get converted into *"float32"*
string... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
@classmethod
def register_for_auto_class(cls, auto_class="AutoConfig"):
"""
Register this class with a given auto class. This should only be used for custom configurations as the ones in
the library are already mapped with `AutoConfig`.
<Tip warning={true}>
This API is expe... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
@staticmethod
def _get_global_generation_defaults() -> Dict[str, Any]:
return {
"max_length": 20,
"min_length": 0,
"do_sample": False,
"early_stopping": False,
"num_beams": 1,
"num_beam_groups": 1,
"diversity_penalty": 0.0,
... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
def _get_non_default_generation_parameters(self) -> Dict[str, Any]:
"""
Gets the non-default generation parameters on the PretrainedConfig instance
"""
non_default_generation_parameters = {}
decoder_attribute_name = None
# Composite models don't have a default config, us... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
for parameter_name, default_global_value in self._get_global_generation_defaults().items():
if hasattr(self_decoder_config, parameter_name):
is_default_in_config = is_default_generation_value = None
parameter_value = getattr(self_decoder_config, parameter_name)
... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
is_default_generation_value = parameter_value == default_global_value | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
is_non_default = (is_default_in_config is False) or (
is_default_in_config is None and is_default_generation_value is False
)
if is_non_default:
non_default_generation_parameters[parameter_name] = getattr(self_decoder_config, parameter_name)
... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
If `decoder` is set to `True`, then only search for decoder config names.
"""
decoder_possible_text_config_names = ("decoder", "generator", "text_config")
encoder_possible_text_config_names = ("text_encoder",)
if decoder:
possible_text_config_names = decoder_possible_text_con... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
if len(valid_text_config_names) > 1:
raise ValueError(
f"Multiple valid text configs were found in the model config: {valid_text_config_names}. In this "
"case, using `get_text_config()` would be ambiguous. Please specify the desied text config directly."
)
... | 46 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/configuration_utils.py |
class FlashAttentionKwargs(TypedDict, total=False):
"""
Keyword arguments for Flash Attention with Compile.
Attributes:
cu_seq_lens_q (`torch.LongTensor`, *optional*)
Gets cumlative sequence length for query state.
cu_seq_lens_k (`torch.LongTensor`, *optional*)
Gets ... | 47 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flash_attention_utils.py |
class SizeDict:
"""
Hashable dictionary to store image size information.
"""
height: int = None
width: int = None
longest_edge: int = None
shortest_edge: int = None
max_height: int = None
max_width: int = None
def __getitem__(self, key):
if hasattr(self, key):
... | 48 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_utils_fast.py |
class BaseImageProcessorFast(BaseImageProcessor):
_transform_params = None
def _build_transforms(self, **kwargs) -> "Compose":
"""
Given the input settings e.g. do_resize, build the image transforms.
"""
raise NotImplementedError
def _validate_params(self, **kwargs) -> None... | 49 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_processing_utils_fast.py |
class ChannelDimension(ExplicitEnum):
FIRST = "channels_first"
LAST = "channels_last" | 50 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_utils.py |
class AnnotationFormat(ExplicitEnum):
COCO_DETECTION = "coco_detection"
COCO_PANOPTIC = "coco_panoptic" | 51 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_utils.py |
class AnnotionFormat(ExplicitEnum):
COCO_DETECTION = AnnotationFormat.COCO_DETECTION.value
COCO_PANOPTIC = AnnotationFormat.COCO_PANOPTIC.value | 52 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_utils.py |
class ImageType(ExplicitEnum):
PIL = "pillow"
TORCH = "torch"
NUMPY = "numpy"
TENSORFLOW = "tensorflow"
JAX = "jax" | 53 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_utils.py |
class ImageFeatureExtractionMixin:
"""
Mixin that contain utilities for preparing image features.
"""
def _ensure_format_supported(self, image):
if not isinstance(image, (PIL.Image.Image, np.ndarray)) and not is_torch_tensor(image):
raise ValueError(
f"Got type {type... | 54 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_utils.py |
Args:
image (`PIL.Image.Image` or `numpy.ndarray` or `torch.Tensor`):
The image to convert to the PIL Image format.
rescale (`bool`, *optional*):
Whether or not to apply the scaling factor (to make pixel values integers between 0 and 255). Will
def... | 54 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_utils.py |
if isinstance(image, np.ndarray):
if rescale is None:
# rescale default to the array being of floating type.
rescale = isinstance(image.flat[0], np.floating)
# If the channel as been moved to first dim, we put it back at the end.
if image.ndim == 3 and... | 54 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_utils.py |
def rescale(self, image: np.ndarray, scale: Union[float, int]) -> np.ndarray:
"""
Rescale a numpy image by scale amount
"""
self._ensure_format_supported(image)
return image * scale
def to_numpy_array(self, image, rescale=None, channel_first=True):
"""
Conver... | 54 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_utils.py |
Args:
image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
The image to convert to a NumPy array.
rescale (`bool`, *optional*):
Whether or not to apply the scaling factor (to make pixel values floats between 0. and 1.). Will
default to `Tru... | 54 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_utils.py |
if channel_first and image.ndim == 3:
image = image.transpose(2, 0, 1)
return image
def expand_dims(self, image):
"""
Expands 2-dimensional `image` to 3 dimensions.
Args:
image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
The image... | 54 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_utils.py |
Args:
image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
The image to normalize.
mean (`List[float]` or `np.ndarray` or `torch.Tensor`):
The mean (per channel) to use for normalization.
std (`List[float]` or `np.ndarray` or `torch.Tensor`):
... | 54 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_utils.py |
if isinstance(image, PIL.Image.Image):
image = self.to_numpy_array(image, rescale=True)
# If the input image is a PIL image, it automatically gets rescaled. If it's another
# type it may need rescaling.
elif rescale:
if isinstance(image, np.ndarray):
image... | 54 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_utils.py |
if not isinstance(mean, torch.Tensor):
if isinstance(mean, np.ndarray):
mean = torch.from_numpy(mean)
else:
mean = torch.tensor(mean)
if not isinstance(std, torch.Tensor):
if isinstance(std, np.ndarray):
... | 54 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_utils.py |
Args:
image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
The image to resize.
size (`int` or `Tuple[int, int]`):
The size to use for resizing the image. If `size` is a sequence like (h, w), output size will be
matched to this. | 54 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_utils.py |
If `size` is an int and `default_to_square` is `True`, then image will be resized to (size, size). If
`size` is an int and `default_to_square` is `False`, then smaller edge of the image will be matched to
this number. i.e, if height > width, then image will be rescaled to (size * height ... | 54 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_utils.py |
max_size (`int`, *optional*, defaults to `None`):
The maximum allowed for the longer edge of the resized image: if the longer edge of the image is
greater than `max_size` after being resized according to `size`, then the image is resized again so
that the longer edge is e... | 54 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_utils.py |
Returns:
image: A resized `PIL.Image.Image`.
"""
resample = resample if resample is not None else PILImageResampling.BILINEAR
self._ensure_format_supported(image)
if not isinstance(image, PIL.Image.Image):
image = self.to_pil_image(image)
if isinstance(... | 54 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_utils.py |
if max_size is not None:
if max_size <= requested_new_short:
raise ValueError(
f"max_size = {max_size} must be strictly greater than the requested "
f"size for the smaller edge size = {size}"
)
... | 54 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_utils.py |
Args:
image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor` of shape (n_channels, height, width) or (height, width, n_channels)):
The image to resize.
size (`int` or `Tuple[int, int]`):
The size to which crop the image.
Returns:
new_image... | 54 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_utils.py |
top = (image_shape[0] - size[0]) // 2
bottom = top + size[0] # In case size is odd, (image_shape[0] + size[0]) // 2 won't give the proper result.
left = (image_shape[1] - size[1]) // 2
right = left + size[1] # In case size is odd, (image_shape[1] + size[1]) // 2 won't give the proper result.
... | 54 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_utils.py |
# Check if cropped area is within image boundaries
if top >= 0 and bottom <= image_shape[0] and left >= 0 and right <= image_shape[1]:
return image[..., top:bottom, left:right]
# Otherwise, we may need to pad if the image is too small. Oh joy...
new_shape = image.shape[:-2] + (max(s... | 54 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_utils.py |
new_image = new_image[
..., max(0, top) : min(new_image.shape[-2], bottom), max(0, left) : min(new_image.shape[-1], right)
]
return new_image
def flip_channel_order(self, image):
"""
Flips the channel order of `image` from RGB to BGR, or vice versa. Note that this will ... | 54 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_utils.py |
def rotate(self, image, angle, resample=None, expand=0, center=None, translate=None, fillcolor=None):
"""
Returns a rotated copy of `image`. This method returns a copy of `image`, rotated the given number of degrees
counter clockwise around its centre.
Args:
image (`PIL.Imag... | 54 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_utils.py |
class Trie:
"""
Trie in Python. Creates a Trie out of a list of words. The trie is used to split on `added_tokens` in one pass
Loose reference https://en.wikipedia.org/wiki/Trie
"""
def __init__(self, *args):
self.data = {}
self._tokens = set()
self._termination_char = ""
... | 55 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils.py |
```python
>>> trie = Trie()
>>> trie.add("Hello 友達")
>>> trie.data
{"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}}
>>> trie.add("Hello")
>>> trie.data
{"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {"達": {"": 1}}}}}}}}}
```
"""
... | 55 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils.py |
```python
>>> trie = Trie()
>>> trie.split("[CLS] This is a extra_id_100")
["[CLS] This is a extra_id_100"]
>>> trie.add("[CLS]")
>>> trie.add("extra_id_1")
>>> trie.add("extra_id_100")
>>> trie.split("[CLS] This is a extra_id_100")
["[CLS]", " This is a ... | 55 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils.py |
# States are going to capture every possible start (indexes as above)
# as keys, and have as values, a pointer to the position in the trie
# where we're at. This is a partial match for now.
# This enables to keep track of multiple matches while we're iterating
# the string
# If t... | 55 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils.py |
# This is used by the lookahead which needs to skip over
# some text where the full match exceeded the place in the initial
# for loop
skip = 0
# Main loop, Giving this algorithm O(n) complexity
for current, current_char in enumerate(text):
if skip and current < skip:... | 55 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils.py |
# In this case, we already have partial matches (But unfinished)
for start, trie_pointer in states.items():
if "" in trie_pointer:
# This is a final match, we need to reset and
# store the results in `offsets`. | 55 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils.py |
# Lookahead to match longest first
# Important in case of extra_id_1 vs extra_id_100
# Here we are also actively looking for other earlier partial
# matches
# "[CLS]", "L", we need to match CLS even if L is special
for l... | 55 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils.py |
# It wasn't updated yet so indices are current ones
lookahead_index = current
end = current
next_char = text[lookahead_index] if lookahead_index < len(text) else None
if "" in looktrie_pointer:
... | 55 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils.py |
while next_char in looktrie_pointer:
looktrie_pointer = looktrie_pointer[next_char]
lookahead_index += 1
if "" in looktrie_pointer:
start = lookstart
end = lookahead_index
... | 55 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils.py |
# Storing and resetting
offsets.append(start)
offsets.append(end)
reset = True
break
elif current_char in trie_pointer:
# The current character being looked at has a match within the trie
... | 55 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils.py |
# Either clearing the full start (we found a real match)
# Or clearing only the partial matches that didn't work.
if reset:
states = {}
else:
for start in to_remove:
del states[start]
# If this character is a starting c... | 55 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils.py |
# We have a cut at the end with states.
for start, trie_pointer in states.items():
if "" in trie_pointer:
# This is a final match, we need to reset and
# store the results in `offsets`.
end = len(text)
offsets.append(start)
... | 55 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils.py |
def cut_text(self, text, offsets):
# We have all the offsets now, we just need to do the actual splitting.
# We need to eventually add the first part of the string and the eventual
# last part.
offsets.append(len(text))
tokens = []
start = 0
for end in offsets:
... | 55 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils.py |
class ExtensionsTrie(Trie):
def __init__(self, *args):
super().__init__(*args)
def extensions(self, prefix: str):
"""
Generates all extensions of a given prefix token in the Trie.
Example:
```python
>>> trie = Trie()
>>> trie.add("apple")
>>> tr... | 56 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils.py |
Returns:
dict: The node in the Trie corresponding to the given token.
"""
node = self.data
for char in token:
if char not in node:
break
node = node[char]
return node
def _collect_tokens(self, node: dict) -> list:
"""
... | 56 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils.py |
class PreTrainedTokenizer(PreTrainedTokenizerBase):
"""
Base class for all slow tokenizers.
Inherits from [`~tokenization_utils_base.PreTrainedTokenizerBase`].
Handle all the shared methods for tokenization and special tokens as well as methods downloading/caching/loading
pretrained tokenizers as ... | 57 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils.py |
# 3. if a `added_tokens_decoder` is passed, we are loading from a saved tokenizer, we overwrite
self._added_tokens_decoder.update(kwargs.pop("added_tokens_decoder", {}))
self._added_tokens_encoder: Dict[str, int] = {k.content: v for v, k in self._added_tokens_decoder.items()}
# 4 init the paren... | 57 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils.py |
@property
def vocab_size(self) -> int:
"""
`int`: Size of the base vocabulary (without the added tokens).
"""
raise NotImplementedError
@property
def added_tokens_encoder(self) -> Dict[str, int]:
"""
Returns the sorted mapping from string to index. The added ... | 57 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils.py |
@added_tokens_decoder.setter
def added_tokens_decoder(self, value: Dict[int, Union[AddedToken, str]]) -> Dict[int, AddedToken]:
# Always raise an error if string because users should define the behavior
for index, token in value.items():
if not isinstance(token, (str, AddedToken)) or not... | 57 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils.py |
def get_added_vocab(self) -> Dict[str, int]:
"""
Returns the added tokens in the vocabulary as a dictionary of token to index. Results might be different from
the fast call because for now we always add the tokens even if they are already in the vocabulary. This is
something we should ch... | 57 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils.py |
def _add_tokens(self, new_tokens: Union[List[str], List[AddedToken]], special_tokens: bool = False) -> int:
"""
Add a list of new tokens to the tokenizer class. If the new tokens are not in the vocabulary, they are added to
it with indices starting from length of the current vocabulary. Special ... | 57 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils.py |
Args:
new_tokens (`List[str]`or `List[tokenizers.AddedToken]`):
Token(s) to add in vocabulary. A token is counted as added if it's not already in the vocabulary
(tested by checking if the tokenizer assign the index of the `unk_token` to them). If a token is part
... | 57 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils.py |
```python
# Let's see how to increase the vocabulary of Bert model and tokenizer
tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased")
model = BertModel.from_pretrained("google-bert/bert-base-uncased") | 57 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils.py |
num_added_toks = tokenizer.add_tokens(["new_tok1", "my_new-tok2"])
print("We have added", num_added_toks, "tokens")
# Note: resize_token_embeddings expects to receive the full size of the new vocabulary, i.e. the length of the tokenizer.
model.resize_token_embeddings(len(tokenizer))
```"... | 57 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.