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 _validate_virtualenv_is_available():
"""
Validates virtualenv is available. If not, throws an `MlflowException` with a brief instruction
on how to install virtualenv.
"""
if not _is_virtualenv_available():
raise MlflowException(
"Could not find the virtualenv binary. Run `pip... |
Validates virtualenv is available. If not, throws an `MlflowException` with a brief instruction
on how to install virtualenv.
| _validate_virtualenv_is_available | python | mlflow/mlflow | mlflow/utils/virtualenv.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/virtualenv.py | Apache-2.0 |
def _find_latest_installable_python_version(version_prefix):
"""
Find the latest installable python version that matches the given version prefix
from the output of `pyenv install --list`. For example, `version_prefix("3.8")` returns '3.8.x'
where 'x' represents the latest micro version in 3.8.
"""
... |
Find the latest installable python version that matches the given version prefix
from the output of `pyenv install --list`. For example, `version_prefix("3.8")` returns '3.8.x'
where 'x' represents the latest micro version in 3.8.
| _find_latest_installable_python_version | python | mlflow/mlflow | mlflow/utils/virtualenv.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/virtualenv.py | Apache-2.0 |
def _install_python(version, pyenv_root=None, capture_output=False):
"""Installs a specified version of python with pyenv and returns a path to the installed python
binary.
Args:
version: Python version to install.
pyenv_root: The value of the "PYENV_ROOT" environment variable used when run... | Installs a specified version of python with pyenv and returns a path to the installed python
binary.
Args:
version: Python version to install.
pyenv_root: The value of the "PYENV_ROOT" environment variable used when running
`pyenv install` which installs python in `{PYENV_ROOT}/vers... | _install_python | python | mlflow/mlflow | mlflow/utils/virtualenv.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/virtualenv.py | Apache-2.0 |
def _get_python_env(local_model_path):
"""Constructs `_PythonEnv` from the model artifacts stored in `local_model_path`. If
`python_env.yaml` is available, use it, otherwise extract model dependencies from `conda.yaml`.
If `conda.yaml` contains conda dependencies except `python`, `pip`, `setuptools`, and, `... | Constructs `_PythonEnv` from the model artifacts stored in `local_model_path`. If
`python_env.yaml` is available, use it, otherwise extract model dependencies from `conda.yaml`.
If `conda.yaml` contains conda dependencies except `python`, `pip`, `setuptools`, and, `wheel`,
an `MlflowException` is thrown bec... | _get_python_env | python | mlflow/mlflow | mlflow/utils/virtualenv.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/virtualenv.py | Apache-2.0 |
def _copy_model_to_writeable_destination(model_src, dst):
"""
Copies the specified `model_src` directory, which may be read-only, to the writeable `dst`
directory.
"""
os.makedirs(dst, exist_ok=True)
for model_item in os.listdir(model_src):
# Copy individual files and subdirectories, rat... |
Copies the specified `model_src` directory, which may be read-only, to the writeable `dst`
directory.
| _copy_model_to_writeable_destination | python | mlflow/mlflow | mlflow/utils/virtualenv.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/virtualenv.py | Apache-2.0 |
def _get_or_create_virtualenv( # noqa: D417
local_model_path,
env_id=None,
env_root_dir=None,
capture_output=False,
pip_requirements_override: Optional[list[str]] = None,
env_manager: Literal["virtualenv", "uv"] = em.UV,
):
"""Restores an MLflow model's environment in a virtual environment ... | Restores an MLflow model's environment in a virtual environment and returns a command
to activate it.
Args:
local_model_path: Local directory containing the model artifacts.
env_id: Optional string that is added to the contents of the yaml file before
calculating the hash. It can be... | _get_or_create_virtualenv | python | mlflow/mlflow | mlflow/utils/virtualenv.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/virtualenv.py | Apache-2.0 |
def write_yaml(root, file_name, data, overwrite=False, sort_keys=True, ensure_yaml_extension=True):
"""Write dictionary data in yaml format.
Args:
root: Directory name.
file_name: Desired file name.
data: Data to be dumped as yaml format.
overwrite: If True, will overwrite exist... | Write dictionary data in yaml format.
Args:
root: Directory name.
file_name: Desired file name.
data: Data to be dumped as yaml format.
overwrite: If True, will overwrite existing files.
sort_keys: Whether to sort the keys when writing the yaml file.
ensure_yaml_exte... | write_yaml | python | mlflow/mlflow | mlflow/utils/yaml_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/yaml_utils.py | Apache-2.0 |
def overwrite_yaml(root, file_name, data, ensure_yaml_extension=True):
"""Safely overwrites a preexisting yaml file, ensuring that file contents are not deleted or
corrupted if the write fails. This is achieved by writing contents to a temporary file
and moving the temporary file to replace the preexisting ... | Safely overwrites a preexisting yaml file, ensuring that file contents are not deleted or
corrupted if the write fails. This is achieved by writing contents to a temporary file
and moving the temporary file to replace the preexisting file, rather than opening the
preexisting file for a direct write.
Ar... | overwrite_yaml | python | mlflow/mlflow | mlflow/utils/yaml_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/yaml_utils.py | Apache-2.0 |
def read_yaml(root, file_name):
"""Read data from yaml file and return as dictionary
Args:
root: Directory name.
file_name: File name. Expects to have '.yaml' extension.
Returns:
Data in yaml file as dictionary.
"""
if not exists(root):
raise MissingConfigException(
... | Read data from yaml file and return as dictionary
Args:
root: Directory name.
file_name: File name. Expects to have '.yaml' extension.
Returns:
Data in yaml file as dictionary.
| read_yaml | python | mlflow/mlflow | mlflow/utils/yaml_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/yaml_utils.py | Apache-2.0 |
def render_and_merge_yaml(root, template_name, context_name):
"""Renders a Jinja2-templated YAML file based on a YAML context file, merge them, and return
result as a dictionary.
Args:
root: Root directory of the YAML files.
template_name: Name of the template file.
context_name: Na... | Renders a Jinja2-templated YAML file based on a YAML context file, merge them, and return
result as a dictionary.
Args:
root: Root directory of the YAML files.
template_name: Name of the template file.
context_name: Name of the context file.
Returns:
Data in yaml file as di... | render_and_merge_yaml | python | mlflow/mlflow | mlflow/utils/yaml_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/yaml_utils.py | Apache-2.0 |
def add_dir(spark, dir_path):
"""Given a SparkSession and a model_path which refers to a pyfunc directory locally,
we will zip the directory up, enable it to be distributed to executors, and return
the "archive_path", which should be used as the path in get_or_load().
"""
_, arch... | Given a SparkSession and a model_path which refers to a pyfunc directory locally,
we will zip the directory up, enable it to be distributed to executors, and return
the "archive_path", which should be used as the path in get_or_load().
| add_dir | python | mlflow/mlflow | mlflow/utils/_spark_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/_spark_utils.py | Apache-2.0 |
def modified_environ(update):
"""Temporarily updates the ``os.environ`` dictionary in-place.
The ``os.environ`` dictionary is updated in-place so that the modification
is sure to work in all situations.
Args:
update: Dictionary of environment variables and values to add/update.
"""
upd... | Temporarily updates the ``os.environ`` dictionary in-place.
The ``os.environ`` dictionary is updated in-place so that the modification
is sure to work in all situations.
Args:
update: Dictionary of environment variables and values to add/update.
| modified_environ | python | mlflow/mlflow | mlflow/utils/_spark_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/_spark_utils.py | Apache-2.0 |
def get_artifact_repo_from_storage_info(
storage_location: str,
scoped_token: TemporaryCredentials,
base_credential_refresh_def: Callable[[], TemporaryCredentials],
is_oss: bool = False,
) -> ArtifactRepository:
"""
Get an ArtifactRepository instance capable of reading/writing to a UC model vers... |
Get an ArtifactRepository instance capable of reading/writing to a UC model version's
file storage location
Args:
storage_location: Storage location of the model version
scoped_token: Protobuf scoped token to use to authenticate to blob storage
base_credential_refresh_def: Function... | get_artifact_repo_from_storage_info | python | mlflow/mlflow | mlflow/utils/_unity_catalog_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/_unity_catalog_utils.py | Apache-2.0 |
def get_full_name_from_sc(name, spark) -> str:
"""
Constructs the full name of a registered model using the active catalog and schema in a spark
session / context.
Args:
name: The model name provided by the user.
spark: The active spark session.
"""
num_levels = len(name.split("... |
Constructs the full name of a registered model using the active catalog and schema in a spark
session / context.
Args:
name: The model name provided by the user.
spark: The active spark session.
| get_full_name_from_sc | python | mlflow/mlflow | mlflow/utils/_unity_catalog_utils.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/_unity_catalog_utils.py | Apache-2.0 |
def _chunk_dict(d, chunk_size):
"""
Splits a dictionary into chunks of the specified size.
Taken from: https://stackoverflow.com/a/22878842
"""
it = iter(d)
for _ in range(0, len(d), chunk_size):
yield {k: d[k] for k in islice(it, chunk_size)} |
Splits a dictionary into chunks of the specified size.
Taken from: https://stackoverflow.com/a/22878842
| _chunk_dict | python | mlflow/mlflow | mlflow/utils/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/__init__.py | Apache-2.0 |
def _truncate_and_ellipsize(value, max_length):
"""
Truncates the string representation of the specified value to the specified
maximum length, if necessary. The end of the string is ellipsized if truncation occurs
"""
value = str(value)
if len(value) > max_length:
return value[: (max_le... |
Truncates the string representation of the specified value to the specified
maximum length, if necessary. The end of the string is ellipsized if truncation occurs
| _truncate_and_ellipsize | python | mlflow/mlflow | mlflow/utils/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/__init__.py | Apache-2.0 |
def _truncate_dict(d, max_key_length=None, max_value_length=None):
"""
Truncates keys and/or values in a dictionary to the specified maximum length.
Truncated items will be converted to strings and ellipsized.
"""
key_is_none = max_key_length is None
val_is_none = max_value_length is None
i... |
Truncates keys and/or values in a dictionary to the specified maximum length.
Truncated items will be converted to strings and ellipsized.
| _truncate_dict | python | mlflow/mlflow | mlflow/utils/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/__init__.py | Apache-2.0 |
def merge_dicts(dict_a, dict_b, raise_on_duplicates=True):
"""This function takes two dictionaries and returns one singular merged dictionary.
Args:
dict_a: The first dictionary.
dict_b: The second dictionary.
raise_on_duplicates: If True, the function raises ValueError if there are dup... | This function takes two dictionaries and returns one singular merged dictionary.
Args:
dict_a: The first dictionary.
dict_b: The second dictionary.
raise_on_duplicates: If True, the function raises ValueError if there are duplicate keys.
Otherwise, duplicate keys in `dict_b` wil... | merge_dicts | python | mlflow/mlflow | mlflow/utils/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/__init__.py | Apache-2.0 |
def _inspect_original_var_name(var, fallback_name):
"""
Inspect variable name, will search above frames and fetch the same instance variable name
in the most outer frame.
If inspect failed, return fallback_name
"""
if var is None:
return fallback_name
try:
original_var_name =... |
Inspect variable name, will search above frames and fetch the same instance variable name
in the most outer frame.
If inspect failed, return fallback_name
| _inspect_original_var_name | python | mlflow/mlflow | mlflow/utils/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/__init__.py | Apache-2.0 |
def find_free_port():
"""
Find free socket port on local machine.
"""
with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
s.bind(("", 0))
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
return s.getsockname()[1] |
Find free socket port on local machine.
| find_free_port | python | mlflow/mlflow | mlflow/utils/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/__init__.py | Apache-2.0 |
def get_results_from_paginated_fn(paginated_fn, max_results_per_page, max_results=None):
"""Gets results by calling the ``paginated_fn`` until either no more results remain or
the specified ``max_results`` threshold has been reached.
Args:
paginated_fn: This function is expected to take in the numb... | Gets results by calling the ``paginated_fn`` until either no more results remain or
the specified ``max_results`` threshold has been reached.
Args:
paginated_fn: This function is expected to take in the number of results to retrieve
per page and a pagination token, and return a PagedList ob... | get_results_from_paginated_fn | python | mlflow/mlflow | mlflow/utils/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/__init__.py | Apache-2.0 |
def is_uuid(s: str) -> bool:
"""
Returns True if the specified string is a UUID, False otherwise.
"""
try:
uuid.UUID(s)
return True
except ValueError:
return False |
Returns True if the specified string is a UUID, False otherwise.
| is_uuid | python | mlflow/mlflow | mlflow/utils/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/__init__.py | Apache-2.0 |
def _at_exit_callback(self) -> None:
"""Callback function to be executed when the program is exiting.
Stops the data processing thread and waits for the queue to be drained. Finally, shuts down
the thread pools used for data logging and artifact processing status check.
"""
try:... | Callback function to be executed when the program is exiting.
Stops the data processing thread and waits for the queue to be drained. Finally, shuts down
the thread pools used for data logging and artifact processing status check.
| _at_exit_callback | python | mlflow/mlflow | mlflow/utils/async_logging/async_artifacts_logging_queue.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/async_logging/async_artifacts_logging_queue.py | Apache-2.0 |
def flush(self) -> None:
"""Flush the async logging queue.
Calling this method will flush the queue to ensure all the data are logged.
"""
# Stop the data processing thread.
self._stop_data_logging_thread_event.set()
# Waits till logging queue is drained.
self._a... | Flush the async logging queue.
Calling this method will flush the queue to ensure all the data are logged.
| flush | python | mlflow/mlflow | mlflow/utils/async_logging/async_artifacts_logging_queue.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/async_logging/async_artifacts_logging_queue.py | Apache-2.0 |
def _logging_loop(self) -> None:
"""
Continuously logs run data until `self._continue_to_process_data` is set to False.
If an exception occurs during logging, a `MlflowException` is raised.
"""
try:
while not self._stop_data_logging_thread_event.is_set():
... |
Continuously logs run data until `self._continue_to_process_data` is set to False.
If an exception occurs during logging, a `MlflowException` is raised.
| _logging_loop | python | mlflow/mlflow | mlflow/utils/async_logging/async_artifacts_logging_queue.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/async_logging/async_artifacts_logging_queue.py | Apache-2.0 |
def _log_artifact(self) -> None:
"""Process the run's artifacts in the running runs queues.
For each run in the running runs queues, this method retrieves the next artifact of run
from the queue and processes it by calling the `_artifact_logging_func` method with the run
ID and artifact... | Process the run's artifacts in the running runs queues.
For each run in the running runs queues, this method retrieves the next artifact of run
from the queue and processes it by calling the `_artifact_logging_func` method with the run
ID and artifact. If the artifact is empty, it is skipped. A... | _log_artifact | python | mlflow/mlflow | mlflow/utils/async_logging/async_artifacts_logging_queue.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/async_logging/async_artifacts_logging_queue.py | Apache-2.0 |
def _wait_for_artifact(self, artifact: RunArtifact) -> None:
"""Wait for given artifacts to be processed by the logging thread.
Args:
artifact: The artifact to wait for.
Raises:
Exception: If an exception occurred while processing the artifact.
"""
artif... | Wait for given artifacts to be processed by the logging thread.
Args:
artifact: The artifact to wait for.
Raises:
Exception: If an exception occurred while processing the artifact.
| _wait_for_artifact | python | mlflow/mlflow | mlflow/utils/async_logging/async_artifacts_logging_queue.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/async_logging/async_artifacts_logging_queue.py | Apache-2.0 |
def __getstate__(self):
"""Return the state of the object for pickling.
This method is called by the `pickle` module when the object is being pickled. It returns a
dictionary containing the object's state, with non-picklable attributes removed.
Returns:
dict: A dictionary c... | Return the state of the object for pickling.
This method is called by the `pickle` module when the object is being pickled. It returns a
dictionary containing the object's state, with non-picklable attributes removed.
Returns:
dict: A dictionary containing the object's state.
... | __getstate__ | python | mlflow/mlflow | mlflow/utils/async_logging/async_artifacts_logging_queue.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/async_logging/async_artifacts_logging_queue.py | Apache-2.0 |
def __setstate__(self, state):
"""Set the state of the object from a given state dictionary.
It pops back the removed non-picklable attributes from `self.__getstate__()`.
Args:
state (dict): A dictionary containing the state of the object.
Returns:
None
... | Set the state of the object from a given state dictionary.
It pops back the removed non-picklable attributes from `self.__getstate__()`.
Args:
state (dict): A dictionary containing the state of the object.
Returns:
None
| __setstate__ | python | mlflow/mlflow | mlflow/utils/async_logging/async_artifacts_logging_queue.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/async_logging/async_artifacts_logging_queue.py | Apache-2.0 |
def log_artifacts_async(self, filename, artifact_path, artifact) -> RunOperations:
"""Asynchronously logs runs artifacts.
Args:
filename: Filename of the artifact to be logged.
artifact_path: Directory within the run's artifact directory in which to log the
artif... | Asynchronously logs runs artifacts.
Args:
filename: Filename of the artifact to be logged.
artifact_path: Directory within the run's artifact directory in which to log the
artifact.
artifact: The artifact to be logged.
Returns:
mlflow.uti... | log_artifacts_async | python | mlflow/mlflow | mlflow/utils/async_logging/async_artifacts_logging_queue.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/async_logging/async_artifacts_logging_queue.py | Apache-2.0 |
def _set_up_logging_thread(self) -> None:
"""Sets up the logging thread.
If the logging thread is already set up, this method does nothing.
"""
with self._lock:
self._artifact_logging_thread = threading.Thread(
target=self._logging_loop,
name=... | Sets up the logging thread.
If the logging thread is already set up, this method does nothing.
| _set_up_logging_thread | python | mlflow/mlflow | mlflow/utils/async_logging/async_artifacts_logging_queue.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/async_logging/async_artifacts_logging_queue.py | Apache-2.0 |
def activate(self) -> None:
"""Activates the async logging queue
1. Initializes queue draining thread.
2. Initializes threads for checking the status of logged artifact.
3. Registering an atexit callback to ensure that any remaining log data
is flushed before the program exi... | Activates the async logging queue
1. Initializes queue draining thread.
2. Initializes threads for checking the status of logged artifact.
3. Registering an atexit callback to ensure that any remaining log data
is flushed before the program exits.
If the queue is already ac... | activate | python | mlflow/mlflow | mlflow/utils/async_logging/async_artifacts_logging_queue.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/async_logging/async_artifacts_logging_queue.py | Apache-2.0 |
def __init__(
self, logging_func: Callable[[str, list[Metric], list[Param], list[RunTag]], None]
) -> None:
"""Initializes an AsyncLoggingQueue object.
Args:
logging_func: A callable function that takes in four arguments: a string
representing the run_id, a list ... | Initializes an AsyncLoggingQueue object.
Args:
logging_func: A callable function that takes in four arguments: a string
representing the run_id, a list of Metric objects,
a list of Param objects, and a list of RunTag objects.
| __init__ | python | mlflow/mlflow | mlflow/utils/async_logging/async_logging_queue.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/async_logging/async_logging_queue.py | Apache-2.0 |
def _at_exit_callback(self) -> None:
"""Callback function to be executed when the program is exiting.
Stops the data processing thread and waits for the queue to be drained. Finally, shuts down
the thread pools used for data logging and batch processing status check.
"""
try:
... | Callback function to be executed when the program is exiting.
Stops the data processing thread and waits for the queue to be drained. Finally, shuts down
the thread pools used for data logging and batch processing status check.
| _at_exit_callback | python | mlflow/mlflow | mlflow/utils/async_logging/async_logging_queue.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/async_logging/async_logging_queue.py | Apache-2.0 |
def shut_down_async_logging(self) -> None:
"""
Shut down the async logging queue and wait for the queue to be drained.
Use this method if the async logging should be terminated.
"""
self.end_async_logging()
self._batch_logging_worker_threadpool.shutdown(wait=True)
... |
Shut down the async logging queue and wait for the queue to be drained.
Use this method if the async logging should be terminated.
| shut_down_async_logging | python | mlflow/mlflow | mlflow/utils/async_logging/async_logging_queue.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/async_logging/async_logging_queue.py | Apache-2.0 |
def flush(self) -> None:
"""
Flush the async logging queue and restart thread to listen
to incoming data after flushing.
Calling this method will flush the queue to ensure all the data are logged.
"""
self.shut_down_async_logging()
# Reinitialize the logging thre... |
Flush the async logging queue and restart thread to listen
to incoming data after flushing.
Calling this method will flush the queue to ensure all the data are logged.
| flush | python | mlflow/mlflow | mlflow/utils/async_logging/async_logging_queue.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/async_logging/async_logging_queue.py | Apache-2.0 |
def _fetch_batch_from_queue(self) -> list[RunBatch]:
"""Fetches a batch of run data from the queue.
Returns:
RunBatch: A batch of run data.
"""
batches = []
if self._queue.empty():
return batches
queue_size = self._queue.qsize() # Estimate the qu... | Fetches a batch of run data from the queue.
Returns:
RunBatch: A batch of run data.
| _fetch_batch_from_queue | python | mlflow/mlflow | mlflow/utils/async_logging/async_logging_queue.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/async_logging/async_logging_queue.py | Apache-2.0 |
def _log_run_data(self) -> None:
"""Process the run data in the running runs queues.
For each run in the running runs queues, this method retrieves the next batch of run data
from the queue and processes it by calling the `_processing_func` method with the run ID,
metrics, parameters, a... | Process the run data in the running runs queues.
For each run in the running runs queues, this method retrieves the next batch of run data
from the queue and processes it by calling the `_processing_func` method with the run ID,
metrics, parameters, and tags in the batch. If the batch is empty,... | _log_run_data | python | mlflow/mlflow | mlflow/utils/async_logging/async_logging_queue.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/async_logging/async_logging_queue.py | Apache-2.0 |
def _wait_for_batch(self, batch: RunBatch) -> None:
"""Wait for the given batch to be processed by the logging thread.
Args:
batch: The batch to wait for.
Raises:
Exception: If an exception occurred while processing the batch.
"""
batch.completion_event.... | Wait for the given batch to be processed by the logging thread.
Args:
batch: The batch to wait for.
Raises:
Exception: If an exception occurred while processing the batch.
| _wait_for_batch | python | mlflow/mlflow | mlflow/utils/async_logging/async_logging_queue.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/async_logging/async_logging_queue.py | Apache-2.0 |
def log_batch_async(
self, run_id: str, params: list[Param], tags: list[RunTag], metrics: list[Metric]
) -> RunOperations:
"""Asynchronously logs a batch of run data (parameters, tags, and metrics).
Args:
run_id (str): The ID of the run to log data for.
params (list[... | Asynchronously logs a batch of run data (parameters, tags, and metrics).
Args:
run_id (str): The ID of the run to log data for.
params (list[mlflow.entities.Param]): A list of parameters to log for the run.
tags (list[mlflow.entities.RunTag]): A list of tags to log for the r... | log_batch_async | python | mlflow/mlflow | mlflow/utils/async_logging/async_logging_queue.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/async_logging/async_logging_queue.py | Apache-2.0 |
def _set_up_logging_thread(self) -> None:
"""
Sets up the logging thread.
This method shouldn't be called directly without shutting down the async
logging first if an existing async logging exists, otherwise it might
hang the program.
"""
with self._lock:
... |
Sets up the logging thread.
This method shouldn't be called directly without shutting down the async
logging first if an existing async logging exists, otherwise it might
hang the program.
| _set_up_logging_thread | python | mlflow/mlflow | mlflow/utils/async_logging/async_logging_queue.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/async_logging/async_logging_queue.py | Apache-2.0 |
def activate(self) -> None:
"""Activates the async logging queue
1. Initializes queue draining thread.
2. Initializes threads for checking the status of logged batch.
3. Registering an atexit callback to ensure that any remaining log data
is flushed before the program exits.... | Activates the async logging queue
1. Initializes queue draining thread.
2. Initializes threads for checking the status of logged batch.
3. Registering an atexit callback to ensure that any remaining log data
is flushed before the program exits.
If the queue is already activ... | activate | python | mlflow/mlflow | mlflow/utils/async_logging/async_logging_queue.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/async_logging/async_logging_queue.py | Apache-2.0 |
def __init__(
self,
filename: str,
artifact_path: str,
artifact: Union["PIL.Image.Image"],
completion_event: threading.Event,
) -> None:
"""Initializes an instance of `RunArtifacts`.
Args:
filename: Filename of the artifact to be logged
... | Initializes an instance of `RunArtifacts`.
Args:
filename: Filename of the artifact to be logged
artifact_path: Directory within the run's artifact directory in which to log the
artifact.
artifact: The artifact to be logged.
completion_event: A th... | __init__ | python | mlflow/mlflow | mlflow/utils/async_logging/run_artifact.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/async_logging/run_artifact.py | Apache-2.0 |
def __init__(
self,
run_id: str,
params: Optional[list["Param"]] = None,
tags: Optional[list["RunTag"]] = None,
metrics: Optional[list["Metric"]] = None,
completion_event: Optional[threading.Event] = None,
):
"""Initializes an instance of `RunBatch`.
... | Initializes an instance of `RunBatch`.
Args:
run_id: The ID of the run.
params: A list of parameters. Default is None.
tags: A list of tags. Default is None.
metrics: A list of metrics. Default is None.
completion_event: A threading.Event object. Defa... | __init__ | python | mlflow/mlflow | mlflow/utils/async_logging/run_batch.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/async_logging/run_batch.py | Apache-2.0 |
def wait(self):
"""Blocks on completion of all futures."""
from mlflow.exceptions import MlflowException
failed_operations = []
for future in self._operation_futures:
try:
future.result()
except Exception as e:
failed_operations.ap... | Blocks on completion of all futures. | wait | python | mlflow/mlflow | mlflow/utils/async_logging/run_operations.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/async_logging/run_operations.py | Apache-2.0 |
def get_combined_run_operations(run_operations_list: list[RunOperations]) -> RunOperations:
"""Combine a list of RunOperations objects into a single RunOperations object.
Given a list of `RunOperations`, returns a single `RunOperations` object that represents the
combined set of operations. If the input li... | Combine a list of RunOperations objects into a single RunOperations object.
Given a list of `RunOperations`, returns a single `RunOperations` object that represents the
combined set of operations. If the input list is empty, returns None. If the input list
contains only one element, returns that element. O... | get_combined_run_operations | python | mlflow/mlflow | mlflow/utils/async_logging/run_operations.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/async_logging/run_operations.py | Apache-2.0 |
def await_completion(self):
"""
Blocks on completion of the MLflow Run operations.
"""
failed_operations = []
for future in self._operation_futures:
try:
future.result()
except Exception as e:
failed_operations.append(e)
... |
Blocks on completion of the MLflow Run operations.
| await_completion | python | mlflow/mlflow | mlflow/utils/autologging_utils/client.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/client.py | Apache-2.0 |
def __exit__(self, exc_type, exc, traceback):
"""
Enables `MlflowAutologgingQueueingClient` to be used as a context manager with
synchronous flushing upon exit, removing the need to call `flush()` for use cases
where logging completion can be waited upon synchronously.
Run conte... |
Enables `MlflowAutologgingQueueingClient` to be used as a context manager with
synchronous flushing upon exit, removing the need to call `flush()` for use cases
where logging completion can be waited upon synchronously.
Run content is only flushed if the context exited without an excep... | __exit__ | python | mlflow/mlflow | mlflow/utils/autologging_utils/client.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/client.py | Apache-2.0 |
def create_run(
self,
experiment_id: str,
start_time: Optional[int] = None,
tags: Optional[dict[str, Any]] = None,
run_name: Optional[str] = None,
) -> PendingRunId:
"""
Enqueues a CreateRun operation with the specified attributes, returning a `PendingRunId`
... |
Enqueues a CreateRun operation with the specified attributes, returning a `PendingRunId`
instance that can be used as input to other client logging APIs (e.g. `log_metrics`,
`log_params`, ...).
Returns:
A `PendingRunId` that can be passed as the `run_id` parameter to other ... | create_run | python | mlflow/mlflow | mlflow/utils/autologging_utils/client.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/client.py | Apache-2.0 |
def set_terminated(
self,
run_id: Union[str, PendingRunId],
status: Optional[str] = None,
end_time: Optional[int] = None,
) -> None:
"""
Enqueues an UpdateRun operation with the specified `status` and `end_time` attributes
for the specified `run_id`.
"... |
Enqueues an UpdateRun operation with the specified `status` and `end_time` attributes
for the specified `run_id`.
| set_terminated | python | mlflow/mlflow | mlflow/utils/autologging_utils/client.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/client.py | Apache-2.0 |
def log_params(self, run_id: Union[str, PendingRunId], params: dict[str, Any]) -> None:
"""
Enqueues a collection of Parameters to be logged to the run specified by `run_id`.
"""
params = _truncate_dict(
params, max_key_length=MAX_ENTITY_KEY_LENGTH, max_value_length=MAX_PARAM... |
Enqueues a collection of Parameters to be logged to the run specified by `run_id`.
| log_params | python | mlflow/mlflow | mlflow/utils/autologging_utils/client.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/client.py | Apache-2.0 |
def log_inputs(
self, run_id: Union[str, PendingRunId], datasets: Optional[list[DatasetInput]]
) -> None:
"""
Enqueues a collection of Dataset to be logged to the run specified by `run_id`.
"""
if datasets is None or len(datasets) == 0:
return
self._get_pe... |
Enqueues a collection of Dataset to be logged to the run specified by `run_id`.
| log_inputs | python | mlflow/mlflow | mlflow/utils/autologging_utils/client.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/client.py | Apache-2.0 |
def log_metrics(
self,
run_id: Union[str, PendingRunId],
metrics: dict[str, float],
step: Optional[int] = None,
dataset: Optional["Dataset"] = None,
model_id: Optional[str] = None,
) -> None:
"""
Enqueues a collection of Metrics to be logged to the run... |
Enqueues a collection of Metrics to be logged to the run specified by `run_id` at the
step specified by `step`.
| log_metrics | python | mlflow/mlflow | mlflow/utils/autologging_utils/client.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/client.py | Apache-2.0 |
def set_tags(self, run_id: Union[str, PendingRunId], tags: dict[str, Any]) -> None:
"""
Enqueues a collection of Tags to be logged to the run specified by `run_id`.
"""
tags = _truncate_dict(
tags, max_key_length=MAX_ENTITY_KEY_LENGTH, max_value_length=MAX_TAG_VAL_LENGTH
... |
Enqueues a collection of Tags to be logged to the run specified by `run_id`.
| set_tags | python | mlflow/mlflow | mlflow/utils/autologging_utils/client.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/client.py | Apache-2.0 |
def flush(self, synchronous=True):
"""
Flushes all queued run operations, resulting in the creation or mutation of runs
and run data.
Args:
synchronous: If `True`, run operations are performed synchronously, and a
`RunOperations` result object is only returne... |
Flushes all queued run operations, resulting in the creation or mutation of runs
and run data.
Args:
synchronous: If `True`, run operations are performed synchronously, and a
`RunOperations` result object is only returned once all operations
are comp... | flush | python | mlflow/mlflow | mlflow/utils/autologging_utils/client.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/client.py | Apache-2.0 |
def _get_pending_operations(self, run_id):
"""
Returns:
A `_PendingRunOperations` containing all pending operations for the
specified `run_id`.
"""
if run_id not in self._pending_ops_by_run_id:
self._pending_ops_by_run_id[run_id] = _PendingRunOperation... |
Returns:
A `_PendingRunOperations` containing all pending operations for the
specified `run_id`.
| _get_pending_operations | python | mlflow/mlflow | mlflow/utils/autologging_utils/client.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/client.py | Apache-2.0 |
def _try_operation(self, fn, *args, **kwargs):
"""
Attempt to evaluate the specified function, `fn`, on the specified `*args` and `**kwargs`,
returning either the result of the function evaluation (if evaluation was successful) or
the exception raised by the function evaluation (if evalu... |
Attempt to evaluate the specified function, `fn`, on the specified `*args` and `**kwargs`,
returning either the result of the function evaluation (if evaluation was successful) or
the exception raised by the function evaluation (if evaluation was unsuccessful).
| _try_operation | python | mlflow/mlflow | mlflow/utils/autologging_utils/client.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/client.py | Apache-2.0 |
def _flush_pending_operations(self, pending_operations):
"""
Synchronously and sequentially flushes the specified list of pending run operations.
NB: Operations are not parallelized on a per-run basis because MLflow's File Store, which
is frequently used for local ML development, does n... |
Synchronously and sequentially flushes the specified list of pending run operations.
NB: Operations are not parallelized on a per-run basis because MLflow's File Store, which
is frequently used for local ML development, does not support threadsafe metadata logging
within a given run.
... | _flush_pending_operations | python | mlflow/mlflow | mlflow/utils/autologging_utils/client.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/client.py | Apache-2.0 |
def enqueue(
self,
params=None,
tags=None,
metrics=None,
datasets=None,
create_run=None,
set_terminated=None,
):
"""
Enqueues a new pending logging operation for the associated MLflow Run.
"""
if create_run:
assert n... |
Enqueues a new pending logging operation for the associated MLflow Run.
| enqueue | python | mlflow/mlflow | mlflow/utils/autologging_utils/client.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/client.py | Apache-2.0 |
def _catch_exception(fn):
"""A decorator that catches exceptions thrown by the wrapped function and logs them."""
def wrapper(*args):
try:
fn(*args)
except Exception as e:
_logger.debug(f"Failed to log autologging event via '{fn}'. Exception: {e}")
return wrapper | A decorator that catches exceptions thrown by the wrapped function and logs them. | _catch_exception | python | mlflow/mlflow | mlflow/utils/autologging_utils/events.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/events.py | Apache-2.0 |
def log_autolog_called(self, integration, call_args, call_kwargs):
"""Called when the `autolog()` method for an autologging integration
is invoked (e.g., when a user invokes `mlflow.sklearn.autolog()`)
Args:
integration: The autologging integration for which `autolog()` was called.
... | Called when the `autolog()` method for an autologging integration
is invoked (e.g., when a user invokes `mlflow.sklearn.autolog()`)
Args:
integration: The autologging integration for which `autolog()` was called.
call_args: **DEPRECATED** The positional arguments passed to the `... | log_autolog_called | python | mlflow/mlflow | mlflow/utils/autologging_utils/events.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/events.py | Apache-2.0 |
def log_patch_function_start(self, session, patch_obj, function_name, call_args, call_kwargs):
"""Called upon invocation of a patched API associated with an autologging integration
(e.g., `sklearn.linear_model.LogisticRegression.fit()`).
Args:
session: The `AutologgingSession` assoc... | Called upon invocation of a patched API associated with an autologging integration
(e.g., `sklearn.linear_model.LogisticRegression.fit()`).
Args:
session: The `AutologgingSession` associated with the patched API call.
patch_obj: The object (class, module, etc) on which the patch... | log_patch_function_start | python | mlflow/mlflow | mlflow/utils/autologging_utils/events.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/events.py | Apache-2.0 |
def log_patch_function_success(self, session, patch_obj, function_name, call_args, call_kwargs):
"""
Called upon successful termination of a patched API associated with an autologging
integration (e.g., `sklearn.linear_model.LogisticRegression.fit()`).
Args:
session: The `Au... |
Called upon successful termination of a patched API associated with an autologging
integration (e.g., `sklearn.linear_model.LogisticRegression.fit()`).
Args:
session: The `AutologgingSession` associated with the patched API call.
patch_obj: The object (class, module, et... | log_patch_function_success | python | mlflow/mlflow | mlflow/utils/autologging_utils/events.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/events.py | Apache-2.0 |
def log_patch_function_error(
self, session, patch_obj, function_name, call_args, call_kwargs, exception
):
"""Called when execution of a patched API associated with an autologging integration
(e.g., `sklearn.linear_model.LogisticRegression.fit()`) terminates with an exception.
Args... | Called when execution of a patched API associated with an autologging integration
(e.g., `sklearn.linear_model.LogisticRegression.fit()`) terminates with an exception.
Args:
session: The `AutologgingSession` associated with the patched API call.
patch_obj: The object (class, mod... | log_patch_function_error | python | mlflow/mlflow | mlflow/utils/autologging_utils/events.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/events.py | Apache-2.0 |
def log_original_function_start(
self, session, patch_obj, function_name, call_args, call_kwargs
):
"""
Called during the execution of a patched API associated with an autologging integration
when the original / underlying API is invoked. For example, this is called when
a pa... |
Called during the execution of a patched API associated with an autologging integration
when the original / underlying API is invoked. For example, this is called when
a patched implementation of `sklearn.linear_model.LogisticRegression.fit()` invokes
the original implementation of `skl... | log_original_function_start | python | mlflow/mlflow | mlflow/utils/autologging_utils/events.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/events.py | Apache-2.0 |
def log_original_function_success(
self, session, patch_obj, function_name, call_args, call_kwargs
):
"""Called during the execution of a patched API associated with an autologging integration
when the original / underlying API invocation terminates successfully. For example,
when a ... | Called during the execution of a patched API associated with an autologging integration
when the original / underlying API invocation terminates successfully. For example,
when a patched implementation of `sklearn.linear_model.LogisticRegression.fit()` invokes the
original / underlying implement... | log_original_function_success | python | mlflow/mlflow | mlflow/utils/autologging_utils/events.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/events.py | Apache-2.0 |
def log_original_function_error(
self, session, patch_obj, function_name, call_args, call_kwargs, exception
):
"""Called during the execution of a patched API associated with an autologging integration
when the original / underlying API invocation terminates with an error. For example,
... | Called during the execution of a patched API associated with an autologging integration
when the original / underlying API invocation terminates with an error. For example,
when a patched implementation of `sklearn.linear_model.LogisticRegression.fit()` invokes the
original / underlying implemen... | log_original_function_error | python | mlflow/mlflow | mlflow/utils/autologging_utils/events.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/events.py | Apache-2.0 |
def _patched_showwarning(self, message, category, filename, lineno, *args, **kwargs):
"""
A patched implementation of `warnings.showwarning` that enforces the warning configuration
options configured on the controller (e.g. rerouting or disablement of MLflow warnings,
disablement of all ... |
A patched implementation of `warnings.showwarning` that enforces the warning configuration
options configured on the controller (e.g. rerouting or disablement of MLflow warnings,
disablement of all warnings for the current thread).
Note that reassigning `warnings.showwarning` is the st... | _patched_showwarning | python | mlflow/mlflow | mlflow/utils/autologging_utils/logging_and_warnings.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/logging_and_warnings.py | Apache-2.0 |
def _modify_patch_state_if_necessary(self):
"""
Patches or unpatches `warnings.showwarning` if necessary, as determined by:
- Whether or not `warnings.showwarning` is already patched
- Whether or not any custom warning state has been configured on the warnings
contr... |
Patches or unpatches `warnings.showwarning` if necessary, as determined by:
- Whether or not `warnings.showwarning` is already patched
- Whether or not any custom warning state has been configured on the warnings
controller (i.e. disablement or rerouting of certain warning... | _modify_patch_state_if_necessary | python | mlflow/mlflow | mlflow/utils/autologging_utils/logging_and_warnings.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/logging_and_warnings.py | Apache-2.0 |
def set_mlflow_warnings_disablement_state_globally(self, disabled=True):
"""Disables (or re-enables) MLflow warnings globally across all threads.
Args:
disabled: If `True`, disables MLflow warnings globally across all threads.
If `False`, enables MLflow warnings globally acr... | Disables (or re-enables) MLflow warnings globally across all threads.
Args:
disabled: If `True`, disables MLflow warnings globally across all threads.
If `False`, enables MLflow warnings globally across all threads.
| set_mlflow_warnings_disablement_state_globally | python | mlflow/mlflow | mlflow/utils/autologging_utils/logging_and_warnings.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/logging_and_warnings.py | Apache-2.0 |
def set_mlflow_warnings_rerouting_state_globally(self, rerouted=True):
"""
Enables (or disables) rerouting of MLflow warnings to an MLflow event logger with level
WARNING (e.g. `logger.warning()`) globally across all threads.
Args:
rerouted: If `True`, enables MLflow warning... |
Enables (or disables) rerouting of MLflow warnings to an MLflow event logger with level
WARNING (e.g. `logger.warning()`) globally across all threads.
Args:
rerouted: If `True`, enables MLflow warning rerouting globally across all threads.
If `False`, disables... | set_mlflow_warnings_rerouting_state_globally | python | mlflow/mlflow | mlflow/utils/autologging_utils/logging_and_warnings.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/logging_and_warnings.py | Apache-2.0 |
def set_non_mlflow_warnings_disablement_state_for_current_thread(self, disabled=True):
"""Disables (or re-enables) non-MLflow warnings for the current thread.
Args:
disabled: If `True`, disables non-MLflow warnings for the current thread. If `False`,
enables non-MLflow warni... | Disables (or re-enables) non-MLflow warnings for the current thread.
Args:
disabled: If `True`, disables non-MLflow warnings for the current thread. If `False`,
enables non-MLflow warnings for the current thread. non-MLflow warning
behavior in other threads is unaffe... | set_non_mlflow_warnings_disablement_state_for_current_thread | python | mlflow/mlflow | mlflow/utils/autologging_utils/logging_and_warnings.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/logging_and_warnings.py | Apache-2.0 |
def set_non_mlflow_warnings_rerouting_state_for_current_thread(self, rerouted=True):
"""Enables (or disables) rerouting of non-MLflow warnings to an MLflow event logger with
level WARNING (e.g. `logger.warning()`) for the current thread.
Args:
rerouted: If `True`, enables non-MLflow... | Enables (or disables) rerouting of non-MLflow warnings to an MLflow event logger with
level WARNING (e.g. `logger.warning()`) for the current thread.
Args:
rerouted: If `True`, enables non-MLflow warning rerouting for the current thread.
If `False`, disables non-MLflow warni... | set_non_mlflow_warnings_rerouting_state_for_current_thread | python | mlflow/mlflow | mlflow/utils/autologging_utils/logging_and_warnings.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/logging_and_warnings.py | Apache-2.0 |
def flush_metrics_queue():
"""Flush the metric queue and log contents in batches to MLflow.
Queue is divided into batches according to run id.
"""
try:
# Multiple queue flushes may be scheduled simultaneously on different threads
# (e.g., if the queue is at its flush threshold and sever... | Flush the metric queue and log contents in batches to MLflow.
Queue is divided into batches according to run id.
| flush_metrics_queue | python | mlflow/mlflow | mlflow/utils/autologging_utils/metrics_queue.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/metrics_queue.py | Apache-2.0 |
def add_to_metrics_queue(key, value, step, time, run_id):
"""Add a metric to the metric queue.
Flush the queue if it exceeds max size.
Args:
key: string, the metrics key,
value: float, the metrics value.
step: int, the step of current metric.
time: int, the timestamp of cur... | Add a metric to the metric queue.
Flush the queue if it exceeds max size.
Args:
key: string, the metrics key,
value: float, the metrics value.
step: int, the step of current metric.
time: int, the timestamp of current metric.
run_id: string, the run id of the associated... | add_to_metrics_queue | python | mlflow/mlflow | mlflow/utils/autologging_utils/metrics_queue.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/metrics_queue.py | Apache-2.0 |
def exception_safe_function_for_class(function):
"""
Wraps the specified function with broad exception handling to guard
against unexpected errors during autologging.
Note this function creates an unpicklable function as `safe_function` is locally defined,
but a class instance containing methods dec... |
Wraps the specified function with broad exception handling to guard
against unexpected errors during autologging.
Note this function creates an unpicklable function as `safe_function` is locally defined,
but a class instance containing methods decorated by this function should be pickalable,
becaus... | exception_safe_function_for_class | python | mlflow/mlflow | mlflow/utils/autologging_utils/safety.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/safety.py | Apache-2.0 |
def picklable_exception_safe_function(function):
"""
Wraps the specified function with broad exception handling to guard
against unexpected errors during autologging while preserving picklability.
"""
if is_testing():
setattr(function, _ATTRIBUTE_EXCEPTION_SAFE, True)
return update_wrap... |
Wraps the specified function with broad exception handling to guard
against unexpected errors during autologging while preserving picklability.
| picklable_exception_safe_function | python | mlflow/mlflow | mlflow/utils/autologging_utils/safety.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/safety.py | Apache-2.0 |
def _exception_safe_class_factory(base_class):
"""
Creates an exception safe metaclass that inherits from `base_class`.
"""
class _ExceptionSafeClass(base_class):
"""
Metaclass that wraps all functions defined on the specified class with broad error handling
logic to guard again... |
Creates an exception safe metaclass that inherits from `base_class`.
| _exception_safe_class_factory | python | mlflow/mlflow | mlflow/utils/autologging_utils/safety.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/safety.py | Apache-2.0 |
def with_managed_run(autologging_integration, patch_function, tags=None):
"""Given a `patch_function`, returns an `augmented_patch_function` that wraps the execution of
`patch_function` with an active MLflow run. The following properties apply:
- An MLflow run is only created if there is no active run ... | Given a `patch_function`, returns an `augmented_patch_function` that wraps the execution of
`patch_function` with an active MLflow run. The following properties apply:
- An MLflow run is only created if there is no active run present when the
patch function is executed
- If an active run... | with_managed_run | python | mlflow/mlflow | mlflow/utils/autologging_utils/safety.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/safety.py | Apache-2.0 |
def safe_patch(
autologging_integration,
destination,
function_name,
patch_function,
manage_run=False,
extra_tags=None,
):
"""Patches the specified `function_name` on the specified `destination` class for autologging
purposes, preceding its implementation with an error-safe copy of the s... | Patches the specified `function_name` on the specified `destination` class for autologging
purposes, preceding its implementation with an error-safe copy of the specified patch
`patch_function` with the following error handling behavior:
- Exceptions thrown from the underlying / original function
... | safe_patch | python | mlflow/mlflow | mlflow/utils/autologging_utils/safety.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/safety.py | Apache-2.0 |
def safe_patch_function(*args, **kwargs):
"""
A safe wrapper around the specified `patch_function` implementation designed to
handle exceptions thrown during the execution of `patch_function`. This wrapper
distinguishes exceptions thrown from the underlying / original function
(`... |
A safe wrapper around the specified `patch_function` implementation designed to
handle exceptions thrown during the execution of `patch_function`. This wrapper
distinguishes exceptions thrown from the underlying / original function
(`<destination>.<function_name>`) from exceptions throw... | safe_patch_function | python | mlflow/mlflow | mlflow/utils/autologging_utils/safety.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/safety.py | Apache-2.0 |
def revert_patches(autologging_integration):
"""Reverts all patches on the specified destination class for autologging disablement purposes.
Args:
autologging_integration: The name of the autologging integration associated with the
patch. Note: If called via fluent api (`autologging_integra... | Reverts all patches on the specified destination class for autologging disablement purposes.
Args:
autologging_integration: The name of the autologging integration associated with the
patch. Note: If called via fluent api (`autologging_integration="mlflow"`), then revert
all patches... | revert_patches | python | mlflow/mlflow | mlflow/utils/autologging_utils/safety.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/safety.py | Apache-2.0 |
def update_wrapper_extended(wrapper, wrapped):
"""Update a `wrapper` function to look like the `wrapped` function. This is an extension of
`functools.update_wrapper` that applies the docstring *and* signature of `wrapped` to
`wrapper`, producing a new function.
Returns:
A new function with the ... | Update a `wrapper` function to look like the `wrapped` function. This is an extension of
`functools.update_wrapper` that applies the docstring *and* signature of `wrapped` to
`wrapper`, producing a new function.
Returns:
A new function with the same implementation as `wrapper` and the same docstrin... | update_wrapper_extended | python | mlflow/mlflow | mlflow/utils/autologging_utils/safety.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/safety.py | Apache-2.0 |
def _wrap_patch(destination, name, patch_obj, settings=None):
"""Apply a patch.
Args:
destination: Patch destination.
name: Name of the attribute at the destination.
patch_obj: Patch object, it should be a function or a property decorated function
to be assigned to the patch... | Apply a patch.
Args:
destination: Patch destination.
name: Name of the attribute at the destination.
patch_obj: Patch object, it should be a function or a property decorated function
to be assigned to the patch point {destination}.{name}.
settings: Settings for gorilla.P... | _wrap_patch | python | mlflow/mlflow | mlflow/utils/autologging_utils/safety.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/safety.py | Apache-2.0 |
def _store_patch(autologging_integration, patch):
"""
Stores a patch for a specified autologging_integration class. Later to be used for being able
to revert the patch when disabling autologging.
Args:
autologging_integration: The name of the autologging integration associated with the
... |
Stores a patch for a specified autologging_integration class. Later to be used for being able
to revert the patch when disabling autologging.
Args:
autologging_integration: The name of the autologging integration associated with the
patch.
patch: The patch to be stored.
| _store_patch | python | mlflow/mlflow | mlflow/utils/autologging_utils/safety.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/safety.py | Apache-2.0 |
def _validate_autologging_run(autologging_integration, run_id):
"""
For testing purposes, verifies that an MLflow run produced by an `autologging_integration`
satisfies the following properties:
- The run has an autologging tag whose value is the name of the autologging integration
- The ru... |
For testing purposes, verifies that an MLflow run produced by an `autologging_integration`
satisfies the following properties:
- The run has an autologging tag whose value is the name of the autologging integration
- The run has a terminal status (e.g., KILLED, FAILED, FINISHED)
| _validate_autologging_run | python | mlflow/mlflow | mlflow/utils/autologging_utils/safety.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/safety.py | Apache-2.0 |
def matches(
self,
autologging_integration,
function_name,
value,
argument_index=None,
argument_name=None,
):
"""
This method checks if the properties provided through the function arguments matches the
properties defined in the NamedTuple.
... |
This method checks if the properties provided through the function arguments matches the
properties defined in the NamedTuple.
Args:
autologging_integration: The name of an autologging integration.
function_name: The name of the function that is being matched.
... | matches | python | mlflow/mlflow | mlflow/utils/autologging_utils/safety.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/safety.py | Apache-2.0 |
def _is_arg_exempt_from_validation(
autologging_integration,
function_name,
argument,
argument_index=None,
argument_name=None,
):
"""This function is responsible for determining whether or not an argument is exempt from
autolog safety validations. This includes both type checking and immutab... | This function is responsible for determining whether or not an argument is exempt from
autolog safety validations. This includes both type checking and immutable checking.
Args:
autologging_integration: The name of the autologging integration.
function_name: The name of the function that is bei... | _is_arg_exempt_from_validation | python | mlflow/mlflow | mlflow/utils/autologging_utils/safety.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/safety.py | Apache-2.0 |
def _validate_args(
autologging_integration,
function_name,
user_call_args,
user_call_kwargs,
autologging_call_args,
autologging_call_kwargs,
):
"""
Used for testing purposes to verify that, when a patched ML function calls its underlying
/ original ML function, the following propert... |
Used for testing purposes to verify that, when a patched ML function calls its underlying
/ original ML function, the following properties are satisfied:
- All arguments supplied to the patched ML function are forwarded to the
original ML function
- Any additional arguments supplied ... | _validate_args | python | mlflow/mlflow | mlflow/utils/autologging_utils/safety.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/safety.py | Apache-2.0 |
def _validate_new_input(inp):
"""
Validates a new input (arg or kwarg) introduced to the underlying / original ML function
call during the execution of a patched ML function. The new input is valid if:
- The new input is a function that has been decorated with
`excepti... |
Validates a new input (arg or kwarg) introduced to the underlying / original ML function
call during the execution of a patched ML function. The new input is valid if:
- The new input is a function that has been decorated with
`exception_safe_function_for_class` or `pickalabl... | _validate_new_input | python | mlflow/mlflow | mlflow/utils/autologging_utils/safety.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/safety.py | Apache-2.0 |
def _validate(autologging_call_input, user_call_input=None):
"""
Validates that the specified `autologging_call_input` and `user_call_input`
are compatible. If `user_call_input` is `None`, then `autologging_call_input`
is regarded as a new input added by autologging and is validated usin... |
Validates that the specified `autologging_call_input` and `user_call_input`
are compatible. If `user_call_input` is `None`, then `autologging_call_input`
is regarded as a new input added by autologging and is validated using
`_validate_new_input`. Otherwise, the following properties mus... | _validate | python | mlflow/mlflow | mlflow/utils/autologging_utils/safety.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/safety.py | Apache-2.0 |
def _check_spark_version_in_range(ver, min_ver, max_ver):
"""
Utility function for allowing late addition release changes to PySpark minor version increments
to be accepted, provided that the previous minor version has been previously validated.
For example, if version 3.2.1 has been validated as functi... |
Utility function for allowing late addition release changes to PySpark minor version increments
to be accepted, provided that the previous minor version has been previously validated.
For example, if version 3.2.1 has been validated as functional with MLflow, an upgrade of
PySpark's minor version to 3.... | _check_spark_version_in_range | python | mlflow/mlflow | mlflow/utils/autologging_utils/versioning.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/versioning.py | Apache-2.0 |
def is_flavor_supported_for_associated_package_versions(flavor_name):
"""
Returns:
True if the specified flavor is supported for the currently-installed versions of its
associated packages.
"""
module_name = FLAVOR_TO_MODULE_NAME[flavor_name]
try:
actual_version = importlib.... |
Returns:
True if the specified flavor is supported for the currently-installed versions of its
associated packages.
| is_flavor_supported_for_associated_package_versions | python | mlflow/mlflow | mlflow/utils/autologging_utils/versioning.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/versioning.py | Apache-2.0 |
def autologging_conf_lock(fn):
"""
Apply a global lock on functions that enable / disable autologging.
"""
def wrapper(*args, **kwargs):
with _autolog_conf_global_lock:
return fn(*args, **kwargs)
return update_wrapper_extended(wrapper, fn) |
Apply a global lock on functions that enable / disable autologging.
| autologging_conf_lock | python | mlflow/mlflow | mlflow/utils/autologging_utils/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/__init__.py | Apache-2.0 |
def get_mlflow_run_params_for_fn_args(fn, args, kwargs, unlogged=None):
"""Given arguments explicitly passed to a function, generate a dictionary of MLflow Run
parameter key / value pairs.
Args:
fn: function whose parameters are to be logged.
args: arguments explicitly passed into fn. If `f... | Given arguments explicitly passed to a function, generate a dictionary of MLflow Run
parameter key / value pairs.
Args:
fn: function whose parameters are to be logged.
args: arguments explicitly passed into fn. If `fn` is defined on a class,
`self` should not be part of `args`; the ... | get_mlflow_run_params_for_fn_args | python | mlflow/mlflow | mlflow/utils/autologging_utils/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/__init__.py | Apache-2.0 |
def resolve_input_example_and_signature(
get_input_example, infer_model_signature, log_input_example, log_model_signature, logger
):
"""Handles the logic of calling functions to gather the input example and infer the model
signature.
Args:
get_input_example: Function which returns an input exam... | Handles the logic of calling functions to gather the input example and infer the model
signature.
Args:
get_input_example: Function which returns an input example, usually sliced from a
dataset. This function can raise an exception, its message will be
shown to the user in a war... | resolve_input_example_and_signature | python | mlflow/mlflow | mlflow/utils/autologging_utils/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/__init__.py | Apache-2.0 |
def flush(self):
"""
The metrics accumulated by BatchMetricsLogger will be batch logged to an MLflow run.
"""
self._timed_log_batch()
self.data = [] |
The metrics accumulated by BatchMetricsLogger will be batch logged to an MLflow run.
| flush | python | mlflow/mlflow | mlflow/utils/autologging_utils/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/__init__.py | Apache-2.0 |
def gen_autologging_package_version_requirements_doc(integration_name):
"""
Returns:
A document note string saying the compatibility for the specified autologging
integration's associated package versions.
"""
min_ver, max_ver, pip_release = get_min_max_version_and_pip_release(integratio... |
Returns:
A document note string saying the compatibility for the specified autologging
integration's associated package versions.
| gen_autologging_package_version_requirements_doc | python | mlflow/mlflow | mlflow/utils/autologging_utils/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/__init__.py | Apache-2.0 |
def _check_and_log_warning_for_unsupported_package_versions(integration_name):
"""
When autologging is enabled and `disable_for_unsupported_versions=False` for the specified
autologging integration, check whether the currently-installed versions of the integration's
associated package versions are suppo... |
When autologging is enabled and `disable_for_unsupported_versions=False` for the specified
autologging integration, check whether the currently-installed versions of the integration's
associated package versions are supported by the specified integration. If the package versions
are not supported, log ... | _check_and_log_warning_for_unsupported_package_versions | python | mlflow/mlflow | mlflow/utils/autologging_utils/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/__init__.py | Apache-2.0 |
def autologging_integration(name):
"""
**All autologging integrations should be decorated with this wrapper.**
Wraps an autologging function in order to store its configuration arguments. This enables
patch functions to broadly obey certain configurations (e.g., disable=True) without
requiring spec... |
**All autologging integrations should be decorated with this wrapper.**
Wraps an autologging function in order to store its configuration arguments. This enables
patch functions to broadly obey certain configurations (e.g., disable=True) without
requiring specific logic to be present in each autologgi... | autologging_integration | python | mlflow/mlflow | mlflow/utils/autologging_utils/__init__.py | https://github.com/mlflow/mlflow/blob/master/mlflow/utils/autologging_utils/__init__.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.