instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Document all public functions with docstrings
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from .em import EM, EmptyClusterResolveError class PQ(EM): def __init__( self, W, block_size, n_centroi...
--- +++ @@ -7,6 +7,34 @@ class PQ(EM): + """ + Quantizes the layer weights W with the standard Product Quantization + technique. This learns a codebook of codewords or centroids of size + block_size from W. For further reference on using PQ to quantize + neural networks, see "And the Bit Goes Down: R...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/modules/quantization/pq/pq.py
Document this code for team use
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # import math import torch import torch.nn as nn import torch.nn.functional as F from fairseq.modules.fairseq_dropout import FairseqDropout ...
--- +++ @@ -15,6 +15,9 @@ class SingleHeadAttention(nn.Module): + """ + Single-head attention that supports Gating and Downsampling + """ def __init__( self, @@ -78,6 +81,13 @@ key_padding_mask=None, use_scalar_bias=False, ): + """Input shape: Time x Batch x Cha...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/modules/downsampled_multihead_attention.py
Add docstrings for better understanding
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch.nn as nn import torch import torch.nn.functional as F class LocationAttention(nn.Module): def __init__( self, ...
--- +++ @@ -9,6 +9,16 @@ class LocationAttention(nn.Module): + """ + Attention-Based Models for Speech Recognition + https://arxiv.org/pdf/1506.07503.pdf + + :param int encoder_dim: # projection-units of encoder + :param int decoder_dim: # units of decoder + :param int attn_dim: attention dimensio...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/modules/location_attention.py
Help me comply with documentation standards
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch.nn as nn import math import torch class PositionalEncoding(nn.Module): def __init__(self, d_model, dropout_rate, max_len=5...
--- +++ @@ -9,8 +9,17 @@ class PositionalEncoding(nn.Module): + """Positional encoding. + + Args: + d_model: Embedding dimension. + dropout_rate: Dropout rate. + max_len: Maximum input length. + reverse: Whether to reverse the input position. + """ def __init__(self, d_mo...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/modules/positional_encoding.py
Document this script properly
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn.functional as F from fairseq import utils from fairseq.incremental_decoding_utils import with_incremental_state ...
--- +++ @@ -16,6 +16,13 @@ @with_incremental_state class LinearizedConvolution(ConvTBC): + """An optimized version of nn.Conv1d. + + At training time, this module uses ConvTBC, which is an optimized version + of Conv1d. At inference time, it optimizes incremental generation (i.e., + one time step at a ti...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/modules/linearized_convolution.py
Add minimal docstrings for each function
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import torch from fairseq import optim from omegaconf import DictConfig logger = logging.getLogger(__name__) class AMPOptim...
--- +++ @@ -13,6 +13,9 @@ class AMPOptimizer(optim.FairseqOptimizer): + """ + Wrap an *optimizer* to support AMP (automatic mixed precision) training. + """ def __init__(self, cfg: DictConfig, params, fp32_optimizer, **kwargs): super().__init__(cfg.optimizer) @@ -25,10 +28,21 @@ @clas...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/optim/amp_optimizer.py
Improve my code by adding docstrings
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from dataclasses import dataclass, field import torch import torch.distributed as dist from fairseq.dataclass.configs import FairseqBMUFConfi...
--- +++ @@ -13,6 +13,14 @@ class FairseqBMUF(FairseqOptimizer): + """ + Implements incremental block distributed data parallelism similar to + https://ieeexplore.ieee.org/document/7472805 + + Paper title: Scalable training of deep learning machines by incremental + block training with intra-block par...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/optim/bmuf.py
Help me write clear docstrings
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch.optim from . import LegacyFairseqOptimizer, register_optimizer @register_optimizer("adadelta") class Adadelta(LegacyFairseqOpt...
--- +++ @@ -16,6 +16,7 @@ @staticmethod def add_args(parser): + """Add optimizer-specific arguments to the parser.""" # fmt: off parser.add_argument('--adadelta-rho', type=float, default=0.9, metavar='RHO', help='coefficient used for computing a running a...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/optim/adadelta.py
Write reusable docstrings
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import importlib from collections.abc import Collection from dataclasses import dataclass, field from typing import List import torch from fa...
--- +++ @@ -52,6 +52,12 @@ @register_optimizer("cpu_adam", dataclass=FairseqCPUAdamConfig) class FairseqCPUAdam(FairseqOptimizer): + """Adam optimizer for fairseq, optimized for CPU tensors. + + Important note: this optimizer corresponds to the "AdamW" variant of + Adam in its weight decay behavior. As such...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/optim/cpu_adam.py
Create documentation strings for testing functions
import torch class RotaryPositionalEmbedding(torch.nn.Module): def __init__(self, dim, base=10000, precision=torch.half): super().__init__() inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim)) self.register_buffer("inv_freq", inv_freq) self.seq_len_cached = 0 ...
--- +++ @@ -3,6 +3,14 @@ class RotaryPositionalEmbedding(torch.nn.Module): def __init__(self, dim, base=10000, precision=torch.half): + """Rotary positional embedding + Reference : https://blog.eleuther.ai/rotary-embeddings/ + Paper: https://arxiv.org/pdf/2104.09864.pdf + Args: + ...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/modules/rotary_positional_embedding.py
Add docstrings with type hints explained
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch import torch.optim from . import LegacyFairseqOptimizer, register_optimizer @register_optimizer("adamax") class FairseqAdamax(...
--- +++ @@ -17,6 +17,7 @@ @staticmethod def add_args(parser): + """Add optimizer-specific arguments to the parser.""" # fmt: off parser.add_argument('--adamax-betas', default='(0.9, 0.999)', metavar='B', help='betas for Adam optimizer') @@ -30,6 +31,12 @@...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/optim/adamax.py
Write docstrings that follow conventions
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import math from typing import Dict, List, Optional, Tuple import torch import torch.nn.functional as F from torch import Tensor, nn from tor...
--- +++ @@ -28,6 +28,14 @@ # TODO: move this into xformers? # TODO: uint8 input type should just output a bool def _mask_for_xformers(mask: Tensor, to_dtype: Optional[torch.dtype] = None): + """ + call to pytorch multihead accepts three mask types: + - ByteTensor where non-zero means to mask + - F...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/modules/multihead_attention.py
Create simple docstrings for beginners
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging from collections import defaultdict from dataclasses import dataclass, field from typing import Dict, Any, List, Optional impo...
--- +++ @@ -182,6 +182,7 @@ yield group def get_lr(self): + """Return the current learning rate.""" k = ( "default" if "default" in self.optimizers @@ -190,9 +191,11 @@ return self.optimizers[k].param_groups[0]["lr"] def state_dict(self): +...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/optim/composite.py
Turn comments into proper docstrings
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import math from typing import Any, Optional import torch import torch.onnx.operators from fairseq import utils from torch import nn, Tensor ...
--- +++ @@ -13,6 +13,10 @@ class SinusoidalPositionalEmbedding(nn.Module): + """This module produces sinusoidal positional embeddings of any length. + + Padding symbols are ignored. + """ def __init__(self, embedding_dim, padding_idx, init_size=1024, auto_expand=True): super().__init__() @@...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/modules/sinusoidal_positional_embedding.py
Generate documentation strings for clarity
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch.optim from . import LegacyFairseqOptimizer, register_optimizer @register_optimizer("adagrad") class Adagrad(LegacyFairseqOptim...
--- +++ @@ -16,6 +16,7 @@ @staticmethod def add_args(parser): + """Add optimizer-specific arguments to the parser.""" # fmt: off parser.add_argument('--weight-decay', '--wd', default=0.0, type=float, metavar='WD', help='weight decay') @@ -23,6 +24,12 @@ ...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/optim/adagrad.py
Add clean documentation to messy code
# Originally from Microsoft Corporation. # Licensed under the MIT License. import math import warnings from typing import List import torch from torch import nn try: from fairseq import ngram_repeat_block_cuda EXTENSION_BUILT = True except ImportError: EXTENSION_BUILT = False def is_cuda_extension_usa...
--- +++ @@ -1,6 +1,7 @@ # Originally from Microsoft Corporation. # Licensed under the MIT License. +""" Wrapper for ngram_repeat_block cuda extension """ import math import warnings from typing import List @@ -17,6 +18,7 @@ def is_cuda_extension_usable() -> bool: + """Check whether ngram_repeat_block_cuda ...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/ngram_repeat_block.py
Add docstrings to meet PEP guidelines
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import math import torch import torch.optim from . import LegacyFairseqOptimizer, register_optimizer @register_optimizer("adafactor") clas...
--- +++ @@ -19,6 +19,7 @@ @staticmethod def add_args(parser): + """Add optimizer-specific arguments to the parser.""" # fmt: off parser.add_argument('--adafactor-eps', default='(1e-30, 1e-3)', metavar="E", help='epsilons for Adafactor optimizer') @@ -41,6...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/optim/adafactor.py
Expand my code with proper documentation strings
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import math from dataclasses import dataclass, field from typing import List from omegaconf import II from fairseq.dataclass import FairseqD...
--- +++ @@ -33,6 +33,10 @@ @register_lr_scheduler("triangular", dataclass=TriangularLRScheduleConfig) class TriangularLRSchedule(FairseqLRScheduler): + """Assign LR based on a triangular cyclical schedule. + + See https://arxiv.org/pdf/1506.01186.pdf for details. + """ def __init__(self, cfg: Triangu...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/optim/lr_scheduler/triangular_lr_scheduler.py
Document my Python code with docstrings
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Optional, Tuple import torch import torch.nn as nn from fairseq.modules import ( FairseqDropout, LayerDropModuleLi...
--- +++ @@ -19,6 +19,18 @@ def init_bert_params(module): + """ + 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 initialize...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/modules/transformer_sentence_encoder.py
Add standardized docstrings across the file
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import math from dataclasses import dataclass, field from typing import Optional, List, Tuple from omegaconf import II from fairseq.dataclass...
--- +++ @@ -49,6 +49,42 @@ @register_lr_scheduler("tri_stage", dataclass=TriStageLRScheduleConfig) class TriStageLRSchedule(FairseqLRScheduler): + """Tristage learning rate schedulr + + Implement the learning rate scheduler in https://arxiv.org/pdf/1904.08779.pdf + + Similar to inverse_squre_root scheduler,...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/optim/lr_scheduler/tri_stage_lr_scheduler.py
Add docstrings to improve readability
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from collections.abc import Collection from dataclasses import dataclass, field from typing import List from omegaconf import II from fairse...
--- +++ @@ -36,6 +36,7 @@ @register_lr_scheduler("step", dataclass=StepLRScheduleConfig) class StepLRSchedule(FairseqLRScheduler): + """Decay learning rate every k updates by a fixed factor""" def __init__(self, cfg: StepLRScheduleConfig, fairseq_optimizer): super().__init__(cfg, fairseq_optimizer...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/optim/lr_scheduler/step_lr_scheduler.py
Generate helpful docstrings for debugging
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from collections.abc import Collection from dataclasses import dataclass, field from typing import List import torch from fairseq.dataclass i...
--- +++ @@ -31,6 +31,12 @@ @property def optimizer_config(self): + """ + Return a kwarg dictionary that will be used to override optimizer + args stored in checkpoints. This allows us to load a checkpoint and + resume training using a different set of optimizer args, e.g., with a ...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/optim/nag.py
Document helper functions with docstrings
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Dict, List, Optional import torch from numpy.random import uniform from torch import Tensor from fairseq.modules import L...
--- +++ @@ -14,6 +14,20 @@ class AugTransformerDecoderLayerBase(TransformerDecoderLayerBase): + """Decoder layer block augmented with an additional cross-attention. + + This decoder block is processed with the sequence of the following sub-modules. + self-attention -> cross-attention (first) -> cross-a...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/modules/transformer_layer_aug.py
Write docstrings that follow conventions
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import math from collections.abc import Collection from dataclasses import dataclass, field from typing import Any, List impor...
--- +++ @@ -43,6 +43,12 @@ @register_optimizer("adam", dataclass=FairseqAdamConfig) class FairseqAdam(FairseqOptimizer): + """Adam optimizer for fairseq. + + Important note: this optimizer corresponds to the "AdamW" variant of + Adam in its weight decay behavior. As such, it is most closely + analogous t...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/optim/adam.py
Generate documentation strings for clarity
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging from fairseq.modules.quantization import pq, quantization_options, scalar from omegaconf import DictConfig logger = logging....
--- +++ @@ -73,6 +73,7 @@ self.size_tracker = pq.SizeTracker(self.trainer.get_model()) def step(self): + """Move to the next stage of quantization.""" if self.quantization_step >= len(self.layers_to_quantize): # Maybe we just finished the last training step or we loaded ...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/quantization_utils.py
Write proper docstrings for these functions
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from collections import defaultdict from itertools import chain import torch from omegaconf import DictConfig from fairseq import optim fro...
--- +++ @@ -78,17 +78,31 @@ return fp32_params def state_dict(self): + """Return the optimizer's state dict.""" state_dict = self.fp32_optimizer.state_dict() if self.scaler is not None: state_dict["loss_scale"] = self.scaler.loss_scale return state_dict ...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/optim/fp16_optimizer.py
Create docstrings for each class method
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Dict, List, Optional import torch import torch.nn as nn from torch import Tensor from fairseq import utils from fairseq.m...
--- +++ @@ -17,6 +17,19 @@ class TransformerEncoderLayerBase(nn.Module): + """Encoder layer block. + + In the original paper each operation (multi-head attention or FFN) is + postprocessed with: `dropout -> add residual -> layernorm`. In the + tensor2tensor code they suggest that learning is more robust...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/modules/transformer_layer.py
Add docstrings including usage examples
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from collections import OrderedDic...
--- +++ @@ -40,6 +40,7 @@ @register_task("audio_classification", dataclass=AudioClassificationConfig) class AudioClassificationTask(AudioPretrainingTask): + """Task for audio classification tasks.""" cfg: AudioClassificationConfig @@ -169,6 +170,8 @@ @property def target_dictionary(self): + ...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/tasks/audio_classification.py
Add concise docstrings to each method
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch from fairseq import utils from fairseq.dataclass.utils import gen_parser_from_dataclass from collections import defaultdict cla...
--- +++ @@ -16,12 +16,14 @@ @classmethod def add_args(cls, parser): + """Add optimizer-specific arguments to the parser.""" dc = getattr(cls, "__dataclass", None) if dc is not None: gen_parser_from_dataclass(parser, dc()) @property def optimizer(self): + ...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/optim/fairseq_optimizer.py
Generate docstrings for each module
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import types import torch def get_fused_adam_class(): try: # The "deprecated" interface in recent versions of apex is a bit ...
--- +++ @@ -9,6 +9,11 @@ def get_fused_adam_class(): + """ + Look for the FusedAdam optimizer from apex. We first try to load the + "contrib" interface, which is a bit faster than the main interface, + but is technically deprecated. + """ try: # The "deprecated" interface in recent vers...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/optim/fused_adam.py
Add docstrings for better understanding
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import math from collections.abc import Collection from dataclasses import dataclass, field from typing import List from omegaconf import II ...
--- +++ @@ -46,6 +46,27 @@ @register_lr_scheduler("cosine", dataclass=CosineLRScheduleConfig) class CosineLRSchedule(FairseqLRScheduler): + """Assign LR based on a cyclical schedule that follows the cosine function. + + See https://arxiv.org/pdf/1608.03983.pdf for details. + + We also support a warmup phase...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/optim/lr_scheduler/cosine_lr_scheduler.py
Add docstrings for production code
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from argparse import Namespace from fairseq.dataclass.utils import gen_parser_from_dataclass from fairseq.optim import FairseqOptimizer cla...
--- +++ @@ -20,20 +20,25 @@ @classmethod def add_args(cls, parser): + """Add arguments to the parser for this LR scheduler.""" dc = getattr(cls, "__dataclass", None) if dc is not None: gen_parser_from_dataclass(parser, dc()) def state_dict(self): + """Retur...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/optim/lr_scheduler/fairseq_lr_scheduler.py
Write docstrings describing functionality
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from dataclasses import dataclass, field from typing import Optional, List from omegaconf import II from fairseq.dataclass import FairseqData...
--- +++ @@ -30,6 +30,7 @@ @register_lr_scheduler("fixed", dataclass=FixedLRScheduleConfig) class FixedLRSchedule(FairseqLRScheduler): + """Decay the LR on a fixed schedule.""" def __init__(self, cfg: FixedLRScheduleConfig, optimizer): super().__init__(cfg, optimizer) @@ -60,14 +61,16 @@ re...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/optim/lr_scheduler/fixed_schedule.py
Generate descriptive docstrings automatically
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import contextlib import logging import os from collections import OrderedDict from argparse import ArgumentError import torch from fairseq i...
--- +++ @@ -32,6 +32,7 @@ def _lang_token_index(dic: Dictionary, lang: str): + """Return language token index.""" idx = dic.index(_lang_token(lang)) assert idx != dic.unk_index, "cannot find language token for lang {}".format(lang) return idx @@ -39,9 +40,33 @@ @register_task("multilingual_trans...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/tasks/multilingual_translation.py
Document this script properly
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch.optim from . import LegacyFairseqOptimizer, register_optimizer @register_optimizer("sgd") class SGD(LegacyFairseqOptimizer): ...
--- +++ @@ -16,6 +16,7 @@ @staticmethod def add_args(parser): + """Add optimizer-specific arguments to the parser.""" # fmt: off parser.add_argument('--momentum', default=0.0, type=float, metavar='M', help='momentum factor') @@ -25,6 +26,12 @@ @prop...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/optim/sgd.py
Write Python docstrings for this snippet
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import os import warnings from argparse import Namespace from typing import Any, Callable, Dict, List import torch from fairse...
--- +++ @@ -48,15 +48,35 @@ class FairseqTask(object): + """ + Tasks store dictionaries and provide helpers for loading/iterating over + Datasets, initializing the Model/Criterion and calculating the loss. + + Tasks have limited statefulness. In particular, state that needs to be + saved to/loaded fr...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/tasks/fairseq_task.py
Generate consistent docstrings
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from . import LegacyFairseqLRScheduler, register_lr_scheduler import logging import ast logger = logging.getLogger(__name__) logger.setLevel(...
--- +++ @@ -13,6 +13,7 @@ @register_lr_scheduler("manual") class ManualSchedule(LegacyFairseqLRScheduler): + """Decay the LR on a manual schedule.""" def __init__(self, args, optimizer): super().__init__(args, optimizer) @@ -53,6 +54,7 @@ @staticmethod def add_args(parser): + """...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/optim/lr_scheduler/manual_lr_scheduler.py
Create docstrings for all classes and functions
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import itertools import logging import os from collections import OrderedDict import numpy as np from fairseq import tokenizer, utils from fa...
--- +++ @@ -22,9 +22,18 @@ @register_task("cross_lingual_lm") class CrossLingualLMTask(LegacyFairseqTask): + """ + Task for training cross-lingual language models. + + For more details look at: https://arxiv.org/pdf/1901.07291.pdf + + Args: + dictionary (Dictionary): the dictionary for the input o...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/tasks/cross_lingual_lm.py
Turn comments into proper docstrings
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import contextlib import json import logging import math import os from argparse import Namespace from collections import OrderedDict, default...
--- +++ @@ -40,6 +40,7 @@ class PiecewiseLinearFn: + """Piecewise linear function. Can be configured with a string.""" def __init__(self, pieces: Sequence[Tuple[int, float]]): assert pieces == sorted( @@ -58,6 +59,14 @@ @staticmethod def from_string(configuration: str) -> "PiecewiseLin...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/tasks/online_backtranslation.py
Insert docstrings into my code
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import logging import os import sy...
--- +++ @@ -101,11 +101,17 @@ @register_task("audio_pretraining", dataclass=AudioPretrainingConfig) class AudioPretrainingTask(FairseqTask): + """ """ cfg: AudioPretrainingConfig @classmethod def setup_task(cls, cfg: AudioPretrainingConfig, **kwargs): + """Setup the task (e.g., load dict...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/tasks/audio_pretraining.py
Write Python docstrings for this snippet
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from collections.abc import Collection from dataclasses import dataclass, field from typing import List from omegaconf import II from fairse...
--- +++ @@ -30,6 +30,23 @@ @register_lr_scheduler("inverse_sqrt", dataclass=InverseSquareRootLRScheduleConfig) class InverseSquareRootSchedule(FairseqLRScheduler): + """Decay the LR based on the inverse square root of the update number. + + We also support a warmup phase where we linearly increase the learning...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/optim/lr_scheduler/inverse_square_root_schedule.py
Write docstrings for data processing functions
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import os import numpy as np from fairseq import utils from fairseq.data import ( ConcatSentencesDataset, Dictionary, ...
--- +++ @@ -31,9 +31,16 @@ @register_task("sentence_ranking") class SentenceRankingTask(LegacyFairseqTask): + """ + Ranking task on multiple sentences. + + Args: + dictionary (Dictionary): the dictionary for the input of the task + """ @staticmethod def add_args(parser): + """Ad...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/tasks/sentence_ranking.py
Help me document legacy Python code
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import os from dataclasses import dataclass, field from typing import Any, Optional import numpy as np from omegaconf import I...
--- +++ @@ -137,6 +137,9 @@ @register_task("denoising", dataclass=DenoisingConfig) class DenoisingTask(FairseqTask): + """ + Denoising task for applying sequence to sequence denoising. (ie. BART) + """ cfg: DenoisingConfig @@ -149,6 +152,7 @@ @classmethod def setup_task(cls, cfg: Denoisi...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/tasks/denoising.py
Add concise docstrings to each method
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import os from dataclasses import dataclass, field from typing import Optional from collections import OrderedDict import nump...
--- +++ @@ -136,6 +136,29 @@ @register_task("speech_dlm_task", dataclass=SpeechDLMConfig) class SpeechDLMTask(LegacyFairseqTask): + """Task for the SpeechDLM model as described in the paper: + https://arxiv.org/pdf/2203.16502.pdf + + It create a multi-channel dataset (SpeechDLMDataset) from multiple + di...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/tasks/speech_dlm_task.py
Write docstrings describing functionality
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import os from dataclasses import dataclass, field from typing import Optional import numpy as np from omegaconf import II, MI...
--- +++ @@ -104,6 +104,9 @@ @register_task("span_masked_lm", dataclass=SpanMaskedLMConfig) class SpanMaskedLMTask(FairseqTask): + """ + Span masked language modeling task. (ie. T5) + """ cfg: SpanMaskedLMConfig @@ -113,6 +116,7 @@ @classmethod def setup_task(cls, cfg: SpanMaskedLMConfig,...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/tasks/span_masked_lm.py
Add missing documentation to my Python functions
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import datetime import logging import time import torch from fairseq.data import ( FairseqDataset, LanguagePairDataset, ListDatas...
--- +++ @@ -38,9 +38,30 @@ @register_task("translation_multi_simple_epoch") class TranslationMultiSimpleEpochTask(LegacyFairseqTask): + """ + Translate from one (source) language to another (target) language. + + Args: + langs (List[str]): a list of languages that are being supported + dicts (...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/tasks/translation_multi_simple_epoch.py
Write Python docstrings for this snippet
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch from fairseq import utils from fairseq.data import LanguagePairDataset from . import register_task from .translation import Tran...
--- +++ @@ -13,9 +13,29 @@ @register_task("translation_from_pretrained_bart") class TranslationFromPretrainedBARTTask(TranslationTask): + """ + Translate from source language to target language with a model initialized with a multilingual pretrain. + + Args: + src_dict (~fairseq.data.Dictionary): dic...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/tasks/translation_from_pretrained_bart.py
Write docstrings describing functionality
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from dataclasses import dataclass, field from typing import Optional, List from omegaconf import II from fairseq.dataclass import FairseqData...
--- +++ @@ -38,6 +38,7 @@ @register_lr_scheduler("polynomial_decay", dataclass=PolynomialDecayLRScheduleConfig) class PolynomialDecayLRSchedule(FairseqLRScheduler): + """Decay the LR on a fixed schedule.""" def __init__(self, cfg: PolynomialDecayLRScheduleConfig, optimizer): super().__init__(cfg, ...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/optim/lr_scheduler/polynomial_decay_schedule.py
Add structured docstrings to improve clarity
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from collections import Counter from typing import List, Optional, Set, Tuple import torch class ConstraintState: def __init__(self): ...
--- +++ @@ -3,6 +3,29 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. +"""Implements tracking of constraints for a beam item. + +A list of constraints is given as a list of one or more token +sequences, each of length at least one token. ...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/token_generation_constraints.py
Write docstrings for this repository
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import unicodedata import sacrebleu as sb from fairseq.dataclass import ChoiceEnum SACREBLEU_V2_ABOVE = int(sb.__version__[0]) >= 2 class...
--- +++ @@ -13,6 +13,18 @@ class EvaluationTokenizer(object): + """A generic evaluation-time tokenizer, which leverages built-in tokenizers + in sacreBLEU (https://github.com/mjpost/sacrebleu). It additionally provides + lowercasing, punctuation removal and character tokenization, which are + applied af...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/scoring/tokenizer.py
Write Python docstrings for this snippet
#!/usr/bin/env python3 -u # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import math import os import sys from argparse import Namespace from typing import Iterable, List, O...
--- +++ @@ -4,6 +4,9 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. +""" +Evaluate the perplexity of a trained language model. +""" import logging import math @@ -43,6 +46,34 @@ remove_bos_token: bool = False, device: Option...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq_cli/eval_lm.py
Create structured documentation for my script
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from dataclasses import dataclass from fairseq.dataclass import FairseqDataclass from fairseq.optim.lr_scheduler import FairseqLRScheduler, r...
--- +++ @@ -16,6 +16,7 @@ @register_lr_scheduler("pass_through", dataclass=PassThroughScheduleConfig) class PassThroughScheduleSchedule(FairseqLRScheduler): + """Delegate lr scheduling to the optimizer.""" def __init__(self, cfg: PassThroughScheduleConfig, optimizer): super().__init__(cfg, optimiz...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/optim/lr_scheduler/pass_through.py
Write Python docstrings for this snippet
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from dataclasses import dataclass, field from typing import List import torch.optim.lr_scheduler from omegaconf import II from fairseq.datac...
--- +++ @@ -56,6 +56,21 @@ "reduce_lr_on_plateau", dataclass=ReduceLROnPlateauLRScheduleConfig ) class ReduceLROnPlateauLRSchedule(FairseqLRScheduler): + """ + Decay the LR by a factor every time the validation loss plateaus. + Also comes with optional warmup phase, where we linearly increase + the le...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/optim/lr_scheduler/reduce_lr_on_plateau.py
Add docstrings to existing functions
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from dataclasses import dataclass from fairseq.data.legacy.masked_lm_dictionary import MaskedLMDictionary from fairseq.tasks.translation impor...
--- +++ @@ -19,7 +19,21 @@ "translation_from_pretrained_xlm", dataclass=TranslationFromPretrainedXLMConfig ) class TranslationFromPretrainedXLMTask(TranslationTask): + """ + Same as TranslationTask except use the MaskedLMDictionary class so that + we can load data that was binarized with the MaskedLMDict...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/tasks/translation_from_pretrained_xlm.py
Write Python docstrings for this snippet
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from dataclasses import dataclass, field import torch from fairseq import utils from fairseq.data import LanguagePairDataset from fairseq.data...
--- +++ @@ -30,10 +30,19 @@ @register_task("translation_lev", dataclass=TranslationLevenshteinConfig) class TranslationLevenshteinTask(TranslationTask): + """ + Translation (Sequence Generation) task for Levenshtein Transformer + See `"Levenshtein Transformer" <https://arxiv.org/abs/1905.11006>`_. + """ ...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/tasks/translation_lev.py
Document all public functions with docstrings
#!/usr/bin/env python3 -u # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import argparse import logging import math import os import sys from typing import Any, Callable, Dict, List, Option...
--- +++ @@ -3,6 +3,9 @@ # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. +""" +Train a new model on one or across multiple GPUs. +""" import argparse import logging @@ -258,6 +261,7 @@ def train( cfg: DictConfig, trainer: Trainer, t...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq_cli/train.py
Turn comments into proper docstrings
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from fairseq.optim import LegacyFairseqOptimizer, register_optimizer @register_optimizer("lamb") class FairseqLAMB(LegacyFairseqOptimizer): ...
--- +++ @@ -8,6 +8,7 @@ @register_optimizer("lamb") class FairseqLAMB(LegacyFairseqOptimizer): + """LAMB optimizer.""" def __init__(self, args, params): super().__init__(args) @@ -20,6 +21,7 @@ @staticmethod def add_args(parser): + """Add optimizer-specific arguments to the parse...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/optim/fused_lamb.py
Create docstrings for API functions
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import math import sys from typing import Dict, List, Optional import torch import torch.nn as nn from torch import Tensor from fairseq impo...
--- +++ @@ -40,6 +40,30 @@ lm_weight=1.0, tokens_to_suppress=(), ): + """Generates translations of a given source sentence. + + Args: + models (List[~fairseq.models.FairseqModel]): ensemble of models, + currently support fairseq.models.TransformerModel for s...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/sequence_generator.py
Create documentation for each function signature
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import os from dataclasses import dataclass, field from typing import Optional import numpy as np import torch from fairseq im...
--- +++ @@ -108,6 +108,33 @@ @register_task("language_modeling", dataclass=LanguageModelingConfig) class LanguageModelingTask(LegacyFairseqTask): + """ + Train a language model. + + Args: + dictionary (~fairseq.data.Dictionary): the dictionary for the input of + the language model + ...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/tasks/language_modeling.py
Write docstrings describing each step
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import math from typing import List, Optional import torch import torch.nn as nn from fairseq.token_generation_constraints import ( Cons...
--- +++ @@ -31,6 +31,31 @@ def step( self, step, lprobs, scores, prev_output_tokens=None, original_batch_idxs=None ): + """Take a single search step. + + Args: + step: the current search step, starting at 0 + lprobs: (bsz x input_beam_size x vocab_size) + ...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/search.py
Add return value explanations in docstrings
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import itertools import logging import os import numpy as np from fairseq import tokenizer, utils from fairseq.data import ConcatDataset, Dic...
--- +++ @@ -21,9 +21,15 @@ @register_task("legacy_masked_lm") class LegacyMaskedLMTask(LegacyFairseqTask): + """ + Task for training Masked LM (BERT) model. + Args: + dictionary (Dictionary): the dictionary for the input of the task + """ @staticmethod def add_args(parser): + ""...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/tasks/legacy_masked_lm.py
Add docstrings to clarify complex logic
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import os from dataclasses import dataclass, field from typing import Optional import numpy as np import torch from omegaconf ...
--- +++ @@ -151,6 +151,33 @@ "multilingual_language_modeling", dataclass=MultilingualLanguageModelingConfig ) class MultilingualLanguageModelingTask(LegacyFairseqTask): + """ + Train a language model. + + Args: + dictionary (~fairseq.data.Dictionary): the dictionary for the input of + t...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/tasks/multilingual_language_modeling.py
Create docstrings for reusable components
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import os import contextlib from dataclasses import dataclass, field from typing import Optional from omegaconf import MISSING...
--- +++ @@ -92,6 +92,12 @@ @register_task("sentence_prediction", dataclass=SentencePredictionConfig) class SentencePredictionTask(FairseqTask): + """ + Sentence (or sentence pair) prediction (classification or regression) task. + + Args: + dictionary (Dictionary): the dictionary for the input of the ...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/tasks/sentence_prediction.py
Add documentation for all methods
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import os from dataclasses import dataclass, field from typing import Optional import numpy as np from omegaconf import II fro...
--- +++ @@ -60,6 +60,7 @@ @classmethod def setup_task(cls, cfg: MultilingualDenoisingConfig, **kwargs): + """Setup the task.""" paths = cfg.data.split(":") assert len(paths) > 0 dictionary = Dictionary.load(os.path.join(paths[0], "dict.txt")) @@ -94,12 +95,21 @@ self...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/tasks/multilingual_denoising.py
Provide clean and structured docstrings
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from dataclasses import dataclass, field import itertools import json import logging import os from typing import Optional from argparse impor...
--- +++ @@ -267,6 +267,18 @@ @register_task("translation", dataclass=TranslationConfig) class TranslationTask(FairseqTask): + """ + Translate from one (source) language to another (target) language. + + Args: + src_dict (~fairseq.data.Dictionary): dictionary for the source language + tgt_dict ...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/tasks/translation.py
Help me comply with documentation standards
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import os from collections import OrderedDict from fairseq import utils from fairseq.data import ( BacktranslationDataset,...
--- +++ @@ -39,6 +39,14 @@ # ported from UnsupervisedMT def parse_lambda_config(x): + """ + 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 + ...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/tasks/semisupervised_translation.py
Add docstrings for internal functions
from pathlib import Path from fastapi import HTTPException from deerflow.config.paths import get_paths def resolve_thread_virtual_path(thread_id: str, virtual_path: str) -> Path: try: return get_paths().resolve_virtual_path(thread_id, virtual_path) except ValueError as e: status = 403 if "t...
--- +++ @@ -1,3 +1,4 @@+"""Shared path resolution for thread virtual paths (e.g. mnt/user-data/outputs/...).""" from pathlib import Path @@ -7,8 +8,21 @@ def resolve_thread_virtual_path(thread_id: str, virtual_path: str) -> Path: + """Resolve a virtual path to the actual filesystem path under thread user-da...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/app/gateway/path_utils.py
Create documentation strings for testing functions
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import os import numpy as np import torch from fairseq import utils from fairseq.data import ( ConcatDataset, Diction...
--- +++ @@ -34,9 +34,11 @@ @register_task("multilingual_masked_lm") class MultiLingualMaskedLMTask(LegacyFairseqTask): + """Task for training masked language models (e.g., BERT, RoBERTa).""" @staticmethod def add_args(parser): + """Add task-specific arguments to the parser.""" parser.a...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/tasks/multilingual_masked_lm.py
Write Python docstrings for this snippet
import logging import re import shutil import yaml from fastapi import APIRouter, HTTPException from pydantic import BaseModel, Field from deerflow.config.agents_config import AgentConfig, list_custom_agents, load_agent_config, load_agent_soul from deerflow.config.paths import get_paths logger = logging.getLogger(_...
--- +++ @@ -1,3 +1,4 @@+"""CRUD API for custom agents.""" import logging import re @@ -17,6 +18,7 @@ class AgentResponse(BaseModel): + """Response model for a custom agent.""" name: str = Field(..., description="Agent name (hyphen-case)") description: str = Field(default="", description="Agent de...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/app/gateway/routers/agents.py
Add structured docstrings to improve clarity
from __future__ import annotations import logging from fastapi import APIRouter, HTTPException from pydantic import BaseModel logger = logging.getLogger(__name__) router = APIRouter(prefix="/api/channels", tags=["channels"]) class ChannelStatusResponse(BaseModel): service_running: bool channels: dict[str...
--- +++ @@ -1,3 +1,4 @@+"""Gateway router for IM channel management.""" from __future__ import annotations @@ -23,6 +24,7 @@ @router.get("/", response_model=ChannelStatusResponse) async def get_channels_status() -> ChannelStatusResponse: + """Get the status of all IM channels.""" from app.channels.servi...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/app/gateway/routers/channels.py
Write docstrings for backend logic
import json import logging import shutil import stat import tempfile import zipfile from pathlib import Path from fastapi import APIRouter, HTTPException from pydantic import BaseModel, Field from app.gateway.path_utils import resolve_thread_virtual_path from deerflow.config.extensions_config import ExtensionsConfig,...
--- +++ @@ -19,6 +19,7 @@ def _is_unsafe_zip_member(info: zipfile.ZipInfo) -> bool: + """Return True if the zip member path is absolute or attempts directory traversal.""" name = info.filename if not name: return False @@ -31,6 +32,7 @@ def _is_symlink_member(info: zipfile.ZipInfo) -> bool...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/app/gateway/routers/skills.py
Document all public functions with docstrings
from fastapi import APIRouter from pydantic import BaseModel, Field from deerflow.agents.memory.updater import get_memory_data, reload_memory_data from deerflow.config.memory_config import get_memory_config router = APIRouter(prefix="/api", tags=["memory"]) class ContextSection(BaseModel): summary: str = Fiel...
--- +++ @@ -1,3 +1,4 @@+"""Memory API router for retrieving and managing global memory data.""" from fastapi import APIRouter from pydantic import BaseModel, Field @@ -9,12 +10,14 @@ class ContextSection(BaseModel): + """Model for context sections (user and history).""" summary: str = Field(default=""...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/app/gateway/routers/memory.py
Document functions with clear intent
import logging from pathlib import Path from fastapi import APIRouter, File, HTTPException, UploadFile from pydantic import BaseModel from deerflow.config.paths import VIRTUAL_PATH_PREFIX, get_paths from deerflow.sandbox.sandbox_provider import get_sandbox_provider from deerflow.utils.file_conversion import CONVERTI...
--- +++ @@ -1,3 +1,4 @@+"""Upload router for handling file uploads.""" import logging from pathlib import Path @@ -15,6 +16,7 @@ class UploadResponse(BaseModel): + """Response model for file upload.""" success: bool files: list[dict[str, str]] @@ -22,6 +24,14 @@ def get_uploads_dir(thread_id:...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/app/gateway/routers/uploads.py
Add docstrings to existing functions
import json import logging from pathlib import Path from typing import Literal from fastapi import APIRouter, HTTPException from pydantic import BaseModel, Field from deerflow.config.extensions_config import ExtensionsConfig, get_extensions_config, reload_extensions_config logger = logging.getLogger(__name__) router...
--- +++ @@ -13,6 +13,7 @@ class McpOAuthConfigResponse(BaseModel): + """OAuth configuration for an MCP server.""" enabled: bool = Field(default=True, description="Whether OAuth token injection is enabled") token_url: str = Field(default="", description="OAuth token endpoint URL") @@ -31,6 +32,7 @@ ...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/app/gateway/routers/mcp.py
Write Python docstrings for this snippet
from fastapi import APIRouter, HTTPException from pydantic import BaseModel, Field from deerflow.config import get_app_config router = APIRouter(prefix="/api", tags=["models"]) class ModelResponse(BaseModel): name: str = Field(..., description="Unique identifier for the model") display_name: str | None = F...
--- +++ @@ -7,6 +7,7 @@ class ModelResponse(BaseModel): + """Response model for model information.""" name: str = Field(..., description="Unique identifier for the model") display_name: str | None = Field(None, description="Human-readable name") @@ -16,6 +17,7 @@ class ModelsListResponse(BaseMode...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/app/gateway/routers/models.py
Generate docstrings for each module
import logging import mimetypes import zipfile from pathlib import Path from urllib.parse import quote from fastapi import APIRouter, HTTPException, Request from fastapi.responses import FileResponse, HTMLResponse, PlainTextResponse, Response from app.gateway.path_utils import resolve_thread_virtual_path logger = lo...
--- +++ @@ -15,6 +15,7 @@ def is_text_file_by_content(path: Path, sample_size: int = 8192) -> bool: + """Check if file is text by examining content for null bytes.""" try: with open(path, "rb") as f: chunk = f.read(sample_size) @@ -25,6 +26,15 @@ def _extract_file_from_skill_archiv...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/app/gateway/routers/artifacts.py
Help me document legacy Python code
from __future__ import annotations import contextlib import logging from collections.abc import AsyncIterator from langgraph.types import Checkpointer from deerflow.agents.checkpointer.provider import ( POSTGRES_CONN_REQUIRED, POSTGRES_INSTALL, SQLITE_INSTALL, _resolve_sqlite_conn_str, ) from deerfl...
--- +++ @@ -1,3 +1,19 @@+"""Async checkpointer factory. + +Provides an **async context manager** for long-running async servers that need +proper resource cleanup. + +Supported backends: memory, sqlite, postgres. + +Usage (e.g. FastAPI lifespan):: + + from deerflow.agents.checkpointer.async_provider import make_chec...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/agents/checkpointer/async_provider.py
Add docstrings to clarify complex logic
from datetime import datetime from deerflow.config.agents_config import load_agent_soul from deerflow.skills import load_skills def _build_subagent_section(max_concurrent: int) -> str: n = max_concurrent return f"""<subagent_system> **🚀 SUBAGENT MODE ACTIVE - DECOMPOSE, DELEGATE, SYNTHESIZE** You are runni...
--- +++ @@ -5,6 +5,14 @@ def _build_subagent_section(max_concurrent: int) -> str: + """Build the subagent system prompt section with dynamic concurrency limit. + + Args: + max_concurrent: Maximum number of concurrent subagent calls allowed per response. + + Returns: + Formatted subagent secti...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/agents/lead_agent/prompt.py
Generate docstrings for script automation
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import os import os.path as op import torch import torch.nn.functional as F import numpy as np from fairseq.data.audio.text_t...
--- +++ @@ -328,6 +328,19 @@ def antidiag_indices(offset, min_i=0, max_i=None, min_j=0, max_j=None): + """ + for a (3, 4) matrix with min_i=1, max_i=3, min_j=1, max_j=4, outputs + + offset=2 (1, 1), + offset=3 (2, 1), (1, 2) + offset=4 (2, 2), (1, 3) + offset=5 (2, 3) + + constraints: + ...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/tasks/text_to_speech.py
Add docstrings including usage examples
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import contextlib import logging import os import sys import time from argparse import Namespace from itertools import chain from typing impo...
--- +++ @@ -3,6 +3,9 @@ # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. +""" +Train a network across multiple GPUs. +""" import contextlib import logging @@ -31,6 +34,14 @@ class Trainer(object): + """Main class for data parallel ...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/trainer.py
Add docstrings for utility scripts
from collections.abc import Callable from typing import override from langchain.agents import AgentState from langchain.agents.middleware import AgentMiddleware from langchain_core.messages import ToolMessage from langgraph.graph import END from langgraph.prebuilt.tool_node import ToolCallRequest from langgraph.types...
--- +++ @@ -1,3 +1,4 @@+"""Middleware for intercepting clarification requests and presenting them to the user.""" from collections.abc import Callable from typing import override @@ -11,18 +12,46 @@ class ClarificationMiddlewareState(AgentState): + """Compatible with the `ThreadState` schema.""" pass ...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/agents/middlewares/clarification_middleware.py
Document my Python code with docstrings
import logging from langchain.agents import create_agent from langchain.agents.middleware import SummarizationMiddleware from langchain_core.runnables import RunnableConfig from deerflow.agents.lead_agent.prompt import apply_prompt_template from deerflow.agents.middlewares.clarification_middleware import Clarificatio...
--- +++ @@ -23,6 +23,7 @@ def _resolve_model_name(requested_model_name: str | None = None) -> str: + """Resolve a runtime model name safely, falling back to default if invalid. Returns None if no models are configured.""" app_config = get_app_config() default_model_name = app_config.models[0].name if a...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/agents/lead_agent/agent.py
Help me add docstrings to my project
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import argparse import collections import contextlib import copy import importlib import logging import os import sys import warnings from ite...
--- +++ @@ -143,6 +143,7 @@ incremental_state: Optional[Dict[str, Dict[str, Optional[Tensor]]]], key: str, ) -> Optional[Dict[str, Optional[Tensor]]]: + """Helper for getting incremental state for an nn.Module.""" return module.get_incremental_state(incremental_state, key) @@ -152,6 +153,7 @@ ...
https://raw.githubusercontent.com/facebookresearch/fairseq/HEAD/fairseq/utils.py
Replace inline comments with docstrings
import json import re import uuid from datetime import datetime from pathlib import Path from typing import Any from deerflow.agents.memory.prompt import ( MEMORY_UPDATE_PROMPT, format_conversation_for_update, ) from deerflow.config.memory_config import get_memory_config from deerflow.config.paths import get_...
--- +++ @@ -1,3 +1,4 @@+"""Memory updater for reading, writing, and updating memory data.""" import json import re @@ -16,6 +17,15 @@ def _get_memory_file_path(agent_name: str | None = None) -> Path: + """Get the path to the memory file. + + Args: + agent_name: If provided, returns the per-agent me...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/agents/memory/updater.py
Auto-generate documentation strings for this file
import logging from collections.abc import Awaitable, Callable from typing import override from langchain.agents import AgentState from langchain.agents.middleware import AgentMiddleware from langchain.agents.middleware.types import ModelCallResult, ModelRequest, ModelResponse logger = logging.getLogger(__name__) ...
--- +++ @@ -1,3 +1,13 @@+"""Middleware to filter deferred tool schemas from model binding. + +When tool_search is enabled, MCP tools are registered in the DeferredToolRegistry +and passed to ToolNode for execution, but their schemas should NOT be sent to the +LLM via bind_tools (that's the whole point of deferral — sav...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/agents/middlewares/deferred_tool_filter_middleware.py
Add docstrings with type hints explained
import logging from typing import override from langchain.agents import AgentState from langchain.agents.middleware import AgentMiddleware from langgraph.runtime import Runtime from deerflow.subagents.executor import MAX_CONCURRENT_SUBAGENTS logger = logging.getLogger(__name__) # Valid range for max_concurrent_sub...
--- +++ @@ -1,3 +1,4 @@+"""Middleware to enforce maximum concurrent subagent tool calls per model response.""" import logging from typing import override @@ -16,10 +17,21 @@ def _clamp_subagent_limit(value: int) -> int: + """Clamp subagent limit to valid range [2, 4].""" return max(MIN_SUBAGENT_LIMIT, m...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/agents/middlewares/subagent_limit_middleware.py
Fill in missing docstrings in my code
import logging from collections.abc import Awaitable, Callable from typing import override from langchain.agents import AgentState from langchain.agents.middleware import AgentMiddleware from langchain.agents.middleware.types import ModelCallResult, ModelRequest, ModelResponse from langchain_core.messages import Tool...
--- +++ @@ -1,3 +1,17 @@+"""Middleware to fix dangling tool calls in message history. + +A dangling tool call occurs when an AIMessage contains tool_calls but there are +no corresponding ToolMessages in the history (e.g., due to user interruption or +request cancellation). This causes LLM errors due to incomplete messa...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/agents/middlewares/dangling_tool_call_middleware.py
Create simple docstrings for beginners
import hashlib import json import logging import threading from collections import OrderedDict, defaultdict from typing import override from langchain.agents import AgentState from langchain.agents.middleware import AgentMiddleware from langchain_core.messages import SystemMessage from langgraph.runtime import Runtim...
--- +++ @@ -1,3 +1,16 @@+"""Middleware to detect and break repetitive tool call loops. + +P0 safety: prevents the agent from calling the same tool with the same +arguments indefinitely until the recursion limit kills the run. + +Detection strategy: + 1. After each model response, hash the tool calls (name + args). + ...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/agents/middlewares/loop_detection_middleware.py
Add docstrings to incomplete code
import re from typing import Any, override from langchain.agents import AgentState from langchain.agents.middleware import AgentMiddleware from langgraph.runtime import Runtime from deerflow.agents.memory.queue import get_memory_queue from deerflow.config.memory_config import get_memory_config class MemoryMiddlewa...
--- +++ @@ -1,3 +1,4 @@+"""Middleware for memory mechanism.""" import re from typing import Any, override @@ -11,11 +12,34 @@ class MemoryMiddlewareState(AgentState): + """Compatible with the `ThreadState` schema.""" pass def _filter_messages_for_memory(messages: list[Any]) -> list[Any]: + """...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/agents/middlewares/memory_middleware.py
Create simple docstrings for beginners
from __future__ import annotations import asyncio import json import logging import threading from typing import Any from app.channels.base import Channel from app.channels.message_bus import InboundMessageType, MessageBus, OutboundMessage, ResolvedAttachment logger = logging.getLogger(__name__) class FeishuChann...
--- +++ @@ -1,3 +1,4 @@+"""Feishu/Lark channel — connects to Feishu via WebSocket (no public IP needed).""" from __future__ import annotations @@ -14,6 +15,22 @@ class FeishuChannel(Channel): + """Feishu/Lark IM channel using the ``lark-oapi`` WebSocket client. + + Configuration keys (in ``config.yaml`` ...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/app/channels/feishu.py
Add docstrings to my Python code
from __future__ import annotations import logging from abc import ABC, abstractmethod from typing import Any from app.channels.message_bus import InboundMessage, InboundMessageType, MessageBus, OutboundMessage, ResolvedAttachment logger = logging.getLogger(__name__) class Channel(ABC): def __init__(self, nam...
--- +++ @@ -1,3 +1,4 @@+"""Abstract base class for IM channels.""" from __future__ import annotations @@ -11,6 +12,14 @@ class Channel(ABC): + """Base class for all IM channel implementations. + + Each channel connects to an external messaging platform and: + 1. Receives messages, wraps them as Inboun...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/app/channels/base.py
Document helper functions with docstrings
from __future__ import annotations import logging import time from abc import ABC, abstractmethod import requests from .sandbox_info import SandboxInfo logger = logging.getLogger(__name__) def wait_for_sandbox_ready(sandbox_url: str, timeout: int = 30) -> bool: start_time = time.time() while time.time() ...
--- +++ @@ -1,3 +1,4 @@+"""Abstract base class for sandbox provisioning backends.""" from __future__ import annotations @@ -13,6 +14,15 @@ def wait_for_sandbox_ready(sandbox_url: str, timeout: int = 30) -> bool: + """Poll sandbox health endpoint until ready or timeout. + + Args: + sandbox_url: URL...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/community/aio_sandbox/backend.py
Create documentation strings for testing functions
from __future__ import annotations import logging import requests from .backend import SandboxBackend from .sandbox_info import SandboxInfo logger = logging.getLogger(__name__) class RemoteSandboxBackend(SandboxBackend): def __init__(self, provisioner_url: str): self._provisioner_url = provisioner_u...
--- +++ @@ -1,3 +1,19 @@+"""Remote sandbox backend — delegates Pod lifecycle to the provisioner service. + +The provisioner dynamically creates per-sandbox-id Pods + NodePort Services +in k3s. The backend accesses sandbox pods directly via ``k3s:{NodePort}``. + +Architecture: + ┌────────────┐ HTTP ┌─────────────...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/community/aio_sandbox/remote_backend.py
Generate docstrings with examples
from __future__ import annotations import asyncio import logging from typing import Any from markdown_to_mrkdwn import SlackMarkdownConverter from app.channels.base import Channel from app.channels.message_bus import InboundMessageType, MessageBus, OutboundMessage, ResolvedAttachment logger = logging.getLogger(__n...
--- +++ @@ -1,3 +1,4 @@+"""Slack channel — connects via Socket Mode (no public IP needed).""" from __future__ import annotations @@ -16,6 +17,13 @@ class SlackChannel(Channel): + """Slack IM channel using Socket Mode (WebSocket, no public IP). + + Configuration keys (in ``config.yaml`` under ``channels.s...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/app/channels/slack.py
Add docstrings to improve collaboration
import atexit import fcntl import hashlib import logging import os import signal import threading import time import uuid from deerflow.config import get_app_config from deerflow.config.paths import VIRTUAL_PATH_PREFIX, Paths, get_paths from deerflow.sandbox.sandbox import Sandbox from deerflow.sandbox.sandbox_provid...
--- +++ @@ -1,3 +1,14 @@+"""AIO Sandbox Provider — orchestrates sandbox lifecycle with pluggable backends. + +This provider composes: +- SandboxBackend: how sandboxes are provisioned (local container vs remote/K8s) + +The provider itself handles: +- In-process caching for fast repeated access +- Idle timeout management...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/community/aio_sandbox/aio_sandbox_provider.py
Write reusable docstrings
from __future__ import annotations import asyncio import logging import time from collections.abc import Callable, Coroutine from dataclasses import dataclass, field from enum import StrEnum from pathlib import Path from typing import Any logger = logging.getLogger(__name__) # -------------------------------------...
--- +++ @@ -1,3 +1,4 @@+"""MessageBus — async pub/sub hub that decouples channels from the agent dispatcher.""" from __future__ import annotations @@ -19,6 +20,7 @@ class InboundMessageType(StrEnum): + """Types of messages arriving from IM channels.""" CHAT = "chat" COMMAND = "command" @@ -26,6 ...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/app/channels/message_bus.py
Generate docstrings for exported functions
from __future__ import annotations import logging import os import subprocess from deerflow.utils.network import get_free_port, release_port from .backend import SandboxBackend, wait_for_sandbox_ready from .sandbox_info import SandboxInfo logger = logging.getLogger(__name__) class LocalContainerBackend(SandboxBa...
--- +++ @@ -1,3 +1,8 @@+"""Local container backend for sandbox provisioning. + +Manages sandbox containers using Docker or Apple Container on the local machine. +Handles container lifecycle, port allocation, and cross-process container discovery. +""" from __future__ import annotations @@ -14,6 +19,17 @@ class...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/community/aio_sandbox/local_backend.py
Document helper functions with docstrings
import asyncio import json import logging import mimetypes import os import re import shutil import tempfile import uuid import zipfile from collections.abc import Generator from dataclasses import dataclass, field from pathlib import Path from typing import Any from langchain.agents import create_agent from langchai...
--- +++ @@ -1,3 +1,19 @@+"""DeerFlowClient — Embedded Python client for DeerFlow agent system. + +Provides direct programmatic access to DeerFlow's agent capabilities +without requiring LangGraph Server or Gateway API processes. + +Usage: + from deerflow.client import DeerFlowClient + + client = DeerFlowClient() ...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/client.py
Create docstrings for all classes and functions
from __future__ import annotations import asyncio import logging import mimetypes import time from collections.abc import Mapping from typing import Any from app.channels.message_bus import InboundMessage, InboundMessageType, MessageBus, OutboundMessage, ResolvedAttachment from app.channels.store import ChannelStore...
--- +++ @@ -1,3 +1,4 @@+"""ChannelManager — consumes inbound messages and dispatches them to the DeerFlow agent via LangGraph Server.""" from __future__ import annotations @@ -39,6 +40,16 @@ def _extract_response_text(result: dict | list) -> str: + """Extract the last AI message text from a LangGraph runs.w...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/app/channels/manager.py
Write docstrings for utility functions
import base64 import logging from agent_sandbox import Sandbox as AioSandboxClient from deerflow.sandbox.sandbox import Sandbox logger = logging.getLogger(__name__) class AioSandbox(Sandbox): def __init__(self, id: str, base_url: str, home_dir: str | None = None): super().__init__(id) self._ba...
--- +++ @@ -9,8 +9,19 @@ class AioSandbox(Sandbox): + """Sandbox implementation using the agent-infra/sandbox Docker container. + + This sandbox connects to a running AIO sandbox container via HTTP API. + """ def __init__(self, id: str, base_url: str, home_dir: str | None = None): + """Initia...
https://raw.githubusercontent.com/bytedance/deer-flow/HEAD/backend/packages/harness/deerflow/community/aio_sandbox/aio_sandbox.py