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 encode(
self, sentence: str, *addl_sentences, no_separator=False
) -> 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>`) and we use a... |
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>`) and we use an
extra end-of-sentence (`</s>`) as a separator.
Example (single sentence): `<s> a b c </s>`
... | encode | python | OFA-Sys/OFA | fairseq/fairseq/models/roberta/hub_interface.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/roberta/hub_interface.py | Apache-2.0 |
def extract_features_aligned_to_words(
self, sentence: str, return_all_hiddens: bool = False
) -> torch.Tensor:
"""Extract RoBERTa features, aligned to spaCy's word-level tokenizer."""
from fairseq.models.roberta import alignment_utils
from spacy.tokens import Doc
nlp = alig... | Extract RoBERTa features, aligned to spaCy's word-level tokenizer. | extract_features_aligned_to_words | python | OFA-Sys/OFA | fairseq/fairseq/models/roberta/hub_interface.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/roberta/hub_interface.py | Apache-2.0 |
def disambiguate_pronoun(self, sentence: str) -> bool:
"""
Usage::
>>> disambiguate_pronoun('The _trophy_ would not fit in the brown suitcase because [it] was too big.')
True
>>> disambiguate_pronoun('The trophy would not fit in the brown suitcase because [it] was t... |
Usage::
>>> disambiguate_pronoun('The _trophy_ would not fit in the brown suitcase because [it] was too big.')
True
>>> disambiguate_pronoun('The trophy would not fit in the brown suitcase because [it] was too big.')
'The trophy'
| disambiguate_pronoun | python | OFA-Sys/OFA | fairseq/fairseq/models/roberta/hub_interface.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/roberta/hub_interface.py | Apache-2.0 |
def forward(
self,
src_tokens,
features_only=False,
return_all_hiddens=False,
masked_tokens=None,
**unused,
):
"""
Args:
src_tokens (LongTensor): input tokens of shape `(batch, src_len)`
features_only (bool, optional): skip LM h... |
Args:
src_tokens (LongTensor): input tokens of shape `(batch, src_len)`
features_only (bool, optional): skip LM head and just return
features. If True, the output will be of shape
`(batch, src_len, embed_dim)`.
return_all_hiddens (bool, option... | forward | python | OFA-Sys/OFA | fairseq/fairseq/models/roberta/model.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/roberta/model.py | Apache-2.0 |
def __init__(
self,
input_layers: List[int],
conv_layers: List[Tuple[int]],
in_channels: int,
input_feat_per_channel: int,
num_blstm_layers: int,
lstm_size: int,
dropout: float,
):
"""
Args:
input_layers: list of linear laye... |
Args:
input_layers: list of linear layer dimensions. These layers are
applied to the input features and are followed by tanh and
possibly dropout.
conv_layers: list of conv2d layer configurations. A configuration is
a tuple (out_channels, ... | __init__ | python | OFA-Sys/OFA | fairseq/fairseq/models/speech_to_text/berard.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/speech_to_text/berard.py | Apache-2.0 |
def forward(self, src_tokens, src_lengths=None, **kwargs):
"""
Args
src_tokens: padded tensor (B, T, C * feat)
src_lengths: tensor of original lengths of input utterances (B,)
"""
bsz, max_seq_len, _ = src_tokens.size()
# (B, C, T, feat)
x = (
... |
Args
src_tokens: padded tensor (B, T, C * feat)
src_lengths: tensor of original lengths of input utterances (B,)
| forward | python | OFA-Sys/OFA | fairseq/fairseq/models/speech_to_text/berard.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/speech_to_text/berard.py | Apache-2.0 |
def forward(self, decoder_state, source_hids, encoder_padding_mask):
"""The expected input dimensions are:
decoder_state: bsz x decoder_hidden_state_dim
source_hids: src_len x bsz x context_dim
encoder_padding_mask: src_len x bsz
"""
src_len, bsz, _ = source_hids.size()
... | The expected input dimensions are:
decoder_state: bsz x decoder_hidden_state_dim
source_hids: src_len x bsz x context_dim
encoder_padding_mask: src_len x bsz
| forward | python | OFA-Sys/OFA | fairseq/fairseq/models/speech_to_text/berard.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/speech_to_text/berard.py | Apache-2.0 |
def __init__(
self,
dictionary,
embed_dim,
num_layers,
hidden_size,
dropout,
encoder_output_dim,
attention_dim,
output_layer_dim,
):
"""
Args:
dictionary: target text dictionary.
embed_dim: embedding dime... |
Args:
dictionary: target text dictionary.
embed_dim: embedding dimension for target tokens.
num_layers: number of LSTM layers.
hidden_size: hidden size for LSTM layers.
dropout: dropout probability. Dropout can be applied to the
embedd... | __init__ | python | OFA-Sys/OFA | fairseq/fairseq/models/speech_to_text/berard.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/speech_to_text/berard.py | Apache-2.0 |
def berard(args):
"""The original version: "End-to-End Automatic Speech Translation of
Audiobooks" (https://arxiv.org/abs/1802.04200)
"""
args.input_layers = getattr(args, "input_layers", "[256, 128]")
args.conv_layers = getattr(args, "conv_layers", "[(16, 3, 2), (16, 3, 2)]")
args.num_blstm_lay... | The original version: "End-to-End Automatic Speech Translation of
Audiobooks" (https://arxiv.org/abs/1802.04200)
| berard | python | OFA-Sys/OFA | fairseq/fairseq/models/speech_to_text/berard.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/speech_to_text/berard.py | Apache-2.0 |
def forward(self, src_tokens, src_lengths):
"""Encode input sequence.
:param torch.Tensor xs: input tensor
:param torch.Tensor masks: input mask
:return: position embedded tensor and mask
:rtype Tuple[torch.Tensor, torch.Tensor]:
"""
bsz, max_seq_len, _ = src_toke... | Encode input sequence.
:param torch.Tensor xs: input tensor
:param torch.Tensor masks: input mask
:return: position embedded tensor and mask
:rtype Tuple[torch.Tensor, torch.Tensor]:
| forward | python | OFA-Sys/OFA | fairseq/fairseq/models/speech_to_text/convtransformer.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/speech_to_text/convtransformer.py | Apache-2.0 |
def forward(self, src_tokens, src_lengths, prev_output_tokens):
"""
The forward method inherited from the base class has a **kwargs
argument in its input, which is not supported in torchscript. This
method overwrites the forward method definition without **kwargs.
"""
enc... |
The forward method inherited from the base class has a **kwargs
argument in its input, which is not supported in torchscript. This
method overwrites the forward method definition without **kwargs.
| forward | python | OFA-Sys/OFA | fairseq/fairseq/models/speech_to_text/s2t_transformer.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/speech_to_text/s2t_transformer.py | Apache-2.0 |
def assert_equal(value1, value2, name1=None, name2=None):
"""Asserts two values are equal otherwise raise an error."""
str_name1 = "" if name1 is None else "{} ".format(name1)
str_name2 = "" if name2 is None else "{} ".format(name2)
if value1 != value2:
str_value1 = "{}" if name1 is None else "... | Asserts two values are equal otherwise raise an error. | assert_equal | python | OFA-Sys/OFA | fairseq/fairseq/models/speech_to_text/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/speech_to_text/utils.py | Apache-2.0 |
def check_and_return_expected(value, undefined_value, expected_value, name=None):
"""
Return the expected value while checking if the given value is undefined or
equal to the expected value.
"""
if (undefined_value is None and value is None) or (undefined_value == value):
return expected_val... |
Return the expected value while checking if the given value is undefined or
equal to the expected value.
| check_and_return_expected | python | OFA-Sys/OFA | fairseq/fairseq/models/speech_to_text/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/speech_to_text/utils.py | Apache-2.0 |
def get_time_axis(layout):
"""
Extract the time axis from the layout, for example for breaking sequence into
segments.
"""
if layout in ["TB", "TBD"]:
return 0
if layout in ["BT", "BTD"]:
return 1
if layout in ["BCTD"]:
return 2
raise ValueError("Unsupported layou... |
Extract the time axis from the layout, for example for breaking sequence into
segments.
| get_time_axis | python | OFA-Sys/OFA | fairseq/fairseq/models/speech_to_text/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/speech_to_text/utils.py | Apache-2.0 |
def get_batch_axis(layout):
"""
Extract the batch axis from the layout
"""
if layout in ["TB", "TBD"]:
return 1
if layout in ["BT", "BTD", "BCTD"]:
return 0
raise ValueError("Unsupported layout = {}".format(layout)) |
Extract the batch axis from the layout
| get_batch_axis | python | OFA-Sys/OFA | fairseq/fairseq/models/speech_to_text/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/speech_to_text/utils.py | Apache-2.0 |
def monotonically_increasing_and_bounded(iterable, min=None, max=None):
"""
Check if the elements in the given iterable are monotonically increasing and
bounded by upper/lower bounds.
"""
if not isinstance(iterable, Iterable):
raise TypeError(
"Expected iterable to be of type Ite... |
Check if the elements in the given iterable are monotonically increasing and
bounded by upper/lower bounds.
| monotonically_increasing_and_bounded | python | OFA-Sys/OFA | fairseq/fairseq/models/speech_to_text/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/speech_to_text/utils.py | Apache-2.0 |
def to_pair(value, name):
"""Make a pair (of type tuple) of given value."""
if isinstance(value, Iterable):
if len(value) != 2:
raise ValueError(
"Expected `{}` to have exactly 2 elements, got: ({})".format(
name, value
)
)
... | Make a pair (of type tuple) of given value. | to_pair | python | OFA-Sys/OFA | fairseq/fairseq/models/speech_to_text/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/speech_to_text/utils.py | Apache-2.0 |
def infer_conv_output_attrs(
module, input_channels, input_dim, batch_size=1, max_length=8
):
"""Get output attributes of a module with input."""
input = torch.randn(batch_size, input_channels, max_length, input_dim)
output = module(input)
output_channels = output.shape[1]
output_dim = output.sh... | Get output attributes of a module with input. | infer_conv_output_attrs | python | OFA-Sys/OFA | fairseq/fairseq/models/speech_to_text/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/speech_to_text/utils.py | Apache-2.0 |
def lengths_to_padding_mask(lengths: Tensor) -> Tensor:
"""Convert lengths of shape (B, ) to padding mask."""
batch_size = lengths.shape[0]
max_length = int(torch.max(lengths).item())
padding_mask = torch.arange( # [0, ..., T-1]
max_length, device=lengths.device, dtype=lengths.dtype
).expan... | Convert lengths of shape (B, ) to padding mask. | lengths_to_padding_mask | python | OFA-Sys/OFA | fairseq/fairseq/models/speech_to_text/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/speech_to_text/utils.py | Apache-2.0 |
def infer_output_norm(module, output_norm=None):
"""
Infer the output norm (string and module) needed on the module gvien desired
output normalization.
"""
if output_norm == module.output_norm():
# output_norm already matches module.output_norm().
return (None, NoOp())
if output... |
Infer the output norm (string and module) needed on the module gvien desired
output normalization.
| infer_output_norm | python | OFA-Sys/OFA | fairseq/fairseq/models/speech_to_text/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/speech_to_text/utils.py | Apache-2.0 |
def infer_channels_from_layout(layout, channels):
"""Extract the number of channels from the layout."""
if layout in ("TBD", "BTD"):
if channels is not None and channels != 1:
raise ValueError(
"Expected channels ({}) to be 1 for layout = {}".format(
chann... | Extract the number of channels from the layout. | infer_channels_from_layout | python | OFA-Sys/OFA | fairseq/fairseq/models/speech_to_text/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/speech_to_text/utils.py | Apache-2.0 |
def pad_sequence(
sequence: Tensor,
time_axis: int,
extra_left_context: int = 0,
extra_right_context: int = 0,
) -> Tensor:
"""Pad extra left/right contexts to the sequence."""
if extra_left_context == 0 and extra_right_context == 0:
return sequence
tensors_to_concat = []
if e... | Pad extra left/right contexts to the sequence. | pad_sequence | python | OFA-Sys/OFA | fairseq/fairseq/models/speech_to_text/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/speech_to_text/utils.py | Apache-2.0 |
def lengths_to_encoder_padding_mask(lengths, batch_first: bool = False):
"""
convert lengths (a 1-D Long/Int tensor) to 2-D binary tensor
Args:
lengths: a (B, )-shaped tensor
batch_first: whether to return a (B, T) tensor
Return:
max_length: maximum length of B sequences
... |
convert lengths (a 1-D Long/Int tensor) to 2-D binary tensor
Args:
lengths: a (B, )-shaped tensor
batch_first: whether to return a (B, T) tensor
Return:
max_length: maximum length of B sequences
encoder_padding_mask: a (max_length, B) binary mask, where
[t, b] = Fa... | lengths_to_encoder_padding_mask | python | OFA-Sys/OFA | fairseq/fairseq/models/speech_to_text/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/speech_to_text/utils.py | Apache-2.0 |
def forward(self, src_tokens, src_lengths, prev_output_tokens, **kwargs):
"""
The forward method inherited from the base class has a **kwargs
argument in its input, which is not supported in torchscript. This
method overrites the forward method definition without **kwargs.
"""
... |
The forward method inherited from the base class has a **kwargs
argument in its input, which is not supported in torchscript. This
method overrites the forward method definition without **kwargs.
| forward | python | OFA-Sys/OFA | fairseq/fairseq/models/speech_to_text/xm_transformer.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/speech_to_text/xm_transformer.py | Apache-2.0 |
def forward(self, input_and_summary, state):
"""
input: Encoder states of current segment with left or right context,
plus one summarization query
"""
length, batch_size, _ = input_and_summary.shape
length = length - 1 # not include sum_query, last index
m... |
input: Encoder states of current segment with left or right context,
plus one summarization query
| forward | python | OFA-Sys/OFA | fairseq/fairseq/models/speech_to_text/modules/augmented_memory_attention.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/speech_to_text/modules/augmented_memory_attention.py | Apache-2.0 |
def suppress_mem_on_mem_attention(
self, B: int, num_heads: int, mem_size: int, attention_weight: Tensor
):
"""
Arguments:
- B: batch size
- num_heads: number of attention heads
- mem_size: size of memory bank
- attention_weight: a [B*num_heads... |
Arguments:
- B: batch size
- num_heads: number of attention heads
- mem_size: size of memory bank
- attention_weight: a [B*num_heads, T + 1, T + mem_size] vector
Return:
modified attention_weight with [B*num_heads, -1, :mem_size] = -inf
... | suppress_mem_on_mem_attention | python | OFA-Sys/OFA | fairseq/fairseq/models/speech_to_text/modules/augmented_memory_attention.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/speech_to_text/modules/augmented_memory_attention.py | Apache-2.0 |
def incremental_encode(
self,
seg_src_tokens: Tensor,
seg_src_lengths: Tensor,
states=None,
):
"""
Different from forward function, this function takes segmented speech
as input, and append encoder states to previous states
"""
(seg_encoder_sta... |
Different from forward function, this function takes segmented speech
as input, and append encoder states to previous states
| incremental_encode | python | OFA-Sys/OFA | fairseq/fairseq/models/speech_to_text/modules/augmented_memory_attention.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/speech_to_text/modules/augmented_memory_attention.py | Apache-2.0 |
def forward(
self,
input: Tensor,
lengths: Tensor,
mems: Tensor,
attention_mask: Tensor,
pre_mems: Optional[Tensor] = None,
left_context_key: Optional[Tensor] = None,
left_context_val: Optional[Tensor] = None,
rpe: Optional[Tensor] = None,
) ->... |
forward function for NoSegAugmentedMemoryMultiheadAttentionBmm in training.
args:
input: formed in the following way
[right_context_0, right_contex_1, ..., seg_0, seg_1,
..., summary_0, summary_1,..]
lengths: the length of query which is [seg_0, ... | forward | python | OFA-Sys/OFA | fairseq/fairseq/models/speech_to_text/modules/emformer.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/speech_to_text/modules/emformer.py | Apache-2.0 |
def forward_jit(
self,
input: Tensor,
lengths: Tensor,
mems: Tensor,
left_context_key: Tensor,
left_context_val: Tensor,
rpe: Optional[Tensor],
) -> Tuple[Tensor, Tensor, Tensor, Tensor]:
"""
forward function for NoSegAugmentedMemoryMultiheadAt... |
forward function for NoSegAugmentedMemoryMultiheadAttentionBmm in decoding.
args:
input: formed in the following way
[right_context_0, right_contex_1, ..., seg_0, seg_1,
..., summary_0, summary_1,..]
lengths: the length of query which is [seg_0, ... | forward_jit | python | OFA-Sys/OFA | fairseq/fairseq/models/speech_to_text/modules/emformer.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/speech_to_text/modules/emformer.py | Apache-2.0 |
def forward_jit_test(
self, input: Tensor, lengths: Tensor, state: Optional[List[Tensor]] = None
) -> Tuple[Tensor, Tensor, List[Tensor]]:
"""
This one simulate sequence encoder forward jit. This is for unit test purpose.
It is not used in training or decoding. Note, extra_right_cont... |
This one simulate sequence encoder forward jit. This is for unit test purpose.
It is not used in training or decoding. Note, extra_right_context is set in
the model. In unit test, input = [utterance, right_context], lengths =
[utterance_length].
args:
input: input ut... | forward_jit_test | python | OFA-Sys/OFA | fairseq/fairseq/models/speech_to_text/modules/emformer.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/speech_to_text/modules/emformer.py | Apache-2.0 |
def forward_jit(
self, input: Tensor, lengths: Tensor, state: Optional[List[Tensor]] = None
) -> Tuple[Tensor, Tensor, List[Tensor]]:
"""
Forward helper for online decoding.
args:
input: [seg, right_context]. We assume in online we
always padding the righ... |
Forward helper for online decoding.
args:
input: [seg, right_context]. We assume in online we
always padding the right context to the preset right context size.
For the last segment, we may have short segment size, but right
context size is t... | forward_jit | python | OFA-Sys/OFA | fairseq/fairseq/models/speech_to_text/modules/emformer.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/speech_to_text/modules/emformer.py | Apache-2.0 |
def forward(
self,
src_tokens,
src_lengths,
prev_output_tokens,
return_all_hiddens: bool = True,
features_only: bool = False,
alignment_layer: Optional[int] = None,
alignment_heads: Optional[int] = None,
):
"""
Run the forward pass for ... |
Run the forward pass for an encoder-decoder model.
Copied from the base class, but without ``**kwargs``,
which are not supported by TorchScript.
| forward | python | OFA-Sys/OFA | fairseq/fairseq/models/transformer/transformer_base.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/transformer/transformer_base.py | Apache-2.0 |
def _copy_keys(args, cls, prefix, seen):
"""
copy the prefixed keys (decoder_embed_dim) to the DC fields: decoder.embed_dim
"""
cfg = cls()
for fld in fields(cls):
# for all the fields in the DC, find the fields (e.g. embed_dim)
# in the namespace with... |
copy the prefixed keys (decoder_embed_dim) to the DC fields: decoder.embed_dim
| _copy_keys | python | OFA-Sys/OFA | fairseq/fairseq/models/transformer/transformer_config.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/transformer/transformer_config.py | Apache-2.0 |
def forward(
self,
prev_output_tokens,
encoder_out: Optional[Dict[str, List[Tensor]]] = None,
incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,
features_only: bool = False,
full_context_alignment: bool = False,
alignment_layer: Optional[i... |
Args:
prev_output_tokens (LongTensor): previous decoder outputs of shape
`(batch, tgt_len)`, for teacher forcing
encoder_out (optional): output from the encoder, used for
encoder-side attention, should be of size T x B x C
incremental_state (d... | forward | python | OFA-Sys/OFA | fairseq/fairseq/models/transformer/transformer_decoder.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/transformer/transformer_decoder.py | Apache-2.0 |
def upgrade_state_dict_named(self, state_dict, name):
"""Upgrade a (possibly old) state dict for new versions of fairseq."""
if isinstance(self.embed_positions, SinusoidalPositionalEmbedding):
weights_key = "{}.embed_positions.weights".format(name)
if weights_key in state_dict:
... | Upgrade a (possibly old) state dict for new versions of fairseq. | upgrade_state_dict_named | python | OFA-Sys/OFA | fairseq/fairseq/models/transformer/transformer_decoder.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/transformer/transformer_decoder.py | Apache-2.0 |
def forward(
self,
src_tokens,
src_lengths: Optional[torch.Tensor] = None,
return_all_hiddens: bool = False,
token_embeddings: Optional[torch.Tensor] = None,
):
"""
Args:
src_tokens (LongTensor): tokens in the source language of shape
... |
Args:
src_tokens (LongTensor): tokens in the source language of shape
`(batch, src_len)`
src_lengths (torch.LongTensor): lengths of each source sentence of
shape `(batch)`
return_all_hiddens (bool, optional): also return all of the
... | forward | python | OFA-Sys/OFA | fairseq/fairseq/models/transformer/transformer_encoder.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/transformer/transformer_encoder.py | Apache-2.0 |
def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor):
"""
Computes the output length of the convolutional layers
"""
def _conv_out_length(input_length, kernel_size, stride):
return torch.floor((input_length - kernel_size) / stride + 1)
conv_cf... |
Computes the output length of the convolutional layers
| _get_feat_extract_output_lengths | python | OFA-Sys/OFA | fairseq/fairseq/models/wav2vec/wav2vec2.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/wav2vec/wav2vec2.py | Apache-2.0 |
def forward(
self,
x: torch.Tensor,
self_attn_mask: torch.Tensor = None,
self_attn_padding_mask: torch.Tensor = None,
need_weights: bool = False,
att_args=None,
):
"""
LayerNorm is applied either before or after the self-attention/ffn
modules s... |
LayerNorm is applied either before or after the self-attention/ffn
modules similar to the original Transformer imlementation.
| forward | python | OFA-Sys/OFA | fairseq/fairseq/models/wav2vec/wav2vec2.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/wav2vec/wav2vec2.py | Apache-2.0 |
def forward(
self, prev_output_tokens, encoder_out=None, incremental_state=None, **unused
):
"""
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/wav2vec/wav2vec2_asr.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/models/wav2vec/wav2vec2_asr.py | Apache-2.0 |
def upgrade_state_dict_named(self, state_dict, name):
"""
Rename layer norm states from `...layer_norms.0.weight` to
`...self_attn_layer_norm.weight` and `...layer_norms.1.weight` to
`...final_layer_norm.weight`
"""
layer_norm_map = {"0": "self_attn_layer_norm", "1": "fin... |
Rename layer norm states from `...layer_norms.0.weight` to
`...self_attn_layer_norm.weight` and `...layer_norms.1.weight` to
`...final_layer_norm.weight`
| upgrade_state_dict_named | python | OFA-Sys/OFA | fairseq/fairseq/model_parallel/models/pipeline_parallel_transformer/layers.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/model_parallel/models/pipeline_parallel_transformer/layers.py | Apache-2.0 |
def forward(self, input):
"""
Args:
input (Tuple):
input[0] (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`
input[1] (ByteTensor/FloatTensor): encoder padding mask -
binary ByteTensor of shape `(batch, src_len)` where pa... |
Args:
input (Tuple):
input[0] (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`
input[1] (ByteTensor/FloatTensor): encoder padding mask -
binary ByteTensor of shape `(batch, src_len)` where padding elements
ar... | forward | python | OFA-Sys/OFA | fairseq/fairseq/model_parallel/models/pipeline_parallel_transformer/layers.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/model_parallel/models/pipeline_parallel_transformer/layers.py | Apache-2.0 |
def forward(self, input):
"""
Args:
input (Tuple):
input[0] (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`
input[1] (Tensor): encoder output of shape `(batch, src_len, embed_dim)`
input[2] (ByteTensor/FloatTensor): encoder ... |
Args:
input (Tuple):
input[0] (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`
input[1] (Tensor): encoder output of shape `(batch, src_len, embed_dim)`
input[2] (ByteTensor/FloatTensor): encoder padding mask -
bi... | forward | python | OFA-Sys/OFA | fairseq/fairseq/model_parallel/models/pipeline_parallel_transformer/layers.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/model_parallel/models/pipeline_parallel_transformer/layers.py | Apache-2.0 |
def max_positions_helper(
self, embedding_layer, max_positions_field="max_source_positions"
):
"""Maximum input length supported by the encoder or decoder."""
if embedding_layer.embed_positions is None:
return getattr(embedding_layer, max_positions_field)
return min(
... | Maximum input length supported by the encoder or decoder. | max_positions_helper | python | OFA-Sys/OFA | fairseq/fairseq/model_parallel/models/pipeline_parallel_transformer/model.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/model_parallel/models/pipeline_parallel_transformer/model.py | Apache-2.0 |
def forward(self, src_tokens, src_lengths):
"""
Args:
input_tuple(
src_tokens (LongTensor): tokens in the source language of shape
`(batch, src_len)`
src_lengths (torch.LongTensor): lengths of each source sentence of
sha... |
Args:
input_tuple(
src_tokens (LongTensor): tokens in the source language of shape
`(batch, src_len)`
src_lengths (torch.LongTensor): lengths of each source sentence of
shape `(batch)`
)
Returns:
... | forward | python | OFA-Sys/OFA | fairseq/fairseq/model_parallel/models/pipeline_parallel_transformer/model.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/model_parallel/models/pipeline_parallel_transformer/model.py | Apache-2.0 |
def forward(
self,
query,
key: Optional[Tensor],
value: Optional[Tensor],
key_padding_mask: Optional[Tensor] = None,
incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None,
static_kv: bool = False,
attn_mask: Optional[Tensor] = None,
... | Input shape: Time x Batch x Channel
Args:
key_padding_mask (ByteTensor, optional): mask to exclude
keys that are pads, of shape `(batch, src_len)`, where
padding elements are indicated by 1s.
attn_mask (ByteTensor, optional): typically used to
... | forward | python | OFA-Sys/OFA | fairseq/fairseq/model_parallel/modules/multihead_attention.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/model_parallel/modules/multihead_attention.py | Apache-2.0 |
def adapt_target(self, target):
"""
In order to be efficient, the AdaptiveSoftMax does not compute the
scores for all the word of the vocabulary for all the examples. It is
thus necessary to call the method adapt_target of the AdaptiveSoftMax
layer inside each forward pass.
... |
In order to be efficient, the AdaptiveSoftMax does not compute the
scores for all the word of the vocabulary for all the examples. It is
thus necessary to call the method adapt_target of the AdaptiveSoftMax
layer inside each forward pass.
| adapt_target | python | OFA-Sys/OFA | fairseq/fairseq/modules/adaptive_softmax.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/adaptive_softmax.py | Apache-2.0 |
def forward(self, input, target):
"""
Args:
input: (b x t x d)
target: (b x t)
Returns:
2 lists: output for each cutoff section and new targets by cut off
"""
input = input.contiguous().view(-1, input.size(-1))
input = self.dropout_mod... |
Args:
input: (b x t x d)
target: (b x t)
Returns:
2 lists: output for each cutoff section and new targets by cut off
| forward | python | OFA-Sys/OFA | fairseq/fairseq/modules/adaptive_softmax.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/adaptive_softmax.py | Apache-2.0 |
def get_log_prob(self, input, target):
"""
Computes the log probabilities for all the words of the vocabulary,
given a 2D tensor of hidden vectors.
"""
bsz, length, dim = input.size()
input = input.contiguous().view(-1, dim)
if target is not None:
_,... |
Computes the log probabilities for all the words of the vocabulary,
given a 2D tensor of hidden vectors.
| get_log_prob | python | OFA-Sys/OFA | fairseq/fairseq/modules/adaptive_softmax.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/adaptive_softmax.py | Apache-2.0 |
def checkpoint_wrapper(m, offload_to_cpu=False):
"""
A friendlier wrapper for performing activation checkpointing.
Compared to the PyTorch version, this version:
- wraps an nn.Module, so that all subsequent calls will use checkpointing
- handles keyword arguments in the forward
- handles non-Te... |
A friendlier wrapper for performing activation checkpointing.
Compared to the PyTorch version, this version:
- wraps an nn.Module, so that all subsequent calls will use checkpointing
- handles keyword arguments in the forward
- handles non-Tensor outputs from the forward
Usage::
chec... | checkpoint_wrapper | python | OFA-Sys/OFA | fairseq/fairseq/modules/checkpoint_activations.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/checkpoint_activations.py | Apache-2.0 |
def unwrap_checkpoint(m: torch.nn.Module):
"""
unwrap a module and its children from checkpoint_wrapper
"""
for module in m.modules():
if hasattr(module, "precheckpoint_forward"):
module.forward = module.precheckpoint_forward
del module.precheckpoint_forward
return m |
unwrap a module and its children from checkpoint_wrapper
| unwrap_checkpoint | python | OFA-Sys/OFA | fairseq/fairseq/modules/checkpoint_activations.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/checkpoint_activations.py | Apache-2.0 |
def pack_kwargs(*args, **kwargs) -> Tuple[List[str], List[Any]]:
"""
Usage::
kwarg_keys, flat_args = pack_kwargs(1, 2, a=3, b=4)
args, kwargs = unpack_kwargs(kwarg_keys, flat_args)
assert args == [1, 2]
assert kwargs == {"a": 3, "b": 4}
"""
kwarg_keys = []
flat_args ... |
Usage::
kwarg_keys, flat_args = pack_kwargs(1, 2, a=3, b=4)
args, kwargs = unpack_kwargs(kwarg_keys, flat_args)
assert args == [1, 2]
assert kwargs == {"a": 3, "b": 4}
| pack_kwargs | python | OFA-Sys/OFA | fairseq/fairseq/modules/checkpoint_activations.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/checkpoint_activations.py | Apache-2.0 |
def split_non_tensors(
mixed: Union[torch.Tensor, Tuple[Any]]
) -> Tuple[Tuple[torch.Tensor], Dict[str, List[Any]]]:
"""
Usage::
x = torch.Tensor([1])
y = torch.Tensor([2])
tensors, packed_non_tensors = split_non_tensors((x, y, None, 3))
recon = unpack_non_tensors(tensors, p... |
Usage::
x = torch.Tensor([1])
y = torch.Tensor([2])
tensors, packed_non_tensors = split_non_tensors((x, y, None, 3))
recon = unpack_non_tensors(tensors, packed_non_tensors)
assert recon == (x, y, None, 3)
| split_non_tensors | python | OFA-Sys/OFA | fairseq/fairseq/modules/checkpoint_activations.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/checkpoint_activations.py | Apache-2.0 |
def __init__(
self,
embed_dim,
channels,
depthwise_kernel_size,
dropout,
activation_fn="swish",
bias=False,
export=False,
):
"""
Args:
embed_dim: Embedding dimension
channels: Number of channels in depthwise conv... |
Args:
embed_dim: Embedding dimension
channels: Number of channels in depthwise conv layers
depthwise_kernel_size: Depthwise conv layer kernel size
dropout: dropout value
activation_fn: Activation function to use after depthwise convolution kernel
... | __init__ | python | OFA-Sys/OFA | fairseq/fairseq/modules/conformer_layer.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/conformer_layer.py | Apache-2.0 |
def forward(self, x):
"""
Args:
x: Input of shape B X T X C
Returns:
Tensor of shape B X T X C
"""
x = self.layer_norm(x)
# exchange the temporal dimension and the feature dimension
x = x.transpose(1, 2)
# GLU mechanism
x = s... |
Args:
x: Input of shape B X T X C
Returns:
Tensor of shape B X T X C
| forward | python | OFA-Sys/OFA | fairseq/fairseq/modules/conformer_layer.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/conformer_layer.py | Apache-2.0 |
def __init__(
self,
input_feat,
hidden_units,
dropout1,
dropout2,
activation_fn="swish",
bias=True,
):
"""
Args:
input_feat: Input feature dimension
hidden_units: Hidden unit dimension
dropout1: dropout value... |
Args:
input_feat: Input feature dimension
hidden_units: Hidden unit dimension
dropout1: dropout value for layer1
dropout2: dropout value for layer2
activation_fn: Name of activation function
bias: If linear layers should have bias
| __init__ | python | OFA-Sys/OFA | fairseq/fairseq/modules/conformer_layer.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/conformer_layer.py | Apache-2.0 |
def forward(self, x):
"""
Args:
x: Input Tensor of shape T X B X C
Returns:
Tensor of shape T X B X C
"""
x = self.layer_norm(x)
x = self.w_1(x)
x = self.activation(x)
x = self.dropout1(x)
x = self.w_2(x)
return sel... |
Args:
x: Input Tensor of shape T X B X C
Returns:
Tensor of shape T X B X C
| forward | python | OFA-Sys/OFA | fairseq/fairseq/modules/conformer_layer.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/conformer_layer.py | Apache-2.0 |
def __init__(
self,
embed_dim,
ffn_embed_dim,
attention_heads,
dropout,
use_fp16,
depthwise_conv_kernel_size=31,
activation_fn="swish",
attn_type=None,
pos_enc_type="abs",
):
"""
Args:
embed_dim: Input embedd... |
Args:
embed_dim: Input embedding dimension
ffn_embed_dim: FFN layer dimension
attention_heads: Number of attention heads in MHA
dropout: dropout value
depthwise_conv_kernel_size: Size of kernel in depthwise conv layer in convolution module
... | __init__ | python | OFA-Sys/OFA | fairseq/fairseq/modules/conformer_layer.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/conformer_layer.py | Apache-2.0 |
def forward(
self,
x,
encoder_padding_mask: Optional[torch.Tensor],
position_emb: Optional[torch.Tensor] = None,
):
"""
Args:
x: Tensor of shape T X B X C
encoder_padding_mask: Optional mask tensor
positions:
Returns:
... |
Args:
x: Tensor of shape T X B X C
encoder_padding_mask: Optional mask tensor
positions:
Returns:
Tensor of shape T X B X C
| forward | python | OFA-Sys/OFA | fairseq/fairseq/modules/conformer_layer.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/conformer_layer.py | Apache-2.0 |
def forward(
self,
query,
key,
value,
mask_future_timesteps=False,
key_padding_mask=None,
use_scalar_bias=False,
):
"""Input shape: Time x Batch x Channel
Self-attention can be implemented by passing in the same arguments for
query, key... | Input shape: Time x Batch x Channel
Self-attention can be implemented by passing in the same arguments for
query, key and value. Future timesteps can be masked with the
`mask_future_timesteps` argument. Padding elements can be excluded from
the key by passing a binary ByteTensor (`key_pa... | forward | python | OFA-Sys/OFA | fairseq/fairseq/modules/downsampled_multihead_attention.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/downsampled_multihead_attention.py | Apache-2.0 |
def GatedLinear(in_features, out_features, dropout=0.0, bias=True):
"""Weight-normalized Linear layer (input: B x T x C) with interspersed GLU units"""
return nn.Sequential(
Linear(in_features, out_features * 4, dropout, bias),
nn.GLU(),
Linear(out_features * 2, out_features * 2, dropout... | Weight-normalized Linear layer (input: B x T x C) with interspersed GLU units | GatedLinear | python | OFA-Sys/OFA | fairseq/fairseq/modules/downsampled_multihead_attention.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/downsampled_multihead_attention.py | Apache-2.0 |
def forward(self, x, incremental_state=None, query=None, unfold=None):
"""Assuming the input, x, of the shape T x B x C and producing an output in the shape T x B x C
args:
x: Input of shape T x B x C, i.e. (timesteps, batch_size, input_size)
incremental_state: A dict to keep the... | Assuming the input, x, of the shape T x B x C and producing an output in the shape T x B x C
args:
x: Input of shape T x B x C, i.e. (timesteps, batch_size, input_size)
incremental_state: A dict to keep the state
unfold: unfold the input or not. If not, we use the matrix tric... | forward | python | OFA-Sys/OFA | fairseq/fairseq/modules/dynamic_convolution.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/dynamic_convolution.py | Apache-2.0 |
def _forward_unfolded(self, x, incremental_state, query):
"""The conventional implementation of convolutions.
Unfolding the input by having a window shifting to the right."""
T, B, C = x.size()
K, H = self.kernel_size, self.num_heads
R = C // H
assert R * H == C == self.i... | The conventional implementation of convolutions.
Unfolding the input by having a window shifting to the right. | _forward_unfolded | python | OFA-Sys/OFA | fairseq/fairseq/modules/dynamic_convolution.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/dynamic_convolution.py | Apache-2.0 |
def _forward_expanded(self, x, incremental_stat, query):
"""Turn the convolution filters into band matrices and do matrix multiplication.
This is faster when the sequence is short, but less memory efficient.
This is not used in the decoder during inference.
"""
T, B, C = x.size()... | Turn the convolution filters into band matrices and do matrix multiplication.
This is faster when the sequence is short, but less memory efficient.
This is not used in the decoder during inference.
| _forward_expanded | python | OFA-Sys/OFA | fairseq/fairseq/modules/dynamic_convolution.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/dynamic_convolution.py | Apache-2.0 |
def forward(self, emissions, targets, masks, beam=None):
"""
Compute the conditional log-likelihood of a sequence of target tokens given emission scores
Args:
emissions (`~torch.Tensor`): Emission score are usually the unnormalized decoder output
``(batch_size, seq_l... |
Compute the conditional log-likelihood of a sequence of target tokens given emission scores
Args:
emissions (`~torch.Tensor`): Emission score are usually the unnormalized decoder output
``(batch_size, seq_len, vocab_size)``. We assume batch-first
targets (`~torc... | forward | python | OFA-Sys/OFA | fairseq/fairseq/modules/dynamic_crf_layer.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/dynamic_crf_layer.py | Apache-2.0 |
def forward_qkv(self, query, key, value, **kwargs):
"""Transform query, key and value.
Args:
query: Query tensor B X T1 X C
key: Key tensor B X T2 X C
value: Value tensor B X T2 X C
Returns:
torch.Tensor: Transformed query tensor B X n_head X T1... | Transform query, key and value.
Args:
query: Query tensor B X T1 X C
key: Key tensor B X T2 X C
value: Value tensor B X T2 X C
Returns:
torch.Tensor: Transformed query tensor B X n_head X T1 X d_k
torch.Tensor: Transformed key tensor B X n_h... | forward_qkv | python | OFA-Sys/OFA | fairseq/fairseq/modules/espnet_multihead_attention.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/espnet_multihead_attention.py | Apache-2.0 |
def forward_attention(self, value, scores, mask):
"""Compute attention context vector.
Args:
value: Transformed value B X n_head X T2 X d_k.
scores: Attention score B X n_head X T1 X T2
mask: Mask T2 X B
Returns:
torch.Tensor: Transformed value ... | Compute attention context vector.
Args:
value: Transformed value B X n_head X T2 X d_k.
scores: Attention score B X n_head X T1 X T2
mask: Mask T2 X B
Returns:
torch.Tensor: Transformed value B X T1 X d_model
weighted by the attention sc... | forward_attention | python | OFA-Sys/OFA | fairseq/fairseq/modules/espnet_multihead_attention.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/espnet_multihead_attention.py | Apache-2.0 |
def forward(self, query, key, value, key_padding_mask=None, **kwargs):
"""Compute scaled dot product attention.
Args:
query (torch.Tensor): Query tensor T X B X C
key (torch.Tensor): Key tensor T X B X C
value (torch.Tensor): Value tensor T X B X C
mask (t... | Compute scaled dot product attention.
Args:
query (torch.Tensor): Query tensor T X B X C
key (torch.Tensor): Key tensor T X B X C
value (torch.Tensor): Value tensor T X B X C
mask (torch.Tensor): Mask tensor T X B
Returns:
torch.Tensor: Output ... | forward | python | OFA-Sys/OFA | fairseq/fairseq/modules/espnet_multihead_attention.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/espnet_multihead_attention.py | Apache-2.0 |
def rel_shift(self, x):
"""Compute relative positional encoding.
Args:
x: Input tensor B X n_head X T X 2T-1
Returns:
torch.Tensor: Output tensor.
"""
zero_pad = torch.zeros((*x.size()[:3], 1), device=x.device, dtype=x.dtype)
x_padded = torch.cat([... | Compute relative positional encoding.
Args:
x: Input tensor B X n_head X T X 2T-1
Returns:
torch.Tensor: Output tensor.
| rel_shift | python | OFA-Sys/OFA | fairseq/fairseq/modules/espnet_multihead_attention.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/espnet_multihead_attention.py | Apache-2.0 |
def forward(self, query, key, value, pos_emb, key_padding_mask=None, **kwargs):
"""Compute scaled dot product attention.
Args:
query: Query tensor T X B X C
key: Key tensor T X B X C
value: Value tensor T X B X C
pos_emb: Positional embedding tensor B X 2T... | Compute scaled dot product attention.
Args:
query: Query tensor T X B X C
key: Key tensor T X B X C
value: Value tensor T X B X C
pos_emb: Positional embedding tensor B X 2T-1 X C
key_padding_mask: Mask tensor T X B
Returns:
torch.T... | forward | python | OFA-Sys/OFA | fairseq/fairseq/modules/espnet_multihead_attention.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/espnet_multihead_attention.py | Apache-2.0 |
def forward(self, query, key, value, key_padding_mask=None, **kwargs):
"""Compute rotary position attention.
Args:
query: Query tensor T X B X C
key: Key tensor T X B X C
value: Value tensor T X B X C
key_padding_mask: Mask tensor T X B
Returns:
... | Compute rotary position attention.
Args:
query: Query tensor T X B X C
key: Key tensor T X B X C
value: Value tensor T X B X C
key_padding_mask: Mask tensor T X B
Returns:
torch.Tensor: Output tensor T X B X D.
Notes:
Assume... | forward | python | OFA-Sys/OFA | fairseq/fairseq/modules/espnet_multihead_attention.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/espnet_multihead_attention.py | Apache-2.0 |
def __init__(
self,
dim,
num_vars,
temp,
groups,
combine_groups,
vq_dim,
time_first,
activation=nn.GELU(),
weight_proj_depth=1,
weight_proj_factor=1,
):
"""Vector quantization using gumbel softmax
Args:
... | Vector quantization using gumbel softmax
Args:
dim: input dimension (channels)
num_vars: number of quantized vectors per group
temp: temperature for training. this should be a tuple of 3 elements: (start, stop, decay factor)
groups: number of groups for vector qu... | __init__ | python | OFA-Sys/OFA | fairseq/fairseq/modules/gumbel_vector_quantizer.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/gumbel_vector_quantizer.py | Apache-2.0 |
def forward(self, x, incremental_state=None, unfold=False):
"""Assuming the input, x, of the shape T x B x C and producing an output in the shape T x B x C
args:
x: Input of shape T x B x C, i.e. (timesteps, batch_size, input_size)
incremental_state: A dict to keep the state
... | Assuming the input, x, of the shape T x B x C and producing an output in the shape T x B x C
args:
x: Input of shape T x B x C, i.e. (timesteps, batch_size, input_size)
incremental_state: A dict to keep the state
unfold: unfold the input or not. If not, we use the matrix tric... | forward | python | OFA-Sys/OFA | fairseq/fairseq/modules/lightweight_convolution.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/lightweight_convolution.py | Apache-2.0 |
def forward(self, input, incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None):
"""
Args:
incremental_state: Used to buffer signal; if not None, then input is
expected to contain a single frame. If the input order changes
between time ste... |
Args:
incremental_state: Used to buffer signal; if not None, then input is
expected to contain a single frame. If the input order changes
between time steps, call reorder_incremental_state.
Input:
Time x Batch x Channel during training
... | forward | python | OFA-Sys/OFA | fairseq/fairseq/modules/linearized_convolution.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/linearized_convolution.py | Apache-2.0 |
def forward(self, encoder_out, encoder_padding_mask, decoder_h, attn_state):
"""
:param torch.Tensor encoder_out: padded encoder hidden state B x T x D
:param torch.Tensor encoder_padding_mask: encoder padding mask
:param torch.Tensor decoder_h: decoder hidden state B x D
:param ... |
:param torch.Tensor encoder_out: padded encoder hidden state B x T x D
:param torch.Tensor encoder_padding_mask: encoder padding mask
:param torch.Tensor decoder_h: decoder hidden state B x D
:param torch.Tensor attn_prev: previous attention weight B x K x T
:return: attention w... | forward | python | OFA-Sys/OFA | fairseq/fairseq/modules/location_attention.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/location_attention.py | Apache-2.0 |
def forward(self, x: torch.Tensor):
"""Add positional encoding.
Args:
x : Input tensor T X B X C.
Returns:
torch.Tensor: Encoded tensor T X B X C.
"""
x = x.transpose(0, 1) # Change TBC to BTC
self.extend_pe(x)
pos_emb = self.pe[
... | Add positional encoding.
Args:
x : Input tensor T X B X C.
Returns:
torch.Tensor: Encoded tensor T X B X C.
| forward | python | OFA-Sys/OFA | fairseq/fairseq/modules/positional_embedding.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/positional_embedding.py | Apache-2.0 |
def quant_noise(module, p, block_size):
"""
Wraps modules and applies quantization noise to the weights for
subsequent quantization with Iterative Product Quantization as
described in "Training with Quantization Noise for Extreme Model Compression"
Args:
- module: nn.Module
- p: amo... |
Wraps modules and applies quantization noise to the weights for
subsequent quantization with Iterative Product Quantization as
described in "Training with Quantization Noise for Extreme Model Compression"
Args:
- module: nn.Module
- p: amount of Quantization Noise
- block_size:... | quant_noise | python | OFA-Sys/OFA | fairseq/fairseq/modules/quant_noise.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/quant_noise.py | Apache-2.0 |
def __init__(self, dim, base=10000, precision=torch.half):
"""Rotary positional embedding
Reference : https://blog.eleuther.ai/rotary-embeddings/
Paper: https://arxiv.org/pdf/2104.09864.pdf
Args:
dim: Dimension of embedding
base: Base value for exponential
... | Rotary positional embedding
Reference : https://blog.eleuther.ai/rotary-embeddings/
Paper: https://arxiv.org/pdf/2104.09864.pdf
Args:
dim: Dimension of embedding
base: Base value for exponential
precision: precision to use for numerical values
| __init__ | python | OFA-Sys/OFA | fairseq/fairseq/modules/rotary_positional_embedding.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/rotary_positional_embedding.py | Apache-2.0 |
def forward(self, x, seq_len=None):
"""
Args:
x: Input x with T X B X C
seq_len: Sequence length of input x
"""
if seq_len != self.seq_len_cached:
self.seq_len_cached = seq_len
t = torch.arange(seq_len, device=x.device).type_as(self.inv_fre... |
Args:
x: Input x with T X B X C
seq_len: Sequence length of input x
| forward | python | OFA-Sys/OFA | fairseq/fairseq/modules/rotary_positional_embedding.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/rotary_positional_embedding.py | Apache-2.0 |
def get_embedding(
num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None
):
"""Build sinusoidal embeddings.
This matches the implementation in tensor2tensor, but differs slightly
from the description in Section 3.5 of "Attention Is All You Need".
"""
... | Build sinusoidal embeddings.
This matches the implementation in tensor2tensor, but differs slightly
from the description in Section 3.5 of "Attention Is All You Need".
| get_embedding | python | OFA-Sys/OFA | fairseq/fairseq/modules/sinusoidal_positional_embedding.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/sinusoidal_positional_embedding.py | Apache-2.0 |
def forward(
self,
x,
encoder_padding_mask: Optional[Tensor],
attn_mask: Optional[Tensor] = None,
):
"""
Args:
x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`
encoder_padding_mask (ByteTensor): binary ByteTensor of shape
... |
Args:
x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)`
encoder_padding_mask (ByteTensor): binary ByteTensor of shape
`(batch, seq_len)` where padding elements are indicated by ``1``.
attn_mask (ByteTensor): binary tensor of shape `(tgt_le... | forward | python | OFA-Sys/OFA | fairseq/fairseq/modules/transformer_layer.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/transformer_layer.py | Apache-2.0 |
def init_bert_params(module):
"""
Initialize the weights specific to the BERT Model.
This overrides the default initializations depending on the specified arguments.
1. If normal_init_linear_weights is set then weights of linear
layer will be initialized using the normal distribution and
... |
Initialize the weights specific to the BERT Model.
This overrides the default initializations depending on the specified arguments.
1. If normal_init_linear_weights is set then weights of linear
layer will be initialized using the normal distribution and
bais will be set to the sp... | init_bert_params | python | OFA-Sys/OFA | fairseq/fairseq/modules/transformer_sentence_encoder.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/transformer_sentence_encoder.py | Apache-2.0 |
def forward(
self,
x: torch.Tensor,
self_attn_mask: Optional[torch.Tensor] = None,
self_attn_padding_mask: Optional[torch.Tensor] = None,
):
"""
LayerNorm is applied either before or after the self-attention/ffn
modules similar to the original Transformer impl... |
LayerNorm is applied either before or after the self-attention/ffn
modules similar to the original Transformer implementation.
| forward | python | OFA-Sys/OFA | fairseq/fairseq/modules/transformer_sentence_encoder_layer.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/transformer_sentence_encoder_layer.py | Apache-2.0 |
def initialize_centroids(self):
"""
Initializes the centroids by sampling random columns from W.
"""
in_features, out_features = self.W.size()
indices = torch.randint(
low=0, high=out_features, size=(self.n_centroids,)
).long()
self.centroids = self.W... |
Initializes the centroids by sampling random columns from W.
| initialize_centroids | python | OFA-Sys/OFA | fairseq/fairseq/modules/quantization/pq/em.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/quantization/pq/em.py | Apache-2.0 |
def step(self, i):
"""
There are two standard steps for each iteration: expectation (E) and
minimization (M). The E-step (assignment) is performed with an exhaustive
search and the M-step (centroid computation) is performed with
the exact solution.
Args:
- i:... |
There are two standard steps for each iteration: expectation (E) and
minimization (M). The E-step (assignment) is performed with an exhaustive
search and the M-step (centroid computation) is performed with
the exact solution.
Args:
- i: step number
Remarks:... | step | python | OFA-Sys/OFA | fairseq/fairseq/modules/quantization/pq/em.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/quantization/pq/em.py | Apache-2.0 |
def resolve_empty_clusters(self):
"""
If one cluster is empty, the most populated cluster is split into
two clusters by shifting the respective centroids. This is done
iteratively for a fixed number of tentatives.
"""
# empty clusters
counts = Counter(map(lambda ... |
If one cluster is empty, the most populated cluster is split into
two clusters by shifting the respective centroids. This is done
iteratively for a fixed number of tentatives.
| resolve_empty_clusters | python | OFA-Sys/OFA | fairseq/fairseq/modules/quantization/pq/em.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/quantization/pq/em.py | Apache-2.0 |
def compute_distances(self):
"""
For every centroid m, computes
||M - m[None, :]||_2
Remarks:
- We rely on PyTorch's broadcasting to speed up computations
and reduce the memory overhead
- Without chunking, the sizes in the broadca... |
For every centroid m, computes
||M - m[None, :]||_2
Remarks:
- We rely on PyTorch's broadcasting to speed up computations
and reduce the memory overhead
- Without chunking, the sizes in the broadcasting are modified as:
(n_... | compute_distances | python | OFA-Sys/OFA | fairseq/fairseq/modules/quantization/pq/em.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/quantization/pq/em.py | Apache-2.0 |
def assign(self):
"""
Assigns each column of W to its closest centroid, thus essentially
performing the E-step in train().
Remarks:
- The function must be called after train() or after loading
centroids using self.load(), otherwise it will return empty tensors
... |
Assigns each column of W to its closest centroid, thus essentially
performing the E-step in train().
Remarks:
- The function must be called after train() or after loading
centroids using self.load(), otherwise it will return empty tensors
| assign | python | OFA-Sys/OFA | fairseq/fairseq/modules/quantization/pq/em.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/quantization/pq/em.py | Apache-2.0 |
def save(self, path, layer):
"""
Saves centroids and assignments.
Args:
- path: folder used to save centroids and assignments
"""
torch.save(self.centroids, os.path.join(path, "{}_centroids.pth".format(layer)))
torch.save(
self.assignments, os.pa... |
Saves centroids and assignments.
Args:
- path: folder used to save centroids and assignments
| save | python | OFA-Sys/OFA | fairseq/fairseq/modules/quantization/pq/em.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/quantization/pq/em.py | Apache-2.0 |
def load(self, path, layer):
"""
Loads centroids and assignments from a given path
Args:
- path: folder use to load centroids and assignments
"""
self.centroids = torch.load(
os.path.join(path, "{}_centroids.pth".format(layer))
)
self.ass... |
Loads centroids and assignments from a given path
Args:
- path: folder use to load centroids and assignments
| load | python | OFA-Sys/OFA | fairseq/fairseq/modules/quantization/pq/em.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/quantization/pq/em.py | Apache-2.0 |
def _reshape(self, W):
"""
Reshapes the matrix W as expained in step (1).
"""
# fully connected: by convention the weight has size out_features x in_features
if len(W.size()) == 2:
self.out_features, self.in_features = W.size()
assert (
se... |
Reshapes the matrix W as expained in step (1).
| _reshape | python | OFA-Sys/OFA | fairseq/fairseq/modules/quantization/pq/pq.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/quantization/pq/pq.py | Apache-2.0 |
def decode(self):
"""
Returns the encoded full weight matrix. Must be called after
the encode function.
"""
# fully connected case
if "k_h" not in self.__dict__:
return (
self.centroids[self.assignments]
.reshape(-1, self.out_f... |
Returns the encoded full weight matrix. Must be called after
the encode function.
| decode | python | OFA-Sys/OFA | fairseq/fairseq/modules/quantization/pq/pq.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/quantization/pq/pq.py | Apache-2.0 |
def quantize_model_(
model,
size_tracker,
layers_to_quantize,
block_sizes_config,
n_centroids_config,
step=0,
n_iter=15,
eps=1e-6,
max_tentatives=100,
remove_weights=False,
verbose=True,
state_dict=None,
):
"""
Quantize a model in-place by stages. All the targeted... |
Quantize a model in-place by stages. All the targeted
layers are replaced by their quantized counterpart,
and the model is ready for the finetuning of the
centroids in a standard training loop (no modifications
required). Note that we do not quantize biases.
Args:
- model: a nn.Module
... | quantize_model_ | python | OFA-Sys/OFA | fairseq/fairseq/modules/quantization/pq/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/quantization/pq/utils.py | Apache-2.0 |
def get_param(module, layer_name, param_config):
"""
Given a quantization configuration, get the right parameter
for the module to be quantized.
Args:
- module: a nn.Module
- layer_name: the name of the layer
- param_config: a dict like
{
'Conv2d': ('kern... |
Given a quantization configuration, get the right parameter
for the module to be quantized.
Args:
- module: a nn.Module
- layer_name: the name of the layer
- param_config: a dict like
{
'Conv2d': ('kernel_size', {'(3, 3)': 9, '(1, 1)': 4}),
'Li... | get_param | python | OFA-Sys/OFA | fairseq/fairseq/modules/quantization/pq/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/quantization/pq/utils.py | Apache-2.0 |
def compute_size(self):
"""
Computes the size of the model (in MB).
"""
res = 0
for _, p in self.model.named_parameters():
res += p.numel()
return res * 4 / 1024 / 1024 |
Computes the size of the model (in MB).
| compute_size | python | OFA-Sys/OFA | fairseq/fairseq/modules/quantization/pq/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/quantization/pq/utils.py | Apache-2.0 |
def update(self, W, block_size, n_centroids):
"""
Updates the running statistics when quantizing a new layer.
"""
# bits per weights
bits_per_weight = np.log2(n_centroids) / block_size
self.n_quantized_layers += 1
# size of indexing the subvectors of size block_... |
Updates the running statistics when quantizing a new layer.
| update | python | OFA-Sys/OFA | fairseq/fairseq/modules/quantization/pq/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/quantization/pq/utils.py | Apache-2.0 |
def quantize_model_(model, p=0.2, bits=8, update_step=3000, method="histogram", remove_weights=False):
"""
Replaces all modules with their scalar quantized counterpart and
registers hooks to quantize the post-ativations of those modules.
Args:
- model: a nn.Module
- p: amount of noise (... |
Replaces all modules with their scalar quantized counterpart and
registers hooks to quantize the post-ativations of those modules.
Args:
- model: a nn.Module
- p: amount of noise (0 for no noise, 1 to quantize all the weights/activations)
- bits: number of bits
- update_ste... | quantize_model_ | python | OFA-Sys/OFA | fairseq/fairseq/modules/quantization/scalar/utils.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/modules/quantization/scalar/utils.py | Apache-2.0 |
def optimizer_config(self):
"""
Return a kwarg dictionary that will be used to override optimizer
args stored in checkpoints. This allows us to load a checkpoint and
resume training using a different set of optimizer args, e.g., with a
different learning rate.
Note : Conv... |
Return a kwarg dictionary that will be used to override optimizer
args stored in checkpoints. This allows us to load a checkpoint and
resume training using a different set of optimizer args, e.g., with a
different learning rate.
Note : Convergence issues empirically observed wit... | optimizer_config | python | OFA-Sys/OFA | fairseq/fairseq/optim/adafactor.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/optim/adafactor.py | Apache-2.0 |
def step(self, closure=None):
"""Performs a single optimization step.
Args:
closure (callable, optional): A closure that reevaluates the model
and returns the loss.
"""
loss = None
if closure is not None:
loss = closure()
for grou... | Performs a single optimization step.
Args:
closure (callable, optional): A closure that reevaluates the model
and returns the loss.
| step | python | OFA-Sys/OFA | fairseq/fairseq/optim/adafactor.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/optim/adafactor.py | Apache-2.0 |
def average_params(self):
"""Reduce Params is only used during BMUF distributed training."""
state_dict = self.optimizer.state_dict()
total_gpus = float(dist.get_world_size())
for _, value in state_dict["state"].items():
value["exp_avg"] /= total_gpus
value["exp_... | Reduce Params is only used during BMUF distributed training. | average_params | python | OFA-Sys/OFA | fairseq/fairseq/optim/adam.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/optim/adam.py | Apache-2.0 |
def build_optimizer(cls, cfg: DictConfig, params, **kwargs):
"""
Args:
cfg (omegaconf.DictConfig): fairseq args
params (iterable): iterable of parameters to optimize
"""
fp32_optimizer = optim.build_optimizer(cfg.optimizer, params)
return cls(cfg, params, ... |
Args:
cfg (omegaconf.DictConfig): fairseq args
params (iterable): iterable of parameters to optimize
| build_optimizer | python | OFA-Sys/OFA | fairseq/fairseq/optim/amp_optimizer.py | https://github.com/OFA-Sys/OFA/blob/master/fairseq/fairseq/optim/amp_optimizer.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.