id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
183,734
import os import subprocess import sys from setuptools import setup, find_packages, Extension from setuptools import Extension, find_packages, setup version = write_version_py() extensions = [ Extension( "fairseq.libbleu", sources=[ "fairseq/clib/libbleu/libbleu.cpp", "fairse...
null
183,735
import os import subprocess import sys from setuptools import setup, find_packages, Extension from setuptools import Extension, find_packages, setup if "READTHEDOCS" in os.environ: # don't build extensions when generating docs extensions = [] if "build_ext" in cmdclass: del cmdclass["build_ext"] ...
null
183,736
import os import sys import time import logging from tqdm import tqdm import torch from fairseq import utils, tasks, options from fairseq.checkpoint_utils import load_model_ensemble_and_task from fairseq.dataclass.utils import convert_namespace_to_omegaconf from torch import Tensor from typing import Dict, List, Option...
null
183,737
import os import sys import time import logging from tqdm import tqdm import torch from fairseq import utils, tasks, options from fairseq.checkpoint_utils import load_model_ensemble_and_task from fairseq.dataclass.utils import convert_namespace_to_omegaconf from torch import Tensor from typing import Dict, List, Option...
null
183,738
import os import sys import time import logging from tqdm import tqdm import torch from fairseq import utils, tasks, options from fairseq.checkpoint_utils import load_model_ensemble_and_task from fairseq.dataclass.utils import convert_namespace_to_omegaconf from torch import Tensor from typing import Dict, List, Option...
null
183,739
import os import sys import time import logging from tqdm import tqdm import torch from fairseq import utils, tasks, options from fairseq.checkpoint_utils import load_model_ensemble_and_task from fairseq.dataclass.utils import convert_namespace_to_omegaconf from torch import Tensor from typing import Dict, List, Option...
null
183,740
import math from math import log import torch import torch.nn.functional as F from fairseq import metrics, utils from fairseq.criterions import FairseqCriterion, register_criterion from torch import Tensor import numpy as np def log_metric(key, logging_outputs): if len(logging_outputs) > 0 and key in logging_outpu...
null
183,741
import torch from fairseq import utils from fairseq.iterative_refinement_generator import DecoderOut from fairseq.models import register_model, register_model_architecture from fairseq.models.nat import FairseqNATModel from fairseq.modules.transformer_sentence_encoder import init_bert_params import torch from fairseq.m...
null
183,742
import torch from fairseq import utils from fairseq.iterative_refinement_generator import DecoderOut from fairseq.models import register_model, register_model_architecture from fairseq.models.nat import FairseqNATModel from fairseq.modules.transformer_sentence_encoder import init_bert_params import torch from fairseq.m...
null
183,743
import torch from fairseq import utils from fairseq.iterative_refinement_generator import DecoderOut from fairseq.models import register_model, register_model_architecture from fairseq.models.nat import FairseqNATModel from fairseq.modules.transformer_sentence_encoder import init_bert_params import torch from fairseq.m...
null
183,754
import functools from typing import Any, Dict, List, Tuple, Union import torch import torch.utils.checkpoint as checkpoint from fairseq import utils def _checkpointed_forward(original_forward, offload_to_cpu, *args, **kwargs): # Autograd Functions in PyTorch work best with positional args, since # the backward ...
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:: checkpointed_module = checkpoint_wrapper...
183,760
import torch import torch.nn as nn import torch.nn.functional as F from fairseq import utils from fairseq.incremental_decoding_utils import with_incremental_state from fairseq.modules.fairseq_dropout import FairseqDropout from .unfold import unfold1d class DynamicConv1dTBC(nn.Module): def __init__( sel...
null
183,762
from typing import Optional, Tuple import torch import torch.nn as nn from fairseq.modules import ( FairseqDropout, LayerDropModuleList, LayerNorm, MultiheadAttention, PositionalEmbedding, TransformerSentenceEncoderLayer, ) from fairseq.modules.quant_noise import quant_noise as apply_quant_noise...
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 specified value. 2. If normal_init_embed_...
183,767
import logging import re from operator import attrgetter, itemgetter import numpy as np import torch.distributed as dist import torch.nn as nn from .modules import PQConv2d, PQEmbedding, PQLinear from .pq import PQ def get_layers(model, filter_regexp): """ Filters out the layers according to a regexp. Note that...
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 - size_tracker: useful for trackin...
183,769
import logging from operator import attrgetter import torch.distributed as dist import torch.nn as nn from ..pq.utils import attrsetter, get_layers from .modules import ActivationQuantizer, IntConv2d, IntEmbedding, IntLinear MAPPING = {nn.Linear: IntLinear, nn.Embedding: IntEmbedding, nn.Conv2d: IntConv2d} def get_lay...
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_step: update quantization parameters every update...
183,771
import torch def quantize(w, scale, zero_point): def emulate_int8_histogram(w, scale=None, zero_point=None): if scale is None: obs = torch.quantization.observer.HistogramObserver() _ = obs(w.float()) scale, zero_point = obs.calculate_qparams() scale = scale.cuda().type_as(w) ...
null
183,772
import torch def quantize(w, scale, zero_point): def emulate_int8_channel(w, scale=None, zero_point=None): if scale is None: obs = torch.quantization.observer.PerChannelMinMaxObserver( ch_axis=-1, qscheme=torch.per_channel_symmetric ) _ = obs(w) scale, zero_point, ch_axi...
null
183,773
import torch def quantize(w, scale, zero_point): return ( torch.clamp(torch.round(w / scale + zero_point), 0, 255) - zero_point ) * scale def emulate_int8_tensor(w, scale=None, zero_point=None): if scale is None: obs = torch.quantization.observer.MinMaxObserver() _ = obs(w) ...
null
183,775
import ast import collections import contextlib import logging import os import re import traceback from collections import OrderedDict from typing import Any, Dict, Optional, Union import torch from fairseq.dataclass.configs import CheckpointConfig, FairseqConfig from fairseq.dataclass.utils import ( convert_names...
Load a checkpoint and restore the training iterator. *passthrough_args* will be passed through to ``trainer.get_train_iterator``.
183,776
import ast import collections import contextlib import logging import os import re import traceback from collections import OrderedDict from typing import Any, Dict, Optional, Union import torch from fairseq.dataclass.configs import CheckpointConfig, FairseqConfig from fairseq.dataclass.utils import ( convert_names...
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
183,777
import ast import collections import contextlib import logging import os import re import traceback from collections import OrderedDict from typing import Any, Dict, Optional, Union import torch from fairseq.dataclass.configs import CheckpointConfig, FairseqConfig from fairseq.dataclass.utils import ( convert_names...
null
183,778
import ast import collections import contextlib import logging import os import re import traceback from collections import OrderedDict from typing import Any, Dict, Optional, Union import torch from fairseq.dataclass.configs import CheckpointConfig, FairseqConfig from fairseq.dataclass.utils import ( convert_names...
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 to occur. It's ca...
183,779
import ast import collections import contextlib import logging import os import re import traceback from collections import OrderedDict from typing import Any, Dict, Optional, Union import torch from fairseq.dataclass.configs import CheckpointConfig, FairseqConfig from fairseq.dataclass.utils import ( convert_names...
Load a pretrained FairseqEncoder or FairseqDecoder from checkpoint into the provided `component` object. If state_dict fails to load, there may be a mismatch in the architecture of the corresponding `component` found in the `checkpoint` file.
183,780
import ast import collections import contextlib import logging import os import re import traceback from collections import OrderedDict from typing import Any, Dict, Optional, Union import torch from fairseq.dataclass.configs import CheckpointConfig, FairseqConfig from fairseq.dataclass.utils import ( convert_names...
null
183,782
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,783
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,784
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,785
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,786
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
Helper for getting incremental state for an nn.Module.
183,787
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
Helper for setting incremental state for an nn.Module.
183,788
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,789
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,790
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
Parse embedding text file into a dictionary of word and embedding tensors. The first line can have vocabulary size and dimension. The following lines should contain word and embedding separated by spaces. Example: 2 5 the -0.0230 -0.0264 0.0287 0.0171 0.1403 at -0.0395 -0.1286 0.0275 0.0254 -0.0932
183,791
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,792
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,793
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols are ignored.
183,794
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,795
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,796
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,797
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,798
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
FP16-compatible function that fills a tensor with -inf.
183,799
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
Resolve max position constraints from multiple sources.
183,800
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,801
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,802
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,803
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,804
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
Returns the activation function corresponding to `activation`
183,805
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,806
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,807
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,808
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,809
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,810
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
Parses a single line from the alingment file. Args: line (str): String containing the alignment of the format: <src_idx_1>-<tgt_idx_1> <src_idx_2>-<tgt_idx_2> .. <src_idx_m>-<tgt_idx_m>. All indices are 0 indexed. Returns: torch.IntTensor: packed alignments of shape (2 * m).
183,811
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,812
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,813
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
Return a Tensor of `size` filled with a range function on the device of x. If size is empty, using the size of the variable x.
183,814
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,815
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,816
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,817
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,818
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,819
import argparse import contextlib import copy import importlib import logging import os import sys import tempfile import warnings from itertools import accumulate from typing import Callable, Dict, List, Optional import torch import torch.nn.functional as F from fairseq.modules.multihead_attention import MultiheadAtte...
null
183,820
import os from collections import Counter import torch from fairseq.file_io import PathManager from fairseq.tokenizer import tokenize_line from typing import List, Dict def safe_readline(f): pos = f.tell() while True: try: return f.readline() except UnicodeDecodeError: p...
null
183,824
import atexit import json import logging import os import sys from collections import OrderedDict from contextlib import contextmanager from numbers import Number from typing import Optional import torch from .meters import AverageMeter, StopwatchMeter, TimeMeter def progress_bar( iterator, log_format: Optional...
Legacy wrapper that takes an argparse.Namespace.
183,828
import contextlib import time import uuid from collections import OrderedDict, defaultdict from typing import Callable, Dict, List, Optional from .meters import * _aggregators = OrderedDict() _active_aggregators = OrderedDict() _active_aggregators_cnt = defaultdict(lambda: 0) class MetersDict(OrderedDict): """A so...
Context manager to aggregate metrics under a given name. Aggregations can be nested. If *new_root* is ``False``, then logged metrics will be recorded along the entire stack of nested aggregators, including a global "default" aggregator. If *new_root* is ``True``, then this aggregator will be the root of a new aggregati...
183,829
import contextlib import time import uuid from collections import OrderedDict, defaultdict from typing import Callable, Dict, List, Optional from .meters import * def get_active_aggregators() -> List[MetersDict]: return list(_active_aggregators.values()) class AverageMeter(Meter): """Computes and stores the av...
Log a scalar value. Args: key (str): name of the field to log value (float): value to log weight (float): weight that this value contributes to the average. A weight of 0 will always log the latest value. priority (int): smaller values are logged earlier in the output round (Optional[int]): number of digits to round to...
183,830
import contextlib import time import uuid from collections import OrderedDict, defaultdict from typing import Callable, Dict, List, Optional from .meters import * def get_active_aggregators() -> List[MetersDict]: return list(_active_aggregators.values()) class MetersDict(OrderedDict): """A sorted dictionary of...
Log a scalar value derived from other meters. Args: key (str): name of the field to log fn (Callable[[MetersDict], float]): function that takes a single argument *meters* and returns the derived value priority (int): smaller values are logged earlier in the output
183,831
import contextlib import time import uuid from collections import OrderedDict, defaultdict from typing import Callable, Dict, List, Optional from .meters import * def reset() -> None: """Reset all metrics aggregators.""" _aggregators.clear() _active_aggregators.clear() _active_aggregators_cnt.clear() ...
Log the rate of some quantity per second. Args: key (str): name of the field to log value (float): value to log priority (int): smaller values are logged earlier in the output round (Optional[int]): number of digits to round to when displaying
183,832
import contextlib import time import uuid from collections import OrderedDict, defaultdict from typing import Callable, Dict, List, Optional from .meters import * def get_active_aggregators() -> List[MetersDict]: return list(_active_aggregators.values()) class StopwatchMeter(Meter): """Computes the sum/avg dur...
Log the duration of some event in seconds. The duration will be computed once :func:`log_stop_time` is called. Args: key (str): name of the field to log priority (int): smaller values are logged earlier in the output round (Optional[int]): number of digits to round to when displaying
183,833
import contextlib import time import uuid from collections import OrderedDict, defaultdict from typing import Callable, Dict, List, Optional from .meters import * def get_active_aggregators() -> List[MetersDict]: return list(_active_aggregators.values()) The provided code snippet includes necessary dependencies fo...
Log the duration of some event in seconds. The duration will be computed since :func:`log_start_time` was called. Set weight > 0 to report the average time instead of the sum. Args: key (str): name of the field to log weight (float): weight that this time contributes to the average prehook (function, no arguments): wil...
183,834
import contextlib import time import uuid from collections import OrderedDict, defaultdict from typing import Callable, Dict, List, Optional from .meters import * def get_active_aggregators() -> List[MetersDict]: return list(_active_aggregators.values()) class Meter(object): """Base class for Meters.""" d...
Log using a custom Meter. Any extra *args* or *kwargs* will be passed through to the Meter's *update* method. Args: new_meter_fn (Callable[[], Meter]): function that returns a new Meter instance key (str): name of the field to log priority (int): smaller values are logged earlier in the output
183,835
import contextlib import time import uuid from collections import OrderedDict, defaultdict from typing import Callable, Dict, List, Optional from .meters import * def reset() -> None: """Reset all metrics aggregators.""" _aggregators.clear() _active_aggregators.clear() _active_aggregators_cnt.clear() ...
Reset Meter instance aggregated under a given *name* and *key*.
183,836
import contextlib import time import uuid from collections import OrderedDict, defaultdict from typing import Callable, Dict, List, Optional from .meters import * def reset() -> None: """Reset all metrics aggregators.""" _aggregators.clear() _active_aggregators.clear() _active_aggregators_cnt.clear() ...
Reset Meter instances aggregated under a given *name*.
183,837
import contextlib import time import uuid from collections import OrderedDict, defaultdict from typing import Callable, Dict, List, Optional from .meters import * _aggregators = OrderedDict() The provided code snippet includes necessary dependencies for implementing the `get_smoothed_value` function. Write a Python fu...
Get a single smoothed value. Raises: KeyError: if no metrics have been logged under *name* and *key*.
183,838
import contextlib import time import uuid from collections import OrderedDict, defaultdict from typing import Callable, Dict, List, Optional from .meters import * _aggregators = OrderedDict() The provided code snippet includes necessary dependencies for implementing the `get_smoothed_values` function. Write a Python f...
Get smoothed values aggregated under a given *name*. Raises: KeyError: if no metrics have been logged under *name*.
183,839
import contextlib import time import uuid from collections import OrderedDict, defaultdict from typing import Callable, Dict, List, Optional from .meters import * _aggregators = OrderedDict() def state_dict(): return OrderedDict([(name, agg.state_dict()) for name, agg in _aggregators.items()])
null
183,840
import contextlib import time import uuid from collections import OrderedDict, defaultdict from typing import Callable, Dict, List, Optional from .meters import * _aggregators = OrderedDict() class MetersDict(OrderedDict): """A sorted dictionary of :class:`Meters`. Meters are sorted according to a priority th...
null
183,841
import contextlib import logging import sys import time from argparse import Namespace from itertools import chain from typing import Any, Dict, List import torch from fairseq import checkpoint_utils, models, optim, utils from fairseq.dataclass.configs import FairseqConfig from fairseq.dataclass.utils import convert_na...
null
183,842
import contextlib import logging import sys import time from argparse import Namespace from itertools import chain from typing import Any, Dict, List import torch from fairseq import checkpoint_utils, models, optim, utils from fairseq.dataclass.configs import FairseqConfig from fairseq.dataclass.utils import convert_na...
null
183,843
import contextlib import logging import sys import time from argparse import Namespace from itertools import chain from typing import Any, Dict, List import torch from fairseq import checkpoint_utils, models, optim, utils from fairseq.dataclass.configs import FairseqConfig from fairseq.dataclass.utils import convert_na...
null
183,852
import contextlib import itertools import logging import os import warnings from typing import Optional, Tuple import numpy as np import torch from fairseq.file_io import PathManager class PathManager: """ Wrapper for insulating OSS I/O (using Python builtin operations) from iopath's PathManager abstractio...
Infer language pair from filename: <split>.<lang1>-<lang2>.(...).idx
183,853
import contextlib import itertools import logging import os import warnings from typing import Optional, Tuple import numpy as np import torch from fairseq.file_io import PathManager logger = logging.getLogger(__name__) class ConcatDataset(FairseqDataset): def cumsum(sequence, sample_ratios): r, s = [], 0 ...
A helper function for loading indexed datasets. Args: path (str): path to indexed dataset (e.g., 'data-bin/train') dictionary (~fairseq.data.Dictionary): data dictionary dataset_impl (str, optional): which dataset implementation to use. If not provided, it will be inferred automatically. For legacy indexed data we use ...
183,854
import contextlib import itertools import logging import os import warnings from typing import Optional, Tuple import numpy as np import torch from fairseq.file_io import PathManager The provided code snippet includes necessary dependencies for implementing the `numpy_seed` function. Write a Python function `def numpy...
Context manager which seeds the NumPy PRNG with the specified seed and restores the state afterward
183,855
import contextlib import itertools import logging import os import warnings from typing import Optional, Tuple import numpy as np import torch from fairseq.file_io import PathManager logger = logging.getLogger(__name__) def _filter_by_size_dynamic(indices, size_fn, max_positions, raise_exception=False): def compare...
[deprecated] Filter indices based on their size. Use `FairseqDataset::filter_indices_by_size` instead. Args: indices (List[int]): ordered list of dataset indices dataset (FairseqDataset): fairseq dataset instance max_positions (tuple): filter elements larger than this size. Comparisons are done component-wise. raise_ex...
183,856
import contextlib import itertools import logging import os import warnings from typing import Optional, Tuple import numpy as np import torch from fairseq.file_io import PathManager The provided code snippet includes necessary dependencies for implementing the `filter_paired_dataset_indices_by_size` function. Write a...
Filter a list of sample indices. Remove those that are longer than specified in max_sizes. Args: indices (np.array): original array of sample indices max_sizes (int or list[int] or tuple[int]): max sample size, can be defined separately for src and tgt (then list or tuple) Returns: np.array: filtered sample array list:...
183,857
import contextlib import itertools import logging import os import warnings from typing import Optional, Tuple import numpy as np import torch from fairseq.file_io import PathManager The provided code snippet includes necessary dependencies for implementing the `batch_by_size` function. Write a Python function `def ba...
Yield mini-batches of indices bucketed by size. Batches may contain sequences of different lengths. Args: indices (List[int]): ordered list of dataset indices num_tokens_fn (callable): function that returns the number of tokens at a given index num_tokens_vec (List[int], optional): precomputed vector of the number of t...
183,858
import contextlib import itertools import logging import os import warnings from typing import Optional, Tuple import numpy as np import torch from fairseq.file_io import PathManager def post_process(sentence: str, symbol: str): if symbol == "sentencepiece": sentence = sentence.replace(" ", "").replace("\u...
null
183,859
import contextlib import itertools import logging import os import warnings from typing import Optional, Tuple import numpy as np import torch from fairseq.file_io import PathManager The provided code snippet includes necessary dependencies for implementing the `compute_mask_indices` function. Write a Python function ...
Computes random mask spans for a given shape Args: shape: the the shape for which to compute masks. should be of size 2 where first element is batch size and 2nd is timesteps padding_mask: optional padding mask of the same size as shape, which will prevent masking padded elements mask_prob: probability for each token t...
183,860
import contextlib import itertools import logging import os import warnings from typing import Optional, Tuple import numpy as np import torch from fairseq.file_io import PathManager def get_mem_usage(): try: import psutil mb = 1024 * 1024 return f"used={psutil.virtual_memory().used / mb}M...
null
183,861
import contextlib import itertools import logging import os import warnings from typing import Optional, Tuple import numpy as np import torch from fairseq.file_io import PathManager def lengths_to_padding_mask(lens: torch.LongTensor) -> torch.BoolTensor: bsz, max_lens = lens.size(0), torch.max(lens).item() mas...
null
183,862
import os.path as op from typing import BinaryIO, Optional, Tuple, Union import numpy as np def get_waveform( path_or_fp: Union[str, BinaryIO], normalization=True ) -> Tuple[np.ndarray, int]: """Get the waveform and sample rate of a 16-bit mono-channel WAV or FLAC. Args: path_or_fp (str or BinaryIO)...
Get mel-filter bank features via PyKaldi or TorchAudio. Prefer PyKaldi (faster CPP implementation) to TorchAudio (Python implementation). Note that Kaldi/TorchAudio requires 16-bit signed integers as inputs and hence the waveform should not be normalized.
183,863
import csv import io import logging import os.path as op import re from typing import Dict, List, Optional, Tuple import numpy as np import torch from fairseq.data import ( ConcatDataset, Dictionary, FairseqDataset, ResamplingDataset, data_utils as fairseq_data_utils, ) from fairseq.data.audio.audio...
Get speech features from .npy file or waveform from .wav/.flac file. The file may be inside an uncompressed ZIP file and is accessed via byte offset and length. Args: path (str): File path in the format of "<.npy/.wav/.flac path>" or "<zip path>:<byte offset>:<byte length>". need_waveform (bool): return waveform instea...
183,864
import csv import io import logging import os.path as op import re from typing import Dict, List, Optional, Tuple import numpy as np import torch from fairseq.data import ( ConcatDataset, Dictionary, FairseqDataset, ResamplingDataset, data_utils as fairseq_data_utils, ) from fairseq.data.audio.audio...
Convert a list of 2D frames into a padded 3D tensor Args: frames (list): list of 2D frames of size L[i]*f_dim. Where L[i] is length of i-th frame and f_dim is static dimension of features Returns: 3D tensor of size len(frames)*len_max*f_dim where len_max is max of L[i]
183,865
import itertools import json import logging import math import os from collections import OrderedDict, defaultdict from fairseq import utils from fairseq.data import ( AppendTokenDataset, ConcatDataset, Dictionary, LanguagePairDataset, PrependTokenDataset, SampledMultiDataset, SampledMultiEp...
Return language ID index.
183,866
import itertools import json import logging import math import os from collections import OrderedDict, defaultdict from fairseq import utils from fairseq.data import ( AppendTokenDataset, ConcatDataset, Dictionary, LanguagePairDataset, PrependTokenDataset, SampledMultiDataset, SampledMultiEp...
null
183,875
import logging import numpy as np import torch from fairseq.data import FairseqDataset, data_utils logger = logging.getLogger(__name__) def collate( samples, pad_idx, eos_idx, left_pad_source=True, left_pad_target=False, input_feeding=True, pad_to_length=None, pad_to_multiple=1, ): ...
null
183,878
import numpy as np import torch from . import FairseqDataset, data_utils def collate(samples, pad_idx, eos_idx): if len(samples) == 0: return {} def merge(key, is_list=False): if is_list: res = [] for i in range(len(samples[0][key])): res.append( ...
null
183,886
import shutil import struct from functools import lru_cache import numpy as np import torch from fairseq.dataclass.constants import DATASET_IMPL_CHOICES from fairseq.data.fasta_dataset import FastaDataset from fairseq.file_io import PathManager from . import FairseqDataset from typing import Union DATASET_IMPL_CHOICES...
null
183,887
import shutil import struct from functools import lru_cache import numpy as np import torch from fairseq.dataclass.constants import DATASET_IMPL_CHOICES from fairseq.data.fasta_dataset import FastaDataset from fairseq.file_io import PathManager from . import FairseqDataset from typing import Union def index_file_path(p...
null
183,888
import shutil import struct from functools import lru_cache import numpy as np import torch from fairseq.dataclass.constants import DATASET_IMPL_CHOICES from fairseq.data.fasta_dataset import FastaDataset from fairseq.file_io import PathManager from . import FairseqDataset from typing import Union def best_fitting_int_...
null