instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Please document this code using docstrings
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -30,6 +30,14 @@ def _noisy_mean_initialization(embed_weight: "torch.Tensor", num_new_tokens: int) -> None: + """Initialize new token embeddings with mean + Gaussian noise. + + This is the default initialization method used by LlamaFactory. + + Args: + embed_weight: The embedding weight ma...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/model/model_utils/embedding.py
Add return value explanations in docstrings
# Copyright 2025 HuggingFace Inc., the KVCache.AI team, Approaching AI, and the LlamaFactory team. # # This code is inspired by the HuggingFace's transformers library. # https://github.com/huggingface/transformers/blob/v4.40.0/examples/pytorch/language-modeling/run_clm.py # # Licensed under the Apache License, Version ...
--- +++ @@ -32,6 +32,7 @@ @dataclass class BaseModelArguments: + r"""Arguments pertaining to the model.""" model_name_or_path: str | None = field( default=None, @@ -272,6 +273,7 @@ @dataclass class QuantizationArguments: + r"""Arguments pertaining to the quantization method.""" quanti...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/hparams/model_args.py
Generate docstrings for this script
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -53,6 +53,17 @@ def fix_valuehead_checkpoint( model: "AutoModelForCausalLMWithValueHead", output_dir: str, safe_serialization: bool ) -> None: + r"""Fix the valuehead checkpoint files. + + The model is already unwrapped. + + There are three cases: + 1. full tuning without ds_zero3: state_di...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/train/callbacks.py
Generate consistent docstrings
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -25,12 +25,18 @@ answer: str def _parse_example(self, example: dict[str, str]) -> tuple[str, str]: + r"""Parse eval example. + + input: a dict with keys {"question", "A", "B", "C", "D", "answer"} + output: a tuple of (prompt, response). + """ candidates = [self...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/eval/template.py
Document this module using docstrings
# Copyright 2025 Musab Gultekin and the LlamaFactory team. # # This code is based on the Musab Gultekin's functionary library. # https://github.com/MeetKai/functionary/blob/main/functionary/train/packing/monkey_patch_packing.py # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this f...
--- +++ @@ -53,6 +53,19 @@ def get_seqlens_in_batch(attention_mask: "torch.Tensor") -> "torch.Tensor": + r"""Get the sequence lengths in the current batch. + + e.g. + ```python + # input + [ + [1, 1, 2, 2, 2, 0], + [1, 2, 2, 3, 3, 3], + ] + # output + [2, 3, 1, 2, 3] + ``` +...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/model/model_utils/packing.py
Add standardized docstrings across the file
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -12,6 +12,15 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Convert a HuggingFace model to DCP checkpoint format. + +Usage: + python scripts/hf2dcp.py convert --hf_path=/path/to/hf --dcp_path=/path/to/dcp + +Arguments: + hf_path: Path to the...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/scripts/hf2dcp.py
Generate NumPy-style docstrings
# Copyright 2025 Optuna, HuggingFace Inc. and the LlamaFactory team. # # This code is inspired by the HuggingFace's transformers library. # https://github.com/huggingface/transformers/blob/v4.40.0/src/transformers/utils/logging.py # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use thi...
--- +++ @@ -32,6 +32,7 @@ class LoggerHandler(logging.Handler): + r"""Redirect the logging output to the logging file for LLaMA Board.""" def __init__(self, output_dir: str) -> None: super().__init__() @@ -65,6 +66,7 @@ class _Logger(logging.Logger): + r"""A logger that supports rank0 logg...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/extras/logging.py
Add docstrings to make code maintainable
# Copyright 2025 HuggingFace Inc. and the LlamaFactory team. # # This code is inspired by the HuggingFace's Transformers and Optimum library. # https://github.com/huggingface/transformers/blob/v4.41.0/src/transformers/utils/quantization_config.py # https://github.com/huggingface/optimum/blob/v1.20.0/optimum/gptq/data.p...
--- +++ @@ -41,6 +41,7 @@ def _get_quantization_dataset(tokenizer: "PreTrainedTokenizer", model_args: "ModelArguments") -> list[dict[str, Any]]: + r"""Prepare the tokenized dataset to perform AutoGPTQ. Do not use tensor output for JSON serialization.""" if os.path.isfile(model_args.export_quantization_datas...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/model/model_utils/quantization.py
Add docstrings for production code
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -12,6 +12,17 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Why we need this script for qwen_omni? + +Because the qwen_omni model is constructed by two parts: +1. [Thinker]:[audio_encoder, vision_encoder, LLM backbone], which our repository do...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/scripts/qwen_omni_merge.py
Write docstrings describing functionality
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -37,6 +37,10 @@ class BaseEngine(ABC): + r"""Base class for inference engine of chat models. + + Must implements async methods: chat(), stream_chat() and get_scores(). + """ name: "EngineName" model: Union["PreTrainedModel", "AsyncLLMEngine"] @@ -53,6 +57,7 @@ finetuning_args...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/chat/base_engine.py
Write clean docstrings for readability
# Copyright 2025 Moonshot AI and the LlamaFactory team. # # This code is based on the MoonshotAI's Moonlight library. # https://github.com/MoonshotAI/Moonlight/blob/master/examples/toy_train.py # and the Keller Jordan's Muon library. # https://github.com/KellerJordan/Muon/blob/master/muon.py # # Licensed under the Apac...
--- +++ @@ -46,6 +46,15 @@ def zeropower_via_newtonschulz5(G: "torch.Tensor", steps: int) -> "torch.Tensor": + """Newton-Schulz iteration to compute the zeroth power / orthogonalization of G. + + We opt to use a quintic iteration whose coefficients are selected to maximize the slope at zero. + For the purp...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/third_party/muon/muon.py
Add docstrings including usage examples
# Copyright 2025 HuggingFace Inc. and the LlamaFactory team. # # This code is inspired by the HuggingFace's Transformers library. # https://github.com/huggingface/transformers/blob/v4.40.0/src/transformers/models/llava/processing_llava.py # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not...
--- +++ @@ -93,6 +93,14 @@ def _get_paligemma_token_type_ids(imglens: list[int], seqlens: list[int], processor: "MMProcessor") -> list[list[int]]: + r"""Get paligemma token type ids for computing loss. + + It is slightly different with the original token type ids where the prompt part is 0. + + Returns: + ...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/data/mm_plugin.py
Create documentation for each function signature
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -51,6 +51,7 @@ def merge_dataset( all_datasets: list[Union["Dataset", "IterableDataset"]], data_args: "DataArguments", seed: int ) -> Union["Dataset", "IterableDataset"]: + r"""Merge multiple datasets to a unified dataset.""" if len(all_datasets) == 1: return all_datasets[0] @@ -87,6...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/data/data_utils.py
Create simple docstrings for beginners
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -50,6 +50,7 @@ def check_lfi_path(path: str) -> None: + """Checks if a given path is vulnerable to LFI. Raises HTTPException if unsafe.""" if not ALLOW_LOCAL_FILES: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Local file access is disabled.") @@ -67,6 +68,7 @@ ...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/api/common.py
Create docstrings for each class method
# Copyright 2025 THUDM and the LlamaFactory team. # # This code is inspired by the THUDM's ChatGLM implementation. # https://github.com/THUDM/ChatGLM-6B/blob/main/cli_demo.py # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may ...
--- +++ @@ -37,6 +37,12 @@ class ChatModel: + r"""General class for chat models. Backed by huggingface or vllm engines. + + Supports both sync and async methods. + Sync methods: chat(), stream_chat() and get_scores(). + Async methods: achat(), astream_chat() and aget_scores(). + """ def __init...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/chat/chat_model.py
Add docstrings for utility scripts
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -32,6 +32,7 @@ def smooth(scalars: list[float]) -> list[float]: + r"""EMA implementation according to TensorBoard.""" if len(scalars) == 0: return [] @@ -46,6 +47,7 @@ def gen_loss_plot(trainer_log: list[dict[str, Any]]) -> "matplotlib.figure.Figure": + r"""Plot loss curves in L...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/extras/ploting.py
Write beginner-friendly docstrings
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -122,24 +122,32 @@ @dataclass class ToolUtils(ABC): + """Base class for tool utilities.""" @staticmethod @abstractmethod def tool_formatter(tools: list[dict[str, Any]]) -> str: + r"""Generate the system message describing all the available tools.""" ... @staticme...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/data/tool_utils.py
Add docstrings for production code
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -54,6 +54,7 @@ data_args: "DataArguments", training_args: "Seq2SeqTrainingArguments", ) -> Union["Dataset", "IterableDataset"]: + r"""Load a single dataset and aligns it to the standard format.""" logger.info_rank0(f"Loading dataset {dataset_attr}...") data_path, data_name, data_dir, d...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/data/loader.py
Add docstrings to improve readability
# Copyright 2025 the KVCache.AI team, Approaching AI, and the LlamaFactory team. # # 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 ...
--- +++ @@ -67,6 +67,7 @@ def load_kt_pretrained_model(config: "PretrainedConfig", model_args: "ModelArguments") -> "PreTrainedModel": + r"""Optionally load pretrained model with KTransformers. Used in training.""" custom_models = { "DeepseekV2ForCausalLM": DeepseekV2ForCausalLM, "Deepseek...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/model/model_utils/ktransformers.py
Write docstrings for utility functions
# Copyright 2025 HuggingFace Inc. and the LlamaFactory team. # # This code is inspired by the HuggingFace's PEFT library. # https://github.com/huggingface/peft/blob/v0.10.0/src/peft/peft_model.py # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with th...
--- +++ @@ -55,6 +55,7 @@ class AverageMeter: + r"""Compute and store the average and current value.""" def __init__(self): self.reset() @@ -73,6 +74,7 @@ def check_version(requirement: str, mandatory: bool = False) -> None: + r"""Optionally check the package version.""" if is_env_ena...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/extras/misc.py
Add docstrings to clarify complex logic
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -41,6 +41,7 @@ data_args: "DataArguments" def _find_medias(self, medias: Union["MediaType", list["MediaType"], None]) -> list["MediaType"] | None: + r"""Optionally concatenate media path to media dir when loading from local disk.""" if medias is None: return None ...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/data/converter.py
Write reusable docstrings
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -51,6 +51,7 @@ def load_unsloth_pretrained_model( config: "PretrainedConfig", model_args: "ModelArguments", finetuning_args: "FinetuningArguments" ) -> Optional["PreTrainedModel"]: + r"""Optionally load pretrained model with unsloth. Used in training.""" from unsloth import FastLanguageModel #...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/model/model_utils/unsloth.py
Add docstrings to incomplete code
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -18,6 +18,7 @@ @dataclass class FreezeArguments: + r"""Arguments pertaining to the freeze (partial-parameter) training.""" freeze_trainable_layers: int = field( default=2, @@ -53,6 +54,7 @@ @dataclass class LoraArguments: + r"""Arguments pertaining to the LoRA training.""" ...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/hparams/finetuning_args.py
Provide clean and structured docstrings
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -44,6 +44,16 @@ class SGLangEngine(BaseEngine): + """Inference engine for SGLang models. + + This class wraps the SGLang engine to provide a consistent interface for text generation + that matches LLaMA Factory's requirements. It uses the SGLang HTTP server approach for + better interaction a...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/chat/sglang_engine.py
Improve documentation using docstrings
# Copyright 2025 HuggingFace Inc. and the LlamaFactory team. # # This code is inspired by the HuggingFace's transformers library. # https://github.com/huggingface/transformers/blob/v4.40.0/examples/pytorch/language-modeling/run_clm.py # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use...
--- +++ @@ -67,6 +67,7 @@ def read_args(args: dict[str, Any] | list[str] | None = None) -> dict[str, Any] | list[str]: + r"""Get arguments from the command line or a config file.""" if args is not None: return args @@ -100,6 +101,11 @@ def _verify_trackio_args(training_args: "TrainingArgument...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/hparams/parser.py
Write docstrings for data processing functions
# Copyright 2025 OpenAccess AI Collective and the LlamaFactory team. # # This code is inspired by the OpenAccess AI Collective's axolotl library. # https://github.com/OpenAccess-AI-Collective/axolotl/blob/main/src/axolotl/monkeypatch/utils.py # # Licensed under the Apache License, Version 2.0 (the "License"); # you may...
--- +++ @@ -40,6 +40,31 @@ def prepare_4d_attention_mask(attention_mask_with_indices: "torch.Tensor", dtype: "torch.dtype") -> "torch.Tensor": + r"""Expand 2d attention mask to 4d attention mask. + + Expand the attention mask with indices from (batch_size, seq_len) to (batch_size, 1, seq_len, seq_len), + h...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/data/collator.py
Document all public functions with docstrings
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -30,9 +30,14 @@ @abstractmethod def apply(self, **kwargs) -> SLOTS: + r"""Forms a list of slots according to the inputs to encode.""" ... def extract(self, content: str) -> str | list["FunctionCall"]: + r"""Extract a list of tuples from the response message if using t...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/data/formatter.py
Add docstrings for better understanding
# Copyright 2025 HuggingFace Inc., Daniel Han-Chen & the Unsloth team and the LlamaFactory team. # # This code is inspired by the HuggingFace's Transformers and PEFT library, # https://github.com/huggingface/transformers/blob/v4.40.0/src/transformers/modeling_utils.py # https://github.com/huggingface/peft/blob/v0.10.0/...
--- +++ @@ -42,6 +42,7 @@ def get_unsloth_gradient_checkpointing_func() -> Callable: class UnslothGradientCheckpointing(torch.autograd.Function): + r"""Saves VRAM by smartly offloading to RAM.""" @staticmethod @torch.cuda.amp.custom_fwd @@ -77,6 +78,7 @@ def get_custom_gradient_che...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/model/model_utils/checkpointing.py
Write docstrings describing each step
# Copyright 2025 HuggingFace Inc. and the LlamaFactory team. # # This code is inspired by the HuggingFace's TRL library. # https://github.com/huggingface/trl/blob/v0.8.0/trl/trainer/dpo_trainer.py # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with t...
--- +++ @@ -144,9 +144,11 @@ @override def get_batch_samples(self, *args, **kwargs): + r"""Replace the method of DPO Trainer with the one of the standard Trainer.""" return Trainer.get_batch_samples(self, *args, **kwargs) def odds_ratio_loss(self, chosen_logps: "torch.Tensor", rejected...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/train/dpo/trainer.py
Add docstrings with type hints explained
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -12,6 +12,26 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""The definition of data engine. + +How to use: +data_engine = DataEngine(data_args.train_dataset) +data_engine[i]: Get the sample via index. + +Init workflow: +1. Parse dataset info fr...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/core/data_engine.py
Add detailed docstrings explaining each function
# Copyright 2025 HuggingFace Inc. and the LlamaFactory team. # # This code is inspired by the original GaLore's implementation: https://github.com/jiaweizzhao/GaLore # and the original LoRA+'s implementation: https://github.com/nikhil-ghosh-berkeley/loraplus # and the original BAdam's implementation: https://github.com...
--- +++ @@ -66,6 +66,7 @@ class DummyOptimizer(torch.optim.Optimizer): + r"""A dummy optimizer used for the GaLore or APOLLO algorithm.""" def __init__( self, lr: float = 1e-3, optimizer_dict: Optional[dict["torch.nn.Parameter", "torch.optim.Optimizer"]] = None @@ -115,6 +116,10 @@ def create_ref...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/train/trainer_utils.py
Insert docstrings into my code
# Copyright 2025 HuggingFace Inc. and the LlamaFactory team. # # This code is inspired by the HuggingFace's TRL library. # https://github.com/huggingface/trl/blob/v0.8.0/trl/trainer/ppo_trainer.py # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with t...
--- +++ @@ -62,6 +62,7 @@ class CustomPPOTrainer(PPOTrainer, Trainer): + r"""Inherit PPOTrainer.""" def __init__( self, @@ -197,6 +198,7 @@ self.add_callback(BAdamCallback) def ppo_train(self, resume_from_checkpoint: Optional[str] = None) -> None: + r"""Implement trainin...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/train/ppo/trainer.py
Generate missing documentation strings
# Copyright 2025 HuggingFace Inc. and the LlamaFactory team. # # This code is inspired by the HuggingFace's transformers library. # https://github.com/huggingface/transformers/blob/v4.40.0/src/transformers/trainer_seq2seq.py # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file...
--- +++ @@ -45,6 +45,7 @@ class CustomSeq2SeqTrainer(Seq2SeqTrainer): + r"""Inherits Seq2SeqTrainer to compute generative metrics such as BLEU and ROUGE.""" def __init__( self, @@ -169,6 +170,10 @@ ignore_keys: Optional[list[str]] = None, **gen_kwargs, ) -> tuple[Optional[fl...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/train/sft/trainer.py
Create docstrings for all classes and functions
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -29,6 +29,7 @@ temp_str: str, temp_weight: float, ) -> str: + """Update model input with temporary string.""" if not temp_str: return "" @@ -45,6 +46,7 @@ def _concat_text_content(message: Message) -> str: + """Concatenate text fields in a message.""" message_text = "...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/plugins/model_plugins/templates/qwen3_nothink.py
Document functions with clear intent
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -57,6 +57,7 @@ class DataConverterPlugin(BasePlugin): + """Plugin for data converters.""" def __call__(self, raw_sample: dict[str, Any]) -> Sample: return super().__call__(raw_sample) @@ -64,6 +65,16 @@ @DataConverterPlugin("alpaca").register() def alpaca_converter(raw_sample: Alpac...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/plugins/data_plugins/converter.py
Generate documentation strings for clarity
# Copyright 2025 HuggingFace Inc. and the LlamaFactory team. # # This code is inspired by the HuggingFace's transformers library. # https://github.com/huggingface/transformers/blob/v5.0.0rc0/src/transformers/training_args.py # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file...
--- +++ @@ -21,9 +21,11 @@ class PluginConfig(dict): + """Dictionary that allows attribute access.""" @property def name(self) -> str: + """Plugin name.""" if "name" not in self: raise ValueError("Plugin configuration must have a 'name' field.") @@ -35,6 +37,7 @@ @uni...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/config/arg_utils.py
Generate consistent documentation across files
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -24,6 +24,7 @@ class DataLoaderPlugin(BasePlugin): + """Plugin for loading dataset.""" def load(self, dataset_info: DatasetInfo) -> HFDataset: path = dataset_info["path"] @@ -33,6 +34,14 @@ def _get_builder_name(path: str) -> Literal["arrow", "csv", "json", "parquet", "text"]: + ...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/plugins/data_plugins/loader.py
Document all public functions with docstrings
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -78,6 +78,7 @@ def _find_all_linear_modules(model: HFModel) -> list[str]: + r"""Find all available modules to apply LoRA.""" forbidden_modules = {"lm_head", "output_layer", "output"} module_names = set() for name, module in model.named_modules(): @@ -103,6 +104,13 @@ def load_adapte...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/plugins/model_plugins/peft.py
Add docstrings explaining edge cases
# Copyright 2025 HuggingFace Inc. and the LlamaFactory team. # # This code is inspired by the HuggingFace's TRL library. # https://github.com/huggingface/trl/blob/v0.8.0/trl/trainer/kto_trainer.py # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with t...
--- +++ @@ -134,6 +134,7 @@ @override def _get_train_sampler(self, *args, **kwargs) -> Optional["torch.utils.data.Sampler"]: + r"""Replace the sequential sampler of KTO Trainer created by trl with the random sampler.""" if self.finetuning_args.disable_shuffling: return torch.util...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/train/kto/trainer.py
Add docstrings to clarify complex logic
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -12,6 +12,13 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""The definition of NPU fused SwiGLU kernels. + +Init Phase: +1. Define SwiGLU forward functions. +2. Register NPU fused SwiGLU kernel. + +""" import re import types @@ -31,18 +38,4...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/plugins/model_plugins/kernels/ops/mlp/npu_swiglu.py
Create simple docstrings for beginners
# Copyright 2025 Bytedance Ltd. and the LlamaFactory team. # # This code is inspired by the Bytedance's VeOmni library. # https://github.com/ByteDance-Seed/VeOmni/blob/v0.1.4/veomni/utils/dist_utils.py # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance w...
--- +++ @@ -15,6 +15,14 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Utility functions used by the distributed interface. + +Including: +- Environment info (rank, world_size, local_rank, etc.) +- Accelerator info (device type, device count, etc.) +- Co...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/accelerator/helper.py
Fully document this Python code with docstrings
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -12,6 +12,22 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""The definition of model engine. + +How to use: +model_engine = ModelEngine(model_args, is_train=True) +model_engine.processor: Get the tokenizer or multi-modal processor. +model_engin...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/core/model_engine.py
Add docstrings following best practices
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -32,6 +32,7 @@ def get_rewards_from_server(server_url: str, messages: list[str]) -> list["torch.Tensor"]: + r"""Get reward scores from the API server.""" headers = {"Content-Type": "application/json"} payload = {"model": "model", "messages": messages} response = requests.post(server_url...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/train/ppo/ppo_utils.py
Add clean documentation to messy code
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -27,6 +27,14 @@ def create_fp8_kwargs(training_args: "TrainingArguments") -> list[Any]: + """Create AORecipeKwargs for FP8 training with HuggingFace Accelerate. + + Args: + training_args: Training arguments containing FP8 configuration + + Returns: + List containing AORecipeKwargs ...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/train/fp8_utils.py
Create docstrings for all classes and functions
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -12,6 +12,14 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""The definition of kernel interface. + +Init Phase: +1. Scan all kernels. +2. Register default kernels. +3. Define kernel plugin. + +""" import importlib from pathlib import Path @...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/plugins/model_plugins/kernels/interface.py
Write docstrings that follow conventions
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -37,14 +37,39 @@ model: HFModel, renderer: Renderer, ) -> None: + """Initialize the engine. + + Args: + args: Sample arguments. + model_args: Model arguments. + model: Model. + renderer: Renderer. + """ ... ...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/core/utils/inference_engine.py
Improve my code by adding docstrings
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -12,6 +12,14 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Rendering utils. + +How to use: +renderer = Renderer(template, processor) +renderer.render_messages(messages: list[Message], tools: str | None) -> ModelInputs +renderer.parse_message(...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/core/utils/rendering.py
Write docstrings for data processing functions
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -48,7 +48,9 @@ is_generate: bool = False, enable_thinking: bool = False, ) -> ModelInput: + """Render messages in the template format.""" return self["render_messages"](processor, messages, tools, is_generate, enable_thinking) def parse_messages(self, generated_te...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/plugins/model_plugins/rendering.py
Provide clean and structured docstrings
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -21,6 +21,14 @@ class BaseSampler: + """Base sampler. + + Args: + args: Sample arguments. + model_args: Model arguments. + model: Model. + renderer: Renderer. + """ def __init__( self, @@ -35,8 +43,25 @@ raise ValueError(f"Unknown sample ba...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/core/base_sampler.py
Provide docstrings following PEP 257
# Copyright 2025 Bytedance Ltd. and the LlamaFactory team. # # This code is inspired by the Bytedance's VeOmni library. # https://github.com/ByteDance-Seed/VeOmni/blob/v0.1.4/veomni/distributed/parallel_state.py # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in co...
--- +++ @@ -15,6 +15,16 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""A unified interface for model parallelism and data parallelism. + +Supports model parallelism types: +- mp_replicate: Replicate model across multiple devices. +- mp_shard: Shard model...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/accelerator/interface.py
Add concise docstrings to each method
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -12,6 +12,13 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""The definition of base kernel class. + +Init Phase: +1. Define base kernel class. +2. Define abstract methods. + +""" from abc import ABC, abstractmethod from typing import Any @@...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/plugins/model_plugins/kernels/base.py
Fill in missing docstrings in my code
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -12,6 +12,20 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""The definition of trainer. + +Init Phase: + +1. Init batch generator. +2. Init optimizer (deepspeed). +3. Shard model. +4. Init optimizer (fsdp). +5. Init lr scheduler. + +Train Phase...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/core/base_trainer.py
Add inline docstrings for readability
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -12,6 +12,14 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""The definition of NPU fused MoE kernels. + +Init Phase: +1. Define GMM functions. +2. Define NPU fused MoE functions. +3. Register NPU fused MoE kernel. + +""" import types @@ -3...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/plugins/model_plugins/kernels/ops/mlp/npu_fused_moe.py
Add concise docstrings to each method
# Copyright 2025 HuggingFace Inc., THUDM, and the LlamaFactory team. # # This code is inspired by the HuggingFace's transformers library and the THUDM's ChatGLM implementation. # https://github.com/huggingface/transformers/blob/v4.40.0/examples/pytorch/summarization/run_summarization.py # https://github.com/THUDM/ChatG...
--- +++ @@ -45,6 +45,7 @@ def eval_logit_processor(logits: "torch.Tensor", labels: "torch.Tensor") -> "torch.Tensor": + r"""Compute the token with the largest likelihood to reduce memory footprint.""" if isinstance(logits, (list, tuple)): if logits[0].dim() == 3: # (batch_size, seq_len, vocab_size...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/train/sft/metric.py
Write docstrings including parameters and return values
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -29,6 +29,7 @@ temp_str: str, temp_weight: float, ) -> str: + """Update model input with temporary string.""" if not temp_str: return "" @@ -45,6 +46,7 @@ def _concat_text_content(message: Message) -> str: + """Concatenate text fields in a message.""" message_text = "...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/plugins/model_plugins/templates/qwen3.py
Add docstrings for better understanding
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -12,6 +12,13 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""The definition of NPU fused RoPE kernels. + +Init Phase: +1. Define RoPE forward functions. +2. Register NPU fused RoPE kernel. + +""" import sys @@ -33,6 +40,19 @@ def _appl...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/plugins/model_plugins/kernels/ops/rope/npu_rope.py
Generate consistent docstrings
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -24,13 +24,40 @@ class BasePlugin: + """Base class for plugins. + + A plugin is a callable object that can be registered and called by name. + + Example usage: + ```python + class PrintPlugin(BasePlugin): + def again(self): # optional + self["again"]() + + + @PrintPlu...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/utils/plugin.py
Add verbose docstrings with examples
# Copyright 2025 HuggingFace Inc. and the LlamaFactory team. # # This code is inspired by the HuggingFace's transformers library. # https://github.com/huggingface/transformers/blob/v4.40.0/src/transformers/trainer.py # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except ...
--- +++ @@ -41,6 +41,7 @@ class PairwiseTrainer(Trainer): + r"""Inherits Trainer to compute pairwise loss.""" def __init__( self, finetuning_args: "FinetuningArguments", processor: Optional["ProcessorMixin"], **kwargs @@ -87,6 +88,13 @@ def compute_loss( self, model: "PreTrainedModel...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/train/rm/trainer.py
Write docstrings describing functionality
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -19,10 +19,16 @@ class BatchingPlugin(BasePlugin): def compute_length(self, data_provider: DataLoader) -> int: + """Compute the length of the batch generator. + + The approximate length is used to calculate the lr schedule. + """ raise NotImplementedError() def fil...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/plugins/trainer_plugins/batching.py
Document this module using docstrings
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -12,6 +12,12 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""DeepSpeed integration via accelerate's built-in capabilities. + +Instead of manually calling deepspeed.initialize() and syncing config, +this module leverages accelerate's Accelerator...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/plugins/trainer_plugins/distributed/deepspeed.py
Write reusable docstrings
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -12,6 +12,13 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""The definition of NPU fused RMSNorm kernels. + +Init Phase: +1. Define RMSNorm forward function. +2. Register NPU fused RMSNorm kernel. + +""" import re import types @@ -23,6 +30,...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/plugins/model_plugins/kernels/ops/rms_norm/npu_rms_norm.py
Write clean docstrings for readability
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -214,6 +214,7 @@ return model def _save_non_persistent_buffers(self, model: HFModel) -> dict: + """Save non-persistent buffers, such as inv_freq.""" saved = {} for mod_name, module in model.named_modules(): for buf_name in module._non_persistent_buffers_se...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/plugins/trainer_plugins/distributed/fsdp2.py
Add docstrings that explain inputs and outputs
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -12,6 +12,13 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""The definition of kernel registry. + +Init Phase: +1. Define kernel registry. +2. Register kernels. + +""" from ....accelerator.helper import get_current_accelerator from .base im...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/plugins/model_plugins/kernels/registry.py
Write docstrings including parameters and return values
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -43,6 +43,15 @@ self._thread.start() def generate(self, messages: list[Message], tools: str | None = None) -> Generator[str, None, None]: + """Generate tokens synchronously. + + Args: + messages: List of messages. + tools: Tools string. + + Yields: + ...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/samplers/cli_sampler.py
Write proper docstrings for these functions
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -23,14 +23,35 @@ def set_seed(seed: int) -> None: + """Set seed for reproducibility. + + Args: + seed: Random seed. + """ hf_set_seed(seed) def is_tokenizer(processor: Processor) -> bool: + """Check if processor is tokenizer. + + Args: + processor: Processor. + + ...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/utils/helper.py
Add docstrings including usage examples
# Copyright 2025 Optuna, HuggingFace Inc. and the LlamaFactory team. # # This code is inspired by the HuggingFace's transformers library. # https://github.com/huggingface/transformers/blob/v5.0.0rc0/src/transformers/utils/logging.py # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use t...
--- +++ @@ -29,6 +29,7 @@ class _Logger(logging.Logger): + """A logger that supports rank0 logging.""" def info_rank0(self, *args, **kwargs) -> None: self.info(*args, **kwargs) @@ -41,6 +42,7 @@ def _get_default_logging_level() -> "logging._Level": + """Return the default logging level."""...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/utils/logging.py
Add docstrings to my Python code
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -39,11 +39,20 @@ def switch_hub(hub_name: str) -> None: + r"""Switch model hub. + + Inputs: top.hub_name + """ os.environ["USE_MODELSCOPE_HUB"] = "1" if hub_name == "modelscope" else "0" os.environ["USE_OPENMIND_HUB"] = "1" if hub_name == "openmind" else "0" def can_quantize(finet...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/webui/control.py
Document my Python code with docstrings
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -17,6 +17,7 @@ def find_available_port() -> int: + """Find an available port on the local machine.""" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(("", 0)) port = sock.getsockname()[1] @@ -25,6 +26,7 @@ def is_env_enabled(env_var: str, default: str = "0") -> bo...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/utils/env.py
Insert docstrings into my code
# Copyright 2025 Optuna, HuggingFace Inc. and the LlamaFactory team. # # This code is inspired by the HuggingFace's transformers library. # https://github.com/huggingface/transformers/blob/v5.0.0rc0/src/transformers/utils/logging.py # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use t...
--- +++ @@ -19,6 +19,7 @@ class StatefulBuffer: + """A buffer that stores model inputs.""" def __init__(self, max_buffer_size: int = 1_000_000_000) -> None: self._buffer: list[ModelInput] = [] @@ -33,6 +34,7 @@ return self._buffer_size def put(self, samples: list[ModelInput]) -> No...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/v1/utils/objects.py
Add inline docstrings for readability
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -39,10 +39,15 @@ def _escape_html(text: str) -> str: + r"""Escape HTML characters.""" return text.replace("<", "&lt;").replace(">", "&gt;") def _format_response(text: str, lang: str, escape_html: bool, thought_words: tuple[str, str]) -> str: + r"""Post-process the response text. + + Ba...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/webui/chatter.py
Create docstrings for API functions
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -44,6 +44,7 @@ def abort_process(pid: int) -> None: + r"""Abort the processes recursively in a bottom-up way.""" try: children = Process(pid).children() if children: @@ -56,6 +57,7 @@ def get_save_dir(*paths: str) -> os.PathLike: + r"""Get the path to saved model checkpoi...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/webui/common.py
Generate documentation strings for clarity
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -26,6 +26,7 @@ class Engine: + r"""A general engine to control the behaviors of Web UI.""" def __init__(self, demo_mode: bool = False, pure_chat: bool = False) -> None: self.demo_mode = demo_mode @@ -37,6 +38,7 @@ create_ds_config() def _update_component(self, input_...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/webui/engine.py
Add return value explanations in docstrings
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -40,6 +40,7 @@ def can_preview(dataset_dir: str, dataset: list) -> "gr.Button": + r"""Check if the dataset is a local dataset.""" try: with open(os.path.join(dataset_dir, DATA_CONFIG), encoding="utf-8") as f: dataset_info = json.load(f) @@ -67,6 +68,7 @@ def get_preview(...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/webui/components/data.py
Add docstrings for production code
from __future__ import annotations import os import shutil import string from importlib import import_module from pathlib import Path from typing import TYPE_CHECKING, Any, cast from urllib.parse import urlparse import scrapy from scrapy.commands import ScrapyCommand from scrapy.exceptions import UsageError from scra...
--- +++ @@ -19,6 +19,10 @@ def sanitize_module_name(module_name: str) -> str: + """Sanitize the given module name, by replacing dashes and points + with underscores and prefixing it with a letter if it doesn't start + with one + """ module_name = module_name.replace("-", "_").replace(".", "_") ...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/commands/genspider.py
Add verbose docstrings with examples
from __future__ import annotations import argparse import builtins import os from abc import ABC, abstractmethod from pathlib import Path from typing import TYPE_CHECKING, Any from twisted.python import failure from scrapy.exceptions import UsageError from scrapy.utils.conf import arglist_to_dict, feed_process_para...
--- +++ @@ -1,3 +1,6 @@+""" +Base class for Scrapy commands +""" from __future__ import annotations @@ -39,19 +42,36 @@ self._crawler: Crawler = crawler def syntax(self) -> str: + """ + Command syntax (preferably one-line). Do not include command name. + """ return "" ...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/commands/__init__.py
Document this script properly
from __future__ import annotations import logging from typing import TYPE_CHECKING, Any from scrapy.exceptions import NotConfigured from scrapy.utils.conf import build_component_list from scrapy.utils.misc import build_from_crawler, load_object if TYPE_CHECKING: from scrapy.crawler import Crawler from scrapy...
--- +++ @@ -16,12 +16,22 @@ class AddonManager: + """This class facilitates loading and storing :ref:`topics-addons`.""" def __init__(self, crawler: Crawler) -> None: self.crawler: Crawler = crawler self.addons: list[Any] = [] def load_settings(self, settings: Settings) -> None: +...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/addons.py
Add docstrings to incomplete code
from __future__ import annotations import logging import re from typing import TYPE_CHECKING from warnings import warn from w3lib import html from scrapy.exceptions import NotConfigured, ScrapyDeprecationWarning from scrapy.http import HtmlResponse, Response from scrapy.utils.url import escape_ajax if TYPE_CHECKING...
--- +++ @@ -24,6 +24,9 @@ class AjaxCrawlMiddleware: + """ + Handle 'AJAX crawlable' pages marked as crawlable via meta tag. + """ def __init__(self, settings: BaseSettings): if not settings.getbool("AJAXCRAWL_ENABLED"): @@ -73,6 +76,9 @@ return ajax_crawl_request def _has_aj...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/downloadermiddlewares/ajaxcrawl.py
Include argument descriptions in docstrings
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -52,8 +52,10 @@ class Runner: + r"""A class to manage the running status of the trainers.""" def __init__(self, manager: "Manager", demo_mode: bool = False) -> None: + r"""Init a runner.""" self.manager = manager self.demo_mode = demo_mode """ Resume """ @@ -70...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/webui/runner.py
Write clean docstrings for readability
from __future__ import annotations import ipaddress import itertools import logging from collections import deque from typing import TYPE_CHECKING, Any, cast from h2.config import H2Configuration from h2.connection import H2Connection from h2.errors import ErrorCodes from h2.events import ( ConnectionTerminated, ...
--- +++ @@ -93,6 +93,15 @@ settings: Settings, conn_lost_deferred: Deferred[list[BaseException]], ) -> None: + """ + Arguments: + uri -- URI of the base url to which HTTP/2 Connection will be made. + uri is used to verify that incoming client requests have c...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/core/http2/protocol.py
Create Google-style docstrings for my code
from __future__ import annotations import logging from enum import Enum from io import BytesIO from typing import TYPE_CHECKING, Any from h2.errors import ErrorCodes from h2.exceptions import H2Error, ProtocolError, StreamClosedError from twisted.internet.defer import Deferred from twisted.internet.error import Conne...
--- +++ @@ -32,6 +32,9 @@ class InactiveStreamClosed(ConnectionClosed): + """Connection was closed without sending request headers + of the stream. This happens when a stream is waiting for other + streams to close and connection is lost.""" def __init__(self, request: Request) -> None: sel...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/core/http2/stream.py
Add inline docstrings for readability
from __future__ import annotations import warnings from time import time from typing import TYPE_CHECKING from urllib.parse import urldefrag, urlparse, urlunparse from twisted.internet import defer from twisted.internet.protocol import ClientFactory from twisted.web.http import HTTPClient from scrapy.exceptions imp...
--- +++ @@ -1,3 +1,4 @@+"""Deprecated HTTP/1.0 helper classes used by HTTP10DownloadHandler.""" from __future__ import annotations @@ -202,6 +203,16 @@ self.response_headers = headers def gotStatus(self, version, status, message): + """ + Set the status of the request on us. + @...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/core/downloader/webclient.py
Generate docstrings for script automation
from __future__ import annotations import ipaddress import logging import ssl from http.cookiejar import Cookie, CookieJar from io import BytesIO from typing import TYPE_CHECKING, Any, NoReturn, TypedDict import httpx from scrapy import Request, signals from scrapy.exceptions import ( CannotResolveHostError, ...
--- +++ @@ -1,3 +1,4 @@+"""``httpx``-based HTTP(S) download handler. Currently not recommended for production use.""" from __future__ import annotations @@ -57,6 +58,7 @@ # workaround for (and from) https://github.com/encode/httpx/issues/2992 class _NullCookieJar(CookieJar): # pragma: no cover + """A Cookie...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/core/downloader/handlers/_httpx.py
Create simple docstrings for beginners
from __future__ import annotations import inspect import logging import warnings from typing import TYPE_CHECKING, Any, Protocol, cast from scrapy import Request, Spider, signals from scrapy.exceptions import NotConfigured, NotSupported, ScrapyDeprecationWarning from scrapy.utils.defer import ( deferred_from_cor...
--- +++ @@ -1,3 +1,4 @@+"""Download handlers for different schemes""" from __future__ import annotations @@ -69,6 +70,9 @@ crawler.signals.connect(self._close, signals.engine_stopped) def _get_handler(self, scheme: str) -> DownloadHandlerProtocol | None: + """Lazy-load the downloadhandler for...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/core/downloader/handlers/__init__.py
Please document this code using docstrings
from __future__ import annotations import asyncio import logging import warnings from time import time from traceback import format_exc from typing import TYPE_CHECKING, Any from twisted.internet.defer import CancelledError, Deferred, inlineCallbacks from twisted.python.failure import Failure from scrapy import sig...
--- +++ @@ -1,3 +1,9 @@+""" +This is the Scrapy engine which controls the Scheduler, Downloader and Spider. + +For more information see docs/topics/architecture.rst + +""" from __future__ import annotations @@ -166,6 +172,10 @@ ) async def start_async(self, *, _start_request_processing: bool = True)...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/core/engine.py
Add docstrings to improve code quality
from __future__ import annotations import ipaddress import logging import re from contextlib import suppress from io import BytesIO from time import time from typing import TYPE_CHECKING, Any, TypedDict, TypeVar, cast from urllib.parse import urldefrag, urlparse from twisted.internet import ssl from twisted.internet...
--- +++ @@ -1,3 +1,4 @@+"""Download handlers for http and https schemes""" from __future__ import annotations @@ -95,6 +96,7 @@ self._disconnect_timeout: int = 1 async def download_request(self, request: Request) -> Response: + """Return a deferred for the HTTP download""" if hasattr...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/core/downloader/handlers/http11.py
Write docstrings including parameters and return values
from __future__ import annotations from collections import deque from typing import TYPE_CHECKING from twisted.internet import defer from twisted.internet.defer import Deferred from twisted.python.failure import Failure from twisted.web.client import ( URI, BrowserLikePolicyForHTTPS, ResponseFailed, _...
--- +++ @@ -105,6 +105,11 @@ d.errback(ResponseFailed(errors)) def close_connections(self) -> None: + """Close all the HTTP/2 connections and remove them from pool + + Returns: + Deferred that fires when all connections have been closed + """ for conn in self....
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/core/http2/agent.py
Generate consistent docstrings
from __future__ import annotations import warnings from typing import TYPE_CHECKING, Any from OpenSSL import SSL from twisted.internet._sslverify import _setAcceptableProtocols from twisted.internet.ssl import ( AcceptableCiphers, CertificateOptions, optionsForClientTLS, platformTrust, ) from twisted....
--- +++ @@ -37,6 +37,15 @@ @implementer(IPolicyForHTTPS) class ScrapyClientContextFactory(BrowserLikePolicyForHTTPS): + """ + Non-peer-certificate verifying HTTPS context factory + + Default OpenSSL method is TLS_METHOD (also called SSLv23_METHOD) + which allows TLS protocol negotiation + + 'A TLS/SSL...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/core/downloader/contextfactory.py
Add docstrings to my Python code
from __future__ import annotations import logging import warnings from collections import deque from collections.abc import AsyncIterator from typing import TYPE_CHECKING, Any, TypeAlias, TypeVar from twisted.internet.defer import Deferred, inlineCallbacks from twisted.python.failure import Failure from scrapy impo...
--- +++ @@ -1,3 +1,5 @@+"""This module implements the Scraper component which parses responses and +extracts information from them""" from __future__ import annotations @@ -55,6 +57,7 @@ class Slot: + """Scraper slot (one per running spider)""" MIN_RESPONSE_SIZE = 1024 @@ -159,6 +162,10 @@ ...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/core/scraper.py
Create documentation strings for testing functions
from __future__ import annotations import asyncio import contextlib import logging import pprint import signal import warnings from abc import ABC, abstractmethod from typing import TYPE_CHECKING, Any, TypeVar from twisted.internet.defer import Deferred, DeferredList, inlineCallbacks from scrapy import Spider from s...
--- +++ @@ -136,6 +136,12 @@ ) def _apply_reactorless_default_settings(self) -> None: + """Change some setting defaults when not using a Twisted reactor. + + Some settings need different defaults when using and not using a + reactor, but as we can't put this logic into default_settin...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/crawler.py
Add docstrings to improve readability
# Copyright 2025 the LlamaFactory team. # # 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 i...
--- +++ @@ -21,31 +21,41 @@ class Manager: + r"""A class to manage all the gradio components in Web UI.""" def __init__(self) -> None: self._id_to_elem: dict[str, Component] = {} self._elem_to_id: dict[Component, str] = {} def add_elems(self, tab_name: str, elem_dict: dict[str, "C...
https://raw.githubusercontent.com/hiyouga/LlamaFactory/HEAD/src/llamafactory/webui/manager.py
Document functions with detailed explanations
from __future__ import annotations import json from typing import TYPE_CHECKING, Any from itemadapter import ItemAdapter, is_item from scrapy.contracts import Contract from scrapy.exceptions import ContractFail from scrapy.http import Request if TYPE_CHECKING: from collections.abc import Callable # contracts ...
--- +++ @@ -15,6 +15,9 @@ # contracts class UrlContract(Contract): + """Contract to set the url of the request (mandatory) + @url http://scrapy.org + """ name = "url" @@ -24,6 +27,11 @@ class CallbackKeywordArgumentsContract(Contract): + """Contract to set the keyword arguments for the reque...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/contracts/default.py
Create docstrings for all classes and functions
from __future__ import annotations import csv import marshal import pickle import pprint from abc import ABC, abstractmethod from collections.abc import Callable, Iterable, Mapping from io import BytesIO, TextIOWrapper from typing import TYPE_CHECKING, Any from xml.sax.saxutils import XMLGenerator from xml.sax.xmlrea...
--- +++ @@ -1,3 +1,6 @@+""" +Item Exporters are used to export/serialize items into different formats. +""" from __future__ import annotations @@ -39,6 +42,10 @@ self._configure(kwargs, dont_fail=dont_fail) def _configure(self, options: dict[str, Any], dont_fail: bool = False) -> None: + """C...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/exporters.py
Add professional docstrings to my codebase
from __future__ import annotations import json import logging from abc import abstractmethod from pathlib import Path from typing import TYPE_CHECKING, Any from warnings import warn # working around https://github.com/sphinx-doc/sphinx/issues/10400 from twisted.internet.defer import Deferred # noqa: TC002 from scra...
--- +++ @@ -34,6 +34,9 @@ class BaseSchedulerMeta(type): + """ + Metaclass to check scheduler classes against the necessary interface + """ def __instancecheck__(cls, instance: Any) -> bool: return cls.__subclasscheck__(type(instance)) @@ -50,29 +53,205 @@ class BaseScheduler(metaclass=...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/core/scheduler.py
Generate docstrings for this script
from __future__ import annotations from threading import Thread from typing import TYPE_CHECKING, Any from scrapy.commands import ScrapyCommand from scrapy.http import Request from scrapy.shell import Shell from scrapy.utils.defer import _schedule_coro from scrapy.utils.spider import DefaultSpider, spidercls_for_req...
--- +++ @@ -1,3 +1,8 @@+""" +Scrapy Shell + +See documentation in docs/topics/shell.rst +""" from __future__ import annotations @@ -53,6 +58,9 @@ ) def update_vars(self, vars: dict[str, Any]) -> None: # noqa: A002 + """You can use this function to update the Scrapy objects that will be + ...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/commands/shell.py
Document classes and their methods
from __future__ import annotations import gzip import logging import pickle from email.utils import mktime_tz, parsedate_tz from importlib import import_module from pathlib import Path from time import time from typing import IO, TYPE_CHECKING, Any, Concatenate, cast from weakref import WeakKeyDictionary from w3lib.h...
--- +++ @@ -331,6 +331,7 @@ pass def retrieve_response(self, spider: Spider, request: Request) -> Response | None: + """Return response if present in cache, or None otherwise.""" metadata = self._read_meta(spider, request) if metadata is None: return None # not cach...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/extensions/httpcache.py
Add inline docstrings for readability
from __future__ import annotations import logging from collections import defaultdict from typing import TYPE_CHECKING, Any from tldextract import TLDExtract from scrapy.exceptions import NotConfigured from scrapy.http import Response from scrapy.http.cookies import CookieJar from scrapy.utils.decorators import _war...
--- +++ @@ -38,6 +38,7 @@ class CookiesMiddleware: + """This middleware enables working with sites that need cookies""" crawler: Crawler @@ -129,6 +130,10 @@ logger.debug(msg, extra={"spider": self.crawler.spider}) def _format_cookie(self, cookie: VerboseCookie, request: Request) ...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/downloadermiddlewares/cookies.py
Generate docstrings for script automation
from __future__ import annotations from typing import TYPE_CHECKING from w3lib.http import basic_auth_header from scrapy import Request, Spider, signals from scrapy.utils.decorators import _warn_spider_arg from scrapy.utils.url import url_is_from_any_domain if TYPE_CHECKING: # typing.Self requires Python 3.11 ...
--- +++ @@ -1,3 +1,8 @@+""" +HTTP basic auth downloader middleware + +See documentation in docs/topics/downloader-middleware.rst +""" from __future__ import annotations @@ -18,6 +23,8 @@ class HttpAuthMiddleware: + """Set Basic HTTP Authorization header + (http_user and http_pass spider class attributes)...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/downloadermiddlewares/httpauth.py
Generate NumPy-style docstrings
from __future__ import annotations from collections.abc import Mapping from typing import TYPE_CHECKING, Any, AnyStr, TypeAlias, cast from w3lib.http import headers_dict_to_raw from scrapy.utils.datatypes import CaseInsensitiveDict, CaselessDict from scrapy.utils.python import to_unicode if TYPE_CHECKING: from ...
--- +++ @@ -21,6 +21,7 @@ # isn't fully compatible typing-wise with either dict or CaselessDict, # but it needs refactoring anyway, see also https://github.com/scrapy/scrapy/pull/5146 class Headers(CaselessDict): + """Case insensitive http headers dictionary""" def __init__( self, @@ -40,9 +41,11 @...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/http/headers.py
Add docstrings for utility scripts
from __future__ import annotations import logging from pathlib import Path from typing import TYPE_CHECKING from warnings import warn from scrapy.exceptions import ScrapyDeprecationWarning from scrapy.utils.job import job_dir from scrapy.utils.request import ( RequestFingerprinter, RequestFingerprinterProtoco...
--- +++ @@ -25,6 +25,8 @@ class BaseDupeFilter: + """Dummy duplicate request filtering class (:setting:`DUPEFILTER_CLASS`) + that does not filter out any request.""" @classmethod def from_crawler(cls, crawler: Crawler) -> Self: @@ -40,6 +42,7 @@ pass def log(self, request: Request, ...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/dupefilters.py
Add docstrings for utility scripts
from __future__ import annotations from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from scrapy.http import Response # Internal class NotConfigured(Exception): class _InvalidOutput(TypeError): # HTTP and crawling class IgnoreRequest(Exception): class DontCloseSpider(Exception): class CloseSpi...
--- +++ @@ -1,3 +1,9 @@+""" +Scrapy core exceptions + +These exceptions are documented in docs/topics/exceptions.rst. Please don't add +new exceptions here without documenting them there. +""" from __future__ import annotations @@ -10,21 +16,29 @@ class NotConfigured(Exception): + """Indicates a missing con...
https://raw.githubusercontent.com/scrapy/scrapy/HEAD/scrapy/exceptions.py