text stringlengths 1 1.02k | class_index int64 0 10.8k | source stringlengths 85 188 |
|---|---|---|
if padding_side == "right":
if return_attention_mask:
encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference
if "token_type_ids" in encoded_inputs:
encoded_inputs["token_type_ids"] = (
encoded... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs[
"token_type_ids"
]
if "special_tokens_mask" in encoded_inputs:
encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tok... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
return encoded_inputs
def convert_tokens_to_string(self, tokens: List[str]) -> str:
"""
Converts a sequence of tokens in a single string. The most simple way to do it is `" ".join(tokens)` but we
often want to remove sub-word tokenization artifacts at the same time.
Args:
... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Args:
sequences (`Union[List[int], List[List[int]], np.ndarray, torch.Tensor, tf.Tensor]`):
List of tokenized input ids. Can be obtained using the `__call__` method.
skip_special_tokens (`bool`, *optional*, defaults to `False`):
Whether or not to remove special to... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Returns:
`List[str]`: The list of decoded sentences.
"""
return [
self.decode(
seq,
skip_special_tokens=skip_special_tokens,
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
**kwargs,
)
... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Args:
token_ids (`Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]`):
List of tokenized input ids. Can be obtained using the `__call__` method.
skip_special_tokens (`bool`, *optional*, defaults to `False`):
Whether or not to remove special tokens in the ... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
return self._decode(
token_ids=token_ids,
skip_special_tokens=skip_special_tokens,
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
**kwargs,
)
def _decode(
self,
token_ids: Union[int, List[int]],
skip_special_tokens: bool = ... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Args:
token_ids_0 (`List[int]`):
List of ids of the first sequence.
token_ids_1 (`List[int]`, *optional*):
List of ids of the second sequence.
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
Whether or not the toke... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
special_tokens_mask = [1 if token in all_special_ids else 0 for token in token_ids_0]
return special_tokens_mask
@staticmethod
def clean_up_tokenization(out_string: str) -> str:
"""
Clean up a list of simple English tokenization artifacts like spaces before punctuations and abbreviated... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
def _eventual_warn_about_too_long_sequence(self, ids: List[int], max_length: Optional[int], verbose: bool):
"""
Depending on the input and internal state we might trigger a warning about a sequence that is too long for its
corresponding model
Args:
ids (`List[str]`): The ids... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
"""
if max_length is None and len(ids) > self.model_max_length and verbose:
if not self.deprecation_warnings.get("sequence-length-is-longer-than-the-specified-maximum", False):
logger.warning(
"Token indices sequence length is longer than the specified maximum seq... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
@contextmanager
def as_target_tokenizer(self):
"""
Temporarily sets the tokenizer for encoding the targets. Useful for tokenizer associated to
sequence-to-sequence models that need a slightly different processing for the labels.
"""
warnings.warn(
"`as_target_toke... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
@classmethod
def register_for_auto_class(cls, auto_class="AutoTokenizer"):
"""
Register this class with a given auto class. This should only be used for custom tokenizers as the ones in the
library are already mapped with `AutoTokenizer`.
<Tip warning={true}>
This API is ex... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
def prepare_seq2seq_batch(
self,
src_texts: List[str],
tgt_texts: Optional[List[str]] = None,
max_length: Optional[int] = None,
max_target_length: Optional[int] = None,
padding: str = "longest",
return_tensors: str = None,
truncation: bool = True,
... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Arguments:
src_texts (`List[str]`):
List of documents to summarize or source language texts.
tgt_texts (`list`, *optional*):
List of summaries or target language texts.
max_length (`int`, *optional*):
Controls the maximum length for enc... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
Activates and controls padding. Accepts the following values: | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
sequence if provided).
- `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
acceptable input length for the model if that ... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
- `'tf'`: Return TensorFlow `tf.constant` objects.
- `'pt'`: Return PyTorch `torch.Tensor` objects.
- `'np'`: Return Numpy `np.ndarray` objects.
truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `True`):
Acti... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
- `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or
to the maximum acceptable input length for the model if that argument is not provided. This will
truncate token by token, removing a token from the longest sequence in the pair if ... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
- `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
greater than the model maximum admissible input size).
**kwargs:
... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
Return:
[`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
- **input_ids** -- List of token ids to be fed to the encoder.
- **attention_mask** -- List of indices specifying which tokens should be attended to by the model.
- **labels** -- List of token ids ... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
model_inputs = tokenizer(src_texts, ...)
labels = tokenizer(text_target=tgt_texts, ...)
model_inputs["labels"] = labels["input_ids"] | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
See the documentation of your specific tokenizer for more details on the specific arguments to the tokenizer of choice.
For a more complete example, see the implementation of `prepare_seq2seq_batch`.
"""
warnings.warn(formatted_warning, FutureWarning)
# mBART-specific kwargs that should be ignored by ot... | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
add_special_tokens=True,
return_tensors=return_tensors,
padding=padding,
max_length=max_target_length,
truncation=truncation,
**kwargs,
)
model_inputs["labels"] = labels["input_ids"]
return model_inputs | 75 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/tokenization_utils_base.py |
class CaptureStd:
"""
Context manager to capture:
- stdout: replay it, clean it up and make it available via `obj.out`
- stderr: replay it and make it available via `obj.err`
Args:
out (`bool`, *optional*, defaults to `True`): Whether to capture stdout or not.
err (`bool`, ... | 76 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
with CaptureStderr() as cs:
print("Warning: ", file=sys.stderr)
assert "Warning" in cs.err
# to capture both streams with auto-replay
with CaptureStd() as cs:
print("Secret message")
print("Warning: ", file=sys.stderr)
assert "message" in cs.out
assert "Warning" in cs.err
... | 76 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
if out:
self.out_buf = StringIO()
self.out = "error: CaptureStd context is unfinished yet, called too early"
else:
self.out_buf = None
self.out = "not capturing stdout"
if err:
self.err_buf = StringIO()
self.err = "error: CaptureSt... | 76 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
if self.err_buf:
sys.stderr = self.err_old
captured = self.err_buf.getvalue()
if self.replay:
sys.stderr.write(captured)
self.err = captured
def __repr__(self):
msg = ""
if self.out_buf:
msg += f"stdout: {self.out}\n"
... | 76 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
class CaptureStdout(CaptureStd):
"""Same as CaptureStd but captures only stdout"""
def __init__(self, replay=True):
super().__init__(err=False, replay=replay) | 77 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
class CaptureStderr(CaptureStd):
"""Same as CaptureStd but captures only stderr"""
def __init__(self, replay=True):
super().__init__(out=False, replay=replay) | 78 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
class CaptureLogger:
"""
Context manager to capture `logging` streams
Args:
logger: 'logging` logger object
Returns:
The captured output is available via `self.out`
Example:
```python
>>> from transformers import logging
>>> from transformers.testing_utils import Capt... | 79 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
def __repr__(self):
return f"captured: {self.out}\n" | 79 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
class TemporaryHubRepo:
"""Create a temporary Hub repository and return its `RepoUrl` object. This is similar to
`tempfile.TemporaryDirectory` and can be used as a context manager. For example:
with TemporaryHubRepo(token=self._token) as temp_repo:
...
Upon exiting the context, the rep... | 80 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
def __exit__(self, exc, value, tb):
delete_repo(repo_id=self.repo_url.repo_id, token=self.token, missing_ok=True) | 80 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
class TestCasePlus(unittest.TestCase):
"""
This class extends *unittest.TestCase* with additional features.
Feature 1: A set of fully resolved important file and dir path accessors.
In tests often we need to know where things are relative to the current test file, and it's not trivial since the
te... | 81 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
- stringified paths---same as above but these return paths as strings, rather than `pathlib` objects:
- `test_file_path_str`
- `test_file_dir_str`
- `tests_dir_str`
- `examples_dir_str`
- `repo_root_dir_str`
- `src_dir_str`
Feature 2: Flexible auto-removable temporary dir... | 81 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
This is useful for debug when you want to monitor a specific directory and want to make sure the previous tests
didn't leave any data in there.
3. You can override the first two options by directly overriding the `before` and `after` args, leading to the
following behavior:
`before=True`: the temp... | 81 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
Note 2: Each test can register multiple temporary dirs and they all will get auto-removed, unless requested
otherwise.
Feature 3: Get a copy of the `os.environ` object that sets up `PYTHONPATH` specific to the current test suite. This
is useful for invoking external programs from the test suite - e.g. dist... | 81 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
# figure out the resolved paths for repo_root, tests, examples, etc.
self._test_file_path = inspect.getfile(self.__class__)
path = Path(self._test_file_path).resolve()
self._test_file_dir = path.parents[0]
for up in [1, 2, 3]:
tmp_dir = path.parents[up]
if (tmp_di... | 81 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
@property
def test_file_dir_str(self):
return str(self._test_file_dir)
@property
def tests_dir(self):
return self._tests_dir
@property
def tests_dir_str(self):
return str(self._tests_dir)
@property
def examples_dir(self):
return self._examples_dir
@pro... | 81 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
It always inserts `./src` first, then `./tests` or `./examples` depending on the test suite type and finally
the preset `PYTHONPATH` if any (all full resolved paths).
"""
env = os.environ.copy()
paths = [self.src_dir_str]
if "/examples" in self.test_file_dir_str:
pat... | 81 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
- `tmp_dir` will be created
- sets `before=True` if `before` is `None`
- sets `after=False` if `after` is `None`
before (`bool`, *optional*):
If `True` and the `tmp_dir` already exists, make sure to empty it right away if `False` and the
... | 81 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
Returns:
tmp_dir(`string`): either the same value as passed via *tmp_dir* or the path to the auto-selected tmp dir
"""
if tmp_dir is not None:
# defining the most likely desired behavior for when a custom path is provided.
# this most likely indicates the debug mode w... | 81 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
# ensure the dir is empty to start with
if before is True and path.exists():
shutil.rmtree(tmp_dir, ignore_errors=True)
path.mkdir(parents=True, exist_ok=True)
else:
# defining the most likely desired behavior for when a unique tmp path is auto generated
... | 81 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
def python_one_liner_max_rss(self, one_liner_str):
"""
Runs the passed python one liner (just the code) and returns how much max cpu memory was used to run the
program.
Args:
one_liner_str (`string`):
a python one liner code that gets passed to `python -c`
... | 81 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
cmd = shlex.split(f"/usr/bin/time -f %M python -c '{one_liner_str}'")
with CaptureStd() as cs:
execute_subprocess_async(cmd, env=self.get_env())
# returned data is in KB so convert to bytes
max_rss = int(cs.err.split("\n")[-2].replace("stderr: ", "")) * 1024
return max_rss
... | 81 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
class _RunOutput:
def __init__(self, returncode, stdout, stderr):
self.returncode = returncode
self.stdout = stdout
self.stderr = stderr | 82 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
class SubprocessCallException(Exception):
pass | 83 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
class RequestCounter:
"""
Helper class that will count all requests made online.
Might not be robust if urllib3 changes its logging format but should be good enough for us.
Usage:
```py
with RequestCounter() as counter:
_ = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random... | 84 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
self.patcher = patch.object(
urllib3.connectionpool.log, "debug", side_effect=patched_with_thread_info(urllib3.connectionpool.log.debug)
)
self.mock = self.patcher.start()
return self
def __exit__(self, *args, **kwargs) -> None:
assert len(self.mock.call_args_list) == le... | 84 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
class HfDocTestParser(doctest.DocTestParser):
"""
Overwrites the DocTestParser from doctest to properly parse the codeblocks that are formatted with black. This
means that there are no extra lines at the end of our snippets. The `# doctest: +IGNORE_RESULT` marker is also
added anywhere a `load_dataset` ... | 85 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
# This regular expression is used to find doctest examples in a
# string. It defines three groups: `source` is the source code
# (including leading indentation and prompts); `indent` is the
# indentation of the first (PS1) line of the source code; and
# `want` is the expected output (including leading ... | 85 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
# !!!!!!!!!!! HF Specific !!!!!!!!!!!
(?:\n|$) # Match a new line or end of string
)*)
''', re.MULTILINE | re.VERBOSE
)
# fmt: on | 85 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
# !!!!!!!!!!! HF Specific !!!!!!!!!!!
skip_cuda_tests: bool = bool(os.environ.get("SKIP_CUDA_DOCTEST", False))
# !!!!!!!!!!! HF Specific !!!!!!!!!!!
def parse(self, string, name="<string>"):
"""
Overwrites the `parse` method to incorporate a skip for CUDA tests, and remove logs and dataset ... | 85 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
class HfDoctestModule(Module):
"""
Overwrites the `DoctestModule` of the pytest package to make sure the HFDocTestParser is used when discovering
tests.
"""
def collect(self) -> Iterable[DoctestItem]:
class MockAwareDocTestFinder(doctest.DocTestFinder):
"""A hackish doctest find... | 86 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
if hasattr(obj, "__wrapped__"):
# Get the main obj in case of it being wrapped
obj = inspect.unwrap(obj)
# Type ignored because this is a private function.
return super()._find_lineno( # type:ignore[misc]
obj,
... | 86 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
if self.path.name == "conftest.py":
module = self.config.pluginmanager._importconftest(
self.path,
self.config.getoption("importmode"),
rootpath=self.config.rootpath,
)
else:
try:
module = import_path(
... | 86 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
# !!!!!!!!!!! HF Specific !!!!!!!!!!!
finder = MockAwareDocTestFinder(parser=HfDocTestParser())
# !!!!!!!!!!! HF Specific !!!!!!!!!!!
optionflags = get_optionflags(self)
runner = _get_runner(
verbose=False,
optionflags=optionflags,
checker=_get_checker... | 86 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
class MockAwareDocTestFinder(doctest.DocTestFinder):
"""A hackish doctest finder that overrides stdlib internals to fix a stdlib bug.
https://github.com/pytest-dev/pytest/issues/3456 https://bugs.python.org/issue25532
"""
def _find_lineno(self, obj, source_lines):
... | 87 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
# Type ignored because this is a private function.
return super()._find_lineno( # type:ignore[misc]
obj,
source_lines,
)
def _find(self, tests, obj, name, module, source_lines, globs, seen) -> None:
if _is_mocked(obj):... | 87 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/testing_utils.py |
class PytorchGELUTanh(nn.Module):
"""
A fast C implementation of the tanh approximation of the GeLU activation function. See
https://arxiv.org/abs/1606.08415.
This implementation is equivalent to NewGELU and FastGELU but much faster. However, it is not an exact numerical
match due to rounding error... | 88 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/activations.py |
class NewGELUActivation(nn.Module):
"""
Implementation of the GELU activation function currently in Google BERT repo (identical to OpenAI GPT). Also see
the Gaussian Error Linear Units paper: https://arxiv.org/abs/1606.08415
"""
def forward(self, input: Tensor) -> Tensor:
return 0.5 * input... | 89 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/activations.py |
class GELUActivation(nn.Module):
"""
Original Implementation of the GELU activation function in Google BERT repo when initially created. For
information: OpenAI GPT's GELU is slightly different (and gives slightly different results): 0.5 * x * (1 +
torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * tor... | 90 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/activations.py |
class FastGELUActivation(nn.Module):
"""
Applies GELU approximation that is slower than QuickGELU but more accurate. See: https://github.com/hendrycks/GELUs
"""
def forward(self, input: Tensor) -> Tensor:
return 0.5 * input * (1.0 + torch.tanh(input * 0.7978845608 * (1.0 + 0.044715 * input * in... | 91 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/activations.py |
class QuickGELUActivation(nn.Module):
"""
Applies GELU approximation that is fast but somewhat inaccurate. See: https://github.com/hendrycks/GELUs
"""
def forward(self, input: Tensor) -> Tensor:
return input * torch.sigmoid(1.702 * input) | 92 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/activations.py |
class ClippedGELUActivation(nn.Module):
"""
Clip the range of possible GeLU outputs between [min, max]. This is especially useful for quantization purpose, as
it allows mapping negatives values in the GeLU spectrum. For more information on this trick, please refer to
https://arxiv.org/abs/2004.09602.
... | 93 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/activations.py |
class AccurateGELUActivation(nn.Module):
"""
Applies GELU approximation that is faster than default and more accurate than QuickGELU. See:
https://github.com/hendrycks/GELUs
Implemented along with MEGA (Moving Average Equipped Gated Attention)
"""
def __init__(self):
super().__init__()... | 94 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/activations.py |
class MishActivation(nn.Module):
"""
See Mish: A Self-Regularized Non-Monotonic Activation Function (Misra., https://arxiv.org/abs/1908.08681). Also
visit the official repository for the paper: https://github.com/digantamisra98/Mish
"""
def __init__(self):
super().__init__()
if vers... | 95 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/activations.py |
class LinearActivation(nn.Module):
"""
Applies the linear activation function, i.e. forwarding input directly to output.
"""
def forward(self, input: Tensor) -> Tensor:
return input | 96 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/activations.py |
class LaplaceActivation(nn.Module):
"""
Applies elementwise activation based on Laplace function, introduced in MEGA as an attention activation. See
https://arxiv.org/abs/2209.10655
Inspired by squared relu, but with bounded range and gradient for better stability
"""
def forward(self, input, ... | 97 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/activations.py |
class ReLUSquaredActivation(nn.Module):
"""
Applies the relu^2 activation introduced in https://arxiv.org/abs/2109.08668v2
"""
def forward(self, input):
relu_applied = nn.functional.relu(input)
squared = torch.square(relu_applied)
return squared | 98 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/activations.py |
class ClassInstantier(OrderedDict):
def __getitem__(self, key):
content = super().__getitem__(key)
cls, kwargs = content if isinstance(content, tuple) else (content, {})
return cls(**kwargs) | 99 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/activations.py |
class EvalPrediction:
"""
Evaluation output (always contains labels), to be used to compute metrics.
Parameters:
predictions (`np.ndarray`): Predictions of the model.
label_ids (`np.ndarray`): Targets to be matched.
inputs (`np.ndarray`, *optional*): Input data passed to the model.
... | 100 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
def __init__(
self,
predictions: Union[np.ndarray, Tuple[np.ndarray]],
label_ids: Union[np.ndarray, Tuple[np.ndarray]],
inputs: Optional[Union[np.ndarray, Tuple[np.ndarray]]] = None,
losses: Optional[Union[np.ndarray, Tuple[np.ndarray]]] = None,
):
self.predictions = ... | 100 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
class EvalLoopOutput(NamedTuple):
predictions: Union[np.ndarray, Tuple[np.ndarray]]
label_ids: Optional[Union[np.ndarray, Tuple[np.ndarray]]]
metrics: Optional[Dict[str, float]]
num_samples: Optional[int] | 101 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
class PredictionOutput(NamedTuple):
predictions: Union[np.ndarray, Tuple[np.ndarray]]
label_ids: Optional[Union[np.ndarray, Tuple[np.ndarray]]]
metrics: Optional[Dict[str, float]] | 102 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
class TrainOutput(NamedTuple):
global_step: int
training_loss: float
metrics: Dict[str, float] | 103 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
class IntervalStrategy(ExplicitEnum):
NO = "no"
STEPS = "steps"
EPOCH = "epoch" | 104 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
class SaveStrategy(ExplicitEnum):
NO = "no"
STEPS = "steps"
EPOCH = "epoch"
BEST = "best" | 105 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
class EvaluationStrategy(ExplicitEnum):
NO = "no"
STEPS = "steps"
EPOCH = "epoch" | 106 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
class HubStrategy(ExplicitEnum):
END = "end"
EVERY_SAVE = "every_save"
CHECKPOINT = "checkpoint"
ALL_CHECKPOINTS = "all_checkpoints" | 107 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
class BestRun(NamedTuple):
"""
The best run found by a hyperparameter search (see [`~Trainer.hyperparameter_search`]).
Parameters:
run_id (`str`):
The id of the best run (if models were saved, the corresponding checkpoint will be in the folder ending
with run-{run_id}).
... | 108 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
class HPSearchBackend(ExplicitEnum):
OPTUNA = "optuna"
RAY = "ray"
SIGOPT = "sigopt"
WANDB = "wandb" | 109 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
class SchedulerType(ExplicitEnum):
"""
Scheduler names for the parameter `lr_scheduler_type` in [`TrainingArguments`].
By default, it uses "linear". Internally, this retrieves `get_linear_schedule_with_warmup` scheduler from [`Trainer`].
Scheduler types:
- "linear" = get_linear_schedule_with_warm... | 110 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
LINEAR = "linear"
COSINE = "cosine"
COSINE_WITH_RESTARTS = "cosine_with_restarts"
POLYNOMIAL = "polynomial"
CONSTANT = "constant"
CONSTANT_WITH_WARMUP = "constant_with_warmup"
INVERSE_SQRT = "inverse_sqrt"
REDUCE_ON_PLATEAU = "reduce_lr_on_plateau"
COSINE_WITH_MIN_LR = "cosine_with_min_l... | 110 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
class TrainerMemoryTracker:
"""
A helper class that tracks cpu and gpu memory.
This class will silently skip unless `psutil` is available. Install with `pip install psutil`.
When a stage completes, it can pass metrics dict to update with the memory metrics gathered during this stage.
Example :
... | 111 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
def __init__(self, skip_memory_metrics=False):
self.skip_memory_metrics = skip_memory_metrics
if not is_psutil_available():
# soft dependency on psutil
self.skip_memory_metrics = True
if self.skip_memory_metrics:
return
import psutil # noqa
... | 111 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
self.cur_stage = None
self.cpu = {}
self.init_reported = False
def derive_stage(self):
"""derives the stage/caller name automatically"""
caller = inspect.currentframe().f_back.f_back.f_code.co_name
if caller in self.stages:
return self.stages[caller]
else... | 111 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
def start(self):
"""start tracking for the caller's stage"""
if self.skip_memory_metrics:
return
stage = self.derive_stage()
# deal with nested calls of eval during train - simply ignore those
if self.cur_stage is not None and self.cur_stage != stage:
ret... | 111 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
if self.torch is not None:
if torch.cuda.is_available():
self.torch.cuda.reset_peak_memory_stats()
self.torch.cuda.empty_cache()
elif is_torch_mlu_available():
self.torch.mlu.reset_peak_memory_stats()
self.torch.mlu.empty_cache()
... | 111 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
# gpu
if self.torch is not None:
if torch.cuda.is_available():
self.gpu_mem_used_at_start = self.torch.cuda.memory_allocated()
elif is_torch_mlu_available():
self.gpu_mem_used_at_start = self.torch.mlu.memory_allocated()
elif is_torch_musa_avai... | 111 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
self.peak_monitoring = True
peak_monitor_thread = threading.Thread(target=self.peak_monitor_func)
peak_monitor_thread.daemon = True
peak_monitor_thread.start()
def stop(self, stage):
"""stop tracking for the passed stage"""
# deal with nested calls of eval during train - si... | 111 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
if self.torch is not None:
if torch.cuda.is_available():
self.torch.cuda.empty_cache()
elif is_torch_mlu_available():
self.torch.mlu.empty_cache()
elif is_torch_musa_available():
self.torch.musa.empty_cache()
elif is_torch_x... | 111 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
# gpu
if self.torch is not None:
if torch.cuda.is_available():
self.gpu_mem_used_now = self.torch.cuda.memory_allocated()
self.gpu_mem_used_peak = self.torch.cuda.max_memory_allocated()
elif is_torch_mlu_available():
self.gpu_mem_used_now =... | 111 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
self.gpu_mem_used_peak = self.torch.npu.max_memory_allocated()
elif is_torch_mps_available():
self.gpu_mem_used_now = self.torch.mps.current_allocated_memory()
# self.torch.mps.max_memory_allocated() does not exist yet
self.gpu_mem_used_peak = None | 111 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
else:
raise ValueError("No available GPU device found!")
self.gpu[self.cur_stage] = {
"begin": self.gpu_mem_used_at_start,
"end": self.gpu_mem_used_now,
"alloc": (self.gpu_mem_used_now - self.gpu_mem_used_at_start),
}
i... | 111 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
def update_metrics(self, stage, metrics):
"""updates the metrics"""
if self.skip_memory_metrics:
return
# deal with nested calls of eval during train - simply ignore those
if self.cur_stage is not None and self.cur_stage != stage:
return
# since we don't... | 111 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
for stage in stages:
for t in ["alloc", "peaked"]:
if stage in self.cpu and t in self.cpu[stage]:
metrics[f"{stage}_mem_cpu_{t}_delta"] = self.cpu[stage][t]
if self.torch is not None and stage in self.gpu and t in self.gpu[stage]:
metri... | 111 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
# since memory can be allocated before init, and it might be difficult to track overall
# memory usage, in particular for GPU, let's report memory usage at the point init was called
if stages[0] == "init":
metrics["before_init_mem_cpu"] = self.cpu["init"]["begin"]
if self.torch i... | 111 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
def stop_and_update_metrics(self, metrics=None):
"""combine stop and metrics update in one call for simpler code"""
if self.skip_memory_metrics:
return
stage = self.derive_stage()
self.stop(stage)
# init doesn't have metrics to update so we just save that data for l... | 111 | /Users/nielsrogge/Documents/python_projecten/transformers/src/transformers/trainer_utils.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.