instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Add well-formatted docstrings
# vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) import sys import re from powerline.lib.shell import asrun, run_cmd from powerline.lib.unicode import out_u from powerline.segments import Segment, with_docstring STATE_SYMBOLS = { 'fallback': '', 'p...
--- +++ @@ -18,6 +18,7 @@ def _convert_state(state): + '''Guess player state''' state = state.lower() if 'play' in state: return 'play' @@ -29,6 +30,7 @@ def _convert_seconds(seconds): + '''Convert seconds to minutes:seconds format''' if isinstance(seconds, str): seconds = seconds.replace(","...
https://raw.githubusercontent.com/powerline/powerline/HEAD/powerline/segments/common/players.py
Improve documentation using docstrings
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import logging import math import os import cv2 import types from copy import deepcopy from functools import partial from einops import rearrange import numpy as np import torch import torch.distributed as dist from peft import set_peft_model_sta...
--- +++ @@ -49,6 +49,34 @@ convert_model_dtype=False, use_relighting_lora=False ): + r""" + Initializes the generation model components. + + Args: + config (EasyDict): + Object containing model parameters initialized from config.py + checkp...
https://raw.githubusercontent.com/Wan-Video/Wan2.2/HEAD/wan/animate.py
Generate docstrings for exported functions
# vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) import re from powerline.theme import requires_segment_info from powerline.bindings.wm import get_i3_connection WORKSPACE_REGEX = re.compile(r'^[0-9]+: ?') def workspace_groups(w): group = [] if w.fo...
--- +++ @@ -66,6 +66,47 @@ def workspaces(pl, segment_info, only_show=None, output=None, strip=0, format='{name}', icons=WS_ICONS, sort_workspaces=False, show_output=False, priority_workspaces=[], hide_empty_workspaces=False): + '''Return list of used workspaces + + :param list only_show: + Specifies which workspa...
https://raw.githubusercontent.com/powerline/powerline/HEAD/powerline/segments/i3wm.py
Generate missing documentation strings
# vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) import os from powerline.theme import requires_segment_info @requires_segment_info def current_line(pl, segment_info): return str(segment_info['curframe'].f_lineno) @requires_segment_info def curren...
--- +++ @@ -8,11 +8,18 @@ @requires_segment_info def current_line(pl, segment_info): + '''Displays line number that is next to be run + ''' return str(segment_info['curframe'].f_lineno) @requires_segment_info def current_file(pl, segment_info, basename=True): + '''Displays current file name + + :param bool b...
https://raw.githubusercontent.com/powerline/powerline/HEAD/powerline/segments/pdb.py
Add clean documentation to messy code
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import math import types from copy import deepcopy from einops import rearrange from typing import List import numpy as np import torch import torch.cuda.amp as amp import torch.nn as nn from diffusers.configuration_utils import ConfigMixin, regi...
--- +++ @@ -39,6 +39,11 @@ class HeadAnimate(Head): def forward(self, x, e): + """ + Args: + x(Tensor): Shape [B, L1, C] + e(Tensor): Shape [B, L1, C] + """ assert e.dtype == torch.float32 with amp.autocast(dtype=torch.float32): e = (self....
https://raw.githubusercontent.com/Wan-Video/Wan2.2/HEAD/wan/modules/animate/model_animate.py
Document functions with clear intent
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import os import cv2 import time import math import matplotlib import matplotlib.pyplot as plt import numpy as np from typing import Dict, List import random from pose2d_utils import AAPoseMeta def draw_handpose(canvas, keypoints, hand_score_th=...
--- +++ @@ -12,6 +12,20 @@ def draw_handpose(canvas, keypoints, hand_score_th=0.6): + """ + Draw keypoints and connections representing hand pose on a given canvas. + + Args: + canvas (np.ndarray): A 3D numpy array representing the canvas (image) on which to draw the hand pose. + keypoints (L...
https://raw.githubusercontent.com/Wan-Video/Wan2.2/HEAD/wan/modules/animate/preprocess/human_visualization.py
Write docstrings for algorithm functions
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import torch import torch.cuda.amp as amp from ..modules.model import sinusoidal_embedding_1d from .ulysses import distributed_attention from .util import gather_forward, get_rank, get_world_size def pad_freqs(original_tensor, target_len): ...
--- +++ @@ -22,6 +22,11 @@ @torch.amp.autocast('cuda', enabled=False) def rope_apply(x, grid_sizes, freqs): + """ + x: [B, L, N, C]. + grid_sizes: [B, 3]. + freqs: [M, C // 2]. + """ s, n, c = x.size(1), x.size(2), x.size(3) // 2 # split freqs freqs = freqs.split([c - 2 * ...
https://raw.githubusercontent.com/Wan-Video/Wan2.2/HEAD/wan/distributed/sequence_parallel.py
Add docstrings explaining edge cases
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import torch import torch.distributed as dist def init_distributed_group(): if not dist.is_initialized(): dist.init_process_group(backend='nccl') def get_rank(): return dist.get_rank() def get_world_size(): return dist.ge...
--- +++ @@ -4,6 +4,8 @@ def init_distributed_group(): + """r initialize sequence parallel group. + """ if not dist.is_initialized(): dist.init_process_group(backend='nccl') @@ -17,6 +19,9 @@ def all_to_all(x, scatter_dim, gather_dim, group=None, **kwargs): + """ + `scatter` along one...
https://raw.githubusercontent.com/Wan-Video/Wan2.2/HEAD/wan/distributed/util.py
Add structured docstrings to improve clarity
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import argparse import binascii import logging import os import os.path as osp import shutil import subprocess import imageio import torch import torchvision __all__ = ['save_video', 'save_image', 'str2bool'] def rand_name(length=8, suffix='')...
--- +++ @@ -24,6 +24,14 @@ def merge_video_audio(video_path: str, audio_path: str): + """ + Merge the video and audio into a new video, with the duration set to the shorter of the two, + and overwrite the original video file. + + Parameters: + video_path (str): Path to the original video file + au...
https://raw.githubusercontent.com/Wan-Video/Wan2.2/HEAD/wan/utils/utils.py
Add docstrings including usage examples
# vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) import os import re import csv import sys from collections import defaultdict try: import vim except ImportError: vim = object() from powerline.bindings.vim import (vim_get_func, getbufvar, vim_getbu...
--- +++ @@ -90,6 +90,15 @@ @requires_segment_info def mode(pl, segment_info, override=None): + '''Return the current vim mode. + + If mode (returned by ``mode()`` VimL function, see ``:h mode()`` in Vim) + consists of multiple characters and necessary mode is not known to powerline + then it will fall back to mode w...
https://raw.githubusercontent.com/powerline/powerline/HEAD/powerline/segments/vim/__init__.py
Create documentation strings for testing functions
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import math import types from copy import deepcopy import numpy as np import torch import torch.cuda.amp as amp import torch.nn as nn from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.models.modeling_utils i...
--- +++ @@ -33,6 +33,9 @@ def zero_module(module): + """ + Zero out the parameters of a module and return it. + """ for p in module.parameters(): p.detach().zero_() return module @@ -132,6 +135,11 @@ class Head_S2V(Head): def forward(self, x, e): + """ + Args: + ...
https://raw.githubusercontent.com/Wan-Video/Wan2.2/HEAD/wan/modules/s2v/model_s2v.py
Expand my code with proper documentation strings
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import math import torch import torch.nn as nn from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.models.modeling_utils import ModelMixin from .attention import flash_attention __all__ = ['WanModel'] def ...
--- +++ @@ -75,6 +75,10 @@ self.weight = nn.Parameter(torch.ones(dim)) def forward(self, x): + r""" + Args: + x(Tensor): Shape [B, L, C] + """ return self._norm(x.float()).type_as(x) * self.weight def _norm(self, x): @@ -87,6 +91,10 @@ super().__ini...
https://raw.githubusercontent.com/Wan-Video/Wan2.2/HEAD/wan/modules/model.py
Add minimal docstrings for each function
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import logging import torch import torch.cuda.amp as amp import torch.nn as nn import torch.nn.functional as F from einops import rearrange __all__ = [ "Wan2_2_VAE", ] CACHE_T = 2 class CausalConv3d(nn.Conv3d): def __init__(self, *ar...
--- +++ @@ -15,6 +15,9 @@ class CausalConv3d(nn.Conv3d): + """ + Causal 3d convolusion. + """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -59,6 +62,9 @@ class Upsample(nn.Upsample): def forward(self, x): + """ + Fix bfloat16 support for nea...
https://raw.githubusercontent.com/Wan-Video/Wan2.2/HEAD/wan/modules/vae2_2.py
Create docstrings for each class method
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. from torch import nn import torch from typing import Tuple, Optional from einops import rearrange import torch.nn.functional as F import math from ...distributed.util import gather_forward, get_rank, get_world_size try: from flash_attn impor...
--- +++ @@ -40,6 +40,28 @@ max_seqlen_q=None, batch_size=1, ): + """ + Perform QKV self attention. + + Args: + q (torch.Tensor): Query tensor with shape [b, s, a, d], where a is the number of heads. + k (torch.Tensor): Key tensor with shape [b, s1, a, d] + v (torch.Tensor): Value...
https://raw.githubusercontent.com/Wan-Video/Wan2.2/HEAD/wan/modules/animate/face_blocks.py
Annotate my code with docstrings
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import gc import logging import math import os import random import sys import types from contextlib import contextmanager from functools import partial import numpy as np import torch import torch.cuda.amp as amp import torch.distributed as dist...
--- +++ @@ -45,6 +45,32 @@ init_on_cpu=True, convert_model_dtype=False, ): + r""" + Initializes the image-to-video generation model components. + + Args: + config (EasyDict): + Object containing model parameters initialized from config.py + ...
https://raw.githubusercontent.com/Wan-Video/Wan2.2/HEAD/wan/image2video.py
Create Google-style docstrings for my code
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import gc import logging import math import os import random import sys import types from contextlib import contextmanager from functools import partial import torch import torch.cuda.amp as amp import torch.distributed as dist from tqdm import t...
--- +++ @@ -43,6 +43,32 @@ init_on_cpu=True, convert_model_dtype=False, ): + r""" + Initializes the Wan text-to-video generation model components. + + Args: + config (EasyDict): + Object containing model parameters initialized from config.py + ...
https://raw.githubusercontent.com/Wan-Video/Wan2.2/HEAD/wan/text2video.py
Write docstrings for data processing functions
# Copyright (c) 2025. Your modifications here. # This file wraps and extends sam2.utils.misc for custom modifications. from sam2.utils import misc as sam2_misc from sam2.utils.misc import * from PIL import Image import numpy as np import torch from tqdm import tqdm import os import logging import torch from hydra i...
--- +++ @@ -40,6 +40,14 @@ async_loading_frames=False, frame_names=None, ): + """ + Load the video frames from a directory of JPEG files ("<frame_index>.jpg" format). + + The frames are resized to image_size x image_size and are loaded to GPU if + `offload_video_to_cpu` is `False` and to CPU if `o...
https://raw.githubusercontent.com/Wan-Video/Wan2.2/HEAD/wan/modules/animate/preprocess/sam_utils.py
Generate docstrings for exported functions
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import warnings import cv2 import numpy as np from typing import List from PIL import Image def box_convert_simple(box, convert_type='xyxy2xywh'): if convert_type == 'xyxy2xywh': return [box[0], box[1], box[2] - box[0], box[3] - box[...
--- +++ @@ -168,6 +168,16 @@ @staticmethod def load_from_kp2ds(kp2ds: List[np.ndarray], width: int, height: int): + """input 133x3 numpy keypoints and output AAPoseMeta + + Args: + kp2ds (List[np.ndarray]): _description_ + width (int): _description_ + height (i...
https://raw.githubusercontent.com/Wan-Video/Wan2.2/HEAD/wan/modules/animate/preprocess/pose2d_utils.py
Create docstrings for reusable components
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import logging import torch import torch.cuda.amp as amp import torch.nn as nn import torch.nn.functional as F from einops import rearrange __all__ = [ 'Wan2_1_VAE', ] CACHE_T = 2 class CausalConv3d(nn.Conv3d): def __init__(self, *ar...
--- +++ @@ -15,6 +15,9 @@ class CausalConv3d(nn.Conv3d): + """ + Causal 3d convolusion. + """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -54,6 +57,9 @@ class Upsample(nn.Upsample): def forward(self, x): + """ + Fix bfloat16 support for nea...
https://raw.githubusercontent.com/Wan-Video/Wan2.2/HEAD/wan/modules/vae2_1.py
Write docstrings for backend logic
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import gc import logging import math import os import random import sys import types from contextlib import contextmanager from copy import deepcopy from functools import partial import numpy as np import torch import torch.cuda.amp as amp import...
--- +++ @@ -59,6 +59,32 @@ init_on_cpu=True, convert_model_dtype=False, ): + r""" + Initializes the image-to-video generation model components. + + Args: + config (EasyDict): + Object containing model parameters initialized from config.py + ...
https://raw.githubusercontent.com/Wan-Video/Wan2.2/HEAD/wan/speech2video.py
Help me add docstrings to my project
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import os import cv2 from typing import Union, List import numpy as np import torch import onnxruntime from pose2d_utils import ( read_img, box_convert_simple, bbox_from_detector, crop, keypoints_from_heatmaps, load_pose_...
--- +++ @@ -87,6 +87,12 @@ def preprocess(self, input_image): + """ + Preprocesses the input image before performing inference. + + Returns: + image_data: Preprocessed image data ready for inference. + """ img = read_img(input_image) # Get...
https://raw.githubusercontent.com/Wan-Video/Wan2.2/HEAD/wan/modules/animate/preprocess/pose2d.py
Document my Python code with docstrings
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import gc import logging import math import os import random import sys import types from contextlib import contextmanager from functools import partial import torch import torch.cuda.amp as amp import torch.distributed as dist import torchvision...
--- +++ @@ -46,6 +46,32 @@ init_on_cpu=True, convert_model_dtype=False, ): + r""" + Initializes the Wan text-to-video generation model components. + + Args: + config (EasyDict): + Object containing model parameters initialized from config.py + ...
https://raw.githubusercontent.com/Wan-Video/Wan2.2/HEAD/wan/textimage2video.py
Write docstrings describing each step
# Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. import json import logging import math import os import random import sys import tempfile from dataclasses import dataclass from http import HTTPStatus from typing import Optional, Union import dashscope import torch from PIL import Image try: ...
--- +++ @@ -124,6 +124,16 @@ retry_times=4, is_vl=False, **kwargs): + ''' + Args: + api_key: The API key for Dash Scope authentication and access to related services. + model_name: Model name, 'qwen-plus' for extending prompts, 'qw...
https://raw.githubusercontent.com/Wan-Video/Wan2.2/HEAD/wan/utils/prompt_extend.py
Generate consistent documentation across files
# Copied from https://github.com/kq-chen/qwen-vl-utils # Copyright 2024-2025 The Alibaba Wan Team Authors. All rights reserved. from __future__ import annotations import base64 import logging import math import os import sys import time import warnings from functools import lru_cache from io import BytesIO import req...
--- +++ @@ -37,14 +37,17 @@ def round_by_factor(number: int, factor: int) -> int: + """Returns the closest integer to 'number' that is divisible by 'factor'.""" return round(number / factor) * factor def ceil_by_factor(number: int, factor: int) -> int: + """Returns the smallest integer greater than ...
https://raw.githubusercontent.com/Wan-Video/Wan2.2/HEAD/wan/utils/qwen_vl_utils.py
Add docstrings explaining edge cases
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import division import numpy as np import matplotlib.pyplot as plt from bs4 import BeautifulSoup import requests import csv def load_data(): with open('gans.tsv') as fid: reader = csv.DictReader(fid, delimiter='\t') ga...
--- +++ @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +""" Update Readme.md and cumulative_gans.jpg """ from __future__ import print_function from __future__ import division @@ -10,6 +11,7 @@ def load_data(): + """ Load GANs data from the gans.csv file """ with open('gans.tsv') as fid: reader = csv...
https://raw.githubusercontent.com/hindupuravinash/the-gan-zoo/HEAD/update.py
Document this module using docstrings
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
--- +++ @@ -122,6 +122,23 @@ # 2. DistributedTrainer performs allreduce(summation) and average # while Trainer only performs allreduce(summation). class DistributedTrainer(mx.gluon.Trainer): + """The distributed trainer for data parallel training. + + Arguments: + params: dict of parameters to train +...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/mxnet/__init__.py
Help me write clear docstrings
# Copyright IBM Corp. 2020. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
--- +++ @@ -25,10 +25,25 @@ def is_jsrun_installed(): + """Returns True if jsrun is installed.""" return find_executable('jsrun') is not None def js_run(settings, nics, env, command, stdout=None, stderr=None): + """ + Runs Horovod with jsrun. + + Args: + settings: Settings for running j...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/runner/js_run.py
Write docstrings including parameters and return values
# Copyright 2018 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -12,31 +12,40 @@ # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== +"""Gradient compression algorithms.""" class Compressor(object): + """Interface for compressing a...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/mxnet/compression.py
Document this module using docstrings
# Copyright (C) 2022, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
--- +++ @@ -16,6 +16,7 @@ class DataModule(ABC): + """Context manager base class for data module/loader implementations.""" short_name = None # implementations should provide a short name for easy reference, e.g. 'petastorm', 'nvtabular', etc. def __init__(self, train_dir: str, val_dir: str, num_...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/spark/common/datamodule.py
Include argument descriptions in docstrings
from typing import Dict, List import socket import ray import os from horovod.ray import ray_logger class BaseHorovodWorker: executable = None def __init__(self, world_rank=0, world_size=1): os.environ["HOROVOD_HOSTNAME"] = self.node_id() os.environ["HOROVOD_RANK"] = str(world_rank) o...
--- +++ @@ -22,19 +22,34 @@ return socket.gethostname() def get_gpu_ids(self) -> List[int]: + """Return list of CUDA device IDs available to this worker.""" return ray.get_gpu_ids() def update_env_vars(self, env_vars: Dict[str, str]): + """Update the env vars in the actor pr...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/ray/worker.py
Create docstrings for API functions
# Copyright 2017 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -45,6 +45,43 @@ op=Average, num_groups=0, groups=None): + """ + An optimizer that wraps another keras.optimizers.Optimizer, using an allreduce to + average gradient values before applying gradients to model weights. + + ...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/keras/__init__.py
Add inline docstrings for readability
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -41,6 +41,16 @@ def host_hash(salt=None): + """ + Computes this host's host hash by invoking horovod.runner.common.util.host_hash.host_hash. + + Consider environment variable CONTAINER_ID which is present when running Spark via YARN. + A YARN container does not share memory with other contain...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/spark/common/util.py
Insert docstrings into my code
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved. # Modifications copyright Microsoft # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENS...
--- +++ @@ -16,10 +16,18 @@ class HorovodInternalError(RuntimeError): + """Internal error raised when a Horovod collective operation (e.g., allreduce) fails. + + This is handled in elastic mode as a recoverable error, and will result in a reset event. + """ pass class HostsUpdatedInterrupt(Runtim...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/common/exceptions.py
Add docstrings to meet PEP guidelines
from typing import * # for type annotations, importing mpi4py has dangerous side effects try: from horovod.common.basics import HorovodBasics except ImportError: class HorovodBasics: ... class MPI: class Comm: ... from horovod.common.util import is_iterable _basics = None # type: Optiona...
--- +++ @@ -16,6 +16,12 @@ class ProcessSet: + """ Representation of a set of Horovod processes that will run collective operations together + + Initialize a ProcessSet with a list of process ranks or an MPI communicator. Then pass this instance to hvd.init() + or hvd.add_process_set(). If a valid process ...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/common/process_sets.py
Insert docstrings into my code
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -18,6 +18,36 @@ def __init__(self, num_proc=None, verbose=0, ssh_port=None, ssh_identity_file=None, extra_mpi_args=None, tcp_flag=None, binding_args=None, key=None, start_timeout=None, output_filename=None, run_func_mode=None, nics=None, elastic=False, prefix_output_wi...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/runner/common/util/settings.py
Improve my code by adding docstrings
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -19,22 +19,46 @@ class BaseDataLoader(object): def __len__(self): + """ + Length of the batches to be loaded. + """ raise NotImplementedError() def _iterate(self): + """ + Interface for the implimentation of iterate batches + """ raise...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/data/data_loader_base.py
Add minimal docstrings for each function
# Copyright (C) 2019 Uber Technologies, Inc. # Modifications copyright Microsoft # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless re...
--- +++ @@ -27,6 +27,7 @@ class HorovodBasics(object): + """Wrapper class for the basic Horovod API.""" def __init__(self, pkg_path, *args): full_path = util.get_extension_full_path(pkg_path, *args) @@ -49,6 +50,27 @@ def init(self, comm: Optional[Union[Sequence[int], MPI.Comm]] = None, ...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/common/basics.py
Document this module using docstrings
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -48,6 +48,30 @@ def _launch_task_servers(all_host_names, local_host_names, driver_addresses, settings): + """ + Executes the task server and service client task for registration on the + hosts. + :param all_host_names: list of addresses. for example, + ['worker-...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/runner/driver/driver_service.py
Help me add docstrings to my project
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -81,6 +81,19 @@ def prefix_connection(src_connection, dst_stream, prefix, index, prefix_output_with_timestamp): + """ + Prefixes the given source connection with timestamp, a prefix and an index. + Each line of the source will be prefix in this format, if index and prefix are not None: + ...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/runner/common/util/safe_shell_exec.py
Document this code for team use
# Copyright 2018 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -21,8 +21,25 @@ class BroadcastGlobalVariablesCallback(_impl.BroadcastGlobalVariablesCallbackImpl, keras.callbacks.Callback): + """ + Keras Callback that will broadcast all global variables from root rank + to all other processes during initialization. + + This is necessary to ensure consiste...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/keras/callbacks.py
Write clean docstrings for readability
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -83,6 +83,12 @@ env['PYTHONUNBUFFERED'] = '1' def slot_info_to_command(slot_info): + """ + Given a slot_info, creates a command used by gloo to launch a single job. + + :param slot_info: host and slot to execute the run command on + :return: + """ env_va...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/runner/gloo_run.py
Document classes and their methods
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -35,6 +35,17 @@ self._keys_in_use[key] -= 1 def next_dataset_index(self, key): + """Finds the next available `dataset_idx` given a key. + + Indices start a 0 and go up until the first unused index is found. + + Will attempt to reuse earlier indices if they are no longe...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/spark/common/cache.py
Generate docstrings with parameter types
from typing import Callable, List, Any, Dict, Optional import logging import socket import time import os import random import math import threading import warnings from horovod.runner.common.util import timeout, secret from horovod.runner.http.http_server import RendezvousServer from horovod.runner.gloo_run import (...
--- +++ @@ -37,6 +37,9 @@ class RayHostDiscovery(HostDiscovery): + """Uses Ray global state to obtain host mapping. + + Assumes that the whole global state is available for usage.""" def __init__(self, use_gpu=False, cpus_per_slot=1, gpus_per_slot=1): self.use_gpu = use_gpu @@ -46,6 +49,7 @@ ...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/ray/elastic.py
Add docstrings to incomplete code
import ray from ray.util.placement_group import get_current_placement_group from collections import defaultdict from dataclasses import dataclass, asdict import os from typing import Dict, Callable, Any, Optional, List import logging import ray.exceptions from horovod.ray.adapter import Adapter, BaseParams from horov...
--- +++ @@ -19,6 +19,10 @@ @dataclass class MiniSettings: + """Minimal settings necessary for Ray to work. + + Can be replaced with a proper Horovod Settings object. + """ nics: set = None verbose: int = 1 key: str = secret.make_secret_key() if secret else None @@ -39,6 +43,10 @@ class Co...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/ray/runner.py
Generate docstrings with parameter types
from typing import Callable, List, Any, Dict, Optional, Tuple import logging import ray.exceptions import socket import time import os import random import math import threading from dataclasses import dataclass from horovod.ray.adapter import Adapter, BaseParams from horovod.runner.http.http_server import Rendezvous...
--- +++ @@ -38,6 +38,9 @@ class RayHostDiscovery(HostDiscovery): + """Uses Ray global state to obtain host mapping. + + Assumes that the whole global state is available for usage.""" def __init__(self, use_gpu=False, cpus_per_worker=1, gpus_per_worker=1): self.use_gpu = use_gpu @@ -47,6 +50,7 ...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/ray/elastic_v2.py
Add docstrings for utility scripts
# Copyright IBM Corp. 2020. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
--- +++ @@ -24,6 +24,7 @@ class LSFUtils: + """LSF Utilities""" _CSM_ALLOCATION_QUERY = "/opt/ibm/csm/bin/csm_allocation_query" _CSM_NODE_QUERY = "/opt/ibm/csm/bin/csm_node_attributes_query" _LSCPU_CMD = "LANG=en_US.utf8 lscpu" @@ -32,10 +33,12 @@ @staticmethod def using_lsf(): + ...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/runner/util/lsf.py
Add docstrings for internal functions
from abc import ABC, abstractmethod from typing import Dict, Callable, Any, Optional, List from dataclasses import dataclass @dataclass class BaseParams: cpus_per_worker: int = 1 use_gpu: bool = False gpus_per_worker: Optional[int] = None def __post_init__(self): if self.gpus_per_worker and not...
--- +++ @@ -20,17 +20,45 @@ class Adapter(ABC): + """Adapter for executing Ray calls for various types(e.g. static and elastic) + Horovod jobs. + """ @abstractmethod def start(self, executable_cls: type = None, executable_args: Optional[List] = None, e...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/ray/adapter.py
Write docstrings for utility functions
# Copyright 2020 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -24,6 +24,12 @@ class State(object): + """State representation used for tracking in memory state across workers. + + Args: + bcast_object: Function used to broadcast a variable from rank 0 to the other workers. + get_rank: Function that returns the current rank of this worker. + ""...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/common/elastic.py
Create docstrings for reusable components
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -44,14 +44,30 @@ class AckResponse(object): + """Used for situations when the response does not carry any data.""" pass class AckStreamResponse(object): + """Used to indicate that stream data follow.""" pass class Wire(object): + """ + Used for serialization/deserializatio...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/runner/common/util/network.py
Auto-generate documentation strings for this file
# Copyright 2020 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -85,6 +85,7 @@ logging.debug(f"cooldown delta seconds: {cooldown_delta_seconds}") def blacklist(self): + """Moves this host to a blacklist, and starts the cooldown period.""" self._blacklisted = True now = time.time() if self._in_cooldown_period(now): @@ -93,1...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/runner/elastic/discovery.py
Write clean docstrings for readability
# Copyright 2022 G-Research. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
--- +++ @@ -26,6 +26,7 @@ class RegisterDispatcherRequest(object): + """Registers a dispatcher server address along with a dispatcher id.""" def __init__(self, dispatcher_id, dispatcher_address): self.dispatcher_id = dispatcher_id @@ -36,6 +37,7 @@ class WaitForDispatcherRegistrationRequest(o...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/runner/common/service/compute_service.py
Create docstrings for reusable components
from collections import defaultdict import logging from typing import Dict import ray from ray.util.placement_group import get_current_placement_group from horovod.ray.utils import map_blocking from horovod.ray.worker import BaseHorovodWorker logger = logging.getLogger(__name__) def create_placement_group(resources...
--- +++ @@ -31,6 +31,7 @@ class BaseStrategy: + """Base class for implementing different placement strategies.""" placement_group = None workers = None @@ -43,6 +44,7 @@ @classmethod def get_node_workers(cls, workers): + """Returns list of one worker per node to use for NIC detectio...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/ray/strategy.py
Create structured documentation for my script
from typing import List, Optional, Callable, Any, Dict from contextlib import contextmanager import ray from horovod.runner.driver import driver_service from horovod.ray.driver_service import _driver_fn from horovod.runner.util import network class _DiscoveryActor: def execute(self, func: Callable) -> Any: ...
--- +++ @@ -9,6 +9,7 @@ class _DiscoveryActor: def execute(self, func: Callable) -> Any: + """Executes an arbitrary function on self.""" return func(self) @@ -35,6 +36,27 @@ def detect_nics(settings, all_host_names: List[str], node_workers: Optional[List] = N...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/ray/utils.py
Help me comply with documentation standards
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -28,17 +28,41 @@ class Backend(object): + """Interface for remote execution of the distributed training function. + + A custom backend can be used in cases where the training environment running Horovod is different + from the Spark application running the HorovodEstimator. + """ def r...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/spark/common/backend.py
Write proper docstrings for these functions
# Copyright 2020 Uber Technologies, Inc. All Rights Reserved. # Modifications copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # #...
--- +++ @@ -25,6 +25,18 @@ def broadcast_object(obj, root_rank=0, name=None): + """ + Serializes and broadcasts an object from root rank to all other processes. + + Arguments: + obj: An object capable of being serialized without losing any context. + root_rank: The rank of the process from wh...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/mxnet/functions.py
Create docstrings for reusable components
# Copyright 2017 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -90,6 +90,9 @@ return self.get_weights() def register_local_var(self, var): + """Registers a source/variable as worker local. Horovod will not perform any global + operations on gradients corresponding to these sources and will instead return the local + ...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/_keras/__init__.py
Write docstrings for backend logic
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # Modifications copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the Lic...
--- +++ @@ -84,6 +84,41 @@ def allreduce(tensor, average=None, name=None, priority=0, prescale_factor=1.0, postscale_factor=1.0, process_set=global_process_set, op=None): + """ + A function that performs averaging or summation of the input tensor over + all the Horovod processes. The input ten...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/mxnet/mpi_ops.py
Provide clean and structured docstrings
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -78,6 +78,20 @@ def _get_mpi_implementation(env=None): + """ + Detects the available MPI implementation by invoking `mpirun --version`. + This command is executed by the given execute function, which takes the + command as the only argument and returns (output, exit code). Output + represe...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/runner/mpi_run.py
Generate docstrings with parameter types
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # Modifications copyright (C) 2019 Uber Technologies, Inc. # Modifications copyright Microsoft # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of t...
--- +++ @@ -31,6 +31,7 @@ def get_ext_suffix(): + """Determine library extension for various versions of Python.""" ext_suffix = sysconfig.get_config_var('EXT_SUFFIX') if ext_suffix: return ext_suffix @@ -61,6 +62,10 @@ def _check_extension_lambda(ext_base_name, fn, fn_desc, verbose): + ...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/common/util.py
Generate consistent documentation across files
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -36,65 +36,99 @@ class Store(object): + """ + Storage layer for intermediate files (materialized DataFrames) and training artifacts (checkpoints, logs). + + Store provides an abstraction over a filesystem (e.g., local vs HDFS) or blob storage database. It provides the + basic semantics for re...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/spark/common/store.py
Add structured docstrings to improve clarity
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -43,22 +43,27 @@ class StreamCommandStdOutRequest(StreamCommandOutputRequest): + """Streams the command stdout to the client.""" pass class StreamCommandStdErrRequest(StreamCommandOutputRequest): + """Streams the command stderr to the client.""" pass class CommandOutputNotCaptur...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/runner/common/service/task_service.py
Add docstrings that explain logic
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -24,9 +24,25 @@ class HorovodEstimator(Estimator, EstimatorParams): def fit(self, df, params=None): + """Fits the model to the DataFrame. + + Args: + df: Input dataset, which is an instance of :py:class:`pyspark.sql.DataFrame`. + params: An optional param map that o...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/spark/common/estimator.py
Write docstrings describing each step
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -21,6 +21,26 @@ args_list, block_until_all_done=True, max_concurrent_executions=1000): + """ + Executes fn in multiple threads each with one set of the args in the + args_list. + :param fn: ...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/runner/util/threads.py
Create simple docstrings for beginners
import warnings _queue = None _queue_set = False warning_raised = False def configure(queue): global _queue global _queue_set _queue = queue # We maintain a _queue_set variable because somehow # the _queue variable makes a lot of unnecessary remote calls. _queue_set = True def log(info_di...
--- +++ @@ -1,3 +1,8 @@+"""Module for supporting multi-node callbacks. + +This module maintains a set of global variables for each +Ray process. +""" import warnings @@ -7,6 +12,7 @@ def configure(queue): + """Sets the proper global variables.""" global _queue global _queue_set @@ -17,6 +23,11 @...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/ray/ray_logger.py
Help me document legacy Python code
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -20,6 +20,7 @@ class TaskHostHashIndicesRequest(object): + """Request task indices for a given host hash.""" def __init__(self, host_hash): self.host_hash = host_hash @@ -31,6 +32,7 @@ class SetLocalRankToRankRequest(object): + """Set local rank to rank.""" def __init__(sel...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/spark/driver/driver_service.py
Write docstrings for utility functions
# Copyright 2020 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -20,25 +20,66 @@ class KerasState(TensorFlowKerasState): + """State representation of a `keras` model and optimizer. + + Args: + model: Keras model. + optimizer: Optional optimizer, can be compiled into model instead. + kwargs: Additional properties to sync, will be exposed as ...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/keras/elastic.py
Write documentation strings for class attributes
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -52,6 +52,12 @@ def parse_host_files(filename): + """ + Transform the hostfile into a format of + <IP address> or <host name>:<Number of GPUs> + :param filename: Should be in <IP address> or <host name> slots=<number of GPUs> + :return: Comma separated string of <IP address> or <host name>...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/runner/common/util/hosts.py
Add docstrings including usage examples
# Copyright 2020 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -34,6 +34,18 @@ def gloo_run(executable, settings, nics, driver, env, stdout=None, stderr=None): + """ + Run distributed gloo jobs. + + :param executable: Executable to run when launching the workers. + :param settings: Settings for running the distributed jobs. + Note: se...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/spark/gloo_run.py
Write beginner-friendly docstrings
# Copyright (C) 2022, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
--- +++ @@ -22,6 +22,7 @@ class PetastormDataModule(DataModule): + """Default Petastorm-based DataModule for KerasEstimator.""" def __init__(self, reader_pool_type="thread", @@ -135,6 +136,7 @@ class MapIterable(): + """Wraps an iterable with a user-defined map function for N epoc...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/spark/torch/datamodule.py
Add docstrings to clarify complex logic
# Copyright (C) 2022, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
--- +++ @@ -20,6 +20,7 @@ class PetastormDataModule(DataModule): + """Default Petastorm-based DataModule for KerasEstimator.""" def __init__(self, reader_pool_type: str='thread', train_reader_worker_count: int=2, val_reader_worker_count: int=2, @@ -103,6 +104,...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/spark/keras/datamodule.py
Document this module using docstrings
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -23,6 +23,17 @@ def save_bare_keras_optimizer(optimizer, h5py_file): def get_json_type(obj): + """Serialize any object to a JSON-serializable structure. + + # Arguments + obj: the object to serialize + + # Returns + JSON-serializable structure representing `o...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/spark/keras/bare.py
Generate descriptive docstrings automatically
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved. # Modifications copyright (C) 2022, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # ...
--- +++ @@ -87,11 +87,79 @@ class TorchEstimatorParamsReadable(MLReadable): @classmethod def read(cls): + """Returns a DefaultParamsReader instance for this class.""" return TorchEstimatorParamsReader(cls) class TorchEstimator(HorovodEstimator, TorchEstimatorParamsWritable, ...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/spark/torch/estimator.py
Can you add docstrings to this Python file?
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved. # Modifications copyright (C) 2022, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # ...
--- +++ @@ -91,11 +91,78 @@ class KerasEstimatorParamsReadable(MLReadable): @classmethod def read(cls): + """Returns a KerasEstimatorParamsReader instance for this class.""" return KerasEstimatorParamsReader(cls) class KerasEstimator(HorovodEstimator, KerasEstimatorParamsReadable, ...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/spark/keras/estimator.py
Write docstrings describing each step
# Copyright 2020 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -20,25 +20,66 @@ class KerasState(TensorFlowKerasState): + """State representation of a `tf.keras` model and optimizer. + + Args: + model: Keras model. + optimizer: Optional optimizer, can be compiled into model instead. + kwargs: Additional properties to sync, will be exposed ...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/tensorflow/keras/elastic.py
Generate docstrings with examples
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -130,7 +130,9 @@ def _make_spark_thread(spark_context, spark_job_group, driver, result_queue, settings, use_gloo, is_elastic): + """Creates `settings.num_proc` Spark tasks in a parallel thread.""" def run_spark(): + """Creates `settings.num_proc` Spark tasks, each exe...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/spark/runner.py
Generate docstrings for this script
# Copyright 2020 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -28,6 +28,18 @@ def broadcast_parameters(params, root_rank): + """ + Broadcasts the parameters from root rank to all other processes. + Typical usage is to broadcast the ``model.state_dict()``, + ``model.named_parameters()``, or ``model.parameters()``. + + Arguments: + params: One o...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/torch/functions.py
Add minimal docstrings for each function
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # Modifications copyright (C) 2019 Uber Technologies, Inc. # Modifications copyright Microsoft # Modifications copyright (C) 2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use ...
--- +++ @@ -15,6 +15,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= +"""Inter-process communication using MPI.""" import re import tensorflow as tf @@ -32,6 +33,14 @@ de...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/tensorflow/mpi_ops.py
Document this module using docstrings
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -93,11 +93,104 @@ class TorchEstimatorParamsReadable(MLReadable): @classmethod def read(cls): + """Returns a DefaultParamsReader instance for this class.""" return TorchEstimatorParamsReader(cls) class TorchEstimator(HorovodEstimator, TorchEstimatorParamsWritable, ...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/spark/lightning/estimator.py
Document classes and their methods
# Copyright 2022 G-Research. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
--- +++ @@ -87,6 +87,9 @@ @contextmanager def tf_data_service(compute_config: TfDataServiceConfig, rank: int) -> str: + """ + Provides the address of the TF Dispatcher. + """ compute = compute_config.compute_client(verbose=2) @@ -142,6 +145,7 @@ def compute_worker_fn(compute_config: TfDataServi...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/tensorflow/data/compute_service.py
Write beginner-friendly docstrings
import os import tensorflow as tf from packaging import version from horovod.tensorflow.mpi_ops import size_op from horovod.tensorflow.mpi_ops import global_process_set _POST_TF_2_4_0 = version.parse(tf.__version__) >= version.parse('2.4.0') _IS_TF2 = version.parse(tf.__version__) >= version.parse('2.0.0') class Lo...
--- +++ @@ -10,6 +10,11 @@ class LocalGradientAggregationHelperEager: + """ + LocalGradientAggregationHelperEager aggregates gradient updates + locally, and communicates the updates across machines only once + every backward_passes_per_step. Only supports eager execution. + """ def __init__( ...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/tensorflow/gradient_aggregation_eager.py
Add return value explanations in docstrings
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved. # Modifications copyright Microsoft # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENS...
--- +++ @@ -303,6 +303,18 @@ @contextmanager def skip_synchronize(self): + """ + A context manager used to specify that optimizer.step() should + not perform synchronization. + + It's typically used in a following pattern: + + .. code-block:: python + + optimizer...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/torch/optimizer.py
Document all public functions with docstrings
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved. # Modifications copyright Microsoft # Modifications copyright (C) 2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may ...
--- +++ @@ -157,12 +157,42 @@ def allreduce_async(tensor, average=None, name=None, op=None, prescale_factor=1.0, postscale_factor=1.0, process_set=global_process_set): + """ + A function that performs asynchronous averaging or summation of the input tensor + over all t...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/torch/mpi_ops.py
Generate helpful docstrings for debugging
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -47,6 +47,7 @@ is_module_available = is_module_available_fn() def _serialize(model): + """Serialize model into byte array encoded into base 64.""" if is_module_available('torch'): import torch sys.modules["torch._C._nn"] = torch.nn.functional @@ -65,6 +66,...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/spark/lightning/util.py
Add structured docstrings to improve clarity
# Copyright 2020 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -29,6 +29,25 @@ def run(func): + """Decorator used to run the elastic training process. + + The purpose of this decorator is to allow for uninterrupted execution of the wrapped function + across multiple workers in parallel, as workers come and go from the system. When a new worker is added, + ...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/tensorflow/elastic.py
Generate NumPy-style docstrings
import os import tensorflow as tf from packaging import version from horovod.tensorflow.mpi_ops import size_op from horovod.tensorflow.mpi_ops import global_process_set _IS_TF2 = version.parse(tf.__version__) >= version.parse('2.0.0') def apply_op_to_not_none_tensors(tensor_op, tensors, *args): return [ ...
--- +++ @@ -21,6 +21,11 @@ class LocalGradientAggregationHelper: + """ + LocalGradientAggregationHelper aggregates gradient updates locally, + and communicates the updates across machines only once every + backward_passes_per_step. Only supports graph mode execution. + """ _OPTIMIZER_TYPE_KERA...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/tensorflow/gradient_aggregation.py
Add docstrings to incomplete code
# Copyright 2020 Google Research. All Rights Reserved. # Modifications copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # htt...
--- +++ @@ -20,6 +20,7 @@ from horovod.tensorflow.mpi_ops import Sum class SyncBatchNormalization(tf.keras.layers.BatchNormalization): + """ Synchronous batch normalization. Stats are synchronized across all workers during training. """ def __init__(self, fused=False, **kwargs): if fused in (True, None): ...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/tensorflow/sync_batch_norm.py
Document classes and their methods
# Copyright 2018 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -28,8 +28,25 @@ class BroadcastGlobalVariablesCallback(_impl.BroadcastGlobalVariablesCallbackImpl, keras.callbacks.Callback): + """ + Keras Callback that will broadcast all global variables from root rank + to all other processes during initialization. + + This is necessary to ensure consiste...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/tensorflow/keras/callbacks.py
Help me comply with documentation standards
# Copyright 2018 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -58,6 +58,55 @@ groups=None, process_set=global_process_set, scale_local_gradients=True): + """ + An optimizer that wraps another keras.optimizers.Optimizer, using an allreduce to + average gradient values before applying g...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/tensorflow/keras/__init__.py
Create simple docstrings for beginners
# Copyright 2020 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -64,6 +64,24 @@ def broadcast_variables(variables, root_rank, process_set=global_process_set, inplace=False): + """ + Broadcasts variables from root rank to all other processes + in a process set (defaults to all Horovod processes). + + Optionally, the broadcast may be performed in-place, whi...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/tensorflow/functions.py
Add documentation for all methods
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # Modifications copyright (C) 2019 Uber Technologies, Inc. # Modifications copyright Microsoft # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of t...
--- +++ @@ -60,6 +60,43 @@ prescale_factor=1.0, postscale_factor=1.0, name=None, process_set=global_process_set, ignore_name_scope=False): + """Perform an allreduce on a tf.Tensor or tf.IndexedSlices. + + This function performs a bandwidth-optimal ring allreduce on the ...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/tensorflow/__init__.py
Please document this code using docstrings
# Copyright 2019 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -24,6 +24,7 @@ class ResourcesRequest(object): + """Request Spark resources info for this task.""" class ResourcesResponse(object): @@ -106,6 +107,10 @@ return dict() def wait_for_command_termination(self): + """ + Waits for command termination. Ensures this method ta...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/spark/task/task_service.py
Generate NumPy-style docstrings
# Copyright 2018 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -12,33 +12,42 @@ # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== +"""Gradient compression algorithms.""" import torch class Compressor(object): + """Interface f...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/torch/compression.py
Turn comments into proper docstrings
# -*- coding:utf-8 -*- import pandas as pd from tushare.stock import cons as ct from tushare.stock import ref_vars as rv import json import re from pandas.util.testing import _network_error_classes import time import tushare.stock.fundamental as fd from tushare.util.netbase import Client try: from urllib.request...
--- +++ @@ -1,236 +1,358 @@-# -*- coding:utf-8 -*- - - -import pandas as pd -from tushare.stock import cons as ct -from tushare.stock import ref_vars as rv -import json -import re -from pandas.util.testing import _network_error_classes -import time -import tushare.stock.fundamental as fd -from tushare.util.netbase impo...
https://raw.githubusercontent.com/waditu/tushare/HEAD/tushare/stock/classifying.py
Help me write clear docstrings
# -*- coding:utf-8 -*- from tushare.pro import client from tushare.util import upass from tushare.util.formula import MA PRICE_COLS = ['open', 'close', 'high', 'low', 'pre_close'] FORMAT = lambda x: '%.2f' % x FREQS = {'D': '1DAY', 'W': '1WEEK', 'Y': '1YEAR', } def pro_api(token=''): ...
--- +++ @@ -1,4 +1,11 @@ # -*- coding:utf-8 -*- +""" +pro init +Created on 2018/07/01 +@author: Jimmy Liu +@group : tushare.pro +@contact: jimmysoa@sina.cn +""" from tushare.pro import client from tushare.util import upass from tushare.util.formula import MA @@ -12,6 +19,9 @@ def pro_api(token=''): + """ + ...
https://raw.githubusercontent.com/waditu/tushare/HEAD/tushare/pro/data_pro.py
Write docstrings for algorithm functions
# Copyright 2020 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -22,6 +22,25 @@ class ElasticSampler(torch.utils.data.Sampler): + """Sampler that partitions dataset across ranks and repartitions after reset events. + + Works similar to `DistributedSampler`, but with an optional capability to record + which dataset indices have been processed each batch. When...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/torch/elastic/sampler.py
Add verbose docstrings with examples
# -*- coding:utf-8 -*- from __future__ import division import time import json import re import pandas as pd import numpy as np from tushare.fund import cons as ct from tushare.util import dateu as du try: from urllib.request import urlopen, Request except ImportError: from urllib2 import urlopen, Request d...
--- +++ @@ -1,5 +1,12 @@ # -*- coding:utf-8 -*- +""" +获取基金净值数据接口 +Created on 2016/04/03 +@author: leo +@group : lazytech +@contact: lazytech@sina.cn +""" from __future__ import division import time @@ -16,6 +23,34 @@ def get_nav_open(fund_type='all'): + """ + 获取开放型基金净值数据 + Parameters + ------...
https://raw.githubusercontent.com/waditu/tushare/HEAD/tushare/fund/nav.py
Fill in missing docstrings in my code
# -*- coding:utf-8 -*- import pandas as pd import numpy as np import itertools def ma(df, n=10): pv = pd.DataFrame() pv['date'] = df['date'] pv['v'] = df.close.rolling(n).mean() return pv def _ma(series, n): return series.rolling(n).mean() def md(df, n=10): _md = pd.DataFrame() _md['d...
--- +++ @@ -1,11 +1,24 @@ # -*- coding:utf-8 -*- +""" +股票技术指标接口 +Created on 2018/07/26 +@author: Wangzili +@group : ** +@contact: 446406177@qq.com + +所有指标中参数df为通过get_k_data获取的股票数据 +""" import pandas as pd import numpy as np import itertools def ma(df, n=10): + """ + 移动平均线 Moving Average + MA(N)=(第1日收...
https://raw.githubusercontent.com/waditu/tushare/HEAD/tushare/stock/trendline.py
Help me add docstrings to my project
#!/usr/bin/env python # -*- coding:utf-8 -*- import pandas as pd import traceback import time import json try: from urllib.request import urlopen, Request except ImportError: from urllib2 import urlopen, Request URL = { "hb": { "rt" : 'http://api.huobi.com/staticmarket/ticker_%s...
--- +++ @@ -1,5 +1,12 @@ #!/usr/bin/env python # -*- coding:utf-8 -*- +""" +数字货币行情数据 +Created on 2017年9月9日 +@author: Jimmy Liu +@group : waditu +@contact: jimmysoa@sina.cn +""" import pandas as pd import traceback @@ -77,9 +84,81 @@ def coins_tick(broker='hb', code='btc'): + """ + 实时tick行情 + params: ...
https://raw.githubusercontent.com/waditu/tushare/HEAD/tushare/coins/market.py
Add inline docstrings for readability
# Copyright 2018 Uber Technologies, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
--- +++ @@ -12,33 +12,42 @@ # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== +"""Gradient compression algorithms.""" import tensorflow as tf class Compressor(object): + """...
https://raw.githubusercontent.com/horovod/horovod/HEAD/horovod/tensorflow/compression.py
Add verbose docstrings with examples
# -*- coding:utf-8 -*- import pandas as pd import numpy as np from tushare.stock import cons as ct from tushare.util import dateu as du from tushare.util.netbase import Client from pandas.compat import StringIO def shibor_data(year=None): year = du.get_year() if year is None else year lab = ct.SHIBOR_TYPE['Shi...
--- +++ @@ -1,4 +1,11 @@ # -*- coding:utf-8 -*- +""" +上海银行间同业拆放利率(Shibor)数据接口 +Created on 2014/07/31 +@author: Jimmy Liu +@group : waditu +@contact: jimmysoa@sina.cn +""" import pandas as pd import numpy as np from tushare.stock import cons as ct @@ -7,6 +14,24 @@ from pandas.compat import StringIO def shibor_dat...
https://raw.githubusercontent.com/waditu/tushare/HEAD/tushare/stock/shibor.py