code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def _insert_module_as_submodule(self, mod: nn.Module) -> str:
"""
Helper method which tries to insert a module that was not declared as submodule.
"""
# If one of the module attributes is a Proxy, it means that its instantiation is input-dependent.
# It is not possible to insert ... |
Helper method which tries to insert a module that was not declared as submodule.
| _insert_module_as_submodule | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/fx.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/fx.py | Apache-2.0 |
def path_of_module(self, mod: nn.Module) -> str:
"""
Helper method to find the qualified name of `mod` in the Module hierarchy of `root`. For example, if `root` has
a submodule named `foo`, which has a submodule named `bar`, passing `bar` into this function will return the
string "foo.ba... |
Helper method to find the qualified name of `mod` in the Module hierarchy of `root`. For example, if `root` has
a submodule named `foo`, which has a submodule named `bar`, passing `bar` into this function will return the
string "foo.bar".
Args:
mod (str): The `Module` to re... | path_of_module | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/fx.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/fx.py | Apache-2.0 |
def symbolic_trace(
model: PreTrainedModel,
input_names: Optional[List[str]] = None,
disable_check: bool = False,
) -> GraphModule:
"""
Performs symbolic tracing on the model.
Args:
model ([`PretrainedModel`]):
The model to trace.
input_names (`List[str]`, *optional... |
Performs symbolic tracing on the model.
Args:
model ([`PretrainedModel`]):
The model to trace.
input_names (`List[str]`, *optional*):
The names of the inputs of the traced model. If unset, model.dummy_inputs.keys() are used instead.
disable_check (`bool`, *optio... | symbolic_trace | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/fx.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/fx.py | Apache-2.0 |
def is_tensor(x):
"""
Tests if `x` is a `torch.Tensor`, `tf.Tensor`, `jaxlib.xla_extension.DeviceArray` or `np.ndarray`.
"""
if is_torch_fx_proxy(x):
return True
if is_torch_available():
import torch
if isinstance(x, torch.Tensor):
return True
if is_tf_availa... |
Tests if `x` is a `torch.Tensor`, `tf.Tensor`, `jaxlib.xla_extension.DeviceArray` or `np.ndarray`.
| is_tensor | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/generic.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/generic.py | Apache-2.0 |
def to_py_obj(obj):
"""
Convert a TensorFlow tensor, PyTorch tensor, Numpy array or python list to a python list.
"""
if isinstance(obj, (dict, UserDict)):
return {k: to_py_obj(v) for k, v in obj.items()}
elif isinstance(obj, (list, tuple)):
return [to_py_obj(o) for o in obj]
eli... |
Convert a TensorFlow tensor, PyTorch tensor, Numpy array or python list to a python list.
| to_py_obj | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/generic.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/generic.py | Apache-2.0 |
def to_numpy(obj):
"""
Convert a TensorFlow tensor, PyTorch tensor, Numpy array or python list to a Numpy array.
"""
if isinstance(obj, (dict, UserDict)):
return {k: to_numpy(v) for k, v in obj.items()}
elif isinstance(obj, (list, tuple)):
return np.array(obj)
elif is_tf_tensor(o... |
Convert a TensorFlow tensor, PyTorch tensor, Numpy array or python list to a Numpy array.
| to_numpy | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/generic.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/generic.py | Apache-2.0 |
def find_labels(model_class):
"""
Find the labels used by a given model.
Args:
model_class (`type`): The class of the model.
"""
model_name = model_class.__name__
if model_name.startswith("TF"):
signature = inspect.signature(model_class.call)
elif model_name.startswith("Flax... |
Find the labels used by a given model.
Args:
model_class (`type`): The class of the model.
| find_labels | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/generic.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/generic.py | Apache-2.0 |
def flatten_dict(d: MutableMapping, parent_key: str = "", delimiter: str = "."):
"""Flatten a nested dict into a single level dict."""
def _flatten_dict(d, parent_key="", delimiter="."):
for k, v in d.items():
key = str(parent_key) + delimiter + str(k) if parent_key else k
if v ... | Flatten a nested dict into a single level dict. | flatten_dict | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/generic.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/generic.py | Apache-2.0 |
def transpose(array, axes=None):
"""
Framework-agnostic version of `numpy.transpose` that will work on torch/TensorFlow/Jax tensors as well as NumPy
arrays.
"""
if is_numpy_array(array):
return np.transpose(array, axes=axes)
elif is_torch_tensor(array):
return array.T if axes is ... |
Framework-agnostic version of `numpy.transpose` that will work on torch/TensorFlow/Jax tensors as well as NumPy
arrays.
| transpose | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/generic.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/generic.py | Apache-2.0 |
def reshape(array, newshape):
"""
Framework-agnostic version of `numpy.reshape` that will work on torch/TensorFlow/Jax tensors as well as NumPy
arrays.
"""
if is_numpy_array(array):
return np.reshape(array, newshape)
elif is_torch_tensor(array):
return array.reshape(*newshape)
... |
Framework-agnostic version of `numpy.reshape` that will work on torch/TensorFlow/Jax tensors as well as NumPy
arrays.
| reshape | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/generic.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/generic.py | Apache-2.0 |
def squeeze(array, axis=None):
"""
Framework-agnostic version of `numpy.squeeze` that will work on torch/TensorFlow/Jax tensors as well as NumPy
arrays.
"""
if is_numpy_array(array):
return np.squeeze(array, axis=axis)
elif is_torch_tensor(array):
return array.squeeze() if axis i... |
Framework-agnostic version of `numpy.squeeze` that will work on torch/TensorFlow/Jax tensors as well as NumPy
arrays.
| squeeze | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/generic.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/generic.py | Apache-2.0 |
def expand_dims(array, axis):
"""
Framework-agnostic version of `numpy.expand_dims` that will work on torch/TensorFlow/Jax tensors as well as NumPy
arrays.
"""
if is_numpy_array(array):
return np.expand_dims(array, axis)
elif is_torch_tensor(array):
return array.unsqueeze(dim=axi... |
Framework-agnostic version of `numpy.expand_dims` that will work on torch/TensorFlow/Jax tensors as well as NumPy
arrays.
| expand_dims | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/generic.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/generic.py | Apache-2.0 |
def tensor_size(array):
"""
Framework-agnostic version of `numpy.size` that will work on torch/TensorFlow/Jax tensors as well as NumPy arrays.
"""
if is_numpy_array(array):
return np.size(array)
elif is_torch_tensor(array):
return array.numel()
elif is_tf_tensor(array):
r... |
Framework-agnostic version of `numpy.size` that will work on torch/TensorFlow/Jax tensors as well as NumPy arrays.
| tensor_size | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/generic.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/generic.py | Apache-2.0 |
def get_cached_models(cache_dir: Union[str, Path] = None) -> List[Tuple]:
"""
Returns a list of tuples representing model binaries that are cached locally. Each tuple has shape `(model_url,
etag, size_MB)`. Filenames in `cache_dir` are use to get the metadata for each model, only urls ending with *.bin*
... |
Returns a list of tuples representing model binaries that are cached locally. Each tuple has shape `(model_url,
etag, size_MB)`. Filenames in `cache_dir` are use to get the metadata for each model, only urls ending with *.bin*
are added.
Args:
cache_dir (`Union[str, Path]`, *optional*):
... | get_cached_models | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/hub.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/hub.py | Apache-2.0 |
def http_user_agent(user_agent: Union[Dict, str, None] = None) -> str:
"""
Formats a user-agent string with basic info about a request.
"""
ua = f"transformers/{__version__}; python/{sys.version.split()[0]}; session_id/{SESSION_ID}"
if is_torch_available():
ua += f"; torch/{_torch_version}"
... |
Formats a user-agent string with basic info about a request.
| http_user_agent | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/hub.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/hub.py | Apache-2.0 |
def download_url(url, proxies=None):
"""
Downloads a given url in a temporary file. This function is not safe to use in multiple processes. Its only use is
for deprecated behavior allowing to download config/models with a single url instead of using the Hub.
Args:
url (`str`): The url of the fi... |
Downloads a given url in a temporary file. This function is not safe to use in multiple processes. Its only use is
for deprecated behavior allowing to download config/models with a single url instead of using the Hub.
Args:
url (`str`): The url of the file to download.
proxies (`Dict[str, ... | download_url | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/hub.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/hub.py | Apache-2.0 |
def has_file(
path_or_repo: Union[str, os.PathLike],
filename: str,
revision: Optional[str] = None,
proxies: Optional[Dict[str, str]] = None,
use_auth_token: Optional[Union[bool, str]] = None,
):
"""
Checks if a repo contains a given file wihtout downloading it. Works for remote repos and lo... |
Checks if a repo contains a given file wihtout downloading it. Works for remote repos and local folders.
<Tip warning={false}>
This function will raise an error if the repository `path_or_repo` is not valid or if `revision` does not exist for
this repo, but will return False for regular connection er... | has_file | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/hub.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/hub.py | Apache-2.0 |
def _create_repo(
self,
repo_id: str,
private: Optional[bool] = None,
use_auth_token: Optional[Union[bool, str]] = None,
repo_url: Optional[str] = None,
organization: Optional[str] = None,
):
"""
Create the repo if needed, cleans up repo_id with deprec... |
Create the repo if needed, cleans up repo_id with deprecated kwards `repo_url` and `organization`, retrives the
token.
| _create_repo | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/hub.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/hub.py | Apache-2.0 |
def _upload_modified_files(
self,
working_dir: Union[str, os.PathLike],
repo_id: str,
files_timestamps: Dict[str, float],
commit_message: Optional[str] = None,
token: Optional[str] = None,
create_pr: bool = False,
):
"""
Uploads all modified fi... |
Uploads all modified files in `working_dir` to `repo_id`, based on `files_timestamps`.
| _upload_modified_files | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/hub.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/hub.py | Apache-2.0 |
def send_example_telemetry(example_name, *example_args, framework="pytorch"):
"""
Sends telemetry that helps tracking the examples use.
Args:
example_name (`str`): The name of the example.
*example_args (dataclasses or `argparse.ArgumentParser`): The arguments to the script. This function w... |
Sends telemetry that helps tracking the examples use.
Args:
example_name (`str`): The name of the example.
*example_args (dataclasses or `argparse.ArgumentParser`): The arguments to the script. This function will only
try to extract the model and dataset name from those. Nothing el... | send_example_telemetry | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/hub.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/hub.py | Apache-2.0 |
def convert_file_size_to_int(size: Union[int, str]):
"""
Converts a size expressed as a string with digits an unit (like `"5MB"`) to an integer (in bytes).
Args:
size (`int` or `str`): The size to convert. Will be directly returned if an `int`.
Example:
```py
>>> convert_file_size_to_i... |
Converts a size expressed as a string with digits an unit (like `"5MB"`) to an integer (in bytes).
Args:
size (`int` or `str`): The size to convert. Will be directly returned if an `int`.
Example:
```py
>>> convert_file_size_to_int("1MiB")
1048576
```
| convert_file_size_to_int | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/hub.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/hub.py | Apache-2.0 |
def get_checkpoint_shard_files(
pretrained_model_name_or_path,
index_filename,
cache_dir=None,
force_download=False,
proxies=None,
resume_download=False,
local_files_only=False,
use_auth_token=None,
user_agent=None,
revision=None,
subfolder="",
_commit_hash=None,
):
"... |
For a given model:
- download and cache all the shards of a sharded checkpoint if `pretrained_model_name_or_path` is a model ID on the
Hub
- returns the list of paths to all the shards, as well as some metadata.
For the description of each arg, see [`PreTrainedModel.from_pretrained`]. `index_fi... | get_checkpoint_shard_files | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/hub.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/hub.py | Apache-2.0 |
def get_all_cached_files(cache_dir=None):
"""
Returns a list for all files cached with appropriate metadata.
"""
if cache_dir is None:
cache_dir = TRANSFORMERS_CACHE
else:
cache_dir = str(cache_dir)
if not os.path.isdir(cache_dir):
return []
cached_files = []
for... |
Returns a list for all files cached with appropriate metadata.
| get_all_cached_files | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/hub.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/hub.py | Apache-2.0 |
def extract_info_from_url(url):
"""
Extract repo_name, revision and filename from an url.
"""
search = re.search(r"^https://huggingface\.co/(.*)/resolve/([^/]*)/(.*)$", url)
if search is None:
return None
repo, revision, filename = search.groups()
cache_repo = "--".join(["models"] + ... |
Extract repo_name, revision and filename from an url.
| extract_info_from_url | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/hub.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/hub.py | Apache-2.0 |
def clean_files_for(file):
"""
Remove, if they exist, file, file.json and file.lock
"""
for f in [file, f"{file}.json", f"{file}.lock"]:
if os.path.isfile(f):
os.remove(f) |
Remove, if they exist, file, file.json and file.lock
| clean_files_for | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/hub.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/hub.py | Apache-2.0 |
def move_to_new_cache(file, repo, filename, revision, etag, commit_hash):
"""
Move file to repo following the new huggingface hub cache organization.
"""
os.makedirs(repo, exist_ok=True)
# refs
os.makedirs(os.path.join(repo, "refs"), exist_ok=True)
if revision != commit_hash:
ref_pa... |
Move file to repo following the new huggingface hub cache organization.
| move_to_new_cache | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/hub.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/hub.py | Apache-2.0 |
def is_torch_tpu_available(check_device=True):
"Checks if `torch_xla` is installed and potentially if a TPU is in the environment"
if not _torch_available:
return False
if importlib.util.find_spec("torch_xla") is not None:
if check_device:
# We need to check if `xla_device` can b... | Checks if `torch_xla` is installed and potentially if a TPU is in the environment | is_torch_tpu_available | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/import_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/import_utils.py | Apache-2.0 |
def _get_default_logging_level():
"""
If TRANSFORMERS_VERBOSITY env var is set to one of the valid choices return that as the new default level. If it is
not - fall back to `_default_log_level`
"""
env_level_str = os.getenv("TRANSFORMERS_VERBOSITY", None)
if env_level_str:
if env_level_s... |
If TRANSFORMERS_VERBOSITY env var is set to one of the valid choices return that as the new default level. If it is
not - fall back to `_default_log_level`
| _get_default_logging_level | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/logging.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/logging.py | Apache-2.0 |
def get_logger(name: Optional[str] = None) -> logging.Logger:
"""
Return a logger with the specified name.
This function is not supposed to be directly accessed unless you are writing a custom transformers module.
"""
if name is None:
name = _get_library_name()
_configure_library_root... |
Return a logger with the specified name.
This function is not supposed to be directly accessed unless you are writing a custom transformers module.
| get_logger | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/logging.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/logging.py | Apache-2.0 |
def disable_default_handler() -> None:
"""Disable the default handler of the HuggingFace Transformers's root logger."""
_configure_library_root_logger()
assert _default_handler is not None
_get_library_root_logger().removeHandler(_default_handler) | Disable the default handler of the HuggingFace Transformers's root logger. | disable_default_handler | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/logging.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/logging.py | Apache-2.0 |
def enable_default_handler() -> None:
"""Enable the default handler of the HuggingFace Transformers's root logger."""
_configure_library_root_logger()
assert _default_handler is not None
_get_library_root_logger().addHandler(_default_handler) | Enable the default handler of the HuggingFace Transformers's root logger. | enable_default_handler | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/logging.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/logging.py | Apache-2.0 |
def add_handler(handler: logging.Handler) -> None:
"""adds a handler to the HuggingFace Transformers's root logger."""
_configure_library_root_logger()
assert handler is not None
_get_library_root_logger().addHandler(handler) | adds a handler to the HuggingFace Transformers's root logger. | add_handler | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/logging.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/logging.py | Apache-2.0 |
def remove_handler(handler: logging.Handler) -> None:
"""removes given handler from the HuggingFace Transformers's root logger."""
_configure_library_root_logger()
assert handler is not None and handler not in _get_library_root_logger().handlers
_get_library_root_logger().removeHandler(handler) | removes given handler from the HuggingFace Transformers's root logger. | remove_handler | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/logging.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/logging.py | Apache-2.0 |
def enable_propagation() -> None:
"""
Enable propagation of the library log outputs. Please disable the HuggingFace Transformers's default handler to
prevent double logging if the root logger has been configured.
"""
_configure_library_root_logger()
_get_library_root_logger().propagate = True |
Enable propagation of the library log outputs. Please disable the HuggingFace Transformers's default handler to
prevent double logging if the root logger has been configured.
| enable_propagation | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/logging.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/logging.py | Apache-2.0 |
def enable_explicit_format() -> None:
"""
Enable explicit formatting for every HuggingFace Transformers's logger. The explicit formatter is as follows:
```
[LEVELNAME|FILENAME|LINE NUMBER] TIME >> MESSAGE
```
All handlers currently bound to the root logger are affected by this method.
""... |
Enable explicit formatting for every HuggingFace Transformers's logger. The explicit formatter is as follows:
```
[LEVELNAME|FILENAME|LINE NUMBER] TIME >> MESSAGE
```
All handlers currently bound to the root logger are affected by this method.
| enable_explicit_format | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/logging.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/logging.py | Apache-2.0 |
def reset_format() -> None:
"""
Resets the formatting for HuggingFace Transformers's loggers.
All handlers currently bound to the root logger are affected by this method.
"""
handlers = _get_library_root_logger().handlers
for handler in handlers:
handler.setFormatter(None) |
Resets the formatting for HuggingFace Transformers's loggers.
All handlers currently bound to the root logger are affected by this method.
| reset_format | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/logging.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/logging.py | Apache-2.0 |
def warning_advice(self, *args, **kwargs):
"""
This method is identical to `logger.warning()`, but if env var TRANSFORMERS_NO_ADVISORY_WARNINGS=1 is set, this
warning will not be printed
"""
no_advisory_warnings = os.getenv("TRANSFORMERS_NO_ADVISORY_WARNINGS", False)
if no_advisory_warnings:
... |
This method is identical to `logger.warning()`, but if env var TRANSFORMERS_NO_ADVISORY_WARNINGS=1 is set, this
warning will not be printed
| warning_advice | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/logging.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/logging.py | Apache-2.0 |
def get_device_map(n_layers, devices):
"""Returns a dictionary of layers distributed evenly across all devices."""
layers = list(range(n_layers))
n_blocks = int(ceil(n_layers / len(devices)))
layers_list = list(layers[i : i + n_blocks] for i in range(0, n_layers, n_blocks))
return dict(zip(devices,... | Returns a dictionary of layers distributed evenly across all devices. | get_device_map | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/model_parallel_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/model_parallel_utils.py | Apache-2.0 |
def format_time(t):
"Format `t` (in seconds) to (h):mm:ss"
t = int(t)
h, m, s = t // 3600, (t // 60) % 60, t % 60
return f"{h}:{m:02d}:{s:02d}" if h != 0 else f"{m:02d}:{s:02d}" | Format `t` (in seconds) to (h):mm:ss | format_time | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/notebook.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/notebook.py | Apache-2.0 |
def text_to_html_table(items):
"Put the texts in `items` in an HTML table."
html_code = """<table border="1" class="dataframe">\n"""
html_code += """ <thead>\n <tr style="text-align: left;">\n"""
for i in items[0]:
html_code += f" <th>{i}</th>\n"
html_code += " </tr>\n </thead>\n ... | Put the texts in `items` in an HTML table. | text_to_html_table | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/notebook.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/notebook.py | Apache-2.0 |
def update(self, value: int, force_update: bool = False, comment: str = None):
"""
The main method to update the progress bar to `value`.
Args:
value (`int`):
The value to use. Must be between 0 and `total`.
force_update (`bool`, *optional*, defaults to `... |
The main method to update the progress bar to `value`.
Args:
value (`int`):
The value to use. Must be between 0 and `total`.
force_update (`bool`, *optional*, defaults to `False`):
Whether or not to force and update of the internal state and disp... | update | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/notebook.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/notebook.py | Apache-2.0 |
def write_line(self, values):
"""
Write the values in the inner table.
Args:
values (`Dict[str, float]`): The values to display.
"""
if self.inner_table is None:
self.inner_table = [list(values.keys()), list(values.values())]
else:
col... |
Write the values in the inner table.
Args:
values (`Dict[str, float]`): The values to display.
| write_line | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/notebook.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/notebook.py | Apache-2.0 |
def require_version(requirement: str, hint: Optional[str] = None) -> None:
"""
Perform a runtime check of the dependency versions, using the exact same syntax used by pip.
The installed module version comes from the *site-packages* dir via *importlib_metadata*.
Args:
requirement (`str`): pip s... |
Perform a runtime check of the dependency versions, using the exact same syntax used by pip.
The installed module version comes from the *site-packages* dir via *importlib_metadata*.
Args:
requirement (`str`): pip style definition, e.g., "tokenizers==0.9.4", "tqdm>=4.27", "numpy"
hint (`... | require_version | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/src/transformers/utils/versions.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/src/transformers/utils/versions.py | Apache-2.0 |
def init_cache(self, batch_size, max_length, encoder_outputs):
r"""
Args:
batch_size (`int`):
batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
max_length (`int`):
maximum possible length for auto-r... |
Args:
batch_size (`int`):
batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
max_length (`int`):
maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
... | init_cache | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_flax_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_flax_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def encode(
self,
input_ids: jnp.ndarray,
attention_mask: Optional[jnp.ndarray] = None,
position_ids: Optional[jnp.ndarray] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
t... |
Returns:
Example:
```python
>>> from transformers import {{cookiecutter.camelcase_modelname}}Tokenizer, Flax{{cookiecutter.camelcase_modelname}}ForConditionalGeneration
>>> model = Flax{{cookiecutter.camelcase_modelname}}ForConditionalGeneration.from_pretrained('{{cookiecutte... | encode | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_flax_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_flax_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def decode(
self,
decoder_input_ids,
encoder_outputs,
encoder_attention_mask: Optional[jnp.ndarray] = None,
decoder_attention_mask: Optional[jnp.ndarray] = None,
decoder_position_ids: Optional[jnp.ndarray] = None,
past_key_values: dict = None,
output_atten... |
Returns:
Example:
```python
>>> import jax.numpy as jnp
>>> from transformers import {{cookiecutter.camelcase_modelname}}Tokenizer, Flax{{cookiecutter.camelcase_modelname}}ForConditionalGeneration
>>> model = Flax{{cookiecutter.camelcase_modelname}}ForConditionalGener... | decode | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_flax_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_flax_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def decode(
self,
decoder_input_ids,
encoder_outputs,
encoder_attention_mask: Optional[jnp.ndarray] = None,
decoder_attention_mask: Optional[jnp.ndarray] = None,
decoder_position_ids: Optional[jnp.ndarray] = None,
past_key_values: dict = None,
output_atten... |
Returns:
Example:
```python
>>> import jax.numpy as jnp
>>> from transformers import {{cookiecutter.camelcase_modelname}}Tokenizer, Flax{{cookiecutter.camelcase_modelname}}ForConditionalGeneration
>>> model = Flax{{cookiecutter.camelcase_modelname}}ForConditionalGener... | decode | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_flax_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_flax_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def call(
self,
input_ids: Optional[TFModelInputType] = None,
attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
head_mask: Optional[Uni... |
encoder_hidden_states (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
the model is configured as a decoder.
encoder_attention_mask (`tf.Tens... | call | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_tf_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_tf_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def call(
self,
input_ids: Optional[TFModelInputType] = None,
attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
head_mask: Optional[Uni... |
labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored
(masked),... | call | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_tf_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_tf_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def call(
self,
input_ids: Optional[TFModelInputType] = None,
attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
head_mask: Optional[Uni... |
encoder_hidden_states (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
the model is configured as a decoder.
encoder_attention_mask (`tf.Tens... | call | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_tf_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_tf_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def call(
self,
input_ids: Optional[TFModelInputType] = None,
attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
head_mask: Optional[Uni... |
labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*):
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss),
If `config.n... | call | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_tf_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_tf_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def call(
self,
input_ids: Optional[TFModelInputType] = None,
attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
head_mask: Optional[Uni... |
labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*):
Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]` where `num_choices` is the size of the second dimension of the input tensors. (See
`input_ids` above)
... | call | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_tf_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_tf_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def call(
self,
input_ids: Optional[TFModelInputType] = None,
attention_mask: Optional[Union[np.ndarray, tf.Tensor]] = None,
token_type_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
position_ids: Optional[Union[np.ndarray, tf.Tensor]] = None,
head_mask: Optional[Uni... |
start_positions (`tf.Tensor` or `np.ndarray` of shape `(batch_size,)`, *optional*):
Labels for position (index) of the start of the labelled span for computing the token classification loss.
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the... | call | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_tf_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_tf_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def call(
self,
hidden_states,
attention_mask: Optional[tf.Tensor] = None,
encoder_hidden_states: Optional[tf.Tensor] = None,
encoder_attention_mask: Optional[tf.Tensor] = None,
layer_head_mask: Optional[tf.Tensor] = None,
cross_attn_layer_head_mask: Optional[tf.T... |
Args:
hidden_states (`tf.Tensor`): input to the layer of shape *(seq_len, batch, embed_dim)*
attention_mask (`tf.Tensor`): attention mask of size
*(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
encoder_hidden... | call | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_tf_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_tf_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def call(
self,
input_ids=None,
inputs_embeds=None,
attention_mask=None,
head_mask=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
training=False,
):
"""
Args:
input_ids (`tf.Tensor` of sha... |
Args:
input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
provide it.
Indices can be obtained using [`~{{cookiecutter.camelcase_modelname}... | call | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_tf_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_tf_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def call(
self,
input_ids=None,
inputs_embeds=None,
attention_mask=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
head_mask=None,
cross_attn_head_mask=None,
past_key_values=None,
use_cache=None,
output_attentions=Non... |
Args:
input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
provide it.
Indices can be obtained using [`~{{cookiecutter.camelcase_modelname}... | call | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_tf_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_tf_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def call(
self,
input_ids=None,
attention_mask=None,
decoder_input_ids=None,
decoder_attention_mask=None,
head_mask=None,
decoder_head_mask=None,
cross_attn_head_mask=None,
encoder_outputs: Optional[TFBaseModelOutput] = None,
past_key_value... |
Returns:
Examples:
```python
>>> from transformers import {{cookiecutter.camelcase_modelname}}Tokenizer, TF{{cookiecutter.camelcase_modelname}}ForConditionalGeneration
>>> import tensorflow as tf
>>> mname = '{{cookiecutter.checkpoint_identifier}}'
>>> tokenize... | call | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_tf_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_tf_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
past_key_values=None,
use_cache=None,
... |
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
if the model is configured as a decoder.
encoder_attention_mask (... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
labels=None,
output_attentions=None,
... |
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss.
Indices should be in `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring)
Tokens with indices set to `-100` are ignored (maske... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
inputs_embeds=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
head_mask=None,
cross_attn_... |
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
the model is configured as a decoder.
encoder_attention_mask (... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=None,
output_attentions=None,
output_hidden_states=None,
... |
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the sequence classification/regression loss.
Indices should be in `[0, ..., config.num_labels - 1]`.
If `config.num_labels == 1` a regression loss is computed (Mean-Square loss),
... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=None,
output_attentions=None,
output_hidden_states=None,
... |
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the multiple choice classification loss.
Indices should be in `[0, ..., num_choices-1]` where `num_choices` is the size of the second dimension
of the input tensors. (See `input_ids` above... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
r""... |
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the token classification loss.
Indices should be in `[0, ..., config.num_labels - 1]`.
| forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
start_positions=None,
end_positions=None,
output_attentions=None,
output_hidden_states=None,
... |
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for position (index) of the start of the labelled span for computing the token classification loss.
Positions are clamped to the length of the sequence (`sequence_length`).
Position outside of ... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: torch.Tensor,
layer_head_mask: torch.Tensor,
output_attentions: bool = False,
):
"""
Args:
hidden_states (`torch.FloatTensor`): input to the layer of shape *(seq_len, batch, embed_dim)... |
Args:
hidden_states (`torch.FloatTensor`): input to the layer of shape *(seq_len, batch, embed_dim)*
attention_mask (`torch.FloatTensor`): attention mask of size
*(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
encoder_hidden_states: Optional[torch.Tensor] = None,
encoder_attention_mask: Optional[torch.Tensor] = None,
layer_head_mask: Optional[torch.Tensor] = None,
cross_layer_... |
Args:
hidden_states (`torch.FloatTensor`): input to the layer of shape *(seq_len, batch, embed_dim)*
attention_mask (`torch.FloatTensor`): attention mask of size
*(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def forward(
self,
input_ids=None,
attention_mask=None,
head_mask=None,
inputs_embeds=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
r"""
Args:
input_ids (`torch.LongTensor` of shape `(batch_si... |
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
provide it.
Indices can be obtained using [`~{{cookiecutter.camelcase_mod... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def forward(
self,
input_ids=None,
attention_mask=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
head_mask=None,
cross_attn_head_mask=None,
past_key_values=None,
inputs_embeds=None,
use_cache=None,
output_attentions=... |
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
provide it.
Indices can be obtained using [`~{{cookiecutter.camelcase_mod... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def forward(
self,
input_ids=None,
attention_mask=None,
decoder_input_ids=None,
decoder_attention_mask=None,
head_mask=None,
decoder_head_mask=None,
cross_attn_head_mask=None,
encoder_outputs=None,
past_key_values=None,
inputs_embed... |
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
(masked)... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def forward(
self,
input_ids=None,
attention_mask=None,
decoder_input_ids=None,
decoder_attention_mask=None,
encoder_outputs=None,
inputs_embeds=None,
decoder_inputs_embeds=None,
labels=None,
use_cache=None,
output_attentions=None,
... |
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
| forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def forward(
self,
input_ids=None,
attention_mask=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
head_mask=None,
cross_attn_head_mask=None,
past_key_values=None,
inputs_embeds=None,
labels=None,
use_cache=None,
... |
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
provide it.
Indices can be obtained using [`~{{cookiecutter.camelcase_mod... | forward | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/modeling_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def _assert_tensors_equal(a, b, atol=1e-12, prefix=""):
"""If tensors not close, or a and b arent both tensors, raise a nice Assertion error."""
if a is None and b is None:
return True
try:
if _assert_tensors_equal(a, b, atol=atol):
return True
raise
except Exception:... | If tensors not close, or a and b arent both tensors, raise a nice Assertion error. | _assert_tensors_equal | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/test_modeling_flax_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/test_modeling_flax_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def create_token_type_ids_from_sequences(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
"""
Create a mask from the two sequences passed to be used in a sequence-pair classification task.
{{cookiecutter.modelname}} does not make use of token... |
Create a mask from the two sequences passed to be used in a sequence-pair classification task.
{{cookiecutter.modelname}} does not make use of token type ids, therefore a list of zeros is returned.
Args:
token_ids_0 (`List[int]`):
List of IDs.
token_ids_... | create_token_type_ids_from_sequences | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/tokenization_fast_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/tokenization_fast_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def save_vocabulary(self, save_directory):
"""
Save the vocabulary and special tokens file to a directory.
Args:
save_directory (`str`):
The directory in which to save the vocabulary.
Returns:
`Tuple(str)`: Paths to the files saved.
""" |
Save the vocabulary and special tokens file to a directory.
Args:
save_directory (`str`):
The directory in which to save the vocabulary.
Returns:
`Tuple(str)`: Paths to the files saved.
| save_vocabulary | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/tokenization_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/tokenization_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def build_inputs_with_special_tokens(
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
"""
Build model inputs from a sequence or a pair of sequence for sequence classification tasks
by concatenating and adding special tokens.
A {{cooki... |
Build model inputs from a sequence or a pair of sequence for sequence classification tasks
by concatenating and adding special tokens.
A {{cookiecutter.modelname}} sequence has the following format:
- single sequence: `<s> X </s>`
- pair of sequences: `<s> A </s></s> B </s>`
... | build_inputs_with_special_tokens | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/tokenization_{{cookiecutter.lowercase_modelname}}.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/templates/adding_a_new_model/cookiecutter-template-{{cookiecutter.modelname}}/tokenization_{{cookiecutter.lowercase_modelname}}.py | Apache-2.0 |
def prepare_image_inputs(feature_extract_tester, equal_resolution=False, numpify=False, torchify=False):
"""This function prepares a list of PIL images, or a list of numpy arrays if one specifies numpify=True,
or a list of PyTorch tensors if one specifies torchify=True.
One can specify whether the images a... | This function prepares a list of PIL images, or a list of numpy arrays if one specifies numpify=True,
or a list of PyTorch tensors if one specifies torchify=True.
One can specify whether the images are of the same resolution or not.
| prepare_image_inputs | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/tests/test_feature_extraction_common.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/tests/test_feature_extraction_common.py | Apache-2.0 |
def prepare_video(feature_extract_tester, width=10, height=10, numpify=False, torchify=False):
"""This function prepares a video as a list of PIL images/NumPy arrays/PyTorch tensors."""
video = []
for i in range(feature_extract_tester.num_frames):
video.append(np.random.randint(255, size=(feature_e... | This function prepares a video as a list of PIL images/NumPy arrays/PyTorch tensors. | prepare_video | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/tests/test_feature_extraction_common.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/tests/test_feature_extraction_common.py | Apache-2.0 |
def prepare_video_inputs(feature_extract_tester, equal_resolution=False, numpify=False, torchify=False):
"""This function prepares a batch of videos: a list of list of PIL images, or a list of list of numpy arrays if
one specifies numpify=True, or a list of list of PyTorch tensors if one specifies torchify=True... | This function prepares a batch of videos: a list of list of PIL images, or a list of list of numpy arrays if
one specifies numpify=True, or a list of list of PyTorch tensors if one specifies torchify=True.
One can specify whether the videos are of the same resolution or not.
| prepare_video_inputs | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/tests/test_feature_extraction_common.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/tests/test_feature_extraction_common.py | Apache-2.0 |
def _make_attention_mask_non_null(self, inputs_dict):
"""Make sure no sequence has all zeros as attention mask"""
for k in ["attention_mask", "encoder_attention_mask", "decoder_attention_mask"]:
if k in inputs_dict:
attention_mask = inputs_dict[k]
# Make sur... | Make sure no sequence has all zeros as attention mask | _make_attention_mask_non_null | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/tests/test_modeling_common.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/tests/test_modeling_common.py | Apache-2.0 |
def _postprocessing_to_ignore_test_cases(self, tf_outputs, pt_outputs, model_class):
"""For temporarily ignoring some failed test cases (issues to be fixed)"""
tf_keys = set([k for k, v in tf_outputs.items() if v is not None])
pt_keys = set([k for k, v in pt_outputs.items() if v is not None])
... | For temporarily ignoring some failed test cases (issues to be fixed) | _postprocessing_to_ignore_test_cases | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/tests/test_modeling_common.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/tests/test_modeling_common.py | Apache-2.0 |
def check_pt_tf_outputs(self, tf_outputs, pt_outputs, model_class, tol=1e-5, name="outputs", attributes=None):
"""Check the outputs from PyTorch and TensorFlow models are close enough. Checks are done in a recursive way.
Args:
model_class: The class of the model that is currently testing. F... | Check the outputs from PyTorch and TensorFlow models are close enough. Checks are done in a recursive way.
Args:
model_class: The class of the model that is currently testing. For example, `TFBertModel`,
TFBertForMaskedLM`, `TFBertForSequenceClassification`, etc. Mainly used for pro... | check_pt_tf_outputs | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/tests/test_modeling_common.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/tests/test_modeling_common.py | Apache-2.0 |
def check_pt_flax_outputs(self, fx_outputs, pt_outputs, model_class, tol=1e-5, name="outputs", attributes=None):
"""
Args:
model_class: The class of the model that is currently testing. For example, ..., etc.
Currently unused, but it could make debugging easier and faster.
... |
Args:
model_class: The class of the model that is currently testing. For example, ..., etc.
Currently unused, but it could make debugging easier and faster.
names: A string, or a list of strings. These specify what fx_outputs/pt_outputs represent in the model outputs.
... | check_pt_flax_outputs | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/tests/test_modeling_common.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/tests/test_modeling_common.py | Apache-2.0 |
def get_current_gpu_memory_use():
"""returns a list of cuda memory allocations per GPU in MBs"""
per_device_memory = []
for id in range(torch.cuda.device_count()):
with torch.cuda.device(id):
per_device_memory.append(torch.cuda.memory_allocated() ... | returns a list of cuda memory allocations per GPU in MBs | get_current_gpu_memory_use | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/tests/test_modeling_common.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/tests/test_modeling_common.py | Apache-2.0 |
def ids_tensor(shape, vocab_size, rng=None):
"""Creates a random int32 tensor of the shape within the vocab size."""
if rng is None:
rng = random.Random()
total_dims = 1
for dim in shape:
total_dims *= dim
values = []
for _ in range(total_dims):
values.append(rng.randin... | Creates a random int32 tensor of the shape within the vocab size. | ids_tensor | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/tests/test_modeling_flax_common.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/tests/test_modeling_flax_common.py | Apache-2.0 |
def test_xla_generate_fast(self):
"""
Basic quick test for generate-compatible classes that confirms that XLA-generated tokens are the same as their
non XLA counterparts.
Either the model supports XLA generation and passes the inner test, or it raises an appropriate exception
""... |
Basic quick test for generate-compatible classes that confirms that XLA-generated tokens are the same as their
non XLA counterparts.
Either the model supports XLA generation and passes the inner test, or it raises an appropriate exception
| test_xla_generate_fast | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/tests/test_modeling_tf_common.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/tests/test_modeling_tf_common.py | Apache-2.0 |
def test_xla_generate_slow(self):
"""
Slow and challenging version of `test_xla_generate_fast` -- this test asks for several long sequences using
beam search, with and without XLA. The two outputs should match, and a failure in this test indicates that the
model may need further analysis... |
Slow and challenging version of `test_xla_generate_fast` -- this test asks for several long sequences using
beam search, with and without XLA. The two outputs should match, and a failure in this test indicates that the
model may need further analysis if it is to be used for XLA generation.
... | test_xla_generate_slow | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/tests/test_modeling_tf_common.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/tests/test_modeling_tf_common.py | Apache-2.0 |
def tokenizer_integration_test_util(
self,
expected_encoding: Dict,
model_name: str,
revision: str = None,
sequences: List[str] = None,
decode_kwargs: Dict[str, Any] = None,
padding: bool = True,
):
"""
Util for integration test.
Text ... |
Util for integration test.
Text is tokenized and then reverted back to text. Both results are then checked.
Args:
expected_encoding:
The expected result of the tokenizer output.
model_name:
The model name of the tokenizer to load and use... | tokenizer_integration_test_util | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/tests/test_tokenization_common.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/tests/test_tokenization_common.py | Apache-2.0 |
def test_pickle_tokenizer(self):
"""Google pickle __getstate__ __setstate__ if you are struggling with this."""
tokenizers = self.get_tokenizers()
for tokenizer in tokenizers:
with self.subTest(f"{tokenizer.__class__.__name__}"):
self.assertIsNotNone(tokenizer)
... | Google pickle __getstate__ __setstate__ if you are struggling with this. | test_pickle_tokenizer | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/tests/test_tokenization_common.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/tests/test_tokenization_common.py | Apache-2.0 |
def test_padding_to_max_length(self):
"""We keep this test for backward compatibility but it should be remove when `pad_to_max_length` is deprecated."""
tokenizers = self.get_tokenizers(do_lower_case=False)
for tokenizer in tokenizers:
with self.subTest(f"{tokenizer.__class__.__name_... | We keep this test for backward compatibility but it should be remove when `pad_to_max_length` is deprecated. | test_padding_to_max_length | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/tests/test_tokenization_common.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/tests/test_tokenization_common.py | Apache-2.0 |
def check_subword_sampling(
self,
tokenizer: PreTrainedTokenizer,
text: str = None,
) -> None:
"""
Check if the tokenizer generates different results when subword regularization is enabled.
Subword regularization augments training data with subword sampling.
... |
Check if the tokenizer generates different results when subword regularization is enabled.
Subword regularization augments training data with subword sampling.
This has a random component.
Args:
tokenizer: The tokenizer to check.
text: The text to use for the c... | check_subword_sampling | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/tests/test_tokenization_common.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/tests/test_tokenization_common.py | Apache-2.0 |
def test_batch_encode_dynamic_overflowing(self):
"""
When calling batch_encode with multiple sequence it can returns different number of
overflowing encoding for each sequence:
[
Sequence 1: [Encoding 1, Encoding 2],
Sequence 2: [Encoding 1],
Sequence 3: [En... |
When calling batch_encode with multiple sequence it can returns different number of
overflowing encoding for each sequence:
[
Sequence 1: [Encoding 1, Encoding 2],
Sequence 2: [Encoding 1],
Sequence 3: [Encoding 1, Encoding 2, ... Encoding N]
]
This... | test_batch_encode_dynamic_overflowing | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/tests/test_tokenization_common.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/tests/test_tokenization_common.py | Apache-2.0 |
def get_master_port(real_launcher=False):
"""
When using a single gpu launcher emulation (i.e. not deepspeed or python -m torch.distributed)
the issue is that once the port is tied it can't be used anywhere else outside of this process,
since torch.dist doesn't free the port until the process exits. The... |
When using a single gpu launcher emulation (i.e. not deepspeed or python -m torch.distributed)
the issue is that once the port is tied it can't be used anywhere else outside of this process,
since torch.dist doesn't free the port until the process exits. Therefore for the sake of being
able to run both... | get_master_port | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/tests/deepspeed/test_deepspeed.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/tests/deepspeed/test_deepspeed.py | Apache-2.0 |
def require_deepspeed_aio(test_case):
"""
Decorator marking a test that requires deepspeed aio (nvme)
"""
if not is_deepspeed_available():
return unittest.skip("test requires deepspeed")(test_case)
import deepspeed
from deepspeed.ops.aio import AsyncIOBuilder
if not deepspeed.ops._... |
Decorator marking a test that requires deepspeed aio (nvme)
| require_deepspeed_aio | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/tests/deepspeed/test_deepspeed.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/tests/deepspeed/test_deepspeed.py | Apache-2.0 |
def test_generate_with_head_masking(self):
"""Test designed for encoder-decoder models to ensure the attention head masking is used."""
attention_names = ["encoder_attentions", "decoder_attentions", "cross_attentions"]
for model_class in self.all_generative_model_classes:
config, inp... | Test designed for encoder-decoder models to ensure the attention head masking is used. | test_generate_with_head_masking | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/tests/generation/test_generation_utils.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/tests/generation/test_generation_utils.py | Apache-2.0 |
def tearDown(self):
r"""
TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to
avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27
"""
del self.model_fp16
del s... |
TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to
avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27
| tearDown | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/tests/mixed_int8/test_mixed_int8.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/tests/mixed_int8/test_mixed_int8.py | Apache-2.0 |
def test_memory_footprint(self):
r"""
A simple test to check if the model conversion has been done correctly by checking on the
memory footprint of the converted model and the class type of the linear layers of the converted models
"""
from bitsandbytes.nn import Int8Params
... |
A simple test to check if the model conversion has been done correctly by checking on the
memory footprint of the converted model and the class type of the linear layers of the converted models
| test_memory_footprint | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/tests/mixed_int8/test_mixed_int8.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/tests/mixed_int8/test_mixed_int8.py | Apache-2.0 |
def test_generate_quality(self):
r"""
Test the generation quality of the quantized model and see that we are matching the expected output.
Given that we are operating on small numbers + the testing model is relatively small, we might not get
the same output across GPUs. So we'll generate... |
Test the generation quality of the quantized model and see that we are matching the expected output.
Given that we are operating on small numbers + the testing model is relatively small, we might not get
the same output across GPUs. So we'll generate few tokens (5-10) and check their output.
... | test_generate_quality | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/tests/mixed_int8/test_mixed_int8.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/tests/mixed_int8/test_mixed_int8.py | Apache-2.0 |
def test_correct_head_class(self):
r"""
A simple test to check if the last modules for some classes (AutoModelForCausalLM or SequenceClassification)
are kept in their native class.
"""
from bitsandbytes.nn import Int8Params
# last param of a base model should be a linear... |
A simple test to check if the last modules for some classes (AutoModelForCausalLM or SequenceClassification)
are kept in their native class.
| test_correct_head_class | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/tests/mixed_int8/test_mixed_int8.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/tests/mixed_int8/test_mixed_int8.py | Apache-2.0 |
def test_pipeline(self):
r"""
The aim of this test is to verify that the mixed int8 is compatible with `pipeline` from transformers. Since
we used pipline for inference speed benchmarking we want to make sure that this feature does not break anything
on pipline.
"""
# sel... |
The aim of this test is to verify that the mixed int8 is compatible with `pipeline` from transformers. Since
we used pipline for inference speed benchmarking we want to make sure that this feature does not break anything
on pipline.
| test_pipeline | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/tests/mixed_int8/test_mixed_int8.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/tests/mixed_int8/test_mixed_int8.py | Apache-2.0 |
def test_multi_gpu_loading(self):
r"""
This tests that the model has been loaded and can be used correctly on a multi-GPU setup.
Let's just try to load a model on 2 GPUs and see if it works. The model we test has ~2GB of total, 3GB should suffice
"""
memory_mapping = {0: "1GB", ... |
This tests that the model has been loaded and can be used correctly on a multi-GPU setup.
Let's just try to load a model on 2 GPUs and see if it works. The model we test has ~2GB of total, 3GB should suffice
| test_multi_gpu_loading | python | FMInference/FlexLLMGen | benchmark/third_party/transformers/tests/mixed_int8/test_mixed_int8.py | https://github.com/FMInference/FlexLLMGen/blob/master/benchmark/third_party/transformers/tests/mixed_int8/test_mixed_int8.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.