instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Auto-generate documentation strings for this file
import abc import asyncio import base64 import functools import hashlib import logging import os import sys import struct import tornado from urllib.parse import urlparse import warnings import zlib from tornado.concurrent import Future, future_set_result_unless_cancelled from tornado.escape import utf8, native_str, ...
--- +++ @@ -1,3 +1,15 @@+"""Implementation of the WebSocket protocol. + +`WebSockets <http://dev.w3.org/html5/websockets/>`_ allow for bidirectional +communication between the browser and server. WebSockets are supported in the +current versions of all major browsers. + +This module implements the final version of the ...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/websocket.py
Add professional docstrings to my codebase
# Copyright 2015 The Tornado Authors # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
--- +++ @@ -12,6 +12,168 @@ # License for the specific language governing permissions and limitations # under the License. +"""Flexible routing implementation. + +Tornado routes HTTP requests to appropriate handlers using `Router` +class implementations. The `tornado.web.Application` class is a +`Router` implementat...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/routing.py
Generate docstrings with parameter types
# # Copyright 2009 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
--- +++ @@ -13,6 +13,188 @@ # License for the specific language governing permissions and limitations # under the License. +"""A simple template system that compiles templates to Python code. + +Basic usage looks like:: + + t = template.Template("<html>{{ myvalue }}</html>") + print(t.generate(myvalue="XXX")) ...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/template.py
Create documentation strings for testing functions
import asyncio import builtins import collections from collections.abc import Generator import concurrent.futures import datetime import functools from functools import singledispatch from inspect import isawaitable import sys import types from tornado.concurrent import ( Future, is_future, chain_future, ...
--- +++ @@ -1,3 +1,65 @@+"""``tornado.gen`` implements generator-based coroutines. + +.. note:: + + The "decorator and generator" approach in this module is a + precursor to native coroutines (using ``async def`` and ``await``) + which were introduced in Python 3.5. Applications that do not + require compatibil...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/gen.py
Add docstrings for internal functions
# # Copyright 2009 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
--- +++ @@ -13,6 +13,7 @@ # License for the specific language governing permissions and limitations # under the License. +"""Non-blocking HTTP client implementation using pycurl.""" import collections import functools @@ -107,6 +108,9 @@ self._set_timeout(0) def _handle_socket(self, event: int, fd...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/curl_httpclient.py
Add docstrings to my Python code
import asyncio import atexit import concurrent.futures import contextvars import errno import functools import select import socket import sys import threading import typing import warnings from tornado.gen import convert_yielded from tornado.ioloop import IOLoop, _Selectable from typing import ( Any, Callabl...
--- +++ @@ -1,3 +1,26 @@+"""Bridges between the `asyncio` module and Tornado IOLoop. + +.. versionadded:: 3.2 + +This module integrates Tornado with the ``asyncio`` module introduced +in Python 3.4. This makes it possible to combine the two libraries on +the same event loop. + +.. deprecated:: 5.0 + + While the code ...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/platform/asyncio.py
Add docstrings that explain purpose and usage
import datetime import functools from io import BytesIO import ssl import time import weakref from tornado.concurrent import ( Future, future_set_result_unless_cancelled, future_set_exception_unless_cancelled, ) from tornado.escape import utf8, native_str from tornado import gen, httputil from tornado.iol...
--- +++ @@ -1,3 +1,40 @@+"""Blocking and non-blocking HTTP client interfaces. + +This module defines a common interface shared by two implementations, +``simple_httpclient`` and ``curl_httpclient``. Applications may either +instantiate their chosen implementation class directly or use the +`AsyncHTTPClient` class from...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/httpclient.py
Add minimal docstrings for each function
# # Copyright 2014 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
--- +++ @@ -13,6 +13,10 @@ # License for the specific language governing permissions and limitations # under the License. +"""Client and server implementations of HTTP/1.x. + +.. versionadded:: 4.0 +""" import asyncio import logging @@ -43,6 +47,10 @@ class _ExceptionLoggingContext: + """Used with the ``w...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/http1connection.py
Write Python docstrings for this snippet
# # Copyright 2009 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
--- +++ @@ -13,6 +13,15 @@ # License for the specific language governing permissions and limitations # under the License. +"""Utility classes to write to and read from non-blocking files and sockets. + +Contents: + +* `BaseIOStream`: Generic interface for reading and writing. +* `IOStream`: Implementation of BaseIOS...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/iostream.py
Write documentation strings for class attributes
# # Copyright 2009 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
--- +++ @@ -13,6 +13,91 @@ # License for the specific language governing permissions and limitations # under the License. +"""A command line parsing module that lets modules define their own options. + +This module is inspired by Google's `gflags +<https://github.com/google/python-gflags>`_. The primary difference +...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/options.py
Write docstrings including parameters and return values
# # Copyright 2009 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
--- +++ @@ -13,6 +13,61 @@ # License for the specific language governing permissions and limitations # under the License. +"""This module contains implementations of various third-party +authentication schemes. + +All the classes in this file are class mixins designed to be used with +the `tornado.web.RequestHandler...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/auth.py
Generate missing documentation strings
# # Copyright 2009 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
--- +++ @@ -13,6 +13,19 @@ # License for the specific language governing permissions and limitations # under the License. +"""WSGI support for the Tornado web framework. + +WSGI is the Python standard for web servers, and allows for interoperability +between Tornado and other Python web frameworks and servers. + +Th...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/wsgi.py
Add docstrings to meet PEP guidelines
# # Copyright 2011 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
--- +++ @@ -13,6 +13,9 @@ # License for the specific language governing permissions and limitations # under the License. +"""Utilities for working with multiple processes, including both forking +the server into multiple processes and managing subprocesses. +""" import asyncio import os @@ -44,6 +47,7 @@ def...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/process.py
Add structured docstrings to improve clarity
# # Copyright 2009 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
--- +++ @@ -13,6 +13,15 @@ # License for the specific language governing permissions and limitations # under the License. +"""An I/O event loop for non-blocking sockets. + +In Tornado 6.0, `.IOLoop` is a wrapper around the `asyncio` event loop, with a +slightly different interface. The `.IOLoop` interface is now pro...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/ioloop.py
Create structured documentation for my script
# # Copyright 2009 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
--- +++ @@ -13,6 +13,35 @@ # License for the specific language governing permissions and limitations # under the License. +"""Automatically restart the server when a source file is modified. + +Most applications should not access this module directly. Instead, +pass the keyword argument ``autoreload=True`` to the +...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/autoreload.py
Document my Python code with docstrings
from tornado.escape import _unicode from tornado import gen, version from tornado.httpclient import ( HTTPResponse, HTTPError, AsyncHTTPClient, main, _RequestProxy, HTTPRequest, ) from tornado import httputil from tornado.http1connection import HTTP1Connection, HTTP1ConnectionParameters from tor...
--- +++ @@ -42,6 +42,13 @@ class HTTPTimeoutError(HTTPError): + """Error raised by SimpleAsyncHTTPClient on timeout. + + For historical reasons, this is a subclass of `.HTTPClientError` + which simulates a response code of 599. + + .. versionadded:: 5.1 + """ def __init__(self, message: str) -...
https://raw.githubusercontent.com/tornadoweb/tornado/HEAD/tornado/simple_httpclient.py
Write clean docstrings for readability
import argparse import json import os import subprocess import sys from pathlib import Path from typing import Any, Dict, List, Optional, Tuple, Type, TypeVar, Union from huggingface_hub import HfApi, snapshot_download # pylint: disable=import-error from huggingface_hub.utils import HfHubHTTPError # pylint: disable...
--- +++ @@ -1,3 +1,4 @@+"""Continuous model delivery for MLC LLM models.""" import argparse import json @@ -30,6 +31,9 @@ class OverrideConfigs(BaseModel): + """ + The class that specifies the override configurations. + """ context_window_size: Optional[int] = None sliding_window_size: Opti...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/cli/delivery.py
Include argument descriptions in docstrings
import os from pathlib import Path from typing import Union from mlc_llm.interface.help import HELP from mlc_llm.interface.package import package from mlc_llm.support.argparse import ArgumentParser def main(argv): parser = ArgumentParser("MLC LLM Package CLI") def _parse_package_config(path: Union[str, Pat...
--- +++ @@ -1,3 +1,4 @@+"""Command line entrypoint of package.""" import os from pathlib import Path @@ -9,6 +10,7 @@ def main(argv): + """Parse command line arguments and call `mlc_llm.interface.package`.""" parser = ArgumentParser("MLC LLM Package CLI") def _parse_package_config(path: Union[str...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/cli/package.py
Add docstrings to my Python code
from typing import Dict, List, Tuple import tvm from tvm import relax, tir from tvm.ir.module import IRModule from tvm.relax.analysis import remove_all_unused from tvm.relax.expr_functor import PyExprMutator, mutator @tvm.transform.module_pass(opt_level=0, name="LiftTIRGlobalBufferAlloc") class LiftTIRGlobalBufferA...
--- +++ @@ -1,3 +1,4 @@+"""A compiler pass that lifts TIR-level global allocation to Relax.""" from typing import Dict, List, Tuple @@ -10,12 +11,14 @@ @tvm.transform.module_pass(opt_level=0, name="LiftTIRGlobalBufferAlloc") class LiftTIRGlobalBufferAlloc: # pylint: disable=too-few-public-methods + """A com...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/compiler_pass/lift_global_buffer_alloc.py
Add docstrings following best practices
# pylint: disable=missing-docstring from __future__ import annotations from typing import Iterable, List, Optional, Sequence, Tuple import numpy as np from langchain.embeddings import OpenAIEmbeddings # pylint: disable=import-error from langchain_community.embeddings.openai import ( # pylint: disable=import-error ...
--- +++ @@ -17,6 +17,7 @@ class MLCEmbeddings(OpenAIEmbeddings): def _chunk_tokens(self, texts: Sequence[str]) -> Tuple[List[List], List[int]]: + """Tokenize and chunk texts to fit in the model's context window.""" if not self.embedding_ctx_length: raise ValueError( ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/contrib/embeddings/openai.py
Fill in missing docstrings in my code
import dataclasses import enum from io import StringIO from typing import Optional from mlc_llm.support import argparse, logging from mlc_llm.support.config import ConfigOverrideBase logger = logging.getLogger(__name__) class IPCAllReduceStrategyType(enum.IntEnum): NONE = 0 ONESHOT = 1 TWOSHOT = 2 ...
--- +++ @@ -1,3 +1,4 @@+"""Flags for overriding model config.""" import dataclasses import enum @@ -11,6 +12,7 @@ class IPCAllReduceStrategyType(enum.IntEnum): + """The all-reduce strategy.""" NONE = 0 ONESHOT = 1 @@ -20,6 +22,7 @@ @dataclasses.dataclass class OptimizationFlags: + """Optimi...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/interface/compiler_flags.py
Generate missing documentation strings
import argparse import asyncio import json import random import re from datetime import datetime from pathlib import Path from typing import List, Literal, Optional import tqdm from mlc_llm import AsyncMLCEngine DEVICES = ["cuda", "rocm", "metal", "vulkan"] ANSWER_TRIGGER = "The answer is" INVALID_ANS = "[invalid]"...
--- +++ @@ -1,3 +1,4 @@+"""Eval GSM8K with MLCEngine.""" import argparse import asyncio @@ -18,6 +19,7 @@ def extract_answer(text: str, regex: re.Pattern, select_index: int) -> str: + """Extract the answer from the text.""" match_all = regex.findall(text) if len(match_all) == 0: return INV...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/bench/evaluation/gsm8k.py
Generate documentation strings for clarity
import tvm from tvm import IRModule from tvm.script import tir as T from ..support.max_thread_check import ( check_thread_limits, get_max_num_threads_per_block, ) @tvm.transform.module_pass(opt_level=0, name="AttachLogitProcessFunc") class AttachLogitProcessFunc: # pylint: disable=too-few-public-methods ...
--- +++ @@ -1,3 +1,4 @@+"""The pass that attaches logit processor functions to the IRModule.""" import tvm from tvm import IRModule @@ -11,11 +12,20 @@ @tvm.transform.module_pass(opt_level=0, name="AttachLogitProcessFunc") class AttachLogitProcessFunc: # pylint: disable=too-few-public-methods + """Attach log...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/compiler_pass/attach_logit_processor.py
Add docstrings to my Python code
from typing import Dict, List, Optional, Tuple import tvm from tvm import relax, tir from tvm.ir.module import IRModule from tvm.relax.expr_functor import PyExprMutator, PyExprVisitor, mutator, visitor @tvm.transform.module_pass(opt_level=0, name="PipelineParallelRewrite") class PipelineParallelRewrite: # pylint: ...
--- +++ @@ -1,3 +1,4 @@+"""A compiler pass that rewrites IR for pipeline parallelism.""" from typing import Dict, List, Optional, Tuple @@ -9,12 +10,14 @@ @tvm.transform.module_pass(opt_level=0, name="PipelineParallelRewrite") class PipelineParallelRewrite: # pylint: disable=too-few-public-methods + """A co...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/compiler_pass/pipeline_parallel_rewrite.py
Fill in missing docstrings in my code
import argparse import json import random from datetime import datetime from typing import Dict, List, Optional, Tuple import numpy as np import pandas as pd # pylint: disable=import-error from datasets import load_dataset # pylint: disable=import-error from transformers import AutoTokenizer # pylint: disable=impo...
--- +++ @@ -1,3 +1,4 @@+"""MLC LLM benchmark dataset classes""" import argparse import json @@ -19,6 +20,7 @@ class Dataset: # pylint: disable=too-few-public-methods + """The dataset base class.""" # We set a truncation limit of 100k. truncate_length = int(1e5) @@ -37,10 +39,12 @@ input_...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/bench/dataset.py
Turn comments into proper docstrings
from mlc_llm.interface.chat import ModelConfigOverride, chat from mlc_llm.interface.help import HELP from mlc_llm.support.argparse import ArgumentParser def main(argv): parser = ArgumentParser("MLC LLM Chat CLI") parser.add_argument( "model", type=str, help=HELP["model"] + " (require...
--- +++ @@ -1,3 +1,4 @@+"""Command line entrypoint of chat.""" from mlc_llm.interface.chat import ModelConfigOverride, chat from mlc_llm.interface.help import HELP @@ -5,6 +6,7 @@ def main(argv): + """Parse command line arguments and call `mlc_llm.interface.chat`.""" parser = ArgumentParser("MLC LLM Cha...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/cli/chat.py
Add docstrings for production code
from typing import Any, Dict import tvm from tvm import IRModule, relax @tvm.transform.module_pass(opt_level=0, name="AttachAllocEmbeddingTensorFunc") class AttachAllocEmbeddingTensorFunc: # pylint: disable=too-few-public-methods def __init__(self, metadata: Dict[str, Any]): self.metadata = metadata ...
--- +++ @@ -1,3 +1,4 @@+"""The pass that attaches embedding allocation function to the IRModule.""" from typing import Any, Dict @@ -7,11 +8,13 @@ @tvm.transform.module_pass(opt_level=0, name="AttachAllocEmbeddingTensorFunc") class AttachAllocEmbeddingTensorFunc: # pylint: disable=too-few-public-methods + "...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/compiler_pass/attach_embedding_allocator.py
Write docstrings describing each step
# pylint: disable=invalid-name from typing import Optional import tvm from tvm import relax from tvm.relax.analysis import remove_all_unused from tvm.relax.expr_functor import PyExprMutator, mutator from tvm.script import tir as T from ..support.max_thread_check import get_max_num_threads_per_block def _get_add_r...
--- +++ @@ -1,3 +1,4 @@+"""A compiler pass that fuses add + rms_norm.""" # pylint: disable=invalid-name @@ -153,11 +154,20 @@ @tvm.transform.module_pass(opt_level=0, name="FuseAddRMSNorm") class FuseAddRMSNorm: # pylint: disable=too-few-public-methods + """A compiler pass that fuses add + rms_norm.""" ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/compiler_pass/fuse_add_norm.py
Add professional docstrings to my codebase
import dataclasses import json from io import StringIO from typing import Literal, Optional from mlc_llm.interface.help import HELP from mlc_llm.interface.serve import serve from mlc_llm.support import argparse from mlc_llm.support.argparse import ArgumentParser @dataclasses.dataclass class EngineConfigOverride: #...
--- +++ @@ -1,3 +1,4 @@+"""Command line entrypoint of serve.""" import dataclasses import json @@ -12,6 +13,7 @@ @dataclasses.dataclass class EngineConfigOverride: # pylint: disable=too-many-instance-attributes + """Arguments for overriding engine config.""" # Overrides for EngineConfig (runtime) ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/cli/serve.py
Add well-formatted docstrings
import tvm from tvm import tir from tvm.ir.module import IRModule from tvm.s_tir import dlight as dl # pylint: disable=too-many-locals,not-callable @tvm.transform.module_pass(opt_level=0, name="LowBatchGemvSpecialize") class LowBatchGemvSpecialize: # pylint: disable=too-few-public-methods def transform_module...
--- +++ @@ -1,3 +1,4 @@+"""A compiler pass that dispatch low-batch-gemm to gemv schedule.""" import tvm from tvm import tir @@ -9,12 +10,14 @@ @tvm.transform.module_pass(opt_level=0, name="LowBatchGemvSpecialize") class LowBatchGemvSpecialize: # pylint: disable=too-few-public-methods + """A compiler pass tha...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/compiler_pass/low_batch_specialization.py
Help me document legacy Python code
import dataclasses import json import os import shutil import subprocess import sys from pathlib import Path from typing import Any, Dict, List, Literal from mlc_llm.interface import jit from mlc_llm.support import download_cache, logging, style logging.enable_logging() logger = logging.getLogger(__name__) SUPPORTE...
--- +++ @@ -1,3 +1,4 @@+"""Python entrypoint of package.""" import dataclasses import json @@ -20,6 +21,7 @@ def build_model_library( # pylint: disable=too-many-branches,too-many-locals,too-many-statements package_config: Dict[str, Any], device: str, bundle_dir: Path, app_config_path: Path ) -> Dict[str, str...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/interface/package.py
Write beginner-friendly docstrings
# pylint: disable=fixme from http import HTTPStatus from typing import AsyncGenerator, List, Literal, Optional, Type import fastapi import uvicorn from fastapi.middleware.cors import CORSMiddleware from mlc_llm.protocol import error_protocol from mlc_llm.protocol.openai_api_protocol import CompletionLogProbs, Comple...
--- +++ @@ -1,3 +1,4 @@+"""Python entrypoint of router.""" # pylint: disable=fixme from http import HTTPStatus @@ -26,6 +27,7 @@ pd_balance_factor: float = 0.0, router_type: Type[Router] = Router, ): # pylint: disable=too-many-arguments + """Start the router with the specified configuration.""" #...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/interface/router.py
Create documentation for each function signature
import json import math from dataclasses import asdict from pathlib import Path from typing import Any, Dict, List, Union from tvm.runtime import DataType from mlc_llm.support import logging from mlc_llm.support.argparse import ArgumentParser from mlc_llm.support.config import ConfigBase from mlc_llm.support.style i...
--- +++ @@ -1,3 +1,4 @@+"""A tool that inspects the metadata of a model lib.""" import json import math @@ -142,6 +143,7 @@ def main(): + """Entry point for the model metadata tool.""" parser = ArgumentParser(description="A tool that inspects the metadata of a model lib.") parser.add_argument( ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/cli/model_metadata.py
Expand my code with proper documentation strings
from typing import Dict import tvm from tvm import relax from tvm.ir.module import IRModule from tvm.relax.analysis import remove_all_unused from tvm.relax.expr import Expr, Var from tvm.relax.expr_functor import PyExprMutator, mutator @tvm.transform.module_pass(opt_level=0, name="ScatterTupleGetItem") class Scatte...
--- +++ @@ -1,3 +1,4 @@+"""A compiler pass that scatters TupleGetItem for lazy TupleGetItems.""" from typing import Dict @@ -11,8 +12,10 @@ @tvm.transform.module_pass(opt_level=0, name="ScatterTupleGetItem") class ScatterTupleGetItem: # pylint: disable=too-few-public-methods + """A compiler pass that scatte...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/compiler_pass/scatter_tuple_get_item.py
Generate docstrings with parameter types
import json from pathlib import Path from typing import Any, Dict, List, Optional, Tuple import numpy as np import tvm import tvm_ffi from tvm import relax from tvm.contrib import tvmjs from tvm.runtime import Device, Module from tvm.runtime.vm import VirtualMachine from mlc_llm.serve import engine_utils from mlc_ll...
--- +++ @@ -1,3 +1,4 @@+"""The Python API for MLC Embeddings.""" import json from pathlib import Path @@ -49,8 +50,22 @@ class DefaultDebugInstrument: + """The default debug instrument to use if users don't specify + a customized one. + + This debug instrument will dump the arguments and output of each...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/contrib/embeddings/embeddings.py
Add docstrings following best practices
import dataclasses import hashlib import json import os import shlex import shutil import subprocess import sys import tempfile from pathlib import Path from typing import Any, Dict, Optional, Union from tvm.runtime import Device from mlc_llm.model import MODELS from mlc_llm.support import logging from mlc_llm.suppo...
--- +++ @@ -1,3 +1,4 @@+"""Just-in-time compilation of MLC-Chat models.""" import dataclasses import hashlib @@ -31,12 +32,14 @@ @dataclasses.dataclass class JITResult: + """The jit compilation result class.""" model_lib_path: str system_lib_prefix: Optional[str] = None def log_jit_policy(): ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/interface/jit.py
Generate missing documentation strings
import dataclasses from io import StringIO from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Tuple from tvm import IRModule, relax, tir from tvm.ir.transform import Pass, PassContext from tvm.relax.frontend import nn from tvm.target import Target from mlc_llm import compiler_pass as _ ...
--- +++ @@ -1,3 +1,4 @@+"""Python entrypoint of compilation.""" import dataclasses from io import StringIO @@ -25,6 +26,7 @@ @dataclasses.dataclass class CompileArgs: # pylint: disable=too-many-instance-attributes + """Arguments to MLC LLM's compiler.""" config: Path quantization: Quantization @@...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/interface/compile.py
Document helper functions with docstrings
import dataclasses from typing import Any, Dict, List, Optional, Union from prompt_toolkit import prompt as get_prompt # pylint: disable=import-error from prompt_toolkit.key_binding import KeyBindings # pylint: disable=import-error from mlc_llm.json_ffi import JSONFFIEngine from mlc_llm.protocol import openai_api_...
--- +++ @@ -1,3 +1,4 @@+"""Python entrypoint of chat.""" import dataclasses from typing import Any, Dict, List, Optional, Union @@ -45,6 +46,7 @@ @dataclasses.dataclass class ChatCompletionOverride(ConfigOverrideBase): # pylint: disable=too-many-instance-attributes + """Flags for overriding chat completions....
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/interface/chat.py
Add docstrings for utility scripts
import argparse import json import re from functools import partial from pathlib import Path from typing import Union from mlc_llm.interface.compile import ( # pylint: disable=redefined-builtin ModelConfigOverride, OptimizationFlags, compile, ) from mlc_llm.interface.help import HELP from mlc_llm.model i...
--- +++ @@ -1,3 +1,4 @@+"""Command line entrypoint of compilation.""" import argparse import json @@ -24,6 +25,7 @@ def main(argv): + """Parse command line arguments and call `mlc_llm.compiler.compile`.""" def _parse_output(path: Union[str, Path]) -> Path: path = Path(path) @@ -138,4 +140,4 @...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/cli/compile.py
Write docstrings for algorithm functions
# pylint: disable=E1101 import dataclasses import json import re import shutil from dataclasses import asdict from pathlib import Path from typing import Optional from mlc_llm.conversation_template import ConvTemplateRegistry from mlc_llm.model import Model from mlc_llm.protocol.mlc_chat_config import MLCChatConfig f...
--- +++ @@ -1,3 +1,4 @@+"""Generator of mlc-chat-config.json and tokenizer configuration.""" # pylint: disable=E1101 import dataclasses @@ -26,12 +27,14 @@ def apply_system_defaults_for_missing_fields(mlc_chat_config: MLCChatConfig) -> None: + """Apply system default value.""" for key, value in mlc_chat...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/interface/gen_config.py
Add docstrings to meet PEP guidelines
import tvm from tvm import IRModule, relax from tvm.relax.dpl.pattern import GlobalVarPattern, TuplePattern, is_op, wildcard @tvm.transform.module_pass(opt_level=0, name="FuseDequantizeMatmulEwise") class FuseDequantizeMatmulEwise: # pylint: disable=too-few-public-methods def transform_module( self, ...
--- +++ @@ -1,3 +1,4 @@+"""A compiler pass that fuses dequantize + matmul + elementwise.""" import tvm from tvm import IRModule, relax @@ -6,12 +7,14 @@ @tvm.transform.module_pass(opt_level=0, name="FuseDequantizeMatmulEwise") class FuseDequantizeMatmulEwise: # pylint: disable=too-few-public-methods + """A c...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/compiler_pass/fuse_dequantize_matmul_ewise.py
Add docstrings to my Python code
import functools import json import random from typing import Any, Dict, List, Optional, Tuple import numpy as np import requests from transformers import AutoTokenizer # pylint: disable=import-error import mlc_llm from mlc_llm.bench.api_endpoint import SUPPORTED_BACKENDS, create_api_endpoint from mlc_llm.bench.dat...
--- +++ @@ -1,3 +1,4 @@+"""MLC LLM benchmark main entrance""" import functools import json @@ -90,6 +91,7 @@ tokenizer: AutoTokenizer, args: argparse.argparse.Namespace, ) -> Tuple[Dict[str, Any], List[RequestRecord]]: + """Run the pipeline with the given dataset and args. Return the benchmark report d...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/bench/__main__.py
Write Python docstrings for this snippet
import tvm from tvm import relax, s_tir, tir from tvm.ir.module import IRModule from tvm.relax.analysis import remove_all_unused from tvm.relax.expr_functor import PyExprMutator, mutator @tvm.transform.module_pass(opt_level=0, name="FuseDequantizeTranspose") class FuseDequantizeTranspose: # pylint: disable=too-few-...
--- +++ @@ -1,3 +1,4 @@+"""A compiler pass that fuses transpose + dequantize.""" import tvm from tvm import relax, s_tir, tir @@ -8,8 +9,10 @@ @tvm.transform.module_pass(opt_level=0, name="FuseDequantizeTranspose") class FuseDequantizeTranspose: # pylint: disable=too-few-public-methods + """A compiler pass t...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/compiler_pass/fuse_dequantize_transpose.py
Create docstrings for reusable components
from tvm import register_global_func from . import protocol, serve from .libinfo import __version__ from .serve import AsyncMLCEngine, MLCEngine @register_global_func("runtime.disco.create_socket_session_local_workers", override=True) def _create_socket_session_local_workers(num_workers): from tvm.runtime.disco...
--- +++ @@ -1,3 +1,7 @@+"""MLC Chat python package. + +MLC Chat is the app runtime of MLC LLM. +""" from tvm import register_global_func @@ -8,8 +12,9 @@ @register_global_func("runtime.disco.create_socket_session_local_workers", override=True) def _create_socket_session_local_workers(num_workers): + """Creat...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/__init__.py
Add clean documentation to messy code
import tvm from tvm import IRModule, relax @tvm.transform.module_pass(opt_level=0, name="AttachCUDAGraphAllocInitFunc") class AttachCUDAGraphAllocInitFunc: # pylint: disable=too-few-public-methods def __init__(self): pass def transform_module(self, mod: IRModule, _ctx: tvm.transform.PassContext) -...
--- +++ @@ -1,3 +1,4 @@+"""The pass that attaches an empty function for initialization.""" import tvm from tvm import IRModule, relax @@ -5,11 +6,13 @@ @tvm.transform.module_pass(opt_level=0, name="AttachCUDAGraphAllocInitFunc") class AttachCUDAGraphAllocInitFunc: # pylint: disable=too-few-public-methods + "...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/compiler_pass/attach_cuda_graph_alloc_init_func.py
Generate docstrings for each module
from typing import List import tvm from tvm.ir.module import IRModule @tvm.transform.module_pass(opt_level=0, name="CleanUpTIRAttrs") class CleanUpTIRAttrs: # pylint: disable=too-few-public-methods def __init__(self, attrs: List[str]): self.attrs = attrs def transform_module( self, ...
--- +++ @@ -1,3 +1,4 @@+"""A compiler pass that cleans up undesired TIR attrs.""" from typing import List @@ -7,6 +8,7 @@ @tvm.transform.module_pass(opt_level=0, name="CleanUpTIRAttrs") class CleanUpTIRAttrs: # pylint: disable=too-few-public-methods + """A compiler pass that cleans up undesired TIR attrs.""...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/compiler_pass/clean_up_tir_attrs.py
Add docstrings for internal functions
import argparse import json import os import time import traceback from typing import Optional from typing_extensions import Self from mlc_llm.bench.request_record import Metrics, RequestRecord, ServerMetrics from mlc_llm.support import logging logger = logging.getLogger(__name__) class APIEndPoint: def __in...
--- +++ @@ -1,3 +1,4 @@+"""MLC LLM bench backends""" import argparse import json @@ -15,6 +16,9 @@ class APIEndPoint: + """Manages the sending of requests to a specified API endpoint and gathers + inference statistics. + """ def __init__(self, include_server_metrics: bool = False) -> None: ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/bench/api_endpoint.py
Add concise docstrings to each method
import argparse import asyncio import concurrent.futures import copy import os import random import time from typing import Any, Callable, Dict, List, Optional import numpy as np import requests from tqdm import tqdm from transformers import AutoTokenizer # pylint: disable=import-error from mlc_llm.bench.api_endpoi...
--- +++ @@ -1,3 +1,4 @@+"""MLC LLM Bench Request""" import argparse import asyncio @@ -27,12 +28,17 @@ class RequestProcessor: # pylint: disable=too-few-public-methods + """The request processor base class. + Each processor can take a list of RequestRecord, applying the process, + and returning the pr...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/bench/request_processor.py
Add verbose docstrings with examples
import sys from mlc_llm.support import logging from mlc_llm.support.argparse import ArgumentParser logging.enable_logging() def main(): parser = ArgumentParser("MLC LLM Command Line Interface.") parser.add_argument( "subcommand", type=str, choices=[ "compile", ...
--- +++ @@ -1,3 +1,4 @@+"""Entrypoint of all CLI commands from MLC LLM""" import sys @@ -8,6 +9,7 @@ def main(): + """Entrypoint of all CLI commands from MLC LLM""" parser = ArgumentParser("MLC LLM Command Line Interface.") parser.add_argument( "subcommand", @@ -64,4 +66,4 @@ if __nam...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/__main__.py
Generate documentation strings for clarity
#! pylint: disable=protected-access import os import sys __version__ = "0.1.dev0" MLC_LIBRARY_PATH = os.environ.get("MLC_LIBRARY_PATH", None) def get_env_paths(env_var, splitter): if os.environ.get(env_var, None): return [p.strip() for p in os.environ[env_var].split(splitter)] return [] def get_dl...
--- +++ @@ -1,3 +1,4 @@+"""Library information. This is a standalone file that can be used to get various info""" #! pylint: disable=protected-access import os @@ -8,12 +9,14 @@ def get_env_paths(env_var, splitter): + """Get path in env variable""" if os.environ.get(env_var, None): return [p.st...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/libinfo.py
Create simple docstrings for beginners
import contextlib import dataclasses import math import os import tempfile from io import StringIO from pathlib import Path from typing import Any, Dict, Iterator, Optional, Tuple from tvm import tir from tvm.contrib import tvmjs from tvm.runtime import DataType, Device, Tensor from tvm.runtime import cpu as cpu_devi...
--- +++ @@ -1,3 +1,4 @@+"""Python entrypoint of weight conversion.""" import contextlib import dataclasses @@ -27,6 +28,7 @@ @dataclasses.dataclass class ConversionArgs: # pylint: disable=too-many-instance-attributes + """Arguments to MLC LLM's weight conversation and quantization flow.""" config: Pat...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/interface/convert_weight.py
Add standardized docstrings across the file
import tvm from tvm import IRModule, relax, tir from tvm.relax import BlockBuilder, TensorStructInfo from tvm.script import tir as T @tvm.transform.module_pass(opt_level=0, name="AttachSpecDecodeAuxFuncs") class AttachSpecDecodeAuxFuncs: # pylint: disable=too-few-public-methods tensor_parallel_shards: int ...
--- +++ @@ -1,3 +1,4 @@+"""The pass that attaches logit processor functions to the IRModule.""" import tvm from tvm import IRModule, relax, tir @@ -7,6 +8,7 @@ @tvm.transform.module_pass(opt_level=0, name="AttachSpecDecodeAuxFuncs") class AttachSpecDecodeAuxFuncs: # pylint: disable=too-few-public-methods + "...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/compiler_pass/attach_spec_decode_aux_funcs.py
Generate docstrings for each module
from typing import Dict, Optional from mlc_llm.protocol.conversation_protocol import Conversation, MessagePlaceholders class ConvTemplateRegistry: _conv_templates: Dict[str, Conversation] = {} @staticmethod def register_conv_template(conv_template: Conversation, override: bool = False) -> None: ...
--- +++ @@ -1,3 +1,4 @@+"""The conversation template registry and presets in MLC LLM""" from typing import Dict, Optional @@ -5,11 +6,16 @@ class ConvTemplateRegistry: + """Global conversation template registry for preset templates.""" _conv_templates: Dict[str, Conversation] = {} @staticmetho...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/conversation_template/registry.py
Add docstrings explaining edge cases
import tvm from tvm import IRModule, relax, te, tir from tvm.relax.dpl.pattern import is_op, wildcard from tvm.relax.expr_functor import PyExprMutator, mutator @tvm.transform.module_pass(opt_level=0, name="FuseTransposeMatmul") class FuseTransposeMatmul: # pylint: disable=too-few-public-methods def transform_m...
--- +++ @@ -1,3 +1,4 @@+"""A compiler pass that fuses transpose + matmul.""" import tvm from tvm import IRModule, relax, te, tir @@ -7,8 +8,10 @@ @tvm.transform.module_pass(opt_level=0, name="FuseTransposeMatmul") class FuseTransposeMatmul: # pylint: disable=too-few-public-methods + """A compiler pass that f...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/compiler_pass/fuse_transpose_matmul.py
Generate docstrings with examples
from mlc_llm.interface.calibrate import calibrate from mlc_llm.interface.help import HELP from mlc_llm.support.argparse import ArgumentParser from .serve import EngineConfigOverride def main(argv): parser = ArgumentParser("MLC LLM Calibration CLI") parser.add_argument( "model", type=str, ...
--- +++ @@ -1,3 +1,4 @@+"""Command line entrypoint of calibration.""" from mlc_llm.interface.calibrate import calibrate from mlc_llm.interface.help import HELP @@ -7,6 +8,7 @@ def main(argv): + """Main entrypoint for calibration.""" parser = ArgumentParser("MLC LLM Calibration CLI") parser.add_argu...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/cli/calibrate.py
Document all public functions with docstrings
from math import lcm from typing import Any, Dict, List import tvm from tvm import IRModule, relax, tir from tvm.ir import Op from tvm.relax.expr_functor import PyExprVisitor, visitor @tvm.transform.module_pass(opt_level=0, name="AttachVariableBounds") class AttachVariableBounds: # pylint: disable=too-few-public-m...
--- +++ @@ -1,3 +1,4 @@+"""A couple of passes that simply supportive information onto the IRModule.""" from math import lcm from typing import Any, Dict, List @@ -10,6 +11,7 @@ @tvm.transform.module_pass(opt_level=0, name="AttachVariableBounds") class AttachVariableBounds: # pylint: disable=too-few-public-metho...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/compiler_pass/attach_support_info.py
Generate NumPy-style docstrings
# pylint: disable=chained-comparison,missing-docstring,too-few-public-methods,too-many-instance-attributes # pylint: disable=too-many-arguments,too-many-locals,unused-argument,unused-variable import json import queue import threading from typing import Any, Callable, Dict, Iterator, List, Literal, Optional, Union impo...
--- +++ @@ -39,6 +39,13 @@ def handle_chat_completion( self, ffi: dict, request_json_str: str, include_usage: bool, request_id: str ) -> Iterator[openai_api_protocol.ChatCompletionStreamResponse]: + """Helper class to handle chat completion + + Note + ---- + ffi is explicit...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/json_ffi/engine.py
Add docstrings for better understanding
import argparse from pathlib import Path from typing import Union from mlc_llm.interface.convert_weight import convert_weight from mlc_llm.interface.help import HELP from mlc_llm.model import MODELS from mlc_llm.quantization import QUANTIZATION from mlc_llm.support.argparse import ArgumentParser from mlc_llm.support....
--- +++ @@ -1,3 +1,4 @@+"""Command line entrypoint of weight conversion.""" import argparse from pathlib import Path @@ -14,6 +15,7 @@ def main(argv): + """Parse command line argumennts and apply quantization.""" def _parse_source(path: Union[str, Path], config_path: Path) -> Path: if path ==...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/cli/convert_weight.py
Add standardized docstrings across the file
from mlc_llm.interface.help import HELP from mlc_llm.interface.router import serve from mlc_llm.support.argparse import ArgumentParser def main(argv): # Define a custom argument type for a list of strings def list_of_strings(arg): return arg.split(",") parser = ArgumentParser("MLC LLM Router Se...
--- +++ @@ -1,3 +1,4 @@+"""Command line entrypoint of router.""" from mlc_llm.interface.help import HELP from mlc_llm.interface.router import serve @@ -5,6 +6,7 @@ def main(argv): + """Parse command line arguments and call `mlc_llm.interface.router`.""" # Define a custom argument type for a list of st...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/cli/router.py
Add verbose docstrings with examples
from typing import Dict import tvm from tvm import IRModule, relax, te, tir from tvm.relax.frontend import nn from tvm.script import tir as T from mlc_llm.op.batch_spec_verify import batch_spec_verify from mlc_llm.op.top_p_pivot import top_p_pivot, top_p_renorm @tvm.transform.module_pass(opt_level=0, name="AttachG...
--- +++ @@ -1,3 +1,4 @@+"""The pass that attaches GPU sampler functions to the IRModule.""" from typing import Dict @@ -12,6 +13,7 @@ @tvm.transform.module_pass(opt_level=0, name="AttachGPUSamplingFunc") class AttachGPUSamplingFunc: # pylint: disable=too-few-public-methods + """Attach GPU sampling functions...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/compiler_pass/attach_sampler.py
Write docstrings for algorithm functions
import tvm from tvm import IRModule, relax, tir from tvm.relax.dpl.pattern import ( GlobalVarPattern, TuplePattern, is_const, is_op, wildcard, ) @tvm.transform.module_pass(opt_level=0, name="FuseDequantizeTake") class FuseDequantizeTake: # pylint: disable=too-few-public-methods def transfor...
--- +++ @@ -1,3 +1,4 @@+"""A compiler pass that fuses dequantize + take.""" import tvm from tvm import IRModule, relax, tir @@ -12,12 +13,14 @@ @tvm.transform.module_pass(opt_level=0, name="FuseDequantizeTake") class FuseDequantizeTake: # pylint: disable=too-few-public-methods + """A compiler pass that fuses...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/compiler_pass/fuse_dequantize_take.py
Insert docstrings into my code
import tvm from tvm import IRModule, relax from tvm.relax.backend import get_patterns_with_prefix try: import tvm.relax.backend.cuda.cublas as _cublas import tvm.relax.backend.rocm.hipblas as _hipblas except ImportError: # Note: legacy path of cublas/hipblas for backward compatibility import tvm.relax...
--- +++ @@ -1,3 +1,4 @@+"""A compiler pass that dispatches patterns to CUBLAS.""" import tvm from tvm import IRModule, relax @@ -14,6 +15,7 @@ @tvm.transform.module_pass(opt_level=0, name="BLASDispatch") class BLASDispatch: # pylint: disable=too-few-public-methods,broad-exception-raised + """A compiler pass ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/compiler_pass/blas_dispatch.py
Create docstrings for each class method
from pathlib import Path from typing import Any, Dict, List, Optional import tvm from tvm import IRModule from tvm.relax import register_pipeline # pylint: disable=no-name-in-module from tvm.relax.frontend import nn from tvm.s_tir import dlight as dl from mlc_llm.interface.compiler_flags import IPCAllReduceStrategy...
--- +++ @@ -1,3 +1,4 @@+"""The compilation pipeline for LLM applications.""" from pathlib import Path from typing import Any, Dict, List, Optional @@ -46,17 +47,21 @@ @tvm.transform.module_pass(opt_level=0, name="_LogProgress") class _LogProgress: # pylint: disable=too-few-public-methods + """A dummy compile...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/compiler_pass/pipeline.py
Add well-formatted docstrings
from pathlib import Path from typing import Union from mlc_llm.interface.gen_config import CONV_TEMPLATES, gen_config from mlc_llm.interface.help import HELP from mlc_llm.model import MODELS from mlc_llm.quantization import QUANTIZATION from mlc_llm.support.argparse import ArgumentParser from mlc_llm.support.auto_con...
--- +++ @@ -1,3 +1,4 @@+"""Command line entrypoint of configuration generation.""" from pathlib import Path from typing import Union @@ -11,6 +12,7 @@ def main(argv): + """Parse command line argumennts and call `mlc_llm.compiler.gen_config`.""" parser = ArgumentParser("MLC LLM Configuration Generator") ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/cli/gen_config.py
Add missing documentation to my Python functions
import json from typing import Any, Dict, List import tvm from tvm import IRModule, relax from tvm.relax.frontend.nn.llm import kv_cache from tvm.relax.frontend.nn.llm.kv_cache import RopeMode from mlc_llm.support import logging logger = logging.getLogger(__name__) def extract_creation_args(func: relax.Function) ...
--- +++ @@ -1,3 +1,4 @@+"""A pass that rewrites KV cache creation functions in IRModule.""" import json from typing import Any, Dict, List @@ -13,6 +14,7 @@ def extract_creation_args(func: relax.Function) -> Dict[str, Any]: + """Extract the KV cache creation args from the given generic creation func.""" ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/compiler_pass/dispatch_kv_cache_creation.py
Generate docstrings for this script
import json from typing import Any, Dict import tvm from tvm import relax, tir from tvm.ir import IRModule, Op from tvm.relax.expr_functor import PyExprVisitor, visitor from mlc_llm.support import logging logger = logging.getLogger(__name__) @tvm.transform.module_pass(opt_level=0, name="AttachMetadata") class Att...
--- +++ @@ -1,3 +1,4 @@+"""Memory usage estimation analysis function for Relax functions.""" import json from typing import Any, Dict @@ -14,11 +15,13 @@ @tvm.transform.module_pass(opt_level=0, name="AttachMetadata") class AttachMetadataWithMemoryUsage: # pylint: disable=too-few-public-methods + """Attach a ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/compiler_pass/estimate_memory_usage.py
Insert docstrings into my code
import operator from functools import reduce import tvm from tvm import IRModule, relax from tvm.relax.dpl import rewrite_call from tvm.relax.dpl.pattern import is_op, wildcard @tvm.transform.module_pass(opt_level=0, name="FuseDequantizeEpilogue") class FuseFTDequantizeEpilogue: # pylint: disable=too-few-public-me...
--- +++ @@ -1,3 +1,4 @@+"""A compiler pass that fuses dequantize matmul + epilogue.""" import operator from functools import reduce @@ -10,12 +11,14 @@ @tvm.transform.module_pass(opt_level=0, name="FuseDequantizeEpilogue") class FuseFTDequantizeEpilogue: # pylint: disable=too-few-public-methods + """A compil...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/compiler_pass/fuse_ft_dequantize_matmul_epilogue.py
Generate consistent documentation across files
import asyncio import json import random from typing import List, Mapping, Optional, Tuple import numpy as np import tqdm.asyncio import tvm from tvm.contrib import tvmjs from mlc_llm.serve.engine import AsyncMLCEngine, EngineConfig from mlc_llm.tokenizers import Tokenizer class CalibrationObserver: instance:...
--- +++ @@ -1,3 +1,4 @@+"""Python entrypoint for calibration.""" import asyncio import json @@ -14,6 +15,7 @@ class CalibrationObserver: + """A singleton class to observe the calibration parameters.""" "" instance: "CalibrationObserver" = None @@ -21,6 +23,7 @@ @staticmethod def get(): + ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/interface/calibrate.py
Add docstrings to improve code quality
import argparse import dataclasses import json import os import shutil import subprocess import sys import tempfile from pathlib import Path from typing import Any, Callable, Dict, List from mlc_llm.support import logging from mlc_llm.support.argparse import ArgumentParser from mlc_llm.support.constants import MLC_TE...
--- +++ @@ -1,3 +1,4 @@+"""Continuous model delivery for MLC LLM models.""" import argparse import dataclasses @@ -20,6 +21,7 @@ @dataclasses.dataclass class ModelInfo: # pylint: disable=too-many-instance-attributes + """Necessary information for the model delivery""" model_id: str model: Path @@...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/cli/lib_delivery.py
Add docstrings that explain purpose and usage
from typing import Any, Dict, Optional import tvm from tvm import relax, tir from tvm.ir.module import IRModule from tvm.relax.expr_functor import PyExprMutator, mutator from tvm.script import tir as T from ..support.max_thread_check import get_max_num_threads_per_block @tvm.transform.module_pass(opt_level=0, name...
--- +++ @@ -1,3 +1,4 @@+"""A compiler pass that attaches two-stage softmax with temperature.""" from typing import Any, Dict, Optional @@ -12,6 +13,7 @@ @tvm.transform.module_pass(opt_level=0, name="AttachSoftmaxWithTemperature") class AttachSoftmaxWithTemperature: # pylint: disable=too-few-public-methods + ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/compiler_pass/attach_softmax_with_temperature.py
Document all endpoints with docstrings
from typing import Any, Dict, List, Optional, Tuple, Union import pandas as pd # pylint: disable=import-error from pydantic import BaseModel from mlc_llm.protocol.openai_api_protocol import ChatCompletionRequest from mlc_llm.support import logging logger = logging.getLogger(__name__) class ServerMetrics(BaseMode...
--- +++ @@ -1,3 +1,4 @@+"""MLC LLM Bench Request""" from typing import Any, Dict, List, Optional, Tuple, Union @@ -11,6 +12,7 @@ class ServerMetrics(BaseModel): + """The metrics from the server side.""" input_tokens: int prefill_tokens: int @@ -23,6 +25,7 @@ class Metrics(BaseModel): + ""...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/bench/request_record.py
Add docstrings to make code maintainable
# pylint: disable=invalid-name from typing import List import tvm from tvm import IRModule, relax from tvm.relax.expr_functor import PyExprMutator, mutator from mlc_llm.op.triton import ( get_tir_w8a8_block_fp8_group_matmul, get_tir_w8a8_block_fp8_matmul, ) from mlc_llm.support import logging logger = logg...
--- +++ @@ -1,3 +1,4 @@+"""A pass that dispatch generic calls of triton kernels to specific kernel implementations.""" # pylint: disable=invalid-name @@ -25,6 +26,7 @@ self.extern_mods: List[tvm.runtime.Module] = [] def transform(self) -> tvm.IRModule: # pylint: disable=too-many-locals + """...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/compiler_pass/dispatch_triton_kernel.py
Can you add docstrings to this Python file?
import dataclasses from functools import partial from typing import Any, Dict, Optional from tvm import te, tir from tvm.relax.frontend import nn from tvm.relax.frontend.nn import Tensor, op from mlc_llm import op as op_ext from mlc_llm.nn import PagedKVCache, RopeMode from mlc_llm.nn.expert import MixtralExperts fr...
--- +++ @@ -1,3 +1,6 @@+""" +Implementation for Deepseek architecture. +""" import dataclasses from functools import partial @@ -20,6 +23,7 @@ @dataclasses.dataclass class DeepseekConfig(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the Deepseek model.""" vocab_size...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/deepseek/deepseek_model.py
Add missing documentation to my Python functions
import dataclasses import math from typing import Any, Dict, Literal, Optional, Tuple from tvm import te, tir from tvm.relax.frontend import nn from tvm.relax.frontend.nn import Tensor, op from tvm.relax.frontend.nn.llm import position_embedding from mlc_llm import op as op_ext from mlc_llm.nn import PagedKVCache, R...
--- +++ @@ -1,3 +1,6 @@+""" +Implementation for Deepseek V2 architecture +""" import dataclasses import math @@ -22,6 +25,7 @@ @dataclasses.dataclass class DeepseekV2Config(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the Deepseek V2 model.""" vocab_size: int ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/deepseek_v2/deepseek_v2_model.py
Write beginner-friendly docstrings
import functools import numpy as np from mlc_llm.loader import ExternMapping from mlc_llm.quantization import Quantization from .deepseek_model import DeepseekConfig, DeepseekForCausalLM def huggingface(model_config: DeepseekConfig, quantization: Quantization) -> ExternMapping: model = DeepseekForCausalLM(mod...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's Deepseek parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools @@ -10,6 +14,22 @@ def huggingface(model_config: DeepseekConfig, quantization: Quantization) -> ExternMapping: + """Returns ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/deepseek/deepseek_loader.py
Please document this code using docstrings
import functools import numpy as np from mlc_llm.loader import ExternMapping from mlc_llm.loader.standard_loader import make_standard_hf_loader from mlc_llm.quantization import Quantization, make_awq_quant from .eagle_model import EagleConfig, EagleForCausalLM awq_quant = make_awq_quant(EagleForCausalLM) hugging...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's EAGLE parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools @@ -20,6 +24,21 @@ def awq(model_config: EagleConfig, quantization: Quantization) -> ExternMapping: + """Returns a parameter ma...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/eagle/eagle_loader.py
Add docstrings for internal functions
import functools from mlc_llm.loader import ExternMapping from mlc_llm.loader.standard_loader import make_standard_hf_loader from mlc_llm.quantization import Quantization from .gemma3_model import Gemma3Config, Gemma3ForCausalLM def huggingface(model_config: Gemma3Config, quantization: Quantization) -> ExternMappi...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's Gemma3 parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools @@ -9,6 +13,7 @@ def huggingface(model_config: Gemma3Config, quantization: Quantization) -> ExternMapping: + """Create HF weig...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/gemma3/gemma3_loader.py
Add docstrings explaining edge cases
import dataclasses from typing import Callable, Dict, List, Set, Union import numpy as np from tvm.runtime import Tensor MapFuncVariadic = Union[ Callable[[], np.ndarray], Callable[[np.ndarray], np.ndarray], Callable[[np.ndarray, np.ndarray], np.ndarray], Callable[[np.ndarray, np.ndarray, np.ndarray]...
--- +++ @@ -1,3 +1,4 @@+"""Parameter mapping for converting different LLM implementations to MLC LLM.""" import dataclasses from typing import Callable, Dict, List, Set, Union @@ -16,6 +17,29 @@ @dataclasses.dataclass class ExternMapping: + """Mapping from a parameter name in MLC LLM's model definition to its...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/loader/mapping.py
Add documentation for all methods
import dataclasses from typing import Any, Dict, Optional from tvm import te, tir from tvm.relax.frontend import nn from tvm.relax.frontend.nn import Tensor, op from mlc_llm import op as op_ext from mlc_llm.nn import PagedKVCache, RopeMode from mlc_llm.support import logging from mlc_llm.support import tensor_parall...
--- +++ @@ -1,3 +1,4 @@+"""Implementation for Gemma architecture.""" import dataclasses from typing import Any, Dict, Optional @@ -18,6 +19,7 @@ @dataclasses.dataclass class GemmaConfig(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the Gemma model.""" hidden_size: i...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/gemma/gemma_model.py
Write Python docstrings for this snippet
from __future__ import annotations import functools from typing import Callable, Iterable, Optional, Sequence, Type import numpy as np from tvm.relax.frontend import nn # type: ignore[import] from mlc_llm.loader import ExternMapping from mlc_llm.quantization import Quantization NameTransform = Callable[[str], str...
--- +++ @@ -1,3 +1,4 @@+"""Standard HuggingFace loader mapping helpers.""" from __future__ import annotations @@ -38,6 +39,11 @@ export_spec_getter: Optional[ExportSpecGetter] = None, num_layers_getter: Optional[Callable[[object], int]] = None, ) -> Callable[[object, Quantization], ExternMapping]: + "...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/loader/standard_loader.py
Create structured documentation for my script
import gc import json from collections import OrderedDict, defaultdict from pathlib import Path from typing import Callable, Dict, Iterator, List, Optional, Tuple import numpy as np from tqdm import tqdm from tvm.runtime import Device, Tensor from tvm.runtime import tensor as as_tensor from mlc_llm.support import lo...
--- +++ @@ -1,3 +1,4 @@+"""A weight loader for HuggingFace's PyTorch format""" import gc import json @@ -22,6 +23,28 @@ class HuggingFaceLoader: # pylint: disable=too-few-public-methods + """A loader loading HuggingFace's PyTorch/SafeTensor format and converts them + to MLC's parameters. + + Attribute...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/loader/huggingface_loader.py
Can you add docstrings to this Python file?
import functools from mlc_llm.loader import ExternMapping from mlc_llm.loader.standard_loader import make_standard_hf_loader from mlc_llm.quantization import Quantization from .gemma_model import GemmaConfig, GemmaForCausalLM def huggingface(model_config: GemmaConfig, quantization: Quantization) -> ExternMapping: ...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's Gemma parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools @@ -9,6 +13,7 @@ def huggingface(model_config: GemmaConfig, quantization: Quantization) -> ExternMapping: + """Create HF weight...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/gemma/gemma_loader.py
Document classes and their methods
import functools import numpy as np from mlc_llm.loader import ExternMapping from mlc_llm.loader.standard_loader import make_standard_hf_loader from mlc_llm.quantization import Quantization, make_awq_quant from .cohere_model import CohereConfig, CohereForCausalLM awq_quant = make_awq_quant(CohereForCausalLM) def...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's Cohere parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools @@ -27,6 +31,21 @@ # https://huggingface.co/alijawad07/aya-23-8B-AWQ-GEMM/tree/main def awq(model_config: CohereConfig, quantizati...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/cohere/cohere_loader.py
Insert docstrings into my code
import dataclasses from typing import Optional from tvm import tir from tvm.relax.frontend import nn from tvm.relax.frontend.nn import Tensor, op from mlc_llm import op as op_ext from mlc_llm.model.llama.llama_model import LlamaAttention, LlamaConfig, LlamaFFN from mlc_llm.nn import PagedKVCache, RopeMode from mlc_l...
--- +++ @@ -1,3 +1,6 @@+""" +Implementation for EAGLE architecture. +""" import dataclasses from typing import Optional @@ -17,6 +20,7 @@ @dataclasses.dataclass class EagleConfig(LlamaConfig): + """Configuration of the Eagle model.""" bias: bool = True # Whether to use bias in the fc layers @@ -247,...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/eagle/eagle_model.py
Write proper docstrings for these functions
import dataclasses from typing import Any, Dict, Optional import tvm from tvm import te, tir from tvm.relax.frontend import nn from tvm.relax.frontend.nn import Tensor, op from tvm.relax.frontend.nn.llm import position_embedding from mlc_llm import op as op_ext from mlc_llm.model.qwen3.qwen3_model import ACT2FN from...
--- +++ @@ -1,3 +1,6 @@+""" +Implementation for Llama4 architecture. +""" import dataclasses from typing import Any, Dict, Optional @@ -21,6 +24,7 @@ @dataclasses.dataclass class Llama4TextConfig(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the Text portion of the Llama m...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/llama4/llama4_model.py
Add missing documentation to my Python functions
import functools import numpy as np from mlc_llm.loader import ExternMapping from mlc_llm.loader.standard_loader import make_standard_hf_loader from mlc_llm.quantization import Quantization, make_awq_quant from .llama_model import LlamaConfig, LlamaForCausalLM awq_quant = make_awq_quant(LlamaForCausalLM) hugging...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's Llama parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools @@ -19,6 +23,21 @@ def awq(model_config: LlamaConfig, quantization: Quantization) -> ExternMapping: + """Returns a parameter ma...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/llama/llama_loader.py
Document this code for team use
import dataclasses from typing import Any, Dict, Optional from tvm import te, tir from tvm.relax.frontend import nn from tvm.relax.frontend.nn import Tensor, op from mlc_llm import op as op_ext from mlc_llm.nn import PagedKVCache, RopeMode from mlc_llm.support import logging from mlc_llm.support import tensor_parall...
--- +++ @@ -1,3 +1,6 @@+""" +Implementation for InternLM2 architecture. +""" import dataclasses from typing import Any, Dict, Optional @@ -18,6 +21,7 @@ @dataclasses.dataclass class InternLM2Config(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the InternLM2 model.""" ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/internlm2/internlm2_model.py
Write reusable docstrings
import dataclasses import time from contextlib import contextmanager from mlc_llm.support import logging from mlc_llm.support.style import green logger = logging.getLogger(__name__) @dataclasses.dataclass class Stats: load_time_sec: float = 0.0 map_time_sec: float = 0.0 quant_time_sec: float = 0.0 ...
--- +++ @@ -1,3 +1,4 @@+"""Statistics of the loading process of parameter loaders""" import dataclasses import time @@ -11,6 +12,31 @@ @dataclasses.dataclass class Stats: + """Statistics of the loading process of parameter loaders. + + Attributes + ---------- + load_time_sec : float + Time use...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/loader/stats.py
Add docstrings that explain logic
import dataclasses from typing import Any, Dict, Optional from tvm import te, tir from tvm.relax.frontend import nn from tvm.relax.frontend.nn import Tensor, op from mlc_llm import op as op_ext from mlc_llm.nn import PagedKVCache, RopeMode from mlc_llm.support import logging from mlc_llm.support import tensor_parall...
--- +++ @@ -1,3 +1,6 @@+""" +Implementation for Llama2 architecture. +""" import dataclasses from typing import Any, Dict, Optional @@ -18,6 +21,7 @@ @dataclasses.dataclass class LlamaConfig(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the Llama model.""" hidden_si...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/llama/llama_model.py
Create docstrings for reusable components
import dataclasses from typing import Any, Dict, Optional from tvm import te, tir from tvm.relax.frontend import nn from tvm.relax.frontend.nn import Tensor, op from mlc_llm import op as op_ext from mlc_llm.nn import PagedKVCache, RopeMode from mlc_llm.support import logging from mlc_llm.support import tensor_parall...
--- +++ @@ -1,3 +1,6 @@+""" +Implementation for BAICHUAN architecture. +""" import dataclasses from typing import Any, Dict, Optional @@ -18,6 +21,7 @@ @dataclasses.dataclass class BaichuanConfig(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the Baichuan model.""" v...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/baichuan/baichuan_model.py
Write docstrings for data processing functions
import dataclasses from typing import Any, Dict, Optional from tvm import te, tir from tvm.relax.frontend import nn from tvm.relax.frontend.nn import Tensor, op from mlc_llm import op as op_ext from mlc_llm.nn import PagedKVCache, RopeMode from mlc_llm.support import logging from mlc_llm.support import tensor_parall...
--- +++ @@ -1,3 +1,6 @@+""" +Implementation for GPTBigCode architecture. +""" import dataclasses from typing import Any, Dict, Optional @@ -18,6 +21,7 @@ @dataclasses.dataclass class GPTBigCodeConfig(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the GPTBigCode model.""" ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/gpt_bigcode/gpt_bigcode_model.py
Document functions with clear intent
import dataclasses import logging from typing import Any, Dict, Optional from tvm import te, tir from tvm.relax.frontend import nn from tvm.relax.frontend.nn import Tensor, op from mlc_llm import op as op_ext from mlc_llm.nn import PagedKVCache, RopeMode from mlc_llm.support import tensor_parallel as tp from mlc_llm...
--- +++ @@ -1,3 +1,6 @@+""" +Implementation for GPTNeoX architecture. +""" import dataclasses import logging @@ -18,6 +21,7 @@ @dataclasses.dataclass class GPTNeoXConfig(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the GPTNeoX model.""" use_parallel_residual: bool ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/gpt_neox/gpt_neox_model.py
Document all endpoints with docstrings
import functools from mlc_llm.loader import ExternMapping from mlc_llm.loader.standard_loader import make_standard_hf_loader from mlc_llm.quantization import Quantization from .gemma2_model import Gemma2Config, Gemma2ForCausalLM def huggingface(model_config: Gemma2Config, quantization: Quantization) -> ExternMappi...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's Gemma2 parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools @@ -9,6 +13,7 @@ def huggingface(model_config: Gemma2Config, quantization: Quantization) -> ExternMapping: + """Create HF weig...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/gemma2/gemma2_loader.py
Add detailed docstrings explaining each function
import dataclasses from functools import partial from typing import Any, Dict, Optional from tvm import te, tir from tvm.relax.frontend import nn from tvm.relax.frontend.nn import Tensor, op from mlc_llm import op as op_ext from mlc_llm.support import logging from mlc_llm.support.config import ConfigBase from mlc_ll...
--- +++ @@ -1,3 +1,6 @@+""" +Implementation for BERT architecture. +""" import dataclasses from functools import partial @@ -17,6 +20,7 @@ @dataclasses.dataclass class BertConfig(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the BERT model.""" vocab_size: int h...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/bert/bert_model.py
Add docstrings for better understanding
# pylint: disable=too-few-public-methods from pathlib import Path from typing import TYPE_CHECKING, Iterator, Set, Tuple import numpy as np from mlc_llm.support import logging if TYPE_CHECKING: from tvm.runtime import Tensor from .mapping import ExternMapping logger = logging.getLogger(__name__) def ch...
--- +++ @@ -1,3 +1,4 @@+"""Common utilities for loading parameters""" # pylint: disable=too-few-public-methods from pathlib import Path @@ -17,6 +18,7 @@ def check_parameter_usage(param_map: "ExternMapping", extern_weights: Set[str]): + """Check that all external parameters have been used and are stored in t...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/loader/utils.py
Add minimal docstrings for each function
import dataclasses from typing import Any, Dict, Optional from tvm import te, tir from tvm.relax.frontend import nn from tvm.relax.frontend.nn import Tensor, op from mlc_llm import op as op_ext from mlc_llm.nn import PagedKVCache, RopeMode from mlc_llm.support import logging from mlc_llm.support import tensor_parall...
--- +++ @@ -1,3 +1,6 @@+""" +Implementation for Aya23 architecture +""" import dataclasses from typing import Any, Dict, Optional @@ -18,6 +21,7 @@ @dataclasses.dataclass class CohereConfig(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the Cohere Aya-23 model""" mod...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/cohere/cohere_model.py
Add docstrings to improve readability
import functools import numpy as np from mlc_llm.loader import ExternMapping from mlc_llm.quantization import Quantization from .llama4_model import Llama4Config, Llama4ForCausalLM def huggingface(model_config: Llama4Config, quantization: Quantization) -> ExternMapping: model = Llama4ForCausalLM(model_config)...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's Llama parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools @@ -10,6 +14,22 @@ def huggingface(model_config: Llama4Config, quantization: Quantization) -> ExternMapping: + """Returns a par...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/llama4/llama4_loader.py
Generate documentation strings for clarity
import dataclasses from typing import Any, Dict, Optional from tvm import te, tir from tvm.relax.frontend import nn from tvm.relax.frontend.nn import Tensor, op from mlc_llm import op as op_ext from mlc_llm.nn import PagedKVCache, RopeMode from mlc_llm.support import logging from mlc_llm.support import tensor_parall...
--- +++ @@ -1,3 +1,6 @@+""" +Implementation for InternLM architecture. +""" import dataclasses from typing import Any, Dict, Optional @@ -18,6 +21,7 @@ @dataclasses.dataclass class InternLMConfig(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the InternLM model.""" v...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/internlm/internlm_model.py
Auto-generate documentation strings for this file
import dataclasses from typing import Any, Dict, Optional from tvm import te, tir from tvm.relax.frontend import nn from tvm.relax.frontend.nn import Tensor, op from mlc_llm import op as op_ext from mlc_llm.nn import PagedKVCache, RopeMode from mlc_llm.support import logging from mlc_llm.support import tensor_parall...
--- +++ @@ -1,3 +1,6 @@+""" +Implementation for GPT-2 architecture. +""" import dataclasses from typing import Any, Dict, Optional @@ -18,6 +21,7 @@ @dataclasses.dataclass class GPT2Config(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the GPT-2 model.""" vocab_size:...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/gpt2/gpt2_model.py
Add docstrings to make code maintainable
import functools from mlc_llm.loader import ExternMapping from mlc_llm.quantization import Quantization from .chatglm3_model import ChatGLMForCausalLM, GLMConfig def huggingface(model_config: GLMConfig, quantization: Quantization) -> ExternMapping: model = ChatGLMForCausalLM(model_config) if quantization i...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's ChatGLM3 parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools @@ -8,6 +12,22 @@ def huggingface(model_config: GLMConfig, quantization: Quantization) -> ExternMapping: + """Returns a para...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/chatglm3/chatglm3_loader.py