instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Add inline docstrings for readability
# Copyright 2023-present the HuggingFace Inc. 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...
--- +++ @@ -27,6 +27,13 @@ @dataclass class LoraRuntimeConfig: + """ + This is the sub-configuration class to store the runtime configurations for the model. + + Args: + ephemeral_gpu_offload (`bool`): + Whether to use ephemeral GPU offloading for models partially kept in CPU memory. + ...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/lora/config.py
Add concise docstrings to each method
# Copyright 2025-present the HuggingFace Inc. 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...
--- +++ @@ -52,6 +52,18 @@ ) def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + ...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/road/bnb.py
Document classes and their methods
# Copyright 2023-present the HuggingFace Inc. 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...
--- +++ @@ -73,6 +73,18 @@ return DoraLinearVariant() def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *o...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/lora/bnb.py
Add clean documentation to messy code
# Copyright 2024-present the HuggingFace Inc. 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...
--- +++ @@ -65,6 +65,18 @@ return DoraLinearVariant() def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optio...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/lora/hqq.py
Write docstrings for data processing functions
# Copyright 2023-present the HuggingFace Inc. 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...
--- +++ @@ -68,6 +68,7 @@ ) def _register_pre_hooks(self, task_ids): + """Helper method to register pre hooks.""" if task_ids is None: return [] @@ -86,6 +87,7 @@ @contextmanager def _manage_pre_hooks(self, task_ids): + """Context manager to handle the...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/poly/model.py
Write docstrings that follow conventions
# Copyright 2023-present the HuggingFace Inc. 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...
--- +++ @@ -18,6 +18,40 @@ class PrefixEncoder(torch.nn.Module): + r""" + The `torch.nn` model to encode the prefix. + + Args: + config ([`PrefixTuningConfig`]): The configuration of the prefix encoder. + + Example: + + ```py + >>> from peft import PrefixEncoder, PrefixTuningConfig + + >...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/prefix_tuning/model.py
Add clean documentation to messy code
# Copyright 2025-present the HuggingFace Inc. 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...
--- +++ @@ -39,6 +39,18 @@ tensor_or_shape: Union[torch.Tensor, tuple[int, ...]], generator: torch.Generator, ) -> torch.Tensor: + """ + Kaiming Uniform Initialisation adapted to accept a `torch.Generator` object for PRNG. + + Args: + tensor_or_shape (`Union[torch.Tensor, tuple[int, ...]]`): +...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/randlora/model.py
Help me document legacy Python code
# Copyright 2024-present the HuggingFace Inc. 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...
--- +++ @@ -38,6 +38,10 @@ def target_modules(model: nn.Module, config: LoraConfig) -> Iterable[nn.Module]: + """ + Iterate over CorDA target name and modules of a model. A module is a target if its name is in + `config.target_modules` and is `nn.Linear` or `Conv1D`. + """ for name, module in model...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/lora/corda.py
Write docstrings describing functionality
# Copyright 2023-present the HuggingFace Inc. 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...
--- +++ @@ -33,6 +33,23 @@ class ArrowLinearVariant(LoraVariant): @staticmethod def init(module: Linear, adapter_name: str, config: LoraConfig, **kwargs): + """ + Initialise the ArrowLoraLinearLayer() inside lora_arrow. lora_arrow is nn.ModuleDict(), serving as a container + for ArrowLora...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/lora/variants.py
Help me write clear docstrings
# Copyright 2025-present the HuggingFace Inc. 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...
--- +++ @@ -49,6 +49,7 @@ def _convert_module_to_lora( module: BaseTunerLayer, rank: int | float, adapter_name: str = "default" ) -> tuple[torch.Tensor, torch.Tensor, int]: + """Convert a single BaseTunerLayer's adapter weight to a LoRA weight, return A, B, and the effective rank.""" delta_weight = module...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/lora/conversion.py
Add clean documentation to messy code
# Copyright 2024-present the HuggingFace Inc. 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...
--- +++ @@ -64,6 +64,18 @@ ) def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + ...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/oft/hqq.py
Write docstrings for this repository
# Copyright 2023-present the HuggingFace Inc. 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...
--- +++ @@ -19,12 +19,30 @@ def llama_rotate_half(x: torch.Tensor) -> torch.Tensor: + """ + Rotate half the hidden dims of the input. + + This function was duplicated verbatim from: + https://github.com/huggingface/transformers/blob/1de8ce9ee1191ba761a593ac15d9ccbf5851bfc5/src/transformers/models/llama/...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/adaption_prompt/utils.py
Create docstrings for all classes and functions
# Copyright 2025-present the HuggingFace Inc. 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...
--- +++ @@ -12,6 +12,9 @@ # See the License for the specific language governing permissions and # limitations under the License. +""" +Main entry point to run the experiments. Contains general setup and the proper inference code. +""" import argparse import gc @@ -41,6 +44,7 @@ def load_base_results(model_id...
https://raw.githubusercontent.com/huggingface/peft/HEAD/method_comparison/text_generation_benchmark/run.py
Help me comply with documentation standards
# Copyright 2023-present the HuggingFace Inc. 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...
--- +++ @@ -86,6 +86,7 @@ @lru_cache def is_torch_tpu_available(check_device=True): + "Checks if `torch_xla` is installed and potentially if a TPU is in the environment" if importlib.util.find_spec("torch_xla") is not None: if check_device: # We need to check if `xla_device` can be foun...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/import_utils.py
Generate consistent documentation across files
# Copyright 2025-present the HuggingFace Inc. 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...
--- +++ @@ -131,6 +131,18 @@ self.update_layer(adapter_name, mask, r, init_weights=init_weights) def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_me...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/shira/layer.py
Add inline docstrings for readability
# Copyright 2025-present the HuggingFace Inc. 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...
--- +++ @@ -80,6 +80,11 @@ return None def _collect_token_weights(self, weight: torch.Tensor, rows: torch.Tensor, embed_dim: int) -> torch.Tensor: + """DeepSpeed zero3 specific code to initialize trainable tokens. + + Ensures that only the necessary weights are collected to a single rank, i...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/trainable_tokens/layer.py
Document this module using docstrings
# Copyright 2025-present the HuggingFace Inc. 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...
--- +++ @@ -113,6 +113,10 @@ parent: nn.Module, current_key: str, ) -> None: + """ + The same as `_create_and_replace` but takes a dictionary instead of a peft config so that we can add keys that + are not present in the config, such as `tied_adapter`. + """ kw...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/trainable_tokens/model.py
Insert docstrings into my code
# Copyright 2024-present the HuggingFace Inc. 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...
--- +++ @@ -21,6 +21,17 @@ @dataclass class CPTConfig(PromptLearningConfig): + """ + CPT Configuration class extending PeftConfig for Context-aware Prompt Tuning (CPT). + + This class introduces additional parameters required for CPT, such as: + - Token type masks + - Prompt tuning initialization + ...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/cpt/config.py
Add docstrings for better understanding
# Copyright 2023-present the HuggingFace Inc. 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...
--- +++ @@ -72,6 +72,18 @@ @contextmanager def onload_layer(layer): + r""" + A utility for modifying a module containing one or more tuners and a base layer, any of which are offloaded to the + CPU or disk. Moves a module's sub-modules to the execution device before some action is performed, after that the ...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/tuners_utils.py
Add standardized docstrings across the file
# Copyright 2025-present the HuggingFace Inc. 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...
--- +++ @@ -82,6 +82,7 @@ self.out_features = out_features def update_layer(self, adapter_name: str, effective_rank: int, **kwargs): + """Update layer to add a new OSF adapter.""" if effective_rank <= 0: raise ValueError( f"`effective_rank` should be a positi...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/osf/layer.py
Add docstrings to meet PEP guidelines
# Copyright 2026-present the HuggingFace Inc. 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...
--- +++ @@ -28,6 +28,23 @@ class LilyModel(BaseTuner): + """ + Creates a Low-Rank Interconnected Adaptation Across Layers (Lily) model from a pretrained transformers model. + + The method is described in detail in https://arxiv.org/abs/2407.09946. + + Args: + model ([`torch.nn.Module`]): The mode...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/lily/model.py
Replace inline comments with docstrings
# Copyright 2023-present the HuggingFace Inc. 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...
--- +++ @@ -23,6 +23,21 @@ class AdaptionPromptModel(nn.Module): + """ + Implements adaption prompts as described in https://huggingface.co/papers/2303.16199. + + The top L attention modules are replaced with AdaptedAttention modules that wrap the original ones, but insert + trainable prompts with gates...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/adaption_prompt/model.py
Write docstrings including parameters and return values
# Copyright 2024-present the HuggingFace Inc. 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...
--- +++ @@ -125,6 +125,20 @@ state.reset_grads() def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): The name of the adapter for which the delta weight should be...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/vera/bnb.py
Add well-formatted docstrings
# Copyright 2023-present the HuggingFace Inc. 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...
--- +++ @@ -166,6 +166,18 @@ self.is_target_conv_1d_layer = is_target_conv_1d_layer def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, ...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/vera/layer.py
Can you add docstrings to this Python file?
# Copyright 2025-present the HuggingFace Inc. 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...
--- +++ @@ -24,6 +24,31 @@ class RoadLayer(BaseTunerLayer): + """ + Road layer. + + Generally the idea of RoAD is to split the input vector into many 2D vectors and rotate each 2D vector with its own + 2D rotation matrix. For additional flexibility, each rotation matrix is multiplied by a trainable scal...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/road/layer.py
Generate docstrings for exported functions
# Copyright 2023-present the HuggingFace Inc. 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...
--- +++ @@ -33,6 +33,56 @@ class OFTModel(BaseTuner): + """ + Creates Orthogonal Finetuning model from a pretrained model. The method is described in + https://huggingface.co/papers/2306.07280 + + Args: + model (`torch.nn.Module`): The model to which the adapter tuner layers will be attached. + ...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/oft/model.py
Add docstrings to make code maintainable
# Copyright 2023-present the HuggingFace Inc. 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...
--- +++ @@ -26,12 +26,29 @@ class MultiplicativeDropoutLayer(nn.Module): + """ + Implements the multiplicative dropout layer for OFT. + """ def __init__(self, p=0.0): + """ + Initializes the multiplicative dropout layer. + + Parameters: + p (float): The probability of dro...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/oft/layer.py
Add return value explanations in docstrings
# Copyright 2023-present the HuggingFace Inc. 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...
--- +++ @@ -90,6 +90,18 @@ self.update_layer(adapter_name, init_ia3_weights) def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *option...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/ia3/layer.py
Create structured documentation for my script
# Copyright 2026-present the HuggingFace Inc. 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...
--- +++ @@ -29,6 +29,9 @@ class OrthLayer(nn.Module): + """ + r*r orthogonal transformation R used in PSOFT between A and B. Forward: output = input @ R.T + """ def __init__( self, @@ -342,6 +345,9 @@ return self.psoft_R[adapter_name].get_matrix() def get_delta_weight(self, a...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/psoft/layer.py
Create documentation for each function signature
# Copyright 2023-present the HuggingFace Inc. 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...
--- +++ @@ -38,6 +38,9 @@ xloramodel: nn.Module, # XLoraModel config: XLoraConfig, ) -> tuple[int, torch.device | None]: + """ + Returns the number of swapped layers. + """ total_swapped = 0 all_layers = [] @@ -94,6 +97,12 @@ subfolder: Optional[str] = None, **kwargs, ): + "...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/xlora/model.py
Can you add docstrings to this Python file?
# Copyright 2025-present the HuggingFace Inc. 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...
--- +++ @@ -59,6 +59,18 @@ ) def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + ...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/randlora/bnb.py
Document functions with clear intent
# Copyright 2025-present the HuggingFace Inc. 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...
--- +++ @@ -33,12 +33,45 @@ class PveraModel(BaseTuner): + """ + Creates Probabilistic Vector-based Random Matrix Adaptation (PVeRA) model from a pretrained transformers model. + + Args: + model ([`~transformers.PreTrainedModel`]): The model to be adapted. + config ([`PveraConfig`]): The conf...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/pvera/model.py
Help me add docstrings to my project
# Copyright 2025-present the HuggingFace Inc. 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...
--- +++ @@ -168,6 +168,18 @@ self.is_target_conv_1d_layer = is_target_conv_1d_layer def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, ...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/pvera/layer.py
Add docstrings to existing functions
# Copyright 2023-present the HuggingFace Inc. 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...
--- +++ @@ -34,6 +34,7 @@ @contextmanager def gather_params_ctx(param, modifier_rank: Optional[int] = 0, fwd_module: torch.nn.Module = None): + """Call DeepSpeed GatheredParameters context manager if DeepSpeed is enabled, otherwise do nothing.""" if not check_deepspeed_zero3_enabled(): yield @@ -4...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/utils/integrations.py
Auto-generate documentation strings for this file
# Copyright 2024-present the HuggingFace Inc. 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...
--- +++ @@ -59,6 +59,13 @@ inference_mode: bool = False, **kwargs, ) -> None: + """Internal function to create miss adapter + + Args: + adapter_name (`str`): Name for the adapter to add. + r (`int`): Rank for the added adapter. + init_weights (`bool`)...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/miss/layer.py
Insert docstrings into my code
# Copyright 2023-present the HuggingFace Inc. 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...
--- +++ @@ -39,6 +39,18 @@ tensor_or_shape: Union[torch.Tensor, tuple[int, ...]], generator: torch.Generator, ) -> torch.Tensor: + """ + Kaiming Uniform Initialisation adapted to accept a `torch.Generator` object for PRNG. + + Args: + tensor_or_shape (`Union[torch.Tensor, tuple[int, ...]]`): +...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/vera/model.py
Fill in missing docstrings in my code
# Copyright 2024-present the HuggingFace Inc. 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...
--- +++ @@ -19,12 +19,33 @@ def reshape_weight_task_tensors(task_tensors, weights): + """ + Reshapes `weights` to match the shape of `task_tensors` by unsqeezing in the remaining dimenions. + + Args: + task_tensors (`torch.Tensor`): The tensors that will be used to reshape `weights`. + weight...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/utils/merge_utils.py
Add docstrings that explain inputs and outputs
# Copyright 2025-present the HuggingFace Inc. 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...
--- +++ @@ -12,18 +12,54 @@ # See the License for the specific language governing permissions and # limitations under the License. +""" +Minimal wavelet implementation extracted from PyWavelets + +This code contains portions derived from PyWavelets: Copyright (c) 2006-2012 Filip Wasilewski <http://en.ig.ma/> +Copyri...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/waveft/wavelet.py
Document my Python code with docstrings
# Copyright 2023-present the HuggingFace Inc. 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...
--- +++ @@ -39,6 +39,9 @@ class XLoraClassifier(nn.Module): + """ + A classifier to select LoRA layers for XLora. + """ def __init__( self, @@ -48,6 +51,10 @@ n_layers: int, device: torch.device, ): + """ + Construct an X-LoRA classifier from a model, con...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/xlora/classifier.py
Document this code for team use
# Copyright 2023-present the HuggingFace Inc. 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...
--- +++ @@ -135,6 +135,24 @@ def prepare_model_for_kbit_training(model, use_gradient_checkpointing=True, gradient_checkpointing_kwargs=None): + r""" + Note this method only works for `transformers` models. + + This method wraps the entire protocol for preparing a model before running a training. This inclu...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/utils/other.py
Help me add docstrings to my project
# Copyright 2025-present the HuggingFace Inc. 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...
--- +++ @@ -125,6 +125,20 @@ state.reset_grads() def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): The name of the adapter for which the delta weight should be...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/pvera/bnb.py
Add docstrings including usage examples
# Copyright 2025-present the HuggingFace Inc. 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...
--- +++ @@ -214,6 +214,18 @@ self.update_layer(adapter_name, n_frequency, scaling, init_weights, random_loc_seed, wavelet_family, use_idwt) def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base we...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/waveft/layer.py
Can you add docstrings to this Python file?
# Copyright 2025-present the HuggingFace Inc. 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...
--- +++ @@ -33,6 +33,7 @@ target_module_mapping = TRANSFORMERS_MODELS_TO_WAVEFT_TARGET_MODULES_MAPPING def _calculate_proportional_parameters(self, model: torch.nn.Module, waveft_config): + """Calculate proportional parameter allocation for all target modules.""" target_modules_info = [] ...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/waveft/model.py
Write docstrings for backend logic
# Copyright 2024-present the HuggingFace Inc. 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...
--- +++ @@ -34,6 +34,11 @@ def _update_scaling(lora_module, adapter_name, scaling=None): + """ + Update the value of the scalings of the LoRA module. + + Takes into consideration that scalings can be tensors from prepare_model_for_compiled_hotswap. + """ if lora_module.scaling[adapter_name] == scal...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/utils/hotswap.py
Help me comply with documentation standards
# Copyright 2024-present the HuggingFace Inc. 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...
--- +++ @@ -26,6 +26,10 @@ class XLoraLayer: + """ + A XLoraLayer wraps any LoraLayer and performs the XLora operation on the LoRA adaptors specified. Its primary API + is the forward method, which uses the scalings to execute the XLora algorithm. + """ def __init__( self, @@ -92,6 +96,1...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/xlora/layer.py
Provide clean and structured docstrings
# Copyright 2024-present the HuggingFace Inc. 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...
--- +++ @@ -27,6 +27,43 @@ class VBLoRAModel(BaseTuner): + """ + Creates VBLoRA model from a pretrained transformers model. + + The method is described in detail in https://huggingface.co/papers/2405.15179. + + Args: + model ([`~transformers.PreTrainedModel`]): The model to be adapted. + c...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/vblora/model.py
Write docstrings for data processing functions
# Copyright 2024-present the HuggingFace Inc. 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...
--- +++ @@ -29,6 +29,12 @@ def cache_decorator(cache_key: str): + """Caching decorator for DoRA + + Caching is only enabled if ENABLE_DORA_CACHING is set to True (default: False), when in eval mode, and when the + adapter_name is passed (e.g. not during layer initialization). + + """ def cache_va...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/lora/dora.py
Generate docstrings for this script
# Copyright 2023-present the HuggingFace Inc. 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...
--- +++ @@ -181,6 +181,9 @@ def _low_rank_decomposition(weight, reduced_rank=32): + """ + :param weight: The matrix to decompose, of shape (H, W) :param reduced_rank: the final rank :return: + """ matrix_dimension = len(weight.size()) if matrix_dimension != 2: raise ValueError(f"Only sup...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/utils/loftq_utils.py
Add docstrings to my Python code
# Copyright 2023-present the HuggingFace Inc. 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...
--- +++ @@ -43,10 +43,12 @@ def has_valid_embedding_base_layer(layer): + """Check if the layer has an embedding base layer""" return hasattr(layer, "base_layer") and isinstance(layer.base_layer, (torch.nn.Linear, torch.nn.Embedding)) def get_embedding_layer_name(model, layer, is_embedding_in_target_mod...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/utils/save_and_load.py
Create documentation for each function signature
# Copyright 2024-present the HuggingFace Inc. 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...
--- +++ @@ -18,6 +18,30 @@ class IncrementalPCA: + """ + An implementation of Incremental Principal Components Analysis (IPCA) that leverages PyTorch for GPU acceleration. + Adapted from https://github.com/scikit-learn/scikit-learn/blob/main/sklearn/decomposition/_incremental_pca.py + + This class provi...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/utils/incremental_pca.py
Add docstrings following best practices
# Copyright 2024-present the HuggingFace Inc. 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...
--- +++ @@ -136,6 +136,18 @@ self.is_target_conv_1d_layer = is_target_conv_1d_layer def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, ...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/vblora/layer.py
Provide docstrings following PEP 257
# Copyright 2023-present the HuggingFace Inc. 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...
--- +++ @@ -72,6 +72,7 @@ def _get_encoder(model: nn.Module) -> nn.Module | None: + """Check if the model has an encoder and if it has, returns it; otherwise returns None""" if not hasattr(model, "get_encoder"): return None @@ -84,12 +85,92 @@ class LoraModel(BaseTuner): + """ + Creates...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/lora/model.py
Add docstrings to meet PEP guidelines
# Copyright 2023-present the HuggingFace Inc. 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...
--- +++ @@ -32,6 +32,9 @@ def _prepare_model_for_gradient_checkpointing(model: nn.Module) -> None: + r""" + Prepares the model for gradient checkpointing if necessary + """ # Note: same as PeftModel._prepare_model_for_gradient_checkpointing if not getattr(model, "is_gradient_checkpointing", True)...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/mixed_model.py
Add docstrings to clarify complex logic
# Copyright 2025-present the HuggingFace Inc. 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...
--- +++ @@ -202,6 +202,18 @@ self.is_target_conv_1d_layer = is_target_conv_1d_layer def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, ...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/randlora/layer.py
Create Google-style docstrings for my code
# Copyright 2023-present the HuggingFace Inc. 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...
--- +++ @@ -17,6 +17,9 @@ class PeftType(str, enum.Enum): + """ + Enum class for the different types of adapters in PEFT. + """ PROMPT_TUNING = "PROMPT_TUNING" MULTITASK_PROMPT_TUNING = "MULTITASK_PROMPT_TUNING" @@ -56,6 +59,18 @@ class TaskType(str, enum.Enum): + """ + Enum class for...
https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/utils/peft_types.py
Add docstrings for production code
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -31,6 +31,12 @@ class PeriodN(Indicator): + ''' + Base class for indicators which take a period (__init__ has to be called + either via super or explicitly) + + This class has no defined lines + ''' params = (('period', 1),) def __init__(self): @@ -39,6 +45,18 @@ class Oper...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/indicators/basicops.py
Add docstrings explaining edge cases
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -34,6 +34,7 @@ class MetaIBData(DataBase.__class__): def __init__(cls, name, bases, dct): + '''Class has already been created ... register''' # Initialize the class super(MetaIBData, cls).__init__(name, bases, dct) @@ -42,6 +43,155 @@ class IBData(with_metaclass(MetaIBDa...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/feeds/ibdata.py
Add docstrings that explain inputs and outputs
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -27,6 +27,23 @@ class EnvelopeMixIn(object): + ''' + MixIn class to create a subclass with another indicator. The main line of + that indicator will be surrounded by an upper and lower band separated a + given "perc"entage from the input main line + + The usage is: + + - Class XXXEnve...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/indicators/envelope.py
Create docstrings for API functions
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -31,6 +31,7 @@ class MetaVChartFile(bt.DataBase.__class__): def __init__(cls, name, bases, dct): + '''Class has already been created ... register''' # Initialize the class super(MetaVChartFile, cls).__init__(name, bases, dct) @@ -39,6 +40,15 @@ class VChartFile(bt.with_m...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/feeds/vchartfile.py
Add docstrings including usage examples
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -36,24 +36,93 @@ class VCCommInfo(CommInfoBase): + ''' + Commissions are calculated by ib, but the trades calculations in the + ```Strategy`` rely on the order carrying a CommInfo object attached for the + calculation of the operation cost and value. + + These are non-critical informations...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/brokers/vcbroker.py
Add docstrings that explain logic
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -33,6 +33,9 @@ class MetaAnalyzer(bt.MetaParams): def donew(cls, *args, **kwargs): + ''' + Intercept the strategy parameter + ''' # Create the object and set the params in place _obj, args, kwargs = super(MetaAnalyzer, cls).donew(*args, **kwargs) @@ -84,9 +87,5...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/analyzer.py
Generate docstrings with examples
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -25,6 +25,22 @@ class MACD(Indicator): + ''' + Moving Average Convergence Divergence. Defined by Gerald Appel in the 70s. + + It measures the distance of a short and a long term moving average to + try to identify the trend. + + A second lagging moving average over the convergence-divergen...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/indicators/macd.py
Improve documentation using docstrings
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -25,6 +25,18 @@ class BollingerBands(Indicator): + ''' + Defined by John Bollinger in the 80s. It measures volatility by defining + upper and lower bands at distance x standard deviations + + Formula: + - midband = SimpleMovingAverage(close, period) + - topband = midband + devfactor...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/indicators/bollinger.py
Add clean documentation to messy code
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -58,6 +58,218 @@ class Cerebro(with_metaclass(MetaParams, object)): + '''Params: + + - ``preload`` (default: ``True``) + + Whether to preload the different ``data feeds`` passed to cerebro for + the Strategies + + - ``runonce`` (default: ``True``) + + Run ``Indicators`` ...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/cerebro.py
Create documentation for each function signature
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -29,6 +29,36 @@ class DrawDown(bt.Analyzer): + '''This analyzer calculates trading system drawdowns stats such as drawdown + values in %s and in dollars, max drawdown in %s and in dollars, drawdown + length and drawdown max length + + Params: + + - ``fund`` (default: ``None``) + + ...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/analyzers/drawdown.py
Add docstrings to clarify complex logic
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -30,10 +30,12 @@ class MetaChainer(bt.DataBase.__class__): def __init__(cls, name, bases, dct): + '''Class has already been created ... register''' # Initialize the class super(MetaChainer, cls).__init__(name, bases, dct) def donew(cls, *args, **kwargs): + '''Int...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/feeds/chainer.py
Write docstrings including parameters and return values
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -66,8 +66,33 @@ class IBOrder(OrderBase, ib.ext.Order.Order): + '''Subclasses the IBPy order to provide the minimum extra functionality + needed to be compatible with the internally defined orders + + Once ``OrderBase`` has processed the parameters, the __init__ method takes + over to use the...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/brokers/ibbroker.py
Document all public functions with docstrings
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -29,9 +29,35 @@ class SQN(Analyzer): + '''SQN or SystemQualityNumber. Defined by Van K. Tharp to categorize trading + systems. + + - 1.6 - 1.9 Below average + - 2.0 - 2.4 Average + - 2.5 - 2.9 Good + - 3.0 - 5.0 Excellent + - 5.1 - 6.9 Superb + - 7.0 - Holy Grail? ...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/analyzers/sqn.py
Add professional docstrings to my codebase
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -29,6 +29,33 @@ class SessionFiller(with_metaclass(metabase.MetaParams, object)): + ''' + Bar Filler for a Data Source inside the declared session start/end times. + + The fill bars are constructed using the declared Data Source ``timeframe`` + and ``compression`` (used to calculate the inter...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/filters/session.py
Generate docstrings with examples
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -113,6 +113,18 @@ class SimpleFilterWrapper(object): + '''Wrapper for filters added via .addfilter to turn them + into processors. + + Filters are callables which + + - Take a ``data`` as an argument + - Return False if the current bar has not triggered the filter + - Return True ...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/dataseries.py
Add detailed documentation for each class
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -37,6 +37,33 @@ class QuandlCSV(feed.CSVDataBase): + ''' + Parses pre-downloaded Quandl CSV Data Feeds (or locally generated if they + comply to the Quandl format) + + Specific parameters: + + - ``dataname``: The filename to parse or a file-like object + + - ``reverse`` (default: ``...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/feeds/quandl.py
Generate docstrings for exported functions
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -31,6 +31,53 @@ class PyFolio(bt.Analyzer): + '''This analyzer uses 4 children analyzers to collect data and transforms it + in to a data set compatible with ``pyfolio`` + + Children Analyzer + + - ``TimeReturn`` + + Used to calculate the returns of the global portfolio value + + ...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/analyzers/pyfolio.py
Write proper docstrings for these functions
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -28,6 +28,21 @@ class PandasDirectData(feed.DataBase): + ''' + Uses a Pandas DataFrame as the feed source, iterating directly over the + tuples returned by "itertuples". + + This means that all parameters related to lines must have numeric + values as indices into the tuples + + Note: +...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/feeds/pandafeed.py
Turn comments into proper docstrings
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -25,6 +25,26 @@ class StandardDeviation(Indicator): + ''' + Calculates the standard deviation of the passed data for a given period + + Note: + - If 2 datas are provided as parameters, the 2nd is considered to be the + mean of the first + + - ``safepow`` (default: False) If this...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/indicators/deviation.py
Document all endpoints with docstrings
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -28,6 +28,20 @@ class FixedSize(with_metaclass(MetaParams, object)): + '''Returns the execution size for a given order using a *percentage* of the + volume in a bar. + + This percentage is set with the parameter ``perc`` + + Params: + + - ``size`` (default: ``None``) maximum size to be ...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/fillers.py
Write docstrings for data processing functions
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -34,6 +34,193 @@ class BackBroker(bt.BrokerBase): + '''Broker Simulator + + The simulation supports different order types, checking a submitted order + cash requirements against current cash, keeping track of cash and value + for each iteration of ``cerebro`` and keeping the current pos...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/brokers/bbroker.py
Add docstrings to clarify complex logic
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -25,6 +25,19 @@ class TrueHigh(Indicator): + ''' + Defined by J. Welles Wilder, Jr. in 1978 in his book *"New Concepts in + Technical Trading Systems"* for the ATR + + Records the "true high" which is the maximum of today's high and + yesterday's close + + Formula: + - truehigh = m...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/indicators/atr.py
Add docstrings to my Python code
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -36,6 +36,7 @@ class MetaVCData(DataBase.__class__): def __init__(cls, name, bases, dct): + '''Class has already been created ... register''' # Initialize the class super(MetaVCData, cls).__init__(name, bases, dct) @@ -44,6 +45,54 @@ class VCData(with_metaclass(MetaVCDat...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/feeds/vcdata.py
Create docstrings for API functions
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -41,6 +41,16 @@ class DivByZero(Logic): + '''This operation is a Lines object and fills it values by executing a + division on the numerator / denominator arguments and avoiding a division + by zero exception by checking the denominator + + Params: + - a: numerator (numeric or iterable o...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/functions.py
Generate NumPy-style docstrings
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -44,18 +44,33 @@ return abs(size) * price def getoperationcost(self, size, price): + '''Returns the needed amount of cash an operation would cost''' # Same reasoning as above return abs(size) * price class MetaOandaBroker(BrokerBase.__class__): def __init__(c...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/brokers/oandabroker.py
Add docstrings that explain purpose and usage
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -29,6 +29,25 @@ class CalendarDays(with_metaclass(metabase.MetaParams, object)): + ''' + Bar Filler to add missing calendar days to trading days + + Params: + + - fill_price (def: None): + + > 0: The given value to fill + 0 or None: Use the last known closing price + -1...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/filters/calendardays.py
Generate docstrings with examples
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -42,6 +42,9 @@ _indcol = dict() def __init__(cls, name, bases, dct): + ''' + Class has already been created ... register subclasses + ''' # Initialize the class super(MetaAbstractDataBase, cls).__init__(name, bases, dct) @@ -206,6 +209,7 @@ return s...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/feed.py
Add docstrings with type hints explained
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -25,6 +25,14 @@ class NonZeroDifference(Indicator): + ''' + Keeps track of the difference between two data inputs skipping, memorizing + the last non zero value if the current difference is zero + + Formula: + - diff = data - data1 + - nzd = diff if diff else diff(-1) + ''' ...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/indicators/crossover.py
Generate docstrings with examples
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -26,6 +26,19 @@ class DoubleExponentialMovingAverage(MovingAverageBase): + ''' + DEMA was first time introduced in 1994, in the article "Smoothing Data with + Faster Moving Averages" by Patrick G. Mulloy in "Technical Analysis of + Stocks & Commodities" magazine. + + It attempts to reduce ...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/indicators/dema.py
Add docstrings for better understanding
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -29,10 +29,12 @@ class MetaRollOver(bt.DataBase.__class__): def __init__(cls, name, bases, dct): + '''Class has already been created ... register''' # Initialize the class super(MetaRollOver, cls).__init__(name, bases, dct) def donew(cls, *args, **kwargs): + '''I...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/feeds/rollover.py
Document functions with detailed explanations
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -23,6 +23,19 @@ class BarReplayer_Open(object): + ''' + This filters splits a bar in two parts: + + - ``Open``: the opening price of the bar will be used to deliver an + initial price bar in which the four components (OHLC) are equal + + The volume/openinterest fields are 0 for t...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/filters/daysteps.py
Generate docstrings for exported functions
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -35,6 +35,49 @@ class YahooFinanceCSVData(feed.CSVDataBase): + ''' + Parses pre-downloaded Yahoo CSV Data Feeds (or locally generated if they + comply to the Yahoo format) + + Specific parameters: + + - ``dataname``: The filename to parse or a file-like object + + - ``reverse`` (def...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/feeds/yahoo.py
Add docstrings for internal functions
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -26,19 +26,26 @@ class BacktraderError(Exception): + '''Base exception for all other exceptions''' pass class StrategySkipError(BacktraderError): + '''Requests the platform to skip this strategy for backtesting. To be + raised during the initialization (``__init__``) phase of the insta...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/errors.py
Add detailed docstrings explaining each function
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -33,6 +33,7 @@ class MetaOandaData(DataBase.__class__): def __init__(cls, name, bases, dct): + '''Class has already been created ... register''' # Initialize the class super(MetaOandaData, cls).__init__(name, bases, dct) @@ -41,6 +42,101 @@ class OandaData(with_metaclass...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/feeds/oanda.py
Document functions with clear intent
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -31,6 +31,9 @@ class MetaBroker(MetaParams): def __init__(cls, name, bases, dct): + ''' + Class has already been created ... fill missing methods if needed be + ''' # Initialize the class super(MetaBroker, cls).__init__(name, bases, dct) translations = {...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/broker.py
Create documentation strings for testing functions
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -25,6 +25,17 @@ class _AroonBase(Indicator): + ''' + Base class which does the calculation of the AroonUp/AroonDown values and + defines the common parameters. + + It uses the class attributes _up and _down (boolean flags) to decide which + value has to be calculated. + + Values are not...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/indicators/aroon.py
Add minimal docstrings for each function
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -18,6 +18,16 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################### +''' + +.. module:: lineroot + +Definition of the base class LineRoot and base classes LineSingle/LineMultiple +to define interfaces and ...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/lineroot.py
Add minimal docstrings for each function
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -18,6 +18,16 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################### +''' + +.. module:: linebuffer + +Classes that hold the buffer for a *line* and can operate on it +with appends, forwarding, rewinding, r...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/linebuffer.py
Add docstrings to existing functions
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -18,6 +18,16 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################### +''' + +.. module:: lineroot + +Defines LineSeries and Descriptors inside of it for classes that hold multiple +lines at once. + +.. modu...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/lineseries.py
Write docstrings describing each step
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -28,6 +28,94 @@ class CommInfoBase(with_metaclass(MetaParams)): + '''Base Class for the Commission Schemes. + + Params: + + - ``commission`` (def: ``0.0``): base commission value in percentage or + monetary units + + - ``mult`` (def ``1.0``): multiplier applied to the asset for + ...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/comminfo.py
Generate consistent docstrings
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -25,6 +25,19 @@ class UpMove(Indicator): + ''' + Defined by J. Welles Wilder, Jr. in 1978 in his book *"New Concepts in + Technical Trading Systems"* as part of the Directional Move System to + calculate Directional Indicators. + + Positive if the given data has moved higher than the previ...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/indicators/directionalmove.py
Document classes and their methods
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -31,6 +31,84 @@ class SharpeRatio(Analyzer): + '''This analyzer calculates the SharpeRatio of a strategy using a risk free + asset which is simply an interest rate + + See also: + + - https://en.wikipedia.org/wiki/Sharpe_ratio + + Params: + + - ``timeframe``: (default: ``TimeFrame.Y...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/analyzers/sharpe.py
Create docstrings for reusable components
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -25,14 +25,41 @@ def average(x, bessel=False): + ''' + Args: + x: iterable with len + + oneless: (default ``False``) reduces the length of the array for the + division. + + Returns: + A float with the average of the elements of x + ''' return math.fsum(x) / ...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/mathsupport.py
Create Google-style docstrings for my code
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -28,6 +28,17 @@ class LaguerreRSI(PeriodN): + ''' + Defined by John F. Ehlers in `Cybernetic Analysis for Stock and Futures`, + 2004, published by Wiley. `ISBN: 978-0-471-46307-8` + + The Laguerre RSI tries to implements a better RSI by providing a sort of + *Time Warp without Time Travel*...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/indicators/lrsi.py
Generate docstrings for each module
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2023 Daniel Rodriguez # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License a...
--- +++ @@ -330,14 +330,27 @@ pass def prenext(self): + ''' + This method will be called before the minimum period of all + datas/indicators have been meet for the strategy to start executing + ''' pass def nextstart(self): + ''' + This method wil...
https://raw.githubusercontent.com/mementum/backtrader/HEAD/backtrader/lineiterator.py