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 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_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 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_percentage(self, percentage: int) -> None:
"""Set the speed percentage of the fan."""
_LOGGER.debug("Setting the fan speed percentage to: %s", percentage)
if percentage == 0:
await self.async_turn_off()
return
if self._natural_mode:
... | Set the speed percentage of the fan. | async_set_percentage | 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_direction(self, direction: str) -> None:
"""Set the direction of the fan."""
if direction == "forward":
direction = "right"
if direction == "reverse":
direction = "left"
if self._oscillate:
await self._try_command(
... | Set the direction of the fan. | async_set_direction | 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_delay_off(self, delay_off_countdown: int) -> None:
"""Set scheduled off timer in minutes."""
await self._try_command(
"Setting delay off miio device failed.",
self._device.delay_off,
delay_off_countdown * 60,
) | Set scheduled off timer in minutes. | async_set_delay_off | 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 |
def get_from_config():
"""Get benchmarks configuration from the config.json file"""
current_path = Path(__file__).resolve().parent
config_path = current_path / "config.json"
with open(config_path, "r") as config_file:
config_file = "".join(line for line in config_file if line and "//" not in li... | Get benchmarks configuration from the config.json file | get_from_config | python | scikit-learn/scikit-learn | asv_benchmarks/benchmarks/common.py | https://github.com/scikit-learn/scikit-learn/blob/master/asv_benchmarks/benchmarks/common.py | BSD-3-Clause |
def get_estimator_path(benchmark, directory, params, save=False):
"""Get path of pickled fitted estimator"""
path = Path(__file__).resolve().parent / "cache"
path = (path / "estimators" / directory) if save else (path / "tmp")
filename = (
benchmark.__class__.__name__
+ "_estimator_"
... | Get path of pickled fitted estimator | get_estimator_path | python | scikit-learn/scikit-learn | asv_benchmarks/benchmarks/common.py | https://github.com/scikit-learn/scikit-learn/blob/master/asv_benchmarks/benchmarks/common.py | BSD-3-Clause |
def make_data(self, params):
"""Return the dataset for a combination of parameters"""
# The datasets are cached using joblib.Memory so it's fast and can be
# called for each repeat
pass | Return the dataset for a combination of parameters | make_data | python | scikit-learn/scikit-learn | asv_benchmarks/benchmarks/common.py | https://github.com/scikit-learn/scikit-learn/blob/master/asv_benchmarks/benchmarks/common.py | BSD-3-Clause |
def setup_cache(self):
"""Pickle a fitted estimator for all combinations of parameters"""
# This is run once per benchmark class.
clear_tmp()
param_grid = list(itertools.product(*self.params))
for params in param_grid:
if self.skip(params):
continue... | Pickle a fitted estimator for all combinations of parameters | setup_cache | python | scikit-learn/scikit-learn | asv_benchmarks/benchmarks/common.py | https://github.com/scikit-learn/scikit-learn/blob/master/asv_benchmarks/benchmarks/common.py | BSD-3-Clause |
def setup(self, *params):
"""Generate dataset and load the fitted estimator"""
# This is run once per combination of parameters and per repeat so we
# need to avoid doing expensive operations there.
if self.skip(params):
raise NotImplementedError
self.X, self.X_val,... | Generate dataset and load the fitted estimator | setup | python | scikit-learn/scikit-learn | asv_benchmarks/benchmarks/common.py | https://github.com/scikit-learn/scikit-learn/blob/master/asv_benchmarks/benchmarks/common.py | BSD-3-Clause |
def load_data(dtype=np.float32, order="C", random_state=13):
"""Load the data, then cache and memmap the train/test split"""
######################################################################
# Load dataset
print("Loading dataset...")
data = fetch_covtype(
download_if_missing=True, shuff... | Load the data, then cache and memmap the train/test split | load_data | python | scikit-learn/scikit-learn | benchmarks/bench_covertype.py | https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_covertype.py | BSD-3-Clause |
def print_outlier_ratio(y):
"""
Helper function to show the distinct value count of element in the target.
Useful indicator for the datasets used in bench_isolation_forest.py.
"""
uniq, cnt = np.unique(y, return_counts=True)
print("----- Target count values: ")
for u, c in zip(uniq, cnt):
... |
Helper function to show the distinct value count of element in the target.
Useful indicator for the datasets used in bench_isolation_forest.py.
| print_outlier_ratio | python | scikit-learn/scikit-learn | benchmarks/bench_isolation_forest.py | https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_isolation_forest.py | BSD-3-Clause |
def get_data(
n_samples_train, n_samples_test, n_features, contamination=0.1, random_state=0
):
"""Function based on code from: https://scikit-learn.org/stable/
auto_examples/ensemble/plot_isolation_forest.html#sphx-glr-auto-
examples-ensemble-plot-isolation-forest-py
"""
rng = np.random.RandomS... | Function based on code from: https://scikit-learn.org/stable/
auto_examples/ensemble/plot_isolation_forest.html#sphx-glr-auto-
examples-ensemble-plot-isolation-forest-py
| get_data | python | scikit-learn/scikit-learn | benchmarks/bench_isolation_forest_predict.py | https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_isolation_forest_predict.py | BSD-3-Clause |
def bench_isotonic_regression(Y):
"""
Runs a single iteration of isotonic regression on the input data,
and reports the total time taken (in seconds).
"""
gc.collect()
tstart = default_timer()
isotonic_regression(Y)
return default_timer() - tstart |
Runs a single iteration of isotonic regression on the input data,
and reports the total time taken (in seconds).
| bench_isotonic_regression | python | scikit-learn/scikit-learn | benchmarks/bench_isotonic.py | https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_isotonic.py | BSD-3-Clause |
def benchmark(
metrics=tuple(v for k, v in sorted(METRICS.items())),
formats=tuple(v for k, v in sorted(FORMATS.items())),
samples=1000,
classes=4,
density=0.2,
n_times=5,
):
"""Times metric calculations for a number of inputs
Parameters
----------
metrics : array-like of callab... | Times metric calculations for a number of inputs
Parameters
----------
metrics : array-like of callables (1d or 0d)
The metric functions to time.
formats : array-like of callables (1d or 0d)
These may transform a dense indicator matrix into multilabel
representation.
sampl... | benchmark | python | scikit-learn/scikit-learn | benchmarks/bench_multilabel_metrics.py | https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_multilabel_metrics.py | BSD-3-Clause |
def _tabulate(results, metrics, formats):
"""Prints results by metric and format
Uses the last ([-1]) value of other fields
"""
column_width = max(max(len(k) for k in formats) + 1, 8)
first_width = max(len(k) for k in metrics)
head_fmt = "{:<{fw}s}" + "{:>{cw}s}" * len(formats)
row_fmt = "{... | Prints results by metric and format
Uses the last ([-1]) value of other fields
| _tabulate | python | scikit-learn/scikit-learn | benchmarks/bench_multilabel_metrics.py | https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_multilabel_metrics.py | BSD-3-Clause |
def _plot(
results,
metrics,
formats,
title,
x_ticks,
x_label,
format_markers=("x", "|", "o", "+"),
metric_colors=("c", "m", "y", "k", "g", "r", "b"),
):
"""
Plot the results by metric, format and some other variable given by
x_label
"""
fig = plt.figure("scikit-learn... |
Plot the results by metric, format and some other variable given by
x_label
| _plot | python | scikit-learn/scikit-learn | benchmarks/bench_multilabel_metrics.py | https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_multilabel_metrics.py | BSD-3-Clause |
def autolabel_auc(rects, ax):
"""Attach a text label above each bar displaying its height."""
for rect in rects:
height = rect.get_height()
ax.text(
rect.get_x() + rect.get_width() / 2.0,
1.05 * height,
"%.3f" % height,
ha="center",
va=... | Attach a text label above each bar displaying its height. | autolabel_auc | python | scikit-learn/scikit-learn | benchmarks/bench_online_ocsvm.py | https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_online_ocsvm.py | BSD-3-Clause |
def _nls_subproblem(
X, W, H, tol, max_iter, alpha=0.0, l1_ratio=0.0, sigma=0.01, beta=0.1
):
"""Non-negative least square solver
Solves a non-negative least squares subproblem using the projected
gradient descent algorithm.
Parameters
----------
X : array-like, shape (n_samples, n_features)... | Non-negative least square solver
Solves a non-negative least squares subproblem using the projected
gradient descent algorithm.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Constant matrix.
W : array-like, shape (n_samples, n_components)
Constant matrix.
... | _nls_subproblem | python | scikit-learn/scikit-learn | benchmarks/bench_plot_nmf.py | https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_plot_nmf.py | BSD-3-Clause |
def norm_diff(A, norm=2, msg=True, random_state=None):
"""
Compute the norm diff with the original matrix, when randomized
SVD is called with *params.
norm: 2 => spectral; 'fro' => Frobenius
"""
if msg:
print("... computing %s norm ..." % norm)
if norm == 2:
# s = sp.linalg... |
Compute the norm diff with the original matrix, when randomized
SVD is called with *params.
norm: 2 => spectral; 'fro' => Frobenius
| norm_diff | python | scikit-learn/scikit-learn | benchmarks/bench_plot_randomized_svd.py | https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_plot_randomized_svd.py | BSD-3-Clause |
def bench_scikit_tree_classifier(X, Y):
"""Benchmark with scikit-learn decision tree classifier"""
from sklearn.tree import DecisionTreeClassifier
gc.collect()
# start time
tstart = datetime.now()
clf = DecisionTreeClassifier()
clf.fit(X, Y).predict(X)
delta = datetime.now() - tstart
... | Benchmark with scikit-learn decision tree classifier | bench_scikit_tree_classifier | python | scikit-learn/scikit-learn | benchmarks/bench_tree.py | https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_tree.py | BSD-3-Clause |
def bench_scikit_tree_regressor(X, Y):
"""Benchmark with scikit-learn decision tree regressor"""
from sklearn.tree import DecisionTreeRegressor
gc.collect()
# start time
tstart = datetime.now()
clf = DecisionTreeRegressor()
clf.fit(X, Y).predict(X)
delta = datetime.now() - tstart
... | Benchmark with scikit-learn decision tree regressor | bench_scikit_tree_regressor | python | scikit-learn/scikit-learn | benchmarks/bench_tree.py | https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_tree.py | BSD-3-Clause |
def nn_accuracy(X, X_embedded, k=1):
"""Accuracy of the first nearest neighbor"""
knn = NearestNeighbors(n_neighbors=1, n_jobs=-1)
_, neighbors_X = knn.fit(X).kneighbors()
_, neighbors_X_embedded = knn.fit(X_embedded).kneighbors()
return np.mean(neighbors_X == neighbors_X_embedded) | Accuracy of the first nearest neighbor | nn_accuracy | python | scikit-learn/scikit-learn | benchmarks/bench_tsne_mnist.py | https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_tsne_mnist.py | BSD-3-Clause |
def bhtsne(X):
"""Wrapper for the reference lvdmaaten/bhtsne implementation."""
# PCA preprocessing is done elsewhere in the benchmark script
n_iter = -1 # TODO find a way to report the number of iterations
return (
run_bh_tsne(
X,
... | Wrapper for the reference lvdmaaten/bhtsne implementation. | bhtsne | python | scikit-learn/scikit-learn | benchmarks/bench_tsne_mnist.py | https://github.com/scikit-learn/scikit-learn/blob/master/benchmarks/bench_tsne_mnist.py | BSD-3-Clause |
def has_openmp_flags(target):
"""Return whether target sources use OpenMP flags.
Make sure that both compiler and linker source use OpenMP.
Look at `get_meson_info` docstring to see what `target` looks like.
"""
target_sources = target["target_sources"]
target_use_openmp_flags = any(
h... | Return whether target sources use OpenMP flags.
Make sure that both compiler and linker source use OpenMP.
Look at `get_meson_info` docstring to see what `target` looks like.
| has_openmp_flags | python | scikit-learn/scikit-learn | build_tools/check-meson-openmp-dependencies.py | https://github.com/scikit-learn/scikit-learn/blob/master/build_tools/check-meson-openmp-dependencies.py | BSD-3-Clause |
def get_canonical_name_meson(target, build_path):
"""Return a name based on generated shared library.
The goal is to return a name that can be easily matched with the output
from `git_grep_info`.
Look at `get_meson_info` docstring to see what `target` looks like.
"""
# Expect a list with one e... | Return a name based on generated shared library.
The goal is to return a name that can be easily matched with the output
from `git_grep_info`.
Look at `get_meson_info` docstring to see what `target` looks like.
| get_canonical_name_meson | python | scikit-learn/scikit-learn | build_tools/check-meson-openmp-dependencies.py | https://github.com/scikit-learn/scikit-learn/blob/master/build_tools/check-meson-openmp-dependencies.py | BSD-3-Clause |
def get_meson_info():
"""Return names of extension that use OpenMP based on meson introspect output.
The meson introspect json info is a list of targets where a target is a dict
that looks like this (parts not used in this script are not shown for simplicity):
{
'name': '_k_means_elkan.cpython-31... | Return names of extension that use OpenMP based on meson introspect output.
The meson introspect json info is a list of targets where a target is a dict
that looks like this (parts not used in this script are not shown for simplicity):
{
'name': '_k_means_elkan.cpython-312-x86_64-linux-gnu',
'f... | get_meson_info | python | scikit-learn/scikit-learn | build_tools/check-meson-openmp-dependencies.py | https://github.com/scikit-learn/scikit-learn/blob/master/build_tools/check-meson-openmp-dependencies.py | BSD-3-Clause |
def get_git_grep_info():
"""Return names of extensions that use OpenMP based on git grep regex."""
git_grep_filenames = subprocess.check_output(
["git", "grep", "-lP", "cython.*parallel|_openmp_helpers"], text=True
).splitlines()
git_grep_filenames = [f for f in git_grep_filenames if ".pyx" in f... | Return names of extensions that use OpenMP based on git grep regex. | get_git_grep_info | python | scikit-learn/scikit-learn | build_tools/check-meson-openmp-dependencies.py | https://github.com/scikit-learn/scikit-learn/blob/master/build_tools/check-meson-openmp-dependencies.py | BSD-3-Clause |
def get_contributors():
"""Get the list of contributor profiles. Require admin rights."""
# get core devs and contributor experience team
core_devs = []
documentation_team = []
contributor_experience_team = []
comm_team = []
core_devs_slug = "core-devs"
contributor_experience_team_slug =... | Get the list of contributor profiles. Require admin rights. | get_contributors | python | scikit-learn/scikit-learn | build_tools/generate_authors_table.py | https://github.com/scikit-learn/scikit-learn/blob/master/build_tools/generate_authors_table.py | BSD-3-Clause |
def get_profile(login):
"""Get the GitHub profile from login"""
print("get profile for %s" % (login,))
try:
profile = get("https://api.github.com/users/%s" % login).json()
except requests.exceptions.HTTPError:
return dict(name=login, avatar_url=LOGO_URL, html_url="")
if profile["nam... | Get the GitHub profile from login | get_profile | python | scikit-learn/scikit-learn | build_tools/generate_authors_table.py | https://github.com/scikit-learn/scikit-learn/blob/master/build_tools/generate_authors_table.py | BSD-3-Clause |
def key(profile):
"""Get a sorting key based on the lower case last name, then firstname"""
components = profile["name"].lower().split(" ")
return " ".join([components[-1]] + components[:-1]) | Get a sorting key based on the lower case last name, then firstname | key | python | scikit-learn/scikit-learn | build_tools/generate_authors_table.py | https://github.com/scikit-learn/scikit-learn/blob/master/build_tools/generate_authors_table.py | BSD-3-Clause |
def get_versions(versions_file):
"""Get the versions of the packages used in the linter job.
Parameters
----------
versions_file : str
The path to the file that contains the versions of the packages.
Returns
-------
versions : dict
A dictionary with the versions of the pack... | Get the versions of the packages used in the linter job.
Parameters
----------
versions_file : str
The path to the file that contains the versions of the packages.
Returns
-------
versions : dict
A dictionary with the versions of the packages.
| get_versions | python | scikit-learn/scikit-learn | build_tools/get_comment.py | https://github.com/scikit-learn/scikit-learn/blob/master/build_tools/get_comment.py | BSD-3-Clause |
def get_step_message(log, start, end, title, message, details):
"""Get the message for a specific test.
Parameters
----------
log : str
The log of the linting job.
start : str
The string that marks the start of the test.
end : str
The string that marks the end of the t... | Get the message for a specific test.
Parameters
----------
log : str
The log of the linting job.
start : str
The string that marks the start of the test.
end : str
The string that marks the end of the test.
title : str
The title for this section.
message ... | get_step_message | python | scikit-learn/scikit-learn | build_tools/get_comment.py | https://github.com/scikit-learn/scikit-learn/blob/master/build_tools/get_comment.py | BSD-3-Clause |
def get_headers(token):
"""Get the headers for the GitHub API."""
return {
"Accept": "application/vnd.github+json",
"Authorization": f"Bearer {token}",
"X-GitHub-Api-Version": "2022-11-28",
} | Get the headers for the GitHub API. | get_headers | python | scikit-learn/scikit-learn | build_tools/get_comment.py | https://github.com/scikit-learn/scikit-learn/blob/master/build_tools/get_comment.py | BSD-3-Clause |
def create_or_update_comment(comment, message, repo, pr_number, token):
"""Create a new comment or update existing one."""
# repo is in the form of "org/repo"
if comment is not None:
print("updating existing comment")
# API doc: https://docs.github.com/en/rest/issues/comments?apiVersion=2022... | Create a new comment or update existing one. | create_or_update_comment | python | scikit-learn/scikit-learn | build_tools/get_comment.py | https://github.com/scikit-learn/scikit-learn/blob/master/build_tools/get_comment.py | BSD-3-Clause |
def make_distributor_init_64_bits(
distributor_init,
vcomp140_dll_filename,
msvcp140_dll_filename,
):
"""Create a _distributor_init.py file for 64-bit architectures.
This file is imported first when importing the sklearn package
so as to pre-load the vendored vcomp140.dll and msvcp140.dll.
... | Create a _distributor_init.py file for 64-bit architectures.
This file is imported first when importing the sklearn package
so as to pre-load the vendored vcomp140.dll and msvcp140.dll.
| make_distributor_init_64_bits | python | scikit-learn/scikit-learn | build_tools/github/vendor.py | https://github.com/scikit-learn/scikit-learn/blob/master/build_tools/github/vendor.py | BSD-3-Clause |
def _get_guide(*refs, is_developer=False):
"""Get the rst to refer to user/developer guide.
`refs` is several references that can be used in the :ref:`...` directive.
"""
if len(refs) == 1:
ref_desc = f":ref:`{refs[0]}` section"
elif len(refs) == 2:
ref_desc = f":ref:`{refs[0]}` and... | Get the rst to refer to user/developer guide.
`refs` is several references that can be used in the :ref:`...` directive.
| _get_guide | python | scikit-learn/scikit-learn | doc/api_reference.py | https://github.com/scikit-learn/scikit-learn/blob/master/doc/api_reference.py | BSD-3-Clause |
def _get_submodule(module_name, submodule_name):
"""Get the submodule docstring and automatically add the hook.
`module_name` is e.g. `sklearn.feature_extraction`, and `submodule_name` is e.g.
`image`, so we get the docstring and hook for `sklearn.feature_extraction.image`
submodule. `module_name` is u... | Get the submodule docstring and automatically add the hook.
`module_name` is e.g. `sklearn.feature_extraction`, and `submodule_name` is e.g.
`image`, so we get the docstring and hook for `sklearn.feature_extraction.image`
submodule. `module_name` is used to reset the current module because autosummary
... | _get_submodule | python | scikit-learn/scikit-learn | doc/api_reference.py | https://github.com/scikit-learn/scikit-learn/blob/master/doc/api_reference.py | BSD-3-Clause |
def add_js_css_files(app, pagename, templatename, context, doctree):
"""Load additional JS and CSS files only for certain pages.
Note that `html_js_files` and `html_css_files` are included in all pages and
should be used for the ones that are used by multiple pages. All page-specific
JS and CSS files s... | Load additional JS and CSS files only for certain pages.
Note that `html_js_files` and `html_css_files` are included in all pages and
should be used for the ones that are used by multiple pages. All page-specific
JS and CSS files should be added here instead.
| add_js_css_files | python | scikit-learn/scikit-learn | doc/conf.py | https://github.com/scikit-learn/scikit-learn/blob/master/doc/conf.py | BSD-3-Clause |
def make_carousel_thumbs(app, exception):
"""produces the final resized carousel images"""
if exception is not None:
return
print("Preparing carousel images")
image_dir = os.path.join(app.builder.outdir, "_images")
for glr_plot, max_width in carousel_thumbs.items():
image = os.path.... | produces the final resized carousel images | make_carousel_thumbs | python | scikit-learn/scikit-learn | doc/conf.py | https://github.com/scikit-learn/scikit-learn/blob/master/doc/conf.py | BSD-3-Clause |
def skip_properties(app, what, name, obj, skip, options):
"""Skip properties that are fitted attributes"""
if isinstance(obj, property):
if name.endswith("_") and not name.startswith("_"):
return True
return skip | Skip properties that are fitted attributes | skip_properties | python | scikit-learn/scikit-learn | doc/conf.py | https://github.com/scikit-learn/scikit-learn/blob/master/doc/conf.py | BSD-3-Clause |
def infer_next_release_versions():
"""Infer the most likely next release versions to make."""
all_version_full = {"rc": "0.99.0rc1", "final": "0.99.0", "bf": "0.98.1"}
all_version_short = {"rc": "0.99", "final": "0.99", "bf": "0.98"}
all_previous_tag = {"rc": "unused", "final": "0.98.33", "bf": "0.97.22... | Infer the most likely next release versions to make. | infer_next_release_versions | python | scikit-learn/scikit-learn | doc/conf.py | https://github.com/scikit-learn/scikit-learn/blob/master/doc/conf.py | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.