id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
19,068 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq.modules.scalar_bias import scalar_bias
def Linear(in_features, out_features, dropout=0., bias=True):
"""Weight-normalized Linear layer (input: B x T x C)"""
m = nn.Linear(in_features, out_features, bias=bias)
m.weigh... | Weight-normalized Linear layer (input: B x T x C) with interspersed GLU units |
19,069 | import torch
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `quant_noise` function. Write a Python function `def quant_noise(module, p, block_size)` to solve the following problem:
Wraps modules and applies quantization noise to the weights for subsequent quantizat... | Wraps modules and applies quantization noise to the weights for subsequent quantization with Iterative Product Quantization as described in "Training with Quantization Noise for Extreme Model Compression" Args: - module: nn.Module - p: amount of Quantization Noise - block_size: size of the blocks for subsequent quantiz... |
19,070 | import logging
import re
from operator import attrgetter, itemgetter
import numpy as np
import torch.nn as nn
import torch.distributed as dist
from .modules import PQConv2d, PQLinear, PQEmbedding
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... |
19,071 | def convert_yaml_to_tuple(yaml_dictionary):
"""Converts a yaml dictionary with two keys: `key` and `value` into a two
argument tuple of those values."""
return (yaml_dictionary["key"], yaml_dictionary["value"])
def parse_config_yaml(yaml_data):
# Initialize to default options.
quantization_options ... | null |
19,072 | import logging
from operator import attrgetter
import torch.nn as nn
import torch.distributed as dist
from ..pq.utils import get_layers, attrsetter
from .modules import IntConv2d, IntLinear, IntEmbedding, ActivationQuantizer
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... |
19,073 | import torch
def emulate_int(w, bits, method, scale=None, zero_point=None):
q = globals()[f"emulate_int{bits}_{method}"]
return q(w, scale=scale, zero_point=zero_point) | null |
19,074 | 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_histogram(w, scale=None, zero_point=None):
if scale is None:
obs = torch.quantization.observer.HistogramObserver()
_ = obs(w.float())
... | null |
19,075 | 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_channel(w, scale=None, zero_point=None):
if scale is None:
obs = torch.quantization.observer.PerChannelMinMaxObserver(
ch_axis=-1, qscheme... | null |
19,076 | import torch
def quantize(w, scale, zero_point):
def emulate_int8_tensor(w, scale=None, zero_point=None):
if scale is None:
obs = torch.quantization.observer.MinMaxObserver()
_ = obs(w)
scale, zero_point = obs.calculate_qparams()
scale = scale.cuda().type_as(w)
zero_point = ... | null |
19,077 | import torch.nn as nn
from .learned_positional_embedding import LearnedPositionalEmbedding
from .sinusoidal_positional_embedding import SinusoidalPositionalEmbedding
class LearnedPositionalEmbedding(nn.Embedding):
def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int):
def forward(
... | null |
19,078 | import collections
import logging
import os
import re
import traceback
from collections import OrderedDict
from typing import Union
import torch
from fairseq.file_io import PathManager
from fairseq.models import FairseqDecoder, FairseqEncoder
from torch.serialization import default_restore_location
def save_checkpoint(... | Load a checkpoint and restore the training iterator. *passthrough_args* will be passed through to ``trainer.get_train_iterator``. |
19,079 | import collections
import logging
import os
import re
import traceback
from collections import OrderedDict
from typing import Union
import torch
from fairseq.file_io import PathManager
from fairseq.models import FairseqDecoder, FairseqEncoder
from torch.serialization import default_restore_location
def torch_persistent... | null |
19,080 | import collections
import logging
import os
import re
import traceback
from collections import OrderedDict
from typing import Union
import torch
from fairseq.file_io import PathManager
from fairseq.models import FairseqDecoder, FairseqEncoder
from torch.serialization import default_restore_location
logger = logging.get... | 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... |
19,081 | import collections
import logging
import os
import re
import traceback
from collections import OrderedDict
from typing import Union
import torch
from fairseq.file_io import PathManager
from fairseq.models import FairseqDecoder, FairseqEncoder
from torch.serialization import default_restore_location
def load_checkpoint_... | 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. |
19,082 | import collections
import logging
import os
import re
import traceback
from collections import OrderedDict
from typing import Union
import torch
from fairseq.file_io import PathManager
from fairseq.models import FairseqDecoder, FairseqEncoder
from torch.serialization import default_restore_location
logger = logging.get... | null |
19,083 | import contextlib
import copy
import importlib.util
import logging
import math
import os
import sys
import warnings
from collections import defaultdict
from itertools import accumulate
from typing import Callable, Dict, List, Optional
import numpy as np
import torch
import torch.nn.functional as F
from fairseq.logging.... | null |
19,084 | import contextlib
import copy
import importlib.util
import logging
import math
import os
import sys
import warnings
from collections import defaultdict
from itertools import accumulate
from typing import Callable, Dict, List, Optional
import numpy as np
import torch
import torch.nn.functional as F
from fairseq.logging.... | Helper for getting incremental state for an nn.Module. |
19,085 | import contextlib
import copy
import importlib.util
import logging
import math
import os
import sys
import warnings
from collections import defaultdict
from itertools import accumulate
from typing import Callable, Dict, List, Optional
import numpy as np
import torch
import torch.nn.functional as F
from fairseq.logging.... | Helper for setting incremental state for an nn.Module. |
19,086 | import contextlib
import copy
import importlib.util
import logging
import math
import os
import sys
import warnings
from collections import defaultdict
from itertools import accumulate
from typing import Callable, Dict, List, Optional
import numpy as np
import torch
import torch.nn.functional as F
from fairseq.logging.... | null |
19,087 | import contextlib
import copy
import importlib.util
import logging
import math
import os
import sys
import warnings
from collections import defaultdict
from itertools import accumulate
from typing import Callable, Dict, List, Optional
import numpy as np
import torch
import torch.nn.functional as F
from fairseq.logging.... | 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 |
19,088 | import contextlib
import copy
import importlib.util
import logging
import math
import os
import sys
import warnings
from collections import defaultdict
from itertools import accumulate
from typing import Callable, Dict, List, Optional
import numpy as np
import torch
import torch.nn.functional as F
from fairseq.logging.... | null |
19,089 | import contextlib
import copy
import importlib.util
import logging
import math
import os
import sys
import warnings
from collections import defaultdict
from itertools import accumulate
from typing import Callable, Dict, List, Optional
import numpy as np
import torch
import torch.nn.functional as F
from fairseq.logging.... | Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols are ignored. |
19,090 | import contextlib
import copy
import importlib.util
import logging
import math
import os
import sys
import warnings
from collections import defaultdict
from itertools import accumulate
from typing import Callable, Dict, List, Optional
import numpy as np
import torch
import torch.nn.functional as F
from fairseq.logging.... | null |
19,091 | import contextlib
import copy
import importlib.util
import logging
import math
import os
import sys
import warnings
from collections import defaultdict
from itertools import accumulate
from typing import Callable, Dict, List, Optional
import numpy as np
import torch
import torch.nn.functional as F
from fairseq.logging.... | null |
19,092 | import contextlib
import copy
import importlib.util
import logging
import math
import os
import sys
import warnings
from collections import defaultdict
from itertools import accumulate
from typing import Callable, Dict, List, Optional
import numpy as np
import torch
import torch.nn.functional as F
from fairseq.logging.... | null |
19,093 | import contextlib
import copy
import importlib.util
import logging
import math
import os
import sys
import warnings
from collections import defaultdict
from itertools import accumulate
from typing import Callable, Dict, List, Optional
import numpy as np
import torch
import torch.nn.functional as F
from fairseq.logging.... | FP16-compatible function that fills a tensor with -inf. |
19,094 | import contextlib
import copy
import importlib.util
import logging
import math
import os
import sys
import warnings
from collections import defaultdict
from itertools import accumulate
from typing import Callable, Dict, List, Optional
import numpy as np
import torch
import torch.nn.functional as F
from fairseq.logging.... | null |
19,095 | import contextlib
import copy
import importlib.util
import logging
import math
import os
import sys
import warnings
from collections import defaultdict
from itertools import accumulate
from typing import Callable, Dict, List, Optional
import numpy as np
import torch
import torch.nn.functional as F
from fairseq.logging.... | null |
19,096 | import contextlib
import copy
import importlib.util
import logging
import math
import os
import sys
import warnings
from collections import defaultdict
from itertools import accumulate
from typing import Callable, Dict, List, Optional
import numpy as np
import torch
import torch.nn.functional as F
from fairseq.logging.... | Returns the activation function corresponding to `activation` |
19,097 | import contextlib
import copy
import importlib.util
import logging
import math
import os
import sys
import warnings
from collections import defaultdict
from itertools import accumulate
from typing import Callable, Dict, List, Optional
import numpy as np
import torch
import torch.nn.functional as F
from fairseq.logging.... | null |
19,098 | import contextlib
import copy
import importlib.util
import logging
import math
import os
import sys
import warnings
from collections import defaultdict
from itertools import accumulate
from typing import Callable, Dict, List, Optional
import numpy as np
import torch
import torch.nn.functional as F
from fairseq.logging.... | null |
19,099 | import contextlib
import copy
import importlib.util
import logging
import math
import os
import sys
import warnings
from collections import defaultdict
from itertools import accumulate
from typing import Callable, Dict, List, Optional
import numpy as np
import torch
import torch.nn.functional as F
from fairseq.logging.... | 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). |
19,100 | import contextlib
import copy
import importlib.util
import logging
import math
import os
import sys
import warnings
from collections import defaultdict
from itertools import accumulate
from typing import Callable, Dict, List, Optional
import numpy as np
import torch
import torch.nn.functional as F
from fairseq.logging.... | null |
19,101 | import os
from collections import Counter
from fairseq.tokenizer import tokenize_line
import torch
def safe_readline(f):
pos = f.tell()
while True:
try:
return f.readline()
except UnicodeDecodeError:
pos -= 1
f.seek(pos) # search where this character begins | null |
19,102 | 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. |
19,103 | 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
class AverageMeter(Meter):
"""Computes and stores t... | null |
19,104 | 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 rename_logger(logger, new_name):
old_name = log... | null |
19,105 | 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
try:
_tensorboard_writers = {}
from tensorboardX... | null |
19,106 | from collections import defaultdict, OrderedDict
import contextlib
import time
from typing import Callable, Dict, List, Optional
import uuid
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... |
19,107 | from collections import defaultdict, OrderedDict
import contextlib
import time
from typing import Callable, Dict, List, Optional
import uuid
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 |
19,108 | from collections import defaultdict, OrderedDict
import contextlib
import time
from typing import Callable, Dict, List, Optional
import uuid
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 |
19,109 | from collections import defaultdict, OrderedDict
import contextlib
import time
from typing import Callable, Dict, List, Optional
import uuid
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 |
19,110 | from collections import defaultdict, OrderedDict
import contextlib
import time
from typing import Callable, Dict, List, Optional
import uuid
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... |
19,111 | from collections import defaultdict, OrderedDict
import contextlib
import time
from typing import Callable, Dict, List, Optional
import uuid
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 |
19,112 | from collections import defaultdict, OrderedDict
import contextlib
import time
from typing import Callable, Dict, List, Optional
import uuid
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*. |
19,113 | from collections import defaultdict, OrderedDict
import contextlib
import time
from typing import Callable, Dict, List, Optional
import uuid
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*. |
19,114 | from collections import defaultdict, OrderedDict
import contextlib
import time
from typing import Callable, Dict, List, Optional
import uuid
from .meters import *
_aggregators = OrderedDict()
def state_dict():
return OrderedDict([
(name, agg.state_dict())
for name, agg in _aggregators.items()
]... | null |
19,115 | from collections import defaultdict, OrderedDict
import contextlib
import time
from typing import Callable, Dict, List, Optional
import uuid
from .meters import *
_aggregators = OrderedDict()
class MetersDict(OrderedDict):
"""A sorted dictionary of :class:`Meters`.
Meters are sorted according to a priority th... | null |
19,116 | import contextlib
from itertools import chain
import logging
import sys
from typing import Any, Dict, List
import torch
from fairseq import checkpoint_utils, distributed_utils, models, optim, utils
from fairseq.file_io import PathManager
from fairseq.logging import meters, metrics
from fairseq.nan_detector import NanDe... | null |
19,117 | import contextlib
from itertools import chain
import logging
import sys
from typing import Any, Dict, List
import torch
from fairseq import checkpoint_utils, distributed_utils, models, optim, utils
from fairseq.file_io import PathManager
from fairseq.logging import meters, metrics
from fairseq.nan_detector import NanDe... | null |
19,118 | import contextlib
from itertools import chain
import logging
import sys
from typing import Any, Dict, List
import torch
from fairseq import checkpoint_utils, distributed_utils, models, optim, utils
from fairseq.file_io import PathManager
from fairseq.logging import meters, metrics
from fairseq.nan_detector import NanDe... | null |
19,119 | import fnmatch
from functools import wraps, partial
from hashlib import sha256
from io import open
import json
import logging
import os
import shutil
import tarfile
import tempfile
The provided code snippet includes necessary dependencies for implementing the `filename_to_url` function. Write a Python function `def fi... | Return the url and etag (which may be ``None``) stored for `filename`. Raise ``EnvironmentError`` if `filename` or its stored metadata do not exist. |
19,120 | import fnmatch
from functools import wraps, partial
from hashlib import sha256
from io import open
import json
import logging
import os
import shutil
import tarfile
import tempfile
The provided code snippet includes necessary dependencies for implementing the `s3_request` function. Write a Python function `def s3_requ... | Wrapper function for s3 requests in order to create more helpful error messages. |
19,121 | import fnmatch
from functools import wraps, partial
from hashlib import sha256
from io import open
import json
import logging
import os
import shutil
import tarfile
import tempfile
The provided code snippet includes necessary dependencies for implementing the `read_set_from_file` function. Write a Python function `def... | Extract a de-duped collection (set) of text from a file. Expected file format is one item per line. |
19,122 | import fnmatch
from functools import wraps, partial
from hashlib import sha256
from io import open
import json
import logging
import os
import shutil
import tarfile
import tempfile
def get_file_extension(path, dot=True, lower=True):
ext = os.path.splitext(path)[1]
ext = ext if dot else ext[1:]
return ext.l... | null |
19,123 | import logging
import os
import pickle
import random
import socket
import struct
import subprocess
import warnings
from collections import OrderedDict
from typing import Any, Dict, Mapping
import torch
import torch.distributed as dist
from fairseq import utils
def get_rank():
return dist.get_rank()
def get_world_si... | Gathers arbitrary data from all nodes into a list. Similar to :func:`~torch.distributed.all_gather` but for arbitrary Python data. Note that *data* must be picklable. Args: data (Any): data from the local worker to be gathered on other workers group (optional): group of the collective max_size (int, optional): maximum ... |
19,124 | import logging
import os
import pickle
import random
import socket
import struct
import subprocess
import warnings
from collections import OrderedDict
from typing import Any, Dict, Mapping
import torch
import torch.distributed as dist
from fairseq import utils
def all_reduce(tensor, group=None):
if isinstance(group... | AllReduce a dictionary of values across workers. We separately reduce items that are already on the device and items on CPU for better performance. Args: data (Mapping[str, Any]): dictionary of data to all-reduce, but cannot be a nested dictionary device (torch.device): device for the reduction group (optional): group ... |
19,125 | import numpy as np
from fairseq.data import data_utils
from . import BaseWrapperDataset
class TruncateDataset(BaseWrapperDataset):
"""Truncate a sequence by returning the first truncation_length tokens
"""
def __init__(self, dataset, truncation_length):
super().__init__(dataset)
assert trunc... | null |
19,126 | import numpy as np
import torch
import math
from . import data_utils, FairseqDataset
def collate(
samples,
pad_idx,
eos_idx,
vocab,
left_pad_source=False,
left_pad_target=False,
input_feeding=True,
):
assert input_feeding
if len(samples) == 0:
return {}
def merge(key, l... | null |
19,127 | from collections import OrderedDict
from typing import Callable, Dict, List
import numpy as np
from . import FairseqDataset
def uniform_sampler(x):
# Sample from uniform distribution
return np.random.choice(x, 1).item() | null |
19,128 | import contextlib
import itertools
import logging
import os
import sys
import types
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `infer_language_pair` function. Write a Python function `def infer_language_pair(path)` to solve the following problem:
Infer language pa... | Infer language pair from filename: <split>.<lang1>-<lang2>.(...).idx |
19,129 | import contextlib
import itertools
import logging
import os
import sys
import types
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `numpy_seed` function. Write a Python function `def numpy_seed(seed, *addl_seeds)` to solve the following problem:
Context manager which ... | Context manager which seeds the NumPy PRNG with the specified seed and restores the state afterward |
19,130 | import contextlib
import itertools
import logging
import os
import sys
import types
import numpy as np
logger = logging.getLogger(__name__)
def _filter_by_size_dynamic(indices, size_fn, max_positions, raise_exception=False):
def check_size(idx):
if isinstance(max_positions, float) or isinstance(max_position... | Filter indices based on their size. 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_exception (bool, optional): if ``True``, raise an exception if any el... |
19,131 | import contextlib
import itertools
import logging
import os
import sys
import types
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `batch_by_size` function. Write a Python function `def batch_by_size( indices, num_tokens_fn, max_tokens=None, max_sentences=None, ... | 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 max_tokens (int, optional): max number of tokens in each batch (default: No... |
19,132 | import contextlib
import itertools
import logging
import os
import sys
import types
import numpy as np
def process_bpe_symbol(sentence: str, bpe_symbol: str):
if bpe_symbol == 'sentencepiece':
sentence = sentence.replace(' ', '').replace('\u2581', ' ').strip()
elif bpe_symbol == '_EOW':
sentenc... | null |
19,133 | import itertools
import math
import operator
import os
import time
import numpy as np
import torch
import queue
import logging
from threading import Thread
from . import data_utils
def _chunk_iterator(itr, chunk_size):
chunk = []
for x in itr:
chunk.append(x)
if len(chunk) == chunk_size:
... | null |
19,134 | import logging
import numpy as np
import torch
from . import data_utils, FairseqDataset
logger = logging.getLogger(__name__)
def collate(
samples, pad_idx, eos_idx, left_pad_source=True, left_pad_target=False,
input_feeding=True,
):
if len(samples) == 0:
return {}
def merge(key, left_pad, move... | null |
19,135 | from collections import OrderedDict
import torch
from torch.utils.data.dataloader import default_collate
from . import FairseqDataset
The provided code snippet includes necessary dependencies for implementing the `_flatten` function. Write a Python function `def _flatten(dico, prefix=None)` to solve the following prob... | Flatten a nested dictionary. |
19,136 | from collections import OrderedDict
import torch
from torch.utils.data.dataloader import default_collate
from . import FairseqDataset
The provided code snippet includes necessary dependencies for implementing the `_unflatten` function. Write a Python function `def _unflatten(dico)` to solve the following problem:
Unfl... | Unflatten a flattened dictionary into a nested dictionary. |
19,137 | import numpy as np
import torch
from . import data_utils, FairseqDataset
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(data_uti... | null |
19,138 | import torch
from fairseq.data import encoders
def get_whole_word_mask(args, dictionary):
bpe = encoders.build_bpe(args)
if bpe is not None:
def is_beginning_of_word(i):
if i < dictionary.nspecial:
# special elements are always considered beginnings
return Tr... | null |
19,139 | from functools import lru_cache
import json
The provided code snippet includes necessary dependencies for implementing the `bytes_to_unicode` function. Write a Python function `def bytes_to_unicode()` to solve the following problem:
Returns list of utf-8 byte and a corresponding list of unicode strings. The reversible... | Returns list of utf-8 byte and a corresponding list of unicode strings. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. This ... |
19,140 | from functools import lru_cache
import json
The provided code snippet includes necessary dependencies for implementing the `get_pairs` function. Write a Python function `def get_pairs(word)` to solve the following problem:
Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being var... | Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings). |
19,141 | from functools import lru_cache
import json
class Encoder:
def __init__(self, encoder, bpe_merges, errors='replace'):
self.encoder = encoder
self.decoder = {v:k for k,v in self.encoder.items()}
self.errors = errors # how to handle errors in decoding
self.byte_encoder = bytes_to_unico... | null |
19,142 | import re
def byte_decode(x: str) -> str:
try:
return bytes([BCHAR_TO_BYTE[bc] for bc in x]).decode('utf-8')
except ValueError:
return ''
def smart_byte_decode(x: str) -> str:
output = byte_decode(x)
if output == '':
# DP the best recovery (max valid chars) if it's broken
... | null |
19,143 | import torch
from fairseq import utils
from . import FairseqDataset
The provided code snippet includes necessary dependencies for implementing the `backtranslate_samples` function. Write a Python function `def backtranslate_samples(samples, collate_fn, generate_fn, cuda=True)` to solve the following problem:
Backtrans... | Backtranslate a list of samples. Given an input (*samples*) of the form: [{'id': 1, 'source': 'hallo welt'}] this will return: [{'id': 1, 'source': 'hello world', 'target': 'hallo welt'}] Args: samples (List[dict]): samples to backtranslate. Individual samples are expected to have a 'source' key, which will become the ... |
19,144 | from functools import lru_cache
import os
import shutil
import struct
import numpy as np
import torch
from . import FairseqDataset
def read_longs(f, n):
a = np.empty(n, dtype=np.int64)
f.readinto(a)
return a | null |
19,145 | from functools import lru_cache
import os
import shutil
import struct
import numpy as np
import torch
from . import FairseqDataset
def write_longs(f, a):
f.write(np.array(a, dtype=np.int64)) | null |
19,146 | from functools import lru_cache
import os
import shutil
import struct
import numpy as np
import torch
from . import FairseqDataset
dtypes = {
1: np.uint8,
2: np.int8,
3: np.int16,
4: np.int32,
5: np.int64,
6: np.float,
7: np.double,
8: np.uint16
}
def code(dtype):
for k in dtypes.ke... | null |
19,147 | from functools import lru_cache
import os
import shutil
import struct
import numpy as np
import torch
from . import FairseqDataset
def data_file_path(prefix_path):
return prefix_path + '.bin' | null |
19,148 | from functools import lru_cache
import os
import shutil
import struct
import numpy as np
import torch
from . import FairseqDataset
def _warmup_mmap_file(path):
with open(path, 'rb') as stream:
while stream.read(100 * 1024 * 1024):
pass | null |
19,149 | import argparse
REGISTRIES = {}
def set_defaults(args, cls):
"""Helper to set default arguments based on *add_args*."""
if not hasattr(cls, 'add_args'):
return
parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS, allow_abbrev=False)
cls.add_args(parser)
# copied from argparse... | null |
19,150 | import argparse
import copy
import logging
import os
from typing import List, Dict, Iterator, Tuple, Any
import torch
from torch import nn
from fairseq import utils
from fairseq.data import encoders
def from_pretrained(
model_name_or_path,
checkpoint_file='model.pt',
data_name_or_path='.',
archive_map=... | null |
19,151 | from argparse import Namespace
import json
import itertools
import logging
import os
import numpy as np
from fairseq import metrics, options, utils
from fairseq.data import (
AppendTokenDataset,
ConcatDataset,
data_utils,
encoders,
indexed_dataset,
LanguagePairDataset,
PrependTokenDataset,
... | null |
19,152 | from collections import OrderedDict
import logging
import os
import torch
from fairseq import metrics, options
from fairseq.data import (
Dictionary,
LanguagePairDataset,
RoundRobinZipDatasets,
TransformEosLangPairDataset,
)
from fairseq.models import FairseqMultiModel
from fairseq.tasks.translation imp... | Return language token index. |
19,153 | from collections import OrderedDict
import logging
import os
from fairseq.data import (
BacktranslationDataset,
data_utils,
indexed_dataset,
IndexedCachedDataset,
IndexedDataset,
IndexedRawTextDataset,
LanguagePairDataset,
NoisingDataset,
RoundRobinZipDatasets,
)
from fairseq.models ... | null |
19,154 | from collections import OrderedDict
import logging
import os
from fairseq.data import (
BacktranslationDataset,
data_utils,
indexed_dataset,
IndexedCachedDataset,
IndexedDataset,
IndexedRawTextDataset,
LanguagePairDataset,
NoisingDataset,
RoundRobinZipDatasets,
)
from fairseq.models ... | null |
19,155 | from collections import OrderedDict
import logging
import os
from fairseq.data import (
BacktranslationDataset,
data_utils,
indexed_dataset,
IndexedCachedDataset,
IndexedDataset,
IndexedRawTextDataset,
LanguagePairDataset,
NoisingDataset,
RoundRobinZipDatasets,
)
from fairseq.models ... | Parse the configuration of lambda coefficient (for scheduling). x = "3" # lambda will be a constant equal to x x = "0:1,1000:0" # lambda will start from 1 and linearly decrease # to 0 during the first 1000 iterations x = "0:0,1000:0,2000:1" # lambda will be equal to 0 for the first 1000 # iterations, then will linearly... |
19,156 | import argparse
import sys
from typing import Callable, List, Optional
import torch
from fairseq import utils
from fairseq.data.indexed_dataset import get_available_dataset_impl
def get_generation_parser(interactive=False, default_task="translation"):
parser = get_parser("Generation", default_task)
add_dataset_... | null |
19,157 | import argparse
import sys
from typing import Callable, List, Optional
import torch
from fairseq import utils
from fairseq.data.indexed_dataset import get_available_dataset_impl
def eval_bool(x, default=False):
if x is None:
return default
try:
return bool(eval(x))
except TypeError:
... | null |
19,158 | import math
from fairseq import metrics, utils
from fairseq.criterions import FairseqCriterion, register_criterion
def label_smoothed_nll_loss(lprobs, target, epsilon, ignore_index=None, reduce=True):
if target.dim() == lprobs.dim() - 1:
target = target.unsqueeze(-1)
nll_loss = -lprobs.gather(dim=-1, i... | null |
19,159 | import math
import torch
import torch.nn.functional as F
from fairseq import utils
from fairseq.criterions import FairseqCriterion, register_criterion
The provided code snippet includes necessary dependencies for implementing the `compute_cross_entropy_loss` function. Write a Python function `def compute_cross_entropy... | Function to compute the cross entropy loss. The default value of ignore_index is the same as the default value for F.cross_entropy in pytorch. |
19,160 | import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq import utils
from fairseq.models import (
FairseqEncoder,
register_model,
register_model_architecture,
)
from fairseq.models.roberta import (
RobertaModel,
RobertaEncoder,
RobertaLMHead,
RobertaCla... | null |
19,161 | import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq import utils
from fairseq.models import (
FairseqEncoder,
register_model,
register_model_architecture,
)
from fairseq.models.roberta import (
RobertaModel,
RobertaEncoder,
RobertaLMHead,
RobertaCla... | null |
19,162 | import torch.nn as nn
from fairseq.models import (
register_model,
register_model_architecture,
)
from fairseq.models.transformer_lm import (
base_lm_architecture,
TransformerLanguageModel,
)
from fairseq.model_parallel.models.transformer import (
ModelParallelTransformerDecoder,
)
def base_lm_arch... | null |
19,163 | import torch.nn as nn
from fairseq.models import (
register_model,
register_model_architecture,
)
from fairseq.models.transformer_lm import (
base_lm_architecture,
TransformerLanguageModel,
)
from fairseq.model_parallel.models.transformer import (
ModelParallelTransformerDecoder,
)
def base_lm_arch... | null |
19,164 | import multiprocessing
import os
import pdb
import sys
class MultiprocessingPdb(pdb.Pdb):
"""A Pdb wrapper that works in a multiprocessing environment.
Usage: `from fairseq import pdb; pdb.set_trace()`
"""
def __init__(self):
pdb.Pdb.__init__(self, nosigint=True)
def _cmdloop(self):
... | null |
19,165 | from typing import Dict, Optional
import uuid
from torch import Tensor
class FairseqIncrementalState(object):
def __init__(self, *args, **kwargs):
def init_incremental_state(self):
def _get_full_incremental_state_key(self, key: str) -> str:
def get_incremental_state(
self,
in... | null |
19,166 | import logging
from fairseq.modules.quantization import pq, quantization_options, scalar
def quantize_model_scalar(model, args):
quant_noise_scalar = getattr(args, 'quant_noise_scalar', 0)
if quant_noise_scalar > 0:
# quantize_model edits the model in place
scalar.quantize_model_(model, p=quant... | null |
19,167 | import torch.nn as nn
import torch.nn.functional as F
from fairseq.data import Dictionary
from fairseq.models import (
FairseqDecoder,
FairseqLanguageModel,
register_model,
register_model_architecture,
)
def base_architecture(args):
pass | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.