code stringlengths 17 6.64M |
|---|
class StreamingEpochBatchIterator(EpochBatchIterating):
def __init__(self, dataset, epoch=0, num_shards=1, shard_id=0):
self.dataset = dataset
self.epoch = epoch
self._current_epoch_iterator = None
self.num_shards = num_shards
self.shard_id = shard_id
def next_epoch_i... |
class EpochBatchIterator(EpochBatchIterating):
'A multi-epoch iterator over a :class:`torch.utils.data.Dataset`.\n\n Compared to :class:`torch.utils.data.DataLoader`, this iterator:\n\n - can be reused across multiple epochs with the :func:`next_epoch_itr`\n method (optionally shuffled between epochs)\... |
class GroupedIterator(object):
'Wrapper around an iterable that returns groups (chunks) of items.\n\n Args:\n iterable (iterable): iterable to wrap\n chunk_size (int): size of each chunk\n '
def __init__(self, iterable, chunk_size):
self._len = int(math.ceil((len(iterable) / float... |
class ShardedIterator(object):
"A sharded wrapper around an iterable, padded to length.\n\n Args:\n iterable (iterable): iterable to wrap\n num_shards (int): number of shards to split the iterable into\n shard_id (int): which shard to iterator over\n fill_value (Any, optional): padd... |
class BlockPairDataset(FairseqDataset):
"Break a Dataset of tokens into sentence pair blocks for next sentence\n prediction as well as masked language model.\n\n High-level logics are:\n 1. break input tensor to tensor blocks\n 2. pair the blocks with 50% next sentence and 50% random sente... |
class MaskedLMDataset(FairseqDataset):
'\n A wrapper Dataset for masked language modelling. The dataset\n wraps around TokenBlockDataset or BlockedPairDataset and creates a batch\n where the input blocks are masked according to the specified masking\n probability. Additionally the batch can also conta... |
class MaskedLMDictionary(Dictionary):
'\n Dictionary for Masked Language Modelling tasks. This extends Dictionary by\n adding the mask symbol.\n '
def __init__(self, pad='<pad>', eos='</s>', unk='<unk>', mask='<mask>'):
super().__init__(pad, eos, unk)
self.mask_word = mask
se... |
class BertDictionary(MaskedLMDictionary):
'\n Dictionary for BERT task. This extends MaskedLMDictionary by adding support\n for cls and sep symbols.\n '
def __init__(self, pad='<pad>', eos='</s>', unk='<unk>', mask='<mask>', cls='<cls>', sep='<sep>'):
super().__init__(pad, eos, unk, mask)
... |
class ListDataset(BaseWrapperDataset):
def __init__(self, dataset, sizes=None):
super().__init__(dataset)
self._sizes = sizes
def collater(self, samples):
return samples
@property
def sizes(self):
return self._sizes
def num_tokens(self, index):
return se... |
class LRUCacheDataset(BaseWrapperDataset):
def __init__(self, dataset, token=None):
super().__init__(dataset)
@lru_cache(maxsize=8)
def __getitem__(self, index):
return self.dataset[index]
@lru_cache(maxsize=8)
def collater(self, samples):
return self.dataset.collater(sa... |
class MaskTokensDataset(BaseWrapperDataset):
'\n A wrapper Dataset for masked language modeling.\n\n Input items are masked according to the specified masking probability.\n\n Args:\n dataset: Dataset to wrap.\n sizes: Sentence lengths\n vocab: Dictionary with the vocabulary and spec... |
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_utils.collate_tokens([s[key][i] for s in samples], pad_idx, eos_idx, left... |
class MonolingualDataset(FairseqDataset):
'\n A wrapper around torch.utils.data.Dataset for monolingual data.\n\n Args:\n dataset (torch.utils.data.Dataset): dataset to wrap\n sizes (List[int]): sentence lengths\n vocab (~fairseq.data.Dictionary): vocabulary\n shuffle (bool, opti... |
def uniform_sampler(x):
return np.random.choice(x, 1).item()
|
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 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... |
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:
print('| dis... |
def suppress_output(is_master):
'Suppress printing on the current device. Force printing with `force=True`.'
import builtins as __builtin__
builtin_print = __builtin__.print
def print(*args, **kwargs):
force = kwargs.pop('force', False)
if (is_master or force):
builtin_pri... |
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 ... |
def load_archive_file(archive_file):
try:
resolved_archive_file = cached_path(archive_file, cache_dir=None)
except EnvironmentError:
print("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.".format... |
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 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 AverageMeter(object):
'Computes and stores the average and current value'
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += (val... |
class TimeMeter(object):
'Computes the average occurrence of some event per second'
def __init__(self, init=0):
self.reset(init)
def reset(self, init=0):
self.init = init
self.start = time.time()
self.n = 0
def update(self, val=1):
self.n += val
@propert... |
class StopwatchMeter(object):
'Computes the sum/avg duration of some event in seconds'
def __init__(self):
self.reset()
def start(self):
self.start_time = time.time()
def stop(self, n=1):
if (self.start_time is not None):
delta = (time.time() - self.start_time)
... |
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... |
def _skeptical_unmasking(output_scores, output_masks, p):
sorted_index = output_scores.sort((- 1))[1]
boundary_len = ((output_masks.sum(1, keepdim=True).type_as(output_scores) - 2) * p).long()
skeptical_mask = (new_arange(output_masks) < boundary_len)
return skeptical_mask.scatter(1, sorted_index, ske... |
@register_model('cmlm_transformer')
class CMLMNATransformerModel(NATransformerModel):
@staticmethod
def add_args(parser):
NATransformerModel.add_args(parser)
def forward(self, src_tokens, src_lengths, prev_output_tokens, tgt_tokens, **kwargs):
assert (not self.decoder.src_embedding_copy)... |
@register_model_architecture('cmlm_transformer', 'cmlm_transformer')
def base_architecture(args):
args.encoder_embed_path = getattr(args, 'encoder_embed_path', None)
args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512)
args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 2048)
... |
@register_model_architecture('cmlm_transformer', 'cmlm_transformer_wmt_en_de')
def iter_nat_wmt_en_de(args):
base_architecture(args)
|
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:`... |
def DistributedFairseqModel(args, model):
'\n Wrap a *model* to support distributed data parallel training.\n\n This is similar to the built-in DistributedDataParallel, but allows\n additional configuration of the DistributedDataParallel class to\n use, and also provides easier access to the wrapped m... |
class FairseqDecoder(nn.Module):
'Base class for decoders.'
def __init__(self, dictionary):
super().__init__()
self.dictionary = dictionary
self.onnx_trace = False
def forward(self, prev_output_tokens, encoder_out=None, **kwargs):
"\n Args:\n prev_output... |
class FairseqEncoder(nn.Module):
'Base class for encoders.'
def __init__(self, dictionary):
super().__init__()
self.dictionary = dictionary
def forward(self, src_tokens, src_lengths=None, **kwargs):
'\n Args:\n src_tokens (LongTensor): tokens in the source langu... |
class FairseqIncrementalDecoder(FairseqDecoder):
'Base class for incremental decoders.\n\n Incremental decoding is a special mode at inference time where the Model\n only receives a single timestep of input corresponding to the previous\n output token (for teacher forcing) and must produce the next outpu... |
class BaseFairseqModel(nn.Module):
'Base class for fairseq models.'
def __init__(self):
super().__init__()
self._is_generation_fast = False
@staticmethod
def add_args(parser):
'Add model-specific arguments to the parser.'
pass
@classmethod
def build_model(cls... |
class FairseqEncoderDecoderModel(BaseFairseqModel):
'Base class for encoder-decoder models.\n\n Args:\n encoder (FairseqEncoder): the encoder\n decoder (FairseqDecoder): the decoder\n '
def __init__(self, encoder, decoder):
super().__init__()
self.encoder = encoder
... |
class FairseqModel(FairseqEncoderDecoderModel):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
utils.deprecation_warning('FairseqModel is deprecated, please use FairseqEncoderDecoderModel or BaseFairseqModel instead', stacklevel=4)
|
class FairseqMultiModel(BaseFairseqModel):
'Base class for combining multiple encoder-decoder models.'
def __init__(self, encoders, decoders):
super().__init__()
assert (encoders.keys() == decoders.keys())
self.keys = list(encoders.keys())
for key in self.keys:
ass... |
class FairseqLanguageModel(BaseFairseqModel):
'Base class for decoder-only models.\n\n Args:\n decoder (FairseqDecoder): the decoder\n '
def __init__(self, decoder):
super().__init__()
self.decoder = decoder
assert isinstance(self.decoder, FairseqDecoder)
def forward... |
class FairseqEncoderModel(BaseFairseqModel):
'Base class for encoder-only models.\n\n Args:\n encoder (FairseqEncoder): the encoder\n '
def __init__(self, encoder):
super().__init__()
self.encoder = encoder
assert isinstance(self.encoder, FairseqEncoder)
def forward(... |
@register_model('fconv_lm')
class FConvLanguageModel(FairseqLanguageModel):
def __init__(self, decoder):
super().__init__(decoder)
@staticmethod
def add_args(parser):
'Add model-specific arguments to the parser.'
parser.add_argument('--dropout', type=float, metavar='D', help='dro... |
@register_model_architecture('fconv_lm', 'fconv_lm')
def base_lm_architecture(args):
args.dropout = getattr(args, 'dropout', 0.1)
args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 128)
args.decoder_layers = getattr(args, 'decoder_layers', '[(1268, 4)] * 13')
args.decoder_attention = getattr(... |
@register_model_architecture('fconv_lm', 'fconv_lm_dauphin_wikitext103')
def fconv_lm_dauphin_wikitext103(args):
layers = '[(850, 6)] * 3'
layers += ' + [(850, 1)] * 1'
layers += ' + [(850, 5)] * 4'
layers += ' + [(850, 1)] * 1'
layers += ' + [(850, 4)] * 3'
layers += ' + [(1024, 4)] * 1'
... |
@register_model_architecture('fconv_lm', 'fconv_lm_dauphin_gbw')
def fconv_lm_dauphin_gbw(args):
layers = '[(512, 5)]'
layers += ' + [(128, 1, 0), (128, 5, 0), (512, 1, 3)] * 3'
layers += ' + [(512, 1, 0), (512, 5, 0), (1024, 1, 3)] * 3'
layers += ' + [(1024, 1, 0), (1024, 5, 0), (2048, 1, 3)] * 6'
... |
@register_model('fconv_self_att')
class FConvModelSelfAtt(FairseqEncoderDecoderModel):
@classmethod
def hub_models(cls):
return {'conv.stories': 'https://dl.fbaipublicfiles.com/fairseq/models/stories_checkpoint.tar.bz2', 'data.stories': 'https://dl.fbaipublicfiles.com/fairseq/data/stories_test.tar.bz... |
class FConvEncoder(FairseqEncoder):
'Convolutional encoder'
def __init__(self, dictionary, embed_dim=512, max_positions=1024, convolutions=(((512, 3),) * 20), dropout=0.1, attention=False, attention_nheads=1):
super().__init__(dictionary)
self.dropout = dropout
self.num_attention_laye... |
class FConvDecoder(FairseqDecoder):
'Convolutional decoder'
def __init__(self, dictionary, embed_dim=512, out_embed_dim=256, max_positions=1024, convolutions=(((512, 3),) * 8), attention=True, dropout=0.1, selfattention=False, attention_nheads=1, selfattention_nheads=1, project_input=False, gated_attention=F... |
class SelfAttention(nn.Module):
def __init__(self, out_channels, embed_dim, num_heads, project_input=False, gated=False, downsample=False):
super().__init__()
self.attention = DownsampledMultiHeadAttention(out_channels, embed_dim, num_heads, dropout=0, bias=True, project_input=project_input, gate... |
def Embedding(num_embeddings, embedding_dim, padding_idx):
m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)
m.weight.data.normal_(0, 0.1)
return m
|
def PositionalEmbedding(num_embeddings, embedding_dim, padding_idx):
m = LearnedPositionalEmbedding(num_embeddings, embedding_dim, padding_idx)
m.weight.data.normal_(0, 0.1)
return m
|
def Linear(in_features, out_features, dropout=0.0):
'Weight-normalized Linear layer (input: N x T x C)'
m = nn.Linear(in_features, out_features)
m.weight.data.normal_(mean=0, std=math.sqrt(((1 - dropout) / in_features)))
m.bias.data.zero_()
return m
|
def LinearizedConv1d(in_channels, out_channels, kernel_size, dropout=0.0, **kwargs):
'Weight-normalized Conv1d layer optimized for decoding'
m = LinearizedConvolution(in_channels, out_channels, kernel_size, **kwargs)
std = math.sqrt(((4 * (1.0 - dropout)) / (m.kernel_size[0] * in_channels)))
m.weight.... |
def ConvTBC(in_channels, out_channels, kernel_size, dropout=0, **kwargs):
'Weight-normalized Conv1d layer'
from fairseq.modules import ConvTBC
m = ConvTBC(in_channels, out_channels, kernel_size, **kwargs)
std = math.sqrt(((4 * (1.0 - dropout)) / (m.kernel_size[0] * in_channels)))
m.weight.data.nor... |
@register_model_architecture('fconv_self_att', 'fconv_self_att')
def base_architecture(args):
args.dropout = getattr(args, 'dropout', 0.1)
args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512)
args.encoder_layers = getattr(args, 'encoder_layers', '[(512, 3)] * 3')
args.decoder_embed_dim = g... |
@register_model_architecture('fconv_self_att', 'fconv_self_att_wp')
def fconv_self_att_wp(args):
args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 256)
args.encoder_layers = getattr(args, 'encoder_layers', '[(128, 3)] * 2 + [(512,3)] * 1')
args.decoder_embed_dim = getattr(args, 'decoder_embed_di... |
@register_model('lightconv_lm')
class LightConvLanguageModel(FairseqLanguageModel):
def __init__(self, decoder):
super().__init__(decoder)
@staticmethod
def add_args(parser):
'Add model-specific arguments to the parser.'
parser.add_argument('--dropout', default=0.1, type=float, m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.