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 load_pretrained_component_from_model(
component: Union[FairseqEncoder, FairseqDecoder], checkpoint: str
):
"""
Load a pretrained FairseqEncoder or FairseqDecoder from checkpoint into the
provided `component` object. If state_dict fails to load, there may be a
mismatch in the architecture of the ... |
Load a pretrained FairseqEncoder or FairseqDecoder from checkpoint into the
provided `component` object. If state_dict fails to load, there may be a
mismatch in the architecture of the corresponding `component` found in the
`checkpoint` file.
| load_pretrained_component_from_model | python | OFA-Sys/OFA | fairseq/fairseq/checkpoint_utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/checkpoint_utils.py | Apache-2.0 |
def load_ema_from_checkpoint(fpath):
"""Loads exponential moving averaged (EMA) checkpoint from input and
returns a model with ema weights.
Args:
fpath: A string path of checkpoint to load from.
Returns:
A dict of string keys mapping to various values. The 'model' key
from the return... | Loads exponential moving averaged (EMA) checkpoint from input and
returns a model with ema weights.
Args:
fpath: A string path of checkpoint to load from.
Returns:
A dict of string keys mapping to various values. The 'model' key
from the returned dict should correspond to an OrderedDict ... | load_ema_from_checkpoint | python | OFA-Sys/OFA | fairseq/fairseq/checkpoint_utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/checkpoint_utils.py | Apache-2.0 |
def find_offsets(filename: str, num_chunks: int) -> tp.List[int]:
"""
given a file and a number of chuncks, find the offsets in the file
to be able to chunk around full lines.
"""
with open(filename, "r", encoding="utf-8") as f:
size = os.fstat(f.fileno()).st_size
chunk_size = size /... |
given a file and a number of chuncks, find the offsets in the file
to be able to chunk around full lines.
| find_offsets | python | OFA-Sys/OFA | fairseq/fairseq/file_chunker_utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/file_chunker_utils.py | Apache-2.0 |
def path_requires_pathmanager(path: str) -> bool:
"""Do we require PathManager to access given path?"""
if IOPathManager:
for p in IOPathManager._path_handlers.keys():
if path.startswith(p):
return True
return False | Do we require PathManager to access given path? | path_requires_pathmanager | python | OFA-Sys/OFA | fairseq/fairseq/file_io.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/file_io.py | Apache-2.0 |
def opena(
path: str,
mode: str = "r",
buffering: int = -1,
encoding: Optional[str] = None,
errors: Optional[str] = None,
newline: Optional[str] = None,
):
"""
Return file descriptor with asynchronous write operations.
"""
global IOPath... |
Return file descriptor with asynchronous write operations.
| opena | python | OFA-Sys/OFA | fairseq/fairseq/file_io.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/file_io.py | Apache-2.0 |
def async_close() -> bool:
"""
Wait for files to be written and clean up asynchronous PathManager.
NOTE: `PathManager.async_close()` must be called at the end of any
script that uses `PathManager.opena(...)`.
"""
global IOPathManager
if IOPathManager:
... |
Wait for files to be written and clean up asynchronous PathManager.
NOTE: `PathManager.async_close()` must be called at the end of any
script that uses `PathManager.opena(...)`.
| async_close | python | OFA-Sys/OFA | fairseq/fairseq/file_io.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/file_io.py | Apache-2.0 |
def cached_path_from_pm(url_or_filename):
"""
Tries to cache the specified URL using PathManager class.
Returns the cached path if success otherwise failure.
"""
try:
from fairseq.file_io import PathManager
local_path = PathManager.get_local_path(url_or_filename)
return local... |
Tries to cache the specified URL using PathManager class.
Returns the cached path if success otherwise failure.
| cached_path_from_pm | python | OFA-Sys/OFA | fairseq/fairseq/file_utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/file_utils.py | Apache-2.0 |
def get_incremental_state(
self,
incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]],
key: str,
) -> Optional[Dict[str, Optional[Tensor]]]:
"""Helper for getting incremental state for an nn.Module."""
full_key = self._get_full_incremental_state_key(key)
... | Helper for getting incremental state for an nn.Module. | get_incremental_state | python | OFA-Sys/OFA | fairseq/fairseq/incremental_decoding_utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/incremental_decoding_utils.py | Apache-2.0 |
def set_incremental_state(
self,
incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]],
key: str,
value: Dict[str, Optional[Tensor]],
) -> Optional[Dict[str, Dict[str, Optional[Tensor]]]]:
"""Helper for setting incremental state for an nn.Module."""
if i... | Helper for setting incremental state for an nn.Module. | set_incremental_state | python | OFA-Sys/OFA | fairseq/fairseq/incremental_decoding_utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/incremental_decoding_utils.py | Apache-2.0 |
def __init__(
self,
tgt_dict,
models=None,
eos_penalty=0.0,
max_iter=10,
max_ratio=2,
beam_size=1,
decoding_format=None,
retain_dropout=False,
adaptive=True,
retain_history=False,
reranking=False,
):
"""
... |
Generates translations based on iterative refinement.
Args:
tgt_dict: target dictionary
eos_penalty: if > 0.0, it penalized early-stopping in decoding
max_iter: maximum number of refinement iterations
max_ratio: generate sequences of maximum length ax, w... | __init__ | python | OFA-Sys/OFA | fairseq/fairseq/iterative_refinement_generator.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/iterative_refinement_generator.py | Apache-2.0 |
def generate_batched_itr(
self,
data_itr,
maxlen_a=None,
maxlen_b=None,
cuda=False,
timer=None,
prefix_size=0,
):
"""Iterate over a batched dataset and yield individual translations.
Args:
maxlen_a/b: generate sequences of maximum ... | Iterate over a batched dataset and yield individual translations.
Args:
maxlen_a/b: generate sequences of maximum length ax + b,
where x is the source sentence length.
cuda: use GPU for generation
timer: StopwatchMeter for timing generations.
| generate_batched_itr | python | OFA-Sys/OFA | fairseq/fairseq/iterative_refinement_generator.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/iterative_refinement_generator.py | Apache-2.0 |
def forward(
self,
tokens,
lprobs,
bsz: int,
beam_size: int,
step: int,
):
"""
Args:
tokens(Tensor): Input tokens(Bsz*beam, seq_len)
lprobs(Tensor): likelihood probability,
Expected to be updated in place.(Bsz*beam, ... |
Args:
tokens(Tensor): Input tokens(Bsz*beam, seq_len)
lprobs(Tensor): likelihood probability,
Expected to be updated in place.(Bsz*beam, vocab_size)
bsz(int): batch size
step(int): current step
beam_size(int): beam size
no_repe... | forward | python | OFA-Sys/OFA | fairseq/fairseq/ngram_repeat_block.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/ngram_repeat_block.py | Apache-2.0 |
def _no_repeat_ngram(self, tokens, lprobs, bsz: int, beam_size: int, step: int):
"""For each hypothesis generate a list of previous ngrams and set associated lprobs to -inf"""
gen_ngrams: List[Dict[str, List[int]]] = [
torch.jit.annotate(Dict[str, List[int]], {})
for bbsz_idx in ... | For each hypothesis generate a list of previous ngrams and set associated lprobs to -inf | _no_repeat_ngram | python | OFA-Sys/OFA | fairseq/fairseq/ngram_repeat_block.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/ngram_repeat_block.py | Apache-2.0 |
def parse_args_and_arch(
parser: argparse.ArgumentParser,
input_args: List[str] = None,
parse_known: bool = False,
suppress_defaults: bool = False,
modify_parser: Optional[Callable[[argparse.ArgumentParser], None]] = None,
):
"""
Args:
parser (ArgumentParser): the parser
inpu... |
Args:
parser (ArgumentParser): the parser
input_args (List[str]): strings to parse, defaults to sys.argv
parse_known (bool): only parse known arguments, similar to
`ArgumentParser.parse_known_args`
suppress_defaults (bool): parse while ignoring all default values
... | parse_args_and_arch | python | OFA-Sys/OFA | fairseq/fairseq/options.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/options.py | Apache-2.0 |
def step(self):
"""Move to the next stage of quantization."""
if self.quantization_step >= len(self.layers_to_quantize):
# Maybe we just finished the last training step or we loaded
# a checkpoint for an iterative PQ model which previously
# finished training. Either ... | Move to the next stage of quantization. | step | python | OFA-Sys/OFA | fairseq/fairseq/quantization_utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/quantization_utils.py | Apache-2.0 |
def begin_epoch(self, epoch):
"""Called at the beginning of each epoch (epochs start at 1)."""
if (
(
self.epoch_schedule is not None
and epoch > 0
and (epoch - 1) % self.epoch_schedule == 0
)
# we always step once in th... | Called at the beginning of each epoch (epochs start at 1). | begin_epoch | python | OFA-Sys/OFA | fairseq/fairseq/quantization_utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/quantization_utils.py | Apache-2.0 |
def step_update(self, num_updates):
"""Called at the end of each step."""
if (
self.update_schedule is not None
and num_updates > 0
and num_updates % self.update_schedule == 0
):
self.step() | Called at the end of each step. | step_update | python | OFA-Sys/OFA | fairseq/fairseq/quantization_utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/quantization_utils.py | Apache-2.0 |
def step(
self, step, lprobs, scores, prev_output_tokens=None, original_batch_idxs=None
):
"""Take a single search step.
Args:
step: the current search step, starting at 0
lprobs: (bsz x input_beam_size x vocab_size)
the model's log-probabilities over... | Take a single search step.
Args:
step: the current search step, starting at 0
lprobs: (bsz x input_beam_size x vocab_size)
the model's log-probabilities over the vocabulary at the current step
scores: (bsz x input_beam_size x step)
the histori... | step | python | OFA-Sys/OFA | fairseq/fairseq/search.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/search.py | Apache-2.0 |
def step(
self,
step: int,
lprobs: Tensor,
scores: Optional[Tensor],
prev_output_tokens: Optional[Tensor] = None,
original_batch_idxs: Optional[Tensor] = None,
):
"""
A constrained step builds a large candidates list from the following:
- the t... |
A constrained step builds a large candidates list from the following:
- the top 2 * {beam_size} items over the whole beam
- for each item in the beam
- the top {each_k} (default 1)
- all next constraints
We then compute the constrained state of each beam item, and as... | step | python | OFA-Sys/OFA | fairseq/fairseq/search.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/search.py | Apache-2.0 |
def step_sentence(
self,
step: int,
sentno: int,
lprobs: Tensor,
constraint_states: List[List[ConstraintState]],
beams_buf: Tensor,
indices_buf: Tensor,
scores_buf: Tensor,
):
"""Does per-sentence processing. Adds all constraints for each
... | Does per-sentence processing. Adds all constraints for each
hypothesis to the list of candidates; then removes duplicates,
sorts, and dynamically stripes across the banks. All tensor inputs
are collapsed to those pertaining to a single input sentence.
| step_sentence | python | OFA-Sys/OFA | fairseq/fairseq/search.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/search.py | Apache-2.0 |
def _sample_topp(self, lprobs):
"""Sample among the smallest set of elements whose cumulative probability mass exceeds p.
See `"The Curious Case of Neural Text Degeneration"
(Holtzman et al., 2019) <https://arxiv.org/abs/1904.09751>`_.
Args:
lprobs: (bsz x input_beam_size x... | Sample among the smallest set of elements whose cumulative probability mass exceeds p.
See `"The Curious Case of Neural Text Degeneration"
(Holtzman et al., 2019) <https://arxiv.org/abs/1904.09751>`_.
Args:
lprobs: (bsz x input_beam_size x vocab_size)
the model's lo... | _sample_topp | python | OFA-Sys/OFA | fairseq/fairseq/search.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/search.py | Apache-2.0 |
def __init__(
self,
models,
tgt_dict,
beam_size=1,
max_len_a=0,
max_len_b=200,
max_len=0,
min_len=1,
normalize_scores=True,
len_penalty=1.0,
unk_penalty=0.0,
temperature=1.0,
match_source_len=False,
no_repeat... | Generates translations of a given source sentence.
Args:
models (List[~fairseq.models.FairseqModel]): ensemble of models,
currently support fairseq.models.TransformerModel for scripting
beam_size (int, optional): beam width (default: 1)
max_len_a/b (int, opti... | __init__ | python | OFA-Sys/OFA | fairseq/fairseq/sequence_generator.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/sequence_generator.py | Apache-2.0 |
def forward(
self,
sample: Dict[str, Dict[str, Tensor]],
prefix_tokens: Optional[Tensor] = None,
bos_token: Optional[int] = None,
):
"""Generate a batch of translations.
Args:
sample (dict): batch
prefix_tokens (torch.LongTensor, optional): fo... | Generate a batch of translations.
Args:
sample (dict): batch
prefix_tokens (torch.LongTensor, optional): force decoder to begin
with these tokens
bos_token (int, optional): beginning of sentence token
(default: self.eos)
| forward | python | OFA-Sys/OFA | fairseq/fairseq/sequence_generator.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/sequence_generator.py | Apache-2.0 |
def generate_batched_itr(self, data_itr, beam_size=None, cuda=False, timer=None):
"""Iterate over a batched dataset and yield individual translations.
Args:
cuda (bool, optional): use GPU for generation
timer (StopwatchMeter, optional): time generations
"""
for sa... | Iterate over a batched dataset and yield individual translations.
Args:
cuda (bool, optional): use GPU for generation
timer (StopwatchMeter, optional): time generations
| generate_batched_itr | python | OFA-Sys/OFA | fairseq/fairseq/sequence_generator.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/sequence_generator.py | Apache-2.0 |
def finalize_hypos(
self,
step: int,
bbsz_idx,
eos_scores,
tokens,
scores,
finalized: List[List[Dict[str, Tensor]]],
finished: List[bool],
beam_size: int,
attn: Optional[Tensor],
src_lengths,
max_len: int,
):
"""... | Finalize hypothesis, store finalized information in `finalized`, and change `finished` accordingly.
A sentence is finalized when {beam_size} finished items have been collected for it.
Returns number of sentences (not beam items) being finalized.
These will be removed from the batch and not proc... | finalize_hypos | python | OFA-Sys/OFA | fairseq/fairseq/sequence_generator.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/sequence_generator.py | Apache-2.0 |
def is_finished(
self,
step: int,
unfin_idx: int,
max_len: int,
finalized_sent_len: int,
beam_size: int,
):
"""
Check whether decoding for a sentence is finished, which
occurs when the list of finalized sentences has reached the
beam si... |
Check whether decoding for a sentence is finished, which
occurs when the list of finalized sentences has reached the
beam size, or when we reach the maximum length.
| is_finished | python | OFA-Sys/OFA | fairseq/fairseq/sequence_generator.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/sequence_generator.py | Apache-2.0 |
def reorder_encoder_out(
self, encoder_outs: Optional[List[Dict[str, List[Tensor]]]], new_order
):
"""
Reorder encoder output according to *new_order*.
Args:
encoder_out: output from the ``forward()`` method
new_order (LongTensor): desired order
Retu... |
Reorder encoder output according to *new_order*.
Args:
encoder_out: output from the ``forward()`` method
new_order (LongTensor): desired order
Returns:
*encoder_out* rearranged according to *new_order*
| reorder_encoder_out | python | OFA-Sys/OFA | fairseq/fairseq/sequence_generator.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/sequence_generator.py | Apache-2.0 |
def __init__(
self, models, tgt_dict, left_pad_target=False, print_alignment="hard", **kwargs
):
"""Generates translations of a given source sentence.
Produces alignments following "Jointly Learning to Align and
Translate with Transformer Models" (Garg et al., EMNLP 2019).
... | Generates translations of a given source sentence.
Produces alignments following "Jointly Learning to Align and
Translate with Transformer Models" (Garg et al., EMNLP 2019).
Args:
left_pad_target (bool, optional): Whether or not the
hypothesis should be left padded ... | __init__ | python | OFA-Sys/OFA | fairseq/fairseq/sequence_generator.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/sequence_generator.py | Apache-2.0 |
def pack_constraints(batch_constraints: List[List[torch.Tensor]]) -> torch.Tensor:
"""Takes a list of list of constraints in tensor form (a list of
tensor constraints for each sentence) and transforms it into a
packed Tensor. For example, here is a batch of size 3 with 3, 0,
and 1 constraints:
... | Takes a list of list of constraints in tensor form (a list of
tensor constraints for each sentence) and transforms it into a
packed Tensor. For example, here is a batch of size 3 with 3, 0,
and 1 constraints:
[ [ [3 1 2], [3], [4 5 6 7], ]
[],
[ [1 8 9 10 1 4 11 12], ]
]... | pack_constraints | python | OFA-Sys/OFA | fairseq/fairseq/token_generation_constraints.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/token_generation_constraints.py | Apache-2.0 |
def unpack_constraints(constraint_tensor: torch.Tensor) -> List[torch.Tensor]:
"""
Transforms *one row* of a packed constraint tensor (e.g., for one
sentence in the batch) into a list of constraint tensors.
"""
constraint_list = []
num_constraints = constraint_tensor[0]
constraints = constra... |
Transforms *one row* of a packed constraint tensor (e.g., for one
sentence in the batch) into a list of constraint tensors.
| unpack_constraints | python | OFA-Sys/OFA | fairseq/fairseq/token_generation_constraints.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/token_generation_constraints.py | Apache-2.0 |
def token_counts(self) -> Counter:
"""Returns a counter of the number of times each token is used
in a constraint.
"""
token_counts = Counter()
kids = list(self.children.values())
while len(kids) > 0:
kid = kids.pop()
token_counts[kid.id] += kid.nu... | Returns a counter of the number of times each token is used
in a constraint.
| token_counts | python | OFA-Sys/OFA | fairseq/fairseq/token_generation_constraints.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/token_generation_constraints.py | Apache-2.0 |
def add_sequence(self, sequence: List[int]):
"""Adds a constraint, represented as a list of integers, to
the trie."""
assert len(sequence) > 0
token = int(sequence[0])
if token not in self.children:
self.children[token] = ConstraintNode(token, parent=self)
n... | Adds a constraint, represented as a list of integers, to
the trie. | add_sequence | python | OFA-Sys/OFA | fairseq/fairseq/token_generation_constraints.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/token_generation_constraints.py | Apache-2.0 |
def num_completed(self):
"""The number of constraints (not constraint tokens) that are completed.
In addition to the already-completed states, we need to account for the
current state, which might get marked as completed when another token
is generated.
"""
in_final = sel... | The number of constraints (not constraint tokens) that are completed.
In addition to the already-completed states, we need to account for the
current state, which might get marked as completed when another token
is generated.
| num_completed | python | OFA-Sys/OFA | fairseq/fairseq/token_generation_constraints.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/token_generation_constraints.py | Apache-2.0 |
def next_tokens(self) -> Set[int]:
"""Returns the list of tokens that could come next.
These are (a) all tokens extending the root state and, for
non-root states, additionally all tokens extending the current
state."""
if self.node != self.root:
return self.root.next... | Returns the list of tokens that could come next.
These are (a) all tokens extending the root state and, for
non-root states, additionally all tokens extending the current
state. | next_tokens | python | OFA-Sys/OFA | fairseq/fairseq/token_generation_constraints.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/token_generation_constraints.py | Apache-2.0 |
def advance(self, token: int):
"""Reads in a token and advances the state. Here's how it works.
We can advance to the next state if:
- there is a matching child
- its path isn't blocked
A path is blocked when all constraints that are descendants of
that node have alread... | Reads in a token and advances the state. Here's how it works.
We can advance to the next state if:
- there is a matching child
- its path isn't blocked
A path is blocked when all constraints that are descendants of
that node have already been generated, in the current state.
... | advance | python | OFA-Sys/OFA | fairseq/fairseq/token_generation_constraints.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/token_generation_constraints.py | Apache-2.0 |
def rewind():
"""If we're mid-trie and an "illegal" token is chosen next, we need
to reset our state to the root state. However, along the way, we need
to check whether a prefix of the current trie state represents a state
we could mark as completed.
"""
... | If we're mid-trie and an "illegal" token is chosen next, we need
to reset our state to the root state. However, along the way, we need
to check whether a prefix of the current trie state represents a state
we could mark as completed.
| rewind | python | OFA-Sys/OFA | fairseq/fairseq/token_generation_constraints.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/token_generation_constraints.py | Apache-2.0 |
def __init__(self, sequences: List[List[int]]):
"""Represents a set of possibly multitoken constraints by
concatenating them and internally recording the end points.
"""
self.sequences = []
self.endpoints = []
self.num_tokens = 0
self.tokens = set()
for se... | Represents a set of possibly multitoken constraints by
concatenating them and internally recording the end points.
| __init__ | python | OFA-Sys/OFA | fairseq/fairseq/token_generation_constraints.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/token_generation_constraints.py | Apache-2.0 |
def parse_embedding(embed_path):
"""Parse embedding text file into a dictionary of word and embedding tensors.
The first line can have vocabulary size and dimension. The following lines
should contain word and embedding separated by spaces.
Example:
2 5
the -0.0230 -0.0264 0.0287 0.0... | Parse embedding text file into a dictionary of word and embedding tensors.
The first line can have vocabulary size and dimension. The following lines
should contain word and embedding separated by spaces.
Example:
2 5
the -0.0230 -0.0264 0.0287 0.0171 0.1403
at -0.0395 -0.1286 ... | parse_embedding | python | OFA-Sys/OFA | fairseq/fairseq/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/utils.py | Apache-2.0 |
def make_positions(tensor, padding_idx: int, onnx_trace: bool = False):
"""Replace non-padding symbols with their position numbers.
Position numbers begin at padding_idx+1. Padding symbols are ignored.
"""
# The series of casts and type-conversions here are carefully
# balanced to both work with ON... | Replace non-padding symbols with their position numbers.
Position numbers begin at padding_idx+1. Padding symbols are ignored.
| make_positions | python | OFA-Sys/OFA | fairseq/fairseq/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/utils.py | Apache-2.0 |
def _match_types(arg1, arg2):
"""Convert the numerical argument to the same type as the other argument"""
def upgrade(arg_number, arg_structure):
if isinstance(arg_structure, tuple):
return tuple([arg_number] * len(arg_structure))
elif isinstance(arg_structure, dict):
ar... | Convert the numerical argument to the same type as the other argument | _match_types | python | OFA-Sys/OFA | fairseq/fairseq/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/utils.py | Apache-2.0 |
def resolve_max_positions(*args):
"""Resolve max position constraints from multiple sources."""
def map_value_update(d1, d2):
updated_value = copy.deepcopy(d1)
for key in d2:
if key not in updated_value:
updated_value[key] = d2[key]
else:
... | Resolve max position constraints from multiple sources. | resolve_max_positions | python | OFA-Sys/OFA | fairseq/fairseq/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/utils.py | Apache-2.0 |
def get_activation_fn(activation: str) -> Callable:
"""Returns the activation function corresponding to `activation`"""
from fairseq.modules import gelu, gelu_accurate
if activation == "relu":
return F.relu
elif activation == "gelu":
return gelu
elif activation == "gelu_fast":
... | Returns the activation function corresponding to `activation` | get_activation_fn | python | OFA-Sys/OFA | fairseq/fairseq/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/utils.py | Apache-2.0 |
def parse_alignment(line):
"""
Parses a single line from the alingment file.
Args:
line (str): String containing the alignment of the format:
<src_idx_1>-<tgt_idx_1> <src_idx_2>-<tgt_idx_2> ..
<src_idx_m>-<tgt_idx_m>. All indices are 0 indexed.
Returns:
torch.In... |
Parses a single line from the alingment file.
Args:
line (str): String containing the alignment of the format:
<src_idx_1>-<tgt_idx_1> <src_idx_2>-<tgt_idx_2> ..
<src_idx_m>-<tgt_idx_m>. All indices are 0 indexed.
Returns:
torch.IntTensor: packed alignments of shap... | parse_alignment | python | OFA-Sys/OFA | fairseq/fairseq/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/utils.py | Apache-2.0 |
def new_arange(x, *size):
"""
Return a Tensor of `size` filled with a range function on the device of x.
If size is empty, using the size of the variable x.
"""
if len(size) == 0:
size = x.size()
return torch.arange(size[-1], device=x.device).expand(*size).contiguous() |
Return a Tensor of `size` filled with a range function on the device of x.
If size is empty, using the size of the variable x.
| new_arange | python | OFA-Sys/OFA | fairseq/fairseq/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/utils.py | Apache-2.0 |
def pretty_print_cuda_env_list(cuda_env_list):
"""
Given a list of CudaEnviorments, pretty print them
"""
num_workers = len(cuda_env_list)
center = "CUDA enviroments for all {} workers".format(num_workers)
banner_len = 40 - len(center) // 2
first_line = "*" * bann... |
Given a list of CudaEnviorments, pretty print them
| pretty_print_cuda_env_list | python | OFA-Sys/OFA | fairseq/fairseq/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/utils.py | Apache-2.0 |
def safe_getattr(obj, k, default=None):
"""Returns obj[k] if it exists and is not None, otherwise returns default."""
from omegaconf import OmegaConf
if OmegaConf.is_config(obj):
return obj[k] if k in obj and obj[k] is not None else default
return getattr(obj, k, default) | Returns obj[k] if it exists and is not None, otherwise returns default. | safe_getattr | python | OFA-Sys/OFA | fairseq/fairseq/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/utils.py | Apache-2.0 |
def load_dataset(self, split, epoch=1, combine=False, **kwargs):
"""Load a given dataset split.
Args:
split (str): name of the split (e.g., train, valid, test)
"""
if self.cfg.batch_size is not None:
bsz = self.cfg.batch_size
else:
bsz = max(1,... | Load a given dataset split.
Args:
split (str): name of the split (e.g., train, valid, test)
| load_dataset | python | OFA-Sys/OFA | fairseq/fairseq/benchmark/dummy_lm.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/benchmark/dummy_lm.py | Apache-2.0 |
def build_criterion(cls, cfg: FairseqDataclass, task):
"""Construct a criterion from command-line args."""
# arguments in the __init__.
init_args = {}
for p in inspect.signature(cls).parameters.values():
if (
p.kind == p.POSITIONAL_ONLY
or p.ki... | Construct a criterion from command-line args. | build_criterion | python | OFA-Sys/OFA | fairseq/fairseq/criterions/fairseq_criterion.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/criterions/fairseq_criterion.py | Apache-2.0 |
def forward(self, model, sample, reduce=True, log_pred=False):
"""Compute the loss for the given sample.
Returns a tuple with three elements:
1) the loss
2) the sample size, which is used as the denominator for the gradient
3) logging outputs to display while training
"""... | Compute the loss for the given sample.
Returns a tuple with three elements:
1) the loss
2) the sample size, which is used as the denominator for the gradient
3) logging outputs to display while training
| forward | python | OFA-Sys/OFA | fairseq/fairseq/criterions/hubert_criterion.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/criterions/hubert_criterion.py | Apache-2.0 |
def reduce_metrics(logging_outputs) -> None:
"""Aggregate logging outputs from data parallel training (copied from normal cross entropy)."""
loss_sum = sum(log.get("loss", 0) for log in logging_outputs)
ntokens = sum(log.get("ntokens", 0) for log in logging_outputs)
sample_size = sum(log... | Aggregate logging outputs from data parallel training (copied from normal cross entropy). | reduce_metrics | python | OFA-Sys/OFA | fairseq/fairseq/criterions/hubert_criterion.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/criterions/hubert_criterion.py | Apache-2.0 |
def compute_cross_entropy_loss(logits, targets, ignore_index=-100):
"""
Function to compute the cross entropy loss. The default value of
ignore_index is the same as the default value for F.cross_entropy in
pytorch.
"""
assert logits.size(0) == targets.size(
-1
), "Logits and Targets ... |
Function to compute the cross entropy loss. The default value of
ignore_index is the same as the default value for F.cross_entropy in
pytorch.
| compute_cross_entropy_loss | python | OFA-Sys/OFA | fairseq/fairseq/criterions/legacy_masked_lm.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/criterions/legacy_masked_lm.py | Apache-2.0 |
def _compute_loss(
self, outputs, targets, masks=None, label_smoothing=0.0, name="loss", factor=1.0
):
"""
outputs: batch x len x d_model
targets: batch x len
masks: batch x len
policy_logprob: if there is some policy
depends on the likelihood score as ... |
outputs: batch x len x d_model
targets: batch x len
masks: batch x len
policy_logprob: if there is some policy
depends on the likelihood score as rewards.
| _compute_loss | python | OFA-Sys/OFA | fairseq/fairseq/criterions/nat_loss.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/criterions/nat_loss.py | Apache-2.0 |
def forward(self, model, sample, reduce=True):
"""Compute ranking loss for the given sample.
Returns a tuple with three elements:
1) the loss
2) the sample size, which is used as the denominator for the gradient
3) logging outputs to display while training
"""
as... | Compute ranking loss for the given sample.
Returns a tuple with three elements:
1) the loss
2) the sample size, which is used as the denominator for the gradient
3) logging outputs to display while training
| forward | python | OFA-Sys/OFA | fairseq/fairseq/criterions/sentence_ranking.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/criterions/sentence_ranking.py | Apache-2.0 |
def logging_outputs_can_be_summed(self) -> bool:
"""
Whether the logging outputs returned by `forward` can be summed
across workers prior to calling `reduce_metrics`. Setting this
to True will improves distributed training speed.
"""
# XXX: Gather based reduction not impl... |
Whether the logging outputs returned by `forward` can be summed
across workers prior to calling `reduce_metrics`. Setting this
to True will improves distributed training speed.
| logging_outputs_can_be_summed | python | OFA-Sys/OFA | fairseq/fairseq/criterions/wav2vec_criterion.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/criterions/wav2vec_criterion.py | Apache-2.0 |
def backtranslate_samples(samples, collate_fn, generate_fn, cuda=True):
"""Backtranslate a list of samples.
Given an input (*samples*) of the form:
[{'id': 1, 'source': 'hallo welt'}]
this will return:
[{'id': 1, 'source': 'hello world', 'target': 'hallo welt'}]
Args:
sample... | Backtranslate a list of samples.
Given an input (*samples*) of the form:
[{'id': 1, 'source': 'hallo welt'}]
this will return:
[{'id': 1, 'source': 'hello world', 'target': 'hallo welt'}]
Args:
samples (List[dict]): samples to backtranslate. Individual samples are
ex... | backtranslate_samples | python | OFA-Sys/OFA | fairseq/fairseq/data/backtranslation_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/backtranslation_dataset.py | Apache-2.0 |
def collater(self, samples):
"""Merge and backtranslate a list of samples to form a mini-batch.
Using the samples from *tgt_dataset*, load a collated target sample to
feed to the backtranslation model. Then take the backtranslation with
the best score as the source and the original inpu... | Merge and backtranslate a list of samples to form a mini-batch.
Using the samples from *tgt_dataset*, load a collated target sample to
feed to the backtranslation model. Then take the backtranslation with
the best score as the source and the original input as the target.
Note: we expec... | collater | python | OFA-Sys/OFA | fairseq/fairseq/data/backtranslation_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/backtranslation_dataset.py | Apache-2.0 |
def size(self, index):
"""Return an example's size as a float or tuple. This value is used
when filtering a dataset with ``--max-positions``.
Note: we use *tgt_dataset* to approximate the length of the source
sentence, since we do not know the actual length until after
backtrans... | Return an example's size as a float or tuple. This value is used
when filtering a dataset with ``--max-positions``.
Note: we use *tgt_dataset* to approximate the length of the source
sentence, since we do not know the actual length until after
backtranslation.
| size | python | OFA-Sys/OFA | fairseq/fairseq/data/backtranslation_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/backtranslation_dataset.py | Apache-2.0 |
def ordered_indices(self):
"""
Returns indices sorted by length. So less padding is needed.
"""
if isinstance(self.sizes, np.ndarray) and len(self.sizes.shape) > 1:
# special handling for concatenating lang_pair_datasets
indices = np.arange(len(self))
... |
Returns indices sorted by length. So less padding is needed.
| ordered_indices | python | OFA-Sys/OFA | fairseq/fairseq/data/concat_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/concat_dataset.py | Apache-2.0 |
def collater(self, samples, pad_to_length=None):
"""Merge a list of samples to form a mini-batch.
Args:
samples (List[dict]): samples to collate
Returns:
dict: a mini-batch of data
"""
return collate(
samples, self.vocab.pad(), self.eos, self.v... | Merge a list of samples to form a mini-batch.
Args:
samples (List[dict]): samples to collate
Returns:
dict: a mini-batch of data
| collater | python | OFA-Sys/OFA | fairseq/fairseq/data/denoising_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/denoising_dataset.py | Apache-2.0 |
def index(self, sym):
"""Returns the index of the specified symbol"""
assert isinstance(sym, str)
if sym in self.indices:
return self.indices[sym]
return self.unk_index | Returns the index of the specified symbol | index | python | OFA-Sys/OFA | fairseq/fairseq/data/dictionary.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/dictionary.py | Apache-2.0 |
def string(
self,
tensor,
bpe_symbol=None,
escape_unk=False,
extra_symbols_to_ignore=None,
unk_string=None,
include_eos=False,
separator=" ",
):
"""Helper for converting a tensor of token indices to a string.
Can optionally remove BPE ... | Helper for converting a tensor of token indices to a string.
Can optionally remove BPE symbols or escape <unk> words.
| string | python | OFA-Sys/OFA | fairseq/fairseq/data/dictionary.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/dictionary.py | Apache-2.0 |
def unk_string(self, escape=False):
"""Return unknown string, optionally escaped as: <<unk>>"""
if escape:
return "<{}>".format(self.unk_word)
else:
return self.unk_word | Return unknown string, optionally escaped as: <<unk>> | unk_string | python | OFA-Sys/OFA | fairseq/fairseq/data/dictionary.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/dictionary.py | Apache-2.0 |
def finalize(self, threshold=-1, nwords=-1, padding_factor=8):
"""Sort symbols by frequency in descending order, ignoring special ones.
Args:
- threshold defines the minimum word count
- nwords defines the total number of words in the final dictionary,
including ... | Sort symbols by frequency in descending order, ignoring special ones.
Args:
- threshold defines the minimum word count
- nwords defines the total number of words in the final dictionary,
including special symbols
- padding_factor can be used to pad the dictio... | finalize | python | OFA-Sys/OFA | fairseq/fairseq/data/dictionary.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/dictionary.py | Apache-2.0 |
def pad_to_multiple_(self, padding_factor):
"""Pad Dictionary size to be a multiple of *padding_factor*."""
if padding_factor > 1:
i = 0
while len(self) % padding_factor != 0:
symbol = "madeupword{:04d}".format(i)
self.add_symbol(symbol, n=0)
... | Pad Dictionary size to be a multiple of *padding_factor*. | pad_to_multiple_ | python | OFA-Sys/OFA | fairseq/fairseq/data/dictionary.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/dictionary.py | Apache-2.0 |
def load(cls, f):
"""Loads the dictionary from a text file with the format:
```
<symbol0> <count0>
<symbol1> <count1>
...
```
"""
d = cls()
d.add_from_file(f)
return d | Loads the dictionary from a text file with the format:
```
<symbol0> <count0>
<symbol1> <count1>
...
```
| load | python | OFA-Sys/OFA | fairseq/fairseq/data/dictionary.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/dictionary.py | Apache-2.0 |
def add_from_file(self, f):
"""
Loads a pre-existing dictionary from a text file and adds its symbols
to this instance.
"""
if isinstance(f, str):
try:
with open(PathManager.get_local_path(f), "r", encoding="utf-8") as fd:
self.add_... |
Loads a pre-existing dictionary from a text file and adds its symbols
to this instance.
| add_from_file | python | OFA-Sys/OFA | fairseq/fairseq/data/dictionary.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/dictionary.py | Apache-2.0 |
def batch_by_size(
self,
indices,
max_tokens=None,
max_sentences=None,
required_batch_size_multiple=1,
):
"""
Given an ordered set of indices, return batches according to
*max_tokens*, *max_sentences* and *required_batch_size_multiple*.
"""
... |
Given an ordered set of indices, return batches according to
*max_tokens*, *max_sentences* and *required_batch_size_multiple*.
| batch_by_size | python | OFA-Sys/OFA | fairseq/fairseq/data/fairseq_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/fairseq_dataset.py | Apache-2.0 |
def filter_indices_by_size(self, indices, max_sizes):
"""
Filter a list of sample indices. Remove those that are longer than
specified in *max_sizes*.
WARNING: don't update, override method in child classes
Args:
indices (np.array): original array of sample indices
... |
Filter a list of sample indices. Remove those that are longer than
specified in *max_sizes*.
WARNING: don't update, override method in child classes
Args:
indices (np.array): original array of sample indices
max_sizes (int or list[int] or tuple[int]): max sampl... | filter_indices_by_size | python | OFA-Sys/OFA | fairseq/fairseq/data/fairseq_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/fairseq_dataset.py | Apache-2.0 |
def skip(self, n):
"""Fast-forward the iterator by skipping n elements."""
for _ in range(n):
next(self)
return self | Fast-forward the iterator by skipping n elements. | skip | python | OFA-Sys/OFA | fairseq/fairseq/data/iterators.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/iterators.py | Apache-2.0 |
def take(self, n):
"""Truncate the iterator to n elements at most."""
self.total = min(self.total, n)
# Propagate this change to the underlying iterator
if hasattr(self._itr, "take"):
self._itr.take(max(n - self.n, 0))
return self | Truncate the iterator to n elements at most. | take | python | OFA-Sys/OFA | fairseq/fairseq/data/iterators.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/iterators.py | Apache-2.0 |
def next_epoch_itr(
self, shuffle=True, fix_batches_to_gpus=False, set_dataset_epoch=True
):
"""Return a new iterator over the dataset.
Args:
shuffle (bool, optional): shuffle batches before returning the
iterator (default: True).
fix_batches_to_gpus ... | Return a new iterator over the dataset.
Args:
shuffle (bool, optional): shuffle batches before returning the
iterator (default: True).
fix_batches_to_gpus (bool, optional): ensure that batches are always
allocated to the same shards across epochs. Require... | next_epoch_itr | python | OFA-Sys/OFA | fairseq/fairseq/data/iterators.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/iterators.py | Apache-2.0 |
def iterations_in_epoch(self):
"""The number of consumed batches in the current epoch."""
if self._cur_epoch_itr is not None:
return self._cur_epoch_itr.n
elif self._next_epoch_itr is not None:
return self._next_epoch_itr.n
return 0 | The number of consumed batches in the current epoch. | iterations_in_epoch | python | OFA-Sys/OFA | fairseq/fairseq/data/iterators.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/iterators.py | Apache-2.0 |
def state_dict(self):
"""Returns a dictionary containing a whole state of the iterator."""
if self.end_of_epoch():
epoch = self.epoch + 1
iter_in_epoch = 0
else:
epoch = self.epoch
iter_in_epoch = self.iterations_in_epoch
return {
... | Returns a dictionary containing a whole state of the iterator. | state_dict | python | OFA-Sys/OFA | fairseq/fairseq/data/iterators.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/iterators.py | Apache-2.0 |
def load_state_dict(self, state_dict):
"""Copies the state of the iterator from the given *state_dict*."""
self.epoch = state_dict["epoch"]
itr_pos = state_dict.get("iterations_in_epoch", 0)
version = state_dict.get("version", 1)
if itr_pos > 0:
# fast-forward epoch i... | Copies the state of the iterator from the given *state_dict*. | load_state_dict | python | OFA-Sys/OFA | fairseq/fairseq/data/iterators.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/iterators.py | Apache-2.0 |
def compute_alignment_weights(alignments):
"""
Given a tensor of shape [:, 2] containing the source-target indices
corresponding to the alignments, a weight vector containing the
inverse frequency of each target index is computed.
For e.g. if alignments = [[5, 7], [2, 3], [1, 3],... |
Given a tensor of shape [:, 2] containing the source-target indices
corresponding to the alignments, a weight vector containing the
inverse frequency of each target index is computed.
For e.g. if alignments = [[5, 7], [2, 3], [1, 3], [4, 2]], then
a tensor containing [1., 0.5, 0... | compute_alignment_weights | python | OFA-Sys/OFA | fairseq/fairseq/data/language_pair_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/language_pair_dataset.py | Apache-2.0 |
def collater(self, samples, pad_to_length=None):
"""Merge a list of samples to form a mini-batch.
Args:
samples (List[dict]): samples to collate
pad_to_length (dict, optional): a dictionary of
{'source': source_pad_to_length, 'target': target_pad_to_length}
... | Merge a list of samples to form a mini-batch.
Args:
samples (List[dict]): samples to collate
pad_to_length (dict, optional): a dictionary of
{'source': source_pad_to_length, 'target': target_pad_to_length}
to indicate the max length to pad to in source an... | collater | python | OFA-Sys/OFA | fairseq/fairseq/data/language_pair_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/language_pair_dataset.py | Apache-2.0 |
def num_tokens(self, index):
"""Return the number of tokens in a sample. This value is used to
enforce ``--max-tokens`` during batching."""
return max(
self.src_sizes[index],
self.tgt_sizes[index] if self.tgt_sizes is not None else 0,
) | Return the number of tokens in a sample. This value is used to
enforce ``--max-tokens`` during batching. | num_tokens | python | OFA-Sys/OFA | fairseq/fairseq/data/language_pair_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/language_pair_dataset.py | Apache-2.0 |
def num_tokens_vec(self, indices):
"""Return the number of tokens for a set of positions defined by indices.
This value is used to enforce ``--max-tokens`` during batching."""
sizes = self.src_sizes[indices]
if self.tgt_sizes is not None:
sizes = np.maximum(sizes, self.tgt_si... | Return the number of tokens for a set of positions defined by indices.
This value is used to enforce ``--max-tokens`` during batching. | num_tokens_vec | python | OFA-Sys/OFA | fairseq/fairseq/data/language_pair_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/language_pair_dataset.py | Apache-2.0 |
def filter_indices_by_size(self, indices, max_sizes):
"""Filter a list of sample indices. Remove those that are longer
than specified in max_sizes.
Args:
indices (np.array): original array of sample indices
max_sizes (int or list[int] or tuple[int]): max sample size,... | Filter a list of sample indices. Remove those that are longer
than specified in max_sizes.
Args:
indices (np.array): original array of sample indices
max_sizes (int or list[int] or tuple[int]): max sample size,
can be defined separately for src and tgt (then ... | filter_indices_by_size | python | OFA-Sys/OFA | fairseq/fairseq/data/language_pair_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/language_pair_dataset.py | Apache-2.0 |
def apply_mask(cls, dataset: torch.utils.data.Dataset, *args, **kwargs):
"""Return the source and target datasets for masked LM training."""
dataset = LRUCacheDataset(dataset)
return (
LRUCacheDataset(cls(dataset, *args, **kwargs, return_masked_tokens=False)),
LRUCacheDat... | Return the source and target datasets for masked LM training. | apply_mask | python | OFA-Sys/OFA | fairseq/fairseq/data/mask_tokens_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/mask_tokens_dataset.py | Apache-2.0 |
def collater(self, samples):
"""Merge a list of samples to form a mini-batch.
Args:
samples (List[dict]): samples to collate
Returns:
dict: a mini-batch with the following keys:
- `id` (LongTensor): example IDs in the original input order
... | Merge a list of samples to form a mini-batch.
Args:
samples (List[dict]): samples to collate
Returns:
dict: a mini-batch with the following keys:
- `id` (LongTensor): example IDs in the original input order
- `ntokens` (int): total number of tok... | collater | python | OFA-Sys/OFA | fairseq/fairseq/data/monolingual_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/monolingual_dataset.py | Apache-2.0 |
def _map_index(self, index: int):
"""
If dataset A has length N and dataset B has length M
then index 1 maps to index 1 of dataset A, and index N + 1
maps to index 1 of B.
"""
counter = 0
for key, dataset in self.datasets.items():
if index < counter + ... |
If dataset A has length N and dataset B has length M
then index 1 maps to index 1 of dataset A, and index N + 1
maps to index 1 of B.
| _map_index | python | OFA-Sys/OFA | fairseq/fairseq/data/multi_corpus_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/multi_corpus_dataset.py | Apache-2.0 |
def collater(self, samples):
"""
If we are doing batch sampling, then pick the right collater to use.
Otherwise we assume all collaters are the same.
"""
if len(samples) == 0:
return None
if "full_id" in samples[0]:
_, key = self._map_index(sample... |
If we are doing batch sampling, then pick the right collater to use.
Otherwise we assume all collaters are the same.
| collater | python | OFA-Sys/OFA | fairseq/fairseq/data/multi_corpus_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/multi_corpus_dataset.py | Apache-2.0 |
def ordered_indices(self):
"""
Ordered indices for batching. Here we call the underlying
dataset's ordered_indices() so that we get the same random ordering
as we would have from using the underlying dataset directly.
"""
if self._ordered_indices is None:
self... |
Ordered indices for batching. Here we call the underlying
dataset's ordered_indices() so that we get the same random ordering
as we would have from using the underlying dataset directly.
| ordered_indices | python | OFA-Sys/OFA | fairseq/fairseq/data/multi_corpus_sampled_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/multi_corpus_sampled_dataset.py | Apache-2.0 |
def _map_index_to_dataset(self, key: int, index: int):
"""
Different underlying datasets have different lengths. In order to ensure
we are not accessing an index outside the range of the current dataset
size, we wrap around. This function should be called after we have
created an... |
Different underlying datasets have different lengths. In order to ensure
we are not accessing an index outside the range of the current dataset
size, we wrap around. This function should be called after we have
created an ordering for this and all underlying datasets.
| _map_index_to_dataset | python | OFA-Sys/OFA | fairseq/fairseq/data/multi_corpus_sampled_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/multi_corpus_sampled_dataset.py | Apache-2.0 |
def __getitem__(self, index: int):
"""
Get the item associated with index from each underlying dataset.
Since index is in the range of [0, TotalNumInstances], we need to
map the index to the dataset before retrieving the item.
"""
return OrderedDict(
[
... |
Get the item associated with index from each underlying dataset.
Since index is in the range of [0, TotalNumInstances], we need to
map the index to the dataset before retrieving the item.
| __getitem__ | python | OFA-Sys/OFA | fairseq/fairseq/data/multi_corpus_sampled_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/multi_corpus_sampled_dataset.py | Apache-2.0 |
def collater(self, samples: List[Dict]):
"""
Generate a mini-batch for this dataset.
To convert this into a regular mini-batch we use the following
logic:
1. Select a dataset using the specified probability distribution.
2. Call the collater function of the select... |
Generate a mini-batch for this dataset.
To convert this into a regular mini-batch we use the following
logic:
1. Select a dataset using the specified probability distribution.
2. Call the collater function of the selected dataset.
| collater | python | OFA-Sys/OFA | fairseq/fairseq/data/multi_corpus_sampled_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/multi_corpus_sampled_dataset.py | Apache-2.0 |
def num_tokens(self, index: int):
"""
Return an example's length (number of tokens), used for batching. Here
we return the max across all examples at index across all underlying
datasets.
"""
return max(
dataset.num_tokens(self._map_index_to_dataset(key, index... |
Return an example's length (number of tokens), used for batching. Here
we return the max across all examples at index across all underlying
datasets.
| num_tokens | python | OFA-Sys/OFA | fairseq/fairseq/data/multi_corpus_sampled_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/multi_corpus_sampled_dataset.py | Apache-2.0 |
def size(self, index: int):
"""
Return an example's size as a float or tuple. Here we return the max
across all underlying datasets. This value is used when filtering a
dataset with max-positions.
"""
return max(
dataset.size(self._map_index_to_dataset(key, in... |
Return an example's size as a float or tuple. Here we return the max
across all underlying datasets. This value is used when filtering a
dataset with max-positions.
| size | python | OFA-Sys/OFA | fairseq/fairseq/data/multi_corpus_sampled_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/multi_corpus_sampled_dataset.py | Apache-2.0 |
def _unflatten(dico):
"""Unflatten a flattened dictionary into a nested dictionary."""
new_dico = OrderedDict()
for full_k, v in dico.items():
full_k = full_k.split(".")
node = new_dico
for k in full_k[:-1]:
if k.startswith("[") and k.endswith("]"):
k = in... | Unflatten a flattened dictionary into a nested dictionary. | _unflatten | python | OFA-Sys/OFA | fairseq/fairseq/data/nested_dictionary_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/nested_dictionary_dataset.py | Apache-2.0 |
def collater(self, samples):
"""Merge a list of samples to form a mini-batch.
Args:
samples (List[dict]): samples to collate
Returns:
dict: a mini-batch suitable for forwarding with a Model
"""
if len(samples) == 0:
return {}
sample =... | Merge a list of samples to form a mini-batch.
Args:
samples (List[dict]): samples to collate
Returns:
dict: a mini-batch suitable for forwarding with a Model
| collater | python | OFA-Sys/OFA | fairseq/fairseq/data/nested_dictionary_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/nested_dictionary_dataset.py | Apache-2.0 |
def prefetch(self, indices):
"""Prefetch the data required for this epoch."""
for ds in self.defn.values():
if getattr(ds, "supports_prefetch", False):
ds.prefetch(indices) | Prefetch the data required for this epoch. | prefetch | python | OFA-Sys/OFA | fairseq/fairseq/data/nested_dictionary_dataset.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/nested_dictionary_dataset.py | Apache-2.0 |
def _get_bpe_word_idx(self, x):
"""
Given a list of BPE tokens, for every index in the tokens list,
return the index of the word grouping that it belongs to.
For example, for input x corresponding to ["how", "are", "y@@", "ou"],
return [[0], [1], [2], [2]].
"""
# ... |
Given a list of BPE tokens, for every index in the tokens list,
return the index of the word grouping that it belongs to.
For example, for input x corresponding to ["how", "are", "y@@", "ou"],
return [[0], [1], [2], [2]].
| _get_bpe_word_idx | python | OFA-Sys/OFA | fairseq/fairseq/data/noising.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/noising.py | Apache-2.0 |
def _get_token_idx(self, x):
"""
This is to extend noising functions to be able to apply to non-bpe
tokens, e.g. word or characters.
"""
x = torch.t(x)
word_idx = np.array([range(len(x_i)) for x_i in x])
return np.transpose(word_idx) |
This is to extend noising functions to be able to apply to non-bpe
tokens, e.g. word or characters.
| _get_token_idx | python | OFA-Sys/OFA | fairseq/fairseq/data/noising.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/noising.py | Apache-2.0 |
def __init__(
self,
src_dataset,
src_dict,
seed,
noiser=None,
noising_class=UnsupervisedMTNoising,
**kwargs
):
"""
Wrap a :class:`~torch.utils.data.Dataset` and apply noise to the
samples based on the supplied noising configuration.
... |
Wrap a :class:`~torch.utils.data.Dataset` and apply noise to the
samples based on the supplied noising configuration.
Args:
src_dataset (~torch.utils.data.Dataset): dataset to wrap.
to build self.src_dataset --
a LanguagePairDataset with src dataset ... | __init__ | python | OFA-Sys/OFA | fairseq/fairseq/data/noising.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/noising.py | Apache-2.0 |
def __getitem__(self, index):
"""
Returns a single noisy sample. Multiple samples are fed to the collater
create a noising dataset batch.
"""
src_tokens = self.src_dataset[index]
src_lengths = torch.LongTensor([len(src_tokens)])
src_tokens = src_tokens.unsqueeze(0... |
Returns a single noisy sample. Multiple samples are fed to the collater
create a noising dataset batch.
| __getitem__ | python | OFA-Sys/OFA | fairseq/fairseq/data/noising.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/noising.py | Apache-2.0 |
def __init__(self, array, split_path: str, hash_data: Hashable, plasma_path=None):
"""
Args:
array: numpy array to store. This can be read with ``PlasmaView().array``
split_path: the path whence the data was read, used for hashing
hash_data: other metadata about the a... |
Args:
array: numpy array to store. This can be read with ``PlasmaView().array``
split_path: the path whence the data was read, used for hashing
hash_data: other metadata about the array that can be used to create a unique key.
as of writing, the 3 callers in ... | __init__ | python | OFA-Sys/OFA | fairseq/fairseq/data/plasma_utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/plasma_utils.py | Apache-2.0 |
def get_object_id(split_path: str, hash_data: Hashable):
"""Returns plasma.ObjectID from hashing split_path and object_num."""
hash = hashlib.blake2b(bytes(split_path, "utf-8"), digest_size=20)
harg = json.dumps(hash_data).encode("utf-8")
hash.update(harg)
return plasma.ObjectID(... | Returns plasma.ObjectID from hashing split_path and object_num. | get_object_id | python | OFA-Sys/OFA | fairseq/fairseq/data/plasma_utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/data/plasma_utils.py | Apache-2.0 |
def collater(self, samples):
"""Merge a list of samples to form a mini-batch."""
if len(samples) == 0:
return None
if self.eval_key is None:
return OrderedDict(
[
(key, dataset.collater([sample[key] for sample in samples]))
... | Merge a list of samples to form a mini-batch. | collater | 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 num_tokens(self, index):
"""Return an example's length (number of tokens), used for batching."""
# TODO make it configurable whether to use max() or sum() here
return max(
dataset.num_tokens(self._map_index(key, index))
for key, dataset in self.datasets.items()
... | Return an example's length (number of tokens), used for batching. | num_tokens | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.