code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def list_models(path):
"""
Lists all model files in the given directory.
Args:
path (str): The directory path to search for model files.
Returns:
list: A list of model file paths.
"""
nonlocal current_model_dir
current_model_dir = path
re... |
Lists all model files in the given directory.
Args:
path (str): The directory path to search for model files.
Returns:
list: A list of model file paths.
| list_models | python | bmaltais/kohya_ss | kohya_gui/convert_lcm_gui.py | https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/convert_lcm_gui.py | Apache-2.0 |
def list_save_to(path):
"""
Lists all save-to options for the given directory.
Args:
path (str): The directory path to search for save-to options.
Returns:
list: A list of save-to options.
"""
nonlocal current_save_dir
current_save_dir = path
... |
Lists all save-to options for the given directory.
Args:
path (str): The directory path to search for save-to options.
Returns:
list: A list of save-to options.
| list_save_to | python | bmaltais/kohya_ss | kohya_gui/convert_lcm_gui.py | https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/convert_lcm_gui.py | Apache-2.0 |
def _get_caption_path(image_file, images_dir, caption_ext):
"""
Returns the expected path of a caption file for a given image path
"""
caption_file_name = os.path.splitext(image_file)[0] + caption_ext
caption_file_path = os.path.join(images_dir, caption_file_name)
return caption_file_path |
Returns the expected path of a caption file for a given image path
| _get_caption_path | python | bmaltais/kohya_ss | kohya_gui/manual_caption_gui.py | https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/manual_caption_gui.py | Apache-2.0 |
def _get_quick_tags(quick_tags_text):
"""
Gets a list of tags from the quick tags text box
"""
quick_tags = [t.strip() for t in quick_tags_text.split(",") if t.strip()]
quick_tags_set = set(quick_tags)
return quick_tags, quick_tags_set |
Gets a list of tags from the quick tags text box
| _get_quick_tags | python | bmaltais/kohya_ss | kohya_gui/manual_caption_gui.py | https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/manual_caption_gui.py | Apache-2.0 |
def _get_tag_checkbox_updates(caption, quick_tags, quick_tags_set):
"""
Updates a list of caption checkboxes to show possible tags and tags
already included in the caption
"""
caption_tags_have = [c.strip() for c in caption.split(",") if c.strip()]
caption_tags_unique = [t for t in caption_tags_... |
Updates a list of caption checkboxes to show possible tags and tags
already included in the caption
| _get_tag_checkbox_updates | python | bmaltais/kohya_ss | kohya_gui/manual_caption_gui.py | https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/manual_caption_gui.py | Apache-2.0 |
def import_tags_from_captions(
images_dir, caption_ext, quick_tags_text, ignore_load_tags_word_count
):
"""
Scans images directory for all available captions and loads all tags
under a specified word count into the quick tags box
"""
def empty_return():
return gr.Text()
# Check for... |
Scans images directory for all available captions and loads all tags
under a specified word count into the quick tags box
| import_tags_from_captions | python | bmaltais/kohya_ss | kohya_gui/manual_caption_gui.py | https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/manual_caption_gui.py | Apache-2.0 |
def load_images(images_dir, caption_ext, loaded_images_dir, page, max_page):
"""
Triggered to load a new set of images from the folder to caption
This loads in the total expected image counts to be used by pagination
before running update_images
"""
def empty_return():
return [loaded_im... |
Triggered to load a new set of images from the folder to caption
This loads in the total expected image counts to be used by pagination
before running update_images
| load_images | python | bmaltais/kohya_ss | kohya_gui/manual_caption_gui.py | https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/manual_caption_gui.py | Apache-2.0 |
def update_images(
images_dir,
caption_ext,
quick_tags_text,
page,
):
"""
Updates the displayed images and captions from the current page and
image directory
"""
# Load Images
images_list = os.listdir(images_dir)
image_files = [f for f in images_list if f.lower().endswith(IM... |
Updates the displayed images and captions from the current page and
image directory
| update_images | python | bmaltais/kohya_ss | kohya_gui/manual_caption_gui.py | https://github.com/bmaltais/kohya_ss/blob/master/kohya_gui/manual_caption_gui.py | Apache-2.0 |
def check_python_version():
"""
Check if the current Python version is within the acceptable range.
Returns:
bool: True if the current Python version is valid, False otherwise.
"""
log.debug("Checking Python version...")
try:
current_version = sys.version_info
log.info(f"... |
Check if the current Python version is within the acceptable range.
Returns:
bool: True if the current Python version is valid, False otherwise.
| check_python_version | python | bmaltais/kohya_ss | setup/setup_common.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/setup_common.py | Apache-2.0 |
def update_submodule(quiet=True):
"""
Ensure the submodule is initialized and updated.
"""
log.debug("Updating submodule...")
git_command = ["git", "submodule", "update", "--init", "--recursive"]
if quiet:
git_command.append("--quiet")
try:
subprocess.run(git_command, check=... |
Ensure the submodule is initialized and updated.
| update_submodule | python | bmaltais/kohya_ss | setup/setup_common.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/setup_common.py | Apache-2.0 |
def clone_or_checkout(repo_url, branch_or_tag, directory_name):
"""
Clone a repo or checkout a specific branch or tag if the repo already exists.
"""
log.debug(
f"Cloning or checking out repository: {repo_url}, branch/tag: {branch_or_tag}, directory: {directory_name}"
)
original_dir = os... |
Clone a repo or checkout a specific branch or tag if the repo already exists.
| clone_or_checkout | python | bmaltais/kohya_ss | setup/setup_common.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/setup_common.py | Apache-2.0 |
def setup_logging():
"""
Set up logging to file and console.
"""
log.debug("Setting up logging...")
from rich.theme import Theme
from rich.logging import RichHandler
from rich.console import Console
console = Console(
log_time=True,
log_time_format="%H:%M:%S-%f",
... |
Set up logging to file and console.
| setup_logging | python | bmaltais/kohya_ss | setup/setup_common.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/setup_common.py | Apache-2.0 |
def check_repo_version():
"""
This function checks the version of the repository by reading the contents of a file named '.release'
in the current directory. If the file exists, it reads the release version from the file and logs it.
If the file does not exist, it logs a debug message indicating that th... |
This function checks the version of the repository by reading the contents of a file named '.release'
in the current directory. If the file exists, it reads the release version from the file and logs it.
If the file does not exist, it logs a debug message indicating that the release could not be read.
| check_repo_version | python | bmaltais/kohya_ss | setup/setup_common.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/setup_common.py | Apache-2.0 |
def pip(arg: str, ignore: bool = False, quiet: bool = False, show_stdout: bool = False):
"""
Executes a pip command with the specified arguments.
This function is designed to run pip commands and handle their output.
It can be used to install, upgrade, or uninstall packages using pip.
If an error o... |
Executes a pip command with the specified arguments.
This function is designed to run pip commands and handle their output.
It can be used to install, upgrade, or uninstall packages using pip.
If an error occurs during the pip operation and the 'ignore' flag is not set,
it logs the error message a... | pip | python | bmaltais/kohya_ss | setup/setup_common.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/setup_common.py | Apache-2.0 |
def installed(package, friendly: str = None):
"""
Checks if the specified package(s) are installed with the correct version.
This function can handle package specifications with or without version constraints,
and can also filter out command-line options and URLs when a 'friendly' string is provided.
... |
Checks if the specified package(s) are installed with the correct version.
This function can handle package specifications with or without version constraints,
and can also filter out command-line options and URLs when a 'friendly' string is provided.
Parameters:
- package: A string that specifies... | installed | python | bmaltais/kohya_ss | setup/setup_common.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/setup_common.py | Apache-2.0 |
def install(
package,
friendly: str = None,
ignore: bool = False,
reinstall: bool = False,
show_stdout: bool = False,
):
"""
Installs or upgrades a Python package using pip, with options to ignode errors,
reinstall packages, and display outputs.
Parameters:
- package (str): The ... |
Installs or upgrades a Python package using pip, with options to ignode errors,
reinstall packages, and display outputs.
Parameters:
- package (str): The name of the package to be installed or upgraded. Can include
version specifiers. Anything after a '#' in the package name will be ignored.
... | install | python | bmaltais/kohya_ss | setup/setup_common.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/setup_common.py | Apache-2.0 |
def install_requirements(
requirements_file, check_no_verify_flag=False, show_stdout: bool = False
):
"""
Install or verify modules from a requirements file.
Parameters:
- requirements_file (str): Path to the requirements file.
- check_no_verify_flag (bool): If True, verify modules installation... |
Install or verify modules from a requirements file.
Parameters:
- requirements_file (str): Path to the requirements file.
- check_no_verify_flag (bool): If True, verify modules installation status without installing.
- show_stdout (bool): If True, show the standard output of the installation proce... | install_requirements | python | bmaltais/kohya_ss | setup/setup_common.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/setup_common.py | Apache-2.0 |
def sync_bits_and_bytes_files():
"""
Check for "different" bitsandbytes Files and copy only if necessary.
This function is specific for Windows OS.
"""
# Only execute on Windows
if os.name != "nt":
print("This function is only applicable to Windows OS.")
return
try:
... |
Check for "different" bitsandbytes Files and copy only if necessary.
This function is specific for Windows OS.
| sync_bits_and_bytes_files | python | bmaltais/kohya_ss | setup/update_bitsandbytes.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/update_bitsandbytes.py | Apache-2.0 |
def check_path_with_space():
"""Check if the current working directory contains a space."""
cwd = os.getcwd()
log.debug(f"Current working directory: {cwd}")
if " " in cwd:
# Log an error if the current working directory contains spaces
log.error(
"The path in which this pytho... | Check if the current working directory contains a space. | check_path_with_space | python | bmaltais/kohya_ss | setup/validate_requirements.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/validate_requirements.py | Apache-2.0 |
def detect_toolkit():
"""Detect the available toolkit (NVIDIA, AMD, or Intel) and log the information."""
log.debug("Detecting available toolkit...")
# Check for NVIDIA toolkit by looking for nvidia-smi executable
if shutil.which("nvidia-smi") or os.path.exists(
os.path.join(
os.envi... | Detect the available toolkit (NVIDIA, AMD, or Intel) and log the information. | detect_toolkit | python | bmaltais/kohya_ss | setup/validate_requirements.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/validate_requirements.py | Apache-2.0 |
def check_torch():
"""Check if torch is available and log the relevant information."""
# Detect the available toolkit (e.g., NVIDIA, AMD, Intel, or CPU)
toolkit = detect_toolkit()
log.info(f"{toolkit} toolkit detected")
try:
# Import PyTorch
log.debug("Importing PyTorch...")
... | Check if torch is available and log the relevant information. | check_torch | python | bmaltais/kohya_ss | setup/validate_requirements.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/validate_requirements.py | Apache-2.0 |
def log_cuda_info(torch):
"""Log information about CUDA-enabled GPUs."""
# Log the CUDA and cuDNN versions if available
if torch.version.cuda:
log.info(
f'Torch backend: nVidia CUDA {torch.version.cuda} cuDNN {torch.backends.cudnn.version() if torch.backends.cudnn.is_available() else "N/... | Log information about CUDA-enabled GPUs. | log_cuda_info | python | bmaltais/kohya_ss | setup/validate_requirements.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/validate_requirements.py | Apache-2.0 |
def log_mps_info(torch):
"""Log information about Apple Silicone (MPS)"""
max_reccomended_mem = round(torch.mps.recommended_max_memory() / 1024**2)
log.info(
f"Torch detected Apple MPS: {max_reccomended_mem}MB Unified Memory Available"
)
log.warning('MPS support is still experimental, procee... | Log information about Apple Silicone (MPS) | log_mps_info | python | bmaltais/kohya_ss | setup/validate_requirements.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/validate_requirements.py | Apache-2.0 |
def log_xpu_info(torch, ipex):
"""Log information about Intel XPU-enabled GPUs."""
# Log the Intel Extension for PyTorch (IPEX) version if available
if ipex:
log.info(f"Torch backend: Intel IPEX {ipex.__version__}")
# Log information about each detected XPU-enabled GPU
for device in range(to... | Log information about Intel XPU-enabled GPUs. | log_xpu_info | python | bmaltais/kohya_ss | setup/validate_requirements.py | https://github.com/bmaltais/kohya_ss/blob/master/setup/validate_requirements.py | Apache-2.0 |
def writable_dir(target_path):
""" Check if a path is a valid directory and that it can be written to. """
path = Path(target_path)
if path.is_dir():
if os.access(path, os.W_OK):
return path
else:
raise argparse.ArgumentTypeError(f"Directory '{path}' is not writable."... | Check if a path is a valid directory and that it can be written to. | writable_dir | python | bmaltais/kohya_ss | tools/caption.py | https://github.com/bmaltais/kohya_ss/blob/master/tools/caption.py | Apache-2.0 |
def create_text_file(image_filename, output_directory, text_extension):
"""Create a text file with the same name as the image file."""
# Extract prompt from filename
prompt = Path(image_filename).stem
# Construct path for the output text file
text_file_path = Path(output_directory) / (prompt + text... | Create a text file with the same name as the image file. | create_text_file | python | bmaltais/kohya_ss | tools/caption_from_filename.py | https://github.com/bmaltais/kohya_ss/blob/master/tools/caption_from_filename.py | Apache-2.0 |
def writable_dir(target_path):
""" Check if a path is a valid directory and that it can be written to. """
path = Path(target_path)
if path.is_dir():
if os.access(path, os.W_OK):
return path
else:
raise argparse.ArgumentTypeError(f"Directory '{path}' is not writable."... | Check if a path is a valid directory and that it can be written to. | writable_dir | python | bmaltais/kohya_ss | tools/cleanup_captions.py | https://github.com/bmaltais/kohya_ss/blob/master/tools/cleanup_captions.py | Apache-2.0 |
def writable_dir(target_path):
""" Check if a path is a valid directory and that it can be written to. """
path = Path(target_path)
if path.is_dir():
if os.access(path, os.W_OK):
return path
else:
raise argparse.ArgumentTypeError(f"Directory '{path}' is not writable."... | Check if a path is a valid directory and that it can be written to. | writable_dir | python | bmaltais/kohya_ss | tools/convert_images_to_hq_jpg.py | https://github.com/bmaltais/kohya_ss/blob/master/tools/convert_images_to_hq_jpg.py | Apache-2.0 |
def writable_dir(target_path):
""" Check if a path is a valid directory and that it can be written to. """
path = Path(target_path)
if path.is_dir():
if os.access(path, os.W_OK):
return path
else:
raise argparse.ArgumentTypeError(f"Directory '{path}' is not writable."... | Check if a path is a valid directory and that it can be written to. | writable_dir | python | bmaltais/kohya_ss | tools/convert_images_to_webp.py | https://github.com/bmaltais/kohya_ss/blob/master/tools/convert_images_to_webp.py | Apache-2.0 |
def aspect_ratio(img_path):
"""
Calculate and return the aspect ratio of an image.
Parameters:
img_path: A string representing the path to the input image.
Returns:
float: Aspect ratio of the input image, defined as width / height.
Returns None if the image cannot be read.
... |
Calculate and return the aspect ratio of an image.
Parameters:
img_path: A string representing the path to the input image.
Returns:
float: Aspect ratio of the input image, defined as width / height.
Returns None if the image cannot be read.
| aspect_ratio | python | bmaltais/kohya_ss | tools/crop_images_to_n_buckets.py | https://github.com/bmaltais/kohya_ss/blob/master/tools/crop_images_to_n_buckets.py | Apache-2.0 |
def sort_images_by_aspect_ratio(path):
"""Sort all images in a folder by aspect ratio"""
images = []
for filename in os.listdir(path):
if filename.endswith(".jpg") or filename.endswith(".jpeg") or filename.endswith(".png") or filename.endswith(".webp"):
print(filename)
img_pa... | Sort all images in a folder by aspect ratio | sort_images_by_aspect_ratio | python | bmaltais/kohya_ss | tools/crop_images_to_n_buckets.py | https://github.com/bmaltais/kohya_ss/blob/master/tools/crop_images_to_n_buckets.py | Apache-2.0 |
def create_groups(sorted_images, n_groups):
"""
Create groups of images from a sorted list of images.
This function takes a sorted list of images and a group size as input, and returns a list of groups,
where each group contains a specified number of images.
Parameters:
sorted_images (list of ... |
Create groups of images from a sorted list of images.
This function takes a sorted list of images and a group size as input, and returns a list of groups,
where each group contains a specified number of images.
Parameters:
sorted_images (list of tuples): A list of tuples, where each tuple contain... | create_groups | python | bmaltais/kohya_ss | tools/crop_images_to_n_buckets.py | https://github.com/bmaltais/kohya_ss/blob/master/tools/crop_images_to_n_buckets.py | Apache-2.0 |
def average_aspect_ratio(group):
"""
Calculate the average aspect ratio for a given group of images.
Parameters:
group (list of tuples):, A list of tuples, where each tuple contains the path to an image and its aspect ratio.
Returns:
float: The average aspect ratio of the images in the group.
... |
Calculate the average aspect ratio for a given group of images.
Parameters:
group (list of tuples):, A list of tuples, where each tuple contains the path to an image and its aspect ratio.
Returns:
float: The average aspect ratio of the images in the group.
| average_aspect_ratio | python | bmaltais/kohya_ss | tools/crop_images_to_n_buckets.py | https://github.com/bmaltais/kohya_ss/blob/master/tools/crop_images_to_n_buckets.py | Apache-2.0 |
def center_crop_image(image, target_aspect_ratio):
"""Crop the input image to the target aspect ratio.
The function calculates the crop region for the input image based on its current aspect ratio and the target aspect ratio.
Args:
image: A numpy array representing the input image.
target_... | Crop the input image to the target aspect ratio.
The function calculates the crop region for the input image based on its current aspect ratio and the target aspect ratio.
Args:
image: A numpy array representing the input image.
target_aspect_ratio: A float representing the target aspect ratio... | center_crop_image | python | bmaltais/kohya_ss | tools/crop_images_to_n_buckets.py | https://github.com/bmaltais/kohya_ss/blob/master/tools/crop_images_to_n_buckets.py | Apache-2.0 |
def copy_related_files(img_path, save_path):
"""
Copy all files in the same directory as the input image that have the same base name as the input image to the
output directory with the corresponding new filename.
Args:
img_path (str): Path to the input image file.
save_path: Path to th... |
Copy all files in the same directory as the input image that have the same base name as the input image to the
output directory with the corresponding new filename.
Args:
img_path (str): Path to the input image file.
save_path: Path to the output directory where the files should be copied ... | copy_related_files | python | bmaltais/kohya_ss | tools/crop_images_to_n_buckets.py | https://github.com/bmaltais/kohya_ss/blob/master/tools/crop_images_to_n_buckets.py | Apache-2.0 |
def save_resized_cropped_images(group, folder_name, group_number, avg_aspect_ratio, use_original_name=False):
"""Crop and resize all images in the input group to the smallest resolution, and save them to a folder.
Args:
group: A list of tuples, where each tuple contains the path to an image and its asp... | Crop and resize all images in the input group to the smallest resolution, and save them to a folder.
Args:
group: A list of tuples, where each tuple contains the path to an image and its aspect ratio.
folder_name: A string representing the name of the folder to save the images to.
group_num... | save_resized_cropped_images | python | bmaltais/kohya_ss | tools/crop_images_to_n_buckets.py | https://github.com/bmaltais/kohya_ss/blob/master/tools/crop_images_to_n_buckets.py | Apache-2.0 |
def main():
"""Main method for building model from command line."""
empty_args = core.convert_build_args_to_argparser() # Create new ArgumentParser
parsed_args = empty_args.parse_args() # Parse through command line
# Post processing of arguments
parsed_args = core._parse_args(parsed_args) # pylin... | Main method for building model from command line. | main | python | llSourcell/Doctor-Dignity | mlc_llm/build.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/mlc_llm/build.py | Apache-2.0 |
def convert_build_args_to_argparser() -> argparse.ArgumentParser:
"""Convert from BuildArgs to an equivalent ArgumentParser."""
args = argparse.ArgumentParser()
for field in fields(BuildArgs):
name = field.name.replace("_", "-")
field_name = f"--{name}"
# `kwargs` contains `help`, `c... | Convert from BuildArgs to an equivalent ArgumentParser. | convert_build_args_to_argparser | python | llSourcell/Doctor-Dignity | mlc_llm/core.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/mlc_llm/core.py | Apache-2.0 |
def mod_transform_before_build(
mod: tvm.IRModule,
param_manager: param_manager.ParamManager,
args: argparse.Namespace,
config: Dict,
) -> tvm.IRModule:
"""First-stage: Legalize ops and trace"""
if args.model.startswith("minigpt"):
model_names = ["embed"]
else:
model_names = ... | First-stage: Legalize ops and trace | mod_transform_before_build | python | llSourcell/Doctor-Dignity | mlc_llm/core.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/mlc_llm/core.py | Apache-2.0 |
def build_model(args: BuildArgs) -> (Optional[str], Optional[str], Optional[str]):
r"""Builds/compiles a model.
Parameters
----------
args : :class:`BuildArgs`
A dataclass of arguments for building models.
Returns
----------
lib_path: Optional[str]
The path to the model lib... | Builds/compiles a model.
Parameters
----------
args : :class:`BuildArgs`
A dataclass of arguments for building models.
Returns
----------
lib_path: Optional[str]
The path to the model library file. Return ``None`` if not applicable.
model_path: Optional[str]
The pat... | build_model | python | llSourcell/Doctor-Dignity | mlc_llm/core.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/mlc_llm/core.py | Apache-2.0 |
def debug_dump_benchmark_script(
mod: tvm.ir.IRModule,
name: str,
args: argparse.Namespace,
) -> None:
"""Extract model level benchmark workloads from relax model."""
if not args.debug_dump:
return
from tvm.dlight.benchmark import ( # pylint: disable=import-error,import-outside-topleve... | Extract model level benchmark workloads from relax model. | debug_dump_benchmark_script | python | llSourcell/Doctor-Dignity | mlc_llm/utils.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/mlc_llm/utils.py | Apache-2.0 |
def tvm_callback_cuda_compile(code, target): # pylint: disable=unused-argument
"""use nvcc to generate fatbin code for better optimization"""
arch = []
for compute_version in compute_versions:
arch += ["-gencode", f"arch=compute_{compute_version},code=sm_{compute_ver... | use nvcc to generate fatbin code for better optimization | tvm_callback_cuda_compile | python | llSourcell/Doctor-Dignity | mlc_llm/utils.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/mlc_llm/utils.py | Apache-2.0 |
def get_loaded_tensor_info(
self, pname: str, param_info: relax.TensorStructInfo
) -> Tuple[List[str], List[relax.TensorStructInfo]]:
"""Returns the names and shapes and dtypes of the tensors that need to
be loaded from the disk.
It is useful when the parameter is pre-quantized. In ... | Returns the names and shapes and dtypes of the tensors that need to
be loaded from the disk.
It is useful when the parameter is pre-quantized. In such cases, we need
to know how many tensors the parameter is quantized into, and together
with the dtype and shape of each tensor, so that w... | get_loaded_tensor_info | python | llSourcell/Doctor-Dignity | mlc_llm/quantization/quantization.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/mlc_llm/quantization/quantization.py | Apache-2.0 |
def get_dequantize_func(
self,
param_info: relax.TensorStructInfo,
qparam_info: List[relax.TensorStructInfo],
) -> Optional[FQuantize]:
"""Returns the function which computes dequantization.
Returning `None` means the parameter does not need dequantization.
The retur... | Returns the function which computes dequantization.
Returning `None` means the parameter does not need dequantization.
The returned function takes a Relax BlockBuilder and a (list of)
quantized weight relax Var, computes the dequantization and returns the
result Relax Var(s).
Y... | get_dequantize_func | python | llSourcell/Doctor-Dignity | mlc_llm/quantization/quantization.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/mlc_llm/quantization/quantization.py | Apache-2.0 |
def get_param_quant_kind(
name: str, param_info: relax.TensorStructInfo
) -> ParamQuantKind:
"""No quantization for MiniGPT. Use q0f16 or q0f32 when building it."""
return ParamQuantKind.others | No quantization for MiniGPT. Use q0f16 or q0f32 when building it. | get_param_quant_kind | python | llSourcell/Doctor-Dignity | mlc_llm/relax_model/minigpt.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/mlc_llm/relax_model/minigpt.py | Apache-2.0 |
def register_params(
self,
model: nn.Module,
func_name: str,
quantization_scheme: quantization.QuantizationScheme,
f_get_param_quant_kind: Callable[
[str, relax.TensorStructInfo], quantization.ParamQuantKind
],
) -> None:
"""Register the parameters... | Register the parameters of the input model (within the context of the
input function) in the parameter manager.
Parameters
----------
model : nn.Module
The input model whose parameters are registered.
func_name : str
The name of the function the input mo... | register_params | python | llSourcell/Doctor-Dignity | mlc_llm/relax_model/param_manager.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/mlc_llm/relax_model/param_manager.py | Apache-2.0 |
def set_param_loading_func(
self,
model_path: str,
use_safetensors: bool,
f_convert_pname_fwd: Callable[[str], List[str]] = lambda pname: [pname],
f_convert_param_bkwd: Callable[
[str, Any], Optional[List[Tuple[str, Any]]]
] = lambda pname, torch_param: [(pnam... | Set the parameter loading functions.
Parameters
----------
model_path : str
The path of the Hugging Face model on disk.
use_safetensors : bool
Whether to use ``.safetensors`` instead of ``.bin`` to load model.
f_convert_pname_fwd : Callable[[str], List[... | set_param_loading_func | python | llSourcell/Doctor-Dignity | mlc_llm/relax_model/param_manager.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/mlc_llm/relax_model/param_manager.py | Apache-2.0 |
def transform_dequantize(self, mod: tvm.IRModule) -> tvm.IRModule:
"""Apply dequantization to the input IRModule.
Parameters
----------
mod : tvm.IRModule
The input IRModule to be applied dequantization.
The IRModule contains all the constructed Relax functions
... | Apply dequantization to the input IRModule.
Parameters
----------
mod : tvm.IRModule
The input IRModule to be applied dequantization.
The IRModule contains all the constructed Relax functions
(e.g., the "prefill"/"decode" functions) and is expected to
... | transform_dequantize | python | llSourcell/Doctor-Dignity | mlc_llm/relax_model/param_manager.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/mlc_llm/relax_model/param_manager.py | Apache-2.0 |
def get_param_loading_functions(
self,
model_params: List[Optional[tvm.nd.NDArray]],
loaded_params: List[tvm.nd.NDArray],
loaded_idx_set: Set[int],
loaded_torch_bins: Set[str],
cached_relax_params: Dict[int, tvm.nd.NDArray],
cached_torch_params: Dict[str, Any],
... | A wrapper function which returns the `get_item` and `set_item`
functions for parameter lazy loading.
Parameters
----------
model_params : List[Optional[tvm.nd.NDArray]]
The pre-loaded model parameters, for which we skip lazy loading.
loaded_params : List[tvm.nd.NDAr... | get_param_loading_functions | python | llSourcell/Doctor-Dignity | mlc_llm/relax_model/param_manager.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/mlc_llm/relax_model/param_manager.py | Apache-2.0 |
def _register_param(
self,
name: str,
var: relax.Var,
quant_spec: quantization.QuantizationSpec,
func_name: str,
) -> Parameter:
"""Register a single parameter in the parameter manager.
In most cases, this method is not directly used outside this class:
... | Register a single parameter in the parameter manager.
In most cases, this method is not directly used outside this class:
it is called by `register_params` above.
Parameters
----------
name : str
The name of the parameter to register.
Name serves as the u... | _register_param | python | llSourcell/Doctor-Dignity | mlc_llm/relax_model/param_manager.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/mlc_llm/relax_model/param_manager.py | Apache-2.0 |
def _dequantize(
self,
param: Parameter,
quantized_tuple: relax.Var,
bb: relax.BlockBuilder,
qparams: List[relax.Var] = None,
) -> relax.Var:
"""Applying dequantization to the input parameter.
This method is called by `transform_module` below, and is not
... | Applying dequantization to the input parameter.
This method is called by `transform_module` below, and is not
directly invoked outside the class.
Parameters
----------
param : Parameter
The parameter whose quantized tensors are to be dequantized.
quantized_t... | _dequantize | python | llSourcell/Doctor-Dignity | mlc_llm/relax_model/param_manager.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/mlc_llm/relax_model/param_manager.py | Apache-2.0 |
def load_torch_pname2binname_map(
model_path: str,
use_safetensors: bool,
relax_pnames: Set[str],
f_convert_pname_fwd: Callable[[str], List[str]] = lambda pname: [pname],
) -> Dict[str, str]:
"""Constructing the dictionary from each torch parameter's name to
the name of the binary shard where th... | Constructing the dictionary from each torch parameter's name to
the name of the binary shard where the torch parameter is saved.
Parameters
----------
model_path : str
The path of the Hugging Face model on disk.
use_safetensors: bool
Whether to use ``.safetensors`` instead of ``.bi... | load_torch_pname2binname_map | python | llSourcell/Doctor-Dignity | mlc_llm/relax_model/param_manager.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/mlc_llm/relax_model/param_manager.py | Apache-2.0 |
def create_quantize_func(param_manager: ParamManager) -> tvm.IRModule:
"""Construct the Relax function which computes quantization.
This method is called by `transform_module` below, and is not
directly invoked outside the class.
Parameters
----------
param_manager : ParamManager
The pa... | Construct the Relax function which computes quantization.
This method is called by `transform_module` below, and is not
directly invoked outside the class.
Parameters
----------
param_manager : ParamManager
The parameter manager which has all the parameter information.
Returns
----... | create_quantize_func | python | llSourcell/Doctor-Dignity | mlc_llm/relax_model/param_manager.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/mlc_llm/relax_model/param_manager.py | Apache-2.0 |
def create_kv_cache_func(bb: relax.BlockBuilder, config: RWKVConfig) -> None:
"""NOTE: It's not typical kv-cache, but try to reuse the logic for the quick hack."""
init_shape = relax.ShapeExpr((1, config.hidden_size))
with bb.function("create_kv_cache", []):
with bb.dataflow():
input_dty... | NOTE: It's not typical kv-cache, but try to reuse the logic for the quick hack. | create_kv_cache_func | python | llSourcell/Doctor-Dignity | mlc_llm/relax_model/rwkv.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/mlc_llm/relax_model/rwkv.py | Apache-2.0 |
def remove_global_buf_alloc(
func: tir.PrimFunc,
) -> Tuple[tir.PrimFunc, List[relax.TensorStructInfo]]:
"""Remove the global buffer allocation for a given TIR PrimFunc."""
assert isinstance(func.body, tir.BlockRealize)
params = list(func.params)
buffer_map = dict(func.buffer_map)
tensor_sinfo =... | Remove the global buffer allocation for a given TIR PrimFunc. | remove_global_buf_alloc | python | llSourcell/Doctor-Dignity | mlc_llm/transform/lift_tir_global_buffer_alloc.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/mlc_llm/transform/lift_tir_global_buffer_alloc.py | Apache-2.0 |
def resolve_tir_var_mapping(
func: tir.PrimFunc, call: relax.Call, tensor_sinfo: List[relax.TensorStructInfo]
) -> Tuple[List[relax.TensorStructInfo], bool]:
"""Resolve the TIR symbolic var relationship across sides of PrimFunc and Relax Function"""
var_map: Dict[tir.Var, tir.PrimExpr] = dict()
n_arg =... | Resolve the TIR symbolic var relationship across sides of PrimFunc and Relax Function | resolve_tir_var_mapping | python | llSourcell/Doctor-Dignity | mlc_llm/transform/lift_tir_global_buffer_alloc.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/mlc_llm/transform/lift_tir_global_buffer_alloc.py | Apache-2.0 |
def analyze_func(
func: relax.Function,
pidx2binname: Dict[int, str],
) -> Tuple[
List[relax.Binding],
Dict[relax.Var, List[relax.Binding]],
Dict[relax.Binding, int],
]:
"""Binding grouping analysis function.
It takes the function to be analyzed, and mapping from each raw tensor index
to... | Binding grouping analysis function.
It takes the function to be analyzed, and mapping from each raw tensor index
to the name of the binary file where it resides.
This analysis function
* computes a new order of weight fetching bindings (the bindings in form
`lv = params[idx]`) based on weight locat... | analyze_func | python | llSourcell/Doctor-Dignity | mlc_llm/transform/reorder_transform_func.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/mlc_llm/transform/reorder_transform_func.py | Apache-2.0 |
def reorder_func(
func: relax.Function,
pidx2binname: Dict[int, str],
) -> relax.Function:
"""Reorder the bindings of the input weight transform Relax function
according the weight location in binary files.
This function first analyzes the input function and gets the reordered
weight fetching b... | Reorder the bindings of the input weight transform Relax function
according the weight location in binary files.
This function first analyzes the input function and gets the reordered
weight fetching bindings and the use-def information for topological sort.
It then reorders all bindings in the functio... | reorder_func | python | llSourcell/Doctor-Dignity | mlc_llm/transform/reorder_transform_func.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/mlc_llm/transform/reorder_transform_func.py | Apache-2.0 |
def get_lib_path():
"""Get library path, name and version"""
# Directly exec libinfo to get the right setup
libinfo_py = os.path.join(CURRENT_DIR, "./mlc_chat/libinfo.py")
libinfo = {"__file__": libinfo_py}
exec(compile(open(libinfo_py, "rb").read(), libinfo_py, "exec"), libinfo, libinfo)
versio... | Get library path, name and version | get_lib_path | python | llSourcell/Doctor-Dignity | python/setup.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/python/setup.py | Apache-2.0 |
def get_delta_message(curr_message: str, new_message: str) -> str:
r"""Given the current message and the new message, compute the delta message
(the newly generated part, the diff of the new message from the current message).
Parameters
----------
curr_message : str
The message generated in... | Given the current message and the new message, compute the delta message
(the newly generated part, the diff of the new message from the current message).
Parameters
----------
curr_message : str
The message generated in the previous round.
new_message : str
The message generated in... | get_delta_message | python | llSourcell/Doctor-Dignity | python/mlc_chat/base.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/python/mlc_chat/base.py | Apache-2.0 |
def __call__(self, message: str = "", stopped: bool = False):
r"""Process newly generated message using callback functions.
Parameters
----------
message : str
The newly generated message.
stopped : bool
Whether generation reaches an end. If True, clear t... | Process newly generated message using callback functions.
Parameters
----------
message : str
The newly generated message.
stopped : bool
Whether generation reaches an end. If True, clear the state of current message.
| __call__ | python | llSourcell/Doctor-Dignity | python/mlc_chat/callback.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/python/mlc_chat/callback.py | Apache-2.0 |
def __init__(self, callback_interval: int = 2):
r"""Initialize the callback class with callback interval.
Parameters
----------
callback_interval : int
The refresh rate of the streaming process.
"""
super().__init__()
self.callback_interval = callback... | Initialize the callback class with callback interval.
Parameters
----------
callback_interval : int
The refresh rate of the streaming process.
| __init__ | python | llSourcell/Doctor-Dignity | python/mlc_chat/callback.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/python/mlc_chat/callback.py | Apache-2.0 |
def _get_model_path(model: str) -> (str, str):
"""Use user-provided argument ``model`` to search for a valid model path.
We define "valid" as having an ``mlc-chat-config.json`` right under the folder.
Parameters
----------
model : str
User's input; may be a compiled model's name, or a full... | Use user-provided argument ``model`` to search for a valid model path.
We define "valid" as having an ``mlc-chat-config.json`` right under the folder.
Parameters
----------
model : str
User's input; may be a compiled model's name, or a full path.
Returns
------
model_path : str
... | _get_model_path | python | llSourcell/Doctor-Dignity | python/mlc_chat/chat_module.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/python/mlc_chat/chat_module.py | Apache-2.0 |
def _get_chat_config(config_file_path: str, user_chat_config: Optional[ChatConfig]) -> ChatConfig:
"""Read in the config file in model path, then potentially override with user input.
Parameters
----------
config_file_path : str
``chat_file`` returned by ``_get_model_path()``.
user_chat_con... | Read in the config file in model path, then potentially override with user input.
Parameters
----------
config_file_path : str
``chat_file`` returned by ``_get_model_path()``.
user_chat_config : Optional[ChatConfig]
User's input, a partial ``ChatConfig`` to override the one in ``config_... | _get_chat_config | python | llSourcell/Doctor-Dignity | python/mlc_chat/chat_module.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/python/mlc_chat/chat_module.py | Apache-2.0 |
def _get_lib_module(
model: str,
model_path: str,
chat_config: ChatConfig,
lib_path: Optional[str],
device_name: str,
config_file_path: str,
) -> tvm.runtime.Module:
"""Look up the model library. Then return a corresponding ``tvm`` runtime Module.
Parameters
----------
model : s... | Look up the model library. Then return a corresponding ``tvm`` runtime Module.
Parameters
----------
model : str
User's input; may be a compiled model's name, or a full path.
model_path : str
Model path found by `_get_model_path`.
chat_config : ChatConfig
Chat config after p... | _get_lib_module | python | llSourcell/Doctor-Dignity | python/mlc_chat/chat_module.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/python/mlc_chat/chat_module.py | Apache-2.0 |
def _detect_local_device(device_id: int = 0):
"""Automatically detect the local device if user does not specify.
Parameters
----------
device_id : int
The local device id.
Returns
------
dev : Device
The local device.
"""
if tvm.metal().exist:
return tvm.met... | Automatically detect the local device if user does not specify.
Parameters
----------
device_id : int
The local device id.
Returns
------
dev : Device
The local device.
| _detect_local_device | python | llSourcell/Doctor-Dignity | python/mlc_chat/chat_module.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/python/mlc_chat/chat_module.py | Apache-2.0 |
def generate(self, prompt: str, progress_callback=None) -> str:
r"""A high-level method that returns the full response from the chat module given a user prompt.
User can optionally specify which callback method to use upon receiving the response. By default,
no callback will be applied.
... | A high-level method that returns the full response from the chat module given a user prompt.
User can optionally specify which callback method to use upon receiving the response. By default,
no callback will be applied.
Parameters
----------
prompt : str
The user inp... | generate | python | llSourcell/Doctor-Dignity | python/mlc_chat/chat_module.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/python/mlc_chat/chat_module.py | Apache-2.0 |
def reset_chat(self, chat_config: Optional[ChatConfig] = None):
r"""Reset the chat session, clear all chat history, and potentially
override the original `mlc-chat-config.json`.
Parameters
----------
chat_config : Optional[ChatConfig]
A ``ChatConfig`` instance partia... | Reset the chat session, clear all chat history, and potentially
override the original `mlc-chat-config.json`.
Parameters
----------
chat_config : Optional[ChatConfig]
A ``ChatConfig`` instance partially filled. If specified, the chat
module will reload the `mlc-c... | reset_chat | python | llSourcell/Doctor-Dignity | python/mlc_chat/chat_module.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/python/mlc_chat/chat_module.py | Apache-2.0 |
def benchmark_generate(self, prompt: str, generate_length: int) -> str:
r"""Controlled generation with input prompt and fixed number of
generated tokens, ignoring system prompt. For example,
.. code:: python
from mlc_chat import ChatModule
cm = ChatModule(model="Llama-... | Controlled generation with input prompt and fixed number of
generated tokens, ignoring system prompt. For example,
.. code:: python
from mlc_chat import ChatModule
cm = ChatModule(model="Llama-2-7b-chat-hf-q4f16_1")
output = cm.benchmark_generate("What's the meanin... | benchmark_generate | python | llSourcell/Doctor-Dignity | python/mlc_chat/chat_module.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/python/mlc_chat/chat_module.py | Apache-2.0 |
def _prefill(
self,
input: str,
decode_next_token: bool = True,
place_in_prompt: PlaceInPrompt = PlaceInPrompt.All,
):
r"""Run prefill stage for a given input and optionally decode the first output token.
User can decide where to place the input in the prompt.
... | Run prefill stage for a given input and optionally decode the first output token.
User can decide where to place the input in the prompt.
Parameters
----------
input : str
The user input string.
decode_next_token : bool
Whether to decode the next token af... | _prefill | python | llSourcell/Doctor-Dignity | python/mlc_chat/chat_module.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/python/mlc_chat/chat_module.py | Apache-2.0 |
def _get_all_available_models_under_dir(artifact_path: str) -> Dict[str, str]:
r"""Given the artifact path storing all models, returns a dict mapping available model names
to the correct `model` args passed into ChatModule.
Note
----
We only search for folders under the artifact_path, without recur... | Given the artifact path storing all models, returns a dict mapping available model names
to the correct `model` args passed into ChatModule.
Note
----
We only search for folders under the artifact_path, without recursive search for subfolders.
For each folder, we count it as a valid MLC model folde... | _get_all_available_models_under_dir | python | llSourcell/Doctor-Dignity | python/mlc_chat/gradio.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/python/mlc_chat/gradio.py | Apache-2.0 |
def gradio_reload_model(self, model_name: str):
r"""Reload the model given the user-selected model name."""
self.chat_mod = ChatModule(self.model_dict[model_name], self.device_str)
updated_dict = {
"chatbot": None,
"chat_state": [],
"img_list": [],
... | Reload the model given the user-selected model name. | gradio_reload_model | python | llSourcell/Doctor-Dignity | python/mlc_chat/gradio.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/python/mlc_chat/gradio.py | Apache-2.0 |
def gradio_ask(self, text_input, chatbot):
r"""Display user text input in the chatbot."""
chatbot = chatbot + [[text_input, None]]
text_input = ""
return text_input, chatbot | Display user text input in the chatbot. | gradio_ask | python | llSourcell/Doctor-Dignity | python/mlc_chat/gradio.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/python/mlc_chat/gradio.py | Apache-2.0 |
def gradio_answer(self, chatbot, stream_interval):
r"""Generate and display the chat module's response.
Note: Below is a low-level implementation of generate() API, since it's easier
to yield without delta callback."""
prompt = chatbot[-1][0]
self.chat_mod._prefill(prompt)
... | Generate and display the chat module's response.
Note: Below is a low-level implementation of generate() API, since it's easier
to yield without delta callback. | gradio_answer | python | llSourcell/Doctor-Dignity | python/mlc_chat/gradio.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/python/mlc_chat/gradio.py | Apache-2.0 |
def launch_gradio(
artifact_path: str = "dist", device: str = "auto", port: int = 7860, share: bool = False, host: str = "127.0.0.1"):
r"""Launch the gradio interface with a given port, creating a publically sharable link if specified."""
# create a gradio module
mod = GradioModule(artifact_path, devic... | Launch the gradio interface with a given port, creating a publically sharable link if specified. | launch_gradio | python | llSourcell/Doctor-Dignity | python/mlc_chat/gradio.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/python/mlc_chat/gradio.py | Apache-2.0 |
def get_dll_directories():
"""Get extra mlc llm dll directories"""
curr_dir = os.path.dirname(os.path.realpath(os.path.expanduser(__file__)))
source_dir = os.path.abspath(os.path.join(curr_dir, "..", ".."))
dll_path = [
curr_dir,
os.path.join(source_dir, "build"),
os.path.join(so... | Get extra mlc llm dll directories | get_dll_directories | python | llSourcell/Doctor-Dignity | python/mlc_chat/libinfo.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/python/mlc_chat/libinfo.py | Apache-2.0 |
def find_lib_path(name, optional=False):
"""Find mlc llm library
Parameters
----------
name : str
The name of the library
optional: boolean
Whether the library is required
"""
if sys.platform.startswith("linux") or sys.platform.startswith("freebsd"):
lib_name = f"li... | Find mlc llm library
Parameters
----------
name : str
The name of the library
optional: boolean
Whether the library is required
| find_lib_path | python | llSourcell/Doctor-Dignity | python/mlc_chat/libinfo.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/python/mlc_chat/libinfo.py | Apache-2.0 |
def convert_args_to_argparser() -> argparse.ArgumentParser:
"""Convert from RestAPIArgs to an equivalent ArgumentParser."""
args = argparse.ArgumentParser("MLC Chat REST API")
for field in fields(RestAPIArgs):
name = field.name.replace("_", "-")
field_name = f"--{name}"
# `kwargs` co... | Convert from RestAPIArgs to an equivalent ArgumentParser. | convert_args_to_argparser | python | llSourcell/Doctor-Dignity | python/mlc_chat/rest.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/python/mlc_chat/rest.py | Apache-2.0 |
async def request_completion(request: ChatCompletionRequest):
"""
Creates model response for the given chat conversation.
"""
if len(request.messages) > 1:
raise ValueError(
"""
The /v1/chat/completions endpoint currently only supports single message prompts.
... |
Creates model response for the given chat conversation.
| request_completion | python | llSourcell/Doctor-Dignity | python/mlc_chat/rest.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/python/mlc_chat/rest.py | Apache-2.0 |
async def reset():
"""
Reset the chat for the currently initialized model.
"""
session["chat_mod"].reset_chat() |
Reset the chat for the currently initialized model.
| reset | python | llSourcell/Doctor-Dignity | python/mlc_chat/rest.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/python/mlc_chat/rest.py | Apache-2.0 |
def _chunk_tokens(self, texts: Sequence[str]) -> Tuple[List[List], List[int]]:
"""Tokenize and chunk texts to fit in the model's context window."""
if not self.embedding_ctx_length:
raise ValueError(
"embedding_ctx_length must be defined to use _get_len_safe_embeddings."
... | Tokenize and chunk texts to fit in the model's context window. | _chunk_tokens | python | llSourcell/Doctor-Dignity | python/mlc_chat/embeddings/openai.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/python/mlc_chat/embeddings/openai.py | Apache-2.0 |
def embed_documents(
self, texts: List[str], chunk_size: Optional[int] = None
) -> List[List[float]]:
"""Call out to OpenAI's embedding endpoint for embedding search docs.
Args:
texts: The list of texts to embed.
chunk_size: The chunk size of embeddings. If None, wil... | Call out to OpenAI's embedding endpoint for embedding search docs.
Args:
texts: The list of texts to embed.
chunk_size: The chunk size of embeddings. If None, will use the chunk size
specified by the class.
Returns:
List of embeddings, one for each t... | embed_documents | python | llSourcell/Doctor-Dignity | python/mlc_chat/embeddings/openai.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/python/mlc_chat/embeddings/openai.py | Apache-2.0 |
async def aembed_documents(
self, texts: List[str], chunk_size: Optional[int] = 0
) -> List[List[float]]:
"""Call out to OpenAI's embedding endpoint async for embedding search docs.
Args:
texts: The list of texts to embed.
chunk_size: The chunk size of embeddings. If... | Call out to OpenAI's embedding endpoint async for embedding search docs.
Args:
texts: The list of texts to embed.
chunk_size: The chunk size of embeddings. If None, will use the chunk size
specified by the class.
Returns:
List of embeddings, one for ... | aembed_documents | python | llSourcell/Doctor-Dignity | python/mlc_chat/embeddings/openai.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/python/mlc_chat/embeddings/openai.py | Apache-2.0 |
async def aembed_query(self, text: str) -> List[float]:
"""Call out to OpenAI's embedding endpoint async for embedding query text.
Args:
text: The text to embed.
Returns:
Embedding for the text.
"""
embeddings = await self.aembed_documents([text])
... | Call out to OpenAI's embedding endpoint async for embedding query text.
Args:
text: The text to embed.
Returns:
Embedding for the text.
| aembed_query | python | llSourcell/Doctor-Dignity | python/mlc_chat/embeddings/openai.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/python/mlc_chat/embeddings/openai.py | Apache-2.0 |
def old_make_args():
"""The exact old way of creating `ArgumentParser`, used to test whether
`BuildArgs` is equivalent to this. """
args = argparse.ArgumentParser()
args.add_argument(
"--model",
type=str,
default="auto",
help=(
'The name of the model to build.... | The exact old way of creating `ArgumentParser`, used to test whether
`BuildArgs` is equivalent to this. | old_make_args | python | llSourcell/Doctor-Dignity | tests/python/test_build_args.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/tests/python/test_build_args.py | Apache-2.0 |
def argparsers_equal(self, parse_a: argparse.ArgumentParser,
parse_b: argparse.ArgumentParser):
"""
Small helper to check pseudo-equality of parsed arguments on `ArgumentParser` instances.
"""
self.assertEqual(len(parse_a._actions), len(parse_b._actions)) # pyl... |
Small helper to check pseudo-equality of parsed arguments on `ArgumentParser` instances.
| argparsers_equal | python | llSourcell/Doctor-Dignity | tests/python/test_build_args.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/tests/python/test_build_args.py | Apache-2.0 |
def test_namespaces_are_equivalent_str(self):
"""Tests whether the resulting namespaces from command line entry
and Python API entry are equivalent, as they are passed down to the
same workflow."""
# Namespace that would be created through Python API build_model
build_args = Buil... | Tests whether the resulting namespaces from command line entry
and Python API entry are equivalent, as they are passed down to the
same workflow. | test_namespaces_are_equivalent_str | python | llSourcell/Doctor-Dignity | tests/python/test_build_args.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/tests/python/test_build_args.py | Apache-2.0 |
def test_namespaces_are_equivalent_str_boolean_int(self):
"""Same test, but for a mixture of argument types."""
# 1. Equal
build_args = BuildArgs(model="RedPJ", max_seq_len=20, debug_dump=True)
build_args_as_dict = dataclasses.asdict(build_args)
build_args_namespace = argparse.Na... | Same test, but for a mixture of argument types. | test_namespaces_are_equivalent_str_boolean_int | python | llSourcell/Doctor-Dignity | tests/python/test_build_args.py | https://github.com/llSourcell/Doctor-Dignity/blob/master/tests/python/test_build_args.py | Apache-2.0 |
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the miio fan device from config."""
if DATA_KEY not in hass.data:
hass.data[DATA_KEY] = {}
host = config[CONF_HOST]
name = config[CONF_NAME]
token = config[CONF_TOKEN]
model = config.get(CON... | Set up the miio fan device from config. | async_setup_platform | python | syssi/xiaomi_airpurifier | custom_components/xiaomi_miio_airpurifier/climate.py | https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/climate.py | Apache-2.0 |
async def async_service_handler(service):
"""Map services to methods on XiaomiAirDehumidifier."""
method = SERVICE_TO_METHOD.get(service.service)
params = {
key: value for key, value in service.data.items() if key != ATTR_ENTITY_ID
}
entity_ids = service.data.get(ATTR... | Map services to methods on XiaomiAirDehumidifier. | async_service_handler | python | syssi/xiaomi_airpurifier | custom_components/xiaomi_miio_airpurifier/climate.py | https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/climate.py | Apache-2.0 |
async def _try_command(self, mask_error, func, *args, **kwargs):
"""Call a miio device command handling error messages."""
try:
result = await self.hass.async_add_executor_job(
partial(func, *args, **kwargs)
)
except DeviceException as exc:
_LO... | Call a miio device command handling error messages. | _try_command | python | syssi/xiaomi_airpurifier | custom_components/xiaomi_miio_airpurifier/climate.py | https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/climate.py | Apache-2.0 |
def hvac_mode(self):
"""Return hvac operation ie. heat, cool mode."""
if self.is_on:
return HVACMode.DRY
return HVACMode.OFF | Return hvac operation ie. heat, cool mode. | hvac_mode | python | syssi/xiaomi_airpurifier | custom_components/xiaomi_miio_airpurifier/climate.py | https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/climate.py | Apache-2.0 |
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the miio fan device from config."""
if DATA_KEY not in hass.data:
hass.data[DATA_KEY] = {}
host = config[CONF_HOST]
token = config[CONF_TOKEN]
name = config[CONF_NAME]
model = config.get(CON... | Set up the miio fan device from config. | async_setup_platform | python | syssi/xiaomi_airpurifier | custom_components/xiaomi_miio_airpurifier/fan.py | https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py | Apache-2.0 |
async def async_service_handler(service):
"""Map services to methods on XiaomiAirPurifier."""
method = SERVICE_TO_METHOD.get(service.service)
params = {
key: value for key, value in service.data.items() if key != ATTR_ENTITY_ID
}
entity_ids = service.data.get(ATTR_ENT... | Map services to methods on XiaomiAirPurifier. | async_service_handler | python | syssi/xiaomi_airpurifier | custom_components/xiaomi_miio_airpurifier/fan.py | https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py | Apache-2.0 |
async def _try_command(self, mask_error, func, *args, **kwargs):
"""Call a miio device command handling error messages."""
try:
result = await self.hass.async_add_executor_job(
partial(func, *args, **kwargs)
)
_LOGGER.debug("Response received from mii... | Call a miio device command handling error messages. | _try_command | python | syssi/xiaomi_airpurifier | custom_components/xiaomi_miio_airpurifier/fan.py | https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py | Apache-2.0 |
async def async_set_preset_mode(self, preset_mode: str) -> None:
"""Set the preset mode of the fan."""
_LOGGER.debug("Setting the preset mode to: %s", preset_mode)
await self._try_command(
"Setting preset mode of the miio device failed.",
self._device.set_mode,
... | Set the preset mode of the fan. | async_set_preset_mode | python | syssi/xiaomi_airpurifier | custom_components/xiaomi_miio_airpurifier/fan.py | https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py | Apache-2.0 |
async def async_reset_filter(self):
"""Reset the filter lifetime and usage."""
if self._device_features & FEATURE_RESET_FILTER == 0:
return
await self._try_command(
"Resetting the filter lifetime of the miio device failed.",
self._device.reset_filter,
... | Reset the filter lifetime and usage. | async_reset_filter | python | syssi/xiaomi_airpurifier | custom_components/xiaomi_miio_airpurifier/fan.py | https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py | Apache-2.0 |
async def async_set_preset_mode(self, preset_mode: str) -> None:
"""Set the preset mode of the fan."""
_LOGGER.debug("Setting the preset mode to: %s", preset_mode)
await self._try_command(
"Setting preset mode of the miio device failed.",
self._device.set_mode,
... | Set the preset mode of the fan. | async_set_preset_mode | python | syssi/xiaomi_airpurifier | custom_components/xiaomi_miio_airpurifier/fan.py | https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py | Apache-2.0 |
async def async_set_preset_mode(self, preset_mode: str) -> None:
"""Set the preset mode of the fan."""
_LOGGER.debug("Setting the preset mode to: %s", preset_mode)
await self._try_command(
"Setting preset mode of the miio device failed.",
self._device.set_mode,
... | Set the preset mode of the fan. | async_set_preset_mode | python | syssi/xiaomi_airpurifier | custom_components/xiaomi_miio_airpurifier/fan.py | https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py | Apache-2.0 |
async def async_set_preset_mode(self, preset_mode: str) -> None:
"""Set the preset mode of the fan."""
_LOGGER.debug("Setting the preset mode to: %s", preset_mode)
await self._try_command(
"Setting preset mode of the miio device failed.",
self._device.set_mode,
... | Set the preset mode of the fan. | async_set_preset_mode | python | syssi/xiaomi_airpurifier | custom_components/xiaomi_miio_airpurifier/fan.py | https://github.com/syssi/xiaomi_airpurifier/blob/master/custom_components/xiaomi_miio_airpurifier/fan.py | Apache-2.0 |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.