text stringlengths 1 1.02k | class_index int64 0 10.8k | source stringlengths 85 188 |
|---|---|---|
# TODO (joao): remove `=None` in non-optional arguments in v4.46. Remove from `OBJECTS_TO_IGNORE` as well.
def __init__(
self,
config: PretrainedConfig,
batch_size: int = None,
max_cache_len: int = None,
device: Union[torch.device, str] = "cpu",
dtype: torch.dtype = t... | 223 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
"sliding window attention, please check if there is a `sliding_window` field in the model "
"config and it's not set to None."
)
self.max_cache_len = max_cache_len
self.max_batch_size = batch_size or max_batch_size
# Some model define a custom `head_dim` != config.hid... | 223 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
self.dtype = dtype
self.num_key_value_heads = (
config.num_attention_heads if config.num_key_value_heads is None else config.num_key_value_heads
)
layer_switch = config.sliding_window_pattern if hasattr(config, "sliding_window_pattern") else 2 # 2 is for BC
self.is_sliding =... | 223 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
else:
layer_device = device
# Note: `mark_static_address` is used to tag the cache as an fixed data pointer, preventing cuda graph
# breaks when updating the cache.
cache_shape = global_cache_shape if not self.is_sliding[i] else sliding_cache_shape
new_lay... | 223 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
def _sliding_update(self, cache_position, layer_idx, key_states, value_states, k_out, v_out, max_cache_len):
if cache_position.shape[0] > max_cache_len:
k_out = key_states[:, :, -max_cache_len:, :]
v_out = value_states[:, :, -max_cache_len:, :]
# Assumption: caches are all ze... | 223 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
slicing = torch.ones(max_cache_len, dtype=torch.long, device=value_states.device).cumsum(0)
cache_position = cache_position.clamp(0, max_cache_len - 1)
to_shift = cache_position >= max_cache_len - 1
indices = (slicing + to_shift[-1].int() - 1) % max_cache_len
k_out = k_out[:, :, indices]... | 223 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
self.key_cache[layer_idx] = k_out
self.value_cache[layer_idx] = v_out
return k_out, v_out
def update(
self,
key_states: torch.Tensor,
value_states: torch.Tensor,
layer_idx: int,
cache_kwargs: Optional[Dict[str, Any]] = None,
) -> Tuple[torch.Tensor]:
... | 223 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
def get_seq_length(self, layer_idx: Optional[int] = 0):
# Occupied cache == any slot in the 3rd dim (sequence length) holds a non-zero value. To save on compute, let's
# limit the check to the first batch member and head dimension.
# TODO: deprecate this function in favor of `cache_position`
... | 223 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
@property
def batch_size(self):
logger.warning_once(
f"The 'batch_size' attribute of {self.__class__.__name__} is deprecated and will be removed in "
"v4.49. Use the more precisely named 'self.max_batch_size' attribute instead."
)
return self.max_batch_size | 223 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
class MambaCache:
"""
Cache for mamba model which does not have attention mechanism and key value states.
Arguments:
config (`PretrainedConfig):
The configuration file defining the shape-related attributes required to initialize the static cache.
batch_size (`int`):
... | 224 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
Attributes:
dtype: (`torch.dtype`):
The default `dtype` used to initializing the cache.
intermediate_size: (`int`):
Model's intermediate_size taken from config.
ssm_state_size: (`int`):
Model's state_size taken from config.
conv_kernel_size: (`int`):
... | 224 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
>>> inputs = tokenizer(text="My name is Mamba", return_tensors="pt")
>>> # Prepare a cache class and pass it to model's forward
>>> past_key_values = MambaCache(config=model.config, batch_size=1, device=model.device, dtype=model.dtype)
>>> outputs = model(**inputs, past_key_values=past_key_valu... | 224 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
# TODO (joao): remove `=None` in non-optional arguments in v4.46. Remove from `OBJECTS_TO_IGNORE` as well.
def __init__(
self,
config: PretrainedConfig,
batch_size: int = None,
dtype: torch.dtype = torch.float16,
device: Optional[Union[torch.device, str]] = None,
max_... | 224 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
self.conv_states: torch.Tensor = torch.zeros(
config.num_hidden_layers,
self.max_batch_size,
self.intermediate_size,
self.conv_kernel_size,
device=device,
dtype=dtype,
)
self.ssm_states: torch.Tensor = torch.zeros(
confi... | 224 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
conv_state = conv_state.roll(shifts=-1, dims=-1)
conv_state[:, :, cache_position] = new_conv_state.to(device=conv_state.device, dtype=conv_state.dtype)
self.conv_states[layer_idx].zero_()
self.conv_states[layer_idx] += conv_state
return self.conv_states[layer_idx]
def update_ssm_sta... | 224 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
class OffloadedStaticCache(StaticCache):
"""
Static cache class to be used with `torch.compile(model)` that offloads to the CPU or
another device. | 225 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
Args:
config (`PretrainedConfig):
The configuration file defining the shape-related attributes required to initialize
the static cache.
max_batch_size (`int`):
The maximum batch size with which the model will be used.
max_cache_len (`int`):
The max... | 225 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
Mapping between the layers and its device. This is required when you are manually initializing the cache and the model is splitted between differents gpus.
You can know which layers mapped to which device by checking the associated device_map: `model.hf_device_map`. | 225 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
Attributes:
key_cache (`List[torch.Tensor]`):
Off-loaded key cache tensors. First one will be on device, where-as the others are
off-loaded.
value_cache (`List[torch.Tensor]`):
Off-loaded value cache tensors. First one will be on device, where-as the others are
... | 225 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
>>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
>>> tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
>>> inputs = tokenizer(text="My name is GPT2", return_tensors="pt")
>>> # Prepare a cache class and pass it to model's forward
>>> # Leave em... | 225 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
def __init__(
self,
config: PretrainedConfig,
max_batch_size: int,
max_cache_len: Optional[int],
device: Union[str, torch.device],
dtype: Optional[torch.dtype] = None,
offload_device: Union[str, torch.device] = torch.device("cpu"),
layer_device_map: Option... | 225 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
num_key_value_heads = (
config.num_attention_heads
if getattr(config, "num_key_value_heads", None) is None
else config.num_key_value_heads
)
cache_shape = (max_batch_size, num_key_value_heads, self.max_cache_len, head_dim)
# Create offloaded CPU tensors.
... | 225 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
for i in range(2):
key_cache, value_cache = self._create_key_value_cache_tensors(cache_shape, self.device)
self._device_key_cache.append(key_cache)
self._device_value_cache.append(value_cache)
# For backwards compatibility.
# TODO(gante): Remove this.
self._... | 225 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
Parameters:
key_states (`torch.Tensor`):
The new key states to cache.
value_states (`torch.Tensor`):
The new value states to cache.
layer_idx (`int`):
The index of the layer to cache the states for.
cache_kwargs (`Dict[str, ... | 225 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
# Always there.
k_out = self.key_cache[0]
v_out = self.value_cache[0]
else:
# Wait for prefetch stream.
if self._prefetch_stream is not None:
torch.cuda.default_stream(self.device).wait_stream(self._prefetch_stream)
k_out = self._devic... | 225 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
# Copy the values to the offloaded device as well.
if layer_idx == 0:
self.key_cache[layer_idx].copy_(key_states.to(self.offload_device))
self.value_cache[layer_idx].copy_(value_states.to(self.offload_device))
else:
# Note: here we use `tensor.index_copy_(... | 225 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
# Copy the values to the offloaded device as well.
if layer_idx != 0:
cache_position = cache_position.to(self.offload_device)
key_states = key_states.to(self.offload_device)
value_states = value_states.to(self.offload_device)
try:
... | 225 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
"""Returns the sequence length of the cached states that were seen by the model."""
# TODO(gante): Remove this.
return self._seen_tokens
def get_max_cache_shape(self) -> Optional[int]:
"""Returns the maximum sequence le... | 225 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
def _create_key_value_cache_tensors(
self, shape: Tuple[int, ...], device: torch.device
) -> Tuple[torch.Tensor, torch.Tensor]:
"""Creates K/V cache tensors on a device. Pins memory for CPU tensors. Marks them as static
addresses for non-CPU tensors.
Args:
shape (`Tuple[... | 225 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
return key_cache, value_cache
def _prefetch_layer(self, layer_idx: int) -> None:
"""Prefetch a layer to the device. Needs to be called in order of layer indices."""
# Don't fetch layers that do not exist.
if layer_idx >= len(self.key_cache):
return
# Alternate between ... | 225 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/cache_utils.py |
class AttentionMaskConverter:
"""
A utility attention mask class that allows one to:
- Create a causal 4d mask
- Create a causal 4d mask with slided window
- Convert a 2d attention mask (batch_size, query_length) to a 4d attention mask (batch_size, 1, query_length,
key_value_le... | 226 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_attn_mask_utils.py |
>>> converter = AttentionMaskConverter(True)
>>> converter.to_4d(torch.tensor([[0, 0, 0, 1, 1]]), 5, key_value_length=5, dtype=torch.float32)
tensor([[[[-3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38],
[-3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38, -3.4028e+38],
[-... | 226 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_attn_mask_utils.py |
def __init__(self, is_causal: bool, sliding_window: Optional[int] = None):
self.is_causal = is_causal
self.sliding_window = sliding_window
if self.sliding_window is not None and self.sliding_window <= 0:
raise ValueError(
f"Make sure that when passing `sliding_window... | 226 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_attn_mask_utils.py |
# If shape is not cached, create a new causal mask and cache it
input_shape = (batch_size, query_length)
past_key_values_length = key_value_length - query_length
# create causal mask
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
causal_4d_mask = None
if input_sh... | 226 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_attn_mask_utils.py |
def to_4d(
self,
attention_mask_2d: torch.Tensor,
query_length: int,
dtype: torch.dtype,
key_value_length: Optional[int] = None,
) -> torch.Tensor:
"""
Converts 2D attention mask to 4D attention mask by expanding mask to (bsz, head_dim=1, query_length,
... | 226 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_attn_mask_utils.py |
past_key_values_length = key_value_length - query_length
causal_4d_mask = self._make_causal_mask(
input_shape,
dtype,
device=attention_mask_2d.device,
past_key_values_length=past_key_values_length,
sliding_window=self.sliding_wi... | 226 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_attn_mask_utils.py |
@staticmethod
def _make_causal_mask(
input_ids_shape: torch.Size,
dtype: torch.dtype,
device: torch.device,
past_key_values_length: int = 0,
sliding_window: Optional[int] = None,
):
"""
Make causal mask used for bi-directional self-attention.
"""
... | 226 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_attn_mask_utils.py |
context_mask = torch.tril(torch.ones_like(mask, dtype=torch.bool), diagonal=diagonal)
# Recent changes in PyTorch prevent mutations on tensors converted with aten::_to_copy
# See https://github.com/pytorch/pytorch/issues/127571
if is_torchdynamo_compiling():
mask = ma... | 226 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_attn_mask_utils.py |
return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
@staticmethod
def _unmask_unattended(
expanded_mask: torch.FloatTensor,
min_dtype: float,
):
# fmt: off
"""
Attend to all tokens in masked rows from the expanded attention mask, fo... | 226 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_attn_mask_utils.py |
For example, if `expanded_mask` is (e.g. here left-padding case)
```
[[[[0, 0, 0],
[0, 0, 0],
[0, 0, 1]]],
[[[1, 0, 0],
[1, 1, 0],
[1, 1, 1]]],
[[[0, 0, 0],
[0, 1, 0],
[0, 1, 1]]]]
```
then the modified `... | 226 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_attn_mask_utils.py |
@staticmethod
def _ignore_causal_mask_sdpa(
attention_mask: Optional[torch.Tensor],
inputs_embeds: torch.Tensor,
past_key_values_length: int,
sliding_window: Optional[int] = None,
is_training: bool = False,
) -> bool:
"""
Detects whether the optional user-... | 226 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_attn_mask_utils.py |
is_tracing = torch.jit.is_tracing() or isinstance(inputs_embeds, torch.fx.Proxy) or is_torchdynamo_compiling()
ignore_causal_mask = False | 226 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_attn_mask_utils.py |
if attention_mask is None:
# TODO: When tracing with TorchDynamo with fullgraph=True, the model is recompiled depending on the input
# shape, thus SDPA's `is_causal` argument is rightfully updated
# (see https://gist.github.com/fxmarty/1313f39037fc1c112508989628c57363). However, when... | 226 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_attn_mask_utils.py |
(is_training or not is_tracing)
and (query_length == 1 or key_value_length == query_length)
and (sliding_window is None or key_value_length < sliding_window)
):
ignore_causal_mask = True
elif sliding_window is None or key_value_length < sliding_window:... | 226 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_attn_mask_utils.py |
# Unfortunately, for query_length > 1 and key_value_length != query_length, we cannot generally ignore
# the attention mask, as SDPA causal mask generation may be wrong. We will set `is_causal=False` in
# SDPA and rely on Transformers attention_mask instead, hence not setting it to None ... | 226 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_attn_mask_utils.py |
class TransposeType(ExplicitEnum):
"""
Possible ...
"""
NO = "no"
SIMPLE = "simple"
CONV1D = "conv1d"
CONV2D = "conv2d" | 227 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_tf_pytorch_utils.py |
class PreTrainedTokenizerFast(PreTrainedTokenizerBase):
"""
Base class for all fast tokenizers (wrapping HuggingFace tokenizers library).
Inherits from [`~tokenization_utils_base.PreTrainedTokenizerBase`].
Handles all the shared methods for tokenization and special tokens, as well as methods for
d... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
def __init__(self, *args, **kwargs):
tokenizer_object = kwargs.pop("tokenizer_object", None)
slow_tokenizer = kwargs.pop("__slow_tokenizer", None)
gguf_file = kwargs.pop("gguf_file", None)
fast_tokenizer_file = kwargs.pop("tokenizer_file", None)
from_slow = kwargs.pop("from_slow"... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
if tokenizer_object is not None:
fast_tokenizer = copy.deepcopy(tokenizer_object)
elif fast_tokenizer_file is not None and not from_slow:
# We have a serialization from tokenizers which let us directly build the backend
fast_tokenizer = TokenizerFast.from_file(fast_tokenizer_... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
if len(additional_kwargs) > 0:
kwargs.update(additional_kwargs)
elif self.slow_tokenizer_class is not None and slow_tokenizer is not False:
# We need to create and convert a slow tokenizer to build the backend
slow_tokenizer = self.slow_tokenizer_class(*args, **kwargs)
... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
"(2) a slow tokenizer instance to convert or \n"
"(3) an equivalent slow tokenizer class to instantiate and convert. \n"
"You need to have sentencepiece or tiktoken installed to convert a slow tokenizer to a fast one."
) | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
self._tokenizer = fast_tokenizer
if slow_tokenizer is not None:
kwargs.update(slow_tokenizer.init_kwargs)
self._decode_use_source_tokenizer = False
_truncation = self._tokenizer.truncation
if _truncation is not None:
self._tokenizer.enable_truncation(**_trunca... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
_padding = self._tokenizer.padding
if _padding is not None:
self._tokenizer.enable_padding(**_padding)
kwargs.setdefault("pad_token", _padding["pad_token"])
kwargs.setdefault("pad_token_type_id", _padding["pad_type_id"])
kwargs.setdefault("padding_side", _padding[... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
added_tokens_decoder_hash = {hash(repr(token)) for token in self.added_tokens_decoder}
tokens_to_add = [
token
for index, token in sorted(added_tokens_decoder.items(), key=lambda x: x[0])
if hash(repr(token)) not in added_tokens_decoder_hash
]
encoder = list(s... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
if len(tokens_to_add) > 0:
tokens = []
special_tokens = self.all_special_tokens
for token in tokens_to_add:
is_special = (
(token.special or str(token) in special_tokens)
if isinstance(token, AddedToken)
else... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
try:
pre_tok_state = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())
if pre_tok_state.get("add_prefix_space", self.add_prefix_space) != self.add_prefix_space:
pre_tok_class = getattr(pre_tokenizers_fast, pre_tok_state.pop("type"))
pre_tok_state["ad... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
@property
def can_save_slow_tokenizer(self) -> bool:
"""
`bool`: Whether or not the slow tokenizer can be saved. Usually for sentencepiece based slow tokenizer, this
can only be `True` if the original `"sentencepiece.model"` was not deleted.
"""
return True
@property
... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
@property
def added_tokens_encoder(self) -> Dict[str, int]:
"""
Returns the sorted mapping from string to index. The added tokens encoder is cached for performance
optimisation in `self._added_tokens_encoder` for the slow tokenizers.
"""
return {k.content: v for v, k in sorte... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
Returns:
`Dict[str, int]`: The added tokens.
"""
return {k.content: v for v, k in sorted(self.added_tokens_decoder.items(), key=lambda item: item[0])}
def __len__(self) -> int:
"""
Size of the full vocabulary with the added tokens.
"""
return self._tokeni... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
def _convert_encoding(
self,
encoding: EncodingFast,
return_token_type_ids: Optional[bool] = None,
return_attention_mask: Optional[bool] = None,
return_overflowing_tokens: bool = False,
return_special_tokens_mask: bool = False,
return_offsets_mapping: bool = False... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
Output shape: (overflows, sequence length)
"""
if return_token_type_ids is None:
return_token_type_ids = "token_type_ids" in self.model_input_names
if return_attention_mask is None:
return_attention_mask = "attention_mask" in self.model_input_names
if return_over... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
if return_token_type_ids:
encoding_dict["token_type_ids"].append(e.type_ids)
if return_attention_mask:
encoding_dict["attention_mask"].append(e.attention_mask)
if return_special_tokens_mask:
encoding_dict["special_tokens_mask"].append(e.special_tok... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
Returns:
`int` or `List[int]`: The token id or list of token ids.
"""
if isinstance(tokens, str):
return self._convert_token_to_id_with_added_voc(tokens)
return [self._convert_token_to_id_with_added_voc(token) for token in tokens]
def _convert_token_to_id_with_added... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
def num_special_tokens_to_add(self, pair: bool = False) -> int:
"""
Returns the number of added tokens when encoding a sequence with special tokens.
<Tip>
This encodes a dummy input and checks the number of added tokens, and is therefore not efficient. Do not put
this inside yo... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
Args:
ids (`int` or `List[int]`):
The token id (or token ids) to convert to tokens.
skip_special_tokens (`bool`, *optional*, defaults to `False`):
Whether or not to remove special tokens in the decoding.
Returns:
`str` or `List[str]`: The deco... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
def set_truncation_and_padding(
self,
padding_strategy: PaddingStrategy,
truncation_strategy: TruncationStrategy,
max_length: int,
stride: int,
pad_to_multiple_of: Optional[int],
padding_side: Optional[bool],
):
"""
Define the truncation and th... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
Args:
padding_strategy ([`~utils.PaddingStrategy`]):
The kind of padding that will be applied to the input
truncation_strategy ([`~tokenization_utils_base.TruncationStrategy`]):
The kind of truncation that will be applied to the input
max_length (`int`... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
_truncation = self._tokenizer.truncation
_padding = self._tokenizer.padding
# Set truncation and padding on the backend tokenizer
if truncation_strategy == TruncationStrategy.DO_NOT_TRUNCATE:
if _truncation is not None:
self._tokenizer.no_truncation()
else:
... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
# _truncation might contain more keys that the target `transformers`
# supports. Use only the target keys to trigger `enable_truncation`.
# This should enable this code to works on various `tokenizers`
# targets.
if _truncation is None:
current = None
... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
if padding_strategy == PaddingStrategy.DO_NOT_PAD:
if _padding is not None:
self._tokenizer.no_padding()
else:
length = max_length if padding_strategy == PaddingStrategy.MAX_LENGTH else None
target = {
"length": length,
"directi... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
def _batch_encode_plus(
self,
batch_text_or_text_pairs: Union[
List[TextInput], List[TextInputPair], List[PreTokenizedInput], List[PreTokenizedInputPair]
],
add_special_tokens: bool = True,
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
trunca... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
) -> BatchEncoding:
if not isinstance(batch_text_or_text_pairs, (tuple, list)):
raise TypeError(
f"batch_text_or_text_pairs has to be a list or a tuple (got {type(batch_text_or_text_pairs)})"
) | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
# Set the truncation and padding strategy and restore the initial configuration
self.set_truncation_and_padding(
padding_strategy=padding_strategy,
truncation_strategy=truncation_strategy,
max_length=max_length,
stride=stride,
pad_to_multiple_of=pad_to... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
# Convert encoding to dict
# `Tokens` has type: Tuple[
# List[Dict[str, List[List[int]]]] or List[Dict[str, 2D-Tensor]],
# List[EncodingFast]
# ]
# with nested dimensions corresponding to batch, overflows, sequence le... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
# Convert the output to have dict[list] from list[dict] and remove the additional overflows dimension
# From (variable) shape (batch, overflows, sequence length) to ~ (batch * overflows, sequence length)
# (we say ~ because the number of overflow varies with the example in the batch)
#
#... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
# If returning overflowing tokens, we need to return a mapping
# from the batch idx to the original sample
if return_overflowing_tokens:
overflow_to_sample_mapping = []
for i, (toks, _) in enumerate(tokens_and_encodings):
overflow_to_sample_mapping += [i] * len(to... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
def _encode_plus(
self,
text: Union[TextInput, PreTokenizedInput],
text_pair: Optional[Union[TextInput, PreTokenizedInput]] = None,
add_special_tokens: bool = True,
padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
truncation_strategy: TruncationStrategy = T... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
batched_input = [(text, text_pair)] if text_pair else [text]
batched_output = self._batch_encode_plus(
batched_input,
is_split_into_words=is_split_into_words,
add_special_tokens=add_special_tokens,
padding_strategy=padding_strategy,
truncation_strategy... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
# Return tensor is None, then we can remove the leading batch axis
# Overflowing tokens are returned as a batch of output so we keep them in this case
if return_tensors is None and not return_overflowing_tokens:
batched_output = BatchEncoding(
{
key: (valu... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
def _decode(
self,
token_ids: Union[int, List[int]],
skip_special_tokens: bool = False,
clean_up_tokenization_spaces: bool = None,
**kwargs,
) -> str:
self._decode_use_source_tokenizer = kwargs.pop("use_source_tokenizer", False)
if isinstance(token_ids, int):... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
def _save_pretrained(
self,
save_directory: Union[str, os.PathLike],
file_names: Tuple[str],
legacy_format: Optional[bool] = None,
filename_prefix: Optional[str] = None,
) -> Tuple[str]:
"""
Save a tokenizer using the slow-tokenizer/legacy format: vocabulary +... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
save_slow = (
(legacy_format is None or legacy_format is True)
and self.slow_tokenizer_class is not None
and self.can_save_slow_tokenizer
)
save_fast = legacy_format is None or legacy_format is False
if save_slow:
added_tokens_file = os.path.join(... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
vocab_files = self.save_vocabulary(save_directory, filename_prefix=filename_prefix)
file_names = file_names + vocab_files + (added_tokens_file,)
if save_fast:
tokenizer_file = os.path.join(
save_directory, (filename_prefix + "-" if filename_prefix else "") + TOKENIZER_FI... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
Args:
text_iterator (generator of `List[str]`):
The training corpus. Should be a generator of batches of texts, for instance a list of lists of texts
if you have everything in memory.
vocab_size (`int`):
The size of the vocabulary you want for your... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
Additional keyword arguments passed along to the trainer from the 🤗 Tokenizers library. | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
Returns:
[`PreTrainedTokenizerFast`]: A new tokenizer of the same type as the original one, trained on
`text_iterator`.
"""
tokenizer_json = json.loads(self._tokenizer.to_str())
# Remove added tokens for now (uses IDs of tokens)
added_tokens = tokenizer_json.pop(... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
unk_token = None
# Remove vocab
if tokenizer_json["model"]["type"] == "BPE":
tokenizer_json["model"]["vocab"] = {}
tokenizer_json["model"]["merges"] = []
elif tokenizer_json["model"]["type"] == "Unigram":
if tokenizer_json["model"]["unk_id"] is not None:
... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
"only BPE, Unigram, WordLevel and WordPiece."
) | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
if (
special_tokens_map is not None
and "unk_token" in tokenizer_json["model"]
and tokenizer_json["model"]["unk_token"] in special_tokens_map
):
tokenizer_json["model"]["unk_token"] = special_tokens_map[tokenizer_json["model"]["unk_token"]]
tokenizer = To... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
if new_special_tokens is not None:
special_tokens.extend(new_special_tokens) | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
# Trainer needs to know the end of word / continuing subword thingies in BPE
if (
tokenizer_json["model"]["type"] == "BPE"
and "continuing_subword_prefix" not in kwargs
and tokenizer_json["model"]["continuing_subword_prefix"] is not None
):
kwargs["continu... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
or tokenizer_json["pre_tokenizer"]["type"] == "Sequence"
and "pretokenizers" in tokenizer_json["pre_tokenizer"]
and any(
pretokenizer["type"] == "ByteLevel"
for pretokenizer in tokenizer_json["pre_tokenizer"]["pretokenizers"]
)
... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
trainer_class = MODEL_TO_TRAINER_MAPPING[tokenizer_json["model"]["type"]]
trainer = trainer_class(vocab_size=vocab_size, special_tokens=special_tokens, **kwargs)
tokenizer.train_from_iterator(text_iterator, length=length, trainer=trainer) | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
if post_processor is not None:
trained_tokenizer_json = json.loads(tokenizer.to_str())
# Almost done, we just have to adjust the token IDs in the post processor
if "special_tokens" in post_processor:
for key in post_processor["special_tokens"]:
tok... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
post_processor["special_tokens"][key]["ids"] = [tokenizer.token_to_id(token) for token in tokens]
for special_token in ["cls", "sep"]:
if special_token in post_processor:
token, _ = post_processor[special_token]
if special_tokens_map is not None and t... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
kwargs = self.init_kwargs.copy()
# Map pad/cls/mask token at the Transformers level
special_tokens_list = SpecialTokensMixin.SPECIAL_TOKENS_ATTRIBUTES.copy()
special_tokens_list.remove("additional_special_tokens")
for token in special_tokens_list:
if getattr(self, token) is n... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
special_token_full = self._special_tokens_map.get(token, None)
if isinstance(special_token_full, AddedToken):
# Create an added token with the same parameters except the content
kwargs[token] = AddedToken(
special_token,
... | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
return self.__class__(tokenizer_object=tokenizer, **kwargs) | 228 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_fast.py |
class ModuleUtilsMixin:
"""
A few utilities for `torch.nn.Modules`, to be used as a mixin.
"""
@staticmethod
def _hook_rss_memory_pre_forward(module, *args, **kwargs):
try:
import psutil
except ImportError:
raise ImportError("You need to install psutil (pip i... | 229 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py |
process = psutil.Process(os.getpid())
mem = process.memory_info()
module.mem_rss_post_forward = mem.rss
mem_rss_diff = module.mem_rss_post_forward - module.mem_rss_pre_forward
module.mem_rss_diff = mem_rss_diff + (module.mem_rss_diff if hasattr(module, "mem_rss_diff") else 0)
ret... | 229 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/modeling_utils.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.