instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Add docstrings to make code maintainable
# pylint: disable=relative-import from __future__ import print_function import os import re from config import CONFIG from .git_adapter import GitRepositoryAdapter class LearnXinY(GitRepositoryAdapter): _adapter_name = "learnxiny" _output_format = "code" _cache_needed = True _repository_url = "http...
--- +++ @@ -1,3 +1,10 @@+""" +Adapters for the cheat sheets from the Learn X in Y project + +Configuration parameters: + + log.level +""" # pylint: disable=relative-import @@ -9,6 +16,9 @@ class LearnXinY(GitRepositoryAdapter): + """ + Adapter for the LearnXinY project + """ _adapter_name = ...
https://raw.githubusercontent.com/chubin/cheat.sh/HEAD/lib/adapter/learnxiny.py
Document all public functions with docstrings
from __future__ import print_function import sys import os import textwrap import hashlib import re from itertools import groupby, chain from subprocess import Popen from tempfile import NamedTemporaryFile from config import CONFIG from languages_data import VIM_NAME import cache FNULL = open(os.devnull, "w") TEXT ...
--- +++ @@ -1,3 +1,22 @@+""" +Extract text from the text-code stream and comment it. + +Supports three modes of normalization and commenting: + + 1. Don't add any comments + 2. Add comments + 3. Remove text, leave code only + +Since several operations are quite expensive, +it actively uses caching. + +Exported...
https://raw.githubusercontent.com/chubin/cheat.sh/HEAD/lib/fmt/comments.py
Write documentation strings for class attributes
from __future__ import print_function import sys import logging def fatal(text): sys.stderr.write("ERROR: %s\n" % text) sys.exit(1) def error(text): if not text.startswith("Too many queries"): print(text) logging.error("ERROR %s", text) raise RuntimeError(text) def log(text): if ...
--- +++ @@ -1,3 +1,8 @@+""" +Global functions that our used everywhere in the project. +Please, no global variables here. +For the configuration related things see `config.py` +""" from __future__ import print_function @@ -6,11 +11,19 @@ def fatal(text): + """ + Fatal error function. + + The function ...
https://raw.githubusercontent.com/chubin/cheat.sh/HEAD/lib/globals.py
Document functions with detailed explanations
# coding=utf-8 # Copyright 2018 The Google AI Language Team 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 ...
--- +++ @@ -12,6 +12,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +"""Run masked LM/next sentence masked_lm pre-training for BERT.""" from __future__ import absolute_import fro...
https://raw.githubusercontent.com/google-research/bert/HEAD/run_pretraining.py
Add docstrings to meet PEP guidelines
# coding=utf-8 # Copyright 2018 The Google AI Language Team 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 ...
--- +++ @@ -12,6 +12,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +"""Extract pre-computed feature vectors from BERT.""" from __future__ import absolute_import from __future__ ...
https://raw.githubusercontent.com/google-research/bert/HEAD/extract_features.py
Insert docstrings into my code
# coding=utf-8 # Copyright 2018 The Google AI Language Team 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 ...
--- +++ @@ -12,6 +12,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +"""Functions and classes related to optimization (weight updates).""" from __future__ import absolute_import ...
https://raw.githubusercontent.com/google-research/bert/HEAD/optimization.py
Write documentation strings for class attributes
# coding=utf-8 # Copyright 2018 The Google AI Language Team 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 ...
--- +++ @@ -12,6 +12,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +"""BERT finetuning runner.""" from __future__ import absolute_import from __future__ import division @@ -124,...
https://raw.githubusercontent.com/google-research/bert/HEAD/run_classifier.py
Help me document legacy Python code
# coding=utf-8 # Copyright 2018 The Google AI Language Team 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 ...
--- +++ @@ -12,6 +12,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +"""Create masked LM/next sentence masked_lm TF examples for BERT.""" from __future__ import absolute_import f...
https://raw.githubusercontent.com/google-research/bert/HEAD/create_pretraining_data.py
Expand my code with proper documentation strings
# coding=utf-8 # Copyright 2018 The Google AI Language Team 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 ...
--- +++ @@ -12,6 +12,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +"""The main BERT model and related functions.""" from __future__ import absolute_import from __future__ impor...
https://raw.githubusercontent.com/google-research/bert/HEAD/modeling.py
Write documentation strings for class attributes
# coding=utf-8 # Copyright 2018 The Google AI Language Team 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 ...
--- +++ @@ -12,6 +12,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +"""BERT finetuning runner with TF-Hub.""" from __future__ import absolute_import from __future__ import divis...
https://raw.githubusercontent.com/google-research/bert/HEAD/run_classifier_with_tfhub.py
Create docstrings for reusable components
# coding=utf-8 # Copyright 2018 The Google AI Language Team 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 ...
--- +++ @@ -12,6 +12,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +"""Run BERT on SQuAD 1.1 and SQuAD 2.0.""" from __future__ import absolute_import from __future__ import divi...
https://raw.githubusercontent.com/google-research/bert/HEAD/run_squad.py
Add docstrings for internal functions
# coding=utf-8 # Copyright 2018 The Google AI Language Team 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 ...
--- +++ @@ -12,6 +12,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +"""Tokenization classes.""" from __future__ import absolute_import from __future__ import division @@ -25,6 +...
https://raw.githubusercontent.com/google-research/bert/HEAD/tokenization.py
Generate descriptive docstrings automatically
import base64 import dataclasses from enum import auto, IntEnum from io import BytesIO import os from typing import List, Any, Dict, Union, Tuple class SeparatorStyle(IntEnum): ADD_COLON_SINGLE = auto() ADD_COLON_TWO = auto() ADD_COLON_SPACE_SINGLE = auto() NO_COLON_SINGLE = auto() NO_COLON_TWO ...
--- +++ @@ -1,3 +1,9 @@+""" +Conversation prompt templates. + +We kindly request that you import fastchat instead of copying this file if you wish to use it. +If you have any changes in mind, please contribute back so the community can benefit collectively and continue to maintain these valuable templates. +""" impo...
https://raw.githubusercontent.com/lm-sys/FastChat/HEAD/fastchat/conversation.py
Add detailed documentation for each class
import argparse from collections import defaultdict import re import gradio as gr from fastchat.llm_judge.common import ( load_questions, load_model_answers, load_single_model_judgments, load_pairwise_model_judgments, resolve_single_judgment_dict, resolve_pairwise_judgment_dict, get_singl...
--- +++ @@ -1,3 +1,7 @@+""" +Usage: +python3 qa_browser.py --share +""" import argparse from collections import defaultdict @@ -111,6 +115,7 @@ def post_process_answer(x): + """Fix Markdown rendering problems.""" x = x.replace("\u2022", "- ") x = re.sub(newline_pattern1, "\n\g<1>", x) x = re.s...
https://raw.githubusercontent.com/lm-sys/FastChat/HEAD/fastchat/llm_judge/qa_browser.py
Add missing documentation to my Python functions
import dataclasses import gc import glob import os from accelerate import init_empty_weights from accelerate.utils import set_module_tensor_to_device from huggingface_hub import snapshot_download import torch from torch import Tensor from torch.nn import functional as F import torch.nn as nn from tqdm import tqdm from...
--- +++ @@ -22,6 +22,7 @@ @dataclasses.dataclass class CompressionConfig: + """Group-wise quantization.""" num_bits: int group_size: int @@ -36,6 +37,7 @@ class CLinear(nn.Module): + """Compressed Linear Layer.""" def __init__(self, weight=None, bias=None, device=None): super()....
https://raw.githubusercontent.com/lm-sys/FastChat/HEAD/fastchat/model/compression.py
Add docstrings to improve readability
import argparse from concurrent.futures import ProcessPoolExecutor import json from typing import Dict, Sequence, Optional import transformers from tqdm import tqdm def make_sample(sample, start_idx, end_idx): assert (end_idx - start_idx) % 2 == 0 return { "id": sample["id"] + "_" + str(start_idx), ...
--- +++ @@ -1,3 +1,11 @@+""" +Split long conversations based on certain max length. + +Usage: python3 -m fastchat.data.split_long_conversation \ + --in sharegpt_clean.json \ + --out sharegpt_split.json \ + --model-name-or-path $<model-name> +""" import argparse from concurrent.futures import ProcessPoolExecu...
https://raw.githubusercontent.com/lm-sys/FastChat/HEAD/fastchat/data/split_long_conversation.py
Help me comply with documentation standards
import ast import dataclasses import glob import json import os import re import time from typing import Optional import openai import anthropic from fastchat.model.model_adapter import ( get_conversation_template, ANTHROPIC_MODEL_LIST, OPENAI_MODEL_LIST, ) # API setting constants API_MAX_RETRY = 16 API...
--- +++ @@ -1,3 +1,6 @@+""" +Common data structures and utilities. +""" import ast import dataclasses @@ -83,6 +86,7 @@ def load_questions(question_file: str, begin: Optional[int], end: Optional[int]): + """Load questions from a file.""" questions = [] with open(question_file, "r") as ques_file: ...
https://raw.githubusercontent.com/lm-sys/FastChat/HEAD/fastchat/llm_judge/common.py
Add inline docstrings for readability
import json def identity_questions(): content = [] name = "Vicuna" org = "Large Model Systems Organization (LMSYS)" def generate_conversations(questions, answers): for q in questions: for a in answers: content.append( { ...
--- +++ @@ -1,7 +1,13 @@+""" +Hardcoded question and answers. +""" import json def identity_questions(): + """ " + Adapted from https://github.com/young-geng/koala_data_pipeline/blob/main/process_hard_coded_data.py + """ content = [] name = "Vicuna" @@ -159,4 +165,4 @@ content = [] c...
https://raw.githubusercontent.com/lm-sys/FastChat/HEAD/fastchat/data/hardcoded_questions.py
Write clean docstrings for readability
import math import os import re import sys from typing import Dict, List, Optional import warnings if sys.version_info >= (3, 9): from functools import cache else: from functools import lru_cache as cache import psutil import torch from transformers import ( AutoConfig, AutoModel, AutoModelForCau...
--- +++ @@ -1,3 +1,4 @@+"""Model adapter registration.""" import math import os @@ -94,6 +95,7 @@ class BaseModelAdapter: + """The base and the default model adapter.""" use_fast_tokenizer = True @@ -148,11 +150,13 @@ def register_model_adapter(cls): + """Register a model adapter.""" mod...
https://raw.githubusercontent.com/lm-sys/FastChat/HEAD/fastchat/model/model_adapter.py
Fully document this Python code with docstrings
import math from typing import List, Optional, Tuple import torch from torch import nn import transformers def rotate_half(x): x1 = x[..., : x.shape[-1] // 2].clone() x2 = x[..., x.shape[-1] // 2 :].clone() return torch.cat((-x2, x1), dim=-1) def apply_rotary_pos_emb(q, k, cos, sin, position_ids): ...
--- +++ @@ -1,3 +1,7 @@+""" +Monkey patch the llama implementation in the huggingface/transformers library. +Avoid bugs in mps backend by not using in-place operations. +""" import math from typing import List, Optional, Tuple @@ -7,6 +11,7 @@ def rotate_half(x): + """Rotates half the hidden dims of the inpu...
https://raw.githubusercontent.com/lm-sys/FastChat/HEAD/fastchat/model/monkey_patch_non_inplace.py
Add docstrings to meet PEP guidelines
import argparse import json import os import random import time import shortuuid import torch from tqdm import tqdm from fastchat.llm_judge.common import load_questions, temperature_config from fastchat.model import load_model, get_conversation_template from fastchat.utils import str_to_torch_dtype def run_eval( ...
--- +++ @@ -1,3 +1,8 @@+"""Generate answers with local models. + +Usage: +python3 gen_model_answer.py --model-path lmsys/fastchat-t5-3b-v1.0 --model-id fastchat-t5-3b-v1.0 +""" import argparse import json import os @@ -186,6 +191,7 @@ def reorg_answer_file(answer_file): + """Sort by question id and de-duplica...
https://raw.githubusercontent.com/lm-sys/FastChat/HEAD/fastchat/llm_judge/gen_model_answer.py
Add detailed documentation for each class
# Adapted from tatsu-lab@stanford_alpaca. Below is the original copyright: # Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may ob...
--- +++ @@ -73,6 +73,7 @@ def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str): + """Collects the state dict and dump to disk.""" state_dict = trainer.model.state_dict() if trainer.args.should_save: cpu_state_dict = {key: value.cpu() for key, value in state_dict.i...
https://raw.githubusercontent.com/lm-sys/FastChat/HEAD/fastchat/train/train_flant5.py
Expand my code with proper documentation strings
# This code is based on tatsu-lab/stanford_alpaca. Below is the original copyright: # # Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # ...
--- +++ @@ -69,6 +69,7 @@ def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str): + """Collects the state dict and dump to disk.""" state_dict = trainer.model.state_dict() if trainer.args.should_save: cpu_state_dict = {key: value.cpu() for key, value in state_dict.i...
https://raw.githubusercontent.com/lm-sys/FastChat/HEAD/fastchat/train/train_baichuan.py
Improve my code by adding docstrings
import asyncio import argparse import json import os from typing import Generator, Optional, Union, Dict, List, Any import aiohttp import fastapi from fastapi import Depends, HTTPException from fastapi.exceptions import RequestValidationError from fastapi.middleware.cors import CORSMiddleware from fastapi.responses im...
--- +++ @@ -1,3 +1,12 @@+"""A server that provides OpenAI-compatible RESTful APIs. It supports: + +- Chat Completions. (Reference: https://platform.openai.com/docs/api-reference/chat) +- Completions. (Reference: https://platform.openai.com/docs/api-reference/completions) +- Embeddings. (Reference: https://platform.open...
https://raw.githubusercontent.com/lm-sys/FastChat/HEAD/fastchat/serve/openai_api_server.py
Auto-generate documentation strings for this file
import os import math import multiprocessing as mp from functools import partial import numpy as np from scipy.special import expit from scipy.optimize import minimize import pandas as pd from tqdm import tqdm STYLE_CONTROL_ELEMENTS_V1 = [ "sum_assistant_a_tokens", "header_count_a", "list_count_a", "b...
--- +++ @@ -29,6 +29,11 @@ def preprocess_for_elo(df): + """ + in Elo we want numpy arrays for matchups and outcomes + matchups: int32 (N,2) contains model ids for the competitors in a match + outcomes: float64 (N,) contains 1.0, 0.5, or 0.0 representing win, tie, or loss for model_a + """ ...
https://raw.githubusercontent.com/lm-sys/FastChat/HEAD/fastchat/serve/monitor/rating_systems.py
Add professional docstrings to my codebase
# A JSON logger that sends data to remote endpoint. # Architecturally, it hosts a background thread that sends logs to a remote endpoint. import os import json import requests import threading import queue import logging _global_logger = None def get_remote_logger(): global _global_logger if _global_logger i...
--- +++ @@ -22,6 +22,7 @@ class EmptyLogger: + """Dummy logger that does nothing.""" def __init__(self): pass @@ -31,6 +32,7 @@ class RemoteLogger: + """A JSON logger that sends data to remote endpoint.""" def __init__(self, url: str): self.url = url @@ -54,4 +56,4 @@ ...
https://raw.githubusercontent.com/lm-sys/FastChat/HEAD/fastchat/serve/remote_logger.py
Write docstrings for utility functions
# This code is based on tatsu-lab/stanford_alpaca. Below is the original copyright: # # Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # ...
--- +++ @@ -69,6 +69,7 @@ def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str): + """Collects the state dict and dump to disk.""" state_dict = trainer.model.state_dict() if trainer.args.should_save: cpu_state_dict = {key: value.cpu() for key, value in state_dict.i...
https://raw.githubusercontent.com/lm-sys/FastChat/HEAD/fastchat/train/train_with_template.py
Generate docstrings for each module
from asyncio import AbstractEventLoop from io import BytesIO import base64 import json import logging import logging.handlers import os import platform import sys import time from typing import AsyncGenerator, Generator import warnings import requests from fastchat.constants import LOGDIR handler = None visited_log...
--- +++ @@ -1,3 +1,6 @@+""" +Common utilities. +""" from asyncio import AbstractEventLoop from io import BytesIO import base64 @@ -79,6 +82,9 @@ class StreamToLogger(object): + """ + Fake file-like stream object that redirects writes to a logger instance. + """ def __init__(self, logger, log_leve...
https://raw.githubusercontent.com/lm-sys/FastChat/HEAD/fastchat/utils.py
Add documentation for all methods
# This code is based on tatsu-lab/stanford_alpaca. Below is the original copyright: # # Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # ...
--- +++ @@ -314,6 +314,7 @@ class SupervisedDataset(Dataset): + """Dataset for supervised fine-tuning.""" def __init__( self, raw_data, data_args, tokenizer: transformers.PreTrainedTokenizer @@ -340,6 +341,7 @@ class LazySupervisedDataset(Dataset): + """Dataset for supervised fine-tuning."...
https://raw.githubusercontent.com/lm-sys/FastChat/HEAD/fastchat/train/train_yuan2.py
Turn comments into proper docstrings
# This code is based on tatsu-lab/stanford_alpaca. Below is the original copyright: # # Copyright 2023 Rohan Taori, Ishaan Gulrajani, Tianyi Zhang, Yann Dubois, Xuechen Li # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # ...
--- +++ @@ -178,6 +178,7 @@ class SupervisedDataset(Dataset): + """Dataset for supervised fine-tuning.""" def __init__(self, raw_data, tokenizer: transformers.PreTrainedTokenizer): super(SupervisedDataset, self).__init__() @@ -202,6 +203,7 @@ class LazySupervisedDataset(Dataset): + """Data...
https://raw.githubusercontent.com/lm-sys/FastChat/HEAD/fastchat/train/train.py
Add well-formatted docstrings
import enum from typing import Dict, List, Optional, Set, Tuple from vllm.block import PhysicalTokenBlock from .sequence import Sequence, SequenceGroup, SequenceStatus from vllm.utils import Device # Mapping: logical block number -> physical block. BlockTable = List[PhysicalTokenBlock] class BlockAllocator: d...
--- +++ @@ -1,3 +1,4 @@+"""A block manager that manages token blocks.""" import enum from typing import Dict, List, Optional, Set, Tuple @@ -11,6 +12,12 @@ class BlockAllocator: + """Manages free physical token blocks for a device. + + The allocator maintains a list of free blocks and allocates a block wh...
https://raw.githubusercontent.com/2noise/ChatTTS/HEAD/ChatTTS/model/velocity/block_manager.py
Create Google-style docstrings for my code
from enum import IntEnum from functools import cached_property from typing import Callable, List, Optional, Union import torch _SAMPLING_EPS = 1e-5 class SamplingType(IntEnum): GREEDY = 0 RANDOM = 1 BEAM = 2 LogitsProcessor = Callable[[List[int], torch.Tensor], torch.Tensor] """LogitsProcessor is a f...
--- +++ @@ -1,3 +1,4 @@+"""Sampling parameters for text generation.""" from enum import IntEnum from functools import cached_property @@ -21,6 +22,74 @@ class SamplingParams: + """Sampling parameters for text generation. + + Overall, we follow the sampling parameters from the OpenAI text completion + A...
https://raw.githubusercontent.com/2noise/ChatTTS/HEAD/ChatTTS/model/velocity/sampling_params.py
Add docstrings to existing functions
# Copyright (c) 2022-2024, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # See LICENSE for license information. # # From https://github.com/NVIDIA/TransformerEngine/blob/main/docs/examples/te_llama/te_llama.py # # Edited by fumiama. import re from contextlib import contextmanager from typing import Dict imp...
--- +++ @@ -27,6 +27,9 @@ @contextmanager def replace_decoder(te_decoder_cls, llama_rms_norm_cls): + """ + Replace `LlamaDecoderLayer` with custom `TELlamaDecoderLayer`. + """ original_llama_decoder_cls = ( transformers.models.llama.modeling_llama.LlamaDecoderLayer ) @@ -45,6 +48,15 @@ ...
https://raw.githubusercontent.com/2noise/ChatTTS/HEAD/ChatTTS/model/cuda/te_llama.py
Document classes and their methods
from typing import List, Optional import torch from .sequence import ( PromptLogprobs, SampleLogprobs, SequenceGroup, SequenceStatus, ) class CompletionOutput: def __init__( self, index: int, text: str, token_ids: List[int], cumulative_logprob: float, ...
--- +++ @@ -10,6 +10,18 @@ class CompletionOutput: + """The output data of one completion output of a request. + + Args: + index: The index of the output in the request. + text: The generated output text. + token_ids: The token IDs of the generated output text. + cumulative_logprob...
https://raw.githubusercontent.com/2noise/ChatTTS/HEAD/ChatTTS/model/velocity/output.py
Create docstrings for API functions
import contextlib import torch import torch.nn as nn from vllm.config import ModelConfig from vllm.model_executor.models import ModelRegistry from vllm.model_executor.weight_utils import get_quant_config, initialize_dummy_weights from .llama import LlamaModel @contextlib.contextmanager def _set_default_torch_dtyp...
--- +++ @@ -1,3 +1,4 @@+"""Utilities for selecting and loading models.""" import contextlib @@ -13,6 +14,7 @@ @contextlib.contextmanager def _set_default_torch_dtype(dtype: torch.dtype): + """Sets the default torch dtype to the given dtype.""" old_dtype = torch.get_default_dtype() torch.set_default...
https://raw.githubusercontent.com/2noise/ChatTTS/HEAD/ChatTTS/model/velocity/model_loader.py
Document all endpoints with docstrings
from typing import Optional, Union, Tuple import os import torch from transformers import PretrainedConfig from vllm.logger import init_logger from vllm.transformers_utils.config import get_config from vllm.utils import get_cpu_memory, is_hip import argparse import dataclasses from dataclasses import dataclass log...
--- +++ @@ -19,6 +19,48 @@ class ModelConfig: + """Configuration for the model. + + Args: + model: Name or path of the huggingface model to use. + tokenizer: Name or path of the huggingface tokenizer to use. + tokenizer_mode: Tokenizer mode. "auto" will use the fast tokenizer if + ...
https://raw.githubusercontent.com/2noise/ChatTTS/HEAD/ChatTTS/model/velocity/configs.py
Generate consistent docstrings
import copy import enum from typing import Dict, List, Optional, Union import torch from vllm.block import LogicalTokenBlock from .sampling_params import SamplingParams PromptLogprobs = List[Optional[Dict[int, float]]] SampleLogprobs = List[Dict[int, float]] class SequenceStatus(enum.Enum): WAITING = enum.auto...
--- +++ @@ -1,3 +1,4 @@+"""Sequence and its related classes.""" import copy import enum @@ -11,6 +12,7 @@ class SequenceStatus(enum.Enum): + """Status of a sequence.""" WAITING = enum.auto() RUNNING = enum.auto() @@ -48,6 +50,17 @@ class SequenceData: + """Data associated with a sequence. ...
https://raw.githubusercontent.com/2noise/ChatTTS/HEAD/ChatTTS/model/velocity/sequence.py
Help me document legacy Python code
from io import BufferedWriter, BytesIO from pathlib import Path from typing import Dict, Tuple, Optional, Union, List import av from av.audio.frame import AudioFrame from av.audio.resampler import AudioResampler import numpy as np video_format_dict: Dict[str, str] = { "m4a": "mp4", } audio_format_dict: Dict[str...
--- +++ @@ -19,6 +19,9 @@ def wav2(i: BytesIO, o: BufferedWriter, format: str): + """ + https://github.com/fumiama/Retrieval-based-Voice-Conversion-WebUI/blob/412a9950a1e371a018c381d1bfb8579c4b0de329/infer/lib/audio.py#L20 + """ inp = av.open(i, "r") format = video_format_dict.get(format, format)...
https://raw.githubusercontent.com/2noise/ChatTTS/HEAD/tools/audio/av.py
Add structured docstrings to improve clarity
import wave from io import BytesIO import numpy as np from .np import float_to_int16 from .av import wav2 def _pcm_to_wav_buffer(wav: np.ndarray, sample_rate: int = 24000) -> BytesIO: # Create an in-memory byte stream buffer buf = BytesIO() # Open a WAV file stream in write mode with wave.open(buf, "...
--- +++ @@ -6,6 +6,13 @@ def _pcm_to_wav_buffer(wav: np.ndarray, sample_rate: int = 24000) -> BytesIO: + """ + Convert PCM audio data to a WAV format byte stream (internal utility function). + + :param wav: PCM data, NumPy array, typically in float32 format. + :param sample_rate: Sample rate (in Hz), de...
https://raw.githubusercontent.com/2noise/ChatTTS/HEAD/tools/audio/pcm.py
Generate docstrings with parameter types
import copy from collections import defaultdict import os import time from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, Union from vllm.config import CacheConfig, ModelConfig, ParallelConfig, SchedulerConfig from .scheduler import Scheduler, SchedulerOutputs from .configs import EngineArgs ...
--- +++ @@ -36,6 +36,31 @@ class LLMEngine: + """An LLM engine that receives requests and generates texts. + + This is the main class for the vLLM engine. It receives requests + from clients and generates texts from the LLM. It includes a tokenizer, a + language model (possibly distributed across multip...
https://raw.githubusercontent.com/2noise/ChatTTS/HEAD/ChatTTS/model/velocity/llm_engine.py
Create docstrings for all classes and functions
from typing import List, Optional, Union from tqdm import tqdm from transformers import PreTrainedTokenizer, PreTrainedTokenizerFast from vllm.utils import Counter from .configs import EngineArgs from .llm_engine import LLMEngine from .output import RequestOutput from .sampling_params import SamplingParams class LL...
--- +++ @@ -11,6 +11,59 @@ class LLM: + """An LLM for generating texts from given prompts and sampling parameters. + + This class includes a tokenizer, a language model (possibly distributed + across multiple GPUs), and GPU memory space allocated for intermediate + states (aka KV cache). Given a batch o...
https://raw.githubusercontent.com/2noise/ChatTTS/HEAD/ChatTTS/model/velocity/llm.py
Create docstrings for reusable components
import os from typing import Dict, List, Optional, Tuple import torch import torch.distributed from vllm.config import CacheConfig, ModelConfig, ParallelConfig, SchedulerConfig from vllm.model_executor import set_random_seed from vllm.model_executor.parallel_utils.communication_op import broadcast_object_list from v...
--- +++ @@ -1,3 +1,4 @@+"""A GPU worker class.""" import os from typing import Dict, List, Optional, Tuple @@ -16,6 +17,12 @@ class Worker: + """A worker class that executes (a partition of) the model on a GPU. + + Each worker is associated with a single GPU. The worker is responsible for + maintaining...
https://raw.githubusercontent.com/2noise/ChatTTS/HEAD/ChatTTS/model/velocity/worker.py
Add minimal docstrings for each function
# Copyright (c) Microsoft Corporation. import os from torch.utils.data import Dataset, DataLoader import copy from typing import Text, Union import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Function from ql...
--- +++ @@ -21,6 +21,19 @@ class ADARNN(Model): + """ADARNN Model + + Parameters + ---------- + d_feat : int + input dimension for each time step + metric: str + the evaluation metric used in early stop + optimizer : str + optimizer name + GPU : str + the GPU ID(s) u...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/model/pytorch_adarnn.py
Add docstrings to make code maintainable
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import division from __future__ import print_function import numpy as np import pandas as pd from typing import Text, Union import copy from ...utils import get_or_create_path from ...log import get_module_logger import torch im...
--- +++ @@ -178,6 +178,21 @@ class SFM(Model): + """SFM Model + + Parameters + ---------- + input_dim : int + input dimension + output_dim : int + output dimension + lr : float + learning rate + optimizer : str + optimizer name + GPU : int + the GPU ID used...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/model/pytorch_sfm.py
Add docstrings for utility scripts
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import io import os import copy import math import json import numpy as np import pandas as pd import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F try: from torch.ut...
--- +++ @@ -31,6 +31,33 @@ class TRAModel(Model): + """ + TRA Model + + Args: + model_config (dict): model config (will be used by RNN or Transformer) + tra_config (dict): TRA config (will be used by TRA) + model_type (str): which backbone model to use (RNN/Transformer) + lr (fl...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/model/pytorch_tra.py
Fully document this Python code with docstrings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import copy from typing import Iterable import pandas as pd import plotly.graph_objs as go from ..graph import ScatterGraph from ..analysis_position.parse_position import get_position_data def _get_figure_with_position( position: dict, la...
--- +++ @@ -14,6 +14,14 @@ def _get_figure_with_position( position: dict, label_data: pd.DataFrame, start_date=None, end_date=None ) -> Iterable[go.Figure]: + """Get average analysis figures + + :param position: position + :param label_data: + :param start_date: + :param end_date: + :return: + ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/report/analysis_position/rank_label.py
Add docstrings explaining edge cases
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import logging import os from pathlib import Path import sys import fire from jinja2 import Template, meta from ruamel.yaml import YAML import qlib from qlib.config import C from qlib.log import get_module_logger from qlib.model.trainer import...
--- +++ @@ -28,6 +28,16 @@ def sys_config(config, config_path): + """ + Configure the `sys` section + + Parameters + ---------- + config : dict + configuration of the workflow. + config_path : str + path of the configuration + """ sys_config = config.get("sys", {}) # a...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/cli/run.py
Add detailed docstrings explaining each function
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import copy import torch import warnings import numpy as np import pandas as pd from qlib.utils.data import guess_horizon from qlib.utils import init_instance_by_config from qlib.data.dataset import DatasetH device = "cuda" if torch.cuda.is_ava...
--- +++ @@ -21,6 +21,13 @@ def _create_ts_slices(index, seq_len): + """ + create time series slices from pandas index + + Args: + index (pd.MultiIndex): pandas multiindex with <instrument, datetime> order + seq_len (int): sequence length + """ assert isinstance(index, pd.MultiIndex), ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/data/dataset.py
Insert docstrings into my code
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from pathlib import Path from setuptools_scm import get_version try: from ._version import version as __version__ except ImportError: __version__ = get_version(root="..", relative_to=__file__) __version__bak = __version__ # This version...
--- +++ @@ -23,6 +23,22 @@ # init qlib def init(default_conf="client", **kwargs): + """ + + Parameters + ---------- + default_conf: str + the default value is client. Accepted values: client/server. + **kwargs : + clear_mem_cache: str + the default value is True; + ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/__init__.py
Add structured docstrings to improve clarity
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import numpy as np import torch from torch import nn from .utils import preds_to_weight_with_clamp, SingleMetaBase class TimeWeightMeta(SingleMetaBase): def __init__(self, hist_step_n, clip_weight=None, clip_method="clamp"): # clip...
--- +++ @@ -42,6 +42,12 @@ class PredNet(nn.Module): def __init__(self, step, hist_step_n, clip_weight=None, clip_method="tanh", alpha: float = 0.0): + """ + Parameters + ---------- + alpha : float + the regularization for sub model (useful when align meta model with linear...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/meta/data_selection/net.py
Write docstrings describing each step
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import numpy as np import pandas as pd from datetime import datetime from qlib.data.cache import H from qlib.data.data import Cal from qlib.data.ops import ElemOperator, PairOperator from qlib.utils.time import time_to_day_index def get_calenda...
--- +++ @@ -11,6 +11,22 @@ def get_calendar_day(freq="1min", future=False): + """ + Load High-Freq Calendar Date Using Memcache. + !!!NOTE: Loading the calendar is quite slow. So loading calendar before start multiprocessing will make it faster. + + Parameters + ---------- + freq : str + fr...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/ops/high_freq.py
Write docstrings that follow conventions
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import division from __future__ import print_function import numpy as np import pandas as pd import warnings from typing import Union, Literal from ..log import get_module_logger from ..utils import get_date_range from ..utils.r...
--- +++ @@ -24,6 +24,26 @@ def risk_analysis(r, N: int = None, freq: str = "day", mode: Literal["sum", "product"] = "sum"): + """Risk Analysis + NOTE: + The calculation of annualized return is different from the definition of annualized return. + It is implemented by design. + Qlib tries to cumulate ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/evaluate.py
Add docstrings for utility scripts
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # pylint: skip-file # flake8: noqa import pathlib import pickle import pandas as pd from ruamel.yaml import YAML from ...data import D from ...config import C from ...log import get_module_logger from ...utils import get_next_trading_date from ....
--- +++ @@ -19,6 +19,14 @@ def load_instance(file_path): + """ + load a pickle file + Parameter + file_path : string / pathlib.Path() + path of file to be loaded + :return + An instance loaded from file + """ file_path = pathlib.Path(file_path) if...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/online/utils.py
Add detailed docstrings explaining each function
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import pandas as pd import numpy as np from qlib.contrib.report.data.base import FeaAnalyser from qlib.contrib.report.utils import sub_fig_generator from qlib.utils.paral import datetime_groupby_apply from qlib.contrib.eva.alpha import pred_autoc...
--- +++ @@ -1,5 +1,17 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +""" +Here we have a comprehensive set of analysis classes. + +Here is an example. + +.. code-block:: python + + from qlib.contrib.report.data.ana import FeaMeanStd + fa = FeaMeanStd(ret_df) + fa.plot_all(wspace=...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/report/data/ana.py
Generate docstrings for each module
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import annotations import os import re import copy import logging import platform import multiprocessing from pathlib import Path from typing import Callable, Optional, Union from typing import TYPE_CHECKING from qlib.constant i...
--- +++ @@ -1,5 +1,15 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +""" +About the configs +================= + +The config will be based on _default_config. +Two modes are supported +- client +- server + +""" from __future__ import annotations @@ -27,6 +37,17 @@ class QSettings...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/config.py
Create docstrings for each class method
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # pylint: skip-file # flake8: noqa import logging from ...log import get_module_logger from ..evaluate import risk_analysis from ...data import D class User: def __init__(self, account, strategy, model, verbose=False): self.logger...
--- +++ @@ -13,6 +13,19 @@ class User: def __init__(self, account, strategy, model, verbose=False): + """ + A user in online system, which contains account, strategy and model three module. + Parameter + account : Account() + strategy : + ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/online/user.py
Provide docstrings following PEP 257
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import pandas as pd import numpy as np from copy import deepcopy from joblib import Parallel, delayed # pylint: disable=E0401 from typing import Dict, List, Union, Text, Tuple from qlib.data.dataset.utils import init_task_handler from qlib.data.d...
--- +++ @@ -27,6 +27,25 @@ self.exp_name = exp_name def setup(self, trainer=TrainerR, trainer_kwargs={}): + """ + after running this function `self.data_ic_df` will become set. + Each col represents a data. + Each row represents the Timestamp of performance of that data. + ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/meta/data_selection/dataset.py
Provide clean and structured docstrings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import numpy as np import torch from torch import nn from qlib.constant import EPS from qlib.log import get_module_logger class ICLoss(nn.Module): def __init__(self, skip_size=50): super().__init__() self.skip_size = skip_s...
--- +++ @@ -15,6 +15,15 @@ self.skip_size = skip_size def forward(self, pred, y, idx): + """forward. + FIXME: + - Some times it will be a slightly different from the result from `pandas.corr()` + - It may be caused by the precision problem of model; + + :param pred: + ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/meta/data_selection/utils.py
Add well-formatted docstrings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import pandas as pd import numpy as np import torch from torch import nn from torch import optim from tqdm.auto import tqdm import copy from typing import Union, List from ....model.meta.dataset import MetaTaskDataset from ....model.meta.model i...
--- +++ @@ -38,6 +38,9 @@ class MetaModelDS(MetaTaskModel): + """ + The meta-model for meta-learning-based data selection. + """ def __init__( self, @@ -52,6 +55,10 @@ alpha=0.0, loss_skip_thresh=50, ): + """ + loss_skip_size: int + The number ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/meta/data_selection/model.py
Generate docstrings for script automation
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import division from __future__ import print_function from collections import defaultdict import os import gc import numpy as np import pandas as pd from packaging import version from typing import Callable, Optional, Text, Unio...
--- +++ @@ -37,6 +37,22 @@ class DNNModelPytorch(Model): + """DNN Model + Parameters + ---------- + input_dim : int + input dimension + output_dim : int + output dimension + layers : tuple + layer sizes + lr : float + learning rate + optimizer : str + optim...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/model/pytorch_nn.py
Write docstrings describing each step
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import division from __future__ import print_function import copy import math from typing import Text, Union import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torch...
--- +++ @@ -27,6 +27,21 @@ class ADD(Model): + """ADD Model + + Parameters + ---------- + lr : float + learning rate + d_feat : int + input dimensions for each time step + metric : str + the evaluation metric used in early stop + optimizer : str + optimizer n...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/model/pytorch_add.py
Add docstrings that explain logic
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from pathlib import Path import pickle from typing import Optional, Union import pandas as pd import yaml from qlib.contrib.meta.data_selection.dataset import InternalData, MetaDatasetDS from qlib.contrib.meta.data_selection.model import MetaMod...
--- +++ @@ -68,6 +68,13 @@ class DDGDA(Rolling): + """ + It is a rolling based on DDG-DA + + **NOTE** + before running the example, please clean your previous results with following command + - `rm -r mlruns` + """ def __init__( self, @@ -82,6 +89,27 @@ working_dir: Optiona...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/rolling/ddgda.py
Expand my code with proper documentation strings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import division from __future__ import print_function from torch.utils.data import DataLoader import numpy as np import pandas as pd from typing import Union import copy import torch import torch.optim as optim from torch.optim...
--- +++ @@ -31,6 +31,23 @@ class GeneralPTNN(Model): + """ + Motivation: + We want to provide a Qlib General Pytorch Model Adaptor + You can reuse it for all kinds of Pytorch models. + It should include the training and predict process + + Parameters + ---------- + d_feat : int +...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/model/pytorch_general_nn.py
Write documentation strings for class attributes
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import numpy as np import cvxpy as cp from typing import Union, Optional, Dict, Any, List from qlib.log import get_module_logger from .base import BaseOptimizer logger = get_module_logger("EnhancedIndexingOptimizer") class EnhancedIndexingOp...
--- +++ @@ -13,6 +13,35 @@ class EnhancedIndexingOptimizer(BaseOptimizer): + """ + Portfolio Optimizer for Enhanced Indexing + + Notations: + w0: current holding weights + wb: benchmark weight + r: expected return + F: factor exposure + cov_b: factor covariance + v...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/strategy/optimizer/enhanced_indexing.py
Document all public functions with docstrings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from functools import partial import pandas as pd import plotly.graph_objs as go import statsmodels.api as sm import matplotlib.pyplot as plt from scipy import stats from typing import Sequence from qlib.typehint import Literal from ..graph ...
--- +++ @@ -19,6 +19,13 @@ def _group_return(pred_label: pd.DataFrame = None, reverse: bool = False, N: int = 5, **kwargs) -> tuple: + """ + + :param pred_label: + :param reverse: + :param N: + :return: + """ if reverse: pred_label["score"] *= -1 @@ -72,6 +79,12 @@ def _plot_qq...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/report/analysis_model/analysis_model_performance.py
Fully document this Python code with docstrings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import warnings import numpy as np import pandas as pd import lightgbm as lgb from ...model.base import ModelFT from ...data.dataset import DatasetH from ...data.dataset.handler import DataHandlerLP from ...model.interpret.base import LightGBMFI...
--- +++ @@ -13,6 +13,7 @@ class HFLGBModel(ModelFT, LightGBMFInt): + """LightGBM Model for high frequency prediction""" def __init__(self, loss="mse", **kwargs): if loss not in {"mse", "binary"}: @@ -22,6 +23,9 @@ self.model = None def _cal_signal_metrics(self, y_test, l_cut, r_cut...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/model/highfreq_gdbt_model.py
Help me write clear docstrings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import division from __future__ import print_function import numpy as np import pandas as pd from typing import Text, Union import copy from ...utils import get_or_create_path from ...log import get_module_logger import torch i...
--- +++ @@ -37,6 +37,27 @@ device, **params, ): + """Build a Sandwich model + + Parameters + ---------- + fea_dim : int + The feature dimension + cnn_dim_1 : int + The hidden dimension of the first CNN + cnn_dim_2 : int + T...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/model/pytorch_sandwich.py
Generate missing documentation strings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import pandas as pd from typing import Dict, Iterable, Union def align_index(df_dict, join): res = {} for k, df in df_dict.items(): if join is not None and k != join: df = df.reindex(df_dict[join].index) res[k...
--- +++ @@ -15,12 +15,35 @@ # Mocking the pd.DataFrame class class SepDataFrame: + """ + (Sep)erate DataFrame + We usually concat multiple dataframe to be processed together(Such as feature, label, weight, filter). + However, they are usually be used separately at last. + This will result in extra cos...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/data/utils/sepdf.py
Improve my code by adding docstrings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import pandas as pd from ..graph import SubplotsGraph, BaseGraph def _calculate_maximum(df: pd.DataFrame, is_ex: bool = False): if is_ex: end_date = df["cum_ex_return_wo_cost_mdd"].idxmin() start_date = df.loc[df.index <= e...
--- +++ @@ -7,6 +7,12 @@ def _calculate_maximum(df: pd.DataFrame, is_ex: bool = False): + """ + + :param df: + :param is_ex: + :return: + """ if is_ex: end_date = df["cum_ex_return_wo_cost_mdd"].idxmin() start_date = df.loc[df.index <= end_date]["cum_ex_return_wo_cost"].idxmax(...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/report/analysis_position/report.py
Add documentation for all methods
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import warnings import numpy as np import pandas as pd import scipy.optimize as so from typing import Optional, Union, Callable, List from .base import BaseOptimizer class PortfolioOptimizer(BaseOptimizer): OPT_GMV = "gmv" OPT_MVO = ...
--- +++ @@ -12,6 +12,17 @@ class PortfolioOptimizer(BaseOptimizer): + """Portfolio Optimizer + + The following optimization algorithms are supported: + - `gmv`: Global Minimum Variance Portfolio + - `mvo`: Mean Variance Optimized Portfolio + - `rp`: Risk Parity + - `inv`: Inverse V...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/strategy/optimizer/optimizer.py
Add docstrings for internal functions
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from typing import Iterable import pandas as pd import plotly.graph_objs as py from ...evaluate import risk_analysis from ..graph import SubplotsGraph, ScatterGraph def _get_risk_analysis_data_with_report( report_normal_df: pd.DataFrame...
--- +++ @@ -17,6 +17,13 @@ # report_long_short_df: pd.DataFrame, date: pd.Timestamp, ) -> pd.DataFrame: + """Get risk analysis data with report + + :param report_normal_df: report data + :param report_long_short_df: report data + :param date: date string + :return: + """ analysis = di...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/report/analysis_position/risk_analysis.py
Write docstrings for algorithm functions
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import lightgbm as lgb import numpy as np import pandas as pd from typing import Text, Union from ...model.base import Model from ...data.dataset import DatasetH from ...data.dataset.handler import DataHandlerLP from ...model.interpret.base impor...
--- +++ @@ -13,6 +13,7 @@ class DEnsembleModel(Model, FeatureInt): + """Double Ensemble Model""" def __init__( self, @@ -137,6 +138,17 @@ return dtrain, dvalid def sample_reweight(self, loss_curve, loss_values, k_th): + """ + the SR module of Double Ensemble + ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/model/double_ensemble.py
Add return value explanations in docstrings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from .order_generator import OrderGenWInteract from .signal_strategy import WeightStrategyBase class SoftTopkStrategy(WeightStrategyBase): def __init__( self, model=None, dataset=None, topk=None, orde...
--- +++ @@ -18,6 +18,20 @@ buy_method="first_fill", **kwargs, ): + """ + Refactored SoftTopkStrategy with a budget-constrained rebalancing engine. + + Parameters + ---------- + topk : int + The number of top-N stocks to be held in the portfolio. + ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/strategy/cost_control.py
Document this script properly
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import matplotlib.pyplot as plt import pandas as pd def sub_fig_generator(sub_figsize=(3, 3), col_n=10, row_n=1, wspace=None, hspace=None, sharex=False, sharey=False): assert col_n > 1 while True: fig, axes = plt.subplots( ...
--- +++ @@ -5,6 +5,30 @@ def sub_fig_generator(sub_figsize=(3, 3), col_n=10, row_n=1, wspace=None, hspace=None, sharex=False, sharey=False): + """sub_fig_generator. + it will return a generator, each row contains <col_n> sub graph + + FIXME: Known limitation: + - The last row will not be plotted automat...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/report/utils.py
Improve my code by adding docstrings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import division from __future__ import print_function import numpy as np import pandas as pd from scipy.stats import spearmanr, pearsonr from ..data import D from collections import OrderedDict def _get_position_value_from_d...
--- +++ @@ -15,6 +15,14 @@ def _get_position_value_from_df(evaluate_date, position, close_data_df): + """Get position value by existed close data df + close_data_df: + pd.DataFrame + multi-index + close_data_df['$close'][stock_id][evaluate_date]: close price for (stock_id, evaluate_date) ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/evaluate_portfolio.py
Create Google-style docstrings for my code
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import copy from typing import Iterable import pandas as pd import plotly.graph_objs as go from ..graph import BaseGraph, SubplotsGraph from ..analysis_position.parse_position import get_position_data def _get_cum_return_data_with_position( ...
--- +++ @@ -19,6 +19,15 @@ start_date=None, end_date=None, ): + """ + + :param position: + :param report_normal: + :param label_data: + :param start_date: + :param end_date: + :return: + """ _cumulative_return_df = get_position_data( position=position, report_nor...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/report/analysis_position/cumulative_return.py
Write docstrings describing each step
import pandas as pd from typing import Tuple from qlib import get_module_logger from qlib.utils.paral import complex_parallel, DelayedDict from joblib import Parallel, delayed def calc_long_short_prec( pred: pd.Series, label: pd.Series, date_col="datetime", quantile: float = 0.2, dropna=False, is_alpha=False ) -...
--- +++ @@ -1,3 +1,8 @@+""" +Here is a batch of evaluation functions. + +The interface should be redesigned carefully in the future. +""" import pandas as pd from typing import Tuple @@ -9,6 +14,30 @@ def calc_long_short_prec( pred: pd.Series, label: pd.Series, date_col="datetime", quantile: float = 0.2, dropn...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/eva/alpha.py
Create docstrings for each class method
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import abc class BaseOptimizer(abc.ABC): @abc.abstractmethod def __call__(self, *args, **kwargs) -> object:
--- +++ @@ -5,6 +5,8 @@ class BaseOptimizer(abc.ABC): + """Construct portfolio with a optimization related method""" @abc.abstractmethod - def __call__(self, *args, **kwargs) -> object:+ def __call__(self, *args, **kwargs) -> object: + """Generate a optimized portfolio allocation"""
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/strategy/optimizer/base.py
Document functions with clear intent
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from pathlib import Path import warnings import numpy as np import pandas as pd from typing import IO, List, Tuple, Union from qlib.data.dataset.utils import convert_index_format from qlib.utils import lazy_sort_index from ...utils.resam import ...
--- +++ @@ -20,8 +20,19 @@ class TWAPStrategy(BaseStrategy): + """TWAP Strategy for trading + + NOTE: + - This TWAP strategy will celling round when trading. This will make the TWAP trading strategy produce the order + earlier when the total trade unit of amount is less than the trading step +...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/strategy/rule_strategy.py
Add docstrings to existing functions
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import pandas as pd from qlib.log import TimeInspector from qlib.contrib.report.utils import sub_fig_generator class FeaAnalyser: def __init__(self, dataset: pd.DataFrame): self._dataset = dataset with TimeInspector.logt("ca...
--- +++ @@ -1,5 +1,12 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +""" +This module is responsible for analysing data + +Assumptions +- The analyse each feature individually + +""" import pandas as pd from qlib.log import TimeInspector @@ -8,6 +15,24 @@ class FeaAnalyser: def...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/report/data/base.py
Document all public functions with docstrings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import math import importlib from typing import Iterable import pandas as pd import plotly.offline as py import plotly.graph_objs as go from plotly.subplots import make_subplots from plotly.figure_factory import create_distplot class BaseGra...
--- +++ @@ -20,6 +20,18 @@ def __init__( self, df: pd.DataFrame = None, layout: dict = None, graph_kwargs: dict = None, name_dict: dict = None, **kwargs ): + """ + + :param df: + :param layout: + :param graph_kwargs: + :param name_dict: + :param kwargs: + ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/report/graph.py
Create docstrings for each class method
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from copy import deepcopy from pathlib import Path from ruamel.yaml import YAML from typing import List, Optional, Union import fire import pandas as pd from qlib import auto_init from qlib.log import get_module_logger from qlib.model.ens.ensemb...
--- +++ @@ -22,6 +22,33 @@ class Rolling: + """ + The motivation of Rolling Module + - It only focus **offlinely** turn a specific task to rollinng + - To make the implementation easier, following factors are ignored. + - The tasks is dependent (e.g. time series). + + Related modules and diffe...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/rolling/base.py
Add detailed docstrings explaining each function
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # pylint: skip-file # flake8: noqa import fire import pandas as pd import pathlib import qlib import logging from ...data import D from ...log import get_module_logger from ...utils import get_pre_trading_date, is_tradable_date from ..evaluate ...
--- +++ @@ -1,212 +1,320 @@-# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - -# pylint: skip-file -# flake8: noqa - -import fire -import pandas as pd -import pathlib -import qlib -import logging - -from ...data import D -from ...log import get_module_logger -from ...utils import get_pre_tradi...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/online/operator.py
Write docstrings for utility functions
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import division from __future__ import print_function import numpy as np import pandas as pd from typing import Text, Union import copy from ...utils import get_or_create_path from ...log import get_module_logger import torch imp...
--- +++ @@ -50,6 +50,12 @@ pretrain=True, pretrain_file=None, ): + """ + TabNet model for Qlib + + Args: + ps: probability to generate the bernoulli mask + """ # set hyper-parameters. self.d_feat = d_feat self.out_dim = out_dim @@ -351,...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/model/pytorch_tabnet.py
Create structured documentation for my script
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from ...backtest.position import Position from ...backtest.exchange import Exchange import pandas as pd import copy class OrderGenerator: def generate_order_list_from_target_weight_position( self, current: Position, ...
--- +++ @@ -1,6 +1,9 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +""" +This order generator is for strategies based on WeightStrategyBase +""" from ...backtest.position import Position from ...backtest.exchange import Exchange @@ -21,10 +24,32 @@ trade_start_time: pd.Times...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/strategy/order_generator.py
Create docstrings for API functions
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import numpy as np import pandas as pd import lightgbm as lgb from typing import List, Text, Tuple, Union from ...model.base import ModelFT from ...data.dataset import DatasetH from ...data.dataset.handler import DataHandlerLP from ...model.inter...
--- +++ @@ -14,6 +14,7 @@ class LGBModel(ModelFT, LightGBMFInt): + """LightGBM Model""" def __init__(self, loss="mse", early_stopping_rounds=50, num_boost_round=1000, **kwargs): if loss not in {"mse", "binary"}: @@ -25,6 +26,10 @@ self.model = None def _prepare_data(self, dataset: ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/model/gbdt.py
Document this code for team use
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import pandas as pd from ....backtest.profit_attribution import get_stock_weight_df def parse_position(position: dict = None) -> pd.DataFrame: position_weight_df = get_stock_weight_df(position) # If the day does not exist, use the la...
--- +++ @@ -8,6 +8,28 @@ def parse_position(position: dict = None) -> pd.DataFrame: + """Parse position dict to position DataFrame + + :param position: position data + :return: position DataFrame; + + + .. code-block:: python + + position_df = parse_position(positions) + print(...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/report/analysis_position/parse_position.py
Generate docstrings with parameter types
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import division from __future__ import print_function import numpy as np import pandas as pd from typing import Text, Union import copy from ...utils import get_or_create_path from ...log import get_module_logger import torch i...
--- +++ @@ -1,403 +1,511 @@-# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - - -from __future__ import division -from __future__ import print_function - -import numpy as np -import pandas as pd -from typing import Text, Union -import copy -from ...utils import get_or_create_path -from ...log ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/model/pytorch_krnn.py
Add docstrings including usage examples
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # pylint: skip-file # flake8: noqa import pathlib import pandas as pd import shutil from ruamel.yaml import YAML from ...backtest.account import Account from .user import User from .utils import load_instance, save_instance from ...utils import ...
--- +++ @@ -16,6 +16,27 @@ class UserManager: def __init__(self, user_data_path, save_report=True): + """ + This module is designed to manager the users in online system + all users' data were assumed to be saved in user_data_path + Parameter + user_data_path : stri...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/online/manager.py
Add documentation for all methods
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import numpy as np import pandas as pd from typing import Text, Union from qlib.log import get_module_logger from qlib.data.dataset.weight import Reweighter from scipy.optimize import nnls from sklearn.linear_model import LinearRegression, Ridge,...
--- +++ @@ -15,6 +15,15 @@ class LinearModel(Model): + """Linear Model + + Solve one of the following regression problems: + - `ols`: min_w |y - Xw|^2_2 + - `nnls`: min_w |y - Xw|^2_2, s.t. w >= 0 + - `ridge`: min_w |y - Xw|^2_2 + \alpha*|w|^2_2 + - `lasso`: min_w |y - Xw|^2_2 + \a...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/model/linear.py
Add docstrings to improve code quality
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import os import copy import warnings import numpy as np import pandas as pd from typing import Dict, List, Text, Tuple, Union from abc import ABC from qlib.data import D from qlib.data.dataset import Dataset from qlib.model.base import BaseMode...
--- +++ @@ -35,6 +35,23 @@ common_infra=None, **kwargs, ): + """ + Parameters + ----------- + signal : + the information to describe a signal. Please refer to the docs of `qlib.backtest.signal.create_signal_from` + the decision of the strategy will...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/strategy/signal_strategy.py
Fully document this Python code with docstrings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import print_function from abc import abstractmethod import re import pandas as pd import numpy as np import abc from .data import Cal, DatasetD class BaseDFilter(abc.ABC): def __init__(self): pass @staticmet...
--- +++ @@ -13,28 +13,86 @@ class BaseDFilter(abc.ABC): + """Dynamic Instruments Filter Abstract class + + Users can override this class to construct their own filter + + Override __init__ to input filter regulations + + Override filter_main to use the regulations to filter instruments + """ d...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/data/filter.py
Help me add docstrings to my project
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import division from __future__ import print_function import numpy as np import pandas as pd from typing import Union, List, Type from scipy.stats import percentileofscore from .base import Expression, ExpressionOps, Feature, P...
--- +++ @@ -35,6 +35,18 @@ #################### Element-Wise Operator #################### class ElemOperator(ExpressionOps): + """Element-wise Operator + + Parameters + ---------- + feature : Expression + feature instance + + Returns + ---------- + Expression + feature operation o...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/data/ops.py
Add clean documentation to messy code
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import division from __future__ import print_function import abc import pandas as pd from ..log import get_module_logger class Expression(abc.ABC): def __str__(self): return type(self).__name__ def __repr__(s...
--- +++ @@ -11,6 +11,17 @@ class Expression(abc.ABC): + """ + Expression base class + + Expression is designed to handle the calculation of data with the format below + data with two dimension for each instrument, + + - feature + - time: it could be observation time or period time. + + - ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/data/base.py
Add docstrings to meet PEP guidelines
from abc import abstractmethod import pandas as pd import numpy as np from .handler import DataHandler from typing import Union, List from qlib.log import get_module_logger from .utils import get_level_index, fetch_df_by_index, fetch_df_by_col class BaseHandlerStorage: @abstractmethod def fetch( se...
--- +++ @@ -10,6 +10,11 @@ class BaseHandlerStorage: + """ + Base data storage for datahandler + - pd.DataFrame is the default data storage format in Qlib datahandler + - If users want to use custom data storage, they should define subclass inherited BaseHandlerStorage, and implement the following metho...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/data/dataset/storage.py
Write proper docstrings for these functions
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import annotations import pandas as pd from typing import Union, List, TYPE_CHECKING from qlib.utils import init_instance_by_config if TYPE_CHECKING: from qlib.data.dataset import DataHandler def get_level_index(df: pd.DataF...
--- +++ @@ -10,6 +10,22 @@ def get_level_index(df: pd.DataFrame, level: Union[str, int]) -> int: + """ + + get the level index of `df` given `level` + + Parameters + ---------- + df : pd.DataFrame + data + level : Union[str, int] + index level + + Returns + ------- + int: + ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/data/dataset/utils.py
Add detailed docstrings explaining each function
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import abc from qlib.model.meta.task import MetaTask from typing import Dict, Union, List, Tuple, Text from ...utils.serial import Serializable class MetaTaskDataset(Serializable, metaclass=abc.ABCMeta): def __init__(self, segments: Union[...
--- +++ @@ -8,12 +8,56 @@ class MetaTaskDataset(Serializable, metaclass=abc.ABCMeta): + """ + A dataset fetching the data in a meta-level. + + A Meta Dataset is responsible for + + - input tasks(e.g. Qlib tasks) and prepare meta tasks + + - meta task contains more information than normal tasks (e...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/model/meta/dataset.py
Add docstrings to existing functions
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import annotations from typing import TYPE_CHECKING, Generic, Optional, TypeVar from qlib.typehint import final from .simulator import StateType if TYPE_CHECKING: from .utils.env_wrapper import EnvWrapper __all__ = ["Aux...
--- +++ @@ -19,6 +19,7 @@ class AuxiliaryInfoCollector(Generic[StateType, AuxInfoType]): + """Override this class to collect customized auxiliary information from environment.""" env: Optional[EnvWrapper] = None @@ -27,4 +28,16 @@ return self.collect(simulator_state) def collect(self, sim...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/rl/aux_info.py
Write proper docstrings for these functions
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import division from __future__ import print_function import os import sys import stat import time import pickle import traceback import redis_lock import contextlib import abc from pathlib import Path import numpy as np import ...
--- +++ @@ -42,6 +42,7 @@ class MemCacheUnit(abc.ABC): + """Memory Cache Unit.""" def __init__(self, *args, **kwargs): self.size_limit = kwargs.pop("size_limit", 0) @@ -83,6 +84,7 @@ @property def limited(self): + """whether memory cache is limited""" return self.size_l...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/data/cache.py
Add docstrings following best practices
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import abc from pathlib import Path import warnings import pandas as pd from typing import Tuple, Union, List, Dict from qlib.data import D from qlib.utils import load_dataset, init_instance_by_config, time_to_slc_point from qlib.utils.pickle_u...
--- +++ @@ -16,14 +16,75 @@ class DataLoader(abc.ABC): + """ + DataLoader is designed for loading raw data from original data source. + """ @abc.abstractmethod def load(self, instruments, start_time=None, end_time=None) -> pd.DataFrame: + """ + load the data as pd.DataFrame. + + ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/data/dataset/loader.py