instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Write docstrings that follow conventions | # Community
# by https://github.com/Ozzyz
from typing import Dict, List, Optional
import cipheycore
import logging
from rich.logging import RichHandler
from ciphey.common import fix_case
from ciphey.iface import Config, Cracker, CrackInfo, CrackResult, ParamSpec, registry
from ciphey.mathsHelper import mathsHelper
... | --- +++ @@ -14,6 +14,15 @@
@registry.register
class Affine(Cracker[str]):
+ """
+ Each character in the Affine Cipher is encoded with the rule E(x) = (ax + b) mod m
+ m is the size of the alphabet, while a and b are the keys in the cipher. a must be coprime to b.
+ The Caesar cipher is a specific case of... | https://raw.githubusercontent.com/bee-san/Ciphey/HEAD/ciphey/basemods/Crackers/affine.py |
Annotate my code with docstrings | from abc import ABC, abstractmethod
from typing import Any, Dict, Generic, List, NamedTuple, Optional, Set, Type, TypeVar
from rich import box
from rich.console import Console
from rich.markup import escape
from rich.table import Table
from ._fwd import config as Config
T = TypeVar("T")
U = TypeVar("U")
console = C... | --- +++ @@ -15,6 +15,15 @@
class ParamSpec(NamedTuple):
+ """
+ Attributes:
+ req Whether this argument is required
+ desc A description of what this argument does
+ default The default value for this argument. Ignored if req == True or configPath is not None
+ c... | https://raw.githubusercontent.com/bee-san/Ciphey/HEAD/ciphey/iface/_modules.py |
Document my Python code with docstrings |
from collections import OrderedDict
from string import punctuation
from typing import Optional
import logging
from rich.logging import RichHandler
class mathsHelper:
def __init__(self):
# ETAOIN is the most popular letters in order
self.ETAOIN = "ETAOINSHRDLCUMWFGYPBVKJXQZ"
self.LETTERS... | --- +++ @@ -1,118 +1,210 @@-
-from collections import OrderedDict
-from string import punctuation
-from typing import Optional
-
-import logging
-from rich.logging import RichHandler
-
-
-class mathsHelper:
-
- def __init__(self):
- # ETAOIN is the most popular letters in order
- self.ETAOIN = "ETAOINS... | https://raw.githubusercontent.com/bee-san/Ciphey/HEAD/ciphey/mathsHelper.py |
Document this script properly | import os
import warnings
from typing import Any, Optional, Union
import click
from appdirs import AppDirs
import logging
from rich.logging import RichHandler
from rich.console import Console
from . import iface
warnings.filterwarnings("ignore")
console = Console()
def decrypt(config: iface.Config, ctext: Any) ->... | --- +++ @@ -1,3 +1,16 @@+"""
+ ██████╗██╗██████╗ ██╗ ██╗███████╗██╗ ██╗
+██╔════╝██║██╔══██╗██║ ██║██╔════╝╚██╗ ██╔╝
+██║ ██║██████╔╝███████║█████╗ ╚████╔╝
+██║ ██║██╔═══╝ ██╔══██║██╔══╝ ╚██╔╝
+╚██████╗██║██║ ██║ ██║███████╗ ██║
+https://github.com/Ciphey
+https://github.com/Ciphey/Ciphey/wiki
+... | https://raw.githubusercontent.com/bee-san/Ciphey/HEAD/ciphey/ciphey.py |
Generate consistent documentation across files | import re
import time
from typing import Dict, Optional, Tuple
import logging
from rich.logging import RichHandler
from ciphey.iface import Config, Decoder, ParamSpec, T, U, WordList, registry
@registry.register
class Brainfuck(Decoder[str]):
def decode(self, ctext: T) -> Optional[U]:
logging.debug("At... | --- +++ @@ -11,6 +11,25 @@ @registry.register
class Brainfuck(Decoder[str]):
def decode(self, ctext: T) -> Optional[U]:
+ """
+ Takes a ciphertext and treats it as a Brainfuck program,
+ interpreting it and saving the output as a string to return.
+
+ Brainfuck is a very simple, Turing... | https://raw.githubusercontent.com/bee-san/Ciphey/HEAD/ciphey/basemods/Decoders/brainfuck.py |
Annotate my code with docstrings | from typing import Any
def id_lambda(value: Any):
return lambda *args: value
def fix_case(target: str, base: str) -> str:
ret = "".join(
[
target[i].upper() if base[i].isupper() else target[i]
for i in range(len(target))
]
)
return "".join(
[
... | --- +++ @@ -1,11 +1,16 @@+"""Some useful adapters"""
from typing import Any
def id_lambda(value: Any):
+ """
+ A function used in dynamic class generation that abstracts away a constant return value (like in getName)
+ """
return lambda *args: value
def fix_case(target: str, base: str) -> str:
... | https://raw.githubusercontent.com/bee-san/Ciphey/HEAD/ciphey/common.py |
Can you add docstrings to this Python file? | import os
from typing import Any, List
from datetime import datetime
import numpy as np
from psycopg2 import connect
from psycopg2.extras import DictCursor
from pgvector.psycopg2 import register_vector
from services.date import to_unix_timestamp
from datastore.providers.pgvector_datastore import PGClient, PgVectorDat... | --- +++ @@ -39,6 +39,9 @@ self.client.close()
async def upsert(self, table: str, json: dict[str, Any]):
+ """
+ Takes in a list of documents and inserts them into the table.
+ """
with self.client.cursor() as cur:
if not json.get("created_at"):
... | https://raw.githubusercontent.com/openai/chatgpt-retrieval-plugin/HEAD/datastore/providers/postgres_datastore.py |
Add docstrings for production code | import logging
import os
import certifi
import numpy as np
import pymongo
from pymongo.mongo_client import MongoClient
from abc import ABC, abstractmethod
from typing import Dict, List, Optional
from datetime import datetime
from datastore.datastore import DataStore
from models.models import (
DocumentChunk,
... | --- +++ @@ -234,6 +234,10 @@ return store
async def _upsert(self, chunks: Dict[str, List[DocumentChunk]]) -> List[str]:
+ """
+ Takes in a list of list of document chunks and inserts them into the database.
+ Return a list of document ids.
+ """
# Initialize a list of... | https://raw.githubusercontent.com/openai/chatgpt-retrieval-plugin/HEAD/datastore/providers/azurecosmosdb_datastore.py |
Add structured docstrings to improve clarity | import asyncio
import os
import re
import uuid
from typing import Dict, List, Optional
import weaviate
from loguru import logger
from weaviate import Client
from weaviate.util import generate_uuid5
from datastore.datastore import DataStore
from models.models import (
DocumentChunk,
DocumentChunkMetadata,
... | --- +++ @@ -147,6 +147,10 @@ return None
async def _upsert(self, chunks: Dict[str, List[DocumentChunk]]) -> List[str]:
+ """
+ Takes in a list of list of document chunks and inserts them into the database.
+ Return a list of document ids.
+ """
doc_ids = []
... | https://raw.githubusercontent.com/openai/chatgpt-retrieval-plugin/HEAD/datastore/providers/weaviate_datastore.py |
Document helper functions with docstrings | import heapq
class Imperfection:
"""
graph = {'A': ['B', 'C'],
'B': ['C', 'D'],
'C': ['D'],
'D': ['C'],
'E': ['F'],
'F': ['C']}"""
def __init__(self):
None
def findBestNode(self, nodes):
return next(iter(nodes))
#... | --- +++ @@ -2,6 +2,41 @@
class Imperfection:
+ """The graph is a Node: [List of nodes]
+ Where each item in the list of nodes can also have a node with a list of nodes
+
+ The result is that we can keep track of edges, while also keeping it small
+
+ To calculate current, we push the entire graph to A*
... | https://raw.githubusercontent.com/bee-san/Ciphey/HEAD/ciphey/basemods/Searchers/imperfection.py |
Turn comments into proper docstrings | import asyncio
import os
import re
import json
import redis.asyncio as redis
import numpy as np
from redis.commands.search.query import Query as RediSearchQuery
from redis.commands.search.indexDefinition import IndexDefinition, IndexType
from redis.commands.search.field import (
TagField,
TextField,
Numeri... | --- +++ @@ -87,6 +87,9 @@
@classmethod
async def init(cls, **kwargs):
+ """
+ Setup the index if it does not exist.
+ """
try:
# Connect to the Redis Client
logger.info("Connecting to Redis")
@@ -142,10 +145,29 @@
@staticmethod
def _redis_key... | https://raw.githubusercontent.com/openai/chatgpt-retrieval-plugin/HEAD/datastore/providers/redis_datastore.py |
Add return value explanations in docstrings | import os
from typing import Any, List
from datetime import datetime
from supabase import Client
from datastore.providers.pgvector_datastore import PGClient, PgVectorDataStore
from models.models import (
DocumentMetadataFilter,
)
SUPABASE_URL = os.environ.get("SUPABASE_URL")
assert SUPABASE_URL is not None, "SUP... | --- +++ @@ -34,12 +34,18 @@ self.client = Client(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY)
async def upsert(self, table: str, json: dict[str, Any]):
+ """
+ Takes in a list of documents and inserts them into the table.
+ """
if "created_at" in json:
json["cre... | https://raw.githubusercontent.com/openai/chatgpt-retrieval-plugin/HEAD/datastore/providers/supabase_datastore.py |
Write beginner-friendly docstrings | import os
import asyncio
from typing import Dict, List, Optional, Tuple, Any
from datetime import datetime
from loguru import logger
from psycopg2cffi import compat
compat.register()
import psycopg2
from psycopg2.extras import DictCursor
from psycopg2.pool import SimpleConnectionPool
from services.date import to_uni... | --- +++ @@ -108,6 +108,10 @@ )
async def _upsert(self, chunks: Dict[str, List[DocumentChunk]]) -> List[str]:
+ """
+ Takes in a dict of document_ids to list of document chunks and inserts them into the database.
+ Return a list of document ids.
+ """
loop = asynci... | https://raw.githubusercontent.com/openai/chatgpt-retrieval-plugin/HEAD/datastore/providers/analyticdb_datastore.py |
Add docstrings to make code maintainable | import asyncio
import base64
import os
import re
import time
from typing import Dict, List, Optional, Union
from azure.core.credentials import AzureKeyCredential
from azure.identity import DefaultAzureCredential as DefaultAzureCredentialSync
from azure.identity.aio import DefaultAzureCredential
from azure.search.docum... | --- +++ @@ -162,9 +162,15 @@ return True
async def _query(self, queries: List[QueryWithEmbedding]) -> List[QueryResult]:
+ """
+ Takes in a list of queries with embeddings and filters and returns a list of query results with matching document chunks and scores.
+ """
return ... | https://raw.githubusercontent.com/openai/chatgpt-retrieval-plugin/HEAD/datastore/providers/azuresearch_datastore.py |
Generate missing documentation strings | import os
import uuid
from typing import Dict, List, Optional
from grpc._channel import _InactiveRpcError
from qdrant_client.http.exceptions import UnexpectedResponse
from qdrant_client.http.models import PayloadSchemaType
from datastore.datastore import DataStore
from models.models import (
DocumentChunk,
Do... | --- +++ @@ -39,6 +39,14 @@ distance: str = "Cosine",
recreate_collection: bool = False,
):
+ """
+ Args:
+ collection_name: Name of the collection to be used
+ vector_size: Size of the embedding stored in a collection
+ distance:
+ Any ... | https://raw.githubusercontent.com/openai/chatgpt-retrieval-plugin/HEAD/datastore/providers/qdrant_datastore.py |
Document functions with detailed explanations | import json
import os
import asyncio
from loguru import logger
from typing import Dict, List, Optional
from pymilvus import (
Collection,
connections,
utility,
FieldSchema,
DataType,
CollectionSchema,
MilvusException,
)
from uuid import uuid4
from services.date import to_unix_timestamp
fr... | --- +++ @@ -109,6 +109,16 @@ create_new: Optional[bool] = False,
consistency_level: str = "Bounded",
):
+ """Create a Milvus DataStore.
+
+ The Milvus Datastore allows for storing your indexes and metadata within a Milvus instance.
+
+ Args:
+ create_new (Optional[b... | https://raw.githubusercontent.com/openai/chatgpt-retrieval-plugin/HEAD/datastore/providers/milvus_datastore.py |
Document helper functions with docstrings | import cipheycore
class Node:
def __init__(
self,
config,
h: float = None,
edges: (any, float) = None,
ctext: str = None,
):
self.weight = h
# Edges is a list of other nodes it can connect to
self.edges = edges
self.ctext = ctext
... | --- +++ @@ -2,6 +2,10 @@
class Node:
+ """
+ A node has a value associated with it
+ Calculated from the heuristic
+ """
def __init__(
self,
@@ -45,6 +49,9 @@ # }
def __init__(self, adjacency_list):
+ """
+ adjacency list: basically the graph
+ """
... | https://raw.githubusercontent.com/bee-san/Ciphey/HEAD/ciphey/basemods/Searchers/astar.py |
Add documentation for all methods | from typing import List
import openai
import os
from loguru import logger
from tenacity import retry, wait_random_exponential, stop_after_attempt
EMBEDDING_MODEL = os.environ.get("EMBEDDING_MODEL", "text-embedding-3-large")
EMBEDDING_DIMENSION = int(os.environ.get("EMBEDDING_DIMENSION", 256))
@retry(wait=wait_rando... | --- +++ @@ -11,6 +11,18 @@
@retry(wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(3))
def get_embeddings(texts: List[str]) -> List[List[float]]:
+ """
+ Embed texts using OpenAI's ada model.
+
+ Args:
+ texts: The list of texts to embed.
+
+ Returns:
+ A list of embeddi... | https://raw.githubusercontent.com/openai/chatgpt-retrieval-plugin/HEAD/services/openai.py |
Annotate my code with docstrings | from abc import ABC, abstractmethod
from typing import Dict, List, Optional
import asyncio
from models.models import (
Document,
DocumentChunk,
DocumentMetadataFilter,
Query,
QueryResult,
QueryWithEmbedding,
)
from services.chunks import get_document_chunks
from services.openai import get_embed... | --- +++ @@ -18,6 +18,11 @@ async def upsert(
self, documents: List[Document], chunk_token_size: Optional[int] = None
) -> List[str]:
+ """
+ Takes in a list of documents and inserts them into the database.
+ First deletes all the existing vectors with the document id (if necessary... | https://raw.githubusercontent.com/openai/chatgpt-retrieval-plugin/HEAD/datastore/datastore.py |
Generate missing documentation strings | import os
from typing import Dict, List, Any, Optional
from loguru import logger
from importlib.metadata import version
from motor.motor_asyncio import AsyncIOMotorClient
from pymongo.driver_info import DriverInfo
from pymongo import UpdateOne
from datastore.datastore import DataStore
from functools import cached_prop... | --- +++ @@ -38,6 +38,25 @@ collection_name: str = MONGODB_COLLECTION,
oversampling_factor: float = OVERSAMPLING_FACTOR,
):
+ """
+ Initialize a MongoDBAtlasDataStore instance.
+
+ Parameters:
+ - index_name (str, optional): Vector search index. If not provided, default ... | https://raw.githubusercontent.com/openai/chatgpt-retrieval-plugin/HEAD/datastore/providers/mongodb_atlas_datastore.py |
Generate missing documentation strings | import os
from typing import Any, Dict, List, Optional
import pinecone
from tenacity import retry, wait_random_exponential, stop_after_attempt
import asyncio
from loguru import logger
from datastore.datastore import DataStore
from models.models import (
DocumentChunk,
DocumentChunkMetadata,
DocumentChunkWi... | --- +++ @@ -68,6 +68,10 @@
@retry(wait=wait_random_exponential(min=1, max=20), stop=stop_after_attempt(3))
async def _upsert(self, chunks: Dict[str, List[DocumentChunk]]) -> List[str]:
+ """
+ Takes in a dict from document id to list of document chunks and inserts them into the index.
+ ... | https://raw.githubusercontent.com/openai/chatgpt-retrieval-plugin/HEAD/datastore/providers/pinecone_datastore.py |
Generate consistent docstrings | from typing import Dict, List, Optional, Tuple
import uuid
import os
from models.models import Document, DocumentChunk, DocumentChunkMetadata
import tiktoken
from services.openai import get_embeddings
# Global variables
tokenizer = tiktoken.get_encoding(
"cl100k_base"
) # The encoding scheme to use for tokeniza... | --- +++ @@ -23,6 +23,16 @@
def get_text_chunks(text: str, chunk_token_size: Optional[int]) -> List[str]:
+ """
+ Split a text into chunks of ~CHUNK_SIZE tokens, based on punctuation and newline boundaries.
+
+ Args:
+ text: The text to split into chunks.
+ chunk_token_size: The target size of... | https://raw.githubusercontent.com/openai/chatgpt-retrieval-plugin/HEAD/services/chunks.py |
Write docstrings describing functionality | import os
from typing import Dict, List, Any, Optional
import elasticsearch
from elasticsearch import Elasticsearch, helpers
from loguru import logger
from datastore.datastore import DataStore
from models.models import (
DocumentChunk,
DocumentChunkWithScore,
DocumentMetadataFilter,
QueryResult,
Q... | --- +++ @@ -40,6 +40,14 @@ shards: int = ELASTICSEARCH_SHARDS,
recreate_index: bool = True,
):
+ """
+ Args:
+ index_name: Name of the index to be used
+ vector_size: Size of the embedding stored in a collection
+ similarity:
+ Any of "... | https://raw.githubusercontent.com/openai/chatgpt-retrieval-plugin/HEAD/datastore/providers/elasticsearch_datastore.py |
Create Google-style docstrings for my code | from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional
from datetime import datetime
from loguru import logger
from services.date import to_unix_timestamp
from datastore.datastore import DataStore
from models.models import (
DocumentChunk,
DocumentChunkMetadata,
DocumentMetadataFi... | --- +++ @@ -19,24 +19,39 @@ class PGClient(ABC):
@abstractmethod
async def upsert(self, table: str, json: dict[str, Any]) -> None:
+ """
+ Takes in a list of documents and inserts them into the table.
+ """
raise NotImplementedError
@abstractmethod
async def rpc(self,... | https://raw.githubusercontent.com/openai/chatgpt-retrieval-plugin/HEAD/datastore/providers/pgvector_datastore.py |
Write docstrings for backend logic | import json
import os
from typing import Dict, List, Optional, Type
from loguru import logger
from datastore.datastore import DataStore
from models.models import (
DocumentChunk,
DocumentChunkMetadata,
DocumentChunkWithScore,
DocumentMetadataFilter,
Query,
QueryResult,
QueryWithEmbedding,
)
... | --- +++ @@ -44,6 +44,7 @@ index_json_path: Optional[str] = None,
index_type_to_index_cls: Optional[dict[str, Type[BaseGPTIndex]]] = None,
) -> BaseGPTIndex:
+ """Create or load index from json path."""
index_json_path = index_json_path or INDEX_JSON_PATH
index_type_to_index_cls = (
index... | https://raw.githubusercontent.com/openai/chatgpt-retrieval-plugin/HEAD/datastore/providers/llama_datastore.py |
Create documentation strings for testing functions | import re
import json
from collections import defaultdict
from urllib.parse import urlparse, urlunparse
def convert_to_title_case(readme_text):
# Only title-case bracketed text that is immediately followed by '(' —
# this targets the link text portion in Markdown like [Name](url)
def _tc_match(m):
... | --- +++ @@ -50,6 +50,13 @@
def find_duplicate_lines(lines, ignore_case=False, ignore_trailing_whitespace=True):
+ """Return a dict mapping a representative original line text -> list of 1-based line
+ numbers where duplicates (by normalization) appear.
+
+ By default, the normalization ignores trailing whi... | https://raw.githubusercontent.com/emmabostian/developer-portfolios/HEAD/src/alphabetical.py |
Add docstrings for production code | #!/usr/bin/env python3
import re
import json
import sys
def extract_portfolio_data(lines):
portfolios = []
# Regex to match markdown links with optional tagline
# Pattern: - [name](url) optional[tagline]
pattern = re.compile(r'^-\s+\[([^\]]+)\]\(([^)]+)\)(?:\s+\[([^\]]*)\])?')
for line in lines:... | --- +++ @@ -1,4 +1,13 @@ #!/usr/bin/env python3
+"""
+Generate feed.json from README.md
+
+This script extracts all portfolio entries from README.md and creates
+a JSON file with structured data for each portfolio.
+
+Usage:
+ python src/generate_feed.py
+"""
import re
import json
@@ -6,6 +15,14 @@
def extra... | https://raw.githubusercontent.com/emmabostian/developer-portfolios/HEAD/src/generate_feed.py |
Create docstrings for API functions | import datetime
import os
import pydoc
from typing import Any, Callable, Dict, List, Optional, Type, Union
import appdirs
import yaml
import logging
from rich.logging import RichHandler
from . import _fwd
from ._modules import PolymorphicChecker, ResourceLoader, Searcher
class Cache:
def __init__(self):
... | --- +++ @@ -13,6 +13,7 @@
class Cache:
+ """Used to track state between levels of recursion to stop infinite loops, and to optimise repeating actions"""
def __init__(self):
self._cache: Dict[Any, Dict[str, Any]] = {}
@@ -87,6 +88,9 @@ open(path, "w+")
def instantiate(self, ... | https://raw.githubusercontent.com/bee-san/Ciphey/HEAD/ciphey/iface/_config.py |
Add well-formatted docstrings | import os
from io import BufferedReader
from typing import Optional
from fastapi import UploadFile
import mimetypes
from PyPDF2 import PdfReader
import docx2txt
import csv
import pptx
from loguru import logger
from models.models import Document, DocumentMetadata
async def get_document_from_file(
file: UploadFile... | --- +++ @@ -23,6 +23,7 @@
def extract_text_from_filepath(filepath: str, mimetype: Optional[str] = None) -> str:
+ """Return the text content of a file given its filepath."""
if mimetype is None:
# Get the mimetype of the file based on its extension
@@ -88,6 +89,7 @@
# Extract text from a file b... | https://raw.githubusercontent.com/openai/chatgpt-retrieval-plugin/HEAD/services/file.py |
Please document this code using docstrings |
import os
from datetime import datetime
from typing import Dict, List, Optional
import chromadb
from datastore.datastore import DataStore
from models.models import (
Document,
DocumentChunk,
DocumentChunkMetadata,
DocumentChunkWithScore,
DocumentMetadataFilter,
QueryResult,
QueryWithEmbed... | --- +++ @@ -1,3 +1,11 @@+"""
+Chroma datastore support for the ChatGPT retrieval plugin.
+
+Consult the Chroma docs and GitHub repo for more information:
+- https://docs.trychroma.com/usage-guide?lang=py
+- https://github.com/chroma-core/chroma
+- https://www.trychroma.com/
+"""
import os
from datetime import datet... | https://raw.githubusercontent.com/openai/chatgpt-retrieval-plugin/HEAD/datastore/providers/chroma_datastore.py |
Generate documentation strings for clarity | import json
import logging
import re
import threading
from collections.abc import Callable, Sequence
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
from opentelemetry import trace
from opentelemetry.sdk.trace import ReadableSpan, TracerProvider
from opentelemetry.sdk.trace.export im... | --- +++ @@ -182,6 +182,7 @@
def prune_otel_span_attributes(attributes: dict[str, Any]) -> dict[str, Any]:
+ """Drop high-volume LLM payload attributes to keep JSONL event files compact."""
filtered: dict[str, Any] = {}
filtered_count = 0
@@ -204,6 +205,7 @@
class JsonlSpanExporter(SpanExporter): ... | https://raw.githubusercontent.com/usestrix/strix/HEAD/strix/telemetry/utils.py |
Add docstrings to improve collaboration | import argparse
import asyncio
import atexit
import logging
import signal
import sys
import threading
from collections.abc import Callable
from importlib.metadata import PackageNotFoundError
from importlib.metadata import version as pkg_version
from typing import TYPE_CHECKING, Any, ClassVar
if TYPE_CHECKING:
fro... | --- +++ @@ -259,6 +259,7 @@
class VulnerabilityDetailScreen(ModalScreen): # type: ignore[misc]
+ """Modal screen to display vulnerability details."""
SEVERITY_COLORS: ClassVar[dict[str, str]] = {
"critical": "#dc2626", # Red
@@ -456,6 +457,7 @@ return text
def _get_markdown_repor... | https://raw.githubusercontent.com/usestrix/strix/HEAD/strix/interface/tui.py |
Document this module using docstrings | import ipaddress
import json
import re
import secrets
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
from typing import Any
from urllib.error import HTTPError, URLError
from urllib.parse import urlparse
from urllib.request import Request, urlopen
import docker
from docker.errors im... | --- +++ @@ -54,6 +54,7 @@
def format_vulnerability_report(report: dict[str, Any]) -> Text: # noqa: PLR0912, PLR0915
+ """Format a vulnerability report for CLI display with all rich fields."""
field_style = "bold #4ade80"
text = Text()
@@ -202,6 +203,7 @@
def _build_vulnerability_stats(stats_text... | https://raw.githubusercontent.com/usestrix/strix/HEAD/strix/interface/utils.py |
Generate consistent documentation across files | import contextlib
import json
import os
from pathlib import Path
from typing import Any
STRIX_API_BASE = "https://models.strix.ai/api/v1"
class Config:
# LLM Configuration
strix_llm = None
llm_api_key = None
llm_api_base = None
openai_api_base = None
litellm_base_url = None
ollama_api_b... | --- +++ @@ -9,6 +9,7 @@
class Config:
+ """Configuration Manager for Strix."""
# LLM Configuration
strix_llm = None
@@ -187,6 +188,14 @@
def resolve_llm_config() -> tuple[str | None, str | None, str | None]:
+ """Resolve LLM model, api_key, and api_base based on STRIX_LLM prefix.
+
+ Return... | https://raw.githubusercontent.com/usestrix/strix/HEAD/strix/config/config.py |
Create docstrings for all classes and functions | import html
import re
from typing import Any
_INVOKE_OPEN = re.compile(r'<invoke\s+name=["\']([^"\']+)["\']>')
_PARAM_NAME_ATTR = re.compile(r'<parameter\s+name=["\']([^"\']+)["\']>')
_FUNCTION_CALLS_TAG = re.compile(r"</?function_calls>")
_STRIP_TAG_QUOTES = re.compile(r"<(function|parameter)\s*=\s*([^>]*?)>")
def... | --- +++ @@ -10,6 +10,16 @@
def normalize_tool_format(content: str) -> str:
+ """Convert alternative tool-call XML formats to the expected one.
+
+ Handles:
+ <function_calls>...</function_calls> → stripped
+ <invoke name="X"> → <function=X>
+ <parameter name="X"> ... | https://raw.githubusercontent.com/usestrix/strix/HEAD/strix/llm/utils.py |
Generate NumPy-style docstrings |
import enum
import os
import math
import textwrap
from PIL import Image, ImageFont, ImageDraw, ImageEnhance, ImageChops
import os
base_path = os.path.abspath(os.path.dirname(__file__))
class WatermarkerStyles(enum.Enum):
STRIPED = 1 # 斜向重复
CENTRAL = 2 # 居中
class Watermarker(object):
def __init__(
... | --- +++ @@ -1,3 +1,6 @@+"""
+Reference: https://gist.github.com/Deali-Axy/e22ea79bfbe785f9017b2e3cd7fdb3eb
+"""
import enum
import os
@@ -10,12 +13,14 @@
class WatermarkerStyles(enum.Enum):
+ """水印样式"""
STRIPED = 1 # 斜向重复
CENTRAL = 2 # 居中
class Watermarker(object):
+ """图片水印工具"""
... | https://raw.githubusercontent.com/Zeyi-Lin/HivisionIDPhotos/HEAD/hivision/plugin/watermark.py |
Add inline docstrings for readability |
import cv2
import math
import numpy as np
class TranslationWarp(object):
# 瘦脸
@staticmethod
def localTranslationWarp(srcImg, startX, startY, endX, endY, radius):
# 双线性插值法
def BilinearInsert(src, ux, uy):
w, h, c = src.shape
if c == 3:
x1 = int(ux)
... | --- +++ @@ -1,3 +1,12 @@+"""
+@author: cuny
+@file: ThinFace.py
+@time: 2022/7/2 15:50
+@description:
+瘦脸算法,用到了图像局部平移法
+先使用人脸关键点检测,然后再使用图像局部平移法
+需要注意的是,这部分不会包含dlib人脸关键点检测,因为考虑到模型载入的问题
+"""
import cv2
import math
@@ -5,6 +14,12 @@
class TranslationWarp(object):
+ """
+ 本类包含瘦脸算法,由于瘦脸算法包含了很多个版本,所以以类的方式呈现
+ ... | https://raw.githubusercontent.com/Zeyi-Lin/HivisionIDPhotos/HEAD/hivision/plugin/beauty/thin_face.py |
Write clean docstrings for readability | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import cv2
import numpy as np
def resize_image_esp(input_image, esp=2000):
# resize 函数=>可以让原图压缩到最大边为 esp 的尺寸 (不改变比例)
width = input_image.shape[0]
length = input_image.shape[1]
max_num = max(width, length)
if max_num > esp:
print("Image resizi... | --- +++ @@ -1,10 +1,22 @@ #!/usr/bin/env python
# -*- coding: utf-8 -*-
+r"""
+@DATE: 2024/9/5 19:25
+@File: utils.py
+@IDE: pycharm
+@Description:
+ 通用图像处理工具
+"""
import cv2
import numpy as np
def resize_image_esp(input_image, esp=2000):
+ """
+ 输入:
+ input_path:numpy 图片
+ esp:限制的最大边长
+ """
... | https://raw.githubusercontent.com/Zeyi-Lin/HivisionIDPhotos/HEAD/hivision/creator/utils.py |
Add docstrings to meet PEP guidelines |
import cv2
import numpy as np
def rotate_bound(image: np.ndarray, angle: float, center=None):
(h, w) = image.shape[:2]
if center is None:
(cX, cY) = (w / 2, h / 2)
else:
(cX, cY) = center
M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)
cos = np.abs(M[0, 0])
sin = np.abs(M[... | --- +++ @@ -1,9 +1,31 @@+"""
+人脸旋转矫正模块
+
+本模块提供了用于旋转图像的函数,主要用于人脸旋转矫正。
+包含了处理3通道和4通道图像的旋转函数。
+"""
import cv2
import numpy as np
def rotate_bound(image: np.ndarray, angle: float, center=None):
+ """
+ 旋转图像而不损失信息的函数
+
+ Args:
+ image (np.ndarray): 输入图像,3通道numpy数组
+ angle (float): 旋转角度(度)
+ ... | https://raw.githubusercontent.com/Zeyi-Lin/HivisionIDPhotos/HEAD/hivision/creator/rotation_adjust.py |
Add structured docstrings to improve clarity | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class FaceError(Exception):
def __init__(self, err, face_num):
super().__init__(err)
self.face_num = face_num
class APIError(Exception):
def __init__(self, err, status_code):
super().__init__(err)
self.status_code = status_code | --- +++ @@ -1,14 +1,33 @@ #!/usr/bin/env python
# -*- coding: utf-8 -*-
+r"""
+@DATE: 2024/9/5 18:32
+@File: error.py
+@IDE: pycharm
+@Description:
+ 错误处理
+"""
class FaceError(Exception):
def __init__(self, err, face_num):
+ """
+ 证件照人脸错误,此时人脸检测失败,可能是没有检测到人脸或者检测到多个人脸
+ Args:
+ ... | https://raw.githubusercontent.com/Zeyi-Lin/HivisionIDPhotos/HEAD/hivision/error.py |
Document this code for team use | import numpy as np
def decode(loc, priors, variances):
boxes = None
boxes = np.concatenate(
(
priors[:, :2] + loc[:, :2] * variances[0] * priors[:, 2:],
priors[:, 2:] * np.exp(loc[:, 2:] * variances[1]),
),
axis=1,
)
boxes[:, :2] -= boxes[:, 2:] / 2
... | --- +++ @@ -2,6 +2,17 @@
def decode(loc, priors, variances):
+ """Decode locations from predictions using priors to undo
+ the encoding we did for offset regression at train time.
+ Args:
+ loc (tensor): location predictions for loc layers,
+ Shape: [num_priors,4]
+ priors (tensor)... | https://raw.githubusercontent.com/Zeyi-Lin/HivisionIDPhotos/HEAD/hivision/creator/retinaface/box_utils.py |
Write docstrings for algorithm functions | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from .context import Context
from .layout_calculator import generate_layout_array
import hivision.creator.utils as U
import numpy as np
import math
import cv2
def adjust_photo(ctx: Context):
# Step1. 准备人脸参数
face_rect = ctx.face["rectangle"]
standard_size = ctx... | --- +++ @@ -1,5 +1,12 @@ #!/usr/bin/env python
# -*- coding: utf-8 -*-
+r"""
+@DATE: 2024/9/5 20:02
+@File: photo_adjuster.py
+@IDE: pycharm
+@Description:
+ 证件照调整
+"""
from .context import Context
from .layout_calculator import generate_layout_array
import hivision.creator.utils as U
@@ -124,6 +131,20 @@
de... | https://raw.githubusercontent.com/Zeyi-Lin/HivisionIDPhotos/HEAD/hivision/creator/photo_adjuster.py |
Help me write clear docstrings | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from typing import Tuple
import hivision.creator.utils as U
from .context import Context, ContextHandler, Params, Result
from .human_matting import extract_human
from .face_detector import detect_face_mtcnn
from hivision.plugin.beauty.handler import beaut... | --- +++ @@ -1,5 +1,12 @@ #!/usr/bin/env python
# -*- coding: utf-8 -*-
+r"""
+@DATE: 2024/9/5 16:45
+@File: __init__.py
+@IDE: pycharm
+@Description:
+ 创建证件照
+"""
import numpy as np
from typing import Tuple
import hivision.creator.utils as U
@@ -13,6 +20,9 @@
class IDCreator:
+ """
+ 证件照创建类,包含完整的证件照流程
... | https://raw.githubusercontent.com/Zeyi-Lin/HivisionIDPhotos/HEAD/hivision/creator/__init__.py |
Auto-generate documentation strings for this file | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from mtcnnruntime import MTCNN
except ImportError:
raise ImportError(
"Please install mtcnn-runtime by running `pip install mtcnn-runtime`"
)
from .context import Context
from hivision.error import FaceError, APIError
from hivision.utils import resi... | --- +++ @@ -1,5 +1,12 @@ #!/usr/bin/env python
# -*- coding: utf-8 -*-
+r"""
+@DATE: 2024/9/5 19:32
+@File: face_detector.py
+@IDE: pycharm
+@Description:
+ 人脸检测器
+"""
try:
from mtcnnruntime import MTCNN
except ImportError:
@@ -22,6 +29,12 @@
def detect_face_mtcnn(ctx: Context, scale: int = 2):
+ """
... | https://raw.githubusercontent.com/Zeyi-Lin/HivisionIDPhotos/HEAD/hivision/creator/face_detector.py |
Write docstrings that follow conventions | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from PIL import Image
import onnxruntime
from .tensor2numpy import NNormalize, NTo_Tensor, NUnsqueeze
from .context import Context
import cv2
import os
from time import time
WEIGHTS = {
"hivision_modnet": os.path.join(
os.path.dirname(__file... | --- +++ @@ -1,5 +1,12 @@ #!/usr/bin/env python
# -*- coding: utf-8 -*-
+r"""
+@DATE: 2024/9/5 21:21
+@File: human_matting.py
+@IDE: pycharm
+@Description:
+ 人像抠图
+"""
import numpy as np
from PIL import Image
import onnxruntime
@@ -70,6 +77,10 @@
def extract_human(ctx: Context):
+ """
+ 人像抠图
+ :param... | https://raw.githubusercontent.com/Zeyi-Lin/HivisionIDPhotos/HEAD/hivision/creator/human_matting.py |
Add docstrings for production code | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from PIL import Image
import io
import numpy as np
import cv2
import base64
from hivision.plugin.watermark import Watermarker, WatermarkerStyles
def save_image_dpi_to_bytes(image: np.ndarray, output_image_path: str = None, dpi: int = 300):
image = Image.fromarray(imag... | --- +++ @@ -9,6 +9,13 @@
def save_image_dpi_to_bytes(image: np.ndarray, output_image_path: str = None, dpi: int = 300):
+ """
+ 设置图像的DPI(每英寸点数)并返回字节流
+
+ :param image: numpy.ndarray, 输入的图像数组
+ :param output_image_path: Path to save the resized image. 保存调整大小后的图像的路径。
+ :param dpi: int, 要设置的DPI值,默认为300
... | https://raw.githubusercontent.com/Zeyi-Lin/HivisionIDPhotos/HEAD/hivision/utils.py |
Add well-formatted docstrings | import numpy as np
def NTo_Tensor(array):
output = array.transpose((2, 0, 1))
return output
def NNormalize(array, mean=np.array([0.5, 0.5, 0.5]), std=np.array([0.5, 0.5, 0.5]), dtype=np.float32):
im = array / 255.0
im = np.divide(np.subtract(im, mean), std)
output = np.asarray(im, dtype=dtype)
... | --- +++ @@ -1,12 +1,39 @@+"""
+作者:林泽毅
+建这个开源库的起源呢,是因为在做 onnx 推理的时候,需要将原来的 tensor 转换成 numpy.array
+问题是 Tensor 和 Numpy 的矩阵排布逻辑不同
+包括 Tensor 推理经常会进行 Transform,比如 ToTensor,Normalize 等
+就想做一些等价转换的函数。
+"""
import numpy as np
def NTo_Tensor(array):
+ """
+ :param array: opencv/PIL读取的numpy矩阵
+ :return:返回一个形如 Ten... | https://raw.githubusercontent.com/Zeyi-Lin/HivisionIDPhotos/HEAD/hivision/creator/tensor2numpy.py |
Add minimal docstrings for each function |
from .grind_skin import grindSkin
from .whitening import MakeWhiter
from .thin_face import thinFace
import numpy as np
def BeautyTools(
input_image: np.ndarray,
landmark,
thinStrength: int,
thinPlace: int,
grindStrength: int,
whiterStrength: int,
) -> np.ndarray:
try:
_, _, _ = in... | --- +++ @@ -1,3 +1,10 @@+"""
+@author: cuny
+@file: MakeBeautiful.py
+@time: 2022/7/7 20:23
+@description:
+美颜工具集合文件,作为暴露在外的插件接口
+"""
from .grind_skin import grindSkin
from .whitening import MakeWhiter
@@ -13,6 +20,18 @@ grindStrength: int,
whiterStrength: int,
) -> np.ndarray:
+ """
+ 美颜工具的接口函数,用于... | https://raw.githubusercontent.com/Zeyi-Lin/HivisionIDPhotos/HEAD/hivision/plugin/beauty/beauty_tools.py |
Add well-formatted docstrings | # Required Libraries
import cv2
import numpy as np
import gradio as gr
def annotate_image(image, grind_degree, detail_degree, strength):
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 0.5
color = (0, 0, 255)
thickness = 1
line_type = cv2.LINE_AA
# Text positions
y_offset = 20
x_offset =... | --- +++ @@ -5,6 +5,7 @@
def annotate_image(image, grind_degree, detail_degree, strength):
+ """Annotates the image with parameters in the lower-left corner."""
font = cv2.FONT_HERSHEY_SIMPLEX
font_scale = 0.5
color = (0, 0, 255)
@@ -41,6 +42,18 @@
def grindSkin(src, grindDegree: int = 3, detai... | https://raw.githubusercontent.com/Zeyi-Lin/HivisionIDPhotos/HEAD/hivision/plugin/beauty/grind_skin.py |
Create documentation strings for testing functions |
import cv2
import numpy as np
def adjust_brightness_contrast_sharpen_saturation(
image,
brightness_factor=0,
contrast_factor=0,
sharpen_strength=0,
saturation_factor=0,
):
if (
brightness_factor == 0
and contrast_factor == 0
and sharpen_strength == 0
and satura... | --- +++ @@ -1,3 +1,6 @@+"""
+亮度、对比度、锐化、饱和度调整模块
+"""
import cv2
import numpy as np
@@ -10,6 +13,19 @@ sharpen_strength=0,
saturation_factor=0,
):
+ """
+ 调整图像的亮度、对比度、锐度和饱和度。
+
+ 参数:
+ image (numpy.ndarray): 输入的图像数组。
+ brightness_factor (float): 亮度调整因子。大于0增加亮度,小于0降低亮度。
+ contrast_factor (f... | https://raw.githubusercontent.com/Zeyi-Lin/HivisionIDPhotos/HEAD/hivision/plugin/beauty/base_adjust.py |
Write docstrings that follow conventions | import ast
import pandas as pd
def _evaluate_node(df, node):
# Base Case: A simple comparison like 'price > 100'
if isinstance(node, ast.Compare):
if not isinstance(node.left, ast.Name):
raise ValueError("Left side of comparison must be a column name.")
col = node.left.id
... | --- +++ @@ -4,6 +4,9 @@
def _evaluate_node(df, node):
+ """
+ Recursively evaluates an AST node to generate a pandas boolean mask.
+ """
# Base Case: A simple comparison like 'price > 100'
if isinstance(node, ast.Compare):
if not isinstance(node.left, ast.Name):
@@ -68,6 +71,20 @@
de... | https://raw.githubusercontent.com/huggingface/peft/HEAD/method_comparison/sanitizer.py |
Create docstrings for API 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,12 @@
def get_peft_config(config_dict: dict[str, Any]) -> PeftConfig:
+ """
+ Returns a Peft config object from a dictionary.
+
+ Args:
+ config_dict (`Dict[str, Any]`): Dictionary containing the configuration parameters.
+ """
return PEFT_TYPE_TO_CONFIG_MAPPING[config... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/mapping.py |
Create structured documentation for my script | # 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.
+"""
+All utilities related to data handling.
+"""
from collections.abc import Callable
from functools import partial
@@ -30,6 +33,13 @@
def get_filtered_dataset(*, ds: datasets.Da... | https://raw.githubusercontent.com/huggingface/peft/HEAD/method_comparison/MetaMathQA/data.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... | --- +++ @@ -12,6 +12,9 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""
+Data handling utilities for PEFT benchmarking.
+"""
import json
import os
@@ -25,6 +28,15 @@
def load_test_prompts(config: dict) -> dict[str, list[str]]:
+ """
+ Load p... | https://raw.githubusercontent.com/huggingface/peft/HEAD/method_comparison/text_generation_benchmark/data.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... | --- +++ @@ -26,6 +26,23 @@
def update_forward_signature(model: PeftModel) -> None:
+ """
+ Updates the forward signature of the PeftModel to include parents class signature
+ model (`PeftModel`): Peft model to update the forward signature
+
+ Example:
+
+ ```python
+ >>> from transformers impo... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/helpers.py |
Create docstrings for reusable components | # 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... | --- +++ @@ -50,6 +50,12 @@ *,
num_virtual_tokens: int,
) -> torch.Tensor:
+ """
+ Convert a (legacy) `past_key_values` cache into the flattened prompt embeddings tensor saved by PEFT.
+
+ The output matches the layout expected by `PeftModel.get_prompt()` for prefix-style prompt learning: shape
+ `... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/cartridge/utils.py |
Add concise docstrings to each method | # 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... | --- +++ @@ -109,6 +109,18 @@ self.update_layer(adapter_name, r, lora_alpha, config=config)
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 (`... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/adalora/layer.py |
Add docstrings to improve code quality | # 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.
+"""
+This module contains the implementation of the LoRA-FA optimizer.
+"""
from __future__ import annotations
@@ -29,6 +32,26 @@
class LoraFAOptimizer(Optimizer):
+ """
+ ... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/optimizers/lorafa.py |
Create docstrings for all classes and 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... | --- +++ @@ -35,6 +35,12 @@
def _check_and_remove_unused_kwargs(cls, kwargs):
+ """Make PEFT configs forward-compatible by removing unused kwargs that were added in later PEFT versions.
+
+ This assumes that removing the unused kwargs will not affect the default behavior.
+
+ Returns the filtered kwargs and... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/config.py |
Create documentation for each function signature | # 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 training code.
+"""
import argparse
import datetime as dt
@@ -99,6 +102,13 @@
@torch.inference_mo... | https://raw.githubusercontent.com/huggingface/peft/HEAD/method_comparison/MetaMathQA/run.py |
Document helper functions with docstrings |
import sys
from datetime import datetime as dt
from huggingface_hub import scan_cache_dir
def find_old_revisions(scan_results, max_age_days=30):
now = dt.now()
revisions = [(i.revisions, i.last_accessed) for i in scan_results.repos]
revisions_ages = [(rev, (now - dt.fromtimestamp(ts_access)).days) for r... | --- +++ @@ -1,3 +1,13 @@+"""
+Utility to clean cache files that exceed a specific time in days according to their
+last access time recorded in the cache.
+
+Exit code:
+- 1 if no candidates are found
+- 0 if candidates are found
+
+Deletion can be enabled by passing `-d` parameter, otherwise it will only list the cand... | https://raw.githubusercontent.com/huggingface/peft/HEAD/scripts/ci_clean_cache.py |
Please document this code using 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... | --- +++ @@ -70,6 +70,36 @@
class PeftModel(PushToHubMixin, torch.nn.Module):
+ """
+ Base model encompassing various Peft methods.
+
+ Args:
+ model ([`~transformers.PreTrainedModel`]): The base transformer model used for Peft.
+ peft_config ([`PeftConfig`]): The configuration of the Peft mod... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/peft_model.py |
Please document this code using docstrings | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# Adapted from https://botorch.org/api/_modules/botorch/utils/torch.html
# TODO: To be removed once (if) https://github.com/pytorch/pytorch... | --- +++ @@ -17,8 +17,43 @@
class BufferDict(Module):
+ r"""
+ Holds buffers in a dictionary.
+
+ BufferDict can be indexed like a regular Python dictionary, but buffers it contains are properly registered, and
+ will be visible by all Module methods. `torch.nn.BufferDict` is an **ordered** dictionary th... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/_buffer_dict.py |
Add docstrings to meet PEP guidelines | # 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,8 +21,21 @@
class CPTEmbedding(torch.nn.Module):
+ """
+ CPTEmbedding is a custom embedding layer designed for Context-aware Prompt Tuning (CPT) in PEFT. It initializes
+ embeddings, applies prompt-specific projections, and computes loss using label masks.
+ """
def __init__(self, ... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/cpt/model.py |
Annotate my code with 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... | --- +++ @@ -62,6 +62,7 @@ def _compute_delta(
A: torch.Tensor, B: torch.Tensor, delora_lambda: torch.Tensor, r: int, w_norm: torch.Tensor
) -> torch.Tensor:
+ """Compute delta = B @ diag(delora_lambda/r / (||A_i||*||B^j||)) @ A, scaled by provided w_norm (per-input channel)"""
An = tor... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/delora/layer.py |
Add docstrings to improve code quality | # 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,7 @@
@dataclass
class AdaptionPromptConfig(PeftConfig):
+ """Stores the configuration of an [`AdaptionPromptModel`]."""
target_modules: str = field(
default=None, metadata={"help": "Name of the attention submodules to insert adaption prompts into."}
@@ -36,6 +37,7 @@
@pr... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/adaption_prompt/config.py |
Generate docstrings for each module | # 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,41 @@
class IA3Model(BaseTuner):
+ """
+ Creates a Infused Adapter by Inhibiting and Amplifying Inner Activations ((IA)^3) model from a pretrained
+ transformers model. The method is described in detail in https://huggingface.co/papers/2205.05638
+
+ Args:
+ model ([`~transfo... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/ia3/model.py |
Generate documentation strings for clarity | # 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... | --- +++ @@ -23,6 +23,9 @@
class LNTuningLayer(nn.Module, BaseTunerLayer):
+ """
+ Selects a layer from the model.
+ """
adapter_layer_names = ("ln_tuning_layers",)
@@ -43,6 +46,13 @@ self.set_adapter(adapter_name, inference_mode=inference_mode)
def enable_adapters(self, enabled: boo... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/ln_tuning/layer.py |
Annotate my code with 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... | --- +++ @@ -178,6 +178,18 @@ self.update_layer(adapter_name, module_name, r, alpha, gralora_dropout, gralora_k, hybrid_r, init_weights)
def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
+ """
+ Merge the active adapter weights into the base weight... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/gralora/layer.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... | --- +++ @@ -12,6 +12,9 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""
+Utilities for PEFT benchmarking.
+"""
import datetime
import json
@@ -37,6 +40,7 @@
class BenchmarkStatus(Enum):
+ """Status of a benchmark run."""
SUCCESS = "succe... | https://raw.githubusercontent.com/huggingface/peft/HEAD/method_comparison/text_generation_benchmark/utils.py |
Write docstrings for data processing 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... | --- +++ @@ -124,6 +124,18 @@ self.update_layer(adapter_name, block_size, 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_merge (`bool... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/c3a/layer.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... | --- +++ @@ -58,6 +58,14 @@ inference_mode: bool = False,
**kwargs,
) -> None:
+ """Internal function to create hra 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/hra/layer.py |
Add missing documentation to my Python 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... | --- +++ @@ -116,6 +116,18 @@ self.update_layer(adapter_name, n_frequency, scaling, init_weights, random_loc_seed)
def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
+ """
+ Merge the active adapter weights into the base weights
+
+ Args:
+ ... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/fourierft/layer.py |
Annotate my code with 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... | --- +++ @@ -44,6 +44,7 @@
def run_base_model_benchmark(benchmark_config: BenchmarkConfig, print_fn=print) -> dict:
+ """Run benchmark for base model only and return results."""
print_fn(f"Running base model benchmark for: {benchmark_config.model_id}")
@@ -121,6 +122,7 @@
def save_base_results(result... | https://raw.githubusercontent.com/huggingface/peft/HEAD/method_comparison/text_generation_benchmark/run_base.py |
Document all endpoints 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... | --- +++ @@ -34,6 +34,33 @@
class AdaLoraModel(LoraModel):
+ """
+ Creates AdaLoRA (Adaptive LoRA) model from a pretrained transformers model. Paper:
+ https://openreview.net/forum?id=lq62uWRJjiY
+
+ Args:
+ model ([`transformers.PreTrainedModel`]): The model to be adapted.
+ config ([`AdaL... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/adalora/model.py |
Add well-formatted 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... | --- +++ @@ -28,6 +28,10 @@
def get_target_modules(model: nn.Module, config: LoraConfig):
+ """
+ Iterate over LoRA-GA 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.named_modules():... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/lora/loraga.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... | --- +++ @@ -12,6 +12,9 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""
+This module contains the implementation of the LoraPlus optimizer.
+"""
from __future__ import annotations
@@ -29,6 +32,31 @@ def create_loraplus_optimizer(
model: PeftMode... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/optimizers/loraplus.py |
Write beginner-friendly 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... | --- +++ @@ -55,11 +55,31 @@
class MixedModel(BaseTuner):
+ """
+ A class that allows to mix different types of adapters in a single model.
+
+ Note: This class should usually not be initialized directly. Instead, use `get_peft_model` with the argument
+ `mixed=True`.
+
+ Args:
+ model (:obj:`n... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/mixed/model.py |
Create structured documentation for my 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... | --- +++ @@ -31,6 +31,12 @@
class LoraParallelLinear(nn.Module, LoraLayer):
+ """
+ When the target layer parallel_linear is RowParallelLinear, in order to keep the input and output shapes
+ consistent, we need to split the lora matrix A into rows, and the lora_B at this time should be a complete linear
+ ... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/lora/tp_layer.py |
Write clean 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... | --- +++ @@ -33,6 +33,9 @@
@dataclass
class LycorisConfig(PeftConfig):
+ r"""
+ A base config for LyCORIS like adapters
+ """
rank_pattern: Optional[dict] = field(
default_factory=dict,
@@ -55,6 +58,9 @@
class LycorisLayer(BaseTunerLayer):
+ r"""
+ A base layer for LyCORIS like adap... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/lycoris_utils.py |
Add professional docstrings to my codebase | # 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... | --- +++ @@ -110,6 +110,18 @@ inference_mode: bool = False,
**kwargs,
) -> None:
+ """Internal function to create loha adapter
+
+ Args:
+ adapter_name (`str`): Name for the adapter to add.
+ r (`int`): Rank for the added adapter.
+ alpha (`float`): Al... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/loha/layer.py |
Create Google-style docstrings for my 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... | --- +++ @@ -12,6 +12,9 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""
+All utilities not related to data handling.
+"""
import enum
import json
@@ -66,6 +69,28 @@
@dataclass
class TrainConfig:
+ """All configuration parameters associated with ... | https://raw.githubusercontent.com/huggingface/peft/HEAD/method_comparison/MetaMathQA/utils.py |
Generate descriptive docstrings automatically | # 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... | --- +++ @@ -37,6 +37,22 @@ # this function is a 1:1 copy from accelerate
@contextmanager
def patch_environment(**kwargs):
+ """
+ A context manager that will add each keyword argument passed to `os.environ` and remove them when exiting.
+
+ Will convert the values in `kwargs` to strings and upper-case all th... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/boft/layer.py |
Generate consistent docstrings | # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: LicenseRef-Apache2
#
# 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 a... | --- +++ @@ -29,6 +29,13 @@
class TeLinear(torch.nn.Module, LoraLayer):
+ """LoRA layer for TransformerEngine linear modules.
+
+ Supports ``te.pytorch.Linear``, ``te.pytorch.LayerNormLinear``, and ``te.pytorch.LayerNormMLP`` as base layers.
+
+ Note:
+ Adapter weight merging (``merge`` / ``unmerge``... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/lora/te.py |
Document helper functions 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... | --- +++ @@ -43,20 +43,33 @@
class LoraVariant:
+ """
+ Base class for LoRA variants, e.g. DoRA.
+
+ This class should be subclassed and the methods below should be implemented accordingly. The methods should be
+ implemented as static methods, this makes it easier to combine variants.
+
+ Note for de... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/lora/layer.py |
Provide clean and structured docstrings | #!/usr/bin/env python3
# Copyright (c) 2025 Your Organization/Project. All rights reserved.
#
# 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
... | --- +++ @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and
# limitations under the License.
+"""Convert Bone checkpoint to MiSS format."""
import argparse
import json
@@ -26,6 +27,7 @@
def convert_bone_to_miss(bone_dir: Path, miss_dir: Path) -> None:
+ """Convert Bone ... | https://raw.githubusercontent.com/huggingface/peft/HEAD/scripts/convert-bone-to-miss.py |
Write clean 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... | --- +++ @@ -26,6 +26,49 @@
@dataclass
class OFTConfig(PeftConfig):
+ """
+ This is the configuration class to store the configuration of a [`OFTModel`].
+
+ Args:
+ r (`int`): OFT rank, number of OFT blocks per injected layer.
+ oft_block_size (`int`): OFT block size across different layers.
+... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/oft/config.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... | --- +++ @@ -25,6 +25,62 @@
class LoHaModel(LycorisTuner):
+ """
+ Creates Low-Rank Hadamard Product model from a pretrained model. The method is partially described in
+ https://huggingface.co/papers/2108.06098 Current implementation heavily borrows from
+ https://github.com/KohakuBlueleaf/LyCORIS/blob/... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/loha/model.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... | --- +++ @@ -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/bnb.py |
Annotate my code with docstrings | import os
import cv2
import numpy as np
from hivisionai.hycv.utils import get_box_pro
path_pre = os.path.join(os.getcwd(), 'pre')
path_final = os.path.join(os.getcwd(), 'final')
def merge(boxes):
x, y, h, w = boxes[0]
# x 和 y 应该是整个 boxes 里面最小的值
if len(boxes) > 1:
for tmp in boxes:
x_t... | --- +++ @@ -1,3 +1,7 @@+"""
+有一些 png 图像下部也会有一些透明的区域,使得图像无法对其底部边框
+本程序实现移动图像,使其下部与 png 图像实际大小相对齐
+"""
import os
import cv2
import numpy as np
@@ -8,6 +12,9 @@
def merge(boxes):
+ """
+ 生成的边框可能不止只有一个,需要将边框合并
+ """
x, y, h, w = boxes[0]
# x 和 y 应该是整个 boxes 里面最小的值
if len(boxes) > 1:
@@ -25,6 ... | https://raw.githubusercontent.com/Zeyi-Lin/HivisionIDPhotos/HEAD/hivision/creator/move_image.py |
Generate missing documentation strings | # 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... | --- +++ @@ -28,6 +28,9 @@
class ArrowLoraLinearLayer(nn.Module):
+ """
+ This class represent the main logic of the arrow routing algorithm for linear layers.
+ """
def __init__(self, in_features, arrow_config):
super().__init__()
@@ -51,6 +54,10 @@
@torch.no_grad()
def on_adapte... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/lora/arrow.py |
Add docstrings for internal 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... | --- +++ @@ -25,6 +25,63 @@
class LoKrModel(LycorisTuner):
+ """
+ Creates Low-Rank Kronecker Product model from a pretrained model. The original method is partially described in
+ https://huggingface.co/papers/2108.06098 and in https://huggingface.co/papers/2309.14859 Current implementation
+ heavily bo... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/lokr/model.py |
Expand my code with proper documentation strings | from __future__ import annotations
import re
import torch
import torch.nn as nn
from peft.tuners.tuners_utils import BaseTuner
from peft.utils.constants import TRANSFORMERS_MODELS_TO_OSF_TARGET_MODULES_MAPPING
from .layer import OSFLayer, dispatch_default
class OSFModel(BaseTuner):
prefix: str = "osf_"
t... | --- +++ @@ -12,6 +12,7 @@
class OSFModel(BaseTuner):
+ """A minimal tuner implementing Orthogonal Subspace Fine-tuning."""
prefix: str = "osf_"
tuner_layer_cls = OSFLayer
@@ -35,6 +36,11 @@ )
def __getattr__(self, name: str):
+ """Forward missing attributes to the wrapped base m... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/osf/model.py |
Add docstrings to improve readability | # 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... | --- +++ @@ -39,6 +39,9 @@
class _Hook:
+ """
+ A base class for hooks that prepares layer inputs for EVA.
+ """
def __init__(
self,
@@ -101,6 +104,20 @@
class SVDHook(_Hook):
+ """
+ A forward hook for calculating incremental SVD on layer inputs. The hook is designed to be registe... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/lora/eva.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... | --- +++ @@ -11,6 +11,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
+"""Utilities for Orthogonal Subspace Learning with Adaptive OSF."""
from __future__ import annotations
@@ -3... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/osf/utils.py |
Please document this code using 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,8 +23,18 @@
class _BaseAdaptedAttention(nn.Module):
+ """Base module, which defines adaption prompts for multiple model types."""
def __init__(self, model_type: str, adapter_len: int, model, target_dtype=torch.float32):
+ """
+ Initialize object.
+
+ Args:
+ ... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/adaption_prompt/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... | --- +++ @@ -169,6 +169,19 @@ inference_mode: bool = False,
**kwargs,
) -> None:
+ """Internal function to create lokr adapter
+
+ Args:
+ adapter_name (`str`): Name for the adapter to add.
+ r (`int`): Rank for the added adapter.
+ alpha (`float`): Al... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/lokr/layer.py |
Document this script properly | # 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... | --- +++ @@ -40,9 +40,24 @@ super().__init__(base_layer, adapter_name, config=config, **kwargs)
def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
+ """
+ Merge the active adapter weights into the base weights
+
+ Args:
+ ... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/lora/inc.py |
Provide docstrings following PEP 257 | # 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... | --- +++ @@ -38,9 +38,24 @@ super().__init__(base_layer, adapter_name, **kwargs)
def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None:
+ """
+ Merge the active adapter weights into the base weights
+
+ Args:
+ ... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/oft/inc.py |
Add docstrings that explain purpose and usage | # 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... | --- +++ @@ -18,6 +18,16 @@
class CartridgeEncoder(torch.nn.Module):
+ """
+ A parameterized prefix KV cache.
+
+ The parameters are stored in the same flattened layout as `PrefixEncoder` output: `[num_virtual_tokens, num_layers
+ * 2 * token_dim]`, where `token_dim` is per-head hidden size times number ... | https://raw.githubusercontent.com/huggingface/peft/HEAD/src/peft/tuners/cartridge/model.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.