instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Add docstrings to incomplete code
import base64 import gradio as gr import json from typing import List, Dict, Any, Tuple from annotator.openpose import decode_json_as_poses, draw_poses from annotator.openpose.animalpose import draw_animalposes from scripts.controlnet_ui.modal import ModalInterface from modules import shared from scripts.logging impor...
--- +++ @@ -40,6 +40,7 @@ self.modal = None def render_edit(self): + """Renders the buttons in preview image control button group.""" # The hidden button to trigger a re-render of generated image. self.render_button = gr.Button(visible=False, elem_classes=["cnet-render-pose"]) ...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/scripts/controlnet_ui/openpose_editor.py
Generate descriptive docstrings automatically
import math import torch import torch.nn as nn class MLPProjModel(torch.nn.Module): def __init__(self, cross_attention_dim=1024, clip_embeddings_dim=1024): super().__init__() self.proj = torch.nn.Sequential( torch.nn.Linear(clip_embeddings_dim, clip_embeddings_dim), torch...
--- +++ @@ -21,6 +21,9 @@ class MLPProjModelFaceId(torch.nn.Module): + """MLPProjModel used for FaceId. + Source: https://github.com/tencent-ailab/IP-Adapter/blob/main/ip_adapter/ip_adapter_faceid.py + """ def __init__(self, cross_attention_dim=768, id_embeddings_dim=512, num_tokens=4): sup...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/scripts/ipadapter/image_proj_models.py
Add docstrings that explain purpose and usage
import json import gradio as gr import functools import itertools from typing import List, Optional, Union, Dict, Tuple, Literal, Any from dataclasses import dataclass import numpy as np from scripts.supported_preprocessor import Preprocessor from scripts.utils import svg_preprocess, read_image from scripts import ( ...
--- +++ @@ -32,6 +32,7 @@ @dataclass class A1111Context: + """Contains all components from A1111.""" img2img_batch_input_dir: Optional[gr.components.Component] = None img2img_batch_output_dir: Optional[gr.components.Component] = None @@ -273,6 +274,17 @@ ControlNetUiGroup.all_ui_groups.append(...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/scripts/controlnet_ui/controlnet_ui_group.py
Add structured docstrings to improve clarity
from __future__ import annotations from typing import List, NamedTuple, Tuple, Union import torch import torch.nn as nn import numpy as np from transformers.models.clip.modeling_clip import CLIPVisionModelOutput from .image_proj_models import ( Resampler, ImageProjModel, MLPProjModel, MLPProjModelFace...
--- +++ @@ -17,6 +17,7 @@ class ImageEmbed(NamedTuple): + """Image embed for a single image.""" cond_emb: torch.Tensor uncond_emb: torch.Tensor @@ -211,6 +212,7 @@ @torch.inference_mode() def _get_image_embeds_faceid(self, insightface_output: torch.Tensor) -> ImageEmbed: + """Get im...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/scripts/ipadapter/ipadapter_model.py
Generate docstrings with examples
from __future__ import annotations from enum import Enum from typing import List, NamedTuple from functools import lru_cache class UnetBlockType(Enum): INPUT = "input" OUTPUT = "output" MIDDLE = "middle" class TransformerID(NamedTuple): block_type: UnetBlockType # The id of the block the transfo...
--- +++ @@ -37,6 +37,7 @@ class StableDiffusionVersion(Enum): + """The version family of stable diffusion model.""" UNKNOWN = 0 SD1x = 1 @@ -45,6 +46,9 @@ @staticmethod def detect_from_model_name(model_name: str) -> "StableDiffusionVersion": + """Based on the model name provided, gu...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/scripts/enums.py
Help me add docstrings to my project
import os import cv2 import numpy as np import torch import math from dataclasses import dataclass from transformers.models.clip.modeling_clip import CLIPVisionModelOutput from typing import Callable, Tuple, Union from modules.safe import Extra from modules import devices from annotator.util import HWC3 from scripts.l...
--- +++ @@ -14,6 +14,7 @@ def torch_handler(module: str, name: str): + """ Allow all torch access. Bypass A1111 safety whitelist. """ if module == 'torch': return getattr(torch, name) if module == 'torch._tensor': @@ -274,6 +275,12 @@ res: int = 512, **kwargs # Ignore...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/scripts/preprocessor/legacy/processor.py
Generate docstrings for this script
import cv2 import numpy as np from ..supported_preprocessor import Preprocessor, PreprocessorParameter from ..utils import resize_image_with_pad from annotator.util import HWC3 class PreprocessorNone(Preprocessor): def __init__(self): super().__init__(name="none") self.sorting_priority = 10 ...
--- +++ @@ -1,3 +1,4 @@+"""Preprocessors that do not need to run a torch model.""" import cv2 import numpy as np @@ -151,6 +152,7 @@ self.slider_resolution = PreprocessorParameter(value=512, visible=False) def _cached_call(self, *args, **kwargs): + """No cache for shuffle, as each call depends...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/scripts/preprocessor/model_free_preprocessors.py
Generate docstrings with parameter types
# MIT License # Copyright (c) 2022 Intelligent Systems Lab Org # 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, including without limitation the rights # to use, copy, m...
--- +++ @@ -1,102 +1,152 @@-# MIT License - -# Copyright (c) 2022 Intelligent Systems Lab Org - -# 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, including without limit...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/zoe/zoedepth/models/depth_model.py
Document all endpoints with docstrings
# MIT License # Copyright (c) 2022 Intelligent Systems Lab Org # 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, including without limitation the rights # to use, copy, m...
--- +++ @@ -1,267 +1,333 @@-# MIT License - -# Copyright (c) 2022 Intelligent Systems Lab Org - -# 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, including without limit...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/zoe/zoedepth/models/zoedepth_nk/zoedepth_nk_v1.py
Document all endpoints with docstrings
from abc import ABC, abstractmethod from typing import List, ClassVar, Dict, Optional, Set, NamedTuple, Any from dataclasses import dataclass, field import numpy as np import torch from modules import shared, devices from scripts.enums import ControlNetUnionControlType from scripts.logging import logger from scripts.u...
--- +++ @@ -15,6 +15,17 @@ @dataclass class PreprocessorParameter: + """ + Class representing a parameter for a preprocessor. + + Attributes: + label (str): The label for the parameter. + minimum (float): The minimum value of the parameter. Default is 0.0. + maximum (float): The maximum...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/scripts/supported_preprocessor.py
Replace inline comments with docstrings
from einops import rearrange import torch import os import functools import time import base64 import numpy as np import safetensors.torch import cv2 import logging from typing import Any, Callable, Dict, List from modules.safe import unsafe_torch_load from modules.modelloader import load_file_from_url # noqa: F401 f...
--- +++ @@ -31,8 +31,20 @@ def ndarray_lru_cache(max_size: int = 128, typed: bool = False): + """ + Decorator to enable caching for functions with numpy array arguments. + Numpy arrays are mutable, and thus not directly usable as hash keys. + + The idea here is to wrap the incoming arguments with type `...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/scripts/utils.py
Add docstrings that explain inputs and outputs
import collections.abc import math import torch import torchvision import warnings from distutils.version import LooseVersion from itertools import repeat from torch import nn as nn from torch.nn import functional as F from torch.nn import init as init from torch.nn.modules.batchnorm import _BatchNorm from basicsr.ops...
--- +++ @@ -16,6 +16,15 @@ @torch.no_grad() def default_init_weights(module_list, scale=1, bias_fill=0, **kwargs): + """Initialize network weights. + + Args: + module_list (list[nn.Module] | nn.Module): Modules to be initialized. + scale (float): Scale initialized weights, especially for residual...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/archs/arch_util.py
Add docstrings that explain logic
import math import numpy as np import torch from torch import nn, Tensor import torch.nn.functional as F from typing import Optional, List from basicsr.archs.vqgan_arch import * from basicsr.utils import get_root_logger from basicsr.utils.registry import ARCH_REGISTRY def calc_mean_std(feat, eps=1e-5): size = fea...
--- +++ @@ -10,6 +10,13 @@ from basicsr.utils.registry import ARCH_REGISTRY def calc_mean_std(feat, eps=1e-5): + """Calculate mean and std for adaptive_instance_normalization. + + Args: + feat (Tensor): 4D tensor. + eps (float): A small value added to the variance to avoid + divide-by-...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/archs/codeformer_arch.py
Add professional docstrings to my codebase
import torch from torch import nn as nn from torch.nn import functional as F from basicsr.utils.registry import ARCH_REGISTRY from .arch_util import default_init_weights, make_layer, pixel_unshuffle class ResidualDenseBlock(nn.Module): def __init__(self, num_feat=64, num_grow_ch=32): super(ResidualDense...
--- +++ @@ -7,6 +7,14 @@ class ResidualDenseBlock(nn.Module): + """Residual Dense Block. + + Used in RRDB block in ESRGAN. + + Args: + num_feat (int): Channel number of intermediate features. + num_grow_ch (int): Channels for each growth. + """ def __init__(self, num_feat=64, num_gr...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/archs/rrdbnet_arch.py
Write docstrings for backend logic
import cv2 import math import numpy as np import torch from os import path as osp from PIL import Image, ImageDraw from torch.nn import functional as F from basicsr.data.transforms import mod_crop from basicsr.utils import img2tensor, scandir def read_img_seq(path, require_mod_crop=False, scale=1): if isinstance...
--- +++ @@ -11,6 +11,17 @@ def read_img_seq(path, require_mod_crop=False, scale=1): + """Read a sequence of images from a given folder path. + + Args: + path (list[str] | str): List of image paths or image folder path. + require_mod_crop (bool): Require mod crop for each image. + Defa...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/data/data_util.py
Auto-generate documentation strings for this file
import os import torch from collections import OrderedDict from torch import nn as nn from torchvision.models import vgg as vgg from basicsr.utils.registry import ARCH_REGISTRY VGG_PRETRAIN_PATH = 'experiments/pretrained_models/vgg19-dcbb9e9d.pth' NAMES = { 'vgg11': [ 'conv1_1', 'relu1_1', 'pool1', 'conv2...
--- +++ @@ -34,6 +34,14 @@ def insert_bn(names): + """Insert bn layer after each conv. + + Args: + names (list): The list of layer names. + + Returns: + list: The list of layer names with bn layers. + """ names_bn = [] for name in names: names_bn.append(name) @@ -45,6 +5...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/archs/vgg_arch.py
Add docstrings to improve code quality
import importlib import numpy as np import random import torch import torch.utils.data from copy import deepcopy from functools import partial from os import path as osp from basicsr.data.prefetch_dataloader import PrefetchDataLoader from basicsr.utils import get_root_logger, scandir from basicsr.utils.dist_util impor...
--- +++ @@ -23,6 +23,13 @@ def build_dataset(dataset_opt): + """Build dataset from options. + + Args: + dataset_opt (dict): Configuration for dataset. It must constain: + name (str): Dataset name. + type (str): Dataset type. + """ dataset_opt = deepcopy(dataset_opt) d...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/data/__init__.py
Add standardized docstrings across the file
import cv2 import math import random import numpy as np import os.path as osp from scipy.io import loadmat from PIL import Image import torch import torch.utils.data as data from torchvision.transforms.functional import (adjust_brightness, adjust_contrast, adjust_hue, adjust_sat...
--- +++ @@ -115,6 +115,7 @@ @staticmethod def color_jitter(img, shift): + """jitter color: randomly jitter the RGB values, in numpy formats""" jitter_val = np.random.uniform(-shift, shift, 3).astype(np.float32) img = img + jitter_val img = np.clip(img, 0, 1) @@ -122,6 +123,7...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/data/ffhq_blind_dataset.py
Insert docstrings into my code
import cv2 import math import random import numpy as np import os.path as osp from scipy.io import loadmat import torch import torch.utils.data as data from torchvision.transforms.functional import (adjust_brightness, adjust_contrast, adjust_hue, adjust_saturation, normalize) fr...
--- +++ @@ -107,6 +107,7 @@ @staticmethod def color_jitter(img, shift): + """jitter color: randomly jitter the RGB values, in numpy formats""" jitter_val = np.random.uniform(-shift, shift, 3).astype(np.float32) img = img + jitter_val img = np.clip(img, 0, 1) @@ -114,6 +115,7...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/data/ffhq_blind_joint_dataset.py
Add docstrings that explain purpose and usage
import queue as Queue import threading import torch from torch.utils.data import DataLoader class PrefetchGenerator(threading.Thread): def __init__(self, generator, num_prefetch_queue): threading.Thread.__init__(self) self.queue = Queue.Queue(num_prefetch_queue) self.generator = generator...
--- +++ @@ -5,6 +5,15 @@ class PrefetchGenerator(threading.Thread): + """A general prefetch generator. + + Ref: + https://stackoverflow.com/questions/7323664/python-generator-pre-fetch + + Args: + generator: Python generator. + num_prefetch_queue (int): Number of prefetch queue. + """ ...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/data/prefetch_dataloader.py
Create documentation for each function signature
import math import numpy as np import random from scipy.ndimage.interpolation import shift from scipy.stats import multivariate_normal def sigma_matrix2(sig_x, sig_y, theta): D = np.array([[sig_x**2, 0], [0, sig_y**2]]) U = np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(th...
--- +++ @@ -6,6 +6,14 @@ def sigma_matrix2(sig_x, sig_y, theta): + """Calculate the rotated sigma matrix (two dimensional matrix). + Args: + sig_x (float): + sig_y (float): + theta (float): Radian measurement. + Returns: + ndarray: Rotated sigma matrix. + """ D = np.arra...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/data/gaussian_kernels.py
Document all endpoints with docstrings
import cv2 import numpy as np from basicsr.metrics.metric_util import reorder_image, to_y_channel from basicsr.utils.registry import METRIC_REGISTRY @METRIC_REGISTRY.register() def calculate_psnr(img1, img2, crop_border, input_order='HWC', test_y_channel=False): assert img1.shape == img2.shape, (f'Image shapes ...
--- +++ @@ -7,6 +7,22 @@ @METRIC_REGISTRY.register() def calculate_psnr(img1, img2, crop_border, input_order='HWC', test_y_channel=False): + """Calculate PSNR (Peak Signal-to-Noise Ratio). + + Ref: https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio + + Args: + img1 (ndarray): Images with range ...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/metrics/psnr_ssim.py
Add docstrings for utility scripts
import numpy as np from basicsr.utils.matlab_functions import bgr2ycbcr def reorder_image(img, input_order='HWC'): if input_order not in ['HWC', 'CHW']: raise ValueError(f'Wrong input_order {input_order}. Supported input_orders are ' "'HWC' and 'CHW'") if len(img.shape) == 2: img = img[..., ...
--- +++ @@ -4,6 +4,21 @@ def reorder_image(img, input_order='HWC'): + """Reorder images to 'HWC' order. + + If the input_order is (h, w), return (h, w, 1); + If the input_order is (c, h, w), return (h, w, c); + If the input_order is (h, w, c), return as it is. + + Args: + img (ndarray): Input ...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/metrics/metric_util.py
Generate consistent documentation across files
import math import lpips import torch from torch import autograd as autograd from torch import nn as nn from torch.nn import functional as F from basicsr.archs.vgg_arch import VGGFeatureExtractor from basicsr.utils.registry import LOSS_REGISTRY from .loss_util import weighted_loss _reduction_modes = ['none', 'mean', ...
--- +++ @@ -29,6 +29,13 @@ @LOSS_REGISTRY.register() class L1Loss(nn.Module): + """L1 (mean absolute error, MAE) loss. + + Args: + loss_weight (float): Loss weight for L1 loss. Default: 1.0. + reduction (str): Specifies the reduction to apply to the output. + Supported choices are 'non...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/losses/losses.py
Replace inline comments with docstrings
import cv2 import random def mod_crop(img, scale): img = img.copy() if img.ndim in (2, 3): h, w = img.shape[0], img.shape[1] h_remainder, w_remainder = h % scale, w % scale img = img[:h - h_remainder, :w - w_remainder, ...] else: raise ValueError(f'Wrong img ndim: {img.ndim...
--- +++ @@ -3,6 +3,15 @@ def mod_crop(img, scale): + """Mod crop images, used during testing. + + Args: + img (ndarray): Input image. + scale (int): Scale factor. + + Returns: + ndarray: Result image. + """ img = img.copy() if img.ndim in (2, 3): h, w = img.shape[...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/data/transforms.py
Add docstrings to clarify complex logic
import functools from torch.nn import functional as F def reduce_loss(loss, reduction): reduction_enum = F._Reduction.get_enum(reduction) # none: 0, elementwise_mean:1, sum: 2 if reduction_enum == 0: return loss elif reduction_enum == 1: return loss.mean() else: return loss...
--- +++ @@ -3,6 +3,15 @@ def reduce_loss(loss, reduction): + """Reduce loss as specified. + + Args: + loss (Tensor): Elementwise loss tensor. + reduction (str): Options are 'none', 'mean' and 'sum'. + + Returns: + Tensor: Reduced loss tensor. + """ reduction_enum = F._Reduction...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/losses/loss_util.py
Add inline docstrings for readability
import logging import os import torch from collections import OrderedDict from copy import deepcopy from torch.nn.parallel import DataParallel, DistributedDataParallel from basicsr.models import lr_scheduler as lr_scheduler from basicsr.utils.dist_util import master_only logger = logging.getLogger('basicsr') class ...
--- +++ @@ -12,6 +12,7 @@ class BaseModel(): + """Base model.""" def __init__(self, opt): self.opt = opt @@ -30,9 +31,18 @@ pass def save(self, epoch, current_iter): + """Save networks and training state.""" pass def validation(self, dataloader, current_iter,...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/models/base_model.py
Add docstrings to meet PEP guidelines
import math from collections import Counter from torch.optim.lr_scheduler import _LRScheduler class MultiStepRestartLR(_LRScheduler): def __init__(self, optimizer, milestones, gamma=0.1, restarts=(0, ), restart_weights=(1, ), last_epoch=-1): self.milestones = Counter(milestones) self.gamma = gamm...
--- +++ @@ -4,6 +4,17 @@ class MultiStepRestartLR(_LRScheduler): + """ MultiStep with restarts learning rate scheme. + + Args: + optimizer (torch.nn.optimizer): Torch optimizer. + milestones (list): Iterations that will decrease learning rate. + gamma (float): Decrease ratio. Default: 0.1...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/models/lr_scheduler.py
Write Python docstrings for this snippet
import math import torch from torch import nn as nn from torch.autograd import Function from torch.autograd.function import once_differentiable from torch.nn import functional as F from torch.nn.modules.utils import _pair, _single try: from . import deform_conv_ext except ImportError: import os BASICSR_JIT...
--- +++ @@ -244,6 +244,20 @@ class DeformConvPack(DeformConv): + """A Deformable Conv Encapsulation that acts as normal Conv layers. + + Args: + in_channels (int): Same as nn.Conv2d. + out_channels (int): Same as nn.Conv2d. + kernel_size (int or tuple[int]): Same as nn.Conv2d. + st...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/ops/dcn/deform_conv.py
Document this module using docstrings
import math import os import requests from torch.hub import download_url_to_file, get_dir from tqdm import tqdm from urllib.parse import urlparse from .misc import sizeof_fmt def download_file_from_google_drive(file_id, save_path): session = requests.Session() URL = 'https://docs.google.com/uc?export=downlo...
--- +++ @@ -9,6 +9,13 @@ def download_file_from_google_drive(file_id, save_path): + """Download files from google drive. + Ref: + https://stackoverflow.com/questions/25010369/wget-curl-large-file-from-google-drive # noqa E501 + Args: + file_id (str): File id. + save_path (str): Save path....
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/utils/download_util.py
Add docstrings to improve collaboration
import cv2 import lmdb import sys from multiprocessing import Pool from os import path as osp from tqdm import tqdm def make_lmdb_from_imgs(data_path, lmdb_path, img_path_list, keys, batch=5000, com...
--- +++ @@ -15,6 +15,48 @@ multiprocessing_read=False, n_thread=40, map_size=None): + """Make lmdb from images. + + Contents of lmdb. The file structure is: + example.lmdb + ├── data.mdb + ├── lock.mdb + ├── meta_info.txt + + ...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/utils/lmdb_util.py
Add docstrings for utility scripts
# Modified from https://github.com/open-mmlab/mmcv/blob/master/mmcv/fileio/file_client.py # noqa: E501 from abc import ABCMeta, abstractmethod class BaseStorageBackend(metaclass=ABCMeta): @abstractmethod def get(self, filepath): pass @abstractmethod def get_text(self, filepath): pas...
--- +++ @@ -3,6 +3,12 @@ class BaseStorageBackend(metaclass=ABCMeta): + """Abstract class of storage backends. + + All backends need to implement two apis: ``get()`` and ``get_text()``. + ``get()`` reads the file as a byte stream and ``get_text()`` reads the file + as texts. + """ @abstractmet...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/utils/file_client.py
Add documentation for all methods
import cv2 import math import numpy as np import os import torch from torchvision.utils import make_grid def img2tensor(imgs, bgr2rgb=True, float32=True): def _totensor(img, bgr2rgb, float32): if img.shape[2] == 3 and bgr2rgb: if img.dtype == 'float64': img = img.astype('float...
--- +++ @@ -7,6 +7,17 @@ def img2tensor(imgs, bgr2rgb=True, float32=True): + """Numpy array to tensor. + + Args: + imgs (list[ndarray] | ndarray): Input images. + bgr2rgb (bool): Whether to change bgr to rgb. + float32 (bool): Whether to change to float32. + + Returns: + list[te...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/utils/img_util.py
Turn comments into proper docstrings
import cv2 import math import numpy as np import os import queue import threading import torch from torch.nn import functional as F from basicsr.utils.download_util import load_file_from_url from basicsr.utils.misc import get_device # ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) class RealES...
--- +++ @@ -12,6 +12,19 @@ # ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) class RealESRGANer(): + """A helper class for upsampling images with RealESRGAN. + + Args: + scale (int): Upsampling scale factor used in the networks. It is usually 2 or 4. + model_path (str): The...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/utils/realesrgan_utils.py
Add docstrings for production code
import math import numpy as np import torch def cubic(x): absx = torch.abs(x) absx2 = absx**2 absx3 = absx**3 return (1.5 * absx3 - 2.5 * absx2 + 1) * ( (absx <= 1).type_as(absx)) + (-0.5 * absx3 + 2.5 * absx2 - 4 * absx + 2) * (((absx > 1) * ...
--- +++ @@ -4,6 +4,7 @@ def cubic(x): + """cubic function used for calculate_weights_indices.""" absx = torch.abs(x) absx2 = absx**2 absx3 = absx**3 @@ -13,6 +14,15 @@ def calculate_weights_indices(in_length, out_length, scale, kernel, kernel_width, antialiasing): + """Calculate weights and...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/utils/matlab_functions.py
Create docstrings for reusable components
import datetime import logging import time from .dist_util import get_dist_info, master_only initialized_logger = {} class MessageLogger(): def __init__(self, opt, start_iter=1, tb_logger=None): self.exp_name = opt['name'] self.interval = opt['logger']['print_freq'] self.start_iter = st...
--- +++ @@ -8,6 +8,16 @@ class MessageLogger(): + """Message logger for printing. + Args: + opt (dict): Config. It contains the following keys: + name (str): Exp name. + logger (dict): Contains 'print_freq' (str) for logger interval. + train (dict): Contains 'total_iter...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/utils/logger.py
Add inline docstrings for readability
import os import re import random import time import torch import numpy as np from os import path as osp from .dist_util import master_only from .logger import get_root_logger IS_HIGH_VERSION = [int(m) for m in list(re.findall(r"^([0-9]+)\.([0-9]+)\.([0-9]+)([^0-9][a-zA-Z0-9]*)?(\+git.*)?$",\ torch.__version__)[0...
--- +++ @@ -33,6 +33,7 @@ def set_random_seed(seed): + """Set random seeds.""" random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) @@ -45,6 +46,11 @@ def mkdir_and_rename(path): + """mkdirs. If path exists, rename it with timestamp and create a new one. + + Args: + path...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/utils/misc.py
Write beginner-friendly docstrings
import cv2 import copy import re import torch import numpy as np from pathlib import Path from facelib.detection.yolov5face.models.yolo import Model from facelib.detection.yolov5face.utils.datasets import letterbox from facelib.detection.yolov5face.utils.general import ( check_img_size, non_max_suppression_fac...
--- +++ @@ -32,6 +32,12 @@ target_size=None, device='cuda', ): + """ + config_name: name of .yaml config with network configuration from models/ folder. + min_face : minimal face size in pixels. + target_size : target size of smaller image axis (choose lower for faster ...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/facelib/detection/yolov5face/face_detector.py
Write Python docstrings for this snippet
import cv2 import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from PIL import Image from torchvision.models._utils import IntermediateLayerGetter as IntermediateLayerGetter from facelib.detection.align_trans import get_reference_facial_points, warp_and_crop_face from facelib.detectio...
--- +++ @@ -198,6 +198,10 @@ nms_threshold=0.4, use_origin_size=True, ): + """ + Params: + imgs: BGR image + """ image, self.resize = self.transform(image, use_origin_size) image = image.to(device) if self.half_inference: @@ -261,6 +265,12...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/facelib/detection/retinaface/retinaface.py
Generate NumPy-style docstrings
import yaml import time from collections import OrderedDict from os import path as osp from basicsr.utils.misc import get_time_str def ordered_yaml(): try: from yaml import CDumper as Dumper from yaml import CLoader as Loader except ImportError: from yaml import Dumper, Loader _map...
--- +++ @@ -5,6 +5,11 @@ from basicsr.utils.misc import get_time_str def ordered_yaml(): + """Support OrderedDict for yaml. + + Returns: + yaml Loader and Dumper. + """ try: from yaml import CDumper as Dumper from yaml import CLoader as Loader @@ -25,6 +30,15 @@ def parse(o...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/utils/options.py
Generate docstrings for this script
# MIT License # Copyright (c) 2022 Intelligent Systems Lab Org # 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, including without limitation the rights # to use, copy, m...
--- +++ @@ -1,134 +1,169 @@-# MIT License - -# Copyright (c) 2022 Intelligent Systems Lab Org - -# 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, including without limit...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/zoe/zoedepth/models/layers/localbins_layers.py
Generate descriptive docstrings automatically
import os import glob import utils import cv2 import sys import numpy as np import argparse import onnx import onnxruntime as rt from transforms import Resize, NormalizeImage, PrepareForNet def run(input_path, output_path, model_path, model_type="large"): print("initialize") # select device device = "C...
--- +++ @@ -1,110 +1,119 @@-import os -import glob -import utils -import cv2 -import sys -import numpy as np -import argparse - -import onnx -import onnxruntime as rt - -from transforms import Resize, NormalizeImage, PrepareForNet - - -def run(input_path, output_path, model_path, model_type="large"): - print("initia...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/zoe/zoedepth/models/base_models/midas_repo/tf/run_onnx.py
Create docstrings for each class method
from __future__ import annotations import os import torch import numpy as np from typing import Optional, List, Annotated, ClassVar, Callable, Any, Tuple, Union from pydantic import BaseModel, validator, root_validator, Field from PIL import Image from logging import Logger from copy import copy from enum import Enum ...
--- +++ @@ -51,6 +51,9 @@ class ControlNetUnit(BaseModel): + """ + Represents an entire ControlNet processing unit. + """ class Config: arbitrary_types_allowed = True @@ -115,6 +118,11 @@ @root_validator def bound_check_params(cls, values: dict) -> dict: + """ + Che...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/internal_controlnet/args.py
Help me add docstrings to my project
import os import ntpath import glob import torch import utils import cv2 import numpy as np from torchvision.transforms import Compose, Normalize from torchvision import transforms from shutil import copyfile import fileinput import sys sys.path.append(os.getcwd() + '/..') def modify_file(): modi...
--- +++ @@ -1,95 +1,112 @@-import os -import ntpath -import glob -import torch -import utils -import cv2 -import numpy as np -from torchvision.transforms import Compose, Normalize -from torchvision import transforms - -from shutil import copyfile -import fileinput -import sys -sys.path.append(os.getcwd() + '/..') - ...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/annotator/zoe/zoedepth/models/base_models/midas_repo/tf/make_onnx_model.py
Add structured docstrings to improve clarity
import gc import tracemalloc import os import logging from collections import OrderedDict from copy import copy, deepcopy from typing import Dict, Optional, Tuple, List import modules.scripts as scripts from modules import shared, devices, script_callbacks, processing, masking, images import gradio as gr import time f...
--- +++ @@ -105,6 +105,26 @@ def prepare_mask( mask: Image.Image, p: processing.StableDiffusionProcessing ) -> Image.Image: + """ + Prepare an image mask for the inpainting process. + + This function takes as input a PIL Image object and an instance of the + StableDiffusionProcessing class, and perfo...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/scripts/controlnet.py
Create docstrings for reusable components
import cv2 import numpy as np import os import torch from torchvision.transforms.functional import normalize from facelib.detection import init_detection_model from facelib.parsing import init_parsing_model from facelib.utils.misc import img2tensor, imwrite, is_gray, bgr2gray, adain_npy from basicsr.utils.download_uti...
--- +++ @@ -52,6 +52,7 @@ class FaceRestoreHelper(object): + """Helper for the face restoration pipeline (base class).""" def __init__(self, upscale_factor, @@ -127,6 +128,7 @@ self.upscale_factor = upscale_factor def read_image(self, img): + """img can be image pat...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/facelib/utils/face_restoration_helper.py
Add docstrings with type hints explained
import os import glob import numpy as np import PIL import PIL.Image import scipy import scipy.ndimage import argparse from basicsr.utils.download_util import load_file_from_url try: import dlib except ImportError: print('Please install dlib by running:' 'conda install -c conda-forge dlib') # download model ...
--- +++ @@ -1,3 +1,17 @@+""" +brief: face alignment with FFHQ method (https://github.com/NVlabs/ffhq-dataset) +author: lzhbrian (https://lzhbrian.me) +link: https://gist.github.com/lzhbrian/bde87ab23b499dd02ba4f588258f57d5 +date: 2020.1.5 +note: code is heavily borrowed from + https://github.com/NVlabs/ffhq-dataset ...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/scripts/crop_align_face.py
Document classes and their methods
import cv2 import os import os.path as osp import numpy as np from PIL import Image import torch from torch.hub import download_url_to_file, get_dir from urllib.parse import urlparse # from basicsr.utils.download_util import download_file_from_google_drive ROOT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os....
--- +++ @@ -36,6 +36,18 @@ def imwrite(img, file_path, params=None, auto_mkdir=True): + """Write image to file. + + Args: + img (ndarray): Image array to be written. + file_path (str): Image file path. + params (None or list): Same as opencv's :func:`imwrite` interface. + auto_mkdi...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/facelib/utils/misc.py
Insert docstrings into my code
import functools import inspect import logging import time from typing import Callable, Any from .telemetry import record_tool_usage logger = logging.getLogger("blender-mcp-telemetry") def telemetry_tool(tool_name: str): def decorator(func: Callable) -> Callable: @functools.wraps(func) def sync...
--- +++ @@ -1,3 +1,6 @@+""" +Telemetry decorator for Blender MCP tools +""" import functools import inspect @@ -11,6 +14,7 @@ def telemetry_tool(tool_name: str): + """Decorator to add telemetry tracking to MCP tools""" def decorator(func: Callable) -> Callable: @functools.wraps(func) d...
https://raw.githubusercontent.com/ahujasid/blender-mcp/HEAD/src/blender_mcp/telemetry_decorator.py
Write docstrings that follow conventions
import contextlib import json import logging import os import platform import queue import sys import threading import time import uuid from dataclasses import dataclass from enum import Enum from pathlib import Path from typing import Any try: from supabase import create_client, Client HAS_SUPABASE = True ex...
--- +++ @@ -1,3 +1,7 @@+""" +Privacy-focused, anonymous telemetry for Blender MCP +Tracks tool usage, DAU/MAU, and performance metrics +""" import contextlib import json @@ -32,6 +36,7 @@ def get_package_version() -> str: + """Get version from pyproject.toml""" try: pyproject_path = Path(__file...
https://raw.githubusercontent.com/ahujasid/blender-mcp/HEAD/src/blender_mcp/telemetry.py
Annotate my code with docstrings
# Modified from: https://github.com/facebookresearch/fvcore/blob/master/fvcore/common/registry.py # noqa: E501 class Registry(): def __init__(self, name): self._name = name self._obj_map = {} def _do_register(self, name, obj): assert (name not in self._obj_map), (f"An object named '...
--- +++ @@ -2,8 +2,36 @@ class Registry(): + """ + The registry that provides name -> object mapping, to support third-party + users' custom modules. + + To create a registry (e.g. a backbone registry): + + .. code-block:: python + + BACKBONE_REGISTRY = Registry('BACKBONE') + + To register ...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/basicsr/utils/registry.py
Document all endpoints with docstrings
# blender_mcp_server.py from mcp.server.fastmcp import FastMCP, Context, Image import socket import json import asyncio import logging import tempfile from dataclasses import dataclass from contextlib import asynccontextmanager from typing import AsyncIterator, Dict, Any, List import os from pathlib import Path import ...
--- +++ @@ -33,6 +33,7 @@ sock: socket.socket = None # Changed from 'socket' to 'sock' to avoid naming conflict def connect(self) -> bool: + """Connect to the Blender addon socket server""" if self.sock: return True @@ -47,6 +48,7 @@ return False ...
https://raw.githubusercontent.com/ahujasid/blender-mcp/HEAD/src/blender_mcp/server.py
Document helper functions with docstrings
# # For licensing see accompanying LICENSE.md file. # Copyright (C) 2022 Apple Inc. All Rights Reserved. # import logging import operator import torch logging.basicConfig() logger = logging.getLogger() logger.setLevel('INFO') import argparse import gc import json import os import pickle from copy import deepcopy i...
--- +++ @@ -90,6 +90,10 @@ def unet_data_loader(data_dir, device='cpu', calibration_nsamples=None): + """ + Load calibration data from specified path. + Limit number of samples to calibration_nsamples, if specified. + """ dataloader = [] skip_load = False for file in sorted(os.listdir(dat...
https://raw.githubusercontent.com/apple/ml-stable-diffusion/HEAD/python_coreml_stable_diffusion/activation_quantization.py
Generate consistent docstrings
# # For licensing see accompanying LICENSE.md file. # Copyright (C) 2022 Apple Inc. All Rights Reserved. # from python_coreml_stable_diffusion.layer_norm import LayerNormANE from python_coreml_stable_diffusion import attention from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers im...
--- +++ @@ -60,6 +60,8 @@ class CrossAttention(nn.Module): + """ Apple Silicon friendly version of `diffusers.models.attention.CrossAttention` + """ def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64): super().__init__() inner_dim = dim_head * heads @@ -118,6 +120,8 @@...
https://raw.githubusercontent.com/apple/ml-stable-diffusion/HEAD/python_coreml_stable_diffusion/unet.py
Write beginner-friendly docstrings
# # For licensing see accompanying LICENSE.md file. # Copyright (C) 2022 Apple Inc. All Rights Reserved. # from python_coreml_stable_diffusion import ( unet, controlnet, chunk_mlprogram ) import argparse from collections import OrderedDict, defaultdict from copy import deepcopy import coremltools as ct from diffu...
--- +++ @@ -57,6 +57,8 @@ def compute_psnr(a, b): + """ Compute Peak-Signal-to-Noise-Ratio across two numpy.ndarray objects + """ max_b = np.abs(b).max() sumdeltasq = 0.0 @@ -76,6 +78,8 @@ def report_correctness(original_outputs, final_outputs, log_prefix): + """ Report PSNR values across t...
https://raw.githubusercontent.com/apple/ml-stable-diffusion/HEAD/python_coreml_stable_diffusion/torch2coreml.py
Create Google-style docstrings for my code
import math import time import numpy as np import torch import torchvision def check_img_size(img_size, s=32): # Verify img_size is a multiple of stride s new_size = make_divisible(img_size, int(s)) # ceil gs-multiple # if new_size != img_size: # print(f"WARNING: --img-size {img_size:g} must be ...
--- +++ @@ -65,6 +65,16 @@ def box_iou(box1, box2): # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py + """ + Return intersection-over-union (Jaccard index) of boxes. + Both sets of boxes are expected to be in (x1, y1, x2, y2) format. + Arguments: + box1 (Tensor[N, 4]) +...
https://raw.githubusercontent.com/sczhou/CodeFormer/HEAD/facelib/detection/yolov5face/utils/general.py
Document this code for team use
# # For licensing see accompanying LICENSE.md file. # Copyright (C) 2022 Apple Inc. All Rights Reserved. # import argparse from diffusers import StableDiffusionPipeline, StableDiffusionXLPipeline from diffusers.pipelines.pipeline_utils import DiffusionPipeline from diffusers.pipelines.stable_diffusion import StableDi...
--- +++ @@ -45,6 +45,9 @@ class CoreMLStableDiffusionPipeline(DiffusionPipeline): + """ Core ML version of + `diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline` + """ def __init__( self, @@ -610,6 +613,11 @@ controlnet_models=None...
https://raw.githubusercontent.com/apple/ml-stable-diffusion/HEAD/python_coreml_stable_diffusion/pipeline.py
Generate docstrings with parameter types
# Code created by Siddharth Ahuja: www.github.com/ahujasid © 2025 import re import bpy import mathutils import json import threading import socket import time import requests import tempfile import traceback import os import shutil import zipfile from bpy.props import IntProperty, BoolProperty import io from datetime ...
--- +++ @@ -91,6 +91,7 @@ print("BlenderMCP server stopped") def _server_loop(self): + """Main server loop in a separate thread""" print("Server thread started") self.socket.settimeout(1.0) # Timeout to allow for stopping @@ -123,6 +124,7 @@ print("Server thread stoppe...
https://raw.githubusercontent.com/ahujasid/blender-mcp/HEAD/addon.py
Add docstrings to incomplete code
# # For licensing see accompanying LICENSE.md file. # Copyright (C) 2022 Apple Inc. All Rights Reserved. # import coremltools as ct import logging import json logging.basicConfig() logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) import numpy as np import os import time import subprocess import s...
--- +++ @@ -21,6 +21,9 @@ def _macos_version(): + """ + Returns macOS version as a tuple of integers. On non-Macs, returns an empty tuple. + """ if sys.platform == "darwin": try: ver_str = subprocess.run(["sw_vers", "-productVersion"], stdout=subprocess.PIPE).stdout.decode('utf-8...
https://raw.githubusercontent.com/apple/ml-stable-diffusion/HEAD/python_coreml_stable_diffusion/coreml_model.py
Help me comply with documentation standards
# # For licensing see accompanying LICENSE.md file. # Copyright (C) 2022 Apple Inc. All Rights Reserved. # import torch import torch.nn as nn # Reference: https://github.com/apple/ml-ane-transformers/blob/main/ane_transformers/reference/layer_norm.py class LayerNormANE(nn.Module): def __init__(self, ...
--- +++ @@ -9,12 +9,25 @@ # Reference: https://github.com/apple/ml-ane-transformers/blob/main/ane_transformers/reference/layer_norm.py class LayerNormANE(nn.Module): + """ LayerNorm optimized for Apple Neural Engine (ANE) execution + + Note: This layer only supports normalization over the final dim. It expects...
https://raw.githubusercontent.com/apple/ml-stable-diffusion/HEAD/python_coreml_stable_diffusion/layer_norm.py
Create docstrings for API functions
from typing import List, Tuple from enum import Enum import gradio as gr from modules.processing import StableDiffusionProcessing from internal_controlnet.external_code import ControlNetUnit from scripts.logging import logger class Infotext(object): def __init__(self) -> None: self.infotext_fields: List...
--- +++ @@ -18,6 +18,14 @@ return f"ControlNet {unit_index}" def register_unit(self, unit_index: int, uigroup) -> None: + """Register the unit's UI group. By regsitering the unit, A1111 will be + able to paste values from infotext to IOComponents. + + Args: + unit_index: T...
https://raw.githubusercontent.com/Mikubill/sd-webui-controlnet/HEAD/scripts/infotext.py
Add docstrings for internal functions
from collections import OrderedDict from copy import deepcopy from functools import partial import argparse import gc import json import logging logging.basicConfig() logger = logging.getLogger() logger.setLevel('INFO') import numpy as np import os from PIL import Image from python_coreml_stable_diffusion.torch2corem...
--- +++ @@ -68,6 +68,11 @@ val_dtype = val.dtype def _ensure_numerical_range_and_cast(val, low, high, np_dtype): + ''' + For some cases, the computed quantized data might exceed the data range. + For instance, after rounding and addition, we might get `128` for the int8 quantization. + ...
https://raw.githubusercontent.com/apple/ml-stable-diffusion/HEAD/python_coreml_stable_diffusion/mixed_bit_compression_pre_analysis.py
Generate consistent docstrings
def fibonacci_at_position(position): current_position = 0 previous_number, current_number = 0, 1 while current_position < position: current_position += 1 previous_number, current_number = current_number, previous_number + current_number return previous_number def fibonacci_smaller_th...
--- +++ @@ -1,6 +1,15 @@+"""Fibonacci numbers module. + +@see: https://docs.python.org/3/tutorial/modules.html + +A module is a file containing Python definitions and statements. The file name is the module name +with the suffix .py appended. Within a module, the module’s name (as a string) is available as the +value o...
https://raw.githubusercontent.com/trekhleb/learn-python/HEAD/src/modules/fibonacci_module.py
Write docstrings describing each step
# # For licensing see accompanying LICENSE.md file. # Copyright (C) 2022 Apple Inc. All Rights Reserved. # import argparse from collections import OrderedDict import coremltools as ct from coremltools.converters.mil import Block, Program, Var from coremltools.converters.mil.frontend.milproto.load import load as _milp...
--- +++ @@ -35,6 +35,8 @@ first_chunk_model=None, second_chunk_model=None, pipeline_model=None,): + """ Verifies the end-to-end output correctness of full (original) model versus chunked model...
https://raw.githubusercontent.com/apple/ml-stable-diffusion/HEAD/python_coreml_stable_diffusion/chunk_mlprogram.py
Turn comments into proper docstrings
import logging logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) import torch import math SPLIT_SOFTMAX = False def softmax(x, dim): # Reduction max max_x = x.max(dim=dim, keepdim=True).values # EW sub x -= max_x # Scale for EXP to EXP2, Activation EXP2 scaled_x = x * (1 / m...
--- +++ @@ -22,6 +22,12 @@ return exp_act * exp_sum_inv def split_einsum(q, k, v, mask, heads, dim_head): + """ Attention Implementation backing AttentionImplementations.SPLIT_EINSUM + + - Implements https://machinelearning.apple.com/research/neural-engine-transformers + - Recommended for ANE + - Mar...
https://raw.githubusercontent.com/apple/ml-stable-diffusion/HEAD/python_coreml_stable_diffusion/attention.py
Create structured documentation for my script
from __future__ import annotations import re import tomllib import urllib.parse from pathlib import Path # The benchmark SVG includes a CSS media query that adapts to light/dark mode. # PyPI doesn't support this, so we replace it with a light-only version. # See: https://github.com/pypi/warehouse/issues/11251 BENCHM...
--- +++ @@ -1,3 +1,8 @@+"""Transform the README.md to support a specific deployment target. + +By default, we assume that our README.md will be rendered on GitHub. However, +PyPI includes the README with different rendering. +""" from __future__ import annotations @@ -14,6 +19,7 @@ def main() -> None: + """...
https://raw.githubusercontent.com/astral-sh/ty/HEAD/scripts/transform_readme.py
Create docstrings for reusable components
from typing import ( TypeVar, ) from sqlalchemy.sql._typing import ( _ColumnExpressionArgument, ) from sqlalchemy.sql.expression import Select as _Select from typing_extensions import Self _T = TypeVar("_T") # Separate this class in SelectBase, Select, and SelectOfScalar so that they can share # where and h...
--- +++ @@ -17,9 +17,15 @@ inherit_cache = True def where(self, *whereclause: _ColumnExpressionArgument[bool] | bool) -> Self: + """Return a new `Select` construct with the given expression added to + its `WHERE` clause, joined to the existing clause via `AND`, if any. + """ ret...
https://raw.githubusercontent.com/fastapi/sqlmodel/HEAD/sqlmodel/sql/_expression_select_cls.py
Write reusable docstrings
from collections.abc import Mapping, Sequence from typing import ( Any, TypeVar, overload, ) from sqlalchemy import util from sqlalchemy.engine.cursor import CursorResult from sqlalchemy.engine.interfaces import _CoreAnyExecuteParams from sqlalchemy.engine.result import Result, ScalarResult, TupleResult fr...
--- +++ @@ -115,6 +115,24 @@ _parent_execute_state: Any | None = None, _add_event: Any | None = None, ) -> Result[Any]: + """ + 🚨 You probably want to use `session.exec()` instead of `session.execute()`. + + This is the original SQLAlchemy `session.execute()` method that retu...
https://raw.githubusercontent.com/fastapi/sqlmodel/HEAD/sqlmodel/orm/session.py
Document functions with clear intent
import logging import os import re import shutil import subprocess from http.server import HTTPServer, SimpleHTTPRequestHandler from pathlib import Path import mkdocs.utils import typer from jinja2 import Template from ruff.__main__ import find_ruff_bin logging.basicConfig(level=logging.INFO) mkdocs_name = "mkdocs.y...
--- +++ @@ -70,6 +70,9 @@ @app.command() def generate_readme() -> None: + """ + Generate README.md content from main index.md + """ typer.echo("Generating README") readme_path = Path("README.md") new_content = generate_readme_content() @@ -78,6 +81,9 @@ @app.command() def verify_readme() -...
https://raw.githubusercontent.com/fastapi/sqlmodel/HEAD/scripts/docs.py
Write Python docstrings for this snippet
from typing import Any, TypeVar class _DefaultPlaceholder: def __init__(self, value: Any): self.value = value def __bool__(self) -> bool: return bool(self.value) def __eq__(self, o: object) -> bool: return isinstance(o, _DefaultPlaceholder) and o.value == self.value _TDefaultT...
--- +++ @@ -2,6 +2,12 @@ class _DefaultPlaceholder: + """ + You shouldn't use this class directly. + + It's used internally to recognize when a default value has been overwritten, even + if the overridden default value was truthy. + """ def __init__(self, value: Any): self.value = val...
https://raw.githubusercontent.com/fastapi/sqlmodel/HEAD/sqlmodel/default.py
Add docstrings for internal functions
# Copyright (c) 2023-2024 DeepSeek. # # 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, including without limitation the rights to # use, copy, modify, merge, publish, dist...
--- +++ @@ -140,6 +140,33 @@ sft_format: str = "deepseek", system_prompt: str = "", ): + """ + Applies the SFT template to conversation. + + An example of conversation: + conversation = [ + { + "role": "User", + "content": "<imag...
https://raw.githubusercontent.com/deepseek-ai/Janus/HEAD/janus/models/processing_vlm.py
Generate docstrings for each module
# Copyright (c) 2023-2024 DeepSeek. # # 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, including without limitation the rights to # use, copy, modify, merge, publish, dist...
--- +++ @@ -91,6 +91,23 @@ def trunc_normal_(tensor, mean=0.0, std=1.0, a=-2.0, b=2.0): # type: (torch.Tensor, float, float, float, float) -> torch.Tensor + r"""The original timm.models.layers.weight_init.trunc_normal_ can not handle bfloat16 yet, here we first + convert the tensor to float32, apply the tr...
https://raw.githubusercontent.com/deepseek-ai/Janus/HEAD/janus/models/siglip_vit.py
Annotate my code with docstrings
# Copyright (c) 2023-2024 DeepSeek. # # 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, including without limitation the rights to # use, copy, modify, merge, publish, dist...
--- +++ @@ -162,6 +162,33 @@ sft_format: str = "deepseek", system_prompt: str = "", ): + """ + Applies the SFT template to conversation. + + An example of conversation: + conversation = [ + { + "role": "User", + "content": "<imag...
https://raw.githubusercontent.com/deepseek-ai/Janus/HEAD/janus/janusflow/models/processing_vlm.py
Add professional docstrings to my codebase
# Copyright (c) 2023-2024 DeepSeek. # # 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, including without limitation the rights to # use, copy, modify, merge, publish, dist...
--- +++ @@ -91,6 +91,23 @@ def trunc_normal_(tensor, mean=0.0, std=1.0, a=-2.0, b=2.0): # type: (torch.Tensor, float, float, float, float) -> torch.Tensor + r"""The original timm.models.layers.weight_init.trunc_normal_ can not handle bfloat16 yet, here we first + convert the tensor to float32, apply the tr...
https://raw.githubusercontent.com/deepseek-ai/Janus/HEAD/janus/janusflow/models/siglip_vit.py
Add return value explanations in docstrings
# Copyright (c) 2023-2024 DeepSeek. # # 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, including without limitation the rights to # use, copy, modify, merge, publish, dist...
--- +++ @@ -17,6 +17,9 @@ # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +""" +From https://github.com/lm-sys/FastChat/blob/main/fastchat/conversation.py +""" import dataclasses from enum import IntEnum, auto ...
https://raw.githubusercontent.com/deepseek-ai/Janus/HEAD/janus/utils/conversation.py
Add minimal docstrings for each function
# Copyright (c) 2023-2024 DeepSeek. # # 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, including without limitation the rights to # use, copy, modify, merge, publish, dist...
--- +++ @@ -149,6 +149,20 @@ class Downsample2D(nn.Module): + """A 2D downsampling layer with an optional convolution. + + Parameters: + channels (`int`): + number of channels in the inputs and outputs. + use_conv (`bool`, default `False`): + option to use a convolution. + ...
https://raw.githubusercontent.com/deepseek-ai/Janus/HEAD/janus/janusflow/models/uvit.py
Add docstrings to clarify complex logic
# Copyright 2020-2026 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
--- +++ @@ -19,6 +19,7 @@ def _subtract_subsequence(lst: list[str], subseq: list[str]) -> list[str]: + """Return lst with the ordered subsequence subseq removed.""" sub_iter = iter(subseq) current = next(sub_iter, None) result = [] @@ -31,6 +32,15 @@ class TrainingCommand(Command): + """ + ...
https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/cli/commands/training.py
Write Python docstrings for this snippet
# Copyright 2020-2026 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
--- +++ @@ -22,6 +22,17 @@ @dataclass class ScriptArguments: + r""" + Arguments for the script. + + Args: + test_size (`float`, *optional*, defaults to `0.1`): + Fraction of the dataset to include in the test split. + push_to_hub (`bool`, *optional*, defaults to `False`): + ...
https://raw.githubusercontent.com/huggingface/trl/HEAD/scripts/generate_toolcall_dataset.py
Help me write clear docstrings
# Copyright 2020-2026 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
--- +++ @@ -89,6 +89,10 @@ def get_global_statistics( accelerator, xs: torch.Tensor, mask=None, device="cpu" ) -> tuple[torch.Tensor, torch.Tensor, int]: + """ + Computes element-wise mean and variance of the tensor across processes. Reference: + https://github.com/OpenLMLab/MOSS-RLHF/blob/40b91eb2f2b71b...
https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/experimental/bco/bco_trainer.py
Help me write clear docstrings
# Copyright 2020-2026 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
--- +++ @@ -26,6 +26,9 @@ class CallbackHandlerWithRefModel(CallbackHandler): + """ + A [`~transformers.CallbackHandler`] that supports passing a reference model to callbacks. + """ def __init__(self, callbacks, model, ref_model, processing_class, optimizer, lr_scheduler): super().__init__(...
https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/experimental/bema_for_ref_model/callback.py
Add well-formatted docstrings
# Copyright 2020-2026 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
--- +++ @@ -83,6 +83,11 @@ def _get_kl_dataset(batch: dict[str, list[Any]]) -> dict[str, list[Any]]: + """ + Creates mismatched pairs of prompts and completions for the KL dataset by adding a +1 offset to the order of + completions. For best results, the mismatched outputs y' used to estimate the KL term f...
https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/experimental/kto/kto_trainer.py
Help me comply with documentation standards
# Copyright 2020-2026 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
--- +++ @@ -12,6 +12,13 @@ # See the License for the specific language governing permissions and # limitations under the License. +""" +Compatibility shims for third-party dependencies. + +This module contains temporary patches to handle version incompatibilities between TRL's dependencies. + +Each patch should be r...
https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/_compat.py
Can you add docstrings to this Python file?
# Copyright 2020-2026 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
--- +++ @@ -46,6 +46,38 @@ class MergeConfig: + r""" + Configuration class for merging two models using `mergekit`. + + This class provides a structured way to configure and generate merge configurations for various merge methods, such + as `linear`, `ties`, `dare_ties`, and `slerp`. + + Args: + ...
https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/experimental/merge_model_callback.py
Add verbose docstrings with examples
# Copyright 2020-2026 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
--- +++ @@ -21,6 +21,46 @@ source_tokenizer_path: str, resize_to_multiple_of: int | None = 64, ) -> tuple[PreTrainedModel, PreTrainedTokenizer, list[int]]: + """ + Clones a chat template from a source tokenizer to the target tokenizer and updates the model accordingly. + + This function: + - Copie...
https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/chat_template_utils.py
Document classes and their methods
# Copyright 2020-2026 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
--- +++ @@ -46,6 +46,105 @@ class MiniLLMTrainer(GRPOTrainer): + """ + Trainer for the Knowledge Distillation of Language Models (MiniLLM) method. This algorithm was initially proposed + in the paper [Knowledge Distillation of Large Language Models](https://huggingface.co/papers/2306.08543). + + Example...
https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/experimental/minillm/minillm_trainer.py
Add docstrings to my Python code
# Copyright 2020-2026 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
--- +++ @@ -72,6 +72,42 @@ class CPOTrainer(_BaseTrainer): + r""" + Initialize CPOTrainer. + + Args: + model ([`~transformers.PreTrainedModel`]): + The model to train, preferably an [`~transformers.AutoModelForSequenceClassification`]. + args ([`experimental.cpo.CPOConfig`]): + ...
https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/experimental/cpo/cpo_trainer.py
Generate docstrings for this script
# Copyright 2020-2026 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
--- +++ @@ -51,6 +51,44 @@ class GKDTrainer(SFTTrainer): + """Trainer for Generalized Knowledge Distillation (GKD) of language models. + + For details on GKD, see the paper: [On-Policy Distillation of Language Models: Learning from Self-Generated + Mistakes](https://huggingface.co/papers/2306.13649). + + ...
https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/experimental/gkd/gkd_trainer.py
Generate consistent docstrings
# Copyright 2020-2026 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
--- +++ @@ -50,6 +50,21 @@ class PreTrainedModelWrapper(nn.Module): + """ + Wrapper for a [`~transformers.PreTrainedModel`] implemented as a standard PyTorch [`torch.nn.Module`]. + + This class provides a compatibility layer that preserves the key attributes and methods of the original + [`~transformers...
https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/experimental/ppo/modeling_value_head.py
Create docstrings for all classes and functions
# Copyright 2020-2026 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
--- +++ @@ -31,6 +31,46 @@ def prepare_multimodal_messages(messages: list[dict[str, Any]], images: list) -> list[dict[str, Any]]: # docstyle-ignore # because <Image> is not parsable in the code block + """ + Convert messages into a structured multimodal format and inject the provided images into the messa...
https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/data_utils.py
Help me document legacy Python code
# Copyright 2020-2026 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
--- +++ @@ -19,10 +19,18 @@ @dataclass(slots=True) class CommandContext: + """Context shared by CLI commands during execution.""" argv: list[str] def argv_after(self, token: str) -> list[str]: + """ + Return CLI tokens after the first occurrence of `token`. + + Parameters: + ...
https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/cli/commands/base.py
Generate NumPy-style docstrings
# Copyright 2020-2026 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
--- +++ @@ -35,6 +35,7 @@ def get_tracked_python_files(): + """Get a list of all tracked Python files using git.""" try: # Get the list of all tracked files from Git result = subprocess.run(["git", "ls-files"], stdout=subprocess.PIPE, text=True, check=True) @@ -49,6 +50,7 @@ def check_...
https://raw.githubusercontent.com/huggingface/trl/HEAD/scripts/add_copyrights.py
Add docstrings to existing functions
# Copyright 2020-2026 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
--- +++ @@ -76,12 +76,49 @@ def log1mexp(x: torch.FloatTensor) -> torch.FloatTensor: + """Numerically stable computation of log(1-exp(x)).""" # branch at -ln 2 ~ -0.693 to avoid cancellation t = -0.6931471805599453 return torch.where(x < t, torch.log1p(-torch.exp(x)), torch.log(-torch.expm1(x))) ...
https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/experimental/orpo/orpo_trainer.py
Document helper functions with docstrings
# Copyright 2020-2026 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
--- +++ @@ -97,6 +97,46 @@ step: int, num_samples: int = None, ) -> None: + """ + Print out a sample of model completions to the console with multiple reward metrics. + + This function creates a nicely formatted table showing prompt-completion pairs, useful for monitoring model outputs + during tr...
https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/experimental/gold/gold_trainer.py
Write proper docstrings for these functions
# Copyright 2020-2026 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
--- +++ @@ -55,6 +55,19 @@ def _ensure_llm_blender_importable() -> None: + """ + Pre-import shim to work around a known `llm-blender` issue. + + As of `llm-blender` v0.0.2 (see upstream issue: https://github.com/yuchenlin/LLM-Blender/issues/33), importing + `llm_blender` may fail on `transformers` >= 5....
https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/experimental/judges/judges.py
Add standardized docstrings across the file
# Copyright 2020-2026 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
--- +++ @@ -26,6 +26,9 @@ class ReplayBuffer: + """ + A simple replay buffer to store and sample previously seen rollouts. + """ def __init__(self, max_size: int): self.max_size = max_size @@ -424,6 +427,18 @@ def slice_group_data( self, data: torch.Tensor, mask: torch.Tensor, ...
https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/experimental/grpo_with_replay_buffer/grpo_with_replay_buffer_trainer.py
Document classes and their methods
# Copyright 2020-2026 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
--- +++ @@ -28,6 +28,49 @@ class ProfilingContext: + """ + Context manager for profiling code blocks with configurable logging. + + This class handles timing of code execution and logging metrics to various backends (Weights & Biases, MLflow) + without being coupled to the Trainer class. + + Args: + ...
https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/extras/profiling.py
Generate docstrings for this script
# Copyright 2020-2026 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
--- +++ @@ -48,6 +48,15 @@ class GeometricMixtureWrapper(GenerationMixin): + """ + Geometric Mixture generation wrapper that samples from the logits of two model's geometric mixture. + + Args: + model ([`~transformers.PreTrainedModel`]): The model to be wrapped. + ref_model ([`~transformers.P...
https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/experimental/nash_md/nash_md_trainer.py
Generate docstrings for exported functions
# Copyright 2020-2026 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
--- +++ @@ -95,6 +95,42 @@ class PRMTrainer(_BaseTrainer): + """ + Initialize PRMTrainer. + + Args: + model ([`~transformers.PreTrainedModel`]): + The model to train, preferably an `AutoModelForTokenClassification`. + args ([`experimental.prm.PRMConfig`]): + The argument...
https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/experimental/prm/prm_trainer.py
Generate docstrings with parameter types
# Copyright 2020-2026 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
--- +++ @@ -30,6 +30,7 @@ trainer, overrides: dict[str, Any] | None = None, ) -> dict[str, Any]: + """Build base generation kwargs common to both colocate and server modes.""" generation_kwargs: dict[str, Any] = { "n": 1, "temperature": trainer.temperature, @@ -62,6 +63,7 @@ *, ...
https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/experimental/openenv/utils.py
Add docstrings to clarify complex logic
# Copyright 2020-2026 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
--- +++ @@ -24,6 +24,33 @@ def accuracy_reward(completions: list[list[dict[str, str]]], solution: list[str], **kwargs) -> list[float | None]: + r""" + Reward function that checks if the completion matches the ground truth. + - If both gold and prediction are parseable → use math verification. + ...
https://raw.githubusercontent.com/huggingface/trl/HEAD/trl/rewards/accuracy_rewards.py