code stringlengths 17 6.64M |
|---|
class MultiCorpusSampledDataset(FairseqDataset):
'\n Stores multiple instances of FairseqDataset together and in every iteration\n creates a batch by first sampling a dataset according to a specified\n probability distribution and then getting instances from that dataset.\n\n Args:\n datasets: ... |
def _flatten(dico, prefix=None):
'Flatten a nested dictionary.'
new_dico = OrderedDict()
if isinstance(dico, dict):
prefix = ((prefix + '.') if (prefix is not None) else '')
for (k, v) in dico.items():
if (v is None):
continue
new_dico.update(_flatte... |
def _unflatten(dico):
'Unflatten a flattened dictionary into a nested dictionary.'
new_dico = OrderedDict()
for (full_k, v) in dico.items():
full_k = full_k.split('.')
node = new_dico
for k in full_k[:(- 1)]:
if (k.startswith('[') and k.endswith(']')):
k... |
class NestedDictionaryDataset(FairseqDataset):
def __init__(self, defn, sizes=None):
super().__init__()
self.defn = _flatten(defn)
self.sizes = ([sizes] if (not isinstance(sizes, (list, tuple))) else sizes)
first = None
for v in self.defn.values():
if (not isin... |
class NumSamplesDataset(FairseqDataset):
def __getitem__(self, index):
return 1
def __len__(self):
return 0
def collater(self, samples):
return sum(samples)
|
class NumelDataset(BaseWrapperDataset):
def __init__(self, dataset, reduce=False):
super().__init__(dataset)
self.reduce = reduce
def __getitem__(self, index):
item = self.dataset[index]
if torch.is_tensor(item):
return torch.numel(item)
else:
... |
class OffsetTokensDataset(BaseWrapperDataset):
def __init__(self, dataset, offset):
super().__init__(dataset)
self.offset = offset
def __getitem__(self, idx):
return (self.dataset[idx] + self.offset)
|
class PadDataset(BaseWrapperDataset):
def __init__(self, dataset, pad_idx, left_pad):
super().__init__(dataset)
self.pad_idx = pad_idx
self.left_pad = left_pad
def collater(self, samples):
return data_utils.collate_tokens(samples, self.pad_idx, left_pad=self.left_pad)
|
class LeftPadDataset(PadDataset):
def __init__(self, dataset, pad_idx):
super().__init__(dataset, pad_idx, left_pad=True)
|
class RightPadDataset(PadDataset):
def __init__(self, dataset, pad_idx):
super().__init__(dataset, pad_idx, left_pad=False)
|
class PlasmaArray(object):
'\n Wrapper around numpy arrays that automatically moves the data to shared\n memory upon serialization. This is particularly helpful when passing numpy\n arrays through multiprocessing, so that data is not unnecessarily\n duplicated or pickled.\n '
def __init__(self... |
class PrependDataset(BaseWrapperDataset):
def __init__(self, dataset, prepend_getter, ensure_first_token_is=None):
super().__init__(dataset)
self.prepend_getter = prepend_getter
self.ensure_first_token = ensure_first_token_is
def __getitem__(self, idx):
item = self.dataset[id... |
class PrependTokenDataset(BaseWrapperDataset):
def __init__(self, dataset, token=None):
super().__init__(dataset)
self.token = token
if (token is not None):
self._sizes = (np.array(dataset.sizes) + 1)
else:
self._sizes = dataset.sizes
def __getitem__(s... |
class RawLabelDataset(FairseqDataset):
def __init__(self, labels):
super().__init__()
self.labels = labels
def __getitem__(self, index):
return self.labels[index]
def __len__(self):
return len(self.labels)
def collater(self, samples):
return torch.tensor(sam... |
class ReplaceDataset(BaseWrapperDataset):
'Replaces tokens found in the dataset by a specified replacement token\n\n Args:\n dataset (~torch.utils.data.Dataset): dataset to replace tokens in\n replace_map(Dictionary[int,int]): map of token to replace -> replacement token\n ... |
class ResamplingDataset(BaseWrapperDataset):
'Randomly samples from a given dataset at each epoch.\n\n Sampling is done with or without replacement, depending on the "replace"\n parameter.\n\n Optionally, the epoch size can be rescaled. This is potentially desirable\n to increase per-epoch coverage of... |
class RollDataset(BaseWrapperDataset):
def __init__(self, dataset, shifts):
super().__init__(dataset)
self.shifts = shifts
def __getitem__(self, index):
item = self.dataset[index]
return torch.roll(item, self.shifts)
|
class RoundRobinZipDatasets(FairseqDataset):
'Zip multiple :class:`~fairseq.data.FairseqDataset` instances together.\n\n Shorter datasets are repeated in a round-robin fashion to match the length\n of the longest one.\n\n Args:\n datasets (Dict[~fairseq.data.FairseqDataset]): a dictionary of\n ... |
class ShardedDataset(BaseWrapperDataset):
'A :class:`~fairseq.data.FairseqDataset` wrapper that appends/prepends/strips EOS.\n\n Loads a dataset which has been sharded into multiple files. each shard is only loaded for each specific epoch\n\n '
def __init__(self, dictionary, dataset_impl: str, path: st... |
class SortDataset(BaseWrapperDataset):
def __init__(self, dataset, sort_order):
super().__init__(dataset)
if (not isinstance(sort_order, (list, tuple))):
sort_order = [sort_order]
self.sort_order = sort_order
assert all(((len(so) == len(dataset)) for so in sort_order))... |
class StripTokenDataset(BaseWrapperDataset):
def __init__(self, dataset, id_to_strip):
super().__init__(dataset)
self.id_to_strip = id_to_strip
def __getitem__(self, index):
item = self.dataset[index]
return item[item.ne(self.id_to_strip)]
|
class SubsampleDataset(BaseWrapperDataset):
'Subsamples a given dataset by a specified ratio. Subsampling is done on the number of examples\n\n Args:\n dataset (~torch.utils.data.Dataset): dataset to subsample\n size_ratio(float): the ratio to subsample to. must be between... |
class TransformEosDataset(FairseqDataset):
'A :class:`~fairseq.data.FairseqDataset` wrapper that appends/prepends/strips EOS.\n\n Note that the transformation is applied in :func:`collater`.\n\n Args:\n dataset (~fairseq.data.FairseqDataset): dataset to wrap\n eos (int): index of the end-of-se... |
class TruncateDataset(BaseWrapperDataset):
def __init__(self, dataset, truncation_length):
super().__init__(dataset)
assert (truncation_length is not None)
self.truncation_length = truncation_length
self.dataset = dataset
def __getitem__(self, index):
item = self.data... |
class GELU(torch.nn.Module):
def __init__(self):
super(GELU, self).__init__()
def forward(self, x):
return torch.nn.functional.gelu(x)
|
class Swish(torch.nn.Module):
def __init__(self):
super(Swish, self).__init__()
self.sigmoid = nn.Sigmoid()
def forward(self, x):
return (x * self.sigmoid(x))
|
def get_activation_layer(name):
if (name == 'relu'):
return nn.ReLU(inplace=False)
elif (name == 'leaky'):
return nn.LeakyReLU(negative_slope=0.1, inplace=False)
elif (name == 'selu'):
return nn.SELU(inplace=True)
elif (name == 'elu'):
return nn.ELU(inplace=True)
el... |
class DExTraEmb(nn.Module):
'\n This class implements embeddings similar to DeFINE emebeddings introduced in\n https://arxiv.org/abs/1911.12385\n '
def __init__(self, args, map_layer, use_bias: bool=True):
'\n :param args: Argument list\n :param map_layer: Mapping layer... |
class RecurrentDropout(nn.Module):
'\n Applies the same dropout mask across all time steps\n '
def __init__(self, p, batch_first=False):
'\n :param p: Dropout probability\n :param batch_first: Batch first or not\n '
super().__init__()
self.p = p
... |
def bound_function(low, high, value):
return max(low, min(high, value))
|
class GroupLinear(nn.Module):
'\n This class implements the Grouped Linear Transform\n This is based on the Pyramidal recurrent unit paper:\n https://arxiv.org/abs/1808.09029\n '
def __init__(self, in_features: int, out_features: int, n_groups: int=4, use_bias: bool=False, use_shu... |
class Linear(nn.Module):
'\n This class implements the fully connected layer\n '
def __init__(self, in_features, out_features, use_bias=True, num_gates=1, norm_type=None, dropout=0.0, act_type=None):
'\n :param in_features: number of input features\n :param out_features: number of... |
def get_weight_layer(name: str, in_features: int, out_features: int, groups: int=4, use_bias: bool=True, gates: int=1, shuffle: bool=False, norm_type: Optional[str]=None, dropout: float=0.0, act_type: Optional[str]=None):
if ((name == 'glt') and (groups == 1)):
name = 'linear'
if (name == 'linear'):
... |
def get_embedding_layer(num_embeddings, embedding_dim, padding_idx=None):
emb = nn.Embedding(num_embeddings, embedding_dim, padding_idx)
nn.init.normal_(emb.weight, mean=0, std=(embedding_dim ** (- 0.5)))
nn.init.constant_(emb.weight[padding_idx], 0)
return emb
|
class BatchNorm(nn.Module):
def __init__(self, num_features, eps=1e-05, affine=True):
super(BatchNorm, self).__init__()
self.layer = nn.BatchNorm1d(num_features=num_features, eps=eps, affine=affine)
def forward(self, x):
if (x.dim() == 3):
(bsz, seq_len, feature_size) = x... |
def get_norm_layer(name, out_features, num_groups=1, eps=1e-05, affine=True):
if ((name == 'gn') and (num_groups == 1)):
name = 'bn'
if (name == 'bn'):
return BatchNorm(num_features=out_features, eps=eps, affine=affine)
elif (name == 'ln'):
try:
from apex.normalization ... |
def get_curr_time_stamp():
return time.strftime('%Y-%m-%d %H:%M:%S')
|
def print_error_message(message):
time_stamp = get_curr_time_stamp()
error_str = (((text_colors['error'] + text_colors['bold']) + 'ERROR ') + text_colors['end_color'])
print('{} - {} - {}'.format(time_stamp, error_str, message))
print('{} - {} - {}'.format(time_stamp, error_str, 'Exiting!!!'))
ex... |
def print_log_message(message):
time_stamp = get_curr_time_stamp()
log_str = (((text_colors['logs'] + text_colors['bold']) + 'LOGS ') + text_colors['end_color'])
print('{} - {} - {}'.format(time_stamp, log_str, message))
|
def print_warning_message(message):
time_stamp = get_curr_time_stamp()
warn_str = (((text_colors['warning'] + text_colors['bold']) + 'WARNING') + text_colors['end_color'])
print('{} - {} - {}'.format(time_stamp, warn_str, message))
|
def print_info_message(message):
time_stamp = get_curr_time_stamp()
info_str = (((text_colors['info'] + text_colors['bold']) + 'INFO ') + text_colors['end_color'])
print('{} - {} - {}'.format(time_stamp, info_str, message))
|
def print_dash_line():
print((((text_colors['error'] + text_colors['bold']) + ('=' * 100)) + text_colors['end_color']))
|
def print_header(header):
print_dash_line()
print(((((text_colors['info'] + text_colors['bold']) + ('=' * 50)) + str(header)) + text_colors['end_color']))
print_dash_line()
|
def print_header_minor(header):
print(((((text_colors['warning'] + text_colors['bold']) + ('=' * 25)) + str(header)) + text_colors['end_color']))
|
def is_master(args):
return (args.distributed_rank == 0)
|
def infer_init_method(args):
if (args.distributed_init_method is not None):
return
if all(((key in os.environ) for key in ['MASTER_ADDR', 'MASTER_PORT', 'WORLD_SIZE', 'RANK'])):
args.distributed_init_method = 'env://'
args.distributed_world_size = int(os.environ['WORLD_SIZE'])
... |
def distributed_init(args):
if (args.distributed_world_size == 1):
raise ValueError('Cannot initialize distributed with distributed_world_size=1')
if torch.distributed.is_initialized():
warnings.warn('Distributed is already initialized, cannot initialize twice!')
else:
logger.info(... |
def get_rank():
return dist.get_rank()
|
def get_world_size():
return dist.get_world_size()
|
def get_default_group():
return dist.group.WORLD
|
def all_reduce(tensor, group=None):
if (group is None):
group = get_default_group()
return dist.all_reduce(tensor, group=group)
|
def all_gather_list(data, group=None, max_size=16384):
'Gathers arbitrary data from all nodes into a list.\n\n Similar to :func:`~torch.distributed.all_gather` but for arbitrary Python\n data. Note that *data* must be picklable.\n\n Args:\n data (Any): data from the local worker to be gathered on ... |
class PathManager():
"\n Wrapper for insulating OSS I/O (using Python builtin operations) from\n fvcore's PathManager abstraction (for transparently handling various\n internal backends).\n "
@staticmethod
def open(path: str, mode: str='r', buffering: int=(- 1), encoding: Optional[str]=None, ... |
def load_archive_file(archive_file):
try:
resolved_archive_file = cached_path(archive_file, cache_dir=None)
except EnvironmentError:
logger.info("Archive name '{}' was not found in archive name list. We assumed '{}' was a path or URL but couldn't find any file associated to this path or URL.".... |
def url_to_filename(url, etag=None):
"\n Convert `url` into a hashed filename in a repeatable way.\n If `etag` is specified, append its hash to the URL's, delimited\n by a period.\n "
url_bytes = url.encode('utf-8')
url_hash = sha256(url_bytes)
filename = url_hash.hexdigest()
if etag:
... |
def filename_to_url(filename, cache_dir=None):
'\n Return the url and etag (which may be ``None``) stored for `filename`.\n Raise ``EnvironmentError`` if `filename` or its stored metadata do not exist.\n '
if (cache_dir is None):
cache_dir = PYTORCH_FAIRSEQ_CACHE
if isinstance(cache_dir, ... |
def cached_path(url_or_filename, cache_dir=None):
"\n Given something that might be a URL (or might be a local path),\n determine which. If it's a URL, download the file and cache it, and\n return the path to the cached file. If it's already a local path,\n make sure the file exists and then return th... |
def split_s3_path(url):
'Split a full s3 path into the bucket name and path.'
parsed = urlparse(url)
if ((not parsed.netloc) or (not parsed.path)):
raise ValueError('bad s3 path {}'.format(url))
bucket_name = parsed.netloc
s3_path = parsed.path
if s3_path.startswith('/'):
s3_pa... |
def s3_request(func):
'\n Wrapper function for s3 requests in order to create more helpful error\n messages.\n '
@wraps(func)
def wrapper(url, *args, **kwargs):
from botocore.exceptions import ClientError
try:
return func(url, *args, **kwargs)
except ClientErr... |
@s3_request
def s3_etag(url):
'Check ETag on S3 object.'
import boto3
s3_resource = boto3.resource('s3')
(bucket_name, s3_path) = split_s3_path(url)
s3_object = s3_resource.Object(bucket_name, s3_path)
return s3_object.e_tag
|
@s3_request
def s3_get(url, temp_file):
'Pull a file directly from S3.'
import boto3
s3_resource = boto3.resource('s3')
(bucket_name, s3_path) = split_s3_path(url)
s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)
|
def http_get(url, temp_file):
import requests
from tqdm import tqdm
req = requests.get(url, stream=True)
content_length = req.headers.get('Content-Length')
total = (int(content_length) if (content_length is not None) else None)
progress = tqdm(unit='B', total=total)
for chunk in req.iter_c... |
def get_from_cache(url, cache_dir=None):
"\n Given a URL, look for the corresponding dataset in the local cache.\n If it's not there, download it. Then return the path to the cached file.\n "
if (cache_dir is None):
cache_dir = PYTORCH_FAIRSEQ_CACHE
if isinstance(cache_dir, Path):
... |
def read_set_from_file(filename):
'\n Extract a de-duped collection (set) of text from a file.\n Expected file format is one item per line.\n '
collection = set()
with open(filename, 'r', encoding='utf-8') as file_:
for line in file_:
collection.add(line.rstrip())
return c... |
def get_file_extension(path, dot=True, lower=True):
ext = os.path.splitext(path)[1]
ext = (ext if dot else ext[1:])
return (ext.lower() if lower else ext)
|
def from_pretrained(model_name_or_path, checkpoint_file='model.pt', data_name_or_path='.', archive_map=None, **kwargs):
from fairseq import checkpoint_utils, file_utils
if (archive_map is not None):
if (model_name_or_path in archive_map):
model_name_or_path = archive_map[model_name_or_path... |
class GeneratorHubInterface(nn.Module):
'\n PyTorch Hub interface for generating sequences from a pre-trained\n translation or language model.\n '
def __init__(self, args, task, models):
super().__init__()
self.args = args
self.task = task
self.models = nn.ModuleList(... |
class BPEHubInterface(object):
'PyTorch Hub interface for Byte-Pair Encoding (BPE).'
def __init__(self, bpe, **kwargs):
super().__init__()
args = argparse.Namespace(bpe=bpe, **kwargs)
self.bpe = encoders.build_bpe(args)
assert (self.bpe is not None)
def encode(self, sente... |
class TokenizerHubInterface(object):
'PyTorch Hub interface for tokenization.'
def __init__(self, tokenizer, **kwargs):
super().__init__()
args = argparse.Namespace(tokenizer=tokenizer, **kwargs)
self.tokenizer = encoders.build_tokenizer(args)
assert (self.tokenizer is not Non... |
class FairseqIncrementalState(object):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.init_incremental_state()
def init_incremental_state(self):
self._incremental_state_id = str(uuid.uuid4())
def _get_full_incremental_state_key(self, key: str) -> str... |
def with_incremental_state(cls):
cls.__bases__ = ((FairseqIncrementalState,) + tuple((b for b in cls.__bases__ if (b != FairseqIncrementalState))))
return cls
|
class LegacyDistributedDataParallel(nn.Module):
'Implements distributed data parallelism at the module level.\n\n A simplified version of :class:`torch.nn.parallel.DistributedDataParallel`.\n This version uses a c10d process group for communication and does not\n broadcast buffers.\n\n Args:\n ... |
class Meter(object):
'Base class for Meters.'
def __init__(self):
pass
def state_dict(self):
return {}
def load_state_dict(self, state_dict):
pass
def reset(self):
raise NotImplementedError
@property
def smoothed_value(self) -> float:
'Smoothed ... |
def safe_round(number, ndigits):
if hasattr(number, '__round__'):
return round(number, ndigits)
else:
return number
|
class AverageMeter(Meter):
'Computes and stores the average and current value'
def __init__(self, round: Optional[int]=None):
self.round = round
self.reset()
def reset(self):
self.val = None
self.sum = 0
self.count = 0
def update(self, val, n=1):
if (... |
class TimeMeter(Meter):
'Computes the average occurrence of some event per second'
def __init__(self, init: int=0, n: int=0, round: Optional[int]=None):
self.round = round
self.reset(init, n)
def reset(self, init=0, n=0):
self.init = init
self.start = time.perf_counter()
... |
class StopwatchMeter(Meter):
'Computes the sum/avg duration of some event in seconds'
def __init__(self, round: Optional[int]=None):
self.round = round
self.sum = 0
self.n = 0
self.start_time = None
def start(self):
self.start_time = time.perf_counter()
def s... |
class MetersDict(OrderedDict):
'A sorted dictionary of :class:`Meters`.\n\n Meters are sorted according to a priority that is given when the\n meter is first added to the dictionary.\n '
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.priorities = []
... |
@contextlib.contextmanager
def aggregate(name: Optional[str]=None, new_root: bool=False):
'Context manager to aggregate metrics under a given name.\n\n Aggregations can be nested. If *new_root* is ``False``, then logged\n metrics will be recorded along the entire stack of nested\n aggregators, including ... |
def get_active_aggregators() -> List[MetersDict]:
return list(_active_aggregators.values())
|
def log_scalar(key: str, value: float, weight: float=1, priority: int=10, round: Optional[int]=None):
'Log a scalar value.\n\n Args:\n key (str): name of the field to log\n value (float): value to log\n weight (float): weight that this value contributes to the average.\n A weigh... |
def log_derived(key: str, fn: Callable[([MetersDict], float)], priority: int=20):
'Log a scalar value derived from other meters.\n\n Args:\n key (str): name of the field to log\n fn (Callable[[MetersDict], float]): function that takes a single\n argument *meters* and returns the derive... |
def log_speed(key: str, value: float, priority: int=30, round: Optional[int]=None):
'Log the rate of some quantity per second.\n\n Args:\n key (str): name of the field to log\n value (float): value to log\n priority (int): smaller values are logged earlier in the output\n round (Opt... |
def log_start_time(key: str, priority: int=40, round: Optional[int]=None):
'Log the duration of some event in seconds.\n\n The duration will be computed once :func:`log_stop_time` is called.\n\n Args:\n key (str): name of the field to log\n priority (int): smaller values are logged earlier in ... |
def log_stop_time(key: str, weight: float=0.0):
'Log the duration of some event in seconds.\n\n The duration will be computed since :func:`log_start_time` was called.\n Set weight > 0 to report the average time instead of the sum.\n\n Args:\n key (str): name of the field to log\n weight (fl... |
def log_custom(new_meter_fn: Callable[([], Meter)], key: str, *args, priority: int=50, **kwargs):
"Log using a custom Meter.\n\n Any extra *args* or *kwargs* will be passed through to the Meter's\n *update* method.\n\n Args:\n new_meter_fn (Callable[[], Meter]): function that returns a new\n ... |
def reset_meter(name: str, key: str) -> None:
'Reset Meter instance aggregated under a given *name* and *key*.'
meter = get_meter(name, key)
if (meter is not None):
meter.reset()
|
def reset_meters(name: str) -> None:
'Reset Meter instances aggregated under a given *name*.'
meters = get_meters(name)
if (meters is not None):
meters.reset()
|
def get_meter(name: str, key: str) -> Meter:
'Get a single Meter instance aggregated under *name* and *key*.\n\n Returns:\n Meter or None if no metrics have been logged under *name* and *key*.\n '
if (name not in _aggregators):
return None
return _aggregators[name].get(key, None)
|
def get_meters(name: str) -> MetersDict:
'Get Meter instances aggregated under a given *name*.\n\n Returns:\n MetersDict or None if no metrics have been logged under *name*.\n '
return _aggregators.get(name, None)
|
def get_smoothed_value(name: str, key: str) -> float:
'Get a single smoothed value.\n\n Raises:\n KeyError: if no metrics have been logged under *name* and *key*.\n '
return _aggregators[name].get_smoothed_value(key)
|
def get_smoothed_values(name: str) -> Dict[(str, float)]:
'Get smoothed values aggregated under a given *name*.\n\n Raises:\n KeyError: if no metrics have been logged under *name*.\n '
return _aggregators[name].get_smoothed_values()
|
def state_dict():
return OrderedDict([(name, agg.state_dict()) for (name, agg) in _aggregators.items()])
|
def load_state_dict(state_dict):
for (name, agg_state) in state_dict.items():
_aggregators[name] = MetersDict()
_aggregators[name].load_state_dict(agg_state)
|
def build_model(args, task):
return ARCH_MODEL_REGISTRY[args.arch].build_model(args, task)
|
def register_model(name):
"\n New model types can be added to fairseq with the :func:`register_model`\n function decorator.\n\n For example::\n\n @register_model('lstm')\n class LSTM(FairseqEncoderDecoderModel):\n (...)\n\n .. note:: All models must implement the :class:`BaseF... |
def register_model_architecture(model_name, arch_name):
"\n New model architectures can be added to fairseq with the\n :func:`register_model_architecture` function decorator. After registration,\n model architectures can be selected with the ``--arch`` command-line\n argument.\n\n For example::\n\n... |
class CompositeEncoder(FairseqEncoder):
"\n A wrapper around a dictionary of :class:`FairseqEncoder` objects.\n\n We run forward on each encoder and return a dictionary of outputs. The first\n encoder's dictionary is used for initialization.\n\n Args:\n encoders (dict): a dictionary of :class:`... |
@register_model('delight_transformer_lm')
class DeLighTTransformerLanguageModel(FairseqLanguageModel):
@classmethod
def hub_models(cls):
return None
def __init__(self, decoder):
super().__init__(decoder)
@staticmethod
def add_args(parser):
'Add model-specific arguments t... |
@register_model_architecture('delight_transformer_lm', 'delight_transformer_lm')
def base_lm_architecture(args):
args.adaptive_input = getattr(args, 'adaptive_input', False)
args.adaptive_input_factor = getattr(args, 'adaptive_input_factor', ADAPTIVE_SCALE_FACTOR)
args.adaptive_input_cutoff = getattr(args... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.