instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Generate docstrings for this script
import glob import os from typing import Dict, List, Union import torch from diffusers.utils import is_safetensors_available from huggingface_hub.constants import HF_HUB_CACHE if is_safetensors_available(): import safetensors.torch from huggingface_hub import snapshot_download from diffusers import DiffusionPi...
--- +++ @@ -22,6 +22,25 @@ class CheckpointMergerPipeline(DiffusionPipeline): + """ + A class that supports merging diffusion models based on the discussion here: + https://github.com/huggingface/diffusers/issues/877 + + Example usage:- + + pipe = DiffusionPipeline.from_pretrained("CompVis/stable-dif...
https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/scripts/tool.py
Create documentation for each function signature
# 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 warnings import numpy as np import torch from PIL import Image def get_sdpa_settings(): if torch.cuda.is_ava...
--- +++ @@ -42,6 +42,15 @@ def mask_to_box(masks: torch.Tensor): + """ + compute bounding box given an input mask + + Inputs: + - masks: [B, 1, H, W] boxes, dtype=torch.Tensor + + Returns: + - box_coords: [B, 1, 4], contains (x, y) coordinates of top left and bottom right box corners, dtype=torch....
https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/segment_anything2/utils/misc.py
Generate docstrings with parameter types
# 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 from torchvision.transforms import Normalize, Resize, ToTensor class SAM2Transforms(n...
--- +++ @@ -13,6 +13,9 @@ def __init__( self, resolution, mask_threshold, max_hole_area=0.0, max_sprinkle_area=0.0 ): + """ + Transforms for SAM2. + """ super().__init__() self.resolution = resolution self.mask_threshold = mask_threshold @@ -40,6 +43,13 ...
https://raw.githubusercontent.com/Sanster/IOPaint/HEAD/iopaint/plugins/segment_anything2/utils/transforms.py
Add minimal docstrings for each function
import os import sys import re import ctypes import subprocess from pathlib import Path import cutlass CUTE_DSL_PTXAS_PATH = os.environ.get("CUTE_DSL_PTXAS_PATH", None) VERBOSE = os.environ.get("CUTE_DSL_PTXAS_VERBOSE", "0") == "1" _original_load_cuda_library = None _user_wanted_ptx = False # True if user origina...
--- +++ @@ -1,3 +1,9 @@+""" +System ptxas replacement for CUTLASS DSL. +Environment variables: + CUTE_DSL_PTXAS_PATH - Path to ptxas (e.g., /usr/local/cuda/bin/ptxas) + CUTE_DSL_PTXAS_VERBOSE - Set to 1 for verbose output +""" import os import sys @@ -22,6 +28,7 @@ def _get_ptx(compiled_func) -> tuple[...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/cute/cute_dsl_ptxas.py
Create docstrings for each class method
#!/usr/bin/env python import argparse import time import torch import torch.nn.functional as F from flash_attn.cute.interface import _flash_attn_fwd, _flash_attn_bwd # ── Helpers ──────────────────────────────────────────────────────────────── def parse_int_k(s): s = s.strip().lower() if s.endswith("k"): ...
--- +++ @@ -1,4 +1,37 @@ #!/usr/bin/env python +"""Unified SM90 benchmark for forward and backward passes. + +Usage: + # Default: bench fwd+bwd for hdim 64,96,128 at seqlen 8192 + python benchmarks/bench_sm90.py + + # Forward only, specific hdims + python benchmarks/bench_sm90.py --direction fwd --hdim 64,9...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/benchmarks/bench_sm90.py
Auto-generate documentation strings for this file
# Copyright (c) 2025, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao. # A reimplementation of https://github.com/Dao-AILab/flash-attention/blob/main/hopper/flash_bwd_postprocess_kernel.h # from Cutlass C++ to Cute-DSL. import math from typing import Callable, Optional, Type import cuda....
--- +++ @@ -44,6 +44,12 @@ use_2cta_instrs: bool = False, cluster_size: int = 1, # for varlen offsets ): + """ + :param head_dim: head dimension + :type head_dim: int + :param tile_m: m block size + :type tile_m: int + """ self.dtype = dtype ...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/cute/flash_bwd_postprocess.py
Write reusable docstrings
# Copyright (c) 2025, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao. from typing import Tuple, Optional from dataclasses import dataclass import cutlass import cutlass.cute as cute from cutlass import Int32, const_expr from flash_attn.cute.seqlen_info import SeqlenInfoQK, SeqlenInfoQK...
--- +++ @@ -78,6 +78,11 @@ split_idx: Int32 = 0, num_splits: Int32 = 1, ) -> Tuple[Int32, Int32]: + """Get the block range for new K tokens (append KV). + + First computes the full n_block range via get_n_block_min_max, then maps + those blocks into the new-K index space by su...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/cute/block_info.py
Add clean documentation to messy code
import math import torch try: import cudnn except ImportError: cudnn = None # ── FLOPS calculation ──────────────────────────────────────────────────────── def flops( batch, nheads, seqlen_q, seqlen_k, headdim, headdim_v, causal=False, window_size=(None, None) ): if causal: avg_seqlen = (m...
--- +++ @@ -1,3 +1,4 @@+"""Shared benchmark utilities: attention_ref, cuDNN helpers, flops calculation.""" import math import torch @@ -43,6 +44,12 @@ def attention_ref(q, k, v, causal=False): + """Standard attention reference implementation. + + Args: + q, k, v: (batch, seqlen, nheads, headdim) te...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/cute/bench_utils.py
Expand my code with proper documentation strings
# Copyright (c) 2025, Tri Dao. import logging import os import sys import cutlass.cute as cute from cutlass import const_expr _LOG_LEVEL_NAMES = {"off": 0, "host": 1, "kernel": 2, "max": 3} def _parse_log_level(raw: str) -> int: if raw in _LOG_LEVEL_NAMES: return _LOG_LEVEL_NAMES[raw] try: ...
--- +++ @@ -1,5 +1,29 @@ # Copyright (c) 2025, Tri Dao. +"""Unified FlashAttention logging controlled by a single ``FA_LOG_LEVEL`` env var. + +Host-side messages go through Python ``logging`` (logger name ``flash_attn``). +A default ``StreamHandler`` is attached automatically when ``FA_LOG_LEVEL >= 1`` +so that stand...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/cute/fa_logging.py
Annotate my code with docstrings
from typing import Callable, NamedTuple, Tuple import cutlass.cute as cute import torch from flash_attn.cute.cute_dsl_utils import get_broadcast_dims, to_cute_tensor def ceildiv(a: int, b: int) -> int: return (a + b - 1) // b class BlockSparseTensors(NamedTuple): mask_block_cnt: cute.Tensor mask_bloc...
--- +++ @@ -1,3 +1,6 @@+""" +Block-sparsity utilities for FlexAttention +""" from typing import Callable, NamedTuple, Tuple @@ -38,6 +41,7 @@ context: str | None, hint: str | Callable[[], str] | None, ) -> torch.Tensor: + """Check if we need to expand the tensor to expected shape, and do so if possibl...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/cute/block_sparsity.py
Write docstrings describing functionality
# Copyright (c) 2025, Tri Dao. import os import pathlib from typing import Tuple from functools import partial, lru_cache from dataclasses import dataclass, fields import torch try: from triton.tools.disasm import extract except ImportError: extract = None import cutlass import cutlass.cute as cute from cut...
--- +++ @@ -85,6 +85,7 @@ def cute_compile_patched(*args, **kwargs): + """A patched version of cute.compile that dump the SASS to a file if CUTE_CUBIN_PATH is set.""" cubin_path = os.getenv("CUTE_CUBIN_PATH", None) if cubin_path is not None: cutlass.base_dsl.runtime.cuda.load_cubin_module_data...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/cute/cute_dsl_utils.py
Write docstrings for utility functions
from typing import Callable, Optional from functools import partial import math import cutlass import cutlass.cute as cute from cutlass import Float32, Int32, const_expr from quack import copy_utils # Import data structures from block_sparsity from flash_attn.cute.block_sparsity import BlockSparseTensors from flash_...
--- +++ @@ -1,3 +1,9 @@+""" +Block-sparse runtime utilities for CUTE DSL kernels. + +This module contains runtime execution functions for block-sparse attention kernels. +These utilities are used by CUTE DSL kernels to produce and consume block-sparse loads. +""" from typing import Callable, Optional from functools...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/cute/block_sparse_utils.py
Generate docstrings with examples
# Adapted from https://github.com/mlcommons/training_results_v1.1/blob/main/NVIDIA/benchmarks/bert/implementations/pytorch/padding.py import torch import torch.nn.functional as F from einops import rearrange, repeat class IndexFirstAxis(torch.autograd.Function): @staticmethod def forward(ctx, input, indices)...
--- +++ @@ -96,6 +96,18 @@ def unpad_input(hidden_states, attention_mask, unused_mask=None): + """ + Arguments: + hidden_states: (batch, seqlen, ...) + attention_mask: (batch, seqlen), bool / int, 1 means valid and 0 means not valid. + unused_mask: (batch, seqlen), bool / int, 1 means the...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/bert_padding.py
Write beginner-friendly docstrings
# Copyright (c) 2025, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao. # A reimplementation of https://github.com/Dao-AILab/flash-attention/blob/main/hopper/mainloop_bwd_sm80.hpp # from Cutlass C++ to Cute-DSL. import math from types import SimpleNamespace from typing import Type, Callabl...
--- +++ @@ -47,6 +47,21 @@ AtomLayoutMdQ: int = 1, V_in_regs: bool = False, ): + """Initializes the configuration for a flash attention v2 kernel. + + All contiguous dimensions must be at least 16 bytes aligned which indicates the head dimension + should be a multiple of 8. + ...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/cute/flash_bwd.py
Improve documentation using docstrings
# Manage Ahead-of-Time (AOT) compiled kernels import fcntl import hashlib import logging import os import pickle import sys import tempfile import time from functools import lru_cache from getpass import getuser from pathlib import Path from typing import Hashable, TypeAlias import ctypes import cutlass import cutlas...
--- +++ @@ -57,6 +57,16 @@ @lru_cache(maxsize=1) def _compute_source_fingerprint() -> str: + """ + Hash all CuTe Python sources plus runtime ABI stamps into a short fingerprint. + + The fingerprint changes whenever: + - Any .py file under flash_attn/cute is added, removed, renamed, or modified. + - Th...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/cute/cache_utils.py
Add documentation for all methods
# Copyright (c) 2025, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao. # A reimplementation of https://github.com/Dao-AILab/flash-attention/blob/main/hopper/flash_bwd_preprocess_kernel.h # from Cutlass C++ to Cute-DSL. # # Computes D_i = (dO_i * O_i).sum(dim=-1), optionally adjusted for L...
--- +++ @@ -44,6 +44,17 @@ tile_m: int = 128, num_threads: int = 256, ): + """ + All contiguous dimensions must be at least 16 bytes aligned which indicates the head dimension + should be a multiple of 8. + + :param head_dim: head dimension + :type head_dim: int ...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/cute/flash_bwd_preprocess.py
Annotate my code with docstrings
import argparse import time import torch try: import cudnn except ImportError: cudnn = None from einops import rearrange from flash_attn.cute.bench_utils import ( flops, attention_ref, cudnn_fwd_setup, cudnn_bwd_setup, ) try: from flash_attn.flash_attn_interface import flash_attn_func, flash_att...
--- +++ @@ -41,6 +41,13 @@ # ── Autograd backward helper ──────────────────────────────────────────────── def _make_bwd_fn(fwd_fn, g, inputs): + """Run fwd once, return a closure that benchmarks backward. + + Args: + fwd_fn: zero-arg callable that runs the forward pass (with autograd). + g: gradi...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/benchmarks/benchmark_attn.py
Add docstrings to incomplete code
# Copyright (c) 2025, Ted Zadouri, Markus Hoehnerbach, Jay Shah, Tri Dao. import math from typing import Callable, Optional from functools import partial import cuda.bindings.driver as cuda import cutlass import cutlass.cute as cute from cutlass.cute import FastDivmodDivisor from cutlass import Float32, Int32, Int64,...
--- +++ @@ -2757,6 +2757,7 @@ aux_tensors=None, fastdiv_mods=(None, None), ): + """Apply forward score modification for SM100 backward pass.""" # In bwd, S is computed as K @ Q.T so dimensions are (tile_n, tile_m) cS = cute.make_identity_tensor((self.tile_n, self.tile_m)) ...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/cute/flash_bwd_sm100.py
Add concise docstrings to each method
# Copyright (c) 2023, Tri Dao. import torch import torch.utils.benchmark as benchmark def benchmark_forward( fn, *inputs, repeats=10, desc="", verbose=True, amp=False, amp_dtype=torch.float16, **kwinputs ): if verbose: print(desc, "- Forward pass") def amp_wrapper(*inputs, **kwinputs): w...
--- +++ @@ -1,4 +1,5 @@ # Copyright (c) 2023, Tri Dao. +"""Useful functions for writing test code.""" import torch import torch.utils.benchmark as benchmark @@ -7,6 +8,7 @@ def benchmark_forward( fn, *inputs, repeats=10, desc="", verbose=True, amp=False, amp_dtype=torch.float16, **kwinputs ): + """Use Pyto...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/cute/benchmark.py
Create documentation for each function signature
# Copyright (c) 2025, Tri Dao import math from functools import partial from typing import Optional, Tuple, Union import torch from torch import Tensor from einops import rearrange, repeat from flash_attn.ops.triton.rotary import apply_rotary def rotate_half(x, interleaved=False): if not interleaved: x...
--- +++ @@ -21,6 +21,10 @@ def apply_rotary_emb_torch(x, cos, sin, interleaved=False): + """ + x: (batch_size, seqlen, nheads, headdim) + cos, sin: (seqlen, rotary_dim / 2) or (batch_size, seqlen, rotary_dim / 2) + """ ro_dim = cos.shape[-1] * 2 assert ro_dim <= x.shape[-1] cos = repeat(c...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/layers/rotary.py
Write docstrings including parameters and return values
# Adapted from https://github.com/mlcommons/training_results_v1.1/blob/main/NVIDIA/benchmarks/bert/implementations/pytorch/fmha.py import flash_attn_cuda import torch import torch.nn as nn def convert_blockmask(blockmask, causal): assert not causal # TD [2022-05-13]: The indexing and sorting is very tricky ...
--- +++ @@ -5,6 +5,18 @@ def convert_blockmask(blockmask, causal): + """Convert from the 0-1 format to the format used by the CUDA code. + 0 means the block is skipped. + nonzero means the block is not skipped. + Argument: + blockmask: (row, col): a 0-1 tensor + Return: + blockmask_conv...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/flash_blocksparse_attn_interface.py
Generate docstrings for each module
# Copyright (c) 2022, Tri Dao. # This BERT implementation is based on our MLPerf 2.0 and MLPerf 2.1 BERT implementation. # https://github.com/mlcommons/training_results_v2.0/blob/main/HazyResearch/benchmarks/bert/implementations/pytorch/modeling.py # https://github.com/mlcommons/training_results_v2.1/blob/main/Azure-Ha...
--- +++ @@ -158,6 +158,10 @@ ) def forward(self, hidden_states, key_padding_mask=None, subset_mask=None): + """If subset_mask is not None, we only want output for the subset of the sequence. + This means that we only compute the last layer output for these tokens. + subset_mask: (bat...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/models/bert.py
Add docstrings following best practices
# Copyright (c) 2025, Tri Dao. from typing import Optional, Callable, TypeAlias from dataclasses import dataclass import cutlass import cutlass.cute as cute from cutlass import Float32, Int32, Uint32, const_expr from quack import layout_utils import flash_attn.cute.utils as utils from flash_attn.cute.seqlen_info imp...
--- +++ @@ -17,12 +17,22 @@ @cute.jit def r2p_bitmask_below(limit: Int32, s: int) -> Uint32: + """32-bit R2P bitmask keeping positions < limit (exclusive upper bound). + + Positions 0..limit-1 in chunk `s` get bit=1 (keep), the rest bit=0 (mask). + Uses inline PTX to avoid shift-by-type-width UB. + """ ...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/cute/mask.py
Generate docstrings for exported functions
# Copyright (c) 2025, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao. # A reimplementation of https://github.com/Dao-AILab/flash-attention/blob/main/hopper/flash_fwd_combine_kernel.h # from Cutlass C++ to Cute-DSL. import math from typing import Type, Optional from functools import parti...
--- +++ @@ -30,6 +30,19 @@ num_threads: int = 256, stages: int = 4, ): + """ + Forward combine kernel for split attention computation. + + :param dtype: output data type + :param dtype_partial: partial accumulation data type + :param head_dim: head dimension + ...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/cute/flash_fwd_combine.py
Write clean docstrings for readability
# Copyright (c) 2025, Tri Dao. import cutlass import cutlass.cute as cute from quack import layout_utils import flash_attn.cute.utils as utils def pack_gqa_layout(T, qhead_per_kvhead, nheads_kv, head_idx): head_stride = T.stride[head_idx] shape_packed = ( (qhead_per_kvhead, T.shape[0]), *[T...
--- +++ @@ -9,6 +9,17 @@ def pack_gqa_layout(T, qhead_per_kvhead, nheads_kv, head_idx): + """Reshape a tensor to fold qhead_per_kvhead into the seqlen dimension (mode 0). + + The head dimension is at mode ``head_idx``. Modes before it (1..head_idx-1) + are kept as-is (e.g. headdim for Q/O tensors), and mo...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/cute/pack_gqa.py
Provide clean and structured docstrings
# Copyright (c) 2025, Tri Dao. # import math from typing import Optional from dataclasses import dataclass import cutlass.cute as cute from cutlass import Boolean, Int32, const_expr from cutlass.cutlass_dsl import if_generate, dsl_user_op from cutlass.pipeline import PipelineState from cutlass.pipeline import Pipelin...
--- +++ @@ -18,6 +18,11 @@ class PipelineStateSimple: + """ + Pipeline state contains an index and phase bit corresponding to the current position in the circular buffer. + Use a single Int32 to store both the index and phase bit, then we use divmod to get the + index and phase. If stages is a power of ...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/cute/pipeline.py
Add docstrings that explain purpose and usage
import math # H100 hardware limits SMEM_LIMIT = 224 * 1024 # 228 KB minus ~3 KB for LSE, dPsum, mbarriers REG_LIMITS = {2: 216, 3: 128} # per-WG budget: 2WG=240-24, 3WG=160-32 THREADS_PER_WG = 128 def _divisors(n): return [d for d in range(1, n + 1) if n % d == 0] def _acc_regs(M, N, num_wg): return M *...
--- +++ @@ -1,3 +1,13 @@+"""Search feasible SM90 fwd/bwd attention configs for given (head_dim, head_dim_v). + +Enumerates tile sizes, swap modes, atom layouts, and staging options. +Checks GMMA divisibility, register budget, and shared memory budget. + +Usage: + python flash_attn/cute/sm90_config_search.py --headdi...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/cute/sm90_config_search.py
Document functions with clear intent
import math import re from collections import OrderedDict import torch import torch.nn.functional as F from transformers import GPT2Config, GPTBigCodeConfig, PretrainedConfig def remap_state_dict_hf_bigcode(state_dict, config: PretrainedConfig): # Word embedding and position embedding def key_mapping_pos_em...
--- +++ @@ -8,6 +8,9 @@ def remap_state_dict_hf_bigcode(state_dict, config: PretrainedConfig): + """ + Map the state_dict of a Huggingface BigCode model to be flash_attn compatible. + """ # Word embedding and position embedding def key_mapping_pos_emb(key): @@ -107,6 +110,11 @@ def inv_rema...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/models/bigcode.py
Add docstrings for production code
# Copyright (c) 2025, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao. # [2025-07-04] Version in Cute-DSL, for Hopper and Blackwell. You'll need install nvidia-cutlass-dsl==4.2.0. # Supported features: # - BF16 & FP16 dtype # - noncausal & causal attention # - MHA, GQA, MQA # - hdim 64, ...
--- +++ @@ -70,6 +70,7 @@ ) def _parse_arch_str(arch_str): + """Parse arch string (e.g. 'sm_80', 'sm_90a', '80', '100') to int (e.g. 80, 90, 100).""" import re match = re.match(r"^(?:sm_?|SM_?)?(\d+)(\d)([af]?)$", arch_str) if not match: @@ -80,6 +81,16 @@ @lru_cache(maxsize=None) def _get_devic...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/cute/interface.py
Generate documentation strings for clarity
# Copyright (c) 2025, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao. # A reimplementation of # https://github.com/Dao-AILab/flash-attention/blob/main/hopper/flash_fwd_kernel_sm80.h # and https://github.com/Dao-AILab/flash-attention/blob/main/hopper/flash_fwd_kernel_sm90.h # from Cutlass...
--- +++ @@ -56,6 +56,25 @@ has_aux_tensors: bool = False, q_subtile_factor: int | None = None, ): + """Initializes the configuration for a flash attention kernel. + + All contiguous dimensions must be at least 16 bytes aligned, which means that the head dimension + should be a...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/cute/flash_fwd.py
Document all public functions with docstrings
# Copyright (c) 2025, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao. # SM90 (Hopper) forward pass for flash attention, extracted from flash_fwd.py. from types import SimpleNamespace from typing import Callable, Optional from functools import partial import cuda.bindings.driver as cuda...
--- +++ @@ -166,6 +166,11 @@ # Always keep stream as the last parameter (EnvStream: obtained implicitly via TVM FFI). stream: cuda.CUstream = None, ): + """Configures and launches the flash attention kernel. + + mQ/mK/mV/mO has same data types(supports fp16 and bf16) and same layout:...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/cute/flash_fwd_sm90.py
Add concise docstrings to each method
# Supported features: # - BF16 & FP16 dtype # - noncausal & causal attention # - MHA, GQA, MQA # - hdim 64, 96, 128, (192, 128). # - varlen # - sliding window # - split-kv # Unsupported features that will be added later: # - page size != 128 # - more hdim (192, 256) # Based on the cutlass example and cute-dsl example: ...
--- +++ @@ -241,6 +241,14 @@ self.buffer_align_bytes = 1024 def _setup_attributes(self): + """Set up configurations and parameters for the FMHA kernel operation. + + This method initializes and configures various attributes required for the + execution of the fused multi-head attenti...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/cute/flash_fwd_sm100.py
Add docstrings with type hints explained
# Copyright (c) 2024, Tri Dao. import logging import math import re from collections import OrderedDict, namedtuple from collections.abc import Sequence from functools import partial from typing import Dict, List import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange from tran...
--- +++ @@ -309,6 +309,9 @@ class GPTPreTrainedModel(nn.Module): + """An abstract class to handle weights initialization and + a simple interface for dowloading and loading pretrained models. + """ def __init__(self, config, *inputs, **kwargs): super().__init__() @@ -335,6 +338,10 @@ ...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/models/gpt.py
Add docstrings following best practices
# Adapted from https://github.com/facebookresearch/xformers/blob/main/xformers/triton/k_activations.py # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. # # This source code is licensed under the BSD license found in the # LICENSE file in the root directory of this source tree. import math from e...
--- +++ @@ -70,6 +70,11 @@ # ReLU @triton.jit def relu(x): + """ + ReLU_ activation function + + .. _ReLU: https://pytorch.org/docs/stable/generated/torch.nn.ReLU.html + """ zero = 0.0 return tl.where(x >= 0, x, zero.to(x.dtype)) @@ -86,6 +91,11 @@ @triton.jit def squared_relu(x): + """ ...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/ops/triton/k_activations.py
Document this module using docstrings
# Adapted from https://github.com/ELS-RD/kernl/blob/main/src/kernl/implementations/linear_layer.py # and https://github.com/openai/triton/blob/master/python/triton/ops/matmul.py from typing import Optional import torch import triton import triton.language as tl from triton.ops.matmul_perf_model import early_config_pru...
--- +++ @@ -165,6 +165,16 @@ ACTIVATION: tl.constexpr, ): + """ + Kernel for computing Out = activation(A x W + C) + - Input has shape (M, K) + - Weight has shape (K, N) + - Bias has shape (N,) + - Output has shape (M, N) + - ActInputs (optional) has shape (M, N) + 'ActInputs' optionally ...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/ops/triton/linear.py
Add detailed docstrings explaining each function
import math import hydra import torch import torch.nn as nn from einops import rearrange from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input from flash_attn.flash_blocksparse_attn_interface import ( convert_blockmask, flash_blocksparse_attn_func, ) class FlashBlocksparseAttention(nn...
--- +++ @@ -13,6 +13,15 @@ class FlashBlocksparseAttention(nn.Module): + """Implement the scaled dot product attention with softmax. + Arguments + --------- + softmax_temp: The temperature to use for the softmax attention. + (default: 1/sqrt(d_keys) where d_keys is computed at +...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/flash_blocksparse_attention.py
Add inline docstrings for readability
# Copyright (c) 2024, Tri Dao. import torch import torch.nn as nn from flash_attn.ops.triton.cross_entropy import cross_entropy_loss class CrossEntropyLoss(nn.Module): def __init__( self, ignore_index=-100, reduction="mean", label_smoothing=0.0, logit_scale=1.0, l...
--- +++ @@ -18,6 +18,20 @@ process_group=None, return_z_loss=False, ): + """ + Arguments: + ignore_index: int. If labels == ignore_index, the loss is set to 0.0. + label_smoothing: float + lse_square_scale: float. If > 0, we add lse_square_scale * lse...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/losses/cross_entropy.py
Can you add docstrings to this Python file?
# Copyright (c) 2025, Tri Dao. # Ported Cutlass code from C++ to Python: # https://github.com/NVIDIA/cutlass/blob/main/include/cute/arch/mma_sm100_desc.hpp # https://github.com/NVIDIA/cutlass/blob/main/include/cute/atom/mma_traits_sm100.hpp from enum import IntEnum import cutlass import cutlass.cute as cute # ------...
--- +++ @@ -66,6 +66,9 @@ def to_UMMA_format(cutlass_type) -> int: + """ + Map a CUTLASS scalar class to the 3-bit encoding for Matrix A/B. + """ if cutlass_type is cutlass.Int8: return S8Format.INT8 # Unsigned 8-bit (if available in your CUTLASS build) @@ -88,6 +91,9 @@ def to_C_for...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/cute/mma_sm100_desc.py
Add standardized docstrings across the file
from typing import Optional from dataclasses import dataclass import cutlass import cutlass.cute as cute from cutlass import Int32, const_expr from quack import copy_utils """ This consolidates all the info related to sequence length. This is so that we can do all the gmem reads once at the beginning of each tile, r...
--- +++ @@ -52,6 +52,7 @@ padded: cutlass.Constexpr[bool] = False, multiple: int = 1, ) -> cute.Tensor: + """Offset a tensor by batch index. batch dim is at position `dim`, seqlen is at dim=0.""" if const_expr(not self.has_cu_seqlens): idx = (None,) * dim + (batch_idx,...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/cute/seqlen_info.py
Generate NumPy-style docstrings
import math import torch import triton import triton.language as tl # Disabling autotune for now, set num_warps=4 if headdim=64 and num_warps=8 if headdim=128 # @triton.autotune( # configs=[ # triton.Config({"BLOCK_M": 128, "BLOCK_N": 128}, num_warps=4, num_stages=1), # # This config has a race ...
--- +++ @@ -1,3 +1,43 @@+""" +*Experimental* implementation of FlashAttention in Triton. +Tested with triton==2.0.0.dev20221202. +Triton 2.0 has a new backend (MLIR) but seems like it doesn't yet work for head dimensions +other than 64: +https://github.com/openai/triton/blob/d376020f90002757eea3ea9475d4f7cfc2ec5ead/pyt...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/flash_attn_triton.py
Write Python docstrings for this snippet
# Copyright (c) 2023, Tri Dao. # Adapted from https://github.com/NVIDIA/Megatron-LM/blob/0bb597b42c53355a567aba2a1357cc34b9d99ddd/megatron/text_generation/forward_step.py#L31 import gc import time from collections import namedtuple from dataclasses import dataclass, field from functools import partial from typing impor...
--- +++ @@ -22,6 +22,8 @@ @dataclass class InferenceParams: + """Inference parameters that are passed to the main model in order + to efficienly calculate and store the context during inference.""" max_seqlen: int max_batch_size: int @@ -41,6 +43,7 @@ # https://github.com/NVIDIA/Megatron-LM/blob/0b...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/utils/generation.py
Add concise docstrings to each method
# Copyright (c) 2023, Tri Dao. from typing import Optional, Sequence, Tuple, Union import torch import torch.nn as nn import os # isort: off # We need to import the CUDA kernels after importing torch USE_TRITON_ROCM = os.getenv("FLASH_ATTENTION_TRITON_AMD_ENABLE", "FALSE") == "TRUE" if USE_TRITON_ROCM: from aite...
--- +++ @@ -1016,6 +1016,40 @@ deterministic=False, return_attn_probs=False, ): + """dropout_p should be set to 0.0 during evaluation + If Q, K, V are already stacked into 1 tensor, this function will be faster than + calling flash_attn_func on Q, K, V since the backward pass avoids explicit concaten...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/flash_attn_interface.py
Add detailed documentation for each class
# Copyright (c) 2024, Tri Dao. from functools import partial from typing import Optional import torch import torch.nn as nn import torch.nn.functional as F from torch import Tensor from torchvision.ops import StochasticDepth from flash_attn.modules.mha import MHA from flash_attn.modules.mlp import Mlp try: from...
--- +++ @@ -37,6 +37,23 @@ sequence_parallel=False, mark_shared_params=False, ): + """ + For prenorm=True, this Block has a slightly different structure compared to a regular + prenorm Transformer block. + The standard block is: LN -> MHA -> Dropout -> Add -> LN -> MLP ...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/modules/block.py
Add standardized docstrings across the file
# Copyright (c) 2023, Tri Dao. import json import math import os import re from collections import OrderedDict from pathlib import Path from typing import Dict, List, Union import torch import torch.nn.functional as F from sentencepiece import SentencePieceProcessor from transformers import GPT2Config, LlamaConfig f...
--- +++ @@ -19,6 +19,10 @@ def remap_state_dict_meta_llama( state_dict: Dict[str, torch.Tensor], config: GPT2Config ) -> Dict[str, torch.Tensor]: + """Convert the state_dict in Meta format to standard GPT format. + + This function modifies state_dict in place. + """ def key_mapping_layers(key): ...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/models/llama.py
Generate NumPy-style docstrings
# Copyright (c) 2022, Tri Dao. # Inspired by / adapted from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py import math import re from collections import OrderedDict from copy import deepcopy from functools import partial import torch import torch.nn as nn import torch.n...
--- +++ @@ -95,6 +95,10 @@ class VisionTransformer(nn.Module): + """Vision Transformer + A PyTorch impl of : `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale` + - https://arxiv.org/abs/2010.11929 + """ def __init__( self, @@ -125,6 +129,29 @@ fused_...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/models/vit.py
Write documentation strings for class attributes
# Copyright (c) 2025, Tri Dao. import math import operator from typing import Tuple from dataclasses import dataclass import cutlass import cutlass.cute as cute from cutlass import Float32 from quack import layout_utils import flash_attn.cute.utils as utils from quack.cute_dsl_utils import ParamsBase from flash_attn...
--- +++ @@ -56,6 +56,13 @@ is_first: cutlass.Constexpr[bool] = False, check_inf: cutlass.Constexpr[bool] = True, ) -> cute.Tensor: + """Apply online softmax and return the row_scale to rescale O. + + :param acc_S: acc_S tensor + :type acc_S: cute.Tensor + :param is_firs...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/cute/softmax.py
Generate docstrings for each module
# Copyright (c) 2022, Tri Dao. import torch import torch.nn as nn from einops import rearrange from torch import Tensor from flash_attn.utils.distributed import all_reduce, reduce_scatter class GPT2Embeddings(nn.Module): def __init__( self, embed_dim, vocab_size, max_position_emb...
--- +++ @@ -19,6 +19,11 @@ device=None, dtype=None, ): + """ + If max_position_embeddings <= 0, there's no position embeddings + If word_embe_proj_dim is not None (e.g., OPT-350m), we embed to that dimension + the project up to embed_dim + """ factor...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/modules/embedding.py
Generate docstrings for each module
import subprocess from pathlib import Path from typing import List import matplotlib.pyplot as plt import seaborn as sn import torch import wandb from pytorch_lightning import Callback, Trainer from pytorch_lightning.loggers import LoggerCollection, WandbLogger from pytorch_lightning.utilities import rank_zero_only fr...
--- +++ @@ -14,6 +14,7 @@ def get_wandb_logger(trainer: Trainer) -> WandbLogger: + """Safely get Weights&Biases logger from Trainer.""" if trainer.fast_dev_run: raise Exception( @@ -34,6 +35,7 @@ class WatchModel(Callback): + """Make wandb watch model at the beginning of the run.""" ...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/training/src/callbacks/wandb_callbacks.py
Write clean docstrings for readability
# Copyright (c) 2023, Tri Dao. import math from functools import partial import torch import torch.nn as nn from einops import rearrange, repeat from flash_attn.utils.distributed import get_dim_for_local_rank try: from flash_attn import ( flash_attn_kvpacked_func, flash_attn_qkvpacked_func, ...
--- +++ @@ -51,6 +51,15 @@ class FlashSelfAttention(nn.Module): + """Implement the scaled dot product attention with softmax. + Arguments + --------- + softmax_scale: The temperature to use for the softmax attention. + (default: 1/sqrt(d_keys) where d_keys is computed at + ...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/modules/mha.py
Generate docstrings with parameter types
# Copyright (c) 2025, Tri Dao. import math import hashlib import inspect from typing import Type, Callable, Optional, Tuple, overload import cutlass import cutlass.cute as cute from cutlass import Float32, const_expr from cutlass.cute import FastDivmodDivisor from cutlass.cutlass_dsl import T, dsl_user_op from cutla...
--- +++ @@ -57,6 +57,7 @@ def _compute_base_hash(func: Callable) -> str: + """Compute hash from source code or bytecode and closure values.""" try: data = inspect.getsource(func).encode() except (OSError, TypeError): @@ -77,6 +78,12 @@ def hash_callable( func: Callable, mixer_attrs: Tuple...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/cute/utils.py
Write Python docstrings for this snippet
# The triton fused matmul + sqrelu is faster for fp16 but slower for bf16, compared # to naive implementation. import fused_dense_lib as fused_dense_cuda import torch import torch.nn as nn import torch.nn.functional as F from flash_attn.utils.torch import custom_fwd, custom_bwd from flash_attn.ops.activations import s...
--- +++ @@ -14,6 +14,11 @@ @staticmethod @custom_fwd def forward(ctx, x, weight1, bias1, weight2, bias2, checkpoint_lvl=0): + """checkpoint_lvl: + 0: no recomputation in the bwd + 1: recompute gelu_out in the bwd + 2: recompute act_input and gelu_out in the bwd + """ ...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/ops/triton/mlp.py
Help me add docstrings to my project
# Copied from https://github.com/stanford-crfm/mistral/blob/main/src/corpora/detokenization.py # Which was originally from https://github.com/NVIDIA/Megatron-LM/blob/aed2f75e209e525c842aec7c044af7acae2a4614/tasks/zeroshot_gpt/detokenizer.py import re def wikitext_detokenize(string: str) -> str: # Contractions ...
--- +++ @@ -1,10 +1,17 @@ # Copied from https://github.com/stanford-crfm/mistral/blob/main/src/corpora/detokenization.py # Which was originally from https://github.com/NVIDIA/Megatron-LM/blob/aed2f75e209e525c842aec7c044af7acae2a4614/tasks/zeroshot_gpt/detokenizer.py +""" +Handle detokenization for different dataset ...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/training/src/datamodules/datasets/detokenizer.py
Add concise docstrings to each method
# Adapted from https://github.com/PyTorchLightning/lightning-bolts/blob/master/pl_bolts/datamodules/imagenet_datamodule.py import os from pathlib import Path from typing import Any, List, Union, Callable, Optional import torch from torch.utils.data import Dataset, DataLoader, SequentialSampler from torch.utils.data.da...
--- +++ @@ -17,6 +17,10 @@ class DictDataset(Dataset): def __init__(self, dataset_dict, length=None): + """dataset_dict: dictionary mapping from index to batch + length is used in the case of DistributedSampler: e.g. the dataset could have size 1k, but + with 8 GPUs the dataset_dict would on...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/training/src/datamodules/imagenet.py
Create documentation strings for testing functions
from typing import Optional import torch from torch import Tensor from torch.distributed import ProcessGroup # `all_gather_into_tensor` and `reduce_scatter_tensor` are new placeholders for # `_all_gather_base` and `_reduce_scatter_base`. They require the most recent # version of PyTorch. The following 4 lines are for...
--- +++ @@ -47,6 +47,7 @@ class AllGatherFunc(torch.autograd.Function): + """Gather the input from sequence parallel region and concatenate.""" @staticmethod def forward(ctx, input_: Tensor, process_group: ProcessGroup) -> Tensor: @@ -65,6 +66,7 @@ class ReduceScatterFunc(torch.autograd.Function)...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/utils/distributed.py
Generate docstrings for script automation
# Copyright (c) 2022, Tri Dao. # Adapted from https://github.com/NVIDIA/apex/blob/master/apex/contrib/layer_norm/layer_norm.py import torch from torch.nn import init from flash_attn.ops.layer_norm import ( DropoutAddLayerNormFn, DropoutAddLayerNormParallelResidualFn, DropoutAddLayerNormSubsetFn, ) def r...
--- +++ @@ -30,6 +30,9 @@ residual_in_fp32=False, return_dropout_mask=False, ): + """residual_in_fp32 only has an effect if residual is None. + Otherwise residual dtype is residual.dtype. + """ return DropoutAddLayerNormFn.apply( x0, residual, @@ -62,6 +65,9 @@ residual_in_...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/ops/rms_norm.py
Write beginner-friendly docstrings
# Copyright (c) 2022, Tri Dao. # Adapted from https://github.com/NVIDIA/apex/blob/master/apex/contrib/layer_norm/layer_norm.py import dropout_layer_norm import torch from torch.nn import init def maybe_align(x, alignment_in_bytes=16): # TD [2023-07-04] I'm not 100% sure that clone will align the memory # htt...
--- +++ @@ -7,6 +7,7 @@ def maybe_align(x, alignment_in_bytes=16): + """Assume that x already has last dim divisible by alignment_in_bytes""" # TD [2023-07-04] I'm not 100% sure that clone will align the memory # https://discuss.pytorch.org/t/how-to-ensure-that-tensor-data-ptr-is-aligned-to-16-bytes/18...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/ops/layer_norm.py
Add docstrings that explain purpose and usage
from typing import Any, Dict, Optional import torch from torch import Tensor from torchmetrics import Metric class NumTokens(Metric): # TODO: how do we prevent the reset between the epochs? The reset happens on the 1st batch # of the next epoch. # Right now the hack is that we override reset(), which wo...
--- +++ @@ -7,6 +7,8 @@ class NumTokens(Metric): + """Keep track of how many tokens we've seen. + """ # TODO: how do we prevent the reset between the epochs? The reset happens on the 1st batch # of the next epoch. # Right now the hack is that we override reset(), which would mess up the forward...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/training/src/metrics/num_tokens.py
Add documentation for all methods
# Copyright (c) 2023, Tri Dao. # Inspired by https://github.com/NVIDIA/apex/blob/master/apex/fused_dense/fused_dense.py # We make it work with pytorch amp and with bfloat16. # The TensorParallel linear modules are inspired by https://github.com/NVIDIA/apex/blob/master/apex/transformer/tensor_parallel/layers.py from fun...
--- +++ @@ -30,6 +30,10 @@ def forward( ctx, x, weight, bias, return_residual=False, process_group=None, sequence_parallel=True ): + """ + If process_group is not None and sequence_parallel=True, we're doing Tensor Parallel + with sequence parallelism: we do an all_gather_raw of x...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/flash_attn/ops/fused_dense.py
Add concise docstrings to each method
# Inspired by https://github.com/NVIDIA/NeMo/blob/main/nemo/collections/common/metrics/perplexity.py # But we compute the perplexity correctly: exp(average(nll)), not average(exp(nll)) # Also adapted from https://github.com/Lightning-AI/metrics/blob/master/src/torchmetrics/text/perplexity.py # But we pass in the loss t...
--- +++ @@ -19,6 +19,21 @@ class Perplexity(Metric): + r""" + Perplexity measures how well a language model predicts a text sample. It's calculated as the average number of bits + per word a model needs to represent the sample. + Args: + kwargs: + Additional keyword arguments, see :ref...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/training/src/metrics/perplexity.py
Add docstrings to make code maintainable
# Copyright (c) 2024, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao. import sys import warnings import os import stat import re import shutil import ast from pathlib import Path from packaging.version import parse, Version import platform import sysconfig import tarfile import itertool...
--- +++ @@ -135,6 +135,20 @@ with_cuda, **kwargs, # kwargs (ignored) to absorb new flags in torch.utils.cpp_extension ) -> None: + r"""Write a ninja file that does the desired compiling and linking. + + `path`: Where to write this file + `cfl...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/hopper/setup.py
Create simple docstrings for beginners
# Copyright (c) 2023, Tri Dao. from typing import Optional, Union, List, Tuple import os import torch import torch.nn as nn USE_TRITON_ROCM = os.getenv("FLASH_ATTENTION_TRITON_AMD_ENABLE", "FALSE") == "TRUE" if USE_TRITON_ROCM: from aiter.ops.triton._triton_kernels.flash_attn_triton_amd import flash_attn_3 as f...
--- +++ @@ -179,6 +179,10 @@ pack_gqa: Optional[bool] = None, sm_margin: int = 0, ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Symbolic fake implementation of flash attention forward. + Returns tensors with the correct shapes and dtypes without actual computation. + ...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/hopper/flash_attn_interface.py
Create docstrings for API functions
# Copied from https://github.com/fadel/pytorch_ema/blob/master/torch_ema/ema.py from __future__ import division from __future__ import unicode_literals from typing import Iterable, Optional import weakref import copy import contextlib import torch def to_float_maybe(x): return x.float() if x.dtype in [torch.flo...
--- +++ @@ -17,6 +17,15 @@ # Partially based on: # https://github.com/tensorflow/tensorflow/blob/r1.13/tensorflow/python/training/moving_averages.py class ExponentialMovingAverage: + """ + Maintains (exponential) moving average of a set of parameters. + Args: + parameters: Iterable of `torch.nn.Parame...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/training/src/utils/ema.py
Help me add docstrings to my project
# Adapted from https://github.com/mlcommons/training_results_v1.1/blob/main/NVIDIA/benchmarks/bert/implementations/pytorch/padding.py import torch import torch.nn.functional as F from einops import rearrange def unpad_input(hidden_states, attention_mask, unused_mask=None): all_masks = (attention_mask + unused_ma...
--- +++ @@ -6,6 +6,18 @@ def unpad_input(hidden_states, attention_mask, unused_mask=None): + """ + Arguments: + hidden_states: (batch, seqlen, ...) + attention_mask: (batch, seqlen), bool / int, 1 means valid and 0 means not valid. + unused_mask: (batch, seqlen), bool / int, 1 means the e...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/hopper/padding.py
Document this code for team use
import logging import warnings from typing import List, Sequence import pytorch_lightning as pl import rich.syntax import rich.tree from omegaconf import DictConfig, OmegaConf from pytorch_lightning.utilities import rank_zero_only # Copied from https://docs.python.org/3/howto/logging-cookbook.html#using-a-context-ma...
--- +++ @@ -35,6 +35,7 @@ def get_logger(name=__name__) -> logging.Logger: + """Initializes multi-GPU-friendly python logger.""" logger = logging.getLogger(name) @@ -47,6 +48,14 @@ def extras(config: DictConfig) -> None: + """A couple of optional utilities, controlled by main config file: + - ...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/training/src/utils/utils.py
Add docstrings for internal functions
# Meant to work with Apex's DistributeFusedAdam from typing import Any, Callable, Dict, List, Optional, Union from pathlib import Path import types import torch from torch.optim.optimizer import Optimizer from torch.optim import LBFGS from apex.contrib.optimizers.distributed_fused_adam import DistributedFusedAdam f...
--- +++ @@ -62,6 +62,7 @@ return closure_result def clip_grad_by_norm(self, optimizer: DistributedFusedAdam, clip_val: Union[int, float]) -> None: + """Clip gradients by norm.""" # DistributedFusedAdam wants list, not generator # Gradients have not be scaled, so we need to scale ...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/training/src/utils/ddp_zero2.py
Generate docstrings for this script
# Meant to work with Pytorch's ZeroRedundancyOptimizer from typing import Any, Callable, Dict, List, Optional, Union from pathlib import Path import torch from torch.optim.optimizer import Optimizer from torch.distributed.optim import ZeroRedundancyOptimizer from pytorch_lightning.strategies.ddp import DDPStrategy f...
--- +++ @@ -60,6 +60,9 @@ class DDPStrategyZero1(DDPStrategy): + """To use ZeroRedundancyOptimizer, we need to shard the optimizer states when + saving/loading checkpoints. + """ strategy_name = "ddp_zero1" @@ -74,6 +77,12 @@ def save_checkpoint( self, checkpoint: Dict[str, Any], file...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/training/src/utils/ddp_zero1.py
Fully document this Python code with docstrings
# Copyright (c) 2023, Tri Dao. import sys import functools import warnings import os import re import ast import glob import shutil from pathlib import Path from typing import Literal, Optional from packaging.version import parse, Version import platform from setuptools import setup, find_packages import subprocess ...
--- +++ @@ -74,6 +74,9 @@ def get_platform(): + """ + Returns the platform name as used in wheel filenames. + """ if sys.platform.startswith("linux"): return f'linux_{platform.uname().machine}' elif sys.platform == "darwin": @@ -95,6 +98,14 @@ def add_cuda_gencodes(cc_flag, archs, ba...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/setup.py
Generate docstrings with parameter types
# Copied from https://github.com/NVIDIA/DeepLearningExamples/blob/master/PyTorch/LanguageModeling/Transformer-XL/pytorch/utils/distributed.py # Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in com...
--- +++ @@ -21,6 +21,11 @@ def init_distributed(cuda): + """ + Initializes distributed backend. + :param cuda: (bool) if True initializes nccl backend, if False initializes + gloo backend + """ world_size = int(os.environ.get('WORLD_SIZE', 1)) distributed = (world_size > 1) if dist...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/training/src/utils/distributed.py
Write docstrings describing functionality
# Inspired by https://github.com/PyTorchLightning/pytorch-lightning/blob/master/pytorch_lightning/callbacks/stochastic_weight_avg.py # https://github.com/PyTorchLightning/Lightning-Bolts/blob/master/pl_bolts/callbacks/byol_updates.py # https://forums.pytorchlightning.ai/t/adopting-exponential-moving-average-ema-for-pl-...
--- +++ @@ -14,7 +14,14 @@ class EMACallback(Callback): + """TD [2021-08-31]: saving and loading from checkpoint should work. + """ def __init__(self, decay: float, use_num_updates: bool = True): + """ + decay: The exponential decay. + use_num_updates: Whether to use number of update...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/training/src/callbacks/ema.py
Provide clean and structured docstrings
import math from typing import List, Tuple import torch import torchvision.transforms as T from PIL import Image, ImageOps from transformers import AutoProcessor, BatchFeature, LlamaTokenizerFast from transformers.processing_utils import ProcessorMixin from config import IMAGE_SIZE, BASE_SIZE, CROP_MODE, MIN_CROPS, MA...
--- +++ @@ -245,6 +245,24 @@ inference_mode: bool = True, **kwargs, ): + """ + + Args: + prompt (str): the formatted prompt; + conversations (List[Dict]): conversations with a list of messages; + images (List[ImageType]): the list of images; + ...
https://raw.githubusercontent.com/deepseek-ai/DeepSeek-OCR/HEAD/DeepSeek-OCR-master/DeepSeek-OCR-vllm/process/image_process.py
Write docstrings that follow conventions
from typing import List, Optional, Sequence from pathlib import Path import hydra from omegaconf import OmegaConf, DictConfig from pytorch_lightning import ( Callback, LightningDataModule, LightningModule, Trainer, seed_everything, ) from pytorch_lightning.loggers import LightningLoggerBase from s...
--- +++ @@ -18,6 +18,8 @@ def last_modification_time(path): + """Including files / directory 1-level below the path + """ path = Path(path) if path.is_file(): return path.stat().st_mtime @@ -28,6 +30,15 @@ def train(config: DictConfig) -> Optional[float]: + """Contains training pipel...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/training/src/train.py
Add missing documentation to my Python functions
# 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 typing import Optional, Tuple, Type from functool...
--- +++ @@ -94,6 +94,24 @@ window_size: int = 0, global_attn_indexes: Tuple[int, ...] = (), ) -> None: + """ + Args: + img_size (int): Input image size. + patch_size (int): Patch size. + in_chans (int): Number of input image channels. + emb...
https://raw.githubusercontent.com/deepseek-ai/DeepSeek-OCR/HEAD/DeepSeek-OCR-master/DeepSeek-OCR-vllm/deepencoder/sam_vary_sdpa.py
Generate docstrings for this script
import math from functools import partial from collections import namedtuple import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.modules.utils import _pair import hydra from einops import reduce, rearrange def pooling(x, pooling_mode='CLS', key_padding_mask=None, batch_first=True): ...
--- +++ @@ -47,6 +47,7 @@ class ClassificationHeadLinear(nn.Module): + """Head for sentence-level classification tasks.""" def __init__(self, d_model, num_classes, pooling_mode='MEAN', batch_first=False, **kwargs): @@ -57,6 +58,9 @@ self.out_proj = nn.Linear(d_model, num_classes)...
https://raw.githubusercontent.com/Dao-AILab/flash-attention/HEAD/training/src/models/modules/seq_common.py
Add well-formatted docstrings
# No unicode_literals import json import os import unicodedata from binascii import hexlify, unhexlify from cryptography.hazmat.primitives.kdf import hkdf from cryptography.hazmat.primitives import hashes from attr import attrs, attrib def HKDF(skm, outlen, salt=None, CTXinfo=b""): return hkdf.HKDF( hashe...
--- +++ @@ -9,6 +9,18 @@ def HKDF(skm, outlen, salt=None, CTXinfo=b""): + """ + Return the RFC5869 'HMAC-based Key Derivation Function' result of + using the given `salt`, tag from `CTXinfo` and secret from `skm` + with a SHA256 hash. + + :param bytes skm: the input key material + :param int outle...
https://raw.githubusercontent.com/magic-wormhole/magic-wormhole/HEAD/src/wormhole/util.py
Create simple docstrings for beginners
from attrs import frozen, Factory @frozen class Disconnected: pass @frozen class Connecting: url: str last_attempt: int # unix-timestamp when we last tried connecting @frozen class Connected: url: str @frozen class Failed: reason: str @frozen class Closed: @frozen class NoPeer: @froze...
--- +++ @@ -24,23 +24,39 @@ @frozen class Closed: + """ + We have purposely shut down our connection to the server + """ @frozen class NoPeer: + """ + We have yet to see a peer + """ @frozen class StoppedPeer: + """ + We have disconnected from the peer (probably on purpose) + "...
https://raw.githubusercontent.com/magic-wormhole/magic-wormhole/HEAD/src/wormhole/_status.py
Write reusable docstrings
from collections import deque, defaultdict from attr import attrs, attrib from attr.validators import instance_of from zope.interface import implementer from twisted.internet.defer import inlineCallbacks from twisted.internet.interfaces import (ITransport, IProducer, IConsumer, ...
--- +++ @@ -51,6 +51,10 @@ class UnexpectedSubprotocol(Exception): + """ + The peer sends an OPEN for a subprotocol name application code + indicates will never exist + """ @implementer(IAddress) @@ -61,6 +65,13 @@ @implementer(IAddress) @attrs class SubchannelAddress: + """ + All subchanne...
https://raw.githubusercontent.com/magic-wormhole/magic-wormhole/HEAD/src/wormhole/_dilation/subchannel.py
Fully document this Python code with docstrings
# Version: 0.29 # pylint:disable=invalid-name,import-outside-toplevel,missing-function-docstring # pylint:disable=missing-class-docstring,too-many-branches,too-many-statements # pylint:disable=raise-missing-from,too-many-lines,too-many-locals,import-error # pylint:disable=too-few-public-methods,redefined-outer-name,co...
--- +++ @@ -1,5 +1,306 @@ # Version: 0.29 +"""The Versioneer - like a rocketeer, but for versions. + +The Versioneer +============== + +* like a rocketeer, but for versions! +* https://github.com/python-versioneer/python-versioneer +* Brian Warner +* License: Public Domain (Unlicense) +* Compatible with: Python 3.7, ...
https://raw.githubusercontent.com/magic-wormhole/magic-wormhole/HEAD/versioneer.py
Generate docstrings for this script
import os from collections import deque from attr import attrs, attrib, evolve, define, field from attr.validators import instance_of, optional from automat import MethodicalMachine from zope.interface import implementer from twisted.internet.defer import Deferred, inlineCallbacks from twisted.python import log, failur...
--- +++ @@ -55,6 +55,15 @@ @define class DilatedWormhole: + """ + Represents actions available once a wormhole has been successfully dilated. + + New subchannels to the other peer may be established by first + obtaining an `IStreamClientEndpoint` from the + `subprotocol_connector_for("subproto-name")`...
https://raw.githubusercontent.com/magic-wormhole/magic-wormhole/HEAD/src/wormhole/_dilation/manager.py
Document helper functions with docstrings
from zope.interface import Interface # These interfaces are private: we use them as markers to detect # swapped argument bugs in the various .wire() calls class IWormhole(Interface): def got_welcome(welcome): pass def got_code(code): pass def got_key(key): pass def got_ver...
--- +++ @@ -5,6 +5,7 @@ class IWormhole(Interface): + """Internal: this contains the methods invoked 'from below'.""" def got_welcome(welcome): pass @@ -29,20 +30,84 @@ class IWormholeDelegate(Interface): + """ + Must be implemented by the object passed as "delegate=" to wormhole.create...
https://raw.githubusercontent.com/magic-wormhole/magic-wormhole/HEAD/src/wormhole/_interfaces.py
Document my Python code with docstrings
# This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains th...
--- +++ @@ -8,6 +8,7 @@ # Generated by versioneer-0.29 # https://github.com/python-versioneer/python-versioneer +"""Git implementation of _version.py.""" import errno import os @@ -19,6 +20,7 @@ def get_keywords() -> dict[str, str]: + """Get the keywords needed to look up the version information.""" ...
https://raw.githubusercontent.com/magic-wormhole/magic-wormhole/HEAD/src/wormhole/_version.py
Generate docstrings with examples
import os import sys from attr import attrib, attrs from twisted.python import failure from twisted.internet.task import Cooperator from zope.interface import implementer from ._boss import Boss from ._dilation.manager import DILATION_VERSIONS from ._dilation.connector import Connector from ._interfaces import IDefer...
--- +++ @@ -76,6 +76,12 @@ self._boss.send(plaintext) def derive_key(self, purpose, length): + """Derive a new key from the established wormhole channel for some + other purpose. This is a deterministic randomized function of the + session key and the 'purpose' string (unicode/py3-st...
https://raw.githubusercontent.com/magic-wormhole/magic-wormhole/HEAD/src/wormhole/wormhole.py
Write docstrings for algorithm functions
import os import time start = time.time() from sys import stderr, stdout # noqa: E402 from textwrap import dedent, fill # noqa: E402 import click # noqa: E402 from twisted.internet.defer import inlineCallbacks, maybeDeferred # noqa: E402 from twisted.internet.task import react # noqa: E402 from twisted.python.fa...
--- +++ @@ -22,6 +22,9 @@ class Config: + """ + Union of config options that we pass down to (sub) commands. + """ def __init__(self): # This only holds attributes which are *not* set by CLI arguments. @@ -113,6 +116,13 @@ ) @click.pass_context def wormhole(context, dump_timing, transit_h...
https://raw.githubusercontent.com/magic-wormhole/magic-wormhole/HEAD/src/wormhole/cli/cli.py
Create documentation strings for testing functions
import hashlib import os import sys import tempfile import zipfile from humanize import naturalsize from tqdm import tqdm from twisted.internet import reactor from twisted.internet.defer import inlineCallbacks from twisted.python import log from wormhole import __version__, create, input_with_completion from ..errors...
--- +++ @@ -34,6 +34,13 @@ def receive(args, reactor=reactor, _debug_stash_wormhole=None): + """I implement 'wormhole receive'. I return a Deferred that fires with + None (for success), or signals one of the following errors: + * WrongPasswordError: the two sides didn't use matching passwords + * Timeou...
https://raw.githubusercontent.com/magic-wormhole/magic-wormhole/HEAD/src/wormhole/cli/cmd_receive.py
Add docstrings for better understanding
class WormholeError(Exception): class UnsendableFileError(Exception): class ServerError(WormholeError): class ServerConnectionError(WormholeError): def __init__(self, url, reason): self.url = url self.reason = reason def __str__(self): return str(self.reason) class Timeout(Worm...
--- +++ @@ -1,13 +1,24 @@ class WormholeError(Exception): + """Parent class for all wormhole-related errors""" class UnsendableFileError(Exception): + """ + A file you wanted to send couldn't be read, maybe because it's not + a file, or because it's a symlink that points to something + that doesn't ...
https://raw.githubusercontent.com/magic-wormhole/magic-wormhole/HEAD/src/wormhole/errors.py
Generate documentation strings for clarity
import os import socket import sys import time from binascii import hexlify, unhexlify from collections import deque from nacl.secret import SecretBox from twisted.internet import (address, defer, endpoints, error, interfaces, protocol, task) from twisted.internet.defer import inlineCallb...
--- +++ @@ -330,6 +330,18 @@ # Helper methods def connectConsumer(self, consumer, expected=None): + """Helper method to glue an instance of e.g. t.p.ftp.FileConsumer to + us. Inbound records will be written as bytes to the consumer. + + Set 'expected' to an integer to automatically disco...
https://raw.githubusercontent.com/magic-wormhole/magic-wormhole/HEAD/src/wormhole/transit.py
Add docstrings following best practices
import json from twisted.internet.defer import inlineCallbacks from . import wormhole from .tor_manager import get_tor @inlineCallbacks def receive(reactor, appid, relay_url, code, use_tor=False, launch_tor=False, tor_control_port=None, ...
--- +++ @@ -15,6 +15,26 @@ launch_tor=False, tor_control_port=None, on_code=None): + """ + This is a convenience API which returns a Deferred that callbacks + with a single chunk of data from another wormhole (and then closes + the wormhole). Under the hood, it's just u...
https://raw.githubusercontent.com/magic-wormhole/magic-wormhole/HEAD/src/wormhole/xfer_util.py
Add return value explanations in docstrings
# # Copyright 2009 Facebook # # 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, s...
--- +++ @@ -13,6 +13,17 @@ # License for the specific language governing permissions and limitations # under the License. +"""A non-blocking, single-threaded HTTP server. + +Typical applications have little direct interaction with the `HTTPServer` +class except to start a server at the beginning of the process +(and...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/httpserver.py
Add docstrings to clarify complex logic
# Copyright 2015 The Tornado Authors # # 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 w...
--- +++ @@ -12,6 +12,18 @@ # License for the specific language governing permissions and limitations # under the License. +"""Asynchronous queues for coroutines. These classes are very similar +to those provided in the standard library's `asyncio package +<https://docs.python.org/3/library/asyncio-queue.html>`_. + +...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/queues.py
Fill in missing docstrings in my code
# # Copyright 2011 Facebook # # 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, s...
--- +++ @@ -13,6 +13,7 @@ # License for the specific language governing permissions and limitations # under the License. +"""Miscellaneous network utility code.""" import asyncio import concurrent.futures @@ -60,6 +61,29 @@ flags: Optional[int] = None, reuse_port: bool = False, ) -> List[socket.socket]...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/netutil.py
Replace inline comments with docstrings
# # Copyright 2009 Facebook # # 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, s...
--- +++ @@ -13,6 +13,17 @@ # License for the specific language governing permissions and limitations # under the License. +"""Escaping/unescaping methods for HTML, JSON, URLs, and others. + +Also includes a few other miscellaneous string manipulation functions that +have crept in over time. + +Many functions in this...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/escape.py
Write docstrings for this repository
# # Copyright 2009 Facebook # # 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, s...
--- +++ @@ -13,6 +13,48 @@ # License for the specific language governing permissions and limitations # under the License. +"""``tornado.web`` provides a simple web framework with asynchronous +features that allow it to scale to large numbers of open connections, +making it ideal for `long polling +<http://en.wikiped...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/web.py
Create documentation for each function signature
# Copyright 2015 The Tornado Authors # # 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 w...
--- +++ @@ -29,6 +29,14 @@ class _TimeoutGarbageCollector: + """Base class for objects that periodically clean up timed-out waiters. + + Avoids memory leak in a common pattern like: + + while True: + yield condition.wait(short_timeout) + print('looping....') + """ def __...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/locks.py
Fully document this Python code with docstrings
# # Copyright 2012 Facebook # # 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, s...
--- +++ @@ -12,6 +12,21 @@ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. +"""Logging support for Tornado. + +Tornado uses three logger streams: + +* ``tornado.access``: Per-request logging for T...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/log.py
Add verbose docstrings with examples
# # Copyright 2014 Facebook # # 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, s...
--- +++ @@ -13,6 +13,7 @@ # License for the specific language governing permissions and limitations # under the License. +"""A non-blocking TCP connection factory.""" import functools import socket @@ -37,6 +38,22 @@ class _Connector: + """A stateless implementation of the "Happy Eyeballs" algorithm. + + ...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/tcpclient.py
Add docstrings that explain inputs and outputs
# # Copyright 2012 Facebook # # 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, s...
--- +++ @@ -12,6 +12,18 @@ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. +"""Utilities for working with ``Future`` objects. + +Tornado previously provided its own ``Future`` class, but now uses ...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/concurrent.py
Add professional docstrings to my codebase
# # Copyright 2009 Facebook # # 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, s...
--- +++ @@ -13,6 +13,11 @@ # License for the specific language governing permissions and limitations # under the License. +"""HTTP utility code shared by clients and servers. + +This module also defines the `HTTPServerRequest` class which is exposed +via `tornado.web.RequestHandler.request`. +""" import calendar ...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/httputil.py
Add return value explanations in docstrings
# # Copyright 2011 Facebook # # 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, s...
--- +++ @@ -13,6 +13,7 @@ # License for the specific language governing permissions and limitations # under the License. +"""A non-blocking, single-threaded TCP server.""" import errno import os @@ -40,6 +41,85 @@ class TCPServer: + r"""A non-blocking, single-threaded TCP server. + + To use `TCPServer`...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/tcpserver.py
Write documentation strings for class attributes
import array import asyncio from inspect import getfullargspec import os import re import typing import zlib from typing import ( Any, Optional, Dict, Mapping, List, Tuple, Match, Callable, Type, Sequence, ) if typing.TYPE_CHECKING: # Additional imports only used in type c...
--- +++ @@ -1,3 +1,14 @@+"""Miscellaneous utility functions and classes. + +This module is used internally by Tornado. It is not necessarily expected +that the functions and classes defined here will be useful to other +applications, but they are documented here in case they are. + +The one public-facing part of this ...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/util.py
Write documentation strings for class attributes
# Copyright 2009 Facebook # # 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, sof...
--- +++ @@ -12,6 +12,30 @@ # License for the specific language governing permissions and limitations # under the License. +"""Translation methods for generating localized strings. + +To load a locale and generate a translated string:: + + user_locale = tornado.locale.get("es_LA") + print(user_locale.translate(...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/locale.py
Help me write clear docstrings
# 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, software # distributed under th...
--- +++ @@ -9,6 +9,7 @@ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. +"""Bridges between the Twisted package and Tornado.""" import sys @@ -22,6 +23,24 @@ def install() -> None: + "...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/platform/twisted.py