instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Provide docstrings following PEP 257
import functools from typing import Literal import numpy as np from mlc_llm.loader import ExternMapping from mlc_llm.quantization import Quantization from .bert_model import BertConfig, BertModel def huggingface( model_config: BertConfig, quantization: Quantization, hf_prefix: Literal["", "bert."] = "...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's BERT parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools from typing import Literal @@ -15,6 +19,26 @@ quantization: Quantization, hf_prefix: Literal["", "bert."] = "", ) -> ExternMap...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/bert/bert_loader.py
Document this module using docstrings
import dataclasses import logging from typing import Any, Dict, Optional from tvm import tir from tvm.relax.frontend import nn from tvm.relax.frontend.nn import Module, Tensor from tvm.relax.frontend.nn.op import permute_dims, reshape, wrap_nested from tvm.relax.op import strided_slice from mlc_llm import op as op_e...
--- +++ @@ -1,3 +1,7 @@+""" +Implementation of LLaVa Model +Implements the CLIP Vision Encoder. Uses Llama for the Language Encoder. +""" import dataclasses import logging @@ -30,6 +34,9 @@ @dataclasses.dataclass class LlavaConfig(ConfigBase): # pylint: disable=too-many-instance-attributes + """ + LLaVa C...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/llava/llava_model.py
Create documentation strings for testing functions
import functools import numpy as np from mlc_llm.loader import ExternMapping from mlc_llm.quantization import Quantization from .gpt_neox_model import GPTNeoXConfig, GPTNeoXForCausalLM def huggingface(model_config: GPTNeoXConfig, quantization: Quantization) -> ExternMapping: model = GPTNeoXForCausalLM(model_c...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's GPTNeoX parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools @@ -10,6 +14,22 @@ def huggingface(model_config: GPTNeoXConfig, quantization: Quantization) -> ExternMapping: + """Returns a ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/gpt_neox/gpt_neox_loader.py
Document classes and their methods
import dataclasses from tvm.relax.frontend import nn from tvm.relax.frontend.nn import Tensor, op from mlc_llm.model.gemma.gemma_model import ( GemmaAttention, GemmaConfig, GemmaForCausalLM, GemmaMLP, GemmaModel, ) from mlc_llm.nn import PagedKVCache from mlc_llm.support import logging from mlc_l...
--- +++ @@ -1,3 +1,4 @@+"""Implementation for Gemma2 architecture.""" import dataclasses @@ -20,6 +21,7 @@ @dataclasses.dataclass class Gemma2Config(GemmaConfig): + """Configuration of the Gemma2 model, in addition to the Gemma model""" # NOTE: We ignore attn_logit_softcapping in the gemma2 implementa...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/gemma2/gemma2_model.py
Add docstrings that explain logic
import functools from typing import Callable, List import numpy as np from mlc_llm.loader import ExternMapping, QuantizeMapping from mlc_llm.quantization import BlockScaleQuantize, Quantization from .deepseek_v2_model import DeepseekV2Config, DeepseekV2ForCausalLM def huggingface( # pylint: disable=too-many-loca...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's Deepseek-V2 parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools from typing import Callable, List @@ -13,6 +17,22 @@ def huggingface( # pylint: disable=too-many-locals,too-many-statements ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/deepseek_v2/deepseek_v2_loader.py
Help me write clear docstrings
import functools from typing import Callable, List, Optional, Tuple import numpy as np from mlc_llm.loader import ExternMapping, QuantizeMapping from mlc_llm.quantization import BlockScaleQuantize, Quantization from .ministral3_model import Ministral3Config, Mistral3ForConditionalGeneration def _dequantize_block_...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's Ministral3 parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools from typing import Callable, List, Optional, Tuple @@ -13,6 +17,7 @@ def _dequantize_block_scale_weight( # pylint: disable=too-ma...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/ministral3/ministral3_loader.py
Generate docstrings for script automation
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 .llava_model import LlavaConfig, LlavaForCausalLM awq_quant = make_awq_quant(LlavaForCausalLM) def _nu...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's Llava parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools @@ -25,6 +29,21 @@ def awq(model_config: LlavaConfig, quantization: Quantization) -> ExternMapping: + """Returns a parameter ma...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/llava/llava_loader.py
Create simple docstrings for beginners
import dataclasses from typing import Any, Dict, Optional from tvm.relax.frontend import nn from mlc_llm.support import logging from mlc_llm.support.config import ConfigBase logger = logging.getLogger(__name__) @dataclasses.dataclass class MedusaConfig(ConfigBase): # pylint: disable=too-many-instance-attributes ...
--- +++ @@ -1,3 +1,4 @@+"""Medusa model definition.""" import dataclasses from typing import Any, Dict, Optional @@ -12,6 +13,7 @@ @dataclasses.dataclass class MedusaConfig(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the Llama model.""" medusa_num_heads: int ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/medusa/medusa_model.py
Create simple docstrings for beginners
import functools import numpy as np from mlc_llm.loader import ExternMapping from mlc_llm.quantization import Quantization from .minicpm_model import MiniCPMConfig, MiniCPMForCausalLM def huggingface(model_config: MiniCPMConfig, quantization: Quantization) -> ExternMapping: model = MiniCPMForCausalLM(model_co...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's MiniCPM parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools @@ -10,6 +14,22 @@ def huggingface(model_config: MiniCPMConfig, quantization: Quantization) -> ExternMapping: + """Returns a ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/minicpm/minicpm_loader.py
Create docstrings for all classes and 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 Orion-14B architecture. +""" import dataclasses from typing import Any, Dict, Optional @@ -18,6 +21,7 @@ @dataclasses.dataclass class OrionConfig(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the Orion model.""" hidden...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/orion/orion_model.py
Insert docstrings into my code
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.model.gemma.gemma_model import GemmaEmbedding from mlc_llm.nn import PagedKVCache, RopeMode from mlc_llm.suppo...
--- +++ @@ -1,3 +1,4 @@+"""Implementation for Gemma3 architecture.""" import dataclasses from typing import Any, Dict, Optional @@ -19,6 +20,7 @@ @dataclasses.dataclass class Gemma3TextConfig(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the text model inside Gemma3""" ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/gemma3/gemma3_model.py
Create documentation strings for testing functions
import dataclasses import math 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 Mixtr...
--- +++ @@ -1,3 +1,6 @@+""" +Implementation for Minicpm architecture. +""" import dataclasses import math @@ -21,6 +24,7 @@ @dataclasses.dataclass class MiniCPMConfig(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the MiniCPM model.""" vocab_size: int hidden_siz...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/minicpm/minicpm_model.py
Generate helpful docstrings for debugging
import dataclasses from typing import Any, Dict, Optional, Union 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...
--- +++ @@ -1,3 +1,6 @@+""" +Implementation for Phi architecture. +""" import dataclasses from typing import Any, Dict, Optional, Union @@ -18,6 +21,7 @@ @dataclasses.dataclass class Phi1Config(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the Phi-1/Phi-1.5 model.""" ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/phi/phi_model.py
Create documentation for each function signature
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 CHATGLM3 architecture. +""" import dataclasses from typing import Any, Dict, Optional @@ -18,6 +21,7 @@ @dataclasses.dataclass class GLMConfig(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the ChatGLM model.""" hidden_...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/chatglm3/chatglm3_model.py
Add structured docstrings to improve clarity
import functools import numpy as np from mlc_llm.loader import ExternMapping from mlc_llm.quantization import Quantization from .phi_model import Phi1Config, PhiConfig, PhiForCausalLM def huggingface(model_config: PhiConfig, quantization: Quantization) -> ExternMapping: model = PhiForCausalLM(model_config) ...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's Phi parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools @@ -10,6 +14,22 @@ def huggingface(model_config: PhiConfig, quantization: Quantization) -> ExternMapping: + """Returns a paramete...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/phi/phi_loader.py
Add docstrings with type hints explained
# pylint: disable=W0611 import functools import numpy as np from mlc_llm.loader import ExternMapping from mlc_llm.quantization import Quantization from .internlm2_model import InternLM2Config, InternLM2ForCausalLM def huggingface(model_config: InternLM2ForCausalLM, quantization: Quantization) -> ExternMapping: ...
--- +++ @@ -1,4 +1,8 @@ # pylint: disable=W0611 +""" +This file specifies how MLC's InternLM2 parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools @@ -11,6 +15,22 @@ def huggingface(model_config: InternLM2ForCausalLM, quantization: Quantization) ->...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/internlm2/internlm2_loader.py
Create simple docstrings for beginners
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.support import logging from mlc_ll...
--- +++ @@ -1,3 +1,6 @@+""" +Implementation for QWEN2 architecture. +""" import dataclasses from functools import partial @@ -19,6 +22,7 @@ @dataclasses.dataclass class QWen2Config(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the QWen2 model.""" hidden_act: str ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/qwen2/qwen2_model.py
Generate docstrings with parameter types
import functools from mlc_llm.loader import ExternMapping from mlc_llm.quantization import Quantization from .gpt2_model import GPT2Config, GPT2LMHeadModel def huggingface(model_config: GPT2Config, quantization: Quantization) -> ExternMapping: model = GPT2LMHeadModel(model_config) if quantization is not No...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's GPT-2 parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools @@ -8,6 +12,22 @@ def huggingface(model_config: GPT2Config, quantization: Quantization) -> ExternMapping: + """Returns a parame...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/gpt2/gpt2_loader.py
Generate docstrings for this script
import dataclasses import math from functools import partial from typing import Any, Dict, Optional, Tuple 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 ...
--- +++ @@ -1,3 +1,6 @@+""" +Implementation for Ministral 3 architecture. +""" import dataclasses import math @@ -20,6 +23,7 @@ @dataclasses.dataclass class Ministral3Config(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the Ministral 3 model.""" hidden_size: int ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/ministral3/ministral3_model.py
Document this script properly
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 Mistral architecture. +""" import dataclasses from typing import Any, Dict, Optional @@ -18,6 +21,7 @@ @dataclasses.dataclass class MistralConfig(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the Mistral model.""" hidd...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/mistral/mistral_model.py
Add detailed documentation for each class
import functools import numpy as np from mlc_llm.loader import ExternMapping from mlc_llm.quantization import Quantization from .mixtral_model import MixtralConfig, MixtralForCausalLM def huggingface(model_config: MixtralConfig, quantization: Quantization) -> ExternMapping: model = MixtralForCausalLM(model_co...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's Mixtral parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools @@ -10,6 +14,22 @@ def huggingface(model_config: MixtralConfig, quantization: Quantization) -> ExternMapping: + """Returns a ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/mixtral/mixtral_loader.py
Document helper functions with 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 .mistral_model import MistralConfig, MistralForCausalLM awq_quant = make_awq_quant(MistralForCausalLM) ...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's Mistral parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools @@ -19,6 +23,21 @@ def awq(model_config: MistralConfig, quantization: Quantization) -> ExternMapping: + """Returns a paramete...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/mistral/mistral_loader.py
Generate NumPy-style docstrings
import functools import numpy as np from mlc_llm.loader import ExternMapping from mlc_llm.quantization import Quantization from .qwen2_moe_model import Qwen2MoeConfig, Qwen2MoeForCausalLM def huggingface(model_config: Qwen2MoeConfig, quantization: Quantization) -> ExternMapping: model = Qwen2MoeForCausalLM(mo...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's QWen2 parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools @@ -10,6 +14,22 @@ def huggingface(model_config: Qwen2MoeConfig, quantization: Quantization) -> ExternMapping: + """Returns a p...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/qwen2_moe/qwen2_moe_loader.py
Replace inline comments with docstrings
# pylint: disable=missing-function-docstring,missing-class-docstring import dataclasses from functools import partial from typing import Any, Dict, Optional, Tuple 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 ...
--- +++ @@ -1,3 +1,18 @@+"""Partial Qwen2.5-VL implementation focused on decoder-side MRoPE support. + +This file intentionally does not provide complete end-to-end Qwen2.5-VL support yet. +The current scope is: + +- decoder-side text model structure, +- multimodal rotary embedding generation/application, +- position-i...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/qwen2_5_vl/qwen2_5_vl_model.py
Generate consistent documentation across files
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 QWEN architecture. +""" import dataclasses from typing import Any, Dict, Optional @@ -18,6 +21,7 @@ @dataclasses.dataclass class QWenConfig(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the QWen model.""" vocab_size: i...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/qwen/qwen_model.py
Generate docstrings with parameter types
import dataclasses 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, LlamaForCausalLM, LlamaModel, ) from mlc_llm.nn import PagedKVCache from ml...
--- +++ @@ -1,3 +1,4 @@+"""Implementation for Mistral architecture.""" import dataclasses @@ -22,6 +23,7 @@ @dataclasses.dataclass class MixtralConfig(LlamaConfig): # pylint: disable=too-many-instance-attributes + """Configuration of the Mixtral model.""" num_local_experts: int = 0 num_experts_p...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/mixtral/mixtral_model.py
Add structured docstrings to improve clarity
import dataclasses from typing import Any, Dict, Optional from tvm import relax, target, 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.model.phi3 import Phi3Model from mlc_llm.model.vision import CLIPVisionConfig, ImageProcessor f...
--- +++ @@ -1,3 +1,6 @@+""" +Implementation for Phi architecture. +""" import dataclasses from typing import Any, Dict, Optional @@ -33,6 +36,7 @@ @dataclasses.dataclass class Phi3VConfig(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the Phi-3 Vision model.""" model...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/phi3v/phi3v_model.py
Include argument descriptions in docstrings
import dataclasses from typing import Any, Callable, Dict, Literal, Optional, Tuple from tvm.relax.frontend import nn from mlc_llm.loader import ExternMapping, QuantizeMapping from mlc_llm.quantization import make_quantization_functions from mlc_llm.quantization.quantization import Quantization from .baichuan impor...
--- +++ @@ -1,3 +1,4 @@+"""A centralized registry of all existing model architures and their configurations.""" import dataclasses from typing import Any, Callable, Dict, Literal, Optional, Tuple @@ -62,6 +63,19 @@ @dataclasses.dataclass class EmbeddingMetadata: + """Embedding model metadata. + + Parameter...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/model.py
Insert docstrings into my code
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 StableLM architecture. +""" import dataclasses from typing import Any, Dict, Optional @@ -18,6 +21,7 @@ @dataclasses.dataclass class StableLmConfig(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the StableLM model.""" v...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/stable_lm/stablelm_model.py
Add structured docstrings to improve clarity
import dataclasses from typing import Any, Dict, Optional, Tuple from tvm import te, tir from tvm.relax.frontend import nn from tvm.relax.frontend.nn import Object, Tensor, op from tvm.script import tir as T from mlc_llm.nn.rnn_state import RNNState from mlc_llm.support import logging from mlc_llm.support.config imp...
--- +++ @@ -1,3 +1,4 @@+"""Implementation for RWKV6 architecture.""" import dataclasses from typing import Any, Dict, Optional, Tuple @@ -16,6 +17,7 @@ @dataclasses.dataclass class StateID: + """State ID for RWKV6.""" ATT_X = 0 ATT_KV = 1 @@ -24,6 +26,7 @@ @dataclasses.dataclass class RWKV6Conf...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/rwkv6/rwkv6_model.py
Turn comments into proper docstrings
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 Object, Tensor, op from tvm.script import tir as T from mlc_llm.nn.rnn_state import RNNState from mlc_llm.support import logging from mlc_llm.support.config import Con...
--- +++ @@ -1,3 +1,4 @@+"""Implementation for RWKV5 architecture.""" import dataclasses from typing import Any, Dict, Optional @@ -16,6 +17,7 @@ @dataclasses.dataclass class StateID: + """State ID for RWKV5.""" ATT_X = 0 ATT_KV = 1 @@ -24,6 +26,7 @@ @dataclasses.dataclass class RWKV5Config(Conf...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/rwkv5/rwkv5_model.py
Add structured docstrings to improve clarity
import functools from ...loader import ExternMapping from ...quantization import Quantization from .rwkv6_model import RWKV6_ForCausalLM, RWKV6Config def huggingface(model_config: RWKV6Config, quantization: Quantization) -> ExternMapping: model = RWKV6_ForCausalLM(model_config) if quantization is not None: ...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's RWKV6 parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools @@ -7,6 +11,22 @@ def huggingface(model_config: RWKV6Config, quantization: Quantization) -> ExternMapping: + """Returns a param...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/rwkv6/rwkv6_loader.py
Create documentation for each function signature
from tvm import relax, tir from tvm.relax.frontend import nn from tvm.relax.frontend.nn import Module, Tensor, op from tvm.script import tir as T from mlc_llm.model.vision import CLIPVisionModel from mlc_llm.support.config import ConfigBase # mypy: disable-error-code="attr-defined" # pylint: disable=invalid-name,mi...
--- +++ @@ -1,3 +1,6 @@+""" +Implementation for Phi architecture. +""" from tvm import relax, tir from tvm.relax.frontend import nn @@ -262,6 +265,10 @@ return image_features_hd def add_image_newline(self, image_features_hd): + """ + image_features_hd: (num_images, h_crop*12, w_crop*12,...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/phi3v/phi3v_image.py
Write clean docstrings for readability
import dataclasses import logging from typing import Any, Dict, Tuple from tvm import relax from tvm.relax.frontend import nn from tvm.relax.frontend.nn import Module, Tensor from tvm.relax.frontend.nn.modules import Conv2D from tvm.relax.frontend.nn.op import ( add, broadcast_to, concat, permute_dims...
--- +++ @@ -1,3 +1,6 @@+""" +Implements the CLIP Vision Encoder. +""" import dataclasses import logging @@ -25,6 +28,9 @@ @dataclasses.dataclass class CLIPVisionConfig(ConfigBase): # pylint: disable=too-many-instance-attributes + """ + Config for the vision encoder + """ hidden_size: int im...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/vision/clip_vision.py
Document classes and their 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,6 @@+""" +Implementation for Starcoder2 architecture. +""" import dataclasses from typing import Any, Dict, Optional @@ -18,6 +21,7 @@ @dataclasses.dataclass class Starcoder2Config(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the Starcoder2 model.""" ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/starcoder2/starcoder2_model.py
Help me document legacy Python code
import functools import numpy as np from mlc_llm.loader import ExternMapping from mlc_llm.quantization import Quantization from .starcoder2_model import Starcoder2Config, Starcoder2ForCausalLM def huggingface(model_config: Starcoder2Config, quantization: Quantization) -> ExternMapping: model = Starcoder2ForCa...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's Starcoder2 parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools @@ -10,6 +14,22 @@ def huggingface(model_config: Starcoder2Config, quantization: Quantization) -> ExternMapping: + """Retu...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/starcoder2/starcoder2_loader.py
Add docstrings to improve readability
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 Phi-3 architecture. +""" import dataclasses from typing import Any, Dict, Optional @@ -18,6 +21,7 @@ @dataclasses.dataclass class Phi3Config(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the Phi-3 model.""" model_type:...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/phi3/phi3_model.py
Add well-formatted docstrings
from typing import Sequence, Union from tvm import relax as rx from tvm import tir from tvm.relax.frontend.nn import Object, Tensor from tvm.script import tir as T class RNNState(Object): @staticmethod def create( max_batch_size: tir.Var, num_hidden_layers: int, max_history: int, ...
--- +++ @@ -1,3 +1,4 @@+"""RNN State modeling.""" from typing import Sequence, Union @@ -8,6 +9,7 @@ class RNNState(Object): + """The RNN State used in Space State Models""" @staticmethod def create( @@ -17,6 +19,19 @@ init_values: Sequence[Tensor], name: str = "rnn_state", ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/nn/rnn_state.py
Generate docstrings for this script
import tvm from tvm.relax.frontend import nn from tvm.relax.frontend.nn import Tensor, op from mlc_llm.support import logging from . import extern as _extern logger = logging.getLogger(__name__) WARN_FLASHINFER_GROUP_SIZE = False WARN_FLASHINFER_HEAD_DIM = False def attention( # pylint: disable=invalid-name,to...
--- +++ @@ -1,3 +1,4 @@+"""Operators enabled by external modules.""" import tvm from tvm.relax.frontend import nn @@ -22,6 +23,40 @@ attn_score_scaling_factor: float = 1.0, qk_dtype: str = None, ) -> nn.Tensor: + """Attention with casual mask. + + --- Variables --- + s: sequence length of the cur...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/op/attention.py
Add concise docstrings to each method
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.support import logging from mlc_ll...
--- +++ @@ -1,3 +1,7 @@+""" +Implementation for OLMo architecture. +TODO: add docstring +""" import dataclasses from functools import partial @@ -19,6 +23,7 @@ @dataclasses.dataclass class OLMoConfig(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the OLMo model.""" v...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/olmo/olmo_model.py
Add docstrings explaining edge cases
import dataclasses from typing import Optional from tvm.target import Target @dataclasses.dataclass class ExternModuleStore: configured: bool = False target: Optional[Target] = None flashinfer: bool = False faster_transformer: bool = False cutlass_group_gemm: bool = False cutlass_gemm: bool...
--- +++ @@ -1,3 +1,19 @@+"""Potential externel modules managed by MLC compilation stack. + +An externl module could contain one or multiple handcrafted kernels, as long as it is provided as +an object file (`.o`), a C++ source file (`.cc`), or a CUDA source file (`.cu`). It can be +integrated into the system pretty smo...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/op/extern.py
Add professional docstrings to my codebase
import functools from mlc_llm.loader import ExternMapping from mlc_llm.quantization import Quantization from .phi3_model import Phi3Config, Phi3ForCausalLM def phi3_huggingface(model_config: Phi3Config, quantization: Quantization) -> ExternMapping: model = Phi3ForCausalLM(model_config) if quantization is n...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's Phi parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools @@ -8,6 +12,22 @@ def phi3_huggingface(model_config: Phi3Config, quantization: Quantization) -> ExternMapping: + """Returns a par...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/phi3/phi3_loader.py
Write docstrings for this repository
from typing import Literal, Optional, Tuple from tvm import DataType, DataTypeCode, s_tir, tir from tvm.relax.frontend.nn import Tensor, op from tvm.script import tir as T # mypy: disable-error-code="attr-defined,valid-type,name-defined" # pylint: disable=too-many-locals,invalid-name,too-many-arguments,too-many-stat...
--- +++ @@ -1,3 +1,4 @@+"""Mixture of Experts operators""" from typing import Literal, Optional, Tuple @@ -10,6 +11,29 @@ def gemv(x: Tensor, w: Tensor, indptr: Tensor) -> Tensor: + """GEMV for project-in (e1-e3) or project-out (e2) in MLP. + + Parameters + ---------- + x : Tensor + For proj...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/op/moe_matmul.py
Add docstrings to clarify complex logic
from tvm.script import tir as T # mypy: disable-error-code="attr-defined,valid-type,name-defined" # pylint: disable=too-many-locals,invalid-name,too-many-arguments, # pylint: disable=too-many-statements,line-too-long,too-many-nested-blocks,too-many-branches def batch_spec_verify(vocab_size): TX = 1024 def ...
--- +++ @@ -1,3 +1,4 @@+"""Operators for batch verify in speculative decoding.""" from tvm.script import tir as T @@ -7,6 +8,49 @@ def batch_spec_verify(vocab_size): + """Batch draft verify function. This function verifies the token tree. + + Before calling the function + + - token_tree_parent_ptr[b] ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/op/batch_spec_verify.py
Include argument descriptions in docstrings
import operator from functools import reduce from typing import Optional from tvm.relax.frontend import nn from tvm.relax.frontend.nn import op def faster_transformer_dequantize_gemm( # pylint: disable=too-many-arguments x: nn.Tensor, weight: nn.Tensor, scale: nn.Tensor, bias: Optional[nn.Tensor] =...
--- +++ @@ -1,3 +1,4 @@+"""Operators enabled by external modules.""" import operator from functools import reduce @@ -15,6 +16,31 @@ activation: Optional[str] = None, group_size: Optional[int] = None, ): + """ + Faster Transformer dequantize gemm inference with CutlassFpAIntB + + Parameters + ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/op/ft_gemm.py
Add concise docstrings to each method
from __future__ import annotations from dataclasses import dataclass from typing import List, Optional, Sequence, Tuple import numpy as np from tvm import te, tir from tvm.relax.frontend import nn from tvm.relax.frontend.nn import Tensor, op def _rotate_half(x: Tensor) -> Tensor: x1, x2 = op.split(x, 2, axis=...
--- +++ @@ -1,3 +1,4 @@+"""Utilities for Multimodal Rotary Position Embeddings (MRoPE).""" from __future__ import annotations @@ -11,6 +12,7 @@ def _rotate_half(x: Tensor) -> Tensor: + """Rotate the last dimension of ``x`` by swapping pairs.""" x1, x2 = op.split(x, 2, axis=-1) return op.concat([...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/op/mrope.py
Generate docstrings with examples
from typing import Literal, Optional from pydantic import BaseModel class DisaggConfig(BaseModel): kind: Optional[Literal["prepare_receive", "remote_send", "start_generation"]] = None # "kv_append_metadata" is base64-encoded and is thus a string. kv_append_metadata: Optional[str] = None # "kv_windo...
--- +++ @@ -1,3 +1,4 @@+"""Debug protocols in MLC LLM""" from typing import Literal, Optional @@ -5,6 +6,7 @@ class DisaggConfig(BaseModel): + """The class of metadata used in microserving APIs.""" kind: Optional[Literal["prepare_receive", "remote_send", "start_generation"]] = None # "kv_append_...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/protocol/debug_protocol.py
Add docstrings to incomplete code
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 .olmo_model import OLMoConfig, OLMoForCausalLM awq_quant = make_awq_quant(OLMoForCausalLM) huggingface...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's OLMo parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools @@ -19,6 +23,21 @@ def awq(model_config: OLMoConfig, quantization: Quantization) -> ExternMapping: + """Returns a parameter mapp...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/olmo/olmo_loader.py
Document all public functions with docstrings
from pydantic import BaseModel from mlc_llm.protocol.openai_api_protocol import CompletionRequest class PrepRecvRequest(CompletionRequest): end: int class PrepRecvResponse(BaseModel): kv_append_metadata: str prefix_matched_length: int class RemoteSendRequest(CompletionRequest): begin: int ...
--- +++ @@ -1,3 +1,4 @@+"""Protocols in MLC LLM for MicroServing.""" from pydantic import BaseModel @@ -5,17 +6,53 @@ class PrepRecvRequest(CompletionRequest): + """The extra request body for prep_recv request in MicroServing. + + Attributes + ---------- + kv_window_end : int + [0, kv_window...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/protocol/microserving_protocol.py
Create docstrings for all classes and functions
import functools from typing import Callable, List, Literal import numpy as np from mlc_llm.loader import ExternMapping, QuantizeMapping from mlc_llm.quantization import BlockScaleQuantize, Quantization from .qwen3_model import Qwen3Config, Qwen3LMHeadModel def huggingface( model_config: Qwen3Config, quan...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's QWen2 parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools from typing import Callable, List, Literal @@ -15,6 +19,26 @@ quantization: Quantization, hf_prefix: Literal["", "model."] = "...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/qwen3/qwen3_loader.py
Add docstrings to existing functions
# pylint: disable=too-many-instance-attributes from typing import Any, Dict, List, Literal, Optional, Union from pydantic import BaseModel, Field from mlc_llm.support.constants import MLC_CHAT_CONFIG_VERSION from .conversation_protocol import Conversation MLC_CHAT_SYSTEM_DEFAULT = { "pad_token_id": 0, "bos...
--- +++ @@ -1,4 +1,5 @@ # pylint: disable=too-many-instance-attributes +"""Schema for mlc-chat-config""" from typing import Any, Dict, List, Literal, Optional, Union @@ -22,6 +23,7 @@ class MLCChatConfig(BaseModel): + """Fields in the dumped `mlc-chat-config.json` file.""" # Version control vers...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/protocol/mlc_chat_config.py
Add minimal docstrings for each function
import tvm from tvm.script import tir as T from mlc_llm.support.max_thread_check import get_max_num_threads_per_block # mypy: disable-error-code="attr-defined,valid-type,name-defined" # pylint: disable=too-many-locals,invalid-name,too-many-arguments,unnecessary-lambda # pylint: disable=too-many-statements,line-too-l...
--- +++ @@ -1,3 +1,4 @@+"""Operators for choosing the pivot to cut-off top-p percentile""" import tvm from tvm.script import tir as T @@ -10,6 +11,32 @@ def top_p_pivot(pN, target: tvm.target.Target): + """Top-p pivot function. This function finds the pivot to cut-off top-p percentile. + + A valide pivot ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/op/top_p_pivot.py
Add docstrings following best practices
import functools from mlc_llm.loader import ExternMapping from mlc_llm.quantization import Quantization from .phi3v_model import Phi3VConfig, Phi3VForCausalLM # pylint: disable=too-many-statements def huggingface(model_config: Phi3VConfig, quantization: Quantization) -> ExternMapping: model = Phi3VForCausalLM(...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's Phi parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools @@ -9,6 +13,22 @@ # pylint: disable=too-many-statements def huggingface(model_config: Phi3VConfig, quantization: Quantization) -> Ext...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/phi3v/phi3v_loader.py
Write docstrings describing functionality
# pylint: disable=invalid-name from typing import List, Literal, Tuple import tvm from tvm.relax.frontend import nn from tvm.script import ir as I from tvm.script import tir as T try: import triton import triton.language as tl except ImportError: triton = None tl = None # We use a wrapper function...
--- +++ @@ -1,3 +1,4 @@+"""Operators enabled by external modules.""" # pylint: disable=invalid-name @@ -52,6 +53,10 @@ BLOCK_SIZE_K: tl.constexpr, GROUP_SIZE_M: tl.constexpr, ): + """Triton-accelerated function used to perform linear operations (dot + product) on input tensors `...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/op/triton.py
Add docstrings to improve collaboration
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 Nemotron architecture. +""" import dataclasses from typing import Any, Dict, Optional @@ -18,6 +21,7 @@ @dataclasses.dataclass class NemotronConfig(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the Nemotron model.""" v...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/nemotron/nemotron_model.py
Write beginner-friendly docstrings
from enum import Enum from typing import Any, Dict, List, Optional, Tuple, Type, TypeVar, Union from pydantic import BaseModel, Field, field_validator # The message placeholders in the message prompts according to roles. class MessagePlaceholders(Enum): SYSTEM = "{system_message}" USER = "{user_message}" ...
--- +++ @@ -1,3 +1,4 @@+"""The standard conversation protocol in MLC LLM""" from enum import Enum from typing import Any, Dict, List, Optional, Tuple, Type, TypeVar, Union @@ -7,6 +8,7 @@ # The message placeholders in the message prompts according to roles. class MessagePlaceholders(Enum): + """The message pl...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/protocol/conversation_protocol.py
Create docstrings for reusable components
import dataclasses from typing import 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.model.qwen2.qwen2_model import ACT2FN, QWen2Attention, QWen2Config from mlc_llm.nn import PagedKVCache, RopeMode from mlc...
--- +++ @@ -1,3 +1,6 @@+""" +Implementation for QWEN2MOE architecture. +""" import dataclasses from typing import Optional @@ -18,6 +21,7 @@ @dataclasses.dataclass class Qwen2MoeConfig(QWen2Config): # pylint: disable=too-many-instance-attributes + """Configuration of the Qwen2Moe model.""" moe_interme...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/qwen2_moe/qwen2_moe_model.py
Turn comments into proper docstrings
from typing import List from tvm import relax from tvm.relax.frontend.nn import Tensor, op def pipeline_stage_boundary(*tensors: Tensor) -> List[Tensor]: # pylint: disable=protected-access return op.wrap_nested( relax.call_pure_packed( "mlc.pipeline_parallel_stage_boundary", ...
--- +++ @@ -1,3 +1,4 @@+"""Operators for pipeline parallelism.""" from typing import List @@ -6,6 +7,18 @@ def pipeline_stage_boundary(*tensors: Tensor) -> List[Tensor]: + """Pipeline parallelism stage boundary mark operator in MLC. + + Parameters + ---------- + tensors : Tensor + The tensor...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/op/pipeline_parallel.py
Add documentation for all methods
# pylint: disable=missing-class-docstring, disable=too-many-instance-attributes from typing import Dict, List, Optional from pydantic import BaseModel from .debug_protocol import DebugConfig from .openai_api_protocol import RequestResponseFormat class GenerationConfig(BaseModel): # pylint: n: int = 1 tem...
--- +++ @@ -1,3 +1,4 @@+"""Low-level generation config class""" # pylint: disable=missing-class-docstring, disable=too-many-instance-attributes from typing import Dict, List, Optional @@ -9,6 +10,10 @@ class GenerationConfig(BaseModel): # pylint: + """The generation configuration dataclass. + + This is a...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/protocol/generation_config.py
Add docstrings explaining edge cases
import functools from dataclasses import dataclass from typing import Any, Dict, List, Literal, Optional, Sequence, Tuple, Type, Union import numpy as np from tvm import DataType, DataTypeCode, IRModule, relax, runtime, te, tir, topi from tvm.relax.frontend import nn from tvm.runtime import Tensor from mlc_llm.loade...
--- +++ @@ -1,3 +1,4 @@+"""The per-tensor quantization config""" import functools from dataclasses import dataclass @@ -27,6 +28,7 @@ @dataclass class PerTensorQuantize: # pylint: disable=too-many-instance-attributes + """Configuration for per-tensor quantization""" name: str kind: str @@ -63,6 +...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/quantization/per_tensor_quantization.py
Provide clean and structured docstrings
from http import HTTPStatus from typing import Optional import fastapi from pydantic import BaseModel class BadRequestError(ValueError): def __init__(self, *args: object) -> None: super().__init__(*args) class ErrorResponse(BaseModel): object: str = "error" message: str code: Optional[in...
--- +++ @@ -1,3 +1,4 @@+"""Error protocols in MLC LLM""" from http import HTTPStatus from typing import Optional @@ -7,12 +8,14 @@ class BadRequestError(ValueError): + """The exception for bad requests in engines.""" def __init__(self, *args: object) -> None: super().__init__(*args) clas...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/protocol/error_protocol.py
Fill in missing docstrings in my code
# pylint: disable=too-many-lines import asyncio import queue import sys import weakref from typing import ( Any, AsyncGenerator, Dict, Iterator, List, Literal, Optional, Tuple, Union, overload, ) from tvm.runtime import Device from mlc_llm.protocol import debug_protocol, open...
--- +++ @@ -1,3 +1,4 @@+"""The MLC LLM Serving Engine.""" # pylint: disable=too-many-lines @@ -34,6 +35,7 @@ # Note: we define both AsyncChat and Chat for Python type analysis. class AsyncChat: # pylint: disable=too-few-public-methods + """The proxy class to direct to async chat completions.""" def _...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/serve/engine.py
Add docstrings to clarify complex logic
# pylint: disable=missing-class-docstring import json import time from typing import Any, Dict, List, Literal, Optional, Tuple, Union import shortuuid from pydantic import BaseModel, Field, field_validator, model_validator from .conversation_protocol import Conversation from .debug_protocol import DebugConfig from ...
--- +++ @@ -1,3 +1,7 @@+"""Protocols in MLC LLM for OpenAI API. +Adapted from FastChat's OpenAI protocol: +https://github.com/lm-sys/FastChat/blob/main/fastchat/protocol/openai_api_protocol.py +""" # pylint: disable=missing-class-docstring @@ -68,6 +72,9 @@ class EmbeddingRequest(BaseModel): + """OpenAI "v1...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/protocol/openai_api_protocol.py
Add docstrings including usage examples
# pylint: disable=too-many-lines import ast import asyncio import json import numbers import queue import sys import threading from dataclasses import dataclass from pathlib import Path from typing import Any, Callable, Dict, List, Literal, Optional, Tuple, Union import tvm from tvm.runtime import Device from mlc_l...
--- +++ @@ -1,3 +1,4 @@+"""The MLC LLM Serving engine base class.""" # pylint: disable=too-many-lines @@ -32,6 +33,20 @@ @dataclass class ModelInfo: + """The model info dataclass. + + Parameters + ---------- + model : str + The identifier of the input model. + It may be a compiled mode...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/serve/engine_base.py
Add documentation for all methods
import dataclasses from typing import 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.model.qwen3.qwen3_model import ACT2FN, Qwen3Attention, Qwen3Config from mlc_llm.nn import PagedKVCache, RopeMode from mlc...
--- +++ @@ -1,3 +1,6 @@+""" +Implementation for QWEN2MOE architecture. +""" import dataclasses from typing import Optional @@ -18,6 +21,7 @@ @dataclasses.dataclass class Qwen3MoeConfig(Qwen3Config): # pylint: disable=too-many-instance-attributes + """Configuration of the Qwen3Moe model.""" moe_interme...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/qwen3_moe/qwen3_moe_model.py
Add minimal docstrings for each function
import fastapi from fastapi.responses import PlainTextResponse from mlc_llm.serve.server import ServerContext app = fastapi.APIRouter() ################ /metrics ################ @app.get("/metrics", response_class=PlainTextResponse) async def metrics(_request: fastapi.Request): server_context: ServerContext ...
--- +++ @@ -1,3 +1,4 @@+"""MLC LLM server metrics entrypoints""" import fastapi from fastapi.responses import PlainTextResponse @@ -11,6 +12,7 @@ @app.get("/metrics", response_class=PlainTextResponse) async def metrics(_request: fastapi.Request): + """Start the cuda profiler for the engine. Only for debug pur...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/serve/entrypoints/metrics_entrypoints.py
Provide clean and structured docstrings
from dataclasses import dataclass, field from typing import Any, Callable, Dict, List, Optional from tvm import DataType, DataTypeCode, te, tir, topi from tvm.relax.frontend import nn from tvm.runtime import Tensor from mlc_llm.loader import QuantizeMapping from .utils import convert_uint_to_float, is_final_fc, is_...
--- +++ @@ -1,3 +1,4 @@+"""AWQ Quantization""" from dataclasses import dataclass, field from typing import Any, Callable, Dict, List, Optional @@ -32,6 +33,7 @@ @dataclass class AWQQuantize: # pylint: disable=too-many-instance-attributes + """Configuration for AWQ quantization""" name: str kind: ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/quantization/awq_quantization.py
Expand my code with proper documentation strings
import uuid from typing import Any, Callable, Dict, List, Literal, Optional, Union from mlc_llm.protocol import error_protocol, openai_api_protocol from mlc_llm.protocol.generation_config import GenerationConfig from mlc_llm.serve import data RequestProtocol = Union[ openai_api_protocol.CompletionRequest, openai...
--- +++ @@ -1,3 +1,4 @@+"""Utility functions for MLC Serve engine""" import uuid from typing import Any, Callable, Dict, List, Literal, Optional, Union @@ -12,6 +13,9 @@ def get_unsupported_fields(request: RequestProtocol) -> List[str]: + """Get the unsupported fields of the request. + Return the list of ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/serve/engine_utils.py
Write documentation strings for class attributes
import json from http import HTTPStatus import fastapi from mlc_llm.protocol import error_protocol from mlc_llm.serve.server import ServerContext app = fastapi.APIRouter() ################ /debug/dump_event_trace ################ @app.post("/debug/dump_event_trace") async def debug_dump_event_trace(request: fast...
--- +++ @@ -1,3 +1,4 @@+"""MLC LLM server debug entrypoints""" import json from http import HTTPStatus @@ -14,6 +15,10 @@ @app.post("/debug/dump_event_trace") async def debug_dump_event_trace(request: fastapi.Request): + """Return the recorded events in Chrome Trace Event Format in JSON string. + The input...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/serve/entrypoints/debug_entrypoints.py
Write Python docstrings for this snippet
from typing import Callable, List, Optional, Sequence from tvm import IRModule, relax, te, tir from tvm.relax.frontend import nn from tvm.runtime import DataType, DataTypeCode from tvm.s_tir import dlight as dl from tvm.target import Target from mlc_llm.support import tensor_parallel as tp def convert_uint_to_floa...
--- +++ @@ -1,3 +1,4 @@+"""Common utilities for quantization""" from typing import Callable, List, Optional, Sequence @@ -20,6 +21,7 @@ out_shape: Optional[List[tir.PrimExpr]] = None, ft_reorder: Optional[bool] = False, ) -> te.Tensor: + """Convert a quantized uint weight to an unquantized float weigh...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/quantization/utils.py
Create docstrings for each class method
from functools import reduce from typing import Literal, Optional, Tuple, Union import numpy as np from tvm import te, tir from tvm.relax.frontend.nn import IntExpr, Tensor, op from tvm.script import tir as T # mypy: disable-error-code="attr-defined,name-defined" # pylint: disable=line-too-long,too-many-locals,inval...
--- +++ @@ -1,3 +1,4 @@+"""Mixture of Experts operators""" from functools import reduce from typing import Literal, Optional, Tuple, Union @@ -12,6 +13,9 @@ def moe_sum(x: Tensor, dim: int) -> Tensor: + """Compute the sum of the input tensor along the given axis. It is specialized for the MoE + case where...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/op/moe_misc.py
Generate docstrings for this script
import json import math import threading from typing import Any, AsyncGenerator, Iterable, List, Literal, Optional, Tuple import aiohttp # pylint: disable=import-error import tvm from mlc_llm.protocol import openai_api_protocol from mlc_llm.serve import EngineConfig, PopenServer from mlc_llm.serve.entrypoints impor...
--- +++ @@ -1,3 +1,4 @@+"""Programmable router for dispatching OpenAI API to Microserving API""" import json import math @@ -14,6 +15,7 @@ class Router: # pylint: disable=too-many-instance-attributes + """Programmable Router Implementation""" def __init__( self, @@ -26,6 +28,9 @@ rou...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/router/router.py
Add docstrings to clarify complex logic
from dataclasses import dataclass from typing import Dict, List, Optional, Tuple import tvm import tvm_ffi from tvm.runtime import Object, Tensor from . import _ffi_api @tvm_ffi.register_object("mlc.serve.Data") # pylint: disable=protected-access class Data(Object): # pylint: disable=too-few-public-methods ...
--- +++ @@ -1,3 +1,4 @@+"""Classes denoting multi-modality data used in MLC LLM serving""" from dataclasses import dataclass from typing import Dict, List, Optional, Tuple @@ -11,6 +12,7 @@ @tvm_ffi.register_object("mlc.serve.Data") # pylint: disable=protected-access class Data(Object): # pylint: disable=too-f...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/serve/data.py
Generate documentation strings for clarity
# pylint: disable=too-many-locals,too-many-return-statements,too-many-statements,fixme import base64 import struct from http import HTTPStatus from typing import AsyncGenerator, List, Optional import fastapi import numpy as np from mlc_llm.protocol import error_protocol from mlc_llm.protocol.openai_api_protocol impo...
--- +++ @@ -1,3 +1,4 @@+"""OpenAI API-compatible server entrypoints in MLC LLM""" # pylint: disable=too-many-locals,too-many-return-statements,too-many-statements,fixme import base64 @@ -26,6 +27,7 @@ def verify_api_key(request: fastapi.Request): + """Function to verify API key""" server_context = Serve...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/serve/entrypoints/openai_entrypoints.py
Add docstrings that explain logic
import functools import numpy as np from ...loader import ExternMapping from ...quantization import Quantization from .rwkv5_model import RWKV5_ForCausalLM, RWKV5Config def huggingface(model_config: RWKV5Config, quantization: Quantization) -> ExternMapping: model = RWKV5_ForCausalLM(model_config) if quanti...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's RWKV5 parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools @@ -9,6 +13,22 @@ def huggingface(model_config: RWKV5Config, quantization: Quantization) -> ExternMapping: + """Returns a param...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/rwkv5/rwkv5_loader.py
Add docstrings including usage examples
import json from dataclasses import asdict, dataclass, field from typing import List, Literal, Optional, Tuple, Union @dataclass class EngineConfig: # pylint: disable=too-many-instance-attributes model: Optional[str] = None model_lib: Optional[str] = None additional_models: List[Union[str, Tuple[str, s...
--- +++ @@ -1,3 +1,4 @@+"""Configuration dataclasses used in MLC LLM serving""" import json from dataclasses import asdict, dataclass, field @@ -6,6 +7,132 @@ @dataclass class EngineConfig: # pylint: disable=too-many-instance-attributes + """The class of MLCEngine execution configuration. + + Parameters +...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/serve/config.py
Generate helpful docstrings for debugging
from tvm.target import Target def get_max_num_threads_per_block(target: Target) -> int: max_num_threads = target.attrs.get("max_num_threads") max_threads_per_block = target.attrs.get("max_threads_per_block", None) if max_threads_per_block is None: return max_num_threads return max(max_num_thr...
--- +++ @@ -1,8 +1,13 @@+"""Helper functions for checking max num thread.""" from tvm.target import Target def get_max_num_threads_per_block(target: Target) -> int: + """ + max(max_num_threads, max_threads_per_block); if latter does not exist, return max_num_threads. + We add this method since some tar...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/support/max_thread_check.py
Help me comply with documentation standards
import logging from typing import Any, Callable, Dict, Sequence, Tuple from tvm import IRModule, relax from tvm.relax.frontend import nn from tvm.runtime import Device, Tensor from tvm.s_tir import dlight as dl from tvm.target import Target logger = logging.getLogger("preshard") def _sharded_param_name(param_name,...
--- +++ @@ -1,3 +1,4 @@+"""Functions for pre-sharding weights""" import logging from typing import Any, Callable, Dict, Sequence, Tuple @@ -72,6 +73,23 @@ tensor_parallel_shards: int, args: Any, ) -> Tuple[Dict[str, nn.Parameter], Dict[str, Callable[[Tensor], Sequence[Tensor]]]]: + """Apply pre-shardin...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/support/preshard.py
Add docstrings for utility scripts
import asyncio import concurrent.futures import json import os from typing import List, Literal, Optional, Tuple, Union import numpy as np import tvm from tvm import relax from tvm.runtime import Device, ShapeTuple from mlc_llm.serve import engine_utils from mlc_llm.support.auto_device import detect_device from mlc_...
--- +++ @@ -1,3 +1,4 @@+"""Asynchronous embedding inference engine for encoder and decoder models.""" import asyncio import concurrent.futures @@ -16,6 +17,28 @@ class AsyncEmbeddingEngine: # pylint: disable=too-many-instance-attributes + """Asynchronous embedding inference engine. + + Supports both enco...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/serve/embedding_engine.py
Document all public functions with docstrings
# pylint: disable=too-many-statements,too-many-lines,too-many-arguments import json from typing import Any, Dict, List, Literal, Optional, Union import numpy as np from tvm import relax as rx from tvm import tir from tvm.relax.frontend.nn.llm.kv_cache import PagedKVCache as TVMPagedKVCache from tvm.relax.frontend.nn....
--- +++ @@ -1,3 +1,4 @@+"""Attention KV cache modeling.""" # pylint: disable=too-many-statements,too-many-lines,too-many-arguments import json @@ -11,6 +12,7 @@ class PagedKVCache(TVMPagedKVCache): # pylint: disable=too-few-public-methods + """The Paged KV Cache used in LLM batching for efficient attention ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/nn/kv_cache.py
Add docstrings to existing functions
import functools from typing import Callable, List import numpy as np from mlc_llm.loader import ExternMapping, QuantizeMapping from mlc_llm.quantization import BlockScaleQuantize, Quantization from .qwen3_moe_model import Qwen3MoeConfig, Qwen3MoeForCausalLM def huggingface(model_config: Qwen3MoeConfig, quantizat...
--- +++ @@ -1,3 +1,7 @@+""" +This file specifies how MLC's QWen2 parameter maps from other formats, for example HuggingFace +PyTorch, HuggingFace safetensors. +""" import functools from typing import Callable, List @@ -11,6 +15,22 @@ def huggingface(model_config: Qwen3MoeConfig, quantization: Quantization) -> E...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/qwen3_moe/qwen3_moe_loader.py
Document all public functions with docstrings
import dataclasses from functools import partial from typing import Any, Dict, Optional, Tuple 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...
--- +++ @@ -1,3 +1,6 @@+""" +Implementation for QWEN2 architecture. +""" import dataclasses from functools import partial @@ -19,6 +22,7 @@ @dataclasses.dataclass class Qwen3Config(ConfigBase): # pylint: disable=too-many-instance-attributes + """Configuration of the Qwen3 model.""" hidden_act: str ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/model/qwen3/qwen3_model.py
Write docstrings including parameters and return values
from dataclasses import dataclass from typing import Any, Literal, Optional, Tuple import tvm from tvm import DataType, DataTypeCode, te, tir from tvm.relax.frontend import nn from tvm.script import tir as T from mlc_llm.loader import QuantizeMapping from mlc_llm.nn import MixtralExperts from mlc_llm.op import cutla...
--- +++ @@ -1,3 +1,4 @@+"""The block-scale quantization config""" from dataclasses import dataclass from typing import Any, Literal, Optional, Tuple @@ -20,6 +21,7 @@ @dataclass class BlockScaleQuantize: # pylint: disable=too-many-instance-attributes + """Configuration for block-scale quantization""" ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/quantization/block_scale_quantization.py
Write docstrings describing each step
import numpy as np from tvm import relax, runtime from tvm.relax.frontend import nn from mlc_llm.nn import MixtralExperts from ..op import cutlass, extern, moe_matmul from . import per_tensor_quantization as ptq from .utils import apply_sharding class FP8PerTensorQuantizeMixtralExperts( ptq.PerTensorQuantizeMi...
--- +++ @@ -1,3 +1,4 @@+"""Quantization techniques for FP8""" import numpy as np from tvm import relax, runtime @@ -13,6 +14,7 @@ class FP8PerTensorQuantizeMixtralExperts( ptq.PerTensorQuantizeMixtralExperts ): # pylint: disable=too-many-instance-attributes + """MixtralExperts with per-tensor quantization...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/quantization/fp8_quantization.py
Add docstrings to improve collaboration
import logging import os def enable_logging(): if os.getenv("MLC_UNSET_LOGGING"): return logging.basicConfig( level=logging.INFO, style="{", datefmt="%Y-%m-%d %H:%M:%S", format="[{asctime}] {levelname} {filename}:{lineno}: {message}", ) def getLogger(name: str): ...
--- +++ @@ -1,9 +1,14 @@+""" +Logging support for MLC. It derives from Python's logging module, and in the future, +it can be easily replaced by other logging modules such as structlog. +""" import logging import os def enable_logging(): + """Enable MLC's default logging format""" if os.getenv("MLC_UNS...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/support/logging.py
Write beginner-friendly docstrings
import fastapi from mlc_llm.protocol.debug_protocol import DisaggConfig from mlc_llm.protocol.microserving_protocol import ( PrepRecvRequest, PrepRecvResponse, RemoteSendRequest, StartGenerateRequest, ) from mlc_llm.protocol.openai_api_protocol import StreamOptions from .openai_entrypoints import req...
--- +++ @@ -1,3 +1,4 @@+"""MicroServing server entrypoints in MLC LLM""" import fastapi @@ -20,6 +21,11 @@ @app.post("/microserving/prep_recv") async def prep_recv(request: PrepRecvRequest, raw_request: fastapi.Request) -> PrepRecvResponse: + """Handle the microserving request for receive preparation. + M...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/serve/entrypoints/microserving_entrypoints.py
Add docstrings that explain inputs and outputs
import sys def set_global_random_seed(seed): if "numpy" in sys.modules: sys.modules["numpy"].random.seed(seed) if "torch" in sys.modules: sys.modules["torch"].manual_seed(seed) if "random" in sys.modules: sys.modules["random"].seed(seed) # pylint: disable=no-member if "tvm" i...
--- +++ @@ -1,8 +1,10 @@+"""Utility functions for random number generation.""" import sys def set_global_random_seed(seed): + """Set global random seed for python, numpy, torch and tvm.""" if "numpy" in sys.modules: sys.modules["numpy"].random.seed(seed) if "torch" in sys.modules: @@ -12,4...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/support/random.py
Document functions with detailed explanations
from typing import Optional, Tuple from tvm.relax.frontend import nn from tvm.relax.frontend.nn import op def group_gemm( x: nn.Tensor, weight: nn.Tensor, indptr: nn.Tensor, scale: Optional[nn.Tensor] = None, weight_dtype: Optional[str] = None, out_dtype: Optional[str] = None, ): # pylint: ...
--- +++ @@ -1,3 +1,4 @@+"""Operators enabled by external modules.""" from typing import Optional, Tuple @@ -13,6 +14,34 @@ weight_dtype: Optional[str] = None, out_dtype: Optional[str] = None, ): # pylint: disable=too-many-arguments + """ + Cutlass group gemm operator. + + Parameters + ------...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/op/cutlass.py
Write docstrings for utility functions
from typing import Any, Callable, Dict, Optional, Tuple, Type from tvm.relax.frontend import nn from mlc_llm.loader import QuantizeMapping from .awq_quantization import AWQQuantize from .block_scale_quantization import BlockScaleQuantize from .ft_quantization import FTQuantize from .group_quantization import GroupQ...
--- +++ @@ -1,3 +1,4 @@+"""Quantization factory utilities for model quantization.""" from typing import Any, Callable, Dict, Optional, Tuple, Type @@ -29,6 +30,7 @@ set_tensor_parallel_shards: bool = True, per_tensor_use_shards: bool = True, ) -> Dict[str, FuncQuantization]: + """Create standard quant...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/quantization/model_quantization.py
Fill in missing docstrings in my code
import concurrent.futures as cf import hashlib import json import os import shutil import subprocess import tempfile from pathlib import Path from typing import List, Optional, Tuple import requests # pylint: disable=import-error from . import logging, tqdm from .constants import ( MLC_DOWNLOAD_CACHE_POLICY, ...
--- +++ @@ -1,3 +1,4 @@+"""Common utilities for downloading files from HuggingFace or other URLs online.""" import concurrent.futures as cf import hashlib @@ -24,6 +25,7 @@ def log_download_cache_policy(): + """log current download policy""" logger.info( "%s = %s. Can be one of: ON, OFF, REDO, ...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/support/download_cache.py
Generate docstrings with examples
from dataclasses import dataclass from functools import partial from typing import Any, List, Literal, Optional, Tuple, Union from tvm import DataType, DataTypeCode, IRModule, relax, te, tir, topi from tvm.relax.frontend import nn from tvm.runtime import Tensor from mlc_llm.loader import QuantizeMapping from mlc_llm...
--- +++ @@ -1,3 +1,4 @@+"""The group quantization config""" from dataclasses import dataclass from functools import partial @@ -25,6 +26,7 @@ @dataclass class GroupQuantize: # pylint: disable=too-many-instance-attributes + """Configuration for group quantization""" name: str kind: str @@ -66,6 +6...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/quantization/group_quantization.py
Document all endpoints with docstrings
import json from typing import Any, Callable, Dict, List, Literal, Optional, Sequence, Tuple, Union import tvm from mlc_llm.protocol.generation_config import GenerationConfig from mlc_llm.serve import data from mlc_llm.serve.config import EngineConfig from mlc_llm.serve.engine_base import ( EngineMetrics, _c...
--- +++ @@ -1,3 +1,12 @@+"""The MLC LLM synchronized engine. + +NOTE: This engine defined in this file directly wraps the underlying +Engine implementation in C++, is not optimized by multi-threading and +does not offer standard OpenAI API interface. + +We do not expose it and use it by default. As of now it mainly ser...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/serve/sync_engine.py
Help me write clear docstrings
import dataclasses from contextlib import contextmanager from typing import Any, Dict, List, Optional from tvm import te, tir, topi from tvm.relax.frontend import nn @dataclasses.dataclass class ShardSingleDim: name: str dim: int segs: Optional[List[int]] = None def gen_tir(self, shards: int, weig...
--- +++ @@ -1,3 +1,4 @@+"""Sharding operators for tensor parallelism.""" import dataclasses from contextlib import contextmanager @@ -9,12 +10,31 @@ @dataclasses.dataclass class ShardSingleDim: + """ + Shard a tensor by a single dimension. + + + Parameters + ---------- + name : str + The na...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/support/tensor_parallel.py
Add docstrings for internal functions
# pylint: disable=import-error # isort: off import json import os from typing import Dict, List, Optional def bpe( mergeable_ranks: Dict[bytes, int], token: bytes, max_rank: Optional[int] = None ) -> List[bytes]: parts = [bytes([b]) for b in token] while True: min_idx = None min_rank = No...
--- +++ @@ -1,3 +1,7 @@+""" +Adapted from https://gist.github.com/xenova/a452a6474428de0182b17605a98631ee +Generator of mlc-chat-config.json and tokenizer configuration. +""" # pylint: disable=import-error # isort: off @@ -9,6 +13,7 @@ def bpe( mergeable_ranks: Dict[bytes, int], token: bytes, max_rank: Optiona...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/support/convert_tiktoken.py
Create Google-style docstrings for my code
import os from pathlib import Path from typing import TYPE_CHECKING, Callable, List, Optional, Tuple from tvm import IRModule, relax from tvm.contrib import ndk, tar, xcode from tvm.ir.transform import Pass from tvm.target import Target from tvm_ffi import get_global_func, register_global_func from . import logging ...
--- +++ @@ -1,3 +1,4 @@+"""Helper functions for target auto-detection.""" import os from pathlib import Path @@ -28,6 +29,17 @@ def detect_target_and_host(target_hint: str, host_hint: str = "auto") -> Tuple[Target, BuildFunc]: + """Detect the configuration for the target device and its host, for example, tar...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/support/auto_target.py
Add return value explanations in docstrings
import json import tempfile from pathlib import Path from typing import TYPE_CHECKING from . import logging from .style import bold, green if TYPE_CHECKING: from mlc_llm.model import Model # pylint: disable=unused-import from mlc_llm.quantization import Quantization # pylint: disable=unused-import logger...
--- +++ @@ -1,3 +1,4 @@+"""Help function for detecting the model configuration file `config.json`""" import json import tempfile @@ -18,6 +19,20 @@ def detect_mlc_chat_config(mlc_chat_config: str) -> Path: + """Detect and return the path that points to mlc-chat-config.json. + If `mlc_chat_config` is a dir...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/support/auto_config.py
Create structured documentation for my script
from typing import TYPE_CHECKING, Dict, List, Optional from ..engine import AsyncMLCEngine if TYPE_CHECKING: from ..embedding_engine import AsyncEmbeddingEngine class ServerContext: server_context: Optional["ServerContext"] = None enable_debug: bool = False def __init__(self) -> None: sel...
--- +++ @@ -1,3 +1,4 @@+"""Server context that shared by multiple entrypoint files.""" from typing import TYPE_CHECKING, Dict, List, Optional @@ -8,6 +9,9 @@ class ServerContext: + """The global server context, including the running models + and corresponding async engines. + """ server_context...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/serve/server/server_context.py
Write docstrings that follow conventions
import sqlite3 import uuid import json from datetime import datetime from typing import List, Dict, Optional, Tuple class ChatDatabase: def __init__(self, db_path: str = None): if db_path is None: # Auto-detect environment and set appropriate path import os if os.path.ex...
--- +++ @@ -18,6 +18,7 @@ self.init_database() def init_database(self): + """Initialize the SQLite database with required tables""" conn = sqlite3.connect(self.db_path) cursor = conn.cursor() @@ -105,6 +106,7 @@ print("✅ Database initialized successfully") ...
https://raw.githubusercontent.com/PromtEngineer/localGPT/HEAD/backend/database.py
Write docstrings that follow conventions
# pylint: disable=missing-docstring import argparse import logging import os import re import subprocess # Modify the following value during release # --------------------------------------------------- # Current version: # We use the version of the incoming release for code # that is under development. # # It is also...
--- +++ @@ -1,4 +1,11 @@ # pylint: disable=missing-docstring +""" +This is the global script that set the version information of TVM. +This script runs and update all the locations that related to versions + +List of affected files: +- mlc-llm-root/pyproject.toml +""" import argparse import logging import os @@ -30,...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/version.py
Generate missing documentation strings
import os import subprocess import sys from typing import Dict, Optional import tvm from tvm.runtime import Device from tvm_ffi import DLDeviceType from . import logging from .style import bold, green, red FOUND = green("Found") NOT_FOUND = red("Not found") AUTO_DETECT_DEVICES = ["cuda", "rocm", "metal", "vulkan", ...
--- +++ @@ -1,3 +1,4 @@+"""Automatic detection of the device available on the local machine.""" import os import subprocess @@ -21,6 +22,7 @@ def detect_device(device_hint: str) -> Optional[Device]: + """Detect locally available device from string hint.""" if device_hint == "auto": device = Non...
https://raw.githubusercontent.com/mlc-ai/mlc-llm/HEAD/python/mlc_llm/support/auto_device.py