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 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, alignment_layer: Optional[int] = 0, alignment_heads: Optional[int...
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 incremental_state (dict, optional): dictionary us...
forward
python
OFA-Sys/OFA
fairseq/examples/pointer_generator/pointer_generator_src/transformer_pg.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/pointer_generator/pointer_generator_src/transformer_pg.py
Apache-2.0
def output_layer( self, features: Tensor, attn: Tensor, src_tokens: Tensor, p_gens: Tensor ) -> Tensor: """ Project features to the vocabulary size and mix with the attention distributions. """ if self.force_p_gen is not None: ...
Project features to the vocabulary size and mix with the attention distributions.
output_layer
python
OFA-Sys/OFA
fairseq/examples/pointer_generator/pointer_generator_src/transformer_pg.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/pointer_generator/pointer_generator_src/transformer_pg.py
Apache-2.0
def get_normalized_probs( self, net_output: Tuple[Tensor, Optional[Dict[str, List[Optional[Tensor]]]]], log_probs: bool, sample: Optional[Dict[str, Tensor]] = None, ): """ Get normalized probabilities (or log probs) from a net's output. Pointer-generator netwo...
Get normalized probabilities (or log probs) from a net's output. Pointer-generator network output is already normalized.
get_normalized_probs
python
OFA-Sys/OFA
fairseq/examples/pointer_generator/pointer_generator_src/transformer_pg.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/pointer_generator/pointer_generator_src/transformer_pg.py
Apache-2.0
def main(): """ Helper script to encode raw text with the GPT-2 BPE using multiple processes. The encoder.json and vocab.bpe files can be obtained here: - https://dl.fbaipublicfiles.com/fairseq/gpt2_bpe/encoder.json - https://dl.fbaipublicfiles.com/fairseq/gpt2_bpe/vocab.bpe """ parser = ar...
Helper script to encode raw text with the GPT-2 BPE using multiple processes. The encoder.json and vocab.bpe files can be obtained here: - https://dl.fbaipublicfiles.com/fairseq/gpt2_bpe/encoder.json - https://dl.fbaipublicfiles.com/fairseq/gpt2_bpe/vocab.bpe
main
python
OFA-Sys/OFA
fairseq/examples/roberta/multiprocessing_bpe_encoder.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/roberta/multiprocessing_bpe_encoder.py
Apache-2.0
def encode_lines(self, lines): """ Encode a set of lines. All lines will be encoded together. """ enc_lines = [] for line in lines: line = line.strip() if len(line) == 0 and not self.args.keep_empty: return ["EMPTY", None] token...
Encode a set of lines. All lines will be encoded together.
encode_lines
python
OFA-Sys/OFA
fairseq/examples/roberta/multiprocessing_bpe_encoder.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/roberta/multiprocessing_bpe_encoder.py
Apache-2.0
def get_examples(data_dir, set_type): """ Extract paragraph and question-answer list from each json file """ examples = [] levels = ["middle", "high"] set_type_c = set_type.split("-") if len(set_type_c) == 2: levels = [set_type_c[1]] set_type = set_type_c[0] for level in...
Extract paragraph and question-answer list from each json file
get_examples
python
OFA-Sys/OFA
fairseq/examples/roberta/preprocess_RACE.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/roberta/preprocess_RACE.py
Apache-2.0
def main(): """ Helper script to extract paragraphs questions and answers from RACE datasets. """ parser = argparse.ArgumentParser() parser.add_argument( "--input-dir", help="input directory for downloaded RACE dataset", ) parser.add_argument( "--output-dir", ...
Helper script to extract paragraphs questions and answers from RACE datasets.
main
python
OFA-Sys/OFA
fairseq/examples/roberta/preprocess_RACE.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/roberta/preprocess_RACE.py
Apache-2.0
def load_dictionary(cls, filename): """Load the dictionary from the filename Args: filename (str): the filename """ dictionary = Dictionary.load(filename) dictionary.add_symbol("<mask>") return dictionary
Load the dictionary from the filename Args: filename (str): the filename
load_dictionary
python
OFA-Sys/OFA
fairseq/examples/roberta/commonsense_qa/commonsense_qa_task.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/roberta/commonsense_qa/commonsense_qa_task.py
Apache-2.0
def load_dataset( self, split, epoch=1, combine=False, data_path=None, return_only=False, **kwargs ): """Load a given dataset split. Args: split (str): name of the split (e.g., train, valid, test) """ def binarize(s, append_bos=False): if self.bpe is...
Load a given dataset split. Args: split (str): name of the split (e.g., train, valid, test)
load_dataset
python
OFA-Sys/OFA
fairseq/examples/roberta/commonsense_qa/commonsense_qa_task.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/roberta/commonsense_qa/commonsense_qa_task.py
Apache-2.0
def add_args(parser): """Add criterion-specific arguments to the parser.""" parser.add_argument("--wsc-margin-alpha", type=float, metavar="A", default=1.0) parser.add_argument("--wsc-margin-beta", type=float, metavar="B", default=0.0) parser.add_argument( "--wsc-cross-entropy...
Add criterion-specific arguments to the parser.
add_args
python
OFA-Sys/OFA
fairseq/examples/roberta/wsc/wsc_criterion.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/roberta/wsc/wsc_criterion.py
Apache-2.0
def clean_cache( self, incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]], end_id: Optional[int] = None, ): """ Clean cache in the monotonic layers. The cache is generated because of a forward pass of decoder has run but no prediction, so that...
Clean cache in the monotonic layers. The cache is generated because of a forward pass of decoder has run but no prediction, so that the self attention key value in decoder is written in the incremental state. end_id is the last idx of the layers
clean_cache
python
OFA-Sys/OFA
fairseq/examples/simultaneous_translation/models/transformer_monotonic_attention.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/simultaneous_translation/models/transformer_monotonic_attention.py
Apache-2.0
def extract_features( self, prev_output_tokens, encoder_out: Optional[Dict[str, List[Tensor]]], incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None, full_context_alignment: bool = False, # unused alignment_layer: Optional[int] = None, # unused ...
Similar to *forward* but only return features. Returns: tuple: - the decoder's features of shape `(batch, tgt_len, embed_dim)` - a dictionary with any model-specific outputs
extract_features
python
OFA-Sys/OFA
fairseq/examples/simultaneous_translation/models/transformer_monotonic_attention.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/simultaneous_translation/models/transformer_monotonic_attention.py
Apache-2.0
def energy_from_qk( self, query: Tensor, key: Tensor, energy_type: str, key_padding_mask: Optional[Tensor] = None, bias: int = 0 ): """ Compute energy from query and key q_func_value is a tuple looks like (q_proj_func, q_tensor) ...
Compute energy from query and key q_func_value is a tuple looks like (q_proj_func, q_tensor) q_tensor size: bsz, tgt_len, emb_dim k_tensor size: bsz, src_len, emb_dim key_padding_mask size: bsz, src_len attn_mask: bsz, src_len
energy_from_qk
python
OFA-Sys/OFA
fairseq/examples/simultaneous_translation/modules/monotonic_multihead_attention.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/simultaneous_translation/modules/monotonic_multihead_attention.py
Apache-2.0
def monotonic_attention_process_infer( self, query: Optional[Tensor], key: Optional[Tensor], incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]], ): """ Monotonic attention at inference time Notice that this function is designed for simuleval n...
Monotonic attention at inference time Notice that this function is designed for simuleval not sequence_generator
monotonic_attention_process_infer
python
OFA-Sys/OFA
fairseq/examples/simultaneous_translation/modules/monotonic_multihead_attention.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/simultaneous_translation/modules/monotonic_multihead_attention.py
Apache-2.0
def monotonic_attention_process_train( self, query: Optional[Tensor], key: Optional[Tensor], key_padding_mask: Optional[Tensor] = None, ): """ Calculating monotonic attention process for training Including: stepwise probability: p_choose ...
Calculating monotonic attention process for training Including: stepwise probability: p_choose expected hard alignment: alpha expected soft attention: beta
monotonic_attention_process_train
python
OFA-Sys/OFA
fairseq/examples/simultaneous_translation/modules/monotonic_multihead_attention.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/simultaneous_translation/modules/monotonic_multihead_attention.py
Apache-2.0
def forward( self, query: Optional[Tensor], key: Optional[Tensor], value: Optional[Tensor], key_padding_mask: Optional[Tensor] = None, attn_mask: Optional[Tensor] = None, incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None, need_weig...
query: tgt_len, bsz, embed_dim key: src_len, bsz, embed_dim value: src_len, bsz, embed_dim
forward
python
OFA-Sys/OFA
fairseq/examples/simultaneous_translation/modules/monotonic_multihead_attention.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/simultaneous_translation/modules/monotonic_multihead_attention.py
Apache-2.0
def forward( self, x, encoder_out: Optional[Tensor] = None, encoder_padding_mask: Optional[Tensor] = None, incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]] = None, prev_self_attn_state: Optional[List[Tensor]] = None, prev_attn_state: Optional[Li...
Args: x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)` encoder_padding_mask (ByteTensor, optional): binary ByteTensor of shape `(batch, src_len)` where padding elements are indicated by ``1``. need_attn (bool, optional): r...
forward
python
OFA-Sys/OFA
fairseq/examples/simultaneous_translation/modules/monotonic_transformer_layer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/simultaneous_translation/modules/monotonic_transformer_layer.py
Apache-2.0
def exclusive_cumprod(tensor, dim: int, eps: float = 1e-10): """ Implementing exclusive cumprod. There is cumprod in pytorch, however there is no exclusive mode. cumprod(x) = [x1, x1x2, x2x3x4, ..., prod_{i=1}^n x_i] exclusive means cumprod(x) = [1, x1, x1x2, x1x2x3, ..., prod_{i=1}^{n-1} x_i] ...
Implementing exclusive cumprod. There is cumprod in pytorch, however there is no exclusive mode. cumprod(x) = [x1, x1x2, x2x3x4, ..., prod_{i=1}^n x_i] exclusive means cumprod(x) = [1, x1, x1x2, x1x2x3, ..., prod_{i=1}^{n-1} x_i]
exclusive_cumprod
python
OFA-Sys/OFA
fairseq/examples/simultaneous_translation/utils/functions.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/simultaneous_translation/utils/functions.py
Apache-2.0
def safe_cumprod(tensor, dim: int, eps: float = 1e-10): """ An implementation of cumprod to prevent precision issue. cumprod(x) = [x1, x1x2, x1x2x3, ....] = [exp(log(x1)), exp(log(x1) + log(x2)), exp(log(x1) + log(x2) + log(x3)), ...] = exp(cumsum(log(x))) """ if (tensor + eps < 0).any(...
An implementation of cumprod to prevent precision issue. cumprod(x) = [x1, x1x2, x1x2x3, ....] = [exp(log(x1)), exp(log(x1) + log(x2)), exp(log(x1) + log(x2) + log(x3)), ...] = exp(cumsum(log(x)))
safe_cumprod
python
OFA-Sys/OFA
fairseq/examples/simultaneous_translation/utils/functions.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/simultaneous_translation/utils/functions.py
Apache-2.0
def expected_soft_attention( alpha: Tensor, soft_energy: Tensor, padding_mask: Optional[Tensor] = None, chunk_size: Optional[int] = None, eps: float = 1e-10 ): """ Function to compute expected soft attention for monotonic infinite lookback attention from expected alignment and soft e...
Function to compute expected soft attention for monotonic infinite lookback attention from expected alignment and soft energy. Reference: Monotonic Chunkwise Attention https://arxiv.org/abs/1712.05382 Monotonic Infinite Lookback Attention for Simultaneous Machine Translation https://a...
expected_soft_attention
python
OFA-Sys/OFA
fairseq/examples/simultaneous_translation/utils/monotonic_attention.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/simultaneous_translation/utils/monotonic_attention.py
Apache-2.0
def mass_preservation( alpha: Tensor, padding_mask: Optional[Tensor] = None, left_padding: bool = False ): """ Function to compute the mass perservation for alpha. This means that the residual weights of alpha will be assigned to the last token. Reference: Monotonic Infinite Lookbac...
Function to compute the mass perservation for alpha. This means that the residual weights of alpha will be assigned to the last token. Reference: Monotonic Infinite Lookback Attention for Simultaneous Machine Translation https://arxiv.org/abs/1906.05218 alpha: bsz, tgt_len, src_len pa...
mass_preservation
python
OFA-Sys/OFA
fairseq/examples/simultaneous_translation/utils/monotonic_attention.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/simultaneous_translation/utils/monotonic_attention.py
Apache-2.0
def learnable_p_choose( energy, noise_mean: float = 0.0, noise_var: float = 0.0, training: bool = True ): """ Calculating step wise prob for reading and writing 1 to read, 0 to write energy: bsz, tgt_len, src_len """ noise = 0 if training: # add noise here to encoura...
Calculating step wise prob for reading and writing 1 to read, 0 to write energy: bsz, tgt_len, src_len
learnable_p_choose
python
OFA-Sys/OFA
fairseq/examples/simultaneous_translation/utils/p_choose_strategy.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/simultaneous_translation/utils/p_choose_strategy.py
Apache-2.0
def get_tokens(self, idxs): """Normalize tokens by handling CTC blank, ASG replabels, etc.""" idxs = (g[0] for g in it.groupby(idxs)) idxs = filter(lambda x: x != self.blank, idxs) return torch.LongTensor(list(idxs))
Normalize tokens by handling CTC blank, ASG replabels, etc.
get_tokens
python
OFA-Sys/OFA
fairseq/examples/speech_recognition/w2l_decoder.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_recognition/w2l_decoder.py
Apache-2.0
def get_timesteps(self, token_idxs: List[int]) -> List[int]: """Returns frame numbers corresponding to every non-blank token. Parameters ---------- token_idxs : List[int] IDs of decoded tokens. Returns ------- List[int] Frame numbers corr...
Returns frame numbers corresponding to every non-blank token. Parameters ---------- token_idxs : List[int] IDs of decoded tokens. Returns ------- List[int] Frame numbers corresponding to every non-blank token.
get_timesteps
python
OFA-Sys/OFA
fairseq/examples/speech_recognition/w2l_decoder.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_recognition/w2l_decoder.py
Apache-2.0
def score(self, state: LMState, token_index: int, no_cache: bool = False): """ Evaluate language model based on the current lm state and new word Parameters: ----------- state: current lm state token_index: index of the word (can be lexicon index then...
Evaluate language model based on the current lm state and new word Parameters: ----------- state: current lm state token_index: index of the word (can be lexicon index then you should store inside LM the mapping between indices of lexic...
score
python
OFA-Sys/OFA
fairseq/examples/speech_recognition/w2l_decoder.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_recognition/w2l_decoder.py
Apache-2.0
def forward(self, model, sample, reduction="sum", log_probs=True): """Computes the cross entropy with accuracy metric for the given sample. This is similar to CrossEntropyCriterion in fairseq, but also computes accuracy metrics as part of logging Args: logprobs (Torch.tenso...
Computes the cross entropy with accuracy metric for the given sample. This is similar to CrossEntropyCriterion in fairseq, but also computes accuracy metrics as part of logging Args: logprobs (Torch.tensor) of shape N, T, D i.e. batchsize, timesteps, dimensions ...
forward
python
OFA-Sys/OFA
fairseq/examples/speech_recognition/criterions/cross_entropy_acc.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_recognition/criterions/cross_entropy_acc.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``.""" return ( self.frame_sizes[index], len(self.tgt[index]) if self.tgt is not None else 0, )
Return an example's size as a float or tuple. This value is used when filtering a dataset with ``--max-positions``.
size
python
OFA-Sys/OFA
fairseq/examples/speech_recognition/data/asr_dataset.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_recognition/data/asr_dataset.py
Apache-2.0
def _collate_frames(self, frames): """Convert a list of 2d frames into a padded 3d tensor Args: frames (list): list of 2d frames of size L[i]*f_dim. Where L[i] is length of i-th frame and f_dim is static dimension of features Returns: 3d tensor of size len...
Convert a list of 2d frames into a padded 3d tensor Args: frames (list): list of 2d frames of size L[i]*f_dim. Where L[i] is length of i-th frame and f_dim is static dimension of features Returns: 3d tensor of size len(frames)*len_max*f_dim where len_max is max of...
_collate_frames
python
OFA-Sys/OFA
fairseq/examples/speech_recognition/data/collaters.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_recognition/data/collaters.py
Apache-2.0
def collate(self, samples): """ utility function to collate samples into batch for speech recognition. """ if len(samples) == 0: return {} # parse samples into torch tensors parsed_samples = [] for s in samples: # skip invalid samples ...
utility function to collate samples into batch for speech recognition.
collate
python
OFA-Sys/OFA
fairseq/examples/speech_recognition/data/collaters.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_recognition/data/collaters.py
Apache-2.0
def lengths_to_encoder_padding_mask(lengths, batch_first=False): """ convert lengths (a 1-D Long/Int tensor) to 2-D binary tensor Args: lengths: a (B, )-shaped tensor Return: max_length: maximum length of B sequences encoder_padding_mask: a (max_length, B) binary mask, where ...
convert lengths (a 1-D Long/Int tensor) to 2-D binary tensor Args: lengths: a (B, )-shaped tensor Return: max_length: maximum length of B sequences encoder_padding_mask: a (max_length, B) binary mask, where [t, b] = 0 for t < lengths[b] and 1 otherwise TODO: k...
lengths_to_encoder_padding_mask
python
OFA-Sys/OFA
fairseq/examples/speech_recognition/data/data_utils.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_recognition/data/data_utils.py
Apache-2.0
def encoder_padding_mask_to_lengths( encoder_padding_mask, max_lengths, batch_size, device ): """ convert encoder_padding_mask (2-D binary tensor) to a 1-D tensor Conventionally, encoder output contains a encoder_padding_mask, which is a 2-D mask in a shape (T, B), whose (t, b) element indicate whe...
convert encoder_padding_mask (2-D binary tensor) to a 1-D tensor Conventionally, encoder output contains a encoder_padding_mask, which is a 2-D mask in a shape (T, B), whose (t, b) element indicate whether encoder_out[t, b] is a valid output (=0) or not (=1). Occasionally, we need to convert this ...
encoder_padding_mask_to_lengths
python
OFA-Sys/OFA
fairseq/examples/speech_recognition/data/data_utils.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_recognition/data/data_utils.py
Apache-2.0
def pack_replabels(tokens, dictionary, max_reps): """ Pack a token sequence so that repeated symbols are replaced by replabels """ if len(tokens) == 0 or max_reps <= 0: return tokens replabel_value_to_idx = [0] * (max_reps + 1) for i in range(1, max_reps + 1): replabel_value_to_...
Pack a token sequence so that repeated symbols are replaced by replabels
pack_replabels
python
OFA-Sys/OFA
fairseq/examples/speech_recognition/data/replabels.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_recognition/data/replabels.py
Apache-2.0
def unpack_replabels(tokens, dictionary, max_reps): """ Unpack a token sequence so that replabels are replaced by repeated symbols """ if len(tokens) == 0 or max_reps <= 0: return tokens replabel_idx_to_value = {} for i in range(1, max_reps + 1): replabel_idx_to_value[dictionary...
Unpack a token sequence so that replabels are replaced by repeated symbols
unpack_replabels
python
OFA-Sys/OFA
fairseq/examples/speech_recognition/data/replabels.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_recognition/data/replabels.py
Apache-2.0
def __init__( self, input_feat_per_channel, vggblock_config=DEFAULT_ENC_VGGBLOCK_CONFIG, transformer_config=DEFAULT_ENC_TRANSFORMER_CONFIG, encoder_output_dim=512, in_channels=1, transformer_context=None, transformer_sampling=None, ): """constr...
constructor for VGGTransformerEncoder Args: - input_feat_per_channel: feature dim (not including stacked, just base feature) - in_channel: # input channels (e.g., if stack 8 feature vector together, this is 8) - vggblock_config: configuration of...
__init__
python
OFA-Sys/OFA
fairseq/examples/speech_recognition/models/vggtransformer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_recognition/models/vggtransformer.py
Apache-2.0
def forward(self, src_tokens, src_lengths, **kwargs): """ 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() x = src_tokens.view(bsz, max_seq_len, self.in_channels, self.i...
src_tokens: padded tensor (B, T, C * feat) src_lengths: tensor of original lengths of input utterances (B,)
forward
python
OFA-Sys/OFA
fairseq/examples/speech_recognition/models/vggtransformer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_recognition/models/vggtransformer.py
Apache-2.0
def parse_transformer_context(self, transformer_context): """ transformer_context can be the following: - None; indicates no context is used, i.e., transformer can access full context - a tuple/list of two int; indicates left and right context, any number <0 i...
transformer_context can be the following: - None; indicates no context is used, i.e., transformer can access full context - a tuple/list of two int; indicates left and right context, any number <0 indicates infinite context * e.g., (5, 6) indicates th...
parse_transformer_context
python
OFA-Sys/OFA
fairseq/examples/speech_recognition/models/vggtransformer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_recognition/models/vggtransformer.py
Apache-2.0
def parse_transformer_sampling(self, transformer_sampling, num_layers): """ parsing transformer sampling configuration Args: - transformer_sampling, accepted input: * None, indicating no sampling * an Iterable with int (>0) as element - nu...
parsing transformer sampling configuration Args: - transformer_sampling, accepted input: * None, indicating no sampling * an Iterable with int (>0) as element - num_layers, expected number of transformer layers, must match with the ...
parse_transformer_sampling
python
OFA-Sys/OFA
fairseq/examples/speech_recognition/models/vggtransformer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_recognition/models/vggtransformer.py
Apache-2.0
def slice(self, embedding, padding_mask, attn_mask, sampling_factor): """ embedding is a (T, B, D) tensor padding_mask is a (B, T) tensor or None attn_mask is a (T, T) tensor or None """ embedding = embedding[::sampling_factor, :, :] if padding_mask is not None: ...
embedding is a (T, B, D) tensor padding_mask is a (B, T) tensor or None attn_mask is a (T, T) tensor or None
slice
python
OFA-Sys/OFA
fairseq/examples/speech_recognition/models/vggtransformer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_recognition/models/vggtransformer.py
Apache-2.0
def lengths_to_attn_mask(self, input_lengths, subsampling_factor=1): """ create attention mask according to sequence lengths and transformer context Args: - input_lengths: (B, )-shape Int/Long tensor; input_lengths[b] is the length of b-th sequence ...
create attention mask according to sequence lengths and transformer context Args: - input_lengths: (B, )-shape Int/Long tensor; input_lengths[b] is the length of b-th sequence - subsampling_factor: int * Note that the left_context and right...
lengths_to_attn_mask
python
OFA-Sys/OFA
fairseq/examples/speech_recognition/models/vggtransformer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_recognition/models/vggtransformer.py
Apache-2.0
def forward(self, prev_output_tokens, encoder_out=None, incremental_state=None): """ Args: prev_output_tokens (LongTensor): previous decoder outputs of shape `(batch, tgt_len)`, for input feeding/teacher forcing encoder_out (Tensor, optional): output from the enco...
Args: prev_output_tokens (LongTensor): previous decoder outputs of shape `(batch, tgt_len)`, for input feeding/teacher forcing encoder_out (Tensor, optional): output from the encoder, used for encoder-side attention incremental_state (dict): d...
forward
python
OFA-Sys/OFA
fairseq/examples/speech_recognition/models/vggtransformer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_recognition/models/vggtransformer.py
Apache-2.0
def LinearizedConv1d(in_channels, out_channels, kernel_size, dropout=0, **kwargs): """Weight-normalized Conv1d layer optimized for decoding""" m = LinearizedConvolution(in_channels, out_channels, kernel_size, **kwargs) std = math.sqrt((4 * (1.0 - dropout)) / (m.kernel_size[0] * in_channels)) nn.init.nor...
Weight-normalized Conv1d layer optimized for decoding
LinearizedConv1d
python
OFA-Sys/OFA
fairseq/examples/speech_recognition/models/vggtransformer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_recognition/models/vggtransformer.py
Apache-2.0
def merge_shards(self) -> None: """Merges all shard files into shard 0, then removes shard suffix.""" shard_id = self.data_parallel_rank num_shards = self.data_parallel_world_size if self.data_parallel_world_size > 1: def merge_shards_with_root(fname: str) -> None: ...
Merges all shard files into shard 0, then removes shard suffix.
merge_shards
python
OFA-Sys/OFA
fairseq/examples/speech_recognition/new/infer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_recognition/new/infer.py
Apache-2.0
def get_wer_file(cfg: InferConfig) -> Path: """Hashes the decoding parameters to a unique file ID.""" base_path = "wer" if cfg.decoding.results_path is not None: base_path = os.path.join(cfg.decoding.results_path, base_path) if cfg.decoding.unique_wer_file: yaml_str = OmegaConf.to_yaml(...
Hashes the decoding parameters to a unique file ID.
get_wer_file
python
OFA-Sys/OFA
fairseq/examples/speech_recognition/new/infer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_recognition/new/infer.py
Apache-2.0
def main(cfg: InferConfig) -> float: """Entry point for main processing logic. Args: cfg: The inferance configuration to use. wer: Optional shared memory pointer for returning the WER. If not None, the final WER value will be written here instead of being returned. Returns: ...
Entry point for main processing logic. Args: cfg: The inferance configuration to use. wer: Optional shared memory pointer for returning the WER. If not None, the final WER value will be written here instead of being returned. Returns: The final WER if `wer` is None, otherwi...
main
python
OFA-Sys/OFA
fairseq/examples/speech_recognition/new/infer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_recognition/new/infer.py
Apache-2.0
def score( self, state: LMState, token_index: int, no_cache: bool = False, ) -> Tuple[LMState, int]: """ Evaluate language model based on the current lm state and new word Parameters: ----------- state: current lm state token_index: ind...
Evaluate language model based on the current lm state and new word Parameters: ----------- state: current lm state token_index: index of the word (can be lexicon index then you should store inside LM the mapping between indices of lexic...
score
python
OFA-Sys/OFA
fairseq/examples/speech_recognition/new/decoders/flashlight_decoder.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_recognition/new/decoders/flashlight_decoder.py
Apache-2.0
def get_asr_dataset_from_json(data_json_path, tgt_dict): """ Parse data json and create dataset. See scripts/asr_prep_json.py which pack json from raw files Json example: { "utts": { "4771-29403-0025": { "input": { "length_ms": 170, "path": "/...
Parse data json and create dataset. See scripts/asr_prep_json.py which pack json from raw files Json example: { "utts": { "4771-29403-0025": { "input": { "length_ms": 170, "path": "/tmp/file1.flac" }, "output": { ...
get_asr_dataset_from_json
python
OFA-Sys/OFA
fairseq/examples/speech_recognition/tasks/speech_recognition.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_recognition/tasks/speech_recognition.py
Apache-2.0
def get_wer_alignment_codes(hyp_str, ref_str): """ INPUT: hypothesis string, reference string OUTPUT: List of alignment codes (intermediate results from WER computation) """ t = WERTransformer(hyp_str, ref_str, verbose=0) return t.ed_.align(str2toks(ref_str), str2toks(hyp_str)).codes
INPUT: hypothesis string, reference string OUTPUT: List of alignment codes (intermediate results from WER computation)
get_wer_alignment_codes
python
OFA-Sys/OFA
fairseq/examples/speech_recognition/utils/wer_utils.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_recognition/utils/wer_utils.py
Apache-2.0
def batch_mel_spectral_distortion( y1, y2, sr, normalize_type="path", mel_fn=None ): """ https://arxiv.org/pdf/2011.03568.pdf Same as Mel Cepstral Distortion, but computed on log-mel spectrograms. """ if mel_fn is None or mel_fn.sample_rate != sr: mel_fn = torchaudio.transforms.MelS...
ERROR: type should be string, got "\n https://arxiv.org/pdf/2011.03568.pdf\n\n Same as Mel Cepstral Distortion, but computed on log-mel spectrograms.\n "
batch_mel_spectral_distortion
python
OFA-Sys/OFA
fairseq/examples/speech_synthesis/utils.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_synthesis/utils.py
Apache-2.0
def gross_pitch_error(true_t, true_f, est_t, est_f): """The relative frequency in percent of pitch estimates that are outside a threshold around the true pitch. Only frames that are considered pitched by both the ground truth and the estimator (if applicable) are considered. """ correct_frames ...
The relative frequency in percent of pitch estimates that are outside a threshold around the true pitch. Only frames that are considered pitched by both the ground truth and the estimator (if applicable) are considered.
gross_pitch_error
python
OFA-Sys/OFA
fairseq/examples/speech_synthesis/utils.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_synthesis/utils.py
Apache-2.0
def run_asr(asr_dir, split, w2v_ckpt, w2v_label, res_dir): """ results will be saved at {res_dir}/{ref,hypo}.word-{w2v_ckpt.filename}-{split}.txt """ cmd = ["python", "-m", "examples.speech_recognition.infer"] cmd += [str(asr_dir.resolve())] cmd += ["--task", "audio_finetuning", "--nbest", "...
results will be saved at {res_dir}/{ref,hypo}.word-{w2v_ckpt.filename}-{split}.txt
run_asr
python
OFA-Sys/OFA
fairseq/examples/speech_synthesis/evaluation/eval_asr.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_synthesis/evaluation/eval_asr.py
Apache-2.0
def compute_error_rate(hyp_wrd_path, ref_wrd_path, unit="word"): """each line is "<text> (None-<index>)" """ tokenize_line = { "word": lambda x: re.sub(r" \(.*\)$", "", x.rstrip()).split(), "char": lambda x: list(re.sub(r" \(.*\)$", "", x.rstrip())) }.get(unit) if tokenize_line is None: ...
each line is "<text> (None-<index>)"
compute_error_rate
python
OFA-Sys/OFA
fairseq/examples/speech_synthesis/evaluation/eval_asr.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_synthesis/evaluation/eval_asr.py
Apache-2.0
def difference_function(x, n, tau_max): """ Compute difference function of data x. This solution is implemented directly with Numpy fft. :param x: audio data :param n: length of data :param tau_max: integration window size :return: difference function :rtype: list """ x = np.a...
Compute difference function of data x. This solution is implemented directly with Numpy fft. :param x: audio data :param n: length of data :param tau_max: integration window size :return: difference function :rtype: list
difference_function
python
OFA-Sys/OFA
fairseq/examples/speech_synthesis/evaluation/eval_f0.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_synthesis/evaluation/eval_f0.py
Apache-2.0
def cumulative_mean_normalized_difference_function(df, n): """ Compute cumulative mean normalized difference function (CMND). :param df: Difference function :param n: length of data :return: cumulative mean normalized difference function :rtype: list """ # scipy method cmn_df = df[...
Compute cumulative mean normalized difference function (CMND). :param df: Difference function :param n: length of data :return: cumulative mean normalized difference function :rtype: list
cumulative_mean_normalized_difference_function
python
OFA-Sys/OFA
fairseq/examples/speech_synthesis/evaluation/eval_f0.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_synthesis/evaluation/eval_f0.py
Apache-2.0
def get_pitch(cmdf, tau_min, tau_max, harmo_th=0.1): """ Return fundamental period of a frame based on CMND function. :param cmdf: Cumulative Mean Normalized Difference function :param tau_min: minimum period for speech :param tau_max: maximum period for speech :param harmo_th: harmonicity thre...
Return fundamental period of a frame based on CMND function. :param cmdf: Cumulative Mean Normalized Difference function :param tau_min: minimum period for speech :param tau_max: maximum period for speech :param harmo_th: harmonicity threshold to determine if it is necessary to compute pitch f...
get_pitch
python
OFA-Sys/OFA
fairseq/examples/speech_synthesis/evaluation/eval_f0.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_synthesis/evaluation/eval_f0.py
Apache-2.0
def valid_length(self, length): """ Return the nearest valid length to use with the model so that there is no time steps left over in a convolutions, e.g. for all layers, size of the input - kernel_size % stride = 0. If the mixture has a valid length, the estimated sources ...
Return the nearest valid length to use with the model so that there is no time steps left over in a convolutions, e.g. for all layers, size of the input - kernel_size % stride = 0. If the mixture has a valid length, the estimated sources will have exactly the same length. ...
valid_length
python
OFA-Sys/OFA
fairseq/examples/speech_synthesis/preprocessing/denoiser/demucs.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_synthesis/preprocessing/denoiser/demucs.py
Apache-2.0
def fast_conv(conv, x): """ Faster convolution evaluation if either kernel size is 1 or length of sequence is 1. """ batch, chin, length = x.shape chout, chin, kernel = conv.weight.shape assert batch == 1 if kernel == 1: x = x.view(chin, length) out = th.addmm(conv.bias.v...
Faster convolution evaluation if either kernel size is 1 or length of sequence is 1.
fast_conv
python
OFA-Sys/OFA
fairseq/examples/speech_synthesis/preprocessing/denoiser/demucs.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_synthesis/preprocessing/denoiser/demucs.py
Apache-2.0
def flush(self): """ Flush remaining audio by padding it with zero. Call this when you have no more input and want to get back the last chunk of audio. """ pending_length = self.pending.shape[1] padding = th.zeros( self.demucs.chin, self.total_length, device=s...
Flush remaining audio by padding it with zero. Call this when you have no more input and want to get back the last chunk of audio.
flush
python
OFA-Sys/OFA
fairseq/examples/speech_synthesis/preprocessing/denoiser/demucs.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_synthesis/preprocessing/denoiser/demucs.py
Apache-2.0
def feed(self, wav): """ Apply the model to mix using true real time evaluation. Normalization is done online as is the resampling. """ begin = time.time() demucs = self.demucs resample_buffer = self.resample_buffer stride = self.stride resample = ...
Apply the model to mix using true real time evaluation. Normalization is done online as is the resampling.
feed
python
OFA-Sys/OFA
fairseq/examples/speech_synthesis/preprocessing/denoiser/demucs.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_synthesis/preprocessing/denoiser/demucs.py
Apache-2.0
def get_model(args): """ Load local model package or torchhub pre-trained model. """ if args.model_path: logger.info("Loading model from %s", args.model_path) pkg = torch.load(args.model_path) model = deserialize_model(pkg) elif args.dns64: logger.info("Loading pre-tr...
Load local model package or torchhub pre-trained model.
get_model
python
OFA-Sys/OFA
fairseq/examples/speech_synthesis/preprocessing/denoiser/pretrained.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_synthesis/preprocessing/denoiser/pretrained.py
Apache-2.0
def capture_init(init): """capture_init. Decorate `__init__` with this, and you can then recover the *args and **kwargs passed to it in `self._init_args_kwargs` """ @functools.wraps(init) def __init__(self, *args, **kwargs): self._init_args_kwargs = (args, kwargs) init(self, *ar...
capture_init. Decorate `__init__` with this, and you can then recover the *args and **kwargs passed to it in `self._init_args_kwargs`
capture_init
python
OFA-Sys/OFA
fairseq/examples/speech_synthesis/preprocessing/denoiser/utils.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_synthesis/preprocessing/denoiser/utils.py
Apache-2.0
def colorize(text, color): """ Display text with some ANSI color in the terminal. """ code = f"\033[{color}m" restore = "\033[0m" return "".join([code, text, restore])
Display text with some ANSI color in the terminal.
colorize
python
OFA-Sys/OFA
fairseq/examples/speech_synthesis/preprocessing/denoiser/utils.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_synthesis/preprocessing/denoiser/utils.py
Apache-2.0
def set_requires_grad(nets, requires_grad=False): """Set requies_grad=Fasle for all the networks to avoid unnecessary computations Parameters: nets (network list) -- a list of networks requires_grad (bool) -- whether the networks require gradients or not """ if not isinstance(nets...
Set requies_grad=Fasle for all the networks to avoid unnecessary computations Parameters: nets (network list) -- a list of networks requires_grad (bool) -- whether the networks require gradients or not
set_requires_grad
python
OFA-Sys/OFA
fairseq/examples/speech_synthesis/preprocessing/speaker_embedder/__init__.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_synthesis/preprocessing/speaker_embedder/__init__.py
Apache-2.0
def read_wave(path): """Reads a .wav file. Takes the path, and returns (PCM audio data, sample rate). """ with contextlib.closing(wave.open(path, 'rb')) as wf: num_channels = wf.getnchannels() assert num_channels == 1 sample_width = wf.getsampwidth() assert sample_width =...
Reads a .wav file. Takes the path, and returns (PCM audio data, sample rate).
read_wave
python
OFA-Sys/OFA
fairseq/examples/speech_synthesis/preprocessing/vad/__init__.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_synthesis/preprocessing/vad/__init__.py
Apache-2.0
def write_wave(path, audio, sample_rate): """Writes a .wav file. Takes path, PCM audio data, and sample rate. """ with contextlib.closing(wave.open(path, 'wb')) as wf: wf.setnchannels(1) wf.setsampwidth(2) wf.setframerate(sample_rate) wf.writeframes(audio)
Writes a .wav file. Takes path, PCM audio data, and sample rate.
write_wave
python
OFA-Sys/OFA
fairseq/examples/speech_synthesis/preprocessing/vad/__init__.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_synthesis/preprocessing/vad/__init__.py
Apache-2.0
def frame_generator(frame_duration_ms, audio, sample_rate): """Generates audio frames from PCM audio data. Takes the desired frame duration in milliseconds, the PCM data, and the sample rate. Yields Frames of the requested duration. """ n = int(sample_rate * (frame_duration_ms / 1000.0) * 2) ...
Generates audio frames from PCM audio data. Takes the desired frame duration in milliseconds, the PCM data, and the sample rate. Yields Frames of the requested duration.
frame_generator
python
OFA-Sys/OFA
fairseq/examples/speech_synthesis/preprocessing/vad/__init__.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_synthesis/preprocessing/vad/__init__.py
Apache-2.0
def vad_collector(sample_rate, frame_duration_ms, padding_duration_ms, vad, frames): """Filters out non-voiced audio frames. Given a webrtcvad.Vad and a source of audio frames, yields only the voiced audio. Uses a padded, sliding window algorithm over the audio frames. When more th...
Filters out non-voiced audio frames. Given a webrtcvad.Vad and a source of audio frames, yields only the voiced audio. Uses a padded, sliding window algorithm over the audio frames. When more than 90% of the frames in the window are voiced (as reported by the VAD), the collector triggers and begins ...
vad_collector
python
OFA-Sys/OFA
fairseq/examples/speech_synthesis/preprocessing/vad/__init__.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_synthesis/preprocessing/vad/__init__.py
Apache-2.0
def __init__( self, task, sentence_avg, guide_alpha, text_input_cost_ratio, label_smoothing, disable_text_guide_update_num=0, attentive_cost_regularization=0, ): """ guide_alpha: alpha to inteplate nll and kd loss tex...
guide_alpha: alpha to inteplate nll and kd loss text_input_cost_ratio: loss ratio for text only input data label_smoothing: label smoothing ratio disable_text_guide_update_num: only use nll loss for the first N updates attentive_cost_regularization: ratio fo...
__init__
python
OFA-Sys/OFA
fairseq/examples/speech_text_joint_to_text/criterions/text_guide_cross_entropy_acc.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_text_joint_to_text/criterions/text_guide_cross_entropy_acc.py
Apache-2.0
def guide_loss_and_acc(self, model, lprobs, lprobs_teacher, target, reduce=True): """ lprobs_teacher is used as guide for lprobs """ if self.alpha == 0.0 or model.num_updates < self.disable_update_num: return self.compute_loss_and_acc(model, lprobs, target, reduction=('sum' if reduce else 'n...
lprobs_teacher is used as guide for lprobs
guide_loss_and_acc
python
OFA-Sys/OFA
fairseq/examples/speech_text_joint_to_text/criterions/text_guide_cross_entropy_acc.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_text_joint_to_text/criterions/text_guide_cross_entropy_acc.py
Apache-2.0
def set_shared_layer(cls, share_level, src_layer, tgt_layer): """ share parameters from tgt_layer to src_layer share_level: 0: share everything 1: share everything but different model 2: share weight but not bias, layernorm """ if share_level =...
share parameters from tgt_layer to src_layer share_level: 0: share everything 1: share everything but different model 2: share weight but not bias, layernorm
set_shared_layer
python
OFA-Sys/OFA
fairseq/examples/speech_text_joint_to_text/models/s2t_dualinputtransformer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_text_joint_to_text/models/s2t_dualinputtransformer.py
Apache-2.0
def forward( self, src_tokens, src_lengths=None, src_txt_tokens=None, src_txt_lengths=None, **kwargs ): """ Args: src_tokens: padded tensor (B, T, C * feat) src_lengths: tensor of original lengths of input utterances (speech) (B...
Args: src_tokens: padded tensor (B, T, C * feat) src_lengths: tensor of original lengths of input utterances (speech) (B,) src_txt_tokens: padded tensor (B, T) src_txt_lengths: tensor of original lengths of input utterances (text) (B,)
forward
python
OFA-Sys/OFA
fairseq/examples/speech_text_joint_to_text/models/s2t_dualinputtransformer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_text_joint_to_text/models/s2t_dualinputtransformer.py
Apache-2.0
def forward( self, prev_output_tokens, encoder_out, incremental_state=None, has_txt_input=False, **kwargs ): """ Args: prev_output_tokens (LongTensor): previous decoder outputs of shape `(batch, tgt_len)`, for input feeding/...
Args: prev_output_tokens (LongTensor): previous decoder outputs of shape `(batch, tgt_len)`, for input feeding/teacher forcing. If there are two or more input during training, they will share the same prev_output_tokens encoder_out (tuple[Tensor]): output...
forward
python
OFA-Sys/OFA
fairseq/examples/speech_text_joint_to_text/models/s2t_dualinputtransformer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_text_joint_to_text/models/s2t_dualinputtransformer.py
Apache-2.0
def forward( self, src_tokens, src_lengths, prev_output_tokens, use_encoder_outputs=False, src_txt_tokens=None, src_txt_lengths=None, mode="sup_speech", **kwargs ): """ Run the forward pass for an encoder-decoder model. ...
Run the forward pass for an encoder-decoder model. First feed a batch of source tokens through the encoder. Then, feed the encoder output and previous decoder outputs (i.e., teacher forcing) to the decoder to produce the next outputs:: encoder_out = self.encoder(src_tokens...
forward
python
OFA-Sys/OFA
fairseq/examples/speech_text_joint_to_text/models/s2t_dualinputtransformer.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_text_joint_to_text/models/s2t_dualinputtransformer.py
Apache-2.0
def dup_pho(sent, dup_v_num, dup_c_num): """ duplicate phoneme defined as cmudict http://www.speech.cs.cmu.edu/cgi-bin/cmudict """ if dup_v_num == 1 and dup_c_num == 1: return sent ns = [] for p in sent: ns.append(p) if re.search(r"\d$", p): for i in range...
duplicate phoneme defined as cmudict http://www.speech.cs.cmu.edu/cgi-bin/cmudict
dup_pho
python
OFA-Sys/OFA
fairseq/examples/speech_text_joint_to_text/scripts/g2p_encode.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_text_joint_to_text/scripts/g2p_encode.py
Apache-2.0
def __getitem__( self, n: int ) -> Tuple[Tensor, int, str, str, Optional[str], str, str]: """Load the n-th sample from the dataset. Args: n (int): The index of the sample to be loaded Returns: tuple: ``(waveform, sample_rate, sentence, translation, speaker_i...
Load the n-th sample from the dataset. Args: n (int): The index of the sample to be loaded Returns: tuple: ``(waveform, sample_rate, sentence, translation, speaker_id, sample_id)``
__getitem__
python
OFA-Sys/OFA
fairseq/examples/speech_to_text/prep_covost_data.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/speech_to_text/prep_covost_data.py
Apache-2.0
def corpus_bleu( list_of_references, hypotheses, weights=(0.25, 0.25, 0.25, 0.25), smoothing_function=None, auto_reweigh=False, averaging_mode="geometric", no_length_penalty=False ): """ Calculate a single corpus-level BLEU score (aka. system-level BLEU) for all the hypotheses an...
Calculate a single corpus-level BLEU score (aka. system-level BLEU) for all the hypotheses and their respective references. Instead of averaging the sentence level BLEU scores (i.e. marco-average precision), the original BLEU metric (Papineni et al. 2002) accounts for the micro-average precision (...
corpus_bleu
python
OFA-Sys/OFA
fairseq/examples/textless_nlp/gslm/metrics/asr_metrics/misc/bleu_utils.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/textless_nlp/gslm/metrics/asr_metrics/misc/bleu_utils.py
Apache-2.0
def window_sumsquare(window, n_frames, hop_length=200, win_length=800, n_fft=800, dtype=np.float32, norm=None): """ # from librosa 0.6 Compute the sum-square envelope of a window function at a given hop length. This is used to estimate modulation effects induced by windowing ob...
# from librosa 0.6 Compute the sum-square envelope of a window function at a given hop length. This is used to estimate modulation effects induced by windowing observations in short-time fourier transforms. Parameters ---------- window : string, tuple, number, callable, or list-like ...
window_sumsquare
python
OFA-Sys/OFA
fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/audio_processing.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/audio_processing.py
Apache-2.0
def english_cleaners(text): '''Pipeline for English text, including number and abbreviation expansion.''' text = convert_to_ascii(text) text = lowercase(text) text = expand_numbers(text) text = expand_abbreviations(text) text = collapse_whitespace(text) return text
Pipeline for English text, including number and abbreviation expansion.
english_cleaners
python
OFA-Sys/OFA
fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/cleaners.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/cleaners.py
Apache-2.0
def forward(self, x, lengths=None): """Average pooling across time steps (dim=1) with optionally lengths. Args: x: torch.Tensor of shape (N, T, ...) lengths: None or torch.Tensor of shape (N,) dim: dimension to pool """ if lengths is None: ...
Average pooling across time steps (dim=1) with optionally lengths. Args: x: torch.Tensor of shape (N, T, ...) lengths: None or torch.Tensor of shape (N,) dim: dimension to pool
forward
python
OFA-Sys/OFA
fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/layers.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/layers.py
Apache-2.0
def mel_spectrogram(self, y): """Computes mel-spectrograms from a batch of waves PARAMS ------ y: Variable(torch.FloatTensor) with shape (B, T) in range [-1, 1] RETURNS ------- mel_output: torch.FloatTensor of shape (B, n_mel_channels, T) """ asse...
Computes mel-spectrograms from a batch of waves PARAMS ------ y: Variable(torch.FloatTensor) with shape (B, T) in range [-1, 1] RETURNS ------- mel_output: torch.FloatTensor of shape (B, n_mel_channels, T)
mel_spectrogram
python
OFA-Sys/OFA
fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/layers.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/layers.py
Apache-2.0
def get_alignment_energies(self, query, processed_memory, attention_weights_cat): """ PARAMS ------ query: decoder output (batch, n_mel_channels * n_frames_per_step) processed_memory: processed encoder outputs (B, T_in, attention_dim) attent...
PARAMS ------ query: decoder output (batch, n_mel_channels * n_frames_per_step) processed_memory: processed encoder outputs (B, T_in, attention_dim) attention_weights_cat: cumulative and prev. att weights (B, 2, max_time) RETURNS ------- alignment (batch...
get_alignment_energies
python
OFA-Sys/OFA
fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/model.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/model.py
Apache-2.0
def forward(self, attention_hidden_state, memory, processed_memory, attention_weights_cat, mask): """ PARAMS ------ attention_hidden_state: attention rnn last output memory: encoder outputs processed_memory: processed encoder outputs attention_weig...
PARAMS ------ attention_hidden_state: attention rnn last output memory: encoder outputs processed_memory: processed encoder outputs attention_weights_cat: previous and cummulative attention weights mask: binary mask for padded data
forward
python
OFA-Sys/OFA
fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/model.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/model.py
Apache-2.0
def get_go_frame(self, memory): """ Gets all zeros frames to use as first decoder input PARAMS ------ memory: decoder outputs RETURNS ------- decoder_input: all zeros frames """ B = memory.size(0) decoder_input = Variable(memory.data.new( ...
Gets all zeros frames to use as first decoder input PARAMS ------ memory: decoder outputs RETURNS ------- decoder_input: all zeros frames
get_go_frame
python
OFA-Sys/OFA
fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/model.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/model.py
Apache-2.0
def initialize_decoder_states(self, memory, obs_and_lat, mask): """ Initializes attention rnn states, decoder rnn states, attention weights, attention cumulative weights, attention context, stores memory and stores processed memory PARAMS ------ memory: Encoder outputs ...
Initializes attention rnn states, decoder rnn states, attention weights, attention cumulative weights, attention context, stores memory and stores processed memory PARAMS ------ memory: Encoder outputs obs_and_lat: Observed and latent attribute embeddings mask: M...
initialize_decoder_states
python
OFA-Sys/OFA
fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/model.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/model.py
Apache-2.0
def parse_decoder_inputs(self, decoder_inputs): """ Prepares decoder inputs, i.e. mel outputs PARAMS ------ decoder_inputs: inputs used for teacher-forced training, i.e. mel-specs RETURNS ------- inputs: processed decoder inputs """ # (B, n_mel_c...
Prepares decoder inputs, i.e. mel outputs PARAMS ------ decoder_inputs: inputs used for teacher-forced training, i.e. mel-specs RETURNS ------- inputs: processed decoder inputs
parse_decoder_inputs
python
OFA-Sys/OFA
fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/model.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/model.py
Apache-2.0
def parse_decoder_outputs(self, mel_outputs, gate_outputs, alignments): """ Prepares decoder outputs for output PARAMS ------ mel_outputs: gate_outputs: gate output energies alignments: RETURNS ------- mel_outputs: gate_outpust: gate outpu...
Prepares decoder outputs for output PARAMS ------ mel_outputs: gate_outputs: gate output energies alignments: RETURNS ------- mel_outputs: gate_outpust: gate output energies alignments:
parse_decoder_outputs
python
OFA-Sys/OFA
fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/model.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/model.py
Apache-2.0
def decode(self, decoder_input): """ Decoder step using stored states, attention and memory PARAMS ------ decoder_input: previous mel output RETURNS ------- mel_output: gate_output: gate output energies attention_weights: """ cell_...
Decoder step using stored states, attention and memory PARAMS ------ decoder_input: previous mel output RETURNS ------- mel_output: gate_output: gate output energies attention_weights:
decode
python
OFA-Sys/OFA
fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/model.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/model.py
Apache-2.0
def forward(self, memory, obs_and_lat, decoder_inputs, memory_lengths): """ Decoder forward pass for training PARAMS ------ memory: Encoder outputs obs_and_lat: Observed and latent attribute embeddings decoder_inputs: Decoder inputs for teacher forcing. i.e. mel-specs ...
Decoder forward pass for training PARAMS ------ memory: Encoder outputs obs_and_lat: Observed and latent attribute embeddings decoder_inputs: Decoder inputs for teacher forcing. i.e. mel-specs memory_lengths: Encoder output lengths for attention masking. RETURNS...
forward
python
OFA-Sys/OFA
fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/model.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/model.py
Apache-2.0
def inference(self, memory, obs_and_lat, ret_has_eos=False): """ Decoder inference PARAMS ------ memory: Encoder outputs obs_and_lat: Observed and latent attribute embeddings RETURNS ------- mel_outputs: mel outputs from the decoder gate_outputs: ...
Decoder inference PARAMS ------ memory: Encoder outputs obs_and_lat: Observed and latent attribute embeddings RETURNS ------- mel_outputs: mel outputs from the decoder gate_outputs: gate outputs from the decoder alignments: sequence of attention ...
inference
python
OFA-Sys/OFA
fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/model.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/model.py
Apache-2.0
def text_to_sequence(text, cleaner_names): '''Converts a string of text to a sequence of IDs corresponding to the symbols in the text. The text can optionally have ARPAbet sequences enclosed in curly braces embedded in it. For example, "Turn left on {HH AW1 S S T AH0 N} Street." Args: text: string...
Converts a string of text to a sequence of IDs corresponding to the symbols in the text. The text can optionally have ARPAbet sequences enclosed in curly braces embedded in it. For example, "Turn left on {HH AW1 S S T AH0 N} Street." Args: text: string to convert to a sequence cleaner_names: n...
text_to_sequence
python
OFA-Sys/OFA
fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/text.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/text.py
Apache-2.0
def read_binary_audio(bin_data, tar_sr=None): """ read binary audio (`bytes` or `uint8` `numpy.ndarray`) to `float32` `numpy.ndarray` RETURNS: data (np.ndarray) : audio of shape (n,) or (2, n) tar_sr (int) : sample rate """ data, ori_sr = sf.read(io.BytesIO(bin_data), dtype='flo...
read binary audio (`bytes` or `uint8` `numpy.ndarray`) to `float32` `numpy.ndarray` RETURNS: data (np.ndarray) : audio of shape (n,) or (2, n) tar_sr (int) : sample rate
read_binary_audio
python
OFA-Sys/OFA
fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/utils.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/textless_nlp/gslm/unit2speech/tacotron2/utils.py
Apache-2.0
def read_audio(fname): """ Load an audio file and return PCM along with the sample rate """ wav, sr = sf.read(fname) assert sr == 16e3 return wav, 16e3
Load an audio file and return PCM along with the sample rate
read_audio
python
OFA-Sys/OFA
fairseq/examples/wav2vec/wav2vec_featurize.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/wav2vec/wav2vec_featurize.py
Apache-2.0
def ordered_indices(self): """Return an ordered list of indices. Batches will be constructed based on this order.""" if self.shuffle: order = [np.random.permutation(len(self))] else: order = [np.arange(len(self))] if self.sort_by_length: order...
Return an ordered list of indices. Batches will be constructed based on this order.
ordered_indices
python
OFA-Sys/OFA
fairseq/examples/wav2vec/unsupervised/data/extracted_features_dataset.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/wav2vec/unsupervised/data/extracted_features_dataset.py
Apache-2.0
def read_audio(self, fname): """Load an audio file and return PCM along with the sample rate""" wav, sr = sf.read(fname) assert sr == 16e3 return wav
Load an audio file and return PCM along with the sample rate
read_audio
python
OFA-Sys/OFA
fairseq/examples/wav2vec/unsupervised/scripts/wav2vec_cluster_faiss.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/wav2vec/unsupervised/scripts/wav2vec_cluster_faiss.py
Apache-2.0
def setup_task(cls, cfg: UnpairedAudioTextConfig, **kwargs): """Setup the task (e.g., load dictionaries). Args: cfg (AudioPretrainingConfig): configuration of this task """ dict_path = os.path.join(cfg.text_data, "dict.txt") if os.path.exists(dict_path): ...
Setup the task (e.g., load dictionaries). Args: cfg (AudioPretrainingConfig): configuration of this task
setup_task
python
OFA-Sys/OFA
fairseq/examples/wav2vec/unsupervised/tasks/unpaired_audio_text.py
https://github.com/OFA-Sys/OFA/blob/master/fairseq/examples/wav2vec/unsupervised/tasks/unpaired_audio_text.py
Apache-2.0
def load_checkpoint(cfg: CheckpointConfig, trainer, **passthrough_args): """ Load a checkpoint and restore the training iterator. *passthrough_args* will be passed through to ``trainer.get_train_iterator``. """ reset_optimizer = cfg.reset_optimizer reset_lr_scheduler = cfg.reset_lr_schedul...
Load a checkpoint and restore the training iterator. *passthrough_args* will be passed through to ``trainer.get_train_iterator``.
load_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 load_checkpoint_to_cpu(path, arg_overrides=None, load_on_all_ranks=False): """Loads a checkpoint to CPU (with upgrading for backward compatibility). If doing single-GPU training or if the checkpoint is only being loaded by at most one process on each node (current default behavior is for only rank 0 ...
Loads a checkpoint to CPU (with upgrading for backward compatibility). If doing single-GPU training or if the checkpoint is only being loaded by at most one process on each node (current default behavior is for only rank 0 to read the checkpoint from disk), load_on_all_ranks should be False to avoid er...
load_checkpoint_to_cpu
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_model_ensemble( filenames, arg_overrides: Optional[Dict[str, Any]] = None, task=None, strict=True, suffix="", num_shards=1, state=None, ): """Loads an ensemble of models. Args: filenames (List[str]): checkpoint files to load arg_overrides (Dict[str,Any], opt...
Loads an ensemble of models. Args: filenames (List[str]): checkpoint files to load arg_overrides (Dict[str,Any], optional): override model args that were used during model training task (fairseq.tasks.FairseqTask, optional): task to use for loading
load_model_ensemble
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 checkpoint_paths(path, pattern=r"checkpoint(\d+)\.pt", keep_match=False): """Retrieves all checkpoints found in `path` directory. Checkpoints are identified by matching filename to the specified pattern. If the pattern contains groups, the result will be sorted by the first group in descending orde...
Retrieves all checkpoints found in `path` directory. Checkpoints are identified by matching filename to the specified pattern. If the pattern contains groups, the result will be sorted by the first group in descending order.
checkpoint_paths
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 _upgrade_state_dict(state): """Helper for upgrading old model checkpoints.""" # add optimizer_history if "optimizer_history" not in state: state["optimizer_history"] = [ {"criterion_name": "CrossEntropyCriterion", "best_loss": state["best_loss"]} ] state["last_optimi...
Helper for upgrading old model checkpoints.
_upgrade_state_dict
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 prune_state_dict(state_dict, model_cfg: Optional[DictConfig]): """Prune the given state_dict if desired for LayerDrop (https://arxiv.org/abs/1909.11556). Training with LayerDrop allows models to be robust to pruning at inference time. This function prunes state_dict to allow smaller models to be lo...
Prune the given state_dict if desired for LayerDrop (https://arxiv.org/abs/1909.11556). Training with LayerDrop allows models to be robust to pruning at inference time. This function prunes state_dict to allow smaller models to be loaded from a larger model and re-maps the existing state_dict for this ...
prune_state_dict
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