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 filter_indices_by_size(self, indices, max_positions=None):
"""
Filter each sub-dataset independently, then update the round robin to work
on the filtered sub-datasets.
"""
def _deep_until_language_pair(dataset):
if isinstance(dataset, LanguagePairDataset):
... |
Filter each sub-dataset independently, then update the round robin to work
on the filtered sub-datasets.
| filter_indices_by_size | python | OFA-Sys/OFA | fairseq/fairseq/data/round_robin_zip_datasets.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/round_robin_zip_datasets.py | Apache-2.0 |
def _build_slice_indices(
sizes, break_mode, document_sep_len, block_size
) -> Tuple[np.ndarray]:
"""Use token_block_utils_fast to build arrays for indexing into self.dataset"""
try:
from fairseq.data.token_block_utils_fast import (
_get_slice_indices_fast,
... | Use token_block_utils_fast to build arrays for indexing into self.dataset | _build_slice_indices | python | OFA-Sys/OFA | fairseq/fairseq/data/token_block_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/token_block_dataset.py | Apache-2.0 |
def convert_waveform(
waveform: Union[np.ndarray, torch.Tensor], sample_rate: int,
normalize_volume: bool = False, to_mono: bool = False,
to_sample_rate: Optional[int] = None
) -> Tuple[Union[np.ndarray, torch.Tensor], int]:
"""convert a waveform:
- to a target sample rate
- ... | convert a waveform:
- to a target sample rate
- from multi-channel to mono channel
- volume normalization
Args:
waveform (numpy.ndarray or torch.Tensor): 2D original waveform
(channels x length)
sample_rate (int): original sample rate
... | convert_waveform | python | OFA-Sys/OFA | fairseq/fairseq/data/audio/audio_utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/audio/audio_utils.py | Apache-2.0 |
def get_waveform(
path_or_fp: Union[str, BinaryIO], normalization: bool = True,
mono: bool = True, frames: int = -1, start: int = 0,
always_2d: bool = True, output_sample_rate: Optional[int] = None,
normalize_volume: bool = False
) -> Tuple[np.ndarray, int]:
"""Get the waveform and s... | Get the waveform and sample rate of a 16-bit WAV/FLAC/OGG Vorbis audio.
Args:
path_or_fp (str or BinaryIO): the path or file-like object
normalization (bool): normalize values to [-1, 1] (Default: True)
mono (bool): convert multi-channel audio to mono-channel one
frames (int): the n... | get_waveform | python | OFA-Sys/OFA | fairseq/fairseq/data/audio/audio_utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/audio/audio_utils.py | Apache-2.0 |
def _get_kaldi_fbank(
waveform: np.ndarray, sample_rate: int, n_bins=80
) -> Optional[np.ndarray]:
"""Get mel-filter bank features via PyKaldi."""
try:
from kaldi.feat.fbank import FbankOptions, Fbank
from kaldi.feat.mel import MelBanksOptions
from kaldi.feat.window import FrameExtra... | Get mel-filter bank features via PyKaldi. | _get_kaldi_fbank | python | OFA-Sys/OFA | fairseq/fairseq/data/audio/audio_utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/audio/audio_utils.py | Apache-2.0 |
def _get_torchaudio_fbank(
waveform: np.ndarray, sample_rate, n_bins=80
) -> Optional[np.ndarray]:
"""Get mel-filter bank features via TorchAudio."""
try:
import torchaudio.compliance.kaldi as ta_kaldi
waveform = torch.from_numpy(waveform)
features = ta_kaldi.fbank(
wave... | Get mel-filter bank features via TorchAudio. | _get_torchaudio_fbank | python | OFA-Sys/OFA | fairseq/fairseq/data/audio/audio_utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/audio/audio_utils.py | Apache-2.0 |
def get_fbank(path_or_fp: Union[str, BinaryIO], n_bins=80) -> np.ndarray:
"""Get mel-filter bank features via PyKaldi or TorchAudio. Prefer PyKaldi
(faster CPP implementation) to TorchAudio (Python implementation). Note that
Kaldi/TorchAudio requires 16-bit signed integers as inputs and hence the
wavefo... | Get mel-filter bank features via PyKaldi or TorchAudio. Prefer PyKaldi
(faster CPP implementation) to TorchAudio (Python implementation). Note that
Kaldi/TorchAudio requires 16-bit signed integers as inputs and hence the
waveform should not be normalized. | get_fbank | python | OFA-Sys/OFA | fairseq/fairseq/data/audio/audio_utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/audio/audio_utils.py | Apache-2.0 |
def parse_path(path: str) -> Tuple[str, List[int]]:
"""Parse data path which is either a path to
1. a .npy/.wav/.flac/.ogg file
2. a stored ZIP file with slicing info: "[zip_path]:[offset]:[length]"
Args:
path (str): the data path to parse
Returns:
file_path (str): the file... | Parse data path which is either a path to
1. a .npy/.wav/.flac/.ogg file
2. a stored ZIP file with slicing info: "[zip_path]:[offset]:[length]"
Args:
path (str): the data path to parse
Returns:
file_path (str): the file path
slice_ptr (list of int): empty in case 1;
... | parse_path | python | OFA-Sys/OFA | fairseq/fairseq/data/audio/audio_utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/audio/audio_utils.py | Apache-2.0 |
def get_feature_transforms(self, split, is_train):
"""Split-specific feature transforms. Allowing train set
wildcard `_train`, evaluation set wildcard `_eval` and general
wildcard `*` for matching."""
from copy import deepcopy
cfg = deepcopy(self.config)
_cur = cfg.get("... | Split-specific feature transforms. Allowing train set
wildcard `_train`, evaluation set wildcard `_eval` and general
wildcard `*` for matching. | get_feature_transforms | python | OFA-Sys/OFA | fairseq/fairseq/data/audio/data_cfg.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/audio/data_cfg.py | Apache-2.0 |
def get_features_or_waveform(
path: str, need_waveform=False, use_sample_rate=None
):
"""Get speech features from .npy file or waveform from .wav/.flac file.
The file may be inside an uncompressed ZIP file and is accessed via byte
offset and length.
Args:
path (str): File path in the fo... | Get speech features from .npy file or waveform from .wav/.flac file.
The file may be inside an uncompressed ZIP file and is accessed via byte
offset and length.
Args:
path (str): File path in the format of "<.npy/.wav/.flac path>" or
"<zip path>:<byte offset>:<byte length>".
need_wa... | get_features_or_waveform | python | OFA-Sys/OFA | fairseq/fairseq/data/audio/speech_to_text_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/audio/speech_to_text_dataset.py | Apache-2.0 |
def _collate_frames(
frames: List[torch.Tensor], is_audio_input: bool = False
) -> torch.Tensor:
"""
Convert a list of 2D frames into a padded 3D tensor
Args:
frames (list): list of 2D frames of size L[i]*f_dim. Where L[i] is
length of i-th frame and f_dim is static dimension of feat... |
Convert a list of 2D frames into a padded 3D tensor
Args:
frames (list): list of 2D frames of size L[i]*f_dim. Where L[i] is
length of i-th frame and f_dim is static dimension of features
Returns:
3D tensor of size len(frames)*len_max*f_dim where len_max is max of L[i]
| _collate_frames | python | OFA-Sys/OFA | fairseq/fairseq/data/audio/speech_to_text_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/audio/speech_to_text_dataset.py | Apache-2.0 |
def get_size_ratios(
cls, datasets: List[SpeechToTextDataset], alpha: float = 1.0
) -> List[float]:
"""Size ratios for temperature-based sampling
(https://arxiv.org/abs/1907.05019)"""
id_to_lp, lp_to_sz = {}, defaultdict(int)
for ds in datasets:
lang_pairs = {f"{... | Size ratios for temperature-based sampling
(https://arxiv.org/abs/1907.05019) | get_size_ratios | python | OFA-Sys/OFA | fairseq/fairseq/data/audio/speech_to_text_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/audio/speech_to_text_dataset.py | Apache-2.0 |
def get_pairs(word):
"""Return set of symbol pairs in a word.
Word is represented as tuple of symbols (symbols being variable-length strings).
"""
pairs = set()
prev_char = word[0]
for char in word[1:]:
pairs.add((prev_char, char))
prev_char = char
return pairs | Return set of symbol pairs in a word.
Word is represented as tuple of symbols (symbols being variable-length strings).
| get_pairs | python | OFA-Sys/OFA | fairseq/fairseq/data/encoders/gpt2_bpe_utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/encoders/gpt2_bpe_utils.py | Apache-2.0 |
def _pad(self, a: bitarray) -> bitarray:
"""
bitpadding, 1 then 0.
If the array is already a multiple of blocksize, we add a full block.
"""
pad_len = BLOCKSIZE - (len(a) % BLOCKSIZE) - 1
padding = bitarray("1" + "0" * pad_len)
return a + padding |
bitpadding, 1 then 0.
If the array is already a multiple of blocksize, we add a full block.
| _pad | python | OFA-Sys/OFA | fairseq/fairseq/data/huffman/huffman_coder.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/huffman/huffman_coder.py | Apache-2.0 |
def _unpad(self, a: bitarray) -> bitarray:
"""
remove the bitpadding.
There will be a set of 0s preceded by a 1 at the end of the bitarray, we remove that
"""
# count the 0 padding at the end until we find the first 1
# we want to remove the one too
remove_cnt = ... |
remove the bitpadding.
There will be a set of 0s preceded by a 1 at the end of the bitarray, we remove that
| _unpad | python | OFA-Sys/OFA | fairseq/fairseq/data/huffman/huffman_coder.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/huffman/huffman_coder.py | Apache-2.0 |
def encode(self, iter: tp.List[str]) -> bytes:
"""
encode a list of tokens a return bytes. We use bitpadding to make sure the encoded bits fit in bytes.
"""
a = bitarray()
for token in iter:
code = self.get_code(token)
if code is None:
if s... |
encode a list of tokens a return bytes. We use bitpadding to make sure the encoded bits fit in bytes.
| encode | python | OFA-Sys/OFA | fairseq/fairseq/data/huffman/huffman_coder.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/huffman/huffman_coder.py | Apache-2.0 |
def decode(self, bits: bytes) -> tp.Iterator["HuffmanNode"]:
"""
take bitpadded bytes and decode it to a set of leaves. You can then use each node to find the symbol/id
"""
a = bitarray()
a.frombytes(bits)
return self.root.decode(self._unpad(a)) |
take bitpadded bytes and decode it to a set of leaves. You can then use each node to find the symbol/id
| decode | python | OFA-Sys/OFA | fairseq/fairseq/data/huffman/huffman_coder.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/huffman/huffman_coder.py | Apache-2.0 |
def add_item(self, tokens: tp.List[str]) -> None:
"""
add a list of tokens to the dataset, they will compressed with the
provided coder before being written to file.
"""
encoded = self._coder.encode(tokens)
code_len = len(encoded)
last_ptr = 0
if len(self.... |
add a list of tokens to the dataset, they will compressed with the
provided coder before being written to file.
| add_item | python | OFA-Sys/OFA | fairseq/fairseq/data/huffman/huffman_mmap_indexed_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/huffman/huffman_mmap_indexed_dataset.py | Apache-2.0 |
def append(self, other_dataset_path_prefix: str) -> None:
"""
append an existing dataset.
Beware, if it wasn't built with the same coder, you are in trouble.
"""
other_index = HuffmanMMapIndex(
indexed_dataset.index_file_path(other_dataset_path_prefix)
)
... |
append an existing dataset.
Beware, if it wasn't built with the same coder, you are in trouble.
| append | python | OFA-Sys/OFA | fairseq/fairseq/data/huffman/huffman_mmap_indexed_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/huffman/huffman_mmap_indexed_dataset.py | Apache-2.0 |
def _pair_sentences(self, dataset_index):
"""
Give a list of evenly cut blocks/sentences, pair these sentences with 50%
consecutive sentences and 50% random sentences.
This is used for none break mode
"""
# pair sentences
for sent_id, sent in enumerate(dataset_ind... |
Give a list of evenly cut blocks/sentences, pair these sentences with 50%
consecutive sentences and 50% random sentences.
This is used for none break mode
| _pair_sentences | python | OFA-Sys/OFA | fairseq/fairseq/data/legacy/block_pair_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/legacy/block_pair_dataset.py | Apache-2.0 |
def _sent_to_dataset_index(self, sent_sizes):
"""
Build index mapping block indices to the underlying dataset indices
"""
dataset_index = []
ds_idx, ds_remaining = -1, 0
for to_consume in sent_sizes:
sent_size = to_consume
if ds_remaining == 0:
... |
Build index mapping block indices to the underlying dataset indices
| _sent_to_dataset_index | python | OFA-Sys/OFA | fairseq/fairseq/data/legacy/block_pair_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/legacy/block_pair_dataset.py | Apache-2.0 |
def _generate_sentence_pair(self, doc, doc_id, max_num_tokens, sizes):
"""
Go through a single document and genrate sentence paris from it
"""
current_chunk = []
current_length = 0
curr = 0
# To provide more randomness, we decrease target seq length for parts of
... |
Go through a single document and genrate sentence paris from it
| _generate_sentence_pair | python | OFA-Sys/OFA | fairseq/fairseq/data/legacy/block_pair_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/legacy/block_pair_dataset.py | Apache-2.0 |
def _skip_sampling(self, total, skip_ids):
"""
Generate a random integer which is not in skip_ids. Sample range is [0, total)
TODO: ids in skip_ids should be consecutive, we can extend it to more generic version later
"""
rand_id = np.random.randint(total - len(skip_ids))
... |
Generate a random integer which is not in skip_ids. Sample range is [0, total)
TODO: ids in skip_ids should be consecutive, we can extend it to more generic version later
| _skip_sampling | python | OFA-Sys/OFA | fairseq/fairseq/data/legacy/block_pair_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/legacy/block_pair_dataset.py | Apache-2.0 |
def _cut_sentence(self, sent, front_cut, end_cut):
"""
Cut a sentence based on the numbers of tokens to be cut from beginning and end
Represent the sentence as dataset idx and return
"""
start_ds_idx, end_ds_idx, offset = sent[0], sent[-1], 0
target_len = sum(self.dataset... |
Cut a sentence based on the numbers of tokens to be cut from beginning and end
Represent the sentence as dataset idx and return
| _cut_sentence | python | OFA-Sys/OFA | fairseq/fairseq/data/legacy/block_pair_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/legacy/block_pair_dataset.py | Apache-2.0 |
def _fetch_block(self, start_ds_idx, offset, end_ds_idx, length):
"""
Fetch a block of tokens based on its dataset idx
"""
buffer = torch.cat(
[self.dataset[idx] for idx in range(start_ds_idx, end_ds_idx + 1)]
)
s, e = offset, offset + length
return bu... |
Fetch a block of tokens based on its dataset idx
| _fetch_block | python | OFA-Sys/OFA | fairseq/fairseq/data/legacy/block_pair_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/legacy/block_pair_dataset.py | Apache-2.0 |
def _mask_block(
self,
sentence: np.ndarray,
mask_idx: int,
pad_idx: int,
dictionary_token_range: Tuple,
):
"""
Mask tokens for Masked Language Model training
Samples mask_ratio tokens that will be predicted by LM.
Note:This function may not b... |
Mask tokens for Masked Language Model training
Samples mask_ratio tokens that will be predicted by LM.
Note:This function may not be efficient enough since we had multiple
conversions between np and torch, we can replace them with torch
operators later.
Args:
... | _mask_block | python | OFA-Sys/OFA | fairseq/fairseq/data/legacy/masked_lm_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/legacy/masked_lm_dataset.py | Apache-2.0 |
def _collate(self, samples: List[Dict], pad_idx: int, eos_idx: int):
"""
Does the heavy lifting for creating a batch from the input list of
examples. The logic is as follows:
1. Mask the input blocks. In case has_pair is True then we have 2
blocks to mask.
... |
Does the heavy lifting for creating a batch from the input list of
examples. The logic is as follows:
1. Mask the input blocks. In case has_pair is True then we have 2
blocks to mask.
2. Prepend the first masked block tensor with the special token
u... | _collate | python | OFA-Sys/OFA | fairseq/fairseq/data/legacy/masked_lm_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/legacy/masked_lm_dataset.py | Apache-2.0 |
def ordered_indices(self):
"""
Return an ordered list of indices. Batches will be constructed based
on this order.
"""
if self.shuffle:
return np.random.permutation(len(self))
else:
order = [np.arange(len(self))]
order.append(self.sizes... |
Return an ordered list of indices. Batches will be constructed based
on this order.
| ordered_indices | python | OFA-Sys/OFA | fairseq/fairseq/data/legacy/masked_lm_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/legacy/masked_lm_dataset.py | Apache-2.0 |
def add_defaults(cfg: DictConfig) -> None:
"""This function adds default values that are stored in dataclasses that hydra doesn't know about """
from fairseq.registry import REGISTRIES
from fairseq.tasks import TASK_DATACLASS_REGISTRY
from fairseq.models import ARCH_MODEL_NAME_REGISTRY, MODEL_DATACLASS... | This function adds default values that are stored in dataclasses that hydra doesn't know about | add_defaults | python | OFA-Sys/OFA | fairseq/fairseq/dataclass/initialize.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/dataclass/initialize.py | Apache-2.0 |
def gen_parser_from_dataclass(
parser: ArgumentParser,
dataclass_instance: FairseqDataclass,
delete_default: bool = False,
with_prefix: Optional[str] = None,
) -> None:
"""
convert a dataclass instance to tailing parser arguments.
If `with_prefix` is provided, prefix all the keys in... |
convert a dataclass instance to tailing parser arguments.
If `with_prefix` is provided, prefix all the keys in the resulting parser with it. It means that we are
building a flat namespace from a structured dataclass (see transformer_config.py for example).
| gen_parser_from_dataclass | python | OFA-Sys/OFA | fairseq/fairseq/dataclass/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/dataclass/utils.py | Apache-2.0 |
def _set_legacy_defaults(args, cls):
"""Helper to set default arguments based on *add_args*."""
if not hasattr(cls, "add_args"):
return
import argparse
parser = argparse.ArgumentParser(
argument_default=argparse.SUPPRESS, allow_abbrev=False
)
cls.add_args(parser)
# copied f... | Helper to set default arguments based on *add_args*. | _set_legacy_defaults | python | OFA-Sys/OFA | fairseq/fairseq/dataclass/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/dataclass/utils.py | Apache-2.0 |
def override_module_args(args: Namespace) -> Tuple[List[str], List[str]]:
"""use the field in args to overrides those in cfg"""
overrides = []
deletes = []
for k in FairseqConfig.__dataclass_fields__.keys():
overrides.extend(
_override_attr(k, FairseqConfig.__dataclass_fields__[k].t... | use the field in args to overrides those in cfg | override_module_args | python | OFA-Sys/OFA | fairseq/fairseq/dataclass/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/dataclass/utils.py | Apache-2.0 |
def convert_namespace_to_omegaconf(args: Namespace) -> DictConfig:
"""Convert a flat argparse.Namespace to a structured DictConfig."""
# Here we are using field values provided in args to override counterparts inside config object
overrides, deletes = override_module_args(args)
# configs will be in fa... | Convert a flat argparse.Namespace to a structured DictConfig. | convert_namespace_to_omegaconf | python | OFA-Sys/OFA | fairseq/fairseq/dataclass/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/dataclass/utils.py | Apache-2.0 |
def __getattr__(self, name):
"""Forward missing attributes to wrapped module."""
try:
return super().__getattr__(name) # defer to nn.Module's logic
except AttributeError:
return getattr(self.module, name) | Forward missing attributes to wrapped module. | __getattr__ | python | OFA-Sys/OFA | fairseq/fairseq/distributed/distributed_timeout_wrapper.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/distributed/distributed_timeout_wrapper.py | Apache-2.0 |
def fsdp_wrap(module, min_num_params: Optional[int] = None, **kwargs):
"""
Helper to wrap layers/modules in FSDP. This falls back to a no-op if
fairscale is not available.
Args:
module (nn.Module): module to (maybe) wrap
min_num_params (int, Optional): minimum number of layer params to ... |
Helper to wrap layers/modules in FSDP. This falls back to a no-op if
fairscale is not available.
Args:
module (nn.Module): module to (maybe) wrap
min_num_params (int, Optional): minimum number of layer params to wrap
| fsdp_wrap | python | OFA-Sys/OFA | fairseq/fairseq/distributed/fully_sharded_data_parallel.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/distributed/fully_sharded_data_parallel.py | Apache-2.0 |
def no_sync(self):
"""A context manager to disable gradient synchronization."""
old_accumulate_grads = self.accumulate_grads
self.accumulate_grads = True
yield
self.accumulate_grads = old_accumulate_grads | A context manager to disable gradient synchronization. | no_sync | python | OFA-Sys/OFA | fairseq/fairseq/distributed/legacy_distributed_data_parallel.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/distributed/legacy_distributed_data_parallel.py | Apache-2.0 |
def all_reduce_grads(self):
"""
This function must be called explicitly after backward to reduce
gradients. There is no automatic hook like c10d.
"""
def all_reduce_params(params):
buffer = self.buffer
nonzero_buffer = False
if len(params) > 1... |
This function must be called explicitly after backward to reduce
gradients. There is no automatic hook like c10d.
| all_reduce_grads | python | OFA-Sys/OFA | fairseq/fairseq/distributed/legacy_distributed_data_parallel.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/distributed/legacy_distributed_data_parallel.py | Apache-2.0 |
def __getattr__(self, name):
"""Forward missing attributes to twice-wrapped module."""
try:
# defer to nn.Module's logic
return super().__getattr__(name)
except AttributeError:
try:
# forward to the once-wrapped module
return ge... | Forward missing attributes to twice-wrapped module. | __getattr__ | python | OFA-Sys/OFA | fairseq/fairseq/distributed/module_proxy_wrapper.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/distributed/module_proxy_wrapper.py | Apache-2.0 |
def all_to_all(tensor, group):
"""Perform an all-to-all operation on a 1D Tensor."""
assert tensor.dim() == 1
split_count = get_world_size(group=group)
assert tensor.numel() % split_count == 0
if use_xla():
assert isinstance(group, tuple) and group[0] == "tpu"
return xm.all_to_all(
... | Perform an all-to-all operation on a 1D Tensor. | all_to_all | python | OFA-Sys/OFA | fairseq/fairseq/distributed/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/distributed/utils.py | Apache-2.0 |
def all_gather_list(data, group=None, max_size=16384):
"""Gathers arbitrary data from all nodes into a list.
Similar to :func:`~torch.distributed.all_gather` but for arbitrary Python
data. Note that *data* must be picklable and any CUDA tensors will be moved
to CPU and returned on CPU as well.
Arg... | Gathers arbitrary data from all nodes into a list.
Similar to :func:`~torch.distributed.all_gather` but for arbitrary Python
data. Note that *data* must be picklable and any CUDA tensors will be moved
to CPU and returned on CPU as well.
Args:
data (Any): data from the local worker to be gather... | all_gather_list | python | OFA-Sys/OFA | fairseq/fairseq/distributed/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/distributed/utils.py | Apache-2.0 |
def all_reduce_dict(data: Mapping[str, Any], device, group) -> Dict[str, Any]:
"""
AllReduce a dictionary of values across workers. We separately
reduce items that are already on the device and items on CPU for
better performance.
Args:
data (Mapping[str, Any]): dictionary of data to all-re... |
AllReduce a dictionary of values across workers. We separately
reduce items that are already on the device and items on CPU for
better performance.
Args:
data (Mapping[str, Any]): dictionary of data to all-reduce, but
cannot be a nested dictionary
device (torch.device): dev... | all_reduce_dict | python | OFA-Sys/OFA | fairseq/fairseq/distributed/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/distributed/utils.py | Apache-2.0 |
def broadcast_tensors(
tensors: Optional[List[torch.Tensor]],
src_rank: int,
group: object,
dist_device: Optional[torch.device] = None,
) -> List[torch.Tensor]:
"""
Broadcasts a list of tensors without other (non-src) ranks needing to know
the dtypes/shapes of the tensors.
"""
if dis... |
Broadcasts a list of tensors without other (non-src) ranks needing to know
the dtypes/shapes of the tensors.
| broadcast_tensors | python | OFA-Sys/OFA | fairseq/fairseq/distributed/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/distributed/utils.py | Apache-2.0 |
def broadcast_object(
obj: Any,
src_rank: int,
group: object,
dist_device: Optional[torch.device] = None,
) -> Any:
"""Broadcast an arbitrary Python object to other workers."""
if dist_device is None:
if torch.distributed.get_backend(group) == "nccl":
dist_device = torch.devi... | Broadcast an arbitrary Python object to other workers. | broadcast_object | python | OFA-Sys/OFA | fairseq/fairseq/distributed/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/distributed/utils.py | Apache-2.0 |
def aggregate(name: Optional[str] = None, new_root: bool = False):
"""Context manager to aggregate metrics under a given name.
Aggregations can be nested. If *new_root* is ``False``, then logged
metrics will be recorded along the entire stack of nested
aggregators, including a global "default" aggregat... | Context manager to aggregate metrics under a given name.
Aggregations can be nested. If *new_root* is ``False``, then logged
metrics will be recorded along the entire stack of nested
aggregators, including a global "default" aggregator. If *new_root*
is ``True``, then this aggregator will be the root o... | aggregate | python | OFA-Sys/OFA | fairseq/fairseq/logging/metrics.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/logging/metrics.py | Apache-2.0 |
def log_scalar(
key: str,
value: float,
weight: float = 1,
priority: int = 10,
round: Optional[int] = None,
):
"""Log a scalar value.
Args:
key (str): name of the field to log
value (float): value to log
weight (float): weight that this value contributes to the avera... | Log a scalar value.
Args:
key (str): name of the field to log
value (float): value to log
weight (float): weight that this value contributes to the average.
A weight of 0 will always log the latest value.
priority (int): smaller values are logged earlier in the output
... | log_scalar | python | OFA-Sys/OFA | fairseq/fairseq/logging/metrics.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/logging/metrics.py | Apache-2.0 |
def log_scalar_sum(
key: str,
value: float,
priority: int = 10,
round: Optional[int] = None,
):
"""Log a scalar value that is summed for reporting.
Args:
key (str): name of the field to log
value (float): value to log
priority (int): smaller values are logged earlier in ... | Log a scalar value that is summed for reporting.
Args:
key (str): name of the field to log
value (float): value to log
priority (int): smaller values are logged earlier in the output
round (Optional[int]): number of digits to round to when displaying
| log_scalar_sum | python | OFA-Sys/OFA | fairseq/fairseq/logging/metrics.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/logging/metrics.py | Apache-2.0 |
def log_derived(key: str, fn: Callable[[MetersDict], float], priority: int = 20):
"""Log a scalar value derived from other meters.
Args:
key (str): name of the field to log
fn (Callable[[MetersDict], float]): function that takes a single
argument *meters* and returns the derived val... | Log a scalar value derived from other meters.
Args:
key (str): name of the field to log
fn (Callable[[MetersDict], float]): function that takes a single
argument *meters* and returns the derived value
priority (int): smaller values are logged earlier in the output
| log_derived | python | OFA-Sys/OFA | fairseq/fairseq/logging/metrics.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/logging/metrics.py | Apache-2.0 |
def log_speed(
key: str,
value: float,
priority: int = 30,
round: Optional[int] = None,
):
"""Log the rate of some quantity per second.
Args:
key (str): name of the field to log
value (float): value to log
priority (int): smaller values are logged earlier in the output
... | Log the rate of some quantity per second.
Args:
key (str): name of the field to log
value (float): value to log
priority (int): smaller values are logged earlier in the output
round (Optional[int]): number of digits to round to when displaying
| log_speed | python | OFA-Sys/OFA | fairseq/fairseq/logging/metrics.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/logging/metrics.py | Apache-2.0 |
def log_start_time(key: str, priority: int = 40, round: Optional[int] = None):
"""Log the duration of some event in seconds.
The duration will be computed once :func:`log_stop_time` is called.
Args:
key (str): name of the field to log
priority (int): smaller values are logged earlier in th... | Log the duration of some event in seconds.
The duration will be computed once :func:`log_stop_time` is called.
Args:
key (str): name of the field to log
priority (int): smaller values are logged earlier in the output
round (Optional[int]): number of digits to round to when displaying
... | log_start_time | python | OFA-Sys/OFA | fairseq/fairseq/logging/metrics.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/logging/metrics.py | Apache-2.0 |
def log_stop_time(key: str, weight: float = 0.0, prehook=None):
"""Log the duration of some event in seconds.
The duration will be computed since :func:`log_start_time` was called.
Set weight > 0 to report the average time instead of the sum.
Args:
key (str): name of the field to log
w... | Log the duration of some event in seconds.
The duration will be computed since :func:`log_start_time` was called.
Set weight > 0 to report the average time instead of the sum.
Args:
key (str): name of the field to log
weight (float): weight that this time contributes to the average
... | log_stop_time | python | OFA-Sys/OFA | fairseq/fairseq/logging/metrics.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/logging/metrics.py | Apache-2.0 |
def log_custom(
new_meter_fn: Callable[[], Meter],
key: str,
*args,
priority: int = 50,
**kwargs,
):
"""Log using a custom Meter.
Any extra *args* or *kwargs* will be passed through to the Meter's
*update* method.
Args:
new_meter_fn (Callable[[], Meter]): function that retu... | Log using a custom Meter.
Any extra *args* or *kwargs* will be passed through to the Meter's
*update* method.
Args:
new_meter_fn (Callable[[], Meter]): function that returns a new
Meter instance
key (str): name of the field to log
priority (int): smaller values are logg... | log_custom | python | OFA-Sys/OFA | fairseq/fairseq/logging/metrics.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/logging/metrics.py | Apache-2.0 |
def reset_meter(name: str, key: str) -> None:
"""Reset Meter instance aggregated under a given *name* and *key*."""
meter = get_meter(name, key)
if meter is not None:
meter.reset() | Reset Meter instance aggregated under a given *name* and *key*. | reset_meter | python | OFA-Sys/OFA | fairseq/fairseq/logging/metrics.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/logging/metrics.py | Apache-2.0 |
def reset_meters(name: str) -> None:
"""Reset Meter instances aggregated under a given *name*."""
meters = get_meters(name)
if meters is not None:
meters.reset() | Reset Meter instances aggregated under a given *name*. | reset_meters | python | OFA-Sys/OFA | fairseq/fairseq/logging/metrics.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/logging/metrics.py | Apache-2.0 |
def get_meter(name: str, key: str) -> Meter:
"""Get a single Meter instance aggregated under *name* and *key*.
Returns:
Meter or None if no metrics have been logged under *name* and *key*.
"""
if name not in _aggregators:
return None
return _aggregators[name].get(key, None) | Get a single Meter instance aggregated under *name* and *key*.
Returns:
Meter or None if no metrics have been logged under *name* and *key*.
| get_meter | python | OFA-Sys/OFA | fairseq/fairseq/logging/metrics.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/logging/metrics.py | Apache-2.0 |
def build_progress_bar(
args,
iterator,
epoch: Optional[int] = None,
prefix: Optional[str] = None,
default: str = "tqdm",
no_progress_bar: str = "none",
):
"""Legacy wrapper that takes an argparse.Namespace."""
if getattr(args, "no_progress_bar", False):
default = no_progress_bar... | Legacy wrapper that takes an argparse.Namespace. | build_progress_bar | python | OFA-Sys/OFA | fairseq/fairseq/logging/progress_bar.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/logging/progress_bar.py | Apache-2.0 |
def forward(self, src_tokens, src_lengths):
"""
Args:
src_tokens (LongTensor): tokens in the source language of shape
`(batch, src_len)`
src_lengths (LongTensor): lengths of each source sentence of shape
`(batch)`
Returns:
dict... |
Args:
src_tokens (LongTensor): tokens in the source language of shape
`(batch, src_len)`
src_lengths (LongTensor): lengths of each source sentence of shape
`(batch)`
Returns:
dict:
the outputs from each Encoder
... | forward | python | OFA-Sys/OFA | fairseq/fairseq/models/composite_encoder.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/composite_encoder.py | Apache-2.0 |
def DistributedFairseqModel(args, model, process_group, device):
"""
Wrap a *model* to support distributed data parallel training.
This is similar to the built-in DistributedDataParallel, but allows
additional configuration of the DistributedDataParallel class to
use, and also provides easier acces... |
Wrap a *model* to support distributed data parallel training.
This is similar to the built-in DistributedDataParallel, but allows
additional configuration of the DistributedDataParallel class to
use, and also provides easier access to the wrapped model by
forwarding requests for missing attributes... | DistributedFairseqModel | python | OFA-Sys/OFA | fairseq/fairseq/models/distributed_fairseq_model.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/distributed_fairseq_model.py | Apache-2.0 |
def forward(self, prev_output_tokens, encoder_out=None, **kwargs):
"""
Args:
prev_output_tokens (LongTensor): shifted output tokens of shape
`(batch, tgt_len)`, for teacher forcing
encoder_out (dict, optional): output from the encoder, used for
enc... |
Args:
prev_output_tokens (LongTensor): shifted output tokens of shape
`(batch, tgt_len)`, for teacher forcing
encoder_out (dict, optional): output from the encoder, used for
encoder-side attention
Returns:
tuple:
- the... | forward | python | OFA-Sys/OFA | fairseq/fairseq/models/fairseq_decoder.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/fairseq_decoder.py | Apache-2.0 |
def get_normalized_probs(
self,
net_output: Tuple[Tensor, Optional[Dict[str, List[Optional[Tensor]]]]],
log_probs: bool,
sample: Optional[Dict[str, Tensor]] = None,
):
"""Get normalized probabilities (or log probs) from a net's output."""
return self.get_normalized_pr... | Get normalized probabilities (or log probs) from a net's output. | get_normalized_probs | python | OFA-Sys/OFA | fairseq/fairseq/models/fairseq_decoder.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/fairseq_decoder.py | Apache-2.0 |
def forward_torchscript(self, net_input: Dict[str, Tensor]):
"""A TorchScript-compatible version of forward.
Encoders which use additional arguments may want to override
this method for TorchScript compatibility.
"""
if torch.jit.is_scripting():
return self.forward(
... | A TorchScript-compatible version of forward.
Encoders which use additional arguments may want to override
this method for TorchScript compatibility.
| forward_torchscript | python | OFA-Sys/OFA | fairseq/fairseq/models/fairseq_encoder.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/fairseq_encoder.py | Apache-2.0 |
def set_num_updates(self, num_updates):
"""State from trainer to pass along to model at every update."""
def _apply(m):
if hasattr(m, "set_num_updates") and m != self:
m.set_num_updates(num_updates)
self.apply(_apply) | State from trainer to pass along to model at every update. | set_num_updates | python | OFA-Sys/OFA | fairseq/fairseq/models/fairseq_encoder.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/fairseq_encoder.py | Apache-2.0 |
def forward(
self, prev_output_tokens, encoder_out=None, incremental_state=None, **kwargs
):
"""
Args:
prev_output_tokens (LongTensor): shifted output tokens of shape
`(batch, tgt_len)`, for teacher forcing
encoder_out (dict, optional): output from the... |
Args:
prev_output_tokens (LongTensor): shifted output tokens of shape
`(batch, tgt_len)`, for teacher forcing
encoder_out (dict, optional): output from the encoder, used for
encoder-side attention
incremental_state (dict, optional): dictionary... | forward | python | OFA-Sys/OFA | fairseq/fairseq/models/fairseq_incremental_decoder.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/fairseq_incremental_decoder.py | Apache-2.0 |
def extract_features(
self, prev_output_tokens, encoder_out=None, incremental_state=None, **kwargs
):
"""
Returns:
tuple:
- the decoder's features of shape `(batch, tgt_len, embed_dim)`
- a dictionary with any model-specific outputs
"""
... |
Returns:
tuple:
- the decoder's features of shape `(batch, tgt_len, embed_dim)`
- a dictionary with any model-specific outputs
| extract_features | python | OFA-Sys/OFA | fairseq/fairseq/models/fairseq_incremental_decoder.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/fairseq_incremental_decoder.py | Apache-2.0 |
def set_beam_size(self, beam_size):
"""Sets the beam size in the decoder and all children."""
if getattr(self, "_beam_size", -1) != beam_size:
seen = set()
def apply_set_beam_size(module):
if (
module != self
and hasattr(mo... | Sets the beam size in the decoder and all children. | set_beam_size | python | OFA-Sys/OFA | fairseq/fairseq/models/fairseq_incremental_decoder.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/fairseq_incremental_decoder.py | Apache-2.0 |
def get_normalized_probs_scriptable(
self,
net_output: Tuple[Tensor, Optional[Dict[str, List[Optional[Tensor]]]]],
log_probs: bool,
sample: Optional[Dict[str, Tensor]] = None,
):
"""Scriptable helper function for get_normalized_probs in ~BaseFairseqModel"""
if hasattr... | Scriptable helper function for get_normalized_probs in ~BaseFairseqModel | get_normalized_probs_scriptable | python | OFA-Sys/OFA | fairseq/fairseq/models/fairseq_model.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/fairseq_model.py | Apache-2.0 |
def load_state_dict(
self,
state_dict,
strict=True,
model_cfg: Optional[DictConfig] = None,
args: Optional[Namespace] = None,
):
"""Copies parameters and buffers from *state_dict* into this module and
its descendants.
Overrides the method in :class:`n... | Copies parameters and buffers from *state_dict* into this module and
its descendants.
Overrides the method in :class:`nn.Module`. Compared with that method
this additionally "upgrades" *state_dicts* from old checkpoints.
| load_state_dict | python | OFA-Sys/OFA | fairseq/fairseq/models/fairseq_model.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/fairseq_model.py | Apache-2.0 |
def upgrade_state_dict_named(self, state_dict, name):
"""Upgrade old state dicts to work with newer code.
Args:
state_dict (dict): state dictionary to upgrade, in place
name (str): the state dict key corresponding to the current module
"""
assert state_dict is no... | Upgrade old state dicts to work with newer code.
Args:
state_dict (dict): state dictionary to upgrade, in place
name (str): the state dict key corresponding to the current module
| upgrade_state_dict_named | python | OFA-Sys/OFA | fairseq/fairseq/models/fairseq_model.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/fairseq_model.py | Apache-2.0 |
def make_generation_fast_(self, **kwargs):
"""
Legacy entry point to optimize model for faster generation.
Prefer prepare_for_inference_.
"""
if self._is_generation_fast:
return # only apply once
self._is_generation_fast = True
# remove weight norm f... |
Legacy entry point to optimize model for faster generation.
Prefer prepare_for_inference_.
| make_generation_fast_ | python | OFA-Sys/OFA | fairseq/fairseq/models/fairseq_model.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/fairseq_model.py | Apache-2.0 |
def prepare_for_onnx_export_(self, **kwargs):
"""Make model exportable via ONNX trace."""
seen = set()
def apply_prepare_for_onnx_export_(module):
if (
module != self
and hasattr(module, "prepare_for_onnx_export_")
and module not in se... | Make model exportable via ONNX trace. | prepare_for_onnx_export_ | python | OFA-Sys/OFA | fairseq/fairseq/models/fairseq_model.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/fairseq_model.py | Apache-2.0 |
def from_pretrained(
cls,
model_name_or_path,
checkpoint_file="model.pt",
data_name_or_path=".",
**kwargs,
):
"""
Load a :class:`~fairseq.models.FairseqModel` from a pre-trained model
file. Downloads and caches the pre-trained model file if needed.
... |
Load a :class:`~fairseq.models.FairseqModel` from a pre-trained model
file. Downloads and caches the pre-trained model file if needed.
The base implementation returns a
:class:`~fairseq.hub_utils.GeneratorHubInterface`, which can be used to
generate translations or sample from ... | from_pretrained | python | OFA-Sys/OFA | fairseq/fairseq/models/fairseq_model.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/fairseq_model.py | Apache-2.0 |
def forward(self, src_tokens, src_lengths, prev_output_tokens, **kwargs):
"""
Run the forward pass for an encoder-decoder model.
First feed a batch of source tokens through the encoder. Then, feed the
encoder output and previous decoder outputs (i.e., teacher forcing) to
the dec... |
Run the forward pass for an encoder-decoder model.
First feed a batch of source tokens through the encoder. Then, feed the
encoder output and previous decoder outputs (i.e., teacher forcing) to
the decoder to produce the next outputs::
encoder_out = self.encoder(src_tokens... | forward | python | OFA-Sys/OFA | fairseq/fairseq/models/fairseq_model.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/fairseq_model.py | Apache-2.0 |
def build_shared_embeddings(
dicts: Dict[str, Dictionary],
langs: List[str],
embed_dim: int,
build_embedding: callable,
pretrained_embed_path: Optional[str] = None,
):
"""
Helper function to build shared embeddings for a set of languages after
checking... |
Helper function to build shared embeddings for a set of languages after
checking that all dicts corresponding to those languages are equivalent.
Args:
dicts: Dict of lang_id to its corresponding Dictionary
langs: languages that we want to share embeddings for
... | build_shared_embeddings | python | OFA-Sys/OFA | fairseq/fairseq/models/fairseq_model.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/fairseq_model.py | Apache-2.0 |
def max_positions(self):
"""Maximum length supported by the model."""
return {
key: (
self.models[key].encoder.max_positions(),
self.models[key].decoder.max_positions(),
)
for key in self.keys
} | Maximum length supported by the model. | max_positions | python | OFA-Sys/OFA | fairseq/fairseq/models/fairseq_model.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/fairseq_model.py | Apache-2.0 |
def forward(self, src_tokens, src_lengths):
"""
Args:
src_tokens (LongTensor): tokens in the source language of shape
`(batch, src_len)`
src_lengths (LongTensor): lengths of each source sentence of shape
`(batch)`
Returns:
dict... |
Args:
src_tokens (LongTensor): tokens in the source language of shape
`(batch, src_len)`
src_lengths (LongTensor): lengths of each source sentence of shape
`(batch)`
Returns:
dict:
- **encoder_out** (tuple): a tuple wi... | forward | python | OFA-Sys/OFA | fairseq/fairseq/models/fconv.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/fconv.py | Apache-2.0 |
def max_positions(self):
"""Maximum output length supported by the decoder."""
return (
self.embed_positions.max_positions
if self.embed_positions is not None
else float("inf")
) | Maximum output length supported by the decoder. | max_positions | python | OFA-Sys/OFA | fairseq/fairseq/models/fconv.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/fconv.py | Apache-2.0 |
def _split_encoder_out(self, encoder_out, incremental_state):
"""Split and transpose encoder outputs.
This is cached when doing incremental inference.
"""
cached_result = utils.get_incremental_state(
self, incremental_state, "encoder_out"
)
if cached_result i... | Split and transpose encoder outputs.
This is cached when doing incremental inference.
| _split_encoder_out | python | OFA-Sys/OFA | fairseq/fairseq/models/fconv.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/fconv.py | Apache-2.0 |
def extend_conv_spec(convolutions):
"""
Extends convolutional spec that is a list of tuples of 2 or 3 parameters
(kernel size, dim size and optionally how many layers behind to look for residual)
to default the residual propagation param if it is not specified
"""
extended = []
for spec in c... |
Extends convolutional spec that is a list of tuples of 2 or 3 parameters
(kernel size, dim size and optionally how many layers behind to look for residual)
to default the residual propagation param if it is not specified
| extend_conv_spec | python | OFA-Sys/OFA | fairseq/fairseq/models/fconv.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/fconv.py | Apache-2.0 |
def forward(self, src_tokens, **unused):
"""
Args:
src_tokens (LongTensor): tokens in the source language of shape
`(batch, src_len)`
Returns:
dict:
- **encoder_out** (Tensor): the last encoder layer's output of
shape `(s... |
Args:
src_tokens (LongTensor): tokens in the source language of shape
`(batch, src_len)`
Returns:
dict:
- **encoder_out** (Tensor): the last encoder layer's output of
shape `(src_len, batch, embed_dim)`
- **encod... | forward | python | OFA-Sys/OFA | fairseq/fairseq/models/lightconv.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/lightconv.py | Apache-2.0 |
def max_positions(self):
"""Maximum input length supported by the encoder."""
if self.embed_positions is None:
return self.max_source_positions
return min(self.max_source_positions, self.embed_positions.max_positions) | Maximum input length supported by the encoder. | max_positions | python | OFA-Sys/OFA | fairseq/fairseq/models/lightconv.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/lightconv.py | Apache-2.0 |
def forward(
self, prev_output_tokens, encoder_out=None, incremental_state=None, **kwargs
):
"""
Args:
prev_output_tokens (LongTensor): previous decoder outputs of shape
`(batch, tgt_len)`, for teacher forcing
encoder_out (Tensor, optional): output fro... |
Args:
prev_output_tokens (LongTensor): previous decoder outputs of shape
`(batch, tgt_len)`, for teacher forcing
encoder_out (Tensor, optional): output from the encoder, used for
encoder-side attention
incremental_state (dict): dictionary used... | forward | python | OFA-Sys/OFA | fairseq/fairseq/models/lightconv.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/lightconv.py | Apache-2.0 |
def forward(self, x, encoder_padding_mask):
"""
Args:
x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`
encoder_padding_mask (ByteTensor): binary ByteTensor of shape
`(batch, src_len)` where padding elements are indicated by ``1``.
Ret... |
Args:
x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`
encoder_padding_mask (ByteTensor): binary ByteTensor of shape
`(batch, src_len)` where padding elements are indicated by ``1``.
Returns:
encoded output of shape `(batch, src_... | forward | python | OFA-Sys/OFA | fairseq/fairseq/models/lightconv.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/lightconv.py | Apache-2.0 |
def forward(
self,
src_tokens: Tensor,
src_lengths: Tensor,
enforce_sorted: bool = True,
):
"""
Args:
src_tokens (LongTensor): tokens in the source language of
shape `(batch, src_len)`
src_lengths (LongTensor): lengths of each s... |
Args:
src_tokens (LongTensor): tokens in the source language of
shape `(batch, src_len)`
src_lengths (LongTensor): lengths of each source sentence of
shape `(batch)`
enforce_sorted (bool, optional): if True, `src_tokens` is
exp... | forward | python | OFA-Sys/OFA | fairseq/fairseq/models/lstm.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/lstm.py | Apache-2.0 |
def extract_features(
self,
prev_output_tokens,
encoder_out: Optional[Tuple[Tensor, Tensor, Tensor, Tensor]] = None,
incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,
):
"""
Similar to *forward* but only return features.
"""
#... |
Similar to *forward* but only return features.
| extract_features | python | OFA-Sys/OFA | fairseq/fairseq/models/lstm.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/lstm.py | Apache-2.0 |
def output_layer(self, x):
"""Project features to the vocabulary size."""
if self.adaptive_softmax is None:
if self.share_input_output_embed:
x = F.linear(x, self.embed_tokens.weight)
else:
x = self.fc_out(x)
return x | Project features to the vocabulary size. | output_layer | python | OFA-Sys/OFA | fairseq/fairseq/models/lstm.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/lstm.py | Apache-2.0 |
def forward(self, src_tokens, segment_labels=None, masked_tokens=None, **unused):
"""
Forward pass for Masked LM encoder. This first computes the token
embedding using the token embedding matrix, position embeddings (if
specified) and segment embeddings (if specified).
Here we a... |
Forward pass for Masked LM encoder. This first computes the token
embedding using the token embedding matrix, position embeddings (if
specified) and segment embeddings (if specified).
Here we assume that the sentence representation corresponds to the
output of the classificatio... | forward | python | OFA-Sys/OFA | fairseq/fairseq/models/masked_lm.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/masked_lm.py | Apache-2.0 |
def fill_tensors(
x: Optional[Tensor], mask, y: Optional[Tensor], padding_idx: int
) -> Optional[Tensor]:
"""
Filling tensor x with y at masked positions (dim=0).
"""
if x is None or x.size()[0] == 0 or y is None:
return x
assert x.dim() == y.dim() and mask.size(0) == x.size(0)
asser... |
Filling tensor x with y at masked positions (dim=0).
| fill_tensors | python | OFA-Sys/OFA | fairseq/fairseq/models/model_utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/model_utils.py | Apache-2.0 |
def upgrade_state_dict_with_xlm_weights(
state_dict: Dict[str, Any], pretrained_xlm_checkpoint: str
) -> Dict[str, Any]:
"""
Load XLM weights into a Transformer encoder or decoder model.
Args:
state_dict: state dict for either TransformerEncoder or
TransformerDecoder
pretrai... |
Load XLM weights into a Transformer encoder or decoder model.
Args:
state_dict: state dict for either TransformerEncoder or
TransformerDecoder
pretrained_xlm_checkpoint: checkpoint to load XLM weights from
Raises:
AssertionError: If architecture (num layers, attention ... | upgrade_state_dict_with_xlm_weights | python | OFA-Sys/OFA | fairseq/fairseq/models/transformer_from_pretrained_xlm.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/transformer_from_pretrained_xlm.py | Apache-2.0 |
def register_model(name, dataclass=None):
"""
New model types can be added to fairseq with the :func:`register_model`
function decorator.
For example::
@register_model('lstm')
class LSTM(FairseqEncoderDecoderModel):
(...)
.. note:: All models must implement the :class:... |
New model types can be added to fairseq with the :func:`register_model`
function decorator.
For example::
@register_model('lstm')
class LSTM(FairseqEncoderDecoderModel):
(...)
.. note:: All models must implement the :class:`BaseFairseqModel` interface.
Typically y... | register_model | python | OFA-Sys/OFA | fairseq/fairseq/models/__init__.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/__init__.py | Apache-2.0 |
def register_model_architecture(model_name, arch_name):
"""
New model architectures can be added to fairseq with the
:func:`register_model_architecture` function decorator. After registration,
model architectures can be selected with the ``--arch`` command-line
argument.
For example::
... |
New model architectures can be added to fairseq with the
:func:`register_model_architecture` function decorator. After registration,
model architectures can be selected with the ``--arch`` command-line
argument.
For example::
@register_model_architecture('lstm', 'lstm_luong_wmt_en_de')
... | register_model_architecture | python | OFA-Sys/OFA | fairseq/fairseq/models/__init__.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/__init__.py | Apache-2.0 |
def encode(
self, sentence: str, *addl_sentences, no_separator=True
) -> torch.LongTensor:
"""
BPE-encode a sentence (or multiple sentences).
Every sequence begins with a beginning-of-sentence (`<s>`) symbol.
Every sentence ends with an end-of-sentence (`</s>`).
Exa... |
BPE-encode a sentence (or multiple sentences).
Every sequence begins with a beginning-of-sentence (`<s>`) symbol.
Every sentence ends with an end-of-sentence (`</s>`).
Example (single sentence): `<s> a b c </s>`
Example (sentence pair): `<s> d e f </s> 1 2 3 </s>`
The... | encode | python | OFA-Sys/OFA | fairseq/fairseq/models/bart/hub_interface.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/bart/hub_interface.py | Apache-2.0 |
def __init__(self, model, config, device=None):
"""
@param model model to initialize the EMA with
@param config EMAConfig object with configuration like
ema_decay, ema_update_freq, ema_fp32
@param device If provided, copy EMA to this device (e.g. gpu).
Otherwise EMA is in... |
@param model model to initialize the EMA with
@param config EMAConfig object with configuration like
ema_decay, ema_update_freq, ema_fp32
@param device If provided, copy EMA to this device (e.g. gpu).
Otherwise EMA is in the same device as the model.
| __init__ | python | OFA-Sys/OFA | fairseq/fairseq/models/ema/ema.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/ema/ema.py | Apache-2.0 |
def build_fp32_params(self, state_dict=None):
"""
Store a copy of the EMA params in fp32.
If state dict is passed, the EMA params is copied from
the provided state dict. Otherwise, it is copied from the
current EMA model parameters.
"""
if not self.config.ema_fp32... |
Store a copy of the EMA params in fp32.
If state dict is passed, the EMA params is copied from
the provided state dict. Otherwise, it is copied from the
current EMA model parameters.
| build_fp32_params | python | OFA-Sys/OFA | fairseq/fairseq/models/ema/ema.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/ema/ema.py | Apache-2.0 |
def restore(self, state_dict, build_fp32_params=False):
""" Load data from a model spec into EMA model """
self.model.load_state_dict(state_dict, strict=False)
if build_fp32_params:
self.build_fp32_params(state_dict) | Load data from a model spec into EMA model | restore | python | OFA-Sys/OFA | fairseq/fairseq/models/ema/ema.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/ema/ema.py | Apache-2.0 |
def _step_internal(self, new_model, updates=None):
""" One update of the EMA model based on new model weights """
decay = self.decay
ema_state_dict = {}
ema_params = self.fp32_params if self.config.ema_fp32 else self.model.state_dict()
for key, param in new_model.state_dict().it... | One update of the EMA model based on new model weights | _step_internal | python | OFA-Sys/OFA | fairseq/fairseq/models/ema/ema.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/ema/ema.py | Apache-2.0 |
def step(self, new_model, updates=None):
"""
One update of EMA which is done every self.config.ema_update_freq
updates of the model.
@param updates The current number of model updates done.
Decay is set of 0 if model updates < ema_start_update, which means
the model will... |
One update of EMA which is done every self.config.ema_update_freq
updates of the model.
@param updates The current number of model updates done.
Decay is set of 0 if model updates < ema_start_update, which means
the model will be simply copied over to the EMA.
When mode... | step | python | OFA-Sys/OFA | fairseq/fairseq/models/ema/ema.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/ema/ema.py | Apache-2.0 |
def extract_features(
self,
prev_output_tokens,
encoder_out=None,
early_exit=None,
layers=None,
**unused
):
"""
Similar to *forward* but only return features.
Inputs:
prev_output_tokens: Tensor(B, T)
encoder_out: a dicti... |
Similar to *forward* but only return features.
Inputs:
prev_output_tokens: Tensor(B, T)
encoder_out: a dictionary of hidden states and masks
Returns:
tuple:
- the decoder's features of shape `(batch, tgt_len, embed_dim)`
- a d... | extract_features | python | OFA-Sys/OFA | fairseq/fairseq/models/nat/levenshtein_transformer.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/nat/levenshtein_transformer.py | Apache-2.0 |
def _skip(x, mask):
"""
Getting sliced (dim=0) tensor by mask. Supporting tensor and list/dict of tensors.
"""
if isinstance(x, int):
return x
if x is None:
return None
if isinstance(x, torch.Tensor):
if x.size(0) == mask.size(0):
return x[mask]
elif... |
Getting sliced (dim=0) tensor by mask. Supporting tensor and list/dict of tensors.
| _skip | python | OFA-Sys/OFA | fairseq/fairseq/models/nat/levenshtein_utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/nat/levenshtein_utils.py | Apache-2.0 |
def extract_features(
self,
prev_output_tokens,
encoder_out=None,
early_exit=None,
embedding_copy=False,
**unused
):
"""
Similar to *forward* but only return features.
Inputs:
prev_output_tokens: Tensor(B, T)
encoder_ou... |
Similar to *forward* but only return features.
Inputs:
prev_output_tokens: Tensor(B, T)
encoder_out: a dictionary of hidden states and masks
Returns:
tuple:
- the decoder's features of shape `(batch, tgt_len, embed_dim)`
- a ... | extract_features | python | OFA-Sys/OFA | fairseq/fairseq/models/nat/nonautoregressive_transformer.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/nat/nonautoregressive_transformer.py | Apache-2.0 |
def align_bpe_to_words(roberta, bpe_tokens: torch.LongTensor, other_tokens: List[str]):
"""
Helper to align GPT-2 BPE to other tokenization formats (e.g., spaCy).
Args:
roberta (RobertaHubInterface): RoBERTa instance
bpe_tokens (torch.LongTensor): GPT-2 BPE tokens of shape `(T_bpe)`
... |
Helper to align GPT-2 BPE to other tokenization formats (e.g., spaCy).
Args:
roberta (RobertaHubInterface): RoBERTa instance
bpe_tokens (torch.LongTensor): GPT-2 BPE tokens of shape `(T_bpe)`
other_tokens (List[str]): other tokens of shape `(T_words)`
Returns:
List[str]: m... | align_bpe_to_words | python | OFA-Sys/OFA | fairseq/fairseq/models/roberta/alignment_utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/roberta/alignment_utils.py | Apache-2.0 |
def align_features_to_words(roberta, features, alignment):
"""
Align given features to words.
Args:
roberta (RobertaHubInterface): RoBERTa instance
features (torch.Tensor): features to align of shape `(T_bpe x C)`
alignment: alignment between BPE tokens and words returned by
... |
Align given features to words.
Args:
roberta (RobertaHubInterface): RoBERTa instance
features (torch.Tensor): features to align of shape `(T_bpe x C)`
alignment: alignment between BPE tokens and words returned by
func:`align_bpe_to_words`.
| align_features_to_words | python | OFA-Sys/OFA | fairseq/fairseq/models/roberta/alignment_utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/roberta/alignment_utils.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.