text stringlengths 1 1.02k | class_index int64 0 10.8k | source stringlengths 85 188 |
|---|---|---|
# Maybe the checkpoint is sharded, we try to grab the index name in this case.
if resolved_archive_file is None and filename == FLAX_WEIGHTS_NAME:
resolved_archive_file = cached_file(
pretrained_model_name_or_path, FLAX_WEIGHTS_INDEX_NAME, **cached... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
# If we still haven't found anything, look for `safetensors`.
if resolved_archive_file is None:
# No support for sharded safetensors yet, so we'll raise an error if that's all we find.
filename = SAFE_WEIGHTS_NAME
resolved_archi... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
# Since we set _raise_exceptions_for_missing_entries=False, we don't get an exception but a None
# result when internet is up, the repo and revision exist, but the file does not.
if resolved_archive_file is None:
# Otherwise, maybe there is a TF or Torch m... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
"Support for sharded checkpoints using safetensors is coming soon!"
)
elif has_file(pretrained_model_name_or_path, WEIGHTS_NAME, **has_file_kwargs):
raise EnvironmentError(
f"{pretrained_model_name_or_path} d... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
" `from_pt=True` to load this model from those weights."
)
else:
raise EnvironmentError(
f"{pretrained_model_name_or_path} does not appear to have a file named"
f" {FLAX_WEIGHT... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
" 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"
f" directory containing a file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME}."
... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
if is_local:
logger.info(f"loading weights file {archive_file}")
resolved_archive_file = archive_file
filename = resolved_archive_file.split(os.path.sep)[-1]
else:
logger.info(f"loading weights file {filename} from cache at {resolved_archive_fi... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
# We'll need to download and cache each checkpoint shard if the checkpoint is sharded.
if is_sharded:
# resolved_archive_file becomes a list of files that point to the different checkpoint shards in this case.
resolved_archive_file, _ = get_checkpoint_shard_files(
pretrai... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
safetensors_from_pt = False
if filename == SAFE_WEIGHTS_NAME:
with safe_open(resolved_archive_file, framework="flax") as f:
safetensors_metadata = f.metadata()
if safetensors_metadata is None or safetensors_metadata.get("format") not in ["pt", "tf", "flax"]:
... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
if from_pt or safetensors_from_pt:
state = load_pytorch_checkpoint_in_flax_state_dict(model, resolved_archive_file, is_sharded)
else:
if is_sharded:
state = cls.load_flax_sharded_weights(resolved_archive_file)
else:
state = cls.load_flax_weight... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
if "batch_stats" in state: # if flax model contains batch norm layers
# if model is base model only use model_prefix key
if (
cls.base_model_prefix not in dict(model.params_shape_tree["params"])
and cls.base_model_prefix in state["params"]
):
... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
else:
# if model is base model only use model_prefix key
if cls.base_model_prefix not in dict(model.params_shape_tree) and cls.base_model_prefix in state:
state = state[cls.base_model_prefix]
# if model is head model and we are loading weights from base model
... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
# Disabling warning when porting pytorch weights to flax, flax does not uses num_batches_tracked
for unexpected_key in unexpected_keys.copy():
if "num_batches_tracked" in unexpected_key[-1]:
unexpected_keys.remove(unexpected_key)
if missing_keys and not _do_init:
... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
# Mistmatched keys contains tuples key/shape1/shape2 of weights in the checkpoint that have a shape not
# matching the weights in the model.
mismatched_keys = []
for key in state.keys():
if key in random_state and state[key].shape != random_state[key].shape:
if ignore... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
# add missing keys as random parameters if we are initializing
if missing_keys and _do_init:
for missing_key in missing_keys:
state[missing_key] = random_state[missing_key]
# remove unexpected keys to not be saved again
for unexpected_key in unexpected_keys:
... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
if len(unexpected_keys) > 0:
logger.warning(
f"Some weights of the model checkpoint at {pretrained_model_name_or_path} were not used when"
f" initializing {model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are"
f" initializing {model.__cl... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
if len(missing_keys) > 0:
logger.warning(
f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at"
f" {pretrained_model_name_or_path} and are newly initialized: {missing_keys}\nYou should probably"
" TRAIN this model on a... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
f"- {key}: found shape {shape1} in the checkpoint and {shape2} in the model instantiated"
for key, shape1, shape2 in mismatched_keys
]
)
logger.warning(
f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
# dictionary of key: dtypes for the model params
param_dtypes = jax.tree_util.tree_map(lambda x: x.dtype, state)
# extract keys of parameters not in jnp.float32
fp16_params = [k for k in param_dtypes if param_dtypes[k] == jnp.float16]
bf16_params = [k for k in param_dtypes if param_dtype... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
if len(bf16_params) > 0:
logger.warning(
f"Some of the weights of {model.__class__.__name__} were initialized in bfloat16 precision from "
f"the model checkpoint at {pretrained_model_name_or_path}:\n{bf16_params}\n"
"You should probably UPCAST the model weight... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
# If it is a model with generation capabilities, attempt to load the generation config
if model.can_generate():
try:
model.generation_config = GenerationConfig.from_pretrained(
pretrained_model_name_or_path,
cache_dir=cache_dir,
... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
if _do_init:
# set correct parameters
model.params = unflatten_dict(state)
return model
else:
return model, unflatten_dict(state)
def save_pretrained(
self,
save_directory: Union[str, os.PathLike],
params=None,
push_to_hub=Fals... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
Arguments:
save_directory (`str` or `os.PathLike`):
Directory to which to save. Will be created if it doesn't exist.
push_to_hub (`bool`, *optional*, defaults to `False`):
Whether or not to push your model to the Hugging Face model hub after saving it. You can spe... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
</Tip>
token (`str` or `bool`, *optional*):
The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use
the token generated when running `huggingface-cli login` (stored in `~/.huggingface`).
kwargs (`Dict[str, Any]`, *opt... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_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(
... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_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)
# get abs dir
... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
# save model
weights_name = SAFE_WEIGHTS_NAME if safe_serialization else FLAX_WEIGHTS_NAME
output_model_file = os.path.join(save_directory, weights_name)
shards, index = flax_shard_checkpoint(params if params is not None else self.params, max_shard_size)
# Clean the folder from a previo... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
if index is None:
if safe_serialization:
params = params if params is not None else self.params
flat_dict = flatten_dict(params, sep=".")
safe_save_file(flat_dict, output_model_file, metadata={"format": "flax"})
else:
with open(outp... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
else:
save_index_file = os.path.join(save_directory, FLAX_WEIGHTS_INDEX_NAME)
# Save the index as well
with open(save_index_file, "w", encoding="utf-8") as f:
content = json.dumps(index, indent=2, sort_keys=True) + "\n"
f.write(content)
log... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
f.write(shard_bytes) | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
logger.info(f"Model weights saved in {output_model_file}")
if push_to_hub:
self._upload_modified_files(
save_directory,
repo_id,
files_timestamps,
commit_message=commit_message,
token=token,
)
@classmet... | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
import transformers.models.auto as auto_module
if not hasattr(auto_module, auto_class):
raise ValueError(f"{auto_class} is not a valid auto class.")
cls._auto_class = auto_class | 61 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_flax_utils.py |
class PaddingMode(ExplicitEnum):
"""
Enum class for the different padding modes to use when padding images.
"""
CONSTANT = "constant"
REFLECT = "reflect"
REPLICATE = "replicate"
SYMMETRIC = "symmetric" | 62 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_transforms.py |
class FusedRescaleNormalize:
"""
Rescale and normalize the input image in one step.
"""
def __init__(self, mean, std, rescale_factor: float = 1.0, inplace: bool = False):
self.mean = torch.tensor(mean) * (1.0 / rescale_factor)
self.std = torch.tensor(std) * (1.0 / rescale_factor)
... | 63 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_transforms.py |
class Rescale:
"""
Rescale the input image by rescale factor: image *= rescale_factor.
"""
def __init__(self, rescale_factor: float = 1.0):
self.rescale_factor = rescale_factor
def __call__(self, image: "torch.Tensor"):
image = image * self.rescale_factor
return image | 64 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_transforms.py |
class NumpyToTensor:
"""
Convert a numpy array to a PyTorch tensor.
"""
def __call__(self, image: np.ndarray):
# Same as in PyTorch, we assume incoming numpy images are in HWC format
# c.f. https://github.com/pytorch/vision/blob/61d97f41bc209e1407dcfbd685d2ee2da9c1cdad/torchvision/trans... | 65 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/image_transforms.py |
class BatchFeature(UserDict):
r"""
Holds the output of the [`~SequenceFeatureExtractor.pad`] and feature extractor specific `__call__` methods.
This class is derived from a python dictionary and can be used as a dictionary.
Args:
data (`dict`, *optional*):
Dictionary of lists/array... | 66 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
def __getitem__(self, item: str) -> Union[Any]:
"""
If the key is a string, returns the value of the dict associated to `key` ('input_values', 'attention_mask',
etc.).
"""
if isinstance(item, str):
return self.data[item]
else:
raise KeyError("Index... | 66 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
# Copied from transformers.tokenization_utils_base.BatchEncoding.items
def items(self):
return self.data.items()
def _get_is_as_tensor_fns(self, tensor_type: Optional[Union[str, TensorType]] = None):
if tensor_type is None:
return None, None
# Convert to TensorType
... | 66 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
as_tensor = tf.constant
is_tensor = tf.is_tensor
elif tensor_type == TensorType.PYTORCH:
if not is_torch_available():
raise ImportError("Unable to convert output to PyTorch tensors format, PyTorch is not installed.")
import torch # noqa
def as_te... | 66 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
is_tensor = torch.is_tensor
elif tensor_type == TensorType.JAX:
if not is_flax_available():
raise ImportError("Unable to convert output to JAX tensors format, JAX is not installed.")
import jax.numpy as jnp # noqa: F811
as_tensor = jnp.array
is_t... | 66 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
def convert_to_tensors(self, tensor_type: Optional[Union[str, TensorType]] = None):
"""
Convert the inner content to tensors.
Args:
tensor_type (`str` or [`~utils.TensorType`], *optional*):
The type of tensors to use. If `str`, should be one of the values of the enum... | 66 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
self[key] = tensor
except: # noqa E722
if key == "overflowing_values":
raise ValueError("Unable to create tensor returning overflowing values of different lengths. ")
raise ValueError(
"Unable to create tensor, you should probably acti... | 66 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
Args:
args (`Tuple`):
Will be passed to the `to(...)` function of the tensors.
kwargs (`Dict`, *optional*):
Will be passed to the `to(...)` function of the tensors.
To enable asynchronous data transfer, set the `non_blocking` flag in `kwargs` (defa... | 66 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
new_data = {}
device = kwargs.get("device")
non_blocking = kwargs.get("non_blocking", False)
# Check if the args are a device or a dtype
if device is None and len(args) > 0:
# device should be always the first argument
arg = args[0]
if is_torch_dtype(a... | 66 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
new_data[k] = v.to(*args, **kwargs)
elif isinstance(v, torch.Tensor) and device is not None:
new_data[k] = v.to(device=device, non_blocking=non_blocking)
else:
new_data[k] = v
self.data = new_data
return self | 66 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
class FeatureExtractionMixin(PushToHubMixin):
"""
This is a feature extraction 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."""
# Po... | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_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... | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_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
[`~feature_extraction_utils.FeatureExtractionMixin.save_pretrained`] method, e.g.,
... | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.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:/... | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
<Tip>
To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>"`.
</Tip> | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
return_unused_kwargs (`bool`, *optional*, defaults to `False`):
If `False`, then this function returns just the final feature extractor object. If `True`, then this
functions returns a `Tuple(feature_extractor, unused_kwargs)` where *unused_kwargs* is a dictionary
consist... | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
Examples: | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
```python
# We can't instantiate directly the base class *FeatureExtractionMixin* nor *SequenceFeatureExtractor* so let's show the examples on a
# derived class: *Wav2Vec2FeatureExtractor*
feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(
"facebook/wav2vec2-base-960h"
... | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
feature_extractor, unused_kwargs = Wav2Vec2FeatureExtractor.from_pretrained(
"facebook/wav2vec2-base-960h", return_attention_mask=False, foo=False, return_unused_kwargs=True
)
assert feature_extractor.return_attention_mask is False
assert unused_kwargs == {"foo": False}
```""... | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_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... | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
def save_pretrained(self, save_directory: Union[str, os.PathLike], push_to_hub: bool = False, **kwargs):
"""
Save a feature_extractor object to the directory `save_directory`, so that it can be re-loaded using the
[`~feature_extraction_utils.FeatureExtractionMixin.from_pretrained`] class method. | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
Args:
save_directory (`str` or `os.PathLike`):
Directory where the feature extractor 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 ... | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_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... | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.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... | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
@classmethod
def get_feature_extractor_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
feature... | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
Returns:
`Tuple[Dict, Dict]`: The dictionary(ies) that will be used to instantiate the feature extractor object.
"""
cache_dir = kwargs.pop("cache_dir", None)
force_download = kwargs.pop("force_download", False)
resume_download = kwargs.pop("resume_download", None)
pr... | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_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(
... | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_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):
feature_extractor_file = os.path.join(pretrained_model_name_or_path, FEATURE_EXTRACTOR_NAME)
if os.path.isfile(p... | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
cache_dir=cache_dir,
force_download=force_download,
proxies=proxies,
resume_download=resume_download,
local_files_only=local_files_only,
subfolder=subfolder,
token=token,
user_agen... | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
f" same name. Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a"
f" directory containing a {FEATURE_EXTRACTOR_NAME} file"
) | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
try:
# Load feature_extractor dict
with open(resolved_feature_extractor_file, "r", encoding="utf-8") as reader:
text = reader.read()
feature_extractor_dict = json.loads(text)
except json.JSONDecodeError:
raise EnvironmentError(
f"I... | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
if not is_local:
if "auto_map" in feature_extractor_dict:
feature_extractor_dict["auto_map"] = add_model_info_to_auto_map(
feature_extractor_dict["auto_map"], pretrained_model_name_or_path
)
if "custom_pipelines" in feature_extractor_dict:
... | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
Args:
feature_extractor_dict (`Dict[str, Any]`):
Dictionary that will be used to instantiate the feature extractor object. Such a dictionary can be
retrieved from a pretrained checkpoint by leveraging the
[`~feature_extraction_utils.FeatureExtractionMixin.to_d... | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
# Update feature_extractor with kwargs if needed
to_remove = []
for key, value in kwargs.items():
if key in feature_extractor_dict:
feature_extractor_dict[key] = value
to_remove.append(key)
for key in to_remove:
kwargs.pop(key, None)
... | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
def to_dict(self) -> Dict[str, Any]:
"""
Serializes this instance to a Python dictionary. Returns:
`Dict[str, Any]`: Dictionary of all the attributes that make up this configuration instance.
"""
output = copy.deepcopy(self.__dict__)
output["feature_extractor_type"] =... | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
Returns:
A feature extractor of type [`~feature_extraction_utils.FeatureExtractionMixin`]: The feature_extractor
object instantiated from that JSON file.
"""
with open(json_file, "r", encoding="utf-8") as reader:
text = reader.read()
feature_extractor_dict = j... | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.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... | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
@classmethod
def register_for_auto_class(cls, auto_class="AutoFeatureExtractor"):
"""
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 `AutoFeatureExtractor`.
<Tip warning={true}>
... | 67 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/feature_extraction_utils.py |
class AddedToken:
"""
AddedToken represents a token to be added to a Tokenizer An AddedToken can have special options defining the
way it should behave.
The `normalized` will default to `not special` if it is not specified, similarly to the definition in
`tokenizers`.
""... | 68 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
class EncodingFast:
"""This is dummy class because without the `tokenizers` library we don't have these objects anyway"""
pass | 69 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
class TruncationStrategy(ExplicitEnum):
"""
Possible values for the `truncation` argument in [`PreTrainedTokenizerBase.__call__`]. Useful for tab-completion in
an IDE.
"""
ONLY_FIRST = "only_first"
ONLY_SECOND = "only_second"
LONGEST_FIRST = "longest_first"
DO_NOT_TRUNCATE = "do_not_tru... | 70 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
class CharSpan(NamedTuple):
"""
Character span in the original string.
Args:
start (`int`): Index of the first character in the original string.
end (`int`): Index of the character following the last character in the original string.
"""
start: int
end: int | 71 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
class TokenSpan(NamedTuple):
"""
Token span in an encoded string (list of tokens).
Args:
start (`int`): Index of the first token in the span.
end (`int`): Index of the token following the last token in the span.
"""
start: int
end: int | 72 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
class BatchEncoding(UserDict):
"""
Holds the output of the [`~tokenization_utils_base.PreTrainedTokenizerBase.__call__`],
[`~tokenization_utils_base.PreTrainedTokenizerBase.encode_plus`] and
[`~tokenization_utils_base.PreTrainedTokenizerBase.batch_encode_plus`] methods (tokens, attention_masks, etc).
... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Args:
data (`dict`, *optional*):
Dictionary of lists/arrays/tensors returned by the `__call__`/`encode_plus`/`batch_encode_plus` methods
('input_ids', 'attention_mask', etc.).
encoding (`tokenizers.Encoding` or `Sequence[tokenizers.Encoding]`, *optional*):
If the toke... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
parameter has an effect if the parameter `tensor_type` is set, *otherwise has no effect*.
n_sequences (`Optional[int]`, *optional*):
You can give a tensor_type here to convert the lists of integers in PyTorch/TensorFlow/Numpy Tensors at
initialization.
""" | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
def __init__(
self,
data: Optional[Dict[str, Any]] = None,
encoding: Optional[Union[EncodingFast, Sequence[EncodingFast]]] = None,
tensor_type: Union[None, str, TensorType] = None,
prepend_batch_axis: bool = False,
n_sequences: Optional[int] = None,
):
super()... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
@property
def n_sequences(self) -> Optional[int]:
"""
`Optional[int]`: The number of sequences used to generate each sample from the batch encoded in this
[`BatchEncoding`]. Currently can be one of `None` (unknown), `1` (a single sentence) or `2` (a pair of
sentences)
"""
... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
If the key is a slice, returns the value of the dict associated to `key` ('input_ids', 'attention_mask', etc.)
with the constraint of slice.
"""
if isinstance(item, str):
return self.data[item]
elif self._encodings is not None:
return self._encodings[item]
... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
if "encodings" in state:
self._encodings = state["encodings"]
def keys(self):
return self.data.keys()
def values(self):
return self.data.values()
def items(self):
return self.data.items()
# After this point:
# Extended properties and methods only available for... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Args:
batch_index (`int`, *optional*, defaults to 0): The index to access in the batch.
Returns:
`List[str]`: The list of tokens at that index.
"""
if not self._encodings:
raise ValueError(
"tokens() is not available when using non-fast tokeni... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Args:
batch_index (`int`, *optional*, defaults to 0): The index to access in the batch.
Returns:
`List[Optional[int]]`: A list indicating the sequence id corresponding to each token. Special tokens added
by the tokenizer are mapped to `None` and other tokens are mapped to th... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Returns:
`List[Optional[int]]`: A list indicating the word corresponding to each token. Special tokens added by the
tokenizer are mapped to `None` and other tokens are mapped to the index of their corresponding word
(several tokens will be mapped to the same word index if they are pa... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
def word_ids(self, batch_index: int = 0) -> List[Optional[int]]:
"""
Return a list mapping the tokens to their actual word in the initial sentence for a fast tokenizer.
Args:
batch_index (`int`, *optional*, defaults to 0): The index to access in the batch.
Returns:
... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
def token_to_sequence(self, batch_or_token_index: int, token_index: Optional[int] = None) -> int:
"""
Get the index of the sequence represented by the given token. In the general use case, this method returns `0`
for a single sequence or the first sequence of a pair, and `1` for the second seque... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Args:
batch_or_token_index (`int`):
Index of the sequence in the batch. If the batch only comprises one sequence, this can be the index of
the token in the sequence.
token_index (`int`, *optional*):
If a batch index is provided in *batch_or_token_i... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
if not self._encodings:
raise ValueError("token_to_sequence() is not available when using Python based tokenizers")
if token_index is not None:
batch_index = batch_or_token_index
else:
batch_index = 0
token_index = batch_or_token_index
if batch_ind... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
This method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e.,
words are defined by the user). In this case it allows to easily associate encoded tokens with provided
tokenized words.
Args:
batch_or_token_index (`int`):
Ind... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
if not self._encodings:
raise ValueError("token_to_word() is not available when using Python based tokenizers")
if token_index is not None:
batch_index = batch_or_token_index
else:
batch_index = 0
token_index = batch_or_token_index
if batch_index <... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
- `self.word_to_tokens(word_index, sequence_index: int = 0)` if batch size is 1
- `self.word_to_tokens(batch_index, word_index, sequence_index: int = 0)` if batch size is greater or equal to
1
This method is particularly suited when the input sequences are provided as pre-tokenized sequences ... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Args:
batch_or_word_index (`int`):
Index of the sequence in the batch. If the batch only comprises one sequence, this can be the index of
the word in the sequence.
word_index (`int`, *optional*):
If a batch index is provided in *batch_or_token_inde... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Returns:
([`~tokenization_utils_base.TokenSpan`], *optional*): Span of tokens in the encoded sequence. Returns
`None` if no tokens correspond to the word. This can happen especially when the token is a special token
that has been used to format the tokenization. For example when we a... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
if not self._encodings:
raise ValueError("word_to_tokens() is not available when using Python based tokenizers")
if word_index is not None:
batch_index = batch_or_word_index
else:
batch_index = 0
word_index = batch_or_word_index
if batch_index < 0:... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
- **start** -- Index of the first character in the original string associated to the token.
- **end** -- Index of the character following the last character in the original string associated to the
token.
Can be called as:
- `self.token_to_chars(token_index)` if batch size is 1
... | 73 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.