instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Create Google-style docstrings for my code
import csv import dataclasses import json import html import os from contextlib import nullcontext import gradio as gr from modules import call_queue, shared, ui_tempdir, util import modules.images from modules.ui_components import ToolButton import modules.infotext_utils as parameters_copypaste folder_symbol = '\U0...
--- +++ @@ -1,319 +1,322 @@-import csv -import dataclasses -import json -import html -import os -from contextlib import nullcontext - -import gradio as gr - -from modules import call_queue, shared, ui_tempdir, util -import modules.images -from modules.ui_components import ToolButton -import modules.infotext_utils as pa...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules/ui_common.py
Can you add docstrings to this Python file?
import os import torch import gradio as gr from gradio.context import Context from modules import shared_items, shared, ui_common, sd_models, processing, infotext_utils, paths, ui_loadsave from backend import memory_management, stream from backend.args import dynamic_args from modules.shared import cmd_opts total_vr...
--- +++ @@ -165,6 +165,7 @@ def ui_refresh_memory_management_settings(model_memory, async_loading, pin_shared_memory): + """ Passes precalculated 'model_memory' from "GPU Weights" UI slider (skip redundant calculation) """ refresh_memory_management_settings( async_loading=async_loading, pi...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules_forge/main_entry.py
Please document this code using docstrings
import torch import math import struct import numpy as np from PIL import Image import itertools def calculate_parameters(sd, prefix=""): params = 0 for k in sd.keys(): if k.startswith(prefix): w = sd[k] params += w.nelement() return params def weight_dtype(sd, prefix=""...
--- +++ @@ -1,3 +1,20 @@+""" + This file is part of ComfyUI. + Copyright (C) 2024 Comfy + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + ...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/packages_3rdparty/comfyui_lora_collection/utils.py
Add docstrings to clarify complex logic
import os import tempfile from collections import namedtuple from pathlib import Path import gradio.components import gradio as gr from PIL import PngImagePlugin from modules import shared Savedfile = namedtuple("Savedfile", ["name"]) def register_tmp_file(gradio_app, filename): if hasattr(gradio_app, 'temp_...
--- +++ @@ -1,178 +1,199 @@-import os -import tempfile -from collections import namedtuple -from pathlib import Path - -import gradio.components -import gradio as gr - -from PIL import PngImagePlugin - -from modules import shared - - -Savedfile = namedtuple("Savedfile", ["name"]) - - -def register_tmp_file(gradio_app, ...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules/ui_tempdir.py
Add docstrings that explain inputs and outputs
import os import re from modules import shared from modules.paths_internal import script_path, cwd def natural_sort_key(s, regex=re.compile('([0-9]+)')): return [int(text) if text.isdigit() else text.lower() for text in regex.split(s)] def listfiles(dirname): filenames = [os.path.join(dirname, x) for x in ...
--- +++ @@ -1,244 +1,276 @@-import os -import re - -from modules import shared -from modules.paths_internal import script_path, cwd - - -def natural_sort_key(s, regex=re.compile('([0-9]+)')): - return [int(text) if text.isdigit() else text.lower() for text in regex.split(s)] - - -def listfiles(dirname): - filenam...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/modules/util.py
Write Python docstrings for this snippet
from collections import namedtuple from copy import copy from itertools import permutations, chain import random import csv import os.path from io import StringIO from PIL import Image import numpy as np import modules.scripts as scripts import gradio as gr from modules import images, sd_samplers, processing, sd_mode...
--- +++ @@ -1,838 +1,844 @@-from collections import namedtuple -from copy import copy -from itertools import permutations, chain -import random -import csv -import os.path -from io import StringIO -from PIL import Image -import numpy as np - -import modules.scripts as scripts -import gradio as gr - -from modules import...
https://raw.githubusercontent.com/lllyasviel/stable-diffusion-webui-forge/HEAD/scripts/xyz_grid.py
Create structured documentation for my script
# Mobile Verification Toolkit (MVT) # Copyright (c) 2021-2023 The MVT Authors. # Use of this software is governed by the MVT License 1.1 that can be found at # https://license.mvt.re/1.1/ import re from typing import Any, Dict, List, Union from mvt.android.utils import ROOT_PACKAGES from .artifact import AndroidAr...
--- +++ @@ -56,6 +56,9 @@ @staticmethod def parse_dumpsys_package_for_details(output: str) -> Dict[str, Any]: + """ + Parse one entry of a dumpsys package information + """ details = { "uid": "", "version_name": "", @@ -134,6 +137,9 @@ return de...
https://raw.githubusercontent.com/mvt-project/mvt/HEAD/src/mvt/android/artifacts/dumpsys_packages.py
Add verbose docstrings with examples
# Mobile Verification Toolkit (MVT) # Copyright (c) 2021-2023 The MVT Authors. # Use of this software is governed by the MVT License 1.1 that can be found at # https://license.mvt.re/1.1/ from typing import Any from .artifact import AndroidArtifact SUSPICIOUS_MOUNT_POINTS = [ "/system", "/vendor", "/pr...
--- +++ @@ -31,8 +31,20 @@ class Mounts(AndroidArtifact): + """ + This artifact parses mount information from /proc/mounts or similar mount data. + It can detect potentially suspicious mount configurations that may indicate + a rooted or compromised device. + """ def parse(self, entry: str) ->...
https://raw.githubusercontent.com/mvt-project/mvt/HEAD/src/mvt/android/artifacts/mounts.py
Add docstrings explaining edge cases
# Mobile Verification Toolkit (MVT) # Copyright (c) 2021-2023 The MVT Authors. # Use of this software is governed by the MVT License 1.1 that can be found at # https://license.mvt.re/1.1/ import json import logging import os from typing import Callable, Optional, Union from rich.progress import track from mvt.comm...
--- +++ @@ -19,6 +19,9 @@ class DownloadAPKs(AndroidExtraction): + """DownloadAPKs is the main class operating the download of APKs + from the device. + """ def __init__( self, @@ -26,6 +29,12 @@ all_apks: bool = False, packages: Optional[list] = None, ) -> None: + ...
https://raw.githubusercontent.com/mvt-project/mvt/HEAD/src/mvt/android/cmd_download_apks.py
Document helper functions with docstrings
# Mobile Verification Toolkit (MVT) # Copyright (c) 2021-2023 The MVT Authors. # Use of this software is governed by the MVT License 1.1 that can be found at # https://license.mvt.re/1.1/ import logging import os from pathlib import Path from typing import List, Optional from zipfile import ZipFile from mvt.android...
--- +++ @@ -56,6 +56,9 @@ self.__files: List[str] = [] def from_dir(self, dir_path: str) -> None: + """This method is used to initialize the bug report analysis from an + uncompressed directory. + """ self.__format = "dir" self.target_path = dir_path parent...
https://raw.githubusercontent.com/mvt-project/mvt/HEAD/src/mvt/android/cmd_check_bugreport.py
Add docstrings to improve readability
# Mobile Verification Toolkit (MVT) # Copyright (c) 2021-2023 The MVT Authors. # Use of this software is governed by the MVT License 1.1 that can be found at # https://license.mvt.re/1.1/ import datetime from typing import List, Optional, Union import pydantic import betterproto from dateutil import parser from mv...
--- +++ @@ -44,6 +44,11 @@ class TombstoneCrashResult(pydantic.BaseModel): + """ + MVT Result model for a tombstone crash result. + + Needed for validation and serialization, and consistency between text and protobuf tombstones. + """ file_name: str file_timestamp: str # We store the timest...
https://raw.githubusercontent.com/mvt-project/mvt/HEAD/src/mvt/android/artifacts/tombstone_crashes.py
Fully document this Python code with docstrings
# Mobile Verification Toolkit (MVT) # Copyright (c) 2021-2023 The MVT Authors. # Use of this software is governed by the MVT License 1.1 that can be found at # https://license.mvt.re/1.1/ import logging import os import sqlite3 from typing import Optional, Union from mvt.common.utils import convert_chrometime_to_da...
--- +++ @@ -16,6 +16,7 @@ class ChromeHistory(AndroidExtraction): + """This module extracts records from Android's Chrome browsing history.""" def __init__( self, @@ -55,6 +56,11 @@ continue def _parse_db(self, db_path: str) -> None: + """Parse a Chrome History datab...
https://raw.githubusercontent.com/mvt-project/mvt/HEAD/src/mvt/android/modules/adb/chrome_history.py
Auto-generate documentation strings for this file
# Mobile Verification Toolkit (MVT) # Copyright (c) 2021-2023 The MVT Authors. # Use of this software is governed by the MVT License 1.1 that can be found at # https://license.mvt.re/1.1/ import base64 import logging import os import random import string import sys import tempfile import time from typing import Call...
--- +++ @@ -37,6 +37,7 @@ class AndroidExtraction(MVTModule): + """This class provides a base for all Android extraction modules.""" def __init__( self, @@ -61,6 +62,7 @@ @staticmethod def _adb_check_keys() -> None: + """Make sure Android adb keys exist.""" if not os.pa...
https://raw.githubusercontent.com/mvt-project/mvt/HEAD/src/mvt/android/modules/adb/base.py
Create documentation strings for testing functions
# Mobile Verification Toolkit (MVT) # Copyright (c) 2021-2023 The MVT Authors. # Use of this software is governed by the MVT License 1.1 that can be found at # https://license.mvt.re/1.1/ import logging import os import sqlite3 from typing import Optional, Union from mvt.android.parsers.backup import AndroidBackupP...
--- +++ @@ -42,6 +42,7 @@ class SMS(AndroidExtraction): + """This module extracts all SMS messages.""" def __init__( self, @@ -89,6 +90,11 @@ continue def _parse_db(self, db_path: str) -> None: + """Parse an Android bugle_db SMS database file. + + :param db_pa...
https://raw.githubusercontent.com/mvt-project/mvt/HEAD/src/mvt/android/modules/adb/sms.py
Generate docstrings with parameter types
# Mobile Verification Toolkit (MVT) # Copyright (c) 2021-2023 The MVT Authors. # Use of this software is governed by the MVT License 1.1 that can be found at # https://license.mvt.re/1.1/ import base64 import logging import os import sqlite3 from typing import Optional, Union from mvt.common.utils import check_for_...
--- +++ @@ -17,6 +17,7 @@ class Whatsapp(AndroidExtraction): + """This module extracts all WhatsApp messages containing links.""" def __init__( self, @@ -59,6 +60,11 @@ continue def _parse_db(self, db_path: str) -> None: + """Parse an Android msgstore.db WhatsApp dat...
https://raw.githubusercontent.com/mvt-project/mvt/HEAD/src/mvt/android/modules/adb/whatsapp.py
Write reusable docstrings
from collections.abc import Hashable import datetime import functools import logging import random import re import time from typing import Set, List, Optional, Callable, Union logger = logging.getLogger("schedule") class ScheduleError(Exception): pass class ScheduleValueError(ScheduleError): pass cla...
--- +++ @@ -1,3 +1,42 @@+""" +Python job scheduling for humans. + +github.com/dbader/schedule + +An in-process scheduler for periodic jobs that uses the builder pattern +for configuration. Schedule lets you run Python functions (or any other +callable) periodically at pre-determined intervals using a simple, +human-fri...
https://raw.githubusercontent.com/dbader/schedule/HEAD/schedule/__init__.py
Add docstrings to improve code quality
# Mobile Verification Toolkit (MVT) # Copyright (c) 2021-2023 The MVT Authors. # Use of this software is governed by the MVT License 1.1 that can be found at # https://license.mvt.re/1.1/ import fnmatch import logging import os import zipfile from typing import Any, Dict, List, Optional, Union from mvt.common.modul...
--- +++ @@ -13,6 +13,7 @@ class AndroidQFModule(MVTModule): + """This class provides a base for all Android Data analysis modules.""" def __init__( self, @@ -48,6 +49,12 @@ return fnmatch.filter(self.files, pattern) def _get_device_timezone(self): + """ + Get the devi...
https://raw.githubusercontent.com/mvt-project/mvt/HEAD/src/mvt/android/modules/androidqf/base.py
Generate docstrings for script automation
# Mobile Verification Toolkit (MVT) # Copyright (c) 2021-2023 The MVT Authors. # Use of this software is governed by the MVT License 1.1 that can be found at # https://license.mvt.re/1.1/ import json import logging from typing import Optional from .base import AndroidQFModule class RootBinaries(AndroidQFModule): ...
--- +++ @@ -11,6 +11,7 @@ class RootBinaries(AndroidQFModule): + """This module analyzes root_binaries.json for root binaries found by androidqf.""" def __init__( self, @@ -39,6 +40,7 @@ } def check_indicators(self) -> None: + """Check for indicators of device rooting.""" ...
https://raw.githubusercontent.com/mvt-project/mvt/HEAD/src/mvt/android/modules/androidqf/root_binaries.py
Write docstrings for data processing functions
# Mobile Verification Toolkit (MVT) # Copyright (c) 2021-2023 The MVT Authors. # Use of this software is governed by the MVT License 1.1 that can be found at # https://license.mvt.re/1.1/ from rich.prompt import Prompt from mvt.common.config import settings MVT_ANDROID_BACKUP_PASSWORD = "MVT_ANDROID_BACKUP_PASSWO...
--- +++ @@ -12,6 +12,11 @@ def cli_load_android_backup_password(log, backup_password): + """ + Helper to load a backup password from CLI argument or environment variable + + Used in MVT CLI command parsers. + """ password_from_env_or_config = settings.ANDROID_BACKUP_PASSWORD if backup_password...
https://raw.githubusercontent.com/mvt-project/mvt/HEAD/src/mvt/android/modules/backup/helpers.py
Document functions with clear intent
# Mobile Verification Toolkit (MVT) # Copyright (c) 2021-2023 The MVT Authors. # Use of this software is governed by the MVT License 1.1 that can be found at # https://license.mvt.re/1.1/ import logging import json from typing import Optional from mvt.android.artifacts.mounts import Mounts as MountsArtifact from ....
--- +++ @@ -13,6 +13,7 @@ class Mounts(MountsArtifact, AndroidQFModule): + """This module extracts and analyzes mount information from AndroidQF acquisitions.""" def __init__( self, @@ -34,6 +35,13 @@ self.results = [] def run(self) -> None: + """ + Run the mounts ana...
https://raw.githubusercontent.com/mvt-project/mvt/HEAD/src/mvt/android/modules/androidqf/mounts.py
Generate docstrings for this script
# Mobile Verification Toolkit (MVT) # Copyright (c) 2021-2023 The MVT Authors. # Use of this software is governed by the MVT License 1.1 that can be found at # https://license.mvt.re/1.1/ import logging import os from datetime import datetime from typing import Optional, Tuple import requests import yaml from packa...
--- +++ @@ -74,6 +74,10 @@ handle.write(str(timestamp)) def get_latest_update(self) -> int: + """ + Check the time of the latest indicator update. + Returns 0 if this file doesn't exists. + """ if not os.path.exists(self.latest_update_path): return 0 ...
https://raw.githubusercontent.com/mvt-project/mvt/HEAD/src/mvt/common/updates.py
Add docstrings for better understanding
# Mobile Verification Toolkit (MVT) # Copyright (c) 2021-2023 The MVT Authors. # Use of this software is governed by the MVT License 1.1 that can be found at # https://license.mvt.re/1.1/ from typing import Optional import requests from tld import get_tld SHORTENER_DOMAINS = [ "0rz.tw", "1drv.ms", "1li...
--- +++ @@ -332,6 +332,12 @@ self.is_shortened = False def get_domain(self) -> str: + """Get the domain from a URL. + + :returns: Domain name extracted from URL + :rtype: str + + """ return ( get_tld(self.url, as_object=True, fix_protocol=True) ...
https://raw.githubusercontent.com/mvt-project/mvt/HEAD/src/mvt/common/url.py
Create documentation for each function signature
# Mobile Verification Toolkit (MVT) # Copyright (c) 2021-2023 The MVT Authors. # Use of this software is governed by the MVT License 1.1 that can be found at # https://license.mvt.re/1.1/ class Artifact: def __init__(self, *args, **kwargs): self.results = [] self.detected = [] self.indi...
--- +++ @@ -5,6 +5,9 @@ class Artifact: + """ + Main artifact class + """ def __init__(self, *args, **kwargs): self.results = [] @@ -13,7 +16,13 @@ super().__init__(*args, **kwargs) def parse(self, entry: str): + """ + Parse the artifact, adds the parsed informa...
https://raw.githubusercontent.com/mvt-project/mvt/HEAD/src/mvt/common/artifact.py
Write clean docstrings for readability
import os import yaml import json from typing import Tuple, Type, Optional from appdirs import user_config_dir from pydantic import AnyHttpUrl, Field from pydantic_settings import ( BaseSettings, InitSettingsSource, PydanticBaseSettingsSource, SettingsConfigDict, YamlConfigSettingsSource, ) MVT_CO...
--- +++ @@ -72,6 +72,9 @@ def save_settings( self, ) -> None: + """ + Save the current settings to a file. + """ if not os.path.isdir(MVT_CONFIG_FOLDER): os.makedirs(MVT_CONFIG_FOLDER) @@ -82,6 +85,14 @@ @classmethod def initialise(cls) -> "MVTSe...
https://raw.githubusercontent.com/mvt-project/mvt/HEAD/src/mvt/common/config.py
Write clean docstrings for readability
# Mobile Verification Toolkit (MVT) # Copyright (c) 2021-2023 The MVT Authors. # Use of this software is governed by the MVT License 1.1 that can be found at # https://license.mvt.re/1.1/ import glob import json import logging import os from functools import lru_cache from typing import Any, Dict, Iterator, List, Op...
--- +++ @@ -23,6 +23,9 @@ class Indicators: + """This class is used to parse indicators from a STIX2 file and provide + functions to compare extracted artifacts to the indicators. + """ def __init__(self, log=logger) -> None: self.log = log @@ -38,6 +41,9 @@ self.parse_stix2...
https://raw.githubusercontent.com/mvt-project/mvt/HEAD/src/mvt/common/indicators.py
Auto-generate documentation strings for this file
# Mobile Verification Toolkit (MVT) # Copyright (c) 2021-2023 The MVT Authors. # Use of this software is governed by the MVT License 1.1 that can be found at # https://license.mvt.re/1.1/ import base64 import binascii import hashlib from .artifact import AndroidArtifact class DumpsysADBArtifact(AndroidArtifact): ...
--- +++ @@ -14,6 +14,9 @@ multiline_fields = ["user_keys", "keystore"] def indented_dump_parser(self, dump_data): + """ + Parse the indented dumpsys output, generated by DualDumpOutputStream in Android. + """ res = {} stack = [res] cur_indent = 0 @@ -66,6 +69,9...
https://raw.githubusercontent.com/mvt-project/mvt/HEAD/src/mvt/android/artifacts/dumpsys_adb.py
Help me add docstrings to my project
# Mobile Verification Toolkit (MVT) # Copyright (c) 2021-2023 The MVT Authors. # Use of this software is governed by the MVT License 1.1 that can be found at # https://license.mvt.re/1.1/ import csv import json import logging import os import re from typing import Any, Dict, List, Optional, Union from .utils import...
--- +++ @@ -26,6 +26,7 @@ class MVTModule: + """This class provides a base for all extraction modules.""" enabled = True slug: Optional[str] = None @@ -39,6 +40,21 @@ log: logging.Logger = logging.getLogger(__name__), results: Union[List[Dict[str, Any]], Dict[str, Any], None] = None,...
https://raw.githubusercontent.com/mvt-project/mvt/HEAD/src/mvt/common/module.py
Add docstrings to improve readability
# Mobile Verification Toolkit (MVT) # Copyright (c) 2021-2023 The MVT Authors. # Use of this software is governed by the MVT License 1.1 that can be found at # https://license.mvt.re/1.1/ import cProfile import datetime import hashlib import json import logging import os import re from typing import Any, Iterator, U...
--- +++ @@ -17,6 +17,17 @@ class CustomJSONEncoder(json.JSONEncoder): + """ + Custom JSON encoder to handle non-standard types. + + Some modules are storing non-UTF-8 bytes in their results dictionaries. + This causes exceptions when the results are being encoded as JSON. + + Of course this means tha...
https://raw.githubusercontent.com/mvt-project/mvt/HEAD/src/mvt/common/utils.py
Add docstrings for production code
# Mobile Verification Toolkit (MVT) # Copyright (c) 2021-2023 The MVT Authors. # Use of this software is governed by the MVT License 1.1 that can be found at # https://license.mvt.re/1.1/ import binascii import glob import logging import multiprocessing import os import os.path import shutil import sqlite3 from typi...
--- +++ @@ -19,8 +19,17 @@ class DecryptBackup: + """This class provides functions to decrypt an encrypted iTunes backup + using either a password or a key file. + + + """ def __init__(self, backup_path: str, dest_path: Optional[str] = None) -> None: + """Decrypts an encrypted iOS backup. + ...
https://raw.githubusercontent.com/mvt-project/mvt/HEAD/src/mvt/ios/decrypt.py
Add docstrings to make code maintainable
# Mobile Verification Toolkit (MVT) # Copyright (c) 2021-2023 The MVT Authors. # Use of this software is governed by the MVT License 1.1 that can be found at # https://license.mvt.re/1.1/ import hashlib import logging import os import plistlib from datetime import datetime, timezone from typing import Any, Dict, Opt...
--- +++ @@ -26,6 +26,7 @@ class Applications(IOSExtraction): + """Extract information from accounts installed on the phone.""" def __init__( self, @@ -96,6 +97,9 @@ self.detected.append(result) def _parse_itunes_timestamp(self, entry: Dict[str, Any]) -> None: + """ +...
https://raw.githubusercontent.com/mvt-project/mvt/HEAD/src/mvt/ios/modules/mixed/applications.py
Add docstrings following best practices
# Mobile Verification Toolkit (MVT) # Copyright (c) 2021-2023 The MVT Authors. # Use of this software is governed by the MVT License 1.1 that can be found at # https://license.mvt.re/1.1/ import logging import operator import sqlite3 from pathlib import Path from typing import Optional, Union from mvt.common.utils ...
--- +++ @@ -15,6 +15,8 @@ class NetBase(IOSExtraction): + """This class provides a base for DataUsage and NetUsage extraction + modules.""" def __init__( self, @@ -239,6 +241,7 @@ ) def check_manipulated(self): + """Check for missing or manipulate DB entries""" ...
https://raw.githubusercontent.com/mvt-project/mvt/HEAD/src/mvt/ios/modules/net_base.py
Add docstrings to incomplete code
import numpy as np import torch as th from .gaussian_diffusion import GaussianDiffusion, mean_flat class KarrasDenoiser: def __init__(self, sigma_data: float = 0.5): self.sigma_data = sigma_data def get_snr(self, sigmas): return sigmas**-2 def get_sigmas(self, sigmas): return s...
--- +++ @@ -1,3 +1,26 @@+""" +Based on: https://github.com/crowsonkb/k-diffusion + +Copyright (c) 2022 Katherine Crowson + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, in...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/diffusion/k_diffusion.py
Generate docstrings for this script
import math from typing import Any, Dict, Iterable, Optional, Sequence, Union import blobfile as bf import numpy as np import torch as th import yaml def diffusion_from_config(config: Union[str, Dict[str, Any]]) -> "GaussianDiffusion": if isinstance(config, str): with bf.BlobFile(config, "rb") as f: ...
--- +++ @@ -1,3 +1,6 @@+""" +Based on https://github.com/openai/glide-text2im/blob/main/glide_text2im/gaussian_diffusion.py +""" import math from typing import Any, Dict, Iterable, Optional, Sequence, Union @@ -40,6 +43,11 @@ def get_beta_schedule(beta_schedule, *, beta_start, beta_end, num_diffusion_timesteps)...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/diffusion/gaussian_diffusion.py
Add docstrings to existing functions
# Mobile Verification Toolkit (MVT) # Copyright (c) 2021-2023 The MVT Authors. # Use of this software is governed by the MVT License 1.1 that can be found at # https://license.mvt.re/1.1/ import datetime import io import logging import os import plistlib from typing import Optional from mvt.common.module import Dat...
--- +++ @@ -18,6 +18,7 @@ class Manifest(IOSExtraction): + """This module extracts information from a backup Manifest.db file.""" def __init__( self, @@ -38,10 +39,22 @@ ) def _get_key(self, dictionary, key): + """Unserialized plist objects can have keys which are str or byt...
https://raw.githubusercontent.com/mvt-project/mvt/HEAD/src/mvt/ios/modules/backup/manifest.py
Help me document legacy Python code
import hashlib import os from functools import lru_cache from typing import Dict, Optional import requests import torch import yaml from filelock import FileLock from tqdm.auto import tqdm MODEL_PATHS = { "transmitter": "https://openaipublic.azureedge.net/main/shap-e/transmitter.pt", "decoder": "https://open...
--- +++ @@ -1,3 +1,6 @@+""" +Adapted from: https://github.com/openai/glide-text2im/blob/69b530740eb6cef69442d6180579ef5ba9ef063e/glide_text2im/download.py +""" import hashlib import os @@ -46,6 +49,11 @@ def fetch_file_cached( url: str, progress: bool = True, cache_dir: Optional[str] = None, chunk_size: int = ...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/models/download.py
Provide clean and structured docstrings
import math from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple import torch import torch.nn as nn from shap_e.models.nn.checkpoint import checkpoint from .pretrained_clip import FrozenImageCLIP, ImageCLIP, ImageType from .util import timestep_embedding def init_linear(l, stddev): nn.init.n...
--- +++ @@ -201,6 +201,11 @@ ) def forward(self, x: torch.Tensor, t: torch.Tensor): + """ + :param x: an [N x C x T] tensor. + :param t: an [N] tensor. + :return: an [N x C' x T] tensor. + """ assert x.shape[-1] == self.n_ctx t_embed = self.time_em...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/models/generation/transformer.py
Generate helpful docstrings for debugging
from abc import ABC, abstractmethod from functools import partial from typing import Any, Dict, Optional, Tuple import numpy as np import torch import torch.nn as nn from shap_e.models.nn.checkpoint import checkpoint from shap_e.models.nn.encoding import encode_position, spherical_harmonics_basis from shap_e.models.n...
--- +++ @@ -16,6 +16,9 @@ class NeRFModel(ABC): + """ + Parametric scene representation whose outputs are integrated by NeRFRenderer + """ @abstractmethod def forward( @@ -24,9 +27,22 @@ params: Optional[Dict[str, torch.Tensor]] = None, options: Optional[Dict[str, Any]] = None,...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/models/nerf/model.py
Add docstrings to improve readability
from functools import partial from typing import Any, Dict, Optional, Sequence, Tuple, Union import torch from shap_e.models.nerf.model import NeRFModel from shap_e.models.nerf.ray import RayVolumeIntegral, StratifiedRaySampler, render_rays from shap_e.models.nn.meta import subdict from shap_e.models.nn.utils import ...
--- +++ @@ -95,6 +95,12 @@ params: Optional[Dict] = None, options: Optional[AttrDict] = None, ) -> AttrDict: + """ + :param batch: has + + - rays: [batch_size x ... x 2 x 3] specify the origin and direction of each ray. + :param options: Optional[Dict] + """ ...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/models/nerstf/renderer.py
Generate NumPy-style docstrings
from abc import ABC, abstractmethod from dataclasses import dataclass from functools import partial from typing import Any, Dict, List, Optional, Tuple import torch from shap_e.models.nn.utils import sample_pmf from shap_e.models.volume import Volume, VolumeRange from shap_e.util.collections import AttrDict from .mo...
--- +++ @@ -21,6 +21,45 @@ render_with_direction: bool = True, importance_sampling_options: Optional[Dict[str, Any]] = None, ) -> Tuple["RayVolumeIntegralResults", List["RaySampler"], List[AttrDict]]: + """ + Perform volumetric rendering over a partition of possible t's in the union + of rendering vo...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/models/nerf/ray.py
Document classes and their methods
from functools import partial from typing import Any, Dict, Optional import torch from shap_e.models.nn.meta import subdict from shap_e.models.renderer import RayRenderer from shap_e.models.volume import Volume from shap_e.util.collections import AttrDict from .model import NeRFModel from .ray import RayVolumeIntegr...
--- +++ @@ -13,6 +13,10 @@ class TwoStepNeRFRenderer(RayRenderer): + """ + Coarse and fine-grained rendering as proposed by NeRF. This class + additionally supports background rendering like NeRF++. + """ def __init__( self, @@ -32,6 +36,9 @@ device: torch.device = torch.device("...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/models/nerf/renderer.py
Generate docstrings for this script
import math from functools import lru_cache from typing import Optional import torch import torch.nn as nn def encode_position(version: str, *, position: torch.Tensor): if version == "v1": freqs = get_scales(0, 10, position.dtype, position.device).view(1, -1) freqs = position.reshape(-1, 1) * fre...
--- +++ @@ -84,6 +84,12 @@ def forward( self, channels: torch.Tensor, position: torch.Tensor, direction: torch.Tensor ) -> torch.Tensor: + """ + :param channels: [batch_shape, inner_batch_shape, n_channels, height, width] + :param position: [batch_shape, inner_batch_shape, 3, heig...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/models/nn/encoding.py
Document this module using docstrings
from abc import ABC, abstractmethod from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from shap_e.rendering.view_data import ProjectiveCamera @dataclass class DifferentiableCamera(ABC): @abstractmethod def camera_rays(self, coords: torch.Tensor) -> ...
--- +++ @@ -10,16 +10,34 @@ @dataclass class DifferentiableCamera(ABC): + """ + An object describing how a camera corresponds to pixels in an image. + """ @abstractmethod def camera_rays(self, coords: torch.Tensor) -> torch.Tensor: + """ + For every (x, y) coordinate in a rendered ...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/models/nn/camera.py
Add standardized docstrings across the file
import math from typing import List, Optional, Tuple, Union import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from shap_e.util.collections import AttrDict from .meta import MetaModule, subdict from .pointnet2_utils import sample_and_group, sample_and_group_all def gelu(x): r...
--- +++ @@ -232,6 +232,10 @@ init_scale: float = 1.0, zero_out: bool = False, ): + """ + Required: d_input, d_hidden, d_output + Optional: act_name, bias + """ super().__init__() ds = [d_input] + d_hidden + [d_output] @@ -364,6 +368,13 @@ sel...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/models/nn/ops.py
Add docstrings with type hints explained
import itertools import re from collections import OrderedDict import torch.nn as nn from shap_e.util.collections import AttrDict __all__ = [ "MetaModule", "subdict", "superdict", "leveldict", "leveliter", "batch_meta_parameters", "batch_meta_state_dict", ] def subdict(dictionary, key=...
--- +++ @@ -1,3 +1,28 @@+""" +Meta-learning modules based on: https://github.com/tristandeleu/pytorch-meta + +MIT License + +Copyright (c) 2019-2020 Tristan Deleu + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to dea...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/models/nn/meta.py
Document classes and their methods
from abc import abstractmethod from typing import Callable, Dict, List, Optional, Tuple import numpy as np import torch from shap_e.models.nn.camera import ( DifferentiableCamera, DifferentiableProjectiveCamera, get_image_coords, projective_camera_frame, ) from shap_e.models.nn.meta import MetaModule ...
--- +++ @@ -15,6 +15,11 @@ class Renderer(MetaModule): + """ + A rendering abstraction that can render rays and views by calling the + appropriate models. The models are instantiated outside but registered in + this module. + """ @abstractmethod def render_views( @@ -23,9 +28,36 @@ ...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/models/renderer.py
Add docstrings to improve collaboration
from functools import partial from typing import Any, Dict, Optional, Tuple import torch import torch.nn as nn from shap_e.models.nn.checkpoint import checkpoint from shap_e.models.nn.encoding import encode_position, maybe_encode_direction from shap_e.models.nn.meta import MetaModule, subdict from shap_e.models.nn.op...
--- +++ @@ -110,6 +110,11 @@ params: Optional[Dict[str, torch.Tensor]] = None, options: Optional[Dict[str, Any]] = None, ) -> AttrDict: + """ + :param position: [batch_size x ... x 3] + :param params: Meta parameters + :param options: Optional hyperparameters + "...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/models/stf/mlp.py
Generate NumPy-style docstrings
from abc import ABC, abstractmethod from dataclasses import dataclass from functools import partial from typing import Any, Dict, Iterable, List, Optional, Tuple, Union import numpy as np import torch.distributed as dist import torch.nn as nn import torch.nn.functional as F from PIL import Image from torch import torc...
--- +++ @@ -27,6 +27,10 @@ class TransformerChannelsEncoder(ChannelsEncoder, ABC): + """ + Encode point clouds using a transformer model with an extra output + token used to extract a latent vector. + """ def __init__( self, @@ -95,6 +99,10 @@ class PerceiverChannelsEncoder(ChannelsE...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/models/transmitter/channels_encoder.py
Create docstrings for API functions
from time import time import numpy as np import torch import torch.nn as nn import torch.nn.functional as F def timeit(tag, t): print("{}: {}s".format(tag, time() - t)) return time() def pc_normalize(pc): l = pc.shape[0] centroid = np.mean(pc, axis=0) pc = pc - centroid m = np.max(np.sqrt(...
--- +++ @@ -1,3 +1,28 @@+""" +Based on https://github.com/yanx27/Pointnet_Pointnet2_pytorch/blob/master/models/pointnet2_utils.py + +MIT License + +Copyright (c) 2019 benny + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/models/nn/pointnet2_utils.py
Add professional docstrings to my codebase
from typing import Any, Dict, List, Optional, Tuple, Union import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from PIL import Image from shap_e.models.generation.transformer import Transformer from shap_e.rendering.view_data import ProjectiveCamera from shap_e.util.collections impor...
--- +++ @@ -14,6 +14,10 @@ class MultiviewTransformerEncoder(VectorEncoder): + """ + Encode cameras and views using a transformer model with extra output + token(s) used to extract a latent vector. + """ def __init__( self, @@ -125,6 +129,9 @@ return h def views_to_tensor(...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/models/transmitter/multiview_encoder.py
Write docstrings for algorithm functions
from abc import ABC, abstractmethod from typing import Any, Dict, Optional, Tuple import torch.nn as nn from torch import torch from shap_e.models.renderer import Renderer from shap_e.util.collections import AttrDict from .bottleneck import latent_bottleneck_from_config, latent_warp_from_config from .params_proj imp...
--- +++ @@ -13,12 +13,20 @@ class Encoder(nn.Module, ABC): def __init__(self, *, device: torch.device, param_shapes: Dict[str, Tuple[int]]): + """ + Instantiate the encoder with information about the renderer's input + parameters. This information can be used to create output layers to + ...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/models/transmitter/base.py
Add structured docstrings to improve clarity
from abc import ABC, abstractmethod from dataclasses import dataclass from typing import Dict, Optional, Tuple import torch from shap_e.models.nn.meta import MetaModule from shap_e.models.nn.utils import ArrayType, safe_divide, to_torch @dataclass class VolumeRange: t0: torch.Tensor t1: torch.Tensor int...
--- +++ @@ -18,9 +18,18 @@ assert self.t0.shape == self.t1.shape == self.intersected.shape def next_t0(self): + """ + Given convex volume1 and volume2, where volume1 is contained in + volume2, this function returns the t0 at which rays leave volume1 and + intersect with volume...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/models/volume.py
Write documentation strings for class attributes
import argparse import json import math import os import random import sys import bpy from mathutils import Vector from mathutils.noise import random_unit_vector MAX_DEPTH = 5.0 FORMAT_VERSION = 6 # Set by main(), these constants are passed to the script to avoid # duplicating them across multiple files. UNIFORM_LI...
--- +++ @@ -1,3 +1,9 @@+""" +Script to run within blender. + +Provide arguments after `--`. +For example: `blender -b -P blender_script.py -- --help` +""" import argparse import json @@ -267,6 +273,11 @@ def setup_material_extraction_shaders(capturing_material_alpha: bool): + """ + Change every material t...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/rendering/blender/blender_script.py
Create simple docstrings for beginners
# Mobile Verification Toolkit (MVT) # Copyright (c) 2021-2023 The MVT Authors. # Use of this software is governed by the MVT License 1.1 that can be found at # https://license.mvt.re/1.1/ import io import json import tarfile import zlib from cryptography.hazmat.primitives import hashes, padding from cryptography.ha...
--- +++ @@ -18,6 +18,7 @@ class AndroidBackupParsingError(Exception): + """Exception raised file parsing an android backup file""" class AndroidBackupNotImplemented(AndroidBackupParsingError): @@ -44,6 +45,11 @@ def parse_ab_header(data): + """ + Parse the header of an Android Backup file + Ret...
https://raw.githubusercontent.com/mvt-project/mvt/HEAD/src/mvt/android/parsers/backup.py
Add docstrings to improve collaboration
import random from collections import defaultdict from dataclasses import dataclass from typing import BinaryIO, Dict, List, Optional, Union import blobfile as bf import numpy as np from shap_e.rendering.view_data import ViewData from .ply_util import write_ply COLORS = frozenset(["R", "G", "B", "A"]) def preproc...
--- +++ @@ -21,12 +21,28 @@ @dataclass class PointCloud: + """ + An array of points sampled on a surface. Each point may have zero or more + channel attributes. + + :param coords: an [N x 3] array of point coordinates. + :param channels: a dict mapping names to [N] arrays of channel values. + """ ...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/rendering/point_cloud.py
Add detailed documentation for each class
import random from typing import Any, List, Optional, Union import blobfile as bf import numpy as np import torch import torch.nn.functional as F from PIL import Image def center_crop( img: Union[Image.Image, torch.Tensor, np.ndarray] ) -> Union[Image.Image, torch.Tensor, np.ndarray]: if isinstance(img, (np....
--- +++ @@ -11,6 +11,9 @@ def center_crop( img: Union[Image.Image, torch.Tensor, np.ndarray] ) -> Union[Image.Image, torch.Tensor, np.ndarray]: + """ + Center crops an image. + """ if isinstance(img, (np.ndarray, torch.Tensor)): height, width = img.shape[:2] else: @@ -33,6 +36,10 @@ ...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/util/image_util.py
Add docstrings to my Python code
from collections import OrderedDict from typing import Any, Callable, Dict, List, Optional from typing import OrderedDict, Generic, TypeVar K = TypeVar('K') V = TypeVar('V') class AttrDict(OrderedDict[K, V], Generic[K, V]): MARKER = object() # pylint: disable=super-init-not-called def __init__(self, *ar...
--- +++ @@ -6,6 +6,11 @@ V = TypeVar('V') class AttrDict(OrderedDict[K, V], Generic[K, V]): + """ + An attribute dictionary that automatically handles nested keys joined by "/". + + Originally copied from: https://stackoverflow.com/questions/3031219/recursively-access-dict-via-attributes-as-well-as-index-ac...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/util/collections.py
Create docstrings for all classes and functions
# 不想用 Sphinx,也不像弄一堆静态html文件,所以自己写个咯 import os import sys import re def search_code(py_file_name, section_idx): with open('../' + py_file_name, encoding='utf-8', mode="r") as f: content = f.readlines() content_new, i, search_idx, idx_first_match = [], 0, 0, None while i < len(content) and search...
--- +++ @@ -1,6 +1,17 @@ # 不想用 Sphinx,也不像弄一堆静态html文件,所以自己写个咯 +''' +需要从readme中解析出: +1. "-> Demo code: [examples/demo_pso.py](examples/demo_pso.py)" +2. 三个```python为开头,三个 ``` 为结尾 +3. 从py文件中读出文本,并替换 +4. 前几行是求star,只在readme中出现 + + +需要从py文件中解析出: +1. # %% 做断点后赋予index值,然后插入readme +''' import os import sys @@ -8,6 +19,1...
https://raw.githubusercontent.com/guofei9987/blind_watermark/HEAD/docs/make_doc.py
Fill in missing docstrings in my code
# Mobile Verification Toolkit (MVT) # Copyright (c) 2021-2023 The MVT Authors. # Use of this software is governed by the MVT License 1.1 that can be found at # https://license.mvt.re/1.1/ import glob import logging import os import shutil import sqlite3 import subprocess from typing import Iterator, Optional, Union ...
--- +++ @@ -15,6 +15,8 @@ class IOSExtraction(MVTModule): + """This class provides a base for all iOS filesystem/backup extraction + modules.""" def __init__( self, @@ -40,6 +42,11 @@ def _recover_sqlite_db_if_needed( self, file_path: str, forced: bool = False ) -> None: + ...
https://raw.githubusercontent.com/mvt-project/mvt/HEAD/src/mvt/ios/modules/base.py
Help me document legacy Python code
from dataclasses import dataclass, field from typing import Dict, Optional import torch from .mesh import TriMesh @dataclass class TorchMesh: # [N x 3] array of vertex coordinates. verts: torch.Tensor # [M x 3] array of triangles, pointing to indices in verts. faces: torch.Tensor # Extra data...
--- +++ @@ -8,6 +8,9 @@ @dataclass class TorchMesh: + """ + A 3D triangle mesh with optional data at the vertices and faces. + """ # [N x 3] array of vertex coordinates. verts: torch.Tensor @@ -20,6 +23,9 @@ face_channels: Optional[Dict[str, torch.Tensor]] = field(default_factory=dict) ...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/rendering/torch_mesh.py
Write docstrings describing each step
from dataclasses import dataclass from typing import Iterable, Optional import numpy as np import torch import shap_e.rendering.mesh from ._utils import cross_product, normalize @dataclass class Rays: origins: torch.Tensor # [N x 3] float tensor directions: torch.Tensor # [N x 3] float tensor def n...
--- +++ @@ -11,6 +11,9 @@ @dataclass class Rays: + """ + A ray in ray casting. + """ origins: torch.Tensor # [N x 3] float tensor directions: torch.Tensor # [N x 3] float tensor @@ -21,6 +24,9 @@ @dataclass class RayCollisions: + """ + The result of casting N rays onto a mesh. + ""...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/rendering/raycast/types.py
Write docstrings for algorithm functions
import copy import inspect from typing import Any, Callable, List, Sequence, Tuple, Union import numpy as np import torch from pytorch3d.renderer import ( BlendParams, DirectionalLights, FoVPerspectiveCameras, MeshRasterizer, MeshRenderer, RasterizationSettings, SoftPhongShader, Texture...
--- +++ @@ -211,6 +211,10 @@ diffuse_color: Union[float, Tuple[float]] = BASIC_DIFFUSE_COLOR, specular_color: Union[float, Tuple[float]] = 0.0, ) -> "BidirectionalLights": + """ + Create a light that attempts to match the light used by the Blender + renderer when run with `--light_mode basic`. + "...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/rendering/pytorch3d_util.py
Generate docstrings for script automation
from abc import ABC, abstractmethod from dataclasses import dataclass from typing import Dict, List, Tuple import numpy as np @dataclass class Camera(ABC): @abstractmethod def image_coords(self) -> np.ndarray: @abstractmethod def camera_rays(self, coords: np.ndarray) -> np.ndarray: def depth_d...
--- +++ @@ -7,29 +7,72 @@ @dataclass class Camera(ABC): + """ + An object describing how a camera corresponds to pixels in an image. + """ @abstractmethod def image_coords(self) -> np.ndarray: + """ + :return: ([self.height, self.width, 2]).reshape(self.height * self.width, 2) imag...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/rendering/view_data.py
Help me document legacy Python code
from abc import abstractmethod from typing import Any, Dict, Iterable, List, Optional, Tuple, Union import numpy as np import torch.distributed as dist import torch.nn as nn import torch.nn.functional as F from PIL import Image from torch import torch from shap_e.models.generation.perceiver import SimplePerceiver fro...
--- +++ @@ -19,6 +19,10 @@ class PointCloudTransformerEncoder(VectorEncoder): + """ + Encode point clouds using a transformer model with an extra output + token used to extract a latent vector. + """ def __init__( self, @@ -84,6 +88,10 @@ class PerceiverEncoder(VectorEncoder): + "...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/models/transmitter/pc_encoder.py
Add docstrings for production code
from typing import Iterable, List, Optional, Union import numpy as np import torch import torch.nn as nn from PIL import Image from shap_e.models.download import default_cache_dir ImageType = Union[np.ndarray, torch.Tensor, Image.Image] class ImageCLIP(nn.Module): def __init__( self, device: t...
--- +++ @@ -11,6 +11,10 @@ class ImageCLIP(nn.Module): + """ + A wrapper around a pre-trained CLIP model that automatically handles + batches of texts, images, and embeddings. + """ def __init__( self, @@ -67,6 +71,15 @@ texts: Optional[Iterable[Optional[str]]] = None, e...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/models/generation/pretrained_clip.py
Add docstrings to meet PEP guidelines
from dataclasses import dataclass, field from typing import BinaryIO, Dict, Optional, Union import blobfile as bf import numpy as np from .ply_util import write_ply @dataclass class TriMesh: # [N x 3] array of vertex coordinates. verts: np.ndarray # [M x 3] array of triangles, pointing to indices in v...
--- +++ @@ -9,6 +9,9 @@ @dataclass class TriMesh: + """ + A 3D triangle mesh with optional data at the vertices and faces. + """ # [N x 3] array of vertex coordinates. verts: np.ndarray @@ -25,6 +28,9 @@ @classmethod def load(cls, f: Union[str, BinaryIO]) -> "TriMesh": + """ + ...
https://raw.githubusercontent.com/openai/shap-e/HEAD/shap_e/rendering/mesh.py
Write docstrings describing each step
from __future__ import annotations import functools, math, re, typing import psutil, pydantic from pydantic import BeforeValidator from typing_extensions import override from openllm.common import BentoInfo, DeploymentTarget, output, Accelerator def parse_memory_string(v: typing.Any) -> typing.Any: if isinstance(...
--- +++ @@ -9,6 +9,7 @@ def parse_memory_string(v: typing.Any) -> typing.Any: + """Parse memory strings like "60Gi" into float.""" if isinstance(v, str): match = re.match(r'(\d+(\.\d+)?)\s*Gi$', v, re.IGNORECASE) if match: @@ -114,6 +115,9 @@ @functools.lru_cache(typed=True) def can_run(bento: Bent...
https://raw.githubusercontent.com/bentoml/OpenLLM/HEAD/src/openllm/accelerator_spec.py
Add detailed docstrings explaining each function
# 2021.06.15-Changed for implementation of TNT model # Huawei Technologies Co., Ltd. <foss@huawei.com> import torch import torch.nn as nn from functools import partial import math from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.models.helpers import load_pretrained from timm.mode...
--- +++ @@ -115,6 +115,8 @@ class Block(nn.Module): + """ TNT Block + """ def __init__(self, outer_dim, inner_dim, outer_num_heads, inner_num_heads, num_words, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU, norm_lay...
https://raw.githubusercontent.com/xmu-xiaoma666/External-Attention-pytorch/HEAD/model/backbone/TnT.py
Add docstrings for utility scripts
# Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the CC-by-NC license found in the # LICENSE file in the root directory of this source tree. # import torch import torch.nn as nn from functools import partial import torch.nn.functional as F from timm.models.hel...
--- +++ @@ -5,6 +5,9 @@ # LICENSE file in the root directory of this source tree. # +'''These modules are adapted from those of timm, see +https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py +''' import torch import torch.nn as nn @@ -231,6 +234,8 @@ class Patc...
https://raw.githubusercontent.com/xmu-xiaoma666/External-Attention-pytorch/HEAD/model/backbone/ConViT.py
Generate docstrings with examples
# -------------------------------------------------------- # Adopted from Swin Transformer # Modified by Krushi Patel # -------------------------------------------------------- import torch import torch.nn as nn import torch.utils.checkpoint as checkpoint from timm.models.layers import DropPath, to_2tuple, trunc_norm...
--- +++ @@ -30,6 +30,14 @@ def window_partition(x, window_size): + """ + Args: + x: (B, H, W, C) + window_size (int): window size + + Returns: + windows: (num_windows*B, window_size, window_size, C) + """ B, H, W, C = x.shape x = x.view(B, H // window_size, window_size, W ...
https://raw.githubusercontent.com/xmu-xiaoma666/External-Attention-pytorch/HEAD/model/attention/MOATransformer.py
Generate docstrings for exported functions
# -------------------------------------------------------- # Swin Transformer V2 reimplementation # Copyright (c) 2021 Christoph Reich # Licensed under The MIT License [see LICENSE for details] # Written by Christoph Reich # -------------------------------------------------------- import logging import math from typing...
--- +++ @@ -1,3 +1,21 @@+""" Swin Transformer V2 +A PyTorch impl of : `Swin Transformer V2: Scaling Up Capacity and Resolution` + - https://arxiv.org/pdf/2111.09883 +Code adapted from https://github.com/ChristophReich1996/Swin-Transformer-V2, original copyright/license info below +This implementation is experimental...
https://raw.githubusercontent.com/xmu-xiaoma666/External-Attention-pytorch/HEAD/model/backbone/swin_transformer_v2_cr.py
Add docstrings for production code
import torch import torch.nn as nn from functools import partial import math from timm.models.vision_transformer import VisionTransformer, _cfg from timm.models.registry import register_model from timm.models.layers import trunc_normal_, DropPath, to_2tuple import pdb __all__ = [ 'deit_tiny_patch16_224', 'deit_sma...
--- +++ @@ -198,6 +198,8 @@ class PatchEmbed(nn.Module): # taken from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py + """ Image to Patch Embedding + """ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768): super().__...
https://raw.githubusercontent.com/xmu-xiaoma666/External-Attention-pytorch/HEAD/model/backbone/Container.py
Add concise docstrings to each method
import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.models.layers import DropPath, to_2tuple, trunc_normal_ from timm.models.registry import register_model from einops import rearrange from functools import partial from torch ...
--- +++ @@ -1,3 +1,8 @@+""" +CoaT architecture. + +Modified from timm/models/vision_transformer.py +""" import torch import torch.nn as nn @@ -33,6 +38,7 @@ class Mlp(nn.Module): + """ Feed-forward network (FFN, a.k.a. MLP) class. """ def __init__(self, in_features, hidden_features=None, out_features=N...
https://raw.githubusercontent.com/xmu-xiaoma666/External-Attention-pytorch/HEAD/model/backbone/CoaT.py
Add minimal docstrings for each function
# Copyright 2021 Sea Limited. # # 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 agreed to in writing,...
--- +++ @@ -11,6 +11,9 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +""" +Vision OutLOoker (VOLO) implementation +""" import torch import torch.nn as nn import torch.nn.functional...
https://raw.githubusercontent.com/xmu-xiaoma666/External-Attention-pytorch/HEAD/model/backbone/VOLO.py
Create docstrings for reusable components
import torch import torch.nn as nn from functools import partial import pickle from torch.nn.parameter import Parameter from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.models.helpers import load_pretrained from timm.models.layers import DropPath, to_2tuple, trunc_normal_ from timm.models.re...
--- +++ @@ -1,3 +1,6 @@+""" +Code for DeepViT. The implementation has heavy reference to timm. +""" import torch import torch.nn as nn from functools import partial @@ -65,6 +68,10 @@ x = self.proj_drop(x) return x, attn class ReAttention(nn.Module): + """ + It is observed that similarity al...
https://raw.githubusercontent.com/xmu-xiaoma666/External-Attention-pytorch/HEAD/model/backbone/DViT.py
Create Google-style docstrings for my code
import numpy as np import torch from torch import nn from torch.nn import init class MobileViTv2Attention(nn.Module): def __init__(self, d_model): super(MobileViTv2Attention, self).__init__() self.fc_i = nn.Linear(d_model,1) self.fc_k = nn.Linear(d_model, d_model) self.fc_v = nn....
--- +++ @@ -6,8 +6,17 @@ class MobileViTv2Attention(nn.Module): + ''' + Scaled dot-product attention + ''' def __init__(self, d_model): + ''' + :param d_model: Output dimensionality of the model + :param d_k: Dimensionality of queries and keys + :param d_v: Dimensionality...
https://raw.githubusercontent.com/xmu-xiaoma666/External-Attention-pytorch/HEAD/model/attention/MobileViTv2Attention.py
Create docstrings for each class method
import math from functools import partial import torch from torch import nn from torch.nn import functional as F class SwishImplementation(torch.autograd.Function): @staticmethod def forward(ctx, i): result = i * torch.sigmoid(i) ctx.save_for_backward(i) return result @staticmetho...
--- +++ @@ -24,6 +24,7 @@ def drop_connect(inputs, p, training): + """ Drop connect. """ if not training: return inputs batch_size = inputs.shape[0] keep_prob = 1 - p @@ -38,11 +39,15 @@ return partial(Conv2dStaticSamePadding, image_size=image_size) def get_width_and_height_from_size(x): +...
https://raw.githubusercontent.com/xmu-xiaoma666/External-Attention-pytorch/HEAD/model/conv/MBConv.py
Write reusable docstrings
import torch.nn as nn import torch.nn.functional as F import torch from einops.layers.torch import Rearrange from einops import rearrange import numpy as np from typing import Any, List import math import warnings from collections import OrderedDict __all__ = ['ConTBlock', 'ConTNet'] r""" The following trunc_norm...
--- +++ @@ -55,6 +55,22 @@ def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.): # type: (Tensor, float, float, float, float) -> Tensor + r"""Fills the input Tensor with values drawn from a truncated + normal distribution. The values are effectively drawn from the + normal distribution :math:`\mathca...
https://raw.githubusercontent.com/xmu-xiaoma666/External-Attention-pytorch/HEAD/model/backbone/ConTNet.py
Document helper functions with docstrings
# -------------------------------------------------------- # Swin Transformer # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import logging import math from typing import Optional import torch impo...
--- +++ @@ -1,3 +1,11 @@+""" Swin Transformer +A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` + - https://arxiv.org/pdf/2103.14030 +Code/weights from https://github.com/microsoft/Swin-Transformer, original copyright/license info below +S3 (AutoFormerV2, https://arxiv.or...
https://raw.githubusercontent.com/xmu-xiaoma666/External-Attention-pytorch/HEAD/model/backbone/swin_transformer.py
Generate NumPy-style docstrings
import numpy as np import torch from torch import nn from torch.nn import init class SimplifiedScaledDotProductAttention(nn.Module): def __init__(self, d_model, h,dropout=.1): super(SimplifiedScaledDotProductAttention, self).__init__() self.d_model = d_model self.d_k = d_model//h ...
--- +++ @@ -6,8 +6,17 @@ class SimplifiedScaledDotProductAttention(nn.Module): + ''' + Scaled dot-product attention + ''' def __init__(self, d_model, h,dropout=.1): + ''' + :param d_model: Output dimensionality of the model + :param d_k: Dimensionality of queries and keys + ...
https://raw.githubusercontent.com/xmu-xiaoma666/External-Attention-pytorch/HEAD/model/attention/SimplifiedSelfAttention.py
Add docstrings to incomplete code
# Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional as F from timm.models.layers import trunc_normal_, DropPath...
--- +++ @@ -11,6 +11,12 @@ from timm.models.layers import trunc_normal_, DropPath class Block(nn.Module): + """ ConvNeXtV2 Block. + + Args: + dim (int): Number of input channels. + drop_path (float): Stochastic depth rate. Default: 0.0 + """ def __init__(self, dim, drop_path=0.): ...
https://raw.githubusercontent.com/xmu-xiaoma666/External-Attention-pytorch/HEAD/model/backbone/convnextv2.py
Add minimal docstrings for each function
# -------------------------------------------------------- # Swin Transformer V2 # Copyright (c) 2022 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ze Liu # -------------------------------------------------------- import math from typing import Tuple, Optional import torch import to...
--- +++ @@ -1,3 +1,9 @@+""" Swin Transformer V2 +A PyTorch impl of : `Swin Transformer V2: Scaling Up Capacity and Resolution` + - https://arxiv.org/abs/2111.09883 +Code/weights from https://github.com/microsoft/Swin-Transformer, original copyright/license info below +Modifications and additions for timm hacked toge...
https://raw.githubusercontent.com/xmu-xiaoma666/External-Attention-pytorch/HEAD/model/backbone/swin_transformer_v2.py
Add documentation for all methods
from functools import partial from typing import List import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_INCEPTION_MEAN, IMAGENET_INCEPTION_STD from timm.layers import SelectAdaptivePool2d, Linear, create_conv2d, get_norm_act_...
--- +++ @@ -1,3 +1,8 @@+""" MobileNet V3 +A PyTorch impl of MobileNet-V3, compatible with TF weights from official impl. +Paper: Searching for MobileNetV3 - https://arxiv.org/abs/1905.02244 +Hacked together by / Copyright 2019, Ross Wightman +""" from functools import partial from typing import List @@ -100,6 +105,...
https://raw.githubusercontent.com/xmu-xiaoma666/External-Attention-pytorch/HEAD/model/backbone/MobileNetV3.py
Write docstrings for utility functions
import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from timm.models.layers import DropPath, to_2tuple, trunc_normal_ from timm.models.registry import register_model from timm.models.vision_transformer import _cfg from timm.models.vision_transformer import Block as TimmBloc...
--- +++ @@ -30,6 +30,9 @@ class GroupAttention(nn.Module): + """ + LSA: self attention within a group + """ def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., ws=1): assert ws != 1 super(GroupAttention, self).__init__() @@ -69,6 +72,9 @@ ...
https://raw.githubusercontent.com/xmu-xiaoma666/External-Attention-pytorch/HEAD/model/backbone/CPVT.py
Add verbose docstrings with examples
## Author: Jianyuan Guo (jyguo@pku.edu.cn) import math import logging from functools import partial from collections import OrderedDict import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.models.helpers import load_pretrained ...
--- +++ @@ -154,6 +154,8 @@ class PatchEmbed(nn.Module): + """ Image to Patch Embedding + """ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768): super().__init__() img_size = to_2tuple(img_size) @@ -372,6 +374,7 @@ def checkpoint_filter_fn(state_dict, model)...
https://raw.githubusercontent.com/xmu-xiaoma666/External-Attention-pytorch/HEAD/model/backbone/CMT.py
Include argument descriptions in docstrings
import math import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from timm.models.layers import DropPath, to_2tuple, trunc_normal_ from timm.models.registry import register_model from timm.models.vision_transformer import default_cfgs, _cfg __all__ = [ 'ceit_tiny_patch...
--- +++ @@ -201,6 +201,9 @@ class HybridEmbed(nn.Module): + """ CNN Feature Map Embedding + Extract feature map from CNN, flatten, project to embedding dim. + """ def __init__(self, backbone, img_size=224, patch_size=16, feature_size=None, in_chans=3, embed_dim=768): super().__init__() ...
https://raw.githubusercontent.com/xmu-xiaoma666/External-Attention-pytorch/HEAD/model/backbone/CeiT.py
Write docstrings including parameters and return values
import numpy as np import torch from torch import nn from torch.nn import init class ScaledDotProductAttention(nn.Module): def __init__(self, d_model, d_k, d_v, h,dropout=.1): super(ScaledDotProductAttention, self).__init__() self.fc_q = nn.Linear(d_model, h * d_k) self.fc_k = nn.Linear(...
--- +++ @@ -6,8 +6,17 @@ class ScaledDotProductAttention(nn.Module): + ''' + Scaled dot-product attention + ''' def __init__(self, d_model, d_k, d_v, h,dropout=.1): + ''' + :param d_model: Output dimensionality of the model + :param d_k: Dimensionality of queries and keys + ...
https://raw.githubusercontent.com/xmu-xiaoma666/External-Attention-pytorch/HEAD/model/attention/SelfAttention.py
Add docstrings to clarify complex logic
import os import copy import torch import torch.nn as nn from typing import Dict import itertools from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.models.layers import DropPath, trunc_normal_ from timm.models.registry import register_model from timm.models.layers.helpers import to_2tuple E...
--- +++ @@ -1,3 +1,6 @@+""" +EfficientFormer +""" import os import copy import torch @@ -94,6 +97,11 @@ class Embedding(nn.Module): + """ + Patch Embedding that is implemented by a layer of conv. + Input: tensor in shape [B, C, H, W] + Output: tensor in shape [B, C, H/stride, W/stride] + """ ...
https://raw.githubusercontent.com/xmu-xiaoma666/External-Attention-pytorch/HEAD/model/backbone/EfficientFormer.py
Write docstrings for data processing functions
# Copyright IBM All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import torch import torch.nn as nn import torch.nn.functional as F import torch.hub from functools import partial from timm.models.layers import DropPath, to_2tuple, trunc_normal_ from timm.models.registry import register_model from timm.mo...
--- +++ @@ -2,6 +2,10 @@ # SPDX-License-Identifier: Apache-2.0 +""" +Modifed from Timm. https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py + +""" import torch import torch.nn as nn @@ -30,6 +34,8 @@ class PatchEmbed(nn.Module): + """ Image to Patch Embedding +...
https://raw.githubusercontent.com/xmu-xiaoma666/External-Attention-pytorch/HEAD/model/backbone/CrossViT.py
Document this script properly
import torch import torch.nn as nn import torch.utils.checkpoint as checkpoint from timm.models.layers import DropPath, to_2tuple, trunc_normal_ class Mlp(nn.Module): def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): super().__init__() out_featur...
--- +++ @@ -62,6 +62,17 @@ return flops class Attention(nn.Module): + r""" Multi-head self attention module with dynamic position bias. + + Args: + dim (int): Number of input channels. + group_size (tuple[int]): The height and width of the group. + num_heads (int): Number of attent...
https://raw.githubusercontent.com/xmu-xiaoma666/External-Attention-pytorch/HEAD/model/attention/Crossformer.py
Generate docstrings for script automation
import requests import base64 import os import tempfile import git import time import fnmatch from typing import Union, Set, List, Dict, Tuple, Any from urllib.parse import urlparse def crawl_github_files( repo_url, token=None, max_file_size: int = 1 * 1024 * 1024, # 1 MB use_relative_paths: bool = ...
--- +++ @@ -16,6 +16,26 @@ include_patterns: Union[str, Set[str]] = None, exclude_patterns: Union[str, Set[str]] = None ): + """ + Crawl files from a specific path in a GitHub repository at a specific commit. + + Args: + repo_url (str): URL of the GitHub repository with specific path and commi...
https://raw.githubusercontent.com/The-Pocket/PocketFlow-Tutorial-Codebase-Knowledge/HEAD/utils/crawl_github_files.py
Add docstrings to existing functions
# this script is modified from https://github.com/MCG-NKU/AMT/blob/main/demos/demo_2x.py from json import load import os import cv2 import sys import glob import torch import argparse import numpy as np import os.path as osp from warnings import warn from omegaconf import OmegaConf from torchvision.utils import make_gr...
--- +++ @@ -34,6 +34,9 @@ def init(device="cuda"): + ''' + initialize the device and the anchor resolution. + ''' if device == 'cuda': anchor_resolution = 1024 * 512 @@ -52,6 +55,17 @@ def get_input_video_from_path(input_path, device="cuda"): + ''' + Get the input video fr...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/models/frame_interpolation/interpolation.py
Document my Python code with docstrings
import math from typing import TypeVar, Optional, Iterator import torch from torch.utils.data import Sampler, Dataset import torch.distributed as dist T_co = TypeVar('T_co', covariant=True) class CustomDistributedSampler(Sampler[T_co]): def __init__(self, dataset: Dataset, num_replicas: Optional[int] = None, ...
--- +++ @@ -7,6 +7,53 @@ T_co = TypeVar('T_co', covariant=True) class CustomDistributedSampler(Sampler[T_co]): + r"""Sampler that restricts data loading to a subset of the dataset. + + It is especially useful in conjunction with + :class:`torch.nn.parallel.DistributedDataParallel`. In such a case, each + ...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/models/causalvideovae/dataset/ddp_sampler.py
Add well-formatted docstrings
import torch import torch_npu import torch.distributed as dist import os try: from lcalib.functional import lcal_initialize enable_LCCL = True except: lcal_initialize = None enable_LCCL = False class COMM_INFO: def __init__(self): self.group = None self.world_size = 0 self.ra...
--- +++ @@ -31,6 +31,7 @@ return _SEQUENCE_PARALLEL_STATE def initialize_sequence_parallel_group(sequence_parallel_size): + """Initialize the sequence parallel group.""" rank = int(os.getenv('RANK', '0')) world_size = int(os.getenv("WORLD_SIZE", '1')) assert world_size % sequence_parallel_size ...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/acceleration/parallel_states.py
Generate docstrings with examples
import torch from einops import rearrange, repeat from typing import Any, Dict, Optional, Tuple import torch import torch.nn.functional as F from torch import nn from diffusers.models.attention_processor import Attention as Attention_ try: import torch_npu from opensora.npu_config import npu_config, set_run_dty...
--- +++ @@ -18,6 +18,7 @@ from opensora.utils.communications import all_to_all_SBH class PatchEmbed2D(nn.Module): + """2D Image to Patch Embedding but with video""" def __init__( self, @@ -41,6 +42,7 @@ class PositionGetter3D(object): + """ return positions of patches """ def __i...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/models/diffusion/common.py
Create documentation for each function signature
import os.path as osp import random from glob import glob from torchvision import transforms import numpy as np import torch import torch.utils.data as data import torch.nn.functional as F from torchvision.transforms import Lambda from ..dataset.transform import ToTensorVideo, CenterCropVideo from ..utils.dataset_uti...
--- +++ @@ -13,6 +13,20 @@ from ..utils.dataset_utils import DecordInit def TemporalRandomCrop(total_frames, size): + """ + Performs a random temporal crop on a video sequence. + + This function randomly selects a continuous frame sequence of length `size` from a video sequence. + `total_frames` indicate...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/models/causalvideovae/model/dataset_videobase.py
Generate NumPy-style docstrings
import torch import torch.nn as nn from torchvision import models from collections import namedtuple from .....utils.taming_download import get_ckpt_path class LPIPS(nn.Module): # Learned perceptual metric def __init__(self, use_dropout=True): super().__init__() self.scaling_layer = ScalingLay...
--- +++ @@ -1,3 +1,4 @@+"""Stripped version of https://github.com/richzhang/PerceptualSimilarity/tree/master/models""" import torch import torch.nn as nn @@ -62,6 +63,7 @@ class NetLinLayer(nn.Module): + """ A single linear layer which does a 1x1 conv """ def __init__(self, chn_in, chn_out=1, use_dropou...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/models/causalvideovae/model/losses/lpips.py
Generate docstrings for each module
import inspect from typing import Callable, Dict, List, Optional, Tuple, Union from dataclasses import dataclass import numpy as np import torch from einops import rearrange from transformers import CLIPTextModelWithProjection, CLIPTokenizer, CLIPImageProcessor, MT5Tokenizer, T5EncoderModel from diffusers.pipelines.s...
--- +++ @@ -34,6 +34,10 @@ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.rescale_noise_cfg def rescale_noise_cfg(noise_cfg, noise_pred_text, guidance_rescale=0.0): + """ + Rescale `noise_cfg` according to `guidance_rescale`. Based on findings of [Common Diffusion Noise Schedules ...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/sample/pipeline_opensora.py
Create documentation for each function signature
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team import os import re import stat import torch import hashlib from collections import defaultdict, OrderedDict, deque from shutil import copyfile import gc from torch.nn.modules import Module from torch.nn.parameter import Pa...
--- +++ @@ -140,6 +140,7 @@ class EngineTimers(object): + r"""Wallclock timers for DeepSpeedEngine""" def __init__(self, enable_micro_timers, enable_global_timers): self.forward_timers = [] @@ -174,6 +175,7 @@ class DeepSpeedEngine(Module): + r"""DeepSpeed engine for training.""" de...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/adaptor/engine.py
Document my Python code with docstrings
import torch import random import numbers from torchvision.transforms import RandomCrop, RandomResizedCrop import statistics import numpy as np import ftfy import regex as re import html def _is_tensor_video_clip(clip): if not torch.is_tensor(clip): raise TypeError("clip should be Tensor. Got %s" % type(c...
--- +++ @@ -20,6 +20,10 @@ def center_crop_arr(pil_image, image_size): + """ + Center cropping implementation from ADM. + https://github.com/openai/guided-diffusion/blob/8fb3ad9197f16bbc40620447b2742e13458d2831/guided_diffusion/image_datasets.py#L126 + """ while min(*pil_image.size) >= 2 * image_si...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/dataset/transform.py
Write beginner-friendly docstrings
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team import torch import os import pdb from deepspeed import comm as dist from packaging import version as pkg_version from collections import OrderedDict from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors ...
--- +++ @@ -119,6 +119,16 @@ class DeepSpeedZeroOptimizer(ZeROOptimizer): + """ + DeepSpeedZeroOptimizer designed to reduce the memory footprint + required for training large deep learning models. + + For more details please see ZeRO: Memory Optimization Towards Training A Trillion Parameter Models + ...
https://raw.githubusercontent.com/PKU-YuanGroup/Open-Sora-Plan/HEAD/opensora/adaptor/stage_1_and_2.py